Import from old repository commit 61ef2b42a9c4ba8e1600f15bb0236765edc2ad45.
[cascardo/ovs.git] / lib / process.c
1 /*
2  * Copyright (c) 2008, 2009 Nicira Networks.
3  *
4  * Permission to use, copy, modify, and/or distribute this software for any
5  * purpose with or without fee is hereby granted, provided that the above
6  * copyright notice and this permission notice appear in all copies.
7  *
8  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
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 "list.h"
31 #include "poll-loop.h"
32 #include "socket-util.h"
33 #include "util.h"
34
35 #define THIS_MODULE VLM_process
36 #include "vlog.h"
37
38 struct process {
39     struct list node;
40     char *name;
41     pid_t pid;
42
43     /* Modified by signal handler. */
44     volatile bool exited;
45     volatile int status;
46 };
47
48 /* Pipe used to signal child termination. */
49 static int fds[2];
50
51 /* All processes. */
52 static struct list all_processes = LIST_INITIALIZER(&all_processes);
53
54 static void block_sigchld(sigset_t *);
55 static void unblock_sigchld(const sigset_t *);
56 static void sigchld_handler(int signr UNUSED);
57 static bool is_member(int x, const int *array, size_t);
58
59 /* Initializes the process subsystem (if it is not already initialized).  Calls
60  * exit() if initialization fails.
61  *
62  * Calling this function is optional; it will be called automatically by
63  * process_start() if necessary.  Calling it explicitly allows the client to
64  * prevent the process from exiting at an unexpected time. */
65 void
66 process_init(void)
67 {
68     static bool inited;
69     struct sigaction sa;
70
71     if (inited) {
72         return;
73     }
74     inited = true;
75
76     /* Create notification pipe. */
77     if (pipe(fds)) {
78         ovs_fatal(errno, "could not create pipe");
79     }
80     set_nonblocking(fds[0]);
81     set_nonblocking(fds[1]);
82
83     /* Set up child termination signal handler. */
84     memset(&sa, 0, sizeof sa);
85     sa.sa_handler = sigchld_handler;
86     sigemptyset(&sa.sa_mask);
87     sa.sa_flags = SA_NOCLDSTOP | SA_RESTART;
88     if (sigaction(SIGCHLD, &sa, NULL)) {
89         ovs_fatal(errno, "sigaction(SIGCHLD) failed");
90     }
91 }
92
93 char *
94 process_escape_args(char **argv)
95 {
96     struct ds ds = DS_EMPTY_INITIALIZER;
97     char **argp;
98     for (argp = argv; *argp; argp++) {
99         const char *arg = *argp;
100         const char *p;
101         if (argp != argv) {
102             ds_put_char(&ds, ' ');
103         }
104         if (arg[strcspn(arg, " \t\r\n\v\\")]) {
105             ds_put_char(&ds, '"');
106             for (p = arg; *p; p++) {
107                 if (*p == '\\' || *p == '\"') {
108                     ds_put_char(&ds, '\\');
109                 }
110                 ds_put_char(&ds, *p);
111             }
112             ds_put_char(&ds, '"');
113         } else {
114             ds_put_cstr(&ds, arg);
115         }
116     }
117     return ds_cstr(&ds);
118 }
119
120 /* Starts a subprocess with the arguments in the null-terminated argv[] array.
121  * argv[0] is used as the name of the process.  Searches the PATH environment
122  * variable to find the program to execute.
123  *
124  * All file descriptors are closed before executing the subprocess, except for
125  * fds 0, 1, and 2 and the 'n_keep_fds' fds listed in 'keep_fds'.  Also, any of
126  * the 'n_null_fds' fds listed in 'null_fds' are replaced by /dev/null.
127  *
128  * Returns 0 if successful, otherwise a positive errno value indicating the
129  * error.  If successful, '*pp' is assigned a new struct process that may be
130  * used to query the process's status.  On failure, '*pp' is set to NULL. */
131 int
132 process_start(char **argv,
133               const int keep_fds[], size_t n_keep_fds,
134               const int null_fds[], size_t n_null_fds,
135               struct process **pp)
136 {
137     sigset_t oldsigs;
138     char *binary;
139     pid_t pid;
140
141     *pp = NULL;
142     process_init();
143     COVERAGE_INC(process_start);
144
145     if (VLOG_IS_DBG_ENABLED()) {
146         char *args = process_escape_args(argv);
147         VLOG_DBG("starting subprocess: %s", args);
148         free(args);
149     }
150
151     /* execvp() will search PATH too, but the error in that case is more
152      * obscure, since it is only reported post-fork. */
153     binary = process_search_path(argv[0]);
154     if (!binary) {
155         VLOG_ERR("%s not found in PATH", argv[0]);
156         return ENOENT;
157     }
158     free(binary);
159
160     block_sigchld(&oldsigs);
161     pid = fork();
162     if (pid < 0) {
163         unblock_sigchld(&oldsigs);
164         VLOG_WARN("fork failed: %s", strerror(errno));
165         return errno;
166     } else if (pid) {
167         /* Running in parent process. */
168         struct process *p;
169         const char *slash;
170
171         p = xcalloc(1, sizeof *p);
172         p->pid = pid;
173         slash = strrchr(argv[0], '/');
174         p->name = xstrdup(slash ? slash + 1 : argv[0]);
175         p->exited = false;
176
177         list_push_back(&all_processes, &p->node);
178         unblock_sigchld(&oldsigs);
179
180         *pp = p;
181         return 0;
182     } else {
183         /* Running in child process. */
184         int fd_max = get_max_fds();
185         int fd;
186
187         unblock_sigchld(&oldsigs);
188         for (fd = 0; fd < fd_max; fd++) {
189             if (is_member(fd, null_fds, n_null_fds)) {
190                 int nullfd = open("/dev/null", O_RDWR);
191                 dup2(nullfd, fd);
192                 close(nullfd);
193             } else if (fd >= 3 && !is_member(fd, keep_fds, n_keep_fds)) {
194                 close(fd);
195             }
196         }
197         execvp(argv[0], argv);
198         fprintf(stderr, "execvp(\"%s\") failed: %s\n",
199                 argv[0], strerror(errno));
200         _exit(1);
201     }
202 }
203
204 /* Destroys process 'p'. */
205 void
206 process_destroy(struct process *p)
207 {
208     if (p) {
209         sigset_t oldsigs;
210
211         block_sigchld(&oldsigs);
212         list_remove(&p->node);
213         unblock_sigchld(&oldsigs);
214
215         free(p->name);
216         free(p);
217     }
218 }
219
220 /* Sends signal 'signr' to process 'p'.  Returns 0 if successful, otherwise a
221  * positive errno value. */
222 int
223 process_kill(const struct process *p, int signr)
224 {
225     return (p->exited ? ESRCH
226             : !kill(p->pid, signr) ? 0
227             : errno);
228 }
229
230 /* Returns the pid of process 'p'. */
231 pid_t
232 process_pid(const struct process *p)
233 {
234     return p->pid;
235 }
236
237 /* Returns the name of process 'p' (the name passed to process_start() with any
238  * leading directories stripped). */
239 const char *
240 process_name(const struct process *p)
241 {
242     return p->name;
243 }
244
245 /* Returns true if process 'p' has exited, false otherwise. */
246 bool
247 process_exited(struct process *p)
248 {
249     if (p->exited) {
250         return true;
251     } else {
252         char buf[_POSIX_PIPE_BUF];
253         read(fds[0], buf, sizeof buf);
254         return false;
255     }
256 }
257
258 /* Returns process 'p''s exit status, as reported by waitpid(2).
259  * process_status(p) may be called only after process_exited(p) has returned
260  * true. */
261 int
262 process_status(const struct process *p)
263 {
264     assert(p->exited);
265     return p->status;
266 }
267
268 int
269 process_run(char **argv,
270             const int keep_fds[], size_t n_keep_fds,
271             const int null_fds[], size_t n_null_fds,
272             int *status)
273 {
274     struct process *p;
275     int retval;
276
277     COVERAGE_INC(process_run);
278     retval = process_start(argv, keep_fds, n_keep_fds, null_fds, n_null_fds,
279                            &p);
280     if (retval) {
281         *status = 0;
282         return retval;
283     }
284
285     while (!process_exited(p)) {
286         process_wait(p);
287         poll_block();
288     }
289     *status = process_status(p);
290     process_destroy(p);
291     return 0;
292 }
293
294 /* Given 'status', which is a process status in the form reported by waitpid(2)
295  * and returned by process_status(), returns a string describing how the
296  * process terminated.  The caller is responsible for freeing the string when
297  * it is no longer needed. */
298 char *
299 process_status_msg(int status)
300 {
301     struct ds ds = DS_EMPTY_INITIALIZER;
302     if (WIFEXITED(status)) {
303         ds_put_format(&ds, "exit status %d", WEXITSTATUS(status));
304     } else if (WIFSIGNALED(status) || WIFSTOPPED(status)) {
305         int signr = WIFSIGNALED(status) ? WTERMSIG(status) : WSTOPSIG(status);
306         const char *name = NULL;
307 #ifdef HAVE_STRSIGNAL
308         name = strsignal(signr);
309 #endif
310         ds_put_format(&ds, "%s by signal %d",
311                       WIFSIGNALED(status) ? "killed" : "stopped", signr);
312         if (name) {
313             ds_put_format(&ds, " (%s)", name);
314         }
315     } else {
316         ds_put_format(&ds, "terminated abnormally (%x)", status);
317     }
318     if (WCOREDUMP(status)) {
319         ds_put_cstr(&ds, ", core dumped");
320     }
321     return ds_cstr(&ds);
322 }
323
324 /* Causes the next call to poll_block() to wake up when process 'p' has
325  * exited. */
326 void
327 process_wait(struct process *p)
328 {
329     if (p->exited) {
330         poll_immediate_wake();
331     } else {
332         poll_fd_wait(fds[0], POLLIN);
333     }
334 }
335
336 char *
337 process_search_path(const char *name)
338 {
339     char *save_ptr = NULL;
340     char *path, *dir;
341     struct stat s;
342
343     if (strchr(name, '/') || !getenv("PATH")) {
344         return stat(name, &s) == 0 ? xstrdup(name) : NULL;
345     }
346
347     path = xstrdup(getenv("PATH"));
348     for (dir = strtok_r(path, ":", &save_ptr); dir;
349          dir = strtok_r(NULL, ":", &save_ptr)) {
350         char *file = xasprintf("%s/%s", dir, name);
351         if (stat(file, &s) == 0) {
352             free(path);
353             return file;
354         }
355         free(file);
356     }
357     free(path);
358     return NULL;
359 }
360 \f
361 static void
362 sigchld_handler(int signr UNUSED)
363 {
364     struct process *p;
365
366     COVERAGE_INC(process_sigchld);
367     LIST_FOR_EACH (p, struct process, node, &all_processes) {
368         if (!p->exited) {
369             int retval, status;
370             do {
371                 retval = waitpid(p->pid, &status, WNOHANG);
372             } while (retval == -1 && errno == EINTR);
373             if (retval == p->pid) {
374                 p->exited = true;
375                 p->status = status;
376             } else if (retval < 0) {
377                 /* XXX We want to log something but we're in a signal
378                  * handler. */
379                 p->exited = true;
380                 p->status = -1;
381             }
382         }
383     }
384     write(fds[1], "", 1);
385 }
386
387 static bool
388 is_member(int x, const int *array, size_t n)
389 {
390     size_t i;
391
392     for (i = 0; i < n; i++) {
393         if (array[i] == x) {
394             return true;
395         }
396     }
397     return false;
398 }
399
400 static void
401 block_sigchld(sigset_t *oldsigs)
402 {
403     sigset_t sigchld;
404     sigemptyset(&sigchld);
405     sigaddset(&sigchld, SIGCHLD);
406     if (sigprocmask(SIG_BLOCK, &sigchld, oldsigs)) {
407         ovs_fatal(errno, "sigprocmask");
408     }
409 }
410
411 static void
412 unblock_sigchld(const sigset_t *oldsigs)
413 {
414     if (sigprocmask(SIG_SETMASK, oldsigs, NULL)) {
415         ovs_fatal(errno, "sigprocmask");
416     }
417 }