SessionInfo.cpp 48 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571
  1. //---------------------------------------------------------------------------
  2. #include <vcl.h>
  3. #pragma hdrstop
  4. #include <stdio.h>
  5. #include <lmcons.h>
  6. #define SECURITY_WIN32
  7. #include <sspi.h>
  8. #include <secext.h>
  9. #include "Common.h"
  10. #include "SessionInfo.h"
  11. #include "Exceptions.h"
  12. #include "TextsCore.h"
  13. #include "CoreMain.h"
  14. #include "Script.h"
  15. //---------------------------------------------------------------------------
  16. #pragma package(smart_init)
  17. //---------------------------------------------------------------------------
  18. UnicodeString __fastcall DoXmlEscape(UnicodeString Str, bool NewLine)
  19. {
  20. for (int i = 1; i <= Str.Length(); i++)
  21. {
  22. const wchar_t * Repl = NULL;
  23. switch (Str[i])
  24. {
  25. case L'&':
  26. Repl = L"amp;";
  27. break;
  28. case L'>':
  29. Repl = L"gt;";
  30. break;
  31. case L'<':
  32. Repl = L"lt;";
  33. break;
  34. case L'"':
  35. Repl = L"quot;";
  36. break;
  37. case L'\n':
  38. if (NewLine)
  39. {
  40. Repl = L"#10;";
  41. }
  42. break;
  43. case L'\r':
  44. Str.Delete(i, 1);
  45. i--;
  46. break;
  47. }
  48. if (Repl != NULL)
  49. {
  50. Str[i] = L'&';
  51. Str.Insert(Repl, i + 1);
  52. i += wcslen(Repl);
  53. }
  54. }
  55. return Str;
  56. }
  57. //---------------------------------------------------------------------------
  58. UnicodeString __fastcall XmlEscape(UnicodeString Str)
  59. {
  60. return DoXmlEscape(Str, false);
  61. }
  62. //---------------------------------------------------------------------------
  63. UnicodeString __fastcall XmlAttributeEscape(UnicodeString Str)
  64. {
  65. return DoXmlEscape(Str, true);
  66. }
  67. //---------------------------------------------------------------------------
  68. //---------------------------------------------------------------------------
  69. #pragma warn -inl
  70. class TSessionActionRecord
  71. {
  72. public:
  73. __fastcall TSessionActionRecord(TActionLog * Log, TLogAction Action) :
  74. FLog(Log),
  75. FAction(Action),
  76. FState(Opened),
  77. FRecursive(false),
  78. FErrorMessages(NULL),
  79. FNames(new TStringList()),
  80. FValues(new TStringList()),
  81. FFileList(NULL),
  82. FFile(NULL)
  83. {
  84. FLog->AddPendingAction(this);
  85. }
  86. __fastcall ~TSessionActionRecord()
  87. {
  88. delete FErrorMessages;
  89. delete FNames;
  90. delete FValues;
  91. delete FFileList;
  92. delete FFile;
  93. }
  94. void __fastcall Restart()
  95. {
  96. FState = Opened;
  97. FRecursive = false;
  98. delete FErrorMessages;
  99. FErrorMessages = NULL;
  100. delete FFileList;
  101. FFileList = NULL;
  102. delete FFile;
  103. FFile = NULL;
  104. FNames->Clear();
  105. FValues->Clear();
  106. }
  107. bool __fastcall Record()
  108. {
  109. bool Result = (FState != Opened);
  110. if (Result)
  111. {
  112. if (FLog->FLogging && (FState != Cancelled))
  113. {
  114. const wchar_t * Name = ActionName();
  115. UnicodeString Attrs;
  116. if (FRecursive)
  117. {
  118. Attrs = L" recursive=\"true\"";
  119. }
  120. FLog->AddIndented(FORMAT(L"<%s%s>", (Name, Attrs)));
  121. for (int Index = 0; Index < FNames->Count; Index++)
  122. {
  123. UnicodeString Value = FValues->Strings[Index];
  124. if (Value.IsEmpty())
  125. {
  126. FLog->AddIndented(FORMAT(L" <%s />", (FNames->Strings[Index])));
  127. }
  128. else
  129. {
  130. FLog->AddIndented(FORMAT(L" <%s value=\"%s\" />",
  131. (FNames->Strings[Index], XmlAttributeEscape(Value))));
  132. }
  133. }
  134. if (FFileList != NULL)
  135. {
  136. FLog->AddIndented(L" <files>");
  137. for (int Index = 0; Index < FFileList->Count; Index++)
  138. {
  139. TRemoteFile * File = FFileList->Files[Index];
  140. FLog->AddIndented(L" <file>");
  141. FLog->AddIndented(FORMAT(L" <filename value=\"%s\" />", (XmlAttributeEscape(File->FileName))));
  142. FLog->AddIndented(FORMAT(L" <type value=\"%s\" />", (XmlAttributeEscape(File->Type))));
  143. if (!File->IsDirectory)
  144. {
  145. FLog->AddIndented(FORMAT(L" <size value=\"%s\" />", (IntToStr(File->Size))));
  146. }
  147. if (File->ModificationFmt != mfNone)
  148. {
  149. FLog->AddIndented(FORMAT(L" <modification value=\"%s\" />", (StandardTimestamp(File->Modification))));
  150. }
  151. if (!File->Rights->Unknown)
  152. {
  153. FLog->AddIndented(FORMAT(L" <permissions value=\"%s\" />", (XmlAttributeEscape(File->Rights->Text))));
  154. }
  155. if (File->Owner.IsSet)
  156. {
  157. FLog->AddIndented(FORMAT(L" <owner value=\"%s\" />", (XmlAttributeEscape(File->Owner.DisplayText))));
  158. }
  159. if (File->Group.IsSet)
  160. {
  161. FLog->AddIndented(FORMAT(L" <group value=\"%s\" />", (XmlAttributeEscape(File->Group.DisplayText))));
  162. }
  163. FLog->AddIndented(L" </file>");
  164. }
  165. FLog->AddIndented(L" </files>");
  166. }
  167. if (FFile != NULL)
  168. {
  169. FLog->AddIndented(L" <file>");
  170. FLog->AddIndented(FORMAT(L" <type value=\"%s\" />", (XmlAttributeEscape(FFile->Type))));
  171. if (!FFile->IsDirectory)
  172. {
  173. FLog->AddIndented(FORMAT(L" <size value=\"%s\" />", (IntToStr(FFile->Size))));
  174. }
  175. if (FFile->ModificationFmt != mfNone)
  176. {
  177. FLog->AddIndented(FORMAT(L" <modification value=\"%s\" />", (StandardTimestamp(FFile->Modification))));
  178. }
  179. if (!FFile->Rights->Unknown)
  180. {
  181. FLog->AddIndented(FORMAT(L" <permissions value=\"%s\" />", (XmlAttributeEscape(FFile->Rights->Text))));
  182. }
  183. FLog->AddIndented(L" </file>");
  184. }
  185. if (FState == RolledBack)
  186. {
  187. if (FErrorMessages != NULL)
  188. {
  189. FLog->AddIndented(L" <result success=\"false\">");
  190. FLog->AddMessages(L" ", FErrorMessages);
  191. FLog->AddIndented(L" </result>");
  192. }
  193. else
  194. {
  195. FLog->AddIndented(L" <result success=\"false\" />");
  196. }
  197. }
  198. else
  199. {
  200. FLog->AddIndented(L" <result success=\"true\" />");
  201. }
  202. FLog->AddIndented(FORMAT(L"</%s>", (Name)));
  203. }
  204. delete this;
  205. }
  206. return Result;
  207. }
  208. void __fastcall Commit()
  209. {
  210. Close(Committed);
  211. }
  212. void __fastcall Rollback(Exception * E)
  213. {
  214. DebugAssert(FErrorMessages == NULL);
  215. FErrorMessages = ExceptionToMoreMessages(E);
  216. Close(RolledBack);
  217. }
  218. void __fastcall Cancel()
  219. {
  220. Close(Cancelled);
  221. }
  222. void __fastcall FileName(const UnicodeString & FileName)
  223. {
  224. Parameter(L"filename", FileName);
  225. }
  226. void __fastcall Destination(const UnicodeString & Destination)
  227. {
  228. Parameter(L"destination", Destination);
  229. }
  230. void __fastcall Rights(const TRights & Rights)
  231. {
  232. Parameter(L"permissions", Rights.Text);
  233. }
  234. void __fastcall Modification(const TDateTime & DateTime)
  235. {
  236. Parameter(L"modification", StandardTimestamp(DateTime));
  237. }
  238. void __fastcall Recursive()
  239. {
  240. FRecursive = true;
  241. }
  242. void __fastcall Command(const UnicodeString & Command)
  243. {
  244. Parameter(L"command", Command);
  245. }
  246. void __fastcall AddOutput(UnicodeString Output, bool StdError)
  247. {
  248. const wchar_t * Name = (StdError ? L"erroroutput" : L"output");
  249. int Index = FNames->IndexOf(Name);
  250. if (Index >= 0)
  251. {
  252. FValues->Strings[Index] = FValues->Strings[Index] + L"\r\n" + Output;
  253. }
  254. else
  255. {
  256. Parameter(Name, Output);
  257. }
  258. }
  259. void __fastcall ExitCode(int ExitCode)
  260. {
  261. Parameter(L"exitcode", IntToStr(ExitCode));
  262. }
  263. void __fastcall Checksum(const UnicodeString & Alg, const UnicodeString & Checksum)
  264. {
  265. Parameter(L"algorithm", Alg);
  266. Parameter(L"checksum", Checksum);
  267. }
  268. void __fastcall Cwd(const UnicodeString & Path)
  269. {
  270. Parameter(L"cwd", Path);
  271. }
  272. void __fastcall FileList(TRemoteFileList * FileList)
  273. {
  274. if (FFileList == NULL)
  275. {
  276. FFileList = new TRemoteFileList();
  277. }
  278. FileList->DuplicateTo(FFileList);
  279. }
  280. void __fastcall File(TRemoteFile * File)
  281. {
  282. if (FFile != NULL)
  283. {
  284. delete FFile;
  285. }
  286. FFile = File->Duplicate(true);
  287. }
  288. protected:
  289. enum TState { Opened, Committed, RolledBack, Cancelled };
  290. inline void __fastcall Close(TState State)
  291. {
  292. DebugAssert(FState == Opened);
  293. FState = State;
  294. FLog->RecordPendingActions();
  295. }
  296. const wchar_t * __fastcall ActionName()
  297. {
  298. switch (FAction)
  299. {
  300. case laUpload: return L"upload";
  301. case laDownload: return L"download";
  302. case laTouch: return L"touch";
  303. case laChmod: return L"chmod";
  304. case laMkdir: return L"mkdir";
  305. case laRm: return L"rm";
  306. case laMv: return L"mv";
  307. case laCall: return L"call";
  308. case laLs: return L"ls";
  309. case laStat: return L"stat";
  310. case laChecksum: return L"checksum";
  311. case laCwd: return L"cwd";
  312. default: DebugFail(); return L"";
  313. }
  314. }
  315. void __fastcall Parameter(const UnicodeString & Name, const UnicodeString & Value = L"")
  316. {
  317. FNames->Add(Name);
  318. FValues->Add(Value);
  319. }
  320. private:
  321. TActionLog * FLog;
  322. TLogAction FAction;
  323. TState FState;
  324. bool FRecursive;
  325. TStrings * FErrorMessages;
  326. TStrings * FNames;
  327. TStrings * FValues;
  328. TRemoteFileList * FFileList;
  329. TRemoteFile * FFile;
  330. };
  331. #pragma warn .inl
  332. //---------------------------------------------------------------------------
  333. //---------------------------------------------------------------------------
  334. __fastcall TSessionAction::TSessionAction(TActionLog * Log, TLogAction Action)
  335. {
  336. if (Log->FLogging)
  337. {
  338. FRecord = new TSessionActionRecord(Log, Action);
  339. }
  340. else
  341. {
  342. FRecord = NULL;
  343. }
  344. }
  345. //---------------------------------------------------------------------------
  346. __fastcall TSessionAction::~TSessionAction()
  347. {
  348. if (FRecord != NULL)
  349. {
  350. Commit();
  351. }
  352. }
  353. //---------------------------------------------------------------------------
  354. void __fastcall TSessionAction::Restart()
  355. {
  356. if (FRecord != NULL)
  357. {
  358. FRecord->Restart();
  359. }
  360. }
  361. //---------------------------------------------------------------------------
  362. void __fastcall TSessionAction::Commit()
  363. {
  364. if (FRecord != NULL)
  365. {
  366. TSessionActionRecord * Record = FRecord;
  367. FRecord = NULL;
  368. Record->Commit();
  369. }
  370. }
  371. //---------------------------------------------------------------------------
  372. void __fastcall TSessionAction::Rollback(Exception * E)
  373. {
  374. if (FRecord != NULL)
  375. {
  376. TSessionActionRecord * Record = FRecord;
  377. FRecord = NULL;
  378. Record->Rollback(E);
  379. }
  380. }
  381. //---------------------------------------------------------------------------
  382. void __fastcall TSessionAction::Cancel()
  383. {
  384. if (FRecord != NULL)
  385. {
  386. TSessionActionRecord * Record = FRecord;
  387. FRecord = NULL;
  388. Record->Cancel();
  389. }
  390. }
  391. //---------------------------------------------------------------------------
  392. //---------------------------------------------------------------------------
  393. __fastcall TFileSessionAction::TFileSessionAction(TActionLog * Log, TLogAction Action) :
  394. TSessionAction(Log, Action)
  395. {
  396. }
  397. //---------------------------------------------------------------------------
  398. __fastcall TFileSessionAction::TFileSessionAction(
  399. TActionLog * Log, TLogAction Action, const UnicodeString & AFileName) :
  400. TSessionAction(Log, Action)
  401. {
  402. FileName(AFileName);
  403. }
  404. //---------------------------------------------------------------------------
  405. void __fastcall TFileSessionAction::FileName(const UnicodeString & FileName)
  406. {
  407. if (FRecord != NULL)
  408. {
  409. FRecord->FileName(FileName);
  410. }
  411. }
  412. //---------------------------------------------------------------------------
  413. //---------------------------------------------------------------------------
  414. __fastcall TFileLocationSessionAction::TFileLocationSessionAction(
  415. TActionLog * Log, TLogAction Action) :
  416. TFileSessionAction(Log, Action)
  417. {
  418. }
  419. //---------------------------------------------------------------------------
  420. __fastcall TFileLocationSessionAction::TFileLocationSessionAction(
  421. TActionLog * Log, TLogAction Action, const UnicodeString & FileName) :
  422. TFileSessionAction(Log, Action, FileName)
  423. {
  424. }
  425. //---------------------------------------------------------------------------
  426. void __fastcall TFileLocationSessionAction::Destination(const UnicodeString & Destination)
  427. {
  428. if (FRecord != NULL)
  429. {
  430. FRecord->Destination(Destination);
  431. }
  432. }
  433. //---------------------------------------------------------------------------
  434. //---------------------------------------------------------------------------
  435. __fastcall TUploadSessionAction::TUploadSessionAction(TActionLog * Log) :
  436. TFileLocationSessionAction(Log, laUpload)
  437. {
  438. }
  439. //---------------------------------------------------------------------------
  440. //---------------------------------------------------------------------------
  441. __fastcall TDownloadSessionAction::TDownloadSessionAction(TActionLog * Log) :
  442. TFileLocationSessionAction(Log, laDownload)
  443. {
  444. }
  445. //---------------------------------------------------------------------------
  446. //---------------------------------------------------------------------------
  447. __fastcall TChmodSessionAction::TChmodSessionAction(
  448. TActionLog * Log, const UnicodeString & FileName) :
  449. TFileSessionAction(Log, laChmod, FileName)
  450. {
  451. }
  452. //---------------------------------------------------------------------------
  453. void __fastcall TChmodSessionAction::Recursive()
  454. {
  455. if (FRecord != NULL)
  456. {
  457. FRecord->Recursive();
  458. }
  459. }
  460. //---------------------------------------------------------------------------
  461. __fastcall TChmodSessionAction::TChmodSessionAction(
  462. TActionLog * Log, const UnicodeString & FileName, const TRights & ARights) :
  463. TFileSessionAction(Log, laChmod, FileName)
  464. {
  465. Rights(ARights);
  466. }
  467. //---------------------------------------------------------------------------
  468. void __fastcall TChmodSessionAction::Rights(const TRights & Rights)
  469. {
  470. if (FRecord != NULL)
  471. {
  472. FRecord->Rights(Rights);
  473. }
  474. }
  475. //---------------------------------------------------------------------------
  476. __fastcall TTouchSessionAction::TTouchSessionAction(
  477. TActionLog * Log, const UnicodeString & FileName, const TDateTime & Modification) :
  478. TFileSessionAction(Log, laTouch, FileName)
  479. {
  480. if (FRecord != NULL)
  481. {
  482. FRecord->Modification(Modification);
  483. }
  484. }
  485. //---------------------------------------------------------------------------
  486. __fastcall TMkdirSessionAction::TMkdirSessionAction(
  487. TActionLog * Log, const UnicodeString & FileName) :
  488. TFileSessionAction(Log, laMkdir, FileName)
  489. {
  490. }
  491. //---------------------------------------------------------------------------
  492. __fastcall TRmSessionAction::TRmSessionAction(
  493. TActionLog * Log, const UnicodeString & FileName) :
  494. TFileSessionAction(Log, laRm, FileName)
  495. {
  496. }
  497. //---------------------------------------------------------------------------
  498. void __fastcall TRmSessionAction::Recursive()
  499. {
  500. if (FRecord != NULL)
  501. {
  502. FRecord->Recursive();
  503. }
  504. }
  505. //---------------------------------------------------------------------------
  506. __fastcall TMvSessionAction::TMvSessionAction(TActionLog * Log,
  507. const UnicodeString & FileName, const UnicodeString & ADestination) :
  508. TFileLocationSessionAction(Log, laMv, FileName)
  509. {
  510. Destination(ADestination);
  511. }
  512. //---------------------------------------------------------------------------
  513. __fastcall TCallSessionAction::TCallSessionAction(TActionLog * Log,
  514. const UnicodeString & Command, const UnicodeString & Destination) :
  515. TSessionAction(Log, laCall)
  516. {
  517. if (FRecord != NULL)
  518. {
  519. FRecord->Command(Command);
  520. FRecord->Destination(Destination);
  521. }
  522. }
  523. //---------------------------------------------------------------------------
  524. void __fastcall TCallSessionAction::AddOutput(const UnicodeString & Output, bool StdError)
  525. {
  526. if (FRecord != NULL)
  527. {
  528. FRecord->AddOutput(Output, StdError);
  529. }
  530. }
  531. //---------------------------------------------------------------------------
  532. void __fastcall TCallSessionAction::ExitCode(int ExitCode)
  533. {
  534. if (FRecord != NULL)
  535. {
  536. FRecord->ExitCode(ExitCode);
  537. }
  538. }
  539. //---------------------------------------------------------------------------
  540. __fastcall TLsSessionAction::TLsSessionAction(TActionLog * Log,
  541. const UnicodeString & Destination) :
  542. TSessionAction(Log, laLs)
  543. {
  544. if (FRecord != NULL)
  545. {
  546. FRecord->Destination(Destination);
  547. }
  548. }
  549. //---------------------------------------------------------------------------
  550. void __fastcall TLsSessionAction::FileList(TRemoteFileList * FileList)
  551. {
  552. if (FRecord != NULL)
  553. {
  554. FRecord->FileList(FileList);
  555. }
  556. }
  557. //---------------------------------------------------------------------------
  558. //---------------------------------------------------------------------------
  559. __fastcall TStatSessionAction::TStatSessionAction(TActionLog * Log, const UnicodeString & FileName) :
  560. TFileSessionAction(Log, laStat, FileName)
  561. {
  562. }
  563. //---------------------------------------------------------------------------
  564. void __fastcall TStatSessionAction::File(TRemoteFile * File)
  565. {
  566. if (FRecord != NULL)
  567. {
  568. FRecord->File(File);
  569. }
  570. }
  571. //---------------------------------------------------------------------------
  572. //---------------------------------------------------------------------------
  573. __fastcall TChecksumSessionAction::TChecksumSessionAction(TActionLog * Log) :
  574. TFileSessionAction(Log, laChecksum)
  575. {
  576. }
  577. //---------------------------------------------------------------------------
  578. void __fastcall TChecksumSessionAction::Checksum(const UnicodeString & Alg, const UnicodeString & Checksum)
  579. {
  580. if (FRecord != NULL)
  581. {
  582. FRecord->Checksum(Alg, Checksum);
  583. }
  584. }
  585. //---------------------------------------------------------------------------
  586. //---------------------------------------------------------------------------
  587. __fastcall TCwdSessionAction::TCwdSessionAction(TActionLog * Log, const UnicodeString & Path) :
  588. TSessionAction(Log, laCwd)
  589. {
  590. if (FRecord != NULL)
  591. {
  592. FRecord->Cwd(Path);
  593. }
  594. }
  595. //---------------------------------------------------------------------------
  596. //---------------------------------------------------------------------------
  597. TSessionInfo::TSessionInfo()
  598. {
  599. LoginTime = Now();
  600. }
  601. //---------------------------------------------------------------------------
  602. TFileSystemInfo::TFileSystemInfo()
  603. {
  604. memset(&IsCapable, false, sizeof(IsCapable));
  605. }
  606. //---------------------------------------------------------------------------
  607. //---------------------------------------------------------------------------
  608. FILE * __fastcall OpenFile(UnicodeString LogFileName, TDateTime Started, TSessionData * SessionData, bool Append, UnicodeString & NewFileName)
  609. {
  610. FILE * Result;
  611. UnicodeString ANewFileName = GetExpandedLogFileName(LogFileName, Started, SessionData);
  612. Result = _wfopen(ApiPath(ANewFileName).c_str(), (Append ? L"ab" : L"wb"));
  613. if (Result != NULL)
  614. {
  615. setvbuf(Result, NULL, _IONBF, BUFSIZ);
  616. NewFileName = ANewFileName;
  617. }
  618. else
  619. {
  620. throw ECRTExtException(FMTLOAD(LOG_OPENERROR, (ANewFileName)));
  621. }
  622. return Result;
  623. }
  624. //---------------------------------------------------------------------------
  625. //---------------------------------------------------------------------------
  626. const wchar_t *LogLineMarks = L"<>!.*";
  627. __fastcall TSessionLog::TSessionLog(TSessionUI* UI, TDateTime Started, TSessionData * SessionData,
  628. TConfiguration * Configuration)
  629. {
  630. FCriticalSection = new TCriticalSection;
  631. FLogging = false;
  632. FConfiguration = Configuration;
  633. FParent = NULL;
  634. FUI = UI;
  635. FSessionData = SessionData;
  636. FStarted = Started;
  637. FFile = NULL;
  638. FCurrentLogFileName = L"";
  639. FCurrentFileName = L"";
  640. FClosed = false;
  641. }
  642. //---------------------------------------------------------------------------
  643. __fastcall TSessionLog::~TSessionLog()
  644. {
  645. FClosed = true;
  646. ReflectSettings();
  647. DebugAssert(FFile == NULL);
  648. delete FCriticalSection;
  649. }
  650. //---------------------------------------------------------------------------
  651. void __fastcall TSessionLog::SetParent(TSessionLog * Parent, const UnicodeString & Name)
  652. {
  653. FParent = Parent;
  654. FName = Name;
  655. }
  656. //---------------------------------------------------------------------------
  657. void __fastcall TSessionLog::DoAddToParent(TLogLineType Type, const UnicodeString & Line)
  658. {
  659. DebugAssert(FParent != NULL);
  660. FParent->Add(Type, Line);
  661. }
  662. //---------------------------------------------------------------------------
  663. void __fastcall TSessionLog::DoAddToSelf(TLogLineType Type, const UnicodeString & Line)
  664. {
  665. if (LogToFile())
  666. {
  667. if (FFile == NULL)
  668. {
  669. OpenLogFile();
  670. }
  671. if (FFile != NULL)
  672. {
  673. UnicodeString Timestamp = FormatDateTime(L" yyyy-mm-dd hh:nn:ss.zzz ", Now());
  674. UTF8String UtfLine = UTF8String(UnicodeString(LogLineMarks[Type]) + Timestamp + Line + L"\r\n");
  675. for (int Index = 1; Index <= UtfLine.Length(); Index++)
  676. {
  677. if ((UtfLine[Index] == '\n') &&
  678. ((Index == 1) || (UtfLine[Index - 1] != '\r')))
  679. {
  680. UtfLine.Insert('\r', Index);
  681. }
  682. }
  683. int Writting = UtfLine.Length();
  684. CheckSize(Writting);
  685. FCurrentFileSize += fwrite(UtfLine.c_str(), 1, Writting, (FILE *)FFile);
  686. }
  687. }
  688. }
  689. //---------------------------------------------------------------------------
  690. UnicodeString __fastcall TSessionLog::LogPartFileName(const UnicodeString & BaseName, int Index)
  691. {
  692. UnicodeString Result;
  693. if (Index >= 1)
  694. {
  695. Result = FORMAT(L"%s.%d", (BaseName, Index));
  696. }
  697. else
  698. {
  699. Result = BaseName;
  700. }
  701. return Result;
  702. }
  703. //---------------------------------------------------------------------------
  704. void __fastcall TSessionLog::CheckSize(__int64 Addition)
  705. {
  706. __int64 MaxSize = FConfiguration->LogMaxSize;
  707. if ((MaxSize > 0) && (FCurrentFileSize + Addition >= MaxSize))
  708. {
  709. // Before we close it
  710. UnicodeString BaseName = FCurrentFileName;
  711. CloseLogFile();
  712. FCurrentFileSize = 0;
  713. int Index = 0;
  714. while (FileExists(LogPartFileName(BaseName, Index + 1)))
  715. {
  716. Index++;
  717. }
  718. int MaxCount = FConfiguration->LogMaxCount;
  719. do
  720. {
  721. UnicodeString LogPart = LogPartFileName(BaseName, Index);
  722. if ((MaxCount > 0) && (Index >= MaxCount))
  723. {
  724. DeleteFileChecked(LogPart);
  725. }
  726. else
  727. {
  728. THROWOSIFFALSE(RenameFile(LogPart, LogPartFileName(BaseName, Index + 1)));
  729. }
  730. Index--;
  731. }
  732. while (Index >= 0);
  733. OpenLogFile();
  734. }
  735. }
  736. //---------------------------------------------------------------------------
  737. void __fastcall TSessionLog::DoAdd(TLogLineType Type, UnicodeString Line,
  738. void __fastcall (__closure *f)(TLogLineType Type, const UnicodeString & Line))
  739. {
  740. UnicodeString Prefix;
  741. if (!FName.IsEmpty())
  742. {
  743. Prefix = L"[" + FName + L"] ";
  744. }
  745. while (!Line.IsEmpty())
  746. {
  747. f(Type, Prefix + CutToChar(Line, L'\n', false));
  748. }
  749. }
  750. //---------------------------------------------------------------------------
  751. void __fastcall TSessionLog::Add(TLogLineType Type, const UnicodeString & Line)
  752. {
  753. DebugAssert(FConfiguration);
  754. if (Logging)
  755. {
  756. try
  757. {
  758. if (FParent != NULL)
  759. {
  760. DoAdd(Type, Line, DoAddToParent);
  761. }
  762. else
  763. {
  764. TGuard Guard(FCriticalSection);
  765. DoAdd(Type, Line, DoAddToSelf);
  766. }
  767. }
  768. catch (Exception &E)
  769. {
  770. // We failed logging, turn it off and notify user.
  771. FConfiguration->Logging = false;
  772. try
  773. {
  774. throw ExtException(&E, LoadStr(LOG_GEN_ERROR));
  775. }
  776. catch (Exception &E)
  777. {
  778. AddException(&E);
  779. FUI->HandleExtendedException(&E);
  780. }
  781. }
  782. }
  783. }
  784. //---------------------------------------------------------------------------
  785. void __fastcall TSessionLog::AddException(Exception * E)
  786. {
  787. if (E != NULL)
  788. {
  789. Add(llException, ExceptionLogString(E));
  790. }
  791. }
  792. //---------------------------------------------------------------------------
  793. void __fastcall TSessionLog::ReflectSettings()
  794. {
  795. TGuard Guard(FCriticalSection);
  796. FLogging =
  797. !FClosed &&
  798. ((FParent != NULL) || FConfiguration->Logging);
  799. // if logging to file was turned off or log file was changed -> close current log file
  800. if ((FFile != NULL) &&
  801. (!LogToFile() || (FCurrentLogFileName != FConfiguration->LogFileName)))
  802. {
  803. CloseLogFile();
  804. }
  805. if (FFile != NULL)
  806. {
  807. CheckSize(0);
  808. }
  809. }
  810. //---------------------------------------------------------------------------
  811. bool __fastcall TSessionLog::LogToFile()
  812. {
  813. return Logging && FConfiguration->LogToFile && (FParent == NULL);
  814. }
  815. //---------------------------------------------------------------------------
  816. void __fastcall TSessionLog::CloseLogFile()
  817. {
  818. if (FFile != NULL)
  819. {
  820. fclose((FILE *)FFile);
  821. FFile = NULL;
  822. }
  823. FCurrentLogFileName = L"";
  824. FCurrentFileName = L"";
  825. }
  826. //---------------------------------------------------------------------------
  827. void __fastcall TSessionLog::OpenLogFile()
  828. {
  829. try
  830. {
  831. DebugAssert(FFile == NULL);
  832. DebugAssert(FConfiguration != NULL);
  833. FCurrentLogFileName = FConfiguration->LogFileName;
  834. FFile = OpenFile(FCurrentLogFileName, FStarted, FSessionData, FConfiguration->LogFileAppend, FCurrentFileName);
  835. TSearchRec SearchRec;
  836. if (FileSearchRec(FCurrentFileName, SearchRec))
  837. {
  838. FCurrentFileSize = SearchRec.Size;
  839. }
  840. else
  841. {
  842. FCurrentFileSize = 0;
  843. }
  844. }
  845. catch (Exception & E)
  846. {
  847. // We failed logging to file, turn it off and notify user.
  848. FCurrentLogFileName = L"";
  849. FCurrentFileName = L"";
  850. FConfiguration->LogFileName = UnicodeString();
  851. try
  852. {
  853. throw ExtException(&E, LoadStr(LOG_GEN_ERROR));
  854. }
  855. catch (Exception & E)
  856. {
  857. AddException(&E);
  858. // not to deadlock with TSessionLog::ReflectSettings invoked by FConfiguration->LogFileName setter above
  859. TUnguard Unguard(FCriticalSection);
  860. FUI->HandleExtendedException(&E);
  861. }
  862. }
  863. // in case we are appending and the existing log file is already too large
  864. if (FFile != NULL)
  865. {
  866. CheckSize(0);
  867. }
  868. }
  869. //---------------------------------------------------------------------------
  870. void __fastcall TSessionLog::AddSystemInfo()
  871. {
  872. AddStartupInfo(true);
  873. }
  874. //---------------------------------------------------------------------------
  875. void __fastcall TSessionLog::AddStartupInfo()
  876. {
  877. AddStartupInfo(false);
  878. }
  879. //---------------------------------------------------------------------------
  880. void __fastcall TSessionLog::AddStartupInfo(bool System)
  881. {
  882. TSessionData * Data = (System ? NULL : FSessionData);
  883. if (Logging)
  884. {
  885. if (FParent != NULL)
  886. {
  887. // do not add session info for secondary session
  888. // (this should better be handled in the TSecondaryTerminal)
  889. }
  890. else
  891. {
  892. DoAddStartupInfo(Data);
  893. }
  894. }
  895. }
  896. //---------------------------------------------------------------------------
  897. UnicodeString __fastcall TSessionLog::GetTlsVersionName(TTlsVersion TlsVersion)
  898. {
  899. switch (TlsVersion)
  900. {
  901. default:
  902. DebugFail();
  903. case ssl2:
  904. return "SSLv2";
  905. case ssl3:
  906. return "SSLv3";
  907. case tls10:
  908. return "TLSv1.0";
  909. case tls11:
  910. return "TLSv1.1";
  911. case tls12:
  912. return "TLSv1.2";
  913. }
  914. }
  915. //---------------------------------------------------------------------------
  916. UnicodeString __fastcall TSessionLog::LogSensitive(const UnicodeString & Str)
  917. {
  918. if (FConfiguration->LogSensitive && !Str.IsEmpty())
  919. {
  920. return Str;
  921. }
  922. else
  923. {
  924. return BooleanToEngStr(!Str.IsEmpty());
  925. }
  926. }
  927. //---------------------------------------------------------------------------
  928. UnicodeString __fastcall TSessionLog::GetCmdLineLog()
  929. {
  930. UnicodeString Result = CmdLine;
  931. if (!Configuration->LogSensitive)
  932. {
  933. TManagementScript Script(StoredSessions, false);
  934. Script.MaskPasswordInCommandLine(Result, true);
  935. }
  936. return Result;
  937. }
  938. //---------------------------------------------------------------------------
  939. template <typename T>
  940. UnicodeString __fastcall EnumName(T Value, UnicodeString Names)
  941. {
  942. int N = int(Value);
  943. do
  944. {
  945. UnicodeString Name = CutToChar(Names, L';', true);
  946. if (N == 0)
  947. {
  948. return Name;
  949. }
  950. N--;
  951. }
  952. while ((N >= 0) && !Names.IsEmpty());
  953. return L"(unknown)";
  954. }
  955. //---------------------------------------------------------------------------
  956. #define ADSTR(S) DoAdd(llMessage, S, DoAddToSelf);
  957. #define ADF(S, F) ADSTR(FORMAT(S, F));
  958. //---------------------------------------------------------------------------
  959. void __fastcall TSessionLog::DoAddStartupInfo(TSessionData * Data)
  960. {
  961. if (Data == NULL)
  962. {
  963. AddSeparator();
  964. UnicodeString OS = WindowsVersionLong();
  965. AddToList(OS, WindowsProductName(), L" - ");
  966. ADF(L"WinSCP %s (OS %s)", (FConfiguration->VersionStr, OS));
  967. THierarchicalStorage * Storage = FConfiguration->CreateConfigStorage();
  968. try
  969. {
  970. ADF(L"Configuration: %s", (Storage->Source));
  971. }
  972. __finally
  973. {
  974. delete Storage;
  975. }
  976. wchar_t UserName[UNLEN + 1];
  977. unsigned long UserNameSize = LENOF(UserName);
  978. if (DebugAlwaysFalse(!GetUserNameEx(NameSamCompatible, UserName, &UserNameSize)))
  979. {
  980. wcscpy(UserName, L"<Failed to retrieve username>");
  981. }
  982. UnicodeString LogStr;
  983. if (FConfiguration->LogProtocol <= 0)
  984. {
  985. LogStr = L"Normal";
  986. }
  987. else if (FConfiguration->LogProtocol == 1)
  988. {
  989. LogStr = L"Debug 1";
  990. }
  991. else if (FConfiguration->LogProtocol >= 2)
  992. {
  993. LogStr = L"Debug 2";
  994. }
  995. if (FConfiguration->LogSensitive)
  996. {
  997. LogStr += L", Logging passwords";
  998. }
  999. if (FConfiguration->LogMaxSize > 0)
  1000. {
  1001. LogStr += FORMAT(L", Rotating after: %s", (SizeToStr(FConfiguration->LogMaxSize)));
  1002. if (FConfiguration->LogMaxCount > 0)
  1003. {
  1004. LogStr += FORMAT(L", Keeping at most %d logs", (FConfiguration->LogMaxCount));
  1005. }
  1006. }
  1007. ADF(L"Log level: %s", (LogStr));
  1008. ADF(L"Local account: %s", (UserName));
  1009. ADF(L"Working directory: %s", (GetCurrentDir()));
  1010. ADF(L"Process ID: %d", (int(GetCurrentProcessId())));
  1011. ADF(L"Command-line: %s", (GetCmdLineLog()));
  1012. if (FConfiguration->LogProtocol >= 1)
  1013. {
  1014. AddOptions(GetGlobalOptions());
  1015. }
  1016. ADF(L"Time zone: %s", (GetTimeZoneLogString()));
  1017. if (!AdjustClockForDSTEnabled())
  1018. {
  1019. ADSTR(L"Warning: System option \"Automatically adjust clock for Daylight Saving Time\" is disabled, timestamps will not be represented correctly");
  1020. }
  1021. ADF(L"Login time: %s", (FormatDateTime(L"dddddd tt", Now())));
  1022. AddSeparator();
  1023. }
  1024. else
  1025. {
  1026. ADF(L"Session name: %s (%s)", (Data->SessionName, Data->Source));
  1027. ADF(L"Host name: %s (Port: %d)", (Data->HostNameExpanded, Data->PortNumber));
  1028. ADF(L"User name: %s (Password: %s, Key file: %s, Passphrase: %s)",
  1029. (Data->UserNameExpanded, LogSensitive(Data->Password),
  1030. LogSensitive(Data->PublicKeyFile), LogSensitive(Data->Passphrase)));
  1031. if (Data->UsesSsh)
  1032. {
  1033. ADF(L"Tunnel: %s", (BooleanToEngStr(Data->Tunnel)));
  1034. if (Data->Tunnel)
  1035. {
  1036. ADF(L"Tunnel: Host name: %s (Port: %d)", (Data->TunnelHostName, Data->TunnelPortNumber));
  1037. ADF(L"Tunnel: User name: %s (Password: %s, Key file: %s)",
  1038. (Data->TunnelUserName,
  1039. LogSensitive(Data->TunnelPassword),
  1040. LogSensitive(Data->TunnelPublicKeyFile)));
  1041. ADF(L"Tunnel: Local port number: %d", (Data->TunnelLocalPortNumber));
  1042. }
  1043. }
  1044. ADF(L"Transfer Protocol: %s", (Data->FSProtocolStr));
  1045. if (Data->UsesSsh || (Data->FSProtocol == fsFTP))
  1046. {
  1047. TPingType PingType;
  1048. int PingInterval;
  1049. if (Data->FSProtocol == fsFTP)
  1050. {
  1051. PingType = Data->FtpPingType;
  1052. PingInterval = Data->FtpPingInterval;
  1053. }
  1054. else
  1055. {
  1056. PingType = Data->PingType;
  1057. PingInterval = Data->PingInterval;
  1058. }
  1059. ADF(L"Ping type: %s, Ping interval: %d sec; Timeout: %d sec",
  1060. (EnumName(PingType, PingTypeNames), PingInterval, Data->Timeout));
  1061. ADF(L"Disable Nagle: %s",
  1062. (BooleanToEngStr(Data->TcpNoDelay)));
  1063. }
  1064. ADF(L"Proxy: %s",
  1065. ((Data->FtpProxyLogonType != 0) ?
  1066. FORMAT(L"FTP proxy %d", (Data->FtpProxyLogonType)) :
  1067. EnumName(Data->ProxyMethod, ProxyMethodNames)));
  1068. if ((Data->FtpProxyLogonType != 0) || (Data->ProxyMethod != ::pmNone))
  1069. {
  1070. ADF(L"HostName: %s (Port: %d); Username: %s; Passwd: %s",
  1071. (Data->ProxyHost, Data->ProxyPort,
  1072. Data->ProxyUsername, LogSensitive(Data->ProxyPassword)));
  1073. if (Data->ProxyMethod == pmTelnet)
  1074. {
  1075. ADF(L"Telnet command: %s", (Data->ProxyTelnetCommand));
  1076. }
  1077. if (Data->ProxyMethod == pmCmd)
  1078. {
  1079. ADF(L"Local command: %s", (Data->ProxyLocalCommand));
  1080. }
  1081. }
  1082. if (Data->UsesSsh || (Data->FSProtocol == fsFTP))
  1083. {
  1084. ADF(L"Send buffer: %d", (Data->SendBuf));
  1085. }
  1086. if (Data->UsesSsh)
  1087. {
  1088. ADF(L"SSH protocol version: %s; Compression: %s",
  1089. (Data->SshProtStr, BooleanToEngStr(Data->Compression)));
  1090. ADF(L"Bypass authentication: %s",
  1091. (BooleanToEngStr(Data->SshNoUserAuth)));
  1092. ADF(L"Try agent: %s; Agent forwarding: %s; TIS/CryptoCard: %s; KI: %s; GSSAPI: %s",
  1093. (BooleanToEngStr(Data->TryAgent), BooleanToEngStr(Data->AgentFwd), BooleanToEngStr(Data->AuthTIS),
  1094. BooleanToEngStr(Data->AuthKI), BooleanToEngStr(Data->AuthGSSAPI)));
  1095. if (Data->AuthGSSAPI)
  1096. {
  1097. ADF(L"GSSAPI: Forwarding: %s",
  1098. (BooleanToEngStr(Data->GSSAPIFwdTGT)));
  1099. }
  1100. ADF(L"Ciphers: %s; Ssh2DES: %s",
  1101. (Data->CipherList, BooleanToEngStr(Data->Ssh2DES)));
  1102. ADF(L"KEX: %s", (Data->KexList));
  1103. UnicodeString Bugs;
  1104. for (int Index = 0; Index < BUG_COUNT; Index++)
  1105. {
  1106. AddToList(Bugs, EnumName(Data->Bug[(TSshBug)Index], AutoSwitchNames), L",");
  1107. }
  1108. ADF(L"SSH Bugs: %s", (Bugs));
  1109. ADF(L"Simple channel: %s", (BooleanToEngStr(Data->SshSimple)));
  1110. ADF(L"Return code variable: %s; Lookup user groups: %s",
  1111. ((Data->DetectReturnVar ? UnicodeString(L"Autodetect") : Data->ReturnVar),
  1112. EnumName(Data->LookupUserGroups, AutoSwitchNames)));
  1113. ADF(L"Shell: %s", ((Data->Shell.IsEmpty()? UnicodeString(L"default") : Data->Shell)));
  1114. ADF(L"EOL: %s, UTF: %s", (EnumName(Data->EOLType, EOLTypeNames), EnumName(Data->NotUtf, NotAutoSwitchNames))); // NotUtf duplicated in FTP branch
  1115. ADF(L"Clear aliases: %s, Unset nat.vars: %s, Resolve symlinks: %s; Follow directory symlinks: %s",
  1116. (BooleanToEngStr(Data->ClearAliases), BooleanToEngStr(Data->UnsetNationalVars),
  1117. BooleanToEngStr(Data->ResolveSymlinks), BooleanToEngStr(Data->FollowDirectorySymlinks)));
  1118. ADF(L"LS: %s, Ign LS warn: %s, Scp1 Comp: %s",
  1119. (Data->ListingCommand,
  1120. BooleanToEngStr(Data->IgnoreLsWarnings),
  1121. BooleanToEngStr(Data->Scp1Compatibility)));
  1122. }
  1123. if ((Data->FSProtocol == fsSFTP) || (Data->FSProtocol == fsSFTPonly))
  1124. {
  1125. UnicodeString Bugs;
  1126. for (int Index = 0; Index < SFTP_BUG_COUNT; Index++)
  1127. {
  1128. AddToList(Bugs, EnumName(Data->SFTPBug[(TSftpBug)Index], AutoSwitchNames), L",");
  1129. }
  1130. ADF(L"SFTP Bugs: %s", (Bugs));
  1131. ADF(L"SFTP Server: %s", ((Data->SftpServer.IsEmpty()? UnicodeString(L"default") : Data->SftpServer)));
  1132. }
  1133. bool FtpsOn = false;
  1134. if (Data->FSProtocol == fsFTP)
  1135. {
  1136. ADF(L"UTF: %s", (EnumName(Data->NotUtf, NotAutoSwitchNames))); // duplicated in UsesSsh branch
  1137. UnicodeString Ftps;
  1138. switch (Data->Ftps)
  1139. {
  1140. case ftpsImplicit:
  1141. Ftps = L"Implicit TLS/SSL";
  1142. FtpsOn = true;
  1143. break;
  1144. case ftpsExplicitSsl:
  1145. Ftps = L"Explicit SSL/TLS";
  1146. FtpsOn = true;
  1147. break;
  1148. case ftpsExplicitTls:
  1149. Ftps = L"Explicit TLS/SSL";
  1150. FtpsOn = true;
  1151. break;
  1152. default:
  1153. DebugAssert(Data->Ftps == ftpsNone);
  1154. Ftps = L"None";
  1155. break;
  1156. }
  1157. // kind of hidden option, so do not reveal it unless it is set
  1158. if (Data->FtpTransferActiveImmediately != asAuto)
  1159. {
  1160. ADF(L"Transfer active immediately: %s", (EnumName(Data->FtpTransferActiveImmediately, AutoSwitchNames)));
  1161. }
  1162. ADF(L"FTPS: %s [Client certificate: %s]",
  1163. (Ftps, LogSensitive(Data->TlsCertificateFile)));
  1164. ADF(L"FTP: Passive: %s [Force IP: %s]; MLSD: %s [List all: %s]; HOST: %s",
  1165. (BooleanToEngStr(Data->FtpPasvMode),
  1166. EnumName(Data->FtpForcePasvIp, AutoSwitchNames),
  1167. EnumName(Data->FtpUseMlsd, AutoSwitchNames),
  1168. EnumName(Data->FtpListAll, AutoSwitchNames),
  1169. EnumName(Data->FtpHost, AutoSwitchNames)));
  1170. }
  1171. if (Data->FSProtocol == fsWebDAV)
  1172. {
  1173. FtpsOn = (Data->Ftps != ftpsNone);
  1174. ADF(L"HTTPS: %s [Client certificate: %s]",
  1175. (BooleanToEngStr(FtpsOn), LogSensitive(Data->TlsCertificateFile)));
  1176. }
  1177. if (FtpsOn)
  1178. {
  1179. if (Data->FSProtocol == fsFTP)
  1180. {
  1181. ADF(L"Session reuse: %s", (BooleanToEngStr(Data->SslSessionReuse)));
  1182. }
  1183. ADF(L"TLS/SSL versions: %s-%s", (GetTlsVersionName(Data->MinTlsVersion), GetTlsVersionName(Data->MaxTlsVersion)));
  1184. }
  1185. ADF(L"Local directory: %s, Remote directory: %s, Update: %s, Cache: %s",
  1186. ((Data->LocalDirectory.IsEmpty() ? UnicodeString(L"default") : Data->LocalDirectory),
  1187. (Data->RemoteDirectory.IsEmpty() ? UnicodeString(L"home") : Data->RemoteDirectory),
  1188. BooleanToEngStr(Data->UpdateDirectories),
  1189. BooleanToEngStr(Data->CacheDirectories)));
  1190. ADF(L"Cache directory changes: %s, Permanent: %s",
  1191. (BooleanToEngStr(Data->CacheDirectoryChanges),
  1192. BooleanToEngStr(Data->PreserveDirectoryChanges)));
  1193. ADF(L"Recycle bin: Delete to: %s, Overwritten to: %s, Bin path: %s",
  1194. (BooleanToEngStr(Data->DeleteToRecycleBin),
  1195. BooleanToEngStr(Data->OverwrittenToRecycleBin),
  1196. Data->RecycleBinPath));
  1197. if (Data->TrimVMSVersions)
  1198. {
  1199. ADF(L"Trim VMS versions: %s",
  1200. (BooleanToEngStr(Data->TrimVMSVersions)));
  1201. }
  1202. UnicodeString TimeInfo;
  1203. if ((Data->FSProtocol == fsSFTP) || (Data->FSProtocol == fsSFTPonly) || (Data->FSProtocol == fsSCPonly) || (Data->FSProtocol == fsWebDAV))
  1204. {
  1205. AddToList(TimeInfo, FORMAT(L"DST mode: %s", (EnumName(Data->DSTMode, DSTModeNames))), L";");
  1206. }
  1207. if ((Data->FSProtocol == fsSCPonly) || (Data->FSProtocol == fsFTP))
  1208. {
  1209. int TimeDifferenceMin = TimeToMinutes(Data->TimeDifference);
  1210. AddToList(TimeInfo, FORMAT(L"Timezone offset: %dh %dm", ((TimeDifferenceMin / MinsPerHour), (TimeDifferenceMin % MinsPerHour))), L";");
  1211. }
  1212. ADSTR(TimeInfo);
  1213. if (Data->FSProtocol == fsWebDAV)
  1214. {
  1215. ADF(L"Compression: %s",
  1216. (BooleanToEngStr(Data->Compression)));
  1217. }
  1218. AddSeparator();
  1219. }
  1220. }
  1221. //---------------------------------------------------------------------------
  1222. void __fastcall TSessionLog::AddOption(const UnicodeString & LogStr)
  1223. {
  1224. ADSTR(LogStr);
  1225. }
  1226. //---------------------------------------------------------------------------
  1227. void __fastcall TSessionLog::AddOptions(TOptions * Options)
  1228. {
  1229. Options->LogOptions(AddOption);
  1230. }
  1231. //---------------------------------------------------------------------------
  1232. #undef ADF
  1233. #undef ADSTR
  1234. //---------------------------------------------------------------------------
  1235. void __fastcall TSessionLog::AddSeparator()
  1236. {
  1237. Add(llMessage, L"--------------------------------------------------------------------------");
  1238. }
  1239. //---------------------------------------------------------------------------
  1240. //---------------------------------------------------------------------------
  1241. __fastcall TActionLog::TActionLog(TSessionUI * UI, TDateTime Started, TSessionData * SessionData,
  1242. TConfiguration * Configuration)
  1243. {
  1244. DebugAssert(UI != NULL);
  1245. DebugAssert(SessionData != NULL);
  1246. Init(UI, Started, SessionData, Configuration);
  1247. }
  1248. //---------------------------------------------------------------------------
  1249. __fastcall TActionLog::TActionLog(TDateTime Started, TConfiguration * Configuration)
  1250. {
  1251. Init(NULL, Started, NULL, Configuration);
  1252. // not associated with session, so no need to waiting for anything
  1253. ReflectSettings();
  1254. }
  1255. //---------------------------------------------------------------------------
  1256. void __fastcall TActionLog::Init(TSessionUI * UI, TDateTime Started, TSessionData * SessionData,
  1257. TConfiguration * Configuration)
  1258. {
  1259. FCriticalSection = new TCriticalSection;
  1260. FConfiguration = Configuration;
  1261. FUI = UI;
  1262. FSessionData = SessionData;
  1263. FStarted = Started;
  1264. FFile = NULL;
  1265. FCurrentLogFileName = L"";
  1266. FCurrentFileName = L"";
  1267. FLogging = false;
  1268. FClosed = false;
  1269. FFailed = false;
  1270. FPendingActions = new TList();
  1271. FIndent = L" ";
  1272. FInGroup = false;
  1273. FEnabled = true;
  1274. }
  1275. //---------------------------------------------------------------------------
  1276. __fastcall TActionLog::~TActionLog()
  1277. {
  1278. DebugAssert(FPendingActions->Count == 0);
  1279. delete FPendingActions;
  1280. FClosed = true;
  1281. ReflectSettings();
  1282. DebugAssert(FFile == NULL);
  1283. delete FCriticalSection;
  1284. }
  1285. //---------------------------------------------------------------------------
  1286. void __fastcall TActionLog::Add(const UnicodeString & Line)
  1287. {
  1288. DebugAssert(FConfiguration);
  1289. if (FLogging)
  1290. {
  1291. TGuard Guard(FCriticalSection);
  1292. if (FFile == NULL)
  1293. {
  1294. OpenLogFile();
  1295. }
  1296. if (FFile != NULL)
  1297. {
  1298. try
  1299. {
  1300. UTF8String UtfLine = UTF8String(Line);
  1301. size_t Written =
  1302. fwrite(UtfLine.c_str(), 1, UtfLine.Length(), (FILE *)FFile);
  1303. if (Written != static_cast<size_t>(UtfLine.Length()))
  1304. {
  1305. throw ECRTExtException(L"");
  1306. }
  1307. #ifdef _DEBUG
  1308. #endif
  1309. Written =
  1310. fwrite("\n", 1, 1, (FILE *)FFile);
  1311. if (Written != 1)
  1312. {
  1313. throw ECRTExtException(L"");
  1314. }
  1315. }
  1316. catch (Exception &E)
  1317. {
  1318. FCriticalSection->Release();
  1319. // avoid endless loop when trying to close tags when closing log, when logging has failed
  1320. if (!FFailed)
  1321. {
  1322. FFailed = true;
  1323. // We failed logging, turn it off and notify user.
  1324. FConfiguration->LogActions = false;
  1325. if (FConfiguration->LogActionsRequired)
  1326. {
  1327. throw EFatal(&E, LoadStr(LOG_FATAL_ERROR));
  1328. }
  1329. else
  1330. {
  1331. try
  1332. {
  1333. throw ExtException(&E, LoadStr(LOG_GEN_ERROR));
  1334. }
  1335. catch (Exception &E)
  1336. {
  1337. if (FUI != NULL)
  1338. {
  1339. FUI->HandleExtendedException(&E);
  1340. }
  1341. }
  1342. }
  1343. }
  1344. }
  1345. }
  1346. }
  1347. }
  1348. //---------------------------------------------------------------------------
  1349. void __fastcall TActionLog::AddIndented(const UnicodeString & Line)
  1350. {
  1351. Add(FIndent + Line);
  1352. }
  1353. //---------------------------------------------------------------------------
  1354. void __fastcall TActionLog::AddFailure(TStrings * Messages)
  1355. {
  1356. AddIndented(L"<failure>");
  1357. AddMessages(L" ", Messages);
  1358. AddIndented(L"</failure>");
  1359. }
  1360. //---------------------------------------------------------------------------
  1361. void __fastcall TActionLog::AddFailure(Exception * E)
  1362. {
  1363. TStrings * Messages = ExceptionToMoreMessages(E);
  1364. if (Messages != NULL)
  1365. {
  1366. try
  1367. {
  1368. AddFailure(Messages);
  1369. }
  1370. __finally
  1371. {
  1372. delete Messages;
  1373. }
  1374. }
  1375. }
  1376. //---------------------------------------------------------------------------
  1377. void __fastcall TActionLog::AddMessages(UnicodeString Indent, TStrings * Messages)
  1378. {
  1379. for (int Index = 0; Index < Messages->Count; Index++)
  1380. {
  1381. AddIndented(
  1382. FORMAT(Indent + L"<message>%s</message>", (XmlEscape(Messages->Strings[Index]))));
  1383. }
  1384. }
  1385. //---------------------------------------------------------------------------
  1386. void __fastcall TActionLog::ReflectSettings()
  1387. {
  1388. TGuard Guard(FCriticalSection);
  1389. bool ALogging =
  1390. !FClosed && FConfiguration->LogActions && Enabled;
  1391. if (ALogging && !FLogging)
  1392. {
  1393. FLogging = true;
  1394. Add(L"<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
  1395. UnicodeString SessionName =
  1396. (FSessionData != NULL) ? XmlAttributeEscape(FSessionData->SessionName) : UnicodeString(L"nosession");
  1397. Add(FORMAT(L"<session xmlns=\"http://winscp.net/schema/session/1.0\" name=\"%s\" start=\"%s\">",
  1398. (SessionName, StandardTimestamp())));
  1399. }
  1400. else if (!ALogging && FLogging)
  1401. {
  1402. if (FInGroup)
  1403. {
  1404. EndGroup();
  1405. }
  1406. // do not try to close the file, if it has not been opened, to avoid recursion
  1407. if (FFile != NULL)
  1408. {
  1409. Add(L"</session>");
  1410. }
  1411. CloseLogFile();
  1412. FLogging = false;
  1413. }
  1414. }
  1415. //---------------------------------------------------------------------------
  1416. void __fastcall TActionLog::CloseLogFile()
  1417. {
  1418. if (FFile != NULL)
  1419. {
  1420. fclose((FILE *)FFile);
  1421. FFile = NULL;
  1422. }
  1423. FCurrentLogFileName = L"";
  1424. FCurrentFileName = L"";
  1425. }
  1426. //---------------------------------------------------------------------------
  1427. void __fastcall TActionLog::OpenLogFile()
  1428. {
  1429. try
  1430. {
  1431. DebugAssert(FFile == NULL);
  1432. DebugAssert(FConfiguration != NULL);
  1433. FCurrentLogFileName = FConfiguration->ActionsLogFileName;
  1434. FFile = OpenFile(FCurrentLogFileName, FStarted, FSessionData, false, FCurrentFileName);
  1435. }
  1436. catch (Exception & E)
  1437. {
  1438. // We failed logging to file, turn it off and notify user.
  1439. FCurrentLogFileName = L"";
  1440. FCurrentFileName = L"";
  1441. FConfiguration->LogActions = false;
  1442. if (FConfiguration->LogActionsRequired)
  1443. {
  1444. throw EFatal(&E, LoadStr(LOG_FATAL_ERROR));
  1445. }
  1446. else
  1447. {
  1448. try
  1449. {
  1450. throw ExtException(&E, LoadStr(LOG_GEN_ERROR));
  1451. }
  1452. catch (Exception & E)
  1453. {
  1454. if (FUI != NULL)
  1455. {
  1456. // not to deadlock with TSessionLog::ReflectSettings invoked by FConfiguration->LogFileName setter above
  1457. TUnguard Unguard(FCriticalSection);
  1458. FUI->HandleExtendedException(&E);
  1459. }
  1460. }
  1461. }
  1462. }
  1463. }
  1464. //---------------------------------------------------------------------------
  1465. void __fastcall TActionLog::AddPendingAction(TSessionActionRecord * Action)
  1466. {
  1467. FPendingActions->Add(Action);
  1468. }
  1469. //---------------------------------------------------------------------------
  1470. void __fastcall TActionLog::RecordPendingActions()
  1471. {
  1472. while ((FPendingActions->Count > 0) &&
  1473. static_cast<TSessionActionRecord *>(FPendingActions->Items[0])->Record())
  1474. {
  1475. FPendingActions->Delete(0);
  1476. }
  1477. }
  1478. //---------------------------------------------------------------------------
  1479. void __fastcall TActionLog::BeginGroup(UnicodeString Name)
  1480. {
  1481. DebugAssert(!FInGroup);
  1482. FInGroup = true;
  1483. DebugAssert(FIndent == L" ");
  1484. AddIndented(FORMAT(L"<group name=\"%s\" start=\"%s\">",
  1485. (XmlAttributeEscape(Name), StandardTimestamp())));
  1486. FIndent = L" ";
  1487. }
  1488. //---------------------------------------------------------------------------
  1489. void __fastcall TActionLog::EndGroup()
  1490. {
  1491. DebugAssert(FInGroup);
  1492. FInGroup = false;
  1493. DebugAssert(FIndent == L" ");
  1494. FIndent = L" ";
  1495. // this is called from ReflectSettings that in turn is called when logging fails,
  1496. // so do not try to close the group, if it has not been opened, to avoid recursion
  1497. if (FFile != NULL)
  1498. {
  1499. AddIndented(L"</group>");
  1500. }
  1501. }
  1502. //---------------------------------------------------------------------------
  1503. void __fastcall TActionLog::SetEnabled(bool value)
  1504. {
  1505. if (Enabled != value)
  1506. {
  1507. FEnabled = value;
  1508. ReflectSettings();
  1509. }
  1510. }