ConsoleRunner.cpp 64 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185
  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. };
  493. //---------------------------------------------------------------------------
  494. __fastcall TExternalConsole::TExternalConsole(
  495. const UnicodeString Instance, bool NoInteractiveInput)
  496. {
  497. UnicodeString Name;
  498. Name = FORMAT(L"%s%s", (CONSOLE_EVENT_REQUEST, (Instance)));
  499. FRequestEvent = OpenEvent(EVENT_ALL_ACCESS, false, Name.c_str());
  500. Name = FORMAT(L"%s%s", (CONSOLE_EVENT_RESPONSE, (Instance)));
  501. FResponseEvent = OpenEvent(EVENT_ALL_ACCESS, false, Name.c_str());
  502. Name = FORMAT(L"%s%s", (CONSOLE_EVENT_CANCEL, (Instance)));
  503. FCancelEvent = OpenEvent(EVENT_ALL_ACCESS, false, Name.c_str());
  504. Name = FORMAT(L"%s%s", (CONSOLE_MAPPING, (Instance)));
  505. FFileMapping = OpenFileMapping(FILE_MAP_ALL_ACCESS, false, Name.c_str());
  506. if ((FRequestEvent == NULL) || (FResponseEvent == NULL) || (FFileMapping == NULL))
  507. {
  508. throw Exception(LoadStr(EXTERNAL_CONSOLE_INIT_ERROR));
  509. }
  510. HANDLE Job = OpenJobObject(JOB_OBJECT_ASSIGN_PROCESS, FALSE,
  511. FORMAT(L"%s%s", (CONSOLE_JOB, Instance)).c_str());
  512. if (ALWAYS_TRUE(Job != NULL))
  513. {
  514. AssignProcessToJobObject(Job, GetCurrentProcess());
  515. // winscp.com/winscp.dll keeps the only reference to the job.
  516. // once it gets closed (because winscp.com if forcefully terminated),
  517. // we get terminated as well
  518. CloseHandle(Job);
  519. }
  520. TConsoleCommStruct * CommStruct = GetCommStruct();
  521. try
  522. {
  523. if (CommStruct->Version != TConsoleCommStruct::CurrentVersion)
  524. {
  525. throw Exception(FMTLOAD(EXTERNAL_CONSOLE_INCOMPATIBLE, (CommStruct->Version)));
  526. }
  527. CommStruct->Version = TConsoleCommStruct::CurrentVersionConfirmed;
  528. }
  529. __finally
  530. {
  531. FreeCommStruct(CommStruct);
  532. }
  533. // to break application event loop regularly during "watching for changes"
  534. // to allow user to abort it
  535. SetTimer(Application->Handle, 1, 500, NULL);
  536. FNoInteractiveInput = NoInteractiveInput;
  537. Init();
  538. }
  539. //---------------------------------------------------------------------------
  540. __fastcall TExternalConsole::~TExternalConsole()
  541. {
  542. CloseHandle(FRequestEvent);
  543. CloseHandle(FResponseEvent);
  544. CloseHandle(FCancelEvent);
  545. CloseHandle(FFileMapping);
  546. KillTimer(Application->Handle, 1);
  547. }
  548. //---------------------------------------------------------------------------
  549. TConsoleCommStruct * __fastcall TExternalConsole::GetCommStruct()
  550. {
  551. TConsoleCommStruct * Result;
  552. Result = static_cast<TConsoleCommStruct*>(MapViewOfFile(FFileMapping,
  553. FILE_MAP_ALL_ACCESS, 0, 0, 0));
  554. if (Result == NULL)
  555. {
  556. throw Exception(LoadStr(CONSOLE_COMM_ERROR));
  557. }
  558. return Result;
  559. }
  560. //---------------------------------------------------------------------------
  561. void __fastcall TExternalConsole::FreeCommStruct(TConsoleCommStruct * CommStruct)
  562. {
  563. UnmapViewOfFile(CommStruct);
  564. }
  565. //---------------------------------------------------------------------------
  566. void __fastcall TExternalConsole::SendEvent(int Timeout)
  567. {
  568. SetEvent(FRequestEvent);
  569. unsigned int Result = WaitForSingleObject(FResponseEvent, Timeout);
  570. if (Result != WAIT_OBJECT_0)
  571. {
  572. UnicodeString Message = LoadStr(CONSOLE_SEND_TIMEOUT);
  573. if (FPipeOutput)
  574. {
  575. Message = FORMAT("%s %s", (Message, LoadStr(CONSOLE_SEND_PIPE)));
  576. }
  577. throw Exception(Message);
  578. }
  579. }
  580. //---------------------------------------------------------------------------
  581. void __fastcall TExternalConsole::Print(UnicodeString Str, bool FromBeginning)
  582. {
  583. // need to do at least one iteration, even when Str is empty (new line)
  584. do
  585. {
  586. TConsoleCommStruct * CommStruct = GetCommStruct();
  587. try
  588. {
  589. size_t MaxLen = LENOF(CommStruct->PrintEvent.Message) - 1;
  590. UnicodeString Piece = Str.SubString(1, MaxLen);
  591. Str.Delete(1, MaxLen);
  592. CommStruct->Event = TConsoleCommStruct::PRINT;
  593. wcscpy(CommStruct->PrintEvent.Message, Piece.c_str());
  594. CommStruct->PrintEvent.FromBeginning = FromBeginning;
  595. // In the next iteration we need to append never overwrite.
  596. // Note that this won't work properly for disk/pipe outputs,
  597. // when the next line is also FromBeginning,
  598. // as !FromBeginning print effectively commits previous FromBeginning print.
  599. // On the other hand, FromBeginning print is always initiated by us,
  600. // and it's not likely we ever issue print over 10 KB.
  601. FromBeginning = false;
  602. }
  603. __finally
  604. {
  605. FreeCommStruct(CommStruct);
  606. }
  607. SendEvent(PrintTimeout);
  608. }
  609. while (!Str.IsEmpty());
  610. }
  611. //---------------------------------------------------------------------------
  612. bool __fastcall TExternalConsole::Input(UnicodeString & Str, bool Echo, unsigned int Timer)
  613. {
  614. TConsoleCommStruct * CommStruct = GetCommStruct();
  615. try
  616. {
  617. CommStruct->Event = TConsoleCommStruct::INPUT;
  618. CommStruct->InputEvent.Echo = Echo;
  619. CommStruct->InputEvent.Result = false;
  620. CommStruct->InputEvent.Str[0] = L'\0';
  621. CommStruct->InputEvent.Timer = Timer;
  622. }
  623. __finally
  624. {
  625. FreeCommStruct(CommStruct);
  626. }
  627. SendEvent(INFINITE);
  628. bool Result;
  629. CommStruct = GetCommStruct();
  630. try
  631. {
  632. Result = CommStruct->InputEvent.Result;
  633. Str = CommStruct->InputEvent.Str;
  634. }
  635. __finally
  636. {
  637. FreeCommStruct(CommStruct);
  638. }
  639. return Result;
  640. }
  641. //---------------------------------------------------------------------------
  642. int __fastcall TExternalConsole::Choice(UnicodeString Options, int Cancel, int Break,
  643. int Timeouted, bool Timeouting, unsigned int Timer)
  644. {
  645. TConsoleCommStruct * CommStruct = GetCommStruct();
  646. try
  647. {
  648. CommStruct->Event = TConsoleCommStruct::CHOICE;
  649. assert(Options.Length() < static_cast<int>(LENOF(CommStruct->ChoiceEvent.Options)));
  650. wcscpy(CommStruct->ChoiceEvent.Options, Options.c_str());
  651. CommStruct->ChoiceEvent.Cancel = Cancel;
  652. CommStruct->ChoiceEvent.Break = Break;
  653. CommStruct->ChoiceEvent.Result = Break;
  654. CommStruct->ChoiceEvent.Timeouted = Timeouted;
  655. CommStruct->ChoiceEvent.Timer = Timer;
  656. CommStruct->ChoiceEvent.Timeouting = Timeouting;
  657. }
  658. __finally
  659. {
  660. FreeCommStruct(CommStruct);
  661. }
  662. SendEvent(INFINITE);
  663. int Result;
  664. CommStruct = GetCommStruct();
  665. try
  666. {
  667. Result = CommStruct->ChoiceEvent.Result;
  668. }
  669. __finally
  670. {
  671. FreeCommStruct(CommStruct);
  672. }
  673. return Result;
  674. }
  675. //---------------------------------------------------------------------------
  676. bool __fastcall TExternalConsole::PendingAbort()
  677. {
  678. return (WaitForSingleObject(FCancelEvent, 0) == WAIT_OBJECT_0);
  679. }
  680. //---------------------------------------------------------------------------
  681. void __fastcall TExternalConsole::SetTitle(UnicodeString Title)
  682. {
  683. TConsoleCommStruct * CommStruct = GetCommStruct();
  684. try
  685. {
  686. // Truncate to maximum allowed. Title over 10 KB won't fit to screen anyway
  687. Title = Title.SubString(1, LENOF(CommStruct->TitleEvent.Title) - 1);
  688. CommStruct->Event = TConsoleCommStruct::TITLE;
  689. wcscpy(CommStruct->TitleEvent.Title, Title.c_str());
  690. }
  691. __finally
  692. {
  693. FreeCommStruct(CommStruct);
  694. }
  695. SendEvent(INFINITE);
  696. }
  697. //---------------------------------------------------------------------------
  698. void __fastcall TExternalConsole::Init()
  699. {
  700. TConsoleCommStruct * CommStruct = GetCommStruct();
  701. try
  702. {
  703. CommStruct->Event = TConsoleCommStruct::INIT;
  704. CommStruct->InitEvent.WantsProgress = false;
  705. }
  706. __finally
  707. {
  708. FreeCommStruct(CommStruct);
  709. }
  710. SendEvent(INFINITE);
  711. CommStruct = GetCommStruct();
  712. try
  713. {
  714. FLimitedOutput = (CommStruct->InitEvent.OutputType == FILE_TYPE_CHAR);
  715. FLiveOutput =
  716. (CommStruct->InitEvent.OutputType != FILE_TYPE_DISK) &&
  717. (CommStruct->InitEvent.OutputType != FILE_TYPE_PIPE);
  718. FPipeOutput = (CommStruct->InitEvent.OutputType != FILE_TYPE_PIPE);
  719. FWantsProgress = CommStruct->InitEvent.WantsProgress;
  720. }
  721. __finally
  722. {
  723. FreeCommStruct(CommStruct);
  724. }
  725. }
  726. //---------------------------------------------------------------------------
  727. bool __fastcall TExternalConsole::LimitedOutput()
  728. {
  729. return FLimitedOutput;
  730. }
  731. //---------------------------------------------------------------------------
  732. bool __fastcall TExternalConsole::LiveOutput()
  733. {
  734. return FLiveOutput;
  735. }
  736. //---------------------------------------------------------------------------
  737. bool __fastcall TExternalConsole::NoInteractiveInput()
  738. {
  739. return FNoInteractiveInput;
  740. }
  741. //---------------------------------------------------------------------------
  742. void __fastcall TExternalConsole::WaitBeforeExit()
  743. {
  744. // noop
  745. }
  746. //---------------------------------------------------------------------------
  747. bool __fastcall TExternalConsole::CommandLineOnly()
  748. {
  749. return true;
  750. }
  751. //---------------------------------------------------------------------------
  752. bool __fastcall TExternalConsole::WantsProgress()
  753. {
  754. return FWantsProgress;
  755. }
  756. //---------------------------------------------------------------------------
  757. void __fastcall TExternalConsole::Progress(const TScriptProgress & Progress)
  758. {
  759. TConsoleCommStruct * CommStruct = GetCommStruct();
  760. try
  761. {
  762. CommStruct->Event = TConsoleCommStruct::PROGRESS;
  763. typedef TConsoleCommStruct::TProgressEvent TProgressEvent;
  764. TProgressEvent & ProgressEvent = CommStruct->ProgressEvent;
  765. switch (Progress.Operation)
  766. {
  767. case foCopy:
  768. case foMove:
  769. ProgressEvent.Operation = TProgressEvent::COPY;
  770. break;
  771. default:
  772. FAIL;
  773. }
  774. switch (Progress.Side)
  775. {
  776. case osLocal:
  777. ProgressEvent.Side = TProgressEvent::LOCAL;
  778. break;
  779. case osRemote:
  780. ProgressEvent.Side = TProgressEvent::REMOTE;
  781. break;
  782. default:
  783. FAIL;
  784. }
  785. wcsncpy(ProgressEvent.FileName, Progress.FileName.c_str(), LENOF(ProgressEvent.FileName));
  786. NULL_TERMINATE(ProgressEvent.FileName);
  787. wcsncpy(ProgressEvent.Directory, Progress.Directory.c_str(), LENOF(ProgressEvent.Directory));
  788. NULL_TERMINATE(ProgressEvent.Directory);
  789. ProgressEvent.OverallProgress = Progress.OverallProgress;
  790. ProgressEvent.FileProgress = Progress.FileProgress;
  791. ProgressEvent.CPS = Progress.CPS;
  792. }
  793. __finally
  794. {
  795. FreeCommStruct(CommStruct);
  796. }
  797. SendEvent(INFINITE);
  798. // nothing to read from response, just wait for it
  799. FreeCommStruct(GetCommStruct());
  800. }
  801. //---------------------------------------------------------------------------
  802. class TNullConsole : public TConsole
  803. {
  804. public:
  805. __fastcall TNullConsole();
  806. virtual void __fastcall Print(UnicodeString Str, bool FromBeginning = false);
  807. virtual bool __fastcall Input(UnicodeString & Str, bool Echo, unsigned int Timer);
  808. virtual int __fastcall Choice(UnicodeString Options, int Cancel, int Break,
  809. int Timeouted, bool Timeouting, unsigned int Timer);
  810. virtual bool __fastcall PendingAbort();
  811. virtual void __fastcall SetTitle(UnicodeString Title);
  812. virtual bool __fastcall LimitedOutput();
  813. virtual bool __fastcall LiveOutput();
  814. virtual bool __fastcall NoInteractiveInput();
  815. virtual void __fastcall WaitBeforeExit();
  816. virtual bool __fastcall CommandLineOnly();
  817. virtual bool __fastcall WantsProgress();
  818. virtual void __fastcall Progress(const TScriptProgress & Progress);
  819. };
  820. //---------------------------------------------------------------------------
  821. __fastcall TNullConsole::TNullConsole()
  822. {
  823. }
  824. //---------------------------------------------------------------------------
  825. void __fastcall TNullConsole::Print(UnicodeString /*Str*/, bool /*FromBeginning*/)
  826. {
  827. // noop
  828. }
  829. //---------------------------------------------------------------------------
  830. bool __fastcall TNullConsole::Input(UnicodeString & /*Str*/, bool /*Echo*/,
  831. unsigned int /*Timer*/)
  832. {
  833. return false;
  834. }
  835. //---------------------------------------------------------------------------
  836. int __fastcall TNullConsole::Choice(UnicodeString /*Options*/, int /*Cancel*/,
  837. int Break, int Timeouted, bool Timeouting, unsigned int Timer)
  838. {
  839. int Result;
  840. if (Timeouting)
  841. {
  842. Sleep(Timer);
  843. Result = Timeouted;
  844. }
  845. else
  846. {
  847. Result = Break;
  848. }
  849. return Result;
  850. }
  851. //---------------------------------------------------------------------------
  852. bool __fastcall TNullConsole::PendingAbort()
  853. {
  854. return false;
  855. }
  856. //---------------------------------------------------------------------------
  857. void __fastcall TNullConsole::SetTitle(UnicodeString /*Title*/)
  858. {
  859. // noop
  860. }
  861. //---------------------------------------------------------------------------
  862. bool __fastcall TNullConsole::LimitedOutput()
  863. {
  864. return false;
  865. }
  866. //---------------------------------------------------------------------------
  867. bool __fastcall TNullConsole::LiveOutput()
  868. {
  869. return false;
  870. }
  871. //---------------------------------------------------------------------------
  872. bool __fastcall TNullConsole::NoInteractiveInput()
  873. {
  874. // do not matter, even if we return false,
  875. // it fails immediately afterwards in TNullConsole::Input
  876. return true;
  877. }
  878. //---------------------------------------------------------------------------
  879. void __fastcall TNullConsole::WaitBeforeExit()
  880. {
  881. FAIL;
  882. // noop
  883. }
  884. //---------------------------------------------------------------------------
  885. bool __fastcall TNullConsole::CommandLineOnly()
  886. {
  887. FAIL;
  888. return false;
  889. }
  890. //---------------------------------------------------------------------------
  891. bool __fastcall TNullConsole::WantsProgress()
  892. {
  893. return false;
  894. }
  895. //---------------------------------------------------------------------------
  896. void __fastcall TNullConsole::Progress(const TScriptProgress & /*Progress*/)
  897. {
  898. FAIL;
  899. }
  900. //---------------------------------------------------------------------------
  901. static UnicodeString TimestampVarName(L"TIMESTAMP");
  902. //---------------------------------------------------------------------------
  903. class TConsoleRunner
  904. {
  905. public:
  906. TConsoleRunner(TConsole * Console);
  907. ~TConsoleRunner();
  908. int __fastcall Run(const UnicodeString Session, TOptions * Options,
  909. TStrings * ScriptCommands, TStrings * ScriptParameters);
  910. void __fastcall ShowException(Exception * E);
  911. protected:
  912. bool __fastcall DoInput(UnicodeString & Str, bool Echo, unsigned int Timer,
  913. bool Interactive);
  914. void __fastcall Input(const UnicodeString Prompt, UnicodeString & Str,
  915. bool Echo, bool Interactive);
  916. inline void __fastcall Print(const UnicodeString & Str, bool FromBeginning = false);
  917. inline void __fastcall PrintLine(const UnicodeString & Str);
  918. inline void __fastcall PrintMessage(const UnicodeString & Str);
  919. void __fastcall UpdateTitle();
  920. inline void __fastcall NotifyAbort();
  921. inline bool __fastcall Aborted(bool AllowCompleteAbort = true);
  922. void __fastcall MasterPasswordPrompt();
  923. void __fastcall DoShowException(TTerminal * Terminal, Exception * E);
  924. private:
  925. TManagementScript * FScript;
  926. TConsole * FConsole;
  927. TSynchronizeController FSynchronizeController;
  928. int FLastProgressLen;
  929. bool FSynchronizeAborted;
  930. bool FCommandError;
  931. bool FBatchScript;
  932. bool FAborted;
  933. TTimer * Timer;
  934. bool FExternalTimestampVar;
  935. void __fastcall ScriptPrint(TScript * Script, const UnicodeString Str);
  936. void __fastcall ScriptPrintProgress(TScript * Script, bool First, const UnicodeString Str);
  937. void __fastcall ScriptInput(TScript * Script, const UnicodeString Prompt, UnicodeString & Str);
  938. void __fastcall ScriptTerminalPromptUser(TTerminal * Terminal,
  939. TPromptKind Kind, UnicodeString Name, UnicodeString Instructions, TStrings * Prompts,
  940. TStrings * Results, bool & Result, void * Arg);
  941. void __fastcall ScriptShowExtendedException(TTerminal * Terminal,
  942. Exception * E, void * Arg);
  943. void __fastcall ScriptTerminalQueryUser(TObject * Sender, const UnicodeString Query,
  944. TStrings * MoreMessages, unsigned int Answers, const TQueryParams * Params, unsigned int & Answer,
  945. TQueryType QueryType, void * Arg);
  946. void __fastcall ScriptQueryCancel(TScript * Script, bool & Cancel);
  947. void __fastcall SynchronizeControllerAbort(TObject * Sender, bool Close);
  948. void __fastcall SynchronizeControllerLog(TSynchronizeController * Controller,
  949. TSynchronizeLogEntry Entry, const UnicodeString Message);
  950. void __fastcall ScriptSynchronizeStartStop(TScript * Script,
  951. const UnicodeString LocalDirectory, const UnicodeString RemoteDirectory,
  952. const TCopyParamType & CopyParam, int SynchronizeParams);
  953. void __fastcall SynchronizeControllerSynchronize(TSynchronizeController * Sender,
  954. const UnicodeString LocalDirectory, const UnicodeString RemoteDirectory,
  955. const TCopyParamType & CopyParam, const TSynchronizeParamType & Params,
  956. TSynchronizeChecklist ** Checklist, TSynchronizeOptions * Options, bool Full);
  957. void __fastcall SynchronizeControllerSynchronizeInvalid(TSynchronizeController * Sender,
  958. const UnicodeString Directory, const UnicodeString ErrorStr);
  959. void __fastcall SynchronizeControllerTooManyDirectories(TSynchronizeController * Sender,
  960. int & MaxDirectories);
  961. unsigned int InputTimeout();
  962. void __fastcall TimerTimer(TObject * Sender);
  963. UnicodeString ExpandCommand(UnicodeString Command, TStrings * ScriptParameters);
  964. void __fastcall Failed(bool & AnyError);
  965. void __fastcall ScriptProgress(TScript * Script, const TScriptProgress & Progress);
  966. void __fastcall ConfigurationChange(TObject * Sender);
  967. };
  968. //---------------------------------------------------------------------------
  969. TConsoleRunner::TConsoleRunner(TConsole * Console) :
  970. FSynchronizeController(&SynchronizeControllerSynchronize,
  971. &SynchronizeControllerSynchronizeInvalid,
  972. &SynchronizeControllerTooManyDirectories)
  973. {
  974. FConsole = Console;
  975. FLastProgressLen = 0;
  976. FScript = NULL;
  977. FAborted = false;
  978. FBatchScript = false;
  979. Timer = new TTimer(Application);
  980. Timer->OnTimer = TimerTimer;
  981. Timer->Interval = MSecsPerSec;
  982. Timer->Enabled = true;
  983. assert(WinConfiguration->OnMasterPasswordPrompt == NULL);
  984. WinConfiguration->OnMasterPasswordPrompt = MasterPasswordPrompt;
  985. assert(Configuration->OnChange == NULL);
  986. FExternalTimestampVar = !GetEnvironmentVariable(TimestampVarName).IsEmpty();
  987. Configuration->OnChange = ConfigurationChange;
  988. }
  989. //---------------------------------------------------------------------------
  990. TConsoleRunner::~TConsoleRunner()
  991. {
  992. assert(WinConfiguration->OnMasterPasswordPrompt == MasterPasswordPrompt);
  993. WinConfiguration->OnMasterPasswordPrompt = NULL;
  994. assert(Configuration->OnChange == ConfigurationChange);
  995. Configuration->OnChange = NULL;
  996. delete Timer;
  997. }
  998. //---------------------------------------------------------------------------
  999. void __fastcall TConsoleRunner::TimerTimer(TObject * /*Sender*/)
  1000. {
  1001. // sole presence of timer causes message to be dispatched,
  1002. // hence breaks the loops
  1003. }
  1004. //---------------------------------------------------------------------------
  1005. unsigned int TConsoleRunner::InputTimeout()
  1006. {
  1007. return ((FScript != NULL) && (FScript->Batch != TScript::BatchOff) ? BATCH_INPUT_TIMEOUT : 0);
  1008. }
  1009. //---------------------------------------------------------------------------
  1010. void __fastcall TConsoleRunner::Input(
  1011. const UnicodeString Prompt, UnicodeString & Str, bool Echo, bool Interactive)
  1012. {
  1013. Print(Prompt);
  1014. if (!DoInput(Str, Echo, InputTimeout(), Interactive))
  1015. {
  1016. Abort();
  1017. }
  1018. }
  1019. //---------------------------------------------------------------------------
  1020. void __fastcall TConsoleRunner::ScriptInput(TScript * /*Script*/,
  1021. const UnicodeString Prompt, UnicodeString & Str)
  1022. {
  1023. Input(Prompt, Str, true, true);
  1024. }
  1025. //---------------------------------------------------------------------------
  1026. void __fastcall TConsoleRunner::Print(const UnicodeString & Str, bool FromBeginning)
  1027. {
  1028. if (FLastProgressLen > 0)
  1029. {
  1030. FConsole->Print(L"\n" + Str, FromBeginning);
  1031. FLastProgressLen = 0;
  1032. }
  1033. else
  1034. {
  1035. FConsole->Print(Str, FromBeginning);
  1036. }
  1037. }
  1038. //---------------------------------------------------------------------------
  1039. void __fastcall TConsoleRunner::PrintLine(const UnicodeString & Str)
  1040. {
  1041. Print(Str + L"\n");
  1042. }
  1043. //---------------------------------------------------------------------------
  1044. void __fastcall TConsoleRunner::PrintMessage(const UnicodeString & Str)
  1045. {
  1046. UnicodeString Line =
  1047. ReplaceStr(ReplaceStr(Str.TrimRight(), L"\n\n", L"\n"),
  1048. L"\n \n", L"\n");
  1049. if (FScript != NULL)
  1050. {
  1051. // this also logs the message
  1052. FScript->PrintLine(Line);
  1053. }
  1054. else
  1055. {
  1056. PrintLine(Line);
  1057. }
  1058. }
  1059. //---------------------------------------------------------------------------
  1060. void __fastcall TConsoleRunner::NotifyAbort()
  1061. {
  1062. if (FBatchScript)
  1063. {
  1064. FAborted = true;
  1065. }
  1066. }
  1067. //---------------------------------------------------------------------------
  1068. bool __fastcall TConsoleRunner::Aborted(bool AllowCompleteAbort)
  1069. {
  1070. bool Result;
  1071. if (FAborted)
  1072. {
  1073. Result = true;
  1074. }
  1075. else
  1076. {
  1077. Result = FConsole->PendingAbort();
  1078. if (Result)
  1079. {
  1080. PrintMessage(LoadStr(USER_TERMINATED));
  1081. if (AllowCompleteAbort)
  1082. {
  1083. NotifyAbort();
  1084. }
  1085. }
  1086. }
  1087. return Result;
  1088. }
  1089. //---------------------------------------------------------------------------
  1090. void __fastcall TConsoleRunner::ScriptPrint(TScript * /*Script*/,
  1091. const UnicodeString Str)
  1092. {
  1093. Print(Str);
  1094. }
  1095. //---------------------------------------------------------------------------
  1096. void __fastcall TConsoleRunner::ScriptPrintProgress(TScript * /*Script*/,
  1097. bool First, const UnicodeString Str)
  1098. {
  1099. UnicodeString S = Str;
  1100. if (First && (FLastProgressLen > 0))
  1101. {
  1102. S = L"\n" + S;
  1103. }
  1104. else if (S.Length() < FLastProgressLen)
  1105. {
  1106. int Padding = FLastProgressLen - S.Length();
  1107. S += UnicodeString::StringOfChar(L' ', Padding) +
  1108. UnicodeString::StringOfChar(L'\b', Padding);
  1109. }
  1110. FConsole->Print(S, true);
  1111. FLastProgressLen = Str.Length();
  1112. }
  1113. //---------------------------------------------------------------------------
  1114. void __fastcall TConsoleRunner::ScriptTerminalPromptUser(TTerminal * /*Terminal*/,
  1115. TPromptKind /*Kind*/, UnicodeString Name, UnicodeString Instructions, TStrings * Prompts,
  1116. TStrings * Results, bool & Result, void * /*Arg*/)
  1117. {
  1118. if (!Instructions.IsEmpty())
  1119. {
  1120. PrintMessage(Instructions);
  1121. }
  1122. // if there are no prompts, success is default
  1123. Result = true;
  1124. for (int Index = 0; Index < Prompts->Count; Index++)
  1125. {
  1126. UnicodeString Prompt = Prompts->Strings[Index];
  1127. if (!Prompt.IsEmpty() && (Prompt[Prompt.Length()] != L' '))
  1128. {
  1129. Prompt += L' ';
  1130. }
  1131. int P = Prompt.Pos(L'&');
  1132. if (P > 0)
  1133. {
  1134. Prompt.Delete(P, 1);
  1135. }
  1136. Print(Prompt);
  1137. UnicodeString AResult = Results->Strings[Index]; // useless
  1138. bool Echo = FLAGSET(int(Prompts->Objects[Index]), pupEcho);
  1139. Result = DoInput(AResult, Echo, InputTimeout(), true);
  1140. Results->Strings[Index] = AResult;
  1141. }
  1142. }
  1143. //---------------------------------------------------------------------------
  1144. void __fastcall TConsoleRunner::ScriptShowExtendedException(
  1145. TTerminal * Terminal, Exception * E, void * /*Arg*/)
  1146. {
  1147. DoShowException(Terminal, E);
  1148. }
  1149. //---------------------------------------------------------------------------
  1150. void __fastcall TConsoleRunner::ScriptTerminalQueryUser(TObject * /*Sender*/,
  1151. const UnicodeString Query, TStrings * MoreMessages, unsigned int Answers,
  1152. const TQueryParams * Params, unsigned int & Answer, TQueryType /*QueryType*/,
  1153. void * /*Arg*/)
  1154. {
  1155. UnicodeString AQuery = Query;
  1156. unsigned int Timer = 0;
  1157. unsigned int Timeout = 0;
  1158. unsigned int TimeoutA = 0;
  1159. unsigned int NoBatchA = 0;
  1160. if (Params != NULL)
  1161. {
  1162. if (Params->Timeout > 0)
  1163. {
  1164. Timeout = Params->Timeout;
  1165. TimeoutA = Params->TimeoutAnswer;
  1166. }
  1167. if (Params->Timer > 0)
  1168. {
  1169. Timer = Params->Timer;
  1170. if (Params->TimerAnswers > 0)
  1171. {
  1172. Answers = Params->TimerAnswers;
  1173. }
  1174. // not considering TimerQueryType as we do not use QueryType anyway
  1175. if (!Params->TimerMessage.IsEmpty())
  1176. {
  1177. AQuery = Params->TimerMessage;
  1178. }
  1179. }
  1180. if (FLAGSET(Params->Params, qpFatalAbort))
  1181. {
  1182. AQuery = FMTLOAD(WARN_FATAL_ERROR, (AQuery));
  1183. }
  1184. NoBatchA = Params->NoBatchAnswers;
  1185. }
  1186. AQuery = UnformatMessage(AQuery);
  1187. AQuery = RemoveInteractiveMsgTag(AQuery);
  1188. ApplyTabs(AQuery, L' ', NULL, NULL);
  1189. unsigned int AAnswers = Answers;
  1190. PrintMessage(AQuery);
  1191. if ((MoreMessages != NULL) && (MoreMessages->Count > 0))
  1192. {
  1193. PrintMessage(MoreMessages->Text);
  1194. }
  1195. std::vector<unsigned int> Buttons;
  1196. std::vector<UnicodeString> Captions;
  1197. std::vector<TNotifyEvent> OnClicks;
  1198. for (unsigned int Answer = qaFirst; Answer <= qaLast; Answer = Answer << 1)
  1199. {
  1200. if (FLAGSET(Answers, Answer))
  1201. {
  1202. UnicodeString Name; // unused
  1203. UnicodeString Caption;
  1204. AnswerNameAndCaption(Answer, Name, Caption);
  1205. Captions.push_back(Caption);
  1206. Buttons.push_back(Answer);
  1207. OnClicks.push_back(NULL);
  1208. AAnswers -= Answer;
  1209. }
  1210. }
  1211. USEDPARAM(AAnswers);
  1212. assert(AAnswers == 0);
  1213. assert(!Buttons.empty());
  1214. if ((Params != NULL) && (Params->Aliases != NULL))
  1215. {
  1216. for (unsigned int bi = 0; bi < Buttons.size(); bi++)
  1217. {
  1218. for (unsigned int ai = 0; ai < Params->AliasesCount; ai++)
  1219. {
  1220. if (Params->Aliases[ai].Button == Buttons[bi])
  1221. {
  1222. if (!Params->Aliases[ai].Alias.IsEmpty())
  1223. {
  1224. Captions[bi] = Params->Aliases[ai].Alias;
  1225. }
  1226. OnClicks[bi] = Params->Aliases[ai].OnClick;
  1227. break;
  1228. }
  1229. }
  1230. }
  1231. }
  1232. UnicodeString Accels;
  1233. for (unsigned int Index = 0; Index < Buttons.size(); Index++)
  1234. {
  1235. UnicodeString & Caption = Captions[Index];
  1236. int P = Caption.Pos(L'&');
  1237. if ((P > 0) && (P < Caption.Length()))
  1238. {
  1239. wchar_t Accel = AnsiUpperCase(Caption)[P + 1];
  1240. if (Accels.Pos(Accel) > 0)
  1241. {
  1242. Caption.Delete(P, 1);
  1243. Accels += L' ';
  1244. }
  1245. else
  1246. {
  1247. Accels += Accel;
  1248. }
  1249. }
  1250. else
  1251. {
  1252. Accels += L' ';
  1253. }
  1254. }
  1255. assert(Accels.Length() == static_cast<int>(Buttons.size()));
  1256. int NumberAccel = 0;
  1257. unsigned int CancelA = CancelAnswer(Answers);
  1258. int CancelIndex;
  1259. unsigned int AbortA = AbortAnswer(Answers & ~NoBatchA);
  1260. int AbortIndex;
  1261. unsigned int ContinueA = ContinueAnswer(Answers & ~NoBatchA);
  1262. int ContinueIndex;
  1263. int TimeoutIndex = 0;
  1264. for (unsigned int Index = 0; Index < Buttons.size(); Index++)
  1265. {
  1266. UnicodeString & Caption = Captions[Index];
  1267. if (Accels[Index + 1] == L' ')
  1268. {
  1269. for (int Index2 = 1; Index2 <= Caption.Length(); Index2++)
  1270. {
  1271. wchar_t C = AnsiUpperCase(Caption)[Index2];
  1272. if (IsLetter(C) && (Accels.Pos(C) == 0))
  1273. {
  1274. Caption.Insert(L"&", Index2);
  1275. Accels[Index + 1] = C;
  1276. break;
  1277. }
  1278. }
  1279. }
  1280. if (Accels[Index + 1] == L' ')
  1281. {
  1282. for (int Index2 = 1; Index2 <= Caption.Length(); Index2++)
  1283. {
  1284. wchar_t C = AnsiUpperCase(Caption)[Index2];
  1285. if ((C != L' ') && (Accels.Pos(C) == 0))
  1286. {
  1287. Caption.Insert(L"&", Index2);
  1288. Accels[Index + 1] = C;
  1289. break;
  1290. }
  1291. }
  1292. }
  1293. if (Accels[Index + 1] == L' ')
  1294. {
  1295. NumberAccel++;
  1296. assert(NumberAccel <= 9);
  1297. Caption = FORMAT(L"&%d%s", (NumberAccel, Caption));
  1298. Accels[Index + 1] = Caption[2];
  1299. }
  1300. if (Buttons[Index] == CancelA)
  1301. {
  1302. CancelIndex = Index + 1;
  1303. }
  1304. if (Buttons[Index] == AbortA)
  1305. {
  1306. AbortIndex = Index + 1;
  1307. }
  1308. if (Buttons[Index] == ContinueA)
  1309. {
  1310. ContinueIndex = Index + 1;
  1311. }
  1312. if (Buttons[Index] == TimeoutA)
  1313. {
  1314. TimeoutIndex = Index + 1;
  1315. }
  1316. }
  1317. assert(Accels.Pos(L' ') == 0);
  1318. bool Timeouting = (Timeout > 0);
  1319. bool FirstOutput = true;
  1320. do
  1321. {
  1322. Answer = 0;
  1323. int AnswerIndex;
  1324. bool Retry;
  1325. do
  1326. {
  1327. Retry = false;
  1328. if (FirstOutput || FConsole->LiveOutput())
  1329. {
  1330. UnicodeString Output;
  1331. for (unsigned int i = 0; i < Buttons.size(); i++)
  1332. {
  1333. if (i > 0)
  1334. {
  1335. Output += L", ";
  1336. }
  1337. UnicodeString Caption = Captions[i];
  1338. int P = Caption.Pos(L'&');
  1339. if (ALWAYS_TRUE(P >= 0))
  1340. {
  1341. Caption[P] = L'(';
  1342. Caption.Insert(L")", P + 2);
  1343. }
  1344. if (i + 1 == static_cast<unsigned int>(TimeoutIndex))
  1345. {
  1346. assert(Timeouting);
  1347. Caption = FMTLOAD(TIMEOUT_BUTTON, (Caption, int(Timeout / MSecsPerSec)));
  1348. }
  1349. Output += Caption;
  1350. }
  1351. Output += L": ";
  1352. // note that length of string may decrease over time due to number of
  1353. // seconds length, but supposing it decreases by one character at time
  1354. // at most, we do not mind as the prompt is terminated with space
  1355. // If output is not live (file or pipe), do not use 'from beginning'
  1356. // as it means that the output is not actually stored until new line
  1357. // is sent (and we will not [because we cannot] rewrite the output anyway)
  1358. Print(Output, !FirstOutput);
  1359. FirstOutput = false;
  1360. }
  1361. if (!Timeouting && (FScript->Batch == TScript::BatchContinue))
  1362. {
  1363. AnswerIndex = ContinueIndex;
  1364. }
  1365. else if (!Timeouting && (FScript->Batch != TScript::BatchOff))
  1366. {
  1367. AnswerIndex = AbortIndex;
  1368. }
  1369. else if (Timeouting && (Timeout < MSecsPerSec))
  1370. {
  1371. AnswerIndex = TimeoutIndex;
  1372. }
  1373. else
  1374. {
  1375. unsigned int ActualTimer =
  1376. (Timeouting && ((Timer == 0) || (Timer > MSecsPerSec)) ? MSecsPerSec : Timer);
  1377. AnswerIndex = FConsole->Choice(Accels, CancelIndex, -1, -2,
  1378. Timeouting, ActualTimer);
  1379. if (AnswerIndex == -1)
  1380. {
  1381. NotifyAbort();
  1382. AnswerIndex = AbortIndex;
  1383. }
  1384. else if (AnswerIndex == -2)
  1385. {
  1386. if (Timeouting)
  1387. {
  1388. assert(Timeout >= MSecsPerSec);
  1389. Timeout -= ActualTimer;
  1390. Retry = true;
  1391. }
  1392. // this does not take Timer into account,
  1393. // but as of now Timer is used for TSecureShell timeout prompt only,
  1394. // where Timer is less than MSecsPerSec
  1395. if (Timer > 0)
  1396. {
  1397. assert((Params != NULL) && (Params->TimerEvent != NULL));
  1398. if ((Params != NULL) && (Params->TimerEvent != NULL))
  1399. {
  1400. unsigned int AAnswer = 0;
  1401. Params->TimerEvent(AAnswer);
  1402. if (AAnswer != 0)
  1403. {
  1404. Answer = AAnswer;
  1405. Retry = false;
  1406. }
  1407. else
  1408. {
  1409. Retry = true;
  1410. }
  1411. }
  1412. }
  1413. }
  1414. }
  1415. }
  1416. while (Retry);
  1417. if (Answer == 0)
  1418. {
  1419. assert((AnswerIndex >= 1) && (AnswerIndex <= Accels.Length()));
  1420. UnicodeString AnswerCaption = Captions[AnswerIndex - 1];
  1421. int P = AnswerCaption.Pos(L"&");
  1422. assert(P >= 0);
  1423. AnswerCaption.Delete(P, 1);
  1424. PrintLine(AnswerCaption);
  1425. FirstOutput = true;
  1426. if (OnClicks[AnswerIndex - 1] != NULL)
  1427. {
  1428. OnClicks[AnswerIndex - 1](NULL);
  1429. }
  1430. else
  1431. {
  1432. Answer = Buttons[AnswerIndex - 1];
  1433. }
  1434. }
  1435. else
  1436. {
  1437. PrintLine(L"");
  1438. }
  1439. }
  1440. while (Answer == 0);
  1441. if ((Answer == AbortA) &&
  1442. ((Params == NULL) || 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. TDateTime N = Now();
  1657. if (!FExternalTimestampVar)
  1658. {
  1659. Command =
  1660. ReplaceStr(Command, FORMAT(L"%%%s%%", (TimestampVarName)), FormatDateTime(L"yyyymmddhhnnss", N));
  1661. }
  1662. int Offset = 1;
  1663. int P2;
  1664. do
  1665. {
  1666. int P = Pos(UpperCase(L"%" + TimestampVarName + L"#"), UpperCase(Command.SubString(Offset, Command.Length() - Offset + 1)));
  1667. if (P > 0)
  1668. {
  1669. P += Offset - 1;
  1670. Offset = P + 1 + TimestampVarName.Length() + 1;
  1671. P2 = Pos(L"%", Command.SubString(Offset, Command.Length() - Offset + 1));
  1672. if (P2 > 0)
  1673. {
  1674. UnicodeString TimestampFormat = Command.SubString(Offset, P2 - 1);
  1675. UnicodeString TimestampValue = FormatDateTime(TimestampFormat, N);
  1676. Command = Command.SubString(1, P - 1) + TimestampValue + Command.SubString(Offset + P2, Command.Length() - Offset - P2 + 1);
  1677. Offset = P + TimestampValue.Length();
  1678. }
  1679. }
  1680. else
  1681. {
  1682. P2 = 0;
  1683. }
  1684. }
  1685. while (P2 > 0);
  1686. Command = ExpandEnvironmentVariables(Command);
  1687. return Command;
  1688. }
  1689. //---------------------------------------------------------------------------
  1690. void __fastcall TConsoleRunner::Failed(bool & AnyError)
  1691. {
  1692. if (FScript != NULL)
  1693. {
  1694. FScript->Log(llMessage, L"Failed");
  1695. }
  1696. AnyError = true;
  1697. }
  1698. //---------------------------------------------------------------------------
  1699. int __fastcall TConsoleRunner::Run(const UnicodeString Session, TOptions * Options,
  1700. TStrings * ScriptCommands, TStrings * ScriptParameters)
  1701. {
  1702. int ExitCode;
  1703. try
  1704. {
  1705. bool AnyError = false;
  1706. try
  1707. {
  1708. FScript = new TManagementScript(StoredSessions, FConsole->LimitedOutput());
  1709. FScript->CopyParam = GUIConfiguration->DefaultCopyParam;
  1710. FScript->SynchronizeParams = GUIConfiguration->SynchronizeParams;
  1711. FScript->WantsProgress = FConsole->WantsProgress();
  1712. FScript->OnPrint = ScriptPrint;
  1713. FScript->OnPrintProgress = ScriptPrintProgress;
  1714. FScript->OnInput = ScriptInput;
  1715. FScript->OnTerminalPromptUser = ScriptTerminalPromptUser;
  1716. FScript->OnShowExtendedException = ScriptShowExtendedException;
  1717. FScript->OnTerminalQueryUser = ScriptTerminalQueryUser;
  1718. FScript->OnQueryCancel = ScriptQueryCancel;
  1719. FScript->OnSynchronizeStartStop = ScriptSynchronizeStartStop;
  1720. FScript->OnProgress = ScriptProgress;
  1721. UpdateTitle();
  1722. // everything until the first manually entered command is "batch"
  1723. // (including opening session from command line and script file)
  1724. FBatchScript = true;
  1725. if (!Session.IsEmpty())
  1726. {
  1727. PrintMessage(LoadStr(SCRIPT_CMDLINE_SESSION));
  1728. FCommandError = false;
  1729. FScript->Connect(Session, Options, false);
  1730. if (FCommandError)
  1731. {
  1732. Failed(AnyError);
  1733. }
  1734. }
  1735. FScript->Groups = Options->SwitchValue(L"xmlgroups", true, false);
  1736. int ScriptPos = 0;
  1737. bool Result;
  1738. do
  1739. {
  1740. UpdateTitle();
  1741. UnicodeString Command;
  1742. if ((ScriptCommands != NULL) && (ScriptPos < ScriptCommands->Count))
  1743. {
  1744. Result = true;
  1745. Command = ScriptCommands->Strings[ScriptPos];
  1746. ScriptPos++;
  1747. }
  1748. else
  1749. {
  1750. if (FBatchScript)
  1751. {
  1752. // no longer batch
  1753. FBatchScript = false;
  1754. FScript->StartInteractive();
  1755. }
  1756. Print(L"winscp> ");
  1757. Result = DoInput(Command, true, 0, false);
  1758. }
  1759. if (Result)
  1760. {
  1761. FCommandError = false;
  1762. FScript->Command(ExpandCommand(Command, ScriptParameters));
  1763. if (FCommandError)
  1764. {
  1765. Failed(AnyError);
  1766. if (FScript->Batch == TScript::BatchAbort)
  1767. {
  1768. Result = false;
  1769. }
  1770. }
  1771. if (FScript->Terminal != NULL)
  1772. {
  1773. FScript->Terminal->Idle();
  1774. }
  1775. }
  1776. }
  1777. while (Result && FScript->Continue && !Aborted());
  1778. }
  1779. catch(Exception & E)
  1780. {
  1781. Failed(AnyError);
  1782. ShowException(&E);
  1783. }
  1784. if (FLastProgressLen > 0)
  1785. {
  1786. FConsole->Print(L"\n");
  1787. FLastProgressLen = 0;
  1788. }
  1789. ExitCode = AnyError ? RESULT_ANY_ERROR : RESULT_SUCCESS;
  1790. if (FScript != NULL)
  1791. {
  1792. FScript->Log(llMessage, FORMAT(L"Exit code: %d", (ExitCode)));
  1793. }
  1794. }
  1795. __finally
  1796. {
  1797. delete FScript;
  1798. FScript = NULL;
  1799. }
  1800. return ExitCode;
  1801. }
  1802. //---------------------------------------------------------------------------
  1803. void __fastcall TConsoleRunner::UpdateTitle()
  1804. {
  1805. UnicodeString NewTitle;
  1806. if (FScript->Terminal != NULL)
  1807. {
  1808. NewTitle = FormatMainFormCaption(FScript->Terminal->SessionData->SessionName);
  1809. }
  1810. else
  1811. {
  1812. NewTitle = FormatMainFormCaption(L"");
  1813. }
  1814. FConsole->SetTitle(NewTitle);
  1815. }
  1816. //---------------------------------------------------------------------------
  1817. void __fastcall TConsoleRunner::ConfigurationChange(TObject * /*Sender*/)
  1818. {
  1819. if (FScript != NULL)
  1820. {
  1821. FScript->ReflectSettings();
  1822. }
  1823. }
  1824. //---------------------------------------------------------------------------
  1825. void __fastcall LoadScriptFromFile(UnicodeString FileName, TStrings * Lines)
  1826. {
  1827. Lines->LoadFromFile(FileName);
  1828. }
  1829. //---------------------------------------------------------------------------
  1830. void __fastcall ConsolePrintLine(TConsole * Console, const UnicodeString & Str)
  1831. {
  1832. Console->Print(Str + L"\n");
  1833. }
  1834. //---------------------------------------------------------------------------
  1835. void __fastcall Usage(TConsole * Console)
  1836. {
  1837. UnicodeString Usage = LoadStr(USAGE10, 10240);
  1838. UnicodeString ExeBaseName = ExtractFileBaseName(Application->ExeName);
  1839. Usage = ReplaceText(Usage, L"%APP%", ExeBaseName);
  1840. UnicodeString Copyright =
  1841. ReplaceText(LoadStr(WINSCP_COPYRIGHT), L"©", L"(c)");
  1842. Usage = FORMAT(Usage, (Configuration->VersionStr, Copyright));
  1843. std::unique_ptr<TStrings> Lines(TextToStringList(Usage));
  1844. for (int Index = 0; Index < Lines->Count; Index++)
  1845. {
  1846. bool Print = true;
  1847. UnicodeString Line = Lines->Strings[Index];
  1848. if ((Line.Length() >= 2) && (Line[2] == L':'))
  1849. {
  1850. switch (Line[1])
  1851. {
  1852. case L'G':
  1853. Print = !Console->CommandLineOnly();
  1854. break;
  1855. case L'C':
  1856. Print = Console->CommandLineOnly();
  1857. break;
  1858. case L'B':
  1859. Print = true;
  1860. break;
  1861. default:
  1862. FAIL;
  1863. break;
  1864. }
  1865. Line.Delete(1, 2);
  1866. }
  1867. if (Print)
  1868. {
  1869. ConsolePrintLine(Console, Line);
  1870. }
  1871. }
  1872. Console->WaitBeforeExit();
  1873. }
  1874. //---------------------------------------------------------------------------
  1875. void __fastcall BatchSettings(TConsole * Console, TProgramParams * Params)
  1876. {
  1877. std::unique_ptr<TStrings> Arguments(new TStringList());
  1878. if (ALWAYS_TRUE(Params->FindSwitch(L"batchsettings", Arguments.get())))
  1879. {
  1880. if (Arguments->Count < 1)
  1881. {
  1882. ConsolePrintLine(Console, LoadStr(BATCH_SET_NO_MASK));
  1883. }
  1884. else if (Arguments->Count < 2)
  1885. {
  1886. ConsolePrintLine(Console, LoadStr(BATCH_SET_NO_SETTINGS));
  1887. }
  1888. else
  1889. {
  1890. TFileMasks Mask(Arguments->Strings[0]);
  1891. Arguments->Delete(0);
  1892. std::unique_ptr<TOptionsStorage> OptionsStorage(new TOptionsStorage(Arguments.get()));
  1893. int Matches = 0;
  1894. int Changes = 0;
  1895. for (int Index = 0; Index < StoredSessions->Count; Index++)
  1896. {
  1897. TSessionData * Data = StoredSessions->Sessions[Index];
  1898. if (!Data->IsWorkspace &&
  1899. Mask.Matches(Data->Name, false, false))
  1900. {
  1901. Matches++;
  1902. std::unique_ptr<TSessionData> OriginalData(new TSessionData(L""));
  1903. OriginalData->Assign(Data);
  1904. Data->ApplyRawSettings(OptionsStorage.get());
  1905. bool Changed = !OriginalData->IsSame(Data, false);
  1906. if (Changed)
  1907. {
  1908. Changes++;
  1909. }
  1910. UnicodeString StateStr = LoadStr(Changed ? BATCH_SET_CHANGED : BATCH_SET_NOT_CHANGED);
  1911. ConsolePrintLine(Console, FORMAT(L"%s - %s", (Data->Name, StateStr)));
  1912. }
  1913. }
  1914. StoredSessions->Save(false, true); // explicit
  1915. ConsolePrintLine(Console, FMTLOAD(BATCH_SET_SUMMARY, (Matches, Changes)));
  1916. }
  1917. Console->WaitBeforeExit();
  1918. }
  1919. }
  1920. //---------------------------------------------------------------------------
  1921. int __fastcall Console(TConsoleMode Mode)
  1922. {
  1923. assert(Mode != cmNone);
  1924. TProgramParams * Params = TProgramParams::Instance();
  1925. int Result = 0;
  1926. TConsole * Console = NULL;
  1927. TConsoleRunner * Runner = NULL;
  1928. TStrings * ScriptCommands = new TStringList();
  1929. TStrings * ScriptParameters = new TStringList();
  1930. try
  1931. {
  1932. UnicodeString ConsoleInstance;
  1933. // First check for /consoleinstance as /console is always used by winscp.com
  1934. if (Params->FindSwitch(L"consoleinstance", ConsoleInstance))
  1935. {
  1936. Configuration->Usage->Inc(L"ConsoleExternal");
  1937. Console = new TExternalConsole(ConsoleInstance, Params->FindSwitch(L"nointeractiveinput"));
  1938. }
  1939. else if (Params->FindSwitch(L"Console") || (Mode != cmScripting))
  1940. {
  1941. Configuration->Usage->Inc(L"ConsoleOwn");
  1942. Console = TOwnConsole::Instance();
  1943. }
  1944. else
  1945. {
  1946. Configuration->Usage->Inc(L"ConsoleNull");
  1947. Console = new TNullConsole();
  1948. }
  1949. SetNoGUI();
  1950. if (Mode == cmHelp)
  1951. {
  1952. Configuration->Usage->Inc(L"UsageShown");
  1953. Usage(Console);
  1954. }
  1955. else if (Mode == cmBatchSettings)
  1956. {
  1957. if (CheckSafe(Params))
  1958. {
  1959. Configuration->Usage->Inc(L"BatchSettings");
  1960. BatchSettings(Console, Params);
  1961. }
  1962. }
  1963. else
  1964. {
  1965. Runner = new TConsoleRunner(Console);
  1966. try
  1967. {
  1968. if (CheckSafe(Params))
  1969. {
  1970. UnicodeString Value;
  1971. if (Params->FindSwitch(L"script", Value) && !Value.IsEmpty())
  1972. {
  1973. Configuration->Usage->Inc(L"ScriptFile");
  1974. LoadScriptFromFile(Value, ScriptCommands);
  1975. }
  1976. Params->FindSwitch(L"command", ScriptCommands);
  1977. if (ScriptCommands->Count > 0)
  1978. {
  1979. Configuration->Usage->Inc(L"ScriptCommands");
  1980. }
  1981. Params->FindSwitch(L"parameter", ScriptParameters);
  1982. if (ScriptParameters->Count > 0)
  1983. {
  1984. Configuration->Usage->Inc(L"ScriptParameters");
  1985. }
  1986. }
  1987. UnicodeString Session;
  1988. if (Params->ParamCount >= 1)
  1989. {
  1990. Session = Params->Param[1];
  1991. }
  1992. bool DefaultsOnly;
  1993. delete StoredSessions->ParseUrl(Session, Params, DefaultsOnly);
  1994. UnicodeString LogFile;
  1995. if (Params->FindSwitch(L"Log", LogFile) && CheckSafe(Params))
  1996. {
  1997. Configuration->Usage->Inc(L"ScriptLog");
  1998. Configuration->TemporaryLogging(LogFile);
  1999. }
  2000. CheckXmlLogParam(Params);
  2001. Result = Runner->Run(Session, Params,
  2002. (ScriptCommands->Count > 0 ? ScriptCommands : NULL),
  2003. ScriptParameters);
  2004. }
  2005. catch(Exception & E)
  2006. {
  2007. Runner->ShowException(&E);
  2008. Result = RESULT_ANY_ERROR;
  2009. }
  2010. }
  2011. }
  2012. __finally
  2013. {
  2014. delete Runner;
  2015. delete Console;
  2016. delete ScriptCommands;
  2017. delete ScriptParameters;
  2018. }
  2019. return Result;
  2020. }