SessionInfo.cpp 32 KB

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