TerminalManager.cpp 66 KB

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