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