ConsoleRunner.cpp 79 KB

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