subprocess.c 36 KB

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