SessionInfo.cpp 48 KB

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