ConsoleRunner.cpp 80 KB

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