ConsoleRunner.cpp 61 KB

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