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