ConsoleRunner.cpp 90 KB

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