SessionInfo.cpp 57 KB

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