SessionInfo.cpp 53 KB

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