process_win32.c 32 KB

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