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