TerminalManager.cpp 61 KB

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