SessionInfo.cpp 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485
  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. //---------------------------------------------------------------------------
  14. #pragma package(smart_init)
  15. //---------------------------------------------------------------------------
  16. UnicodeString __fastcall DoXmlEscape(UnicodeString Str, bool NewLine)
  17. {
  18. for (int i = 1; i <= Str.Length(); i++)
  19. {
  20. const wchar_t * Repl = NULL;
  21. switch (Str[i])
  22. {
  23. case L'&':
  24. Repl = L"amp;";
  25. break;
  26. case L'>':
  27. Repl = L"gt;";
  28. break;
  29. case L'<':
  30. Repl = L"lt;";
  31. break;
  32. case L'"':
  33. Repl = L"quot;";
  34. break;
  35. case L'\n':
  36. if (NewLine)
  37. {
  38. Repl = L"#10;";
  39. }
  40. break;
  41. case L'\r':
  42. Str.Delete(i, 1);
  43. i--;
  44. break;
  45. }
  46. if (Repl != NULL)
  47. {
  48. Str[i] = L'&';
  49. Str.Insert(Repl, i + 1);
  50. i += wcslen(Repl);
  51. }
  52. }
  53. return Str;
  54. }
  55. //---------------------------------------------------------------------------
  56. UnicodeString __fastcall XmlEscape(UnicodeString Str)
  57. {
  58. return DoXmlEscape(Str, false);
  59. }
  60. //---------------------------------------------------------------------------
  61. UnicodeString __fastcall XmlAttributeEscape(UnicodeString Str)
  62. {
  63. return DoXmlEscape(Str, true);
  64. }
  65. //---------------------------------------------------------------------------
  66. //---------------------------------------------------------------------------
  67. #pragma warn -inl
  68. class TSessionActionRecord
  69. {
  70. public:
  71. __fastcall TSessionActionRecord(TActionLog * Log, TLogAction Action) :
  72. FLog(Log),
  73. FAction(Action),
  74. FState(Opened),
  75. FRecursive(false),
  76. FErrorMessages(NULL),
  77. FNames(new TStringList()),
  78. FValues(new TStringList()),
  79. FFileList(NULL),
  80. FFile(NULL)
  81. {
  82. FLog->AddPendingAction(this);
  83. }
  84. __fastcall ~TSessionActionRecord()
  85. {
  86. delete FErrorMessages;
  87. delete FNames;
  88. delete FValues;
  89. delete FFileList;
  90. delete FFile;
  91. }
  92. void __fastcall Restart()
  93. {
  94. FState = Opened;
  95. FRecursive = false;
  96. delete FErrorMessages;
  97. FErrorMessages = NULL;
  98. delete FFileList;
  99. FFileList = NULL;
  100. delete FFile;
  101. FFile = NULL;
  102. FNames->Clear();
  103. FValues->Clear();
  104. }
  105. bool __fastcall Record()
  106. {
  107. bool Result = (FState != Opened);
  108. if (Result)
  109. {
  110. if (FLog->FLogging && (FState != Cancelled))
  111. {
  112. const wchar_t * Name = ActionName();
  113. UnicodeString Attrs;
  114. if (FRecursive)
  115. {
  116. Attrs = L" recursive=\"true\"";
  117. }
  118. FLog->AddIndented(FORMAT(L"<%s%s>", (Name, Attrs)));
  119. for (int Index = 0; Index < FNames->Count; Index++)
  120. {
  121. UnicodeString Value = FValues->Strings[Index];
  122. if (Value.IsEmpty())
  123. {
  124. FLog->AddIndented(FORMAT(L" <%s />", (FNames->Strings[Index])));
  125. }
  126. else
  127. {
  128. FLog->AddIndented(FORMAT(L" <%s value=\"%s\" />",
  129. (FNames->Strings[Index], XmlAttributeEscape(Value))));
  130. }
  131. }
  132. if (FFileList != NULL)
  133. {
  134. FLog->AddIndented(L" <files>");
  135. for (int Index = 0; Index < FFileList->Count; Index++)
  136. {
  137. TRemoteFile * File = FFileList->Files[Index];
  138. FLog->AddIndented(L" <file>");
  139. FLog->AddIndented(FORMAT(L" <filename value=\"%s\" />", (XmlAttributeEscape(File->FileName))));
  140. FLog->AddIndented(FORMAT(L" <type value=\"%s\" />", (XmlAttributeEscape(File->Type))));
  141. if (!File->IsDirectory)
  142. {
  143. FLog->AddIndented(FORMAT(L" <size value=\"%s\" />", (IntToStr(File->Size))));
  144. }
  145. FLog->AddIndented(FORMAT(L" <modification value=\"%s\" />", (StandardTimestamp(File->Modification))));
  146. FLog->AddIndented(FORMAT(L" <permissions value=\"%s\" />", (XmlAttributeEscape(File->Rights->Text))));
  147. if (File->Owner.IsSet)
  148. {
  149. FLog->AddIndented(FORMAT(L" <owner value=\"%s\" />", (XmlAttributeEscape(File->Owner.DisplayText))));
  150. }
  151. if (File->Group.IsSet)
  152. {
  153. FLog->AddIndented(FORMAT(L" <group value=\"%s\" />", (XmlAttributeEscape(File->Group.DisplayText))));
  154. }
  155. FLog->AddIndented(L" </file>");
  156. }
  157. FLog->AddIndented(L" </files>");
  158. }
  159. if (FFile != NULL)
  160. {
  161. FLog->AddIndented(L" <file>");
  162. FLog->AddIndented(FORMAT(L" <type value=\"%s\" />", (XmlAttributeEscape(FFile->Type))));
  163. if (!FFile->IsDirectory)
  164. {
  165. FLog->AddIndented(FORMAT(L" <size value=\"%s\" />", (IntToStr(FFile->Size))));
  166. }
  167. FLog->AddIndented(FORMAT(L" <modification value=\"%s\" />", (StandardTimestamp(FFile->Modification))));
  168. FLog->AddIndented(FORMAT(L" <permissions value=\"%s\" />", (XmlAttributeEscape(FFile->Rights->Text))));
  169. FLog->AddIndented(L" </file>");
  170. }
  171. if (FState == RolledBack)
  172. {
  173. if (FErrorMessages != NULL)
  174. {
  175. FLog->AddIndented(L" <result success=\"false\">");
  176. FLog->AddMessages(L" ", FErrorMessages);
  177. FLog->AddIndented(L" </result>");
  178. }
  179. else
  180. {
  181. FLog->AddIndented(L" <result success=\"false\" />");
  182. }
  183. }
  184. else
  185. {
  186. FLog->AddIndented(L" <result success=\"true\" />");
  187. }
  188. FLog->AddIndented(FORMAT(L"</%s>", (Name)));
  189. }
  190. delete this;
  191. }
  192. return Result;
  193. }
  194. void __fastcall Commit()
  195. {
  196. Close(Committed);
  197. }
  198. void __fastcall Rollback(Exception * E)
  199. {
  200. assert(FErrorMessages == NULL);
  201. FErrorMessages = ExceptionToMoreMessages(E);
  202. Close(RolledBack);
  203. }
  204. void __fastcall Cancel()
  205. {
  206. Close(Cancelled);
  207. }
  208. void __fastcall FileName(const UnicodeString & FileName)
  209. {
  210. Parameter(L"filename", FileName);
  211. }
  212. void __fastcall Destination(const UnicodeString & Destination)
  213. {
  214. Parameter(L"destination", Destination);
  215. }
  216. void __fastcall Rights(const TRights & Rights)
  217. {
  218. Parameter(L"permissions", Rights.Text);
  219. }
  220. void __fastcall Modification(const TDateTime & DateTime)
  221. {
  222. Parameter(L"modification", StandardTimestamp(DateTime));
  223. }
  224. void __fastcall Recursive()
  225. {
  226. FRecursive = true;
  227. }
  228. void __fastcall Command(const UnicodeString & Command)
  229. {
  230. Parameter(L"command", Command);
  231. }
  232. void __fastcall AddOutput(UnicodeString Output, bool StdError)
  233. {
  234. const wchar_t * Name = (StdError ? L"erroroutput" : L"output");
  235. int Index = FNames->IndexOf(Name);
  236. if (Index >= 0)
  237. {
  238. FValues->Strings[Index] = FValues->Strings[Index] + L"\r\n" + Output;
  239. }
  240. else
  241. {
  242. Parameter(Name, Output);
  243. }
  244. }
  245. void __fastcall ExitCode(int ExitCode)
  246. {
  247. Parameter(L"exitcode", IntToStr(ExitCode));
  248. }
  249. void __fastcall Checksum(const UnicodeString & Alg, const UnicodeString & Checksum)
  250. {
  251. Parameter(L"algorithm", Alg);
  252. Parameter(L"checksum", Checksum);
  253. }
  254. void __fastcall Cwd(const UnicodeString & Path)
  255. {
  256. Parameter(L"cwd", Path);
  257. }
  258. void __fastcall FileList(TRemoteFileList * FileList)
  259. {
  260. if (FFileList == NULL)
  261. {
  262. FFileList = new TRemoteFileList();
  263. }
  264. FileList->DuplicateTo(FFileList);
  265. }
  266. void __fastcall File(TRemoteFile * File)
  267. {
  268. if (FFile != NULL)
  269. {
  270. delete FFile;
  271. }
  272. FFile = File->Duplicate(true);
  273. }
  274. protected:
  275. enum TState { Opened, Committed, RolledBack, Cancelled };
  276. inline void __fastcall Close(TState State)
  277. {
  278. assert(FState == Opened);
  279. FState = State;
  280. FLog->RecordPendingActions();
  281. }
  282. const wchar_t * __fastcall ActionName()
  283. {
  284. switch (FAction)
  285. {
  286. case laUpload: return L"upload";
  287. case laDownload: return L"download";
  288. case laTouch: return L"touch";
  289. case laChmod: return L"chmod";
  290. case laMkdir: return L"mkdir";
  291. case laRm: return L"rm";
  292. case laMv: return L"mv";
  293. case laCall: return L"call";
  294. case laLs: return L"ls";
  295. case laStat: return L"stat";
  296. case laChecksum: return L"checksum";
  297. case laCwd: return L"cwd";
  298. default: FAIL; return L"";
  299. }
  300. }
  301. void __fastcall Parameter(const UnicodeString & Name, const UnicodeString & Value = L"")
  302. {
  303. FNames->Add(Name);
  304. FValues->Add(Value);
  305. }
  306. private:
  307. TActionLog * FLog;
  308. TLogAction FAction;
  309. TState FState;
  310. bool FRecursive;
  311. TStrings * FErrorMessages;
  312. TStrings * FNames;
  313. TStrings * FValues;
  314. TRemoteFileList * FFileList;
  315. TRemoteFile * FFile;
  316. };
  317. #pragma warn .inl
  318. //---------------------------------------------------------------------------
  319. //---------------------------------------------------------------------------
  320. __fastcall TSessionAction::TSessionAction(TActionLog * Log, TLogAction Action)
  321. {
  322. if (Log->FLogging)
  323. {
  324. FRecord = new TSessionActionRecord(Log, Action);
  325. }
  326. else
  327. {
  328. FRecord = NULL;
  329. }
  330. }
  331. //---------------------------------------------------------------------------
  332. __fastcall TSessionAction::~TSessionAction()
  333. {
  334. if (FRecord != NULL)
  335. {
  336. Commit();
  337. }
  338. }
  339. //---------------------------------------------------------------------------
  340. void __fastcall TSessionAction::Restart()
  341. {
  342. if (FRecord != NULL)
  343. {
  344. FRecord->Restart();
  345. }
  346. }
  347. //---------------------------------------------------------------------------
  348. void __fastcall TSessionAction::Commit()
  349. {
  350. if (FRecord != NULL)
  351. {
  352. TSessionActionRecord * Record = FRecord;
  353. FRecord = NULL;
  354. Record->Commit();
  355. }
  356. }
  357. //---------------------------------------------------------------------------
  358. void __fastcall TSessionAction::Rollback(Exception * E)
  359. {
  360. if (FRecord != NULL)
  361. {
  362. TSessionActionRecord * Record = FRecord;
  363. FRecord = NULL;
  364. Record->Rollback(E);
  365. }
  366. }
  367. //---------------------------------------------------------------------------
  368. void __fastcall TSessionAction::Cancel()
  369. {
  370. if (FRecord != NULL)
  371. {
  372. TSessionActionRecord * Record = FRecord;
  373. FRecord = NULL;
  374. Record->Cancel();
  375. }
  376. }
  377. //---------------------------------------------------------------------------
  378. //---------------------------------------------------------------------------
  379. __fastcall TFileSessionAction::TFileSessionAction(TActionLog * Log, TLogAction Action) :
  380. TSessionAction(Log, Action)
  381. {
  382. }
  383. //---------------------------------------------------------------------------
  384. __fastcall TFileSessionAction::TFileSessionAction(
  385. TActionLog * Log, TLogAction Action, const UnicodeString & AFileName) :
  386. TSessionAction(Log, Action)
  387. {
  388. FileName(AFileName);
  389. }
  390. //---------------------------------------------------------------------------
  391. void __fastcall TFileSessionAction::FileName(const UnicodeString & FileName)
  392. {
  393. if (FRecord != NULL)
  394. {
  395. FRecord->FileName(FileName);
  396. }
  397. }
  398. //---------------------------------------------------------------------------
  399. //---------------------------------------------------------------------------
  400. __fastcall TFileLocationSessionAction::TFileLocationSessionAction(
  401. TActionLog * Log, TLogAction Action) :
  402. TFileSessionAction(Log, Action)
  403. {
  404. }
  405. //---------------------------------------------------------------------------
  406. __fastcall TFileLocationSessionAction::TFileLocationSessionAction(
  407. TActionLog * Log, TLogAction Action, const UnicodeString & FileName) :
  408. TFileSessionAction(Log, Action, FileName)
  409. {
  410. }
  411. //---------------------------------------------------------------------------
  412. void __fastcall TFileLocationSessionAction::Destination(const UnicodeString & Destination)
  413. {
  414. if (FRecord != NULL)
  415. {
  416. FRecord->Destination(Destination);
  417. }
  418. }
  419. //---------------------------------------------------------------------------
  420. //---------------------------------------------------------------------------
  421. __fastcall TUploadSessionAction::TUploadSessionAction(TActionLog * Log) :
  422. TFileLocationSessionAction(Log, laUpload)
  423. {
  424. }
  425. //---------------------------------------------------------------------------
  426. //---------------------------------------------------------------------------
  427. __fastcall TDownloadSessionAction::TDownloadSessionAction(TActionLog * Log) :
  428. TFileLocationSessionAction(Log, laDownload)
  429. {
  430. }
  431. //---------------------------------------------------------------------------
  432. //---------------------------------------------------------------------------
  433. __fastcall TChmodSessionAction::TChmodSessionAction(
  434. TActionLog * Log, const UnicodeString & FileName) :
  435. TFileSessionAction(Log, laChmod, FileName)
  436. {
  437. }
  438. //---------------------------------------------------------------------------
  439. void __fastcall TChmodSessionAction::Recursive()
  440. {
  441. if (FRecord != NULL)
  442. {
  443. FRecord->Recursive();
  444. }
  445. }
  446. //---------------------------------------------------------------------------
  447. __fastcall TChmodSessionAction::TChmodSessionAction(
  448. TActionLog * Log, const UnicodeString & FileName, const TRights & ARights) :
  449. TFileSessionAction(Log, laChmod, FileName)
  450. {
  451. Rights(ARights);
  452. }
  453. //---------------------------------------------------------------------------
  454. void __fastcall TChmodSessionAction::Rights(const TRights & Rights)
  455. {
  456. if (FRecord != NULL)
  457. {
  458. FRecord->Rights(Rights);
  459. }
  460. }
  461. //---------------------------------------------------------------------------
  462. __fastcall TTouchSessionAction::TTouchSessionAction(
  463. TActionLog * Log, const UnicodeString & FileName, const TDateTime & Modification) :
  464. TFileSessionAction(Log, laTouch, FileName)
  465. {
  466. if (FRecord != NULL)
  467. {
  468. FRecord->Modification(Modification);
  469. }
  470. }
  471. //---------------------------------------------------------------------------
  472. __fastcall TMkdirSessionAction::TMkdirSessionAction(
  473. TActionLog * Log, const UnicodeString & FileName) :
  474. TFileSessionAction(Log, laMkdir, FileName)
  475. {
  476. }
  477. //---------------------------------------------------------------------------
  478. __fastcall TRmSessionAction::TRmSessionAction(
  479. TActionLog * Log, const UnicodeString & FileName) :
  480. TFileSessionAction(Log, laRm, FileName)
  481. {
  482. }
  483. //---------------------------------------------------------------------------
  484. void __fastcall TRmSessionAction::Recursive()
  485. {
  486. if (FRecord != NULL)
  487. {
  488. FRecord->Recursive();
  489. }
  490. }
  491. //---------------------------------------------------------------------------
  492. __fastcall TMvSessionAction::TMvSessionAction(TActionLog * Log,
  493. const UnicodeString & FileName, const UnicodeString & ADestination) :
  494. TFileLocationSessionAction(Log, laMv, FileName)
  495. {
  496. Destination(ADestination);
  497. }
  498. //---------------------------------------------------------------------------
  499. __fastcall TCallSessionAction::TCallSessionAction(TActionLog * Log,
  500. const UnicodeString & Command, const UnicodeString & Destination) :
  501. TSessionAction(Log, laCall)
  502. {
  503. if (FRecord != NULL)
  504. {
  505. FRecord->Command(Command);
  506. FRecord->Destination(Destination);
  507. }
  508. }
  509. //---------------------------------------------------------------------------
  510. void __fastcall TCallSessionAction::AddOutput(const UnicodeString & Output, bool StdError)
  511. {
  512. if (FRecord != NULL)
  513. {
  514. FRecord->AddOutput(Output, StdError);
  515. }
  516. }
  517. //---------------------------------------------------------------------------
  518. void __fastcall TCallSessionAction::ExitCode(int ExitCode)
  519. {
  520. if (FRecord != NULL)
  521. {
  522. FRecord->ExitCode(ExitCode);
  523. }
  524. }
  525. //---------------------------------------------------------------------------
  526. __fastcall TLsSessionAction::TLsSessionAction(TActionLog * Log,
  527. const UnicodeString & Destination) :
  528. TSessionAction(Log, laLs)
  529. {
  530. if (FRecord != NULL)
  531. {
  532. FRecord->Destination(Destination);
  533. }
  534. }
  535. //---------------------------------------------------------------------------
  536. void __fastcall TLsSessionAction::FileList(TRemoteFileList * FileList)
  537. {
  538. if (FRecord != NULL)
  539. {
  540. FRecord->FileList(FileList);
  541. }
  542. }
  543. //---------------------------------------------------------------------------
  544. //---------------------------------------------------------------------------
  545. __fastcall TStatSessionAction::TStatSessionAction(TActionLog * Log, const UnicodeString & FileName) :
  546. TFileSessionAction(Log, laStat, FileName)
  547. {
  548. }
  549. //---------------------------------------------------------------------------
  550. void __fastcall TStatSessionAction::File(TRemoteFile * File)
  551. {
  552. if (FRecord != NULL)
  553. {
  554. FRecord->File(File);
  555. }
  556. }
  557. //---------------------------------------------------------------------------
  558. //---------------------------------------------------------------------------
  559. __fastcall TChecksumSessionAction::TChecksumSessionAction(TActionLog * Log) :
  560. TFileSessionAction(Log, laChecksum)
  561. {
  562. }
  563. //---------------------------------------------------------------------------
  564. void __fastcall TChecksumSessionAction::Checksum(const UnicodeString & Alg, const UnicodeString & Checksum)
  565. {
  566. if (FRecord != NULL)
  567. {
  568. FRecord->Checksum(Alg, Checksum);
  569. }
  570. }
  571. //---------------------------------------------------------------------------
  572. //---------------------------------------------------------------------------
  573. __fastcall TCwdSessionAction::TCwdSessionAction(TActionLog * Log, const UnicodeString & Path) :
  574. TSessionAction(Log, laCwd)
  575. {
  576. if (FRecord != NULL)
  577. {
  578. FRecord->Cwd(Path);
  579. }
  580. }
  581. //---------------------------------------------------------------------------
  582. //---------------------------------------------------------------------------
  583. TSessionInfo::TSessionInfo()
  584. {
  585. LoginTime = Now();
  586. }
  587. //---------------------------------------------------------------------------
  588. TFileSystemInfo::TFileSystemInfo()
  589. {
  590. memset(&IsCapable, false, sizeof(IsCapable));
  591. }
  592. //---------------------------------------------------------------------------
  593. //---------------------------------------------------------------------------
  594. FILE * __fastcall OpenFile(UnicodeString LogFileName, TSessionData * SessionData, bool Append, UnicodeString & NewFileName)
  595. {
  596. FILE * Result;
  597. UnicodeString ANewFileName = GetExpandedLogFileName(LogFileName, SessionData);
  598. Result = _wfopen(ApiPath(ANewFileName).c_str(), (Append ? L"a" : L"w"));
  599. if (Result != NULL)
  600. {
  601. setvbuf(Result, NULL, _IONBF, BUFSIZ);
  602. NewFileName = ANewFileName;
  603. }
  604. else
  605. {
  606. throw ECRTExtException(FMTLOAD(LOG_OPENERROR, (ANewFileName)));
  607. }
  608. return Result;
  609. }
  610. //---------------------------------------------------------------------------
  611. //---------------------------------------------------------------------------
  612. const wchar_t *LogLineMarks = L"<>!.*";
  613. __fastcall TSessionLog::TSessionLog(TSessionUI* UI, TSessionData * SessionData,
  614. TConfiguration * Configuration):
  615. TStringList()
  616. {
  617. FCriticalSection = new TCriticalSection;
  618. FLogging = false;
  619. FConfiguration = Configuration;
  620. FParent = NULL;
  621. FUI = UI;
  622. FSessionData = SessionData;
  623. FFile = NULL;
  624. FLoggedLines = 0;
  625. FTopIndex = -1;
  626. FCurrentLogFileName = L"";
  627. FCurrentFileName = L"";
  628. FClosed = false;
  629. }
  630. //---------------------------------------------------------------------------
  631. __fastcall TSessionLog::~TSessionLog()
  632. {
  633. FClosed = true;
  634. ReflectSettings();
  635. assert(FFile == NULL);
  636. delete FCriticalSection;
  637. }
  638. //---------------------------------------------------------------------------
  639. void __fastcall TSessionLog::Lock()
  640. {
  641. FCriticalSection->Enter();
  642. }
  643. //---------------------------------------------------------------------------
  644. void __fastcall TSessionLog::Unlock()
  645. {
  646. FCriticalSection->Leave();
  647. }
  648. //---------------------------------------------------------------------------
  649. UnicodeString __fastcall TSessionLog::GetSessionName()
  650. {
  651. assert(FSessionData != NULL);
  652. return FSessionData->SessionName;
  653. }
  654. //---------------------------------------------------------------------------
  655. UnicodeString __fastcall TSessionLog::GetLine(Integer Index)
  656. {
  657. return Strings[Index - FTopIndex];
  658. }
  659. //---------------------------------------------------------------------------
  660. TLogLineType __fastcall TSessionLog::GetType(int Index)
  661. {
  662. return (TLogLineType)Objects[Index - FTopIndex];
  663. }
  664. //---------------------------------------------------------------------------
  665. void __fastcall TSessionLog::DoAddToParent(TLogLineType Type, const UnicodeString & Line)
  666. {
  667. assert(FParent != NULL);
  668. FParent->Add(Type, Line);
  669. }
  670. //---------------------------------------------------------------------------
  671. void __fastcall TSessionLog::DoAddToSelf(TLogLineType Type, const UnicodeString & Line)
  672. {
  673. if (FTopIndex < 0)
  674. {
  675. FTopIndex = 0;
  676. }
  677. TStringList::AddObject(Line, (TObject*)Type);
  678. FLoggedLines++;
  679. if (LogToFile())
  680. {
  681. if (FFile == NULL)
  682. {
  683. OpenLogFile();
  684. }
  685. if (FFile != NULL)
  686. {
  687. UnicodeString Timestamp = FormatDateTime(L" yyyy-mm-dd hh:nn:ss.zzz ", Now());
  688. UTF8String UtfLine = UTF8String(UnicodeString(LogLineMarks[Type]) + Timestamp + Line + "\n");
  689. fwrite(UtfLine.c_str(), UtfLine.Length(), 1, (FILE *)FFile);
  690. }
  691. }
  692. }
  693. //---------------------------------------------------------------------------
  694. void __fastcall TSessionLog::DoAdd(TLogLineType Type, UnicodeString Line,
  695. void __fastcall (__closure *f)(TLogLineType Type, const UnicodeString & Line))
  696. {
  697. UnicodeString Prefix;
  698. if (!Name.IsEmpty())
  699. {
  700. Prefix = L"[" + Name + L"] ";
  701. }
  702. while (!Line.IsEmpty())
  703. {
  704. f(Type, Prefix + CutToChar(Line, L'\n', false));
  705. }
  706. }
  707. //---------------------------------------------------------------------------
  708. void __fastcall TSessionLog::Add(TLogLineType Type, const UnicodeString & Line)
  709. {
  710. assert(FConfiguration);
  711. if (Logging)
  712. {
  713. try
  714. {
  715. if (FParent != NULL)
  716. {
  717. DoAdd(Type, Line, DoAddToParent);
  718. }
  719. else
  720. {
  721. TGuard Guard(FCriticalSection);
  722. BeginUpdate();
  723. try
  724. {
  725. DoAdd(Type, Line, DoAddToSelf);
  726. }
  727. __finally
  728. {
  729. DeleteUnnecessary();
  730. EndUpdate();
  731. }
  732. }
  733. }
  734. catch (Exception &E)
  735. {
  736. // We failed logging, turn it off and notify user.
  737. FConfiguration->Logging = false;
  738. try
  739. {
  740. throw ExtException(&E, LoadStr(LOG_GEN_ERROR));
  741. }
  742. catch (Exception &E)
  743. {
  744. AddException(&E);
  745. FUI->HandleExtendedException(&E);
  746. }
  747. }
  748. }
  749. }
  750. //---------------------------------------------------------------------------
  751. void __fastcall TSessionLog::AddException(Exception * E)
  752. {
  753. if (E != NULL)
  754. {
  755. Add(llException, ExceptionLogString(E));
  756. }
  757. }
  758. //---------------------------------------------------------------------------
  759. void __fastcall TSessionLog::ReflectSettings()
  760. {
  761. TGuard Guard(FCriticalSection);
  762. bool ALogging =
  763. !FClosed &&
  764. ((FParent != NULL) || FConfiguration->Logging);
  765. if (FLogging != ALogging)
  766. {
  767. FLogging = ALogging;
  768. StateChange();
  769. }
  770. // if logging to file was turned off or log file was changed -> close current log file
  771. if ((FFile != NULL) &&
  772. (!LogToFile() || (FCurrentLogFileName != FConfiguration->LogFileName)))
  773. {
  774. CloseLogFile();
  775. }
  776. DeleteUnnecessary();
  777. }
  778. //---------------------------------------------------------------------------
  779. bool __fastcall TSessionLog::LogToFile()
  780. {
  781. return Logging && FConfiguration->LogToFile && (FParent == NULL);
  782. }
  783. //---------------------------------------------------------------------------
  784. void __fastcall TSessionLog::CloseLogFile()
  785. {
  786. if (FFile != NULL)
  787. {
  788. fclose((FILE *)FFile);
  789. FFile = NULL;
  790. }
  791. FCurrentLogFileName = L"";
  792. FCurrentFileName = L"";
  793. StateChange();
  794. }
  795. //---------------------------------------------------------------------------
  796. void __fastcall TSessionLog::OpenLogFile()
  797. {
  798. try
  799. {
  800. assert(FFile == NULL);
  801. assert(FConfiguration != NULL);
  802. FCurrentLogFileName = FConfiguration->LogFileName;
  803. FFile = OpenFile(FCurrentLogFileName, FSessionData, FConfiguration->LogFileAppend, FCurrentFileName);
  804. }
  805. catch (Exception & E)
  806. {
  807. // We failed logging to file, turn it off and notify user.
  808. FCurrentLogFileName = L"";
  809. FCurrentFileName = L"";
  810. FConfiguration->LogFileName = UnicodeString();
  811. try
  812. {
  813. throw ExtException(&E, LoadStr(LOG_GEN_ERROR));
  814. }
  815. catch (Exception & E)
  816. {
  817. AddException(&E);
  818. FUI->HandleExtendedException(&E);
  819. }
  820. }
  821. StateChange();
  822. }
  823. //---------------------------------------------------------------------------
  824. void __fastcall TSessionLog::StateChange()
  825. {
  826. if (FOnStateChange != NULL)
  827. {
  828. FOnStateChange(this);
  829. }
  830. }
  831. //---------------------------------------------------------------------------
  832. void __fastcall TSessionLog::DeleteUnnecessary()
  833. {
  834. BeginUpdate();
  835. try
  836. {
  837. if (!Logging || (FParent != NULL))
  838. {
  839. Clear();
  840. }
  841. else
  842. {
  843. while (!FConfiguration->LogWindowComplete && (Count > FConfiguration->LogWindowLines))
  844. {
  845. Delete(0);
  846. FTopIndex++;
  847. }
  848. }
  849. }
  850. __finally
  851. {
  852. EndUpdate();
  853. }
  854. }
  855. //---------------------------------------------------------------------------
  856. void __fastcall TSessionLog::AddSystemInfo()
  857. {
  858. AddStartupInfo(true);
  859. }
  860. //---------------------------------------------------------------------------
  861. void __fastcall TSessionLog::AddStartupInfo()
  862. {
  863. AddStartupInfo(false);
  864. }
  865. //---------------------------------------------------------------------------
  866. void __fastcall TSessionLog::AddStartupInfo(bool System)
  867. {
  868. TSessionData * Data = (System ? NULL : FSessionData);
  869. if (Logging)
  870. {
  871. if (FParent != NULL)
  872. {
  873. // do not add session info for secondary session
  874. // (this should better be handled in the TSecondaryTerminal)
  875. }
  876. else
  877. {
  878. DoAddStartupInfo(Data);
  879. }
  880. }
  881. }
  882. //---------------------------------------------------------------------------
  883. UnicodeString __fastcall TSessionLog::GetTlsVersionName(TTlsVersion TlsVersion)
  884. {
  885. switch (TlsVersion)
  886. {
  887. default:
  888. FAIL;
  889. case ssl2:
  890. return "SSLv2";
  891. case ssl3:
  892. return "SSLv3";
  893. case tls10:
  894. return "TLSv1.0";
  895. case tls11:
  896. return "TLSv1.1";
  897. case tls12:
  898. return "TLSv1.2";
  899. }
  900. }
  901. //---------------------------------------------------------------------------
  902. UnicodeString __fastcall TSessionLog::LogSensitive(const UnicodeString & Str)
  903. {
  904. if (FConfiguration->LogSensitive && !Str.IsEmpty())
  905. {
  906. return Str;
  907. }
  908. else
  909. {
  910. return BooleanToEngStr(!Str.IsEmpty());
  911. }
  912. }
  913. //---------------------------------------------------------------------------
  914. #define ADSTR(S) DoAdd(llMessage, S, DoAddToSelf);
  915. #define ADF(S, F) ADSTR(FORMAT(S, F));
  916. //---------------------------------------------------------------------------
  917. void __fastcall TSessionLog::DoAddStartupInfo(TSessionData * Data)
  918. {
  919. TGuard Guard(FCriticalSection);
  920. BeginUpdate();
  921. try
  922. {
  923. if (Data == NULL)
  924. {
  925. AddSeparator();
  926. ADF(L"WinSCP %s (OS %s)", (FConfiguration->VersionStr, FConfiguration->OSVersionStr));
  927. THierarchicalStorage * Storage = FConfiguration->CreateConfigStorage();
  928. try
  929. {
  930. ADF(L"Configuration: %s", (Storage->Source));
  931. }
  932. __finally
  933. {
  934. delete Storage;
  935. }
  936. wchar_t UserName[UNLEN + 1];
  937. unsigned long UserNameSize = LENOF(UserName);
  938. if (ALWAYS_FALSE(!GetUserNameEx(NameSamCompatible, UserName, &UserNameSize)))
  939. {
  940. wcscpy(UserName, L"<Failed to retrieve username>");
  941. }
  942. UnicodeString LogStr;
  943. if (FConfiguration->LogProtocol <= 0)
  944. {
  945. LogStr = L"Normal";
  946. }
  947. else if (FConfiguration->LogProtocol == 1)
  948. {
  949. LogStr = L"Debug 1";
  950. }
  951. else if (FConfiguration->LogProtocol >= 2)
  952. {
  953. LogStr = L"Debug 2";
  954. }
  955. if (FConfiguration->LogSensitive)
  956. {
  957. LogStr += L", Logging passwords";
  958. }
  959. ADF(L"Log level: %s", (LogStr));
  960. ADF(L"Local account: %s", (UserName));
  961. ADF(L"Working directory: %s", (GetCurrentDir()));
  962. ADF(L"Process ID: %d", (int(GetCurrentProcessId())));
  963. ADF(L"Command-line: %s", (CmdLine));
  964. if (FConfiguration->LogProtocol >= 1)
  965. {
  966. AddOptions(GetGlobalOptions());
  967. }
  968. ADF(L"Time zone: %s", (GetTimeZoneLogString()));
  969. if (!AdjustClockForDSTEnabled())
  970. {
  971. ADSTR(L"Warning: System option \"Automatically adjust clock for Daylight Saving Time\" is disabled, timestamps will not be represented correctly");
  972. }
  973. ADF(L"Login time: %s", (FormatDateTime(L"dddddd tt", Now())));
  974. AddSeparator();
  975. }
  976. else
  977. {
  978. ADF(L"Session name: %s (%s)", (Data->SessionName, Data->Source));
  979. ADF(L"Host name: %s (Port: %d)", (Data->HostNameExpanded, Data->PortNumber));
  980. ADF(L"User name: %s (Password: %s, Key file: %s)",
  981. (Data->UserNameExpanded, LogSensitive(Data->Password),
  982. LogSensitive(Data->PublicKeyFile)));
  983. if (Data->UsesSsh)
  984. {
  985. ADF(L"Tunnel: %s", (BooleanToEngStr(Data->Tunnel)));
  986. if (Data->Tunnel)
  987. {
  988. ADF(L"Tunnel: Host name: %s (Port: %d)", (Data->TunnelHostName, Data->TunnelPortNumber));
  989. ADF(L"Tunnel: User name: %s (Password: %s, Key file: %s)",
  990. (Data->TunnelUserName,
  991. LogSensitive(Data->TunnelPassword),
  992. LogSensitive(Data->TunnelPublicKeyFile)));
  993. ADF(L"Tunnel: Local port number: %d", (Data->TunnelLocalPortNumber));
  994. }
  995. }
  996. ADF(L"Transfer Protocol: %s", (Data->FSProtocolStr));
  997. wchar_t * PingTypes = L"-NC";
  998. if (Data->UsesSsh || (Data->FSProtocol == fsFTP))
  999. {
  1000. TPingType PingType;
  1001. int PingInterval;
  1002. if (Data->FSProtocol == fsFTP)
  1003. {
  1004. PingType = Data->FtpPingType;
  1005. PingInterval = Data->FtpPingInterval;
  1006. }
  1007. else
  1008. {
  1009. PingType = Data->PingType;
  1010. PingInterval = Data->PingInterval;
  1011. }
  1012. ADF(L"Ping type: %s, Ping interval: %d sec; Timeout: %d sec",
  1013. (UnicodeString(PingTypes[PingType]), PingInterval, Data->Timeout));
  1014. ADF(L"Disable Nagle: %s",
  1015. (BooleanToEngStr(Data->TcpNoDelay)));
  1016. }
  1017. ADF(L"Proxy: %s",
  1018. ((Data->FtpProxyLogonType != 0) ?
  1019. FORMAT(L"FTP proxy %d", (Data->FtpProxyLogonType)) :
  1020. UnicodeString(ProxyMethodList[Data->ProxyMethod])));
  1021. if ((Data->FtpProxyLogonType != 0) || (Data->ProxyMethod != ::pmNone))
  1022. {
  1023. ADF(L"HostName: %s (Port: %d); Username: %s; Passwd: %s",
  1024. (Data->ProxyHost, Data->ProxyPort,
  1025. Data->ProxyUsername, LogSensitive(Data->ProxyPassword)));
  1026. if (Data->ProxyMethod == pmTelnet)
  1027. {
  1028. ADF(L"Telnet command: %s", (Data->ProxyTelnetCommand));
  1029. }
  1030. if (Data->ProxyMethod == pmCmd)
  1031. {
  1032. ADF(L"Local command: %s", (Data->ProxyLocalCommand));
  1033. }
  1034. }
  1035. if (Data->UsesSsh || (Data->FSProtocol == fsFTP))
  1036. {
  1037. ADF(L"Send buffer: %d", (Data->SendBuf));
  1038. }
  1039. wchar_t const * BugFlags = L"+-A";
  1040. if (Data->UsesSsh)
  1041. {
  1042. ADF(L"SSH protocol version: %s; Compression: %s",
  1043. (Data->SshProtStr, BooleanToEngStr(Data->Compression)));
  1044. ADF(L"Bypass authentication: %s",
  1045. (BooleanToEngStr(Data->SshNoUserAuth)));
  1046. ADF(L"Try agent: %s; Agent forwarding: %s; TIS/CryptoCard: %s; KI: %s; GSSAPI: %s",
  1047. (BooleanToEngStr(Data->TryAgent), BooleanToEngStr(Data->AgentFwd), BooleanToEngStr(Data->AuthTIS),
  1048. BooleanToEngStr(Data->AuthKI), BooleanToEngStr(Data->AuthGSSAPI)));
  1049. if (Data->AuthGSSAPI)
  1050. {
  1051. ADF(L"GSSAPI: Forwarding: %s; Server realm: %s",
  1052. (BooleanToEngStr(Data->GSSAPIFwdTGT), Data->GSSAPIServerRealm));
  1053. }
  1054. ADF(L"Ciphers: %s; Ssh2DES: %s",
  1055. (Data->CipherList, BooleanToEngStr(Data->Ssh2DES)));
  1056. ADF(L"KEX: %s", (Data->KexList));
  1057. UnicodeString Bugs;
  1058. for (int Index = 0; Index < BUG_COUNT; Index++)
  1059. {
  1060. Bugs += UnicodeString(BugFlags[Data->Bug[(TSshBug)Index]])+(Index<BUG_COUNT-1?L",":L"");
  1061. }
  1062. ADF(L"SSH Bugs: %s", (Bugs));
  1063. ADF(L"Simple channel: %s", (BooleanToEngStr(Data->SshSimple)));
  1064. ADF(L"Return code variable: %s; Lookup user groups: %s",
  1065. ((Data->DetectReturnVar ? UnicodeString(L"Autodetect") : Data->ReturnVar),
  1066. BugFlags[Data->LookupUserGroups]));
  1067. ADF(L"Shell: %s", ((Data->Shell.IsEmpty()? UnicodeString(L"default") : Data->Shell)));
  1068. ADF(L"EOL: %d, UTF: %d", (Data->EOLType, Data->NotUtf)); // NotUtf duplicated in FTP branch
  1069. ADF(L"Clear aliases: %s, Unset nat.vars: %s, Resolve symlinks: %s",
  1070. (BooleanToEngStr(Data->ClearAliases), BooleanToEngStr(Data->UnsetNationalVars),
  1071. BooleanToEngStr(Data->ResolveSymlinks)));
  1072. ADF(L"LS: %s, Ign LS warn: %s, Scp1 Comp: %s",
  1073. (Data->ListingCommand,
  1074. BooleanToEngStr(Data->IgnoreLsWarnings),
  1075. BooleanToEngStr(Data->Scp1Compatibility)));
  1076. }
  1077. if ((Data->FSProtocol == fsSFTP) || (Data->FSProtocol == fsSFTPonly))
  1078. {
  1079. UnicodeString Bugs;
  1080. for (int Index = 0; Index < SFTP_BUG_COUNT; Index++)
  1081. {
  1082. Bugs += UnicodeString(BugFlags[Data->SFTPBug[(TSftpBug)Index]])+(Index<SFTP_BUG_COUNT-1?L",":L"");
  1083. }
  1084. ADF(L"SFTP Bugs: %s", (Bugs));
  1085. ADF(L"SFTP Server: %s", ((Data->SftpServer.IsEmpty()? UnicodeString(L"default") : Data->SftpServer)));
  1086. }
  1087. if (Data->FSProtocol == fsFTP)
  1088. {
  1089. ADF(L"UTF: %d", (Data->NotUtf)); // duplicated in UsesSsh branch
  1090. UnicodeString Ftps;
  1091. switch (Data->Ftps)
  1092. {
  1093. case ftpsImplicit:
  1094. Ftps = L"Implicit TLS/SSL";
  1095. break;
  1096. case ftpsExplicitSsl:
  1097. Ftps = L"Explicit SSL";
  1098. break;
  1099. case ftpsExplicitTls:
  1100. Ftps = L"Explicit TLS";
  1101. break;
  1102. default:
  1103. assert(Data->Ftps == ftpsNone);
  1104. Ftps = L"None";
  1105. break;
  1106. }
  1107. ADF(L"FTP: FTPS: %s; Passive: %s [Force IP: %s]; MLSD: %s [List all: %s]",
  1108. (Ftps, BooleanToEngStr(Data->FtpPasvMode),
  1109. BugFlags[Data->FtpForcePasvIp],
  1110. BugFlags[Data->FtpUseMlsd],
  1111. BugFlags[Data->FtpListAll]));
  1112. if (Data->Ftps != ftpsNone)
  1113. {
  1114. ADF(L"Session reuse: %s", (BooleanToEngStr(Data->SslSessionReuse)));
  1115. ADF(L"TLS/SSL versions: %s-%s", (GetTlsVersionName(Data->MinTlsVersion), GetTlsVersionName(Data->MaxTlsVersion)));
  1116. }
  1117. // kind of hidden option, so do not reveal it unless it is set
  1118. if (Data->FtpTransferActiveImmediately)
  1119. {
  1120. ADF(L"Transfer active immediately: %s", (BooleanToEngStr(Data->FtpTransferActiveImmediately)));
  1121. }
  1122. }
  1123. ADF(L"Local directory: %s, Remote directory: %s, Update: %s, Cache: %s",
  1124. ((Data->LocalDirectory.IsEmpty() ? UnicodeString(L"default") : Data->LocalDirectory),
  1125. (Data->RemoteDirectory.IsEmpty() ? UnicodeString(L"home") : Data->RemoteDirectory),
  1126. BooleanToEngStr(Data->UpdateDirectories),
  1127. BooleanToEngStr(Data->CacheDirectories)));
  1128. ADF(L"Cache directory changes: %s, Permanent: %s",
  1129. (BooleanToEngStr(Data->CacheDirectoryChanges),
  1130. BooleanToEngStr(Data->PreserveDirectoryChanges)));
  1131. UnicodeString TimeInfo;
  1132. if ((Data->FSProtocol == fsSFTP) || (Data->FSProtocol == fsSFTPonly) || (Data->FSProtocol == fsSCPonly) || (Data->FSProtocol == fsWebDAV))
  1133. {
  1134. AddToList(TimeInfo, FORMAT(L"DST mode: %d", (int(Data->DSTMode))), L";");
  1135. }
  1136. if ((Data->FSProtocol == fsSCPonly) || (Data->FSProtocol == fsFTP))
  1137. {
  1138. int TimeDifferenceMin = TimeToMinutes(Data->TimeDifference);
  1139. AddToList(TimeInfo, FORMAT(L"Timezone offset: %dh %dm", ((TimeDifferenceMin / MinsPerHour), (TimeDifferenceMin % MinsPerHour))), L";");
  1140. }
  1141. ADSTR(TimeInfo);
  1142. if (Data->FSProtocol == fsWebDAV)
  1143. {
  1144. ADF(L"Compression: %s",
  1145. (BooleanToEngStr(Data->Compression)));
  1146. }
  1147. AddSeparator();
  1148. }
  1149. }
  1150. __finally
  1151. {
  1152. DeleteUnnecessary();
  1153. EndUpdate();
  1154. }
  1155. }
  1156. //---------------------------------------------------------------------------
  1157. void __fastcall TSessionLog::AddOption(const UnicodeString & LogStr)
  1158. {
  1159. ADSTR(LogStr);
  1160. }
  1161. //---------------------------------------------------------------------------
  1162. void __fastcall TSessionLog::AddOptions(TOptions * Options)
  1163. {
  1164. Options->LogOptions(AddOption);
  1165. }
  1166. //---------------------------------------------------------------------------
  1167. #undef ADF
  1168. #undef ADSTR
  1169. //---------------------------------------------------------------------------
  1170. void __fastcall TSessionLog::AddSeparator()
  1171. {
  1172. Add(llMessage, L"--------------------------------------------------------------------------");
  1173. }
  1174. //---------------------------------------------------------------------------
  1175. int __fastcall TSessionLog::GetBottomIndex()
  1176. {
  1177. return (Count > 0 ? (TopIndex + Count - 1) : -1);
  1178. }
  1179. //---------------------------------------------------------------------------
  1180. bool __fastcall TSessionLog::GetLoggingToFile()
  1181. {
  1182. assert((FFile == NULL) || LogToFile());
  1183. return (FFile != NULL);
  1184. }
  1185. //---------------------------------------------------------------------------
  1186. void __fastcall TSessionLog::Clear()
  1187. {
  1188. TGuard Guard(FCriticalSection);
  1189. FTopIndex += Count;
  1190. TStringList::Clear();
  1191. }
  1192. //---------------------------------------------------------------------------
  1193. //---------------------------------------------------------------------------
  1194. __fastcall TActionLog::TActionLog(TSessionUI * UI, TSessionData * SessionData,
  1195. TConfiguration * Configuration)
  1196. {
  1197. assert(UI != NULL);
  1198. assert(SessionData != NULL);
  1199. Init(UI, SessionData, Configuration);
  1200. }
  1201. //---------------------------------------------------------------------------
  1202. __fastcall TActionLog::TActionLog(TConfiguration * Configuration)
  1203. {
  1204. Init(NULL, NULL, Configuration);
  1205. // not associated with session, so no need to waiting for anything
  1206. ReflectSettings();
  1207. }
  1208. //---------------------------------------------------------------------------
  1209. void __fastcall TActionLog::Init(TSessionUI * UI, TSessionData * SessionData,
  1210. TConfiguration * Configuration)
  1211. {
  1212. FCriticalSection = new TCriticalSection;
  1213. FConfiguration = Configuration;
  1214. FUI = UI;
  1215. FSessionData = SessionData;
  1216. FFile = NULL;
  1217. FCurrentLogFileName = L"";
  1218. FCurrentFileName = L"";
  1219. FLogging = false;
  1220. FClosed = false;
  1221. FPendingActions = new TList();
  1222. FIndent = L" ";
  1223. FInGroup = false;
  1224. FEnabled = true;
  1225. }
  1226. //---------------------------------------------------------------------------
  1227. __fastcall TActionLog::~TActionLog()
  1228. {
  1229. assert(FPendingActions->Count == 0);
  1230. delete FPendingActions;
  1231. FClosed = true;
  1232. ReflectSettings();
  1233. assert(FFile == NULL);
  1234. delete FCriticalSection;
  1235. }
  1236. //---------------------------------------------------------------------------
  1237. void __fastcall TActionLog::Add(const UnicodeString & Line)
  1238. {
  1239. assert(FConfiguration);
  1240. if (FLogging)
  1241. {
  1242. try
  1243. {
  1244. TGuard Guard(FCriticalSection);
  1245. if (FFile == NULL)
  1246. {
  1247. OpenLogFile();
  1248. }
  1249. if (FFile != NULL)
  1250. {
  1251. UTF8String UtfLine = UTF8String(Line);
  1252. fwrite(UtfLine.c_str(), 1, UtfLine.Length(), (FILE *)FFile);
  1253. fwrite("\n", 1, 1, (FILE *)FFile);
  1254. }
  1255. }
  1256. catch (Exception &E)
  1257. {
  1258. // We failed logging, turn it off and notify user.
  1259. FConfiguration->LogActions = false;
  1260. try
  1261. {
  1262. throw ExtException(&E, LoadStr(LOG_GEN_ERROR));
  1263. }
  1264. catch (Exception &E)
  1265. {
  1266. if (FUI != NULL)
  1267. {
  1268. FUI->HandleExtendedException(&E);
  1269. }
  1270. }
  1271. }
  1272. }
  1273. }
  1274. //---------------------------------------------------------------------------
  1275. void __fastcall TActionLog::AddIndented(const UnicodeString & Line)
  1276. {
  1277. Add(FIndent + Line);
  1278. }
  1279. //---------------------------------------------------------------------------
  1280. void __fastcall TActionLog::AddFailure(TStrings * Messages)
  1281. {
  1282. AddIndented(L"<failure>");
  1283. AddMessages(L" ", Messages);
  1284. AddIndented(L"</failure>");
  1285. }
  1286. //---------------------------------------------------------------------------
  1287. void __fastcall TActionLog::AddFailure(Exception * E)
  1288. {
  1289. TStrings * Messages = ExceptionToMoreMessages(E);
  1290. if (Messages != NULL)
  1291. {
  1292. try
  1293. {
  1294. AddFailure(Messages);
  1295. }
  1296. __finally
  1297. {
  1298. delete Messages;
  1299. }
  1300. }
  1301. }
  1302. //---------------------------------------------------------------------------
  1303. void __fastcall TActionLog::AddMessages(UnicodeString Indent, TStrings * Messages)
  1304. {
  1305. for (int Index = 0; Index < Messages->Count; Index++)
  1306. {
  1307. AddIndented(
  1308. FORMAT(Indent + L"<message>%s</message>", (XmlEscape(Messages->Strings[Index]))));
  1309. }
  1310. }
  1311. //---------------------------------------------------------------------------
  1312. void __fastcall TActionLog::ReflectSettings()
  1313. {
  1314. TGuard Guard(FCriticalSection);
  1315. bool ALogging =
  1316. !FClosed && FConfiguration->LogActions && Enabled;
  1317. if (ALogging && !FLogging)
  1318. {
  1319. FLogging = true;
  1320. Add(L"<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
  1321. UnicodeString SessionName =
  1322. (FSessionData != NULL) ? XmlAttributeEscape(FSessionData->SessionName) : UnicodeString(L"nosession");
  1323. Add(FORMAT(L"<session xmlns=\"http://winscp.net/schema/session/1.0\" name=\"%s\" start=\"%s\">",
  1324. (SessionName, StandardTimestamp())));
  1325. }
  1326. else if (!ALogging && FLogging)
  1327. {
  1328. if (FInGroup)
  1329. {
  1330. EndGroup();
  1331. }
  1332. // do not try to close the file, if it has not been opened, to avoid recursion
  1333. if (FFile != NULL)
  1334. {
  1335. Add(L"</session>");
  1336. }
  1337. CloseLogFile();
  1338. FLogging = false;
  1339. }
  1340. }
  1341. //---------------------------------------------------------------------------
  1342. void __fastcall TActionLog::CloseLogFile()
  1343. {
  1344. if (FFile != NULL)
  1345. {
  1346. fclose((FILE *)FFile);
  1347. FFile = NULL;
  1348. }
  1349. FCurrentLogFileName = L"";
  1350. FCurrentFileName = L"";
  1351. }
  1352. //---------------------------------------------------------------------------
  1353. void __fastcall TActionLog::OpenLogFile()
  1354. {
  1355. try
  1356. {
  1357. assert(FFile == NULL);
  1358. assert(FConfiguration != NULL);
  1359. FCurrentLogFileName = FConfiguration->ActionsLogFileName;
  1360. FFile = OpenFile(FCurrentLogFileName, FSessionData, false, FCurrentFileName);
  1361. }
  1362. catch (Exception & E)
  1363. {
  1364. // We failed logging to file, turn it off and notify user.
  1365. FCurrentLogFileName = L"";
  1366. FCurrentFileName = L"";
  1367. FConfiguration->LogActions = false;
  1368. try
  1369. {
  1370. throw ExtException(&E, LoadStr(LOG_GEN_ERROR));
  1371. }
  1372. catch (Exception & E)
  1373. {
  1374. if (FUI != NULL)
  1375. {
  1376. FUI->HandleExtendedException(&E);
  1377. }
  1378. }
  1379. }
  1380. }
  1381. //---------------------------------------------------------------------------
  1382. void __fastcall TActionLog::AddPendingAction(TSessionActionRecord * Action)
  1383. {
  1384. FPendingActions->Add(Action);
  1385. }
  1386. //---------------------------------------------------------------------------
  1387. void __fastcall TActionLog::RecordPendingActions()
  1388. {
  1389. while ((FPendingActions->Count > 0) &&
  1390. static_cast<TSessionActionRecord *>(FPendingActions->Items[0])->Record())
  1391. {
  1392. FPendingActions->Delete(0);
  1393. }
  1394. }
  1395. //---------------------------------------------------------------------------
  1396. void __fastcall TActionLog::BeginGroup(UnicodeString Name)
  1397. {
  1398. assert(!FInGroup);
  1399. FInGroup = true;
  1400. assert(FIndent == L" ");
  1401. AddIndented(FORMAT(L"<group name=\"%s\" start=\"%s\">",
  1402. (XmlAttributeEscape(Name), StandardTimestamp())));
  1403. FIndent = L" ";
  1404. }
  1405. //---------------------------------------------------------------------------
  1406. void __fastcall TActionLog::EndGroup()
  1407. {
  1408. assert(FInGroup);
  1409. FInGroup = false;
  1410. assert(FIndent == L" ");
  1411. FIndent = L" ";
  1412. // this is called from ReflectSettings that in turn is called when logging fails,
  1413. // so do not try to close the group, if it has not been opened, to avoid recursion
  1414. if (FFile != NULL)
  1415. {
  1416. AddIndented(L"</group>");
  1417. }
  1418. }
  1419. //---------------------------------------------------------------------------
  1420. void __fastcall TActionLog::SetEnabled(bool value)
  1421. {
  1422. if (Enabled != value)
  1423. {
  1424. FEnabled = value;
  1425. ReflectSettings();
  1426. }
  1427. }