SessionInfo.cpp 32 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084
  1. //---------------------------------------------------------------------------
  2. #include <vcl.h>
  3. #pragma hdrstop
  4. #include <stdio.h>
  5. #include "Common.h"
  6. #include "SessionInfo.h"
  7. #include "Exceptions.h"
  8. #include "TextsCore.h"
  9. //---------------------------------------------------------------------------
  10. #pragma package(smart_init)
  11. //---------------------------------------------------------------------------
  12. AnsiString __fastcall XmlEscape(AnsiString Str)
  13. {
  14. for (int i = 1; i <= Str.Length(); i++)
  15. {
  16. const char * Repl = NULL;
  17. switch (Str[i])
  18. {
  19. case '&':
  20. Repl = "amp;";
  21. break;
  22. case '>':
  23. Repl = "gt;";
  24. break;
  25. case '<':
  26. Repl = "lt;";
  27. break;
  28. case '"':
  29. Repl = "quot;";
  30. break;
  31. case '\r':
  32. Str.Delete(i, 1);
  33. i--;
  34. break;
  35. }
  36. if (Repl != NULL)
  37. {
  38. Str[i] = '&';
  39. Str.Insert(Repl, i + 1);
  40. i += strlen(Repl);
  41. }
  42. }
  43. Str = AnsiToUtf8(Str);
  44. return Str;
  45. }
  46. //---------------------------------------------------------------------------
  47. AnsiString __fastcall XmlTimestamp(const TDateTime & DateTime)
  48. {
  49. return FormatDateTime("yyyy'-'mm'-'dd'T'hh':'nn':'ss'.'zzz'Z'", ConvertTimestampToUTC(DateTime));
  50. }
  51. //---------------------------------------------------------------------------
  52. AnsiString __fastcall XmlTimestamp()
  53. {
  54. return XmlTimestamp(Now());
  55. }
  56. //---------------------------------------------------------------------------
  57. #pragma warn -inl
  58. class TSessionActionRecord
  59. {
  60. public:
  61. __fastcall TSessionActionRecord(TSessionLog * Log, TLogAction Action) :
  62. FLog(Log),
  63. FAction(Action),
  64. FState(Opened),
  65. FRecursive(false),
  66. FErrorMessages(NULL),
  67. FNames(new TStringList()),
  68. FValues(new TStringList()),
  69. FFileList(NULL)
  70. {
  71. FLog->AddPendingAction(this);
  72. }
  73. __fastcall ~TSessionActionRecord()
  74. {
  75. delete FErrorMessages;
  76. delete FNames;
  77. delete FValues;
  78. delete FFileList;
  79. }
  80. void __fastcall Restart()
  81. {
  82. FState = Opened;
  83. FRecursive = false;
  84. delete FErrorMessages;
  85. FErrorMessages = NULL;
  86. delete FFileList;
  87. FFileList = NULL;
  88. FNames->Clear();
  89. FValues->Clear();
  90. }
  91. bool __fastcall Record()
  92. {
  93. bool Result = (FState != Opened);
  94. if (Result)
  95. {
  96. if ((FLog->FLoggingActions) && (FState != Cancelled))
  97. {
  98. const char * Name = ActionName();
  99. AnsiString Attrs;
  100. if (FRecursive)
  101. {
  102. Attrs = " recursive=\"true\"";
  103. }
  104. FLog->Add(llAction, FORMAT(" <%s%s>", (Name, Attrs)));
  105. for (int Index = 0; Index < FNames->Count; Index++)
  106. {
  107. AnsiString Value = FValues->Strings[Index];
  108. if (Value.IsEmpty())
  109. {
  110. FLog->Add(llAction, FORMAT(" <%s />", (FNames->Strings[Index])));
  111. }
  112. else
  113. {
  114. FLog->Add(llAction, FORMAT(" <%s value=\"%s\" />",
  115. (FNames->Strings[Index], XmlEscape(Value))));
  116. }
  117. }
  118. if (FFileList != NULL)
  119. {
  120. FLog->Add(llAction, " <files>");
  121. for (int Index = 0; Index < FFileList->Count; Index++)
  122. {
  123. TRemoteFile * File = FFileList->Files[Index];
  124. FLog->Add(llAction, " <file>");
  125. FLog->Add(llAction, FORMAT(" <filename value=\"%s\" />", (XmlEscape(File->FileName))));
  126. FLog->Add(llAction, FORMAT(" <type value=\"%s\" />", (XmlEscape(File->Type))));
  127. if (!File->IsDirectory)
  128. {
  129. FLog->Add(llAction, FORMAT(" <size value=\"%s\" />", (IntToStr(File->Size))));
  130. }
  131. FLog->Add(llAction, FORMAT(" <modification value=\"%s\" />", (XmlTimestamp(File->Modification))));
  132. FLog->Add(llAction, FORMAT(" <permissions value=\"%s\" />", (XmlEscape(File->Rights->Text))));
  133. FLog->Add(llAction, " </file>");
  134. }
  135. FLog->Add(llAction, " </files>");
  136. }
  137. if (FState == RolledBack)
  138. {
  139. if (FErrorMessages != NULL)
  140. {
  141. FLog->Add(llAction, " <result success=\"false\">");
  142. for (int Index = 0; Index < FErrorMessages->Count; Index++)
  143. {
  144. FLog->Add(llAction,
  145. FORMAT(" <message>%s</message>", (XmlEscape(FErrorMessages->Strings[Index]))));
  146. }
  147. FLog->Add(llAction, " </result>");
  148. }
  149. else
  150. {
  151. FLog->Add(llAction, " <result success=\"false\" />");
  152. }
  153. }
  154. else
  155. {
  156. FLog->Add(llAction, " <result success=\"true\" />");
  157. }
  158. FLog->Add(llAction, FORMAT(" </%s>", (Name)));
  159. }
  160. delete this;
  161. }
  162. return Result;
  163. }
  164. void __fastcall Commit()
  165. {
  166. Close(Committed);
  167. }
  168. void __fastcall Rollback(Exception * E)
  169. {
  170. assert(FErrorMessages == NULL);
  171. FErrorMessages = new TStringList();
  172. if (!E->Message.IsEmpty())
  173. {
  174. FErrorMessages->Add(E->Message);
  175. }
  176. ExtException * EE = dynamic_cast<ExtException *>(E);
  177. if ((EE != NULL) && (EE->MoreMessages != NULL))
  178. {
  179. FErrorMessages->AddStrings(EE->MoreMessages);
  180. }
  181. if (FErrorMessages->Count == 0)
  182. {
  183. delete FErrorMessages;
  184. FErrorMessages = NULL;
  185. }
  186. Close(RolledBack);
  187. }
  188. void __fastcall Cancel()
  189. {
  190. Close(Cancelled);
  191. }
  192. void __fastcall FileName(const AnsiString & FileName)
  193. {
  194. Parameter("filename", FileName);
  195. }
  196. void __fastcall Destination(const AnsiString & Destination)
  197. {
  198. Parameter("destination", Destination);
  199. }
  200. void __fastcall Rights(const TRights & Rights)
  201. {
  202. Parameter("permissions", Rights.Text);
  203. }
  204. void __fastcall Modification(const TDateTime & DateTime)
  205. {
  206. Parameter("modification", XmlTimestamp(DateTime));
  207. }
  208. void __fastcall Recursive()
  209. {
  210. FRecursive = true;
  211. }
  212. void __fastcall Command(const AnsiString & Command)
  213. {
  214. Parameter("command", Command);
  215. }
  216. void __fastcall AddOutput(AnsiString Output, bool StdError)
  217. {
  218. const char * Name = (StdError ? "erroroutput" : "output");
  219. int Index = FNames->IndexOf(Name);
  220. if (Index >= 0)
  221. {
  222. FValues->Strings[Index] = FValues->Strings[Index] + "\r\n" + Output;
  223. }
  224. else
  225. {
  226. Parameter(Name, Output);
  227. }
  228. }
  229. void __fastcall FileList(TRemoteFileList * FileList)
  230. {
  231. if (FFileList == NULL)
  232. {
  233. FFileList = new TRemoteFileList();
  234. }
  235. FileList->DuplicateTo(FFileList);
  236. }
  237. protected:
  238. enum TState { Opened, Committed, RolledBack, Cancelled };
  239. inline void __fastcall Close(TState State)
  240. {
  241. assert(FState == Opened);
  242. FState = State;
  243. FLog->RecordPendingActions();
  244. }
  245. const char * __fastcall ActionName()
  246. {
  247. switch (FAction)
  248. {
  249. case laUpload: return "upload";
  250. case laDownload: return "download";
  251. case laTouch: return "touch";
  252. case laChmod: return "chmod";
  253. case laMkdir: return "mkdir";
  254. case laRm: return "rm";
  255. case laMv: return "mv";
  256. case laCall: return "call";
  257. case laLs: return "ls";
  258. default: assert(false); return "";
  259. }
  260. }
  261. void __fastcall Parameter(const AnsiString & Name, const AnsiString & Value = "")
  262. {
  263. FNames->Add(Name);
  264. FValues->Add(Value);
  265. }
  266. private:
  267. TSessionLog * FLog;
  268. TLogAction FAction;
  269. TState FState;
  270. bool FRecursive;
  271. TStrings * FErrorMessages;
  272. TStrings * FNames;
  273. TStrings * FValues;
  274. TRemoteFileList * FFileList;
  275. };
  276. #pragma warn .inl
  277. //---------------------------------------------------------------------------
  278. //---------------------------------------------------------------------------
  279. __fastcall TSessionAction::TSessionAction(TSessionLog * Log, TLogAction Action)
  280. {
  281. if (Log->FLoggingActions)
  282. {
  283. FRecord = new TSessionActionRecord(Log, Action);
  284. }
  285. else
  286. {
  287. FRecord = NULL;
  288. }
  289. }
  290. //---------------------------------------------------------------------------
  291. __fastcall TSessionAction::~TSessionAction()
  292. {
  293. if (FRecord != NULL)
  294. {
  295. Commit();
  296. }
  297. }
  298. //---------------------------------------------------------------------------
  299. void __fastcall TSessionAction::Restart()
  300. {
  301. if (FRecord != NULL)
  302. {
  303. FRecord->Restart();
  304. }
  305. }
  306. //---------------------------------------------------------------------------
  307. void __fastcall TSessionAction::Commit()
  308. {
  309. if (FRecord != NULL)
  310. {
  311. TSessionActionRecord * Record = FRecord;
  312. FRecord = NULL;
  313. Record->Commit();
  314. }
  315. }
  316. //---------------------------------------------------------------------------
  317. void __fastcall TSessionAction::Rollback(Exception * E)
  318. {
  319. if (FRecord != NULL)
  320. {
  321. TSessionActionRecord * Record = FRecord;
  322. FRecord = NULL;
  323. Record->Rollback(E);
  324. }
  325. }
  326. //---------------------------------------------------------------------------
  327. void __fastcall TSessionAction::Cancel()
  328. {
  329. if (FRecord != NULL)
  330. {
  331. TSessionActionRecord * Record = FRecord;
  332. FRecord = NULL;
  333. Record->Cancel();
  334. }
  335. }
  336. //---------------------------------------------------------------------------
  337. //---------------------------------------------------------------------------
  338. __fastcall TFileSessionAction::TFileSessionAction(TSessionLog * Log, TLogAction Action) :
  339. TSessionAction(Log, Action)
  340. {
  341. };
  342. //---------------------------------------------------------------------------
  343. __fastcall TFileSessionAction::TFileSessionAction(
  344. TSessionLog * Log, TLogAction Action, const AnsiString & AFileName) :
  345. TSessionAction(Log, Action)
  346. {
  347. FileName(AFileName);
  348. };
  349. //---------------------------------------------------------------------------
  350. void __fastcall TFileSessionAction::FileName(const AnsiString & FileName)
  351. {
  352. if (FRecord != NULL)
  353. {
  354. FRecord->FileName(FileName);
  355. }
  356. }
  357. //---------------------------------------------------------------------------
  358. //---------------------------------------------------------------------------
  359. __fastcall TFileLocationSessionAction::TFileLocationSessionAction(
  360. TSessionLog * Log, TLogAction Action) :
  361. TFileSessionAction(Log, Action)
  362. {
  363. };
  364. //---------------------------------------------------------------------------
  365. __fastcall TFileLocationSessionAction::TFileLocationSessionAction(
  366. TSessionLog * Log, TLogAction Action, const AnsiString & FileName) :
  367. TFileSessionAction(Log, Action, FileName)
  368. {
  369. };
  370. //---------------------------------------------------------------------------
  371. void __fastcall TFileLocationSessionAction::Destination(const AnsiString & Destination)
  372. {
  373. if (FRecord != NULL)
  374. {
  375. FRecord->Destination(Destination);
  376. }
  377. }
  378. //---------------------------------------------------------------------------
  379. //---------------------------------------------------------------------------
  380. __fastcall TUploadSessionAction::TUploadSessionAction(TSessionLog * Log) :
  381. TFileLocationSessionAction(Log, laUpload)
  382. {
  383. };
  384. //---------------------------------------------------------------------------
  385. //---------------------------------------------------------------------------
  386. __fastcall TDownloadSessionAction::TDownloadSessionAction(TSessionLog * Log) :
  387. TFileLocationSessionAction(Log, laDownload)
  388. {
  389. };
  390. //---------------------------------------------------------------------------
  391. //---------------------------------------------------------------------------
  392. __fastcall TChmodSessionAction::TChmodSessionAction(
  393. TSessionLog * Log, const AnsiString & FileName) :
  394. TFileSessionAction(Log, laChmod, FileName)
  395. {
  396. }
  397. //---------------------------------------------------------------------------
  398. void __fastcall TChmodSessionAction::Recursive()
  399. {
  400. if (FRecord != NULL)
  401. {
  402. FRecord->Recursive();
  403. }
  404. }
  405. //---------------------------------------------------------------------------
  406. __fastcall TChmodSessionAction::TChmodSessionAction(
  407. TSessionLog * Log, const AnsiString & FileName, const TRights & ARights) :
  408. TFileSessionAction(Log, laChmod, FileName)
  409. {
  410. Rights(ARights);
  411. }
  412. //---------------------------------------------------------------------------
  413. void __fastcall TChmodSessionAction::Rights(const TRights & Rights)
  414. {
  415. if (FRecord != NULL)
  416. {
  417. FRecord->Rights(Rights);
  418. }
  419. }
  420. //---------------------------------------------------------------------------
  421. __fastcall TTouchSessionAction::TTouchSessionAction(
  422. TSessionLog * Log, const AnsiString & FileName, const TDateTime & Modification) :
  423. TFileSessionAction(Log, laTouch, FileName)
  424. {
  425. if (FRecord != NULL)
  426. {
  427. FRecord->Modification(Modification);
  428. }
  429. }
  430. //---------------------------------------------------------------------------
  431. __fastcall TMkdirSessionAction::TMkdirSessionAction(
  432. TSessionLog * Log, const AnsiString & FileName) :
  433. TFileSessionAction(Log, laMkdir, FileName)
  434. {
  435. }
  436. //---------------------------------------------------------------------------
  437. __fastcall TRmSessionAction::TRmSessionAction(
  438. TSessionLog * Log, const AnsiString & FileName) :
  439. TFileSessionAction(Log, laRm, FileName)
  440. {
  441. }
  442. //---------------------------------------------------------------------------
  443. void __fastcall TRmSessionAction::Recursive()
  444. {
  445. if (FRecord != NULL)
  446. {
  447. FRecord->Recursive();
  448. }
  449. }
  450. //---------------------------------------------------------------------------
  451. __fastcall TMvSessionAction::TMvSessionAction(TSessionLog * Log,
  452. const AnsiString & FileName, const AnsiString & ADestination) :
  453. TFileLocationSessionAction(Log, laMv, FileName)
  454. {
  455. Destination(ADestination);
  456. }
  457. //---------------------------------------------------------------------------
  458. __fastcall TCallSessionAction::TCallSessionAction(TSessionLog * Log,
  459. const AnsiString & Command, const AnsiString & Destination) :
  460. TSessionAction(Log, laCall)
  461. {
  462. if (FRecord != NULL)
  463. {
  464. FRecord->Command(Command);
  465. FRecord->Destination(Destination);
  466. }
  467. }
  468. //---------------------------------------------------------------------------
  469. void __fastcall TCallSessionAction::AddOutput(const AnsiString & Output, bool StdError)
  470. {
  471. if (FRecord != NULL)
  472. {
  473. FRecord->AddOutput(Output, StdError);
  474. }
  475. }
  476. //---------------------------------------------------------------------------
  477. __fastcall TLsSessionAction::TLsSessionAction(TSessionLog * Log,
  478. const AnsiString & Destination) :
  479. TSessionAction(Log, laLs)
  480. {
  481. if (FRecord != NULL)
  482. {
  483. FRecord->Destination(Destination);
  484. }
  485. }
  486. //---------------------------------------------------------------------------
  487. void __fastcall TLsSessionAction::FileList(TRemoteFileList * FileList)
  488. {
  489. if (FRecord != NULL)
  490. {
  491. FRecord->FileList(FileList);
  492. }
  493. }
  494. //---------------------------------------------------------------------------
  495. //---------------------------------------------------------------------------
  496. TSessionInfo::TSessionInfo()
  497. {
  498. LoginTime = Now();
  499. }
  500. //---------------------------------------------------------------------------
  501. TFileSystemInfo::TFileSystemInfo()
  502. {
  503. memset(&IsCapable, false, sizeof(IsCapable));
  504. }
  505. //---------------------------------------------------------------------------
  506. const char *LogLineMarks = "<>!.*";
  507. __fastcall TSessionLog::TSessionLog(TSessionUI* UI, TSessionData * SessionData,
  508. TConfiguration * Configuration):
  509. TStringList()
  510. {
  511. FCriticalSection = new TCriticalSection;
  512. FConfiguration = Configuration;
  513. FParent = NULL;
  514. FUI = UI;
  515. FSessionData = SessionData;
  516. FFile = NULL;
  517. FLoggedLines = 0;
  518. FTopIndex = -1;
  519. FCurrentLogFileName = "";
  520. FCurrentFileName = "";
  521. FLoggingActions = false;
  522. FClosed = false;
  523. FPendingActions = new TList();
  524. }
  525. //---------------------------------------------------------------------------
  526. __fastcall TSessionLog::~TSessionLog()
  527. {
  528. assert(FPendingActions->Count == 0);
  529. delete FPendingActions;
  530. FClosed = true;
  531. ReflectSettings();
  532. assert(FFile == NULL);
  533. delete FCriticalSection;
  534. }
  535. //---------------------------------------------------------------------------
  536. void __fastcall TSessionLog::Lock()
  537. {
  538. FCriticalSection->Enter();
  539. }
  540. //---------------------------------------------------------------------------
  541. void __fastcall TSessionLog::Unlock()
  542. {
  543. FCriticalSection->Leave();
  544. }
  545. //---------------------------------------------------------------------------
  546. AnsiString __fastcall TSessionLog::GetSessionName()
  547. {
  548. assert(FSessionData != NULL);
  549. return FSessionData->SessionName;
  550. }
  551. //---------------------------------------------------------------------------
  552. AnsiString __fastcall TSessionLog::GetLine(Integer Index)
  553. {
  554. return Strings[Index - FTopIndex];
  555. }
  556. //---------------------------------------------------------------------------
  557. TLogLineType __fastcall TSessionLog::GetType(int Index)
  558. {
  559. return (TLogLineType)Objects[Index - FTopIndex];
  560. }
  561. //---------------------------------------------------------------------------
  562. void __fastcall TSessionLog::DoAddToParent(TLogLineType Type, const AnsiString & Line)
  563. {
  564. assert(FParent != NULL);
  565. FParent->Add(Type, Line);
  566. }
  567. //---------------------------------------------------------------------------
  568. void __fastcall TSessionLog::DoAddToSelf(TLogLineType Type, const AnsiString & Line)
  569. {
  570. if (FTopIndex < 0)
  571. {
  572. FTopIndex = 0;
  573. }
  574. TStringList::AddObject(Line, (TObject*)Type);
  575. FLoggedLines++;
  576. if (LogToFile())
  577. {
  578. if (FFile == NULL)
  579. {
  580. OpenLogFile();
  581. }
  582. if (FFile != NULL)
  583. {
  584. if (Type != llAction)
  585. {
  586. AnsiString Timestamp = FormatDateTime(" yyyy-mm-dd hh:nn:ss.zzz ", Now());
  587. fputc(LogLineMarks[Type], (FILE *)FFile);
  588. fwrite(Timestamp.c_str(), Timestamp.Length(), 1, (FILE *)FFile);
  589. }
  590. // use fwrite instead of fprintf to make sure that even
  591. // non-ascii data (unicode) gets in.
  592. fwrite(Line.c_str(), Line.Length(), 1, (FILE *)FFile);
  593. fputc('\n', (FILE *)FFile);
  594. }
  595. }
  596. }
  597. //---------------------------------------------------------------------------
  598. void __fastcall TSessionLog::DoAdd(TLogLineType Type, AnsiString Line,
  599. void __fastcall (__closure *f)(TLogLineType Type, const AnsiString & Line))
  600. {
  601. AnsiString Prefix;
  602. if ((Type != llAction) && !Name.IsEmpty())
  603. {
  604. Prefix = "[" + Name + "] ";
  605. }
  606. while (!Line.IsEmpty())
  607. {
  608. f(Type, Prefix + CutToChar(Line, '\n', false));
  609. }
  610. }
  611. //---------------------------------------------------------------------------
  612. void __fastcall TSessionLog::Add(TLogLineType Type, const AnsiString & Line)
  613. {
  614. assert(FConfiguration);
  615. if (Logging && (FConfiguration->LogActions == (Type == llAction)))
  616. {
  617. try
  618. {
  619. if (FParent != NULL)
  620. {
  621. DoAdd(Type, Line, &DoAddToParent);
  622. }
  623. else
  624. {
  625. TGuard Guard(FCriticalSection);
  626. BeginUpdate();
  627. try
  628. {
  629. DoAdd(Type, Line, DoAddToSelf);
  630. }
  631. __finally
  632. {
  633. DeleteUnnecessary();
  634. EndUpdate();
  635. }
  636. }
  637. }
  638. catch (Exception &E)
  639. {
  640. // We failed logging, turn it off and notify user.
  641. FConfiguration->Logging = false;
  642. try
  643. {
  644. throw ExtException(&E, LOG_GEN_ERROR);
  645. }
  646. catch (Exception &E)
  647. {
  648. AddException(&E);
  649. FUI->HandleExtendedException(&E);
  650. }
  651. }
  652. }
  653. }
  654. //---------------------------------------------------------------------------
  655. void __fastcall TSessionLog::AddException(Exception * E)
  656. {
  657. if (E != NULL)
  658. {
  659. Add(llException, ExceptionLogString(E));
  660. }
  661. }
  662. //---------------------------------------------------------------------------
  663. void __fastcall TSessionLog::ReflectSettings()
  664. {
  665. TGuard Guard(FCriticalSection);
  666. bool ALogging =
  667. !FClosed &&
  668. ((FParent != NULL) || FConfiguration->Logging) &&
  669. ((FParent == NULL) || !FConfiguration->LogActions);
  670. bool LoggingActions = ALogging && FConfiguration->LogActions;
  671. if (LoggingActions && !FLoggingActions)
  672. {
  673. FLoggingActions = true;
  674. FLogging = ALogging;
  675. Add(llAction, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
  676. Add(llAction, FORMAT("<session xmlns=\"http://winscp.net/schema/session/1.0\" name=\"%s\" start=\"%s\">",
  677. (XmlEscape(FSessionData->SessionName), XmlTimestamp())));
  678. StateChange();
  679. }
  680. else if (!LoggingActions && FLoggingActions)
  681. {
  682. FLoggingActions = false;
  683. Add(llAction, "</session>");
  684. FLogging = ALogging;
  685. StateChange();
  686. }
  687. else if (FLogging != ALogging)
  688. {
  689. FLogging = ALogging;
  690. StateChange();
  691. }
  692. // if logging to file was turned off or log file was change -> close current log file
  693. // but disallow changing logfilename for xml logging
  694. if ((FFile != NULL) &&
  695. ((!LogToFile() || (FCurrentLogFileName != FConfiguration->LogFileName)) && !FLoggingActions))
  696. {
  697. CloseLogFile();
  698. }
  699. DeleteUnnecessary();
  700. }
  701. //---------------------------------------------------------------------------
  702. bool __fastcall TSessionLog::LogToFile()
  703. {
  704. return Logging && FConfiguration->LogToFile && (FParent == NULL);
  705. }
  706. //---------------------------------------------------------------------------
  707. void __fastcall TSessionLog::CloseLogFile()
  708. {
  709. if (FFile != NULL)
  710. {
  711. fclose((FILE *)FFile);
  712. FFile = NULL;
  713. }
  714. FCurrentLogFileName = "";
  715. FCurrentFileName = "";
  716. StateChange();
  717. }
  718. //---------------------------------------------------------------------------
  719. void TSessionLog::OpenLogFile()
  720. {
  721. try
  722. {
  723. assert(FFile == NULL);
  724. assert(FConfiguration != NULL);
  725. FCurrentLogFileName = FConfiguration->LogFileName;
  726. AnsiString NewFileName = StripPathQuotes(ExpandEnvironmentVariables(FCurrentLogFileName));
  727. TDateTime N = Now();
  728. for (int Index = 1; Index < NewFileName.Length(); Index++)
  729. {
  730. if (NewFileName[Index] == '!')
  731. {
  732. AnsiString Replacement;
  733. // keep consistent with TFileCustomCommand::PatternReplacement
  734. switch (tolower(NewFileName[Index + 1]))
  735. {
  736. case 'y':
  737. Replacement = FormatDateTime("yyyy", N);
  738. break;
  739. case 'm':
  740. Replacement = FormatDateTime("mm", N);
  741. break;
  742. case 'd':
  743. Replacement = FormatDateTime("dd", N);
  744. break;
  745. case 't':
  746. Replacement = FormatDateTime("hhnnss", N);
  747. break;
  748. case '@':
  749. Replacement = MakeValidFileName(FSessionData->HostName);
  750. break;
  751. case 's':
  752. Replacement = MakeValidFileName(FSessionData->SessionName);
  753. break;
  754. case '!':
  755. Replacement = "!";
  756. break;
  757. default:
  758. Replacement = AnsiString("!") + NewFileName[Index + 1];
  759. break;
  760. }
  761. NewFileName.Delete(Index, 2);
  762. NewFileName.Insert(Replacement, Index);
  763. Index += Replacement.Length() - 1;
  764. }
  765. }
  766. FFile = fopen(NewFileName.c_str(),
  767. (FConfiguration->LogFileAppend && !FLoggingActions ? "a" : "w"));
  768. if (FFile)
  769. {
  770. setvbuf((FILE *)FFile, NULL, _IONBF, BUFSIZ);
  771. FCurrentFileName = NewFileName;
  772. }
  773. else
  774. {
  775. throw Exception(FMTLOAD(LOG_OPENERROR, (NewFileName)));
  776. }
  777. }
  778. catch (Exception & E)
  779. {
  780. // We failed logging to file, turn it off and notify user.
  781. FCurrentLogFileName = "";
  782. FCurrentFileName = "";
  783. FConfiguration->LogToFile = false;
  784. try
  785. {
  786. throw ExtException(&E, LOG_GEN_ERROR);
  787. }
  788. catch (Exception & E)
  789. {
  790. AddException(&E);
  791. FUI->HandleExtendedException(&E);
  792. }
  793. }
  794. StateChange();
  795. }
  796. //---------------------------------------------------------------------------
  797. void TSessionLog::StateChange()
  798. {
  799. if (FOnStateChange != NULL)
  800. {
  801. FOnStateChange(this);
  802. }
  803. }
  804. //---------------------------------------------------------------------------
  805. void TSessionLog::DeleteUnnecessary()
  806. {
  807. BeginUpdate();
  808. try
  809. {
  810. if (!Logging || (FParent != NULL))
  811. {
  812. Clear();
  813. }
  814. else
  815. {
  816. while (!FConfiguration->LogWindowComplete && (Count > FConfiguration->LogWindowLines))
  817. {
  818. Delete(0);
  819. FTopIndex++;
  820. }
  821. }
  822. }
  823. __finally
  824. {
  825. EndUpdate();
  826. }
  827. }
  828. //---------------------------------------------------------------------------
  829. void __fastcall TSessionLog::AddStartupInfo()
  830. {
  831. if (Logging && !FConfiguration->LogActions)
  832. {
  833. if (FParent != NULL)
  834. {
  835. // do not add session info for secondary session
  836. // (this should better be handled in the TSecondaryTerminal)
  837. }
  838. else
  839. {
  840. DoAddStartupInfo(FSessionData);
  841. }
  842. }
  843. }
  844. //---------------------------------------------------------------------------
  845. void __fastcall TSessionLog::DoAddStartupInfo(TSessionData * Data)
  846. {
  847. TGuard Guard(FCriticalSection);
  848. BeginUpdate();
  849. try
  850. {
  851. #define ADF(S, F) DoAdd(llMessage, FORMAT(S, F), DoAddToSelf);
  852. AddSeparator();
  853. ADF("WinSCP %s (OS %s)", (FConfiguration->VersionStr, FConfiguration->OSVersionStr));
  854. THierarchicalStorage * Storage = FConfiguration->CreateScpStorage(false);
  855. try
  856. {
  857. ADF("Configuration: %s", (Storage->Source));
  858. }
  859. __finally
  860. {
  861. delete Storage;
  862. }
  863. ADF("Login time: %s", (FormatDateTime("dddddd tt", Now())));
  864. AddSeparator();
  865. ADF("Session name: %s (%s)", (Data->SessionName, Data->Source));
  866. ADF("Host name: %s (Port: %d)", (Data->HostName, Data->PortNumber));
  867. ADF("User name: %s (Password: %s, Key file: %s)",
  868. (Data->UserName, BooleanToEngStr(!Data->Password.IsEmpty()),
  869. BooleanToEngStr(!Data->PublicKeyFile.IsEmpty())))
  870. ADF("Tunnel: %s", (BooleanToEngStr(Data->Tunnel)));
  871. if (Data->Tunnel)
  872. {
  873. ADF("Tunnel: Host name: %s (Port: %d)", (Data->TunnelHostName, Data->TunnelPortNumber));
  874. ADF("Tunnel: User name: %s (Password: %s, Key file: %s)",
  875. (Data->TunnelUserName, BooleanToEngStr(!Data->TunnelPassword.IsEmpty()),
  876. BooleanToEngStr(!Data->TunnelPublicKeyFile.IsEmpty())))
  877. ADF("Tunnel: Local port number: %d", (Data->TunnelLocalPortNumber));
  878. }
  879. ADF("Transfer Protocol: %s", (Data->FSProtocolStr));
  880. char * PingTypes = "-NC";
  881. TPingType PingType;
  882. int PingInterval;
  883. if (Data->FSProtocol == fsFTP)
  884. {
  885. PingType = Data->FtpPingType;
  886. PingInterval = Data->FtpPingInterval;
  887. }
  888. else
  889. {
  890. PingType = Data->PingType;
  891. PingInterval = Data->PingInterval;
  892. }
  893. ADF("Ping type: %s, Ping interval: %d sec; Timeout: %d sec",
  894. (AnsiString(PingTypes[PingType]), PingInterval, Data->Timeout));
  895. ADF("Proxy: %s", (ProxyMethodList[Data->ProxyMethod]));
  896. if (Data->ProxyMethod != pmNone)
  897. {
  898. ADF("HostName: %s (Port: %d); Username: %s; Passwd: %s",
  899. (Data->ProxyHost, Data->ProxyPort,
  900. Data->ProxyUsername, BooleanToEngStr(!Data->ProxyPassword.IsEmpty())));
  901. if (Data->ProxyMethod == pmTelnet)
  902. {
  903. ADF("Telnet command: %s", (Data->ProxyTelnetCommand));
  904. }
  905. if (Data->ProxyMethod == pmCmd)
  906. {
  907. ADF("Local command: %s", (Data->ProxyLocalCommand));
  908. }
  909. }
  910. if (Data->UsesSsh)
  911. {
  912. ADF("SSH protocol version: %s; Compression: %s",
  913. (Data->SshProtStr, BooleanToEngStr(Data->Compression)));
  914. ADF("Bypass authentication: %s",
  915. (BooleanToEngStr(Data->SshNoUserAuth)));
  916. ADF("Try agent: %s; Agent forwarding: %s; TIS/CryptoCard: %s; KI: %s; GSSAPI: %s",
  917. (BooleanToEngStr(Data->TryAgent), BooleanToEngStr(Data->AgentFwd), BooleanToEngStr(Data->AuthTIS),
  918. BooleanToEngStr(Data->AuthKI), BooleanToEngStr(Data->AuthGSSAPI)));
  919. if (Data->AuthGSSAPI)
  920. {
  921. ADF("GSSAPI: Forwarding: %s; Server realm: %s",
  922. (BooleanToEngStr(Data->GSSAPIFwdTGT), Data->GSSAPIServerRealm));
  923. }
  924. ADF("Ciphers: %s; Ssh2DES: %s",
  925. (Data->CipherList, BooleanToEngStr(Data->Ssh2DES)));
  926. AnsiString Bugs;
  927. char const * BugFlags = "A+-";
  928. for (int Index = 0; Index < BUG_COUNT; Index++)
  929. {
  930. Bugs += AnsiString(BugFlags[Data->Bug[(TSshBug)Index]])+(Index<BUG_COUNT-1?",":"");
  931. }
  932. ADF("SSH Bugs: %s", (Bugs));
  933. Bugs = "";
  934. for (int Index = 0; Index < SFTP_BUG_COUNT; Index++)
  935. {
  936. Bugs += AnsiString(BugFlags[Data->SFTPBug[(TSftpBug)Index]])+(Index<SFTP_BUG_COUNT-1?",":"");
  937. }
  938. ADF("SFTP Bugs: %s", (Bugs));
  939. ADF("Return code variable: %s; Lookup user groups: %s",
  940. ((Data->DetectReturnVar ? AnsiString("Autodetect") : Data->ReturnVar),
  941. BooleanToEngStr(Data->LookupUserGroups)));
  942. ADF("Shell: %s", ((Data->Shell.IsEmpty()? AnsiString("default") : Data->Shell)));
  943. ADF("EOL: %d, UTF: %d", (Data->EOLType, Data->NotUtf));
  944. ADF("Clear aliases: %s, Unset nat.vars: %s, Resolve symlinks: %s",
  945. (BooleanToEngStr(Data->ClearAliases), BooleanToEngStr(Data->UnsetNationalVars),
  946. BooleanToEngStr(Data->ResolveSymlinks)));
  947. ADF("LS: %s, Ign LS warn: %s, Scp1 Comp: %s",
  948. (Data->ListingCommand,
  949. BooleanToEngStr(Data->IgnoreLsWarnings),
  950. BooleanToEngStr(Data->Scp1Compatibility)));
  951. }
  952. if (Data->FSProtocol == fsFTP)
  953. {
  954. AnsiString Ftps;
  955. switch (Data->Ftps)
  956. {
  957. case ftpsImplicit:
  958. Ftps = "Implicit SSL/TLS";
  959. break;
  960. case ftpsExplicitSsl:
  961. Ftps = "Explicit SSL";
  962. break;
  963. case ftpsExplicitTls:
  964. Ftps = "Explicit TLS";
  965. break;
  966. default:
  967. assert(Data->Ftps == ftpsNone);
  968. Ftps = "None";
  969. break;
  970. }
  971. ADF("FTP: FTPS: %s; Passive: %s [Force IP: %s]",
  972. (Ftps, BooleanToEngStr(Data->FtpPasvMode),
  973. BooleanToEngStr(Data->FtpForcePasvIp)));
  974. }
  975. ADF("Local directory: %s, Remote directory: %s, Update: %s, Cache: %s",
  976. ((Data->LocalDirectory.IsEmpty() ? AnsiString("default") : Data->LocalDirectory),
  977. (Data->RemoteDirectory.IsEmpty() ? AnsiString("home") : Data->RemoteDirectory),
  978. BooleanToEngStr(Data->UpdateDirectories),
  979. BooleanToEngStr(Data->CacheDirectories)));
  980. ADF("Cache directory changes: %s, Permanent: %s",
  981. (BooleanToEngStr(Data->CacheDirectoryChanges),
  982. BooleanToEngStr(Data->PreserveDirectoryChanges)));
  983. ADF("DST mode: %d", (int(Data->DSTMode)));
  984. AddSeparator();
  985. #undef ADF
  986. }
  987. __finally
  988. {
  989. DeleteUnnecessary();
  990. EndUpdate();
  991. }
  992. }
  993. //---------------------------------------------------------------------------
  994. void __fastcall TSessionLog::AddSeparator()
  995. {
  996. Add(llMessage, "--------------------------------------------------------------------------");
  997. }
  998. //---------------------------------------------------------------------------
  999. int __fastcall TSessionLog::GetBottomIndex()
  1000. {
  1001. return (Count > 0 ? (TopIndex + Count - 1) : -1);
  1002. }
  1003. //---------------------------------------------------------------------------
  1004. bool __fastcall TSessionLog::GetLoggingToFile()
  1005. {
  1006. assert((FFile == NULL) || LogToFile());
  1007. return (FFile != NULL);
  1008. }
  1009. //---------------------------------------------------------------------------
  1010. void __fastcall TSessionLog::Clear()
  1011. {
  1012. TGuard Guard(FCriticalSection);
  1013. FTopIndex += Count;
  1014. TStringList::Clear();
  1015. }
  1016. //---------------------------------------------------------------------------
  1017. void __fastcall TSessionLog::AddPendingAction(TSessionActionRecord * Action)
  1018. {
  1019. FPendingActions->Add(Action);
  1020. }
  1021. //---------------------------------------------------------------------------
  1022. void __fastcall TSessionLog::RecordPendingActions()
  1023. {
  1024. while ((FPendingActions->Count > 0) &&
  1025. static_cast<TSessionActionRecord *>(FPendingActions->Items[0])->Record())
  1026. {
  1027. FPendingActions->Delete(0);
  1028. }
  1029. }