ConsoleRunner.cpp 77 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508
  1. //---------------------------------------------------------------------------
  2. #include <vcl.h>
  3. #pragma hdrstop
  4. #include <Common.h>
  5. #include <Exceptions.h>
  6. #include <Script.h>
  7. #include <CoreMain.h>
  8. #include <Terminal.h>
  9. #include <PuttyTools.h>
  10. #include <Queue.h>
  11. #include <HierarchicalStorage.h>
  12. #include <Consts.hpp>
  13. #include <StrUtils.hpp>
  14. #include "Console.h"
  15. #include "WinInterface.h"
  16. #include "ProgParams.h"
  17. #include "TextsWin.h"
  18. #include "TextsCore.h"
  19. #include "WinConfiguration.h"
  20. #include "SynchronizeController.h"
  21. #include "GUITools.h"
  22. #include "VCLCommon.h"
  23. enum { RESULT_SUCCESS = 0, RESULT_ANY_ERROR = 1 };
  24. //---------------------------------------------------------------------------
  25. #define WM_INTERUPT_IDLE (WM_WINSCP_USER + 3)
  26. #define BATCH_INPUT_TIMEOUT 10000
  27. //---------------------------------------------------------------------------
  28. #pragma package(smart_init)
  29. //---------------------------------------------------------------------------
  30. void TrimNewLine(UnicodeString & Str)
  31. {
  32. while (!Str.IsEmpty() &&
  33. ((Str[Str.Length()] == L'\n') || (Str[Str.Length()] == L'\r')))
  34. {
  35. Str.SetLength(Str.Length() - 1);
  36. }
  37. }
  38. //---------------------------------------------------------------------------
  39. class TConsole
  40. {
  41. public:
  42. virtual __fastcall ~TConsole() {};
  43. virtual void __fastcall Print(UnicodeString Str, bool FromBeginning = false) = 0;
  44. virtual bool __fastcall Input(UnicodeString & Str, bool Echo, unsigned int Timer) = 0;
  45. virtual int __fastcall Choice(UnicodeString Options, int Cancel, int Break,
  46. int Timeouted, bool Timeouting, unsigned int Timer) = 0;
  47. virtual bool __fastcall PendingAbort() = 0;
  48. virtual void __fastcall SetTitle(UnicodeString Title) = 0;
  49. virtual bool __fastcall LimitedOutput() = 0;
  50. virtual bool __fastcall LiveOutput() = 0;
  51. virtual bool __fastcall NoInteractiveInput() = 0;
  52. virtual void __fastcall WaitBeforeExit() = 0;
  53. virtual bool __fastcall CommandLineOnly() = 0;
  54. virtual bool __fastcall WantsProgress() = 0;
  55. virtual void __fastcall Progress(const TScriptProgress & Progress) = 0;
  56. };
  57. //---------------------------------------------------------------------------
  58. class TOwnConsole : public TConsole
  59. {
  60. public:
  61. static TOwnConsole * __fastcall Instance();
  62. virtual void __fastcall Print(UnicodeString Str, bool FromBeginning = false);
  63. virtual bool __fastcall Input(UnicodeString & Str, bool Echo, unsigned int Timer);
  64. virtual int __fastcall Choice(UnicodeString Options, int Cancel, int Break,
  65. int Timeouted, bool Timeouting, unsigned int Timer);
  66. virtual bool __fastcall PendingAbort();
  67. virtual void __fastcall SetTitle(UnicodeString Title);
  68. virtual bool __fastcall LimitedOutput();
  69. virtual bool __fastcall LiveOutput();
  70. virtual bool __fastcall NoInteractiveInput();
  71. virtual void __fastcall WaitBeforeExit();
  72. virtual bool __fastcall CommandLineOnly();
  73. virtual bool __fastcall WantsProgress();
  74. virtual void __fastcall Progress(const TScriptProgress & Progress);
  75. protected:
  76. static TOwnConsole * FInstance;
  77. friend class TConsoleInputThread;
  78. __fastcall TOwnConsole();
  79. virtual __fastcall ~TOwnConsole();
  80. void __fastcall BreakInput();
  81. void __fastcall CancelInput();
  82. static BOOL WINAPI HandlerRoutine(DWORD CtrlType);
  83. void __fastcall WindowStateTimer(TObject * Sender);
  84. void __fastcall ProcessMessages();
  85. void __fastcall TrayIconClick(TObject * Sender);
  86. private:
  87. HANDLE FInput;
  88. HANDLE FOutput;
  89. HWND FConsoleWindow;
  90. TTimer * FWindowStateTimer;
  91. bool FMinimized;
  92. ::TTrayIcon * FTrayIcon;
  93. static std::unique_ptr<TCriticalSection> FSection;
  94. bool FPendingAbort;
  95. };
  96. //---------------------------------------------------------------------------
  97. TOwnConsole * TOwnConsole::FInstance = NULL;
  98. std::unique_ptr<TCriticalSection> TOwnConsole::FSection(new TCriticalSection());
  99. //---------------------------------------------------------------------------
  100. __fastcall TOwnConsole::TOwnConsole()
  101. {
  102. DebugAssert(FInstance == NULL);
  103. FInstance = this;
  104. AllocConsole();
  105. SetConsoleCtrlHandler(HandlerRoutine, true);
  106. FInput = GetStdHandle(STD_INPUT_HANDLE);
  107. FOutput = GetStdHandle(STD_OUTPUT_HANDLE);
  108. FPendingAbort = false;
  109. FConsoleWindow = NULL;
  110. FWindowStateTimer = NULL;
  111. FMinimized = false;
  112. FTrayIcon = new ::TTrayIcon(0);
  113. FTrayIcon->OnClick = TrayIconClick;
  114. if (WinConfiguration->MinimizeToTray)
  115. {
  116. FConsoleWindow = GetConsoleWindow();
  117. if (ALWAYS_TRUE(FConsoleWindow != NULL))
  118. {
  119. FWindowStateTimer = new TTimer(Application);
  120. FWindowStateTimer->OnTimer = WindowStateTimer;
  121. FWindowStateTimer->Interval = 250;
  122. FWindowStateTimer->Enabled = true;
  123. }
  124. }
  125. }
  126. //---------------------------------------------------------------------------
  127. __fastcall TOwnConsole::~TOwnConsole()
  128. {
  129. TGuard Guard(FSection.get());
  130. delete FTrayIcon;
  131. delete FWindowStateTimer;
  132. // deliberately do not remove ConsoleCtrlHandler as it causes
  133. // failures while exiting
  134. FreeConsole();
  135. DebugAssert(FInstance == this);
  136. FInstance = NULL;
  137. }
  138. //---------------------------------------------------------------------------
  139. TOwnConsole * __fastcall TOwnConsole::Instance()
  140. {
  141. return new TOwnConsole();
  142. }
  143. //---------------------------------------------------------------------------
  144. void __fastcall TOwnConsole::WindowStateTimer(TObject * /*Sender*/)
  145. {
  146. DebugAssert(FConsoleWindow != NULL);
  147. WINDOWPLACEMENT Placement;
  148. memset(&Placement, 0, sizeof(Placement));
  149. Placement.length = sizeof(Placement);
  150. if (GetWindowPlacement(FConsoleWindow, &Placement))
  151. {
  152. bool Minimized = (Placement.showCmd == SW_SHOWMINIMIZED);
  153. if (FMinimized != Minimized)
  154. {
  155. FMinimized = Minimized;
  156. if (FMinimized && WinConfiguration->MinimizeToTray)
  157. {
  158. FTrayIcon->Visible = true;
  159. ShowWindow(FConsoleWindow, SW_HIDE);
  160. }
  161. else
  162. {
  163. FTrayIcon->Visible = false;
  164. ShowWindow(FConsoleWindow, SW_SHOW);
  165. }
  166. }
  167. }
  168. else
  169. {
  170. FAIL;
  171. }
  172. }
  173. //---------------------------------------------------------------------------
  174. void __fastcall TOwnConsole::ProcessMessages()
  175. {
  176. // as of now, there's no point doing this unless we have icon tray
  177. // (i.e. we need to monitor window state and eventually process tray icon messages)
  178. if (FWindowStateTimer != NULL)
  179. {
  180. DebugAssert(WinConfiguration->MinimizeToTray);
  181. Application->ProcessMessages();
  182. }
  183. }
  184. //---------------------------------------------------------------------------
  185. void __fastcall TOwnConsole::TrayIconClick(TObject * /*Sender*/)
  186. {
  187. DebugAssert(FConsoleWindow != NULL);
  188. SetForegroundWindow(FConsoleWindow);
  189. ShowWindow(FConsoleWindow, SW_RESTORE);
  190. }
  191. //---------------------------------------------------------------------------
  192. void __fastcall TOwnConsole::BreakInput()
  193. {
  194. FlushConsoleInputBuffer(FInput);
  195. INPUT_RECORD InputRecord;
  196. memset(&InputRecord, 0, sizeof(InputRecord));
  197. InputRecord.EventType = KEY_EVENT;
  198. InputRecord.Event.KeyEvent.bKeyDown = true;
  199. InputRecord.Event.KeyEvent.wRepeatCount = 1;
  200. InputRecord.Event.KeyEvent.uChar.UnicodeChar = L'\r';
  201. unsigned long Written;
  202. // this assertion occasionally fails (when console is being exited)
  203. CHECK(WriteConsoleInput(FInput, &InputRecord, 1, &Written));
  204. DebugAssert(Written == 1);
  205. CancelInput();
  206. }
  207. //---------------------------------------------------------------------------
  208. void __fastcall TOwnConsole::CancelInput()
  209. {
  210. FPendingAbort = true;
  211. PostMessage(Application->Handle, WM_INTERUPT_IDLE, 0, 0);
  212. }
  213. //---------------------------------------------------------------------------
  214. BOOL WINAPI TOwnConsole::HandlerRoutine(DWORD CtrlType)
  215. {
  216. if ((CtrlType == CTRL_C_EVENT) || (CtrlType == CTRL_BREAK_EVENT))
  217. {
  218. {
  219. TGuard Guard(FSection.get());
  220. // just to be real thread-safe
  221. if (FInstance != NULL)
  222. {
  223. FInstance->CancelInput();
  224. }
  225. }
  226. return true;
  227. }
  228. else
  229. {
  230. return false;
  231. }
  232. }
  233. //---------------------------------------------------------------------------
  234. bool __fastcall TOwnConsole::PendingAbort()
  235. {
  236. if (FPendingAbort)
  237. {
  238. FPendingAbort = false;
  239. return true;
  240. }
  241. else
  242. {
  243. return FPendingAbort;
  244. }
  245. }
  246. //---------------------------------------------------------------------------
  247. void __fastcall TOwnConsole::Print(UnicodeString Str, bool FromBeginning)
  248. {
  249. if (FromBeginning)
  250. {
  251. CONSOLE_SCREEN_BUFFER_INFO BufferInfo;
  252. GetConsoleScreenBufferInfo(FOutput, &BufferInfo);
  253. BufferInfo.dwCursorPosition.X = 0;
  254. SetConsoleCursorPosition(FOutput, BufferInfo.dwCursorPosition);
  255. }
  256. unsigned long Written;
  257. bool Result = WriteConsole(FOutput, Str.c_str(), Str.Length(), &Written, NULL);
  258. DebugAssert(Result);
  259. USEDPARAM(Result);
  260. DebugAssert(Str.Length() == static_cast<long>(Written));
  261. ProcessMessages();
  262. }
  263. //---------------------------------------------------------------------------
  264. class TConsoleInputThread : public TSimpleThread
  265. {
  266. public:
  267. __fastcall TConsoleInputThread(HANDLE Input, UnicodeString & Str, bool & Result) :
  268. FInput(Input),
  269. FStr(Str),
  270. FResult(Result)
  271. {
  272. }
  273. virtual __fastcall ~TConsoleInputThread()
  274. {
  275. Close();
  276. }
  277. protected:
  278. virtual void __fastcall Execute()
  279. {
  280. unsigned long Read;
  281. FStr.SetLength(10240);
  282. FResult = ReadConsole(FInput, FStr.c_str(), FStr.Length(), &Read, NULL);
  283. DebugAssert(FResult);
  284. FStr.SetLength(Read);
  285. TrimNewLine(FStr);
  286. }
  287. virtual void __fastcall Terminate()
  288. {
  289. TOwnConsole::FInstance->BreakInput();
  290. }
  291. private:
  292. HANDLE FInput;
  293. UnicodeString & FStr;
  294. bool & FResult;
  295. };
  296. //---------------------------------------------------------------------------
  297. bool __fastcall TOwnConsole::Input(UnicodeString & Str, bool Echo, unsigned int Timer)
  298. {
  299. unsigned long PrevMode, NewMode;
  300. GetConsoleMode(FInput, &PrevMode);
  301. NewMode = PrevMode | ENABLE_PROCESSED_INPUT | ENABLE_LINE_INPUT;
  302. if (Echo)
  303. {
  304. NewMode |= ENABLE_ECHO_INPUT;
  305. }
  306. else
  307. {
  308. NewMode &= ~ENABLE_ECHO_INPUT;
  309. }
  310. SetConsoleMode(FInput, NewMode);
  311. bool Result = false;
  312. try
  313. {
  314. {
  315. const int FirstKey = VK_LBUTTON; // 0x01
  316. const int LastKey = VK_OEM_CLEAR; // 0xFE
  317. // reset key state
  318. for (int Key = FirstKey; Key <= LastKey; Key++)
  319. {
  320. GetAsyncKeyState(Key);
  321. }
  322. TConsoleInputThread InputThread(FInput, Str, Result);
  323. InputThread.Start();
  324. double TimerD = double(Timer)/MSecsPerDay;
  325. double End = Now() + TimerD;
  326. while (!InputThread.IsFinished() &&
  327. ((Timer == 0) || (double(Now()) < End)))
  328. {
  329. ProcessMessages();
  330. InputThread.WaitFor(50);
  331. for (int Key = FirstKey; Key <= LastKey; Key++)
  332. {
  333. if ((GetAsyncKeyState(Key) & 0x01) != 0)
  334. {
  335. End = Now() + TimerD;
  336. // Finishing the loop nevertheless to reset state of all keys
  337. }
  338. }
  339. }
  340. }
  341. if (FPendingAbort || !Echo)
  342. {
  343. Print(L"\n");
  344. }
  345. if (FPendingAbort || (Str.Length() == 0))
  346. {
  347. Result = false;
  348. FPendingAbort = false;
  349. }
  350. }
  351. __finally
  352. {
  353. SetConsoleMode(FInput, PrevMode);
  354. }
  355. return Result;
  356. }
  357. //---------------------------------------------------------------------------
  358. int __fastcall TOwnConsole::Choice(UnicodeString Options, int Cancel, int Break,
  359. int Timeouted, bool /*Timeouting*/, unsigned int Timer)
  360. {
  361. unsigned int ATimer = Timer;
  362. int Result = 0;
  363. unsigned long PrevMode, NewMode;
  364. GetConsoleMode(FInput, &PrevMode);
  365. NewMode = (PrevMode | ENABLE_PROCESSED_INPUT) & ~(ENABLE_LINE_INPUT | ENABLE_ECHO_INPUT);
  366. SetConsoleMode(FInput, NewMode);
  367. try
  368. {
  369. do
  370. {
  371. unsigned long Read;
  372. INPUT_RECORD Record;
  373. if ((PeekConsoleInput(FInput, &Record, 1, &Read) != 0) &&
  374. (Read == 1))
  375. {
  376. if ((ReadConsoleInput(FInput, &Record, 1, &Read) != 0) &&
  377. (Read == 1))
  378. {
  379. if (PendingAbort())
  380. {
  381. Result = Break;
  382. }
  383. else if ((Record.EventType == KEY_EVENT) &&
  384. Record.Event.KeyEvent.bKeyDown)
  385. {
  386. wchar_t C = AnsiUpperCase(Record.Event.KeyEvent.uChar.UnicodeChar)[1];
  387. if (C == 27)
  388. {
  389. Result = Cancel;
  390. }
  391. else if ((Options.Pos(C) > 0) &&
  392. FLAGCLEAR(Record.Event.KeyEvent.dwControlKeyState,
  393. LEFT_CTRL_PRESSED | RIGHT_CTRL_PRESSED | LEFT_ALT_PRESSED |
  394. RIGHT_ALT_PRESSED))
  395. {
  396. Result = Options.Pos(C);
  397. }
  398. }
  399. }
  400. }
  401. if (Result == 0)
  402. {
  403. unsigned int TimerSlice = 50;
  404. Sleep(TimerSlice);
  405. if (Timer > 0)
  406. {
  407. if (ATimer > TimerSlice)
  408. {
  409. ATimer -= TimerSlice;
  410. }
  411. else
  412. {
  413. Result = Timeouted;
  414. }
  415. }
  416. }
  417. ProcessMessages();
  418. }
  419. while (Result == 0);
  420. }
  421. __finally
  422. {
  423. SetConsoleMode(FInput, PrevMode);
  424. }
  425. return Result;
  426. }
  427. //---------------------------------------------------------------------------
  428. void __fastcall TOwnConsole::SetTitle(UnicodeString Title)
  429. {
  430. FTrayIcon->Hint = Title;
  431. SetConsoleTitle(Title.c_str());
  432. }
  433. //---------------------------------------------------------------------------
  434. bool __fastcall TOwnConsole::LimitedOutput()
  435. {
  436. return true;
  437. }
  438. //---------------------------------------------------------------------------
  439. bool __fastcall TOwnConsole::LiveOutput()
  440. {
  441. return true;
  442. }
  443. //---------------------------------------------------------------------------
  444. bool __fastcall TOwnConsole::NoInteractiveInput()
  445. {
  446. return false;
  447. }
  448. //---------------------------------------------------------------------------
  449. void __fastcall TOwnConsole::WaitBeforeExit()
  450. {
  451. unsigned long Read;
  452. INPUT_RECORD Record;
  453. while (true)
  454. {
  455. if (PeekConsoleInput(FInput, &Record, 1, &Read) && (Read == 1) &&
  456. ReadConsoleInput(FInput, &Record, 1, &Read) &&
  457. (Read == 1) && (Record.EventType == KEY_EVENT) &&
  458. (Record.Event.KeyEvent.uChar.UnicodeChar != 0) &&
  459. Record.Event.KeyEvent.bKeyDown)
  460. {
  461. break;
  462. }
  463. Sleep(50);
  464. ProcessMessages();
  465. }
  466. }
  467. //---------------------------------------------------------------------------
  468. bool __fastcall TOwnConsole::CommandLineOnly()
  469. {
  470. return false;
  471. }
  472. //---------------------------------------------------------------------------
  473. bool __fastcall TOwnConsole::WantsProgress()
  474. {
  475. return false;
  476. }
  477. //---------------------------------------------------------------------------
  478. void __fastcall TOwnConsole::Progress(const TScriptProgress & /*Progress*/)
  479. {
  480. FAIL;
  481. }
  482. //---------------------------------------------------------------------------
  483. class TExternalConsole : public TConsole
  484. {
  485. public:
  486. __fastcall TExternalConsole(const UnicodeString Instance, bool NoInteractiveInput);
  487. virtual __fastcall ~TExternalConsole();
  488. virtual void __fastcall Print(UnicodeString Str, bool FromBeginning = false);
  489. virtual bool __fastcall Input(UnicodeString & Str, bool Echo, unsigned int Timer);
  490. virtual int __fastcall Choice(UnicodeString Options, int Cancel, int Break,
  491. int Timeouted, bool Timeouting, unsigned int Timer);
  492. virtual bool __fastcall PendingAbort();
  493. virtual void __fastcall SetTitle(UnicodeString Title);
  494. virtual bool __fastcall LimitedOutput();
  495. virtual bool __fastcall LiveOutput();
  496. virtual bool __fastcall NoInteractiveInput();
  497. virtual void __fastcall WaitBeforeExit();
  498. virtual bool __fastcall CommandLineOnly();
  499. virtual bool __fastcall WantsProgress();
  500. virtual void __fastcall Progress(const TScriptProgress & Progress);
  501. private:
  502. bool FPendingAbort;
  503. HANDLE FRequestEvent;
  504. HANDLE FResponseEvent;
  505. HANDLE FCancelEvent;
  506. HANDLE FFileMapping;
  507. bool FLimitedOutput;
  508. bool FLiveOutput;
  509. bool FPipeOutput;
  510. bool FNoInteractiveInput;
  511. bool FWantsProgress;
  512. static const int PrintTimeout = 30000;
  513. inline TConsoleCommStruct * __fastcall GetCommStruct();
  514. inline void __fastcall FreeCommStruct(TConsoleCommStruct * CommStruct);
  515. inline void __fastcall SendEvent(int Timeout);
  516. void __fastcall Init();
  517. void __fastcall CheckHandle(HANDLE Handle, const UnicodeString & Desc);
  518. };
  519. //---------------------------------------------------------------------------
  520. __fastcall TExternalConsole::TExternalConsole(
  521. const UnicodeString Instance, bool NoInteractiveInput)
  522. {
  523. UnicodeString Name;
  524. Name = FORMAT(L"%s%s", (CONSOLE_EVENT_REQUEST, (Instance)));
  525. CheckHandle(FRequestEvent = OpenEvent(EVENT_ALL_ACCESS, false, Name.c_str()), L"Request event");
  526. Name = FORMAT(L"%s%s", (CONSOLE_EVENT_RESPONSE, (Instance)));
  527. CheckHandle(FResponseEvent = OpenEvent(EVENT_ALL_ACCESS, false, Name.c_str()), L"Response event");
  528. Name = FORMAT(L"%s%s", (CONSOLE_EVENT_CANCEL, (Instance)));
  529. CheckHandle(FCancelEvent = OpenEvent(EVENT_ALL_ACCESS, false, Name.c_str()), L"Cancel event");
  530. Name = FORMAT(L"%s%s", (CONSOLE_MAPPING, (Instance)));
  531. CheckHandle(FFileMapping = OpenFileMapping(FILE_MAP_ALL_ACCESS, false, Name.c_str()), L"File mapping");
  532. HANDLE Job = OpenJobObject(JOB_OBJECT_ASSIGN_PROCESS, FALSE,
  533. FORMAT(L"%s%s", (CONSOLE_JOB, Instance)).c_str());
  534. if (ALWAYS_TRUE(Job != NULL))
  535. {
  536. AssignProcessToJobObject(Job, GetCurrentProcess());
  537. // winscp.com/winscp.dll keeps the only reference to the job.
  538. // once it gets closed (because winscp.com if forcefully terminated),
  539. // we get terminated as well
  540. CloseHandle(Job);
  541. }
  542. TConsoleCommStruct * CommStruct = GetCommStruct();
  543. try
  544. {
  545. if (CommStruct->Version != TConsoleCommStruct::CurrentVersion)
  546. {
  547. throw Exception(FMTLOAD(EXTERNAL_CONSOLE_INCOMPATIBLE, (CommStruct->Version)));
  548. }
  549. CommStruct->Version = TConsoleCommStruct::CurrentVersionConfirmed;
  550. }
  551. __finally
  552. {
  553. FreeCommStruct(CommStruct);
  554. }
  555. // to break application event loop regularly during "watching for changes"
  556. // to allow user to abort it
  557. SetTimer(Application->Handle, 1, 500, NULL);
  558. FNoInteractiveInput = NoInteractiveInput;
  559. Init();
  560. }
  561. //---------------------------------------------------------------------------
  562. __fastcall TExternalConsole::~TExternalConsole()
  563. {
  564. CloseHandle(FRequestEvent);
  565. CloseHandle(FResponseEvent);
  566. CloseHandle(FCancelEvent);
  567. CloseHandle(FFileMapping);
  568. KillTimer(Application->Handle, 1);
  569. }
  570. //---------------------------------------------------------------------------
  571. void __fastcall TExternalConsole::CheckHandle(HANDLE Handle, const UnicodeString & Desc)
  572. {
  573. if (Handle == NULL)
  574. {
  575. throw ExtException(LoadStr(EXTERNAL_CONSOLE_INIT_ERROR), FORMAT(L"%s\n%s", (Desc, LastSysErrorMessage())));
  576. }
  577. }
  578. //---------------------------------------------------------------------------
  579. TConsoleCommStruct * __fastcall TExternalConsole::GetCommStruct()
  580. {
  581. TConsoleCommStruct * Result;
  582. Result = static_cast<TConsoleCommStruct*>(MapViewOfFile(FFileMapping,
  583. FILE_MAP_ALL_ACCESS, 0, 0, 0));
  584. if (Result == NULL)
  585. {
  586. throw Exception(LoadStr(CONSOLE_COMM_ERROR));
  587. }
  588. return Result;
  589. }
  590. //---------------------------------------------------------------------------
  591. void __fastcall TExternalConsole::FreeCommStruct(TConsoleCommStruct * CommStruct)
  592. {
  593. UnmapViewOfFile(CommStruct);
  594. }
  595. //---------------------------------------------------------------------------
  596. void __fastcall TExternalConsole::SendEvent(int Timeout)
  597. {
  598. SetEvent(FRequestEvent);
  599. unsigned int Result = WaitForSingleObject(FResponseEvent, Timeout);
  600. if (Result != WAIT_OBJECT_0)
  601. {
  602. UnicodeString Message = LoadStr(CONSOLE_SEND_TIMEOUT);
  603. if (FPipeOutput)
  604. {
  605. Message = FORMAT("%s %s", (Message, LoadStr(CONSOLE_SEND_PIPE)));
  606. }
  607. throw Exception(Message);
  608. }
  609. }
  610. //---------------------------------------------------------------------------
  611. void __fastcall TExternalConsole::Print(UnicodeString Str, bool FromBeginning)
  612. {
  613. // need to do at least one iteration, even when Str is empty (new line)
  614. do
  615. {
  616. TConsoleCommStruct * CommStruct = GetCommStruct();
  617. try
  618. {
  619. size_t MaxLen = LENOF(CommStruct->PrintEvent.Message) - 1;
  620. UnicodeString Piece = Str.SubString(1, MaxLen);
  621. Str.Delete(1, MaxLen);
  622. CommStruct->Event = TConsoleCommStruct::PRINT;
  623. wcscpy(CommStruct->PrintEvent.Message, Piece.c_str());
  624. CommStruct->PrintEvent.FromBeginning = FromBeginning;
  625. // In the next iteration we need to append never overwrite.
  626. // Note that this won't work properly for disk/pipe outputs,
  627. // when the next line is also FromBeginning,
  628. // as !FromBeginning print effectively commits previous FromBeginning print.
  629. // On the other hand, FromBeginning print is always initiated by us,
  630. // and it's not likely we ever issue print over 10 KB.
  631. FromBeginning = false;
  632. }
  633. __finally
  634. {
  635. FreeCommStruct(CommStruct);
  636. }
  637. SendEvent(PrintTimeout);
  638. }
  639. while (!Str.IsEmpty());
  640. }
  641. //---------------------------------------------------------------------------
  642. bool __fastcall TExternalConsole::Input(UnicodeString & Str, bool Echo, unsigned int Timer)
  643. {
  644. TConsoleCommStruct * CommStruct = GetCommStruct();
  645. try
  646. {
  647. CommStruct->Event = TConsoleCommStruct::INPUT;
  648. CommStruct->InputEvent.Echo = Echo;
  649. CommStruct->InputEvent.Result = false;
  650. CommStruct->InputEvent.Str[0] = L'\0';
  651. CommStruct->InputEvent.Timer = Timer;
  652. }
  653. __finally
  654. {
  655. FreeCommStruct(CommStruct);
  656. }
  657. SendEvent(INFINITE);
  658. bool Result;
  659. CommStruct = GetCommStruct();
  660. try
  661. {
  662. Result = CommStruct->InputEvent.Result;
  663. Str = CommStruct->InputEvent.Str;
  664. TrimNewLine(Str);
  665. }
  666. __finally
  667. {
  668. FreeCommStruct(CommStruct);
  669. }
  670. return Result;
  671. }
  672. //---------------------------------------------------------------------------
  673. int __fastcall TExternalConsole::Choice(UnicodeString Options, int Cancel, int Break,
  674. int Timeouted, bool Timeouting, unsigned int Timer)
  675. {
  676. TConsoleCommStruct * CommStruct = GetCommStruct();
  677. try
  678. {
  679. CommStruct->Event = TConsoleCommStruct::CHOICE;
  680. DebugAssert(Options.Length() < static_cast<int>(LENOF(CommStruct->ChoiceEvent.Options)));
  681. wcscpy(CommStruct->ChoiceEvent.Options, Options.c_str());
  682. CommStruct->ChoiceEvent.Cancel = Cancel;
  683. CommStruct->ChoiceEvent.Break = Break;
  684. CommStruct->ChoiceEvent.Result = Break;
  685. CommStruct->ChoiceEvent.Timeouted = Timeouted;
  686. CommStruct->ChoiceEvent.Timer = Timer;
  687. CommStruct->ChoiceEvent.Timeouting = Timeouting;
  688. }
  689. __finally
  690. {
  691. FreeCommStruct(CommStruct);
  692. }
  693. SendEvent(INFINITE);
  694. int Result;
  695. CommStruct = GetCommStruct();
  696. try
  697. {
  698. Result = CommStruct->ChoiceEvent.Result;
  699. }
  700. __finally
  701. {
  702. FreeCommStruct(CommStruct);
  703. }
  704. return Result;
  705. }
  706. //---------------------------------------------------------------------------
  707. bool __fastcall TExternalConsole::PendingAbort()
  708. {
  709. return (WaitForSingleObject(FCancelEvent, 0) == WAIT_OBJECT_0);
  710. }
  711. //---------------------------------------------------------------------------
  712. void __fastcall TExternalConsole::SetTitle(UnicodeString Title)
  713. {
  714. TConsoleCommStruct * CommStruct = GetCommStruct();
  715. try
  716. {
  717. // Truncate to maximum allowed. Title over 10 KB won't fit to screen anyway
  718. Title = Title.SubString(1, LENOF(CommStruct->TitleEvent.Title) - 1);
  719. CommStruct->Event = TConsoleCommStruct::TITLE;
  720. wcscpy(CommStruct->TitleEvent.Title, Title.c_str());
  721. }
  722. __finally
  723. {
  724. FreeCommStruct(CommStruct);
  725. }
  726. SendEvent(INFINITE);
  727. }
  728. //---------------------------------------------------------------------------
  729. void __fastcall TExternalConsole::Init()
  730. {
  731. TConsoleCommStruct * CommStruct = GetCommStruct();
  732. try
  733. {
  734. CommStruct->Event = TConsoleCommStruct::INIT;
  735. CommStruct->InitEvent.WantsProgress = false;
  736. }
  737. __finally
  738. {
  739. FreeCommStruct(CommStruct);
  740. }
  741. SendEvent(INFINITE);
  742. CommStruct = GetCommStruct();
  743. try
  744. {
  745. FLimitedOutput = (CommStruct->InitEvent.OutputType == FILE_TYPE_CHAR);
  746. FLiveOutput =
  747. (CommStruct->InitEvent.OutputType != FILE_TYPE_DISK) &&
  748. (CommStruct->InitEvent.OutputType != FILE_TYPE_PIPE);
  749. FPipeOutput = (CommStruct->InitEvent.OutputType != FILE_TYPE_PIPE);
  750. FWantsProgress = CommStruct->InitEvent.WantsProgress;
  751. }
  752. __finally
  753. {
  754. FreeCommStruct(CommStruct);
  755. }
  756. }
  757. //---------------------------------------------------------------------------
  758. bool __fastcall TExternalConsole::LimitedOutput()
  759. {
  760. return FLimitedOutput;
  761. }
  762. //---------------------------------------------------------------------------
  763. bool __fastcall TExternalConsole::LiveOutput()
  764. {
  765. return FLiveOutput;
  766. }
  767. //---------------------------------------------------------------------------
  768. bool __fastcall TExternalConsole::NoInteractiveInput()
  769. {
  770. return FNoInteractiveInput;
  771. }
  772. //---------------------------------------------------------------------------
  773. void __fastcall TExternalConsole::WaitBeforeExit()
  774. {
  775. // noop
  776. }
  777. //---------------------------------------------------------------------------
  778. bool __fastcall TExternalConsole::CommandLineOnly()
  779. {
  780. return true;
  781. }
  782. //---------------------------------------------------------------------------
  783. bool __fastcall TExternalConsole::WantsProgress()
  784. {
  785. return FWantsProgress;
  786. }
  787. //---------------------------------------------------------------------------
  788. void __fastcall TExternalConsole::Progress(const TScriptProgress & Progress)
  789. {
  790. TConsoleCommStruct * CommStruct = GetCommStruct();
  791. try
  792. {
  793. CommStruct->Event = TConsoleCommStruct::PROGRESS;
  794. typedef TConsoleCommStruct::TProgressEvent TProgressEvent;
  795. TProgressEvent & ProgressEvent = CommStruct->ProgressEvent;
  796. switch (Progress.Operation)
  797. {
  798. case foCopy:
  799. case foMove:
  800. ProgressEvent.Operation = TProgressEvent::COPY;
  801. break;
  802. default:
  803. FAIL;
  804. }
  805. switch (Progress.Side)
  806. {
  807. case osLocal:
  808. ProgressEvent.Side = TProgressEvent::LOCAL;
  809. break;
  810. case osRemote:
  811. ProgressEvent.Side = TProgressEvent::REMOTE;
  812. break;
  813. default:
  814. FAIL;
  815. }
  816. wcsncpy(ProgressEvent.FileName, Progress.FileName.c_str(), LENOF(ProgressEvent.FileName));
  817. NULL_TERMINATE(ProgressEvent.FileName);
  818. wcsncpy(ProgressEvent.Directory, Progress.Directory.c_str(), LENOF(ProgressEvent.Directory));
  819. NULL_TERMINATE(ProgressEvent.Directory);
  820. ProgressEvent.OverallProgress = Progress.OverallProgress;
  821. ProgressEvent.FileProgress = Progress.FileProgress;
  822. ProgressEvent.CPS = Progress.CPS;
  823. }
  824. __finally
  825. {
  826. FreeCommStruct(CommStruct);
  827. }
  828. SendEvent(INFINITE);
  829. // nothing to read from response, just wait for it
  830. FreeCommStruct(GetCommStruct());
  831. }
  832. //---------------------------------------------------------------------------
  833. class TNullConsole : public TConsole
  834. {
  835. public:
  836. __fastcall TNullConsole();
  837. virtual void __fastcall Print(UnicodeString Str, bool FromBeginning = false);
  838. virtual bool __fastcall Input(UnicodeString & Str, bool Echo, unsigned int Timer);
  839. virtual int __fastcall Choice(UnicodeString Options, int Cancel, int Break,
  840. int Timeouted, bool Timeouting, unsigned int Timer);
  841. virtual bool __fastcall PendingAbort();
  842. virtual void __fastcall SetTitle(UnicodeString Title);
  843. virtual bool __fastcall LimitedOutput();
  844. virtual bool __fastcall LiveOutput();
  845. virtual bool __fastcall NoInteractiveInput();
  846. virtual void __fastcall WaitBeforeExit();
  847. virtual bool __fastcall CommandLineOnly();
  848. virtual bool __fastcall WantsProgress();
  849. virtual void __fastcall Progress(const TScriptProgress & Progress);
  850. };
  851. //---------------------------------------------------------------------------
  852. __fastcall TNullConsole::TNullConsole()
  853. {
  854. }
  855. //---------------------------------------------------------------------------
  856. void __fastcall TNullConsole::Print(UnicodeString /*Str*/, bool /*FromBeginning*/)
  857. {
  858. // noop
  859. }
  860. //---------------------------------------------------------------------------
  861. bool __fastcall TNullConsole::Input(UnicodeString & /*Str*/, bool /*Echo*/,
  862. unsigned int /*Timer*/)
  863. {
  864. return false;
  865. }
  866. //---------------------------------------------------------------------------
  867. int __fastcall TNullConsole::Choice(UnicodeString /*Options*/, int /*Cancel*/,
  868. int Break, int Timeouted, bool Timeouting, unsigned int Timer)
  869. {
  870. int Result;
  871. if (Timeouting)
  872. {
  873. Sleep(Timer);
  874. Result = Timeouted;
  875. }
  876. else
  877. {
  878. Result = Break;
  879. }
  880. return Result;
  881. }
  882. //---------------------------------------------------------------------------
  883. bool __fastcall TNullConsole::PendingAbort()
  884. {
  885. return false;
  886. }
  887. //---------------------------------------------------------------------------
  888. void __fastcall TNullConsole::SetTitle(UnicodeString /*Title*/)
  889. {
  890. // noop
  891. }
  892. //---------------------------------------------------------------------------
  893. bool __fastcall TNullConsole::LimitedOutput()
  894. {
  895. return false;
  896. }
  897. //---------------------------------------------------------------------------
  898. bool __fastcall TNullConsole::LiveOutput()
  899. {
  900. return false;
  901. }
  902. //---------------------------------------------------------------------------
  903. bool __fastcall TNullConsole::NoInteractiveInput()
  904. {
  905. // do not matter, even if we return false,
  906. // it fails immediately afterwards in TNullConsole::Input
  907. return true;
  908. }
  909. //---------------------------------------------------------------------------
  910. void __fastcall TNullConsole::WaitBeforeExit()
  911. {
  912. FAIL;
  913. // noop
  914. }
  915. //---------------------------------------------------------------------------
  916. bool __fastcall TNullConsole::CommandLineOnly()
  917. {
  918. FAIL;
  919. return false;
  920. }
  921. //---------------------------------------------------------------------------
  922. bool __fastcall TNullConsole::WantsProgress()
  923. {
  924. return false;
  925. }
  926. //---------------------------------------------------------------------------
  927. void __fastcall TNullConsole::Progress(const TScriptProgress & /*Progress*/)
  928. {
  929. FAIL;
  930. }
  931. //---------------------------------------------------------------------------
  932. static UnicodeString TimestampVarName(L"TIMESTAMP");
  933. //---------------------------------------------------------------------------
  934. class TConsoleRunner
  935. {
  936. public:
  937. TConsoleRunner(TConsole * Console);
  938. ~TConsoleRunner();
  939. int __fastcall Run(const UnicodeString Session, TOptions * Options,
  940. TStrings * ScriptCommands, TStrings * ScriptParameters);
  941. void __fastcall ShowException(Exception * E);
  942. inline void __fastcall PrintMessage(const UnicodeString & Str);
  943. protected:
  944. bool __fastcall DoInput(UnicodeString & Str, bool Echo, unsigned int Timer,
  945. bool Interactive);
  946. void __fastcall Input(const UnicodeString Prompt, UnicodeString & Str,
  947. bool Echo, bool Interactive);
  948. inline void __fastcall Print(const UnicodeString & Str, bool FromBeginning = false);
  949. inline void __fastcall PrintLine(const UnicodeString & Str);
  950. void __fastcall UpdateTitle();
  951. inline void __fastcall NotifyAbort();
  952. inline bool __fastcall Aborted(bool AllowCompleteAbort = true);
  953. void __fastcall MasterPasswordPrompt();
  954. void __fastcall DoShowException(TTerminal * Terminal, Exception * E);
  955. private:
  956. TManagementScript * FScript;
  957. TConsole * FConsole;
  958. TSynchronizeController FSynchronizeController;
  959. int FLastProgressLen;
  960. bool FSynchronizeAborted;
  961. bool FCommandError;
  962. bool FBatchScript;
  963. bool FAborted;
  964. TTimer * Timer;
  965. bool FExternalTimestampVar;
  966. void __fastcall ScriptPrint(TScript * Script, const UnicodeString Str);
  967. void __fastcall ScriptPrintProgress(TScript * Script, bool First, const UnicodeString Str);
  968. void __fastcall ScriptInput(TScript * Script, const UnicodeString Prompt, UnicodeString & Str);
  969. void __fastcall ScriptTerminalPromptUser(TTerminal * Terminal,
  970. TPromptKind Kind, UnicodeString Name, UnicodeString Instructions, TStrings * Prompts,
  971. TStrings * Results, bool & Result, void * Arg);
  972. void __fastcall ScriptShowExtendedException(TTerminal * Terminal,
  973. Exception * E, void * Arg);
  974. void __fastcall ScriptTerminalQueryUser(TObject * Sender, const UnicodeString Query,
  975. TStrings * MoreMessages, unsigned int Answers, const TQueryParams * Params, unsigned int & Answer,
  976. TQueryType QueryType, void * Arg);
  977. void __fastcall ScriptQueryCancel(TScript * Script, bool & Cancel);
  978. void __fastcall SynchronizeControllerAbort(TObject * Sender, bool Close);
  979. void __fastcall SynchronizeControllerLog(TSynchronizeController * Controller,
  980. TSynchronizeLogEntry Entry, const UnicodeString Message);
  981. void __fastcall ScriptSynchronizeStartStop(TScript * Script,
  982. const UnicodeString LocalDirectory, const UnicodeString RemoteDirectory,
  983. const TCopyParamType & CopyParam, int SynchronizeParams);
  984. void __fastcall SynchronizeControllerSynchronize(TSynchronizeController * Sender,
  985. const UnicodeString LocalDirectory, const UnicodeString RemoteDirectory,
  986. const TCopyParamType & CopyParam, const TSynchronizeParamType & Params,
  987. TSynchronizeChecklist ** Checklist, TSynchronizeOptions * Options, bool Full);
  988. void __fastcall SynchronizeControllerSynchronizeInvalid(TSynchronizeController * Sender,
  989. const UnicodeString Directory, const UnicodeString ErrorStr);
  990. void __fastcall SynchronizeControllerTooManyDirectories(TSynchronizeController * Sender,
  991. int & MaxDirectories);
  992. unsigned int InputTimeout();
  993. void __fastcall TimerTimer(TObject * Sender);
  994. UnicodeString ExpandCommand(UnicodeString Command, TStrings * ScriptParameters);
  995. void __fastcall Failed(bool & AnyError);
  996. void __fastcall ScriptProgress(TScript * Script, const TScriptProgress & Progress);
  997. void __fastcall ConfigurationChange(TObject * Sender);
  998. };
  999. //---------------------------------------------------------------------------
  1000. TConsoleRunner::TConsoleRunner(TConsole * Console) :
  1001. FSynchronizeController(&SynchronizeControllerSynchronize,
  1002. &SynchronizeControllerSynchronizeInvalid,
  1003. &SynchronizeControllerTooManyDirectories)
  1004. {
  1005. FConsole = Console;
  1006. FLastProgressLen = 0;
  1007. FScript = NULL;
  1008. FAborted = false;
  1009. FBatchScript = false;
  1010. Timer = new TTimer(Application);
  1011. Timer->OnTimer = TimerTimer;
  1012. Timer->Interval = MSecsPerSec;
  1013. Timer->Enabled = true;
  1014. DebugAssert(WinConfiguration->OnMasterPasswordPrompt == NULL);
  1015. WinConfiguration->OnMasterPasswordPrompt = MasterPasswordPrompt;
  1016. DebugAssert(Configuration->OnChange == NULL);
  1017. FExternalTimestampVar = !GetEnvironmentVariable(TimestampVarName).IsEmpty();
  1018. Configuration->OnChange = ConfigurationChange;
  1019. Configuration->Scripting = true;
  1020. }
  1021. //---------------------------------------------------------------------------
  1022. TConsoleRunner::~TConsoleRunner()
  1023. {
  1024. DebugAssert(WinConfiguration->OnMasterPasswordPrompt == MasterPasswordPrompt);
  1025. WinConfiguration->OnMasterPasswordPrompt = NULL;
  1026. DebugAssert(Configuration->OnChange == ConfigurationChange);
  1027. Configuration->OnChange = NULL;
  1028. delete Timer;
  1029. }
  1030. //---------------------------------------------------------------------------
  1031. void __fastcall TConsoleRunner::TimerTimer(TObject * /*Sender*/)
  1032. {
  1033. // sole presence of timer causes message to be dispatched,
  1034. // hence breaks the loops
  1035. }
  1036. //---------------------------------------------------------------------------
  1037. unsigned int TConsoleRunner::InputTimeout()
  1038. {
  1039. return ((FScript != NULL) && (FScript->Batch != TScript::BatchOff) ? BATCH_INPUT_TIMEOUT : 0);
  1040. }
  1041. //---------------------------------------------------------------------------
  1042. void __fastcall TConsoleRunner::Input(
  1043. const UnicodeString Prompt, UnicodeString & Str, bool Echo, bool Interactive)
  1044. {
  1045. Print(Prompt);
  1046. if (!DoInput(Str, Echo, InputTimeout(), Interactive))
  1047. {
  1048. Abort();
  1049. }
  1050. }
  1051. //---------------------------------------------------------------------------
  1052. void __fastcall TConsoleRunner::ScriptInput(TScript * /*Script*/,
  1053. const UnicodeString Prompt, UnicodeString & Str)
  1054. {
  1055. Input(Prompt, Str, true, true);
  1056. }
  1057. //---------------------------------------------------------------------------
  1058. void __fastcall TConsoleRunner::Print(const UnicodeString & Str, bool FromBeginning)
  1059. {
  1060. if (FLastProgressLen > 0)
  1061. {
  1062. FConsole->Print(L"\n" + Str, FromBeginning);
  1063. FLastProgressLen = 0;
  1064. }
  1065. else
  1066. {
  1067. FConsole->Print(Str, FromBeginning);
  1068. }
  1069. }
  1070. //---------------------------------------------------------------------------
  1071. void __fastcall TConsoleRunner::PrintLine(const UnicodeString & Str)
  1072. {
  1073. Print(Str + L"\n");
  1074. }
  1075. //---------------------------------------------------------------------------
  1076. void __fastcall TConsoleRunner::PrintMessage(const UnicodeString & Str)
  1077. {
  1078. UnicodeString Line = RemoveEmptyLines(Str);
  1079. if (FScript != NULL)
  1080. {
  1081. // this also logs the message
  1082. FScript->PrintLine(Line);
  1083. }
  1084. else
  1085. {
  1086. PrintLine(Line);
  1087. }
  1088. }
  1089. //---------------------------------------------------------------------------
  1090. void __fastcall TConsoleRunner::NotifyAbort()
  1091. {
  1092. if (FBatchScript)
  1093. {
  1094. FAborted = true;
  1095. }
  1096. }
  1097. //---------------------------------------------------------------------------
  1098. bool __fastcall TConsoleRunner::Aborted(bool AllowCompleteAbort)
  1099. {
  1100. bool Result;
  1101. if (FAborted)
  1102. {
  1103. Result = true;
  1104. }
  1105. else
  1106. {
  1107. Result = FConsole->PendingAbort();
  1108. if (Result)
  1109. {
  1110. PrintMessage(LoadStr(USER_TERMINATED));
  1111. if (AllowCompleteAbort)
  1112. {
  1113. NotifyAbort();
  1114. }
  1115. }
  1116. }
  1117. return Result;
  1118. }
  1119. //---------------------------------------------------------------------------
  1120. void __fastcall TConsoleRunner::ScriptPrint(TScript * /*Script*/,
  1121. const UnicodeString Str)
  1122. {
  1123. Print(Str);
  1124. }
  1125. //---------------------------------------------------------------------------
  1126. void __fastcall TConsoleRunner::ScriptPrintProgress(TScript * /*Script*/,
  1127. bool First, const UnicodeString Str)
  1128. {
  1129. UnicodeString S = Str;
  1130. if (First && (FLastProgressLen > 0))
  1131. {
  1132. S = L"\n" + S;
  1133. }
  1134. else if (S.Length() < FLastProgressLen)
  1135. {
  1136. int Padding = FLastProgressLen - S.Length();
  1137. S += UnicodeString::StringOfChar(L' ', Padding) +
  1138. UnicodeString::StringOfChar(L'\b', Padding);
  1139. }
  1140. FConsole->Print(S, true);
  1141. FLastProgressLen = Str.Length();
  1142. }
  1143. //---------------------------------------------------------------------------
  1144. void __fastcall TConsoleRunner::ScriptTerminalPromptUser(TTerminal * /*Terminal*/,
  1145. TPromptKind /*Kind*/, UnicodeString Name, UnicodeString Instructions, TStrings * Prompts,
  1146. TStrings * Results, bool & Result, void * /*Arg*/)
  1147. {
  1148. if (!Instructions.IsEmpty())
  1149. {
  1150. PrintMessage(Instructions);
  1151. }
  1152. // if there are no prompts, success is default
  1153. Result = true;
  1154. for (int Index = 0; Index < Prompts->Count; Index++)
  1155. {
  1156. UnicodeString Prompt = Prompts->Strings[Index];
  1157. if (!Prompt.IsEmpty() && (Prompt[Prompt.Length()] != L' '))
  1158. {
  1159. Prompt += L' ';
  1160. }
  1161. int P = Prompt.Pos(L'&');
  1162. if (P > 0)
  1163. {
  1164. Prompt.Delete(P, 1);
  1165. }
  1166. Print(Prompt);
  1167. UnicodeString AResult = Results->Strings[Index]; // useless
  1168. bool Echo = FLAGSET(int(Prompts->Objects[Index]), pupEcho);
  1169. Result = DoInput(AResult, Echo, InputTimeout(), true);
  1170. Results->Strings[Index] = AResult;
  1171. }
  1172. }
  1173. //---------------------------------------------------------------------------
  1174. void __fastcall TConsoleRunner::ScriptShowExtendedException(
  1175. TTerminal * Terminal, Exception * E, void * /*Arg*/)
  1176. {
  1177. DoShowException(Terminal, E);
  1178. }
  1179. //---------------------------------------------------------------------------
  1180. void __fastcall TConsoleRunner::ScriptTerminalQueryUser(TObject * /*Sender*/,
  1181. const UnicodeString Query, TStrings * MoreMessages, unsigned int Answers,
  1182. const TQueryParams * Params, unsigned int & Answer, TQueryType /*QueryType*/,
  1183. void * /*Arg*/)
  1184. {
  1185. UnicodeString AQuery = Query;
  1186. unsigned int Timer = 0;
  1187. unsigned int Timeout = 0;
  1188. unsigned int TimeoutA = 0;
  1189. unsigned int NoBatchA = 0;
  1190. if (Params != NULL)
  1191. {
  1192. if (Params->Timeout > 0)
  1193. {
  1194. Timeout = Params->Timeout;
  1195. TimeoutA = Params->TimeoutAnswer;
  1196. }
  1197. if (Params->Timer > 0)
  1198. {
  1199. Timer = Params->Timer;
  1200. if (Params->TimerAnswers > 0)
  1201. {
  1202. Answers = Params->TimerAnswers;
  1203. }
  1204. // not considering TimerQueryType as we do not use QueryType anyway
  1205. if (!Params->TimerMessage.IsEmpty())
  1206. {
  1207. AQuery = Params->TimerMessage;
  1208. }
  1209. }
  1210. if (FLAGSET(Params->Params, qpFatalAbort))
  1211. {
  1212. AQuery = FMTLOAD(WARN_FATAL_ERROR, (AQuery));
  1213. }
  1214. NoBatchA = Params->NoBatchAnswers;
  1215. if (FLAGSET(Params->Params, qpWaitInBatch))
  1216. {
  1217. DebugAssert(Timeout == 0);
  1218. Timeout = InputTimeout();
  1219. // See a duplicate AbortAnswer call below
  1220. TimeoutA = AbortAnswer(Answers & ~NoBatchA);
  1221. }
  1222. }
  1223. AQuery = UnformatMessage(AQuery);
  1224. AQuery = RemoveInteractiveMsgTag(AQuery);
  1225. ApplyTabs(AQuery, L' ', NULL, NULL);
  1226. unsigned int AAnswers = Answers;
  1227. PrintMessage(AQuery);
  1228. if ((MoreMessages != NULL) && (MoreMessages->Count > 0))
  1229. {
  1230. PrintMessage(MoreMessages->Text);
  1231. }
  1232. std::vector<unsigned int> Buttons;
  1233. std::vector<UnicodeString> Captions;
  1234. std::vector<TNotifyEvent> OnClicks;
  1235. for (unsigned int Answer = qaFirst; Answer <= qaLast; Answer = Answer << 1)
  1236. {
  1237. if (FLAGSET(Answers, Answer))
  1238. {
  1239. UnicodeString Name; // unused
  1240. UnicodeString Caption;
  1241. AnswerNameAndCaption(Answer, Name, Caption);
  1242. Captions.push_back(Caption);
  1243. Buttons.push_back(Answer);
  1244. OnClicks.push_back(NULL);
  1245. AAnswers -= Answer;
  1246. }
  1247. }
  1248. USEDPARAM(AAnswers);
  1249. DebugAssert(AAnswers == 0);
  1250. DebugAssert(!Buttons.empty());
  1251. if ((Params != NULL) && (Params->Aliases != NULL))
  1252. {
  1253. for (unsigned int bi = 0; bi < Buttons.size(); bi++)
  1254. {
  1255. for (unsigned int ai = 0; ai < Params->AliasesCount; ai++)
  1256. {
  1257. if (Params->Aliases[ai].Button == Buttons[bi])
  1258. {
  1259. if (!Params->Aliases[ai].Alias.IsEmpty())
  1260. {
  1261. Captions[bi] = Params->Aliases[ai].Alias;
  1262. }
  1263. OnClicks[bi] = Params->Aliases[ai].OnClick;
  1264. break;
  1265. }
  1266. }
  1267. }
  1268. }
  1269. UnicodeString Accels;
  1270. for (unsigned int Index = 0; Index < Buttons.size(); Index++)
  1271. {
  1272. UnicodeString & Caption = Captions[Index];
  1273. int P = Caption.Pos(L'&');
  1274. if ((P > 0) && (P < Caption.Length()))
  1275. {
  1276. wchar_t Accel = AnsiUpperCase(Caption)[P + 1];
  1277. if (Accels.Pos(Accel) > 0)
  1278. {
  1279. Caption.Delete(P, 1);
  1280. Accels += L' ';
  1281. }
  1282. else
  1283. {
  1284. Accels += Accel;
  1285. }
  1286. }
  1287. else
  1288. {
  1289. Accels += L' ';
  1290. }
  1291. }
  1292. DebugAssert(Accels.Length() == static_cast<int>(Buttons.size()));
  1293. int NumberAccel = 0;
  1294. unsigned int CancelA = CancelAnswer(Answers);
  1295. int CancelIndex;
  1296. // AbortAnswer call duplicated in qpWaitInBatch branch above
  1297. unsigned int AbortA = AbortAnswer(Answers & ~NoBatchA);
  1298. int AbortIndex;
  1299. unsigned int ContinueA = ContinueAnswer(Answers & ~NoBatchA);
  1300. int ContinueIndex;
  1301. int TimeoutIndex = 0;
  1302. for (unsigned int Index = 0; Index < Buttons.size(); Index++)
  1303. {
  1304. UnicodeString & Caption = Captions[Index];
  1305. if (Accels[Index + 1] == L' ')
  1306. {
  1307. for (int Index2 = 1; Index2 <= Caption.Length(); Index2++)
  1308. {
  1309. wchar_t C = AnsiUpperCase(Caption)[Index2];
  1310. if (IsLetter(C) && (Accels.Pos(C) == 0))
  1311. {
  1312. Caption.Insert(L"&", Index2);
  1313. Accels[Index + 1] = C;
  1314. break;
  1315. }
  1316. }
  1317. }
  1318. if (Accels[Index + 1] == L' ')
  1319. {
  1320. for (int Index2 = 1; Index2 <= Caption.Length(); Index2++)
  1321. {
  1322. wchar_t C = AnsiUpperCase(Caption)[Index2];
  1323. if ((C != L' ') && (Accels.Pos(C) == 0))
  1324. {
  1325. Caption.Insert(L"&", Index2);
  1326. Accels[Index + 1] = C;
  1327. break;
  1328. }
  1329. }
  1330. }
  1331. if (Accels[Index + 1] == L' ')
  1332. {
  1333. NumberAccel++;
  1334. DebugAssert(NumberAccel <= 9);
  1335. Caption = FORMAT(L"&%d%s", (NumberAccel, Caption));
  1336. Accels[Index + 1] = Caption[2];
  1337. }
  1338. if (Buttons[Index] == CancelA)
  1339. {
  1340. CancelIndex = Index + 1;
  1341. }
  1342. if (Buttons[Index] == AbortA)
  1343. {
  1344. AbortIndex = Index + 1;
  1345. }
  1346. if (Buttons[Index] == ContinueA)
  1347. {
  1348. ContinueIndex = Index + 1;
  1349. }
  1350. if (Buttons[Index] == TimeoutA)
  1351. {
  1352. TimeoutIndex = Index + 1;
  1353. }
  1354. }
  1355. DebugAssert(Accels.Pos(L' ') == 0);
  1356. bool Timeouting = (Timeout > 0);
  1357. bool FirstOutput = true;
  1358. do
  1359. {
  1360. Answer = 0;
  1361. int AnswerIndex;
  1362. bool Retry;
  1363. do
  1364. {
  1365. Retry = false;
  1366. if (FirstOutput || FConsole->LiveOutput())
  1367. {
  1368. UnicodeString Output;
  1369. for (unsigned int i = 0; i < Buttons.size(); i++)
  1370. {
  1371. if (i > 0)
  1372. {
  1373. Output += L", ";
  1374. }
  1375. UnicodeString Caption = Captions[i];
  1376. int P = Caption.Pos(L'&');
  1377. if (ALWAYS_TRUE(P >= 0))
  1378. {
  1379. Caption[P] = L'(';
  1380. Caption.Insert(L")", P + 2);
  1381. }
  1382. if (i + 1 == static_cast<unsigned int>(TimeoutIndex))
  1383. {
  1384. DebugAssert(Timeouting);
  1385. Caption = FMTLOAD(TIMEOUT_BUTTON, (Caption, int(Timeout / MSecsPerSec)));
  1386. }
  1387. Output += Caption;
  1388. }
  1389. Output += L": ";
  1390. // note that length of string may decrease over time due to number of
  1391. // seconds length, but supposing it decreases by one character at time
  1392. // at most, we do not mind as the prompt is terminated with space
  1393. // If output is not live (file or pipe), do not use 'from beginning'
  1394. // as it means that the output is not actually stored until new line
  1395. // is sent (and we will not [because we cannot] rewrite the output anyway)
  1396. Print(Output, !FirstOutput);
  1397. FirstOutput = false;
  1398. }
  1399. if (!Timeouting && (FScript->Batch == TScript::BatchContinue))
  1400. {
  1401. AnswerIndex = ContinueIndex;
  1402. }
  1403. else if (!Timeouting && (FScript->Batch != TScript::BatchOff))
  1404. {
  1405. AnswerIndex = AbortIndex;
  1406. }
  1407. else if (Timeouting && (Timeout < MSecsPerSec))
  1408. {
  1409. AnswerIndex = TimeoutIndex;
  1410. }
  1411. else
  1412. {
  1413. unsigned int ActualTimer =
  1414. (Timeouting && ((Timer == 0) || (Timer > MSecsPerSec)) ? MSecsPerSec : Timer);
  1415. AnswerIndex = FConsole->Choice(Accels, CancelIndex, -1, -2,
  1416. Timeouting, ActualTimer);
  1417. if (AnswerIndex == -1)
  1418. {
  1419. NotifyAbort();
  1420. AnswerIndex = AbortIndex;
  1421. }
  1422. else if (AnswerIndex == -2)
  1423. {
  1424. if (Timeouting)
  1425. {
  1426. DebugAssert(Timeout >= MSecsPerSec);
  1427. Timeout -= ActualTimer;
  1428. Retry = true;
  1429. }
  1430. // this does not take Timer into account,
  1431. // but as of now Timer is used for TSecureShell timeout prompt only,
  1432. // where Timer is less than MSecsPerSec
  1433. if (Timer > 0)
  1434. {
  1435. DebugAssert((Params != NULL) && (Params->TimerEvent != NULL));
  1436. if ((Params != NULL) && (Params->TimerEvent != NULL))
  1437. {
  1438. unsigned int AAnswer = 0;
  1439. Params->TimerEvent(AAnswer);
  1440. if (AAnswer != 0)
  1441. {
  1442. Answer = AAnswer;
  1443. Retry = false;
  1444. }
  1445. else
  1446. {
  1447. Retry = true;
  1448. }
  1449. }
  1450. }
  1451. }
  1452. }
  1453. }
  1454. while (Retry);
  1455. if (Answer == 0)
  1456. {
  1457. DebugAssert((AnswerIndex >= 1) && (AnswerIndex <= Accels.Length()));
  1458. UnicodeString AnswerCaption = Captions[AnswerIndex - 1];
  1459. int P = AnswerCaption.Pos(L"&");
  1460. DebugAssert(P >= 0);
  1461. AnswerCaption.Delete(P, 1);
  1462. PrintLine(AnswerCaption);
  1463. FirstOutput = true;
  1464. if (OnClicks[AnswerIndex - 1] != NULL)
  1465. {
  1466. OnClicks[AnswerIndex - 1](NULL);
  1467. }
  1468. else
  1469. {
  1470. Answer = Buttons[AnswerIndex - 1];
  1471. }
  1472. }
  1473. else
  1474. {
  1475. PrintLine(L"");
  1476. }
  1477. }
  1478. while (Answer == 0);
  1479. if ((Answer == AbortA) &&
  1480. ((Params == NULL) || FLAGCLEAR(Params->Params, qpIgnoreAbort)))
  1481. {
  1482. if (FScript->Terminal != NULL)
  1483. {
  1484. TStrings * Messages = new TStringList();
  1485. try
  1486. {
  1487. Messages->Add(Query);
  1488. if (MoreMessages != NULL)
  1489. {
  1490. Messages->AddStrings(MoreMessages);
  1491. }
  1492. FScript->Terminal->ActionLog->AddFailure(Messages);
  1493. }
  1494. __finally
  1495. {
  1496. delete Messages;
  1497. }
  1498. }
  1499. FCommandError = true;
  1500. }
  1501. }
  1502. //---------------------------------------------------------------------------
  1503. void __fastcall TConsoleRunner::ScriptQueryCancel(TScript * /*Script*/, bool & Cancel)
  1504. {
  1505. if (Aborted())
  1506. {
  1507. Cancel = true;
  1508. }
  1509. }
  1510. //---------------------------------------------------------------------------
  1511. void __fastcall TConsoleRunner::ScriptSynchronizeStartStop(TScript * /*Script*/,
  1512. const UnicodeString LocalDirectory, const UnicodeString RemoteDirectory,
  1513. const TCopyParamType & CopyParam, int SynchronizeParams)
  1514. {
  1515. TSynchronizeParamType Params;
  1516. Params.LocalDirectory = LocalDirectory;
  1517. Params.RemoteDirectory = RemoteDirectory;
  1518. Params.Params = SynchronizeParams;
  1519. Params.Options = soRecurse;
  1520. FSynchronizeController.StartStop(Application, true, Params,
  1521. CopyParam, NULL, SynchronizeControllerAbort, NULL,
  1522. SynchronizeControllerLog);
  1523. try
  1524. {
  1525. FSynchronizeAborted = false;
  1526. while (!FSynchronizeAborted && !Aborted(false))
  1527. {
  1528. Application->HandleMessage();
  1529. FScript->Terminal->Idle();
  1530. }
  1531. }
  1532. __finally
  1533. {
  1534. FSynchronizeController.StartStop(Application, false, Params,
  1535. CopyParam, NULL, SynchronizeControllerAbort, NULL,
  1536. SynchronizeControllerLog);
  1537. }
  1538. }
  1539. //---------------------------------------------------------------------------
  1540. void __fastcall TConsoleRunner::ScriptProgress(TScript * /*Script*/, const TScriptProgress & Progress)
  1541. {
  1542. FConsole->Progress(Progress);
  1543. }
  1544. //---------------------------------------------------------------------------
  1545. void __fastcall TConsoleRunner::SynchronizeControllerLog(
  1546. TSynchronizeController * /*Controller*/, TSynchronizeLogEntry /*Entry*/,
  1547. const UnicodeString Message)
  1548. {
  1549. PrintMessage(Message);
  1550. }
  1551. //---------------------------------------------------------------------------
  1552. void __fastcall TConsoleRunner::SynchronizeControllerAbort(TObject * /*Sender*/,
  1553. bool /*Close*/)
  1554. {
  1555. FSynchronizeAborted = true;
  1556. }
  1557. //---------------------------------------------------------------------------
  1558. void __fastcall TConsoleRunner::SynchronizeControllerSynchronize(
  1559. TSynchronizeController * /*Sender*/, const UnicodeString LocalDirectory,
  1560. const UnicodeString RemoteDirectory, const TCopyParamType & CopyParam,
  1561. const TSynchronizeParamType & Params, TSynchronizeChecklist ** Checklist,
  1562. TSynchronizeOptions * /*Options*/, bool Full)
  1563. {
  1564. if (!Full)
  1565. {
  1566. FScript->Synchronize(LocalDirectory, RemoteDirectory, CopyParam,
  1567. Params.Params, Checklist);
  1568. }
  1569. }
  1570. //---------------------------------------------------------------------------
  1571. void __fastcall TConsoleRunner::SynchronizeControllerSynchronizeInvalid(
  1572. TSynchronizeController * /*Sender*/, const UnicodeString Directory, const UnicodeString ErrorStr)
  1573. {
  1574. if (!Directory.IsEmpty())
  1575. {
  1576. PrintMessage(FMTLOAD(WATCH_ERROR_DIRECTORY, (Directory)));
  1577. }
  1578. else
  1579. {
  1580. PrintMessage(LoadStr(WATCH_ERROR_GENERAL));
  1581. }
  1582. if (!ErrorStr.IsEmpty())
  1583. {
  1584. PrintMessage(ErrorStr);
  1585. }
  1586. }
  1587. //---------------------------------------------------------------------------
  1588. void __fastcall TConsoleRunner::SynchronizeControllerTooManyDirectories(
  1589. TSynchronizeController * /*Sender*/, int & MaxDirectories)
  1590. {
  1591. if (Aborted())
  1592. {
  1593. Abort();
  1594. }
  1595. if (MaxDirectories < GUIConfiguration->MaxWatchDirectories)
  1596. {
  1597. MaxDirectories = GUIConfiguration->MaxWatchDirectories;
  1598. }
  1599. else
  1600. {
  1601. MaxDirectories *= 2;
  1602. }
  1603. }
  1604. //---------------------------------------------------------------------------
  1605. void __fastcall TConsoleRunner::ShowException(Exception * E)
  1606. {
  1607. DoShowException(NULL, E);
  1608. }
  1609. //---------------------------------------------------------------------------
  1610. void __fastcall TConsoleRunner::DoShowException(TTerminal * Terminal, Exception * E)
  1611. {
  1612. if ((Terminal == NULL) && (FScript != NULL))
  1613. {
  1614. Terminal = FScript->Terminal;
  1615. }
  1616. UnicodeString Message;
  1617. if (ExceptionMessage(E, Message))
  1618. {
  1619. FCommandError = true;
  1620. PrintMessage(Message);
  1621. ExtException * EE = dynamic_cast<ExtException *>(E);
  1622. if ((EE != NULL) && (EE->MoreMessages != NULL))
  1623. {
  1624. PrintMessage(EE->MoreMessages->Text);
  1625. }
  1626. }
  1627. TTerminal * LoggingTerminal = Terminal;
  1628. TSecondaryTerminal * SecondaryTerminal = dynamic_cast<TSecondaryTerminal *>(LoggingTerminal);
  1629. if (SecondaryTerminal != NULL)
  1630. {
  1631. LoggingTerminal = SecondaryTerminal->MainTerminal;
  1632. }
  1633. if (LoggingTerminal != NULL)
  1634. {
  1635. LoggingTerminal->ActionLog->AddFailure(E);
  1636. }
  1637. }
  1638. //---------------------------------------------------------------------------
  1639. bool __fastcall TConsoleRunner::DoInput(UnicodeString & Str, bool Echo,
  1640. unsigned int Timeout, bool Interactive)
  1641. {
  1642. bool Result;
  1643. if (Interactive && FConsole->NoInteractiveInput())
  1644. {
  1645. Result = false;
  1646. }
  1647. else
  1648. {
  1649. Result = FConsole->Input(Str, Echo, Timeout);
  1650. }
  1651. if (!Result)
  1652. {
  1653. NotifyAbort();
  1654. }
  1655. return Result;
  1656. }
  1657. //---------------------------------------------------------------------------
  1658. void __fastcall TConsoleRunner::MasterPasswordPrompt()
  1659. {
  1660. bool Retry;
  1661. do
  1662. {
  1663. UnicodeString Password;
  1664. Input(LoadStr(CONSOLE_MASTER_PASSWORD_PROMPT), Password, false, true);
  1665. Retry = !WinConfiguration->ValidateMasterPassword(Password);
  1666. if (Retry)
  1667. {
  1668. PrintLine(LoadStr(MASTER_PASSWORD_INCORRECT));
  1669. }
  1670. else
  1671. {
  1672. WinConfiguration->SetMasterPassword(Password);
  1673. }
  1674. }
  1675. while (Retry);
  1676. }
  1677. //---------------------------------------------------------------------------
  1678. UnicodeString TConsoleRunner::ExpandCommand(UnicodeString Command, TStrings * ScriptParameters)
  1679. {
  1680. DebugAssert(ScriptParameters != NULL);
  1681. for (int Index = 0; Index < ScriptParameters->Count; Index++)
  1682. {
  1683. Command = ReplaceStr(Command, FORMAT(L"%%%d%%", (Index+1)),
  1684. ScriptParameters->Strings[Index]);
  1685. }
  1686. TDateTime N = Now();
  1687. if (!FExternalTimestampVar)
  1688. {
  1689. Command =
  1690. ReplaceStr(Command, FORMAT(L"%%%s%%", (TimestampVarName)), FormatDateTime(L"yyyymmddhhnnss", N));
  1691. }
  1692. int Offset = 1;
  1693. int P2;
  1694. do
  1695. {
  1696. int P = Pos(UpperCase(L"%" + TimestampVarName + L"#"), UpperCase(Command.SubString(Offset, Command.Length() - Offset + 1)));
  1697. if (P > 0)
  1698. {
  1699. P += Offset - 1;
  1700. Offset = P + 1 + TimestampVarName.Length() + 1;
  1701. P2 = Pos(L"%", Command.SubString(Offset, Command.Length() - Offset + 1));
  1702. if (P2 > 0)
  1703. {
  1704. UnicodeString TimestampFormat = Command.SubString(Offset, P2 - 1);
  1705. UnicodeString TimestampValue = FormatDateTime(TimestampFormat, N);
  1706. Command = Command.SubString(1, P - 1) + TimestampValue + Command.SubString(Offset + P2, Command.Length() - Offset - P2 + 1);
  1707. Offset = P + TimestampValue.Length();
  1708. }
  1709. }
  1710. else
  1711. {
  1712. P2 = 0;
  1713. }
  1714. }
  1715. while (P2 > 0);
  1716. Command = ExpandEnvironmentVariables(Command);
  1717. return Command;
  1718. }
  1719. //---------------------------------------------------------------------------
  1720. void __fastcall TConsoleRunner::Failed(bool & AnyError)
  1721. {
  1722. if (FScript != NULL)
  1723. {
  1724. FScript->Log(llMessage, L"Failed");
  1725. }
  1726. AnyError = true;
  1727. }
  1728. //---------------------------------------------------------------------------
  1729. int __fastcall TConsoleRunner::Run(const UnicodeString Session, TOptions * Options,
  1730. TStrings * ScriptCommands, TStrings * ScriptParameters)
  1731. {
  1732. int ExitCode;
  1733. try
  1734. {
  1735. bool AnyError = false;
  1736. try
  1737. {
  1738. FScript = new TManagementScript(StoredSessions, FConsole->LimitedOutput());
  1739. FScript->CopyParam = GUIConfiguration->DefaultCopyParam;
  1740. FScript->SynchronizeParams = GUIConfiguration->SynchronizeParams;
  1741. FScript->WantsProgress = FConsole->WantsProgress();
  1742. FScript->OnPrint = ScriptPrint;
  1743. FScript->OnPrintProgress = ScriptPrintProgress;
  1744. FScript->OnInput = ScriptInput;
  1745. FScript->OnTerminalPromptUser = ScriptTerminalPromptUser;
  1746. FScript->OnShowExtendedException = ScriptShowExtendedException;
  1747. FScript->OnTerminalQueryUser = ScriptTerminalQueryUser;
  1748. FScript->OnQueryCancel = ScriptQueryCancel;
  1749. FScript->OnSynchronizeStartStop = ScriptSynchronizeStartStop;
  1750. FScript->OnProgress = ScriptProgress;
  1751. UpdateTitle();
  1752. // everything until the first manually entered command is "batch"
  1753. // (including opening session from command line and script file)
  1754. FBatchScript = true;
  1755. if (!Session.IsEmpty())
  1756. {
  1757. PrintMessage(LoadStr(SCRIPT_CMDLINE_SESSION));
  1758. FCommandError = false;
  1759. FScript->Connect(Session, Options, false);
  1760. if (FCommandError)
  1761. {
  1762. Failed(AnyError);
  1763. }
  1764. }
  1765. FScript->Groups = Options->SwitchValue(L"xmlgroups", true, false);
  1766. int ScriptPos = 0;
  1767. bool Result;
  1768. do
  1769. {
  1770. UpdateTitle();
  1771. UnicodeString Command;
  1772. if ((ScriptCommands != NULL) && (ScriptPos < ScriptCommands->Count))
  1773. {
  1774. Result = true;
  1775. Command = ScriptCommands->Strings[ScriptPos];
  1776. ScriptPos++;
  1777. }
  1778. else
  1779. {
  1780. if (FBatchScript)
  1781. {
  1782. // no longer batch
  1783. FBatchScript = false;
  1784. FScript->StartInteractive();
  1785. }
  1786. Print(L"winscp> ");
  1787. Result = DoInput(Command, true, 0, false);
  1788. }
  1789. if (Result)
  1790. {
  1791. FCommandError = false;
  1792. FScript->Command(ExpandCommand(Command, ScriptParameters));
  1793. if (FCommandError)
  1794. {
  1795. Failed(AnyError);
  1796. if (FScript->Batch == TScript::BatchAbort)
  1797. {
  1798. Result = false;
  1799. }
  1800. }
  1801. if (FScript->Terminal != NULL)
  1802. {
  1803. FScript->Terminal->Idle();
  1804. }
  1805. }
  1806. }
  1807. while (Result && FScript->Continue && !Aborted());
  1808. }
  1809. catch(Exception & E)
  1810. {
  1811. Failed(AnyError);
  1812. ShowException(&E);
  1813. }
  1814. if (FLastProgressLen > 0)
  1815. {
  1816. FConsole->Print(L"\n");
  1817. FLastProgressLen = 0;
  1818. }
  1819. ExitCode = AnyError ? RESULT_ANY_ERROR : RESULT_SUCCESS;
  1820. if (FScript != NULL)
  1821. {
  1822. FScript->Log(llMessage, FORMAT(L"Exit code: %d", (ExitCode)));
  1823. }
  1824. }
  1825. __finally
  1826. {
  1827. delete FScript;
  1828. FScript = NULL;
  1829. }
  1830. return ExitCode;
  1831. }
  1832. //---------------------------------------------------------------------------
  1833. void __fastcall TConsoleRunner::UpdateTitle()
  1834. {
  1835. UnicodeString NewTitle;
  1836. if (FScript->Terminal != NULL)
  1837. {
  1838. NewTitle = FormatMainFormCaption(FScript->Terminal->SessionData->SessionName);
  1839. }
  1840. else
  1841. {
  1842. NewTitle = FormatMainFormCaption(L"");
  1843. }
  1844. FConsole->SetTitle(NewTitle);
  1845. }
  1846. //---------------------------------------------------------------------------
  1847. void __fastcall TConsoleRunner::ConfigurationChange(TObject * /*Sender*/)
  1848. {
  1849. if (FScript != NULL)
  1850. {
  1851. FScript->ReflectSettings();
  1852. }
  1853. }
  1854. //---------------------------------------------------------------------------
  1855. void __fastcall LoadScriptFromFile(UnicodeString FileName, TStrings * Lines)
  1856. {
  1857. Lines->LoadFromFile(FileName, TEncoding::UTF8);
  1858. }
  1859. //---------------------------------------------------------------------------
  1860. void __fastcall ConsolePrintLine(TConsole * Console, const UnicodeString & Str)
  1861. {
  1862. Console->Print(Str + L"\n");
  1863. }
  1864. //---------------------------------------------------------------------------
  1865. static UnicodeString __fastcall GetExeBaseName()
  1866. {
  1867. return ExtractFileBaseName(Application->ExeName);
  1868. }
  1869. //---------------------------------------------------------------------------
  1870. static void __fastcall PrintUsageSyntax(TConsole * Console, const UnicodeString & Str)
  1871. {
  1872. ConsolePrintLine(Console, GetExeBaseName() + L" " + Str);
  1873. }
  1874. //---------------------------------------------------------------------------
  1875. typedef std::vector<std::pair<UnicodeString, UnicodeString> > TSwitchesUsage;
  1876. //---------------------------------------------------------------------------
  1877. static void __fastcall RegisterSwitch(
  1878. TSwitchesUsage & SwitchesUsage, const UnicodeString & Name, const UnicodeString & Desc)
  1879. {
  1880. SwitchesUsage.push_back(std::make_pair(LowerCase(Name), Desc));
  1881. }
  1882. //---------------------------------------------------------------------------
  1883. static void __fastcall RegisterSwitch(
  1884. TSwitchesUsage & SwitchesUsage, const UnicodeString & Name, int DescID)
  1885. {
  1886. UnicodeString Desc = LoadStr(DescID);
  1887. Desc = ReplaceText(Desc, L"%APP%", GetExeBaseName());
  1888. RegisterSwitch(SwitchesUsage, Name, Desc);
  1889. }
  1890. //---------------------------------------------------------------------------
  1891. void __fastcall Usage(TConsole * Console)
  1892. {
  1893. ConsolePrintLine(Console, FORMAT(L"WinSCP, %s", (Configuration->VersionStr)));
  1894. UnicodeString Copyright =
  1895. ReplaceText(LoadStr(WINSCP_COPYRIGHT), L"©", L"(c)");
  1896. ConsolePrintLine(Console, Copyright);
  1897. ConsolePrintLine(Console, L"");
  1898. ConsolePrintLine(Console, LoadStr(USAGE_SYNTAX_LABEL));
  1899. if (!Console->CommandLineOnly())
  1900. {
  1901. PrintUsageSyntax(Console, L"site|workspace|folder");
  1902. PrintUsageSyntax(Console, L"(sftp|scp|ftp[es]|http[s])://[user[:password]@]host[:port][/path/[file]]");
  1903. PrintUsageSyntax(Console, FORMAT(L"[mysession] /%s=<name>", (LowerCase(SESSIONNAME_SWICH))));
  1904. PrintUsageSyntax(Console, L"[mysession] /newinstance");
  1905. PrintUsageSyntax(Console, L"[mysession] /edit <path>");
  1906. PrintUsageSyntax(Console, L"[mysession] /synchronize [local_dir] [remote_dir] [/defaults]");
  1907. PrintUsageSyntax(Console, L"[mysession] /keepuptodate [local_dir] [remote_dir] [/defaults]");
  1908. PrintUsageSyntax(Console, L"[mysession] [/privatekey=<file>] [/hostkey=<fingerprint>]");
  1909. PrintUsageSyntax(Console, L"[mysession] [/clientcert=<file>] [/certificate=<fingerprint>]");
  1910. PrintUsageSyntax(Console, L"[mysession] [/passive[=on|off]] [/implicit|explicit]");
  1911. PrintUsageSyntax(Console, L"[mysession] [/timeout=<sec>]");
  1912. PrintUsageSyntax(Console, L"[mysession] [/rawsettings setting1=value1 setting2=value2 ...]");
  1913. }
  1914. PrintUsageSyntax(Console,
  1915. UnicodeString(!Console->CommandLineOnly() ? L"[/console] " : L"") +
  1916. FORMAT(L"[/script=file] [/%s cmd1...] [/parameter // param1...]", (LowerCase(COMMAND_SWITCH))));
  1917. PrintUsageSyntax(Console, L"[/log=<logfile> [/loglevel=<level>]] [/xmllog=<logfile> [/xmlgroups]]");
  1918. PrintUsageSyntax(Console, L"[/ini=<inifile>]");
  1919. PrintUsageSyntax(Console, L"[/rawconfig config1=value1 config2=value2 ...]");
  1920. PrintUsageSyntax(Console, L"/batchsettings <site_mask> setting1=value1 setting2=value2 ...");
  1921. PrintUsageSyntax(Console, FORMAT(L"/%s keyfile /%s=output [/%s] [/%s=comment]",
  1922. (LowerCase(KEYGEN_SWITCH), LowerCase(KEYGEN_OUTPUT_SWITCH), LowerCase(KEYGEN_CHANGE_PASSPHRASE_SWITCH), LowerCase(KEYGEN_COMMENT_SWITCH))));
  1923. if (!Console->CommandLineOnly())
  1924. {
  1925. PrintUsageSyntax(Console, L"/update");
  1926. }
  1927. PrintUsageSyntax(Console, L"/help");
  1928. ConsolePrintLine(Console, L"");
  1929. TSwitchesUsage SwitchesUsage;
  1930. if (!Console->CommandLineOnly())
  1931. {
  1932. RegisterSwitch(SwitchesUsage, L"session", USAGE_SESSION);
  1933. RegisterSwitch(SwitchesUsage, TProgramParams::FormatSwitch(SESSIONNAME_SWICH) + L"=", USAGE_SESSIONNAME);
  1934. RegisterSwitch(SwitchesUsage, L"/newinstance", USAGE_NEWINSTANCE);
  1935. RegisterSwitch(SwitchesUsage, L"/edit", USAGE_EDIT);
  1936. RegisterSwitch(SwitchesUsage, L"/synchronize", USAGE_SYNCHRONIZE);
  1937. RegisterSwitch(SwitchesUsage, L"/keepuptodate", USAGE_KEEPUPTODATE);
  1938. RegisterSwitch(SwitchesUsage, L"/defaults", USAGE_DEFAULTS);
  1939. RegisterSwitch(SwitchesUsage, L"/privatekey=", USAGE_PRIVATEKEY);
  1940. RegisterSwitch(SwitchesUsage, L"/hostkey=", USAGE_HOSTKEY);
  1941. RegisterSwitch(SwitchesUsage, L"/clientcert=", USAGE_CLIENTCERT);
  1942. RegisterSwitch(SwitchesUsage, L"/certificate=", USAGE_CERTIFICATE);
  1943. RegisterSwitch(SwitchesUsage, L"/passive=", USAGE_PASSIVE);
  1944. RegisterSwitch(SwitchesUsage, L"/implicit", USAGE_IMPLICIT);
  1945. RegisterSwitch(SwitchesUsage, L"/explicit", USAGE_EXPLICIT);
  1946. RegisterSwitch(SwitchesUsage, L"/timeout=", USAGE_TIMEOUT);
  1947. RegisterSwitch(SwitchesUsage, L"/rawsettings", USAGE_RAWSETTINGS);
  1948. RegisterSwitch(SwitchesUsage, L"/console", USAGE_CONSOLE);
  1949. }
  1950. RegisterSwitch(SwitchesUsage, L"/script=", USAGE_SCRIPT);
  1951. RegisterSwitch(SwitchesUsage, TProgramParams::FormatSwitch(COMMAND_SWITCH), USAGE_COMMAND);
  1952. RegisterSwitch(SwitchesUsage, L"/parameter", USAGE_PARAMETER);
  1953. RegisterSwitch(SwitchesUsage, L"/log=", USAGE_LOG);
  1954. RegisterSwitch(SwitchesUsage, L"/loglevel=", USAGE_LOGLEVEL);
  1955. RegisterSwitch(SwitchesUsage, L"/xmllog=", USAGE_XMLLOG);
  1956. RegisterSwitch(SwitchesUsage, L"/xmlgroups", USAGE_XMLGROUPS);
  1957. RegisterSwitch(SwitchesUsage, L"/ini=", USAGE_INI);
  1958. RegisterSwitch(SwitchesUsage, L"/rawconfig", USAGE_RAWCONFIG);
  1959. RegisterSwitch(SwitchesUsage, L"/batchsettings", USAGE_BATCHSETTINGS);
  1960. UnicodeString KeyGenDesc =
  1961. FMTLOAD(USAGE_KEYGEN, (
  1962. TProgramParams::FormatSwitch(LowerCase(KEYGEN_OUTPUT_SWITCH)) + L"=",
  1963. TProgramParams::FormatSwitch(LowerCase(KEYGEN_CHANGE_PASSPHRASE_SWITCH)),
  1964. TProgramParams::FormatSwitch(LowerCase(KEYGEN_COMMENT_SWITCH)) + L"="));
  1965. RegisterSwitch(SwitchesUsage, TProgramParams::FormatSwitch(KEYGEN_SWITCH), KeyGenDesc);
  1966. if (!Console->CommandLineOnly())
  1967. {
  1968. RegisterSwitch(SwitchesUsage, L"/update", USAGE_UPDATE);
  1969. }
  1970. RegisterSwitch(SwitchesUsage, L"/help", USAGE_HELP);
  1971. int MaxSwitchLen = 0;
  1972. TSwitchesUsage::const_iterator Index = SwitchesUsage.begin();
  1973. while (Index != SwitchesUsage.end())
  1974. {
  1975. MaxSwitchLen = std::max(Index->first.Length(), MaxSwitchLen);
  1976. ++Index;
  1977. }
  1978. Index = SwitchesUsage.begin();
  1979. while (Index != SwitchesUsage.end())
  1980. {
  1981. UnicodeString Label =
  1982. UnicodeString(L" ") +
  1983. Index->first +
  1984. UnicodeString::StringOfChar(L' ', MaxSwitchLen - Index->first.Length()) +
  1985. L" ";
  1986. Console->Print(Label);
  1987. const int ConsoleWidth = 80;
  1988. int DescWidth = ConsoleWidth - Label.Length() - 1;
  1989. bool FirstLine = true;
  1990. UnicodeString Desc = Index->second;
  1991. while (!Desc.IsEmpty())
  1992. {
  1993. UnicodeString DescLine = CutToChar(Desc, L'\n', true);
  1994. DescLine = WrapText(DescLine, L"\n", TSysCharSet() << L' ', DescWidth);
  1995. while (!DescLine.IsEmpty())
  1996. {
  1997. UnicodeString DescLineLine = CutToChar(DescLine, L'\n', true);
  1998. if (!FirstLine)
  1999. {
  2000. DescLineLine =
  2001. UnicodeString::StringOfChar(L' ', Label.Length()) +
  2002. DescLineLine;
  2003. }
  2004. FirstLine = false;
  2005. ConsolePrintLine(Console, DescLineLine);
  2006. }
  2007. }
  2008. ++Index;
  2009. }
  2010. Console->WaitBeforeExit();
  2011. }
  2012. //---------------------------------------------------------------------------
  2013. void __fastcall BatchSettings(TConsole * Console, TProgramParams * Params)
  2014. {
  2015. std::unique_ptr<TStrings> Arguments(new TStringList());
  2016. if (ALWAYS_TRUE(Params->FindSwitch(L"batchsettings", Arguments.get())))
  2017. {
  2018. if (Arguments->Count < 1)
  2019. {
  2020. ConsolePrintLine(Console, LoadStr(BATCH_SET_NO_MASK));
  2021. }
  2022. else if (Arguments->Count < 2)
  2023. {
  2024. ConsolePrintLine(Console, LoadStr(BATCH_SET_NO_SETTINGS));
  2025. }
  2026. else
  2027. {
  2028. TFileMasks Mask(Arguments->Strings[0]);
  2029. Arguments->Delete(0);
  2030. std::unique_ptr<TOptionsStorage> OptionsStorage(new TOptionsStorage(Arguments.get(), false));
  2031. int Matches = 0;
  2032. int Changes = 0;
  2033. for (int Index = 0; Index < StoredSessions->Count; Index++)
  2034. {
  2035. TSessionData * Data = StoredSessions->Sessions[Index];
  2036. if (!Data->IsWorkspace &&
  2037. Mask.Matches(Data->Name, false, false))
  2038. {
  2039. Matches++;
  2040. std::unique_ptr<TSessionData> OriginalData(new TSessionData(L""));
  2041. OriginalData->Assign(Data);
  2042. Data->ApplyRawSettings(OptionsStorage.get());
  2043. bool Changed = !OriginalData->IsSame(Data, false);
  2044. if (Changed)
  2045. {
  2046. Changes++;
  2047. }
  2048. UnicodeString StateStr = LoadStr(Changed ? BATCH_SET_CHANGED : BATCH_SET_NOT_CHANGED);
  2049. ConsolePrintLine(Console, FORMAT(L"%s - %s", (Data->Name, StateStr)));
  2050. }
  2051. }
  2052. StoredSessions->Save(false, true); // explicit
  2053. ConsolePrintLine(Console, FMTLOAD(BATCH_SET_SUMMARY, (Matches, Changes)));
  2054. }
  2055. Console->WaitBeforeExit();
  2056. }
  2057. }
  2058. //---------------------------------------------------------------------------
  2059. bool __fastcall FindPuttygenCompatibleSwitch(
  2060. TProgramParams * Params, const UnicodeString & Name, const UnicodeString & PuttygenName, UnicodeString & Value, bool & Set)
  2061. {
  2062. bool Result = Params->FindSwitch(Name, Value, Set);
  2063. if (!Result)
  2064. {
  2065. std::unique_ptr<TStrings> Args(new TStringList());
  2066. Result = Params->FindSwitchCaseSensitive(PuttygenName, Args.get(), 1);
  2067. if (Result && (Args->Count >= 1))
  2068. {
  2069. Value = Args->Strings[0];
  2070. Set = true;
  2071. }
  2072. }
  2073. return Result;
  2074. }
  2075. //---------------------------------------------------------------------------
  2076. int __fastcall KeyGen(TConsole * Console, TProgramParams * Params)
  2077. {
  2078. int Result = RESULT_SUCCESS;
  2079. UnicodeString Passphrase;
  2080. UnicodeString NewPassphrase;
  2081. try
  2082. {
  2083. UnicodeString InputFileName;
  2084. std::unique_ptr<TStrings> Args(new TStringList());
  2085. if (!Params->FindSwitch(KEYGEN_SWITCH, Args.get(), 1) ||
  2086. (Args->Count < 1) ||
  2087. Args->Strings[0].IsEmpty())
  2088. {
  2089. throw Exception(LoadStr(KEYGEN_NO_INPUT));
  2090. }
  2091. InputFileName = Args->Strings[0];
  2092. bool ValueSet;
  2093. UnicodeString OutputFileName;
  2094. FindPuttygenCompatibleSwitch(Params, KEYGEN_OUTPUT_SWITCH, L"o", OutputFileName, ValueSet);
  2095. UnicodeString NewComment;
  2096. FindPuttygenCompatibleSwitch(Params, KEYGEN_COMMENT_SWITCH, L"C", NewComment, ValueSet);
  2097. bool NewPassphraseSet;
  2098. bool ChangePassphrase =
  2099. FindPuttygenCompatibleSwitch(Params, KEYGEN_CHANGE_PASSPHRASE_SWITCH, L"P", NewPassphrase, NewPassphraseSet);
  2100. TKeyType Type = KeyType(InputFileName);
  2101. int Error = errno;
  2102. switch (Type)
  2103. {
  2104. case ktSSH1:
  2105. throw Exception(LoadStr(KEYGEN_SSH1));
  2106. case ktSSH2:
  2107. if (NewComment.IsEmpty() && !ChangePassphrase)
  2108. {
  2109. throw Exception(LoadStr(KEYGEN_NO_ACTION));
  2110. }
  2111. break;
  2112. case ktOpenSSH:
  2113. case ktSSHCom:
  2114. if (OutputFileName.IsEmpty())
  2115. {
  2116. throw Exception(LoadStr(KEYGEN_NO_OUTPUT));
  2117. }
  2118. break;
  2119. case ktUnopenable:
  2120. throw EOSExtException(FMTLOAD(KEY_TYPE_UNOPENABLE, (InputFileName)), Error);
  2121. default:
  2122. FAIL;
  2123. // fallthru
  2124. case ktUnknown:
  2125. throw Exception(FMTLOAD(KEY_TYPE_UNKNOWN2, (InputFileName)));
  2126. }
  2127. UnicodeString Comment;
  2128. if (IsKeyEncrypted(Type, InputFileName, Comment))
  2129. {
  2130. Passphrase = Params->SwitchValue(PassphraseOption);
  2131. if (Passphrase.IsEmpty())
  2132. {
  2133. Console->Print(StripHotkey(FMTLOAD(PROMPT_KEY_PASSPHRASE, (Comment))) + L" ");
  2134. if (!Console->Input(Passphrase, false, 0) ||
  2135. Passphrase.IsEmpty())
  2136. {
  2137. Abort();
  2138. }
  2139. }
  2140. }
  2141. TPrivateKey * PrivateKey = LoadKey(Type, InputFileName, Passphrase);
  2142. try
  2143. {
  2144. if (!NewComment.IsEmpty())
  2145. {
  2146. ChangeKeyComment(PrivateKey, NewComment);
  2147. }
  2148. if (ChangePassphrase)
  2149. {
  2150. if (!NewPassphraseSet)
  2151. {
  2152. Console->Print(LoadStr(KEYGEN_PASSPHRASE) + L" ");
  2153. if (!Console->Input(NewPassphrase, false, 0))
  2154. {
  2155. Abort();
  2156. }
  2157. Console->Print(LoadStr(KEYGEN_PASSPHRASE2) + L" ");
  2158. UnicodeString NewPassphrase2;
  2159. if (!Console->Input(NewPassphrase2, false, 0))
  2160. {
  2161. Abort();
  2162. }
  2163. if (NewPassphrase != NewPassphrase2)
  2164. {
  2165. Shred(NewPassphrase2);
  2166. throw Exception(LoadStr(KEYGEN_PASSPHRASES_MISMATCH));
  2167. }
  2168. }
  2169. }
  2170. else
  2171. {
  2172. NewPassphrase = Passphrase;
  2173. }
  2174. if (OutputFileName.IsEmpty())
  2175. {
  2176. OutputFileName = InputFileName;
  2177. }
  2178. SaveKey(ktSSH2, OutputFileName, NewPassphrase, PrivateKey);
  2179. ConsolePrintLine(Console, FMTLOAD(KEYGEN_SAVED, (OutputFileName)));
  2180. }
  2181. __finally
  2182. {
  2183. FreeKey(PrivateKey);
  2184. }
  2185. }
  2186. catch (Exception & E)
  2187. {
  2188. UnicodeString Message;
  2189. if (ExceptionMessage(&E, Message))
  2190. {
  2191. ConsolePrintLine(Console, Message);
  2192. ExtException * EE = dynamic_cast<ExtException *>(&E);
  2193. if ((EE != NULL) && (EE->MoreMessages != NULL))
  2194. {
  2195. ConsolePrintLine(Console, EE->MoreMessages->Text);
  2196. }
  2197. }
  2198. Result = RESULT_ANY_ERROR;
  2199. }
  2200. Shred(Passphrase);
  2201. Shred(NewPassphrase);
  2202. Console->WaitBeforeExit();
  2203. return Result;
  2204. }
  2205. //---------------------------------------------------------------------------
  2206. int __fastcall Console(TConsoleMode Mode)
  2207. {
  2208. DebugAssert(Mode != cmNone);
  2209. TProgramParams * Params = TProgramParams::Instance();
  2210. int Result = RESULT_SUCCESS;
  2211. TConsole * Console = NULL;
  2212. TConsoleRunner * Runner = NULL;
  2213. TStrings * ScriptCommands = new TStringList();
  2214. TStrings * ScriptParameters = new TStringList();
  2215. try
  2216. {
  2217. UnicodeString ConsoleInstance;
  2218. // First check for /consoleinstance as /console is always used by winscp.com
  2219. if (Params->FindSwitch(L"consoleinstance", ConsoleInstance))
  2220. {
  2221. Configuration->Usage->Inc(L"ConsoleExternal");
  2222. Console = new TExternalConsole(ConsoleInstance, Params->FindSwitch(L"nointeractiveinput"));
  2223. }
  2224. else if (Params->FindSwitch(L"Console") || (Mode != cmScripting))
  2225. {
  2226. Configuration->Usage->Inc(L"ConsoleOwn");
  2227. Console = TOwnConsole::Instance();
  2228. }
  2229. else
  2230. {
  2231. Configuration->Usage->Inc(L"ConsoleNull");
  2232. Console = new TNullConsole();
  2233. }
  2234. SetNoGUI();
  2235. if (Mode == cmHelp)
  2236. {
  2237. Configuration->Usage->Inc(L"UsageShown");
  2238. Usage(Console);
  2239. }
  2240. else if (Mode == cmBatchSettings)
  2241. {
  2242. if (CheckSafe(Params))
  2243. {
  2244. Configuration->Usage->Inc(L"BatchSettings");
  2245. BatchSettings(Console, Params);
  2246. }
  2247. }
  2248. else if (Mode == cmKeyGen)
  2249. {
  2250. if (CheckSafe(Params))
  2251. {
  2252. Configuration->Usage->Inc(L"KeyGen");
  2253. Result = KeyGen(Console, Params);
  2254. }
  2255. }
  2256. else
  2257. {
  2258. Runner = new TConsoleRunner(Console);
  2259. try
  2260. {
  2261. if (CheckSafe(Params))
  2262. {
  2263. UnicodeString Value;
  2264. if (Params->FindSwitch(L"script", Value) && !Value.IsEmpty())
  2265. {
  2266. Configuration->Usage->Inc(L"ScriptFile");
  2267. LoadScriptFromFile(Value, ScriptCommands);
  2268. }
  2269. Params->FindSwitch(COMMAND_SWITCH, ScriptCommands);
  2270. if (ScriptCommands->Count > 0)
  2271. {
  2272. Configuration->Usage->Inc(L"ScriptCommands");
  2273. }
  2274. Params->FindSwitch(L"parameter", ScriptParameters);
  2275. if (ScriptParameters->Count > 0)
  2276. {
  2277. Configuration->Usage->Inc(L"ScriptParameters");
  2278. }
  2279. }
  2280. UnicodeString Session;
  2281. if (Params->ParamCount >= 1)
  2282. {
  2283. Session = Params->Param[1];
  2284. if (Params->ParamCount > 1)
  2285. {
  2286. Runner->PrintMessage(LoadStr(SCRIPT_CMDLINE_PARAMETERS));
  2287. }
  2288. }
  2289. bool DefaultsOnly;
  2290. delete StoredSessions->ParseUrl(Session, Params, DefaultsOnly);
  2291. UnicodeString LogFile;
  2292. if (Params->FindSwitch(L"Log", LogFile) && CheckSafe(Params))
  2293. {
  2294. Configuration->Usage->Inc(L"ScriptLog");
  2295. Configuration->TemporaryLogging(LogFile);
  2296. }
  2297. CheckXmlLogParam(Params);
  2298. Result = Runner->Run(Session, Params,
  2299. (ScriptCommands->Count > 0 ? ScriptCommands : NULL),
  2300. ScriptParameters);
  2301. }
  2302. catch(Exception & E)
  2303. {
  2304. Runner->ShowException(&E);
  2305. Result = RESULT_ANY_ERROR;
  2306. }
  2307. }
  2308. }
  2309. __finally
  2310. {
  2311. delete Runner;
  2312. delete Console;
  2313. delete ScriptCommands;
  2314. delete ScriptParameters;
  2315. }
  2316. return Result;
  2317. }