ConsoleRunner.cpp 78 KB

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