ConsoleRunner.cpp 42 KB

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