TerminalManager.cpp 58 KB

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