SessionInfo.cpp 57 KB

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