Prepare Open vSwitch 1.1.2 release.
[sliver-openvswitch.git] / lib / process.c
1 /*
2  * Copyright (c) 2008, 2009, 2010, 2011 Nicira Networks.
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     struct ds log;
407     int fds[2];
408 };
409
410 static int
411 stream_open(struct stream *s)
412 {
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 > PROCESS_MAX_CAPTURE) {
447             VLOG_WARN("subprocess output overflowed %d-byte buffer",
448                       PROCESS_MAX_CAPTURE);
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 PROCESS_MAX_CAPTURE 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                     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);
514     if (error) {
515         return error;
516     }
517
518     error = stream_open(&s_stderr);
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 }