TerminalManager.cpp 56 KB

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