process_win32.c 33 KB

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