tevent: Fix bug 9550 - sigprocmask does not work on FreeBSD to stop further signals...
[samba.git] / lib / tevent / tevent_signal.c
1 /* 
2    Unix SMB/CIFS implementation.
3
4    common events code for signal events
5
6    Copyright (C) Andrew Tridgell        2007
7
8      ** NOTE! The following LGPL license applies to the tevent
9      ** library. This does NOT imply that all of Samba is released
10      ** under the LGPL
11
12    This library is free software; you can redistribute it and/or
13    modify it under the terms of the GNU Lesser General Public
14    License as published by the Free Software Foundation; either
15    version 3 of the License, or (at your option) any later version.
16
17    This library is distributed in the hope that it will be useful,
18    but WITHOUT ANY WARRANTY; without even the implied warranty of
19    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
20    Lesser General Public License for more details.
21
22    You should have received a copy of the GNU Lesser General Public
23    License along with this library; if not, see <http://www.gnu.org/licenses/>.
24 */
25
26 #include "replace.h"
27 #include "system/filesys.h"
28 #include "system/wait.h"
29 #include "tevent.h"
30 #include "tevent_internal.h"
31 #include "tevent_util.h"
32
33 #define TEVENT_NUM_SIGNALS 64
34
35 /* maximum number of SA_SIGINFO signals to hold in the queue.
36   NB. This *MUST* be a power of 2, in order for the ring buffer
37   wrap to work correctly. Thanks to Petr Vandrovec <petr@vandrovec.name>
38   for this. */
39
40 #define TEVENT_SA_INFO_QUEUE_COUNT 64
41
42 struct tevent_sigcounter {
43         uint32_t count;
44         uint32_t seen;
45 };
46
47 #define TEVENT_SIG_INCREMENT(s) (s).count++
48 #define TEVENT_SIG_SEEN(s, n) (s).seen += (n)
49 #define TEVENT_SIG_PENDING(s) ((s).seen != (s).count)
50
51 struct tevent_common_signal_list {
52         struct tevent_common_signal_list *prev, *next;
53         struct tevent_signal *se;
54 };
55
56 /*
57   the poor design of signals means that this table must be static global
58 */
59 static struct tevent_sig_state {
60         struct tevent_common_signal_list *sig_handlers[TEVENT_NUM_SIGNALS+1];
61         struct sigaction *oldact[TEVENT_NUM_SIGNALS+1];
62         struct tevent_sigcounter signal_count[TEVENT_NUM_SIGNALS+1];
63         struct tevent_sigcounter got_signal;
64 #ifdef SA_SIGINFO
65         /* with SA_SIGINFO we get quite a lot of info per signal */
66         siginfo_t *sig_info[TEVENT_NUM_SIGNALS+1];
67         struct tevent_sigcounter sig_blocked[TEVENT_NUM_SIGNALS+1];
68 #endif
69 } *sig_state;
70
71 /*
72   return number of sigcounter events not processed yet
73 */
74 static uint32_t tevent_sig_count(struct tevent_sigcounter s)
75 {
76         return s.count - s.seen;
77 }
78
79 /*
80   signal handler - redirects to registered signals
81 */
82 static void tevent_common_signal_handler(int signum)
83 {
84         char c = 0;
85         ssize_t res;
86         struct tevent_common_signal_list *sl;
87         struct tevent_context *ev = NULL;
88         int saved_errno = errno;
89
90         TEVENT_SIG_INCREMENT(sig_state->signal_count[signum]);
91         TEVENT_SIG_INCREMENT(sig_state->got_signal);
92
93         /* Write to each unique event context. */
94         for (sl = sig_state->sig_handlers[signum]; sl; sl = sl->next) {
95                 if (sl->se->event_ctx && sl->se->event_ctx != ev) {
96                         ev = sl->se->event_ctx;
97                         /* doesn't matter if this pipe overflows */
98                         res = write(ev->pipe_fds[1], &c, 1);
99                 }
100         }
101
102         errno = saved_errno;
103 }
104
105 #ifdef SA_SIGINFO
106 /*
107   signal handler with SA_SIGINFO - redirects to registered signals
108 */
109 static void tevent_common_signal_handler_info(int signum, siginfo_t *info,
110                                               void *uctx)
111 {
112         uint32_t count = tevent_sig_count(sig_state->signal_count[signum]);
113         /* sig_state->signal_count[signum].seen % TEVENT_SA_INFO_QUEUE_COUNT
114          * is the base of the unprocessed signals in the ringbuffer. */
115         uint32_t ofs = (sig_state->signal_count[signum].seen + count) %
116                                 TEVENT_SA_INFO_QUEUE_COUNT;
117         sig_state->sig_info[signum][ofs] = *info;
118
119         tevent_common_signal_handler(signum);
120
121         /* handle SA_SIGINFO */
122         if (count+1 == TEVENT_SA_INFO_QUEUE_COUNT) {
123                 /* we've filled the info array - block this signal until
124                    these ones are delivered */
125 #ifdef HAVE_UCONTEXT_T
126                 /*
127                  * This is the only way for this to work.
128                  * By default signum is blocked inside this
129                  * signal handler using a temporary mask,
130                  * but what we really need to do now is
131                  * block it in the callers mask, so it
132                  * stays blocked when the temporary signal
133                  * handler mask is replaced when we return
134                  * from here. The callers mask can be found
135                  * in the ucontext_t passed in as the
136                  * void *uctx argument.
137                  */
138                 ucontext_t *ucp = (ucontext_t *)uctx;
139                 sigaddset(&ucp->uc_sigmask, signum);
140 #else
141                 /*
142                  * WARNING !!! WARNING !!!!
143                  *
144                  * This code doesn't work.
145                  * By default signum is blocked inside this
146                  * signal handler, but calling sigprocmask
147                  * modifies the temporary signal mask being
148                  * used *inside* this handler, which will be
149                  * replaced by the callers signal mask once
150                  * we return from here. See Samba
151                  * bug #9550 for details.
152                  */
153                 sigset_t set;
154                 sigemptyset(&set);
155                 sigaddset(&set, signum);
156                 sigprocmask(SIG_BLOCK, &set, NULL);
157 #endif
158                 TEVENT_SIG_INCREMENT(sig_state->sig_blocked[signum]);
159         }
160 }
161 #endif
162
163 static int tevent_common_signal_list_destructor(struct tevent_common_signal_list *sl)
164 {
165         if (sig_state->sig_handlers[sl->se->signum]) {
166                 DLIST_REMOVE(sig_state->sig_handlers[sl->se->signum], sl);
167         }
168         return 0;
169 }
170
171 /*
172   destroy a signal event
173 */
174 static int tevent_signal_destructor(struct tevent_signal *se)
175 {
176         struct tevent_common_signal_list *sl;
177         sl = talloc_get_type(se->additional_data,
178                              struct tevent_common_signal_list);
179
180         if (se->event_ctx) {
181                 DLIST_REMOVE(se->event_ctx->signal_events, se);
182         }
183
184         talloc_free(sl);
185
186         if (sig_state->sig_handlers[se->signum] == NULL) {
187                 /* restore old handler, if any */
188                 if (sig_state->oldact[se->signum]) {
189                         sigaction(se->signum, sig_state->oldact[se->signum], NULL);
190                         sig_state->oldact[se->signum] = NULL;
191                 }
192 #ifdef SA_SIGINFO
193                 if (se->sa_flags & SA_SIGINFO) {
194                         if (sig_state->sig_info[se->signum]) {
195                                 talloc_free(sig_state->sig_info[se->signum]);
196                                 sig_state->sig_info[se->signum] = NULL;
197                         }
198                 }
199 #endif
200         }
201
202         return 0;
203 }
204
205 /*
206   this is part of the pipe hack needed to avoid the signal race condition
207 */
208 static void signal_pipe_handler(struct tevent_context *ev, struct tevent_fd *fde, 
209                                 uint16_t flags, void *_private)
210 {
211         char c[16];
212         ssize_t res;
213         /* its non-blocking, doesn't matter if we read too much */
214         res = read(fde->fd, c, sizeof(c));
215 }
216
217 /*
218   add a signal event
219   return NULL on failure (memory allocation error)
220 */
221 struct tevent_signal *tevent_common_add_signal(struct tevent_context *ev,
222                                                TALLOC_CTX *mem_ctx,
223                                                int signum,
224                                                int sa_flags,
225                                                tevent_signal_handler_t handler,
226                                                void *private_data,
227                                                const char *handler_name,
228                                                const char *location)
229 {
230         struct tevent_signal *se;
231         struct tevent_common_signal_list *sl;
232         sigset_t set, oldset;
233
234         if (signum >= TEVENT_NUM_SIGNALS) {
235                 errno = EINVAL;
236                 return NULL;
237         }
238
239         /* the sig_state needs to be on a global context as it can last across
240            multiple event contexts */
241         if (sig_state == NULL) {
242                 sig_state = talloc_zero(NULL, struct tevent_sig_state);
243                 if (sig_state == NULL) {
244                         return NULL;
245                 }
246         }
247
248         se = talloc(mem_ctx?mem_ctx:ev, struct tevent_signal);
249         if (se == NULL) return NULL;
250
251         se->event_ctx           = ev;
252         se->signum              = signum;
253         se->sa_flags            = sa_flags;
254         se->handler             = handler;
255         se->private_data        = private_data;
256         se->handler_name        = handler_name;
257         se->location            = location;
258         se->additional_data     = NULL;
259
260         sl = talloc(se, struct tevent_common_signal_list);
261         if (!sl) {
262                 talloc_free(se);
263                 return NULL;
264         }
265         sl->se = se;
266         se->additional_data     = sl;
267
268         /* Ensure, no matter the destruction order, that we always have a handle on the global sig_state */
269         if (!talloc_reference(se, sig_state)) {
270                 talloc_free(se);
271                 return NULL;
272         }
273
274         /* we need to setup the pipe hack handler if not already
275            setup */
276         if (ev->pipe_fde == NULL) {
277                 if (pipe(ev->pipe_fds) == -1) {
278                         talloc_free(se);
279                         return NULL;
280                 }
281                 ev_set_blocking(ev->pipe_fds[0], false);
282                 ev_set_blocking(ev->pipe_fds[1], false);
283                 ev->pipe_fde = tevent_add_fd(ev, ev, ev->pipe_fds[0],
284                                              TEVENT_FD_READ,
285                                              signal_pipe_handler, NULL);
286                 if (!ev->pipe_fde) {
287                         close(ev->pipe_fds[0]);
288                         close(ev->pipe_fds[1]);
289                         talloc_free(se);
290                         return NULL;
291                 }
292         }
293
294         /* only install a signal handler if not already installed */
295         if (sig_state->sig_handlers[signum] == NULL) {
296                 struct sigaction act;
297                 ZERO_STRUCT(act);
298                 act.sa_handler = tevent_common_signal_handler;
299                 act.sa_flags = sa_flags;
300 #ifdef SA_SIGINFO
301                 if (sa_flags & SA_SIGINFO) {
302                         act.sa_handler   = NULL;
303                         act.sa_sigaction = tevent_common_signal_handler_info;
304                         if (sig_state->sig_info[signum] == NULL) {
305                                 sig_state->sig_info[signum] =
306                                         talloc_zero_array(sig_state, siginfo_t,
307                                                           TEVENT_SA_INFO_QUEUE_COUNT);
308                                 if (sig_state->sig_info[signum] == NULL) {
309                                         talloc_free(se);
310                                         return NULL;
311                                 }
312                         }
313                 }
314 #endif
315                 sig_state->oldact[signum] = talloc(sig_state, struct sigaction);
316                 if (sig_state->oldact[signum] == NULL) {
317                         talloc_free(se);
318                         return NULL;                    
319                 }
320                 if (sigaction(signum, &act, sig_state->oldact[signum]) == -1) {
321                         talloc_free(se);
322                         return NULL;
323                 }
324         }
325
326         DLIST_ADD(se->event_ctx->signal_events, se);
327
328         /* Make sure the signal doesn't come in while we're mangling list. */
329         sigemptyset(&set);
330         sigaddset(&set, signum);
331         sigprocmask(SIG_BLOCK, &set, &oldset);
332         DLIST_ADD(sig_state->sig_handlers[signum], sl);
333         sigprocmask(SIG_SETMASK, &oldset, NULL);
334
335         talloc_set_destructor(se, tevent_signal_destructor);
336         talloc_set_destructor(sl, tevent_common_signal_list_destructor);
337
338         return se;
339 }
340
341
342 /*
343   check if a signal is pending
344   return != 0 if a signal was pending
345 */
346 int tevent_common_check_signal(struct tevent_context *ev)
347 {
348         int i;
349
350         if (!sig_state || !TEVENT_SIG_PENDING(sig_state->got_signal)) {
351                 return 0;
352         }
353         
354         for (i=0;i<TEVENT_NUM_SIGNALS+1;i++) {
355                 struct tevent_common_signal_list *sl, *next;
356                 struct tevent_sigcounter counter = sig_state->signal_count[i];
357                 uint32_t count = tevent_sig_count(counter);
358 #ifdef SA_SIGINFO
359                 /* Ensure we null out any stored siginfo_t entries
360                  * after processing for debugging purposes. */
361                 bool clear_processed_siginfo = false;
362 #endif
363
364                 if (count == 0) {
365                         continue;
366                 }
367                 for (sl=sig_state->sig_handlers[i];sl;sl=next) {
368                         struct tevent_signal *se = sl->se;
369                         next = sl->next;
370 #ifdef SA_SIGINFO
371                         if (se->sa_flags & SA_SIGINFO) {
372                                 uint32_t j;
373
374                                 clear_processed_siginfo = true;
375
376                                 for (j=0;j<count;j++) {
377                                         /* sig_state->signal_count[i].seen
378                                          * % TEVENT_SA_INFO_QUEUE_COUNT is
379                                          * the base position of the unprocessed
380                                          * signals in the ringbuffer. */
381                                         uint32_t ofs = (counter.seen + j)
382                                                 % TEVENT_SA_INFO_QUEUE_COUNT;
383                                         se->handler(ev, se, i, 1,
384                                                     (void*)&sig_state->sig_info[i][ofs], 
385                                                     se->private_data);
386                                 }
387 #ifdef SA_RESETHAND
388                                 if (se->sa_flags & SA_RESETHAND) {
389                                         talloc_free(se);
390                                 }
391 #endif
392                                 continue;
393                         }
394 #endif
395                         se->handler(ev, se, i, count, NULL, se->private_data);
396 #ifdef SA_RESETHAND
397                         if (se->sa_flags & SA_RESETHAND) {
398                                 talloc_free(se);
399                         }
400 #endif
401                 }
402
403 #ifdef SA_SIGINFO
404                 if (clear_processed_siginfo) {
405                         uint32_t j;
406                         for (j=0;j<count;j++) {
407                                 uint32_t ofs = (counter.seen + j)
408                                         % TEVENT_SA_INFO_QUEUE_COUNT;
409                                 memset((void*)&sig_state->sig_info[i][ofs],
410                                         '\0',
411                                         sizeof(siginfo_t));
412                         }
413                 }
414 #endif
415
416                 TEVENT_SIG_SEEN(sig_state->signal_count[i], count);
417                 TEVENT_SIG_SEEN(sig_state->got_signal, count);
418
419 #ifdef SA_SIGINFO
420                 if (TEVENT_SIG_PENDING(sig_state->sig_blocked[i])) {
421                         /* We'd filled the queue, unblock the
422                            signal now the queue is empty again.
423                            Note we MUST do this after the
424                            TEVENT_SIG_SEEN(sig_state->signal_count[i], count)
425                            call to prevent a new signal running
426                            out of room in the sig_state->sig_info[i][]
427                            ring buffer. */
428                         sigset_t set;
429                         sigemptyset(&set);
430                         sigaddset(&set, i);
431                         TEVENT_SIG_SEEN(sig_state->sig_blocked[i],
432                                  tevent_sig_count(sig_state->sig_blocked[i]));
433                         sigprocmask(SIG_UNBLOCK, &set, NULL);
434                 }
435 #endif
436         }
437
438         return 1;
439 }
440
441 void tevent_cleanup_pending_signal_handlers(struct tevent_signal *se)
442 {
443         struct tevent_common_signal_list *sl;
444         sl = talloc_get_type(se->additional_data,
445                              struct tevent_common_signal_list);
446
447         tevent_common_signal_list_destructor(sl);
448
449         if (sig_state->sig_handlers[se->signum] == NULL) {
450                 if (sig_state->oldact[se->signum]) {
451                         sigaction(se->signum, sig_state->oldact[se->signum], NULL);
452                         sig_state->oldact[se->signum] = NULL;
453                 }
454         }
455         return;
456 }