TerminalManager.cpp 61 KB

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