ConsoleRunner.cpp 82 KB

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