ConsoleRunner.cpp 95 KB

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