SessionInfo.cpp 51 KB

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