ConsoleRunner.cpp 54 KB

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