ConsoleRunner.cpp 91 KB

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