1
0

SessionInfo.cpp 57 KB

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