ConsoleRunner.cpp 52 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817
  1. //---------------------------------------------------------------------------
  2. #include <vcl.h>
  3. #pragma hdrstop
  4. #include <Common.h>
  5. #include <Exceptions.h>
  6. #include <Script.h>
  7. #include <CoreMain.h>
  8. #include <Terminal.h>
  9. #include <PuttyTools.h>
  10. #include <Queue.h>
  11. #include <Consts.hpp>
  12. #include "Console.h"
  13. #include "WinInterface.h"
  14. #include "ProgParams.h"
  15. #include "TextsWin.h"
  16. #include "TextsCore.h"
  17. #include "WinConfiguration.h"
  18. #include "SynchronizeController.h"
  19. #include "GUITools.h"
  20. enum { RESULT_SUCCESS = 0, RESULT_ANY_ERROR = 1 };
  21. //---------------------------------------------------------------------------
  22. #define WM_INTERUPT_IDLE (WM_WINSCP_USER + 3)
  23. #define BATCH_INPUT_TIMEOUT 10000
  24. //---------------------------------------------------------------------------
  25. #pragma package(smart_init)
  26. //---------------------------------------------------------------------------
  27. class TConsole
  28. {
  29. public:
  30. virtual __fastcall ~TConsole() {};
  31. virtual void __fastcall Print(AnsiString Str, bool FromBeginning = false) = 0;
  32. virtual bool __fastcall Input(AnsiString & Str, bool Echo, unsigned int Timer) = 0;
  33. virtual int __fastcall Choice(AnsiString Options, int Cancel, int Break,
  34. int Timeouted, unsigned int Timer) = 0;
  35. virtual bool __fastcall PendingAbort() = 0;
  36. virtual void __fastcall SetTitle(AnsiString Title) = 0;
  37. virtual bool __fastcall LimitedOutput() = 0;
  38. virtual bool __fastcall LiveOutput() = 0;
  39. virtual void __fastcall WaitBeforeExit() = 0;
  40. virtual bool __fastcall CommandLineOnly() = 0;
  41. };
  42. //---------------------------------------------------------------------------
  43. class TOwnConsole : public TConsole
  44. {
  45. public:
  46. static TOwnConsole * __fastcall Instance();
  47. virtual void __fastcall Print(AnsiString Str, bool FromBeginning = false);
  48. virtual bool __fastcall Input(AnsiString & Str, bool Echo, unsigned int Timer);
  49. virtual int __fastcall Choice(AnsiString Options, int Cancel, int Break,
  50. int Timeouted, unsigned int Timer);
  51. virtual bool __fastcall PendingAbort();
  52. virtual void __fastcall SetTitle(AnsiString Title);
  53. virtual bool __fastcall LimitedOutput();
  54. virtual bool __fastcall LiveOutput();
  55. virtual void __fastcall WaitBeforeExit();
  56. virtual bool __fastcall CommandLineOnly();
  57. protected:
  58. static TOwnConsole * FInstance;
  59. friend class TConsoleInputThread;
  60. __fastcall TOwnConsole();
  61. virtual __fastcall ~TOwnConsole();
  62. void __fastcall BreakInput();
  63. static BOOL WINAPI HandlerRoutine(DWORD CtrlType);
  64. void __fastcall WindowStateTimer(TObject * Sender);
  65. void __fastcall ProcessMessages();
  66. void __fastcall TrayIconClick(TObject * Sender);
  67. private:
  68. HANDLE FInput;
  69. HANDLE FOutput;
  70. HWND FConsoleWindow;
  71. TTimer * FWindowStateTimer;
  72. bool FMinimized;
  73. TTrayIcon * FTrayIcon;
  74. static TCriticalSection FSection;
  75. bool FPendingAbort;
  76. };
  77. //---------------------------------------------------------------------------
  78. TOwnConsole * TOwnConsole::FInstance = NULL;
  79. TCriticalSection TOwnConsole::FSection;
  80. //---------------------------------------------------------------------------
  81. __fastcall TOwnConsole::TOwnConsole()
  82. {
  83. assert(FInstance == NULL);
  84. FInstance = this;
  85. AllocConsole();
  86. SetConsoleCtrlHandler(HandlerRoutine, true);
  87. FInput = GetStdHandle(STD_INPUT_HANDLE);
  88. FOutput = GetStdHandle(STD_OUTPUT_HANDLE);
  89. FPendingAbort = false;
  90. FConsoleWindow = NULL;
  91. FWindowStateTimer = NULL;
  92. FMinimized = false;
  93. FTrayIcon = new TTrayIcon(0);
  94. FTrayIcon->OnClick = TrayIconClick;
  95. if (WinConfiguration->MinimizeToTray)
  96. {
  97. HANDLE Kernel32 = GetModuleHandle(kernel32);
  98. typedef HWND WINAPI (* TGetConsoleWindow)();
  99. TGetConsoleWindow GetConsoleWindow =
  100. (TGetConsoleWindow)GetProcAddress(Kernel32, "GetConsoleWindow");
  101. if (GetConsoleWindow != NULL)
  102. {
  103. FConsoleWindow = GetConsoleWindow();
  104. if (FConsoleWindow != NULL)
  105. {
  106. FWindowStateTimer = new TTimer(Application);
  107. FWindowStateTimer->OnTimer = WindowStateTimer;
  108. FWindowStateTimer->Interval = 250;
  109. FWindowStateTimer->Enabled = true;
  110. }
  111. else
  112. {
  113. assert(false);
  114. }
  115. }
  116. }
  117. }
  118. //---------------------------------------------------------------------------
  119. __fastcall TOwnConsole::~TOwnConsole()
  120. {
  121. TGuard Guard(&FSection);
  122. delete FTrayIcon;
  123. delete FWindowStateTimer;
  124. // deliberatelly do not remove ConsoleCtrlHandler as it causes
  125. // failures while exiting
  126. FreeConsole();
  127. assert(FInstance == this);
  128. FInstance = NULL;
  129. }
  130. //---------------------------------------------------------------------------
  131. TOwnConsole * __fastcall TOwnConsole::Instance()
  132. {
  133. return new TOwnConsole();
  134. }
  135. //---------------------------------------------------------------------------
  136. void __fastcall TOwnConsole::WindowStateTimer(TObject * /*Sender*/)
  137. {
  138. assert(FConsoleWindow != NULL);
  139. WINDOWPLACEMENT Placement;
  140. memset(&Placement, 0, sizeof(Placement));
  141. Placement.length = sizeof(Placement);
  142. if (GetWindowPlacement(FConsoleWindow, &Placement))
  143. {
  144. bool Minimized = (Placement.showCmd == SW_SHOWMINIMIZED);
  145. if (FMinimized != Minimized)
  146. {
  147. FMinimized = Minimized;
  148. if (FMinimized && WinConfiguration->MinimizeToTray)
  149. {
  150. FTrayIcon->Visible = true;
  151. ShowWindow(FConsoleWindow, SW_HIDE);
  152. }
  153. else
  154. {
  155. FTrayIcon->Visible = false;
  156. ShowWindow(FConsoleWindow, SW_SHOW);
  157. }
  158. }
  159. }
  160. else
  161. {
  162. assert(false);
  163. }
  164. }
  165. //---------------------------------------------------------------------------
  166. void __fastcall TOwnConsole::ProcessMessages()
  167. {
  168. // as of now, there's no point doing this unless we have icon tray
  169. // (i.e. we need to monitor window state and eventually process tray icon messages)
  170. if (FWindowStateTimer != NULL)
  171. {
  172. assert(WinConfiguration->MinimizeToTray);
  173. Application->ProcessMessages();
  174. }
  175. }
  176. //---------------------------------------------------------------------------
  177. void __fastcall TOwnConsole::TrayIconClick(TObject * /*Sender*/)
  178. {
  179. assert(FConsoleWindow != NULL);
  180. SetForegroundWindow(FConsoleWindow);
  181. ShowWindow(FConsoleWindow, SW_RESTORE);
  182. }
  183. //---------------------------------------------------------------------------
  184. void __fastcall TOwnConsole::BreakInput()
  185. {
  186. FPendingAbort = true;
  187. PostMessage(Application->Handle, WM_INTERUPT_IDLE, 0, 0);
  188. }
  189. //---------------------------------------------------------------------------
  190. BOOL WINAPI TOwnConsole::HandlerRoutine(DWORD CtrlType)
  191. {
  192. if ((CtrlType == CTRL_C_EVENT) || (CtrlType == CTRL_BREAK_EVENT))
  193. {
  194. {
  195. TGuard Guard(&FSection);
  196. // just to be real thread-safe
  197. if (FInstance != NULL)
  198. {
  199. FInstance->BreakInput();
  200. }
  201. }
  202. return true;
  203. }
  204. else
  205. {
  206. return false;
  207. }
  208. }
  209. //---------------------------------------------------------------------------
  210. bool __fastcall TOwnConsole::PendingAbort()
  211. {
  212. if (FPendingAbort)
  213. {
  214. FPendingAbort = false;
  215. return true;
  216. }
  217. else
  218. {
  219. return FPendingAbort;
  220. }
  221. }
  222. //---------------------------------------------------------------------------
  223. void __fastcall TOwnConsole::Print(AnsiString Str, bool FromBeginning)
  224. {
  225. if (FromBeginning)
  226. {
  227. CONSOLE_SCREEN_BUFFER_INFO BufferInfo;
  228. GetConsoleScreenBufferInfo(FOutput, &BufferInfo);
  229. BufferInfo.dwCursorPosition.X = 0;
  230. SetConsoleCursorPosition(FOutput, BufferInfo.dwCursorPosition);
  231. }
  232. unsigned long Written;
  233. AnsiToOem(Str);
  234. bool Result = WriteConsole(FOutput, Str.c_str(), Str.Length(), &Written, NULL);
  235. assert(Result);
  236. USEDPARAM(Result);
  237. assert(Str.Length() == static_cast<long>(Written));
  238. ProcessMessages();
  239. }
  240. //---------------------------------------------------------------------------
  241. class TConsoleInputThread : public TSimpleThread
  242. {
  243. public:
  244. __fastcall TConsoleInputThread(HANDLE Input, AnsiString & Str, bool & Result) :
  245. FInput(Input),
  246. FStr(Str),
  247. FResult(Result)
  248. {
  249. }
  250. virtual __fastcall ~TConsoleInputThread()
  251. {
  252. Close();
  253. }
  254. protected:
  255. virtual void __fastcall Execute()
  256. {
  257. unsigned long Read;
  258. FStr.SetLength(10240);
  259. FResult = ReadConsole(FInput, FStr.c_str(), FStr.Length(), &Read, NULL);
  260. assert(FResult);
  261. FStr.SetLength(Read);
  262. }
  263. virtual void __fastcall Terminate()
  264. {
  265. TOwnConsole::FInstance->BreakInput();
  266. }
  267. private:
  268. HANDLE FInput;
  269. AnsiString & FStr;
  270. bool & FResult;
  271. };
  272. //---------------------------------------------------------------------------
  273. bool __fastcall TOwnConsole::Input(AnsiString & Str, bool Echo, unsigned int Timer)
  274. {
  275. unsigned long PrevMode, NewMode;
  276. GetConsoleMode(FInput, &PrevMode);
  277. NewMode = PrevMode | ENABLE_PROCESSED_INPUT | ENABLE_LINE_INPUT;
  278. if (Echo)
  279. {
  280. NewMode |= ENABLE_ECHO_INPUT;
  281. }
  282. else
  283. {
  284. NewMode &= ~ENABLE_ECHO_INPUT;
  285. }
  286. SetConsoleMode(FInput, NewMode);
  287. bool Result;
  288. try
  289. {
  290. {
  291. TConsoleInputThread InputThread(FInput, Str, Result);
  292. InputThread.Start();
  293. double Start = Now();
  294. double End = Start + double(Timer)/(24*60*60*1000);
  295. while (!InputThread.IsFinished() &&
  296. ((Timer == 0) || (double(Now()) < End)))
  297. {
  298. ProcessMessages();
  299. InputThread.WaitFor(50);
  300. }
  301. }
  302. OemToAnsi(Str);
  303. if (FPendingAbort || !Echo)
  304. {
  305. Print("\n");
  306. }
  307. if (FPendingAbort || (Str.Length() == 0))
  308. {
  309. Result = false;
  310. FPendingAbort = false;
  311. }
  312. }
  313. __finally
  314. {
  315. SetConsoleMode(FInput, PrevMode);
  316. }
  317. return Result;
  318. }
  319. //---------------------------------------------------------------------------
  320. int __fastcall TOwnConsole::Choice(AnsiString Options, int Cancel, int Break,
  321. int Timeouted, unsigned int Timer)
  322. {
  323. AnsiToOem(Options);
  324. unsigned int ATimer = Timer;
  325. int Result = 0;
  326. unsigned long PrevMode, NewMode;
  327. GetConsoleMode(FInput, &PrevMode);
  328. NewMode = (PrevMode | ENABLE_PROCESSED_INPUT) & ~(ENABLE_LINE_INPUT | ENABLE_ECHO_INPUT);
  329. SetConsoleMode(FInput, NewMode);
  330. try
  331. {
  332. do
  333. {
  334. unsigned long Read;
  335. INPUT_RECORD Record;
  336. if ((PeekConsoleInput(FInput, &Record, 1, &Read) != 0) &&
  337. (Read == 1))
  338. {
  339. if ((ReadConsoleInput(FInput, &Record, 1, &Read) != 0) &&
  340. (Read == 1))
  341. {
  342. if (PendingAbort())
  343. {
  344. Result = Break;
  345. }
  346. else if ((Record.EventType == KEY_EVENT) &&
  347. Record.Event.KeyEvent.bKeyDown)
  348. {
  349. char C = AnsiUpperCase(Record.Event.KeyEvent.uChar.AsciiChar)[1];
  350. if (C == 27)
  351. {
  352. Result = Cancel;
  353. }
  354. else if ((Options.Pos(C) > 0) &&
  355. FLAGCLEAR(Record.Event.KeyEvent.dwControlKeyState,
  356. LEFT_CTRL_PRESSED | RIGHT_CTRL_PRESSED | LEFT_ALT_PRESSED |
  357. RIGHT_CTRL_PRESSED))
  358. {
  359. Result = Options.Pos(C);
  360. }
  361. }
  362. }
  363. }
  364. if (Result == 0)
  365. {
  366. unsigned int TimerSlice = 50;
  367. Sleep(TimerSlice);
  368. if (Timer > 0)
  369. {
  370. if (ATimer > TimerSlice)
  371. {
  372. ATimer -= TimerSlice;
  373. }
  374. else
  375. {
  376. Result = Timeouted;
  377. }
  378. }
  379. }
  380. ProcessMessages();
  381. }
  382. while (Result == 0);
  383. }
  384. __finally
  385. {
  386. SetConsoleMode(FInput, PrevMode);
  387. }
  388. return Result;
  389. }
  390. //---------------------------------------------------------------------------
  391. void __fastcall TOwnConsole::SetTitle(AnsiString Title)
  392. {
  393. FTrayIcon->Hint = Title;
  394. AnsiToOem(Title);
  395. SetConsoleTitle(Title.c_str());
  396. }
  397. //---------------------------------------------------------------------------
  398. bool __fastcall TOwnConsole::LimitedOutput()
  399. {
  400. return true;
  401. }
  402. //---------------------------------------------------------------------------
  403. bool __fastcall TOwnConsole::LiveOutput()
  404. {
  405. return true;
  406. }
  407. //---------------------------------------------------------------------------
  408. void __fastcall TOwnConsole::WaitBeforeExit()
  409. {
  410. unsigned long Read;
  411. INPUT_RECORD Record;
  412. while (true)
  413. {
  414. if (PeekConsoleInput(FInput, &Record, 1, &Read) && (Read == 1) &&
  415. ReadConsoleInput(FInput, &Record, 1, &Read) &&
  416. (Read == 1) && (Record.EventType == KEY_EVENT) &&
  417. (Record.Event.KeyEvent.uChar.AsciiChar != 0) &&
  418. Record.Event.KeyEvent.bKeyDown)
  419. {
  420. break;
  421. }
  422. Sleep(50);
  423. ProcessMessages();
  424. }
  425. }
  426. //---------------------------------------------------------------------------
  427. bool __fastcall TOwnConsole::CommandLineOnly()
  428. {
  429. return false;
  430. }
  431. //---------------------------------------------------------------------------
  432. class TExternalConsole : public TConsole
  433. {
  434. public:
  435. __fastcall TExternalConsole(const AnsiString Instance);
  436. virtual __fastcall ~TExternalConsole();
  437. virtual void __fastcall Print(AnsiString Str, bool FromBeginning = false);
  438. virtual bool __fastcall Input(AnsiString & Str, bool Echo, unsigned int Timer);
  439. virtual int __fastcall Choice(AnsiString Options, int Cancel, int Break,
  440. int Timeouted, unsigned int Timer);
  441. virtual bool __fastcall PendingAbort();
  442. virtual void __fastcall SetTitle(AnsiString Title);
  443. virtual bool __fastcall LimitedOutput();
  444. virtual bool __fastcall LiveOutput();
  445. virtual void __fastcall WaitBeforeExit();
  446. virtual bool __fastcall CommandLineOnly();
  447. private:
  448. bool FPendingAbort;
  449. HANDLE FRequestEvent;
  450. HANDLE FResponseEvent;
  451. HANDLE FCancelEvent;
  452. HANDLE FFileMapping;
  453. bool FLimitedOutput;
  454. bool FLiveOutput;
  455. static const int PrintTimeout = 5000;
  456. inline TConsoleCommStruct * __fastcall GetCommStruct();
  457. inline void __fastcall FreeCommStruct(TConsoleCommStruct * CommStruct);
  458. inline void __fastcall SendEvent(int Timeout);
  459. void __fastcall Init();
  460. };
  461. //---------------------------------------------------------------------------
  462. __fastcall TExternalConsole::TExternalConsole(const AnsiString Instance)
  463. {
  464. FRequestEvent = OpenEvent(EVENT_ALL_ACCESS, false,
  465. FORMAT("%s%s", (CONSOLE_EVENT_REQUEST, (Instance))).c_str());
  466. FResponseEvent = OpenEvent(EVENT_ALL_ACCESS, false,
  467. FORMAT("%s%s", (CONSOLE_EVENT_RESPONSE, (Instance))).c_str());
  468. FCancelEvent = OpenEvent(EVENT_ALL_ACCESS, false,
  469. FORMAT("%s%s", (CONSOLE_EVENT_CANCEL, (Instance))).c_str());
  470. FFileMapping = OpenFileMapping(FILE_MAP_ALL_ACCESS, false,
  471. FORMAT("%s%s", (CONSOLE_MAPPING, (Instance))).c_str());
  472. if ((FRequestEvent == NULL) || (FResponseEvent == NULL) || (FFileMapping == NULL))
  473. {
  474. throw Exception(LoadStr(EXTERNAL_CONSOLE_INIT_ERROR));
  475. }
  476. HANDLE Kernel32 = GetModuleHandle(kernel32);
  477. typedef HANDLE WINAPI (* TOpenJobObject)(DWORD DesiredAccess, BOOL InheritHandles, LPCTSTR Name);
  478. typedef HANDLE WINAPI (* TAssignProcessToJobObject)(HANDLE Job, HANDLE Process);
  479. TOpenJobObject OpenJobObject =
  480. (TOpenJobObject)GetProcAddress(Kernel32, "OpenJobObjectA");
  481. TAssignProcessToJobObject AssignProcessToJobObject =
  482. (TAssignProcessToJobObject)GetProcAddress(Kernel32, "AssignProcessToJobObject");
  483. if ((OpenJobObject != NULL) && (AssignProcessToJobObject != NULL))
  484. {
  485. HANDLE Job = OpenJobObject(JOB_OBJECT_ASSIGN_PROCESS, FALSE,
  486. FORMAT("%s%s", (CONSOLE_JOB, Instance)).c_str());
  487. if (Job != NULL)
  488. {
  489. AssignProcessToJobObject(Job, GetCurrentProcess());
  490. // winscp.com keeps the only reference to the job.
  491. // once it gets closed (because winscp.com if forcefully terminated),
  492. // we get terminated as well
  493. CloseHandle(Job);
  494. }
  495. }
  496. TConsoleCommStruct * CommStruct = GetCommStruct();
  497. try
  498. {
  499. if (CommStruct->Version != TConsoleCommStruct::CurrentVersion)
  500. {
  501. throw Exception(FMTLOAD(EXTERNAL_CONSOLE_INCOMPATIBLE, (CommStruct->CurrentVersion)));
  502. }
  503. CommStruct->Version = TConsoleCommStruct::CurrentVersionConfirmed;
  504. }
  505. __finally
  506. {
  507. FreeCommStruct(CommStruct);
  508. }
  509. // to break application event loop regularly during "watching for changes"
  510. // to allow user to abort it
  511. SetTimer(Application->Handle, 1, 500, NULL);
  512. Init();
  513. }
  514. //---------------------------------------------------------------------------
  515. __fastcall TExternalConsole::~TExternalConsole()
  516. {
  517. CloseHandle(FRequestEvent);
  518. CloseHandle(FResponseEvent);
  519. CloseHandle(FCancelEvent);
  520. CloseHandle(FFileMapping);
  521. KillTimer(Application->Handle, 1);
  522. }
  523. //---------------------------------------------------------------------------
  524. TConsoleCommStruct * __fastcall TExternalConsole::GetCommStruct()
  525. {
  526. TConsoleCommStruct * Result;
  527. Result = static_cast<TConsoleCommStruct*>(MapViewOfFile(FFileMapping,
  528. FILE_MAP_ALL_ACCESS, 0, 0, 0));
  529. if (Result == NULL)
  530. {
  531. throw Exception(LoadStr(CONSOLE_COMM_ERROR));
  532. }
  533. return Result;
  534. }
  535. //---------------------------------------------------------------------------
  536. void __fastcall TExternalConsole::FreeCommStruct(TConsoleCommStruct * CommStruct)
  537. {
  538. UnmapViewOfFile(CommStruct);
  539. }
  540. //---------------------------------------------------------------------------
  541. void __fastcall TExternalConsole::SendEvent(int Timeout)
  542. {
  543. SetEvent(FRequestEvent);
  544. unsigned int Result = WaitForSingleObject(FResponseEvent, Timeout);
  545. if (Result != WAIT_OBJECT_0)
  546. {
  547. throw Exception(LoadStr(CONSOLE_SEND_TIMEOUT));
  548. }
  549. }
  550. //---------------------------------------------------------------------------
  551. void __fastcall TExternalConsole::Print(AnsiString Str, bool FromBeginning)
  552. {
  553. TConsoleCommStruct * CommStruct = GetCommStruct();
  554. try
  555. {
  556. if (Str.Length() >= sizeof(CommStruct->PrintEvent.Message))
  557. {
  558. throw Exception(FMTLOAD(CONSOLE_PRINT_TOO_LONG, (Str.Length())));
  559. }
  560. CommStruct->Event = TConsoleCommStruct::PRINT;
  561. CharToOem(Str.c_str(), CommStruct->PrintEvent.Message);
  562. CommStruct->PrintEvent.FromBeginning = FromBeginning;
  563. }
  564. __finally
  565. {
  566. FreeCommStruct(CommStruct);
  567. }
  568. SendEvent(PrintTimeout);
  569. }
  570. //---------------------------------------------------------------------------
  571. bool __fastcall TExternalConsole::Input(AnsiString & Str, bool Echo, unsigned int Timer)
  572. {
  573. TConsoleCommStruct * CommStruct = GetCommStruct();
  574. try
  575. {
  576. CommStruct->Event = TConsoleCommStruct::INPUT;
  577. CommStruct->InputEvent.Echo = Echo;
  578. CommStruct->InputEvent.Result = false;
  579. CommStruct->InputEvent.Str[0] = '\0';
  580. CommStruct->InputEvent.Timer = Timer;
  581. }
  582. __finally
  583. {
  584. FreeCommStruct(CommStruct);
  585. }
  586. SendEvent(INFINITE);
  587. bool Result;
  588. CommStruct = GetCommStruct();
  589. try
  590. {
  591. Result = CommStruct->InputEvent.Result;
  592. Str.SetLength(strlen(CommStruct->InputEvent.Str));
  593. OemToChar(CommStruct->InputEvent.Str, Str.c_str());
  594. }
  595. __finally
  596. {
  597. FreeCommStruct(CommStruct);
  598. }
  599. return Result;
  600. }
  601. //---------------------------------------------------------------------------
  602. int __fastcall TExternalConsole::Choice(AnsiString Options, int Cancel, int Break,
  603. int Timeouted, unsigned int Timer)
  604. {
  605. TConsoleCommStruct * CommStruct = GetCommStruct();
  606. try
  607. {
  608. CommStruct->Event = TConsoleCommStruct::CHOICE;
  609. assert(Options.Length() < sizeof(CommStruct->ChoiceEvent.Options));
  610. CharToOem(Options.c_str(), CommStruct->ChoiceEvent.Options);
  611. CommStruct->ChoiceEvent.Cancel = Cancel;
  612. CommStruct->ChoiceEvent.Break = Break;
  613. CommStruct->ChoiceEvent.Result = Break;
  614. CommStruct->ChoiceEvent.Timeouted = Timeouted;
  615. CommStruct->ChoiceEvent.Timer = Timer;
  616. }
  617. __finally
  618. {
  619. FreeCommStruct(CommStruct);
  620. }
  621. SendEvent(INFINITE);
  622. int Result;
  623. CommStruct = GetCommStruct();
  624. try
  625. {
  626. Result = CommStruct->ChoiceEvent.Result;
  627. }
  628. __finally
  629. {
  630. FreeCommStruct(CommStruct);
  631. }
  632. return Result;
  633. }
  634. //---------------------------------------------------------------------------
  635. bool __fastcall TExternalConsole::PendingAbort()
  636. {
  637. return (WaitForSingleObject(FCancelEvent, 0) == WAIT_OBJECT_0);
  638. }
  639. //---------------------------------------------------------------------------
  640. void __fastcall TExternalConsole::SetTitle(AnsiString Title)
  641. {
  642. TConsoleCommStruct * CommStruct = GetCommStruct();
  643. try
  644. {
  645. if (Title.Length() >= sizeof(CommStruct->TitleEvent.Title))
  646. {
  647. throw Exception(FMTLOAD(CONSOLE_PRINT_TOO_LONG, (Title.Length())));
  648. }
  649. CommStruct->Event = TConsoleCommStruct::TITLE;
  650. CharToOem(Title.c_str(), CommStruct->TitleEvent.Title);
  651. }
  652. __finally
  653. {
  654. FreeCommStruct(CommStruct);
  655. }
  656. SendEvent(INFINITE);
  657. }
  658. //---------------------------------------------------------------------------
  659. void __fastcall TExternalConsole::Init()
  660. {
  661. TConsoleCommStruct * CommStruct = GetCommStruct();
  662. try
  663. {
  664. CommStruct->Event = TConsoleCommStruct::INIT;
  665. }
  666. __finally
  667. {
  668. FreeCommStruct(CommStruct);
  669. }
  670. SendEvent(INFINITE);
  671. CommStruct = GetCommStruct();
  672. try
  673. {
  674. FLimitedOutput = (CommStruct->InitEvent.OutputType == FILE_TYPE_CHAR);
  675. FLiveOutput =
  676. (CommStruct->InitEvent.OutputType != FILE_TYPE_DISK) &&
  677. (CommStruct->InitEvent.OutputType != FILE_TYPE_PIPE);
  678. }
  679. __finally
  680. {
  681. FreeCommStruct(CommStruct);
  682. }
  683. }
  684. //---------------------------------------------------------------------------
  685. bool __fastcall TExternalConsole::LimitedOutput()
  686. {
  687. return FLimitedOutput;
  688. }
  689. //---------------------------------------------------------------------------
  690. bool __fastcall TExternalConsole::LiveOutput()
  691. {
  692. return FLiveOutput;
  693. }
  694. //---------------------------------------------------------------------------
  695. void __fastcall TExternalConsole::WaitBeforeExit()
  696. {
  697. // noop
  698. }
  699. //---------------------------------------------------------------------------
  700. bool __fastcall TExternalConsole::CommandLineOnly()
  701. {
  702. return true;
  703. }
  704. //---------------------------------------------------------------------------
  705. class TNullConsole : public TConsole
  706. {
  707. public:
  708. __fastcall TNullConsole();
  709. virtual void __fastcall Print(AnsiString Str, bool FromBeginning = false);
  710. virtual bool __fastcall Input(AnsiString & Str, bool Echo, unsigned int Timer);
  711. virtual int __fastcall Choice(AnsiString Options, int Cancel, int Break,
  712. int Timeouted, unsigned int Timer);
  713. virtual bool __fastcall PendingAbort();
  714. virtual void __fastcall SetTitle(AnsiString Title);
  715. virtual bool __fastcall LimitedOutput();
  716. virtual bool __fastcall LiveOutput();
  717. virtual void __fastcall WaitBeforeExit();
  718. virtual bool __fastcall CommandLineOnly();
  719. };
  720. //---------------------------------------------------------------------------
  721. __fastcall TNullConsole::TNullConsole()
  722. {
  723. }
  724. //---------------------------------------------------------------------------
  725. void __fastcall TNullConsole::Print(AnsiString /*Str*/, bool /*FromBeginning*/)
  726. {
  727. // noop
  728. }
  729. //---------------------------------------------------------------------------
  730. bool __fastcall TNullConsole::Input(AnsiString & /*Str*/, bool /*Echo*/,
  731. unsigned int /*Timer*/)
  732. {
  733. return false;
  734. }
  735. //---------------------------------------------------------------------------
  736. int __fastcall TNullConsole::Choice(AnsiString /*Options*/, int /*Cancel*/,
  737. int Break, int /*Timeouted*/, unsigned int /*Timer*/)
  738. {
  739. return Break;
  740. }
  741. //---------------------------------------------------------------------------
  742. bool __fastcall TNullConsole::PendingAbort()
  743. {
  744. return false;
  745. }
  746. //---------------------------------------------------------------------------
  747. void __fastcall TNullConsole::SetTitle(AnsiString /*Title*/)
  748. {
  749. // noop
  750. }
  751. //---------------------------------------------------------------------------
  752. bool __fastcall TNullConsole::LimitedOutput()
  753. {
  754. return false;
  755. }
  756. //---------------------------------------------------------------------------
  757. bool __fastcall TNullConsole::LiveOutput()
  758. {
  759. return false;
  760. }
  761. //---------------------------------------------------------------------------
  762. void __fastcall TNullConsole::WaitBeforeExit()
  763. {
  764. assert(false);
  765. // noop
  766. }
  767. //---------------------------------------------------------------------------
  768. bool __fastcall TNullConsole::CommandLineOnly()
  769. {
  770. assert(false);
  771. return false;
  772. }
  773. //---------------------------------------------------------------------------
  774. class TConsoleRunner
  775. {
  776. public:
  777. TConsoleRunner(TConsole * Console);
  778. ~TConsoleRunner();
  779. int __fastcall Run(const AnsiString Session, TOptions * Options,
  780. TStrings * ScriptCommands, TStrings * ScriptParameters);
  781. void __fastcall ShowException(Exception * E);
  782. protected:
  783. bool __fastcall DoInput(AnsiString & Str, bool Echo, unsigned int Timer);
  784. void __fastcall Input(const AnsiString Prompt, AnsiString & Str, bool Echo);
  785. inline void __fastcall Print(const AnsiString & Str, bool FromBeginning = false);
  786. inline void __fastcall PrintLine(const AnsiString & Str);
  787. inline void __fastcall PrintMessage(const AnsiString & Str);
  788. void __fastcall UpdateTitle();
  789. inline void __fastcall NotifyAbort();
  790. inline bool __fastcall Aborted(bool AllowCompleteAbort = true);
  791. void __fastcall MasterPasswordPrompt();
  792. private:
  793. TManagementScript * FScript;
  794. TConsole * FConsole;
  795. TSynchronizeController FSynchronizeController;
  796. int FLastProgressLen;
  797. bool FSynchronizeAborted;
  798. bool FCommandError;
  799. bool FBatchScript;
  800. bool FAborted;
  801. TTimer * Timer;
  802. void __fastcall ScriptPrint(TScript * Script, const AnsiString Str);
  803. void __fastcall ScriptPrintProgress(TScript * Script, bool First, const AnsiString Str);
  804. void __fastcall ScriptInput(TScript * Script, const AnsiString Prompt, AnsiString & Str);
  805. void __fastcall ScriptTerminalPromptUser(TTerminal * Terminal,
  806. TPromptKind Kind, AnsiString Name, AnsiString Instructions, TStrings * Prompts,
  807. TStrings * Results, bool & Result, void * Arg);
  808. void __fastcall ScriptShowExtendedException(TTerminal * Terminal,
  809. Exception * E, void * Arg);
  810. void __fastcall ScriptTerminalQueryUser(TObject * Sender, const AnsiString Query,
  811. TStrings * MoreMessages, int Answers, const TQueryParams * Params, int & Answer,
  812. TQueryType QueryType, void * Arg);
  813. void __fastcall ScriptQueryCancel(TScript * Script, bool & Cancel);
  814. void __fastcall SynchronizeControllerAbort(TObject * Sender, bool Close);
  815. void __fastcall SynchronizeControllerLog(TSynchronizeController * Controller,
  816. TSynchronizeLogEntry Entry, const AnsiString Message);
  817. void __fastcall ScriptSynchronizeStartStop(TScript * Script,
  818. const AnsiString LocalDirectory, const AnsiString RemoteDirectory,
  819. const TCopyParamType & CopyParam, int SynchronizeParams);
  820. void __fastcall SynchronizeControllerSynchronize(TSynchronizeController * Sender,
  821. const AnsiString LocalDirectory, const AnsiString RemoteDirectory,
  822. const TCopyParamType & CopyParam, const TSynchronizeParamType & Params,
  823. TSynchronizeChecklist ** Checklist, TSynchronizeOptions * Options, bool Full);
  824. void __fastcall SynchronizeControllerSynchronizeInvalid(TSynchronizeController * Sender,
  825. const AnsiString Directory, const AnsiString ErrorStr);
  826. void __fastcall SynchronizeControllerTooManyDirectories(TSynchronizeController * Sender,
  827. int & MaxDirectories);
  828. unsigned int InputTimeout();
  829. void __fastcall TimerTimer(TObject * Sender);
  830. AnsiString ExpandCommand(AnsiString Command, TStrings * ScriptParameters);
  831. };
  832. //---------------------------------------------------------------------------
  833. TConsoleRunner::TConsoleRunner(TConsole * Console) :
  834. FSynchronizeController(&SynchronizeControllerSynchronize,
  835. &SynchronizeControllerSynchronizeInvalid,
  836. &SynchronizeControllerTooManyDirectories)
  837. {
  838. FConsole = Console;
  839. FLastProgressLen = 0;
  840. FScript = NULL;
  841. FAborted = false;
  842. FBatchScript = false;
  843. Timer = new TTimer(Application);
  844. Timer->OnTimer = TimerTimer;
  845. Timer->Interval = 1000;
  846. Timer->Enabled = true;
  847. assert(WinConfiguration->OnMasterPasswordPrompt == NULL);
  848. WinConfiguration->OnMasterPasswordPrompt = MasterPasswordPrompt;
  849. }
  850. //---------------------------------------------------------------------------
  851. TConsoleRunner::~TConsoleRunner()
  852. {
  853. assert(WinConfiguration->OnMasterPasswordPrompt == MasterPasswordPrompt);
  854. WinConfiguration->OnMasterPasswordPrompt = NULL;
  855. delete Timer;
  856. }
  857. //---------------------------------------------------------------------------
  858. void __fastcall TConsoleRunner::TimerTimer(TObject * /*Sender*/)
  859. {
  860. // sole presence of timer causes message to be dispatched,
  861. // hence breaks the loops
  862. }
  863. //---------------------------------------------------------------------------
  864. unsigned int TConsoleRunner::InputTimeout()
  865. {
  866. return ((FScript != NULL) && (FScript->Batch != TScript::BatchOff) ? BATCH_INPUT_TIMEOUT : 0);
  867. }
  868. //---------------------------------------------------------------------------
  869. void __fastcall TConsoleRunner::Input(const AnsiString Prompt, AnsiString & Str, bool Echo)
  870. {
  871. Print(Prompt);
  872. if (!DoInput(Str, Echo, InputTimeout()))
  873. {
  874. Abort();
  875. }
  876. }
  877. //---------------------------------------------------------------------------
  878. void __fastcall TConsoleRunner::ScriptInput(TScript * /*Script*/,
  879. const AnsiString Prompt, AnsiString & Str)
  880. {
  881. Input(Prompt, Str, true);
  882. }
  883. //---------------------------------------------------------------------------
  884. void __fastcall TConsoleRunner::Print(const AnsiString & Str, bool FromBeginning)
  885. {
  886. if (FLastProgressLen > 0)
  887. {
  888. FConsole->Print("\n" + Str, FromBeginning);
  889. FLastProgressLen = 0;
  890. }
  891. else
  892. {
  893. FConsole->Print(Str, FromBeginning);
  894. }
  895. }
  896. //---------------------------------------------------------------------------
  897. void __fastcall TConsoleRunner::PrintLine(const AnsiString & Str)
  898. {
  899. Print(Str + "\n");
  900. }
  901. //---------------------------------------------------------------------------
  902. void __fastcall TConsoleRunner::PrintMessage(const AnsiString & Str)
  903. {
  904. PrintLine(
  905. StringReplace(StringReplace(Str.TrimRight(), "\n\n", "\n", TReplaceFlags() << rfReplaceAll),
  906. "\n \n", "\n", TReplaceFlags() << rfReplaceAll));
  907. }
  908. //---------------------------------------------------------------------------
  909. void __fastcall TConsoleRunner::NotifyAbort()
  910. {
  911. if (FBatchScript)
  912. {
  913. FAborted = true;
  914. }
  915. }
  916. //---------------------------------------------------------------------------
  917. bool __fastcall TConsoleRunner::Aborted(bool AllowCompleteAbort)
  918. {
  919. bool Result;
  920. if (FAborted)
  921. {
  922. Result = true;
  923. }
  924. else
  925. {
  926. Result = FConsole->PendingAbort();
  927. if (Result)
  928. {
  929. PrintLine(LoadStr(USER_TERMINATED));
  930. if (AllowCompleteAbort)
  931. {
  932. NotifyAbort();
  933. }
  934. }
  935. }
  936. return Result;
  937. }
  938. //---------------------------------------------------------------------------
  939. void __fastcall TConsoleRunner::ScriptPrint(TScript * /*Script*/,
  940. const AnsiString Str)
  941. {
  942. Print(Str);
  943. }
  944. //---------------------------------------------------------------------------
  945. void __fastcall TConsoleRunner::ScriptPrintProgress(TScript * /*Script*/,
  946. bool First, const AnsiString Str)
  947. {
  948. AnsiString S = Str;
  949. if (First && (FLastProgressLen > 0))
  950. {
  951. S = "\n" + S;
  952. }
  953. else if (S.Length() < FLastProgressLen)
  954. {
  955. int Padding = FLastProgressLen - S.Length();
  956. S += AnsiString::StringOfChar(' ', Padding) +
  957. AnsiString::StringOfChar('\b', Padding);
  958. }
  959. FConsole->Print(S, true);
  960. FLastProgressLen = Str.Length();
  961. }
  962. //---------------------------------------------------------------------------
  963. void __fastcall TConsoleRunner::ScriptTerminalPromptUser(TTerminal * /*Terminal*/,
  964. TPromptKind /*Kind*/, AnsiString Name, AnsiString Instructions, TStrings * Prompts,
  965. TStrings * Results, bool & Result, void * /*Arg*/)
  966. {
  967. if (!Instructions.IsEmpty())
  968. {
  969. PrintLine(Instructions);
  970. }
  971. for (int Index = 0; Index < Prompts->Count; Index++)
  972. {
  973. AnsiString Prompt = Prompts->Strings[Index];
  974. if (!Prompt.IsEmpty() && (Prompt[Prompt.Length()] != ' '))
  975. {
  976. Prompt += ' ';
  977. }
  978. int P = Prompt.Pos('&');
  979. if (P > 0)
  980. {
  981. Prompt.Delete(P, 1);
  982. }
  983. Print(Prompt);
  984. AnsiString AResult = Results->Strings[Index]; // useless
  985. Result = DoInput(AResult, bool(Prompts->Objects[Index]), InputTimeout());
  986. Results->Strings[Index] = AResult;
  987. }
  988. }
  989. //---------------------------------------------------------------------------
  990. void __fastcall TConsoleRunner::ScriptShowExtendedException(
  991. TTerminal * /*Terminal*/, Exception * E, void * /*Arg*/)
  992. {
  993. ShowException(E);
  994. }
  995. //---------------------------------------------------------------------------
  996. void __fastcall TConsoleRunner::ScriptTerminalQueryUser(TObject * /*Sender*/,
  997. const AnsiString Query, TStrings * MoreMessages, int Answers,
  998. const TQueryParams * Params, int & Answer, TQueryType /*QueryType*/,
  999. void * /*Arg*/)
  1000. {
  1001. AnsiString AQuery = Query;
  1002. unsigned int Timer = 0;
  1003. unsigned int Timeout = 0;
  1004. int TimeoutA = 0;
  1005. int NoBatchA = 0;
  1006. if (Params != NULL)
  1007. {
  1008. if (Params->Timeout > 0)
  1009. {
  1010. assert(Params->Timer == 0);
  1011. Timeout = Params->Timeout;
  1012. TimeoutA = Params->TimeoutAnswer;
  1013. }
  1014. if (Params->Timer > 0)
  1015. {
  1016. assert(Params->Timeout == 0);
  1017. Timer = Params->Timer;
  1018. if (Params->TimerAnswers > 0)
  1019. {
  1020. Answers = Params->TimerAnswers;
  1021. }
  1022. if (!Params->TimerMessage.IsEmpty())
  1023. {
  1024. AQuery = Params->TimerMessage;
  1025. }
  1026. }
  1027. if (FLAGSET(Params->Params, qpFatalAbort))
  1028. {
  1029. AQuery = FMTLOAD(WARN_FATAL_ERROR, (AQuery));
  1030. }
  1031. NoBatchA = Params->NoBatchAnswers;
  1032. }
  1033. int AAnswers = Answers;
  1034. PrintMessage(AQuery);
  1035. if ((MoreMessages != NULL) && (MoreMessages->Count > 0))
  1036. {
  1037. PrintMessage(MoreMessages->Text);
  1038. }
  1039. static const int MaxButtonCount = 15;
  1040. int Buttons[MaxButtonCount];
  1041. AnsiString Captions[MaxButtonCount];
  1042. TNotifyEvent OnClicks[MaxButtonCount];
  1043. int ButtonCount = 0;
  1044. #define ADD_BUTTON(TYPE, CAPTION) \
  1045. if (FLAGSET(AAnswers, qa ## TYPE)) \
  1046. { \
  1047. assert(ButtonCount < MaxButtonCount); \
  1048. Captions[ButtonCount] = CAPTION; \
  1049. Buttons[ButtonCount] = qa ## TYPE; \
  1050. OnClicks[ButtonCount] = NULL; \
  1051. ButtonCount++; \
  1052. AAnswers -= qa ## TYPE; \
  1053. }
  1054. #define ADD_BUTTON_RES(TYPE) ADD_BUTTON(TYPE, LoadResourceString(&_SMsgDlg ## TYPE));
  1055. ADD_BUTTON_RES(Yes);
  1056. ADD_BUTTON_RES(No);
  1057. ADD_BUTTON_RES(OK);
  1058. ADD_BUTTON_RES(Cancel);
  1059. ADD_BUTTON_RES(Abort);
  1060. ADD_BUTTON_RES(Retry);
  1061. ADD_BUTTON_RES(Ignore);
  1062. // to keep the same order as for GUI message box
  1063. ADD_BUTTON(Skip, LoadStr(SKIP_BUTTON));
  1064. ADD_BUTTON_RES(All);
  1065. ADD_BUTTON_RES(NoToAll);
  1066. ADD_BUTTON_RES(YesToAll);
  1067. ADD_BUTTON_RES(Help);
  1068. #undef ADD_BUTTON_RES
  1069. #undef ADD_BUTTON
  1070. USEDPARAM(AAnswers);
  1071. assert(AAnswers == 0);
  1072. assert(ButtonCount > 0);
  1073. if ((Params != NULL) && (Params->Aliases != NULL))
  1074. {
  1075. for (int bi = 0; bi < ButtonCount; bi++)
  1076. {
  1077. for (unsigned int ai = 0; ai < Params->AliasesCount; ai++)
  1078. {
  1079. if (static_cast<int>(Params->Aliases[ai].Button) == Buttons[bi])
  1080. {
  1081. Captions[bi] = Params->Aliases[ai].Alias;
  1082. OnClicks[bi] = Params->Aliases[ai].OnClick;
  1083. break;
  1084. }
  1085. }
  1086. }
  1087. }
  1088. AnsiString Accels;
  1089. for (int Index = 0; Index < ButtonCount; Index++)
  1090. {
  1091. AnsiString & Caption = Captions[Index];
  1092. int P = Caption.Pos('&');
  1093. if ((P > 0) && (P < Caption.Length()))
  1094. {
  1095. char Accel = AnsiUpperCase(Caption)[P + 1];
  1096. if (Accels.Pos(Accel) > 0)
  1097. {
  1098. Caption.Delete(P, 1);
  1099. Accels += ' ';
  1100. }
  1101. else
  1102. {
  1103. Accels += Accel;
  1104. }
  1105. }
  1106. else
  1107. {
  1108. Accels += ' ';
  1109. }
  1110. }
  1111. assert(Accels.Length() == ButtonCount);
  1112. int NumberAccel = 0;
  1113. int CancelA = CancelAnswer(Answers);
  1114. int CancelIndex;
  1115. int AbortA = AbortAnswer(Answers & ~NoBatchA);
  1116. int AbortIndex;
  1117. int ContinueA = ContinueAnswer(Answers & ~NoBatchA);
  1118. int ContinueIndex;
  1119. int TimeoutIndex = 0;
  1120. for (int Index = 0; Index < ButtonCount; Index++)
  1121. {
  1122. AnsiString & Caption = Captions[Index];
  1123. if (Accels[Index + 1] == ' ')
  1124. {
  1125. for (int Index2 = 1; Index2 <= Caption.Length(); Index2++)
  1126. {
  1127. char C = AnsiUpperCase(Caption)[Index2];
  1128. if ((C >= 'A') && (C <= 'Z') && (Accels.Pos(C) == 0))
  1129. {
  1130. Caption.Insert("&", Index2);
  1131. Accels[Index + 1] = C;
  1132. break;
  1133. }
  1134. }
  1135. }
  1136. if (Accels[Index + 1] == ' ')
  1137. {
  1138. for (int Index2 = 1; Index2 <= Caption.Length(); Index2++)
  1139. {
  1140. char C = AnsiUpperCase(Caption)[Index2];
  1141. if ((C != ' ') && (Accels.Pos(C) == 0))
  1142. {
  1143. Caption.Insert("&", Index2);
  1144. Accels[Index + 1] = C;
  1145. break;
  1146. }
  1147. }
  1148. }
  1149. if (Accels[Index + 1] == ' ')
  1150. {
  1151. NumberAccel++;
  1152. assert(NumberAccel <= 9);
  1153. Caption = FORMAT("&%d%s", (NumberAccel, Caption));
  1154. Accels[Index + 1] = Caption[2];
  1155. }
  1156. if (Buttons[Index] == CancelA)
  1157. {
  1158. CancelIndex = Index + 1;
  1159. }
  1160. if (Buttons[Index] == AbortA)
  1161. {
  1162. AbortIndex = Index + 1;
  1163. }
  1164. if (Buttons[Index] == ContinueA)
  1165. {
  1166. ContinueIndex = Index + 1;
  1167. }
  1168. if (Buttons[Index] == TimeoutA)
  1169. {
  1170. TimeoutIndex = Index + 1;
  1171. }
  1172. }
  1173. assert(Accels.Pos(' ') == 0);
  1174. bool Timeouting = (Timeout > 0);
  1175. bool FirstOutput = true;
  1176. do
  1177. {
  1178. Answer = 0;
  1179. int AnswerIndex;
  1180. bool Retry;
  1181. do
  1182. {
  1183. Retry = false;
  1184. if (FirstOutput || FConsole->LiveOutput())
  1185. {
  1186. AnsiString Output;
  1187. for (int i = 0; i < ButtonCount; i++)
  1188. {
  1189. if (i > 0)
  1190. {
  1191. Output += ", ";
  1192. }
  1193. AnsiString Caption = Captions[i];
  1194. int P = Caption.Pos('&');
  1195. assert(P >= 0);
  1196. Caption[P] = '(';
  1197. Caption.Insert(")", P + 2);
  1198. if (i + 1 == TimeoutIndex)
  1199. {
  1200. assert(Timeouting);
  1201. Caption = FMTLOAD(TIMEOUT_BUTTON, (Caption, int(Timeout / 1000)));
  1202. }
  1203. Output += Caption;
  1204. }
  1205. Output += ": ";
  1206. // note that length of string may decrease over time due to number of
  1207. // seconds length, but supposing it decreases by one character at time
  1208. // at most, we do not mind as the prompt is terminated with space
  1209. // If output is not live (file or pipe), do no use 'from beginning'
  1210. // as it means that the output is not actually stored until new line
  1211. // is sent (and we will not [because we cannot] rewrite the output anyway)
  1212. Print(Output, !FirstOutput);
  1213. FirstOutput = false;
  1214. }
  1215. if (!Timeouting && (FScript->Batch == TScript::BatchContinue))
  1216. {
  1217. AnswerIndex = ContinueIndex;
  1218. }
  1219. else if (!Timeouting && (FScript->Batch != TScript::BatchOff))
  1220. {
  1221. AnswerIndex = AbortIndex;
  1222. }
  1223. else if (Timeouting && (Timeout < 1000))
  1224. {
  1225. AnswerIndex = TimeoutIndex;
  1226. }
  1227. else
  1228. {
  1229. AnswerIndex = FConsole->Choice(Accels, CancelIndex, -1, -2,
  1230. (Timeouting ? 1000 : Timer));
  1231. if (AnswerIndex == -1)
  1232. {
  1233. NotifyAbort();
  1234. AnswerIndex = AbortIndex;
  1235. }
  1236. else if (AnswerIndex == -2)
  1237. {
  1238. if (Timeouting)
  1239. {
  1240. assert(Timeout >= 1000);
  1241. Timeout -= 1000;
  1242. Retry = true;
  1243. }
  1244. else
  1245. {
  1246. assert((Params != NULL) && (Params->TimerEvent != NULL));
  1247. if ((Params != NULL) && (Params->TimerEvent != NULL))
  1248. {
  1249. unsigned int AAnswer = 0;
  1250. Params->TimerEvent(AAnswer);
  1251. if (AAnswer != 0)
  1252. {
  1253. Answer = AAnswer;
  1254. }
  1255. else
  1256. {
  1257. Retry = true;
  1258. }
  1259. }
  1260. }
  1261. }
  1262. }
  1263. }
  1264. while (Retry);
  1265. if (Answer == 0)
  1266. {
  1267. assert((AnswerIndex >= 1) && (AnswerIndex <= Accels.Length()));
  1268. AnsiString AnswerCaption = Captions[AnswerIndex - 1];
  1269. int P = AnswerCaption.Pos("&");
  1270. assert(P >= 0);
  1271. AnswerCaption.Delete(P, 1);
  1272. PrintLine(AnswerCaption);
  1273. FirstOutput = true;
  1274. if (OnClicks[AnswerIndex - 1] != NULL)
  1275. {
  1276. OnClicks[AnswerIndex - 1](NULL);
  1277. }
  1278. else
  1279. {
  1280. Answer = Buttons[AnswerIndex - 1];
  1281. }
  1282. }
  1283. else
  1284. {
  1285. PrintLine("");
  1286. }
  1287. }
  1288. while (Answer == 0);
  1289. if (Answer == AbortA)
  1290. {
  1291. FCommandError = true;
  1292. }
  1293. }
  1294. //---------------------------------------------------------------------------
  1295. void __fastcall TConsoleRunner::ScriptQueryCancel(TScript * /*Script*/, bool & Cancel)
  1296. {
  1297. if (Aborted())
  1298. {
  1299. Cancel = true;
  1300. }
  1301. }
  1302. //---------------------------------------------------------------------------
  1303. void __fastcall TConsoleRunner::ScriptSynchronizeStartStop(TScript * /*Script*/,
  1304. const AnsiString LocalDirectory, const AnsiString RemoteDirectory,
  1305. const TCopyParamType & CopyParam, int SynchronizeParams)
  1306. {
  1307. TSynchronizeParamType Params;
  1308. Params.LocalDirectory = LocalDirectory;
  1309. Params.RemoteDirectory = RemoteDirectory;
  1310. Params.Params = SynchronizeParams;
  1311. Params.Options = soRecurse;
  1312. FSynchronizeController.StartStop(Application, true, Params,
  1313. CopyParam, NULL, SynchronizeControllerAbort, NULL,
  1314. SynchronizeControllerLog);
  1315. try
  1316. {
  1317. FSynchronizeAborted = false;
  1318. while (!FSynchronizeAborted && !Aborted(false))
  1319. {
  1320. Application->HandleMessage();
  1321. FScript->Terminal->Idle();
  1322. }
  1323. }
  1324. __finally
  1325. {
  1326. FSynchronizeController.StartStop(Application, false, Params,
  1327. CopyParam, NULL, SynchronizeControllerAbort, NULL,
  1328. SynchronizeControllerLog);
  1329. }
  1330. }
  1331. //---------------------------------------------------------------------------
  1332. void __fastcall TConsoleRunner::SynchronizeControllerLog(
  1333. TSynchronizeController * /*Controller*/, TSynchronizeLogEntry /*Entry*/,
  1334. const AnsiString Message)
  1335. {
  1336. PrintLine(Message);
  1337. }
  1338. //---------------------------------------------------------------------------
  1339. void __fastcall TConsoleRunner::SynchronizeControllerAbort(TObject * /*Sender*/,
  1340. bool /*Close*/)
  1341. {
  1342. FSynchronizeAborted = true;
  1343. }
  1344. //---------------------------------------------------------------------------
  1345. void __fastcall TConsoleRunner::SynchronizeControllerSynchronize(
  1346. TSynchronizeController * /*Sender*/, const AnsiString LocalDirectory,
  1347. const AnsiString RemoteDirectory, const TCopyParamType & CopyParam,
  1348. const TSynchronizeParamType & Params, TSynchronizeChecklist ** Checklist,
  1349. TSynchronizeOptions * /*Options*/, bool Full)
  1350. {
  1351. if (!Full)
  1352. {
  1353. FScript->Synchronize(LocalDirectory, RemoteDirectory, CopyParam,
  1354. Params.Params, Checklist);
  1355. }
  1356. }
  1357. //---------------------------------------------------------------------------
  1358. void __fastcall TConsoleRunner::SynchronizeControllerSynchronizeInvalid(
  1359. TSynchronizeController * /*Sender*/, const AnsiString Directory, const AnsiString ErrorStr)
  1360. {
  1361. if (!Directory.IsEmpty())
  1362. {
  1363. PrintLine(FMTLOAD(WATCH_ERROR_DIRECTORY, (Directory)));
  1364. }
  1365. else
  1366. {
  1367. PrintLine(LoadStr(WATCH_ERROR_GENERAL));
  1368. }
  1369. if (!ErrorStr.IsEmpty())
  1370. {
  1371. PrintLine(ErrorStr);
  1372. }
  1373. }
  1374. //---------------------------------------------------------------------------
  1375. void __fastcall TConsoleRunner::SynchronizeControllerTooManyDirectories(
  1376. TSynchronizeController * /*Sender*/, int & MaxDirectories)
  1377. {
  1378. if (Aborted())
  1379. {
  1380. Abort();
  1381. }
  1382. if (MaxDirectories < GUIConfiguration->MaxWatchDirectories)
  1383. {
  1384. MaxDirectories = GUIConfiguration->MaxWatchDirectories;
  1385. }
  1386. else
  1387. {
  1388. MaxDirectories *= 2;
  1389. }
  1390. }
  1391. //---------------------------------------------------------------------------
  1392. void __fastcall TConsoleRunner::ShowException(Exception * E)
  1393. {
  1394. AnsiString Message;
  1395. if (ExceptionMessage(E, Message))
  1396. {
  1397. FCommandError = true;
  1398. PrintMessage(Message);
  1399. ExtException * EE = dynamic_cast<ExtException *>(E);
  1400. if ((EE != NULL) && (EE->MoreMessages != NULL))
  1401. {
  1402. PrintMessage(EE->MoreMessages->Text);
  1403. }
  1404. }
  1405. }
  1406. //---------------------------------------------------------------------------
  1407. bool __fastcall TConsoleRunner::DoInput(AnsiString & Str, bool Echo, unsigned int Timeout)
  1408. {
  1409. bool Result = FConsole->Input(Str, Echo, Timeout);
  1410. if (Result)
  1411. {
  1412. while (!Str.IsEmpty() &&
  1413. ((Str[Str.Length()] == '\n') || (Str[Str.Length()] == '\r')))
  1414. {
  1415. Str.SetLength(Str.Length() - 1);
  1416. }
  1417. }
  1418. else
  1419. {
  1420. NotifyAbort();
  1421. }
  1422. return Result;
  1423. }
  1424. //---------------------------------------------------------------------------
  1425. void __fastcall TConsoleRunner::MasterPasswordPrompt()
  1426. {
  1427. AnsiString Password;
  1428. Input(LoadStr(CONSOLE_MASTER_PASSWORD_PROMPT), Password, false);
  1429. WinConfiguration->SetMasterPassword(Password);
  1430. }
  1431. //---------------------------------------------------------------------------
  1432. AnsiString TConsoleRunner::ExpandCommand(AnsiString Command, TStrings * ScriptParameters)
  1433. {
  1434. assert(ScriptParameters != NULL);
  1435. for (int Index = 0; Index < ScriptParameters->Count; Index++)
  1436. {
  1437. Command = StringReplace(Command, FORMAT("%%%d%%", (Index+1)),
  1438. ScriptParameters->Strings[Index], TReplaceFlags() << rfReplaceAll);
  1439. }
  1440. Command = ExpandEnvironmentVariables(Command);
  1441. return Command;
  1442. }
  1443. //---------------------------------------------------------------------------
  1444. int __fastcall TConsoleRunner::Run(const AnsiString Session, TOptions * Options,
  1445. TStrings * ScriptCommands, TStrings * ScriptParameters)
  1446. {
  1447. bool AnyError = false;
  1448. try
  1449. {
  1450. FScript = new TManagementScript(StoredSessions, FConsole->LimitedOutput());
  1451. try
  1452. {
  1453. FScript->CopyParam = GUIConfiguration->DefaultCopyParam;
  1454. FScript->SynchronizeParams = GUIConfiguration->SynchronizeParams;
  1455. FScript->OnPrint = ScriptPrint;
  1456. FScript->OnPrintProgress = ScriptPrintProgress;
  1457. FScript->OnInput = ScriptInput;
  1458. FScript->OnTerminalPromptUser = ScriptTerminalPromptUser;
  1459. FScript->OnShowExtendedException = ScriptShowExtendedException;
  1460. FScript->OnTerminalQueryUser = ScriptTerminalQueryUser;
  1461. FScript->OnQueryCancel = ScriptQueryCancel;
  1462. FScript->OnSynchronizeStartStop = ScriptSynchronizeStartStop;
  1463. UpdateTitle();
  1464. // everything until the first manually entered command is "batch"
  1465. // (including opening session from command line and script file)
  1466. FBatchScript = true;
  1467. if (!Session.IsEmpty())
  1468. {
  1469. FScript->Connect(Session, Options, false);
  1470. }
  1471. int ScriptPos = 0;
  1472. bool Result;
  1473. do
  1474. {
  1475. UpdateTitle();
  1476. AnsiString Command;
  1477. if ((ScriptCommands != NULL) && (ScriptPos < ScriptCommands->Count))
  1478. {
  1479. Result = true;
  1480. Command = ScriptCommands->Strings[ScriptPos];
  1481. ScriptPos++;
  1482. }
  1483. else
  1484. {
  1485. // no longer batch
  1486. FBatchScript = false;
  1487. Print("winscp> ");
  1488. Result = DoInput(Command, true, 0);
  1489. }
  1490. if (Result)
  1491. {
  1492. FCommandError = false;
  1493. FScript->Command(ExpandCommand(Command, ScriptParameters));
  1494. if (FCommandError)
  1495. {
  1496. FScript->Log(llMessage, "Failed");
  1497. AnyError = true;
  1498. if (FScript->Batch == TScript::BatchAbort)
  1499. {
  1500. Result = false;
  1501. }
  1502. }
  1503. if (FScript->Terminal != NULL)
  1504. {
  1505. FScript->Terminal->Idle();
  1506. }
  1507. }
  1508. }
  1509. while (Result && FScript->Continue && !Aborted());
  1510. }
  1511. __finally
  1512. {
  1513. delete FScript;
  1514. FScript = NULL;
  1515. }
  1516. }
  1517. catch(Exception & E)
  1518. {
  1519. ShowException(&E);
  1520. AnyError = true;
  1521. }
  1522. return AnyError ? RESULT_ANY_ERROR : RESULT_SUCCESS;
  1523. }
  1524. //---------------------------------------------------------------------------
  1525. void __fastcall TConsoleRunner::UpdateTitle()
  1526. {
  1527. AnsiString NewTitle;
  1528. if (FScript->Terminal != NULL)
  1529. {
  1530. NewTitle = FMTLOAD(APP_CAPTION, (FScript->Terminal->SessionData->SessionName, AppName));
  1531. }
  1532. else
  1533. {
  1534. NewTitle = AppName;
  1535. }
  1536. FConsole->SetTitle(NewTitle);
  1537. }
  1538. //---------------------------------------------------------------------------
  1539. void __fastcall LoadScriptFromFile(AnsiString FileName, TStrings * Lines)
  1540. {
  1541. AnsiString UTFBOM = "\xEF\xBB\xBF";
  1542. Lines->LoadFromFile(FileName);
  1543. if ((Lines->Count > 0) &&
  1544. (Lines->Strings[0].SubString(1, UTFBOM.Length()) == UTFBOM))
  1545. {
  1546. Lines->Strings[0] = Lines->Strings[0].SubString(
  1547. UTFBOM.Length() + 1, Lines->Strings[0].Length() - UTFBOM.Length());
  1548. for (int Index = 0; Index < Lines->Count; Index++)
  1549. {
  1550. Lines->Strings[Index] = DecodeUTF(Lines->Strings[Index]);
  1551. }
  1552. }
  1553. }
  1554. //---------------------------------------------------------------------------
  1555. void __fastcall Usage(TConsole * Console)
  1556. {
  1557. AnsiString Usage = LoadStr(USAGE6, 10240);
  1558. AnsiString ExeBaseName = ChangeFileExt(ExtractFileName(Application->ExeName), "");
  1559. Usage = StringReplace(Usage, "%APP%", ExeBaseName,
  1560. TReplaceFlags() << rfReplaceAll << rfIgnoreCase);
  1561. AnsiString Copyright = StringReplace(LoadStr(WINSCP_COPYRIGHT), "©", "(c)",
  1562. TReplaceFlags() << rfReplaceAll << rfIgnoreCase);
  1563. Usage = FORMAT(Usage, (Configuration->VersionStr, Copyright));
  1564. TStrings * Lines = new TStringList();
  1565. try
  1566. {
  1567. Lines->Text = Usage;
  1568. for (int Index = 0; Index < Lines->Count; Index++)
  1569. {
  1570. bool Print = true;
  1571. AnsiString Line = Lines->Strings[Index];
  1572. if ((Line.Length() >= 2) && (Line[2] == ':'))
  1573. {
  1574. switch (Line[1])
  1575. {
  1576. case 'G':
  1577. Print = !Console->CommandLineOnly();
  1578. break;
  1579. case 'C':
  1580. Print = Console->CommandLineOnly();
  1581. break;
  1582. case 'B':
  1583. Print = true;
  1584. break;
  1585. default:
  1586. assert(false);
  1587. break;
  1588. }
  1589. Line.Delete(1, 2);
  1590. }
  1591. if (Print)
  1592. {
  1593. Console->Print(Line + "\n");
  1594. }
  1595. }
  1596. }
  1597. __finally
  1598. {
  1599. delete Lines;
  1600. }
  1601. Console->WaitBeforeExit();
  1602. }
  1603. //---------------------------------------------------------------------------
  1604. int __fastcall Console(bool Help)
  1605. {
  1606. TProgramParams * Params = TProgramParams::Instance();
  1607. int Result = 0;
  1608. TConsole * Console = NULL;
  1609. TConsoleRunner * Runner = NULL;
  1610. TStrings * ScriptCommands = new TStringList();
  1611. TStrings * ScriptParameters = new TStringList();
  1612. try
  1613. {
  1614. AnsiString ConsoleInstance;
  1615. if (Params->FindSwitch("consoleinstance", ConsoleInstance))
  1616. {
  1617. Console = new TExternalConsole(ConsoleInstance);
  1618. }
  1619. else if (Params->FindSwitch("Console") || Help)
  1620. {
  1621. Console = TOwnConsole::Instance();
  1622. }
  1623. else
  1624. {
  1625. Console = new TNullConsole();
  1626. }
  1627. if (Help)
  1628. {
  1629. Usage(Console);
  1630. }
  1631. else
  1632. {
  1633. Runner = new TConsoleRunner(Console);
  1634. try
  1635. {
  1636. AnsiString Value;
  1637. if (Params->FindSwitch("script", Value) && !Value.IsEmpty())
  1638. {
  1639. LoadScriptFromFile(Value, ScriptCommands);
  1640. }
  1641. Params->FindSwitch("command", ScriptCommands);
  1642. Params->FindSwitch("parameter", ScriptParameters);
  1643. bool Url = false;
  1644. AnsiString Session;
  1645. if (Params->ParamCount >= 1)
  1646. {
  1647. Session = Params->Param[1];
  1648. }
  1649. bool DefaultsOnly;
  1650. delete StoredSessions->ParseUrl(Session, Params, DefaultsOnly,
  1651. NULL, &Url);
  1652. if (Url || Params->FindSwitch("Unsafe"))
  1653. {
  1654. // prevent any automatic action when URL is provided on
  1655. // command-line (the check is duplicated in Execute())
  1656. if ((ScriptCommands->Count > 0) || Params->FindSwitch("Log"))
  1657. {
  1658. Console->Print(LoadStr(UNSAFE_ACTIONS_DISABLED) + "\n");
  1659. }
  1660. ScriptCommands->Clear();
  1661. }
  1662. else
  1663. {
  1664. AnsiString LogFile;
  1665. if (Params->FindSwitch("Log", LogFile))
  1666. {
  1667. Configuration->TemporaryLogging(LogFile);
  1668. }
  1669. }
  1670. Result = Runner->Run(Session, Params,
  1671. (ScriptCommands->Count > 0 ? ScriptCommands : NULL),
  1672. ScriptParameters);
  1673. }
  1674. catch(Exception & E)
  1675. {
  1676. Runner->ShowException(&E);
  1677. Result = RESULT_ANY_ERROR;
  1678. }
  1679. }
  1680. }
  1681. __finally
  1682. {
  1683. delete Runner;
  1684. delete Console;
  1685. delete ScriptCommands;
  1686. delete ScriptParameters;
  1687. }
  1688. return Result;
  1689. }