1
0

ConsoleRunner.cpp 83 KB

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