SessionInfo.cpp 50 KB

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