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 
22 #include "uv.h"
23 #include "internal.h"
24 
25 #include <stdio.h>
26 #include <stdlib.h>
27 #include <assert.h>
28 #include <errno.h>
29 
30 #include <sys/types.h>
31 #include <sys/wait.h>
32 #include <unistd.h>
33 #include <fcntl.h>
34 #include <poll.h>
35 #include <sched.h>
36 
37 #if defined(__APPLE__) && !TARGET_OS_IPHONE
38 # include <crt_externs.h>
39 # define environ (*_NSGetEnviron())
40 #else
41 extern char **environ;
42 #endif
43 
44 #if defined(__linux__) || defined(__GLIBC__)
45 # include <grp.h>
46 #endif
47 
48 #ifndef CMAKE_BOOTSTRAP
49 #if defined(__linux__)
50 # define uv__cpu_set_t cpu_set_t
51 #elif defined(__FreeBSD__)
52 # include <sys/param.h>
53 # include <sys/cpuset.h>
54 # include <pthread_np.h>
55 # define uv__cpu_set_t cpuset_t
56 #endif
57 #endif
58 
uv__chld(uv_signal_t * handle,int signum)59 static void uv__chld(uv_signal_t* handle, int signum) {
60   uv_process_t* process;
61   uv_loop_t* loop;
62   int exit_status;
63   int term_signal;
64   int status;
65   pid_t pid;
66   QUEUE pending;
67   QUEUE* q;
68   QUEUE* h;
69 
70   assert(signum == SIGCHLD);
71 
72   QUEUE_INIT(&pending);
73   loop = handle->loop;
74 
75   h = &loop->process_handles;
76   q = QUEUE_HEAD(h);
77   while (q != h) {
78     process = QUEUE_DATA(q, uv_process_t, queue);
79     q = QUEUE_NEXT(q);
80 
81     do
82       pid = waitpid(process->pid, &status, WNOHANG);
83     while (pid == -1 && errno == EINTR);
84 
85     if (pid == 0)
86       continue;
87 
88     if (pid == -1) {
89       if (errno != ECHILD)
90         abort();
91       continue;
92     }
93 
94     process->status = status;
95     QUEUE_REMOVE(&process->queue);
96     QUEUE_INSERT_TAIL(&pending, &process->queue);
97   }
98 
99   h = &pending;
100   q = QUEUE_HEAD(h);
101   while (q != h) {
102     process = QUEUE_DATA(q, uv_process_t, queue);
103     q = QUEUE_NEXT(q);
104 
105     QUEUE_REMOVE(&process->queue);
106     QUEUE_INIT(&process->queue);
107     uv__handle_stop(process);
108 
109     if (process->exit_cb == NULL)
110       continue;
111 
112     exit_status = 0;
113     if (WIFEXITED(process->status))
114       exit_status = WEXITSTATUS(process->status);
115 
116     term_signal = 0;
117     if (WIFSIGNALED(process->status))
118       term_signal = WTERMSIG(process->status);
119 
120     process->exit_cb(process, exit_status, term_signal);
121   }
122   assert(QUEUE_EMPTY(&pending));
123 }
124 
125 
uv__make_socketpair(int fds[2])126 static int uv__make_socketpair(int fds[2]) {
127 #if defined(__FreeBSD__) || defined(__linux__)
128   if (socketpair(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0, fds))
129     return UV__ERR(errno);
130 
131   return 0;
132 #else
133   int err;
134 
135   if (socketpair(AF_UNIX, SOCK_STREAM, 0, fds))
136     return UV__ERR(errno);
137 
138   err = uv__cloexec(fds[0], 1);
139   if (err == 0)
140     err = uv__cloexec(fds[1], 1);
141 
142   if (err != 0) {
143     uv__close(fds[0]);
144     uv__close(fds[1]);
145     return UV__ERR(errno);
146   }
147 
148   return 0;
149 #endif
150 }
151 
152 
uv__make_pipe(int fds[2],int flags)153 int uv__make_pipe(int fds[2], int flags) {
154 #if defined(__FreeBSD__) || defined(__linux__)
155   if (pipe2(fds, flags | O_CLOEXEC))
156     return UV__ERR(errno);
157 
158   return 0;
159 #else
160   if (pipe(fds))
161     return UV__ERR(errno);
162 
163   if (uv__cloexec(fds[0], 1))
164     goto fail;
165 
166   if (uv__cloexec(fds[1], 1))
167     goto fail;
168 
169   if (flags & UV__F_NONBLOCK) {
170     if (uv__nonblock(fds[0], 1))
171       goto fail;
172 
173     if (uv__nonblock(fds[1], 1))
174       goto fail;
175   }
176 
177   return 0;
178 
179 fail:
180   uv__close(fds[0]);
181   uv__close(fds[1]);
182   return UV__ERR(errno);
183 #endif
184 }
185 
186 
187 /*
188  * Used for initializing stdio streams like options.stdin_stream. Returns
189  * zero on success. See also the cleanup section in uv_spawn().
190  */
uv__process_init_stdio(uv_stdio_container_t * container,int fds[2])191 static int uv__process_init_stdio(uv_stdio_container_t* container, int fds[2]) {
192   int mask;
193   int fd;
194 
195   mask = UV_IGNORE | UV_CREATE_PIPE | UV_INHERIT_FD | UV_INHERIT_STREAM;
196 
197   switch (container->flags & mask) {
198   case UV_IGNORE:
199     return 0;
200 
201   case UV_CREATE_PIPE:
202     assert(container->data.stream != NULL);
203     if (container->data.stream->type != UV_NAMED_PIPE)
204       return UV_EINVAL;
205     else
206       return uv__make_socketpair(fds);
207 
208   case UV_INHERIT_FD:
209   case UV_INHERIT_STREAM:
210     if (container->flags & UV_INHERIT_FD)
211       fd = container->data.fd;
212     else
213       fd = uv__stream_fd(container->data.stream);
214 
215     if (fd == -1)
216       return UV_EINVAL;
217 
218     fds[1] = fd;
219     return 0;
220 
221   default:
222     assert(0 && "Unexpected flags");
223     return UV_EINVAL;
224   }
225 }
226 
227 
uv__process_open_stream(uv_stdio_container_t * container,int pipefds[2])228 static int uv__process_open_stream(uv_stdio_container_t* container,
229                                    int pipefds[2]) {
230   int flags;
231   int err;
232 
233   if (!(container->flags & UV_CREATE_PIPE) || pipefds[0] < 0)
234     return 0;
235 
236   err = uv__close(pipefds[1]);
237   if (err != 0)
238     abort();
239 
240   pipefds[1] = -1;
241   uv__nonblock(pipefds[0], 1);
242 
243   flags = 0;
244   if (container->flags & UV_WRITABLE_PIPE)
245     flags |= UV_HANDLE_READABLE;
246   if (container->flags & UV_READABLE_PIPE)
247     flags |= UV_HANDLE_WRITABLE;
248 
249   return uv__stream_open(container->data.stream, pipefds[0], flags);
250 }
251 
252 
uv__process_close_stream(uv_stdio_container_t * container)253 static void uv__process_close_stream(uv_stdio_container_t* container) {
254   if (!(container->flags & UV_CREATE_PIPE)) return;
255   uv__stream_close(container->data.stream);
256 }
257 
258 
uv__write_int(int fd,int val)259 static void uv__write_int(int fd, int val) {
260   ssize_t n;
261 
262   do
263     n = write(fd, &val, sizeof(val));
264   while (n == -1 && errno == EINTR);
265 
266   if (n == -1 && errno == EPIPE)
267     return; /* parent process has quit */
268 
269   assert(n == sizeof(val));
270 }
271 
272 
273 #if !(defined(__APPLE__) && (TARGET_OS_TV || TARGET_OS_WATCH))
274 /* execvp is marked __WATCHOS_PROHIBITED __TVOS_PROHIBITED, so must be
275  * avoided. Since this isn't called on those targets, the function
276  * doesn't even need to be defined for them.
277  */
uv__process_child_init(const uv_process_options_t * options,int stdio_count,int (* pipes)[2],int error_fd)278 static void uv__process_child_init(const uv_process_options_t* options,
279                                    int stdio_count,
280                                    int (*pipes)[2],
281                                    int error_fd) {
282   sigset_t set;
283   int close_fd;
284   int use_fd;
285   int err;
286   int fd;
287   int n;
288 #ifndef CMAKE_BOOTSTRAP
289 #if defined(__linux__) || defined(__FreeBSD__)
290   int r;
291   int i;
292   int cpumask_size;
293   uv__cpu_set_t cpuset;
294 #endif
295 #endif
296 
297   if (options->flags & UV_PROCESS_DETACHED)
298     setsid();
299 
300   /* First duplicate low numbered fds, since it's not safe to duplicate them,
301    * they could get replaced. Example: swapping stdout and stderr; without
302    * this fd 2 (stderr) would be duplicated into fd 1, thus making both
303    * stdout and stderr go to the same fd, which was not the intention. */
304   for (fd = 0; fd < stdio_count; fd++) {
305     use_fd = pipes[fd][1];
306     if (use_fd < 0 || use_fd >= fd)
307       continue;
308     pipes[fd][1] = fcntl(use_fd, F_DUPFD, stdio_count);
309     if (pipes[fd][1] == -1) {
310       uv__write_int(error_fd, UV__ERR(errno));
311       _exit(127);
312     }
313   }
314 
315   for (fd = 0; fd < stdio_count; fd++) {
316     close_fd = pipes[fd][0];
317     use_fd = pipes[fd][1];
318 
319     if (use_fd < 0) {
320       if (fd >= 3)
321         continue;
322       else {
323         /* redirect stdin, stdout and stderr to /dev/null even if UV_IGNORE is
324          * set
325          */
326         use_fd = open("/dev/null", fd == 0 ? O_RDONLY : O_RDWR);
327         close_fd = use_fd;
328 
329         if (use_fd < 0) {
330           uv__write_int(error_fd, UV__ERR(errno));
331           _exit(127);
332         }
333       }
334     }
335 
336     if (fd == use_fd)
337       uv__cloexec_fcntl(use_fd, 0);
338     else
339       fd = dup2(use_fd, fd);
340 
341     if (fd == -1) {
342       uv__write_int(error_fd, UV__ERR(errno));
343       _exit(127);
344     }
345 
346     if (fd <= 2)
347       uv__nonblock_fcntl(fd, 0);
348 
349     if (close_fd >= stdio_count)
350       uv__close(close_fd);
351   }
352 
353   for (fd = 0; fd < stdio_count; fd++) {
354     use_fd = pipes[fd][1];
355 
356     if (use_fd >= stdio_count)
357       uv__close(use_fd);
358   }
359 
360   if (options->cwd != NULL && chdir(options->cwd)) {
361     uv__write_int(error_fd, UV__ERR(errno));
362     _exit(127);
363   }
364 
365   if (options->flags & (UV_PROCESS_SETUID | UV_PROCESS_SETGID)) {
366     /* When dropping privileges from root, the `setgroups` call will
367      * remove any extraneous groups. If we don't call this, then
368      * even though our uid has dropped, we may still have groups
369      * that enable us to do super-user things. This will fail if we
370      * aren't root, so don't bother checking the return value, this
371      * is just done as an optimistic privilege dropping function.
372      */
373     SAVE_ERRNO(setgroups(0, NULL));
374   }
375 
376   if ((options->flags & UV_PROCESS_SETGID) && setgid(options->gid)) {
377     uv__write_int(error_fd, UV__ERR(errno));
378     _exit(127);
379   }
380 
381   if ((options->flags & UV_PROCESS_SETUID) && setuid(options->uid)) {
382     uv__write_int(error_fd, UV__ERR(errno));
383     _exit(127);
384   }
385 
386 #ifndef CMAKE_BOOTSTRAP
387 #if defined(__linux__) || defined(__FreeBSD__)
388   if (options->cpumask != NULL) {
389     cpumask_size = uv_cpumask_size();
390     assert(options->cpumask_size >= (size_t)cpumask_size);
391 
392     CPU_ZERO(&cpuset);
393     for (i = 0; i < cpumask_size; ++i) {
394       if (options->cpumask[i]) {
395         CPU_SET(i, &cpuset);
396       }
397     }
398 
399     r = -pthread_setaffinity_np(pthread_self(), sizeof(cpuset), &cpuset);
400     if (r != 0) {
401       uv__write_int(error_fd, r);
402       _exit(127);
403     }
404   }
405 #endif
406 #endif
407 
408   if (options->env != NULL) {
409     environ = options->env;
410   }
411 
412   /* Reset signal disposition.  Use a hard-coded limit because NSIG
413    * is not fixed on Linux: it's either 32, 34 or 64, depending on
414    * whether RT signals are enabled.  We are not allowed to touch
415    * RT signal handlers, glibc uses them internally.
416    */
417   for (n = 1; n < 32; n += 1) {
418     if (n == SIGKILL || n == SIGSTOP)
419       continue;  /* Can't be changed. */
420 
421 #if defined(__HAIKU__)
422     if (n == SIGKILLTHR)
423       continue;  /* Can't be changed. */
424 #endif
425 
426     if (SIG_ERR != signal(n, SIG_DFL))
427       continue;
428 
429     uv__write_int(error_fd, UV__ERR(errno));
430     _exit(127);
431   }
432 
433   /* Reset signal mask. */
434   sigemptyset(&set);
435   err = pthread_sigmask(SIG_SETMASK, &set, NULL);
436 
437   if (err != 0) {
438     uv__write_int(error_fd, UV__ERR(err));
439     _exit(127);
440   }
441 
442   execvp(options->file, options->args);
443   uv__write_int(error_fd, UV__ERR(errno));
444   _exit(127);
445 }
446 #endif
447 
448 
uv_spawn(uv_loop_t * loop,uv_process_t * process,const uv_process_options_t * options)449 int uv_spawn(uv_loop_t* loop,
450              uv_process_t* process,
451              const uv_process_options_t* options) {
452 #if defined(__APPLE__) && (TARGET_OS_TV || TARGET_OS_WATCH)
453   /* fork is marked __WATCHOS_PROHIBITED __TVOS_PROHIBITED. */
454   return UV_ENOSYS;
455 #else
456   int signal_pipe[2] = { -1, -1 };
457   int pipes_storage[8][2];
458   int (*pipes)[2];
459   int stdio_count;
460   ssize_t r;
461   pid_t pid;
462   int err;
463   int exec_errorno;
464   int i;
465   int status;
466 
467   if (options->cpumask != NULL) {
468 #ifndef CMAKE_BOOTSTRAP
469 #if defined(__linux__) || defined(__FreeBSD__)
470     if (options->cpumask_size < (size_t)uv_cpumask_size()) {
471       return UV_EINVAL;
472     }
473 #else
474     return UV_ENOTSUP;
475 #endif
476 #else
477     return UV_ENOTSUP;
478 #endif
479   }
480 
481   assert(options->file != NULL);
482   assert(!(options->flags & ~(UV_PROCESS_DETACHED |
483                               UV_PROCESS_SETGID |
484                               UV_PROCESS_SETUID |
485                               UV_PROCESS_WINDOWS_HIDE |
486                               UV_PROCESS_WINDOWS_HIDE_CONSOLE |
487                               UV_PROCESS_WINDOWS_HIDE_GUI |
488                               UV_PROCESS_WINDOWS_VERBATIM_ARGUMENTS)));
489 
490   uv__handle_init(loop, (uv_handle_t*)process, UV_PROCESS);
491   QUEUE_INIT(&process->queue);
492 
493   stdio_count = options->stdio_count;
494   if (stdio_count < 3)
495     stdio_count = 3;
496 
497   err = UV_ENOMEM;
498   pipes = pipes_storage;
499   if (stdio_count > (int) ARRAY_SIZE(pipes_storage))
500     pipes = uv__malloc(stdio_count * sizeof(*pipes));
501 
502   if (pipes == NULL)
503     goto error;
504 
505   for (i = 0; i < stdio_count; i++) {
506     pipes[i][0] = -1;
507     pipes[i][1] = -1;
508   }
509 
510   for (i = 0; i < options->stdio_count; i++) {
511     err = uv__process_init_stdio(options->stdio + i, pipes[i]);
512     if (err)
513       goto error;
514   }
515 
516   /* This pipe is used by the parent to wait until
517    * the child has called `execve()`. We need this
518    * to avoid the following race condition:
519    *
520    *    if ((pid = fork()) > 0) {
521    *      kill(pid, SIGTERM);
522    *    }
523    *    else if (pid == 0) {
524    *      execve("/bin/cat", argp, envp);
525    *    }
526    *
527    * The parent sends a signal immediately after forking.
528    * Since the child may not have called `execve()` yet,
529    * there is no telling what process receives the signal,
530    * our fork or /bin/cat.
531    *
532    * To avoid ambiguity, we create a pipe with both ends
533    * marked close-on-exec. Then, after the call to `fork()`,
534    * the parent polls the read end until it EOFs or errors with EPIPE.
535    */
536   err = uv__make_pipe(signal_pipe, 0);
537   if (err)
538     goto error;
539 
540   uv_signal_start(&loop->child_watcher, uv__chld, SIGCHLD);
541 
542   /* Acquire write lock to prevent opening new fds in worker threads */
543   uv_rwlock_wrlock(&loop->cloexec_lock);
544   pid = fork();
545 
546   if (pid == -1) {
547     err = UV__ERR(errno);
548     uv_rwlock_wrunlock(&loop->cloexec_lock);
549     uv__close(signal_pipe[0]);
550     uv__close(signal_pipe[1]);
551     goto error;
552   }
553 
554   if (pid == 0) {
555     uv__process_child_init(options, stdio_count, pipes, signal_pipe[1]);
556     abort();
557   }
558 
559   /* Release lock in parent process */
560   uv_rwlock_wrunlock(&loop->cloexec_lock);
561   uv__close(signal_pipe[1]);
562 
563   process->status = 0;
564   exec_errorno = 0;
565   do
566     r = read(signal_pipe[0], &exec_errorno, sizeof(exec_errorno));
567   while (r == -1 && errno == EINTR);
568 
569   if (r == 0)
570     ; /* okay, EOF */
571   else if (r == sizeof(exec_errorno)) {
572     do
573       err = waitpid(pid, &status, 0); /* okay, read errorno */
574     while (err == -1 && errno == EINTR);
575     assert(err == pid);
576   } else if (r == -1 && errno == EPIPE) {
577     do
578       err = waitpid(pid, &status, 0); /* okay, got EPIPE */
579     while (err == -1 && errno == EINTR);
580     assert(err == pid);
581   } else
582     abort();
583 
584   uv__close_nocheckstdio(signal_pipe[0]);
585 
586   for (i = 0; i < options->stdio_count; i++) {
587     err = uv__process_open_stream(options->stdio + i, pipes[i]);
588     if (err == 0)
589       continue;
590 
591     while (i--)
592       uv__process_close_stream(options->stdio + i);
593 
594     goto error;
595   }
596 
597   /* Only activate this handle if exec() happened successfully */
598   if (exec_errorno == 0) {
599     QUEUE_INSERT_TAIL(&loop->process_handles, &process->queue);
600     uv__handle_start(process);
601   }
602 
603   process->pid = pid;
604   process->exit_cb = options->exit_cb;
605 
606   if (pipes != pipes_storage)
607     uv__free(pipes);
608 
609   return exec_errorno;
610 
611 error:
612   if (pipes != NULL) {
613     for (i = 0; i < stdio_count; i++) {
614       if (i < options->stdio_count)
615         if (options->stdio[i].flags & (UV_INHERIT_FD | UV_INHERIT_STREAM))
616           continue;
617       if (pipes[i][0] != -1)
618         uv__close_nocheckstdio(pipes[i][0]);
619       if (pipes[i][1] != -1)
620         uv__close_nocheckstdio(pipes[i][1]);
621     }
622 
623     if (pipes != pipes_storage)
624       uv__free(pipes);
625   }
626 
627   return err;
628 #endif
629 }
630 
631 
uv_process_kill(uv_process_t * process,int signum)632 int uv_process_kill(uv_process_t* process, int signum) {
633   return uv_kill(process->pid, signum);
634 }
635 
636 
uv_kill(int pid,int signum)637 int uv_kill(int pid, int signum) {
638   if (kill(pid, signum))
639     return UV__ERR(errno);
640   else
641     return 0;
642 }
643 
644 
uv__process_close(uv_process_t * handle)645 void uv__process_close(uv_process_t* handle) {
646   QUEUE_REMOVE(&handle->queue);
647   uv__handle_stop(handle);
648   if (QUEUE_EMPTY(&handle->loop->process_handles))
649     uv_signal_stop(&handle->loop->child_watcher);
650 }
651