process: Remove process_run(), process_run_capture(), and related code.
[sliver-openvswitch.git] / lib / process.c
1 /*
2  * Copyright (c) 2008, 2009, 2010, 2011, 2012, 2013 Nicira, Inc.
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 <errno.h>
20 #include <fcntl.h>
21 #include <signal.h>
22 #include <stdlib.h>
23 #include <string.h>
24 #include <sys/stat.h>
25 #include <sys/wait.h>
26 #include <unistd.h>
27 #include "coverage.h"
28 #include "dynamic-string.h"
29 #include "fatal-signal.h"
30 #include "list.h"
31 #include "poll-loop.h"
32 #include "signals.h"
33 #include "socket-util.h"
34 #include "util.h"
35 #include "vlog.h"
36
37 VLOG_DEFINE_THIS_MODULE(process);
38
39 COVERAGE_DEFINE(process_sigchld);
40 COVERAGE_DEFINE(process_start);
41
42 struct process {
43     struct list node;
44     char *name;
45     pid_t pid;
46
47     /* Modified by signal handler. */
48     volatile bool exited;
49     volatile int status;
50 };
51
52 /* Pipe used to signal child termination. */
53 static int fds[2];
54
55 /* All processes. */
56 static struct list all_processes = LIST_INITIALIZER(&all_processes);
57
58 static bool sigchld_is_blocked(void);
59 static void block_sigchld(sigset_t *);
60 static void unblock_sigchld(const sigset_t *);
61 static void sigchld_handler(int signr OVS_UNUSED);
62 static bool is_member(int x, const int *array, size_t);
63
64 /* Initializes the process subsystem (if it is not already initialized).  Calls
65  * exit() if initialization fails.
66  *
67  * Calling this function is optional; it will be called automatically by
68  * process_start() if necessary.  Calling it explicitly allows the client to
69  * prevent the process from exiting at an unexpected time. */
70 void
71 process_init(void)
72 {
73     static bool inited;
74     struct sigaction sa;
75
76     if (inited) {
77         return;
78     }
79     inited = true;
80
81     /* Create notification pipe. */
82     xpipe_nonblocking(fds);
83
84     /* Set up child termination signal handler. */
85     memset(&sa, 0, sizeof sa);
86     sa.sa_handler = sigchld_handler;
87     sigemptyset(&sa.sa_mask);
88     sa.sa_flags = SA_NOCLDSTOP | SA_RESTART;
89     xsigaction(SIGCHLD, &sa, NULL);
90 }
91
92 char *
93 process_escape_args(char **argv)
94 {
95     struct ds ds = DS_EMPTY_INITIALIZER;
96     char **argp;
97     for (argp = argv; *argp; argp++) {
98         const char *arg = *argp;
99         const char *p;
100         if (argp != argv) {
101             ds_put_char(&ds, ' ');
102         }
103         if (arg[strcspn(arg, " \t\r\n\v\\\'\"")]) {
104             ds_put_char(&ds, '"');
105             for (p = arg; *p; p++) {
106                 if (*p == '\\' || *p == '\"') {
107                     ds_put_char(&ds, '\\');
108                 }
109                 ds_put_char(&ds, *p);
110             }
111             ds_put_char(&ds, '"');
112         } else {
113             ds_put_cstr(&ds, arg);
114         }
115     }
116     return ds_cstr(&ds);
117 }
118
119 /* Prepare to start a process whose command-line arguments are given by the
120  * null-terminated 'argv' array.  Returns 0 if successful, otherwise a
121  * positive errno value. */
122 static int
123 process_prestart(char **argv)
124 {
125     char *binary;
126
127     process_init();
128
129     /* Log the process to be started. */
130     if (VLOG_IS_DBG_ENABLED()) {
131         char *args = process_escape_args(argv);
132         VLOG_DBG("starting subprocess: %s", args);
133         free(args);
134     }
135
136     /* execvp() will search PATH too, but the error in that case is more
137      * obscure, since it is only reported post-fork. */
138     binary = process_search_path(argv[0]);
139     if (!binary) {
140         VLOG_ERR("%s not found in PATH", argv[0]);
141         return ENOENT;
142     }
143     free(binary);
144
145     return 0;
146 }
147
148 /* Creates and returns a new struct process with the specified 'name' and
149  * 'pid'.
150  *
151  * This is racy unless SIGCHLD is blocked (and has been blocked since before
152  * the fork()) that created the subprocess.  */
153 static struct process *
154 process_register(const char *name, pid_t pid)
155 {
156     struct process *p;
157     const char *slash;
158
159     ovs_assert(sigchld_is_blocked());
160
161     p = xzalloc(sizeof *p);
162     p->pid = pid;
163     slash = strrchr(name, '/');
164     p->name = xstrdup(slash ? slash + 1 : name);
165     p->exited = false;
166
167     list_push_back(&all_processes, &p->node);
168
169     return p;
170 }
171
172 /* Starts a subprocess with the arguments in the null-terminated argv[] array.
173  * argv[0] is used as the name of the process.  Searches the PATH environment
174  * variable to find the program to execute.
175  *
176  * All file descriptors are closed before executing the subprocess, except for
177  * fds 0, 1, and 2 and the 'n_keep_fds' fds listed in 'keep_fds'.  Also, any of
178  * the 'n_null_fds' fds listed in 'null_fds' are replaced by /dev/null.
179  *
180  * Returns 0 if successful, otherwise a positive errno value indicating the
181  * error.  If successful, '*pp' is assigned a new struct process that may be
182  * used to query the process's status.  On failure, '*pp' is set to NULL. */
183 int
184 process_start(char **argv,
185               const int keep_fds[], size_t n_keep_fds,
186               const int null_fds[], size_t n_null_fds,
187               struct process **pp)
188 {
189     sigset_t oldsigs;
190     int nullfd;
191     pid_t pid;
192     int error;
193
194     *pp = NULL;
195     COVERAGE_INC(process_start);
196     error = process_prestart(argv);
197     if (error) {
198         return error;
199     }
200
201     if (n_null_fds) {
202         nullfd = get_null_fd();
203         if (nullfd < 0) {
204             return -nullfd;
205         }
206     } else {
207         nullfd = -1;
208     }
209
210     block_sigchld(&oldsigs);
211     pid = fork();
212     if (pid < 0) {
213         unblock_sigchld(&oldsigs);
214         VLOG_WARN("fork failed: %s", strerror(errno));
215         return errno;
216     } else if (pid) {
217         /* Running in parent process. */
218         *pp = process_register(argv[0], pid);
219         unblock_sigchld(&oldsigs);
220         return 0;
221     } else {
222         /* Running in child process. */
223         int fd_max = get_max_fds();
224         int fd;
225
226         fatal_signal_fork();
227         unblock_sigchld(&oldsigs);
228         for (fd = 0; fd < fd_max; fd++) {
229             if (is_member(fd, null_fds, n_null_fds)) {
230                 dup2(nullfd, fd);
231             } else if (fd >= 3 && fd != nullfd
232                        && !is_member(fd, keep_fds, n_keep_fds)) {
233                 close(fd);
234             }
235         }
236         if (nullfd >= 0
237             && !is_member(nullfd, keep_fds, n_keep_fds)
238             && !is_member(nullfd, null_fds, n_null_fds)) {
239             close(nullfd);
240         }
241         execvp(argv[0], argv);
242         fprintf(stderr, "execvp(\"%s\") failed: %s\n",
243                 argv[0], strerror(errno));
244         _exit(1);
245     }
246 }
247
248 /* Destroys process 'p'. */
249 void
250 process_destroy(struct process *p)
251 {
252     if (p) {
253         sigset_t oldsigs;
254
255         block_sigchld(&oldsigs);
256         list_remove(&p->node);
257         unblock_sigchld(&oldsigs);
258
259         free(p->name);
260         free(p);
261     }
262 }
263
264 /* Sends signal 'signr' to process 'p'.  Returns 0 if successful, otherwise a
265  * positive errno value. */
266 int
267 process_kill(const struct process *p, int signr)
268 {
269     return (p->exited ? ESRCH
270             : !kill(p->pid, signr) ? 0
271             : errno);
272 }
273
274 /* Returns the pid of process 'p'. */
275 pid_t
276 process_pid(const struct process *p)
277 {
278     return p->pid;
279 }
280
281 /* Returns the name of process 'p' (the name passed to process_start() with any
282  * leading directories stripped). */
283 const char *
284 process_name(const struct process *p)
285 {
286     return p->name;
287 }
288
289 /* Returns true if process 'p' has exited, false otherwise. */
290 bool
291 process_exited(struct process *p)
292 {
293     if (p->exited) {
294         return true;
295     } else {
296         char buf[_POSIX_PIPE_BUF];
297         ignore(read(fds[0], buf, sizeof buf));
298         return false;
299     }
300 }
301
302 /* Returns process 'p''s exit status, as reported by waitpid(2).
303  * process_status(p) may be called only after process_exited(p) has returned
304  * true. */
305 int
306 process_status(const struct process *p)
307 {
308     ovs_assert(p->exited);
309     return p->status;
310 }
311
312 /* Given 'status', which is a process status in the form reported by waitpid(2)
313  * and returned by process_status(), returns a string describing how the
314  * process terminated.  The caller is responsible for freeing the string when
315  * it is no longer needed. */
316 char *
317 process_status_msg(int status)
318 {
319     struct ds ds = DS_EMPTY_INITIALIZER;
320     if (WIFEXITED(status)) {
321         ds_put_format(&ds, "exit status %d", WEXITSTATUS(status));
322     } else if (WIFSIGNALED(status)) {
323         char namebuf[SIGNAL_NAME_BUFSIZE];
324
325         ds_put_format(&ds, "killed (%s)",
326                       signal_name(WTERMSIG(status), namebuf, sizeof namebuf));
327     } else if (WIFSTOPPED(status)) {
328         char namebuf[SIGNAL_NAME_BUFSIZE];
329
330         ds_put_format(&ds, "stopped (%s)",
331                       signal_name(WSTOPSIG(status), namebuf, sizeof namebuf));
332     } else {
333         ds_put_format(&ds, "terminated abnormally (%x)", status);
334     }
335     if (WCOREDUMP(status)) {
336         ds_put_cstr(&ds, ", core dumped");
337     }
338     return ds_cstr(&ds);
339 }
340
341 /* Causes the next call to poll_block() to wake up when process 'p' has
342  * exited. */
343 void
344 process_wait(struct process *p)
345 {
346     if (p->exited) {
347         poll_immediate_wake();
348     } else {
349         poll_fd_wait(fds[0], POLLIN);
350     }
351 }
352
353 char *
354 process_search_path(const char *name)
355 {
356     char *save_ptr = NULL;
357     char *path, *dir;
358     struct stat s;
359
360     if (strchr(name, '/') || !getenv("PATH")) {
361         return stat(name, &s) == 0 ? xstrdup(name) : NULL;
362     }
363
364     path = xstrdup(getenv("PATH"));
365     for (dir = strtok_r(path, ":", &save_ptr); dir;
366          dir = strtok_r(NULL, ":", &save_ptr)) {
367         char *file = xasprintf("%s/%s", dir, name);
368         if (stat(file, &s) == 0) {
369             free(path);
370             return file;
371         }
372         free(file);
373     }
374     free(path);
375     return NULL;
376 }
377 \f
378 static void
379 sigchld_handler(int signr OVS_UNUSED)
380 {
381     struct process *p;
382
383     COVERAGE_INC(process_sigchld);
384     LIST_FOR_EACH (p, node, &all_processes) {
385         if (!p->exited) {
386             int retval, status;
387             do {
388                 retval = waitpid(p->pid, &status, WNOHANG);
389             } while (retval == -1 && errno == EINTR);
390             if (retval == p->pid) {
391                 p->exited = true;
392                 p->status = status;
393             } else if (retval < 0) {
394                 /* XXX We want to log something but we're in a signal
395                  * handler. */
396                 p->exited = true;
397                 p->status = -1;
398             }
399         }
400     }
401     ignore(write(fds[1], "", 1));
402 }
403
404 static bool
405 is_member(int x, const int *array, size_t n)
406 {
407     size_t i;
408
409     for (i = 0; i < n; i++) {
410         if (array[i] == x) {
411             return true;
412         }
413     }
414     return false;
415 }
416
417 static bool
418 sigchld_is_blocked(void)
419 {
420     sigset_t sigs;
421
422     xpthread_sigmask(SIG_SETMASK, NULL, &sigs);
423     return sigismember(&sigs, SIGCHLD);
424 }
425
426 static void
427 block_sigchld(sigset_t *oldsigs)
428 {
429     sigset_t sigchld;
430
431     sigemptyset(&sigchld);
432     sigaddset(&sigchld, SIGCHLD);
433     xpthread_sigmask(SIG_BLOCK, &sigchld, oldsigs);
434 }
435
436 static void
437 unblock_sigchld(const sigset_t *oldsigs)
438 {
439     xpthread_sigmask(SIG_SETMASK, oldsigs, NULL);
440 }