process_unix.c 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704
  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_unix.c
  7. * \brief Module for working with Unix processes.
  8. **/
  9. #define PROCESS_UNIX_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/evloop/compat_libevent.h"
  15. #include "lib/log/log.h"
  16. #include "lib/log/util_bug.h"
  17. #include "lib/process/process.h"
  18. #include "lib/process/process_unix.h"
  19. #include "lib/process/waitpid.h"
  20. #include "lib/process/env.h"
  21. #include <stdio.h>
  22. #ifdef HAVE_STRING_H
  23. #include <string.h>
  24. #endif
  25. #ifdef HAVE_ERRNO_H
  26. #include <errno.h>
  27. #endif
  28. #ifdef HAVE_UNISTD_H
  29. #include <unistd.h>
  30. #endif
  31. #ifdef HAVE_FCNTL_H
  32. #include <fcntl.h>
  33. #endif
  34. #if defined(HAVE_SYS_PRCTL_H) && defined(__linux__)
  35. #include <sys/prctl.h>
  36. #endif
  37. #if HAVE_SIGNAL_H
  38. #include <signal.h>
  39. #endif
  40. #ifndef _WIN32
  41. /** Maximum number of file descriptors, if we cannot get it via sysconf() */
  42. #define DEFAULT_MAX_FD 256
  43. /** Internal state for Unix handles. */
  44. struct process_unix_handle_t {
  45. /** Unix File Descriptor. */
  46. int fd;
  47. /** Have we reached end of file? */
  48. bool reached_eof;
  49. /** Event structure for libevent. */
  50. struct event *event;
  51. /** Are we writing? */
  52. bool is_writing;
  53. };
  54. /** Internal state for our Unix process. */
  55. struct process_unix_t {
  56. /** Standard in handle. */
  57. process_unix_handle_t stdin_handle;
  58. /** Standard out handle. */
  59. process_unix_handle_t stdout_handle;
  60. /** Standard error handle. */
  61. process_unix_handle_t stderr_handle;
  62. /** The process identifier of our process. */
  63. pid_t pid;
  64. /** Waitpid Callback structure. */
  65. waitpid_callback_t *waitpid;
  66. };
  67. /** Returns a newly allocated <b>process_unix_t</b>. */
  68. process_unix_t *
  69. process_unix_new(void)
  70. {
  71. process_unix_t *unix_process;
  72. unix_process = tor_malloc_zero(sizeof(process_unix_t));
  73. unix_process->stdin_handle.fd = -1;
  74. unix_process->stderr_handle.fd = -1;
  75. unix_process->stdout_handle.fd = -1;
  76. return unix_process;
  77. }
  78. /** Deallocates the given <b>unix_process</b>. */
  79. void
  80. process_unix_free_(process_unix_t *unix_process)
  81. {
  82. if (! unix_process)
  83. return;
  84. /* Clean up our waitpid callback. */
  85. clear_waitpid_callback(unix_process->waitpid);
  86. /* FIXME(ahf): Refactor waitpid code? */
  87. unix_process->waitpid = NULL;
  88. /* Cleanup our events. */
  89. if (! unix_process->stdout_handle.reached_eof)
  90. process_unix_stop_reading(&unix_process->stdout_handle);
  91. if (! unix_process->stderr_handle.reached_eof)
  92. process_unix_stop_reading(&unix_process->stderr_handle);
  93. if (unix_process->stdin_handle.is_writing)
  94. process_unix_stop_writing(&unix_process->stdin_handle);
  95. /* Close all our file descriptors. */
  96. process_unix_close_file_descriptors(unix_process);
  97. tor_event_free(unix_process->stdout_handle.event);
  98. tor_event_free(unix_process->stderr_handle.event);
  99. tor_event_free(unix_process->stdin_handle.event);
  100. tor_free(unix_process);
  101. }
  102. /** Executes the given process as a child process of Tor. This function is
  103. * responsible for setting up the child process and run it. This includes
  104. * setting up pipes for interprocess communication, initialize the waitpid
  105. * callbacks, and finally run fork() followed by execve(). Returns
  106. * <b>PROCESS_STATUS_RUNNING</b> upon success. */
  107. process_status_t
  108. process_unix_exec(process_t *process)
  109. {
  110. static int max_fd = -1;
  111. process_unix_t *unix_process;
  112. pid_t pid;
  113. int stdin_pipe[2];
  114. int stdout_pipe[2];
  115. int stderr_pipe[2];
  116. int retval, fd;
  117. unix_process = process_get_unix_process(process);
  118. /* Create standard in pipe. */
  119. retval = pipe(stdin_pipe);
  120. if (-1 == retval) {
  121. log_warn(LD_PROCESS,
  122. "Unable to create pipe for stdin "
  123. "communication with process: %s",
  124. strerror(errno));
  125. return PROCESS_STATUS_ERROR;
  126. }
  127. /* Create standard out pipe. */
  128. retval = pipe(stdout_pipe);
  129. if (-1 == retval) {
  130. log_warn(LD_PROCESS,
  131. "Unable to create pipe for stdout "
  132. "communication with process: %s",
  133. strerror(errno));
  134. /** Cleanup standard in pipe. */
  135. close(stdin_pipe[0]);
  136. close(stdin_pipe[1]);
  137. return PROCESS_STATUS_ERROR;
  138. }
  139. /* Create standard error pipe. */
  140. retval = pipe(stderr_pipe);
  141. if (-1 == retval) {
  142. log_warn(LD_PROCESS,
  143. "Unable to create pipe for stderr "
  144. "communication with process: %s",
  145. strerror(errno));
  146. /** Cleanup standard in pipe. */
  147. close(stdin_pipe[0]);
  148. close(stdin_pipe[1]);
  149. /** Cleanup standard out pipe. */
  150. close(stdin_pipe[0]);
  151. close(stdin_pipe[1]);
  152. return PROCESS_STATUS_ERROR;
  153. }
  154. #ifdef _SC_OPEN_MAX
  155. if (-1 == max_fd) {
  156. max_fd = (int)sysconf(_SC_OPEN_MAX);
  157. if (max_fd == -1) {
  158. max_fd = DEFAULT_MAX_FD;
  159. log_warn(LD_PROCESS,
  160. "Cannot find maximum file descriptor, assuming: %d", max_fd);
  161. }
  162. }
  163. #else /* !(defined(_SC_OPEN_MAX)) */
  164. max_fd = DEFAULT_MAX_FD;
  165. #endif /* defined(_SC_OPEN_MAX) */
  166. pid = fork();
  167. if (0 == pid) {
  168. /* This code is running in the child process context. */
  169. #if defined(HAVE_SYS_PRCTL_H) && defined(__linux__)
  170. /* Attempt to have the kernel issue a SIGTERM if the parent
  171. * goes away. Certain attributes of the binary being execve()ed
  172. * will clear this during the execve() call, but it's better
  173. * than nothing.
  174. */
  175. prctl(PR_SET_PDEATHSIG, SIGTERM);
  176. #endif /* defined(HAVE_SYS_PRCTL_H) && defined(__linux__) */
  177. /* Link process stdout to the write end of the pipe. */
  178. retval = dup2(stdout_pipe[1], STDOUT_FILENO);
  179. if (-1 == retval)
  180. goto error;
  181. /* Link process stderr to the write end of the pipe. */
  182. retval = dup2(stderr_pipe[1], STDERR_FILENO);
  183. if (-1 == retval)
  184. goto error;
  185. /* Link process stdin to the read end of the pipe */
  186. retval = dup2(stdin_pipe[0], STDIN_FILENO);
  187. if (-1 == retval)
  188. goto error;
  189. /* Close our pipes now after they have been dup2()'ed. */
  190. close(stderr_pipe[0]);
  191. close(stderr_pipe[1]);
  192. close(stdout_pipe[0]);
  193. close(stdout_pipe[1]);
  194. close(stdin_pipe[0]);
  195. close(stdin_pipe[1]);
  196. /* Close all other fds, including the read end of the pipe. XXX: We should
  197. * now be doing enough FD_CLOEXEC setting to make this needless.
  198. */
  199. for (fd = STDERR_FILENO + 1; fd < max_fd; fd++)
  200. close(fd);
  201. /* Create the argv value for our new process. */
  202. char **argv = process_get_argv(process);
  203. /* Create the env value for our new process. */
  204. process_environment_t *env = process_get_environment(process);
  205. /* Call the requested program. */
  206. retval = execve(argv[0], argv, env->unixoid_environment_block);
  207. /* If we made it here it is because execve failed :-( */
  208. if (-1 == retval)
  209. fprintf(stderr, "Call to execve() failed: %s", strerror(errno));
  210. tor_free(argv);
  211. process_environment_free(env);
  212. tor_assert_unreached();
  213. error:
  214. /* LCOV_EXCL_START */
  215. fprintf(stderr, "Error from child process: %s", strerror(errno));
  216. _exit(1);
  217. /* LCOV_EXCL_STOP */
  218. }
  219. /* We are in the parent process. */
  220. if (-1 == pid) {
  221. log_warn(LD_PROCESS,
  222. "Failed to create child process: %s", strerror(errno));
  223. /** Cleanup standard in pipe. */
  224. close(stdin_pipe[0]);
  225. close(stdin_pipe[1]);
  226. /** Cleanup standard out pipe. */
  227. close(stdin_pipe[0]);
  228. close(stdin_pipe[1]);
  229. /** Cleanup standard error pipe. */
  230. close(stderr_pipe[0]);
  231. close(stderr_pipe[1]);
  232. return PROCESS_STATUS_ERROR;
  233. }
  234. /* Register our PID. */
  235. unix_process->pid = pid;
  236. /* Setup waitpid callbacks. */
  237. unix_process->waitpid = set_waitpid_callback(pid,
  238. process_unix_waitpid_callback,
  239. process);
  240. /* Handle standard out. */
  241. unix_process->stdout_handle.fd = stdout_pipe[0];
  242. retval = close(stdout_pipe[1]);
  243. if (-1 == retval) {
  244. log_warn(LD_PROCESS, "Failed to close write end of standard out pipe: %s",
  245. strerror(errno));
  246. }
  247. /* Handle standard error. */
  248. unix_process->stderr_handle.fd = stderr_pipe[0];
  249. retval = close(stderr_pipe[1]);
  250. if (-1 == retval) {
  251. log_warn(LD_PROCESS,
  252. "Failed to close write end of standard error pipe: %s",
  253. strerror(errno));
  254. }
  255. /* Handle standard in. */
  256. unix_process->stdin_handle.fd = stdin_pipe[1];
  257. retval = close(stdin_pipe[0]);
  258. if (-1 == retval) {
  259. log_warn(LD_PROCESS, "Failed to close read end of standard in pipe: %s",
  260. strerror(errno));
  261. }
  262. /* Setup our handles. */
  263. process_unix_setup_handle(process,
  264. &unix_process->stdout_handle,
  265. EV_READ|EV_PERSIST,
  266. stdout_read_callback);
  267. process_unix_setup_handle(process,
  268. &unix_process->stderr_handle,
  269. EV_READ|EV_PERSIST,
  270. stderr_read_callback);
  271. process_unix_setup_handle(process,
  272. &unix_process->stdin_handle,
  273. EV_WRITE|EV_PERSIST,
  274. stdin_write_callback);
  275. /* Start reading from standard out and standard error. */
  276. process_unix_start_reading(&unix_process->stdout_handle);
  277. process_unix_start_reading(&unix_process->stderr_handle);
  278. return PROCESS_STATUS_RUNNING;
  279. }
  280. /** Terminate the given process. Returns true on success, otherwise false. */
  281. bool
  282. process_unix_terminate(process_t *process)
  283. {
  284. tor_assert(process);
  285. process_unix_t *unix_process = process_get_unix_process(process);
  286. /* All running processes should have a waitpid. */
  287. if (BUG(unix_process->waitpid == NULL))
  288. return false;
  289. bool success = true;
  290. /* Send a SIGTERM to our child process. */
  291. int ret;
  292. ret = kill(unix_process->pid, SIGTERM);
  293. if (ret == -1) {
  294. log_warn(LD_PROCESS, "Unable to terminate process: %s",
  295. strerror(errno));
  296. success = false;
  297. }
  298. /* Close all our FD's. */
  299. if (! process_unix_close_file_descriptors(unix_process))
  300. success = false;
  301. return success;
  302. }
  303. /** Returns the unique process identifier for the given <b>process</b>. */
  304. process_pid_t
  305. process_unix_get_pid(process_t *process)
  306. {
  307. tor_assert(process);
  308. process_unix_t *unix_process = process_get_unix_process(process);
  309. return (process_pid_t)unix_process->pid;
  310. }
  311. /** Write the given <b>buffer</b> as input to the given <b>process</b>'s
  312. * standard input. Returns the number of bytes written. */
  313. int
  314. process_unix_write(process_t *process, buf_t *buffer)
  315. {
  316. tor_assert(process);
  317. tor_assert(buffer);
  318. process_unix_t *unix_process = process_get_unix_process(process);
  319. size_t buffer_flush_len = buf_datalen(buffer);
  320. const size_t max_to_write = MIN(PROCESS_MAX_WRITE, buffer_flush_len);
  321. /* If we have data to write (when buffer_flush_len > 0) and we are not
  322. * currently getting file descriptor events from the kernel, we tell the
  323. * kernel to start notifying us about when we can write to our file
  324. * descriptor and return. */
  325. if (buffer_flush_len > 0 && ! unix_process->stdin_handle.is_writing) {
  326. process_unix_start_writing(&unix_process->stdin_handle);
  327. return 0;
  328. }
  329. /* We don't have any data to write, but the kernel is currently notifying us
  330. * about whether we are able to write or not. Tell the kernel to stop
  331. * notifying us until we have data to write. */
  332. if (buffer_flush_len == 0 && unix_process->stdin_handle.is_writing) {
  333. process_unix_stop_writing(&unix_process->stdin_handle);
  334. return 0;
  335. }
  336. /* We have data to write and the kernel have told us to write it. */
  337. return buf_flush_to_pipe(buffer,
  338. process_get_unix_process(process)->stdin_handle.fd,
  339. max_to_write, &buffer_flush_len);
  340. }
  341. /** Read data from the given process's standard output and put it into
  342. * <b>buffer</b>. Returns the number of bytes read. */
  343. int
  344. process_unix_read_stdout(process_t *process, buf_t *buffer)
  345. {
  346. tor_assert(process);
  347. tor_assert(buffer);
  348. process_unix_t *unix_process = process_get_unix_process(process);
  349. return process_unix_read_handle(process,
  350. &unix_process->stdout_handle,
  351. buffer);
  352. }
  353. /** Read data from the given process's standard error and put it into
  354. * <b>buffer</b>. Returns the number of bytes read. */
  355. int
  356. process_unix_read_stderr(process_t *process, buf_t *buffer)
  357. {
  358. tor_assert(process);
  359. tor_assert(buffer);
  360. process_unix_t *unix_process = process_get_unix_process(process);
  361. return process_unix_read_handle(process,
  362. &unix_process->stderr_handle,
  363. buffer);
  364. }
  365. /** This function is called whenever libevent thinks we have data that could be
  366. * read from the child process's standard output. We notify the Process
  367. * subsystem, which is then responsible for calling back to us for doing the
  368. * actual reading of the data. */
  369. STATIC void
  370. stdout_read_callback(evutil_socket_t fd, short event, void *data)
  371. {
  372. (void)fd;
  373. (void)event;
  374. process_t *process = data;
  375. tor_assert(process);
  376. process_notify_event_stdout(process);
  377. }
  378. /** This function is called whenever libevent thinks we have data that could be
  379. * read from the child process's standard error. We notify the Process
  380. * subsystem, which is then responsible for calling back to us for doing the
  381. * actual reading of the data. */
  382. STATIC void
  383. stderr_read_callback(evutil_socket_t fd, short event, void *data)
  384. {
  385. (void)fd;
  386. (void)event;
  387. process_t *process = data;
  388. tor_assert(process);
  389. process_notify_event_stderr(process);
  390. }
  391. /** This function is called whenever libevent thinks we have data that could be
  392. * written the child process's standard input. We notify the Process subsystem,
  393. * which is then responsible for calling back to us for doing the actual write
  394. * of the data. */
  395. STATIC void
  396. stdin_write_callback(evutil_socket_t fd, short event, void *data)
  397. {
  398. (void)fd;
  399. (void)event;
  400. process_t *process = data;
  401. tor_assert(process);
  402. process_notify_event_stdin(process);
  403. }
  404. /** This function tells libevent that we are interested in receiving read
  405. * events from the given <b>handle</b>. */
  406. STATIC void
  407. process_unix_start_reading(process_unix_handle_t *handle)
  408. {
  409. tor_assert(handle);
  410. if (event_add(handle->event, NULL))
  411. log_warn(LD_PROCESS,
  412. "Unable to add libevent event for handle.");
  413. }
  414. /** This function tells libevent that we are no longer interested in receiving
  415. * read events from the given <b>handle</b>. */
  416. STATIC void
  417. process_unix_stop_reading(process_unix_handle_t *handle)
  418. {
  419. tor_assert(handle);
  420. if (handle->event == NULL)
  421. return;
  422. if (event_del(handle->event))
  423. log_warn(LD_PROCESS,
  424. "Unable to delete libevent event for handle.");
  425. }
  426. /** This function tells libevent that we are interested in receiving write
  427. * events from the given <b>handle</b>. */
  428. STATIC void
  429. process_unix_start_writing(process_unix_handle_t *handle)
  430. {
  431. tor_assert(handle);
  432. if (event_add(handle->event, NULL))
  433. log_warn(LD_PROCESS,
  434. "Unable to add libevent event for handle.");
  435. handle->is_writing = true;
  436. }
  437. /** This function tells libevent that we are no longer interested in receiving
  438. * write events from the given <b>handle</b>. */
  439. STATIC void
  440. process_unix_stop_writing(process_unix_handle_t *handle)
  441. {
  442. tor_assert(handle);
  443. if (handle->event == NULL)
  444. return;
  445. if (event_del(handle->event))
  446. log_warn(LD_PROCESS,
  447. "Unable to delete libevent event for handle.");
  448. handle->is_writing = false;
  449. }
  450. /** This function is called when the waitpid system have detected that our
  451. * process have terminated. We disable the waitpid system and notify the
  452. * Process subsystem that we have terminated. */
  453. STATIC void
  454. process_unix_waitpid_callback(int status, void *data)
  455. {
  456. tor_assert(data);
  457. process_t *process = data;
  458. process_unix_t *unix_process = process_get_unix_process(process);
  459. /* Remove our waitpid callback. */
  460. clear_waitpid_callback(unix_process->waitpid);
  461. unix_process->waitpid = NULL;
  462. /* Notify our process. */
  463. process_notify_event_exit(process, status);
  464. /* Make sure you don't modify the process after we have called
  465. * process_notify_event_exit() on it, to allow users to process_free() it in
  466. * the exit callback. */
  467. }
  468. /** This function sets the file descriptor in the <b>handle</b> as non-blocking
  469. * and configures the libevent event structure based on the given <b>flags</b>
  470. * to ensure that <b>callback</b> is called whenever we have events on the
  471. * given <b>handle</b>. */
  472. STATIC void
  473. process_unix_setup_handle(process_t *process,
  474. process_unix_handle_t *handle,
  475. short flags,
  476. event_callback_fn callback)
  477. {
  478. tor_assert(process);
  479. tor_assert(handle);
  480. tor_assert(callback);
  481. /* Put our file descriptor into non-blocking mode. */
  482. if (fcntl(handle->fd, F_SETFL, O_NONBLOCK) < 0) {
  483. log_warn(LD_PROCESS, "Unable mark Unix handle as non-blocking: %s",
  484. strerror(errno));
  485. }
  486. /* Setup libevent event. */
  487. handle->event = tor_event_new(tor_libevent_get_base(),
  488. handle->fd,
  489. flags,
  490. callback,
  491. process);
  492. }
  493. /** This function reads data from the given <b>handle</b> and puts it into
  494. * <b>buffer</b>. Returns the number of bytes read this way. */
  495. STATIC int
  496. process_unix_read_handle(process_t *process,
  497. process_unix_handle_t *handle,
  498. buf_t *buffer)
  499. {
  500. tor_assert(process);
  501. tor_assert(handle);
  502. tor_assert(buffer);
  503. int ret = 0;
  504. int eof = 0;
  505. int error = 0;
  506. ret = buf_read_from_pipe(buffer,
  507. handle->fd,
  508. PROCESS_MAX_READ,
  509. &eof,
  510. &error);
  511. if (error)
  512. log_warn(LD_PROCESS,
  513. "Unable to read data: %s", strerror(error));
  514. if (eof) {
  515. handle->reached_eof = true;
  516. process_unix_stop_reading(handle);
  517. }
  518. return ret;
  519. }
  520. /** Close the standard in, out, and error handles of the given
  521. * <b>unix_process</b>. */
  522. STATIC bool
  523. process_unix_close_file_descriptors(process_unix_t *unix_process)
  524. {
  525. tor_assert(unix_process);
  526. int ret;
  527. bool success = true;
  528. if (unix_process->stdin_handle.fd != -1) {
  529. ret = close(unix_process->stdin_handle.fd);
  530. if (ret == -1) {
  531. log_warn(LD_PROCESS, "Unable to close standard in");
  532. success = false;
  533. }
  534. unix_process->stdin_handle.fd = -1;
  535. }
  536. if (unix_process->stdout_handle.fd != -1) {
  537. ret = close(unix_process->stdout_handle.fd);
  538. if (ret == -1) {
  539. log_warn(LD_PROCESS, "Unable to close standard out");
  540. success = false;
  541. }
  542. unix_process->stdout_handle.fd = -1;
  543. }
  544. if (unix_process->stderr_handle.fd != -1) {
  545. ret = close(unix_process->stderr_handle.fd);
  546. if (ret == -1) {
  547. log_warn(LD_PROCESS, "Unable to close standard error");
  548. success = false;
  549. }
  550. unix_process->stderr_handle.fd = -1;
  551. }
  552. return success;
  553. }
  554. #endif /* defined(_WIN32). */