ConsoleRunner.cpp 91 KB

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