Add function get_null_fd(), to reduce code redundancy.
[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 "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                 /* We can't use get_null_fd() here because we might have
191                  * already closed its fd. */
192                 int nullfd = open("/dev/null", O_RDWR);
193                 dup2(nullfd, fd);
194                 close(nullfd);
195             } else if (fd >= 3 && !is_member(fd, keep_fds, n_keep_fds)) {
196                 close(fd);
197             }
198         }
199         execvp(argv[0], argv);
200         fprintf(stderr, "execvp(\"%s\") failed: %s\n",
201                 argv[0], strerror(errno));
202         _exit(1);
203     }
204 }
205
206 /* Destroys process 'p'. */
207 void
208 process_destroy(struct process *p)
209 {
210     if (p) {
211         sigset_t oldsigs;
212
213         block_sigchld(&oldsigs);
214         list_remove(&p->node);
215         unblock_sigchld(&oldsigs);
216
217         free(p->name);
218         free(p);
219     }
220 }
221
222 /* Sends signal 'signr' to process 'p'.  Returns 0 if successful, otherwise a
223  * positive errno value. */
224 int
225 process_kill(const struct process *p, int signr)
226 {
227     return (p->exited ? ESRCH
228             : !kill(p->pid, signr) ? 0
229             : errno);
230 }
231
232 /* Returns the pid of process 'p'. */
233 pid_t
234 process_pid(const struct process *p)
235 {
236     return p->pid;
237 }
238
239 /* Returns the name of process 'p' (the name passed to process_start() with any
240  * leading directories stripped). */
241 const char *
242 process_name(const struct process *p)
243 {
244     return p->name;
245 }
246
247 /* Returns true if process 'p' has exited, false otherwise. */
248 bool
249 process_exited(struct process *p)
250 {
251     if (p->exited) {
252         return true;
253     } else {
254         char buf[_POSIX_PIPE_BUF];
255         read(fds[0], buf, sizeof buf);
256         return false;
257     }
258 }
259
260 /* Returns process 'p''s exit status, as reported by waitpid(2).
261  * process_status(p) may be called only after process_exited(p) has returned
262  * true. */
263 int
264 process_status(const struct process *p)
265 {
266     assert(p->exited);
267     return p->status;
268 }
269
270 int
271 process_run(char **argv,
272             const int keep_fds[], size_t n_keep_fds,
273             const int null_fds[], size_t n_null_fds,
274             int *status)
275 {
276     struct process *p;
277     int retval;
278
279     COVERAGE_INC(process_run);
280     retval = process_start(argv, keep_fds, n_keep_fds, null_fds, n_null_fds,
281                            &p);
282     if (retval) {
283         *status = 0;
284         return retval;
285     }
286
287     while (!process_exited(p)) {
288         process_wait(p);
289         poll_block();
290     }
291     *status = process_status(p);
292     process_destroy(p);
293     return 0;
294 }
295
296 /* Given 'status', which is a process status in the form reported by waitpid(2)
297  * and returned by process_status(), returns a string describing how the
298  * process terminated.  The caller is responsible for freeing the string when
299  * it is no longer needed. */
300 char *
301 process_status_msg(int status)
302 {
303     struct ds ds = DS_EMPTY_INITIALIZER;
304     if (WIFEXITED(status)) {
305         ds_put_format(&ds, "exit status %d", WEXITSTATUS(status));
306     } else if (WIFSIGNALED(status) || WIFSTOPPED(status)) {
307         int signr = WIFSIGNALED(status) ? WTERMSIG(status) : WSTOPSIG(status);
308         const char *name = NULL;
309 #ifdef HAVE_STRSIGNAL
310         name = strsignal(signr);
311 #endif
312         ds_put_format(&ds, "%s by signal %d",
313                       WIFSIGNALED(status) ? "killed" : "stopped", signr);
314         if (name) {
315             ds_put_format(&ds, " (%s)", name);
316         }
317     } else {
318         ds_put_format(&ds, "terminated abnormally (%x)", status);
319     }
320     if (WCOREDUMP(status)) {
321         ds_put_cstr(&ds, ", core dumped");
322     }
323     return ds_cstr(&ds);
324 }
325
326 /* Causes the next call to poll_block() to wake up when process 'p' has
327  * exited. */
328 void
329 process_wait(struct process *p)
330 {
331     if (p->exited) {
332         poll_immediate_wake();
333     } else {
334         poll_fd_wait(fds[0], POLLIN);
335     }
336 }
337
338 char *
339 process_search_path(const char *name)
340 {
341     char *save_ptr = NULL;
342     char *path, *dir;
343     struct stat s;
344
345     if (strchr(name, '/') || !getenv("PATH")) {
346         return stat(name, &s) == 0 ? xstrdup(name) : NULL;
347     }
348
349     path = xstrdup(getenv("PATH"));
350     for (dir = strtok_r(path, ":", &save_ptr); dir;
351          dir = strtok_r(NULL, ":", &save_ptr)) {
352         char *file = xasprintf("%s/%s", dir, name);
353         if (stat(file, &s) == 0) {
354             free(path);
355             return file;
356         }
357         free(file);
358     }
359     free(path);
360     return NULL;
361 }
362 \f
363 static void
364 sigchld_handler(int signr UNUSED)
365 {
366     struct process *p;
367
368     COVERAGE_INC(process_sigchld);
369     LIST_FOR_EACH (p, struct process, node, &all_processes) {
370         if (!p->exited) {
371             int retval, status;
372             do {
373                 retval = waitpid(p->pid, &status, WNOHANG);
374             } while (retval == -1 && errno == EINTR);
375             if (retval == p->pid) {
376                 p->exited = true;
377                 p->status = status;
378             } else if (retval < 0) {
379                 /* XXX We want to log something but we're in a signal
380                  * handler. */
381                 p->exited = true;
382                 p->status = -1;
383             }
384         }
385     }
386     write(fds[1], "", 1);
387 }
388
389 static bool
390 is_member(int x, const int *array, size_t n)
391 {
392     size_t i;
393
394     for (i = 0; i < n; i++) {
395         if (array[i] == x) {
396             return true;
397         }
398     }
399     return false;
400 }
401
402 static void
403 block_sigchld(sigset_t *oldsigs)
404 {
405     sigset_t sigchld;
406     sigemptyset(&sigchld);
407     sigaddset(&sigchld, SIGCHLD);
408     if (sigprocmask(SIG_BLOCK, &sigchld, oldsigs)) {
409         ovs_fatal(errno, "sigprocmask");
410     }
411 }
412
413 static void
414 unblock_sigchld(const sigset_t *oldsigs)
415 {
416     if (sigprocmask(SIG_SETMASK, oldsigs, NULL)) {
417         ovs_fatal(errno, "sigprocmask");
418     }
419 }