1
0

TerminalManager.cpp 64 KB

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