process_unix.c 19 KB

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