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