TerminalManager.cpp 62 KB

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