process: New function process_run_capture().
[cascardo/ovs.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 = xcalloc(1, 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     fatal_signal_block();
205     pid = fork();
206     if (pid < 0) {
207         fatal_signal_unblock();
208         unblock_sigchld(&oldsigs);
209         VLOG_WARN("fork failed: %s", strerror(errno));
210         return errno;
211     } else if (pid) {
212         /* Running in parent process. */
213         *pp = process_register(argv[0], pid);
214         fatal_signal_unblock();
215         unblock_sigchld(&oldsigs);
216         return 0;
217     } else {
218         /* Running in child process. */
219         int fd_max = get_max_fds();
220         int fd;
221
222         fatal_signal_fork();
223         fatal_signal_unblock();
224         unblock_sigchld(&oldsigs);
225         for (fd = 0; fd < fd_max; fd++) {
226             if (is_member(fd, null_fds, n_null_fds)) {
227                 /* We can't use get_null_fd() here because we might have
228                  * already closed its fd. */
229                 int nullfd = open("/dev/null", O_RDWR);
230                 dup2(nullfd, fd);
231                 close(nullfd);
232             } else if (fd >= 3 && !is_member(fd, keep_fds, n_keep_fds)) {
233                 close(fd);
234             }
235         }
236         execvp(argv[0], argv);
237         fprintf(stderr, "execvp(\"%s\") failed: %s\n",
238                 argv[0], strerror(errno));
239         _exit(1);
240     }
241 }
242
243 /* Destroys process 'p'. */
244 void
245 process_destroy(struct process *p)
246 {
247     if (p) {
248         sigset_t oldsigs;
249
250         block_sigchld(&oldsigs);
251         list_remove(&p->node);
252         unblock_sigchld(&oldsigs);
253
254         free(p->name);
255         free(p);
256     }
257 }
258
259 /* Sends signal 'signr' to process 'p'.  Returns 0 if successful, otherwise a
260  * positive errno value. */
261 int
262 process_kill(const struct process *p, int signr)
263 {
264     return (p->exited ? ESRCH
265             : !kill(p->pid, signr) ? 0
266             : errno);
267 }
268
269 /* Returns the pid of process 'p'. */
270 pid_t
271 process_pid(const struct process *p)
272 {
273     return p->pid;
274 }
275
276 /* Returns the name of process 'p' (the name passed to process_start() with any
277  * leading directories stripped). */
278 const char *
279 process_name(const struct process *p)
280 {
281     return p->name;
282 }
283
284 /* Returns true if process 'p' has exited, false otherwise. */
285 bool
286 process_exited(struct process *p)
287 {
288     if (p->exited) {
289         return true;
290     } else {
291         char buf[_POSIX_PIPE_BUF];
292         read(fds[0], buf, sizeof buf);
293         return false;
294     }
295 }
296
297 /* Returns process 'p''s exit status, as reported by waitpid(2).
298  * process_status(p) may be called only after process_exited(p) has returned
299  * true. */
300 int
301 process_status(const struct process *p)
302 {
303     assert(p->exited);
304     return p->status;
305 }
306
307 int
308 process_run(char **argv,
309             const int keep_fds[], size_t n_keep_fds,
310             const int null_fds[], size_t n_null_fds,
311             int *status)
312 {
313     struct process *p;
314     int retval;
315
316     COVERAGE_INC(process_run);
317     retval = process_start(argv, keep_fds, n_keep_fds, null_fds, n_null_fds,
318                            &p);
319     if (retval) {
320         *status = 0;
321         return retval;
322     }
323
324     while (!process_exited(p)) {
325         process_wait(p);
326         poll_block();
327     }
328     *status = process_status(p);
329     process_destroy(p);
330     return 0;
331 }
332
333 /* Given 'status', which is a process status in the form reported by waitpid(2)
334  * and returned by process_status(), returns a string describing how the
335  * process terminated.  The caller is responsible for freeing the string when
336  * it is no longer needed. */
337 char *
338 process_status_msg(int status)
339 {
340     struct ds ds = DS_EMPTY_INITIALIZER;
341     if (WIFEXITED(status)) {
342         ds_put_format(&ds, "exit status %d", WEXITSTATUS(status));
343     } else if (WIFSIGNALED(status) || WIFSTOPPED(status)) {
344         int signr = WIFSIGNALED(status) ? WTERMSIG(status) : WSTOPSIG(status);
345         const char *name = NULL;
346 #ifdef HAVE_STRSIGNAL
347         name = strsignal(signr);
348 #endif
349         ds_put_format(&ds, "%s by signal %d",
350                       WIFSIGNALED(status) ? "killed" : "stopped", signr);
351         if (name) {
352             ds_put_format(&ds, " (%s)", name);
353         }
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     struct ds log;
404     int fds[2];
405 };
406
407 static int
408 stream_open(struct stream *s)
409 {
410     ds_init(&s->log);
411     if (pipe(s->fds)) {
412         VLOG_WARN("failed to create pipe: %s", strerror(errno));
413         return errno;
414     }
415     set_nonblocking(s->fds[0]);
416     return 0;
417 }
418
419 static void
420 stream_read(struct stream *s)
421 {
422     int error = 0;
423
424     if (s->fds[0] < 0) {
425         return;
426     }
427
428     error = 0;
429     for (;;) {
430         char buffer[512];
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 > PROCESS_MAX_CAPTURE) {
446             VLOG_WARN("subprocess output overflowed %d-byte buffer",
447                       PROCESS_MAX_CAPTURE);
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 PROCESS_MAX_CAPTURE 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                     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);
513     if (error) {
514         return error;
515     }
516
517     error = stream_open(&s_stderr);
518     if (error) {
519         stream_close(&s_stdout);
520         return error;
521     }
522
523     block_sigchld(&oldsigs);
524     fatal_signal_block();
525     pid = fork();
526     if (pid < 0) {
527         int error = errno;
528
529         fatal_signal_unblock();
530         unblock_sigchld(&oldsigs);
531         VLOG_WARN("fork failed: %s", strerror(error));
532
533         stream_close(&s_stdout);
534         stream_close(&s_stderr);
535         *status = 0;
536         return error;
537     } else if (pid) {
538         /* Running in parent process. */
539         struct process *p;
540
541         p = process_register(argv[0], pid);
542         fatal_signal_unblock();
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         fatal_signal_unblock();
579         unblock_sigchld(&oldsigs);
580
581         dup2(get_null_fd(), 0);
582         dup2(s_stdout.fds[1], 1);
583         dup2(s_stderr.fds[1], 2);
584
585         max_fds = get_max_fds();
586         for (i = 3; i < max_fds; i++) {
587             close(i);
588         }
589
590         execvp(argv[0], argv);
591         fprintf(stderr, "execvp(\"%s\") failed: %s\n",
592                 argv[0], strerror(errno));
593         exit(EXIT_FAILURE);
594     }
595 }
596 \f
597 static void
598 sigchld_handler(int signr UNUSED)
599 {
600     struct process *p;
601
602     COVERAGE_INC(process_sigchld);
603     LIST_FOR_EACH (p, struct process, node, &all_processes) {
604         if (!p->exited) {
605             int retval, status;
606             do {
607                 retval = waitpid(p->pid, &status, WNOHANG);
608             } while (retval == -1 && errno == EINTR);
609             if (retval == p->pid) {
610                 p->exited = true;
611                 p->status = status;
612             } else if (retval < 0) {
613                 /* XXX We want to log something but we're in a signal
614                  * handler. */
615                 p->exited = true;
616                 p->status = -1;
617             }
618         }
619     }
620     write(fds[1], "", 1);
621 }
622
623 static bool
624 is_member(int x, const int *array, size_t n)
625 {
626     size_t i;
627
628     for (i = 0; i < n; i++) {
629         if (array[i] == x) {
630             return true;
631         }
632     }
633     return false;
634 }
635
636 static bool
637 sigchld_is_blocked(void)
638 {
639     sigset_t sigs;
640     if (sigprocmask(SIG_SETMASK, NULL, &sigs)) {
641         ovs_fatal(errno, "sigprocmask");
642     }
643     return sigismember(&sigs, SIGCHLD);
644 }
645
646 static void
647 block_sigchld(sigset_t *oldsigs)
648 {
649     sigset_t sigchld;
650     sigemptyset(&sigchld);
651     sigaddset(&sigchld, SIGCHLD);
652     if (sigprocmask(SIG_BLOCK, &sigchld, oldsigs)) {
653         ovs_fatal(errno, "sigprocmask");
654     }
655 }
656
657 static void
658 unblock_sigchld(const sigset_t *oldsigs)
659 {
660     if (sigprocmask(SIG_SETMASK, oldsigs, NULL)) {
661         ovs_fatal(errno, "sigprocmask");
662     }
663 }