flow: extend it to carry IGMP protocol information
[cascardo/ovs.git] / lib / fatal-signal.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 #include <config.h>
17 #include "fatal-signal.h"
18 #include <errno.h>
19 #include <signal.h>
20 #include <stdbool.h>
21 #include <stdio.h>
22 #include <stdint.h>
23 #include <stdlib.h>
24 #include <string.h>
25 #include <unistd.h>
26 #include "ovs-thread.h"
27 #include "poll-loop.h"
28 #include "shash.h"
29 #include "sset.h"
30 #include "signals.h"
31 #include "socket-util.h"
32 #include "util.h"
33 #include "vlog.h"
34
35 #include "type-props.h"
36
37 #ifndef SIG_ATOMIC_MAX
38 #define SIG_ATOMIC_MAX TYPE_MAXIMUM(sig_atomic_t)
39 #endif
40
41 VLOG_DEFINE_THIS_MODULE(fatal_signal);
42
43 /* Signals to catch. */
44 #ifndef _WIN32
45 static const int fatal_signals[] = { SIGTERM, SIGINT, SIGHUP, SIGALRM };
46 #else
47 static const int fatal_signals[] = { SIGTERM };
48 #endif
49
50 /* Hooks to call upon catching a signal */
51 struct hook {
52     void (*hook_cb)(void *aux);
53     void (*cancel_cb)(void *aux);
54     void *aux;
55     bool run_at_exit;
56 };
57 #define MAX_HOOKS 32
58 static struct hook hooks[MAX_HOOKS];
59 static size_t n_hooks;
60
61 static int signal_fds[2];
62 static HANDLE wevent;
63 static volatile sig_atomic_t stored_sig_nr = SIG_ATOMIC_MAX;
64
65 static struct ovs_mutex mutex;
66
67 static void call_hooks(int sig_nr);
68 #ifdef _WIN32
69 static BOOL WINAPI ConsoleHandlerRoutine(DWORD dwCtrlType);
70 #endif
71
72 /* Initializes the fatal signal handling module.  Calling this function is
73  * optional, because calling any other function in the module will also
74  * initialize it.  However, in a multithreaded program, the module must be
75  * initialized while the process is still single-threaded. */
76 void
77 fatal_signal_init(void)
78 {
79     static bool inited = false;
80
81     if (!inited) {
82         size_t i;
83
84         assert_single_threaded();
85         inited = true;
86
87         ovs_mutex_init_recursive(&mutex);
88 #ifndef _WIN32
89         xpipe_nonblocking(signal_fds);
90 #else
91         wevent = CreateEvent(NULL, TRUE, FALSE, NULL);
92         if (!wevent) {
93             char *msg_buf = ovs_lasterror_to_string();
94             VLOG_FATAL("Failed to create a event (%s).", msg_buf);
95         }
96
97         /* Register a function to handle Ctrl+C. */
98         SetConsoleCtrlHandler(ConsoleHandlerRoutine, true);
99 #endif
100
101         for (i = 0; i < ARRAY_SIZE(fatal_signals); i++) {
102             int sig_nr = fatal_signals[i];
103 #ifndef _WIN32
104             struct sigaction old_sa;
105
106             xsigaction(sig_nr, NULL, &old_sa);
107             if (old_sa.sa_handler == SIG_DFL
108                 && signal(sig_nr, fatal_signal_handler) == SIG_ERR) {
109                 VLOG_FATAL("signal failed (%s)", ovs_strerror(errno));
110             }
111 #else
112             if (signal(sig_nr, fatal_signal_handler) == SIG_ERR) {
113                 VLOG_FATAL("signal failed (%s)", ovs_strerror(errno));
114             }
115 #endif
116         }
117         atexit(fatal_signal_atexit_handler);
118     }
119 }
120
121 /* Registers 'hook_cb' to be called from inside poll_block() following a fatal
122  * signal.  'hook_cb' does not need to be async-signal-safe.  In a
123  * multithreaded program 'hook_cb' might be called from any thread, with
124  * threads other than the one running 'hook_cb' in unknown states.
125  *
126  * If 'run_at_exit' is true, 'hook_cb' is also called during normal process
127  * termination, e.g. when exit() is called or when main() returns.
128  *
129  * If the current process forks, fatal_signal_fork() may be called to clear the
130  * parent process's fatal signal hooks, so that 'hook_cb' is only called when
131  * the child terminates, not when the parent does.  When fatal_signal_fork() is
132  * called, it calls the 'cancel_cb' function if it is nonnull, passing 'aux',
133  * to notify that the hook has been canceled.  This allows the hook to free
134  * memory, etc. */
135 void
136 fatal_signal_add_hook(void (*hook_cb)(void *aux), void (*cancel_cb)(void *aux),
137                       void *aux, bool run_at_exit)
138 {
139     fatal_signal_init();
140
141     ovs_mutex_lock(&mutex);
142     ovs_assert(n_hooks < MAX_HOOKS);
143     hooks[n_hooks].hook_cb = hook_cb;
144     hooks[n_hooks].cancel_cb = cancel_cb;
145     hooks[n_hooks].aux = aux;
146     hooks[n_hooks].run_at_exit = run_at_exit;
147     n_hooks++;
148     ovs_mutex_unlock(&mutex);
149 }
150
151 /* Handles fatal signal number 'sig_nr'.
152  *
153  * Ordinarily this is the actual signal handler.  When other code needs to
154  * handle one of our signals, however, it can register for that signal and, if
155  * and when necessary, call this function to do fatal signal processing for it
156  * and terminate the process.  Currently only timeval.c does this, for SIGALRM.
157  * (It is not important whether the other code sets up its signal handler
158  * before or after this file, because this file will only set up a signal
159  * handler in the case where the signal has its default handling.)  */
160 void
161 fatal_signal_handler(int sig_nr)
162 {
163 #ifndef _WIN32
164     ignore(write(signal_fds[1], "", 1));
165 #else
166     SetEvent(wevent);
167 #endif
168     stored_sig_nr = sig_nr;
169 }
170
171 /* Check whether a fatal signal has occurred and, if so, call the fatal signal
172  * hooks and exit.
173  *
174  * This function is called automatically by poll_block(), but specialized
175  * programs that may not always call poll_block() on a regular basis should
176  * also call it periodically.  (Therefore, any function with "block" in its
177  * name should call fatal_signal_run() each time it is called, either directly
178  * or through poll_block(), because such functions can only used by specialized
179  * programs that can afford to block outside their main loop around
180  * poll_block().)
181  */
182 void
183 fatal_signal_run(void)
184 {
185     sig_atomic_t sig_nr;
186
187     fatal_signal_init();
188
189     sig_nr = stored_sig_nr;
190     if (sig_nr != SIG_ATOMIC_MAX) {
191         char namebuf[SIGNAL_NAME_BUFSIZE];
192
193         ovs_mutex_lock(&mutex);
194
195 #ifndef _WIN32
196         VLOG_WARN("terminating with signal %d (%s)",
197                   (int)sig_nr, signal_name(sig_nr, namebuf, sizeof namebuf));
198 #else
199         VLOG_WARN("terminating with signal %d", (int)sig_nr);
200 #endif
201         call_hooks(sig_nr);
202
203         /* Re-raise the signal with the default handling so that the program
204          * termination status reflects that we were killed by this signal */
205         signal(sig_nr, SIG_DFL);
206         raise(sig_nr);
207
208         ovs_mutex_unlock(&mutex);
209         OVS_NOT_REACHED();
210     }
211 }
212
213 void
214 fatal_signal_wait(void)
215 {
216     fatal_signal_init();
217     poll_fd_wait_event(signal_fds[0], wevent, POLLIN);
218 }
219
220 void
221 fatal_ignore_sigpipe(void)
222 {
223 #ifndef _WIN32
224     signal(SIGPIPE, SIG_IGN);
225 #endif
226 }
227
228 void
229 fatal_signal_atexit_handler(void)
230 {
231     call_hooks(0);
232 }
233
234 static void
235 call_hooks(int sig_nr)
236 {
237     static volatile sig_atomic_t recurse = 0;
238     if (!recurse) {
239         size_t i;
240
241         recurse = 1;
242
243         for (i = 0; i < n_hooks; i++) {
244             struct hook *h = &hooks[i];
245             if (sig_nr || h->run_at_exit) {
246                 h->hook_cb(h->aux);
247             }
248         }
249     }
250 }
251
252 #ifdef _WIN32
253 BOOL WINAPI ConsoleHandlerRoutine(DWORD dwCtrlType)
254 {
255     stored_sig_nr = SIGINT;
256     SetEvent(wevent);
257     return true;
258 }
259 #endif
260 \f
261 /* Files to delete on exit. */
262 static struct sset files = SSET_INITIALIZER(&files);
263
264 /* Has a hook function been registered with fatal_signal_add_hook() (and not
265  * cleared by fatal_signal_fork())? */
266 static bool added_hook;
267
268 static void unlink_files(void *aux);
269 static void cancel_files(void *aux);
270 static void do_unlink_files(void);
271
272 /* Registers 'file' to be unlinked when the program terminates via exit() or a
273  * fatal signal. */
274 void
275 fatal_signal_add_file_to_unlink(const char *file)
276 {
277     fatal_signal_init();
278
279     ovs_mutex_lock(&mutex);
280     if (!added_hook) {
281         added_hook = true;
282         fatal_signal_add_hook(unlink_files, cancel_files, NULL, true);
283     }
284
285     sset_add(&files, file);
286     ovs_mutex_unlock(&mutex);
287 }
288
289 /* Unregisters 'file' from being unlinked when the program terminates via
290  * exit() or a fatal signal. */
291 void
292 fatal_signal_remove_file_to_unlink(const char *file)
293 {
294     fatal_signal_init();
295
296     ovs_mutex_lock(&mutex);
297     sset_find_and_delete(&files, file);
298     ovs_mutex_unlock(&mutex);
299 }
300
301 /* Like fatal_signal_remove_file_to_unlink(), but also unlinks 'file'.
302  * Returns 0 if successful, otherwise a positive errno value. */
303 int
304 fatal_signal_unlink_file_now(const char *file)
305 {
306     int error;
307
308     fatal_signal_init();
309
310     ovs_mutex_lock(&mutex);
311
312     error = unlink(file) ? errno : 0;
313     if (error) {
314         VLOG_WARN("could not unlink \"%s\" (%s)", file, ovs_strerror(error));
315     }
316
317     fatal_signal_remove_file_to_unlink(file);
318
319     ovs_mutex_unlock(&mutex);
320
321     return error;
322 }
323
324 static void
325 unlink_files(void *aux OVS_UNUSED)
326 {
327     do_unlink_files();
328 }
329
330 static void
331 cancel_files(void *aux OVS_UNUSED)
332 {
333     sset_clear(&files);
334     added_hook = false;
335 }
336
337 static void
338 do_unlink_files(void)
339 {
340     const char *file;
341
342     SSET_FOR_EACH (file, &files) {
343         unlink(file);
344     }
345 }
346 \f
347 /* Clears all of the fatal signal hooks without executing them.  If any of the
348  * hooks passed a 'cancel_cb' function to fatal_signal_add_hook(), then those
349  * functions will be called, allowing them to free resources, etc.
350  *
351  * Following a fork, one of the resulting processes can call this function to
352  * allow it to terminate without calling the hooks registered before calling
353  * this function.  New hooks registered after calling this function will take
354  * effect normally. */
355 void
356 fatal_signal_fork(void)
357 {
358     size_t i;
359
360     assert_single_threaded();
361
362     for (i = 0; i < n_hooks; i++) {
363         struct hook *h = &hooks[i];
364         if (h->cancel_cb) {
365             h->cancel_cb(h->aux);
366         }
367     }
368     n_hooks = 0;
369
370     /* Raise any signals that we have already received with the default
371      * handler. */
372     if (stored_sig_nr != SIG_ATOMIC_MAX) {
373         raise(stored_sig_nr);
374     }
375 }
376
377 #ifndef _WIN32
378 /* Blocks all fatal signals and returns previous signal mask into
379  * 'prev_mask'. */
380 void
381 fatal_signal_block(sigset_t *prev_mask)
382 {
383     int i;
384     sigset_t block_mask;
385
386     sigemptyset(&block_mask);
387     for (i = 0; i < ARRAY_SIZE(fatal_signals); i++) {
388         int sig_nr = fatal_signals[i];
389         sigaddset(&block_mask, sig_nr);
390     }
391     xpthread_sigmask(SIG_BLOCK, &block_mask, prev_mask);
392 }
393 #endif