ConsoleRunner.cpp 92 KB

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