ConsoleRunner.cpp 85 KB

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