Main.cpp 29 KB

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