process_win32.c 35 KB

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