1
0

TerminalManager.cpp 66 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059
  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 __fastcall TTerminalManager::SetScpExplorer(TCustomScpExplorerForm * value)
  620. {
  621. if (ScpExplorer != value)
  622. {
  623. // changing explorer is not supported yet
  624. DebugAssert(!ScpExplorer || !value);
  625. FScpExplorer = value;
  626. if (FScpExplorer)
  627. {
  628. FScpExplorer->ManagedSession = ActiveTerminal;
  629. FScpExplorer->Queue = ActiveQueue;
  630. UpdateTaskbarList();
  631. }
  632. }
  633. }
  634. //---------------------------------------------------------------------------
  635. TManagedTerminal * TTerminalManager::GetActiveTerminal()
  636. {
  637. TManagedTerminal * Result;
  638. if ((ActiveSession != NULL) && !ActiveSession->LocalBrowser)
  639. {
  640. Result = ActiveSession;
  641. }
  642. else
  643. {
  644. Result = NULL;
  645. }
  646. return Result;
  647. }
  648. //---------------------------------------------------------------------------
  649. void __fastcall TTerminalManager::SetActiveSession(TManagedTerminal * value)
  650. {
  651. DoSetActiveSession(value, false, false);
  652. }
  653. //---------------------------------------------------------------------------
  654. void __fastcall TTerminalManager::SetActiveTerminalWithAutoReconnect(TManagedTerminal * value)
  655. {
  656. DoSetActiveSession(value, true, false);
  657. }
  658. //---------------------------------------------------------------------------
  659. void __fastcall TTerminalManager::DoSetActiveSession(TManagedTerminal * value, bool AutoReconnect, bool LastTerminalClosed)
  660. {
  661. if (ActiveSession != value)
  662. {
  663. // here used to be call to TCustomScpExporer::UpdateSessionData (now UpdateSession)
  664. // but it seems to be duplicate to call from TCustomScpExporer::SessionChanging
  665. TManagedTerminal * PActiveSession = ActiveSession;
  666. FActiveSession = value;
  667. if (ScpExplorer)
  668. {
  669. if ((ActiveSession != NULL) &&
  670. ((ActiveSession->Status == ssOpened) || ActiveSession->Disconnected || ActiveSession->LocalBrowser))
  671. {
  672. SessionReady();
  673. }
  674. else
  675. {
  676. ScpExplorer->ManagedSession = NULL;
  677. ScpExplorer->Queue = NULL;
  678. }
  679. }
  680. UpdateAppTitle();
  681. if (PActiveSession != NULL)
  682. {
  683. if (PActiveSession->DisconnectedTemporarily && DebugAlwaysTrue(PActiveSession->Disconnected))
  684. {
  685. PActiveSession->Disconnected = false;
  686. PActiveSession->DisconnectedTemporarily = false;
  687. }
  688. if (!PActiveSession->Active)
  689. {
  690. SaveTerminal(PActiveSession);
  691. }
  692. }
  693. if (ActiveSession != NULL)
  694. {
  695. int Index = ActiveSessionIndex;
  696. if (!ActiveSession->Active && !FTerminationMessages->Strings[Index].IsEmpty())
  697. {
  698. UnicodeString Message = FTerminationMessages->Strings[Index];
  699. FTerminationMessages->Strings[Index] = L"";
  700. if (AutoReconnect)
  701. {
  702. ReconnectActiveTerminal();
  703. }
  704. else
  705. {
  706. Exception * E = new ESshFatal(NULL, Message);
  707. try
  708. {
  709. // finally show pending terminal message,
  710. // this gives user also possibility to reconnect
  711. ActiveTerminal->ShowExtendedException(E);
  712. }
  713. __finally
  714. {
  715. delete E;
  716. }
  717. }
  718. }
  719. // LastTerminalClosed is true only for a replacement local session,
  720. // and it should never happen that it fails to be activated
  721. if (LastTerminalClosed && DebugAlwaysFalse(value != ActiveSession))
  722. {
  723. LastTerminalClosed = false; // just in case
  724. }
  725. }
  726. else
  727. {
  728. LastTerminalClosed = true;
  729. }
  730. if (LastTerminalClosed && !Updating && (ScpExplorer != NULL))
  731. {
  732. ScpExplorer->LastTerminalClosed();
  733. }
  734. if ((ActiveSession != NULL) &&
  735. !ActiveSession->Active && !ActiveSession->Disconnected && !ActiveSession->LocalBrowser)
  736. {
  737. ConnectActiveTerminal();
  738. }
  739. }
  740. }
  741. //---------------------------------------------------------------------------
  742. void __fastcall TTerminalManager::QueueStatusUpdated()
  743. {
  744. UpdateAppTitle();
  745. }
  746. //---------------------------------------------------------------------------
  747. bool __fastcall TTerminalManager::ShouldDisplayQueueStatusOnAppTitle()
  748. {
  749. bool Result = IsApplicationMinimized();
  750. if (!Result && (ScpExplorer != NULL))
  751. {
  752. HWND Window = GetActiveWindow();
  753. Window = GetAncestor(Window, GA_ROOTOWNER);
  754. Result = (ScpExplorer->Handle != Window);
  755. }
  756. return Result;
  757. }
  758. //---------------------------------------------------------------------------
  759. UnicodeString __fastcall TTerminalManager::FormatFormCaptionWithSession(TCustomForm * Form, const UnicodeString & Caption)
  760. {
  761. return FormatFormCaption(Form, Caption, GetActiveSessionAppTitle());
  762. }
  763. //---------------------------------------------------------------------------
  764. UnicodeString __fastcall TTerminalManager::GetAppProgressTitle()
  765. {
  766. UnicodeString Result;
  767. UnicodeString QueueProgressTitle;
  768. UnicodeString ProgressTitle = !FProgressTitle.IsEmpty() ? FProgressTitle : ScpExplorer->GetProgressTitle();
  769. if (!FForegroundProgressTitle.IsEmpty())
  770. {
  771. Result = FForegroundProgressTitle;
  772. }
  773. else if (!ProgressTitle.IsEmpty() && !ForegroundTask())
  774. {
  775. Result = ProgressTitle;
  776. }
  777. else if (ShouldDisplayQueueStatusOnAppTitle() &&
  778. !(QueueProgressTitle = ScpExplorer->GetQueueProgressTitle()).IsEmpty())
  779. {
  780. Result = QueueProgressTitle;
  781. }
  782. return Result;
  783. }
  784. //---------------------------------------------------------------------------
  785. void __fastcall TTerminalManager::UpdateAppTitle()
  786. {
  787. if (ScpExplorer)
  788. {
  789. TForm * MainForm = GetMainForm();
  790. if (MainForm != ScpExplorer)
  791. {
  792. // triggers caption update for some forms
  793. MainForm->Perform(WM_MANAGES_CAPTION, 0, 0);
  794. }
  795. UnicodeString NewTitle = FormatMainFormCaption(GetActiveSessionAppTitle());
  796. UnicodeString ProgressTitle = GetAppProgressTitle();
  797. if (!ProgressTitle.IsEmpty())
  798. {
  799. NewTitle = ProgressTitle + L" - " + NewTitle;
  800. }
  801. else if (ScpExplorer != NULL)
  802. {
  803. UnicodeString Path = ScpExplorer->PathForCaption();
  804. if (!Path.IsEmpty())
  805. {
  806. NewTitle = Path + L" - " + NewTitle;
  807. }
  808. }
  809. // Not updating MainForm here, as for all other possible main forms, this code is actually not what we want.
  810. // And they all update their title on their own (some using GetAppProgressTitle()).
  811. ScpExplorer->Caption = NewTitle;
  812. ScpExplorer->ApplicationTitleChanged();
  813. }
  814. }
  815. //---------------------------------------------------------------------------
  816. void __fastcall TTerminalManager::SaveTerminal(TTerminal * Terminal)
  817. {
  818. TSessionData * Data = StoredSessions->FindSame(Terminal->SessionData);
  819. if (Data != NULL)
  820. {
  821. TManagedTerminal * ManagedTerminal = dynamic_cast<TManagedTerminal *>(Terminal);
  822. DebugAssert(ManagedTerminal != NULL);
  823. bool Changed = false;
  824. if (Terminal->SessionData->UpdateDirectories)
  825. {
  826. Data->CopyDirectoriesStateData(ManagedTerminal->StateData);
  827. Changed = true;
  828. }
  829. if (Changed)
  830. {
  831. // modified only, implicit
  832. StoredSessions->Save(false, false);
  833. }
  834. }
  835. }
  836. //---------------------------------------------------------------------------
  837. void __fastcall TTerminalManager::HandleException(Exception * E)
  838. {
  839. // can be null for example when exception is thrown on login dialog
  840. if (ActiveTerminal != NULL)
  841. {
  842. ActiveTerminal->ShowExtendedException(E);
  843. }
  844. else
  845. {
  846. ShowExtendedException(E);
  847. }
  848. }
  849. //---------------------------------------------------------------------------
  850. void __fastcall TTerminalManager::ApplicationException(TObject * /*Sender*/,
  851. Exception * E)
  852. {
  853. HandleException(E);
  854. }
  855. //---------------------------------------------------------------------------
  856. void __fastcall TTerminalManager::ApplicationShowHint(UnicodeString & HintStr,
  857. bool & /*CanShow*/, THintInfo & HintInfo)
  858. {
  859. HintInfo.HintData = HintInfo.HintControl;
  860. if (HasLabelHintPopup(HintInfo.HintControl, HintStr))
  861. {
  862. // Hack for transfer setting labels.
  863. // Should be converted to something like HintLabel()
  864. HintInfo.HideTimeout = 100000; // "almost" never
  865. }
  866. else if (dynamic_cast<TProgressBar *>(HintInfo.HintControl) != NULL)
  867. {
  868. // Hint is forcibly hidden in TProgressForm::FormHide
  869. HintInfo.HideTimeout = 100000; // "almost" never
  870. HintInfo.ReshowTimeout = 500; // updated each 0.5s
  871. }
  872. else
  873. {
  874. int HintMaxWidth = 300;
  875. TControl * ScaleControl = HintInfo.HintControl;
  876. if (DebugAlwaysFalse(HintInfo.HintControl == NULL) ||
  877. (GetParentForm(HintInfo.HintControl) == NULL))
  878. {
  879. ScaleControl = ScpExplorer;
  880. }
  881. HintMaxWidth = ScaleByTextHeight(ScaleControl, HintMaxWidth);
  882. HintInfo.HintMaxWidth = HintMaxWidth;
  883. }
  884. }
  885. //---------------------------------------------------------------------------
  886. bool __fastcall TTerminalManager::HandleMouseWheel(WPARAM WParam, LPARAM LParam)
  887. {
  888. // WORKAROUND This is no longer necessary on Windows 10 (except for WM_WANTS_MOUSEWHEEL_INACTIVE part)
  889. bool Result = false;
  890. if (Application->Active)
  891. {
  892. TPoint Point(LOWORD(LParam), HIWORD(LParam));
  893. TWinControl * Control = FindVCLWindow(Point);
  894. if (Control != NULL)
  895. {
  896. TCustomForm * Form = GetParentForm(Control);
  897. // Only case we expect the parent form to be NULL is on the Find/Replace dialog,
  898. // which is owned by VCL's internal TRedirectorWindow.
  899. DebugAssert((Form != NULL) || (Control->ClassName() == L"TRedirectorWindow"));
  900. if (Form != NULL)
  901. {
  902. // Send it only to windows we tested it with.
  903. // Though we should sooner or later remove this test and pass it to all our windows.
  904. if (Form->Active && (Form->Perform(WM_WANTS_MOUSEWHEEL, 0, 0) == 1))
  905. {
  906. SendMessage(Control->Handle, WM_MOUSEWHEEL, WParam, LParam);
  907. Result = true;
  908. }
  909. else if (!Form->Active && (Form->Perform(WM_WANTS_MOUSEWHEEL_INACTIVE, 0, 0) == 1))
  910. {
  911. TWinControl * Control2;
  912. // FindVCLWindow stops on window level, when the window is not active? or when there's a modal window over it?
  913. // (but in any case, when we have operation running on top of Synchronization checklist).
  914. // WORKAROUND: The while loop does what AllLevels parameter of ControlAtPos should do, but it's broken.
  915. // Based on (now removed) Embarcadero QC 82143.
  916. while ((Control2 = dynamic_cast<TWinControl *>(Control->ControlAtPos(Control->ScreenToClient(Point), false, true))) != NULL)
  917. {
  918. Control = Control2;
  919. }
  920. SendMessage(Control->Handle, WM_MOUSEWHEEL, WParam, LParam);
  921. Result = true;
  922. }
  923. }
  924. }
  925. }
  926. return Result;
  927. }
  928. //---------------------------------------------------------------------------
  929. void __fastcall TTerminalManager::ApplicationMessage(TMsg & Msg, bool & Handled)
  930. {
  931. if (Msg.message == FTaskbarButtonCreatedMessage)
  932. {
  933. CreateTaskbarList();
  934. }
  935. if (Msg.message == WM_MOUSEWHEEL)
  936. {
  937. Handled = HandleMouseWheel(Msg.wParam, Msg.lParam);
  938. }
  939. }
  940. //---------------------------------------------------------------------------
  941. void __fastcall TTerminalManager::ApplicationModalBegin(TObject * /*Sender*/)
  942. {
  943. InterfaceStartDontMeasure();
  944. NonVisualDataModule->StartBusy();
  945. if (ScpExplorer != NULL)
  946. {
  947. ScpExplorer->SuspendWindowLock();
  948. }
  949. }
  950. //---------------------------------------------------------------------------
  951. void __fastcall TTerminalManager::ApplicationModalEnd(TObject * /*Sender*/)
  952. {
  953. NonVisualDataModule->EndBusy();
  954. if (ScpExplorer != NULL)
  955. {
  956. ScpExplorer->ResumeWindowLock();
  957. }
  958. }
  959. //---------------------------------------------------------------------------
  960. void __fastcall TTerminalManager::InitTaskbarButtonCreatedMessage()
  961. {
  962. // XE6 VCL already handles TaskbarButtonCreated, but does not call ChangeWindowMessageFilterEx.
  963. // So we keep our implementation.
  964. // See also https://stackoverflow.com/q/14614823/850848#14618587
  965. FTaskbarButtonCreatedMessage = RegisterWindowMessage(L"TaskbarButtonCreated");
  966. HINSTANCE User32Library = LoadLibrary(L"user32.dll");
  967. ChangeWindowMessageFilterExProc ChangeWindowMessageFilterEx =
  968. (ChangeWindowMessageFilterExProc)GetProcAddress(User32Library, "ChangeWindowMessageFilterEx");
  969. if (ChangeWindowMessageFilterEx != NULL)
  970. {
  971. // without this we won't get TaskbarButtonCreated, when app is running elevated
  972. ChangeWindowMessageFilterEx(
  973. Application->Handle, FTaskbarButtonCreatedMessage, MSGFLT_ALLOW, NULL);
  974. }
  975. }
  976. //---------------------------------------------------------------------------
  977. void __fastcall TTerminalManager::CreateTaskbarList()
  978. {
  979. ReleaseTaskbarList();
  980. if(SUCCEEDED(CoCreateInstance(CLSID_TaskbarList, NULL, CLSCTX_ALL,
  981. IID_ITaskbarList3, (void **) &FTaskbarList)))
  982. {
  983. if (ScpExplorer != NULL)
  984. {
  985. UpdateTaskbarList();
  986. }
  987. }
  988. }
  989. //---------------------------------------------------------------------------
  990. void __fastcall TTerminalManager::ReleaseTaskbarList()
  991. {
  992. if (FTaskbarList != NULL)
  993. {
  994. FTaskbarList->Release();
  995. }
  996. }
  997. //---------------------------------------------------------------------------
  998. void __fastcall TTerminalManager::UpdateTaskbarList()
  999. {
  1000. ScpExplorer->UpdateTaskbarList(FTaskbarList);
  1001. }
  1002. //---------------------------------------------------------------------------
  1003. void __fastcall TTerminalManager::DeleteLocalFile(const UnicodeString FileName, bool Alternative, int & Deleted)
  1004. {
  1005. Deleted = RecursiveDeleteFileChecked(FileName, (WinConfiguration->DeleteToRecycleBin != Alternative));
  1006. }
  1007. //---------------------------------------------------------------------------
  1008. void __fastcall TTerminalManager::TerminalQueryUser(TObject * Sender,
  1009. const UnicodeString Query, TStrings * MoreMessages, unsigned int Answers,
  1010. const TQueryParams * Params, unsigned int & Answer, TQueryType Type, void * /*Arg*/)
  1011. {
  1012. UnicodeString HelpKeyword;
  1013. TMessageParams MessageParams(Params);
  1014. UnicodeString AQuery = Query;
  1015. if (Params != NULL)
  1016. {
  1017. HelpKeyword = Params->HelpKeyword;
  1018. if (FLAGSET(Params->Params, qpFatalAbort))
  1019. {
  1020. AQuery = FMTLOAD(WARN_FATAL_ERROR, (AQuery));
  1021. if (!MessageParams.TimerMessage.IsEmpty())
  1022. {
  1023. MessageParams.TimerMessage = FMTLOAD(WARN_FATAL_ERROR, (MessageParams.TimerMessage));
  1024. }
  1025. }
  1026. }
  1027. if (ScpExplorer)
  1028. {
  1029. Answer = ScpExplorer->MoreMessageDialog(AQuery, MoreMessages, Type, Answers,
  1030. HelpKeyword, &MessageParams, dynamic_cast<TTerminal *>(Sender));
  1031. }
  1032. else
  1033. {
  1034. Answer = MoreMessageDialog(AQuery, MoreMessages, Type, Answers, HelpKeyword,
  1035. &MessageParams);
  1036. }
  1037. }
  1038. //---------------------------------------------------------------------------
  1039. void __fastcall TTerminalManager::AuthenticateFormCancel(TObject * Sender)
  1040. {
  1041. TAuthenticateForm * Form = dynamic_cast<TAuthenticateForm *>(Sender);
  1042. DebugAssert(Form != NULL);
  1043. TManagedTerminal * ManagedTerminal = dynamic_cast<TManagedTerminal *>(Form->Terminal);
  1044. // will be null e.g. for background transfers
  1045. if (ManagedTerminal != NULL)
  1046. {
  1047. TTerminalThread * TerminalThread = ManagedTerminal->TerminalThread;
  1048. // can be NULL for reconnects from transfers
  1049. if ((TerminalThread != NULL) && !TerminalThread->Cancelling)
  1050. {
  1051. Form->Log(LoadStr(AUTH_CANCELLING));
  1052. TerminalThread->Cancel();
  1053. }
  1054. }
  1055. FAuthenticationCancelled = true;
  1056. }
  1057. //---------------------------------------------------------------------------
  1058. TAuthenticateForm * __fastcall TTerminalManager::MakeAuthenticateForm(
  1059. TTerminal * Terminal)
  1060. {
  1061. TAuthenticateForm * Dialog = SafeFormCreate<TAuthenticateForm>();
  1062. Dialog->Init(Terminal);
  1063. DebugAssert(Dialog->OnCancel == NULL);
  1064. Dialog->OnCancel = AuthenticateFormCancel;
  1065. return Dialog;
  1066. }
  1067. //---------------------------------------------------------------------------
  1068. void __fastcall TTerminalManager::FileNameInputDialogInitializeRenameBaseName(
  1069. TObject * /*Sender*/, TInputDialogData * Data)
  1070. {
  1071. EditSelectBaseName(Data->Edit->Handle);
  1072. }
  1073. //---------------------------------------------------------------------------
  1074. void __fastcall TTerminalManager::TerminalPromptUser(
  1075. TTerminal * Terminal, TPromptKind Kind, UnicodeString Name, UnicodeString Instructions,
  1076. TStrings * Prompts, TStrings * Results, bool & Result, void * /*Arg*/)
  1077. {
  1078. if (((Kind == pkPrompt) || (Kind == pkFileName)) && (FAuthenticateForm == NULL) &&
  1079. (Terminal->Status != ssOpening))
  1080. {
  1081. DebugAssert(Instructions.IsEmpty());
  1082. DebugAssert(Prompts->Count == 1);
  1083. DebugAssert(FLAGSET(int(Prompts->Objects[0]), pupEcho));
  1084. UnicodeString AResult = Results->Strings[0];
  1085. TInputDialogInitialize InputDialogInitialize = NULL;
  1086. if ((Kind == pkFileName) && !WinConfiguration->RenameWholeName)
  1087. {
  1088. InputDialogInitialize = FileNameInputDialogInitializeRenameBaseName;
  1089. }
  1090. Result = InputDialog(Name, Prompts->Strings[0], AResult, L"", NULL, false, InputDialogInitialize);
  1091. if (Result)
  1092. {
  1093. Results->Strings[0] = AResult;
  1094. }
  1095. }
  1096. else
  1097. {
  1098. TAuthenticateForm * AuthenticateForm = FAuthenticateForm;
  1099. if (AuthenticateForm == NULL)
  1100. {
  1101. AuthenticateForm = MakeAuthenticateForm(Terminal);
  1102. }
  1103. try
  1104. {
  1105. Result = AuthenticateForm->PromptUser(Kind, Name, Instructions, Prompts, Results,
  1106. (FAuthenticateForm != NULL), Terminal->StoredCredentialsTried);
  1107. }
  1108. __finally
  1109. {
  1110. if (FAuthenticateForm == NULL)
  1111. {
  1112. delete AuthenticateForm;
  1113. }
  1114. }
  1115. }
  1116. }
  1117. //---------------------------------------------------------------------------
  1118. void __fastcall TTerminalManager::TerminalDisplayBanner(
  1119. TTerminal * Terminal, UnicodeString SessionName,
  1120. const UnicodeString & Banner, bool & NeverShowAgain, int Options, unsigned int & Params)
  1121. {
  1122. DebugAssert(FAuthenticateForm != NULL);
  1123. TAuthenticateForm * AuthenticateForm = FAuthenticateForm;
  1124. if (AuthenticateForm == NULL)
  1125. {
  1126. AuthenticateForm = MakeAuthenticateForm(Terminal);
  1127. }
  1128. try
  1129. {
  1130. AuthenticateForm->Banner(Banner, NeverShowAgain, Options, Params);
  1131. }
  1132. __finally
  1133. {
  1134. if (FAuthenticateForm == NULL)
  1135. {
  1136. delete AuthenticateForm;
  1137. }
  1138. }
  1139. }
  1140. //---------------------------------------------------------------------------
  1141. void __fastcall TTerminalManager::TerminalShowExtendedException(
  1142. TTerminal * Terminal, Exception * E, void * /*Arg*/)
  1143. {
  1144. if (ScpExplorer)
  1145. {
  1146. ScpExplorer->ShowExtendedException(Terminal, E);
  1147. }
  1148. else
  1149. {
  1150. ShowExtendedExceptionEx(Terminal, E);
  1151. }
  1152. }
  1153. //---------------------------------------------------------------------------
  1154. static TDateTime DirectoryReadingProgressDelay(0, 0, 1, 500);
  1155. //---------------------------------------------------------------------------
  1156. void __fastcall TTerminalManager::TerminalReadDirectoryProgress(
  1157. TObject * /*Sender*/, int Progress, int ResolvedLinks, bool & Cancel)
  1158. {
  1159. if (Progress == 0)
  1160. {
  1161. if (ScpExplorer != NULL)
  1162. {
  1163. // See also TCustomScpExplorerForm::RemoteDirViewBusy
  1164. ScpExplorer->LockWindow();
  1165. }
  1166. FDirectoryReadingStart = Now();
  1167. if (!FProgressTitle.IsEmpty() || !FForegroundProgressTitle.IsEmpty())
  1168. {
  1169. FProgressTitle = L"";
  1170. FForegroundProgressTitle = L"";
  1171. UpdateAppTitle();
  1172. }
  1173. // Reset "was ESC ever pressed?" state
  1174. GetAsyncKeyState(VK_ESCAPE);
  1175. }
  1176. else if (Progress < 0)
  1177. {
  1178. if (Progress == -2)
  1179. {
  1180. // cancelled
  1181. if (ScpExplorer != NULL)
  1182. {
  1183. ScpExplorer->ReadDirectoryCancelled();
  1184. }
  1185. }
  1186. else
  1187. {
  1188. if (ScpExplorer != NULL)
  1189. {
  1190. ScpExplorer->UnlockWindow();
  1191. }
  1192. FProgressTitle = L"";
  1193. FForegroundProgressTitle = L"";
  1194. UpdateAppTitle();
  1195. }
  1196. }
  1197. else
  1198. {
  1199. // If the least significant bit is set,
  1200. // the key was pressed after the previous call to GetAsyncKeyState.
  1201. int KeyState = GetAsyncKeyState(VK_ESCAPE);
  1202. if (FLAGSET(KeyState, 0x01))
  1203. {
  1204. Cancel = true;
  1205. }
  1206. if ((Now() - FDirectoryReadingStart) >= DirectoryReadingProgressDelay)
  1207. {
  1208. // 4 is arbitrary number
  1209. FForegroundProgressTitle =
  1210. FMTLOAD(ResolvedLinks >= 4 ? DIRECTORY_READING_AND_RESOLVING_PROGRESS : DIRECTORY_READING_PROGRESS,
  1211. (Progress));
  1212. UpdateAppTitle();
  1213. }
  1214. }
  1215. }
  1216. //---------------------------------------------------------------------------
  1217. void __fastcall TTerminalManager::TerminalCustomCommand(
  1218. TTerminal * /*Terminal*/, const UnicodeString & Command, bool & Handled)
  1219. {
  1220. // Implementation has to be thread-safe
  1221. Handled = CopyCommandToClipboard(Command);
  1222. }
  1223. //---------------------------------------------------------------------------
  1224. void __fastcall TTerminalManager::AuthenticatingDone()
  1225. {
  1226. FAuthenticating--;
  1227. if (FAuthenticating == 0)
  1228. {
  1229. BusyEnd(FBusyToken);
  1230. FBusyToken = NULL;
  1231. }
  1232. if (!FKeepAuthenticateForm)
  1233. {
  1234. CloseAutheticateForm();
  1235. }
  1236. }
  1237. //---------------------------------------------------------------------------
  1238. void __fastcall TTerminalManager::TerminalInformation(
  1239. TTerminal * Terminal, const UnicodeString & Str, bool DebugUsedArg(Status), int Phase, const UnicodeString & Additional)
  1240. {
  1241. if (ScpExplorer != NULL)
  1242. {
  1243. ScpExplorer->TerminalConnecting();
  1244. }
  1245. if (Phase == 1)
  1246. {
  1247. if (FAuthenticating == 0)
  1248. {
  1249. FBusyToken = BusyStart();
  1250. }
  1251. FAuthenticating++;
  1252. }
  1253. else if (Phase == 0)
  1254. {
  1255. DebugAssert(FAuthenticating > 0);
  1256. AuthenticatingDone();
  1257. }
  1258. else
  1259. {
  1260. if (FAuthenticating > 0)
  1261. {
  1262. bool ShowPending = false;
  1263. if (FAuthenticateForm == NULL)
  1264. {
  1265. FAuthenticateForm = MakeAuthenticateForm(Terminal);
  1266. ShowPending = true;
  1267. }
  1268. FAuthenticateForm->Log(Str, Additional);
  1269. if (ShowPending)
  1270. {
  1271. FAuthenticateForm->ShowAsModal();
  1272. }
  1273. }
  1274. }
  1275. }
  1276. //---------------------------------------------------------------------------
  1277. void __fastcall TTerminalManager::OperationFinished(::TFileOperation Operation,
  1278. TOperationSide Side, bool Temp, const UnicodeString & FileName, bool Success,
  1279. TOnceDoneOperation & OnceDoneOperation)
  1280. {
  1281. DebugAssert(ScpExplorer);
  1282. ScpExplorer->OperationFinished(Operation, Side, Temp, FileName, Success,
  1283. OnceDoneOperation);
  1284. }
  1285. //---------------------------------------------------------------------------
  1286. void __fastcall TTerminalManager::OperationProgress(
  1287. TFileOperationProgressType & ProgressData)
  1288. {
  1289. UpdateAppTitle();
  1290. DebugAssert(ScpExplorer);
  1291. ScpExplorer->OperationProgress(ProgressData);
  1292. }
  1293. //---------------------------------------------------------------------------
  1294. void __fastcall TTerminalManager::QueueEvent(TTerminalQueue * Queue, TQueueEvent Event)
  1295. {
  1296. TGuard Guard(FQueueSection);
  1297. FQueueEvents.push_back(std::make_pair(Queue, Event));
  1298. }
  1299. //---------------------------------------------------------------------------
  1300. void __fastcall TTerminalManager::DoConfigurationChange()
  1301. {
  1302. DebugAssert(Configuration);
  1303. DebugAssert(Configuration == WinConfiguration);
  1304. TTerminalQueue * Queue;
  1305. for (int Index = 0; Index < Count; Index++)
  1306. {
  1307. DebugAssert(Sessions[Index]->Log);
  1308. Sessions[Index]->Log->ReflectSettings();
  1309. Sessions[Index]->ActionLog->ReflectSettings();
  1310. Queue = reinterpret_cast<TTerminalQueue *>(FQueues->Items[Index]);
  1311. SetQueueConfiguration(Queue);
  1312. }
  1313. if (ScpExplorer)
  1314. {
  1315. ScpExplorer->ConfigurationChanged();
  1316. }
  1317. }
  1318. //---------------------------------------------------------------------------
  1319. void __fastcall TTerminalManager::ConfigurationChange(TObject * /*Sender*/)
  1320. {
  1321. if (FMainThread == GetCurrentThreadId())
  1322. {
  1323. DoConfigurationChange();
  1324. }
  1325. else
  1326. {
  1327. TGuard Guard(FChangeSection.get());
  1328. FPendingConfigurationChange++;
  1329. }
  1330. }
  1331. //---------------------------------------------------------------------------
  1332. void __fastcall TTerminalManager::SessionReady()
  1333. {
  1334. ScpExplorer->ManagedSession = ActiveSession;
  1335. ScpExplorer->Queue = ActiveQueue;
  1336. ScpExplorer->SessionReady();
  1337. }
  1338. //---------------------------------------------------------------------------
  1339. TStrings * __fastcall TTerminalManager::GetSessionList()
  1340. {
  1341. FSessionList->Clear();
  1342. for (int i = 0; i < Count; i++)
  1343. {
  1344. TManagedTerminal * Terminal = Sessions[i];
  1345. UnicodeString Name = GetSessionTitle(Terminal, true);
  1346. FSessionList->AddObject(Name, Terminal);
  1347. }
  1348. return FSessionList;
  1349. }
  1350. //---------------------------------------------------------------------------
  1351. int __fastcall TTerminalManager::GetActiveSessionIndex()
  1352. {
  1353. return (ActiveSession != NULL) ? IndexOf(ActiveSession) : -1;
  1354. }
  1355. //---------------------------------------------------------------------------
  1356. void __fastcall TTerminalManager::SetActiveSessionIndex(int value)
  1357. {
  1358. ActiveSession = Sessions[value];
  1359. }
  1360. //---------------------------------------------------------------------------
  1361. UnicodeString TTerminalManager::GetPathForSessionTabName(const UnicodeString & Path)
  1362. {
  1363. UnicodeString Result = Path;
  1364. const int MaxPathLen = 16;
  1365. if ((WinConfiguration->SessionTabNameFormat == stnfShortPathTrunc) &&
  1366. (Result.Length() > MaxPathLen))
  1367. {
  1368. Result = Result.SubString(1, MaxPathLen - 2) + Ellipsis;
  1369. }
  1370. return Result;
  1371. }
  1372. //---------------------------------------------------------------------------
  1373. UnicodeString __fastcall TTerminalManager::GetSessionTitle(TManagedTerminal * Session, bool Unique)
  1374. {
  1375. UnicodeString Result;
  1376. if (!Session->LocalBrowser)
  1377. {
  1378. Result = Session->SessionData->SessionName;
  1379. if (Unique &&
  1380. (WinConfiguration->SessionTabNameFormat != stnfNone))
  1381. {
  1382. int Index = IndexOf(Session);
  1383. // not for background transfer sessions and disconnected sessions
  1384. if ((Index >= 0) && Session->Active)
  1385. {
  1386. for (int Index2 = 0; Index2 < Count; Index2++)
  1387. {
  1388. UnicodeString Name = Sessions[Index2]->SessionData->SessionName;
  1389. if ((Sessions[Index2] != Session) &&
  1390. Sessions[Index2]->Active &&
  1391. SameText(Name, Result))
  1392. {
  1393. UnicodeString Path = ExtractShortName(Session->CurrentDirectory, true);
  1394. if (!Path.IsEmpty())
  1395. {
  1396. Path = GetPathForSessionTabName(Path);
  1397. Result = FORMAT(L"%s (%s)", (Result, Path));
  1398. }
  1399. break;
  1400. }
  1401. }
  1402. }
  1403. }
  1404. }
  1405. else
  1406. {
  1407. // should happen only when closing
  1408. if (ScpExplorer != NULL)
  1409. {
  1410. Result = ScpExplorer->GetLocalBrowserSessionTitle(Session);
  1411. }
  1412. }
  1413. return Result;
  1414. }
  1415. //---------------------------------------------------------------------------
  1416. UnicodeString __fastcall TTerminalManager::GetActiveSessionAppTitle()
  1417. {
  1418. UnicodeString Result;
  1419. if ((ActiveSession != NULL) && !ActiveSession->LocalBrowser)
  1420. {
  1421. Result = GetSessionTitle(ActiveSession, false);
  1422. }
  1423. return Result;
  1424. }
  1425. //---------------------------------------------------------------------------
  1426. TTerminalQueue * __fastcall TTerminalManager::GetActiveQueue()
  1427. {
  1428. TTerminalQueue * Result = NULL;
  1429. if (ActiveSession != NULL)
  1430. {
  1431. Result = reinterpret_cast<TTerminalQueue *>(FQueues->Items[ActiveSessionIndex]);
  1432. }
  1433. return Result;
  1434. }
  1435. //---------------------------------------------------------------------------
  1436. void __fastcall TTerminalManager::CycleTerminals(bool Forward)
  1437. {
  1438. if (Count > 0)
  1439. {
  1440. int Index = ActiveSessionIndex;
  1441. Index += Forward ? 1 : -1;
  1442. if (Index < 0)
  1443. {
  1444. Index = Count-1;
  1445. }
  1446. else if (Index >= Count)
  1447. {
  1448. Index = 0;
  1449. }
  1450. ActiveSessionIndex = Index;
  1451. }
  1452. }
  1453. //---------------------------------------------------------------------------
  1454. bool __fastcall TTerminalManager::CanOpenInPutty()
  1455. {
  1456. return (ActiveTerminal != NULL) && !GUIConfiguration->PuttyPath.Trim().IsEmpty();
  1457. }
  1458. //---------------------------------------------------------------------------
  1459. void __fastcall TTerminalManager::OpenInPutty()
  1460. {
  1461. Configuration->Usage->Inc(L"OpenInPutty");
  1462. TSessionData * Data = NULL;
  1463. try
  1464. {
  1465. // Is NULL on the first session when called from ConnectActiveTerminal()
  1466. // due to WinConfiguration->AutoOpenInPutty
  1467. if (ScpExplorer != NULL)
  1468. {
  1469. Data = ScpExplorer->CloneCurrentSessionData();
  1470. }
  1471. else
  1472. {
  1473. Data = new TSessionData(L"");
  1474. DebugAssert(ActiveTerminal != NULL);
  1475. Data->Assign(ActiveTerminal->SessionData);
  1476. ActiveTerminal->UpdateSessionCredentials(Data);
  1477. }
  1478. // putty does not support resolving environment variables in session settings
  1479. Data->ExpandEnvironmentVariables();
  1480. if (ActiveTerminal->TunnelLocalPortNumber != 0)
  1481. {
  1482. Data->ConfigureTunnel(ActiveTerminal->TunnelLocalPortNumber);
  1483. }
  1484. OpenSessionInPutty(GUIConfiguration->PuttyPath, Data);
  1485. }
  1486. __finally
  1487. {
  1488. delete Data;
  1489. }
  1490. }
  1491. //---------------------------------------------------------------------------
  1492. void __fastcall TTerminalManager::NewSession(
  1493. const UnicodeString & SessionUrl, bool ReloadSessions, TForm * LinkedForm, bool ReplaceExisting)
  1494. {
  1495. if (ReloadSessions)
  1496. {
  1497. StoredSessions->Reload();
  1498. }
  1499. std::unique_ptr<TObjectList> DataList;
  1500. bool Retry;
  1501. do
  1502. {
  1503. Retry = false;
  1504. if (!DataList) // first round
  1505. {
  1506. DataList.reset(new TObjectList());
  1507. UnicodeString DownloadFile; // unused
  1508. GetLoginData(SessionUrl, NULL, DataList.get(), DownloadFile, true, LinkedForm);
  1509. }
  1510. else
  1511. {
  1512. if (!DoLoginDialog(DataList.get(), LinkedForm))
  1513. {
  1514. Abort(); // As GetLoginData would do
  1515. }
  1516. }
  1517. if (DataList->Count > 0)
  1518. {
  1519. if (ReplaceExisting)
  1520. {
  1521. // Tested for only the implicit Commanders' local browser
  1522. DebugAssert((Count == 0) || ((Count == 1) && Sessions[0]->LocalBrowser));
  1523. TAutoNestingCounter UpdatingCounter(FUpdating); // prevent tab flicker
  1524. FreeAll();
  1525. }
  1526. TManagedTerminal * ANewSession = NewSessions(DataList.get());
  1527. bool AdHoc = (DataList->Count == 1) && (StoredSessions->FindSame(reinterpret_cast<TSessionData *>(DataList->Items[0])) == NULL);
  1528. bool CanRetry = SessionUrl.IsEmpty() && AdHoc;
  1529. bool ShowLoginWhenNoSession = WinConfiguration->ShowLoginWhenNoSession;
  1530. if (CanRetry)
  1531. {
  1532. // we will show our own login dialog, so prevent opening an empty one
  1533. WinConfiguration->ShowLoginWhenNoSession = false;
  1534. }
  1535. try
  1536. {
  1537. ActiveSession = ANewSession;
  1538. }
  1539. __finally
  1540. {
  1541. if (CanRetry) // do not reset the value, unless really needed, as it can theoretically be changed meanwhile by the user
  1542. {
  1543. WinConfiguration->ShowLoginWhenNoSession = ShowLoginWhenNoSession;
  1544. }
  1545. }
  1546. Retry = CanRetry && (ActiveSession != ANewSession);
  1547. }
  1548. }
  1549. while (Retry);
  1550. }
  1551. //---------------------------------------------------------------------------
  1552. void __fastcall TTerminalManager::Idle(bool SkipCurrentTerminal)
  1553. {
  1554. if (FPendingConfigurationChange > 0) // optimization
  1555. {
  1556. bool Changed = false;
  1557. {
  1558. TGuard Guard(FChangeSection.get());
  1559. if (DebugAlwaysTrue(FPendingConfigurationChange > 0))
  1560. {
  1561. FPendingConfigurationChange--;
  1562. Changed = true;
  1563. }
  1564. }
  1565. if (Changed)
  1566. {
  1567. DoConfigurationChange();
  1568. }
  1569. }
  1570. for (int Index = 0; Index < Count; Index++)
  1571. {
  1572. TManagedTerminal * Terminal = Sessions[Index];
  1573. try
  1574. {
  1575. if (!SkipCurrentTerminal || (Terminal != ActiveTerminal))
  1576. {
  1577. // make sure Idle is called on the thread that runs the terminal
  1578. if (Terminal->TerminalThread != NULL)
  1579. {
  1580. Terminal->TerminalThread->Idle();
  1581. }
  1582. else
  1583. {
  1584. if (Terminal->Active)
  1585. {
  1586. Terminal->Idle();
  1587. }
  1588. }
  1589. if (Terminal->Active)
  1590. {
  1591. DebugAssert(Index < FQueues->Count);
  1592. if (Index < FQueues->Count)
  1593. {
  1594. reinterpret_cast<TTerminalQueue *>(FQueues->Items[Index])->Idle();
  1595. }
  1596. }
  1597. }
  1598. }
  1599. catch(Exception & E)
  1600. {
  1601. if (Terminal == ActiveTerminal)
  1602. {
  1603. // throw further, so that the exception is handled in proper place
  1604. // (particularly in broken-transfer reconnect handler, bug 72)
  1605. throw;
  1606. }
  1607. else
  1608. {
  1609. // we may not have inactive terminal, unless there is a explorer,
  1610. // also Idle is called from explorer anyway
  1611. DebugAssert(ScpExplorer != NULL);
  1612. if (ScpExplorer != NULL)
  1613. {
  1614. ScpExplorer->InactiveTerminalException(Terminal, &E);
  1615. }
  1616. if (!Terminal->Active)
  1617. {
  1618. // if session is lost, save the error message and rethrow it
  1619. // once the terminal gets activated
  1620. FTerminationMessages->Strings[Index] = E.Message;
  1621. }
  1622. }
  1623. }
  1624. }
  1625. TTerminalQueue * QueueWithEvent;
  1626. TQueueEvent QueueEvent;
  1627. do
  1628. {
  1629. QueueWithEvent = NULL;
  1630. {
  1631. TGuard Guard(FQueueSection);
  1632. if (!FQueueEvents.empty())
  1633. {
  1634. QueueWithEvent = FQueueEvents[0].first;
  1635. QueueEvent = FQueueEvents[0].second;
  1636. FQueueEvents.erase(FQueueEvents.begin());
  1637. }
  1638. }
  1639. if (QueueWithEvent != NULL)
  1640. {
  1641. int Index = FQueues->IndexOf(QueueWithEvent);
  1642. // the session may not exist anymore
  1643. if (Index >= 0)
  1644. {
  1645. TManagedTerminal * Terminal = Sessions[Index];
  1646. // we can hardly have a queue event without explorer
  1647. DebugAssert(ScpExplorer != NULL);
  1648. if (ScpExplorer != NULL)
  1649. {
  1650. ScpExplorer->QueueEvent(Terminal, QueueWithEvent, QueueEvent);
  1651. }
  1652. }
  1653. }
  1654. }
  1655. while (QueueWithEvent != NULL);
  1656. }
  1657. //---------------------------------------------------------------------------
  1658. void __fastcall TTerminalManager::MasterPasswordPrompt()
  1659. {
  1660. if (GetCurrentThreadId() == MainThreadID)
  1661. {
  1662. if (!DoMasterPasswordDialog())
  1663. {
  1664. Abort();
  1665. }
  1666. }
  1667. else
  1668. {
  1669. // this can happen only when we keep cancelling all master password prompts
  1670. // as long as the sessing finally connects (session password has to be
  1671. // explictly typed in), and background transfer is started
  1672. Abort();
  1673. }
  1674. }
  1675. //---------------------------------------------------------------------------
  1676. void __fastcall TTerminalManager::Move(TTerminal * Source, TTerminal * Target)
  1677. {
  1678. int SourceIndex = IndexOf(Source);
  1679. int TargetIndex = IndexOf(Target);
  1680. TTerminalList::Move(SourceIndex, TargetIndex);
  1681. FQueues->Move(SourceIndex, TargetIndex);
  1682. DoSessionListChanged();
  1683. // when there are indexed sessions with the same name,
  1684. // the index may change when reordering the sessions
  1685. UpdateAppTitle();
  1686. }
  1687. //---------------------------------------------------------------------------
  1688. void __fastcall TTerminalManager::DoSessionListChanged()
  1689. {
  1690. if ((FScpExplorer != NULL) && !Updating)
  1691. {
  1692. FScpExplorer->SessionListChanged();
  1693. }
  1694. }
  1695. //---------------------------------------------------------------------------
  1696. void __fastcall TTerminalManager::SaveWorkspace(TList * DataList)
  1697. {
  1698. for (int Index = 0; Index < Count; Index++)
  1699. {
  1700. TManagedTerminal * ManagedTerminal = Sessions[Index];
  1701. TSessionData * Data = StoredSessions->SaveWorkspaceData(ManagedTerminal->StateData, Index);
  1702. DataList->Add(Data);
  1703. }
  1704. }
  1705. //---------------------------------------------------------------------------
  1706. bool __fastcall TTerminalManager::IsActiveTerminalForSite(TTerminal * Terminal, TSessionData * Data)
  1707. {
  1708. bool Result = Terminal->Active;
  1709. if (Result)
  1710. {
  1711. std::unique_ptr<TSessionData> TerminalData(Terminal->SessionData->Clone());
  1712. Terminal->UpdateSessionCredentials(TerminalData.get());
  1713. Result = TerminalData->IsSameSite(Data);
  1714. }
  1715. return Result;
  1716. }
  1717. //---------------------------------------------------------------------------
  1718. TTerminal * __fastcall TTerminalManager::FindActiveTerminalForSite(TSessionData * Data)
  1719. {
  1720. TTerminal * Result = NULL;
  1721. for (int Index = 0; (Result == NULL) && (Index < Count); Index++)
  1722. {
  1723. TTerminal * Terminal = Sessions[Index];
  1724. if (IsActiveTerminalForSite(Terminal, Data))
  1725. {
  1726. Result = Terminal;
  1727. }
  1728. }
  1729. return Result;
  1730. }
  1731. //---------------------------------------------------------------------------
  1732. TTerminalQueue * __fastcall TTerminalManager::FindQueueForTerminal(TTerminal * Terminal)
  1733. {
  1734. int Index = IndexOf(Terminal);
  1735. return reinterpret_cast<TTerminalQueue *>(FQueues->Items[Index]);
  1736. }
  1737. //---------------------------------------------------------------------------
  1738. TRemoteFile * __fastcall TTerminalManager::CheckRights(
  1739. TTerminal * Terminal, const UnicodeString & EntryType, const UnicodeString & FileName, bool & WrongRights)
  1740. {
  1741. std::unique_ptr<TRemoteFile> FileOwner;
  1742. TRemoteFile * File;
  1743. try
  1744. {
  1745. Terminal->LogEvent(FORMAT(L"Checking %s \"%s\"...", (LowerCase(EntryType), FileName)));
  1746. Terminal->ReadFile(FileName, File);
  1747. FileOwner.reset(File);
  1748. int ForbiddenRights = TRights::rfGroupWrite | TRights::rfOtherWrite;
  1749. if ((File->Rights->Number & ForbiddenRights) != 0)
  1750. {
  1751. Terminal->LogEvent(FORMAT(L"%s \"%s\" exists, but has incorrect permissions %s.", (EntryType, FileName, File->Rights->Octal)));
  1752. WrongRights = true;
  1753. }
  1754. else
  1755. {
  1756. Terminal->LogEvent(FORMAT(L"%s \"%s\" exists and has correct permissions %s.", (EntryType, FileName, File->Rights->Octal)));
  1757. }
  1758. }
  1759. catch (Exception & E)
  1760. {
  1761. }
  1762. return FileOwner.release();
  1763. }
  1764. //---------------------------------------------------------------------------
  1765. bool __fastcall TTerminalManager::UploadPublicKey(
  1766. TTerminal * Terminal, TSessionData * Data, UnicodeString & FileName)
  1767. {
  1768. std::unique_ptr<TOpenDialog> OpenDialog(new TOpenDialog(Application));
  1769. OpenDialog->Title = LoadStr(LOGIN_PUBLIC_KEY_TITLE);
  1770. OpenDialog->Filter = LoadStr(LOGIN_PUBLIC_KEY_FILTER);
  1771. OpenDialog->DefaultExt = PuttyKeyExt;
  1772. OpenDialog->FileName = FileName;
  1773. bool Result = OpenDialog->Execute();
  1774. if (Result)
  1775. {
  1776. Configuration->Usage->Inc(L"PublicKeyInstallation");
  1777. FileName = OpenDialog->FileName;
  1778. bool AutoReadDirectory;
  1779. bool ExceptionOnFail;
  1780. UnicodeString TemporaryDir;
  1781. const UnicodeString SshFolder = L".ssh";
  1782. const UnicodeString AuthorizedKeysFile = L"authorized_keys";
  1783. UnicodeString AuthorizedKeysFilePath = FORMAT(L"%s/%s", (SshFolder, AuthorizedKeysFile));
  1784. VerifyAndConvertKey(FileName, ssh2only, false);
  1785. UnicodeString Comment;
  1786. UnicodeString Line = GetPublicKeyLine(FileName, Comment);
  1787. bool AdHocTerminal = (Terminal == NULL);
  1788. std::unique_ptr<TTerminal> TerminalOwner;
  1789. if (AdHocTerminal)
  1790. {
  1791. DebugAssert(Data != NULL);
  1792. TAutoFlag KeepAuthenticateFormFlag(FKeepAuthenticateForm);
  1793. try
  1794. {
  1795. TerminalOwner.reset(CreateTerminal(Data));
  1796. Terminal = TerminalOwner.get();
  1797. SetupTerminal(Terminal);
  1798. Terminal->OnProgress = NULL;
  1799. Terminal->OnFinished = NULL;
  1800. DoConnectTerminal(Terminal, false, true);
  1801. }
  1802. catch (Exception & E)
  1803. {
  1804. CloseAutheticateForm();
  1805. throw;
  1806. }
  1807. }
  1808. bool Installed = false;
  1809. bool WrongRights = false;
  1810. AutoReadDirectory = Terminal->AutoReadDirectory;
  1811. ExceptionOnFail = Terminal->ExceptionOnFail;
  1812. try
  1813. {
  1814. Terminal->AutoReadDirectory = false;
  1815. Terminal->ExceptionOnFail = true;
  1816. UnicodeString SshImplementation = Terminal->GetSessionInfo().SshImplementation;
  1817. UnicodeString NotOpenSSHMessage = FMTLOAD(LOGIN_NOT_OPENSSH, (SshImplementation));
  1818. if (IsOpenSSH(SshImplementation) ||
  1819. (MessageDialog(NotOpenSSHMessage, qtConfirmation, qaOK | qaCancel, HELP_LOGIN_AUTHORIZED_KEYS) == qaOK))
  1820. {
  1821. Terminal->Log->AddSeparator();
  1822. Terminal->LogEvent(FORMAT(L"Adding public key line to \"%s\" file:\n%s", (AuthorizedKeysFilePath, Line)));
  1823. // Ad-hoc terminal
  1824. if (FAuthenticateForm != NULL)
  1825. {
  1826. FAuthenticateForm->Log(FMTLOAD(LOGIN_PUBLIC_KEY_UPLOAD, (Comment)));
  1827. }
  1828. UnicodeString SshFolderAbsolutePath = UnixIncludeTrailingBackslash(Terminal->GetHomeDirectory()) + SshFolder;
  1829. std::unique_ptr<TRemoteFile> SshFolderFile(CheckRights(Terminal, L"Folder", SshFolderAbsolutePath, WrongRights));
  1830. if (SshFolderFile.get() == NULL)
  1831. {
  1832. TRights SshFolderRights;
  1833. SshFolderRights.Number = TRights::rfUserRead | TRights::rfUserWrite | TRights::rfUserExec;
  1834. TRemoteProperties SshFolderProperties;
  1835. SshFolderProperties.Rights = SshFolderRights;
  1836. SshFolderProperties.Valid = TValidProperties() << vpRights;
  1837. Terminal->LogEvent(FORMAT(L"Trying to create \"%s\" folder with permissions %s...", (SshFolder, SshFolderRights.Octal)));
  1838. Terminal->CreateDirectory(SshFolderAbsolutePath, &SshFolderProperties);
  1839. }
  1840. TemporaryDir = ExcludeTrailingBackslash(WinConfiguration->TemporaryDir());
  1841. if (!ForceDirectories(ApiPath(TemporaryDir)))
  1842. {
  1843. throw EOSExtException(FMTLOAD(CREATE_TEMP_DIR_ERROR, (TemporaryDir)));
  1844. }
  1845. UnicodeString TemporaryAuthorizedKeysFile = IncludeTrailingBackslash(TemporaryDir) + AuthorizedKeysFile;
  1846. UnicodeString AuthorizedKeysFileAbsolutePath = UnixIncludeTrailingBackslash(SshFolderAbsolutePath) + AuthorizedKeysFile;
  1847. bool Updated = true;
  1848. TCopyParamType CopyParam; // Use factory defaults
  1849. CopyParam.ResumeSupport = rsOff; // not to break the permissions
  1850. CopyParam.PreserveTime = false; // not needed
  1851. UnicodeString AuthorizedKeys;
  1852. std::unique_ptr<TRemoteFile> AuthorizedKeysFileFile(CheckRights(Terminal, L"File", AuthorizedKeysFileAbsolutePath, WrongRights));
  1853. if (AuthorizedKeysFileFile.get() != NULL)
  1854. {
  1855. AuthorizedKeysFileFile->FullFileName = AuthorizedKeysFileAbsolutePath;
  1856. std::unique_ptr<TStrings> Files(new TStringList());
  1857. Files->AddObject(AuthorizedKeysFileAbsolutePath, AuthorizedKeysFileFile.get());
  1858. Terminal->LogEvent(FORMAT(L"Downloading current \"%s\" file...", (AuthorizedKeysFile)));
  1859. Terminal->CopyToLocal(Files.get(), TemporaryDir, &CopyParam, cpNoConfirmation, NULL);
  1860. // Overload with Encoding parameter work incorrectly, when used on a file without BOM
  1861. AuthorizedKeys = TFile::ReadAllText(TemporaryAuthorizedKeysFile);
  1862. std::unique_ptr<TStrings> AuthorizedKeysLines(TextToStringList(AuthorizedKeys));
  1863. int P = Line.Pos(L" ");
  1864. if (DebugAlwaysTrue(P > 0))
  1865. {
  1866. P = PosEx(L" ", Line, P + 1);
  1867. }
  1868. UnicodeString Prefix = Line.SubString(1, P); // including the space
  1869. for (int Index = 0; Index < AuthorizedKeysLines->Count; Index++)
  1870. {
  1871. if (StartsStr(Prefix, AuthorizedKeysLines->Strings[Index]))
  1872. {
  1873. Terminal->LogEvent(FORMAT(L"\"%s\" file already contains public key line:\n%s", (AuthorizedKeysFile, AuthorizedKeysLines->Strings[Index])));
  1874. Updated = false;
  1875. }
  1876. }
  1877. if (Updated)
  1878. {
  1879. Terminal->LogEvent(FORMAT(L"\"%s\" file does not contain the public key line yet.", (AuthorizedKeysFile)));
  1880. if (!EndsStr(L"\n", AuthorizedKeys))
  1881. {
  1882. Terminal->LogEvent(FORMAT(L"Adding missing trailing new line to \"%s\" file...", (AuthorizedKeysFile)));
  1883. AuthorizedKeys += L"\n";
  1884. }
  1885. }
  1886. }
  1887. else
  1888. {
  1889. Terminal->LogEvent(FORMAT(L"Creating new \"%s\" file...", (AuthorizedKeysFile)));
  1890. CopyParam.PreserveRights = true;
  1891. CopyParam.Rights.Number = TRights::rfUserRead | TRights::rfUserWrite;
  1892. }
  1893. if (Updated)
  1894. {
  1895. AuthorizedKeys += Line + L"\n";
  1896. // Overload without Encoding parameter uses TEncoding::UTF8, but does not write BOM, what we want
  1897. TFile::WriteAllText(TemporaryAuthorizedKeysFile, AuthorizedKeys);
  1898. std::unique_ptr<TStrings> Files(new TStringList());
  1899. Files->Add(TemporaryAuthorizedKeysFile);
  1900. Terminal->LogEvent(FORMAT(L"Uploading updated \"%s\" file...", (AuthorizedKeysFile)));
  1901. Terminal->CopyToRemote(Files.get(), SshFolderAbsolutePath, &CopyParam, cpNoConfirmation, NULL);
  1902. }
  1903. Installed = true;
  1904. }
  1905. }
  1906. __finally
  1907. {
  1908. Terminal->AutoReadDirectory = AutoReadDirectory;
  1909. Terminal->ExceptionOnFail = ExceptionOnFail;
  1910. if (!TemporaryDir.IsEmpty())
  1911. {
  1912. RecursiveDeleteFile(ExcludeTrailingBackslash(TemporaryDir), false);
  1913. }
  1914. CloseAutheticateForm(); // When uploading from Login dialog
  1915. }
  1916. if (Installed)
  1917. {
  1918. Terminal->LogEvent(L"Public key installation done.");
  1919. if (AdHocTerminal)
  1920. {
  1921. TerminalOwner.reset(NULL);
  1922. }
  1923. else
  1924. {
  1925. Terminal->Log->AddSeparator();
  1926. }
  1927. UnicodeString Message = FMTLOAD(LOGIN_PUBLIC_KEY_UPLOADED, (Comment));
  1928. if (WrongRights)
  1929. {
  1930. Message += L"\n\n" + FMTLOAD(LOGIN_PUBLIC_KEY_PERMISSIONS, (AuthorizedKeysFilePath));
  1931. }
  1932. MessageDialog(Message, qtInformation, qaOK, HELP_LOGIN_AUTHORIZED_KEYS);
  1933. }
  1934. }
  1935. return Result;
  1936. }
  1937. //---------------------------------------------------------------------------
  1938. bool TTerminalManager::IsUpdating()
  1939. {
  1940. return (FUpdating > 0);
  1941. }