ConsoleRunner.cpp 47 KB

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