TerminalManager.cpp 60 KB

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