ConsoleRunner.cpp 52 KB

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