TerminalManager.cpp 58 KB

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