Main.cpp 28 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009
  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. OutputType = GetFileType(ConsoleOutput);
  737. // Until now we should not have printed anything.
  738. // Only in case of a fatal failure, we might have printed a pure ASCII error messages (and never got here).
  739. if ((OutputType == FILE_TYPE_DISK) || (OutputType == FILE_TYPE_PIPE) ||
  740. SupportsUtf8ConsoleOutput)
  741. {
  742. SetConsoleOutputCP(CP_UTF8);
  743. }
  744. else
  745. {
  746. SetConsoleOutputCP(CP_ACP);
  747. }
  748. Event.InputType = InputType;
  749. Event.OutputType = OutputType;
  750. // default anyway
  751. Event.WantsProgress = false;
  752. }
  753. //---------------------------------------------------------------------------
  754. inline void ProcessTransferOutEvent(TConsoleCommStruct::TTransferEvent& Event)
  755. {
  756. fwrite(Event.Data, 1, Event.Len, stdout);
  757. }
  758. //---------------------------------------------------------------------------
  759. void ProcessEvent(HANDLE ResponseEvent, HANDLE FileMapping)
  760. {
  761. TConsoleCommStruct* CommStruct = GetCommStruct(FileMapping);
  762. try
  763. {
  764. if (CommStruct->Version != TConsoleCommStruct::CurrentVersionConfirmed)
  765. {
  766. throw runtime_error("Incompatible console protocol version");
  767. }
  768. switch (CommStruct->Event)
  769. {
  770. case TConsoleCommStruct::PRINT:
  771. ProcessPrintEvent(CommStruct->PrintEvent);
  772. break;
  773. case TConsoleCommStruct::INPUT:
  774. ProcessInputEvent(CommStruct->InputEvent);
  775. break;
  776. case TConsoleCommStruct::CHOICE:
  777. ProcessChoiceEvent(CommStruct->ChoiceEvent);
  778. break;
  779. case TConsoleCommStruct::TITLE:
  780. ProcessTitleEvent(CommStruct->TitleEvent);
  781. break;
  782. case TConsoleCommStruct::INIT:
  783. ProcessInitEvent(CommStruct->InitEvent);
  784. break;
  785. case TConsoleCommStruct::TRANSFEROUT:
  786. ProcessTransferOutEvent(CommStruct->TransferEvent);
  787. break;
  788. default:
  789. throw runtime_error("Unknown event");
  790. }
  791. FreeCommStruct(CommStruct);
  792. SetEvent(ResponseEvent);
  793. }
  794. catch(...)
  795. {
  796. FreeCommStruct(CommStruct);
  797. throw;
  798. }
  799. }
  800. //---------------------------------------------------------------------------
  801. BOOL WINAPI HandlerRoutine(DWORD CtrlType)
  802. {
  803. if ((CtrlType == CTRL_C_EVENT) || (CtrlType == CTRL_BREAK_EVENT))
  804. {
  805. CancelInput();
  806. return true;
  807. }
  808. else
  809. {
  810. FinalizeChild(Child);
  811. return false;
  812. }
  813. }
  814. //---------------------------------------------------------------------------
  815. #pragma argsused
  816. int wmain(int /*argc*/, wchar_t* /*argv*/[])
  817. {
  818. unsigned long Result = RESULT_UNKNOWN_ERROR;
  819. try
  820. {
  821. randomize();
  822. OSVERSIONINFO VersionInfo;
  823. VersionInfo.dwOSVersionInfoSize = sizeof(VersionInfo);
  824. GetVersionEx(&VersionInfo);
  825. ConsoleInput = GetStdHandle(STD_INPUT_HANDLE);
  826. InputType = GetFileType(ConsoleInput);
  827. SetConsoleCtrlHandler(HandlerRoutine, true);
  828. unsigned int SavedConsoleCP = GetConsoleCP();
  829. unsigned int SavedConsoleOutputCP = GetConsoleOutputCP();
  830. ConsoleStandardOutput = GetStdHandle(STD_OUTPUT_HANDLE);
  831. ConsoleOutput = ConsoleStandardOutput;
  832. ConsoleErrorOutput = GetStdHandle(STD_ERROR_HANDLE);
  833. SupportsUtf8ConsoleOutput =
  834. ((VersionInfo.dwMajorVersion == 6) && (VersionInfo.dwMinorVersion >= 1)) ||
  835. (VersionInfo.dwMajorVersion > 6);
  836. if ((InputType == FILE_TYPE_DISK) || (InputType == FILE_TYPE_PIPE) ||
  837. SupportsUtf8ConsoleOutput)
  838. {
  839. SetConsoleCP(CP_UTF8);
  840. }
  841. else
  842. {
  843. SetConsoleCP(CP_ACP);
  844. }
  845. wchar_t InstanceName[MAX_PATH];
  846. HANDLE RequestEvent, ResponseEvent, FileMapping, Job;
  847. InitializeConsole(InstanceName, RequestEvent, ResponseEvent,
  848. CancelEvent, FileMapping, Job);
  849. wchar_t SavedTitle[512];
  850. GetConsoleTitle(SavedTitle, LENOF(SavedTitle));
  851. try
  852. {
  853. #ifndef CONSOLE_TEST
  854. InitializeChild(GetCommandLine(), InstanceName, Child);
  855. #endif
  856. try
  857. {
  858. bool Continue = true;
  859. do
  860. {
  861. HANDLE Handles[2];
  862. Handles[0] = RequestEvent;
  863. Handles[1] = Child;
  864. unsigned int HandleCount;
  865. #ifndef CONSOLE_TEST
  866. HandleCount = 2;
  867. #else
  868. HandleCount = 1;
  869. #endif
  870. unsigned long WaitResult =
  871. WaitForMultipleObjects(HandleCount, Handles, false, INFINITE);
  872. switch (WaitResult)
  873. {
  874. case WAIT_OBJECT_0:
  875. ProcessEvent(ResponseEvent, FileMapping);
  876. break;
  877. case WAIT_OBJECT_0 + 1:
  878. GetExitCodeProcess(Child, &Result);
  879. CloseHandle(Child);
  880. Child = NULL;
  881. Continue = false;
  882. break;
  883. default:
  884. throw runtime_error("Error waiting for communication from child process.");
  885. }
  886. }
  887. while (Continue);
  888. // flush pending progress message
  889. Print(false, L"");
  890. }
  891. catch(const exception& e)
  892. {
  893. PrintException(e);
  894. Result = RESULT_PROCESSING_ERROR;
  895. }
  896. #ifndef CONSOLE_TEST
  897. FinalizeChild(Child);
  898. #endif
  899. SetConsoleTitle(SavedTitle);
  900. SetConsoleCP(SavedConsoleCP);
  901. SetConsoleOutputCP(SavedConsoleOutputCP);
  902. }
  903. catch(const exception& e)
  904. {
  905. PrintException(e);
  906. Result = RESULT_INIT_ERROR;
  907. }
  908. FinalizeConsole(InstanceName, RequestEvent, ResponseEvent,
  909. CancelEvent, FileMapping, Job);
  910. }
  911. catch(const exception& e)
  912. {
  913. PrintException(e);
  914. Result = RESULT_GLOBAL_ERROR;
  915. }
  916. return Result;
  917. }
  918. //---------------------------------------------------------------------------