ConsoleRunner.cpp 65 KB

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