TerminalManager.cpp 62 KB

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