ConsoleRunner.cpp 80 KB

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