9f5c35f2489198e52ec2bcd3aa40fca5c76f9184
[sliver-openvswitch.git] / lib / process.c
1 /*
2  * Copyright (c) 2008, 2009, 2010, 2011, 2012 Nicira, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at:
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #include <config.h>
18 #include "process.h"
19 #include <assert.h>
20 #include <errno.h>
21 #include <fcntl.h>
22 #include <signal.h>
23 #include <stdlib.h>
24 #include <string.h>
25 #include <sys/stat.h>
26 #include <sys/wait.h>
27 #include <unistd.h>
28 #include "coverage.h"
29 #include "dynamic-string.h"
30 #include "fatal-signal.h"
31 #include "list.h"
32 #include "poll-loop.h"
33 #include "signals.h"
34 #include "socket-util.h"
35 #include "util.h"
36 #include "vlog.h"
37
38 VLOG_DEFINE_THIS_MODULE(process);
39
40 COVERAGE_DEFINE(process_run);
41 COVERAGE_DEFINE(process_run_capture);
42 COVERAGE_DEFINE(process_sigchld);
43 COVERAGE_DEFINE(process_start);
44
45 struct process {
46     struct list node;
47     char *name;
48     pid_t pid;
49
50     /* Modified by signal handler. */
51     volatile bool exited;
52     volatile int status;
53 };
54
55 /* Pipe used to signal child termination. */
56 static int fds[2];
57
58 /* All processes. */
59 static struct list all_processes = LIST_INITIALIZER(&all_processes);
60
61 static bool sigchld_is_blocked(void);
62 static void block_sigchld(sigset_t *);
63 static void unblock_sigchld(const sigset_t *);
64 static void sigchld_handler(int signr OVS_UNUSED);
65 static bool is_member(int x, const int *array, size_t);
66
67 /* Initializes the process subsystem (if it is not already initialized).  Calls
68  * exit() if initialization fails.
69  *
70  * Calling this function is optional; it will be called automatically by
71  * process_start() if necessary.  Calling it explicitly allows the client to
72  * prevent the process from exiting at an unexpected time. */
73 void
74 process_init(void)
75 {
76     static bool inited;
77     struct sigaction sa;
78
79     if (inited) {
80         return;
81     }
82     inited = true;
83
84     /* Create notification pipe. */
85     xpipe_nonblocking(fds);
86
87     /* Set up child termination signal handler. */
88     memset(&sa, 0, sizeof sa);
89     sa.sa_handler = sigchld_handler;
90     sigemptyset(&sa.sa_mask);
91     sa.sa_flags = SA_NOCLDSTOP | SA_RESTART;
92     xsigaction(SIGCHLD, &sa, NULL);
93 }
94
95 char *
96 process_escape_args(char **argv)
97 {
98     struct ds ds = DS_EMPTY_INITIALIZER;
99     char **argp;
100     for (argp = argv; *argp; argp++) {
101         const char *arg = *argp;
102         const char *p;
103         if (argp != argv) {
104             ds_put_char(&ds, ' ');
105         }
106         if (arg[strcspn(arg, " \t\r\n\v\\\'\"")]) {
107             ds_put_char(&ds, '"');
108             for (p = arg; *p; p++) {
109                 if (*p == '\\' || *p == '\"') {
110                     ds_put_char(&ds, '\\');
111                 }
112                 ds_put_char(&ds, *p);
113             }
114             ds_put_char(&ds, '"');
115         } else {
116             ds_put_cstr(&ds, arg);
117         }
118     }
119     return ds_cstr(&ds);
120 }
121
122 /* Prepare to start a process whose command-line arguments are given by the
123  * null-terminated 'argv' array.  Returns 0 if successful, otherwise a
124  * positive errno value. */
125 static int
126 process_prestart(char **argv)
127 {
128     char *binary;
129
130     process_init();
131
132     /* Log the process to be started. */
133     if (VLOG_IS_DBG_ENABLED()) {
134         char *args = process_escape_args(argv);
135         VLOG_DBG("starting subprocess: %s", args);
136         free(args);
137     }
138
139     /* execvp() will search PATH too, but the error in that case is more
140      * obscure, since it is only reported post-fork. */
141     binary = process_search_path(argv[0]);
142     if (!binary) {
143         VLOG_ERR("%s not found in PATH", argv[0]);
144         return ENOENT;
145     }
146     free(binary);
147
148     return 0;
149 }
150
151 /* Creates and returns a new struct process with the specified 'name' and
152  * 'pid'.
153  *
154  * This is racy unless SIGCHLD is blocked (and has been blocked since before
155  * the fork()) that created the subprocess.  */
156 static struct process *
157 process_register(const char *name, pid_t pid)
158 {
159     struct process *p;
160     const char *slash;
161
162     assert(sigchld_is_blocked());
163
164     p = xzalloc(sizeof *p);
165     p->pid = pid;
166     slash = strrchr(name, '/');
167     p->name = xstrdup(slash ? slash + 1 : name);
168     p->exited = false;
169
170     list_push_back(&all_processes, &p->node);
171
172     return p;
173 }
174
175 /* Starts a subprocess with the arguments in the null-terminated argv[] array.
176  * argv[0] is used as the name of the process.  Searches the PATH environment
177  * variable to find the program to execute.
178  *
179  * All file descriptors are closed before executing the subprocess, except for
180  * fds 0, 1, and 2 and the 'n_keep_fds' fds listed in 'keep_fds'.  Also, any of
181  * the 'n_null_fds' fds listed in 'null_fds' are replaced by /dev/null.
182  *
183  * Returns 0 if successful, otherwise a positive errno value indicating the
184  * error.  If successful, '*pp' is assigned a new struct process that may be
185  * used to query the process's status.  On failure, '*pp' is set to NULL. */
186 int
187 process_start(char **argv,
188               const int keep_fds[], size_t n_keep_fds,
189               const int null_fds[], size_t n_null_fds,
190               struct process **pp)
191 {
192     sigset_t oldsigs;
193     int nullfd;
194     pid_t pid;
195     int error;
196
197     *pp = NULL;
198     COVERAGE_INC(process_start);
199     error = process_prestart(argv);
200     if (error) {
201         return error;
202     }
203
204     if (n_null_fds) {
205         nullfd = get_null_fd();
206         if (nullfd < 0) {
207             return -nullfd;
208         }
209     } else {
210         nullfd = -1;
211     }
212
213     block_sigchld(&oldsigs);
214     pid = fork();
215     if (pid < 0) {
216         unblock_sigchld(&oldsigs);
217         VLOG_WARN("fork failed: %s", strerror(errno));
218         return errno;
219     } else if (pid) {
220         /* Running in parent process. */
221         *pp = process_register(argv[0], pid);
222         unblock_sigchld(&oldsigs);
223         return 0;
224     } else {
225         /* Running in child process. */
226         int fd_max = get_max_fds();
227         int fd;
228
229         fatal_signal_fork();
230         unblock_sigchld(&oldsigs);
231         for (fd = 0; fd < fd_max; fd++) {
232             if (is_member(fd, null_fds, n_null_fds)) {
233                 dup2(nullfd, fd);
234             } else if (fd >= 3 && fd != nullfd
235                        && !is_member(fd, keep_fds, n_keep_fds)) {
236                 close(fd);
237             }
238         }
239         if (nullfd >= 0
240             && !is_member(nullfd, keep_fds, n_keep_fds)
241             && !is_member(nullfd, null_fds, n_null_fds)) {
242             close(nullfd);
243         }
244         execvp(argv[0], argv);
245         fprintf(stderr, "execvp(\"%s\") failed: %s\n",
246                 argv[0], strerror(errno));
247         _exit(1);
248     }
249 }
250
251 /* Destroys process 'p'. */
252 void
253 process_destroy(struct process *p)
254 {
255     if (p) {
256         sigset_t oldsigs;
257
258         block_sigchld(&oldsigs);
259         list_remove(&p->node);
260         unblock_sigchld(&oldsigs);
261
262         free(p->name);
263         free(p);
264     }
265 }
266
267 /* Sends signal 'signr' to process 'p'.  Returns 0 if successful, otherwise a
268  * positive errno value. */
269 int
270 process_kill(const struct process *p, int signr)
271 {
272     return (p->exited ? ESRCH
273             : !kill(p->pid, signr) ? 0
274             : errno);
275 }
276
277 /* Returns the pid of process 'p'. */
278 pid_t
279 process_pid(const struct process *p)
280 {
281     return p->pid;
282 }
283
284 /* Returns the name of process 'p' (the name passed to process_start() with any
285  * leading directories stripped). */
286 const char *
287 process_name(const struct process *p)
288 {
289     return p->name;
290 }
291
292 /* Returns true if process 'p' has exited, false otherwise. */
293 bool
294 process_exited(struct process *p)
295 {
296     if (p->exited) {
297         return true;
298     } else {
299         char buf[_POSIX_PIPE_BUF];
300         ignore(read(fds[0], buf, sizeof buf));
301         return false;
302     }
303 }
304
305 /* Returns process 'p''s exit status, as reported by waitpid(2).
306  * process_status(p) may be called only after process_exited(p) has returned
307  * true. */
308 int
309 process_status(const struct process *p)
310 {
311     assert(p->exited);
312     return p->status;
313 }
314
315 int
316 process_run(char **argv,
317             const int keep_fds[], size_t n_keep_fds,
318             const int null_fds[], size_t n_null_fds,
319             int *status)
320 {
321     struct process *p;
322     int retval;
323
324     COVERAGE_INC(process_run);
325     retval = process_start(argv, keep_fds, n_keep_fds, null_fds, n_null_fds,
326                            &p);
327     if (retval) {
328         *status = 0;
329         return retval;
330     }
331
332     while (!process_exited(p)) {
333         process_wait(p);
334         poll_block();
335     }
336     *status = process_status(p);
337     process_destroy(p);
338     return 0;
339 }
340
341 /* Given 'status', which is a process status in the form reported by waitpid(2)
342  * and returned by process_status(), returns a string describing how the
343  * process terminated.  The caller is responsible for freeing the string when
344  * it is no longer needed. */
345 char *
346 process_status_msg(int status)
347 {
348     struct ds ds = DS_EMPTY_INITIALIZER;
349     if (WIFEXITED(status)) {
350         ds_put_format(&ds, "exit status %d", WEXITSTATUS(status));
351     } else if (WIFSIGNALED(status)) {
352         ds_put_format(&ds, "killed (%s)", signal_name(WTERMSIG(status)));
353     } else if (WIFSTOPPED(status)) {
354         ds_put_format(&ds, "stopped (%s)", signal_name(WSTOPSIG(status)));
355     } else {
356         ds_put_format(&ds, "terminated abnormally (%x)", status);
357     }
358     if (WCOREDUMP(status)) {
359         ds_put_cstr(&ds, ", core dumped");
360     }
361     return ds_cstr(&ds);
362 }
363
364 /* Causes the next call to poll_block() to wake up when process 'p' has
365  * exited. */
366 void
367 process_wait(struct process *p)
368 {
369     if (p->exited) {
370         poll_immediate_wake();
371     } else {
372         poll_fd_wait(fds[0], POLLIN);
373     }
374 }
375
376 char *
377 process_search_path(const char *name)
378 {
379     char *save_ptr = NULL;
380     char *path, *dir;
381     struct stat s;
382
383     if (strchr(name, '/') || !getenv("PATH")) {
384         return stat(name, &s) == 0 ? xstrdup(name) : NULL;
385     }
386
387     path = xstrdup(getenv("PATH"));
388     for (dir = strtok_r(path, ":", &save_ptr); dir;
389          dir = strtok_r(NULL, ":", &save_ptr)) {
390         char *file = xasprintf("%s/%s", dir, name);
391         if (stat(file, &s) == 0) {
392             free(path);
393             return file;
394         }
395         free(file);
396     }
397     free(path);
398     return NULL;
399 }
400 \f
401 /* process_run_capture() and supporting functions. */
402
403 struct stream {
404     size_t max_size;
405     struct ds log;
406     int fds[2];
407 };
408
409 static int
410 stream_open(struct stream *s, size_t max_size)
411 {
412     s->max_size = max_size;
413     ds_init(&s->log);
414     if (pipe(s->fds)) {
415         VLOG_WARN("failed to create pipe: %s", strerror(errno));
416         return errno;
417     }
418     set_nonblocking(s->fds[0]);
419     return 0;
420 }
421
422 static void
423 stream_read(struct stream *s)
424 {
425     if (s->fds[0] < 0) {
426         return;
427     }
428
429     for (;;) {
430         char buffer[512];
431         int error;
432         size_t n;
433
434         error = read_fully(s->fds[0], buffer, sizeof buffer, &n);
435         ds_put_buffer(&s->log, buffer, n);
436         if (error) {
437             if (error == EAGAIN || error == EWOULDBLOCK) {
438                 return;
439             } else {
440                 if (error != EOF) {
441                     VLOG_WARN("error reading subprocess pipe: %s",
442                               strerror(error));
443                 }
444                 break;
445             }
446         } else if (s->log.length > s->max_size) {
447             VLOG_WARN("subprocess output overflowed %zu-byte buffer",
448                       s->max_size);
449             break;
450         }
451     }
452     close(s->fds[0]);
453     s->fds[0] = -1;
454 }
455
456 static void
457 stream_wait(struct stream *s)
458 {
459     if (s->fds[0] >= 0) {
460         poll_fd_wait(s->fds[0], POLLIN);
461     }
462 }
463
464 static void
465 stream_close(struct stream *s)
466 {
467     ds_destroy(&s->log);
468     if (s->fds[0] >= 0) {
469         close(s->fds[0]);
470     }
471     if (s->fds[1] >= 0) {
472         close(s->fds[1]);
473     }
474 }
475
476 /* Starts the process whose arguments are given in the null-terminated array
477  * 'argv' and waits for it to exit.  On success returns 0 and stores the
478  * process exit value (suitable for passing to process_status_msg()) in
479  * '*status'.  On failure, returns a positive errno value and stores 0 in
480  * '*status'.
481  *
482  * If 'stdout_log' is nonnull, then the subprocess's output to stdout (up to a
483  * limit of 'log_max' bytes) is captured in a memory buffer, which
484  * when this function returns 0 is stored as a null-terminated string in
485  * '*stdout_log'.  The caller is responsible for freeing '*stdout_log' (by
486  * passing it to free()).  When this function returns an error, '*stdout_log'
487  * is set to NULL.
488  *
489  * If 'stderr_log' is nonnull, then it is treated like 'stdout_log' except
490  * that it captures the subprocess's output to stderr. */
491 int
492 process_run_capture(char **argv, char **stdout_log, char **stderr_log,
493                     size_t max_log, int *status)
494 {
495     struct stream s_stdout, s_stderr;
496     sigset_t oldsigs;
497     pid_t pid;
498     int error;
499
500     COVERAGE_INC(process_run_capture);
501     if (stdout_log) {
502         *stdout_log = NULL;
503     }
504     if (stderr_log) {
505         *stderr_log = NULL;
506     }
507     *status = 0;
508     error = process_prestart(argv);
509     if (error) {
510         return error;
511     }
512
513     error = stream_open(&s_stdout, max_log);
514     if (error) {
515         return error;
516     }
517
518     error = stream_open(&s_stderr, max_log);
519     if (error) {
520         stream_close(&s_stdout);
521         return error;
522     }
523
524     block_sigchld(&oldsigs);
525     pid = fork();
526     if (pid < 0) {
527         error = errno;
528
529         unblock_sigchld(&oldsigs);
530         VLOG_WARN("fork failed: %s", strerror(error));
531
532         stream_close(&s_stdout);
533         stream_close(&s_stderr);
534         *status = 0;
535         return error;
536     } else if (pid) {
537         /* Running in parent process. */
538         struct process *p;
539
540         p = process_register(argv[0], pid);
541         unblock_sigchld(&oldsigs);
542
543         close(s_stdout.fds[1]);
544         close(s_stderr.fds[1]);
545         while (!process_exited(p)) {
546             stream_read(&s_stdout);
547             stream_read(&s_stderr);
548
549             stream_wait(&s_stdout);
550             stream_wait(&s_stderr);
551             process_wait(p);
552             poll_block();
553         }
554         stream_read(&s_stdout);
555         stream_read(&s_stderr);
556
557         if (stdout_log) {
558             *stdout_log = ds_steal_cstr(&s_stdout.log);
559         }
560         if (stderr_log) {
561             *stderr_log = ds_steal_cstr(&s_stderr.log);
562         }
563
564         stream_close(&s_stdout);
565         stream_close(&s_stderr);
566
567         *status = process_status(p);
568         process_destroy(p);
569         return 0;
570     } else {
571         /* Running in child process. */
572         int max_fds;
573         int i;
574
575         fatal_signal_fork();
576         unblock_sigchld(&oldsigs);
577
578         dup2(get_null_fd(), 0);
579         dup2(s_stdout.fds[1], 1);
580         dup2(s_stderr.fds[1], 2);
581
582         max_fds = get_max_fds();
583         for (i = 3; i < max_fds; i++) {
584             close(i);
585         }
586
587         execvp(argv[0], argv);
588         fprintf(stderr, "execvp(\"%s\") failed: %s\n",
589                 argv[0], strerror(errno));
590         exit(EXIT_FAILURE);
591     }
592 }
593 \f
594 static void
595 sigchld_handler(int signr OVS_UNUSED)
596 {
597     struct process *p;
598
599     COVERAGE_INC(process_sigchld);
600     LIST_FOR_EACH (p, node, &all_processes) {
601         if (!p->exited) {
602             int retval, status;
603             do {
604                 retval = waitpid(p->pid, &status, WNOHANG);
605             } while (retval == -1 && errno == EINTR);
606             if (retval == p->pid) {
607                 p->exited = true;
608                 p->status = status;
609             } else if (retval < 0) {
610                 /* XXX We want to log something but we're in a signal
611                  * handler. */
612                 p->exited = true;
613                 p->status = -1;
614             }
615         }
616     }
617     ignore(write(fds[1], "", 1));
618 }
619
620 static bool
621 is_member(int x, const int *array, size_t n)
622 {
623     size_t i;
624
625     for (i = 0; i < n; i++) {
626         if (array[i] == x) {
627             return true;
628         }
629     }
630     return false;
631 }
632
633 static bool
634 sigchld_is_blocked(void)
635 {
636     sigset_t sigs;
637
638     xsigprocmask(SIG_SETMASK, NULL, &sigs);
639     return sigismember(&sigs, SIGCHLD);
640 }
641
642 static void
643 block_sigchld(sigset_t *oldsigs)
644 {
645     sigset_t sigchld;
646
647     sigemptyset(&sigchld);
648     sigaddset(&sigchld, SIGCHLD);
649     xsigprocmask(SIG_BLOCK, &sigchld, oldsigs);
650 }
651
652 static void
653 unblock_sigchld(const sigset_t *oldsigs)
654 {
655     xsigprocmask(SIG_SETMASK, oldsigs, NULL);
656 }