ConsoleRunner.cpp 53 KB

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