TerminalManager.cpp 58 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842
  1. //---------------------------------------------------------------------------
  2. #define NO_WIN32_LEAN_AND_MEAN
  3. #include <vcl.h>
  4. #pragma hdrstop
  5. #include "TerminalManager.h"
  6. #include <Authenticate.h>
  7. #include "CustomScpExplorer.h"
  8. #include "NonVisual.h"
  9. #include "WinConfiguration.h"
  10. #include "Tools.h"
  11. #include <Common.h>
  12. #include <CoreMain.h>
  13. #include <GUITools.h>
  14. #include <TextsWin.h>
  15. #include <TextsCore.h>
  16. #include <Progress.h>
  17. #include <Exceptions.h>
  18. #include <VCLCommon.h>
  19. #include <WinApi.h>
  20. #include <PuttyTools.h>
  21. #include <HelpWin.h>
  22. #include <System.IOUtils.hpp>
  23. #include <StrUtils.hpp>
  24. //---------------------------------------------------------------------------
  25. #pragma package(smart_init)
  26. //---------------------------------------------------------------------------
  27. TTerminalManager * TTerminalManager::FInstance = NULL;
  28. //---------------------------------------------------------------------------
  29. __fastcall TManagedTerminal::TManagedTerminal(TSessionData * SessionData,
  30. TConfiguration * Configuration) :
  31. TTerminal(SessionData, Configuration),
  32. LocalExplorerState(NULL), RemoteExplorerState(NULL),
  33. ReopenStart(0), DirectoryLoaded(Now()), TerminalThread(NULL)
  34. {
  35. StateData = new TSessionData(L"");
  36. StateData->Assign(SessionData);
  37. StateData->LocalDirectory = ::ExpandFileName(StateData->LocalDirectory);
  38. }
  39. //---------------------------------------------------------------------------
  40. __fastcall TManagedTerminal::~TManagedTerminal()
  41. {
  42. delete StateData;
  43. delete LocalExplorerState;
  44. delete RemoteExplorerState;
  45. }
  46. //---------------------------------------------------------------------------
  47. //---------------------------------------------------------------------------
  48. TTerminalManager * __fastcall TTerminalManager::Instance(bool ForceCreation)
  49. {
  50. if (!FInstance && ForceCreation)
  51. {
  52. FInstance = new TTerminalManager();
  53. }
  54. return FInstance;
  55. }
  56. //---------------------------------------------------------------------------
  57. void __fastcall TTerminalManager::DestroyInstance()
  58. {
  59. DebugAssert(FInstance);
  60. SAFE_DESTROY(FInstance);
  61. }
  62. //---------------------------------------------------------------------------
  63. __fastcall TTerminalManager::TTerminalManager() :
  64. TTerminalList(Configuration)
  65. {
  66. FQueueSection = new TCriticalSection();
  67. FActiveTerminal = NULL;
  68. FScpExplorer = NULL;
  69. FDestroying = false;
  70. FTerminalPendingAction = tpNull;
  71. FDirectoryReadingStart = 0;
  72. FAuthenticateForm = NULL;
  73. FTaskbarList = NULL;
  74. FAuthenticating = 0;
  75. FMainThread = GetCurrentThreadId();
  76. FChangeSection.reset(new TCriticalSection());
  77. FPendingConfigurationChange = 0;
  78. FKeepAuthenticateForm = false;
  79. FApplicationsEvents.reset(new TApplicationEvents(Application));
  80. FApplicationsEvents->OnException = ApplicationException;
  81. FApplicationsEvents->OnShowHint = ApplicationShowHint;
  82. FApplicationsEvents->OnMessage = ApplicationMessage;
  83. FApplicationsEvents->OnModalBegin = ApplicationModalBegin;
  84. FApplicationsEvents->OnModalEnd = ApplicationModalEnd;
  85. DebugAssert(WinConfiguration->OnMasterPasswordPrompt == NULL);
  86. WinConfiguration->OnMasterPasswordPrompt = MasterPasswordPrompt;
  87. InitTaskbarButtonCreatedMessage();
  88. DebugAssert(Configuration && !Configuration->OnChange);
  89. Configuration->OnChange = ConfigurationChange;
  90. FOnLastTerminalClosed = NULL;
  91. FOnTerminalListChanged = NULL;
  92. FTerminalList = new TStringList();
  93. FQueues = new TList();
  94. FTerminationMessages = new TStringList();
  95. std::unique_ptr<TSessionData> DummyData(new TSessionData(L""));
  96. FLocalTerminal = CreateTerminal(DummyData.get());
  97. SetupTerminal(FLocalTerminal);
  98. }
  99. //---------------------------------------------------------------------------
  100. __fastcall TTerminalManager::~TTerminalManager()
  101. {
  102. FreeAll();
  103. DebugAssert(!ScpExplorer);
  104. DebugAssert(Configuration->OnChange == ConfigurationChange);
  105. Configuration->OnChange = NULL;
  106. FApplicationsEvents.reset(NULL);
  107. DebugAssert(WinConfiguration->OnMasterPasswordPrompt == MasterPasswordPrompt);
  108. WinConfiguration->OnMasterPasswordPrompt = NULL;
  109. delete FLocalTerminal;
  110. delete FQueues;
  111. delete FTerminationMessages;
  112. delete FTerminalList;
  113. CloseAutheticateForm();
  114. delete FQueueSection;
  115. ReleaseTaskbarList();
  116. }
  117. //---------------------------------------------------------------------------
  118. void __fastcall TTerminalManager::SetQueueConfiguration(TTerminalQueue * Queue)
  119. {
  120. Queue->TransfersLimit = GUIConfiguration->QueueTransfersLimit;
  121. Queue->KeepDoneItemsFor =
  122. (GUIConfiguration->QueueKeepDoneItems ? GUIConfiguration->QueueKeepDoneItemsFor : 0);
  123. }
  124. //---------------------------------------------------------------------------
  125. TTerminalQueue * __fastcall TTerminalManager::NewQueue(TTerminal * Terminal)
  126. {
  127. TTerminalQueue * Queue = new TTerminalQueue(Terminal, Configuration);
  128. SetQueueConfiguration(Queue);
  129. Queue->Enabled = WinConfiguration->EnableQueueByDefault;
  130. Queue->OnQueryUser = TerminalQueryUser;
  131. Queue->OnPromptUser = TerminalPromptUser;
  132. Queue->OnShowExtendedException = TerminalShowExtendedException;
  133. Queue->OnEvent = QueueEvent;
  134. return Queue;
  135. }
  136. //---------------------------------------------------------------------------
  137. TTerminal * __fastcall TTerminalManager::CreateTerminal(TSessionData * Data)
  138. {
  139. return new TManagedTerminal(Data, Configuration);
  140. }
  141. //---------------------------------------------------------------------------
  142. void __fastcall TTerminalManager::SetupTerminal(TTerminal * Terminal)
  143. {
  144. Terminal->OnQueryUser = TerminalQueryUser;
  145. Terminal->OnPromptUser = TerminalPromptUser;
  146. Terminal->OnDisplayBanner = TerminalDisplayBanner;
  147. Terminal->OnShowExtendedException = TerminalShowExtendedException;
  148. Terminal->OnProgress = OperationProgress;
  149. Terminal->OnFinished = OperationFinished;
  150. Terminal->OnDeleteLocalFile = DeleteLocalFile;
  151. Terminal->OnReadDirectoryProgress = TerminalReadDirectoryProgress;
  152. Terminal->OnInformation = TerminalInformation;
  153. Terminal->OnCustomCommand = TerminalCustomCommand;
  154. }
  155. //---------------------------------------------------------------------------
  156. TTerminal * __fastcall TTerminalManager::DoNewTerminal(TSessionData * Data)
  157. {
  158. TTerminal * Terminal = TTerminalList::NewTerminal(Data);
  159. try
  160. {
  161. FQueues->Add(NewQueue(Terminal));
  162. FTerminationMessages->Add(L"");
  163. SetupTerminal(Terminal);
  164. }
  165. catch(...)
  166. {
  167. if (Terminal != NULL)
  168. {
  169. FreeTerminal(Terminal);
  170. }
  171. throw;
  172. }
  173. return Terminal;
  174. }
  175. //---------------------------------------------------------------------------
  176. TTerminal * __fastcall TTerminalManager::NewTerminal(TSessionData * Data)
  177. {
  178. TTerminal * Terminal = DoNewTerminal(Data);
  179. DoTerminalListChanged();
  180. return Terminal;
  181. }
  182. //---------------------------------------------------------------------------
  183. TTerminal * __fastcall TTerminalManager::NewTerminals(TList * DataList)
  184. {
  185. TTerminal * Result = NULL;
  186. for (int Index = 0; Index < DataList->Count; Index++)
  187. {
  188. TTerminal * Terminal =
  189. NewTerminal(reinterpret_cast<TSessionData *>(DataList->Items[Index]));
  190. if (Index == 0)
  191. {
  192. Result = Terminal;
  193. }
  194. }
  195. DoTerminalListChanged();
  196. return Result;
  197. }
  198. //---------------------------------------------------------------------------
  199. void __fastcall TTerminalManager::FreeActiveTerminal()
  200. {
  201. if (FTerminalPendingAction == tpNull)
  202. {
  203. DebugAssert(ActiveTerminal);
  204. FreeTerminal(ActiveTerminal);
  205. }
  206. else
  207. {
  208. DebugAssert(FTerminalPendingAction == ::tpNone);
  209. FTerminalPendingAction = tpFree;
  210. }
  211. }
  212. //---------------------------------------------------------------------------
  213. void __fastcall TTerminalManager::DoConnectTerminal(TTerminal * Terminal, bool Reopen, bool AdHoc)
  214. {
  215. TManagedTerminal * ManagedTerminal = dynamic_cast<TManagedTerminal *>(Terminal);
  216. // it must be managed terminal, unless it is secondary terminal (of managed terminal)
  217. DebugAssert((ManagedTerminal != NULL) || (dynamic_cast<TSecondaryTerminal *>(Terminal) != NULL));
  218. // particularly when we are reconnecting RemoteDirectory of managed terminal
  219. // hold the last used remote directory as opposite to session data, which holds
  220. // the default remote directory.
  221. // make sure the last used directory is used, but the default is preserved too
  222. UnicodeString OrigRemoteDirectory = Terminal->SessionData->RemoteDirectory;
  223. try
  224. {
  225. TTerminalThread * TerminalThread = new TTerminalThread(Terminal);
  226. TerminalThread->AllowAbandon = (Terminal == FActiveTerminal);
  227. try
  228. {
  229. if (ManagedTerminal != NULL)
  230. {
  231. Terminal->SessionData->RemoteDirectory = ManagedTerminal->StateData->RemoteDirectory;
  232. if ((double)ManagedTerminal->ReopenStart == 0)
  233. {
  234. ManagedTerminal->ReopenStart = Now();
  235. }
  236. DebugAssert(ManagedTerminal->TerminalThread == NULL);
  237. ManagedTerminal->TerminalThread = TerminalThread;
  238. }
  239. TNotifyEvent OnIdle;
  240. ((TMethod*)&OnIdle)->Code = TerminalThreadIdle;
  241. TerminalThread->OnIdle = OnIdle;
  242. if (Reopen)
  243. {
  244. TerminalThread->TerminalReopen();
  245. }
  246. else
  247. {
  248. TerminalThread->TerminalOpen();
  249. }
  250. }
  251. __finally
  252. {
  253. TerminalThread->OnIdle = NULL;
  254. if (!TerminalThread->Release())
  255. {
  256. if (!AdHoc && (DebugAlwaysTrue(Terminal == FActiveTerminal)))
  257. {
  258. // terminal was abandoned, must create a new one to replace it
  259. Terminal = CreateTerminal(new TSessionData(L""));
  260. SetupTerminal(Terminal);
  261. OwnsObjects = false;
  262. Items[ActiveTerminalIndex] = Terminal;
  263. OwnsObjects = true;
  264. FActiveTerminal = Terminal;
  265. }
  266. // When abandoning cancelled terminal, DoInformation(Phase = 0) does not make it to TerminalInformation handler.
  267. if (DebugAlwaysTrue(FAuthenticating > 0))
  268. {
  269. FKeepAuthenticateForm = false;
  270. AuthenticatingDone();
  271. }
  272. }
  273. else
  274. {
  275. if (ManagedTerminal != NULL)
  276. {
  277. ManagedTerminal->TerminalThread = NULL;
  278. }
  279. }
  280. }
  281. }
  282. __finally
  283. {
  284. Terminal->SessionData->RemoteDirectory = OrigRemoteDirectory;
  285. if (Terminal->Active && (ManagedTerminal != NULL))
  286. {
  287. ManagedTerminal->ReopenStart = 0;
  288. }
  289. }
  290. }
  291. //---------------------------------------------------------------------------
  292. void __fastcall TTerminalManager::CloseAutheticateForm()
  293. {
  294. SAFE_DESTROY(FAuthenticateForm);
  295. }
  296. //---------------------------------------------------------------------------
  297. bool __fastcall TTerminalManager::ConnectTerminal(TTerminal * Terminal)
  298. {
  299. bool Result = true;
  300. // were it an active terminal, it would allow abandoning, what this API cannot deal with
  301. DebugAssert(Terminal != FActiveTerminal);
  302. try
  303. {
  304. DoConnectTerminal(Terminal, false, false);
  305. }
  306. catch (Exception & E)
  307. {
  308. ShowExtendedExceptionEx(Terminal, &E);
  309. Result = false;
  310. }
  311. return Result;
  312. }
  313. //---------------------------------------------------------------------------
  314. void __fastcall TTerminalManager::TerminalThreadIdle(void * /*Data*/, TObject * /*Sender*/)
  315. {
  316. Application->ProcessMessages();
  317. }
  318. //---------------------------------------------------------------------------
  319. bool __fastcall TTerminalManager::ConnectActiveTerminalImpl(bool Reopen)
  320. {
  321. TTerminalPendingAction Action;
  322. bool Result;
  323. do
  324. {
  325. Action = tpNull;
  326. Result = false;
  327. try
  328. {
  329. DebugAssert(ActiveTerminal);
  330. DoConnectTerminal(ActiveTerminal, Reopen, false);
  331. if (ScpExplorer)
  332. {
  333. DebugAssert(ActiveTerminal->Status == ssOpened);
  334. TerminalReady();
  335. }
  336. WinConfiguration->ClearTemporaryLoginData();
  337. Result = true;
  338. }
  339. catch (Exception & E)
  340. {
  341. DebugAssert(FTerminalPendingAction == tpNull);
  342. FTerminalPendingAction = ::tpNone;
  343. try
  344. {
  345. DebugAssert(ActiveTerminal != NULL);
  346. ActiveTerminal->ShowExtendedException(&E);
  347. Action = FTerminalPendingAction;
  348. }
  349. __finally
  350. {
  351. FTerminalPendingAction = tpNull;
  352. }
  353. }
  354. }
  355. while (Action == tpReconnect);
  356. if (Action == tpFree)
  357. {
  358. FreeActiveTerminal();
  359. }
  360. return Result;
  361. }
  362. //---------------------------------------------------------------------------
  363. bool __fastcall TTerminalManager::ConnectActiveTerminal()
  364. {
  365. ActiveTerminal->CollectUsage();
  366. // add only stored sessions to the jump list,
  367. // ad-hoc session cannot be reproduced from just a session name
  368. if (StoredSessions->FindSame(ActiveTerminal->SessionData) != NULL)
  369. {
  370. WinConfiguration->AddSessionToJumpList(ActiveTerminal->SessionData->SessionName);
  371. }
  372. FAuthenticationCancelled = false;
  373. bool Result = ConnectActiveTerminalImpl(false);
  374. UnicodeString DateStamp = StandardDatestamp();
  375. if (Result)
  376. {
  377. if (Configuration->Usage->Get(L"OpenedSessionsFailedLastDate") == DateStamp)
  378. {
  379. Configuration->Usage->Inc(L"OpenedSessionsFailedRecovered");
  380. }
  381. }
  382. else
  383. {
  384. Configuration->Usage->Inc(L"OpenedSessionsFailed");
  385. Configuration->Usage->Set(L"OpenedSessionsFailedLastDate", DateStamp);
  386. if (FAuthenticationCancelled)
  387. {
  388. Configuration->Usage->Inc(L"OpenedSessionsFailedAfterCancel");
  389. }
  390. }
  391. if (Result && WinConfiguration->AutoOpenInPutty && CanOpenInPutty())
  392. {
  393. try
  394. {
  395. OpenInPutty();
  396. }
  397. catch(Exception & E)
  398. {
  399. ShowExtendedExceptionEx(NULL, &E);
  400. }
  401. }
  402. return Result;
  403. }
  404. //---------------------------------------------------------------------------
  405. void __fastcall TTerminalManager::DisconnectActiveTerminal()
  406. {
  407. DebugAssert(ActiveTerminal);
  408. int Index = IndexOf(ActiveTerminal);
  409. TTerminalQueue * OldQueue;
  410. TTerminalQueue * NewQueue;
  411. OldQueue = reinterpret_cast<TTerminalQueue *>(FQueues->Items[Index]);
  412. NewQueue = this->NewQueue(ActiveTerminal);
  413. FQueues->Items[Index] = NewQueue;
  414. ScpExplorer->Queue = NewQueue;
  415. delete OldQueue;
  416. }
  417. //---------------------------------------------------------------------------
  418. void __fastcall TTerminalManager::ReconnectActiveTerminal()
  419. {
  420. DebugAssert(ActiveTerminal);
  421. if (ScpExplorer)
  422. {
  423. if (ScpExplorer->Terminal == ActiveTerminal)
  424. {
  425. ScpExplorer->UpdateTerminal(ActiveTerminal);
  426. }
  427. }
  428. try
  429. {
  430. if (FTerminalPendingAction == tpNull)
  431. {
  432. ConnectActiveTerminalImpl(true);
  433. }
  434. else
  435. {
  436. FTerminalPendingAction = tpReconnect;
  437. }
  438. }
  439. catch(...)
  440. {
  441. FreeActiveTerminal();
  442. throw;
  443. }
  444. }
  445. //---------------------------------------------------------------------------
  446. void __fastcall TTerminalManager::FreeAll()
  447. {
  448. FDestroying = true;
  449. try
  450. {
  451. while (Count)
  452. {
  453. FreeTerminal(Terminals[0]);
  454. }
  455. }
  456. __finally
  457. {
  458. FDestroying = false;
  459. }
  460. }
  461. //---------------------------------------------------------------------------
  462. void __fastcall TTerminalManager::FreeTerminal(TTerminal * Terminal)
  463. {
  464. try
  465. {
  466. // we want the Login dialog to open on auto-workspace name,
  467. // as set in TCustomScpExplorerForm::FormClose
  468. if (!FDestroying || !WinConfiguration->AutoSaveWorkspace)
  469. {
  470. if (StoredSessions->FindSame(Terminal->SessionData) != NULL)
  471. {
  472. WinConfiguration->LastStoredSession = Terminal->SessionData->Name;
  473. }
  474. }
  475. if (ScpExplorer != NULL)
  476. {
  477. ScpExplorer->TerminalRemoved(Terminal);
  478. }
  479. if (Terminal->Active)
  480. {
  481. Terminal->Close();
  482. }
  483. }
  484. __finally
  485. {
  486. int Index = IndexOf(Terminal);
  487. Extract(Terminal);
  488. TTerminalQueue * Queue;
  489. Queue = reinterpret_cast<TTerminalQueue *>(FQueues->Items[Index]);
  490. FQueues->Delete(Index);
  491. FTerminationMessages->Delete(Index);
  492. if (ActiveTerminal && (Terminal == ActiveTerminal))
  493. {
  494. if ((Count > 0) && !FDestroying)
  495. {
  496. ActiveTerminal = Terminals[Index < Count ? Index : Index - 1];
  497. }
  498. else
  499. {
  500. ActiveTerminal = NULL;
  501. }
  502. }
  503. else
  504. {
  505. SaveTerminal(Terminal);
  506. }
  507. // only now all references to/from queue (particularly events to explorer)
  508. // are cleared
  509. delete Queue;
  510. delete Terminal;
  511. DoTerminalListChanged();
  512. }
  513. }
  514. //---------------------------------------------------------------------------
  515. void __fastcall TTerminalManager::SetScpExplorer(TCustomScpExplorerForm * value)
  516. {
  517. if (ScpExplorer != value)
  518. {
  519. // changing explorer is not supported yet
  520. DebugAssert(!ScpExplorer || !value);
  521. FScpExplorer = value;
  522. if (FScpExplorer)
  523. {
  524. FScpExplorer->Terminal = ActiveTerminal;
  525. FScpExplorer->Queue = ActiveQueue;
  526. FOnLastTerminalClosed = FScpExplorer->LastTerminalClosed;
  527. FOnTerminalListChanged = FScpExplorer->TerminalListChanged;
  528. UpdateTaskbarList();
  529. }
  530. else
  531. {
  532. FOnLastTerminalClosed = NULL;
  533. FOnTerminalListChanged = NULL;
  534. }
  535. }
  536. }
  537. //---------------------------------------------------------------------------
  538. void __fastcall TTerminalManager::SetActiveTerminal(TTerminal * value)
  539. {
  540. DoSetActiveTerminal(value, false);
  541. }
  542. //---------------------------------------------------------------------------
  543. void __fastcall TTerminalManager::SetActiveTerminalWithAutoReconnect(TTerminal * value)
  544. {
  545. DoSetActiveTerminal(value, true);
  546. }
  547. //---------------------------------------------------------------------------
  548. void __fastcall TTerminalManager::DoSetActiveTerminal(TTerminal * value, bool AutoReconnect)
  549. {
  550. if (ActiveTerminal != value)
  551. {
  552. // here used to be call to TCustomScpExporer::UpdateSessionData (now UpdateTerminal)
  553. // but it seems to be duplicate to call from TCustomScpExporer::TerminalChanging
  554. TTerminal * PActiveTerminal = ActiveTerminal;
  555. FActiveTerminal = value;
  556. // moved from else block of next if (ActiveTerminal) statement
  557. // so ScpExplorer can update its caption
  558. UpdateAppTitle();
  559. if (ScpExplorer)
  560. {
  561. if (ActiveTerminal && (ActiveTerminal->Status == ssOpened))
  562. {
  563. TerminalReady();
  564. }
  565. else
  566. {
  567. ScpExplorer->Terminal = NULL;
  568. ScpExplorer->Queue = NULL;
  569. }
  570. }
  571. if (PActiveTerminal && !PActiveTerminal->Active)
  572. {
  573. SaveTerminal(PActiveTerminal);
  574. }
  575. if (ActiveTerminal)
  576. {
  577. int Index = ActiveTerminalIndex;
  578. if (!ActiveTerminal->Active && !FTerminationMessages->Strings[Index].IsEmpty())
  579. {
  580. UnicodeString Message = FTerminationMessages->Strings[Index];
  581. FTerminationMessages->Strings[Index] = L"";
  582. if (AutoReconnect)
  583. {
  584. ReconnectActiveTerminal();
  585. }
  586. else
  587. {
  588. Exception * E = new ESshFatal(NULL, Message);
  589. try
  590. {
  591. // finally show pending terminal message,
  592. // this gives user also possibility to reconnect
  593. ActiveTerminal->ShowExtendedException(E);
  594. }
  595. __finally
  596. {
  597. delete E;
  598. }
  599. }
  600. }
  601. }
  602. else
  603. {
  604. if (OnLastTerminalClosed)
  605. {
  606. OnLastTerminalClosed(this);
  607. }
  608. }
  609. if ((ActiveTerminal != NULL) && !ActiveTerminal->Active)
  610. {
  611. ConnectActiveTerminal();
  612. }
  613. }
  614. }
  615. //---------------------------------------------------------------------------
  616. void __fastcall TTerminalManager::QueueStatusUpdated()
  617. {
  618. UpdateAppTitle();
  619. }
  620. //---------------------------------------------------------------------------
  621. bool __fastcall TTerminalManager::ShouldDisplayQueueStatusOnAppTitle()
  622. {
  623. bool Result = IsApplicationMinimized();
  624. if (!Result && (ScpExplorer != NULL))
  625. {
  626. HWND Window = GetActiveWindow();
  627. Window = GetAncestor(Window, GA_ROOTOWNER);
  628. Result = (ScpExplorer->Handle != Window);
  629. }
  630. return Result;
  631. }
  632. //---------------------------------------------------------------------------
  633. UnicodeString __fastcall TTerminalManager::GetAppProgressTitle()
  634. {
  635. UnicodeString Result;
  636. UnicodeString QueueProgressTitle;
  637. UnicodeString ProgressTitle = !FProgressTitle.IsEmpty() ? FProgressTitle : ScpExplorer->GetProgressTitle();
  638. if (!FForegroundProgressTitle.IsEmpty())
  639. {
  640. Result = FForegroundProgressTitle;
  641. }
  642. else if (!ProgressTitle.IsEmpty() && !ForegroundTask())
  643. {
  644. Result = ProgressTitle;
  645. }
  646. else if (ShouldDisplayQueueStatusOnAppTitle() &&
  647. !(QueueProgressTitle = ScpExplorer->GetQueueProgressTitle()).IsEmpty())
  648. {
  649. Result = QueueProgressTitle;
  650. }
  651. if (!Result.IsEmpty())
  652. {
  653. Result += L" - ";
  654. }
  655. return Result;
  656. }
  657. //---------------------------------------------------------------------------
  658. void __fastcall TTerminalManager::UpdateAppTitle()
  659. {
  660. if (ScpExplorer)
  661. {
  662. TForm * MainForm = GetMainForm();
  663. if (MainForm != ScpExplorer)
  664. {
  665. // triggers caption update for some forms
  666. MainForm->Perform(WM_MANAGES_CAPTION, 0, 0);
  667. }
  668. UnicodeString NewTitle = FormatMainFormCaption(GetActiveTerminalTitle(false));
  669. UnicodeString ProgressTitle = GetAppProgressTitle();
  670. if (!ProgressTitle.IsEmpty())
  671. {
  672. NewTitle = ProgressTitle + NewTitle;
  673. }
  674. else if (ActiveTerminal && (ScpExplorer != NULL))
  675. {
  676. AddToList(NewTitle, ScpExplorer->PathForCaption(), L" - ");
  677. }
  678. // Not updating MainForm here, as for all other possible main forms, this code is actually not what we want.
  679. // And they all update their title on their own (some using GetAppProgressTitle()).
  680. ScpExplorer->Caption = NewTitle;
  681. ScpExplorer->ApplicationTitleChanged();
  682. }
  683. }
  684. //---------------------------------------------------------------------------
  685. void __fastcall TTerminalManager::SaveTerminal(TTerminal * Terminal)
  686. {
  687. TSessionData * Data = StoredSessions->FindSame(Terminal->SessionData);
  688. if (Data != NULL)
  689. {
  690. TManagedTerminal * ManagedTerminal = dynamic_cast<TManagedTerminal *>(Terminal);
  691. DebugAssert(ManagedTerminal != NULL);
  692. bool Changed = false;
  693. if (Terminal->SessionData->UpdateDirectories)
  694. {
  695. Data->CopyDirectoriesStateData(ManagedTerminal->StateData);
  696. Changed = true;
  697. }
  698. if (Changed)
  699. {
  700. // modified only, implicit
  701. StoredSessions->Save(false, false);
  702. }
  703. }
  704. }
  705. //---------------------------------------------------------------------------
  706. void __fastcall TTerminalManager::HandleException(Exception * E)
  707. {
  708. // can be null for example when exception is thrown on login dialog
  709. if (ActiveTerminal != NULL)
  710. {
  711. ActiveTerminal->ShowExtendedException(E);
  712. }
  713. else
  714. {
  715. ShowExtendedException(E);
  716. }
  717. }
  718. //---------------------------------------------------------------------------
  719. void __fastcall TTerminalManager::ApplicationException(TObject * /*Sender*/,
  720. Exception * E)
  721. {
  722. HandleException(E);
  723. }
  724. //---------------------------------------------------------------------------
  725. void __fastcall TTerminalManager::ApplicationShowHint(UnicodeString & HintStr,
  726. bool & /*CanShow*/, THintInfo & HintInfo)
  727. {
  728. HintInfo.HintData = HintInfo.HintControl;
  729. if (HasLabelHintPopup(HintInfo.HintControl, HintStr))
  730. {
  731. // Hack for transfer setting labels.
  732. // Should be converted to something like HintLabel()
  733. HintInfo.HideTimeout = 100000; // "almost" never
  734. }
  735. else if (dynamic_cast<TProgressBar *>(HintInfo.HintControl) != NULL)
  736. {
  737. // Hint is forcibly hidden in TProgressForm::FormHide
  738. HintInfo.HideTimeout = 100000; // "almost" never
  739. HintInfo.ReshowTimeout = 500; // updated each 0.5s
  740. }
  741. else
  742. {
  743. int HintMaxWidth = 300;
  744. TControl * ScaleControl = HintInfo.HintControl;
  745. if (DebugAlwaysFalse(HintInfo.HintControl == NULL) ||
  746. (GetParentForm(HintInfo.HintControl) == NULL))
  747. {
  748. ScaleControl = ScpExplorer;
  749. }
  750. HintMaxWidth = ScaleByTextHeight(ScaleControl, HintMaxWidth);
  751. HintInfo.HintMaxWidth = HintMaxWidth;
  752. }
  753. }
  754. //---------------------------------------------------------------------------
  755. bool __fastcall TTerminalManager::HandleMouseWheel(WPARAM WParam, LPARAM LParam)
  756. {
  757. // WORKAROUND This is no longer necessary on Windows 10 (except for WM_WANTS_MOUSEWHEEL_INACTIVE part)
  758. bool Result = false;
  759. if (Application->Active)
  760. {
  761. TPoint Point(LOWORD(LParam), HIWORD(LParam));
  762. TWinControl * Control = FindVCLWindow(Point);
  763. if (Control != NULL)
  764. {
  765. TCustomForm * Form = GetParentForm(Control);
  766. // Only case we expect the parent form to be NULL is on the Find/Replace dialog,
  767. // which is owned by VCL's internal TRedirectorWindow.
  768. DebugAssert((Form != NULL) || (Control->ClassName() == L"TRedirectorWindow"));
  769. if (Form != NULL)
  770. {
  771. // Send it only to windows we tested it with.
  772. // Though we should sooner or later remove this test and pass it to all our windows.
  773. if (Form->Active && (Form->Perform(WM_WANTS_MOUSEWHEEL, 0, 0) == 1))
  774. {
  775. SendMessage(Control->Handle, WM_MOUSEWHEEL, WParam, LParam);
  776. Result = true;
  777. }
  778. else if (!Form->Active && (Form->Perform(WM_WANTS_MOUSEWHEEL_INACTIVE, 0, 0) == 1))
  779. {
  780. TWinControl * Control2;
  781. // FindVCLWindow stops on window level, when the window is not active? or when there's a modal window over it?
  782. // (but in any case, when we have operation running on top of Synchronization checklist).
  783. // WORKAROUND: The while loop does what AllLevels parameter of ControlAtPos should do, but it's broken.
  784. // See http://qc.embarcadero.com/wc/qcmain.aspx?d=82143
  785. while ((Control2 = dynamic_cast<TWinControl *>(Control->ControlAtPos(Control->ScreenToClient(Point), false, true))) != NULL)
  786. {
  787. Control = Control2;
  788. }
  789. SendMessage(Control->Handle, WM_MOUSEWHEEL, WParam, LParam);
  790. Result = true;
  791. }
  792. }
  793. }
  794. }
  795. return Result;
  796. }
  797. //---------------------------------------------------------------------------
  798. void __fastcall TTerminalManager::ApplicationMessage(TMsg & Msg, bool & Handled)
  799. {
  800. if (Msg.message == FTaskbarButtonCreatedMessage)
  801. {
  802. CreateTaskbarList();
  803. }
  804. if (Msg.message == WM_MOUSEWHEEL)
  805. {
  806. Handled = HandleMouseWheel(Msg.wParam, Msg.lParam);
  807. }
  808. }
  809. //---------------------------------------------------------------------------
  810. void __fastcall TTerminalManager::ApplicationModalBegin(TObject * /*Sender*/)
  811. {
  812. NonVisualDataModule->StartBusy();
  813. if (ScpExplorer != NULL)
  814. {
  815. ScpExplorer->SuspendWindowLock();
  816. }
  817. }
  818. //---------------------------------------------------------------------------
  819. void __fastcall TTerminalManager::ApplicationModalEnd(TObject * /*Sender*/)
  820. {
  821. NonVisualDataModule->EndBusy();
  822. if (ScpExplorer != NULL)
  823. {
  824. ScpExplorer->ResumeWindowLock();
  825. }
  826. }
  827. //---------------------------------------------------------------------------
  828. void __fastcall TTerminalManager::InitTaskbarButtonCreatedMessage()
  829. {
  830. // XE6 VCL already handles TaskbarButtonCreated, but does not call ChangeWindowMessageFilterEx.
  831. // So we keep our implementation.
  832. // See also https://stackoverflow.com/q/14614823/850848#14618587
  833. FTaskbarButtonCreatedMessage = RegisterWindowMessage(L"TaskbarButtonCreated");
  834. HINSTANCE User32Library = LoadLibrary(L"user32.dll");
  835. ChangeWindowMessageFilterExProc ChangeWindowMessageFilterEx =
  836. (ChangeWindowMessageFilterExProc)GetProcAddress(User32Library, "ChangeWindowMessageFilterEx");
  837. if (ChangeWindowMessageFilterEx != NULL)
  838. {
  839. // without this we won't get TaskbarButtonCreated, when app is running elevated
  840. ChangeWindowMessageFilterEx(
  841. Application->Handle, FTaskbarButtonCreatedMessage, MSGFLT_ALLOW, NULL);
  842. }
  843. }
  844. //---------------------------------------------------------------------------
  845. void __fastcall TTerminalManager::CreateTaskbarList()
  846. {
  847. ReleaseTaskbarList();
  848. if(SUCCEEDED(CoCreateInstance(CLSID_TaskbarList, NULL, CLSCTX_ALL,
  849. IID_ITaskbarList3, (void **) &FTaskbarList)))
  850. {
  851. if (ScpExplorer != NULL)
  852. {
  853. UpdateTaskbarList();
  854. }
  855. }
  856. }
  857. //---------------------------------------------------------------------------
  858. void __fastcall TTerminalManager::ReleaseTaskbarList()
  859. {
  860. if (FTaskbarList != NULL)
  861. {
  862. FTaskbarList->Release();
  863. }
  864. }
  865. //---------------------------------------------------------------------------
  866. void __fastcall TTerminalManager::UpdateTaskbarList()
  867. {
  868. ScpExplorer->UpdateTaskbarList(FTaskbarList);
  869. }
  870. //---------------------------------------------------------------------------
  871. void __fastcall TTerminalManager::DeleteLocalFile(const UnicodeString FileName, bool Alternative)
  872. {
  873. RecursiveDeleteFileChecked(FileName, (WinConfiguration->DeleteToRecycleBin != Alternative));
  874. }
  875. //---------------------------------------------------------------------------
  876. void __fastcall TTerminalManager::TerminalQueryUser(TObject * Sender,
  877. const UnicodeString Query, TStrings * MoreMessages, unsigned int Answers,
  878. const TQueryParams * Params, unsigned int & Answer, TQueryType Type, void * /*Arg*/)
  879. {
  880. UnicodeString HelpKeyword;
  881. TMessageParams MessageParams(Params);
  882. UnicodeString AQuery = Query;
  883. if (Params != NULL)
  884. {
  885. HelpKeyword = Params->HelpKeyword;
  886. if (FLAGSET(Params->Params, qpFatalAbort))
  887. {
  888. AQuery = FMTLOAD(WARN_FATAL_ERROR, (AQuery));
  889. if (!MessageParams.TimerMessage.IsEmpty())
  890. {
  891. MessageParams.TimerMessage = FMTLOAD(WARN_FATAL_ERROR, (MessageParams.TimerMessage));
  892. }
  893. }
  894. }
  895. if (ScpExplorer)
  896. {
  897. Answer = ScpExplorer->MoreMessageDialog(AQuery, MoreMessages, Type, Answers,
  898. HelpKeyword, &MessageParams, dynamic_cast<TTerminal *>(Sender));
  899. }
  900. else
  901. {
  902. Answer = MoreMessageDialog(AQuery, MoreMessages, Type, Answers, HelpKeyword,
  903. &MessageParams);
  904. }
  905. }
  906. //---------------------------------------------------------------------------
  907. void __fastcall TTerminalManager::AuthenticateFormCancel(TObject * Sender)
  908. {
  909. TAuthenticateForm * Form = dynamic_cast<TAuthenticateForm *>(Sender);
  910. DebugAssert(Form != NULL);
  911. TManagedTerminal * ManagedTerminal = dynamic_cast<TManagedTerminal *>(Form->Terminal);
  912. // will be null e.g. for background transfers
  913. if (ManagedTerminal != NULL)
  914. {
  915. TTerminalThread * TerminalThread = ManagedTerminal->TerminalThread;
  916. // can be NULL for reconnects from transfers
  917. if ((TerminalThread != NULL) && !TerminalThread->Cancelling)
  918. {
  919. Form->Log(LoadStr(AUTH_CANCELLING));
  920. TerminalThread->Cancel();
  921. }
  922. }
  923. FAuthenticationCancelled = true;
  924. }
  925. //---------------------------------------------------------------------------
  926. TAuthenticateForm * __fastcall TTerminalManager::MakeAuthenticateForm(
  927. TTerminal * Terminal)
  928. {
  929. TAuthenticateForm * Dialog = SafeFormCreate<TAuthenticateForm>();
  930. Dialog->Init(Terminal);
  931. DebugAssert(Dialog->OnCancel == NULL);
  932. Dialog->OnCancel = AuthenticateFormCancel;
  933. return Dialog;
  934. }
  935. //---------------------------------------------------------------------------
  936. void __fastcall TTerminalManager::FileNameInputDialogInitializeRenameBaseName(
  937. TObject * /*Sender*/, TInputDialogData * Data)
  938. {
  939. EditSelectBaseName(Data->Edit->Handle);
  940. }
  941. //---------------------------------------------------------------------------
  942. void __fastcall TTerminalManager::TerminalPromptUser(
  943. TTerminal * Terminal, TPromptKind Kind, UnicodeString Name, UnicodeString Instructions,
  944. TStrings * Prompts, TStrings * Results, bool & Result, void * /*Arg*/)
  945. {
  946. if (((Kind == pkPrompt) || (Kind == pkFileName)) && (FAuthenticateForm == NULL) &&
  947. (Terminal->Status != ssOpening))
  948. {
  949. DebugAssert(Instructions.IsEmpty());
  950. DebugAssert(Prompts->Count == 1);
  951. DebugAssert(FLAGSET(int(Prompts->Objects[0]), pupEcho));
  952. UnicodeString AResult = Results->Strings[0];
  953. TInputDialogInitialize InputDialogInitialize = NULL;
  954. if ((Kind == pkFileName) && !WinConfiguration->RenameWholeName)
  955. {
  956. InputDialogInitialize = FileNameInputDialogInitializeRenameBaseName;
  957. }
  958. Result = InputDialog(Name, Prompts->Strings[0], AResult, L"", NULL, false, InputDialogInitialize);
  959. if (Result)
  960. {
  961. Results->Strings[0] = AResult;
  962. }
  963. }
  964. else
  965. {
  966. TAuthenticateForm * AuthenticateForm = FAuthenticateForm;
  967. if (AuthenticateForm == NULL)
  968. {
  969. AuthenticateForm = MakeAuthenticateForm(Terminal);
  970. }
  971. try
  972. {
  973. Result = AuthenticateForm->PromptUser(Kind, Name, Instructions, Prompts, Results,
  974. (FAuthenticateForm != NULL), Terminal->StoredCredentialsTried);
  975. }
  976. __finally
  977. {
  978. if (FAuthenticateForm == NULL)
  979. {
  980. delete AuthenticateForm;
  981. }
  982. }
  983. }
  984. }
  985. //---------------------------------------------------------------------------
  986. void __fastcall TTerminalManager::TerminalDisplayBanner(
  987. TTerminal * Terminal, UnicodeString SessionName,
  988. const UnicodeString & Banner, bool & NeverShowAgain, int Options, unsigned int & Params)
  989. {
  990. DebugAssert(FAuthenticateForm != NULL);
  991. TAuthenticateForm * AuthenticateForm = FAuthenticateForm;
  992. if (AuthenticateForm == NULL)
  993. {
  994. AuthenticateForm = MakeAuthenticateForm(Terminal);
  995. }
  996. try
  997. {
  998. AuthenticateForm->Banner(Banner, NeverShowAgain, Options, Params);
  999. }
  1000. __finally
  1001. {
  1002. if (FAuthenticateForm == NULL)
  1003. {
  1004. delete AuthenticateForm;
  1005. }
  1006. }
  1007. }
  1008. //---------------------------------------------------------------------------
  1009. void __fastcall TTerminalManager::TerminalShowExtendedException(
  1010. TTerminal * Terminal, Exception * E, void * /*Arg*/)
  1011. {
  1012. if (ScpExplorer)
  1013. {
  1014. ScpExplorer->ShowExtendedException(Terminal, E);
  1015. }
  1016. else
  1017. {
  1018. ShowExtendedExceptionEx(Terminal, E);
  1019. }
  1020. }
  1021. //---------------------------------------------------------------------------
  1022. static TDateTime DirectoryReadingProgressDelay(0, 0, 1, 500);
  1023. //---------------------------------------------------------------------------
  1024. void __fastcall TTerminalManager::TerminalReadDirectoryProgress(
  1025. TObject * /*Sender*/, int Progress, int ResolvedLinks, bool & Cancel)
  1026. {
  1027. if (Progress == 0)
  1028. {
  1029. if (ScpExplorer != NULL)
  1030. {
  1031. // See also TCustomScpExplorerForm::RemoteDirViewBusy
  1032. ScpExplorer->LockWindow();
  1033. }
  1034. FDirectoryReadingStart = Now();
  1035. if (!FProgressTitle.IsEmpty() || !FForegroundProgressTitle.IsEmpty())
  1036. {
  1037. FProgressTitle = L"";
  1038. FForegroundProgressTitle = L"";
  1039. UpdateAppTitle();
  1040. }
  1041. // Reset "was ESC ever pressed?" state
  1042. GetAsyncKeyState(VK_ESCAPE);
  1043. }
  1044. else if (Progress < 0)
  1045. {
  1046. if (Progress == -2)
  1047. {
  1048. // cancelled
  1049. if (ScpExplorer != NULL)
  1050. {
  1051. ScpExplorer->ReadDirectoryCancelled();
  1052. }
  1053. }
  1054. else
  1055. {
  1056. if (ScpExplorer != NULL)
  1057. {
  1058. ScpExplorer->UnlockWindow();
  1059. }
  1060. FProgressTitle = L"";
  1061. FForegroundProgressTitle = L"";
  1062. UpdateAppTitle();
  1063. }
  1064. }
  1065. else
  1066. {
  1067. // If the least significant bit is set,
  1068. // the key was pressed after the previous call to GetAsyncKeyState.
  1069. int KeyState = GetAsyncKeyState(VK_ESCAPE);
  1070. if (FLAGSET(KeyState, 0x01))
  1071. {
  1072. Cancel = true;
  1073. }
  1074. if ((Now() - FDirectoryReadingStart) >= DirectoryReadingProgressDelay)
  1075. {
  1076. // 4 is arbitrary number
  1077. FForegroundProgressTitle =
  1078. FMTLOAD(ResolvedLinks >= 4 ? DIRECTORY_READING_AND_RESOLVING_PROGRESS : DIRECTORY_READING_PROGRESS,
  1079. (Progress));
  1080. UpdateAppTitle();
  1081. }
  1082. }
  1083. }
  1084. //---------------------------------------------------------------------------
  1085. void __fastcall TTerminalManager::TerminalCustomCommand(
  1086. TTerminal * /*Terminal*/, const UnicodeString & Command, bool & Handled)
  1087. {
  1088. // Implementation has to be thread-safe
  1089. Handled = CopyCommandToClipboard(Command);
  1090. }
  1091. //---------------------------------------------------------------------------
  1092. void __fastcall TTerminalManager::AuthenticatingDone()
  1093. {
  1094. FAuthenticating--;
  1095. if (FAuthenticating == 0)
  1096. {
  1097. BusyEnd(FBusyToken);
  1098. FBusyToken = NULL;
  1099. }
  1100. if (!FKeepAuthenticateForm)
  1101. {
  1102. CloseAutheticateForm();
  1103. }
  1104. }
  1105. //---------------------------------------------------------------------------
  1106. void __fastcall TTerminalManager::TerminalInformation(
  1107. TTerminal * Terminal, const UnicodeString & Str, bool /*Status*/, int Phase)
  1108. {
  1109. if (Phase == 1)
  1110. {
  1111. if (FAuthenticating == 0)
  1112. {
  1113. FBusyToken = BusyStart();
  1114. }
  1115. FAuthenticating++;
  1116. }
  1117. else if (Phase == 0)
  1118. {
  1119. DebugAssert(FAuthenticating > 0);
  1120. AuthenticatingDone();
  1121. }
  1122. else
  1123. {
  1124. if (FAuthenticating > 0)
  1125. {
  1126. bool ShowPending = false;
  1127. if (FAuthenticateForm == NULL)
  1128. {
  1129. FAuthenticateForm = MakeAuthenticateForm(Terminal);
  1130. ShowPending = true;
  1131. }
  1132. FAuthenticateForm->Log(Str);
  1133. if (ShowPending)
  1134. {
  1135. FAuthenticateForm->ShowAsModal();
  1136. }
  1137. }
  1138. }
  1139. }
  1140. //---------------------------------------------------------------------------
  1141. void __fastcall TTerminalManager::OperationFinished(::TFileOperation Operation,
  1142. TOperationSide Side, bool Temp, const UnicodeString & FileName, bool Success,
  1143. TOnceDoneOperation & OnceDoneOperation)
  1144. {
  1145. DebugAssert(ScpExplorer);
  1146. ScpExplorer->OperationFinished(Operation, Side, Temp, FileName, Success,
  1147. OnceDoneOperation);
  1148. }
  1149. //---------------------------------------------------------------------------
  1150. void __fastcall TTerminalManager::OperationProgress(
  1151. TFileOperationProgressType & ProgressData)
  1152. {
  1153. UpdateAppTitle();
  1154. DebugAssert(ScpExplorer);
  1155. ScpExplorer->OperationProgress(ProgressData);
  1156. }
  1157. //---------------------------------------------------------------------------
  1158. void __fastcall TTerminalManager::QueueEvent(TTerminalQueue * Queue, TQueueEvent Event)
  1159. {
  1160. TGuard Guard(FQueueSection);
  1161. FQueueEvents.push_back(std::make_pair(Queue, Event));
  1162. }
  1163. //---------------------------------------------------------------------------
  1164. void __fastcall TTerminalManager::DoConfigurationChange()
  1165. {
  1166. DebugAssert(Configuration);
  1167. DebugAssert(Configuration == WinConfiguration);
  1168. TTerminalQueue * Queue;
  1169. for (int Index = 0; Index < Count; Index++)
  1170. {
  1171. DebugAssert(Terminals[Index]->Log);
  1172. Terminals[Index]->Log->ReflectSettings();
  1173. Terminals[Index]->ActionLog->ReflectSettings();
  1174. Queue = reinterpret_cast<TTerminalQueue *>(FQueues->Items[Index]);
  1175. SetQueueConfiguration(Queue);
  1176. }
  1177. if (ScpExplorer)
  1178. {
  1179. ScpExplorer->ConfigurationChanged();
  1180. }
  1181. }
  1182. //---------------------------------------------------------------------------
  1183. void __fastcall TTerminalManager::ConfigurationChange(TObject * /*Sender*/)
  1184. {
  1185. if (FMainThread == GetCurrentThreadId())
  1186. {
  1187. DoConfigurationChange();
  1188. }
  1189. else
  1190. {
  1191. TGuard Guard(FChangeSection.get());
  1192. FPendingConfigurationChange++;
  1193. }
  1194. }
  1195. //---------------------------------------------------------------------------
  1196. void __fastcall TTerminalManager::TerminalReady()
  1197. {
  1198. ScpExplorer->Terminal = ActiveTerminal;
  1199. ScpExplorer->Queue = ActiveQueue;
  1200. ScpExplorer->TerminalReady();
  1201. }
  1202. //---------------------------------------------------------------------------
  1203. TStrings * __fastcall TTerminalManager::GetTerminalList()
  1204. {
  1205. FTerminalList->Clear();
  1206. for (int i = 0; i < Count; i++)
  1207. {
  1208. TTerminal * Terminal = Terminals[i];
  1209. UnicodeString Name = GetTerminalTitle(Terminal, true);
  1210. FTerminalList->AddObject(Name, Terminal);
  1211. }
  1212. return FTerminalList;
  1213. }
  1214. //---------------------------------------------------------------------------
  1215. int __fastcall TTerminalManager::GetActiveTerminalIndex()
  1216. {
  1217. return ActiveTerminal ? IndexOf(ActiveTerminal) : -1;
  1218. }
  1219. //---------------------------------------------------------------------------
  1220. void __fastcall TTerminalManager::SetActiveTerminalIndex(int value)
  1221. {
  1222. ActiveTerminal = Terminals[value];
  1223. }
  1224. //---------------------------------------------------------------------------
  1225. UnicodeString __fastcall TTerminalManager::GetTerminalShortPath(TTerminal * Terminal)
  1226. {
  1227. UnicodeString Result = UnixExtractFileName(Terminal->CurrentDirectory);
  1228. if (Result.IsEmpty())
  1229. {
  1230. Result = Terminal->CurrentDirectory;
  1231. }
  1232. return Result;
  1233. }
  1234. //---------------------------------------------------------------------------
  1235. UnicodeString __fastcall TTerminalManager::GetTerminalTitle(TTerminal * Terminal, bool Unique)
  1236. {
  1237. UnicodeString Result = Terminal->SessionData->SessionName;
  1238. if (Unique)
  1239. {
  1240. int Index = IndexOf(Terminal);
  1241. // not for background transfer sessions
  1242. if (Index >= 0)
  1243. {
  1244. for (int Index2 = 0; Index2 < Count; Index2++)
  1245. {
  1246. UnicodeString Name = Terminals[Index2]->SessionData->SessionName;
  1247. if ((Terminals[Index2] != Terminal) &&
  1248. SameText(Name, Result))
  1249. {
  1250. UnicodeString Path = GetTerminalShortPath(Terminal);
  1251. if (!Path.IsEmpty())
  1252. {
  1253. Result = FORMAT(L"%s (%s)", (Result, Path));
  1254. }
  1255. break;
  1256. }
  1257. }
  1258. }
  1259. }
  1260. return Result;
  1261. }
  1262. //---------------------------------------------------------------------------
  1263. UnicodeString __fastcall TTerminalManager::GetActiveTerminalTitle(bool Unique)
  1264. {
  1265. UnicodeString Result;
  1266. if (ActiveTerminal != NULL)
  1267. {
  1268. Result = GetTerminalTitle(ActiveTerminal, Unique);
  1269. }
  1270. return Result;
  1271. }
  1272. //---------------------------------------------------------------------------
  1273. TTerminalQueue * __fastcall TTerminalManager::GetActiveQueue()
  1274. {
  1275. TTerminalQueue * Result = NULL;
  1276. if (ActiveTerminal != NULL)
  1277. {
  1278. Result = reinterpret_cast<TTerminalQueue *>(FQueues->Items[ActiveTerminalIndex]);
  1279. }
  1280. return Result;
  1281. }
  1282. //---------------------------------------------------------------------------
  1283. void __fastcall TTerminalManager::CycleTerminals(bool Forward)
  1284. {
  1285. if (Count > 0)
  1286. {
  1287. int Index = ActiveTerminalIndex;
  1288. Index += Forward ? 1 : -1;
  1289. if (Index < 0)
  1290. {
  1291. Index = Count-1;
  1292. }
  1293. else if (Index >= Count)
  1294. {
  1295. Index = 0;
  1296. }
  1297. ActiveTerminalIndex = Index;
  1298. }
  1299. }
  1300. //---------------------------------------------------------------------------
  1301. bool __fastcall TTerminalManager::CanOpenInPutty()
  1302. {
  1303. return (ActiveTerminal != NULL) && !GUIConfiguration->PuttyPath.Trim().IsEmpty();
  1304. }
  1305. //---------------------------------------------------------------------------
  1306. void __fastcall TTerminalManager::UpdateSessionCredentials(TSessionData * Data)
  1307. {
  1308. Data->UserName = ActiveTerminal->UserName;
  1309. Data->Password = ActiveTerminal->Password;
  1310. }
  1311. //---------------------------------------------------------------------------
  1312. void __fastcall TTerminalManager::OpenInPutty()
  1313. {
  1314. Configuration->Usage->Inc(L"OpenInPutty");
  1315. TSessionData * Data = NULL;
  1316. try
  1317. {
  1318. // Is NULL on the first session when called from ConnectActiveTerminal()
  1319. // due to WinConfiguration->AutoOpenInPutty
  1320. if (ScpExplorer != NULL)
  1321. {
  1322. Data = ScpExplorer->CloneCurrentSessionData();
  1323. }
  1324. else
  1325. {
  1326. Data = new TSessionData(L"");
  1327. DebugAssert(ActiveTerminal != NULL);
  1328. Data->Assign(ActiveTerminal->SessionData);
  1329. UpdateSessionCredentials(Data);
  1330. }
  1331. // putty does not support resolving environment variables in session settings
  1332. Data->ExpandEnvironmentVariables();
  1333. if (ActiveTerminal->TunnelLocalPortNumber != 0)
  1334. {
  1335. Data->ConfigureTunnel(ActiveTerminal->TunnelLocalPortNumber);
  1336. }
  1337. OpenSessionInPutty(GUIConfiguration->PuttyPath, Data);
  1338. }
  1339. __finally
  1340. {
  1341. delete Data;
  1342. }
  1343. }
  1344. //---------------------------------------------------------------------------
  1345. void __fastcall TTerminalManager::NewSession(bool /*FromSite*/, const UnicodeString & SessionUrl, bool ReloadSessions, TForm * LinkedForm)
  1346. {
  1347. if (ReloadSessions)
  1348. {
  1349. StoredSessions->Reload();
  1350. }
  1351. UnicodeString DownloadFile; // unused
  1352. std::unique_ptr<TObjectList> DataList(new TObjectList());
  1353. GetLoginData(SessionUrl, NULL, DataList.get(), DownloadFile, true, LinkedForm);
  1354. if (DataList->Count > 0)
  1355. {
  1356. ActiveTerminal = NewTerminals(DataList.get());
  1357. }
  1358. }
  1359. //---------------------------------------------------------------------------
  1360. void __fastcall TTerminalManager::Idle(bool SkipCurrentTerminal)
  1361. {
  1362. if (FPendingConfigurationChange > 0) // optimization
  1363. {
  1364. bool Changed = false;
  1365. {
  1366. TGuard Guard(FChangeSection.get());
  1367. if (DebugAlwaysTrue(FPendingConfigurationChange > 0))
  1368. {
  1369. FPendingConfigurationChange--;
  1370. Changed = true;
  1371. }
  1372. }
  1373. if (Changed)
  1374. {
  1375. DoConfigurationChange();
  1376. }
  1377. }
  1378. for (int Index = 0; Index < Count; Index++)
  1379. {
  1380. TTerminal * Terminal = Terminals[Index];
  1381. try
  1382. {
  1383. if (!SkipCurrentTerminal || (Terminal != ActiveTerminal))
  1384. {
  1385. TManagedTerminal * ManagedTerminal = dynamic_cast<TManagedTerminal *>(Terminal);
  1386. DebugAssert(ManagedTerminal != NULL);
  1387. // make sure Idle is called on the thread that runs the terminal
  1388. if (ManagedTerminal->TerminalThread != NULL)
  1389. {
  1390. ManagedTerminal->TerminalThread->Idle();
  1391. }
  1392. else
  1393. {
  1394. if (Terminal->Active)
  1395. {
  1396. Terminal->Idle();
  1397. }
  1398. }
  1399. if (Terminal->Active)
  1400. {
  1401. DebugAssert(Index < FQueues->Count);
  1402. if (Index < FQueues->Count)
  1403. {
  1404. reinterpret_cast<TTerminalQueue *>(FQueues->Items[Index])->Idle();
  1405. }
  1406. }
  1407. }
  1408. }
  1409. catch(Exception & E)
  1410. {
  1411. if (Terminal == ActiveTerminal)
  1412. {
  1413. // throw further, so that the exception is handled in proper place
  1414. // (particularly in broken-transfer reconnect handler, bug 72)
  1415. throw;
  1416. }
  1417. else
  1418. {
  1419. // we may not have inactive terminal, unless there is a explorer,
  1420. // also Idle is called from explorer anyway
  1421. DebugAssert(ScpExplorer != NULL);
  1422. if (ScpExplorer != NULL)
  1423. {
  1424. ScpExplorer->InactiveTerminalException(Terminal, &E);
  1425. }
  1426. if (!Terminal->Active)
  1427. {
  1428. // if session is lost, save the error message and rethrow it
  1429. // once the terminal gets activated
  1430. FTerminationMessages->Strings[Index] = E.Message;
  1431. }
  1432. }
  1433. }
  1434. }
  1435. TTerminalQueue * QueueWithEvent;
  1436. TQueueEvent QueueEvent;
  1437. do
  1438. {
  1439. QueueWithEvent = NULL;
  1440. {
  1441. TGuard Guard(FQueueSection);
  1442. if (!FQueueEvents.empty())
  1443. {
  1444. QueueWithEvent = FQueueEvents[0].first;
  1445. QueueEvent = FQueueEvents[0].second;
  1446. FQueueEvents.erase(FQueueEvents.begin());
  1447. }
  1448. }
  1449. if (QueueWithEvent != NULL)
  1450. {
  1451. int Index = FQueues->IndexOf(QueueWithEvent);
  1452. // the session may not exist anymore
  1453. if (Index >= 0)
  1454. {
  1455. TTerminal * Terminal = Terminals[Index];
  1456. // we can hardly have a queue event without explorer
  1457. DebugAssert(ScpExplorer != NULL);
  1458. if (ScpExplorer != NULL)
  1459. {
  1460. ScpExplorer->QueueEvent(Terminal, QueueWithEvent, QueueEvent);
  1461. }
  1462. }
  1463. }
  1464. }
  1465. while (QueueWithEvent != NULL);
  1466. }
  1467. //---------------------------------------------------------------------------
  1468. void __fastcall TTerminalManager::MasterPasswordPrompt()
  1469. {
  1470. if (GetCurrentThreadId() == MainThreadID)
  1471. {
  1472. if (!DoMasterPasswordDialog())
  1473. {
  1474. Abort();
  1475. }
  1476. }
  1477. else
  1478. {
  1479. // this can happen only when we keep cancelling all master password prompts
  1480. // as long as the sessing finally connects (session password has to be
  1481. // explictly typed in), and background transfer is started
  1482. Abort();
  1483. }
  1484. }
  1485. //---------------------------------------------------------------------------
  1486. void __fastcall TTerminalManager::Move(TTerminal * Source, TTerminal * Target)
  1487. {
  1488. int SourceIndex = IndexOf(Source);
  1489. int TargetIndex = IndexOf(Target);
  1490. TTerminalList::Move(SourceIndex, TargetIndex);
  1491. FQueues->Move(SourceIndex, TargetIndex);
  1492. DoTerminalListChanged();
  1493. // when there are indexed sessions with the same name,
  1494. // the index may change when reordering the sessions
  1495. UpdateAppTitle();
  1496. }
  1497. //---------------------------------------------------------------------------
  1498. void __fastcall TTerminalManager::DoTerminalListChanged()
  1499. {
  1500. if (OnTerminalListChanged)
  1501. {
  1502. OnTerminalListChanged(this);
  1503. }
  1504. }
  1505. //---------------------------------------------------------------------------
  1506. void __fastcall TTerminalManager::SaveWorkspace(TList * DataList)
  1507. {
  1508. for (int Index = 0; Index < Count; Index++)
  1509. {
  1510. TManagedTerminal * ManagedTerminal = dynamic_cast<TManagedTerminal *>(Terminals[Index]);
  1511. TSessionData * Data = StoredSessions->SaveWorkspaceData(ManagedTerminal->StateData);
  1512. DataList->Add(Data);
  1513. Data->Name = IntToHex(Index, 4);
  1514. }
  1515. }
  1516. //---------------------------------------------------------------------------
  1517. TTerminal * __fastcall TTerminalManager::FindActiveTerminalForSite(TSessionData * Data)
  1518. {
  1519. TTerminal * Result = NULL;
  1520. for (int Index = 0; (Result == NULL) && (Index < Count); Index++)
  1521. {
  1522. TTerminal * Terminal = Terminals[Index];
  1523. if (Terminal->Active &&
  1524. Terminal->SessionData->IsSameSite(Data))
  1525. {
  1526. Result = Terminal;
  1527. }
  1528. }
  1529. return Result;
  1530. }
  1531. //---------------------------------------------------------------------------
  1532. TTerminalQueue * __fastcall TTerminalManager::FindQueueForTerminal(TTerminal * Terminal)
  1533. {
  1534. int Index = IndexOf(Terminal);
  1535. return reinterpret_cast<TTerminalQueue *>(FQueues->Items[Index]);
  1536. }
  1537. //---------------------------------------------------------------------------
  1538. TRemoteFile * __fastcall TTerminalManager::CheckRights(
  1539. TTerminal * Terminal, const UnicodeString & EntryType, const UnicodeString & FileName, bool & WrongRights)
  1540. {
  1541. std::unique_ptr<TRemoteFile> FileOwner;
  1542. TRemoteFile * File;
  1543. try
  1544. {
  1545. Terminal->LogEvent(FORMAT(L"Checking %s \"%s\"...", (LowerCase(EntryType), FileName)));
  1546. Terminal->ReadFile(FileName, File);
  1547. FileOwner.reset(File);
  1548. int ForbiddenRights = TRights::rfGroupWrite | TRights::rfOtherWrite;
  1549. if ((File->Rights->Number & ForbiddenRights) != 0)
  1550. {
  1551. Terminal->LogEvent(FORMAT(L"%s \"%s\" exists, but has incorrect permissions %s.", (EntryType, FileName, File->Rights->Octal)));
  1552. WrongRights = true;
  1553. }
  1554. else
  1555. {
  1556. Terminal->LogEvent(FORMAT(L"%s \"%s\" exists and has correct permissions %s.", (EntryType, FileName, File->Rights->Octal)));
  1557. }
  1558. }
  1559. catch (Exception & E)
  1560. {
  1561. }
  1562. return FileOwner.release();
  1563. }
  1564. //---------------------------------------------------------------------------
  1565. bool __fastcall TTerminalManager::UploadPublicKey(
  1566. TTerminal * Terminal, TSessionData * Data, UnicodeString & FileName)
  1567. {
  1568. std::unique_ptr<TOpenDialog> OpenDialog(new TOpenDialog(Application));
  1569. OpenDialog->Title = LoadStr(LOGIN_PUBLIC_KEY_TITLE);
  1570. OpenDialog->Filter = LoadStr(LOGIN_PUBLIC_KEY_FILTER);
  1571. OpenDialog->DefaultExt = PuttyKeyExt;
  1572. OpenDialog->FileName = FileName;
  1573. bool Result = OpenDialog->Execute();
  1574. if (Result)
  1575. {
  1576. Configuration->Usage->Inc(L"PublicKeyInstallation");
  1577. FileName = OpenDialog->FileName;
  1578. bool AutoReadDirectory;
  1579. bool ExceptionOnFail;
  1580. UnicodeString TemporaryDir;
  1581. bool WrongRights = false;
  1582. const UnicodeString SshFolder = L".ssh";
  1583. const UnicodeString AuthorizedKeysFile = L"authorized_keys";
  1584. UnicodeString AuthorizedKeysFilePath = FORMAT(L"%s/%s", (SshFolder, AuthorizedKeysFile));
  1585. VerifyAndConvertKey(FileName, ssh2only, false);
  1586. UnicodeString Comment;
  1587. UnicodeString Line = GetPublicKeyLine(FileName, Comment);
  1588. bool AdHocTerminal = (Terminal == NULL);
  1589. std::unique_ptr<TTerminal> TerminalOwner;
  1590. if (AdHocTerminal)
  1591. {
  1592. DebugAssert(Data != NULL);
  1593. TAutoFlag KeepAuthenticateFormFlag(FKeepAuthenticateForm);
  1594. try
  1595. {
  1596. TerminalOwner.reset(CreateTerminal(Data));
  1597. Terminal = TerminalOwner.get();
  1598. SetupTerminal(Terminal);
  1599. Terminal->OnProgress = NULL;
  1600. Terminal->OnFinished = NULL;
  1601. DoConnectTerminal(Terminal, false, true);
  1602. }
  1603. catch (Exception & E)
  1604. {
  1605. CloseAutheticateForm();
  1606. throw;
  1607. }
  1608. }
  1609. AutoReadDirectory = Terminal->AutoReadDirectory;
  1610. ExceptionOnFail = Terminal->ExceptionOnFail;
  1611. try
  1612. {
  1613. Terminal->AutoReadDirectory = false;
  1614. Terminal->ExceptionOnFail = true;
  1615. UnicodeString SshImplementation = Terminal->GetSessionInfo().SshImplementation;
  1616. UnicodeString NotOpenSSHMessage = FMTLOAD(LOGIN_NOT_OPENSSH, (SshImplementation));
  1617. if (IsOpenSSH(SshImplementation) ||
  1618. (MessageDialog(NotOpenSSHMessage, qtConfirmation, qaOK | qaCancel, HELP_LOGIN_AUTHORIZED_KEYS) == qaOK))
  1619. {
  1620. Terminal->Log->AddSeparator();
  1621. Terminal->LogEvent(FORMAT(L"Adding public key line to \"%s\" file:\n%s", (AuthorizedKeysFilePath, Line)));
  1622. // Ad-hoc terminal
  1623. if (FAuthenticateForm != NULL)
  1624. {
  1625. FAuthenticateForm->Log(FMTLOAD(LOGIN_PUBLIC_KEY_UPLOAD, (Comment)));
  1626. }
  1627. UnicodeString SshFolderAbsolutePath = UnixIncludeTrailingBackslash(Terminal->GetHomeDirectory()) + SshFolder;
  1628. std::unique_ptr<TRemoteFile> SshFolderFile(CheckRights(Terminal, L"Folder", SshFolderAbsolutePath, WrongRights));
  1629. if (SshFolderFile.get() == NULL)
  1630. {
  1631. TRights SshFolderRights;
  1632. SshFolderRights.Number = TRights::rfUserRead | TRights::rfUserWrite | TRights::rfUserExec;
  1633. TRemoteProperties SshFolderProperties;
  1634. SshFolderProperties.Rights = SshFolderRights;
  1635. SshFolderProperties.Valid = TValidProperties() << vpRights;
  1636. Terminal->LogEvent(FORMAT(L"Trying to create \"%s\" folder with permissions %s...", (SshFolder, SshFolderRights.Octal)));
  1637. Terminal->CreateDirectory(SshFolderAbsolutePath, &SshFolderProperties);
  1638. }
  1639. TemporaryDir = ExcludeTrailingBackslash(WinConfiguration->TemporaryDir());
  1640. if (!ForceDirectories(ApiPath(TemporaryDir)))
  1641. {
  1642. throw EOSExtException(FMTLOAD(CREATE_TEMP_DIR_ERROR, (TemporaryDir)));
  1643. }
  1644. UnicodeString TemporaryAuthorizedKeysFile = IncludeTrailingBackslash(TemporaryDir) + AuthorizedKeysFile;
  1645. UnicodeString AuthorizedKeysFileAbsolutePath = UnixIncludeTrailingBackslash(SshFolderAbsolutePath) + AuthorizedKeysFile;
  1646. bool Updated = true;
  1647. TCopyParamType CopyParam; // Use factory defaults
  1648. CopyParam.ResumeSupport = rsOff; // not to break the permissions
  1649. CopyParam.PreserveTime = false; // not needed
  1650. UnicodeString AuthorizedKeys;
  1651. std::unique_ptr<TRemoteFile> AuthorizedKeysFileFile(CheckRights(Terminal, L"File", AuthorizedKeysFileAbsolutePath, WrongRights));
  1652. if (AuthorizedKeysFileFile.get() != NULL)
  1653. {
  1654. AuthorizedKeysFileFile->FullFileName = AuthorizedKeysFileAbsolutePath;
  1655. std::unique_ptr<TStrings> Files(new TStringList());
  1656. Files->AddObject(AuthorizedKeysFileAbsolutePath, AuthorizedKeysFileFile.get());
  1657. Terminal->LogEvent(FORMAT(L"Downloading current \"%s\" file...", (AuthorizedKeysFile)));
  1658. Terminal->CopyToLocal(Files.get(), TemporaryDir, &CopyParam, cpNoConfirmation, NULL);
  1659. // Overload with Encoding parameter work incorrectly, when used on a file without BOM
  1660. AuthorizedKeys = TFile::ReadAllText(TemporaryAuthorizedKeysFile);
  1661. std::unique_ptr<TStrings> AuthorizedKeysLines(TextToStringList(AuthorizedKeys));
  1662. int P = Line.Pos(L" ");
  1663. if (DebugAlwaysTrue(P > 0))
  1664. {
  1665. P = PosEx(L" ", Line, P + 1);
  1666. }
  1667. UnicodeString Prefix = Line.SubString(1, P); // including the space
  1668. for (int Index = 0; Index < AuthorizedKeysLines->Count; Index++)
  1669. {
  1670. if (StartsStr(Prefix, AuthorizedKeysLines->Strings[Index]))
  1671. {
  1672. Terminal->LogEvent(FORMAT(L"\"%s\" file already contains public key line:\n%s", (AuthorizedKeysFile, AuthorizedKeysLines->Strings[Index])));
  1673. Updated = false;
  1674. }
  1675. }
  1676. if (Updated)
  1677. {
  1678. Terminal->LogEvent(FORMAT(L"\"%s\" file does not contain the public key line yet.", (AuthorizedKeysFile)));
  1679. if (!EndsStr(L"\n", AuthorizedKeys))
  1680. {
  1681. Terminal->LogEvent(FORMAT(L"Adding missing trailing new line to \"%s\" file...", (AuthorizedKeysFile)));
  1682. AuthorizedKeys += L"\n";
  1683. }
  1684. }
  1685. }
  1686. else
  1687. {
  1688. Terminal->LogEvent(FORMAT(L"Creating new \"%s\" file...", (AuthorizedKeysFile)));
  1689. CopyParam.PreserveRights = true;
  1690. CopyParam.Rights.Number = TRights::rfUserRead | TRights::rfUserWrite;
  1691. }
  1692. if (Updated)
  1693. {
  1694. AuthorizedKeys += Line + L"\n";
  1695. // Overload without Encoding parameter uses TEncoding::UTF8, but does not write BOM, what we want
  1696. TFile::WriteAllText(TemporaryAuthorizedKeysFile, AuthorizedKeys);
  1697. std::unique_ptr<TStrings> Files(new TStringList());
  1698. Files->Add(TemporaryAuthorizedKeysFile);
  1699. Terminal->LogEvent(FORMAT(L"Uploading updated \"%s\" file...", (AuthorizedKeysFile)));
  1700. Terminal->CopyToRemote(Files.get(), SshFolderAbsolutePath, &CopyParam, cpNoConfirmation, NULL);
  1701. }
  1702. }
  1703. }
  1704. __finally
  1705. {
  1706. Terminal->AutoReadDirectory = AutoReadDirectory;
  1707. Terminal->ExceptionOnFail = ExceptionOnFail;
  1708. if (!TemporaryDir.IsEmpty())
  1709. {
  1710. RecursiveDeleteFile(ExcludeTrailingBackslash(TemporaryDir), false);
  1711. }
  1712. CloseAutheticateForm(); // When uploading from Login dialog
  1713. }
  1714. Terminal->LogEvent(L"Public key installation done.");
  1715. if (AdHocTerminal)
  1716. {
  1717. TerminalOwner.reset(NULL);
  1718. }
  1719. else
  1720. {
  1721. Terminal->Log->AddSeparator();
  1722. }
  1723. UnicodeString Message = FMTLOAD(LOGIN_PUBLIC_KEY_UPLOADED, (Comment));
  1724. if (WrongRights)
  1725. {
  1726. Message += L"\n\n" + FMTLOAD(LOGIN_PUBLIC_KEY_PERMISSIONS, (AuthorizedKeysFilePath));
  1727. }
  1728. MessageDialog(Message, qtInformation, qaOK, HELP_LOGIN_AUTHORIZED_KEYS);
  1729. }
  1730. return Result;
  1731. }