ConsoleRunner.cpp 86 KB

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