1
0

ConsoleRunner.cpp 78 KB

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