process_win32.c 36 KB

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