TerminalManager.cpp 58 KB

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