SessionInfo.cpp 50 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678
  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. FUI->HandleExtendedException(&E);
  898. }
  899. }
  900. // in case we are appending and the existing log file is already too large
  901. if (FFile != NULL)
  902. {
  903. CheckSize(0);
  904. }
  905. StateChange();
  906. }
  907. //---------------------------------------------------------------------------
  908. void __fastcall TSessionLog::StateChange()
  909. {
  910. if (FOnStateChange != NULL)
  911. {
  912. FOnStateChange(this);
  913. }
  914. }
  915. //---------------------------------------------------------------------------
  916. void __fastcall TSessionLog::DeleteUnnecessary()
  917. {
  918. BeginUpdate();
  919. try
  920. {
  921. if (!Logging || (FParent != NULL))
  922. {
  923. Clear();
  924. }
  925. else
  926. {
  927. while (!FConfiguration->LogWindowComplete && (Count > FConfiguration->LogWindowLines))
  928. {
  929. Delete(0);
  930. FTopIndex++;
  931. }
  932. }
  933. }
  934. __finally
  935. {
  936. EndUpdate();
  937. }
  938. }
  939. //---------------------------------------------------------------------------
  940. void __fastcall TSessionLog::AddSystemInfo()
  941. {
  942. AddStartupInfo(true);
  943. }
  944. //---------------------------------------------------------------------------
  945. void __fastcall TSessionLog::AddStartupInfo()
  946. {
  947. AddStartupInfo(false);
  948. }
  949. //---------------------------------------------------------------------------
  950. void __fastcall TSessionLog::AddStartupInfo(bool System)
  951. {
  952. TSessionData * Data = (System ? NULL : FSessionData);
  953. if (Logging)
  954. {
  955. if (FParent != NULL)
  956. {
  957. // do not add session info for secondary session
  958. // (this should better be handled in the TSecondaryTerminal)
  959. }
  960. else
  961. {
  962. DoAddStartupInfo(Data);
  963. }
  964. }
  965. }
  966. //---------------------------------------------------------------------------
  967. UnicodeString __fastcall TSessionLog::GetTlsVersionName(TTlsVersion TlsVersion)
  968. {
  969. switch (TlsVersion)
  970. {
  971. default:
  972. DebugFail();
  973. case ssl2:
  974. return "SSLv2";
  975. case ssl3:
  976. return "SSLv3";
  977. case tls10:
  978. return "TLSv1.0";
  979. case tls11:
  980. return "TLSv1.1";
  981. case tls12:
  982. return "TLSv1.2";
  983. }
  984. }
  985. //---------------------------------------------------------------------------
  986. UnicodeString __fastcall TSessionLog::LogSensitive(const UnicodeString & Str)
  987. {
  988. if (FConfiguration->LogSensitive && !Str.IsEmpty())
  989. {
  990. return Str;
  991. }
  992. else
  993. {
  994. return BooleanToEngStr(!Str.IsEmpty());
  995. }
  996. }
  997. //---------------------------------------------------------------------------
  998. UnicodeString __fastcall TSessionLog::GetCmdLineLog()
  999. {
  1000. UnicodeString Result = CmdLine;
  1001. if (!Configuration->LogSensitive)
  1002. {
  1003. TManagementScript Script(StoredSessions, false);
  1004. Script.MaskPasswordInCommandLine(Result, true);
  1005. }
  1006. return Result;
  1007. }
  1008. //---------------------------------------------------------------------------
  1009. template <typename T>
  1010. UnicodeString __fastcall EnumName(T Value, UnicodeString Names)
  1011. {
  1012. int N = int(Value);
  1013. do
  1014. {
  1015. UnicodeString Name = CutToChar(Names, L';', true);
  1016. if (N == 0)
  1017. {
  1018. return Name;
  1019. }
  1020. N--;
  1021. }
  1022. while ((N >= 0) && !Names.IsEmpty());
  1023. return L"(unknown)";
  1024. }
  1025. //---------------------------------------------------------------------------
  1026. #define ADSTR(S) DoAdd(llMessage, S, DoAddToSelf);
  1027. #define ADF(S, F) ADSTR(FORMAT(S, F));
  1028. //---------------------------------------------------------------------------
  1029. void __fastcall TSessionLog::DoAddStartupInfo(TSessionData * Data)
  1030. {
  1031. TGuard Guard(FCriticalSection);
  1032. BeginUpdate();
  1033. try
  1034. {
  1035. if (Data == NULL)
  1036. {
  1037. AddSeparator();
  1038. UnicodeString OS = WindowsVersionLong();
  1039. AddToList(OS, WindowsProductName(), L" - ");
  1040. ADF(L"WinSCP %s (OS %s)", (FConfiguration->VersionStr, OS));
  1041. THierarchicalStorage * Storage = FConfiguration->CreateConfigStorage();
  1042. try
  1043. {
  1044. ADF(L"Configuration: %s", (Storage->Source));
  1045. }
  1046. __finally
  1047. {
  1048. delete Storage;
  1049. }
  1050. wchar_t UserName[UNLEN + 1];
  1051. unsigned long UserNameSize = LENOF(UserName);
  1052. if (DebugAlwaysFalse(!GetUserNameEx(NameSamCompatible, UserName, &UserNameSize)))
  1053. {
  1054. wcscpy(UserName, L"<Failed to retrieve username>");
  1055. }
  1056. UnicodeString LogStr;
  1057. if (FConfiguration->LogProtocol <= 0)
  1058. {
  1059. LogStr = L"Normal";
  1060. }
  1061. else if (FConfiguration->LogProtocol == 1)
  1062. {
  1063. LogStr = L"Debug 1";
  1064. }
  1065. else if (FConfiguration->LogProtocol >= 2)
  1066. {
  1067. LogStr = L"Debug 2";
  1068. }
  1069. if (FConfiguration->LogSensitive)
  1070. {
  1071. LogStr += L", Logging passwords";
  1072. }
  1073. if (FConfiguration->LogMaxSize > 0)
  1074. {
  1075. LogStr += FORMAT(L", Rotating after: %s", (SizeToStr(FConfiguration->LogMaxSize)));
  1076. if (FConfiguration->LogMaxCount > 0)
  1077. {
  1078. LogStr += FORMAT(L", Keeping at most %d logs", (FConfiguration->LogMaxCount));
  1079. }
  1080. }
  1081. ADF(L"Log level: %s", (LogStr));
  1082. ADF(L"Local account: %s", (UserName));
  1083. ADF(L"Working directory: %s", (GetCurrentDir()));
  1084. ADF(L"Process ID: %d", (int(GetCurrentProcessId())));
  1085. ADF(L"Command-line: %s", (GetCmdLineLog()));
  1086. if (FConfiguration->LogProtocol >= 1)
  1087. {
  1088. AddOptions(GetGlobalOptions());
  1089. }
  1090. ADF(L"Time zone: %s", (GetTimeZoneLogString()));
  1091. if (!AdjustClockForDSTEnabled())
  1092. {
  1093. ADSTR(L"Warning: System option \"Automatically adjust clock for Daylight Saving Time\" is disabled, timestamps will not be represented correctly");
  1094. }
  1095. ADF(L"Login time: %s", (FormatDateTime(L"dddddd tt", Now())));
  1096. AddSeparator();
  1097. }
  1098. else
  1099. {
  1100. ADF(L"Session name: %s (%s)", (Data->SessionName, Data->Source));
  1101. ADF(L"Host name: %s (Port: %d)", (Data->HostNameExpanded, Data->PortNumber));
  1102. ADF(L"User name: %s (Password: %s, Key file: %s, Passphrase: %s)",
  1103. (Data->UserNameExpanded, LogSensitive(Data->Password),
  1104. LogSensitive(Data->PublicKeyFile), LogSensitive(Data->Passphrase)));
  1105. if (Data->UsesSsh)
  1106. {
  1107. ADF(L"Tunnel: %s", (BooleanToEngStr(Data->Tunnel)));
  1108. if (Data->Tunnel)
  1109. {
  1110. ADF(L"Tunnel: Host name: %s (Port: %d)", (Data->TunnelHostName, Data->TunnelPortNumber));
  1111. ADF(L"Tunnel: User name: %s (Password: %s, Key file: %s)",
  1112. (Data->TunnelUserName,
  1113. LogSensitive(Data->TunnelPassword),
  1114. LogSensitive(Data->TunnelPublicKeyFile)));
  1115. ADF(L"Tunnel: Local port number: %d", (Data->TunnelLocalPortNumber));
  1116. }
  1117. }
  1118. ADF(L"Transfer Protocol: %s", (Data->FSProtocolStr));
  1119. if (Data->UsesSsh || (Data->FSProtocol == fsFTP))
  1120. {
  1121. TPingType PingType;
  1122. int PingInterval;
  1123. if (Data->FSProtocol == fsFTP)
  1124. {
  1125. PingType = Data->FtpPingType;
  1126. PingInterval = Data->FtpPingInterval;
  1127. }
  1128. else
  1129. {
  1130. PingType = Data->PingType;
  1131. PingInterval = Data->PingInterval;
  1132. }
  1133. ADF(L"Ping type: %s, Ping interval: %d sec; Timeout: %d sec",
  1134. (EnumName(PingType, PingTypeNames), PingInterval, Data->Timeout));
  1135. ADF(L"Disable Nagle: %s",
  1136. (BooleanToEngStr(Data->TcpNoDelay)));
  1137. }
  1138. ADF(L"Proxy: %s",
  1139. ((Data->FtpProxyLogonType != 0) ?
  1140. FORMAT(L"FTP proxy %d", (Data->FtpProxyLogonType)) :
  1141. EnumName(Data->ProxyMethod, ProxyMethodNames)));
  1142. if ((Data->FtpProxyLogonType != 0) || (Data->ProxyMethod != ::pmNone))
  1143. {
  1144. ADF(L"HostName: %s (Port: %d); Username: %s; Passwd: %s",
  1145. (Data->ProxyHost, Data->ProxyPort,
  1146. Data->ProxyUsername, LogSensitive(Data->ProxyPassword)));
  1147. if (Data->ProxyMethod == pmTelnet)
  1148. {
  1149. ADF(L"Telnet command: %s", (Data->ProxyTelnetCommand));
  1150. }
  1151. if (Data->ProxyMethod == pmCmd)
  1152. {
  1153. ADF(L"Local command: %s", (Data->ProxyLocalCommand));
  1154. }
  1155. }
  1156. if (Data->UsesSsh || (Data->FSProtocol == fsFTP))
  1157. {
  1158. ADF(L"Send buffer: %d", (Data->SendBuf));
  1159. }
  1160. if (Data->UsesSsh)
  1161. {
  1162. ADF(L"SSH protocol version: %s; Compression: %s",
  1163. (Data->SshProtStr, BooleanToEngStr(Data->Compression)));
  1164. ADF(L"Bypass authentication: %s",
  1165. (BooleanToEngStr(Data->SshNoUserAuth)));
  1166. ADF(L"Try agent: %s; Agent forwarding: %s; TIS/CryptoCard: %s; KI: %s; GSSAPI: %s",
  1167. (BooleanToEngStr(Data->TryAgent), BooleanToEngStr(Data->AgentFwd), BooleanToEngStr(Data->AuthTIS),
  1168. BooleanToEngStr(Data->AuthKI), BooleanToEngStr(Data->AuthGSSAPI)));
  1169. if (Data->AuthGSSAPI)
  1170. {
  1171. ADF(L"GSSAPI: Forwarding: %s",
  1172. (BooleanToEngStr(Data->GSSAPIFwdTGT)));
  1173. }
  1174. ADF(L"Ciphers: %s; Ssh2DES: %s",
  1175. (Data->CipherList, BooleanToEngStr(Data->Ssh2DES)));
  1176. ADF(L"KEX: %s", (Data->KexList));
  1177. UnicodeString Bugs;
  1178. for (int Index = 0; Index < BUG_COUNT; Index++)
  1179. {
  1180. AddToList(Bugs, EnumName(Data->Bug[(TSshBug)Index], AutoSwitchNames), L",");
  1181. }
  1182. ADF(L"SSH Bugs: %s", (Bugs));
  1183. ADF(L"Simple channel: %s", (BooleanToEngStr(Data->SshSimple)));
  1184. ADF(L"Return code variable: %s; Lookup user groups: %s",
  1185. ((Data->DetectReturnVar ? UnicodeString(L"Autodetect") : Data->ReturnVar),
  1186. EnumName(Data->LookupUserGroups, AutoSwitchNames)));
  1187. ADF(L"Shell: %s", ((Data->Shell.IsEmpty()? UnicodeString(L"default") : Data->Shell)));
  1188. ADF(L"EOL: %s, UTF: %s", (EnumName(Data->EOLType, EOLTypeNames), EnumName(Data->NotUtf, NotAutoSwitchNames))); // NotUtf duplicated in FTP branch
  1189. ADF(L"Clear aliases: %s, Unset nat.vars: %s, Resolve symlinks: %s; Follow directory symlinks: %s",
  1190. (BooleanToEngStr(Data->ClearAliases), BooleanToEngStr(Data->UnsetNationalVars),
  1191. BooleanToEngStr(Data->ResolveSymlinks), BooleanToEngStr(Data->FollowDirectorySymlinks)));
  1192. ADF(L"LS: %s, Ign LS warn: %s, Scp1 Comp: %s",
  1193. (Data->ListingCommand,
  1194. BooleanToEngStr(Data->IgnoreLsWarnings),
  1195. BooleanToEngStr(Data->Scp1Compatibility)));
  1196. }
  1197. if ((Data->FSProtocol == fsSFTP) || (Data->FSProtocol == fsSFTPonly))
  1198. {
  1199. UnicodeString Bugs;
  1200. for (int Index = 0; Index < SFTP_BUG_COUNT; Index++)
  1201. {
  1202. AddToList(Bugs, EnumName(Data->SFTPBug[(TSftpBug)Index], AutoSwitchNames), L",");
  1203. }
  1204. ADF(L"SFTP Bugs: %s", (Bugs));
  1205. ADF(L"SFTP Server: %s", ((Data->SftpServer.IsEmpty()? UnicodeString(L"default") : Data->SftpServer)));
  1206. }
  1207. bool FtpsOn = false;
  1208. if (Data->FSProtocol == fsFTP)
  1209. {
  1210. ADF(L"UTF: %s", (EnumName(Data->NotUtf, NotAutoSwitchNames))); // duplicated in UsesSsh branch
  1211. UnicodeString Ftps;
  1212. switch (Data->Ftps)
  1213. {
  1214. case ftpsImplicit:
  1215. Ftps = L"Implicit TLS/SSL";
  1216. FtpsOn = true;
  1217. break;
  1218. case ftpsExplicitSsl:
  1219. Ftps = L"Explicit SSL/TLS";
  1220. FtpsOn = true;
  1221. break;
  1222. case ftpsExplicitTls:
  1223. Ftps = L"Explicit TLS/SSL";
  1224. FtpsOn = true;
  1225. break;
  1226. default:
  1227. DebugAssert(Data->Ftps == ftpsNone);
  1228. Ftps = L"None";
  1229. break;
  1230. }
  1231. // kind of hidden option, so do not reveal it unless it is set
  1232. if (Data->FtpTransferActiveImmediately != asAuto)
  1233. {
  1234. ADF(L"Transfer active immediately: %s", (EnumName(Data->FtpTransferActiveImmediately, AutoSwitchNames)));
  1235. }
  1236. ADF(L"FTPS: %s [Client certificate: %s]",
  1237. (Ftps, LogSensitive(Data->TlsCertificateFile)));
  1238. ADF(L"FTP: Passive: %s [Force IP: %s]; MLSD: %s [List all: %s]; HOST: %s",
  1239. (BooleanToEngStr(Data->FtpPasvMode),
  1240. EnumName(Data->FtpForcePasvIp, AutoSwitchNames),
  1241. EnumName(Data->FtpUseMlsd, AutoSwitchNames),
  1242. EnumName(Data->FtpListAll, AutoSwitchNames),
  1243. EnumName(Data->FtpHost, AutoSwitchNames)));
  1244. }
  1245. if (Data->FSProtocol == fsWebDAV)
  1246. {
  1247. FtpsOn = (Data->Ftps != ftpsNone);
  1248. ADF(L"HTTPS: %s [Client certificate: %s]",
  1249. (BooleanToEngStr(FtpsOn), LogSensitive(Data->TlsCertificateFile)));
  1250. }
  1251. if (FtpsOn)
  1252. {
  1253. if (Data->FSProtocol == fsFTP)
  1254. {
  1255. ADF(L"Session reuse: %s", (BooleanToEngStr(Data->SslSessionReuse)));
  1256. }
  1257. ADF(L"TLS/SSL versions: %s-%s", (GetTlsVersionName(Data->MinTlsVersion), GetTlsVersionName(Data->MaxTlsVersion)));
  1258. }
  1259. ADF(L"Local directory: %s, Remote directory: %s, Update: %s, Cache: %s",
  1260. ((Data->LocalDirectory.IsEmpty() ? UnicodeString(L"default") : Data->LocalDirectory),
  1261. (Data->RemoteDirectory.IsEmpty() ? UnicodeString(L"home") : Data->RemoteDirectory),
  1262. BooleanToEngStr(Data->UpdateDirectories),
  1263. BooleanToEngStr(Data->CacheDirectories)));
  1264. ADF(L"Cache directory changes: %s, Permanent: %s",
  1265. (BooleanToEngStr(Data->CacheDirectoryChanges),
  1266. BooleanToEngStr(Data->PreserveDirectoryChanges)));
  1267. ADF(L"Recycle bin: Delete to: %s, Overwritten to: %s, Bin path: %s",
  1268. (BooleanToEngStr(Data->DeleteToRecycleBin),
  1269. BooleanToEngStr(Data->OverwrittenToRecycleBin),
  1270. Data->RecycleBinPath));
  1271. if (Data->TrimVMSVersions)
  1272. {
  1273. ADF(L"Trim VMS versions: %s",
  1274. (BooleanToEngStr(Data->TrimVMSVersions)));
  1275. }
  1276. UnicodeString TimeInfo;
  1277. if ((Data->FSProtocol == fsSFTP) || (Data->FSProtocol == fsSFTPonly) || (Data->FSProtocol == fsSCPonly) || (Data->FSProtocol == fsWebDAV))
  1278. {
  1279. AddToList(TimeInfo, FORMAT(L"DST mode: %s", (EnumName(Data->DSTMode, DSTModeNames))), L";");
  1280. }
  1281. if ((Data->FSProtocol == fsSCPonly) || (Data->FSProtocol == fsFTP))
  1282. {
  1283. int TimeDifferenceMin = TimeToMinutes(Data->TimeDifference);
  1284. AddToList(TimeInfo, FORMAT(L"Timezone offset: %dh %dm", ((TimeDifferenceMin / MinsPerHour), (TimeDifferenceMin % MinsPerHour))), L";");
  1285. }
  1286. ADSTR(TimeInfo);
  1287. if (Data->FSProtocol == fsWebDAV)
  1288. {
  1289. ADF(L"Compression: %s",
  1290. (BooleanToEngStr(Data->Compression)));
  1291. }
  1292. AddSeparator();
  1293. }
  1294. }
  1295. __finally
  1296. {
  1297. DeleteUnnecessary();
  1298. EndUpdate();
  1299. }
  1300. }
  1301. //---------------------------------------------------------------------------
  1302. void __fastcall TSessionLog::AddOption(const UnicodeString & LogStr)
  1303. {
  1304. ADSTR(LogStr);
  1305. }
  1306. //---------------------------------------------------------------------------
  1307. void __fastcall TSessionLog::AddOptions(TOptions * Options)
  1308. {
  1309. Options->LogOptions(AddOption);
  1310. }
  1311. //---------------------------------------------------------------------------
  1312. #undef ADF
  1313. #undef ADSTR
  1314. //---------------------------------------------------------------------------
  1315. void __fastcall TSessionLog::AddSeparator()
  1316. {
  1317. Add(llMessage, L"--------------------------------------------------------------------------");
  1318. }
  1319. //---------------------------------------------------------------------------
  1320. int __fastcall TSessionLog::GetBottomIndex()
  1321. {
  1322. return (Count > 0 ? (TopIndex + Count - 1) : -1);
  1323. }
  1324. //---------------------------------------------------------------------------
  1325. bool __fastcall TSessionLog::GetLoggingToFile()
  1326. {
  1327. DebugAssert((FFile == NULL) || LogToFile());
  1328. return (FFile != NULL);
  1329. }
  1330. //---------------------------------------------------------------------------
  1331. void __fastcall TSessionLog::Clear()
  1332. {
  1333. TGuard Guard(FCriticalSection);
  1334. FTopIndex += Count;
  1335. TStringList::Clear();
  1336. }
  1337. //---------------------------------------------------------------------------
  1338. //---------------------------------------------------------------------------
  1339. __fastcall TActionLog::TActionLog(TSessionUI * UI, TDateTime Started, TSessionData * SessionData,
  1340. TConfiguration * Configuration)
  1341. {
  1342. DebugAssert(UI != NULL);
  1343. DebugAssert(SessionData != NULL);
  1344. Init(UI, Started, SessionData, Configuration);
  1345. }
  1346. //---------------------------------------------------------------------------
  1347. __fastcall TActionLog::TActionLog(TDateTime Started, TConfiguration * Configuration)
  1348. {
  1349. Init(NULL, Started, NULL, Configuration);
  1350. // not associated with session, so no need to waiting for anything
  1351. ReflectSettings();
  1352. }
  1353. //---------------------------------------------------------------------------
  1354. void __fastcall TActionLog::Init(TSessionUI * UI, TDateTime Started, TSessionData * SessionData,
  1355. TConfiguration * Configuration)
  1356. {
  1357. FCriticalSection = new TCriticalSection;
  1358. FConfiguration = Configuration;
  1359. FUI = UI;
  1360. FSessionData = SessionData;
  1361. FStarted = Started;
  1362. FFile = NULL;
  1363. FCurrentLogFileName = L"";
  1364. FCurrentFileName = L"";
  1365. FLogging = false;
  1366. FClosed = false;
  1367. FFailed = false;
  1368. FPendingActions = new TList();
  1369. FIndent = L" ";
  1370. FInGroup = false;
  1371. FEnabled = true;
  1372. }
  1373. //---------------------------------------------------------------------------
  1374. __fastcall TActionLog::~TActionLog()
  1375. {
  1376. DebugAssert(FPendingActions->Count == 0);
  1377. delete FPendingActions;
  1378. FClosed = true;
  1379. ReflectSettings();
  1380. DebugAssert(FFile == NULL);
  1381. delete FCriticalSection;
  1382. }
  1383. //---------------------------------------------------------------------------
  1384. void __fastcall TActionLog::Add(const UnicodeString & Line)
  1385. {
  1386. DebugAssert(FConfiguration);
  1387. if (FLogging)
  1388. {
  1389. TGuard Guard(FCriticalSection);
  1390. if (FFile == NULL)
  1391. {
  1392. OpenLogFile();
  1393. }
  1394. if (FFile != NULL)
  1395. {
  1396. try
  1397. {
  1398. UTF8String UtfLine = UTF8String(Line);
  1399. size_t Written =
  1400. fwrite(UtfLine.c_str(), 1, UtfLine.Length(), (FILE *)FFile);
  1401. if (Written != static_cast<size_t>(UtfLine.Length()))
  1402. {
  1403. throw ECRTExtException(L"");
  1404. }
  1405. #ifdef _DEBUG
  1406. #endif
  1407. Written =
  1408. fwrite("\n", 1, 1, (FILE *)FFile);
  1409. if (Written != 1)
  1410. {
  1411. throw ECRTExtException(L"");
  1412. }
  1413. }
  1414. catch (Exception &E)
  1415. {
  1416. FCriticalSection->Release();
  1417. // avoid endless loop when trying to close tags when closing log, when logging has failed
  1418. if (!FFailed)
  1419. {
  1420. FFailed = true;
  1421. // We failed logging, turn it off and notify user.
  1422. FConfiguration->LogActions = false;
  1423. if (FConfiguration->LogActionsRequired)
  1424. {
  1425. throw EFatal(&E, LoadStr(LOG_FATAL_ERROR));
  1426. }
  1427. else
  1428. {
  1429. try
  1430. {
  1431. throw ExtException(&E, LoadStr(LOG_GEN_ERROR));
  1432. }
  1433. catch (Exception &E)
  1434. {
  1435. if (FUI != NULL)
  1436. {
  1437. FUI->HandleExtendedException(&E);
  1438. }
  1439. }
  1440. }
  1441. }
  1442. }
  1443. }
  1444. }
  1445. }
  1446. //---------------------------------------------------------------------------
  1447. void __fastcall TActionLog::AddIndented(const UnicodeString & Line)
  1448. {
  1449. Add(FIndent + Line);
  1450. }
  1451. //---------------------------------------------------------------------------
  1452. void __fastcall TActionLog::AddFailure(TStrings * Messages)
  1453. {
  1454. AddIndented(L"<failure>");
  1455. AddMessages(L" ", Messages);
  1456. AddIndented(L"</failure>");
  1457. }
  1458. //---------------------------------------------------------------------------
  1459. void __fastcall TActionLog::AddFailure(Exception * E)
  1460. {
  1461. TStrings * Messages = ExceptionToMoreMessages(E);
  1462. if (Messages != NULL)
  1463. {
  1464. try
  1465. {
  1466. AddFailure(Messages);
  1467. }
  1468. __finally
  1469. {
  1470. delete Messages;
  1471. }
  1472. }
  1473. }
  1474. //---------------------------------------------------------------------------
  1475. void __fastcall TActionLog::AddMessages(UnicodeString Indent, TStrings * Messages)
  1476. {
  1477. for (int Index = 0; Index < Messages->Count; Index++)
  1478. {
  1479. AddIndented(
  1480. FORMAT(Indent + L"<message>%s</message>", (XmlEscape(Messages->Strings[Index]))));
  1481. }
  1482. }
  1483. //---------------------------------------------------------------------------
  1484. void __fastcall TActionLog::ReflectSettings()
  1485. {
  1486. TGuard Guard(FCriticalSection);
  1487. bool ALogging =
  1488. !FClosed && FConfiguration->LogActions && Enabled;
  1489. if (ALogging && !FLogging)
  1490. {
  1491. FLogging = true;
  1492. Add(L"<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
  1493. UnicodeString SessionName =
  1494. (FSessionData != NULL) ? XmlAttributeEscape(FSessionData->SessionName) : UnicodeString(L"nosession");
  1495. Add(FORMAT(L"<session xmlns=\"http://winscp.net/schema/session/1.0\" name=\"%s\" start=\"%s\">",
  1496. (SessionName, StandardTimestamp())));
  1497. }
  1498. else if (!ALogging && FLogging)
  1499. {
  1500. if (FInGroup)
  1501. {
  1502. EndGroup();
  1503. }
  1504. // do not try to close the file, if it has not been opened, to avoid recursion
  1505. if (FFile != NULL)
  1506. {
  1507. Add(L"</session>");
  1508. }
  1509. CloseLogFile();
  1510. FLogging = false;
  1511. }
  1512. }
  1513. //---------------------------------------------------------------------------
  1514. void __fastcall TActionLog::CloseLogFile()
  1515. {
  1516. if (FFile != NULL)
  1517. {
  1518. fclose((FILE *)FFile);
  1519. FFile = NULL;
  1520. }
  1521. FCurrentLogFileName = L"";
  1522. FCurrentFileName = L"";
  1523. }
  1524. //---------------------------------------------------------------------------
  1525. void __fastcall TActionLog::OpenLogFile()
  1526. {
  1527. try
  1528. {
  1529. DebugAssert(FFile == NULL);
  1530. DebugAssert(FConfiguration != NULL);
  1531. FCurrentLogFileName = FConfiguration->ActionsLogFileName;
  1532. FFile = OpenFile(FCurrentLogFileName, FStarted, FSessionData, false, FCurrentFileName);
  1533. }
  1534. catch (Exception & E)
  1535. {
  1536. // We failed logging to file, turn it off and notify user.
  1537. FCurrentLogFileName = L"";
  1538. FCurrentFileName = L"";
  1539. FConfiguration->LogActions = false;
  1540. if (FConfiguration->LogActionsRequired)
  1541. {
  1542. throw EFatal(&E, LoadStr(LOG_FATAL_ERROR));
  1543. }
  1544. else
  1545. {
  1546. try
  1547. {
  1548. throw ExtException(&E, LoadStr(LOG_GEN_ERROR));
  1549. }
  1550. catch (Exception & E)
  1551. {
  1552. if (FUI != NULL)
  1553. {
  1554. FUI->HandleExtendedException(&E);
  1555. }
  1556. }
  1557. }
  1558. }
  1559. }
  1560. //---------------------------------------------------------------------------
  1561. void __fastcall TActionLog::AddPendingAction(TSessionActionRecord * Action)
  1562. {
  1563. FPendingActions->Add(Action);
  1564. }
  1565. //---------------------------------------------------------------------------
  1566. void __fastcall TActionLog::RecordPendingActions()
  1567. {
  1568. while ((FPendingActions->Count > 0) &&
  1569. static_cast<TSessionActionRecord *>(FPendingActions->Items[0])->Record())
  1570. {
  1571. FPendingActions->Delete(0);
  1572. }
  1573. }
  1574. //---------------------------------------------------------------------------
  1575. void __fastcall TActionLog::BeginGroup(UnicodeString Name)
  1576. {
  1577. DebugAssert(!FInGroup);
  1578. FInGroup = true;
  1579. DebugAssert(FIndent == L" ");
  1580. AddIndented(FORMAT(L"<group name=\"%s\" start=\"%s\">",
  1581. (XmlAttributeEscape(Name), StandardTimestamp())));
  1582. FIndent = L" ";
  1583. }
  1584. //---------------------------------------------------------------------------
  1585. void __fastcall TActionLog::EndGroup()
  1586. {
  1587. DebugAssert(FInGroup);
  1588. FInGroup = false;
  1589. DebugAssert(FIndent == L" ");
  1590. FIndent = L" ";
  1591. // this is called from ReflectSettings that in turn is called when logging fails,
  1592. // so do not try to close the group, if it has not been opened, to avoid recursion
  1593. if (FFile != NULL)
  1594. {
  1595. AddIndented(L"</group>");
  1596. }
  1597. }
  1598. //---------------------------------------------------------------------------
  1599. void __fastcall TActionLog::SetEnabled(bool value)
  1600. {
  1601. if (Enabled != value)
  1602. {
  1603. FEnabled = value;
  1604. ReflectSettings();
  1605. }
  1606. }