ConsoleRunner.cpp 81 KB

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