ConsoleRunner.cpp 92 KB

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