SessionInfo.cpp 48 KB

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