Main.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611
  1. //---------------------------------------------------------------------------
  2. #include <stdexcept>
  3. #include <stdio.h>
  4. #include <stdlib.h>
  5. #include <windows.h>
  6. #include "Console.h"
  7. #define MAX_ATTEMPTS 10
  8. //---------------------------------------------------------------------------
  9. using namespace std;
  10. HANDLE ConsoleInput = NULL;
  11. HANDLE Child = NULL;
  12. HANDLE CancelEvent = NULL;
  13. HANDLE InputTimerEvent = NULL;
  14. unsigned int OutputType = FILE_TYPE_UNKNOWN;
  15. unsigned int InputType = FILE_TYPE_UNKNOWN;
  16. enum { RESULT_GLOBAL_ERROR = 1, RESULT_INIT_ERROR = 2, RESULT_PROCESSING_ERROR = 3,
  17. RESULT_UNKNOWN_ERROR = 4 };
  18. const char * CONSOLE_CHILD_PARAM = "consolechild";
  19. //---------------------------------------------------------------------------
  20. inline TConsoleCommStruct* GetCommStruct(HANDLE FileMapping)
  21. {
  22. TConsoleCommStruct* Result;
  23. Result = static_cast<TConsoleCommStruct*>(MapViewOfFile(FileMapping,
  24. FILE_MAP_ALL_ACCESS, 0, 0, 0));
  25. if (Result == NULL)
  26. {
  27. throw logic_error("Cannot open mapping object.");
  28. }
  29. return Result;
  30. }
  31. //---------------------------------------------------------------------------
  32. inline void FreeCommStruct(TConsoleCommStruct* CommStruct)
  33. {
  34. UnmapViewOfFile(CommStruct);
  35. }
  36. //---------------------------------------------------------------------------
  37. void InitializeConsole(int& InstanceNumber, HANDLE& RequestEvent, HANDLE& ResponseEvent,
  38. HANDLE& CancelEvent, HANDLE& FileMapping)
  39. {
  40. int Attempts = 0;
  41. char Name[MAX_PATH];
  42. bool UniqEvent;
  43. do
  44. {
  45. if (Attempts > MAX_ATTEMPTS)
  46. {
  47. throw logic_error("Cannot find unique name for event object.");
  48. }
  49. #ifdef CONSOLE_TEST
  50. InstanceNumber = 1;
  51. #else
  52. InstanceNumber = random(1000);
  53. #endif
  54. sprintf(Name, "%s%d", CONSOLE_EVENT_REQUEST, InstanceNumber);
  55. HANDLE EventHandle = OpenEvent(EVENT_ALL_ACCESS, false, Name);
  56. UniqEvent = (EventHandle == NULL);
  57. if (!UniqEvent)
  58. {
  59. CloseHandle(EventHandle);
  60. }
  61. Attempts++;
  62. }
  63. while (!UniqEvent);
  64. RequestEvent = CreateEvent(NULL, false, false, Name);
  65. if (RequestEvent == NULL)
  66. {
  67. throw logic_error("Cannot create request event object.");
  68. }
  69. sprintf(Name, "%s%d", CONSOLE_EVENT_RESPONSE, InstanceNumber);
  70. ResponseEvent = CreateEvent(NULL, false, false, Name);
  71. if (ResponseEvent == NULL)
  72. {
  73. throw logic_error("Cannot create response event object.");
  74. }
  75. sprintf(Name, "%s%d", CONSOLE_EVENT_CANCEL, InstanceNumber);
  76. CancelEvent = CreateEvent(NULL, false, false, Name);
  77. if (CancelEvent == NULL)
  78. {
  79. throw logic_error("Cannot create cancel event object.");
  80. }
  81. sprintf(Name, "%s%d", CONSOLE_MAPPING, InstanceNumber);
  82. FileMapping = CreateFileMapping((HANDLE)0xFFFFFFFF, NULL, PAGE_READWRITE,
  83. 0, sizeof(TConsoleCommStruct), Name);
  84. if (FileMapping == NULL)
  85. {
  86. throw logic_error("Cannot create mapping object.");
  87. }
  88. TConsoleCommStruct* CommStruct = GetCommStruct(FileMapping);
  89. CommStruct->Size = sizeof(TConsoleCommStruct);
  90. CommStruct->Version = TConsoleCommStruct::CurrentVersion;
  91. CommStruct->Event = TConsoleCommStruct::NONE;
  92. FreeCommStruct(CommStruct);
  93. }
  94. //---------------------------------------------------------------------------
  95. void InitializeChild(int argc, char* argv[], int InstanceNumber, HANDLE& Child)
  96. {
  97. int SkipParam = 0;
  98. char ChildPath[MAX_PATH] = "";
  99. for (int i = 1; i < argc; i++)
  100. {
  101. if ((strchr("-/", argv[i][0]) != NULL) &&
  102. (strncmpi(argv[i] + 1, CONSOLE_CHILD_PARAM, strlen(CONSOLE_CHILD_PARAM)) == 0) &&
  103. (argv[i][strlen(CONSOLE_CHILD_PARAM) + 1] == '='))
  104. {
  105. SkipParam = i;
  106. strcpy(ChildPath, argv[i] + 1 + strlen(CONSOLE_CHILD_PARAM) + 1);
  107. break;
  108. }
  109. }
  110. if (strlen(ChildPath) == 0)
  111. {
  112. const char* AppPath = argv[0];
  113. const char* LastDelimiter = strrchr(AppPath, '\\');
  114. const char* AppFileName;
  115. if (LastDelimiter != NULL)
  116. {
  117. strncpy(ChildPath, AppPath, LastDelimiter - AppPath + 1);
  118. ChildPath[LastDelimiter - AppPath + 1] = '\0';
  119. AppFileName = LastDelimiter + 1;
  120. }
  121. else
  122. {
  123. ChildPath[0] = '\0';
  124. AppFileName = AppPath;
  125. }
  126. const char* ExtensionStart = strrchr(AppFileName, '.');
  127. if (ExtensionStart != NULL)
  128. {
  129. char* End = ChildPath + strlen(ChildPath);
  130. strncpy(End, AppFileName, ExtensionStart - AppFileName);
  131. *(End + (ExtensionStart - AppFileName)) = '\0';
  132. }
  133. else
  134. {
  135. strcat(ChildPath, AppFileName);
  136. }
  137. strcat(ChildPath, ".exe");
  138. }
  139. char Parameters[10240];
  140. sprintf(Parameters, "\"%s\" /console /consoleinstance=%d ", ChildPath, InstanceNumber);
  141. for (int i = 1; i < argc; i++)
  142. {
  143. if (i != SkipParam)
  144. {
  145. if (strlen(Parameters) + strlen(argv[i]) + 4 > sizeof(Parameters))
  146. {
  147. throw length_error("Too many parameters");
  148. }
  149. strcat(Parameters, "\"");
  150. strcat(Parameters, argv[i]);
  151. strcat(Parameters, "\" ");
  152. }
  153. }
  154. STARTUPINFO StartupInfo = { sizeof(STARTUPINFO) };
  155. PROCESS_INFORMATION ProcessInfomation;
  156. if (CreateProcess(ChildPath, Parameters, NULL, NULL, false, 0, NULL, NULL,
  157. &StartupInfo, &ProcessInfomation) != 0)
  158. {
  159. Child = ProcessInfomation.hProcess;
  160. }
  161. else
  162. {
  163. throw logic_error("Cannot start WinSCP application.");
  164. }
  165. }
  166. //---------------------------------------------------------------------------
  167. void FinalizeChild(HANDLE Child)
  168. {
  169. if (Child != NULL)
  170. {
  171. TerminateProcess(Child, 0);
  172. CloseHandle(Child);
  173. }
  174. }
  175. //---------------------------------------------------------------------------
  176. void FinalizeConsole(int /*InstanceNumber*/, HANDLE RequestEvent,
  177. HANDLE ResponseEvent, HANDLE CancelEvent, HANDLE FileMapping)
  178. {
  179. CloseHandle(RequestEvent);
  180. CloseHandle(ResponseEvent);
  181. CloseHandle(CancelEvent);
  182. CloseHandle(FileMapping);
  183. }
  184. //---------------------------------------------------------------------------
  185. static char LastFromBeginning[sizeof(TConsoleCommStruct::TPrintEvent)] = "";
  186. //---------------------------------------------------------------------------
  187. inline void Print(bool FromBeginning, const char * Message)
  188. {
  189. if ((OutputType == FILE_TYPE_DISK) || (OutputType == FILE_TYPE_PIPE))
  190. {
  191. if (FromBeginning && (Message[0] != '\n'))
  192. {
  193. strcpy(LastFromBeginning, Message);
  194. }
  195. else
  196. {
  197. if (LastFromBeginning[0] != '\0')
  198. {
  199. printf("%s", LastFromBeginning);
  200. LastFromBeginning[0] = '\0';
  201. }
  202. if (FromBeginning && (Message[0] == '\n'))
  203. {
  204. printf("\n");
  205. strcpy(LastFromBeginning, Message + 1);
  206. }
  207. else
  208. {
  209. printf("%s", Message);
  210. }
  211. }
  212. }
  213. else
  214. {
  215. if (FromBeginning)
  216. {
  217. printf("\r");
  218. }
  219. printf("%s", Message);
  220. }
  221. }
  222. //---------------------------------------------------------------------------
  223. inline void ProcessPrintEvent(TConsoleCommStruct::TPrintEvent& Event)
  224. {
  225. Print(Event.FromBeginning, Event.Message);
  226. }
  227. //---------------------------------------------------------------------------
  228. void BreakInput()
  229. {
  230. FlushConsoleInputBuffer(ConsoleInput);
  231. INPUT_RECORD InputRecord;
  232. memset(&InputRecord, 0, sizeof(InputRecord));
  233. InputRecord.EventType = KEY_EVENT;
  234. InputRecord.Event.KeyEvent.bKeyDown = true;
  235. InputRecord.Event.KeyEvent.wRepeatCount = 1;
  236. InputRecord.Event.KeyEvent.uChar.AsciiChar = '\r';
  237. unsigned long Written;
  238. WriteConsoleInput(ConsoleInput, &InputRecord, 1, &Written);
  239. SetEvent(CancelEvent);
  240. }
  241. //---------------------------------------------------------------------------
  242. DWORD WINAPI InputTimerThreadProc(void * Parameter)
  243. {
  244. unsigned int Timer = reinterpret_cast<unsigned int>(Parameter);
  245. if (WaitForSingleObject(InputTimerEvent, Timer) == WAIT_TIMEOUT)
  246. {
  247. BreakInput();
  248. }
  249. return 0;
  250. }
  251. //---------------------------------------------------------------------------
  252. void ProcessInputEvent(TConsoleCommStruct::TInputEvent& Event)
  253. {
  254. if ((InputType == FILE_TYPE_DISK) || (InputType == FILE_TYPE_PIPE))
  255. {
  256. unsigned long Len = 0;
  257. unsigned long Read;
  258. char Ch;
  259. bool Result;
  260. while (((Result = (ReadFile(ConsoleInput, &Ch, 1, &Read, NULL) != 0)) != false) &&
  261. (Read > 0) && (Len < sizeof(Event.Str) - 1) && (Ch != '\n'))
  262. {
  263. if (Ch != '\r')
  264. {
  265. Event.Str[Len] = Ch;
  266. Len++;
  267. }
  268. }
  269. Event.Str[Len] = '\0';
  270. Print(false, Event.Str);
  271. Print(false, "\n");
  272. Event.Result = ((Result && (Read > 0)) || (Len > 0));
  273. }
  274. else
  275. {
  276. unsigned long PrevMode, NewMode;
  277. GetConsoleMode(ConsoleInput, &PrevMode);
  278. NewMode = PrevMode | ENABLE_PROCESSED_INPUT | ENABLE_LINE_INPUT;
  279. if (Event.Echo)
  280. {
  281. NewMode |= ENABLE_ECHO_INPUT;
  282. }
  283. else
  284. {
  285. NewMode &= ~ENABLE_ECHO_INPUT;
  286. }
  287. SetConsoleMode(ConsoleInput, NewMode);
  288. HANDLE InputTimerThread = NULL;
  289. try
  290. {
  291. if (Event.Timer > 0)
  292. {
  293. unsigned long ThreadId;
  294. InputTimerEvent = CreateEvent(NULL, false, false, NULL);
  295. InputTimerThread = CreateThread(NULL, 0, InputTimerThreadProc,
  296. reinterpret_cast<void *>(Event.Timer), 0, &ThreadId);
  297. }
  298. unsigned long Read;
  299. Event.Result = ReadConsole(ConsoleInput, Event.Str, sizeof(Event.Str) - 1, &Read, NULL);
  300. Event.Str[Read] = '\0';
  301. bool PendingCancel = (WaitForSingleObject(CancelEvent, 0) == WAIT_OBJECT_0);
  302. if (PendingCancel || !Event.Echo)
  303. {
  304. printf("\n");
  305. }
  306. if (PendingCancel || (Read == 0))
  307. {
  308. Event.Result = false;
  309. }
  310. }
  311. __finally
  312. {
  313. if (InputTimerThread != NULL)
  314. {
  315. SetEvent(InputTimerEvent);
  316. WaitForSingleObject(InputTimerThread, 100);
  317. CloseHandle(InputTimerEvent);
  318. InputTimerEvent = NULL;
  319. CloseHandle(InputTimerThread);
  320. }
  321. SetConsoleMode(ConsoleInput, PrevMode);
  322. }
  323. }
  324. }
  325. //---------------------------------------------------------------------------
  326. void ProcessChoiceEvent(TConsoleCommStruct::TChoiceEvent& Event)
  327. {
  328. if ((InputType == FILE_TYPE_DISK) || (InputType == FILE_TYPE_PIPE))
  329. {
  330. Event.Result = Event.Cancel;
  331. }
  332. else
  333. {
  334. Event.Result = 0;
  335. unsigned long PrevMode, NewMode;
  336. GetConsoleMode(ConsoleInput, &PrevMode);
  337. NewMode = (PrevMode | ENABLE_PROCESSED_INPUT) & ~(ENABLE_LINE_INPUT | ENABLE_ECHO_INPUT);
  338. SetConsoleMode(ConsoleInput, NewMode);
  339. unsigned int ATimer = Event.Timer;
  340. try
  341. {
  342. do
  343. {
  344. unsigned long Read;
  345. INPUT_RECORD Record;
  346. if ((PeekConsoleInput(ConsoleInput, &Record, 1, &Read) != 0) &&
  347. (Read == 1))
  348. {
  349. if ((ReadConsoleInput(ConsoleInput, &Record, 1, &Read) != 0) &&
  350. (Read == 1))
  351. {
  352. bool PendingCancel = (WaitForSingleObject(CancelEvent, 0) == WAIT_OBJECT_0);
  353. if (PendingCancel)
  354. {
  355. Event.Result = Event.Break;
  356. }
  357. else if ((Record.EventType == KEY_EVENT) &&
  358. Record.Event.KeyEvent.bKeyDown)
  359. {
  360. char CStr[2];
  361. CStr[0] = Record.Event.KeyEvent.uChar.AsciiChar;
  362. CStr[1] = '\0';
  363. CharUpperBuff(CStr, 1);
  364. char C = CStr[0];
  365. if (C == 27)
  366. {
  367. Event.Result = Event.Cancel;
  368. }
  369. else if ((strchr(Event.Options, C) != NULL) &&
  370. ((Record.Event.KeyEvent.dwControlKeyState &
  371. (LEFT_CTRL_PRESSED | RIGHT_CTRL_PRESSED | LEFT_ALT_PRESSED |
  372. RIGHT_CTRL_PRESSED)) == 0))
  373. {
  374. Event.Result = strchr(Event.Options, C) - Event.Options + 1;
  375. }
  376. }
  377. }
  378. }
  379. if (Event.Result == 0)
  380. {
  381. unsigned int TimerSlice = 50;
  382. Sleep(TimerSlice);
  383. if (Event.Timer > 0)
  384. {
  385. if (ATimer > TimerSlice)
  386. {
  387. ATimer -= TimerSlice;
  388. }
  389. else
  390. {
  391. Event.Result = Event.Timeouted;
  392. }
  393. }
  394. }
  395. }
  396. while (Event.Result == 0);
  397. SetConsoleMode(ConsoleInput, PrevMode);
  398. }
  399. catch(...)
  400. {
  401. SetConsoleMode(ConsoleInput, PrevMode);
  402. throw;
  403. }
  404. }
  405. }
  406. //---------------------------------------------------------------------------
  407. inline void ProcessTitleEvent(TConsoleCommStruct::TTitleEvent& Event)
  408. {
  409. SetConsoleTitle(Event.Title);
  410. }
  411. //---------------------------------------------------------------------------
  412. inline void ProcessInitEvent(TConsoleCommStruct::TInitEvent& Event)
  413. {
  414. Event.InputType = InputType;
  415. Event.OutputType = OutputType;
  416. }
  417. //---------------------------------------------------------------------------
  418. void ProcessEvent(HANDLE ResponseEvent, HANDLE FileMapping)
  419. {
  420. TConsoleCommStruct* CommStruct = GetCommStruct(FileMapping);
  421. try
  422. {
  423. if (CommStruct->Version != TConsoleCommStruct::CurrentVersionConfirmed)
  424. {
  425. throw logic_error("Incompatible console protocol version");
  426. }
  427. switch (CommStruct->Event)
  428. {
  429. case TConsoleCommStruct::PRINT:
  430. ProcessPrintEvent(CommStruct->PrintEvent);
  431. break;
  432. case TConsoleCommStruct::INPUT:
  433. ProcessInputEvent(CommStruct->InputEvent);
  434. break;
  435. case TConsoleCommStruct::CHOICE:
  436. ProcessChoiceEvent(CommStruct->ChoiceEvent);
  437. break;
  438. case TConsoleCommStruct::TITLE:
  439. ProcessTitleEvent(CommStruct->TitleEvent);
  440. break;
  441. case TConsoleCommStruct::INIT:
  442. ProcessInitEvent(CommStruct->InitEvent);
  443. break;
  444. default:
  445. throw logic_error("Unknown event");
  446. }
  447. FreeCommStruct(CommStruct);
  448. SetEvent(ResponseEvent);
  449. }
  450. catch(...)
  451. {
  452. FreeCommStruct(CommStruct);
  453. throw;
  454. }
  455. }
  456. //---------------------------------------------------------------------------
  457. BOOL WINAPI HandlerRoutine(DWORD CtrlType)
  458. {
  459. if ((CtrlType == CTRL_C_EVENT) || (CtrlType == CTRL_BREAK_EVENT))
  460. {
  461. BreakInput();
  462. return true;
  463. }
  464. else
  465. {
  466. FinalizeChild(Child);
  467. return false;
  468. }
  469. }
  470. //---------------------------------------------------------------------------
  471. #pragma argsused
  472. int main(int argc, char* argv[])
  473. {
  474. unsigned long Result = RESULT_UNKNOWN_ERROR;
  475. try
  476. {
  477. randomize();
  478. ConsoleInput = GetStdHandle(STD_INPUT_HANDLE);
  479. InputType = GetFileType(ConsoleInput);
  480. SetConsoleCtrlHandler(HandlerRoutine, true);
  481. HANDLE ConsoleOutput = GetStdHandle(STD_OUTPUT_HANDLE);
  482. OutputType = GetFileType(ConsoleOutput);
  483. int InstanceNumber;
  484. HANDLE RequestEvent, ResponseEvent, FileMapping;
  485. InitializeConsole(InstanceNumber, RequestEvent, ResponseEvent,
  486. CancelEvent, FileMapping);
  487. char SavedTitle[512];
  488. GetConsoleTitle(SavedTitle, sizeof(SavedTitle));
  489. try
  490. {
  491. #ifndef CONSOLE_TEST
  492. InitializeChild(argc, argv, InstanceNumber, Child);
  493. #endif
  494. try
  495. {
  496. bool Continue = true;
  497. do
  498. {
  499. HANDLE Handles[2];
  500. Handles[0] = RequestEvent;
  501. Handles[1] = Child;
  502. unsigned int HandleCount;
  503. #ifndef CONSOLE_TEST
  504. HandleCount = 2;
  505. #else
  506. HandleCount = 1;
  507. #endif
  508. unsigned long WaitResult =
  509. WaitForMultipleObjects(HandleCount, Handles, false, INFINITE);
  510. switch (WaitResult)
  511. {
  512. case WAIT_OBJECT_0:
  513. ProcessEvent(ResponseEvent, FileMapping);
  514. break;
  515. case WAIT_OBJECT_0 + 1:
  516. GetExitCodeProcess(Child, &Result);
  517. CloseHandle(Child);
  518. Child = NULL;
  519. Continue = false;
  520. break;
  521. default:
  522. throw logic_error("Error waiting for communication from child process.");
  523. }
  524. }
  525. while (Continue);
  526. // flush pending progress message
  527. Print(false, "");
  528. }
  529. catch(const exception& e)
  530. {
  531. puts(e.what());
  532. Result = RESULT_PROCESSING_ERROR;
  533. }
  534. #ifndef CONSOLE_TEST
  535. FinalizeChild(Child);
  536. #endif
  537. SetConsoleTitle(SavedTitle);
  538. }
  539. catch(const exception& e)
  540. {
  541. puts(e.what());
  542. Result = RESULT_INIT_ERROR;
  543. }
  544. FinalizeConsole(InstanceNumber, RequestEvent, ResponseEvent,
  545. CancelEvent, FileMapping);
  546. }
  547. catch(const exception& e)
  548. {
  549. puts(e.what());
  550. Result = RESULT_GLOBAL_ERROR;
  551. }
  552. return Result;
  553. }
  554. //---------------------------------------------------------------------------