ConsoleRunner.cpp 62 KB

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