b479d005df3ee2ced5e837f58f11b793253b0383
[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 "ovs-thread.h"
32 #include "poll-loop.h"
33 #include "signals.h"
34 #include "socket-util.h"
35 #include "util.h"
36 #include "vlog.h"
37
38 VLOG_DEFINE_THIS_MODULE(process);
39
40 COVERAGE_DEFINE(process_start);
41
42 struct process {
43     struct list node;
44     char *name;
45     pid_t pid;
46
47     /* State. */
48     bool exited;
49     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 void sigchld_handler(int signr OVS_UNUSED);
59
60 /* Initializes the process subsystem (if it is not already initialized).  Calls
61  * exit() if initialization fails.
62  *
63  * This function may not be called after creating any additional threads.
64  *
65  * Calling this function is optional; it will be called automatically by
66  * process_start() if necessary.  Calling it explicitly allows the client to
67  * prevent the process from exiting at an unexpected time. */
68 void
69 process_init(void)
70 {
71 #ifndef _WIN32
72     static bool inited;
73     struct sigaction sa;
74
75     assert_single_threaded();
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 #endif
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 /* Prepare to start a process whose command-line arguments are given by the
121  * null-terminated 'argv' array.  Returns 0 if successful, otherwise a
122  * positive errno value. */
123 static int
124 process_prestart(char **argv)
125 {
126     char *binary;
127
128     process_init();
129
130     /* Log the process to be started. */
131     if (VLOG_IS_DBG_ENABLED()) {
132         char *args = process_escape_args(argv);
133         VLOG_DBG("starting subprocess: %s", args);
134         free(args);
135     }
136
137     /* execvp() will search PATH too, but the error in that case is more
138      * obscure, since it is only reported post-fork. */
139     binary = process_search_path(argv[0]);
140     if (!binary) {
141         VLOG_ERR("%s not found in PATH", argv[0]);
142         return ENOENT;
143     }
144     free(binary);
145
146     return 0;
147 }
148
149 /* Creates and returns a new struct process with the specified 'name' and
150  * 'pid'. */
151 static struct process *
152 process_register(const char *name, pid_t pid)
153 {
154     struct process *p;
155     const char *slash;
156
157     p = xzalloc(sizeof *p);
158     p->pid = pid;
159     slash = strrchr(name, '/');
160     p->name = xstrdup(slash ? slash + 1 : name);
161     p->exited = false;
162
163     list_push_back(&all_processes, &p->node);
164
165     return p;
166 }
167
168 #ifndef _WIN32
169 static bool
170 rlim_is_finite(rlim_t limit)
171 {
172     if (limit == RLIM_INFINITY) {
173         return false;
174     }
175
176 #ifdef RLIM_SAVED_CUR           /* FreeBSD 8.0 lacks RLIM_SAVED_CUR. */
177     if (limit == RLIM_SAVED_CUR) {
178         return false;
179     }
180 #endif
181
182 #ifdef RLIM_SAVED_MAX           /* FreeBSD 8.0 lacks RLIM_SAVED_MAX. */
183     if (limit == RLIM_SAVED_MAX) {
184         return false;
185     }
186 #endif
187
188     return true;
189 }
190
191 /* Returns the maximum valid FD value, plus 1. */
192 static int
193 get_max_fds(void)
194 {
195     static int max_fds;
196
197     if (!max_fds) {
198         struct rlimit r;
199         if (!getrlimit(RLIMIT_NOFILE, &r) && rlim_is_finite(r.rlim_cur)) {
200             max_fds = r.rlim_cur;
201         } else {
202             VLOG_WARN("failed to obtain fd limit, defaulting to 1024");
203             max_fds = 1024;
204         }
205     }
206
207     return max_fds;
208 }
209 #endif /* _WIN32 */
210
211 /* Starts a subprocess with the arguments in the null-terminated argv[] array.
212  * argv[0] is used as the name of the process.  Searches the PATH environment
213  * variable to find the program to execute.
214  *
215  * This function may not be called after creating any additional threads.
216  *
217  * All file descriptors are closed before executing the subprocess, except for
218  * fds 0, 1, and 2.
219  *
220  * Returns 0 if successful, otherwise a positive errno value indicating the
221  * error.  If successful, '*pp' is assigned a new struct process that may be
222  * used to query the process's status.  On failure, '*pp' is set to NULL. */
223 int
224 process_start(char **argv, struct process **pp)
225 {
226 #ifndef _WIN32
227     pid_t pid;
228     int error;
229
230     assert_single_threaded();
231
232     *pp = NULL;
233     COVERAGE_INC(process_start);
234     error = process_prestart(argv);
235     if (error) {
236         return error;
237     }
238
239     pid = fork();
240     if (pid < 0) {
241         VLOG_WARN("fork failed: %s", ovs_strerror(errno));
242         return errno;
243     } else if (pid) {
244         /* Running in parent process. */
245         *pp = process_register(argv[0], pid);
246         return 0;
247     } else {
248         /* Running in child process. */
249         int fd_max = get_max_fds();
250         int fd;
251
252         fatal_signal_fork();
253         for (fd = 3; fd < fd_max; fd++) {
254             close(fd);
255         }
256         execvp(argv[0], argv);
257         fprintf(stderr, "execvp(\"%s\") failed: %s\n",
258                 argv[0], ovs_strerror(errno));
259         _exit(1);
260     }
261 #else
262     *pp = NULL;
263     return ENOSYS;
264 #endif
265 }
266
267 /* Destroys process 'p'. */
268 void
269 process_destroy(struct process *p)
270 {
271     if (p) {
272         list_remove(&p->node);
273         free(p->name);
274         free(p);
275     }
276 }
277
278 /* Sends signal 'signr' to process 'p'.  Returns 0 if successful, otherwise a
279  * positive errno value. */
280 int
281 process_kill(const struct process *p, int signr)
282 {
283 #ifndef _WIN32
284     return (p->exited ? ESRCH
285             : !kill(p->pid, signr) ? 0
286             : errno);
287 #else
288     return ENOSYS;
289 #endif
290 }
291
292 /* Returns the pid of process 'p'. */
293 pid_t
294 process_pid(const struct process *p)
295 {
296     return p->pid;
297 }
298
299 /* Returns the name of process 'p' (the name passed to process_start() with any
300  * leading directories stripped). */
301 const char *
302 process_name(const struct process *p)
303 {
304     return p->name;
305 }
306
307 /* Returns true if process 'p' has exited, false otherwise. */
308 bool
309 process_exited(struct process *p)
310 {
311     return p->exited;
312 }
313
314 /* Returns process 'p''s exit status, as reported by waitpid(2).
315  * process_status(p) may be called only after process_exited(p) has returned
316  * true. */
317 int
318 process_status(const struct process *p)
319 {
320     ovs_assert(p->exited);
321     return p->status;
322 }
323
324 /* Given 'status', which is a process status in the form reported by waitpid(2)
325  * and returned by process_status(), returns a string describing how the
326  * process terminated.  The caller is responsible for freeing the string when
327  * it is no longer needed. */
328 char *
329 process_status_msg(int status)
330 {
331     struct ds ds = DS_EMPTY_INITIALIZER;
332 #ifndef _WIN32
333     if (WIFEXITED(status)) {
334         ds_put_format(&ds, "exit status %d", WEXITSTATUS(status));
335     } else if (WIFSIGNALED(status)) {
336         char namebuf[SIGNAL_NAME_BUFSIZE];
337
338         ds_put_format(&ds, "killed (%s)",
339                       signal_name(WTERMSIG(status), namebuf, sizeof namebuf));
340     } else if (WIFSTOPPED(status)) {
341         char namebuf[SIGNAL_NAME_BUFSIZE];
342
343         ds_put_format(&ds, "stopped (%s)",
344                       signal_name(WSTOPSIG(status), namebuf, sizeof namebuf));
345     } else {
346         ds_put_format(&ds, "terminated abnormally (%x)", status);
347     }
348     if (WCOREDUMP(status)) {
349         ds_put_cstr(&ds, ", core dumped");
350     }
351 #else
352     ds_put_cstr(&ds, "function not supported.");
353 #endif
354     return ds_cstr(&ds);
355 }
356
357 /* Executes periodic maintenance activities required by the process module. */
358 void
359 process_run(void)
360 {
361 #ifndef _WIN32
362     char buf[_POSIX_PIPE_BUF];
363
364     if (!list_is_empty(&all_processes) && read(fds[0], buf, sizeof buf) > 0) {
365         struct process *p;
366
367         LIST_FOR_EACH (p, 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                     VLOG_WARN("waitpid: %s", ovs_strerror(errno));
378                     p->exited = true;
379                     p->status = -1;
380                 }
381             }
382         }
383     }
384 #endif
385 }
386
387
388 /* Causes the next call to poll_block() to wake up when process 'p' has
389  * exited. */
390 void
391 process_wait(struct process *p)
392 {
393 #ifndef _WIN32
394     if (p->exited) {
395         poll_immediate_wake();
396     } else {
397         poll_fd_wait(fds[0], POLLIN);
398     }
399 #else
400     OVS_NOT_REACHED();
401 #endif
402 }
403
404 char *
405 process_search_path(const char *name)
406 {
407     char *save_ptr = NULL;
408     char *path, *dir;
409     struct stat s;
410
411     if (strchr(name, '/') || !getenv("PATH")) {
412         return stat(name, &s) == 0 ? xstrdup(name) : NULL;
413     }
414
415     path = xstrdup(getenv("PATH"));
416     for (dir = strtok_r(path, ":", &save_ptr); dir;
417          dir = strtok_r(NULL, ":", &save_ptr)) {
418         char *file = xasprintf("%s/%s", dir, name);
419         if (stat(file, &s) == 0) {
420             free(path);
421             return file;
422         }
423         free(file);
424     }
425     free(path);
426     return NULL;
427 }
428 \f
429 static void
430 sigchld_handler(int signr OVS_UNUSED)
431 {
432     ignore(write(fds[1], "", 1));
433 }