ConsoleRunner.cpp 77 KB

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