ConsoleRunner.cpp 94 KB

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