ConsoleRunner.cpp 94 KB

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