process_win32.c 35 KB

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