TerminalManager.cpp 58 KB

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