ConsoleRunner.cpp 78 KB

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