TerminalManager.cpp 58 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845
  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. UnicodeString Path = ScpExplorer->PathForCaption();
  677. if (!Path.IsEmpty())
  678. {
  679. NewTitle = Path + L" - " + NewTitle;
  680. }
  681. }
  682. // Not updating MainForm here, as for all other possible main forms, this code is actually not what we want.
  683. // And they all update their title on their own (some using GetAppProgressTitle()).
  684. ScpExplorer->Caption = NewTitle;
  685. ScpExplorer->ApplicationTitleChanged();
  686. }
  687. }
  688. //---------------------------------------------------------------------------
  689. void __fastcall TTerminalManager::SaveTerminal(TTerminal * Terminal)
  690. {
  691. TSessionData * Data = StoredSessions->FindSame(Terminal->SessionData);
  692. if (Data != NULL)
  693. {
  694. TManagedTerminal * ManagedTerminal = dynamic_cast<TManagedTerminal *>(Terminal);
  695. DebugAssert(ManagedTerminal != NULL);
  696. bool Changed = false;
  697. if (Terminal->SessionData->UpdateDirectories)
  698. {
  699. Data->CopyDirectoriesStateData(ManagedTerminal->StateData);
  700. Changed = true;
  701. }
  702. if (Changed)
  703. {
  704. // modified only, implicit
  705. StoredSessions->Save(false, false);
  706. }
  707. }
  708. }
  709. //---------------------------------------------------------------------------
  710. void __fastcall TTerminalManager::HandleException(Exception * E)
  711. {
  712. // can be null for example when exception is thrown on login dialog
  713. if (ActiveTerminal != NULL)
  714. {
  715. ActiveTerminal->ShowExtendedException(E);
  716. }
  717. else
  718. {
  719. ShowExtendedException(E);
  720. }
  721. }
  722. //---------------------------------------------------------------------------
  723. void __fastcall TTerminalManager::ApplicationException(TObject * /*Sender*/,
  724. Exception * E)
  725. {
  726. HandleException(E);
  727. }
  728. //---------------------------------------------------------------------------
  729. void __fastcall TTerminalManager::ApplicationShowHint(UnicodeString & HintStr,
  730. bool & /*CanShow*/, THintInfo & HintInfo)
  731. {
  732. HintInfo.HintData = HintInfo.HintControl;
  733. if (HasLabelHintPopup(HintInfo.HintControl, HintStr))
  734. {
  735. // Hack for transfer setting labels.
  736. // Should be converted to something like HintLabel()
  737. HintInfo.HideTimeout = 100000; // "almost" never
  738. }
  739. else if (dynamic_cast<TProgressBar *>(HintInfo.HintControl) != NULL)
  740. {
  741. // Hint is forcibly hidden in TProgressForm::FormHide
  742. HintInfo.HideTimeout = 100000; // "almost" never
  743. HintInfo.ReshowTimeout = 500; // updated each 0.5s
  744. }
  745. else
  746. {
  747. int HintMaxWidth = 300;
  748. TControl * ScaleControl = HintInfo.HintControl;
  749. if (DebugAlwaysFalse(HintInfo.HintControl == NULL) ||
  750. (GetParentForm(HintInfo.HintControl) == NULL))
  751. {
  752. ScaleControl = ScpExplorer;
  753. }
  754. HintMaxWidth = ScaleByTextHeight(ScaleControl, HintMaxWidth);
  755. HintInfo.HintMaxWidth = HintMaxWidth;
  756. }
  757. }
  758. //---------------------------------------------------------------------------
  759. bool __fastcall TTerminalManager::HandleMouseWheel(WPARAM WParam, LPARAM LParam)
  760. {
  761. // WORKAROUND This is no longer necessary on Windows 10 (except for WM_WANTS_MOUSEWHEEL_INACTIVE part)
  762. bool Result = false;
  763. if (Application->Active)
  764. {
  765. TPoint Point(LOWORD(LParam), HIWORD(LParam));
  766. TWinControl * Control = FindVCLWindow(Point);
  767. if (Control != NULL)
  768. {
  769. TCustomForm * Form = GetParentForm(Control);
  770. // Only case we expect the parent form to be NULL is on the Find/Replace dialog,
  771. // which is owned by VCL's internal TRedirectorWindow.
  772. DebugAssert((Form != NULL) || (Control->ClassName() == L"TRedirectorWindow"));
  773. if (Form != NULL)
  774. {
  775. // Send it only to windows we tested it with.
  776. // Though we should sooner or later remove this test and pass it to all our windows.
  777. if (Form->Active && (Form->Perform(WM_WANTS_MOUSEWHEEL, 0, 0) == 1))
  778. {
  779. SendMessage(Control->Handle, WM_MOUSEWHEEL, WParam, LParam);
  780. Result = true;
  781. }
  782. else if (!Form->Active && (Form->Perform(WM_WANTS_MOUSEWHEEL_INACTIVE, 0, 0) == 1))
  783. {
  784. TWinControl * Control2;
  785. // FindVCLWindow stops on window level, when the window is not active? or when there's a modal window over it?
  786. // (but in any case, when we have operation running on top of Synchronization checklist).
  787. // WORKAROUND: The while loop does what AllLevels parameter of ControlAtPos should do, but it's broken.
  788. // See http://qc.embarcadero.com/wc/qcmain.aspx?d=82143
  789. while ((Control2 = dynamic_cast<TWinControl *>(Control->ControlAtPos(Control->ScreenToClient(Point), false, true))) != NULL)
  790. {
  791. Control = Control2;
  792. }
  793. SendMessage(Control->Handle, WM_MOUSEWHEEL, WParam, LParam);
  794. Result = true;
  795. }
  796. }
  797. }
  798. }
  799. return Result;
  800. }
  801. //---------------------------------------------------------------------------
  802. void __fastcall TTerminalManager::ApplicationMessage(TMsg & Msg, bool & Handled)
  803. {
  804. if (Msg.message == FTaskbarButtonCreatedMessage)
  805. {
  806. CreateTaskbarList();
  807. }
  808. if (Msg.message == WM_MOUSEWHEEL)
  809. {
  810. Handled = HandleMouseWheel(Msg.wParam, Msg.lParam);
  811. }
  812. }
  813. //---------------------------------------------------------------------------
  814. void __fastcall TTerminalManager::ApplicationModalBegin(TObject * /*Sender*/)
  815. {
  816. NonVisualDataModule->StartBusy();
  817. if (ScpExplorer != NULL)
  818. {
  819. ScpExplorer->SuspendWindowLock();
  820. }
  821. }
  822. //---------------------------------------------------------------------------
  823. void __fastcall TTerminalManager::ApplicationModalEnd(TObject * /*Sender*/)
  824. {
  825. NonVisualDataModule->EndBusy();
  826. if (ScpExplorer != NULL)
  827. {
  828. ScpExplorer->ResumeWindowLock();
  829. }
  830. }
  831. //---------------------------------------------------------------------------
  832. void __fastcall TTerminalManager::InitTaskbarButtonCreatedMessage()
  833. {
  834. // XE6 VCL already handles TaskbarButtonCreated, but does not call ChangeWindowMessageFilterEx.
  835. // So we keep our implementation.
  836. // See also https://stackoverflow.com/q/14614823/850848#14618587
  837. FTaskbarButtonCreatedMessage = RegisterWindowMessage(L"TaskbarButtonCreated");
  838. HINSTANCE User32Library = LoadLibrary(L"user32.dll");
  839. ChangeWindowMessageFilterExProc ChangeWindowMessageFilterEx =
  840. (ChangeWindowMessageFilterExProc)GetProcAddress(User32Library, "ChangeWindowMessageFilterEx");
  841. if (ChangeWindowMessageFilterEx != NULL)
  842. {
  843. // without this we won't get TaskbarButtonCreated, when app is running elevated
  844. ChangeWindowMessageFilterEx(
  845. Application->Handle, FTaskbarButtonCreatedMessage, MSGFLT_ALLOW, NULL);
  846. }
  847. }
  848. //---------------------------------------------------------------------------
  849. void __fastcall TTerminalManager::CreateTaskbarList()
  850. {
  851. ReleaseTaskbarList();
  852. if(SUCCEEDED(CoCreateInstance(CLSID_TaskbarList, NULL, CLSCTX_ALL,
  853. IID_ITaskbarList3, (void **) &FTaskbarList)))
  854. {
  855. if (ScpExplorer != NULL)
  856. {
  857. UpdateTaskbarList();
  858. }
  859. }
  860. }
  861. //---------------------------------------------------------------------------
  862. void __fastcall TTerminalManager::ReleaseTaskbarList()
  863. {
  864. if (FTaskbarList != NULL)
  865. {
  866. FTaskbarList->Release();
  867. }
  868. }
  869. //---------------------------------------------------------------------------
  870. void __fastcall TTerminalManager::UpdateTaskbarList()
  871. {
  872. ScpExplorer->UpdateTaskbarList(FTaskbarList);
  873. }
  874. //---------------------------------------------------------------------------
  875. void __fastcall TTerminalManager::DeleteLocalFile(const UnicodeString FileName, bool Alternative)
  876. {
  877. RecursiveDeleteFileChecked(FileName, (WinConfiguration->DeleteToRecycleBin != Alternative));
  878. }
  879. //---------------------------------------------------------------------------
  880. void __fastcall TTerminalManager::TerminalQueryUser(TObject * Sender,
  881. const UnicodeString Query, TStrings * MoreMessages, unsigned int Answers,
  882. const TQueryParams * Params, unsigned int & Answer, TQueryType Type, void * /*Arg*/)
  883. {
  884. UnicodeString HelpKeyword;
  885. TMessageParams MessageParams(Params);
  886. UnicodeString AQuery = Query;
  887. if (Params != NULL)
  888. {
  889. HelpKeyword = Params->HelpKeyword;
  890. if (FLAGSET(Params->Params, qpFatalAbort))
  891. {
  892. AQuery = FMTLOAD(WARN_FATAL_ERROR, (AQuery));
  893. if (!MessageParams.TimerMessage.IsEmpty())
  894. {
  895. MessageParams.TimerMessage = FMTLOAD(WARN_FATAL_ERROR, (MessageParams.TimerMessage));
  896. }
  897. }
  898. }
  899. if (ScpExplorer)
  900. {
  901. Answer = ScpExplorer->MoreMessageDialog(AQuery, MoreMessages, Type, Answers,
  902. HelpKeyword, &MessageParams, dynamic_cast<TTerminal *>(Sender));
  903. }
  904. else
  905. {
  906. Answer = MoreMessageDialog(AQuery, MoreMessages, Type, Answers, HelpKeyword,
  907. &MessageParams);
  908. }
  909. }
  910. //---------------------------------------------------------------------------
  911. void __fastcall TTerminalManager::AuthenticateFormCancel(TObject * Sender)
  912. {
  913. TAuthenticateForm * Form = dynamic_cast<TAuthenticateForm *>(Sender);
  914. DebugAssert(Form != NULL);
  915. TManagedTerminal * ManagedTerminal = dynamic_cast<TManagedTerminal *>(Form->Terminal);
  916. // will be null e.g. for background transfers
  917. if (ManagedTerminal != NULL)
  918. {
  919. TTerminalThread * TerminalThread = ManagedTerminal->TerminalThread;
  920. // can be NULL for reconnects from transfers
  921. if ((TerminalThread != NULL) && !TerminalThread->Cancelling)
  922. {
  923. Form->Log(LoadStr(AUTH_CANCELLING));
  924. TerminalThread->Cancel();
  925. }
  926. }
  927. FAuthenticationCancelled = true;
  928. }
  929. //---------------------------------------------------------------------------
  930. TAuthenticateForm * __fastcall TTerminalManager::MakeAuthenticateForm(
  931. TTerminal * Terminal)
  932. {
  933. TAuthenticateForm * Dialog = SafeFormCreate<TAuthenticateForm>();
  934. Dialog->Init(Terminal);
  935. DebugAssert(Dialog->OnCancel == NULL);
  936. Dialog->OnCancel = AuthenticateFormCancel;
  937. return Dialog;
  938. }
  939. //---------------------------------------------------------------------------
  940. void __fastcall TTerminalManager::FileNameInputDialogInitializeRenameBaseName(
  941. TObject * /*Sender*/, TInputDialogData * Data)
  942. {
  943. EditSelectBaseName(Data->Edit->Handle);
  944. }
  945. //---------------------------------------------------------------------------
  946. void __fastcall TTerminalManager::TerminalPromptUser(
  947. TTerminal * Terminal, TPromptKind Kind, UnicodeString Name, UnicodeString Instructions,
  948. TStrings * Prompts, TStrings * Results, bool & Result, void * /*Arg*/)
  949. {
  950. if (((Kind == pkPrompt) || (Kind == pkFileName)) && (FAuthenticateForm == NULL) &&
  951. (Terminal->Status != ssOpening))
  952. {
  953. DebugAssert(Instructions.IsEmpty());
  954. DebugAssert(Prompts->Count == 1);
  955. DebugAssert(FLAGSET(int(Prompts->Objects[0]), pupEcho));
  956. UnicodeString AResult = Results->Strings[0];
  957. TInputDialogInitialize InputDialogInitialize = NULL;
  958. if ((Kind == pkFileName) && !WinConfiguration->RenameWholeName)
  959. {
  960. InputDialogInitialize = FileNameInputDialogInitializeRenameBaseName;
  961. }
  962. Result = InputDialog(Name, Prompts->Strings[0], AResult, L"", NULL, false, InputDialogInitialize);
  963. if (Result)
  964. {
  965. Results->Strings[0] = AResult;
  966. }
  967. }
  968. else
  969. {
  970. TAuthenticateForm * AuthenticateForm = FAuthenticateForm;
  971. if (AuthenticateForm == NULL)
  972. {
  973. AuthenticateForm = MakeAuthenticateForm(Terminal);
  974. }
  975. try
  976. {
  977. Result = AuthenticateForm->PromptUser(Kind, Name, Instructions, Prompts, Results,
  978. (FAuthenticateForm != NULL), Terminal->StoredCredentialsTried);
  979. }
  980. __finally
  981. {
  982. if (FAuthenticateForm == NULL)
  983. {
  984. delete AuthenticateForm;
  985. }
  986. }
  987. }
  988. }
  989. //---------------------------------------------------------------------------
  990. void __fastcall TTerminalManager::TerminalDisplayBanner(
  991. TTerminal * Terminal, UnicodeString SessionName,
  992. const UnicodeString & Banner, bool & NeverShowAgain, int Options, unsigned int & Params)
  993. {
  994. DebugAssert(FAuthenticateForm != NULL);
  995. TAuthenticateForm * AuthenticateForm = FAuthenticateForm;
  996. if (AuthenticateForm == NULL)
  997. {
  998. AuthenticateForm = MakeAuthenticateForm(Terminal);
  999. }
  1000. try
  1001. {
  1002. AuthenticateForm->Banner(Banner, NeverShowAgain, Options, Params);
  1003. }
  1004. __finally
  1005. {
  1006. if (FAuthenticateForm == NULL)
  1007. {
  1008. delete AuthenticateForm;
  1009. }
  1010. }
  1011. }
  1012. //---------------------------------------------------------------------------
  1013. void __fastcall TTerminalManager::TerminalShowExtendedException(
  1014. TTerminal * Terminal, Exception * E, void * /*Arg*/)
  1015. {
  1016. if (ScpExplorer)
  1017. {
  1018. ScpExplorer->ShowExtendedException(Terminal, E);
  1019. }
  1020. else
  1021. {
  1022. ShowExtendedExceptionEx(Terminal, E);
  1023. }
  1024. }
  1025. //---------------------------------------------------------------------------
  1026. static TDateTime DirectoryReadingProgressDelay(0, 0, 1, 500);
  1027. //---------------------------------------------------------------------------
  1028. void __fastcall TTerminalManager::TerminalReadDirectoryProgress(
  1029. TObject * /*Sender*/, int Progress, int ResolvedLinks, bool & Cancel)
  1030. {
  1031. if (Progress == 0)
  1032. {
  1033. if (ScpExplorer != NULL)
  1034. {
  1035. // See also TCustomScpExplorerForm::RemoteDirViewBusy
  1036. ScpExplorer->LockWindow();
  1037. }
  1038. FDirectoryReadingStart = Now();
  1039. if (!FProgressTitle.IsEmpty() || !FForegroundProgressTitle.IsEmpty())
  1040. {
  1041. FProgressTitle = L"";
  1042. FForegroundProgressTitle = L"";
  1043. UpdateAppTitle();
  1044. }
  1045. // Reset "was ESC ever pressed?" state
  1046. GetAsyncKeyState(VK_ESCAPE);
  1047. }
  1048. else if (Progress < 0)
  1049. {
  1050. if (Progress == -2)
  1051. {
  1052. // cancelled
  1053. if (ScpExplorer != NULL)
  1054. {
  1055. ScpExplorer->ReadDirectoryCancelled();
  1056. }
  1057. }
  1058. else
  1059. {
  1060. if (ScpExplorer != NULL)
  1061. {
  1062. ScpExplorer->UnlockWindow();
  1063. }
  1064. FProgressTitle = L"";
  1065. FForegroundProgressTitle = L"";
  1066. UpdateAppTitle();
  1067. }
  1068. }
  1069. else
  1070. {
  1071. // If the least significant bit is set,
  1072. // the key was pressed after the previous call to GetAsyncKeyState.
  1073. int KeyState = GetAsyncKeyState(VK_ESCAPE);
  1074. if (FLAGSET(KeyState, 0x01))
  1075. {
  1076. Cancel = true;
  1077. }
  1078. if ((Now() - FDirectoryReadingStart) >= DirectoryReadingProgressDelay)
  1079. {
  1080. // 4 is arbitrary number
  1081. FForegroundProgressTitle =
  1082. FMTLOAD(ResolvedLinks >= 4 ? DIRECTORY_READING_AND_RESOLVING_PROGRESS : DIRECTORY_READING_PROGRESS,
  1083. (Progress));
  1084. UpdateAppTitle();
  1085. }
  1086. }
  1087. }
  1088. //---------------------------------------------------------------------------
  1089. void __fastcall TTerminalManager::TerminalCustomCommand(
  1090. TTerminal * /*Terminal*/, const UnicodeString & Command, bool & Handled)
  1091. {
  1092. // Implementation has to be thread-safe
  1093. Handled = CopyCommandToClipboard(Command);
  1094. }
  1095. //---------------------------------------------------------------------------
  1096. void __fastcall TTerminalManager::AuthenticatingDone()
  1097. {
  1098. FAuthenticating--;
  1099. if (FAuthenticating == 0)
  1100. {
  1101. BusyEnd(FBusyToken);
  1102. FBusyToken = NULL;
  1103. }
  1104. if (!FKeepAuthenticateForm)
  1105. {
  1106. CloseAutheticateForm();
  1107. }
  1108. }
  1109. //---------------------------------------------------------------------------
  1110. void __fastcall TTerminalManager::TerminalInformation(
  1111. TTerminal * Terminal, const UnicodeString & Str, bool /*Status*/, int Phase)
  1112. {
  1113. if (Phase == 1)
  1114. {
  1115. if (FAuthenticating == 0)
  1116. {
  1117. FBusyToken = BusyStart();
  1118. }
  1119. FAuthenticating++;
  1120. }
  1121. else if (Phase == 0)
  1122. {
  1123. DebugAssert(FAuthenticating > 0);
  1124. AuthenticatingDone();
  1125. }
  1126. else
  1127. {
  1128. if (FAuthenticating > 0)
  1129. {
  1130. bool ShowPending = false;
  1131. if (FAuthenticateForm == NULL)
  1132. {
  1133. FAuthenticateForm = MakeAuthenticateForm(Terminal);
  1134. ShowPending = true;
  1135. }
  1136. FAuthenticateForm->Log(Str);
  1137. if (ShowPending)
  1138. {
  1139. FAuthenticateForm->ShowAsModal();
  1140. }
  1141. }
  1142. }
  1143. }
  1144. //---------------------------------------------------------------------------
  1145. void __fastcall TTerminalManager::OperationFinished(::TFileOperation Operation,
  1146. TOperationSide Side, bool Temp, const UnicodeString & FileName, bool Success,
  1147. TOnceDoneOperation & OnceDoneOperation)
  1148. {
  1149. DebugAssert(ScpExplorer);
  1150. ScpExplorer->OperationFinished(Operation, Side, Temp, FileName, Success,
  1151. OnceDoneOperation);
  1152. }
  1153. //---------------------------------------------------------------------------
  1154. void __fastcall TTerminalManager::OperationProgress(
  1155. TFileOperationProgressType & ProgressData)
  1156. {
  1157. UpdateAppTitle();
  1158. DebugAssert(ScpExplorer);
  1159. ScpExplorer->OperationProgress(ProgressData);
  1160. }
  1161. //---------------------------------------------------------------------------
  1162. void __fastcall TTerminalManager::QueueEvent(TTerminalQueue * Queue, TQueueEvent Event)
  1163. {
  1164. TGuard Guard(FQueueSection);
  1165. FQueueEvents.push_back(std::make_pair(Queue, Event));
  1166. }
  1167. //---------------------------------------------------------------------------
  1168. void __fastcall TTerminalManager::DoConfigurationChange()
  1169. {
  1170. DebugAssert(Configuration);
  1171. DebugAssert(Configuration == WinConfiguration);
  1172. TTerminalQueue * Queue;
  1173. for (int Index = 0; Index < Count; Index++)
  1174. {
  1175. DebugAssert(Terminals[Index]->Log);
  1176. Terminals[Index]->Log->ReflectSettings();
  1177. Terminals[Index]->ActionLog->ReflectSettings();
  1178. Queue = reinterpret_cast<TTerminalQueue *>(FQueues->Items[Index]);
  1179. SetQueueConfiguration(Queue);
  1180. }
  1181. if (ScpExplorer)
  1182. {
  1183. ScpExplorer->ConfigurationChanged();
  1184. }
  1185. }
  1186. //---------------------------------------------------------------------------
  1187. void __fastcall TTerminalManager::ConfigurationChange(TObject * /*Sender*/)
  1188. {
  1189. if (FMainThread == GetCurrentThreadId())
  1190. {
  1191. DoConfigurationChange();
  1192. }
  1193. else
  1194. {
  1195. TGuard Guard(FChangeSection.get());
  1196. FPendingConfigurationChange++;
  1197. }
  1198. }
  1199. //---------------------------------------------------------------------------
  1200. void __fastcall TTerminalManager::TerminalReady()
  1201. {
  1202. ScpExplorer->Terminal = ActiveTerminal;
  1203. ScpExplorer->Queue = ActiveQueue;
  1204. ScpExplorer->TerminalReady();
  1205. }
  1206. //---------------------------------------------------------------------------
  1207. TStrings * __fastcall TTerminalManager::GetTerminalList()
  1208. {
  1209. FTerminalList->Clear();
  1210. for (int i = 0; i < Count; i++)
  1211. {
  1212. TTerminal * Terminal = Terminals[i];
  1213. UnicodeString Name = GetTerminalTitle(Terminal, true);
  1214. FTerminalList->AddObject(Name, Terminal);
  1215. }
  1216. return FTerminalList;
  1217. }
  1218. //---------------------------------------------------------------------------
  1219. int __fastcall TTerminalManager::GetActiveTerminalIndex()
  1220. {
  1221. return ActiveTerminal ? IndexOf(ActiveTerminal) : -1;
  1222. }
  1223. //---------------------------------------------------------------------------
  1224. void __fastcall TTerminalManager::SetActiveTerminalIndex(int value)
  1225. {
  1226. ActiveTerminal = Terminals[value];
  1227. }
  1228. //---------------------------------------------------------------------------
  1229. UnicodeString __fastcall TTerminalManager::GetTerminalShortPath(TTerminal * Terminal)
  1230. {
  1231. UnicodeString Result = UnixExtractFileName(Terminal->CurrentDirectory);
  1232. if (Result.IsEmpty())
  1233. {
  1234. Result = Terminal->CurrentDirectory;
  1235. }
  1236. return Result;
  1237. }
  1238. //---------------------------------------------------------------------------
  1239. UnicodeString __fastcall TTerminalManager::GetTerminalTitle(TTerminal * Terminal, bool Unique)
  1240. {
  1241. UnicodeString Result = Terminal->SessionData->SessionName;
  1242. if (Unique)
  1243. {
  1244. int Index = IndexOf(Terminal);
  1245. // not for background transfer sessions
  1246. if (Index >= 0)
  1247. {
  1248. for (int Index2 = 0; Index2 < Count; Index2++)
  1249. {
  1250. UnicodeString Name = Terminals[Index2]->SessionData->SessionName;
  1251. if ((Terminals[Index2] != Terminal) &&
  1252. SameText(Name, Result))
  1253. {
  1254. UnicodeString Path = GetTerminalShortPath(Terminal);
  1255. if (!Path.IsEmpty())
  1256. {
  1257. Result = FORMAT(L"%s (%s)", (Result, Path));
  1258. }
  1259. break;
  1260. }
  1261. }
  1262. }
  1263. }
  1264. return Result;
  1265. }
  1266. //---------------------------------------------------------------------------
  1267. UnicodeString __fastcall TTerminalManager::GetActiveTerminalTitle(bool Unique)
  1268. {
  1269. UnicodeString Result;
  1270. if (ActiveTerminal != NULL)
  1271. {
  1272. Result = GetTerminalTitle(ActiveTerminal, Unique);
  1273. }
  1274. return Result;
  1275. }
  1276. //---------------------------------------------------------------------------
  1277. TTerminalQueue * __fastcall TTerminalManager::GetActiveQueue()
  1278. {
  1279. TTerminalQueue * Result = NULL;
  1280. if (ActiveTerminal != NULL)
  1281. {
  1282. Result = reinterpret_cast<TTerminalQueue *>(FQueues->Items[ActiveTerminalIndex]);
  1283. }
  1284. return Result;
  1285. }
  1286. //---------------------------------------------------------------------------
  1287. void __fastcall TTerminalManager::CycleTerminals(bool Forward)
  1288. {
  1289. if (Count > 0)
  1290. {
  1291. int Index = ActiveTerminalIndex;
  1292. Index += Forward ? 1 : -1;
  1293. if (Index < 0)
  1294. {
  1295. Index = Count-1;
  1296. }
  1297. else if (Index >= Count)
  1298. {
  1299. Index = 0;
  1300. }
  1301. ActiveTerminalIndex = Index;
  1302. }
  1303. }
  1304. //---------------------------------------------------------------------------
  1305. bool __fastcall TTerminalManager::CanOpenInPutty()
  1306. {
  1307. return (ActiveTerminal != NULL) && !GUIConfiguration->PuttyPath.Trim().IsEmpty();
  1308. }
  1309. //---------------------------------------------------------------------------
  1310. void __fastcall TTerminalManager::UpdateSessionCredentials(TSessionData * Data)
  1311. {
  1312. Data->UserName = ActiveTerminal->UserName;
  1313. Data->Password = ActiveTerminal->Password;
  1314. }
  1315. //---------------------------------------------------------------------------
  1316. void __fastcall TTerminalManager::OpenInPutty()
  1317. {
  1318. Configuration->Usage->Inc(L"OpenInPutty");
  1319. TSessionData * Data = NULL;
  1320. try
  1321. {
  1322. // Is NULL on the first session when called from ConnectActiveTerminal()
  1323. // due to WinConfiguration->AutoOpenInPutty
  1324. if (ScpExplorer != NULL)
  1325. {
  1326. Data = ScpExplorer->CloneCurrentSessionData();
  1327. }
  1328. else
  1329. {
  1330. Data = new TSessionData(L"");
  1331. DebugAssert(ActiveTerminal != NULL);
  1332. Data->Assign(ActiveTerminal->SessionData);
  1333. UpdateSessionCredentials(Data);
  1334. }
  1335. // putty does not support resolving environment variables in session settings
  1336. Data->ExpandEnvironmentVariables();
  1337. if (ActiveTerminal->TunnelLocalPortNumber != 0)
  1338. {
  1339. Data->ConfigureTunnel(ActiveTerminal->TunnelLocalPortNumber);
  1340. }
  1341. OpenSessionInPutty(GUIConfiguration->PuttyPath, Data);
  1342. }
  1343. __finally
  1344. {
  1345. delete Data;
  1346. }
  1347. }
  1348. //---------------------------------------------------------------------------
  1349. void __fastcall TTerminalManager::NewSession(bool /*FromSite*/, const UnicodeString & SessionUrl, bool ReloadSessions, TForm * LinkedForm)
  1350. {
  1351. if (ReloadSessions)
  1352. {
  1353. StoredSessions->Reload();
  1354. }
  1355. UnicodeString DownloadFile; // unused
  1356. std::unique_ptr<TObjectList> DataList(new TObjectList());
  1357. GetLoginData(SessionUrl, NULL, DataList.get(), DownloadFile, true, LinkedForm);
  1358. if (DataList->Count > 0)
  1359. {
  1360. ActiveTerminal = NewTerminals(DataList.get());
  1361. }
  1362. }
  1363. //---------------------------------------------------------------------------
  1364. void __fastcall TTerminalManager::Idle(bool SkipCurrentTerminal)
  1365. {
  1366. if (FPendingConfigurationChange > 0) // optimization
  1367. {
  1368. bool Changed = false;
  1369. {
  1370. TGuard Guard(FChangeSection.get());
  1371. if (DebugAlwaysTrue(FPendingConfigurationChange > 0))
  1372. {
  1373. FPendingConfigurationChange--;
  1374. Changed = true;
  1375. }
  1376. }
  1377. if (Changed)
  1378. {
  1379. DoConfigurationChange();
  1380. }
  1381. }
  1382. for (int Index = 0; Index < Count; Index++)
  1383. {
  1384. TTerminal * Terminal = Terminals[Index];
  1385. try
  1386. {
  1387. if (!SkipCurrentTerminal || (Terminal != ActiveTerminal))
  1388. {
  1389. TManagedTerminal * ManagedTerminal = dynamic_cast<TManagedTerminal *>(Terminal);
  1390. DebugAssert(ManagedTerminal != NULL);
  1391. // make sure Idle is called on the thread that runs the terminal
  1392. if (ManagedTerminal->TerminalThread != NULL)
  1393. {
  1394. ManagedTerminal->TerminalThread->Idle();
  1395. }
  1396. else
  1397. {
  1398. if (Terminal->Active)
  1399. {
  1400. Terminal->Idle();
  1401. }
  1402. }
  1403. if (Terminal->Active)
  1404. {
  1405. DebugAssert(Index < FQueues->Count);
  1406. if (Index < FQueues->Count)
  1407. {
  1408. reinterpret_cast<TTerminalQueue *>(FQueues->Items[Index])->Idle();
  1409. }
  1410. }
  1411. }
  1412. }
  1413. catch(Exception & E)
  1414. {
  1415. if (Terminal == ActiveTerminal)
  1416. {
  1417. // throw further, so that the exception is handled in proper place
  1418. // (particularly in broken-transfer reconnect handler, bug 72)
  1419. throw;
  1420. }
  1421. else
  1422. {
  1423. // we may not have inactive terminal, unless there is a explorer,
  1424. // also Idle is called from explorer anyway
  1425. DebugAssert(ScpExplorer != NULL);
  1426. if (ScpExplorer != NULL)
  1427. {
  1428. ScpExplorer->InactiveTerminalException(Terminal, &E);
  1429. }
  1430. if (!Terminal->Active)
  1431. {
  1432. // if session is lost, save the error message and rethrow it
  1433. // once the terminal gets activated
  1434. FTerminationMessages->Strings[Index] = E.Message;
  1435. }
  1436. }
  1437. }
  1438. }
  1439. TTerminalQueue * QueueWithEvent;
  1440. TQueueEvent QueueEvent;
  1441. do
  1442. {
  1443. QueueWithEvent = NULL;
  1444. {
  1445. TGuard Guard(FQueueSection);
  1446. if (!FQueueEvents.empty())
  1447. {
  1448. QueueWithEvent = FQueueEvents[0].first;
  1449. QueueEvent = FQueueEvents[0].second;
  1450. FQueueEvents.erase(FQueueEvents.begin());
  1451. }
  1452. }
  1453. if (QueueWithEvent != NULL)
  1454. {
  1455. int Index = FQueues->IndexOf(QueueWithEvent);
  1456. // the session may not exist anymore
  1457. if (Index >= 0)
  1458. {
  1459. TTerminal * Terminal = Terminals[Index];
  1460. // we can hardly have a queue event without explorer
  1461. DebugAssert(ScpExplorer != NULL);
  1462. if (ScpExplorer != NULL)
  1463. {
  1464. ScpExplorer->QueueEvent(Terminal, QueueWithEvent, QueueEvent);
  1465. }
  1466. }
  1467. }
  1468. }
  1469. while (QueueWithEvent != NULL);
  1470. }
  1471. //---------------------------------------------------------------------------
  1472. void __fastcall TTerminalManager::MasterPasswordPrompt()
  1473. {
  1474. if (GetCurrentThreadId() == MainThreadID)
  1475. {
  1476. if (!DoMasterPasswordDialog())
  1477. {
  1478. Abort();
  1479. }
  1480. }
  1481. else
  1482. {
  1483. // this can happen only when we keep cancelling all master password prompts
  1484. // as long as the sessing finally connects (session password has to be
  1485. // explictly typed in), and background transfer is started
  1486. Abort();
  1487. }
  1488. }
  1489. //---------------------------------------------------------------------------
  1490. void __fastcall TTerminalManager::Move(TTerminal * Source, TTerminal * Target)
  1491. {
  1492. int SourceIndex = IndexOf(Source);
  1493. int TargetIndex = IndexOf(Target);
  1494. TTerminalList::Move(SourceIndex, TargetIndex);
  1495. FQueues->Move(SourceIndex, TargetIndex);
  1496. DoTerminalListChanged();
  1497. // when there are indexed sessions with the same name,
  1498. // the index may change when reordering the sessions
  1499. UpdateAppTitle();
  1500. }
  1501. //---------------------------------------------------------------------------
  1502. void __fastcall TTerminalManager::DoTerminalListChanged()
  1503. {
  1504. if (OnTerminalListChanged)
  1505. {
  1506. OnTerminalListChanged(this);
  1507. }
  1508. }
  1509. //---------------------------------------------------------------------------
  1510. void __fastcall TTerminalManager::SaveWorkspace(TList * DataList)
  1511. {
  1512. for (int Index = 0; Index < Count; Index++)
  1513. {
  1514. TManagedTerminal * ManagedTerminal = dynamic_cast<TManagedTerminal *>(Terminals[Index]);
  1515. TSessionData * Data = StoredSessions->SaveWorkspaceData(ManagedTerminal->StateData, Index);
  1516. DataList->Add(Data);
  1517. }
  1518. }
  1519. //---------------------------------------------------------------------------
  1520. TTerminal * __fastcall TTerminalManager::FindActiveTerminalForSite(TSessionData * Data)
  1521. {
  1522. TTerminal * Result = NULL;
  1523. for (int Index = 0; (Result == NULL) && (Index < Count); Index++)
  1524. {
  1525. TTerminal * Terminal = Terminals[Index];
  1526. if (Terminal->Active &&
  1527. Terminal->SessionData->IsSameSite(Data))
  1528. {
  1529. Result = Terminal;
  1530. }
  1531. }
  1532. return Result;
  1533. }
  1534. //---------------------------------------------------------------------------
  1535. TTerminalQueue * __fastcall TTerminalManager::FindQueueForTerminal(TTerminal * Terminal)
  1536. {
  1537. int Index = IndexOf(Terminal);
  1538. return reinterpret_cast<TTerminalQueue *>(FQueues->Items[Index]);
  1539. }
  1540. //---------------------------------------------------------------------------
  1541. TRemoteFile * __fastcall TTerminalManager::CheckRights(
  1542. TTerminal * Terminal, const UnicodeString & EntryType, const UnicodeString & FileName, bool & WrongRights)
  1543. {
  1544. std::unique_ptr<TRemoteFile> FileOwner;
  1545. TRemoteFile * File;
  1546. try
  1547. {
  1548. Terminal->LogEvent(FORMAT(L"Checking %s \"%s\"...", (LowerCase(EntryType), FileName)));
  1549. Terminal->ReadFile(FileName, File);
  1550. FileOwner.reset(File);
  1551. int ForbiddenRights = TRights::rfGroupWrite | TRights::rfOtherWrite;
  1552. if ((File->Rights->Number & ForbiddenRights) != 0)
  1553. {
  1554. Terminal->LogEvent(FORMAT(L"%s \"%s\" exists, but has incorrect permissions %s.", (EntryType, FileName, File->Rights->Octal)));
  1555. WrongRights = true;
  1556. }
  1557. else
  1558. {
  1559. Terminal->LogEvent(FORMAT(L"%s \"%s\" exists and has correct permissions %s.", (EntryType, FileName, File->Rights->Octal)));
  1560. }
  1561. }
  1562. catch (Exception & E)
  1563. {
  1564. }
  1565. return FileOwner.release();
  1566. }
  1567. //---------------------------------------------------------------------------
  1568. bool __fastcall TTerminalManager::UploadPublicKey(
  1569. TTerminal * Terminal, TSessionData * Data, UnicodeString & FileName)
  1570. {
  1571. std::unique_ptr<TOpenDialog> OpenDialog(new TOpenDialog(Application));
  1572. OpenDialog->Title = LoadStr(LOGIN_PUBLIC_KEY_TITLE);
  1573. OpenDialog->Filter = LoadStr(LOGIN_PUBLIC_KEY_FILTER);
  1574. OpenDialog->DefaultExt = PuttyKeyExt;
  1575. OpenDialog->FileName = FileName;
  1576. bool Result = OpenDialog->Execute();
  1577. if (Result)
  1578. {
  1579. Configuration->Usage->Inc(L"PublicKeyInstallation");
  1580. FileName = OpenDialog->FileName;
  1581. bool AutoReadDirectory;
  1582. bool ExceptionOnFail;
  1583. UnicodeString TemporaryDir;
  1584. bool WrongRights = false;
  1585. const UnicodeString SshFolder = L".ssh";
  1586. const UnicodeString AuthorizedKeysFile = L"authorized_keys";
  1587. UnicodeString AuthorizedKeysFilePath = FORMAT(L"%s/%s", (SshFolder, AuthorizedKeysFile));
  1588. VerifyAndConvertKey(FileName, ssh2only, false);
  1589. UnicodeString Comment;
  1590. UnicodeString Line = GetPublicKeyLine(FileName, Comment);
  1591. bool AdHocTerminal = (Terminal == NULL);
  1592. std::unique_ptr<TTerminal> TerminalOwner;
  1593. if (AdHocTerminal)
  1594. {
  1595. DebugAssert(Data != NULL);
  1596. TAutoFlag KeepAuthenticateFormFlag(FKeepAuthenticateForm);
  1597. try
  1598. {
  1599. TerminalOwner.reset(CreateTerminal(Data));
  1600. Terminal = TerminalOwner.get();
  1601. SetupTerminal(Terminal);
  1602. Terminal->OnProgress = NULL;
  1603. Terminal->OnFinished = NULL;
  1604. DoConnectTerminal(Terminal, false, true);
  1605. }
  1606. catch (Exception & E)
  1607. {
  1608. CloseAutheticateForm();
  1609. throw;
  1610. }
  1611. }
  1612. AutoReadDirectory = Terminal->AutoReadDirectory;
  1613. ExceptionOnFail = Terminal->ExceptionOnFail;
  1614. try
  1615. {
  1616. Terminal->AutoReadDirectory = false;
  1617. Terminal->ExceptionOnFail = true;
  1618. UnicodeString SshImplementation = Terminal->GetSessionInfo().SshImplementation;
  1619. UnicodeString NotOpenSSHMessage = FMTLOAD(LOGIN_NOT_OPENSSH, (SshImplementation));
  1620. if (IsOpenSSH(SshImplementation) ||
  1621. (MessageDialog(NotOpenSSHMessage, qtConfirmation, qaOK | qaCancel, HELP_LOGIN_AUTHORIZED_KEYS) == qaOK))
  1622. {
  1623. Terminal->Log->AddSeparator();
  1624. Terminal->LogEvent(FORMAT(L"Adding public key line to \"%s\" file:\n%s", (AuthorizedKeysFilePath, Line)));
  1625. // Ad-hoc terminal
  1626. if (FAuthenticateForm != NULL)
  1627. {
  1628. FAuthenticateForm->Log(FMTLOAD(LOGIN_PUBLIC_KEY_UPLOAD, (Comment)));
  1629. }
  1630. UnicodeString SshFolderAbsolutePath = UnixIncludeTrailingBackslash(Terminal->GetHomeDirectory()) + SshFolder;
  1631. std::unique_ptr<TRemoteFile> SshFolderFile(CheckRights(Terminal, L"Folder", SshFolderAbsolutePath, WrongRights));
  1632. if (SshFolderFile.get() == NULL)
  1633. {
  1634. TRights SshFolderRights;
  1635. SshFolderRights.Number = TRights::rfUserRead | TRights::rfUserWrite | TRights::rfUserExec;
  1636. TRemoteProperties SshFolderProperties;
  1637. SshFolderProperties.Rights = SshFolderRights;
  1638. SshFolderProperties.Valid = TValidProperties() << vpRights;
  1639. Terminal->LogEvent(FORMAT(L"Trying to create \"%s\" folder with permissions %s...", (SshFolder, SshFolderRights.Octal)));
  1640. Terminal->CreateDirectory(SshFolderAbsolutePath, &SshFolderProperties);
  1641. }
  1642. TemporaryDir = ExcludeTrailingBackslash(WinConfiguration->TemporaryDir());
  1643. if (!ForceDirectories(ApiPath(TemporaryDir)))
  1644. {
  1645. throw EOSExtException(FMTLOAD(CREATE_TEMP_DIR_ERROR, (TemporaryDir)));
  1646. }
  1647. UnicodeString TemporaryAuthorizedKeysFile = IncludeTrailingBackslash(TemporaryDir) + AuthorizedKeysFile;
  1648. UnicodeString AuthorizedKeysFileAbsolutePath = UnixIncludeTrailingBackslash(SshFolderAbsolutePath) + AuthorizedKeysFile;
  1649. bool Updated = true;
  1650. TCopyParamType CopyParam; // Use factory defaults
  1651. CopyParam.ResumeSupport = rsOff; // not to break the permissions
  1652. CopyParam.PreserveTime = false; // not needed
  1653. UnicodeString AuthorizedKeys;
  1654. std::unique_ptr<TRemoteFile> AuthorizedKeysFileFile(CheckRights(Terminal, L"File", AuthorizedKeysFileAbsolutePath, WrongRights));
  1655. if (AuthorizedKeysFileFile.get() != NULL)
  1656. {
  1657. AuthorizedKeysFileFile->FullFileName = AuthorizedKeysFileAbsolutePath;
  1658. std::unique_ptr<TStrings> Files(new TStringList());
  1659. Files->AddObject(AuthorizedKeysFileAbsolutePath, AuthorizedKeysFileFile.get());
  1660. Terminal->LogEvent(FORMAT(L"Downloading current \"%s\" file...", (AuthorizedKeysFile)));
  1661. Terminal->CopyToLocal(Files.get(), TemporaryDir, &CopyParam, cpNoConfirmation, NULL);
  1662. // Overload with Encoding parameter work incorrectly, when used on a file without BOM
  1663. AuthorizedKeys = TFile::ReadAllText(TemporaryAuthorizedKeysFile);
  1664. std::unique_ptr<TStrings> AuthorizedKeysLines(TextToStringList(AuthorizedKeys));
  1665. int P = Line.Pos(L" ");
  1666. if (DebugAlwaysTrue(P > 0))
  1667. {
  1668. P = PosEx(L" ", Line, P + 1);
  1669. }
  1670. UnicodeString Prefix = Line.SubString(1, P); // including the space
  1671. for (int Index = 0; Index < AuthorizedKeysLines->Count; Index++)
  1672. {
  1673. if (StartsStr(Prefix, AuthorizedKeysLines->Strings[Index]))
  1674. {
  1675. Terminal->LogEvent(FORMAT(L"\"%s\" file already contains public key line:\n%s", (AuthorizedKeysFile, AuthorizedKeysLines->Strings[Index])));
  1676. Updated = false;
  1677. }
  1678. }
  1679. if (Updated)
  1680. {
  1681. Terminal->LogEvent(FORMAT(L"\"%s\" file does not contain the public key line yet.", (AuthorizedKeysFile)));
  1682. if (!EndsStr(L"\n", AuthorizedKeys))
  1683. {
  1684. Terminal->LogEvent(FORMAT(L"Adding missing trailing new line to \"%s\" file...", (AuthorizedKeysFile)));
  1685. AuthorizedKeys += L"\n";
  1686. }
  1687. }
  1688. }
  1689. else
  1690. {
  1691. Terminal->LogEvent(FORMAT(L"Creating new \"%s\" file...", (AuthorizedKeysFile)));
  1692. CopyParam.PreserveRights = true;
  1693. CopyParam.Rights.Number = TRights::rfUserRead | TRights::rfUserWrite;
  1694. }
  1695. if (Updated)
  1696. {
  1697. AuthorizedKeys += Line + L"\n";
  1698. // Overload without Encoding parameter uses TEncoding::UTF8, but does not write BOM, what we want
  1699. TFile::WriteAllText(TemporaryAuthorizedKeysFile, AuthorizedKeys);
  1700. std::unique_ptr<TStrings> Files(new TStringList());
  1701. Files->Add(TemporaryAuthorizedKeysFile);
  1702. Terminal->LogEvent(FORMAT(L"Uploading updated \"%s\" file...", (AuthorizedKeysFile)));
  1703. Terminal->CopyToRemote(Files.get(), SshFolderAbsolutePath, &CopyParam, cpNoConfirmation, NULL);
  1704. }
  1705. }
  1706. }
  1707. __finally
  1708. {
  1709. Terminal->AutoReadDirectory = AutoReadDirectory;
  1710. Terminal->ExceptionOnFail = ExceptionOnFail;
  1711. if (!TemporaryDir.IsEmpty())
  1712. {
  1713. RecursiveDeleteFile(ExcludeTrailingBackslash(TemporaryDir), false);
  1714. }
  1715. CloseAutheticateForm(); // When uploading from Login dialog
  1716. }
  1717. Terminal->LogEvent(L"Public key installation done.");
  1718. if (AdHocTerminal)
  1719. {
  1720. TerminalOwner.reset(NULL);
  1721. }
  1722. else
  1723. {
  1724. Terminal->Log->AddSeparator();
  1725. }
  1726. UnicodeString Message = FMTLOAD(LOGIN_PUBLIC_KEY_UPLOADED, (Comment));
  1727. if (WrongRights)
  1728. {
  1729. Message += L"\n\n" + FMTLOAD(LOGIN_PUBLIC_KEY_PERMISSIONS, (AuthorizedKeysFilePath));
  1730. }
  1731. MessageDialog(Message, qtInformation, qaOK, HELP_LOGIN_AUTHORIZED_KEYS);
  1732. }
  1733. return Result;
  1734. }