1
0

TerminalManager.cpp 64 KB

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