ConsoleRunner.cpp 86 KB

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