ConsoleRunner.cpp 87 KB

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