Main.cpp 28 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034
  1. //---------------------------------------------------------------------------
  2. #include <stdexcept>
  3. #include <stdio.h>
  4. #include <stdlib.h>
  5. #include <windows.h>
  6. #include <io.h>
  7. #include <fcntl.h>
  8. #include "Console.h"
  9. #define MAX_ATTEMPTS 10
  10. //---------------------------------------------------------------------------
  11. #define LENOF(x) ( (sizeof((x))) / (sizeof(*(x))))
  12. //---------------------------------------------------------------------------
  13. using namespace std;
  14. HANDLE ConsoleInput = NULL;
  15. HANDLE ConsoleOutput = NULL;
  16. HANDLE ConsoleStandardOutput = NULL;
  17. HANDLE ConsoleErrorOutput = NULL;
  18. HANDLE Child = NULL;
  19. HANDLE CancelEvent = NULL;
  20. HANDLE InputTimerEvent = NULL;
  21. bool SupportsUtf8ConsoleOutput = false;
  22. unsigned int OutputType = FILE_TYPE_UNKNOWN;
  23. unsigned int InputType = FILE_TYPE_UNKNOWN;
  24. enum { RESULT_GLOBAL_ERROR = 1, RESULT_INIT_ERROR = 2, RESULT_PROCESSING_ERROR = 3,
  25. RESULT_UNKNOWN_ERROR = 4 };
  26. const wchar_t* CONSOLE_CHILD_PARAM = L"consolechild";
  27. //---------------------------------------------------------------------------
  28. inline TConsoleCommStruct* GetCommStruct(HANDLE FileMapping)
  29. {
  30. TConsoleCommStruct* Result;
  31. Result = static_cast<TConsoleCommStruct*>(MapViewOfFile(FileMapping,
  32. FILE_MAP_ALL_ACCESS, 0, 0, 0));
  33. if (Result == NULL)
  34. {
  35. throw runtime_error("Cannot open mapping object.");
  36. }
  37. return Result;
  38. }
  39. //---------------------------------------------------------------------------
  40. inline void FreeCommStruct(TConsoleCommStruct* CommStruct)
  41. {
  42. UnmapViewOfFile(CommStruct);
  43. }
  44. //---------------------------------------------------------------------------
  45. void InitializeConsole(wchar_t* InstanceName, HANDLE& RequestEvent, HANDLE& ResponseEvent,
  46. HANDLE& CancelEvent, HANDLE& FileMapping, HANDLE& Job)
  47. {
  48. unsigned int Process = GetCurrentProcessId();
  49. int Attempts = 0;
  50. wchar_t Name[MAX_PATH];
  51. bool UniqEvent;
  52. do
  53. {
  54. if (Attempts > MAX_ATTEMPTS)
  55. {
  56. throw runtime_error("Cannot find unique name for event object.");
  57. }
  58. int InstanceNumber;
  59. #ifdef CONSOLE_TEST
  60. InstanceNumber = 1;
  61. #else
  62. InstanceNumber = random(1000);
  63. #endif
  64. swprintf(InstanceName, L"_%u_%d", Process, InstanceNumber);
  65. swprintf(Name, L"%s%s", CONSOLE_EVENT_REQUEST, InstanceName);
  66. HANDLE EventHandle = OpenEvent(EVENT_ALL_ACCESS, false, Name);
  67. UniqEvent = (EventHandle == NULL);
  68. if (!UniqEvent)
  69. {
  70. CloseHandle(EventHandle);
  71. }
  72. Attempts++;
  73. }
  74. while (!UniqEvent);
  75. RequestEvent = CreateEvent(NULL, false, false, Name);
  76. if (RequestEvent == NULL)
  77. {
  78. throw runtime_error("Cannot create request event object.");
  79. }
  80. swprintf(Name, L"%s%s", CONSOLE_EVENT_RESPONSE, InstanceName);
  81. ResponseEvent = CreateEvent(NULL, false, false, Name);
  82. if (ResponseEvent == NULL)
  83. {
  84. throw runtime_error("Cannot create response event object.");
  85. }
  86. swprintf(Name, L"%s%s", CONSOLE_EVENT_CANCEL, InstanceName);
  87. CancelEvent = CreateEvent(NULL, false, false, Name);
  88. if (CancelEvent == NULL)
  89. {
  90. throw runtime_error("Cannot create cancel event object.");
  91. }
  92. swprintf(Name, L"%s%s", CONSOLE_MAPPING, InstanceName);
  93. FileMapping = CreateFileMapping((HANDLE)0xFFFFFFFF, NULL, PAGE_READWRITE,
  94. 0, sizeof(TConsoleCommStruct), Name);
  95. if (FileMapping == NULL)
  96. {
  97. throw runtime_error("Cannot create mapping object.");
  98. }
  99. swprintf(Name, L"%s%s", CONSOLE_JOB, InstanceName);
  100. Job = CreateJobObject(NULL, Name);
  101. if (Job == NULL)
  102. {
  103. throw runtime_error("Cannot create job object.");
  104. }
  105. JOBOBJECT_EXTENDED_LIMIT_INFORMATION ExtendedLimitInformation;
  106. memset(&ExtendedLimitInformation, 0, sizeof(ExtendedLimitInformation));
  107. ExtendedLimitInformation.BasicLimitInformation.LimitFlags =
  108. JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
  109. if (SetInformationJobObject(Job, JobObjectExtendedLimitInformation,
  110. &ExtendedLimitInformation, sizeof(ExtendedLimitInformation)) == 0)
  111. {
  112. CloseHandle(Job);
  113. Job = NULL;
  114. }
  115. TConsoleCommStruct* CommStruct = GetCommStruct(FileMapping);
  116. CommStruct->Size = sizeof(TConsoleCommStruct);
  117. CommStruct->Version = TConsoleCommStruct::CurrentVersion;
  118. CommStruct->Event = TConsoleCommStruct::NONE;
  119. FreeCommStruct(CommStruct);
  120. }
  121. //---------------------------------------------------------------------------
  122. // duplicated in Common.cpp
  123. bool __fastcall CutToken(const wchar_t*& Str, wchar_t* Token)
  124. {
  125. bool Result;
  126. // inspired by Putty's sftp_getcmd() from PSFTP.C
  127. int Length = wcslen(Str);
  128. int Index = 0;
  129. while ((Index < Length) &&
  130. ((Str[Index] == L' ') || (Str[Index] == L'\t')))
  131. {
  132. Index++;
  133. }
  134. if (Index < Length)
  135. {
  136. bool Quoting = false;
  137. while (Index < Length)
  138. {
  139. if (!Quoting && ((Str[Index] == L' ') || (Str[Index] == L'\t')))
  140. {
  141. break;
  142. }
  143. else if ((Str[Index] == L'"') && (Index + 1 < Length) &&
  144. (Str[Index + 1] == L'"'))
  145. {
  146. Index += 2;
  147. *Token = L'"';
  148. Token++;
  149. }
  150. else if (Str[Index] == L'"')
  151. {
  152. Index++;
  153. Quoting = !Quoting;
  154. }
  155. else
  156. {
  157. *Token = Str[Index];
  158. Token++;
  159. Index++;
  160. }
  161. }
  162. if (Index < Length)
  163. {
  164. Index++;
  165. }
  166. Str += Index;
  167. Result = true;
  168. }
  169. else
  170. {
  171. Result = false;
  172. Str += Length;
  173. }
  174. *Token = L'\0';
  175. return Result;
  176. }
  177. //---------------------------------------------------------------------------
  178. char* WideStringToString(const wchar_t* Message)
  179. {
  180. char* Buffer;
  181. int Size = WideCharToMultiByte(CP_UTF8, 0, Message, -1, 0, 0, 0, 0);
  182. if (Size > 0)
  183. {
  184. Buffer = new char[(Size * 2) + 1];
  185. if (WideCharToMultiByte(CP_UTF8, 0, Message, -1, Buffer, Size, 0, 0) > 0)
  186. {
  187. Buffer[Size] = '\0';
  188. }
  189. else
  190. {
  191. delete[] Buffer;
  192. Buffer = NULL;
  193. }
  194. }
  195. return Buffer;
  196. }
  197. //---------------------------------------------------------------------------
  198. void GetProductVersion(wchar_t* ProductVersion)
  199. {
  200. wchar_t Buffer[MAX_PATH];
  201. DWORD ModuleNameLen = GetModuleFileName(NULL, Buffer, MAX_PATH);
  202. if ((ModuleNameLen == 0) || (ModuleNameLen == MAX_PATH))
  203. {
  204. throw runtime_error("Error retrieving executable name.");
  205. }
  206. ProductVersion[0] = '\0';
  207. unsigned long Handle;
  208. unsigned int Size = GetFileVersionInfoSize(Buffer, &Handle);
  209. if (Size > 0)
  210. {
  211. void * VersionInfo = new char[Size];
  212. VS_FIXEDFILEINFO* FixedFileInfo;
  213. unsigned int Length;
  214. if (GetFileVersionInfo(Buffer, Handle, Size, VersionInfo))
  215. {
  216. if (VerQueryValue(VersionInfo, L"\\", (void**)&FixedFileInfo, &Length))
  217. {
  218. int ProductMajor = HIWORD(FixedFileInfo->dwProductVersionMS);
  219. int ProductMinor = LOWORD(FixedFileInfo->dwProductVersionMS);
  220. int ProductBuild = HIWORD(FixedFileInfo->dwProductVersionLS);
  221. if ((ProductMajor >= 1) && (ProductMajor <= 99) &&
  222. (ProductMinor >= 0) && (ProductMinor <= 99) &&
  223. (ProductBuild >= 0) && (ProductBuild <= 99))
  224. {
  225. wsprintf(ProductVersion, L"%d.%d.%d", ProductMajor, ProductMinor, ProductBuild);
  226. }
  227. }
  228. }
  229. delete[] VersionInfo;
  230. }
  231. if (ProductVersion[0] == L'\0')
  232. {
  233. throw runtime_error("Error retrieving product version.");
  234. }
  235. }
  236. //---------------------------------------------------------------------------
  237. void InitializeChild(const wchar_t* CommandLine, const wchar_t* InstanceName, HANDLE& Child)
  238. {
  239. int SkipParam = 0;
  240. wchar_t ChildPath[MAX_PATH] = L"";
  241. size_t CommandLineLen = wcslen(CommandLine);
  242. wchar_t* Buffer = new wchar_t[(CommandLineLen > MAX_PATH ? CommandLineLen : MAX_PATH) + 1];
  243. int Count = 0;
  244. const wchar_t* P = CommandLine;
  245. while (CutToken(P, Buffer))
  246. {
  247. if ((wcschr(L"-/", Buffer[0]) != NULL) &&
  248. (wcsncmpi(Buffer + 1, CONSOLE_CHILD_PARAM, wcslen(CONSOLE_CHILD_PARAM)) == 0) &&
  249. (Buffer[wcslen(CONSOLE_CHILD_PARAM) + 1] == L'='))
  250. {
  251. SkipParam = Count;
  252. wcscpy(ChildPath, Buffer + 1 + wcslen(CONSOLE_CHILD_PARAM) + 1);
  253. }
  254. ++Count;
  255. }
  256. if (wcslen(ChildPath) == 0)
  257. {
  258. DWORD ModuleNameLen = GetModuleFileName(NULL, Buffer, MAX_PATH);
  259. if ((ModuleNameLen == 0) || (ModuleNameLen == MAX_PATH))
  260. {
  261. throw runtime_error("Error retrieving executable name.");
  262. }
  263. const wchar_t* LastDelimiter = wcsrchr(Buffer, L'\\');
  264. const wchar_t* AppFileName;
  265. if (LastDelimiter != NULL)
  266. {
  267. wcsncpy(ChildPath, Buffer, LastDelimiter - Buffer + 1);
  268. ChildPath[LastDelimiter - Buffer + 1] = L'\0';
  269. AppFileName = LastDelimiter + 1;
  270. }
  271. else
  272. {
  273. ChildPath[0] = L'\0';
  274. AppFileName = Buffer;
  275. }
  276. const wchar_t* ExtensionStart = wcsrchr(AppFileName, L'.');
  277. if (ExtensionStart != NULL)
  278. {
  279. wchar_t* End = ChildPath + wcslen(ChildPath);
  280. wcsncpy(End, AppFileName, ExtensionStart - AppFileName);
  281. *(End + (ExtensionStart - AppFileName)) = L'\0';
  282. }
  283. else
  284. {
  285. wcscat(ChildPath, AppFileName);
  286. }
  287. wcscat(ChildPath, L".exe");
  288. }
  289. wchar_t ProductVersion[32];
  290. GetProductVersion(ProductVersion);
  291. wchar_t* Parameters = new wchar_t[(CommandLineLen * 2) + 100 + (Count * 3) + 1];
  292. wsprintf(Parameters, L"\"%s\" /console=%s /consoleinstance=%s ", ChildPath, ProductVersion, InstanceName);
  293. P = CommandLine;
  294. // skip executable path
  295. CutToken(P, Buffer);
  296. int i = 1;
  297. while (CutToken(P, Buffer))
  298. {
  299. if (i != SkipParam)
  300. {
  301. wcscat(Parameters, L"\"");
  302. wchar_t* P2 = Parameters + wcslen(Parameters);
  303. const wchar_t* P3 = Buffer;
  304. const wchar_t* BufferEnd = Buffer + wcslen(Buffer) + 1;
  305. while (P3 != BufferEnd)
  306. {
  307. *P2 = *P3;
  308. ++P2;
  309. if (*P3 == L'"')
  310. {
  311. *P2 = L'"';
  312. ++P2;
  313. }
  314. ++P3;
  315. }
  316. wcscat(Parameters, L"\" ");
  317. }
  318. ++i;
  319. }
  320. delete[] Buffer;
  321. STARTUPINFO StartupInfo = { sizeof(STARTUPINFO) };
  322. PROCESS_INFORMATION ProcessInfomation;
  323. BOOL Result =
  324. CreateProcess(ChildPath, Parameters, NULL, NULL, false, 0, NULL, NULL,
  325. &StartupInfo, &ProcessInfomation);
  326. delete[] Parameters;
  327. if (Result)
  328. {
  329. Child = ProcessInfomation.hProcess;
  330. }
  331. else
  332. {
  333. size_t Len = MAX_PATH + 1024;
  334. DWORD Error = GetLastError();
  335. wchar_t * Buffer = NULL;
  336. Len += FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER, 0, Error, 0, (LPTSTR)&Buffer, 0, NULL);
  337. wchar_t* Message = new wchar_t[Len];
  338. wsprintf(Message, L"Cannot start WinSCP application \"%s\".", ChildPath);
  339. if (Buffer != NULL)
  340. {
  341. wcscat(Message, L"\n");
  342. wcscat(Message, Buffer);
  343. LocalFree(Buffer);
  344. }
  345. char* MessageString = WideStringToString(Message);
  346. delete[] Message;
  347. std::string ErrorString(MessageString);
  348. delete[] MessageString;
  349. throw runtime_error(ErrorString);
  350. }
  351. }
  352. //---------------------------------------------------------------------------
  353. void FinalizeChild(HANDLE Child)
  354. {
  355. if (Child != NULL)
  356. {
  357. TerminateProcess(Child, 0);
  358. CloseHandle(Child);
  359. }
  360. }
  361. //---------------------------------------------------------------------------
  362. void FinalizeConsole(const wchar_t* /*InstanceName*/, HANDLE RequestEvent,
  363. HANDLE ResponseEvent, HANDLE CancelEvent, HANDLE FileMapping, HANDLE Job)
  364. {
  365. CloseHandle(RequestEvent);
  366. CloseHandle(ResponseEvent);
  367. CloseHandle(CancelEvent);
  368. CloseHandle(FileMapping);
  369. if (Job != NULL)
  370. {
  371. CloseHandle(Job);
  372. }
  373. }
  374. //---------------------------------------------------------------------------
  375. static wchar_t LastFromBeginning[sizeof(TConsoleCommStruct::TPrintEvent)] = L""; //???
  376. //---------------------------------------------------------------------------
  377. inline void Flush()
  378. {
  379. if ((OutputType == FILE_TYPE_DISK) || (OutputType == FILE_TYPE_PIPE))
  380. {
  381. fflush(stdout);
  382. }
  383. }
  384. //---------------------------------------------------------------------------
  385. void PrintException(const exception& e)
  386. {
  387. if (ConsoleOutput != NULL)
  388. {
  389. unsigned long Written;
  390. WriteFile(ConsoleOutput, e.what(), strlen(e.what()), &Written, NULL);
  391. }
  392. else
  393. {
  394. puts(e.what());
  395. }
  396. }
  397. //---------------------------------------------------------------------------
  398. void Print(const wchar_t* Message)
  399. {
  400. char* Buffer = WideStringToString(Message);
  401. if (Buffer != NULL)
  402. {
  403. char* Ptr = Buffer;
  404. while ((Ptr = strchr(Ptr, '\n')) != NULL)
  405. {
  406. memmove(Ptr + 1, Ptr, strlen(Ptr) + 1);
  407. *Ptr = '\r';
  408. Ptr += 2;
  409. }
  410. unsigned long Written;
  411. WriteFile(ConsoleOutput, Buffer, strlen(Buffer), &Written, NULL);
  412. delete[] Buffer;
  413. }
  414. }
  415. //---------------------------------------------------------------------------
  416. void Print(bool FromBeginning, const wchar_t* Message)
  417. {
  418. size_t Len = wcslen(Message);
  419. if ((OutputType == FILE_TYPE_DISK) || (OutputType == FILE_TYPE_PIPE))
  420. {
  421. if (FromBeginning && (Message[0] != L'\n'))
  422. {
  423. wcscpy(LastFromBeginning, Message);
  424. }
  425. else
  426. {
  427. if (LastFromBeginning[0] != L'\0')
  428. {
  429. Print(LastFromBeginning);
  430. LastFromBeginning[0] = L'\0';
  431. }
  432. if (FromBeginning && (Message[0] == L'\n'))
  433. {
  434. Print(L"\n");
  435. wcscpy(LastFromBeginning, Message + 1);
  436. }
  437. else
  438. {
  439. Print(Message);
  440. }
  441. Flush();
  442. }
  443. }
  444. else
  445. {
  446. unsigned long Written;
  447. if (FromBeginning)
  448. {
  449. WriteConsole(ConsoleOutput, L"\r", 1, &Written, NULL);
  450. }
  451. bool WriteResult =
  452. WriteConsole(ConsoleOutput, Message, Len, &Written, NULL);
  453. int Error = GetLastError();
  454. // The current console font does not support some characters in the message,
  455. // fall back to ansi-writting
  456. if (!WriteResult && (Error == ERROR_GEN_FAILURE))
  457. {
  458. int Size = WideCharToMultiByte(CP_ACP, 0, Message, -1, 0, 0, 0, 0);
  459. if (Size > 0)
  460. {
  461. char* Buffer = new char[Size];
  462. if (WideCharToMultiByte(CP_ACP, 0, Message, -1, Buffer, Size, 0, 0) > 0)
  463. {
  464. WriteConsoleA(ConsoleOutput, Buffer, strlen(Buffer), &Written, NULL);
  465. }
  466. delete[] Buffer;
  467. }
  468. }
  469. }
  470. }
  471. //---------------------------------------------------------------------------
  472. inline void ProcessPrintEvent(TConsoleCommStruct::TPrintEvent& Event)
  473. {
  474. Print(Event.FromBeginning, Event.Message);
  475. }
  476. //---------------------------------------------------------------------------
  477. void CancelInput()
  478. {
  479. SetEvent(CancelEvent);
  480. }
  481. //---------------------------------------------------------------------------
  482. void BreakInput()
  483. {
  484. FlushConsoleInputBuffer(ConsoleInput);
  485. INPUT_RECORD InputRecord;
  486. memset(&InputRecord, 0, sizeof(InputRecord));
  487. InputRecord.EventType = KEY_EVENT;
  488. InputRecord.Event.KeyEvent.bKeyDown = true;
  489. InputRecord.Event.KeyEvent.wRepeatCount = 1;
  490. InputRecord.Event.KeyEvent.uChar.UnicodeChar = L'\r';
  491. unsigned long Written;
  492. WriteConsoleInput(ConsoleInput, &InputRecord, 1, &Written);
  493. CancelInput();
  494. }
  495. //---------------------------------------------------------------------------
  496. DWORD WINAPI InputTimerThreadProc(void* Parameter)
  497. {
  498. unsigned int Timer = reinterpret_cast<unsigned int>(Parameter);
  499. unsigned int Remaining = Timer;
  500. const unsigned int Step = 1000;
  501. const int FirstKey = VK_LBUTTON; // 0x01
  502. const int LastKey = VK_OEM_CLEAR; // 0xFE
  503. // reset key state
  504. for (int Key = FirstKey; Key <= LastKey; Key++)
  505. {
  506. GetAsyncKeyState(Key);
  507. }
  508. while (Remaining > 0)
  509. {
  510. unsigned long WaitResult = WaitForSingleObject(InputTimerEvent, Step);
  511. if (WaitResult == WAIT_OBJECT_0)
  512. {
  513. // input entered
  514. Remaining = 0;
  515. }
  516. else if (WaitResult == WAIT_TIMEOUT)
  517. {
  518. bool Input = false;
  519. for (int Key = FirstKey; Key <= LastKey; Key++)
  520. {
  521. if ((GetAsyncKeyState(Key) & 0x01) != 0)
  522. {
  523. Input = true;
  524. // Finishing the loop nevertheless to reset state of all keys
  525. }
  526. }
  527. if (Input)
  528. {
  529. // If we have new input, reset timer
  530. Remaining = Timer;
  531. }
  532. else if (Remaining > Step)
  533. {
  534. Remaining -= Step;
  535. }
  536. else
  537. {
  538. BreakInput();
  539. Remaining = 0;
  540. }
  541. }
  542. else
  543. {
  544. // abort input on (unlikely) error
  545. BreakInput();
  546. Remaining = 0;
  547. }
  548. }
  549. return 0;
  550. }
  551. //---------------------------------------------------------------------------
  552. void ProcessInputEvent(TConsoleCommStruct::TInputEvent& Event)
  553. {
  554. if ((InputType == FILE_TYPE_DISK) || (InputType == FILE_TYPE_PIPE))
  555. {
  556. unsigned long Bytes = 0;
  557. unsigned long Read;
  558. bool Result;
  559. char Ch;
  560. char Buf[LENOF(Event.Str) * 3];
  561. while (((Result = (ReadFile(ConsoleInput, &Ch, 1, &Read, NULL) != 0)) != false) &&
  562. (Read > 0) && (Bytes < LENOF(Buf) - 1) && (Ch != '\n'))
  563. {
  564. if (Ch != '\r')
  565. {
  566. Buf[Bytes] = Ch;
  567. Bytes++;
  568. }
  569. }
  570. Buf[Bytes] = L'\0';
  571. MultiByteToWideChar(CP_UTF8, 0, Buf, -1, Event.Str, LENOF(Event.Str) - 1);
  572. Event.Str[LENOF(Event.Str) - 1] = L'\0';
  573. Print(false, Event.Str);
  574. Print(false, L"\n");
  575. Event.Result = ((Result && (Read > 0)) || (Bytes > 0));
  576. }
  577. else
  578. {
  579. unsigned long PrevMode, NewMode;
  580. GetConsoleMode(ConsoleInput, &PrevMode);
  581. NewMode = PrevMode | ENABLE_PROCESSED_INPUT | ENABLE_LINE_INPUT;
  582. if (Event.Echo)
  583. {
  584. NewMode |= ENABLE_ECHO_INPUT;
  585. }
  586. else
  587. {
  588. NewMode &= ~ENABLE_ECHO_INPUT;
  589. }
  590. SetConsoleMode(ConsoleInput, NewMode);
  591. HANDLE InputTimerThread = NULL;
  592. try
  593. {
  594. if (Event.Timer > 0)
  595. {
  596. unsigned long ThreadId;
  597. InputTimerEvent = CreateEvent(NULL, false, false, NULL);
  598. InputTimerThread = CreateThread(NULL, 0, InputTimerThreadProc,
  599. reinterpret_cast<void *>(Event.Timer), 0, &ThreadId);
  600. }
  601. unsigned long Read;
  602. Event.Result = ReadConsole(ConsoleInput, Event.Str, LENOF(Event.Str) - 1, &Read, NULL);
  603. Event.Str[Read] = L'\0';
  604. bool PendingCancel = (WaitForSingleObject(CancelEvent, 0) == WAIT_OBJECT_0);
  605. if (PendingCancel || !Event.Echo)
  606. {
  607. WriteFile(ConsoleOutput, "\n", 1, NULL, NULL);
  608. Flush();
  609. }
  610. if (PendingCancel || (Read == 0))
  611. {
  612. Event.Result = false;
  613. }
  614. }
  615. __finally
  616. {
  617. if (InputTimerThread != NULL)
  618. {
  619. SetEvent(InputTimerEvent);
  620. WaitForSingleObject(InputTimerThread, 100);
  621. CloseHandle(InputTimerEvent);
  622. InputTimerEvent = NULL;
  623. CloseHandle(InputTimerThread);
  624. }
  625. SetConsoleMode(ConsoleInput, PrevMode);
  626. }
  627. }
  628. }
  629. //---------------------------------------------------------------------------
  630. void ProcessChoiceEvent(TConsoleCommStruct::TChoiceEvent& Event)
  631. {
  632. // note that if output is redirected to file, input is still FILE_TYPE_CHAR
  633. if ((InputType == FILE_TYPE_DISK) || (InputType == FILE_TYPE_PIPE))
  634. {
  635. if (Event.Timeouting)
  636. {
  637. Sleep(Event.Timer);
  638. Event.Result = Event.Timeouted;
  639. }
  640. else
  641. {
  642. Event.Result = Event.Break;
  643. }
  644. }
  645. else
  646. {
  647. Event.Result = 0;
  648. unsigned long PrevMode, NewMode;
  649. GetConsoleMode(ConsoleInput, &PrevMode);
  650. NewMode = (PrevMode | ENABLE_PROCESSED_INPUT) & ~(ENABLE_LINE_INPUT | ENABLE_ECHO_INPUT);
  651. SetConsoleMode(ConsoleInput, NewMode);
  652. unsigned int ATimer = Event.Timer;
  653. try
  654. {
  655. do
  656. {
  657. unsigned long Read;
  658. INPUT_RECORD Record;
  659. if ((PeekConsoleInput(ConsoleInput, &Record, 1, &Read) != 0) &&
  660. (Read == 1))
  661. {
  662. if ((ReadConsoleInput(ConsoleInput, &Record, 1, &Read) != 0) &&
  663. (Read == 1))
  664. {
  665. bool PendingCancel = (WaitForSingleObject(CancelEvent, 0) == WAIT_OBJECT_0);
  666. if (PendingCancel)
  667. {
  668. Event.Result = Event.Break;
  669. }
  670. else if ((Record.EventType == KEY_EVENT) &&
  671. Record.Event.KeyEvent.bKeyDown)
  672. {
  673. // This happens when Shift key is pressed
  674. if (Record.Event.KeyEvent.uChar.UnicodeChar != 0)
  675. {
  676. wchar_t CStr[2];
  677. CStr[0] = Record.Event.KeyEvent.uChar.UnicodeChar;
  678. CStr[1] = L'\0';
  679. CharUpperBuff(CStr, 1);
  680. wchar_t C = CStr[0];
  681. if (C == 27)
  682. {
  683. Event.Result = Event.Cancel;
  684. }
  685. else if ((wcschr(Event.Options, C) != NULL) &&
  686. ((Record.Event.KeyEvent.dwControlKeyState &
  687. (LEFT_CTRL_PRESSED | RIGHT_CTRL_PRESSED | LEFT_ALT_PRESSED |
  688. RIGHT_ALT_PRESSED)) == 0))
  689. {
  690. Event.Result = wcschr(Event.Options, C) - Event.Options + 1;
  691. }
  692. }
  693. }
  694. }
  695. }
  696. if (Event.Result == 0)
  697. {
  698. unsigned int TimerSlice = 50;
  699. Sleep(TimerSlice);
  700. if (Event.Timer > 0)
  701. {
  702. if (ATimer > TimerSlice)
  703. {
  704. ATimer -= TimerSlice;
  705. }
  706. else
  707. {
  708. Event.Result = Event.Timeouted;
  709. }
  710. }
  711. }
  712. }
  713. while (Event.Result == 0);
  714. SetConsoleMode(ConsoleInput, PrevMode);
  715. }
  716. catch(...)
  717. {
  718. SetConsoleMode(ConsoleInput, PrevMode);
  719. throw;
  720. }
  721. }
  722. }
  723. //---------------------------------------------------------------------------
  724. inline void ProcessTitleEvent(TConsoleCommStruct::TTitleEvent& Event)
  725. {
  726. SetConsoleTitle(Event.Title);
  727. }
  728. //---------------------------------------------------------------------------
  729. inline void ProcessInitEvent(TConsoleCommStruct::TInitEvent& Event)
  730. {
  731. if (Event.UseStdErr)
  732. {
  733. ConsoleOutput = ConsoleErrorOutput;
  734. setmode(fileno(stdout), O_BINARY);
  735. }
  736. if (Event.BinaryInput)
  737. {
  738. setmode(fileno(stdin), O_BINARY);
  739. }
  740. OutputType = GetFileType(ConsoleOutput);
  741. // Until now we should not have printed anything.
  742. // Only in case of a fatal failure, we might have printed a pure ASCII error messages (and never got here).
  743. if ((OutputType == FILE_TYPE_DISK) || (OutputType == FILE_TYPE_PIPE) ||
  744. SupportsUtf8ConsoleOutput)
  745. {
  746. SetConsoleOutputCP(CP_UTF8);
  747. }
  748. else
  749. {
  750. SetConsoleOutputCP(CP_ACP);
  751. }
  752. Event.InputType = InputType;
  753. Event.OutputType = OutputType;
  754. // default anyway
  755. Event.WantsProgress = false;
  756. }
  757. //---------------------------------------------------------------------------
  758. inline void ProcessTransferOutEvent(TConsoleCommStruct::TTransferEvent& Event)
  759. {
  760. fwrite(Event.Data, 1, Event.Len, stdout);
  761. }
  762. //---------------------------------------------------------------------------
  763. inline void ProcessTransferInEvent(TConsoleCommStruct::TTransferEvent& Event)
  764. {
  765. size_t Read = fread(Event.Data, 1, Event.Len, stdin);
  766. if (Read != Event.Len)
  767. {
  768. if (ferror(stdin))
  769. {
  770. Event.Error = true;
  771. }
  772. else
  773. {
  774. Event.Len = Read;
  775. }
  776. }
  777. }
  778. //---------------------------------------------------------------------------
  779. void ProcessEvent(HANDLE ResponseEvent, HANDLE FileMapping)
  780. {
  781. TConsoleCommStruct* CommStruct = GetCommStruct(FileMapping);
  782. try
  783. {
  784. if (CommStruct->Version != TConsoleCommStruct::CurrentVersionConfirmed)
  785. {
  786. throw runtime_error("Incompatible console protocol version");
  787. }
  788. switch (CommStruct->Event)
  789. {
  790. case TConsoleCommStruct::PRINT:
  791. ProcessPrintEvent(CommStruct->PrintEvent);
  792. break;
  793. case TConsoleCommStruct::INPUT:
  794. ProcessInputEvent(CommStruct->InputEvent);
  795. break;
  796. case TConsoleCommStruct::CHOICE:
  797. ProcessChoiceEvent(CommStruct->ChoiceEvent);
  798. break;
  799. case TConsoleCommStruct::TITLE:
  800. ProcessTitleEvent(CommStruct->TitleEvent);
  801. break;
  802. case TConsoleCommStruct::INIT:
  803. ProcessInitEvent(CommStruct->InitEvent);
  804. break;
  805. case TConsoleCommStruct::TRANSFEROUT:
  806. ProcessTransferOutEvent(CommStruct->TransferEvent);
  807. break;
  808. case TConsoleCommStruct::TRANSFERIN:
  809. ProcessTransferInEvent(CommStruct->TransferEvent);
  810. break;
  811. default:
  812. throw runtime_error("Unknown event");
  813. }
  814. FreeCommStruct(CommStruct);
  815. SetEvent(ResponseEvent);
  816. }
  817. catch(...)
  818. {
  819. FreeCommStruct(CommStruct);
  820. throw;
  821. }
  822. }
  823. //---------------------------------------------------------------------------
  824. BOOL WINAPI HandlerRoutine(DWORD CtrlType)
  825. {
  826. if ((CtrlType == CTRL_C_EVENT) || (CtrlType == CTRL_BREAK_EVENT))
  827. {
  828. CancelInput();
  829. return true;
  830. }
  831. else
  832. {
  833. FinalizeChild(Child);
  834. return false;
  835. }
  836. }
  837. //---------------------------------------------------------------------------
  838. #pragma argsused
  839. int wmain(int /*argc*/, wchar_t* /*argv*/[])
  840. {
  841. unsigned long Result = RESULT_UNKNOWN_ERROR;
  842. try
  843. {
  844. randomize();
  845. OSVERSIONINFO VersionInfo;
  846. VersionInfo.dwOSVersionInfoSize = sizeof(VersionInfo);
  847. GetVersionEx(&VersionInfo);
  848. ConsoleInput = GetStdHandle(STD_INPUT_HANDLE);
  849. InputType = GetFileType(ConsoleInput);
  850. SetConsoleCtrlHandler(HandlerRoutine, true);
  851. unsigned int SavedConsoleCP = GetConsoleCP();
  852. unsigned int SavedConsoleOutputCP = GetConsoleOutputCP();
  853. ConsoleStandardOutput = GetStdHandle(STD_OUTPUT_HANDLE);
  854. ConsoleOutput = ConsoleStandardOutput;
  855. ConsoleErrorOutput = GetStdHandle(STD_ERROR_HANDLE);
  856. SupportsUtf8ConsoleOutput =
  857. ((VersionInfo.dwMajorVersion == 6) && (VersionInfo.dwMinorVersion >= 1)) ||
  858. (VersionInfo.dwMajorVersion > 6);
  859. if ((InputType == FILE_TYPE_DISK) || (InputType == FILE_TYPE_PIPE) ||
  860. SupportsUtf8ConsoleOutput)
  861. {
  862. SetConsoleCP(CP_UTF8);
  863. }
  864. else
  865. {
  866. SetConsoleCP(CP_ACP);
  867. }
  868. wchar_t InstanceName[MAX_PATH];
  869. HANDLE RequestEvent, ResponseEvent, FileMapping, Job;
  870. InitializeConsole(InstanceName, RequestEvent, ResponseEvent,
  871. CancelEvent, FileMapping, Job);
  872. wchar_t SavedTitle[512];
  873. GetConsoleTitle(SavedTitle, LENOF(SavedTitle));
  874. try
  875. {
  876. #ifndef CONSOLE_TEST
  877. InitializeChild(GetCommandLine(), InstanceName, Child);
  878. #endif
  879. try
  880. {
  881. bool Continue = true;
  882. do
  883. {
  884. HANDLE Handles[2];
  885. Handles[0] = RequestEvent;
  886. Handles[1] = Child;
  887. unsigned int HandleCount;
  888. #ifndef CONSOLE_TEST
  889. HandleCount = 2;
  890. #else
  891. HandleCount = 1;
  892. #endif
  893. unsigned long WaitResult =
  894. WaitForMultipleObjects(HandleCount, Handles, false, INFINITE);
  895. switch (WaitResult)
  896. {
  897. case WAIT_OBJECT_0:
  898. ProcessEvent(ResponseEvent, FileMapping);
  899. break;
  900. case WAIT_OBJECT_0 + 1:
  901. GetExitCodeProcess(Child, &Result);
  902. CloseHandle(Child);
  903. Child = NULL;
  904. Continue = false;
  905. break;
  906. default:
  907. throw runtime_error("Error waiting for communication from child process.");
  908. }
  909. }
  910. while (Continue);
  911. // flush pending progress message
  912. Print(false, L"");
  913. }
  914. catch(const exception& e)
  915. {
  916. PrintException(e);
  917. Result = RESULT_PROCESSING_ERROR;
  918. }
  919. #ifndef CONSOLE_TEST
  920. FinalizeChild(Child);
  921. #endif
  922. SetConsoleTitle(SavedTitle);
  923. SetConsoleCP(SavedConsoleCP);
  924. SetConsoleOutputCP(SavedConsoleOutputCP);
  925. }
  926. catch(const exception& e)
  927. {
  928. PrintException(e);
  929. Result = RESULT_INIT_ERROR;
  930. }
  931. FinalizeConsole(InstanceName, RequestEvent, ResponseEvent,
  932. CancelEvent, FileMapping, Job);
  933. }
  934. catch(const exception& e)
  935. {
  936. PrintException(e);
  937. Result = RESULT_GLOBAL_ERROR;
  938. }
  939. return Result;
  940. }
  941. //---------------------------------------------------------------------------