ConsoleRunner.cpp 86 KB

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