1
0

process.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596
  1. /* Copyright Joyent, Inc. and other Node contributors. All rights reserved.
  2. *
  3. * Permission is hereby granted, free of charge, to any person obtaining a copy
  4. * of this software and associated documentation files (the "Software"), to
  5. * deal in the Software without restriction, including without limitation the
  6. * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
  7. * sell copies of the Software, and to permit persons to whom the Software is
  8. * furnished to do so, subject to the following conditions:
  9. *
  10. * The above copyright notice and this permission notice shall be included in
  11. * all copies or substantial portions of the Software.
  12. *
  13. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  14. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  15. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  16. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  17. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  18. * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  19. * IN THE SOFTWARE.
  20. */
  21. #include "uv.h"
  22. #include "internal.h"
  23. #include <stdio.h>
  24. #include <stdlib.h>
  25. #include <assert.h>
  26. #include <errno.h>
  27. #include <sys/types.h>
  28. #include <sys/wait.h>
  29. #include <unistd.h>
  30. #include <fcntl.h>
  31. #include <poll.h>
  32. #if defined(__APPLE__) && !TARGET_OS_IPHONE
  33. # include <crt_externs.h>
  34. # define environ (*_NSGetEnviron())
  35. #else
  36. extern char **environ;
  37. #endif
  38. #if defined(__linux__) || defined(__GLIBC__)
  39. # include <grp.h>
  40. #endif
  41. static void uv__chld(uv_signal_t* handle, int signum) {
  42. uv_process_t* process;
  43. uv_loop_t* loop;
  44. int exit_status;
  45. int term_signal;
  46. int status;
  47. pid_t pid;
  48. QUEUE pending;
  49. QUEUE* q;
  50. QUEUE* h;
  51. assert(signum == SIGCHLD);
  52. QUEUE_INIT(&pending);
  53. loop = handle->loop;
  54. h = &loop->process_handles;
  55. q = QUEUE_HEAD(h);
  56. while (q != h) {
  57. process = QUEUE_DATA(q, uv_process_t, queue);
  58. q = QUEUE_NEXT(q);
  59. do
  60. pid = waitpid(process->pid, &status, WNOHANG);
  61. while (pid == -1 && errno == EINTR);
  62. if (pid == 0)
  63. continue;
  64. if (pid == -1) {
  65. if (errno != ECHILD)
  66. abort();
  67. continue;
  68. }
  69. process->status = status;
  70. QUEUE_REMOVE(&process->queue);
  71. QUEUE_INSERT_TAIL(&pending, &process->queue);
  72. }
  73. h = &pending;
  74. q = QUEUE_HEAD(h);
  75. while (q != h) {
  76. process = QUEUE_DATA(q, uv_process_t, queue);
  77. q = QUEUE_NEXT(q);
  78. QUEUE_REMOVE(&process->queue);
  79. QUEUE_INIT(&process->queue);
  80. uv__handle_stop(process);
  81. if (process->exit_cb == NULL)
  82. continue;
  83. exit_status = 0;
  84. if (WIFEXITED(process->status))
  85. exit_status = WEXITSTATUS(process->status);
  86. term_signal = 0;
  87. if (WIFSIGNALED(process->status))
  88. term_signal = WTERMSIG(process->status);
  89. process->exit_cb(process, exit_status, term_signal);
  90. }
  91. assert(QUEUE_EMPTY(&pending));
  92. }
  93. int uv__make_socketpair(int fds[2], int flags) {
  94. #if defined(__linux__)
  95. static int no_cloexec;
  96. if (no_cloexec)
  97. goto skip;
  98. if (socketpair(AF_UNIX, SOCK_STREAM | UV__SOCK_CLOEXEC | flags, 0, fds) == 0)
  99. return 0;
  100. /* Retry on EINVAL, it means SOCK_CLOEXEC is not supported.
  101. * Anything else is a genuine error.
  102. */
  103. if (errno != EINVAL)
  104. return UV__ERR(errno);
  105. no_cloexec = 1;
  106. skip:
  107. #endif
  108. if (socketpair(AF_UNIX, SOCK_STREAM, 0, fds))
  109. return UV__ERR(errno);
  110. uv__cloexec(fds[0], 1);
  111. uv__cloexec(fds[1], 1);
  112. if (flags & UV__F_NONBLOCK) {
  113. uv__nonblock(fds[0], 1);
  114. uv__nonblock(fds[1], 1);
  115. }
  116. return 0;
  117. }
  118. int uv__make_pipe(int fds[2], int flags) {
  119. #if defined(__linux__)
  120. static int no_pipe2;
  121. if (no_pipe2)
  122. goto skip;
  123. if (uv__pipe2(fds, flags | UV__O_CLOEXEC) == 0)
  124. return 0;
  125. if (errno != ENOSYS)
  126. return UV__ERR(errno);
  127. no_pipe2 = 1;
  128. skip:
  129. #endif
  130. if (pipe(fds))
  131. return UV__ERR(errno);
  132. uv__cloexec(fds[0], 1);
  133. uv__cloexec(fds[1], 1);
  134. if (flags & UV__F_NONBLOCK) {
  135. uv__nonblock(fds[0], 1);
  136. uv__nonblock(fds[1], 1);
  137. }
  138. return 0;
  139. }
  140. /*
  141. * Used for initializing stdio streams like options.stdin_stream. Returns
  142. * zero on success. See also the cleanup section in uv_spawn().
  143. */
  144. static int uv__process_init_stdio(uv_stdio_container_t* container, int fds[2]) {
  145. int mask;
  146. int fd;
  147. mask = UV_IGNORE | UV_CREATE_PIPE | UV_INHERIT_FD | UV_INHERIT_STREAM;
  148. switch (container->flags & mask) {
  149. case UV_IGNORE:
  150. return 0;
  151. case UV_CREATE_PIPE:
  152. assert(container->data.stream != NULL);
  153. if (container->data.stream->type != UV_NAMED_PIPE)
  154. return UV_EINVAL;
  155. else
  156. return uv__make_socketpair(fds, 0);
  157. case UV_INHERIT_FD:
  158. case UV_INHERIT_STREAM:
  159. if (container->flags & UV_INHERIT_FD)
  160. fd = container->data.fd;
  161. else
  162. fd = uv__stream_fd(container->data.stream);
  163. if (fd == -1)
  164. return UV_EINVAL;
  165. fds[1] = fd;
  166. return 0;
  167. default:
  168. assert(0 && "Unexpected flags");
  169. return UV_EINVAL;
  170. }
  171. }
  172. static int uv__process_open_stream(uv_stdio_container_t* container,
  173. int pipefds[2]) {
  174. int flags;
  175. int err;
  176. if (!(container->flags & UV_CREATE_PIPE) || pipefds[0] < 0)
  177. return 0;
  178. err = uv__close(pipefds[1]);
  179. if (err != 0)
  180. abort();
  181. pipefds[1] = -1;
  182. uv__nonblock(pipefds[0], 1);
  183. flags = 0;
  184. if (container->flags & UV_WRITABLE_PIPE)
  185. flags |= UV_HANDLE_READABLE;
  186. if (container->flags & UV_READABLE_PIPE)
  187. flags |= UV_HANDLE_WRITABLE;
  188. return uv__stream_open(container->data.stream, pipefds[0], flags);
  189. }
  190. static void uv__process_close_stream(uv_stdio_container_t* container) {
  191. if (!(container->flags & UV_CREATE_PIPE)) return;
  192. uv__stream_close((uv_stream_t*)container->data.stream);
  193. }
  194. static void uv__write_int(int fd, int val) {
  195. ssize_t n;
  196. do
  197. n = write(fd, &val, sizeof(val));
  198. while (n == -1 && errno == EINTR);
  199. if (n == -1 && errno == EPIPE)
  200. return; /* parent process has quit */
  201. assert(n == sizeof(val));
  202. }
  203. #if !(defined(__APPLE__) && (TARGET_OS_TV || TARGET_OS_WATCH))
  204. /* execvp is marked __WATCHOS_PROHIBITED __TVOS_PROHIBITED, so must be
  205. * avoided. Since this isn't called on those targets, the function
  206. * doesn't even need to be defined for them.
  207. */
  208. static void uv__process_child_init(const uv_process_options_t* options,
  209. int stdio_count,
  210. int (*pipes)[2],
  211. int error_fd) {
  212. sigset_t set;
  213. int close_fd;
  214. int use_fd;
  215. int err;
  216. int fd;
  217. int n;
  218. if (options->flags & UV_PROCESS_DETACHED)
  219. setsid();
  220. /* First duplicate low numbered fds, since it's not safe to duplicate them,
  221. * they could get replaced. Example: swapping stdout and stderr; without
  222. * this fd 2 (stderr) would be duplicated into fd 1, thus making both
  223. * stdout and stderr go to the same fd, which was not the intention. */
  224. for (fd = 0; fd < stdio_count; fd++) {
  225. use_fd = pipes[fd][1];
  226. if (use_fd < 0 || use_fd >= fd)
  227. continue;
  228. pipes[fd][1] = fcntl(use_fd, F_DUPFD, stdio_count);
  229. if (pipes[fd][1] == -1) {
  230. uv__write_int(error_fd, UV__ERR(errno));
  231. _exit(127);
  232. }
  233. }
  234. for (fd = 0; fd < stdio_count; fd++) {
  235. close_fd = pipes[fd][0];
  236. use_fd = pipes[fd][1];
  237. if (use_fd < 0) {
  238. if (fd >= 3)
  239. continue;
  240. else {
  241. /* redirect stdin, stdout and stderr to /dev/null even if UV_IGNORE is
  242. * set
  243. */
  244. use_fd = open("/dev/null", fd == 0 ? O_RDONLY : O_RDWR);
  245. close_fd = use_fd;
  246. if (use_fd == -1) {
  247. uv__write_int(error_fd, UV__ERR(errno));
  248. _exit(127);
  249. }
  250. }
  251. }
  252. if (fd == use_fd)
  253. uv__cloexec_fcntl(use_fd, 0);
  254. else
  255. fd = dup2(use_fd, fd);
  256. if (fd == -1) {
  257. uv__write_int(error_fd, UV__ERR(errno));
  258. _exit(127);
  259. }
  260. if (fd <= 2)
  261. uv__nonblock_fcntl(fd, 0);
  262. if (close_fd >= stdio_count)
  263. uv__close(close_fd);
  264. }
  265. for (fd = 0; fd < stdio_count; fd++) {
  266. use_fd = pipes[fd][1];
  267. if (use_fd >= stdio_count)
  268. uv__close(use_fd);
  269. }
  270. if (options->cwd != NULL && chdir(options->cwd)) {
  271. uv__write_int(error_fd, UV__ERR(errno));
  272. _exit(127);
  273. }
  274. if (options->flags & (UV_PROCESS_SETUID | UV_PROCESS_SETGID)) {
  275. /* When dropping privileges from root, the `setgroups` call will
  276. * remove any extraneous groups. If we don't call this, then
  277. * even though our uid has dropped, we may still have groups
  278. * that enable us to do super-user things. This will fail if we
  279. * aren't root, so don't bother checking the return value, this
  280. * is just done as an optimistic privilege dropping function.
  281. */
  282. SAVE_ERRNO(setgroups(0, NULL));
  283. }
  284. if ((options->flags & UV_PROCESS_SETGID) && setgid(options->gid)) {
  285. uv__write_int(error_fd, UV__ERR(errno));
  286. _exit(127);
  287. }
  288. if ((options->flags & UV_PROCESS_SETUID) && setuid(options->uid)) {
  289. uv__write_int(error_fd, UV__ERR(errno));
  290. _exit(127);
  291. }
  292. if (options->env != NULL) {
  293. environ = options->env;
  294. }
  295. /* Reset signal disposition. Use a hard-coded limit because NSIG
  296. * is not fixed on Linux: it's either 32, 34 or 64, depending on
  297. * whether RT signals are enabled. We are not allowed to touch
  298. * RT signal handlers, glibc uses them internally.
  299. */
  300. for (n = 1; n < 32; n += 1) {
  301. if (n == SIGKILL || n == SIGSTOP)
  302. continue; /* Can't be changed. */
  303. if (SIG_ERR != signal(n, SIG_DFL))
  304. continue;
  305. uv__write_int(error_fd, UV__ERR(errno));
  306. _exit(127);
  307. }
  308. /* Reset signal mask. */
  309. sigemptyset(&set);
  310. err = pthread_sigmask(SIG_SETMASK, &set, NULL);
  311. if (err != 0) {
  312. uv__write_int(error_fd, UV__ERR(err));
  313. _exit(127);
  314. }
  315. execvp(options->file, options->args);
  316. uv__write_int(error_fd, UV__ERR(errno));
  317. _exit(127);
  318. }
  319. #endif
  320. int uv_spawn(uv_loop_t* loop,
  321. uv_process_t* process,
  322. const uv_process_options_t* options) {
  323. #if defined(__APPLE__) && (TARGET_OS_TV || TARGET_OS_WATCH)
  324. /* fork is marked __WATCHOS_PROHIBITED __TVOS_PROHIBITED. */
  325. return UV_ENOSYS;
  326. #else
  327. int signal_pipe[2] = { -1, -1 };
  328. int pipes_storage[8][2];
  329. int (*pipes)[2];
  330. int stdio_count;
  331. ssize_t r;
  332. pid_t pid;
  333. int err;
  334. int exec_errorno;
  335. int i;
  336. int status;
  337. assert(options->file != NULL);
  338. assert(!(options->flags & ~(UV_PROCESS_DETACHED |
  339. UV_PROCESS_SETGID |
  340. UV_PROCESS_SETUID |
  341. UV_PROCESS_WINDOWS_HIDE |
  342. UV_PROCESS_WINDOWS_VERBATIM_ARGUMENTS)));
  343. uv__handle_init(loop, (uv_handle_t*)process, UV_PROCESS);
  344. QUEUE_INIT(&process->queue);
  345. stdio_count = options->stdio_count;
  346. if (stdio_count < 3)
  347. stdio_count = 3;
  348. err = UV_ENOMEM;
  349. pipes = pipes_storage;
  350. if (stdio_count > (int) ARRAY_SIZE(pipes_storage))
  351. pipes = uv__malloc(stdio_count * sizeof(*pipes));
  352. if (pipes == NULL)
  353. goto error;
  354. for (i = 0; i < stdio_count; i++) {
  355. pipes[i][0] = -1;
  356. pipes[i][1] = -1;
  357. }
  358. for (i = 0; i < options->stdio_count; i++) {
  359. err = uv__process_init_stdio(options->stdio + i, pipes[i]);
  360. if (err)
  361. goto error;
  362. }
  363. /* This pipe is used by the parent to wait until
  364. * the child has called `execve()`. We need this
  365. * to avoid the following race condition:
  366. *
  367. * if ((pid = fork()) > 0) {
  368. * kill(pid, SIGTERM);
  369. * }
  370. * else if (pid == 0) {
  371. * execve("/bin/cat", argp, envp);
  372. * }
  373. *
  374. * The parent sends a signal immediately after forking.
  375. * Since the child may not have called `execve()` yet,
  376. * there is no telling what process receives the signal,
  377. * our fork or /bin/cat.
  378. *
  379. * To avoid ambiguity, we create a pipe with both ends
  380. * marked close-on-exec. Then, after the call to `fork()`,
  381. * the parent polls the read end until it EOFs or errors with EPIPE.
  382. */
  383. err = uv__make_pipe(signal_pipe, 0);
  384. if (err)
  385. goto error;
  386. uv_signal_start(&loop->child_watcher, uv__chld, SIGCHLD);
  387. /* Acquire write lock to prevent opening new fds in worker threads */
  388. uv_rwlock_wrlock(&loop->cloexec_lock);
  389. pid = fork();
  390. if (pid == -1) {
  391. err = UV__ERR(errno);
  392. uv_rwlock_wrunlock(&loop->cloexec_lock);
  393. uv__close(signal_pipe[0]);
  394. uv__close(signal_pipe[1]);
  395. goto error;
  396. }
  397. if (pid == 0) {
  398. uv__process_child_init(options, stdio_count, pipes, signal_pipe[1]);
  399. abort();
  400. }
  401. /* Release lock in parent process */
  402. uv_rwlock_wrunlock(&loop->cloexec_lock);
  403. uv__close(signal_pipe[1]);
  404. process->status = 0;
  405. exec_errorno = 0;
  406. do
  407. r = read(signal_pipe[0], &exec_errorno, sizeof(exec_errorno));
  408. while (r == -1 && errno == EINTR);
  409. if (r == 0)
  410. ; /* okay, EOF */
  411. else if (r == sizeof(exec_errorno)) {
  412. do
  413. err = waitpid(pid, &status, 0); /* okay, read errorno */
  414. while (err == -1 && errno == EINTR);
  415. assert(err == pid);
  416. } else if (r == -1 && errno == EPIPE) {
  417. do
  418. err = waitpid(pid, &status, 0); /* okay, got EPIPE */
  419. while (err == -1 && errno == EINTR);
  420. assert(err == pid);
  421. } else
  422. abort();
  423. uv__close_nocheckstdio(signal_pipe[0]);
  424. for (i = 0; i < options->stdio_count; i++) {
  425. err = uv__process_open_stream(options->stdio + i, pipes[i]);
  426. if (err == 0)
  427. continue;
  428. while (i--)
  429. uv__process_close_stream(options->stdio + i);
  430. goto error;
  431. }
  432. /* Only activate this handle if exec() happened successfully */
  433. if (exec_errorno == 0) {
  434. QUEUE_INSERT_TAIL(&loop->process_handles, &process->queue);
  435. uv__handle_start(process);
  436. }
  437. process->pid = pid;
  438. process->exit_cb = options->exit_cb;
  439. if (pipes != pipes_storage)
  440. uv__free(pipes);
  441. return exec_errorno;
  442. error:
  443. if (pipes != NULL) {
  444. for (i = 0; i < stdio_count; i++) {
  445. if (i < options->stdio_count)
  446. if (options->stdio[i].flags & (UV_INHERIT_FD | UV_INHERIT_STREAM))
  447. continue;
  448. if (pipes[i][0] != -1)
  449. uv__close_nocheckstdio(pipes[i][0]);
  450. if (pipes[i][1] != -1)
  451. uv__close_nocheckstdio(pipes[i][1]);
  452. }
  453. if (pipes != pipes_storage)
  454. uv__free(pipes);
  455. }
  456. return err;
  457. #endif
  458. }
  459. int uv_process_kill(uv_process_t* process, int signum) {
  460. return uv_kill(process->pid, signum);
  461. }
  462. int uv_kill(int pid, int signum) {
  463. if (kill(pid, signum))
  464. return UV__ERR(errno);
  465. else
  466. return 0;
  467. }
  468. void uv__process_close(uv_process_t* handle) {
  469. QUEUE_REMOVE(&handle->queue);
  470. uv__handle_stop(handle);
  471. if (QUEUE_EMPTY(&handle->loop->process_handles))
  472. uv_signal_stop(&handle->loop->child_watcher);
  473. }