SessionInfo.cpp 57 KB

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