TerminalManager.cpp 62 KB

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