ConsoleRunner.cpp 95 KB

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