SessionInfo.cpp 47 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559
  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. {
  618. FCriticalSection = new TCriticalSection;
  619. FLogging = false;
  620. FConfiguration = Configuration;
  621. FParent = NULL;
  622. FUI = UI;
  623. FSessionData = SessionData;
  624. FStarted = Started;
  625. FFile = NULL;
  626. FCurrentLogFileName = L"";
  627. FCurrentFileName = L"";
  628. FClosed = false;
  629. }
  630. //---------------------------------------------------------------------------
  631. __fastcall TSessionLog::~TSessionLog()
  632. {
  633. FClosed = true;
  634. ReflectSettings();
  635. DebugAssert(FFile == NULL);
  636. delete FCriticalSection;
  637. }
  638. //---------------------------------------------------------------------------
  639. void __fastcall TSessionLog::SetParent(TSessionLog * Parent, const UnicodeString & Name)
  640. {
  641. FParent = Parent;
  642. FName = Name;
  643. }
  644. //---------------------------------------------------------------------------
  645. void __fastcall TSessionLog::DoAddToParent(TLogLineType Type, const UnicodeString & Line)
  646. {
  647. DebugAssert(FParent != NULL);
  648. FParent->Add(Type, Line);
  649. }
  650. //---------------------------------------------------------------------------
  651. void __fastcall TSessionLog::DoAddToSelf(TLogLineType Type, const UnicodeString & Line)
  652. {
  653. if (LogToFile())
  654. {
  655. if (FFile == NULL)
  656. {
  657. OpenLogFile();
  658. }
  659. if (FFile != NULL)
  660. {
  661. UnicodeString Timestamp = FormatDateTime(L" yyyy-mm-dd hh:nn:ss.zzz ", Now());
  662. UTF8String UtfLine = UTF8String(UnicodeString(LogLineMarks[Type]) + Timestamp + Line + L"\r\n");
  663. for (int Index = 1; Index <= UtfLine.Length(); Index++)
  664. {
  665. if ((UtfLine[Index] == '\n') &&
  666. ((Index == 1) || (UtfLine[Index - 1] != '\r')))
  667. {
  668. UtfLine.Insert('\r', Index);
  669. }
  670. }
  671. int Writting = UtfLine.Length();
  672. CheckSize(Writting);
  673. FCurrentFileSize += fwrite(UtfLine.c_str(), 1, Writting, (FILE *)FFile);
  674. }
  675. }
  676. }
  677. //---------------------------------------------------------------------------
  678. UnicodeString __fastcall TSessionLog::LogPartFileName(const UnicodeString & BaseName, int Index)
  679. {
  680. UnicodeString Result;
  681. if (Index >= 1)
  682. {
  683. Result = FORMAT(L"%s.%d", (BaseName, Index));
  684. }
  685. else
  686. {
  687. Result = BaseName;
  688. }
  689. return Result;
  690. }
  691. //---------------------------------------------------------------------------
  692. void __fastcall TSessionLog::CheckSize(__int64 Addition)
  693. {
  694. __int64 MaxSize = FConfiguration->LogMaxSize;
  695. if ((MaxSize > 0) && (FCurrentFileSize + Addition >= MaxSize))
  696. {
  697. // Before we close it
  698. UnicodeString BaseName = FCurrentFileName;
  699. CloseLogFile();
  700. FCurrentFileSize = 0;
  701. int Index = 0;
  702. while (FileExists(LogPartFileName(BaseName, Index + 1)))
  703. {
  704. Index++;
  705. }
  706. int MaxCount = FConfiguration->LogMaxCount;
  707. do
  708. {
  709. UnicodeString LogPart = LogPartFileName(BaseName, Index);
  710. if ((MaxCount > 0) && (Index >= MaxCount))
  711. {
  712. DeleteFileChecked(LogPart);
  713. }
  714. else
  715. {
  716. THROWOSIFFALSE(RenameFile(LogPart, LogPartFileName(BaseName, Index + 1)));
  717. }
  718. Index--;
  719. }
  720. while (Index >= 0);
  721. OpenLogFile();
  722. }
  723. }
  724. //---------------------------------------------------------------------------
  725. void __fastcall TSessionLog::DoAdd(TLogLineType Type, UnicodeString Line,
  726. void __fastcall (__closure *f)(TLogLineType Type, const UnicodeString & Line))
  727. {
  728. UnicodeString Prefix;
  729. if (!FName.IsEmpty())
  730. {
  731. Prefix = L"[" + FName + L"] ";
  732. }
  733. while (!Line.IsEmpty())
  734. {
  735. f(Type, Prefix + CutToChar(Line, L'\n', false));
  736. }
  737. }
  738. //---------------------------------------------------------------------------
  739. void __fastcall TSessionLog::Add(TLogLineType Type, const UnicodeString & Line)
  740. {
  741. DebugAssert(FConfiguration);
  742. if (Logging)
  743. {
  744. try
  745. {
  746. if (FParent != NULL)
  747. {
  748. DoAdd(Type, Line, DoAddToParent);
  749. }
  750. else
  751. {
  752. TGuard Guard(FCriticalSection);
  753. DoAdd(Type, Line, DoAddToSelf);
  754. }
  755. }
  756. catch (Exception &E)
  757. {
  758. // We failed logging, turn it off and notify user.
  759. FConfiguration->Logging = false;
  760. try
  761. {
  762. throw ExtException(&E, LoadStr(LOG_GEN_ERROR));
  763. }
  764. catch (Exception &E)
  765. {
  766. AddException(&E);
  767. FUI->HandleExtendedException(&E);
  768. }
  769. }
  770. }
  771. }
  772. //---------------------------------------------------------------------------
  773. void __fastcall TSessionLog::AddException(Exception * E)
  774. {
  775. if (E != NULL)
  776. {
  777. Add(llException, ExceptionLogString(E));
  778. }
  779. }
  780. //---------------------------------------------------------------------------
  781. void __fastcall TSessionLog::ReflectSettings()
  782. {
  783. TGuard Guard(FCriticalSection);
  784. FLogging =
  785. !FClosed &&
  786. ((FParent != NULL) || FConfiguration->Logging);
  787. // if logging to file was turned off or log file was changed -> close current log file
  788. if ((FFile != NULL) &&
  789. (!LogToFile() || (FCurrentLogFileName != FConfiguration->LogFileName)))
  790. {
  791. CloseLogFile();
  792. }
  793. if (FFile != NULL)
  794. {
  795. CheckSize(0);
  796. }
  797. }
  798. //---------------------------------------------------------------------------
  799. bool __fastcall TSessionLog::LogToFile()
  800. {
  801. return Logging && FConfiguration->LogToFile && (FParent == NULL);
  802. }
  803. //---------------------------------------------------------------------------
  804. void __fastcall TSessionLog::CloseLogFile()
  805. {
  806. if (FFile != NULL)
  807. {
  808. fclose((FILE *)FFile);
  809. FFile = NULL;
  810. }
  811. FCurrentLogFileName = L"";
  812. FCurrentFileName = L"";
  813. }
  814. //---------------------------------------------------------------------------
  815. void __fastcall TSessionLog::OpenLogFile()
  816. {
  817. try
  818. {
  819. DebugAssert(FFile == NULL);
  820. DebugAssert(FConfiguration != NULL);
  821. FCurrentLogFileName = FConfiguration->LogFileName;
  822. FFile = OpenFile(FCurrentLogFileName, FStarted, FSessionData, FConfiguration->LogFileAppend, FCurrentFileName);
  823. TSearchRec SearchRec;
  824. if (FileSearchRec(FCurrentFileName, SearchRec))
  825. {
  826. FCurrentFileSize = SearchRec.Size;
  827. }
  828. else
  829. {
  830. FCurrentFileSize = 0;
  831. }
  832. }
  833. catch (Exception & E)
  834. {
  835. // We failed logging to file, turn it off and notify user.
  836. FCurrentLogFileName = L"";
  837. FCurrentFileName = L"";
  838. FConfiguration->LogFileName = UnicodeString();
  839. try
  840. {
  841. throw ExtException(&E, LoadStr(LOG_GEN_ERROR));
  842. }
  843. catch (Exception & E)
  844. {
  845. AddException(&E);
  846. // not to deadlock with TSessionLog::ReflectSettings invoked by FConfiguration->LogFileName setter above
  847. TUnguard Unguard(FCriticalSection);
  848. FUI->HandleExtendedException(&E);
  849. }
  850. }
  851. // in case we are appending and the existing log file is already too large
  852. if (FFile != NULL)
  853. {
  854. CheckSize(0);
  855. }
  856. }
  857. //---------------------------------------------------------------------------
  858. void __fastcall TSessionLog::AddSystemInfo()
  859. {
  860. AddStartupInfo(true);
  861. }
  862. //---------------------------------------------------------------------------
  863. void __fastcall TSessionLog::AddStartupInfo()
  864. {
  865. AddStartupInfo(false);
  866. }
  867. //---------------------------------------------------------------------------
  868. void __fastcall TSessionLog::AddStartupInfo(bool System)
  869. {
  870. TSessionData * Data = (System ? NULL : FSessionData);
  871. if (Logging)
  872. {
  873. if (FParent != NULL)
  874. {
  875. // do not add session info for secondary session
  876. // (this should better be handled in the TSecondaryTerminal)
  877. }
  878. else
  879. {
  880. DoAddStartupInfo(Data);
  881. }
  882. }
  883. }
  884. //---------------------------------------------------------------------------
  885. UnicodeString __fastcall TSessionLog::GetTlsVersionName(TTlsVersion TlsVersion)
  886. {
  887. switch (TlsVersion)
  888. {
  889. default:
  890. DebugFail();
  891. case ssl2:
  892. return "SSLv2";
  893. case ssl3:
  894. return "SSLv3";
  895. case tls10:
  896. return "TLSv1.0";
  897. case tls11:
  898. return "TLSv1.1";
  899. case tls12:
  900. return "TLSv1.2";
  901. }
  902. }
  903. //---------------------------------------------------------------------------
  904. UnicodeString __fastcall TSessionLog::LogSensitive(const UnicodeString & Str)
  905. {
  906. if (FConfiguration->LogSensitive && !Str.IsEmpty())
  907. {
  908. return Str;
  909. }
  910. else
  911. {
  912. return BooleanToEngStr(!Str.IsEmpty());
  913. }
  914. }
  915. //---------------------------------------------------------------------------
  916. UnicodeString __fastcall TSessionLog::GetCmdLineLog()
  917. {
  918. UnicodeString Result = CmdLine;
  919. if (!Configuration->LogSensitive)
  920. {
  921. TManagementScript Script(StoredSessions, false);
  922. Script.MaskPasswordInCommandLine(Result, true);
  923. }
  924. return Result;
  925. }
  926. //---------------------------------------------------------------------------
  927. template <typename T>
  928. UnicodeString __fastcall EnumName(T Value, UnicodeString Names)
  929. {
  930. int N = int(Value);
  931. do
  932. {
  933. UnicodeString Name = CutToChar(Names, L';', true);
  934. if (N == 0)
  935. {
  936. return Name;
  937. }
  938. N--;
  939. }
  940. while ((N >= 0) && !Names.IsEmpty());
  941. return L"(unknown)";
  942. }
  943. //---------------------------------------------------------------------------
  944. #define ADSTR(S) DoAdd(llMessage, S, DoAddToSelf);
  945. #define ADF(S, F) ADSTR(FORMAT(S, F));
  946. //---------------------------------------------------------------------------
  947. void __fastcall TSessionLog::DoAddStartupInfo(TSessionData * Data)
  948. {
  949. if (Data == NULL)
  950. {
  951. AddSeparator();
  952. UnicodeString OS = WindowsVersionLong();
  953. AddToList(OS, WindowsProductName(), L" - ");
  954. ADF(L"WinSCP %s (OS %s)", (FConfiguration->VersionStr, OS));
  955. THierarchicalStorage * Storage = FConfiguration->CreateConfigStorage();
  956. try
  957. {
  958. ADF(L"Configuration: %s", (Storage->Source));
  959. }
  960. __finally
  961. {
  962. delete Storage;
  963. }
  964. wchar_t UserName[UNLEN + 1];
  965. unsigned long UserNameSize = LENOF(UserName);
  966. if (DebugAlwaysFalse(!GetUserNameEx(NameSamCompatible, UserName, &UserNameSize)))
  967. {
  968. wcscpy(UserName, L"<Failed to retrieve username>");
  969. }
  970. UnicodeString LogStr;
  971. if (FConfiguration->LogProtocol <= 0)
  972. {
  973. LogStr = L"Normal";
  974. }
  975. else if (FConfiguration->LogProtocol == 1)
  976. {
  977. LogStr = L"Debug 1";
  978. }
  979. else if (FConfiguration->LogProtocol >= 2)
  980. {
  981. LogStr = L"Debug 2";
  982. }
  983. if (FConfiguration->LogSensitive)
  984. {
  985. LogStr += L", Logging passwords";
  986. }
  987. if (FConfiguration->LogMaxSize > 0)
  988. {
  989. LogStr += FORMAT(L", Rotating after: %s", (SizeToStr(FConfiguration->LogMaxSize)));
  990. if (FConfiguration->LogMaxCount > 0)
  991. {
  992. LogStr += FORMAT(L", Keeping at most %d logs", (FConfiguration->LogMaxCount));
  993. }
  994. }
  995. ADF(L"Log level: %s", (LogStr));
  996. ADF(L"Local account: %s", (UserName));
  997. ADF(L"Working directory: %s", (GetCurrentDir()));
  998. ADF(L"Process ID: %d", (int(GetCurrentProcessId())));
  999. ADF(L"Command-line: %s", (GetCmdLineLog()));
  1000. if (FConfiguration->LogProtocol >= 1)
  1001. {
  1002. AddOptions(GetGlobalOptions());
  1003. }
  1004. ADF(L"Time zone: %s", (GetTimeZoneLogString()));
  1005. if (!AdjustClockForDSTEnabled())
  1006. {
  1007. ADSTR(L"Warning: System option \"Automatically adjust clock for Daylight Saving Time\" is disabled, timestamps will not be represented correctly");
  1008. }
  1009. ADF(L"Login time: %s", (FormatDateTime(L"dddddd tt", Now())));
  1010. AddSeparator();
  1011. }
  1012. else
  1013. {
  1014. ADF(L"Session name: %s (%s)", (Data->SessionName, Data->Source));
  1015. ADF(L"Host name: %s (Port: %d)", (Data->HostNameExpanded, Data->PortNumber));
  1016. ADF(L"User name: %s (Password: %s, Key file: %s, Passphrase: %s)",
  1017. (Data->UserNameExpanded, LogSensitive(Data->Password),
  1018. LogSensitive(Data->PublicKeyFile), LogSensitive(Data->Passphrase)));
  1019. if (Data->UsesSsh)
  1020. {
  1021. ADF(L"Tunnel: %s", (BooleanToEngStr(Data->Tunnel)));
  1022. if (Data->Tunnel)
  1023. {
  1024. ADF(L"Tunnel: Host name: %s (Port: %d)", (Data->TunnelHostName, Data->TunnelPortNumber));
  1025. ADF(L"Tunnel: User name: %s (Password: %s, Key file: %s)",
  1026. (Data->TunnelUserName,
  1027. LogSensitive(Data->TunnelPassword),
  1028. LogSensitive(Data->TunnelPublicKeyFile)));
  1029. ADF(L"Tunnel: Local port number: %d", (Data->TunnelLocalPortNumber));
  1030. }
  1031. }
  1032. ADF(L"Transfer Protocol: %s", (Data->FSProtocolStr));
  1033. if (Data->UsesSsh || (Data->FSProtocol == fsFTP))
  1034. {
  1035. TPingType PingType;
  1036. int PingInterval;
  1037. if (Data->FSProtocol == fsFTP)
  1038. {
  1039. PingType = Data->FtpPingType;
  1040. PingInterval = Data->FtpPingInterval;
  1041. }
  1042. else
  1043. {
  1044. PingType = Data->PingType;
  1045. PingInterval = Data->PingInterval;
  1046. }
  1047. ADF(L"Ping type: %s, Ping interval: %d sec; Timeout: %d sec",
  1048. (EnumName(PingType, PingTypeNames), PingInterval, Data->Timeout));
  1049. ADF(L"Disable Nagle: %s",
  1050. (BooleanToEngStr(Data->TcpNoDelay)));
  1051. }
  1052. ADF(L"Proxy: %s",
  1053. ((Data->FtpProxyLogonType != 0) ?
  1054. FORMAT(L"FTP proxy %d", (Data->FtpProxyLogonType)) :
  1055. EnumName(Data->ProxyMethod, ProxyMethodNames)));
  1056. if ((Data->FtpProxyLogonType != 0) || (Data->ProxyMethod != ::pmNone))
  1057. {
  1058. ADF(L"HostName: %s (Port: %d); Username: %s; Passwd: %s",
  1059. (Data->ProxyHost, Data->ProxyPort,
  1060. Data->ProxyUsername, LogSensitive(Data->ProxyPassword)));
  1061. if (Data->ProxyMethod == pmTelnet)
  1062. {
  1063. ADF(L"Telnet command: %s", (Data->ProxyTelnetCommand));
  1064. }
  1065. if (Data->ProxyMethod == pmCmd)
  1066. {
  1067. ADF(L"Local command: %s", (Data->ProxyLocalCommand));
  1068. }
  1069. }
  1070. if (Data->UsesSsh || (Data->FSProtocol == fsFTP))
  1071. {
  1072. ADF(L"Send buffer: %d", (Data->SendBuf));
  1073. }
  1074. if (Data->UsesSsh)
  1075. {
  1076. ADF(L"SSH protocol version: %s; Compression: %s",
  1077. (Data->SshProtStr, BooleanToEngStr(Data->Compression)));
  1078. ADF(L"Bypass authentication: %s",
  1079. (BooleanToEngStr(Data->SshNoUserAuth)));
  1080. ADF(L"Try agent: %s; Agent forwarding: %s; TIS/CryptoCard: %s; KI: %s; GSSAPI: %s",
  1081. (BooleanToEngStr(Data->TryAgent), BooleanToEngStr(Data->AgentFwd), BooleanToEngStr(Data->AuthTIS),
  1082. BooleanToEngStr(Data->AuthKI), BooleanToEngStr(Data->AuthGSSAPI)));
  1083. if (Data->AuthGSSAPI)
  1084. {
  1085. ADF(L"GSSAPI: Forwarding: %s",
  1086. (BooleanToEngStr(Data->GSSAPIFwdTGT)));
  1087. }
  1088. ADF(L"Ciphers: %s; Ssh2DES: %s",
  1089. (Data->CipherList, BooleanToEngStr(Data->Ssh2DES)));
  1090. ADF(L"KEX: %s", (Data->KexList));
  1091. UnicodeString Bugs;
  1092. for (int Index = 0; Index < BUG_COUNT; Index++)
  1093. {
  1094. AddToList(Bugs, EnumName(Data->Bug[(TSshBug)Index], AutoSwitchNames), L",");
  1095. }
  1096. ADF(L"SSH Bugs: %s", (Bugs));
  1097. ADF(L"Simple channel: %s", (BooleanToEngStr(Data->SshSimple)));
  1098. ADF(L"Return code variable: %s; Lookup user groups: %s",
  1099. ((Data->DetectReturnVar ? UnicodeString(L"Autodetect") : Data->ReturnVar),
  1100. EnumName(Data->LookupUserGroups, AutoSwitchNames)));
  1101. ADF(L"Shell: %s", ((Data->Shell.IsEmpty()? UnicodeString(L"default") : Data->Shell)));
  1102. ADF(L"EOL: %s, UTF: %s", (EnumName(Data->EOLType, EOLTypeNames), EnumName(Data->NotUtf, NotAutoSwitchNames))); // NotUtf duplicated in FTP branch
  1103. ADF(L"Clear aliases: %s, Unset nat.vars: %s, Resolve symlinks: %s; Follow directory symlinks: %s",
  1104. (BooleanToEngStr(Data->ClearAliases), BooleanToEngStr(Data->UnsetNationalVars),
  1105. BooleanToEngStr(Data->ResolveSymlinks), BooleanToEngStr(Data->FollowDirectorySymlinks)));
  1106. ADF(L"LS: %s, Ign LS warn: %s, Scp1 Comp: %s",
  1107. (Data->ListingCommand,
  1108. BooleanToEngStr(Data->IgnoreLsWarnings),
  1109. BooleanToEngStr(Data->Scp1Compatibility)));
  1110. }
  1111. if ((Data->FSProtocol == fsSFTP) || (Data->FSProtocol == fsSFTPonly))
  1112. {
  1113. UnicodeString Bugs;
  1114. for (int Index = 0; Index < SFTP_BUG_COUNT; Index++)
  1115. {
  1116. AddToList(Bugs, EnumName(Data->SFTPBug[(TSftpBug)Index], AutoSwitchNames), L",");
  1117. }
  1118. ADF(L"SFTP Bugs: %s", (Bugs));
  1119. ADF(L"SFTP Server: %s", ((Data->SftpServer.IsEmpty()? UnicodeString(L"default") : Data->SftpServer)));
  1120. }
  1121. bool FtpsOn = false;
  1122. if (Data->FSProtocol == fsFTP)
  1123. {
  1124. ADF(L"UTF: %s", (EnumName(Data->NotUtf, NotAutoSwitchNames))); // duplicated in UsesSsh branch
  1125. UnicodeString Ftps;
  1126. switch (Data->Ftps)
  1127. {
  1128. case ftpsImplicit:
  1129. Ftps = L"Implicit TLS/SSL";
  1130. FtpsOn = true;
  1131. break;
  1132. case ftpsExplicitSsl:
  1133. Ftps = L"Explicit SSL/TLS";
  1134. FtpsOn = true;
  1135. break;
  1136. case ftpsExplicitTls:
  1137. Ftps = L"Explicit TLS/SSL";
  1138. FtpsOn = true;
  1139. break;
  1140. default:
  1141. DebugAssert(Data->Ftps == ftpsNone);
  1142. Ftps = L"None";
  1143. break;
  1144. }
  1145. // kind of hidden option, so do not reveal it unless it is set
  1146. if (Data->FtpTransferActiveImmediately != asAuto)
  1147. {
  1148. ADF(L"Transfer active immediately: %s", (EnumName(Data->FtpTransferActiveImmediately, AutoSwitchNames)));
  1149. }
  1150. ADF(L"FTPS: %s [Client certificate: %s]",
  1151. (Ftps, LogSensitive(Data->TlsCertificateFile)));
  1152. ADF(L"FTP: Passive: %s [Force IP: %s]; MLSD: %s [List all: %s]; HOST: %s",
  1153. (BooleanToEngStr(Data->FtpPasvMode),
  1154. EnumName(Data->FtpForcePasvIp, AutoSwitchNames),
  1155. EnumName(Data->FtpUseMlsd, AutoSwitchNames),
  1156. EnumName(Data->FtpListAll, AutoSwitchNames),
  1157. EnumName(Data->FtpHost, AutoSwitchNames)));
  1158. }
  1159. if (Data->FSProtocol == fsWebDAV)
  1160. {
  1161. FtpsOn = (Data->Ftps != ftpsNone);
  1162. ADF(L"HTTPS: %s [Client certificate: %s]",
  1163. (BooleanToEngStr(FtpsOn), LogSensitive(Data->TlsCertificateFile)));
  1164. }
  1165. if (FtpsOn)
  1166. {
  1167. if (Data->FSProtocol == fsFTP)
  1168. {
  1169. ADF(L"Session reuse: %s", (BooleanToEngStr(Data->SslSessionReuse)));
  1170. }
  1171. ADF(L"TLS/SSL versions: %s-%s", (GetTlsVersionName(Data->MinTlsVersion), GetTlsVersionName(Data->MaxTlsVersion)));
  1172. }
  1173. ADF(L"Local directory: %s, Remote directory: %s, Update: %s, Cache: %s",
  1174. ((Data->LocalDirectory.IsEmpty() ? UnicodeString(L"default") : Data->LocalDirectory),
  1175. (Data->RemoteDirectory.IsEmpty() ? UnicodeString(L"home") : Data->RemoteDirectory),
  1176. BooleanToEngStr(Data->UpdateDirectories),
  1177. BooleanToEngStr(Data->CacheDirectories)));
  1178. ADF(L"Cache directory changes: %s, Permanent: %s",
  1179. (BooleanToEngStr(Data->CacheDirectoryChanges),
  1180. BooleanToEngStr(Data->PreserveDirectoryChanges)));
  1181. ADF(L"Recycle bin: Delete to: %s, Overwritten to: %s, Bin path: %s",
  1182. (BooleanToEngStr(Data->DeleteToRecycleBin),
  1183. BooleanToEngStr(Data->OverwrittenToRecycleBin),
  1184. Data->RecycleBinPath));
  1185. if (Data->TrimVMSVersions)
  1186. {
  1187. ADF(L"Trim VMS versions: %s",
  1188. (BooleanToEngStr(Data->TrimVMSVersions)));
  1189. }
  1190. UnicodeString TimeInfo;
  1191. if ((Data->FSProtocol == fsSFTP) || (Data->FSProtocol == fsSFTPonly) || (Data->FSProtocol == fsSCPonly) || (Data->FSProtocol == fsWebDAV))
  1192. {
  1193. AddToList(TimeInfo, FORMAT(L"DST mode: %s", (EnumName(Data->DSTMode, DSTModeNames))), L";");
  1194. }
  1195. if ((Data->FSProtocol == fsSCPonly) || (Data->FSProtocol == fsFTP))
  1196. {
  1197. int TimeDifferenceMin = TimeToMinutes(Data->TimeDifference);
  1198. AddToList(TimeInfo, FORMAT(L"Timezone offset: %dh %dm", ((TimeDifferenceMin / MinsPerHour), (TimeDifferenceMin % MinsPerHour))), L";");
  1199. }
  1200. ADSTR(TimeInfo);
  1201. if (Data->FSProtocol == fsWebDAV)
  1202. {
  1203. ADF(L"Compression: %s",
  1204. (BooleanToEngStr(Data->Compression)));
  1205. }
  1206. AddSeparator();
  1207. }
  1208. }
  1209. //---------------------------------------------------------------------------
  1210. void __fastcall TSessionLog::AddOption(const UnicodeString & LogStr)
  1211. {
  1212. ADSTR(LogStr);
  1213. }
  1214. //---------------------------------------------------------------------------
  1215. void __fastcall TSessionLog::AddOptions(TOptions * Options)
  1216. {
  1217. Options->LogOptions(AddOption);
  1218. }
  1219. //---------------------------------------------------------------------------
  1220. #undef ADF
  1221. #undef ADSTR
  1222. //---------------------------------------------------------------------------
  1223. void __fastcall TSessionLog::AddSeparator()
  1224. {
  1225. Add(llMessage, L"--------------------------------------------------------------------------");
  1226. }
  1227. //---------------------------------------------------------------------------
  1228. //---------------------------------------------------------------------------
  1229. __fastcall TActionLog::TActionLog(TSessionUI * UI, TDateTime Started, TSessionData * SessionData,
  1230. TConfiguration * Configuration)
  1231. {
  1232. DebugAssert(UI != NULL);
  1233. DebugAssert(SessionData != NULL);
  1234. Init(UI, Started, SessionData, Configuration);
  1235. }
  1236. //---------------------------------------------------------------------------
  1237. __fastcall TActionLog::TActionLog(TDateTime Started, TConfiguration * Configuration)
  1238. {
  1239. Init(NULL, Started, NULL, Configuration);
  1240. // not associated with session, so no need to waiting for anything
  1241. ReflectSettings();
  1242. }
  1243. //---------------------------------------------------------------------------
  1244. void __fastcall TActionLog::Init(TSessionUI * UI, TDateTime Started, TSessionData * SessionData,
  1245. TConfiguration * Configuration)
  1246. {
  1247. FCriticalSection = new TCriticalSection;
  1248. FConfiguration = Configuration;
  1249. FUI = UI;
  1250. FSessionData = SessionData;
  1251. FStarted = Started;
  1252. FFile = NULL;
  1253. FCurrentLogFileName = L"";
  1254. FCurrentFileName = L"";
  1255. FLogging = false;
  1256. FClosed = false;
  1257. FFailed = false;
  1258. FPendingActions = new TList();
  1259. FIndent = L" ";
  1260. FInGroup = false;
  1261. FEnabled = true;
  1262. }
  1263. //---------------------------------------------------------------------------
  1264. __fastcall TActionLog::~TActionLog()
  1265. {
  1266. DebugAssert(FPendingActions->Count == 0);
  1267. delete FPendingActions;
  1268. FClosed = true;
  1269. ReflectSettings();
  1270. DebugAssert(FFile == NULL);
  1271. delete FCriticalSection;
  1272. }
  1273. //---------------------------------------------------------------------------
  1274. void __fastcall TActionLog::Add(const UnicodeString & Line)
  1275. {
  1276. DebugAssert(FConfiguration);
  1277. if (FLogging)
  1278. {
  1279. TGuard Guard(FCriticalSection);
  1280. if (FFile == NULL)
  1281. {
  1282. OpenLogFile();
  1283. }
  1284. if (FFile != NULL)
  1285. {
  1286. try
  1287. {
  1288. UTF8String UtfLine = UTF8String(Line);
  1289. size_t Written =
  1290. fwrite(UtfLine.c_str(), 1, UtfLine.Length(), (FILE *)FFile);
  1291. if (Written != static_cast<size_t>(UtfLine.Length()))
  1292. {
  1293. throw ECRTExtException(L"");
  1294. }
  1295. #ifdef _DEBUG
  1296. #endif
  1297. Written =
  1298. fwrite("\n", 1, 1, (FILE *)FFile);
  1299. if (Written != 1)
  1300. {
  1301. throw ECRTExtException(L"");
  1302. }
  1303. }
  1304. catch (Exception &E)
  1305. {
  1306. FCriticalSection->Release();
  1307. // avoid endless loop when trying to close tags when closing log, when logging has failed
  1308. if (!FFailed)
  1309. {
  1310. FFailed = true;
  1311. // We failed logging, turn it off and notify user.
  1312. FConfiguration->LogActions = false;
  1313. if (FConfiguration->LogActionsRequired)
  1314. {
  1315. throw EFatal(&E, LoadStr(LOG_FATAL_ERROR));
  1316. }
  1317. else
  1318. {
  1319. try
  1320. {
  1321. throw ExtException(&E, LoadStr(LOG_GEN_ERROR));
  1322. }
  1323. catch (Exception &E)
  1324. {
  1325. if (FUI != NULL)
  1326. {
  1327. FUI->HandleExtendedException(&E);
  1328. }
  1329. }
  1330. }
  1331. }
  1332. }
  1333. }
  1334. }
  1335. }
  1336. //---------------------------------------------------------------------------
  1337. void __fastcall TActionLog::AddIndented(const UnicodeString & Line)
  1338. {
  1339. Add(FIndent + Line);
  1340. }
  1341. //---------------------------------------------------------------------------
  1342. void __fastcall TActionLog::AddFailure(TStrings * Messages)
  1343. {
  1344. AddIndented(L"<failure>");
  1345. AddMessages(L" ", Messages);
  1346. AddIndented(L"</failure>");
  1347. }
  1348. //---------------------------------------------------------------------------
  1349. void __fastcall TActionLog::AddFailure(Exception * E)
  1350. {
  1351. TStrings * Messages = ExceptionToMoreMessages(E);
  1352. if (Messages != NULL)
  1353. {
  1354. try
  1355. {
  1356. AddFailure(Messages);
  1357. }
  1358. __finally
  1359. {
  1360. delete Messages;
  1361. }
  1362. }
  1363. }
  1364. //---------------------------------------------------------------------------
  1365. void __fastcall TActionLog::AddMessages(UnicodeString Indent, TStrings * Messages)
  1366. {
  1367. for (int Index = 0; Index < Messages->Count; Index++)
  1368. {
  1369. AddIndented(
  1370. FORMAT(Indent + L"<message>%s</message>", (XmlEscape(Messages->Strings[Index]))));
  1371. }
  1372. }
  1373. //---------------------------------------------------------------------------
  1374. void __fastcall TActionLog::ReflectSettings()
  1375. {
  1376. TGuard Guard(FCriticalSection);
  1377. bool ALogging =
  1378. !FClosed && FConfiguration->LogActions && Enabled;
  1379. if (ALogging && !FLogging)
  1380. {
  1381. FLogging = true;
  1382. Add(L"<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
  1383. UnicodeString SessionName =
  1384. (FSessionData != NULL) ? XmlAttributeEscape(FSessionData->SessionName) : UnicodeString(L"nosession");
  1385. Add(FORMAT(L"<session xmlns=\"http://winscp.net/schema/session/1.0\" name=\"%s\" start=\"%s\">",
  1386. (SessionName, StandardTimestamp())));
  1387. }
  1388. else if (!ALogging && FLogging)
  1389. {
  1390. if (FInGroup)
  1391. {
  1392. EndGroup();
  1393. }
  1394. // do not try to close the file, if it has not been opened, to avoid recursion
  1395. if (FFile != NULL)
  1396. {
  1397. Add(L"</session>");
  1398. }
  1399. CloseLogFile();
  1400. FLogging = false;
  1401. }
  1402. }
  1403. //---------------------------------------------------------------------------
  1404. void __fastcall TActionLog::CloseLogFile()
  1405. {
  1406. if (FFile != NULL)
  1407. {
  1408. fclose((FILE *)FFile);
  1409. FFile = NULL;
  1410. }
  1411. FCurrentLogFileName = L"";
  1412. FCurrentFileName = L"";
  1413. }
  1414. //---------------------------------------------------------------------------
  1415. void __fastcall TActionLog::OpenLogFile()
  1416. {
  1417. try
  1418. {
  1419. DebugAssert(FFile == NULL);
  1420. DebugAssert(FConfiguration != NULL);
  1421. FCurrentLogFileName = FConfiguration->ActionsLogFileName;
  1422. FFile = OpenFile(FCurrentLogFileName, FStarted, FSessionData, false, FCurrentFileName);
  1423. }
  1424. catch (Exception & E)
  1425. {
  1426. // We failed logging to file, turn it off and notify user.
  1427. FCurrentLogFileName = L"";
  1428. FCurrentFileName = L"";
  1429. FConfiguration->LogActions = false;
  1430. if (FConfiguration->LogActionsRequired)
  1431. {
  1432. throw EFatal(&E, LoadStr(LOG_FATAL_ERROR));
  1433. }
  1434. else
  1435. {
  1436. try
  1437. {
  1438. throw ExtException(&E, LoadStr(LOG_GEN_ERROR));
  1439. }
  1440. catch (Exception & E)
  1441. {
  1442. if (FUI != NULL)
  1443. {
  1444. // not to deadlock with TSessionLog::ReflectSettings invoked by FConfiguration->LogFileName setter above
  1445. TUnguard Unguard(FCriticalSection);
  1446. FUI->HandleExtendedException(&E);
  1447. }
  1448. }
  1449. }
  1450. }
  1451. }
  1452. //---------------------------------------------------------------------------
  1453. void __fastcall TActionLog::AddPendingAction(TSessionActionRecord * Action)
  1454. {
  1455. FPendingActions->Add(Action);
  1456. }
  1457. //---------------------------------------------------------------------------
  1458. void __fastcall TActionLog::RecordPendingActions()
  1459. {
  1460. while ((FPendingActions->Count > 0) &&
  1461. static_cast<TSessionActionRecord *>(FPendingActions->Items[0])->Record())
  1462. {
  1463. FPendingActions->Delete(0);
  1464. }
  1465. }
  1466. //---------------------------------------------------------------------------
  1467. void __fastcall TActionLog::BeginGroup(UnicodeString Name)
  1468. {
  1469. DebugAssert(!FInGroup);
  1470. FInGroup = true;
  1471. DebugAssert(FIndent == L" ");
  1472. AddIndented(FORMAT(L"<group name=\"%s\" start=\"%s\">",
  1473. (XmlAttributeEscape(Name), StandardTimestamp())));
  1474. FIndent = L" ";
  1475. }
  1476. //---------------------------------------------------------------------------
  1477. void __fastcall TActionLog::EndGroup()
  1478. {
  1479. DebugAssert(FInGroup);
  1480. FInGroup = false;
  1481. DebugAssert(FIndent == L" ");
  1482. FIndent = L" ";
  1483. // this is called from ReflectSettings that in turn is called when logging fails,
  1484. // so do not try to close the group, if it has not been opened, to avoid recursion
  1485. if (FFile != NULL)
  1486. {
  1487. AddIndented(L"</group>");
  1488. }
  1489. }
  1490. //---------------------------------------------------------------------------
  1491. void __fastcall TActionLog::SetEnabled(bool value)
  1492. {
  1493. if (Enabled != value)
  1494. {
  1495. FEnabled = value;
  1496. ReflectSettings();
  1497. }
  1498. }