SessionInfo.cpp 57 KB

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