subprocess.c 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236
  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 subprocess.c
  7. * \brief Launch and monitor other processes.
  8. **/
  9. #define SUBPROCESS_PRIVATE
  10. #include "lib/process/subprocess.h"
  11. #include "lib/container/smartlist.h"
  12. #include "lib/err/torerr.h"
  13. #include "lib/log/log.h"
  14. #include "lib/log/util_bug.h"
  15. #include "lib/log/win32err.h"
  16. #include "lib/malloc/malloc.h"
  17. #include "lib/process/env.h"
  18. #include "lib/process/waitpid.h"
  19. #include "lib/string/compat_ctype.h"
  20. #ifdef HAVE_SYS_TYPES_H
  21. #include <sys/types.h>
  22. #endif
  23. #ifdef HAVE_SYS_PRCTL_H
  24. #include <sys/prctl.h>
  25. #endif
  26. #ifdef HAVE_UNISTD_H
  27. #include <unistd.h>
  28. #endif
  29. #ifdef HAVE_SIGNAL_H
  30. #include <signal.h>
  31. #endif
  32. #ifdef HAVE_FCNTL_H
  33. #include <fcntl.h>
  34. #endif
  35. #ifdef HAVE_SYS_WAIT_H
  36. #include <sys/wait.h>
  37. #endif
  38. #include <errno.h>
  39. #include <string.h>
  40. /** Format a single argument for being put on a Windows command line.
  41. * Returns a newly allocated string */
  42. static char *
  43. format_win_cmdline_argument(const char *arg)
  44. {
  45. char *formatted_arg;
  46. char need_quotes;
  47. const char *c;
  48. int i;
  49. int bs_counter = 0;
  50. /* Backslash we can point to when one is inserted into the string */
  51. const char backslash = '\\';
  52. /* Smartlist of *char */
  53. smartlist_t *arg_chars;
  54. arg_chars = smartlist_new();
  55. /* Quote string if it contains whitespace or is empty */
  56. need_quotes = (strchr(arg, ' ') || strchr(arg, '\t') || '\0' == arg[0]);
  57. /* Build up smartlist of *chars */
  58. for (c=arg; *c != '\0'; c++) {
  59. if ('"' == *c) {
  60. /* Double up backslashes preceding a quote */
  61. for (i=0; i<(bs_counter*2); i++)
  62. smartlist_add(arg_chars, (void*)&backslash);
  63. bs_counter = 0;
  64. /* Escape the quote */
  65. smartlist_add(arg_chars, (void*)&backslash);
  66. smartlist_add(arg_chars, (void*)c);
  67. } else if ('\\' == *c) {
  68. /* Count backslashes until we know whether to double up */
  69. bs_counter++;
  70. } else {
  71. /* Don't double up slashes preceding a non-quote */
  72. for (i=0; i<bs_counter; i++)
  73. smartlist_add(arg_chars, (void*)&backslash);
  74. bs_counter = 0;
  75. smartlist_add(arg_chars, (void*)c);
  76. }
  77. }
  78. /* Don't double up trailing backslashes */
  79. for (i=0; i<bs_counter; i++)
  80. smartlist_add(arg_chars, (void*)&backslash);
  81. /* Allocate space for argument, quotes (if needed), and terminator */
  82. const size_t formatted_arg_len = smartlist_len(arg_chars) +
  83. (need_quotes ? 2 : 0) + 1;
  84. formatted_arg = tor_malloc_zero(formatted_arg_len);
  85. /* Add leading quote */
  86. i=0;
  87. if (need_quotes)
  88. formatted_arg[i++] = '"';
  89. /* Add characters */
  90. SMARTLIST_FOREACH(arg_chars, char*, ch,
  91. {
  92. formatted_arg[i++] = *ch;
  93. });
  94. /* Add trailing quote */
  95. if (need_quotes)
  96. formatted_arg[i++] = '"';
  97. formatted_arg[i] = '\0';
  98. smartlist_free(arg_chars);
  99. return formatted_arg;
  100. }
  101. /** Format a command line for use on Windows, which takes the command as a
  102. * string rather than string array. Follows the rules from "Parsing C++
  103. * Command-Line Arguments" in MSDN. Algorithm based on list2cmdline in the
  104. * Python subprocess module. Returns a newly allocated string */
  105. char *
  106. tor_join_win_cmdline(const char *argv[])
  107. {
  108. smartlist_t *argv_list;
  109. char *joined_argv;
  110. int i;
  111. /* Format each argument and put the result in a smartlist */
  112. argv_list = smartlist_new();
  113. for (i=0; argv[i] != NULL; i++) {
  114. smartlist_add(argv_list, (void *)format_win_cmdline_argument(argv[i]));
  115. }
  116. /* Join the arguments with whitespace */
  117. joined_argv = smartlist_join_strings(argv_list, " ", 0, NULL);
  118. /* Free the newly allocated arguments, and the smartlist */
  119. SMARTLIST_FOREACH(argv_list, char *, arg,
  120. {
  121. tor_free(arg);
  122. });
  123. smartlist_free(argv_list);
  124. return joined_argv;
  125. }
  126. #ifndef _WIN32
  127. /** Format <b>child_state</b> and <b>saved_errno</b> as a hex string placed in
  128. * <b>hex_errno</b>. Called between fork and _exit, so must be signal-handler
  129. * safe.
  130. *
  131. * <b>hex_errno</b> must have at least HEX_ERRNO_SIZE+1 bytes available.
  132. *
  133. * The format of <b>hex_errno</b> is: "CHILD_STATE/ERRNO\n", left-padded
  134. * with spaces. CHILD_STATE indicates where
  135. * in the process of starting the child process did the failure occur (see
  136. * CHILD_STATE_* macros for definition), and SAVED_ERRNO is the value of
  137. * errno when the failure occurred.
  138. *
  139. * On success return the number of characters added to hex_errno, not counting
  140. * the terminating NUL; return -1 on error.
  141. */
  142. STATIC int
  143. format_helper_exit_status(unsigned char child_state, int saved_errno,
  144. char *hex_errno)
  145. {
  146. unsigned int unsigned_errno;
  147. int written, left;
  148. char *cur;
  149. size_t i;
  150. int res = -1;
  151. /* Fill hex_errno with spaces, and a trailing newline (memset may
  152. not be signal handler safe, so we can't use it) */
  153. for (i = 0; i < (HEX_ERRNO_SIZE - 1); i++)
  154. hex_errno[i] = ' ';
  155. hex_errno[HEX_ERRNO_SIZE - 1] = '\n';
  156. /* Convert errno to be unsigned for hex conversion */
  157. if (saved_errno < 0) {
  158. // Avoid overflow on the cast to unsigned int when result is INT_MIN
  159. // by adding 1 to the signed int negative value,
  160. // then, after it has been negated and cast to unsigned,
  161. // adding the original 1 back (the double-addition is intentional).
  162. // Otherwise, the cast to signed could cause a temporary int
  163. // to equal INT_MAX + 1, which is undefined.
  164. unsigned_errno = ((unsigned int) -(saved_errno + 1)) + 1;
  165. } else {
  166. unsigned_errno = (unsigned int) saved_errno;
  167. }
  168. /*
  169. * Count how many chars of space we have left, and keep a pointer into the
  170. * current point in the buffer.
  171. */
  172. left = HEX_ERRNO_SIZE+1;
  173. cur = hex_errno;
  174. /* Emit child_state */
  175. written = format_hex_number_sigsafe(child_state, cur, left);
  176. if (written <= 0)
  177. goto err;
  178. /* Adjust left and cur */
  179. left -= written;
  180. cur += written;
  181. if (left <= 0)
  182. goto err;
  183. /* Now the '/' */
  184. *cur = '/';
  185. /* Adjust left and cur */
  186. ++cur;
  187. --left;
  188. if (left <= 0)
  189. goto err;
  190. /* Need minus? */
  191. if (saved_errno < 0) {
  192. *cur = '-';
  193. ++cur;
  194. --left;
  195. if (left <= 0)
  196. goto err;
  197. }
  198. /* Emit unsigned_errno */
  199. written = format_hex_number_sigsafe(unsigned_errno, cur, left);
  200. if (written <= 0)
  201. goto err;
  202. /* Adjust left and cur */
  203. left -= written;
  204. cur += written;
  205. /* Check that we have enough space left for a newline and a NUL */
  206. if (left <= 1)
  207. goto err;
  208. /* Emit the newline and NUL */
  209. *cur++ = '\n';
  210. *cur++ = '\0';
  211. res = (int)(cur - hex_errno - 1);
  212. goto done;
  213. err:
  214. /*
  215. * In error exit, just write a '\0' in the first char so whatever called
  216. * this at least won't fall off the end.
  217. */
  218. *hex_errno = '\0';
  219. done:
  220. return res;
  221. }
  222. #endif /* !defined(_WIN32) */
  223. /* Maximum number of file descriptors, if we cannot get it via sysconf() */
  224. #define DEFAULT_MAX_FD 256
  225. /** Terminate the process of <b>process_handle</b>, if that process has not
  226. * already exited.
  227. *
  228. * Return 0 if we succeeded in terminating the process (or if the process
  229. * already exited), and -1 if we tried to kill the process but failed.
  230. *
  231. * Based on code originally borrowed from Python's os.kill. */
  232. int
  233. tor_terminate_process(process_handle_t *process_handle)
  234. {
  235. #ifdef _WIN32
  236. if (tor_get_exit_code(process_handle, 0, NULL) == PROCESS_EXIT_RUNNING) {
  237. HANDLE handle = process_handle->pid.hProcess;
  238. if (!TerminateProcess(handle, 0))
  239. return -1;
  240. else
  241. return 0;
  242. }
  243. #else /* !(defined(_WIN32)) */
  244. if (process_handle->waitpid_cb) {
  245. /* We haven't got a waitpid yet, so we can just kill off the process. */
  246. return kill(process_handle->pid, SIGTERM);
  247. }
  248. #endif /* defined(_WIN32) */
  249. return 0; /* We didn't need to kill the process, so report success */
  250. }
  251. /** Return the Process ID of <b>process_handle</b>. */
  252. int
  253. tor_process_get_pid(process_handle_t *process_handle)
  254. {
  255. #ifdef _WIN32
  256. return (int) process_handle->pid.dwProcessId;
  257. #else
  258. return (int) process_handle->pid;
  259. #endif
  260. }
  261. #ifdef _WIN32
  262. HANDLE
  263. tor_process_get_stdout_pipe(process_handle_t *process_handle)
  264. {
  265. return process_handle->stdout_pipe;
  266. }
  267. #else /* !(defined(_WIN32)) */
  268. /* DOCDOC tor_process_get_stdout_pipe */
  269. int
  270. tor_process_get_stdout_pipe(process_handle_t *process_handle)
  271. {
  272. return process_handle->stdout_pipe;
  273. }
  274. #endif /* defined(_WIN32) */
  275. /* DOCDOC process_handle_new */
  276. static process_handle_t *
  277. process_handle_new(void)
  278. {
  279. process_handle_t *out = tor_malloc_zero(sizeof(process_handle_t));
  280. #ifdef _WIN32
  281. out->stdin_pipe = INVALID_HANDLE_VALUE;
  282. out->stdout_pipe = INVALID_HANDLE_VALUE;
  283. out->stderr_pipe = INVALID_HANDLE_VALUE;
  284. #else
  285. out->stdin_pipe = -1;
  286. out->stdout_pipe = -1;
  287. out->stderr_pipe = -1;
  288. #endif /* defined(_WIN32) */
  289. return out;
  290. }
  291. #ifndef _WIN32
  292. /** Invoked when a process that we've launched via tor_spawn_background() has
  293. * been found to have terminated.
  294. */
  295. static void
  296. process_handle_waitpid_cb(int status, void *arg)
  297. {
  298. process_handle_t *process_handle = arg;
  299. process_handle->waitpid_exit_status = status;
  300. clear_waitpid_callback(process_handle->waitpid_cb);
  301. if (process_handle->status == PROCESS_STATUS_RUNNING)
  302. process_handle->status = PROCESS_STATUS_NOTRUNNING;
  303. process_handle->waitpid_cb = 0;
  304. }
  305. #endif /* !defined(_WIN32) */
  306. /**
  307. * @name child-process states
  308. *
  309. * Each of these values represents a possible state that a child process can
  310. * be in. They're used to determine what to say when telling the parent how
  311. * far along we were before failure.
  312. *
  313. * @{
  314. */
  315. #define CHILD_STATE_INIT 0
  316. #define CHILD_STATE_PIPE 1
  317. #define CHILD_STATE_MAXFD 2
  318. #define CHILD_STATE_FORK 3
  319. #define CHILD_STATE_DUPOUT 4
  320. #define CHILD_STATE_DUPERR 5
  321. #define CHILD_STATE_DUPIN 6
  322. #define CHILD_STATE_CLOSEFD 7
  323. #define CHILD_STATE_EXEC 8
  324. #define CHILD_STATE_FAILEXEC 9
  325. /** @} */
  326. /**
  327. * Boolean. If true, then Tor may call execve or CreateProcess via
  328. * tor_spawn_background.
  329. **/
  330. static int may_spawn_background_process = 1;
  331. /**
  332. * Turn off may_spawn_background_process, so that all future calls to
  333. * tor_spawn_background are guaranteed to fail.
  334. **/
  335. void
  336. tor_disable_spawning_background_processes(void)
  337. {
  338. may_spawn_background_process = 0;
  339. }
  340. /** Start a program in the background. If <b>filename</b> contains a '/', then
  341. * it will be treated as an absolute or relative path. Otherwise, on
  342. * non-Windows systems, the system path will be searched for <b>filename</b>.
  343. * On Windows, only the current directory will be searched. Here, to search the
  344. * system path (as well as the application directory, current working
  345. * directory, and system directories), set filename to NULL.
  346. *
  347. * The strings in <b>argv</b> will be passed as the command line arguments of
  348. * the child program (following convention, argv[0] should normally be the
  349. * filename of the executable, and this must be the case if <b>filename</b> is
  350. * NULL). The last element of argv must be NULL. A handle to the child process
  351. * will be returned in process_handle (which must be non-NULL). Read
  352. * process_handle.status to find out if the process was successfully launched.
  353. * For convenience, process_handle.status is returned by this function.
  354. *
  355. * Some parts of this code are based on the POSIX subprocess module from
  356. * Python, and example code from
  357. * http://msdn.microsoft.com/en-us/library/ms682499%28v=vs.85%29.aspx.
  358. */
  359. int
  360. tor_spawn_background(const char *const filename, const char **argv,
  361. process_environment_t *env,
  362. process_handle_t **process_handle_out)
  363. {
  364. if (BUG(may_spawn_background_process == 0)) {
  365. /* We should never reach this point if we're forbidden to spawn
  366. * processes. Instead we should have caught the attempt earlier. */
  367. return PROCESS_STATUS_ERROR;
  368. }
  369. #ifdef _WIN32
  370. HANDLE stdout_pipe_read = NULL;
  371. HANDLE stdout_pipe_write = NULL;
  372. HANDLE stderr_pipe_read = NULL;
  373. HANDLE stderr_pipe_write = NULL;
  374. HANDLE stdin_pipe_read = NULL;
  375. HANDLE stdin_pipe_write = NULL;
  376. process_handle_t *process_handle;
  377. int status;
  378. STARTUPINFOA siStartInfo;
  379. BOOL retval = FALSE;
  380. SECURITY_ATTRIBUTES saAttr;
  381. char *joined_argv;
  382. saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
  383. saAttr.bInheritHandle = TRUE;
  384. /* TODO: should we set explicit security attributes? (#2046, comment 5) */
  385. saAttr.lpSecurityDescriptor = NULL;
  386. /* Assume failure to start process */
  387. status = PROCESS_STATUS_ERROR;
  388. /* Set up pipe for stdout */
  389. if (!CreatePipe(&stdout_pipe_read, &stdout_pipe_write, &saAttr, 0)) {
  390. log_warn(LD_GENERAL,
  391. "Failed to create pipe for stdout communication with child process: %s",
  392. format_win32_error(GetLastError()));
  393. return status;
  394. }
  395. if (!SetHandleInformation(stdout_pipe_read, HANDLE_FLAG_INHERIT, 0)) {
  396. log_warn(LD_GENERAL,
  397. "Failed to configure pipe for stdout communication with child "
  398. "process: %s", format_win32_error(GetLastError()));
  399. return status;
  400. }
  401. /* Set up pipe for stderr */
  402. if (!CreatePipe(&stderr_pipe_read, &stderr_pipe_write, &saAttr, 0)) {
  403. log_warn(LD_GENERAL,
  404. "Failed to create pipe for stderr communication with child process: %s",
  405. format_win32_error(GetLastError()));
  406. return status;
  407. }
  408. if (!SetHandleInformation(stderr_pipe_read, HANDLE_FLAG_INHERIT, 0)) {
  409. log_warn(LD_GENERAL,
  410. "Failed to configure pipe for stderr communication with child "
  411. "process: %s", format_win32_error(GetLastError()));
  412. return status;
  413. }
  414. /* Set up pipe for stdin */
  415. if (!CreatePipe(&stdin_pipe_read, &stdin_pipe_write, &saAttr, 0)) {
  416. log_warn(LD_GENERAL,
  417. "Failed to create pipe for stdin communication with child process: %s",
  418. format_win32_error(GetLastError()));
  419. return status;
  420. }
  421. if (!SetHandleInformation(stdin_pipe_write, HANDLE_FLAG_INHERIT, 0)) {
  422. log_warn(LD_GENERAL,
  423. "Failed to configure pipe for stdin communication with child "
  424. "process: %s", format_win32_error(GetLastError()));
  425. return status;
  426. }
  427. /* Create the child process */
  428. /* Windows expects argv to be a whitespace delimited string, so join argv up
  429. */
  430. joined_argv = tor_join_win_cmdline(argv);
  431. process_handle = process_handle_new();
  432. process_handle->status = status;
  433. ZeroMemory(&(process_handle->pid), sizeof(PROCESS_INFORMATION));
  434. ZeroMemory(&siStartInfo, sizeof(STARTUPINFO));
  435. siStartInfo.cb = sizeof(STARTUPINFO);
  436. siStartInfo.hStdError = stderr_pipe_write;
  437. siStartInfo.hStdOutput = stdout_pipe_write;
  438. siStartInfo.hStdInput = stdin_pipe_read;
  439. siStartInfo.dwFlags |= STARTF_USESTDHANDLES;
  440. /* Create the child process */
  441. retval = CreateProcessA(filename, // module name
  442. joined_argv, // command line
  443. /* TODO: should we set explicit security attributes? (#2046, comment 5) */
  444. NULL, // process security attributes
  445. NULL, // primary thread security attributes
  446. TRUE, // handles are inherited
  447. /*(TODO: set CREATE_NEW CONSOLE/PROCESS_GROUP to make GetExitCodeProcess()
  448. * work?) */
  449. CREATE_NO_WINDOW, // creation flags
  450. (env==NULL) ? NULL : env->windows_environment_block,
  451. NULL, // use parent's current directory
  452. &siStartInfo, // STARTUPINFO pointer
  453. &(process_handle->pid)); // receives PROCESS_INFORMATION
  454. tor_free(joined_argv);
  455. if (!retval) {
  456. log_warn(LD_GENERAL,
  457. "Failed to create child process %s: %s", filename?filename:argv[0],
  458. format_win32_error(GetLastError()));
  459. tor_free(process_handle);
  460. } else {
  461. /* TODO: Close hProcess and hThread in process_handle->pid? */
  462. process_handle->stdout_pipe = stdout_pipe_read;
  463. process_handle->stderr_pipe = stderr_pipe_read;
  464. process_handle->stdin_pipe = stdin_pipe_write;
  465. status = process_handle->status = PROCESS_STATUS_RUNNING;
  466. }
  467. /* TODO: Close pipes on exit */
  468. *process_handle_out = process_handle;
  469. return status;
  470. #else /* !(defined(_WIN32)) */
  471. pid_t pid;
  472. int stdout_pipe[2];
  473. int stderr_pipe[2];
  474. int stdin_pipe[2];
  475. int fd, retval;
  476. process_handle_t *process_handle;
  477. int status;
  478. const char *error_message = SPAWN_ERROR_MESSAGE;
  479. size_t error_message_length;
  480. /* Represents where in the process of spawning the program is;
  481. this is used for printing out the error message */
  482. unsigned char child_state = CHILD_STATE_INIT;
  483. char hex_errno[HEX_ERRNO_SIZE + 2]; /* + 1 should be sufficient actually */
  484. static int max_fd = -1;
  485. status = PROCESS_STATUS_ERROR;
  486. /* We do the strlen here because strlen() is not signal handler safe,
  487. and we are not allowed to use unsafe functions between fork and exec */
  488. error_message_length = strlen(error_message);
  489. // child_state = CHILD_STATE_PIPE;
  490. /* Set up pipe for redirecting stdout, stderr, and stdin of child */
  491. retval = pipe(stdout_pipe);
  492. if (-1 == retval) {
  493. log_warn(LD_GENERAL,
  494. "Failed to set up pipe for stdout communication with child process: %s",
  495. strerror(errno));
  496. return status;
  497. }
  498. retval = pipe(stderr_pipe);
  499. if (-1 == retval) {
  500. log_warn(LD_GENERAL,
  501. "Failed to set up pipe for stderr communication with child process: %s",
  502. strerror(errno));
  503. close(stdout_pipe[0]);
  504. close(stdout_pipe[1]);
  505. return status;
  506. }
  507. retval = pipe(stdin_pipe);
  508. if (-1 == retval) {
  509. log_warn(LD_GENERAL,
  510. "Failed to set up pipe for stdin communication with child process: %s",
  511. strerror(errno));
  512. close(stdout_pipe[0]);
  513. close(stdout_pipe[1]);
  514. close(stderr_pipe[0]);
  515. close(stderr_pipe[1]);
  516. return status;
  517. }
  518. // child_state = CHILD_STATE_MAXFD;
  519. #ifdef _SC_OPEN_MAX
  520. if (-1 == max_fd) {
  521. max_fd = (int) sysconf(_SC_OPEN_MAX);
  522. if (max_fd == -1) {
  523. max_fd = DEFAULT_MAX_FD;
  524. log_warn(LD_GENERAL,
  525. "Cannot find maximum file descriptor, assuming %d", max_fd);
  526. }
  527. }
  528. #else /* !(defined(_SC_OPEN_MAX)) */
  529. max_fd = DEFAULT_MAX_FD;
  530. #endif /* defined(_SC_OPEN_MAX) */
  531. // child_state = CHILD_STATE_FORK;
  532. pid = fork();
  533. if (0 == pid) {
  534. /* In child */
  535. #if defined(HAVE_SYS_PRCTL_H) && defined(__linux__)
  536. /* Attempt to have the kernel issue a SIGTERM if the parent
  537. * goes away. Certain attributes of the binary being execve()ed
  538. * will clear this during the execve() call, but it's better
  539. * than nothing.
  540. */
  541. prctl(PR_SET_PDEATHSIG, SIGTERM);
  542. #endif /* defined(HAVE_SYS_PRCTL_H) && defined(__linux__) */
  543. child_state = CHILD_STATE_DUPOUT;
  544. /* Link child stdout to the write end of the pipe */
  545. retval = dup2(stdout_pipe[1], STDOUT_FILENO);
  546. if (-1 == retval)
  547. goto error;
  548. child_state = CHILD_STATE_DUPERR;
  549. /* Link child stderr to the write end of the pipe */
  550. retval = dup2(stderr_pipe[1], STDERR_FILENO);
  551. if (-1 == retval)
  552. goto error;
  553. child_state = CHILD_STATE_DUPIN;
  554. /* Link child stdin to the read end of the pipe */
  555. retval = dup2(stdin_pipe[0], STDIN_FILENO);
  556. if (-1 == retval)
  557. goto error;
  558. // child_state = CHILD_STATE_CLOSEFD;
  559. close(stderr_pipe[0]);
  560. close(stderr_pipe[1]);
  561. close(stdout_pipe[0]);
  562. close(stdout_pipe[1]);
  563. close(stdin_pipe[0]);
  564. close(stdin_pipe[1]);
  565. /* Close all other fds, including the read end of the pipe */
  566. /* XXX: We should now be doing enough FD_CLOEXEC setting to make
  567. * this needless. */
  568. for (fd = STDERR_FILENO + 1; fd < max_fd; fd++) {
  569. close(fd);
  570. }
  571. // child_state = CHILD_STATE_EXEC;
  572. /* Call the requested program. We need the cast because
  573. execvp doesn't define argv as const, even though it
  574. does not modify the arguments */
  575. if (env)
  576. execve(filename, (char *const *) argv, env->unixoid_environment_block);
  577. else {
  578. static char *new_env[] = { NULL };
  579. execve(filename, (char *const *) argv, new_env);
  580. }
  581. /* If we got here, the exec or open(/dev/null) failed */
  582. child_state = CHILD_STATE_FAILEXEC;
  583. error:
  584. {
  585. /* XXX: are we leaking fds from the pipe? */
  586. int n, err=0;
  587. ssize_t nbytes;
  588. n = format_helper_exit_status(child_state, errno, hex_errno);
  589. if (n >= 0) {
  590. /* Write the error message. GCC requires that we check the return
  591. value, but there is nothing we can do if it fails */
  592. /* TODO: Don't use STDOUT, use a pipe set up just for this purpose */
  593. nbytes = write(STDOUT_FILENO, error_message, error_message_length);
  594. err = (nbytes < 0);
  595. nbytes = write(STDOUT_FILENO, hex_errno, n);
  596. err += (nbytes < 0);
  597. }
  598. _exit(err?254:255); // exit ok: in child.
  599. }
  600. /* Never reached, but avoids compiler warning */
  601. return status; // LCOV_EXCL_LINE
  602. }
  603. /* In parent */
  604. if (-1 == pid) {
  605. log_warn(LD_GENERAL, "Failed to fork child process: %s", strerror(errno));
  606. close(stdin_pipe[0]);
  607. close(stdin_pipe[1]);
  608. close(stdout_pipe[0]);
  609. close(stdout_pipe[1]);
  610. close(stderr_pipe[0]);
  611. close(stderr_pipe[1]);
  612. return status;
  613. }
  614. process_handle = process_handle_new();
  615. process_handle->status = status;
  616. process_handle->pid = pid;
  617. /* TODO: If the child process forked but failed to exec, waitpid it */
  618. /* Return read end of the pipes to caller, and close write end */
  619. process_handle->stdout_pipe = stdout_pipe[0];
  620. retval = close(stdout_pipe[1]);
  621. if (-1 == retval) {
  622. log_warn(LD_GENERAL,
  623. "Failed to close write end of stdout pipe in parent process: %s",
  624. strerror(errno));
  625. }
  626. process_handle->waitpid_cb = set_waitpid_callback(pid,
  627. process_handle_waitpid_cb,
  628. process_handle);
  629. process_handle->stderr_pipe = stderr_pipe[0];
  630. retval = close(stderr_pipe[1]);
  631. if (-1 == retval) {
  632. log_warn(LD_GENERAL,
  633. "Failed to close write end of stderr pipe in parent process: %s",
  634. strerror(errno));
  635. }
  636. /* Return write end of the stdin pipe to caller, and close the read end */
  637. process_handle->stdin_pipe = stdin_pipe[1];
  638. retval = close(stdin_pipe[0]);
  639. if (-1 == retval) {
  640. log_warn(LD_GENERAL,
  641. "Failed to close read end of stdin pipe in parent process: %s",
  642. strerror(errno));
  643. }
  644. status = process_handle->status = PROCESS_STATUS_RUNNING;
  645. /* Set stdin/stdout/stderr pipes to be non-blocking */
  646. if (fcntl(process_handle->stdout_pipe, F_SETFL, O_NONBLOCK) < 0 ||
  647. fcntl(process_handle->stderr_pipe, F_SETFL, O_NONBLOCK) < 0 ||
  648. fcntl(process_handle->stdin_pipe, F_SETFL, O_NONBLOCK) < 0) {
  649. log_warn(LD_GENERAL, "Failed to set stderror/stdout/stdin pipes "
  650. "nonblocking in parent process: %s", strerror(errno));
  651. }
  652. *process_handle_out = process_handle;
  653. return status;
  654. #endif /* defined(_WIN32) */
  655. }
  656. /** Destroy all resources allocated by the process handle in
  657. * <b>process_handle</b>.
  658. * If <b>also_terminate_process</b> is true, also terminate the
  659. * process of the process handle. */
  660. MOCK_IMPL(void,
  661. tor_process_handle_destroy,(process_handle_t *process_handle,
  662. int also_terminate_process))
  663. {
  664. if (!process_handle)
  665. return;
  666. if (also_terminate_process) {
  667. if (tor_terminate_process(process_handle) < 0) {
  668. const char *errstr =
  669. #ifdef _WIN32
  670. format_win32_error(GetLastError());
  671. #else
  672. strerror(errno);
  673. #endif
  674. log_notice(LD_GENERAL, "Failed to terminate process with "
  675. "PID '%d' ('%s').", tor_process_get_pid(process_handle),
  676. errstr);
  677. } else {
  678. log_info(LD_GENERAL, "Terminated process with PID '%d'.",
  679. tor_process_get_pid(process_handle));
  680. }
  681. }
  682. process_handle->status = PROCESS_STATUS_NOTRUNNING;
  683. #ifdef _WIN32
  684. if (process_handle->stdout_pipe)
  685. CloseHandle(process_handle->stdout_pipe);
  686. if (process_handle->stderr_pipe)
  687. CloseHandle(process_handle->stderr_pipe);
  688. if (process_handle->stdin_pipe)
  689. CloseHandle(process_handle->stdin_pipe);
  690. #else /* !(defined(_WIN32)) */
  691. close(process_handle->stdout_pipe);
  692. close(process_handle->stderr_pipe);
  693. close(process_handle->stdin_pipe);
  694. clear_waitpid_callback(process_handle->waitpid_cb);
  695. #endif /* defined(_WIN32) */
  696. memset(process_handle, 0x0f, sizeof(process_handle_t));
  697. tor_free(process_handle);
  698. }
  699. /** Get the exit code of a process specified by <b>process_handle</b> and store
  700. * it in <b>exit_code</b>, if set to a non-NULL value. If <b>block</b> is set
  701. * to true, the call will block until the process has exited. Otherwise if
  702. * the process is still running, the function will return
  703. * PROCESS_EXIT_RUNNING, and exit_code will be left unchanged. Returns
  704. * PROCESS_EXIT_EXITED if the process did exit. If there is a failure,
  705. * PROCESS_EXIT_ERROR will be returned and the contents of exit_code (if
  706. * non-NULL) will be undefined. N.B. Under *nix operating systems, this will
  707. * probably not work in Tor, because waitpid() is called in main.c to reap any
  708. * terminated child processes.*/
  709. int
  710. tor_get_exit_code(process_handle_t *process_handle,
  711. int block, int *exit_code)
  712. {
  713. #ifdef _WIN32
  714. DWORD retval;
  715. BOOL success;
  716. if (block) {
  717. /* Wait for the process to exit */
  718. retval = WaitForSingleObject(process_handle->pid.hProcess, INFINITE);
  719. if (retval != WAIT_OBJECT_0) {
  720. log_warn(LD_GENERAL, "WaitForSingleObject() failed (%d): %s",
  721. (int)retval, format_win32_error(GetLastError()));
  722. return PROCESS_EXIT_ERROR;
  723. }
  724. } else {
  725. retval = WaitForSingleObject(process_handle->pid.hProcess, 0);
  726. if (WAIT_TIMEOUT == retval) {
  727. /* Process has not exited */
  728. return PROCESS_EXIT_RUNNING;
  729. } else if (retval != WAIT_OBJECT_0) {
  730. log_warn(LD_GENERAL, "WaitForSingleObject() failed (%d): %s",
  731. (int)retval, format_win32_error(GetLastError()));
  732. return PROCESS_EXIT_ERROR;
  733. }
  734. }
  735. if (exit_code != NULL) {
  736. success = GetExitCodeProcess(process_handle->pid.hProcess,
  737. (PDWORD)exit_code);
  738. if (!success) {
  739. log_warn(LD_GENERAL, "GetExitCodeProcess() failed: %s",
  740. format_win32_error(GetLastError()));
  741. return PROCESS_EXIT_ERROR;
  742. }
  743. }
  744. #else /* !(defined(_WIN32)) */
  745. int stat_loc;
  746. int retval;
  747. if (process_handle->waitpid_cb) {
  748. /* We haven't processed a SIGCHLD yet. */
  749. retval = waitpid(process_handle->pid, &stat_loc, block?0:WNOHANG);
  750. if (retval == process_handle->pid) {
  751. clear_waitpid_callback(process_handle->waitpid_cb);
  752. process_handle->waitpid_cb = NULL;
  753. process_handle->waitpid_exit_status = stat_loc;
  754. }
  755. } else {
  756. /* We already got a SIGCHLD for this process, and handled it. */
  757. retval = process_handle->pid;
  758. stat_loc = process_handle->waitpid_exit_status;
  759. }
  760. if (!block && 0 == retval) {
  761. /* Process has not exited */
  762. return PROCESS_EXIT_RUNNING;
  763. } else if (retval != process_handle->pid) {
  764. log_warn(LD_GENERAL, "waitpid() failed for PID %d: %s",
  765. (int)process_handle->pid, strerror(errno));
  766. return PROCESS_EXIT_ERROR;
  767. }
  768. if (!WIFEXITED(stat_loc)) {
  769. log_warn(LD_GENERAL, "Process %d did not exit normally",
  770. (int)process_handle->pid);
  771. return PROCESS_EXIT_ERROR;
  772. }
  773. if (exit_code != NULL)
  774. *exit_code = WEXITSTATUS(stat_loc);
  775. #endif /* defined(_WIN32) */
  776. return PROCESS_EXIT_EXITED;
  777. }
  778. #ifdef _WIN32
  779. /** Read from a handle <b>h</b> into <b>buf</b>, up to <b>count</b> bytes. If
  780. * <b>hProcess</b> is NULL, the function will return immediately if there is
  781. * nothing more to read. Otherwise <b>hProcess</b> should be set to the handle
  782. * to the process owning the <b>h</b>. In this case, the function will exit
  783. * only once the process has exited, or <b>count</b> bytes are read. Returns
  784. * the number of bytes read, or -1 on error. */
  785. ssize_t
  786. tor_read_all_handle(HANDLE h, char *buf, size_t count,
  787. const process_handle_t *process)
  788. {
  789. size_t numread = 0;
  790. BOOL retval;
  791. DWORD byte_count;
  792. BOOL process_exited = FALSE;
  793. if (count > SIZE_T_CEILING || count > SSIZE_MAX)
  794. return -1;
  795. while (numread < count) {
  796. /* Check if there is anything to read */
  797. retval = PeekNamedPipe(h, NULL, 0, NULL, &byte_count, NULL);
  798. if (!retval) {
  799. log_warn(LD_GENERAL,
  800. "Failed to peek from handle: %s",
  801. format_win32_error(GetLastError()));
  802. return -1;
  803. } else if (0 == byte_count) {
  804. /* Nothing available: process exited or it is busy */
  805. /* Exit if we don't know whether the process is running */
  806. if (NULL == process)
  807. break;
  808. /* The process exited and there's nothing left to read from it */
  809. if (process_exited)
  810. break;
  811. /* If process is not running, check for output one more time in case
  812. it wrote something after the peek was performed. Otherwise keep on
  813. waiting for output */
  814. tor_assert(process != NULL);
  815. byte_count = WaitForSingleObject(process->pid.hProcess, 0);
  816. if (WAIT_TIMEOUT != byte_count)
  817. process_exited = TRUE;
  818. continue;
  819. }
  820. /* There is data to read; read it */
  821. retval = ReadFile(h, buf+numread, count-numread, &byte_count, NULL);
  822. tor_assert(byte_count + numread <= count);
  823. if (!retval) {
  824. log_warn(LD_GENERAL, "Failed to read from handle: %s",
  825. format_win32_error(GetLastError()));
  826. return -1;
  827. } else if (0 == byte_count) {
  828. /* End of file */
  829. break;
  830. }
  831. numread += byte_count;
  832. }
  833. return (ssize_t)numread;
  834. }
  835. #else /* !(defined(_WIN32)) */
  836. /** Read from a handle <b>fd</b> into <b>buf</b>, up to <b>count</b> bytes. If
  837. * <b>process</b> is NULL, the function will return immediately if there is
  838. * nothing more to read. Otherwise data will be read until end of file, or
  839. * <b>count</b> bytes are read. Returns the number of bytes read, or -1 on
  840. * error. Sets <b>eof</b> to true if <b>eof</b> is not NULL and the end of the
  841. * file has been reached. */
  842. ssize_t
  843. tor_read_all_handle(int fd, char *buf, size_t count,
  844. const process_handle_t *process,
  845. int *eof)
  846. {
  847. size_t numread = 0;
  848. ssize_t result;
  849. if (eof)
  850. *eof = 0;
  851. if (count > SIZE_T_CEILING || count > SSIZE_MAX)
  852. return -1;
  853. while (numread < count) {
  854. result = read(fd, buf+numread, count-numread);
  855. if (result == 0) {
  856. log_debug(LD_GENERAL, "read() reached end of file");
  857. if (eof)
  858. *eof = 1;
  859. break;
  860. } else if (result < 0 && errno == EAGAIN) {
  861. if (process)
  862. continue;
  863. else
  864. break;
  865. } else if (result < 0) {
  866. log_warn(LD_GENERAL, "read() failed: %s", strerror(errno));
  867. return -1;
  868. }
  869. numread += result;
  870. }
  871. log_debug(LD_GENERAL, "read() read %d bytes from handle", (int)numread);
  872. return (ssize_t)numread;
  873. }
  874. #endif /* defined(_WIN32) */
  875. /** Read from stdout of a process until the process exits. */
  876. ssize_t
  877. tor_read_all_from_process_stdout(const process_handle_t *process_handle,
  878. char *buf, size_t count)
  879. {
  880. #ifdef _WIN32
  881. return tor_read_all_handle(process_handle->stdout_pipe, buf, count,
  882. process_handle);
  883. #else
  884. return tor_read_all_handle(process_handle->stdout_pipe, buf, count,
  885. process_handle, NULL);
  886. #endif /* defined(_WIN32) */
  887. }
  888. /** Read from stdout of a process until the process exits. */
  889. ssize_t
  890. tor_read_all_from_process_stderr(const process_handle_t *process_handle,
  891. char *buf, size_t count)
  892. {
  893. #ifdef _WIN32
  894. return tor_read_all_handle(process_handle->stderr_pipe, buf, count,
  895. process_handle);
  896. #else
  897. return tor_read_all_handle(process_handle->stderr_pipe, buf, count,
  898. process_handle, NULL);
  899. #endif /* defined(_WIN32) */
  900. }
  901. /** Return a string corresponding to <b>stream_status</b>. */
  902. const char *
  903. stream_status_to_string(enum stream_status stream_status)
  904. {
  905. switch (stream_status) {
  906. case IO_STREAM_OKAY:
  907. return "okay";
  908. case IO_STREAM_EAGAIN:
  909. return "temporarily unavailable";
  910. case IO_STREAM_TERM:
  911. return "terminated";
  912. case IO_STREAM_CLOSED:
  913. return "closed";
  914. default:
  915. tor_fragile_assert();
  916. return "unknown";
  917. }
  918. }
  919. /** Split buf into lines, and add to smartlist. The buffer <b>buf</b> will be
  920. * modified. The resulting smartlist will consist of pointers to buf, so there
  921. * is no need to free the contents of sl. <b>buf</b> must be a NUL-terminated
  922. * string. <b>len</b> should be set to the length of the buffer excluding the
  923. * NUL. Non-printable characters (including NUL) will be replaced with "." */
  924. int
  925. tor_split_lines(smartlist_t *sl, char *buf, int len)
  926. {
  927. /* Index in buf of the start of the current line */
  928. int start = 0;
  929. /* Index in buf of the current character being processed */
  930. int cur = 0;
  931. /* Are we currently in a line */
  932. char in_line = 0;
  933. /* Loop over string */
  934. while (cur < len) {
  935. /* Loop until end of line or end of string */
  936. for (; cur < len; cur++) {
  937. if (in_line) {
  938. if ('\r' == buf[cur] || '\n' == buf[cur]) {
  939. /* End of line */
  940. buf[cur] = '\0';
  941. /* Point cur to the next line */
  942. cur++;
  943. /* Line starts at start and ends with a nul */
  944. break;
  945. } else {
  946. if (!TOR_ISPRINT(buf[cur]))
  947. buf[cur] = '.';
  948. }
  949. } else {
  950. if ('\r' == buf[cur] || '\n' == buf[cur]) {
  951. /* Skip leading vertical space */
  952. ;
  953. } else {
  954. in_line = 1;
  955. start = cur;
  956. if (!TOR_ISPRINT(buf[cur]))
  957. buf[cur] = '.';
  958. }
  959. }
  960. }
  961. /* We are at the end of the line or end of string. If in_line is true there
  962. * is a line which starts at buf+start and ends at a NUL. cur points to
  963. * the character after the NUL. */
  964. if (in_line)
  965. smartlist_add(sl, (void *)(buf+start));
  966. in_line = 0;
  967. }
  968. return smartlist_len(sl);
  969. }
  970. #ifdef _WIN32
  971. /** Return a smartlist containing lines outputted from
  972. * <b>handle</b>. Return NULL on error, and set
  973. * <b>stream_status_out</b> appropriately. */
  974. MOCK_IMPL(smartlist_t *,
  975. tor_get_lines_from_handle, (HANDLE *handle,
  976. enum stream_status *stream_status_out))
  977. {
  978. int pos;
  979. char stdout_buf[600] = {0};
  980. smartlist_t *lines = NULL;
  981. tor_assert(stream_status_out);
  982. *stream_status_out = IO_STREAM_TERM;
  983. pos = tor_read_all_handle(handle, stdout_buf, sizeof(stdout_buf) - 1, NULL);
  984. if (pos < 0) {
  985. *stream_status_out = IO_STREAM_TERM;
  986. return NULL;
  987. }
  988. if (pos == 0) {
  989. *stream_status_out = IO_STREAM_EAGAIN;
  990. return NULL;
  991. }
  992. /* End with a null even if there isn't a \r\n at the end */
  993. /* TODO: What if this is a partial line? */
  994. stdout_buf[pos] = '\0';
  995. /* Split up the buffer */
  996. lines = smartlist_new();
  997. tor_split_lines(lines, stdout_buf, pos);
  998. /* Currently 'lines' is populated with strings residing on the
  999. stack. Replace them with their exact copies on the heap: */
  1000. SMARTLIST_FOREACH(lines, char *, line,
  1001. SMARTLIST_REPLACE_CURRENT(lines, line, tor_strdup(line)));
  1002. *stream_status_out = IO_STREAM_OKAY;
  1003. return lines;
  1004. }
  1005. #else /* !(defined(_WIN32)) */
  1006. /** Return a smartlist containing lines outputted from
  1007. * <b>fd</b>. Return NULL on error, and set
  1008. * <b>stream_status_out</b> appropriately. */
  1009. MOCK_IMPL(smartlist_t *,
  1010. tor_get_lines_from_handle, (int fd, enum stream_status *stream_status_out))
  1011. {
  1012. enum stream_status stream_status;
  1013. char stdout_buf[400];
  1014. smartlist_t *lines = NULL;
  1015. while (1) {
  1016. memset(stdout_buf, 0, sizeof(stdout_buf));
  1017. stream_status = get_string_from_pipe(fd,
  1018. stdout_buf, sizeof(stdout_buf) - 1);
  1019. if (stream_status != IO_STREAM_OKAY)
  1020. goto done;
  1021. if (!lines) lines = smartlist_new();
  1022. smartlist_split_string(lines, stdout_buf, "\n", 0, 0);
  1023. }
  1024. done:
  1025. *stream_status_out = stream_status;
  1026. return lines;
  1027. }
  1028. #endif /* defined(_WIN32) */
  1029. /** Reads from <b>fd</b> and stores input in <b>buf_out</b> making
  1030. * sure it's below <b>count</b> bytes.
  1031. * If the string has a trailing newline, we strip it off.
  1032. *
  1033. * This function is specifically created to handle input from managed
  1034. * proxies, according to the pluggable transports spec. Make sure it
  1035. * fits your needs before using it.
  1036. *
  1037. * Returns:
  1038. * IO_STREAM_CLOSED: If the stream is closed.
  1039. * IO_STREAM_EAGAIN: If there is nothing to read and we should check back
  1040. * later.
  1041. * IO_STREAM_TERM: If something is wrong with the stream.
  1042. * IO_STREAM_OKAY: If everything went okay and we got a string
  1043. * in <b>buf_out</b>. */
  1044. enum stream_status
  1045. get_string_from_pipe(int fd, char *buf_out, size_t count)
  1046. {
  1047. ssize_t ret;
  1048. tor_assert(count <= INT_MAX);
  1049. ret = read(fd, buf_out, count);
  1050. if (ret == 0)
  1051. return IO_STREAM_CLOSED;
  1052. else if (ret < 0 && errno == EAGAIN)
  1053. return IO_STREAM_EAGAIN;
  1054. else if (ret < 0)
  1055. return IO_STREAM_TERM;
  1056. if (buf_out[ret - 1] == '\n') {
  1057. /* Remove the trailing newline */
  1058. buf_out[ret - 1] = '\0';
  1059. } else
  1060. buf_out[ret] = '\0';
  1061. return IO_STREAM_OKAY;
  1062. }