ConsoleRunner.cpp 93 KB

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