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