TerminalManager.cpp 57 KB

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