SessionInfo.cpp 48 KB

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