ConsoleRunner.cpp 80 KB

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