process_win32.c 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092
  1. /* Copyright (c) 2003, Roger Dingledine
  2. * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  3. * Copyright (c) 2007-2019, The Tor Project, Inc. */
  4. /* See LICENSE for licensing information */
  5. /**
  6. * \file process_win32.c
  7. * \brief Module for working with Windows processes.
  8. **/
  9. #define PROCESS_WIN32_PRIVATE
  10. #include "lib/intmath/cmp.h"
  11. #include "lib/buf/buffers.h"
  12. #include "lib/net/buffers_net.h"
  13. #include "lib/container/smartlist.h"
  14. #include "lib/log/log.h"
  15. #include "lib/log/util_bug.h"
  16. #include "lib/log/win32err.h"
  17. #include "lib/process/process.h"
  18. #include "lib/process/process_win32.h"
  19. #include "lib/process/env.h"
  20. #ifdef HAVE_SYS_TIME_H
  21. #include <sys/time.h>
  22. #endif
  23. #ifdef HAVE_STRING_H
  24. #include <string.h>
  25. #endif
  26. #ifdef _WIN32
  27. /** The size of our intermediate buffers. */
  28. #define BUFFER_SIZE (1024)
  29. /** Timer that ticks once a second and calls the process_win32_timer_callback()
  30. * function. */
  31. static periodic_timer_t *periodic_timer;
  32. /** Structure to represent the state around the pipe HANDLE.
  33. *
  34. * This structure is used to store state about a given HANDLE, including
  35. * whether we have reached end of file, its intermediate buffers, and how much
  36. * data that is available in the intermediate buffer. */
  37. struct process_win32_handle_t {
  38. /** Standard out pipe handle. */
  39. HANDLE pipe;
  40. /** True iff we have reached EOF from the pipe. */
  41. bool reached_eof;
  42. /** How much data is available in buffer. */
  43. size_t data_available;
  44. /** Intermediate buffer for ReadFileEx() and WriteFileEx(). */
  45. char buffer[BUFFER_SIZE];
  46. /** Overlapped structure for ReadFileEx() and WriteFileEx(). */
  47. OVERLAPPED overlapped;
  48. /** Are we waiting for another I/O operation to complete? */
  49. bool busy;
  50. };
  51. /** Structure to represent the Windows specific implementation details of this
  52. * Process backend.
  53. *
  54. * This structure is attached to <b>process_t</b> (see process.h) and is
  55. * reachable from <b>process_t</b> via the <b>process_get_win32_process()</b>
  56. * method. */
  57. struct process_win32_t {
  58. /** Standard in state. */
  59. process_win32_handle_t stdin_handle;
  60. /** Standard out state. */
  61. process_win32_handle_t stdout_handle;
  62. /** Standard error state. */
  63. process_win32_handle_t stderr_handle;
  64. /** Process Information. */
  65. PROCESS_INFORMATION process_information;
  66. };
  67. /** Create a new <b>process_win32_t</b>.
  68. *
  69. * This function constructs a new <b>process_win32_t</b> and initializes the
  70. * default values. */
  71. process_win32_t *
  72. process_win32_new(void)
  73. {
  74. process_win32_t *win32_process;
  75. win32_process = tor_malloc_zero(sizeof(process_win32_t));
  76. win32_process->stdin_handle.pipe = INVALID_HANDLE_VALUE;
  77. win32_process->stdout_handle.pipe = INVALID_HANDLE_VALUE;
  78. win32_process->stderr_handle.pipe = INVALID_HANDLE_VALUE;
  79. return win32_process;
  80. }
  81. /** Free a given <b>process_win32_t</b>.
  82. *
  83. * This function deinitializes and frees up the resources allocated for the
  84. * given <b>process_win32_t</b>. */
  85. void
  86. process_win32_free_(process_win32_t *win32_process)
  87. {
  88. if (! win32_process)
  89. return;
  90. /* Cleanup our handles. */
  91. process_win32_cleanup_handle(&win32_process->stdin_handle);
  92. process_win32_cleanup_handle(&win32_process->stdout_handle);
  93. process_win32_cleanup_handle(&win32_process->stderr_handle);
  94. tor_free(win32_process);
  95. }
  96. /** Initialize the Windows backend of the Process subsystem. */
  97. void
  98. process_win32_init(void)
  99. {
  100. /* We don't start the periodic timer here because it makes no sense to have
  101. * the timer running until we have some processes that benefits from the
  102. * timer timer ticks. */
  103. }
  104. /** Deinitialize the Windows backend of the Process subsystem. */
  105. void
  106. process_win32_deinit(void)
  107. {
  108. /* Stop our timer, but only if it's running. */
  109. if (process_win32_timer_running())
  110. process_win32_timer_stop();
  111. }
  112. /** Execute the given process. This function is responsible for setting up
  113. * named pipes for I/O between the child process and the Tor process. Returns
  114. * <b>PROCESS_STATUS_RUNNING</b> upon success. */
  115. process_status_t
  116. process_win32_exec(process_t *process)
  117. {
  118. tor_assert(process);
  119. process_win32_t *win32_process = process_get_win32_process(process);
  120. HANDLE stdout_pipe_read = NULL;
  121. HANDLE stdout_pipe_write = NULL;
  122. HANDLE stderr_pipe_read = NULL;
  123. HANDLE stderr_pipe_write = NULL;
  124. HANDLE stdin_pipe_read = NULL;
  125. HANDLE stdin_pipe_write = NULL;
  126. BOOL ret = FALSE;
  127. const char *filename = process_get_command(process);
  128. /* Not much we can do if we haven't been told what to start. */
  129. if (BUG(filename == NULL))
  130. return PROCESS_STATUS_ERROR;
  131. /* Setup our security attributes. */
  132. SECURITY_ATTRIBUTES security_attributes;
  133. security_attributes.nLength = sizeof(security_attributes);
  134. security_attributes.bInheritHandle = TRUE;
  135. /* FIXME: should we set explicit security attributes?
  136. * (See Ticket #2046, comment 5) */
  137. security_attributes.lpSecurityDescriptor = NULL;
  138. /* Create our standard out pipe. */
  139. if (! process_win32_create_pipe(&stdout_pipe_read,
  140. &stdout_pipe_write,
  141. &security_attributes,
  142. PROCESS_WIN32_PIPE_TYPE_READER)) {
  143. return PROCESS_STATUS_ERROR;
  144. }
  145. /* Create our standard error pipe. */
  146. if (! process_win32_create_pipe(&stderr_pipe_read,
  147. &stderr_pipe_write,
  148. &security_attributes,
  149. PROCESS_WIN32_PIPE_TYPE_READER)) {
  150. return PROCESS_STATUS_ERROR;
  151. }
  152. /* Create out standard in pipe. */
  153. if (! process_win32_create_pipe(&stdin_pipe_read,
  154. &stdin_pipe_write,
  155. &security_attributes,
  156. PROCESS_WIN32_PIPE_TYPE_WRITER)) {
  157. return PROCESS_STATUS_ERROR;
  158. }
  159. /* Configure startup info for our child process. */
  160. STARTUPINFOA startup_info;
  161. memset(&startup_info, 0, sizeof(startup_info));
  162. startup_info.cb = sizeof(startup_info);
  163. startup_info.hStdError = stderr_pipe_write;
  164. startup_info.hStdOutput = stdout_pipe_write;
  165. startup_info.hStdInput = stdin_pipe_read;
  166. startup_info.dwFlags |= STARTF_USESTDHANDLES;
  167. /* Create the env value for our new process. */
  168. process_environment_t *env = process_get_environment(process);
  169. /* Create the argv value for our new process. */
  170. char **argv = process_get_argv(process);
  171. /* Windows expects argv to be a whitespace delimited string, so join argv up
  172. */
  173. char *joined_argv = tor_join_win_cmdline((const char **)argv);
  174. /* Create the child process */
  175. ret = CreateProcessA(filename,
  176. joined_argv,
  177. NULL,
  178. NULL,
  179. TRUE,
  180. CREATE_NO_WINDOW,
  181. env->windows_environment_block[0] == '\0' ?
  182. NULL : env->windows_environment_block,
  183. NULL,
  184. &startup_info,
  185. &win32_process->process_information);
  186. tor_free(argv);
  187. tor_free(joined_argv);
  188. process_environment_free(env);
  189. if (! ret) {
  190. log_warn(LD_PROCESS, "CreateProcessA() failed: %s",
  191. format_win32_error(GetLastError()));
  192. /* Cleanup our handles. */
  193. CloseHandle(stdout_pipe_read);
  194. CloseHandle(stdout_pipe_write);
  195. CloseHandle(stderr_pipe_read);
  196. CloseHandle(stderr_pipe_write);
  197. CloseHandle(stdin_pipe_read);
  198. CloseHandle(stdin_pipe_write);
  199. return PROCESS_STATUS_ERROR;
  200. }
  201. /* TODO: Should we close hProcess and hThread in
  202. * process_handle->process_information? */
  203. win32_process->stdout_handle.pipe = stdout_pipe_read;
  204. win32_process->stderr_handle.pipe = stderr_pipe_read;
  205. win32_process->stdin_handle.pipe = stdin_pipe_write;
  206. /* Close our ends of the pipes that is now owned by the child process. */
  207. CloseHandle(stdout_pipe_write);
  208. CloseHandle(stderr_pipe_write);
  209. CloseHandle(stdin_pipe_read);
  210. /* Used by the callback functions from ReadFileEx() and WriteFileEx() such
  211. * that we can figure out which process_t that was responsible for the event.
  212. *
  213. * Warning, here be dragons:
  214. *
  215. * MSDN says that the hEvent member of the overlapped structure is unused
  216. * for ReadFileEx() and WriteFileEx, which allows us to store a pointer to
  217. * our process state there.
  218. */
  219. win32_process->stdout_handle.overlapped.hEvent = (HANDLE)process;
  220. win32_process->stderr_handle.overlapped.hEvent = (HANDLE)process;
  221. win32_process->stdin_handle.overlapped.hEvent = (HANDLE)process;
  222. /* Start our timer if it is not already running. */
  223. if (! process_win32_timer_running())
  224. process_win32_timer_start();
  225. /* We use Windows Extended I/O functions, so our completion callbacks are
  226. * called automatically for us when there is data to read. Because of this
  227. * we start the read of standard out and error right away. */
  228. process_notify_event_stdout(process);
  229. process_notify_event_stderr(process);
  230. return PROCESS_STATUS_RUNNING;
  231. }
  232. /** Terminate the given process. Returns true on success, otherwise false. */
  233. bool
  234. process_win32_terminate(process_t *process)
  235. {
  236. tor_assert(process);
  237. process_win32_t *win32_process = process_get_win32_process(process);
  238. /* Terminate our process. */
  239. BOOL ret;
  240. ret = TerminateProcess(win32_process->process_information.hProcess, 0);
  241. if (! ret) {
  242. log_warn(LD_PROCESS, "TerminateProcess() failed: %s",
  243. format_win32_error(GetLastError()));
  244. return false;
  245. }
  246. /* Cleanup our handles. */
  247. process_win32_cleanup_handle(&win32_process->stdin_handle);
  248. process_win32_cleanup_handle(&win32_process->stdout_handle);
  249. process_win32_cleanup_handle(&win32_process->stderr_handle);
  250. return true;
  251. }
  252. /** Returns the unique process identifier for the given <b>process</b>. */
  253. process_pid_t
  254. process_win32_get_pid(process_t *process)
  255. {
  256. tor_assert(process);
  257. process_win32_t *win32_process = process_get_win32_process(process);
  258. return (process_pid_t)win32_process->process_information.dwProcessId;
  259. }
  260. /** Schedule an async write of the data found in <b>buffer</b> for the given
  261. * process. This function runs an async write operation of the content of
  262. * buffer, if we are not already waiting for a pending I/O request. Returns the
  263. * number of bytes that Windows will hopefully write for us in the background.
  264. * */
  265. int
  266. process_win32_write(struct process_t *process, buf_t *buffer)
  267. {
  268. tor_assert(process);
  269. tor_assert(buffer);
  270. process_win32_t *win32_process = process_get_win32_process(process);
  271. BOOL ret = FALSE;
  272. DWORD error_code = 0;
  273. const size_t buffer_size = buf_datalen(buffer);
  274. /* Windows is still writing our buffer. */
  275. if (win32_process->stdin_handle.busy)
  276. return 0;
  277. /* Nothing for us to do right now. */
  278. if (buffer_size == 0)
  279. return 0;
  280. /* We have reached end of file already? */
  281. if (BUG(win32_process->stdin_handle.reached_eof))
  282. return 0;
  283. /* Figure out how much data we should read. */
  284. const size_t write_size = MIN(buffer_size,
  285. sizeof(win32_process->stdin_handle.buffer));
  286. /* Read data from the process_t buffer into our intermediate buffer. */
  287. buf_get_bytes(buffer, win32_process->stdin_handle.buffer, write_size);
  288. /* Because of the slightly weird API for WriteFileEx() we must set this to 0
  289. * before we call WriteFileEx() because WriteFileEx() does not reset the last
  290. * error itself when it's succesful. See comment below after the call to
  291. * GetLastError(). */
  292. SetLastError(0);
  293. /* Schedule our write. */
  294. ret = WriteFileEx(win32_process->stdin_handle.pipe,
  295. win32_process->stdin_handle.buffer,
  296. write_size,
  297. &win32_process->stdin_handle.overlapped,
  298. process_win32_stdin_write_done);
  299. if (! ret) {
  300. error_code = GetLastError();
  301. /* No need to log at warning level for these two. */
  302. if (error_code == ERROR_HANDLE_EOF || error_code == ERROR_BROKEN_PIPE) {
  303. log_debug(LD_PROCESS, "WriteFileEx() returned EOF from pipe: %s",
  304. format_win32_error(error_code));
  305. } else {
  306. log_warn(LD_PROCESS, "WriteFileEx() failed: %s",
  307. format_win32_error(error_code));
  308. }
  309. win32_process->stdin_handle.reached_eof = true;
  310. return 0;
  311. }
  312. /* Here be dragons: According to MSDN's documentation for WriteFileEx() we
  313. * should check GetLastError() after a call to WriteFileEx() even though the
  314. * `ret` return value was successful. If everything is good, GetLastError()
  315. * returns `ERROR_SUCCESS` and nothing happens.
  316. *
  317. * XXX(ahf): I have not managed to trigger this code while stress-testing
  318. * this code. */
  319. error_code = GetLastError();
  320. if (error_code != ERROR_SUCCESS) {
  321. /* LCOV_EXCL_START */
  322. log_warn(LD_PROCESS, "WriteFileEx() failed after returning success: %s",
  323. format_win32_error(error_code));
  324. win32_process->stdin_handle.reached_eof = true;
  325. return 0;
  326. /* LCOV_EXCL_STOP */
  327. }
  328. /* This cast should be safe since our buffer can maximum be BUFFER_SIZE
  329. * large. */
  330. return (int)write_size;
  331. }
  332. /** This function is called from the Process subsystem whenever the Windows
  333. * backend says it has data ready. This function also ensures that we are
  334. * starting a new background read from the standard output of the child process
  335. * and asks Windows to call process_win32_stdout_read_done() when that
  336. * operation is finished. Returns the number of bytes moved into <b>buffer</b>.
  337. * */
  338. int
  339. process_win32_read_stdout(struct process_t *process, buf_t *buffer)
  340. {
  341. tor_assert(process);
  342. tor_assert(buffer);
  343. process_win32_t *win32_process = process_get_win32_process(process);
  344. return process_win32_read_from_handle(&win32_process->stdout_handle,
  345. buffer,
  346. process_win32_stdout_read_done);
  347. }
  348. /** This function is called from the Process subsystem whenever the Windows
  349. * backend says it has data ready. This function also ensures that we are
  350. * starting a new background read from the standard error of the child process
  351. * and asks Windows to call process_win32_stderr_read_done() when that
  352. * operation is finished. Returns the number of bytes moved into <b>buffer</b>.
  353. * */
  354. int
  355. process_win32_read_stderr(struct process_t *process, buf_t *buffer)
  356. {
  357. tor_assert(process);
  358. tor_assert(buffer);
  359. process_win32_t *win32_process = process_get_win32_process(process);
  360. return process_win32_read_from_handle(&win32_process->stderr_handle,
  361. buffer,
  362. process_win32_stderr_read_done);
  363. }
  364. /** This function is responsible for moving the Tor process into what Microsoft
  365. * calls an "alertable" state. Once the process is in an alertable state the
  366. * Windows kernel will notify us when our background I/O requests have finished
  367. * and the callbacks will be executed. */
  368. void
  369. process_win32_trigger_completion_callbacks(void)
  370. {
  371. DWORD ret;
  372. /* The call to SleepEx(dwMilliseconds, dwAlertable) makes the process sleep
  373. * for dwMilliseconds and if dwAlertable is set to TRUE it will also cause
  374. * the process to enter alertable state, where the Windows kernel will notify
  375. * us about completed I/O requests from ReadFileEx() and WriteFileEX(), which
  376. * will cause our completion callbacks to be executed.
  377. *
  378. * This function returns 0 if the time interval expired or WAIT_IO_COMPLETION
  379. * if one or more I/O callbacks were executed. */
  380. ret = SleepEx(0, TRUE);
  381. /* Warn us if the function returned something we did not anticipate. */
  382. if (ret != 0 && ret != WAIT_IO_COMPLETION) {
  383. log_warn(LD_PROCESS, "SleepEx() returned %lu", ret);
  384. }
  385. }
  386. /** Start the periodic timer which is reponsible for checking whether processes
  387. * are still alive and to make sure that the Tor process is periodically being
  388. * moved into an alertable state. */
  389. void
  390. process_win32_timer_start(void)
  391. {
  392. /* Make sure we never start our timer if it's already running. */
  393. if (BUG(process_win32_timer_running()))
  394. return;
  395. /* Wake up once a second. */
  396. static const struct timeval interval = {1, 0};
  397. log_info(LD_PROCESS, "Starting Windows Process I/O timer");
  398. periodic_timer = periodic_timer_new(tor_libevent_get_base(),
  399. &interval,
  400. process_win32_timer_callback,
  401. NULL);
  402. }
  403. /** Stops the periodic timer. */
  404. void
  405. process_win32_timer_stop(void)
  406. {
  407. if (BUG(periodic_timer == NULL))
  408. return;
  409. log_info(LD_PROCESS, "Stopping Windows Process I/O timer");
  410. periodic_timer_free(periodic_timer);
  411. }
  412. /** Returns true iff the periodic timer is running. */
  413. bool
  414. process_win32_timer_running(void)
  415. {
  416. return periodic_timer != NULL;
  417. }
  418. /** This function is called whenever the periodic_timer ticks. The function is
  419. * responsible for moving the Tor process into an alertable state once a second
  420. * and checking for whether our child processes have terminated since the last
  421. * tick. */
  422. STATIC void
  423. process_win32_timer_callback(periodic_timer_t *timer, void *data)
  424. {
  425. tor_assert(timer == periodic_timer);
  426. tor_assert(data == NULL);
  427. /* Move the process into an alertable state. */
  428. process_win32_trigger_completion_callbacks();
  429. /* Check if our processes are still alive. */
  430. /* Since the call to process_win32_timer_test_process() might call
  431. * process_notify_event_exit() which again might call process_free() which
  432. * updates the list of processes returned by process_get_all_processes() it
  433. * is important here that we make sure to not touch the list of processes if
  434. * the call to process_win32_timer_test_process() returns true. */
  435. bool done;
  436. do {
  437. const smartlist_t *processes = process_get_all_processes();
  438. done = true;
  439. SMARTLIST_FOREACH_BEGIN(processes, process_t *, process) {
  440. /* If process_win32_timer_test_process() returns true, it means that
  441. * smartlist_remove() might have been called on the list returned by
  442. * process_get_all_processes(). We start the loop over again until we
  443. * have a succesful run over the entire list where the list was not
  444. * modified. */
  445. if (process_win32_timer_test_process(process)) {
  446. done = false;
  447. break;
  448. }
  449. } SMARTLIST_FOREACH_END(process);
  450. } while (! done);
  451. }
  452. /** Test whether a given process is still alive. Notify the Process subsystem
  453. * if our process have died. Returns true iff the given process have
  454. * terminated. */
  455. STATIC bool
  456. process_win32_timer_test_process(process_t *process)
  457. {
  458. tor_assert(process);
  459. /* No need to look at processes that don't claim they are running. */
  460. if (process_get_status(process) != PROCESS_STATUS_RUNNING)
  461. return false;
  462. process_win32_t *win32_process = process_get_win32_process(process);
  463. BOOL ret = FALSE;
  464. DWORD exit_code = 0;
  465. /* Sometimes the Windows kernel wont give us the EOF/Broken Pipe error
  466. * message until some time after the process have actually terminated. We
  467. * make sure that our ReadFileEx() calls for the process have *all* returned
  468. * and both standard out and error have been marked as EOF before we try to
  469. * see if the process terminated.
  470. *
  471. * This ensures that we *never* call the exit callback of the `process_t`,
  472. * which potentially ends up calling `process_free()` on our `process_t`,
  473. * before all data have been received from the process.
  474. *
  475. * We do NOT have a check here for whether standard in reached EOF since
  476. * standard in's WriteFileEx() function is only called on-demand when we have
  477. * something to write and is thus usually not awaiting to finish any
  478. * operations. If we WriteFileEx() to a file that has terminated we'll simply
  479. * get an error from ReadFileEx() or its completion routine and move on with
  480. * life. */
  481. if (! win32_process->stdout_handle.reached_eof)
  482. return false;
  483. if (! win32_process->stderr_handle.reached_eof)
  484. return false;
  485. /* We start by testing whether our process is still running. */
  486. ret = GetExitCodeProcess(win32_process->process_information.hProcess,
  487. &exit_code);
  488. if (! ret) {
  489. log_warn(LD_PROCESS, "GetExitCodeProcess() failed: %s",
  490. format_win32_error(GetLastError()));
  491. return false;
  492. }
  493. /* Notify our process_t that our process have terminated. Since our
  494. * exit_callback might decide to process_free() our process handle it is very
  495. * important that we do not touch the process_t after the call to
  496. * process_notify_event_exit(). */
  497. if (exit_code != STILL_ACTIVE) {
  498. process_notify_event_exit(process, exit_code);
  499. return true;
  500. }
  501. return false;
  502. }
  503. /** Create a new overlapped named pipe. This function creates a new connected,
  504. * named, pipe in <b>*read_pipe</b> and <b>*write_pipe</b> if the function is
  505. * succesful. Returns true on sucess, false on failure. */
  506. STATIC bool
  507. process_win32_create_pipe(HANDLE *read_pipe,
  508. HANDLE *write_pipe,
  509. SECURITY_ATTRIBUTES *attributes,
  510. process_win32_pipe_type_t pipe_type)
  511. {
  512. tor_assert(read_pipe);
  513. tor_assert(write_pipe);
  514. tor_assert(attributes);
  515. BOOL ret = FALSE;
  516. /* Buffer size. */
  517. const size_t size = 4096;
  518. /* Our additional read/write modes that depends on which pipe type we are
  519. * creating. */
  520. DWORD read_mode = 0;
  521. DWORD write_mode = 0;
  522. /* Generate the unique pipe name. */
  523. char pipe_name[MAX_PATH];
  524. static DWORD process_id = 0;
  525. static DWORD counter = 0;
  526. if (process_id == 0)
  527. process_id = GetCurrentProcessId();
  528. tor_snprintf(pipe_name, sizeof(pipe_name),
  529. "\\\\.\\Pipe\\Tor-Process-Pipe-%lu-%lu",
  530. process_id, counter++);
  531. /* Only one of our handles can be overlapped. */
  532. switch (pipe_type) {
  533. case PROCESS_WIN32_PIPE_TYPE_READER:
  534. read_mode = FILE_FLAG_OVERLAPPED;
  535. break;
  536. case PROCESS_WIN32_PIPE_TYPE_WRITER:
  537. write_mode = FILE_FLAG_OVERLAPPED;
  538. break;
  539. default:
  540. /* LCOV_EXCL_START */
  541. tor_assert_nonfatal_unreached_once();
  542. /* LCOV_EXCL_STOP */
  543. }
  544. /* Setup our read and write handles. */
  545. HANDLE read_handle;
  546. HANDLE write_handle;
  547. /* Create our named pipe. */
  548. read_handle = CreateNamedPipeA(pipe_name,
  549. (PIPE_ACCESS_INBOUND|read_mode),
  550. (PIPE_TYPE_BYTE|PIPE_WAIT),
  551. 1,
  552. size,
  553. size,
  554. 1000,
  555. attributes);
  556. if (read_handle == INVALID_HANDLE_VALUE) {
  557. log_warn(LD_PROCESS, "CreateNamedPipeA() failed: %s",
  558. format_win32_error(GetLastError()));
  559. return false;
  560. }
  561. /* Create our file in the pipe namespace. */
  562. write_handle = CreateFileA(pipe_name,
  563. GENERIC_WRITE,
  564. 0,
  565. attributes,
  566. OPEN_EXISTING,
  567. (FILE_ATTRIBUTE_NORMAL|write_mode),
  568. NULL);
  569. if (write_handle == INVALID_HANDLE_VALUE) {
  570. log_warn(LD_PROCESS, "CreateFileA() failed: %s",
  571. format_win32_error(GetLastError()));
  572. CloseHandle(read_handle);
  573. return false;
  574. }
  575. /* Set the inherit flag for our pipe. */
  576. switch (pipe_type) {
  577. case PROCESS_WIN32_PIPE_TYPE_READER:
  578. ret = SetHandleInformation(read_handle, HANDLE_FLAG_INHERIT, 0);
  579. break;
  580. case PROCESS_WIN32_PIPE_TYPE_WRITER:
  581. ret = SetHandleInformation(write_handle, HANDLE_FLAG_INHERIT, 0);
  582. break;
  583. default:
  584. /* LCOV_EXCL_START */
  585. tor_assert_nonfatal_unreached_once();
  586. /* LCOV_EXCL_STOP */
  587. }
  588. if (! ret) {
  589. log_warn(LD_PROCESS, "SetHandleInformation() failed: %s",
  590. format_win32_error(GetLastError()));
  591. CloseHandle(read_handle);
  592. CloseHandle(write_handle);
  593. return false;
  594. }
  595. /* Everything is good. */
  596. *read_pipe = read_handle;
  597. *write_pipe = write_handle;
  598. return true;
  599. }
  600. /** Cleanup a given <b>handle</b>. */
  601. STATIC void
  602. process_win32_cleanup_handle(process_win32_handle_t *handle)
  603. {
  604. tor_assert(handle);
  605. #if 0
  606. BOOL ret;
  607. DWORD error_code;
  608. /* Cancel any pending I/O requests: This means that instead of getting
  609. * ERROR_BROKEN_PIPE we get ERROR_OPERATION_ABORTED, but it doesn't seem
  610. * like this is needed. */
  611. ret = CancelIo(handle->pipe);
  612. if (! ret) {
  613. error_code = GetLastError();
  614. /* There was no pending I/O requests for our handle. */
  615. if (error_code != ERROR_NOT_FOUND) {
  616. log_warn(LD_PROCESS, "CancelIo() failed: %s",
  617. format_win32_error(error_code));
  618. }
  619. }
  620. #endif
  621. /* Close our handle. */
  622. if (handle->pipe != INVALID_HANDLE_VALUE) {
  623. CloseHandle(handle->pipe);
  624. handle->pipe = INVALID_HANDLE_VALUE;
  625. handle->reached_eof = true;
  626. }
  627. }
  628. /** This function is called when ReadFileEx() completes its background read
  629. * from the child process's standard output. We notify the Process subsystem if
  630. * there is data available for it to read from us. */
  631. STATIC VOID WINAPI
  632. process_win32_stdout_read_done(DWORD error_code,
  633. DWORD byte_count,
  634. LPOVERLAPPED overlapped)
  635. {
  636. tor_assert(overlapped);
  637. tor_assert(overlapped->hEvent);
  638. /* Extract our process_t from the hEvent member of OVERLAPPED. */
  639. process_t *process = (process_t *)overlapped->hEvent;
  640. process_win32_t *win32_process = process_get_win32_process(process);
  641. if (process_win32_handle_read_completion(&win32_process->stdout_handle,
  642. error_code,
  643. byte_count)) {
  644. /* Schedule our next read. */
  645. process_notify_event_stdout(process);
  646. }
  647. }
  648. /** This function is called when ReadFileEx() completes its background read
  649. * from the child process's standard error. We notify the Process subsystem if
  650. * there is data available for it to read from us. */
  651. STATIC VOID WINAPI
  652. process_win32_stderr_read_done(DWORD error_code,
  653. DWORD byte_count,
  654. LPOVERLAPPED overlapped)
  655. {
  656. tor_assert(overlapped);
  657. tor_assert(overlapped->hEvent);
  658. /* Extract our process_t from the hEvent member of OVERLAPPED. */
  659. process_t *process = (process_t *)overlapped->hEvent;
  660. process_win32_t *win32_process = process_get_win32_process(process);
  661. if (process_win32_handle_read_completion(&win32_process->stderr_handle,
  662. error_code,
  663. byte_count)) {
  664. /* Schedule our next read. */
  665. process_notify_event_stderr(process);
  666. }
  667. }
  668. /** This function is called when WriteFileEx() completes its background write
  669. * to the child process's standard input. We notify the Process subsystem that
  670. * it can write data to us again. */
  671. STATIC VOID WINAPI
  672. process_win32_stdin_write_done(DWORD error_code,
  673. DWORD byte_count,
  674. LPOVERLAPPED overlapped)
  675. {
  676. tor_assert(overlapped);
  677. tor_assert(overlapped->hEvent);
  678. (void)byte_count;
  679. process_t *process = (process_t *)overlapped->hEvent;
  680. process_win32_t *win32_process = process_get_win32_process(process);
  681. /* Mark our handle as not having any outstanding I/O requests. */
  682. win32_process->stdin_handle.busy = false;
  683. /* Check if we have been asked to write to the handle that have been marked
  684. * as having reached EOF. */
  685. if (BUG(win32_process->stdin_handle.reached_eof))
  686. return;
  687. if (error_code == 0) {
  688. /** Our data have been succesfully written. Clear our state and schedule
  689. * the next write. */
  690. win32_process->stdin_handle.data_available = 0;
  691. memset(win32_process->stdin_handle.buffer, 0,
  692. sizeof(win32_process->stdin_handle.buffer));
  693. /* Schedule the next write. */
  694. process_notify_event_stdin(process);
  695. } else if (error_code == ERROR_HANDLE_EOF ||
  696. error_code == ERROR_BROKEN_PIPE) {
  697. /* Our WriteFileEx() call was succesful, but we reached the end of our
  698. * file. We mark our handle as having reached EOF and returns. */
  699. tor_assert(byte_count == 0);
  700. win32_process->stdin_handle.reached_eof = true;
  701. } else {
  702. /* An error happened: We warn the user and mark our handle as having
  703. * reached EOF */
  704. log_warn(LD_PROCESS,
  705. "Error in I/O completion routine from WriteFileEx(): %s",
  706. format_win32_error(error_code));
  707. win32_process->stdin_handle.reached_eof = true;
  708. }
  709. }
  710. /** This function reads data from the given <b>handle</b>'s internal buffer and
  711. * moves it into the given <b>buffer</b>. Additionally, we start the next
  712. * ReadFileEx() background operation with the given <b>callback</b> as
  713. * completion callback. Returns the number of bytes written to the buffer. */
  714. STATIC int
  715. process_win32_read_from_handle(process_win32_handle_t *handle,
  716. buf_t *buffer,
  717. LPOVERLAPPED_COMPLETION_ROUTINE callback)
  718. {
  719. tor_assert(handle);
  720. tor_assert(buffer);
  721. tor_assert(callback);
  722. BOOL ret = FALSE;
  723. int bytes_available = 0;
  724. DWORD error_code = 0;
  725. /* We already have a request to read data that isn't complete yet. */
  726. if (BUG(handle->busy))
  727. return 0;
  728. /* Check if we have been asked to read from a handle that have already told
  729. * us that we have reached the end of the file. */
  730. if (BUG(handle->reached_eof))
  731. return 0;
  732. /* This cast should be safe since our buffer can be at maximum up to
  733. * BUFFER_SIZE in size. */
  734. bytes_available = (int)handle->data_available;
  735. if (handle->data_available > 0) {
  736. /* Read data from our intermediate buffer into the process_t buffer. */
  737. buf_add(buffer, handle->buffer, handle->data_available);
  738. /* Reset our read state. */
  739. handle->data_available = 0;
  740. memset(handle->buffer, 0, sizeof(handle->buffer));
  741. }
  742. /* Because of the slightly weird API for ReadFileEx() we must set this to 0
  743. * before we call ReadFileEx() because ReadFileEx() does not reset the last
  744. * error itself when it's succesful. See comment below after the call to
  745. * GetLastError(). */
  746. SetLastError(0);
  747. /* Ask the Windows kernel to read data from our pipe into our buffer and call
  748. * the callback function when it is done. */
  749. ret = ReadFileEx(handle->pipe,
  750. handle->buffer,
  751. sizeof(handle->buffer),
  752. &handle->overlapped,
  753. callback);
  754. if (! ret) {
  755. error_code = GetLastError();
  756. /* No need to log at warning level for these two. */
  757. if (error_code == ERROR_HANDLE_EOF || error_code == ERROR_BROKEN_PIPE) {
  758. log_debug(LD_PROCESS, "ReadFileEx() returned EOF from pipe: %s",
  759. format_win32_error(error_code));
  760. } else {
  761. log_warn(LD_PROCESS, "ReadFileEx() failed: %s",
  762. format_win32_error(error_code));
  763. }
  764. handle->reached_eof = true;
  765. return bytes_available;
  766. }
  767. /* Here be dragons: According to MSDN's documentation for ReadFileEx() we
  768. * should check GetLastError() after a call to ReadFileEx() even though the
  769. * `ret` return value was successful. If everything is good, GetLastError()
  770. * returns `ERROR_SUCCESS` and nothing happens.
  771. *
  772. * XXX(ahf): I have not managed to trigger this code while stress-testing
  773. * this code. */
  774. error_code = GetLastError();
  775. if (error_code != ERROR_SUCCESS) {
  776. /* LCOV_EXCL_START */
  777. log_warn(LD_PROCESS, "ReadFileEx() failed after returning success: %s",
  778. format_win32_error(error_code));
  779. handle->reached_eof = true;
  780. return bytes_available;
  781. /* LCOV_EXCL_STOP */
  782. }
  783. /* We mark our handle as having a pending I/O request. */
  784. handle->busy = true;
  785. return bytes_available;
  786. }
  787. /** This function checks the callback values from ReadFileEx() in
  788. * <b>error_code</b> and <b>byte_count</b> if we have read data. Returns true
  789. * iff our caller should request more data from ReadFileEx(). */
  790. STATIC bool
  791. process_win32_handle_read_completion(process_win32_handle_t *handle,
  792. DWORD error_code,
  793. DWORD byte_count)
  794. {
  795. tor_assert(handle);
  796. /* Mark our handle as not having any outstanding I/O requests. */
  797. handle->busy = false;
  798. if (error_code == 0) {
  799. /* Our ReadFileEx() call was succesful and there is data for us. */
  800. /* This cast should be safe since byte_count should never be larger than
  801. * BUFFER_SIZE. */
  802. tor_assert(byte_count <= BUFFER_SIZE);
  803. handle->data_available = (size_t)byte_count;
  804. /* Tell our caller to schedule the next read. */
  805. return true;
  806. } else if (error_code == ERROR_HANDLE_EOF ||
  807. error_code == ERROR_BROKEN_PIPE) {
  808. /* Our ReadFileEx() finished, but we reached the end of our file. We mark
  809. * our handle as having reached EOF and returns. */
  810. tor_assert(byte_count == 0);
  811. handle->reached_eof = true;
  812. } else {
  813. /* An error happened: We warn the user and mark our handle as having
  814. * reached EOF */
  815. log_warn(LD_PROCESS,
  816. "Error in I/O completion routine from ReadFileEx(): %s",
  817. format_win32_error(error_code));
  818. handle->reached_eof = true;
  819. }
  820. /* Our caller should NOT schedule the next read. */
  821. return false;
  822. }
  823. /** Format a single argument for being put on a Windows command line.
  824. * Returns a newly allocated string */
  825. STATIC char *
  826. format_win_cmdline_argument(const char *arg)
  827. {
  828. char *formatted_arg;
  829. char need_quotes;
  830. const char *c;
  831. int i;
  832. int bs_counter = 0;
  833. /* Backslash we can point to when one is inserted into the string */
  834. const char backslash = '\\';
  835. /* Smartlist of *char */
  836. smartlist_t *arg_chars;
  837. arg_chars = smartlist_new();
  838. /* Quote string if it contains whitespace or is empty */
  839. need_quotes = (strchr(arg, ' ') || strchr(arg, '\t') || '\0' == arg[0]);
  840. /* Build up smartlist of *chars */
  841. for (c=arg; *c != '\0'; c++) {
  842. if ('"' == *c) {
  843. /* Double up backslashes preceding a quote */
  844. for (i=0; i<(bs_counter*2); i++)
  845. smartlist_add(arg_chars, (void*)&backslash);
  846. bs_counter = 0;
  847. /* Escape the quote */
  848. smartlist_add(arg_chars, (void*)&backslash);
  849. smartlist_add(arg_chars, (void*)c);
  850. } else if ('\\' == *c) {
  851. /* Count backslashes until we know whether to double up */
  852. bs_counter++;
  853. } else {
  854. /* Don't double up slashes preceding a non-quote */
  855. for (i=0; i<bs_counter; i++)
  856. smartlist_add(arg_chars, (void*)&backslash);
  857. bs_counter = 0;
  858. smartlist_add(arg_chars, (void*)c);
  859. }
  860. }
  861. /* Don't double up trailing backslashes */
  862. for (i=0; i<bs_counter; i++)
  863. smartlist_add(arg_chars, (void*)&backslash);
  864. /* Allocate space for argument, quotes (if needed), and terminator */
  865. const size_t formatted_arg_len = smartlist_len(arg_chars) +
  866. (need_quotes ? 2 : 0) + 1;
  867. formatted_arg = tor_malloc_zero(formatted_arg_len);
  868. /* Add leading quote */
  869. i=0;
  870. if (need_quotes)
  871. formatted_arg[i++] = '"';
  872. /* Add characters */
  873. SMARTLIST_FOREACH(arg_chars, char*, ch,
  874. {
  875. formatted_arg[i++] = *ch;
  876. });
  877. /* Add trailing quote */
  878. if (need_quotes)
  879. formatted_arg[i++] = '"';
  880. formatted_arg[i] = '\0';
  881. smartlist_free(arg_chars);
  882. return formatted_arg;
  883. }
  884. /** Format a command line for use on Windows, which takes the command as a
  885. * string rather than string array. Follows the rules from "Parsing C++
  886. * Command-Line Arguments" in MSDN. Algorithm based on list2cmdline in the
  887. * Python subprocess module. Returns a newly allocated string */
  888. STATIC char *
  889. tor_join_win_cmdline(const char *argv[])
  890. {
  891. smartlist_t *argv_list;
  892. char *joined_argv;
  893. int i;
  894. /* Format each argument and put the result in a smartlist */
  895. argv_list = smartlist_new();
  896. for (i=0; argv[i] != NULL; i++) {
  897. smartlist_add(argv_list, (void *)format_win_cmdline_argument(argv[i]));
  898. }
  899. /* Join the arguments with whitespace */
  900. joined_argv = smartlist_join_strings(argv_list, " ", 0, NULL);
  901. /* Free the newly allocated arguments, and the smartlist */
  902. SMARTLIST_FOREACH(argv_list, char *, arg,
  903. {
  904. tor_free(arg);
  905. });
  906. smartlist_free(argv_list);
  907. return joined_argv;
  908. }
  909. #endif /* ! defined(_WIN32). */