SessionInfo.cpp 45 KB

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