SessionInfo.cpp 52 KB

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