TerminalManager.cpp 58 KB

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