fatal-signal: Run signal hooks outside of actual signal handlers.
[sliver-openvswitch.git] / lib / process.c
1 /*
2  * Copyright (c) 2008, 2009 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 "socket-util.h"
34 #include "util.h"
35
36 #define THIS_MODULE VLM_process
37 #include "vlog.h"
38
39 struct process {
40     struct list node;
41     char *name;
42     pid_t pid;
43
44     /* Modified by signal handler. */
45     volatile bool exited;
46     volatile int status;
47 };
48
49 /* Pipe used to signal child termination. */
50 static int fds[2];
51
52 /* All processes. */
53 static struct list all_processes = LIST_INITIALIZER(&all_processes);
54
55 static bool sigchld_is_blocked(void);
56 static void block_sigchld(sigset_t *);
57 static void unblock_sigchld(const sigset_t *);
58 static void sigchld_handler(int signr UNUSED);
59 static bool is_member(int x, const int *array, size_t);
60
61 /* Initializes the process subsystem (if it is not already initialized).  Calls
62  * exit() if initialization fails.
63  *
64  * Calling this function is optional; it will be called automatically by
65  * process_start() if necessary.  Calling it explicitly allows the client to
66  * prevent the process from exiting at an unexpected time. */
67 void
68 process_init(void)
69 {
70     static bool inited;
71     struct sigaction sa;
72
73     if (inited) {
74         return;
75     }
76     inited = true;
77
78     /* Create notification pipe. */
79     if (pipe(fds)) {
80         ovs_fatal(errno, "could not create pipe");
81     }
82     set_nonblocking(fds[0]);
83     set_nonblocking(fds[1]);
84
85     /* Set up child termination signal handler. */
86     memset(&sa, 0, sizeof sa);
87     sa.sa_handler = sigchld_handler;
88     sigemptyset(&sa.sa_mask);
89     sa.sa_flags = SA_NOCLDSTOP | SA_RESTART;
90     if (sigaction(SIGCHLD, &sa, NULL)) {
91         ovs_fatal(errno, "sigaction(SIGCHLD) failed");
92     }
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     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     block_sigchld(&oldsigs);
204     pid = fork();
205     if (pid < 0) {
206         unblock_sigchld(&oldsigs);
207         VLOG_WARN("fork failed: %s", strerror(errno));
208         return errno;
209     } else if (pid) {
210         /* Running in parent process. */
211         *pp = process_register(argv[0], pid);
212         unblock_sigchld(&oldsigs);
213         return 0;
214     } else {
215         /* Running in child process. */
216         int fd_max = get_max_fds();
217         int fd;
218
219         fatal_signal_fork();
220         unblock_sigchld(&oldsigs);
221         for (fd = 0; fd < fd_max; fd++) {
222             if (is_member(fd, null_fds, n_null_fds)) {
223                 /* We can't use get_null_fd() here because we might have
224                  * already closed its fd. */
225                 int nullfd = open("/dev/null", O_RDWR);
226                 dup2(nullfd, fd);
227                 close(nullfd);
228             } else if (fd >= 3 && !is_member(fd, keep_fds, n_keep_fds)) {
229                 close(fd);
230             }
231         }
232         execvp(argv[0], argv);
233         fprintf(stderr, "execvp(\"%s\") failed: %s\n",
234                 argv[0], strerror(errno));
235         _exit(1);
236     }
237 }
238
239 /* Destroys process 'p'. */
240 void
241 process_destroy(struct process *p)
242 {
243     if (p) {
244         sigset_t oldsigs;
245
246         block_sigchld(&oldsigs);
247         list_remove(&p->node);
248         unblock_sigchld(&oldsigs);
249
250         free(p->name);
251         free(p);
252     }
253 }
254
255 /* Sends signal 'signr' to process 'p'.  Returns 0 if successful, otherwise a
256  * positive errno value. */
257 int
258 process_kill(const struct process *p, int signr)
259 {
260     return (p->exited ? ESRCH
261             : !kill(p->pid, signr) ? 0
262             : errno);
263 }
264
265 /* Returns the pid of process 'p'. */
266 pid_t
267 process_pid(const struct process *p)
268 {
269     return p->pid;
270 }
271
272 /* Returns the name of process 'p' (the name passed to process_start() with any
273  * leading directories stripped). */
274 const char *
275 process_name(const struct process *p)
276 {
277     return p->name;
278 }
279
280 /* Returns true if process 'p' has exited, false otherwise. */
281 bool
282 process_exited(struct process *p)
283 {
284     if (p->exited) {
285         return true;
286     } else {
287         char buf[_POSIX_PIPE_BUF];
288         ignore(read(fds[0], buf, sizeof buf));
289         return false;
290     }
291 }
292
293 /* Returns process 'p''s exit status, as reported by waitpid(2).
294  * process_status(p) may be called only after process_exited(p) has returned
295  * true. */
296 int
297 process_status(const struct process *p)
298 {
299     assert(p->exited);
300     return p->status;
301 }
302
303 int
304 process_run(char **argv,
305             const int keep_fds[], size_t n_keep_fds,
306             const int null_fds[], size_t n_null_fds,
307             int *status)
308 {
309     struct process *p;
310     int retval;
311
312     COVERAGE_INC(process_run);
313     retval = process_start(argv, keep_fds, n_keep_fds, null_fds, n_null_fds,
314                            &p);
315     if (retval) {
316         *status = 0;
317         return retval;
318     }
319
320     while (!process_exited(p)) {
321         process_wait(p);
322         poll_block();
323     }
324     *status = process_status(p);
325     process_destroy(p);
326     return 0;
327 }
328
329 /* Given 'status', which is a process status in the form reported by waitpid(2)
330  * and returned by process_status(), returns a string describing how the
331  * process terminated.  The caller is responsible for freeing the string when
332  * it is no longer needed. */
333 char *
334 process_status_msg(int status)
335 {
336     struct ds ds = DS_EMPTY_INITIALIZER;
337     if (WIFEXITED(status)) {
338         ds_put_format(&ds, "exit status %d", WEXITSTATUS(status));
339     } else if (WIFSIGNALED(status) || WIFSTOPPED(status)) {
340         int signr = WIFSIGNALED(status) ? WTERMSIG(status) : WSTOPSIG(status);
341         const char *name = NULL;
342 #ifdef HAVE_STRSIGNAL
343         name = strsignal(signr);
344 #endif
345         ds_put_format(&ds, "%s by signal %d",
346                       WIFSIGNALED(status) ? "killed" : "stopped", signr);
347         if (name) {
348             ds_put_format(&ds, " (%s)", name);
349         }
350     } else {
351         ds_put_format(&ds, "terminated abnormally (%x)", status);
352     }
353     if (WCOREDUMP(status)) {
354         ds_put_cstr(&ds, ", core dumped");
355     }
356     return ds_cstr(&ds);
357 }
358
359 /* Causes the next call to poll_block() to wake up when process 'p' has
360  * exited. */
361 void
362 process_wait(struct process *p)
363 {
364     if (p->exited) {
365         poll_immediate_wake();
366     } else {
367         poll_fd_wait(fds[0], POLLIN);
368     }
369 }
370
371 char *
372 process_search_path(const char *name)
373 {
374     char *save_ptr = NULL;
375     char *path, *dir;
376     struct stat s;
377
378     if (strchr(name, '/') || !getenv("PATH")) {
379         return stat(name, &s) == 0 ? xstrdup(name) : NULL;
380     }
381
382     path = xstrdup(getenv("PATH"));
383     for (dir = strtok_r(path, ":", &save_ptr); dir;
384          dir = strtok_r(NULL, ":", &save_ptr)) {
385         char *file = xasprintf("%s/%s", dir, name);
386         if (stat(file, &s) == 0) {
387             free(path);
388             return file;
389         }
390         free(file);
391     }
392     free(path);
393     return NULL;
394 }
395 \f
396 /* process_run_capture() and supporting functions. */
397
398 struct stream {
399     struct ds log;
400     int fds[2];
401 };
402
403 static int
404 stream_open(struct stream *s)
405 {
406     ds_init(&s->log);
407     if (pipe(s->fds)) {
408         VLOG_WARN("failed to create pipe: %s", strerror(errno));
409         return errno;
410     }
411     set_nonblocking(s->fds[0]);
412     return 0;
413 }
414
415 static void
416 stream_read(struct stream *s)
417 {
418     int error = 0;
419
420     if (s->fds[0] < 0) {
421         return;
422     }
423
424     error = 0;
425     for (;;) {
426         char buffer[512];
427         size_t n;
428
429         error = read_fully(s->fds[0], buffer, sizeof buffer, &n);
430         ds_put_buffer(&s->log, buffer, n);
431         if (error) {
432             if (error == EAGAIN || error == EWOULDBLOCK) {
433                 return;
434             } else {
435                 if (error != EOF) {
436                     VLOG_WARN("error reading subprocess pipe: %s",
437                               strerror(error));
438                 }
439                 break;
440             }
441         } else if (s->log.length > PROCESS_MAX_CAPTURE) {
442             VLOG_WARN("subprocess output overflowed %d-byte buffer",
443                       PROCESS_MAX_CAPTURE);
444             break;
445         }
446     }
447     close(s->fds[0]);
448     s->fds[0] = -1;
449 }
450
451 static void
452 stream_wait(struct stream *s)
453 {
454     if (s->fds[0] >= 0) {
455         poll_fd_wait(s->fds[0], POLLIN);
456     }
457 }
458
459 static void
460 stream_close(struct stream *s)
461 {
462     ds_destroy(&s->log);
463     if (s->fds[0] >= 0) {
464         close(s->fds[0]);
465     }
466     if (s->fds[1] >= 0) {
467         close(s->fds[1]);
468     }
469 }
470
471 /* Starts the process whose arguments are given in the null-terminated array
472  * 'argv' and waits for it to exit.  On success returns 0 and stores the
473  * process exit value (suitable for passing to process_status_msg()) in
474  * '*status'.  On failure, returns a positive errno value and stores 0 in
475  * '*status'.
476  *
477  * If 'stdout_log' is nonnull, then the subprocess's output to stdout (up to a
478  * limit of PROCESS_MAX_CAPTURE bytes) is captured in a memory buffer, which
479  * when this function returns 0 is stored as a null-terminated string in
480  * '*stdout_log'.  The caller is responsible for freeing '*stdout_log' (by
481  * passing it to free()).  When this function returns an error, '*stdout_log'
482  * is set to NULL.
483  *
484  * If 'stderr_log' is nonnull, then it is treated like 'stdout_log' except
485  * that it captures the subprocess's output to stderr. */
486 int
487 process_run_capture(char **argv, char **stdout_log, char **stderr_log,
488                     int *status)
489 {
490     struct stream s_stdout, s_stderr;
491     sigset_t oldsigs;
492     pid_t pid;
493     int error;
494
495     COVERAGE_INC(process_run_capture);
496     if (stdout_log) {
497         *stdout_log = NULL;
498     }
499     if (stderr_log) {
500         *stderr_log = NULL;
501     }
502     *status = 0;
503     error = process_prestart(argv);
504     if (error) {
505         return error;
506     }
507
508     error = stream_open(&s_stdout);
509     if (error) {
510         return error;
511     }
512
513     error = stream_open(&s_stderr);
514     if (error) {
515         stream_close(&s_stdout);
516         return error;
517     }
518
519     block_sigchld(&oldsigs);
520     pid = fork();
521     if (pid < 0) {
522         int error = errno;
523
524         unblock_sigchld(&oldsigs);
525         VLOG_WARN("fork failed: %s", strerror(error));
526
527         stream_close(&s_stdout);
528         stream_close(&s_stderr);
529         *status = 0;
530         return error;
531     } else if (pid) {
532         /* Running in parent process. */
533         struct process *p;
534
535         p = process_register(argv[0], pid);
536         unblock_sigchld(&oldsigs);
537
538         close(s_stdout.fds[1]);
539         close(s_stderr.fds[1]);
540         while (!process_exited(p)) {
541             stream_read(&s_stdout);
542             stream_read(&s_stderr);
543
544             stream_wait(&s_stdout);
545             stream_wait(&s_stderr);
546             process_wait(p);
547             poll_block();
548         }
549         stream_read(&s_stdout);
550         stream_read(&s_stderr);
551
552         if (stdout_log) {
553             *stdout_log = ds_steal_cstr(&s_stdout.log);
554         }
555         if (stderr_log) {
556             *stderr_log = ds_steal_cstr(&s_stderr.log);
557         }
558
559         stream_close(&s_stdout);
560         stream_close(&s_stderr);
561
562         *status = process_status(p);
563         process_destroy(p);
564         return 0;
565     } else {
566         /* Running in child process. */
567         int max_fds;
568         int i;
569
570         fatal_signal_fork();
571         unblock_sigchld(&oldsigs);
572
573         dup2(get_null_fd(), 0);
574         dup2(s_stdout.fds[1], 1);
575         dup2(s_stderr.fds[1], 2);
576
577         max_fds = get_max_fds();
578         for (i = 3; i < max_fds; i++) {
579             close(i);
580         }
581
582         execvp(argv[0], argv);
583         fprintf(stderr, "execvp(\"%s\") failed: %s\n",
584                 argv[0], strerror(errno));
585         exit(EXIT_FAILURE);
586     }
587 }
588 \f
589 static void
590 sigchld_handler(int signr UNUSED)
591 {
592     struct process *p;
593
594     COVERAGE_INC(process_sigchld);
595     LIST_FOR_EACH (p, struct process, node, &all_processes) {
596         if (!p->exited) {
597             int retval, status;
598             do {
599                 retval = waitpid(p->pid, &status, WNOHANG);
600             } while (retval == -1 && errno == EINTR);
601             if (retval == p->pid) {
602                 p->exited = true;
603                 p->status = status;
604             } else if (retval < 0) {
605                 /* XXX We want to log something but we're in a signal
606                  * handler. */
607                 p->exited = true;
608                 p->status = -1;
609             }
610         }
611     }
612     ignore(write(fds[1], "", 1));
613 }
614
615 static bool
616 is_member(int x, const int *array, size_t n)
617 {
618     size_t i;
619
620     for (i = 0; i < n; i++) {
621         if (array[i] == x) {
622             return true;
623         }
624     }
625     return false;
626 }
627
628 static bool
629 sigchld_is_blocked(void)
630 {
631     sigset_t sigs;
632     if (sigprocmask(SIG_SETMASK, NULL, &sigs)) {
633         ovs_fatal(errno, "sigprocmask");
634     }
635     return sigismember(&sigs, SIGCHLD);
636 }
637
638 static void
639 block_sigchld(sigset_t *oldsigs)
640 {
641     sigset_t sigchld;
642     sigemptyset(&sigchld);
643     sigaddset(&sigchld, SIGCHLD);
644     if (sigprocmask(SIG_BLOCK, &sigchld, oldsigs)) {
645         ovs_fatal(errno, "sigprocmask");
646     }
647 }
648
649 static void
650 unblock_sigchld(const sigset_t *oldsigs)
651 {
652     if (sigprocmask(SIG_SETMASK, oldsigs, NULL)) {
653         ovs_fatal(errno, "sigprocmask");
654     }
655 }