tevent: define TEVENT_NUM_SIGNALS based on SIGRTMAX
[metze/samba/wip.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 #ifdef SIGRTMAX
34 #define TEVENT_NUM_SIGNALS (SIGRTMAX + 1)
35 #else
36 #define TEVENT_NUM_SIGNALS 64
37 #endif
38
39 /* maximum number of SA_SIGINFO signals to hold in the queue.
40   NB. This *MUST* be a power of 2, in order for the ring buffer
41   wrap to work correctly. Thanks to Petr Vandrovec <petr@vandrovec.name>
42   for this. */
43
44 #define TEVENT_SA_INFO_QUEUE_COUNT 64
45
46 struct tevent_sigcounter {
47         uint32_t count;
48         uint32_t seen;
49 };
50
51 #define TEVENT_SIG_INCREMENT(s) (s).count++
52 #define TEVENT_SIG_SEEN(s, n) (s).seen += (n)
53 #define TEVENT_SIG_PENDING(s) ((s).seen != (s).count)
54
55 struct tevent_common_signal_list {
56         struct tevent_common_signal_list *prev, *next;
57         struct tevent_signal *se;
58 };
59
60 /*
61   the poor design of signals means that this table must be static global
62 */
63 static struct tevent_sig_state {
64         struct tevent_common_signal_list *sig_handlers[TEVENT_NUM_SIGNALS+1];
65         struct sigaction *oldact[TEVENT_NUM_SIGNALS+1];
66         struct tevent_sigcounter signal_count[TEVENT_NUM_SIGNALS+1];
67         struct tevent_sigcounter got_signal;
68 #ifdef SA_SIGINFO
69         /* with SA_SIGINFO we get quite a lot of info per signal */
70         siginfo_t *sig_info[TEVENT_NUM_SIGNALS+1];
71         struct tevent_sigcounter sig_blocked[TEVENT_NUM_SIGNALS+1];
72 #endif
73 } *sig_state;
74
75 /*
76   return number of sigcounter events not processed yet
77 */
78 static uint32_t tevent_sig_count(struct tevent_sigcounter s)
79 {
80         return s.count - s.seen;
81 }
82
83 /*
84   signal handler - redirects to registered signals
85 */
86 static void tevent_common_signal_handler(int signum)
87 {
88         char c = 0;
89         struct tevent_common_signal_list *sl;
90         struct tevent_context *ev = NULL;
91         int saved_errno = errno;
92
93         TEVENT_SIG_INCREMENT(sig_state->signal_count[signum]);
94         TEVENT_SIG_INCREMENT(sig_state->got_signal);
95
96         /* Write to each unique event context. */
97         for (sl = sig_state->sig_handlers[signum]; sl; sl = sl->next) {
98                 if (sl->se->event_ctx && sl->se->event_ctx != ev) {
99                         ev = sl->se->event_ctx;
100                         /* doesn't matter if this pipe overflows */
101                         (void) write(ev->pipe_fds[1], &c, 1);
102                 }
103         }
104
105         errno = saved_errno;
106 }
107
108 #ifdef SA_SIGINFO
109 /*
110   signal handler with SA_SIGINFO - redirects to registered signals
111 */
112 static void tevent_common_signal_handler_info(int signum, siginfo_t *info,
113                                               void *uctx)
114 {
115         uint32_t count = tevent_sig_count(sig_state->signal_count[signum]);
116         /* sig_state->signal_count[signum].seen % TEVENT_SA_INFO_QUEUE_COUNT
117          * is the base of the unprocessed signals in the ringbuffer. */
118         uint32_t ofs = (sig_state->signal_count[signum].seen + count) %
119                                 TEVENT_SA_INFO_QUEUE_COUNT;
120         sig_state->sig_info[signum][ofs] = *info;
121
122         tevent_common_signal_handler(signum);
123
124         /* handle SA_SIGINFO */
125         if (count+1 == TEVENT_SA_INFO_QUEUE_COUNT) {
126                 /* we've filled the info array - block this signal until
127                    these ones are delivered */
128                 sigset_t set;
129                 sigemptyset(&set);
130                 sigaddset(&set, signum);
131                 sigprocmask(SIG_BLOCK, &set, NULL);
132                 TEVENT_SIG_INCREMENT(sig_state->sig_blocked[signum]);
133         }
134 }
135 #endif
136
137 static int tevent_common_signal_list_destructor(struct tevent_common_signal_list *sl)
138 {
139         if (sig_state->sig_handlers[sl->se->signum]) {
140                 DLIST_REMOVE(sig_state->sig_handlers[sl->se->signum], sl);
141         }
142         return 0;
143 }
144
145 /*
146   destroy a signal event
147 */
148 static int tevent_signal_destructor(struct tevent_signal *se)
149 {
150         struct tevent_common_signal_list *sl;
151         sl = talloc_get_type(se->additional_data,
152                              struct tevent_common_signal_list);
153
154         if (se->event_ctx) {
155                 DLIST_REMOVE(se->event_ctx->signal_events, se);
156         }
157
158         talloc_free(sl);
159
160         if (sig_state->sig_handlers[se->signum] == NULL) {
161                 /* restore old handler, if any */
162                 if (sig_state->oldact[se->signum]) {
163                         sigaction(se->signum, sig_state->oldact[se->signum], NULL);
164                         sig_state->oldact[se->signum] = NULL;
165                 }
166 #ifdef SA_SIGINFO
167                 if (se->sa_flags & SA_SIGINFO) {
168                         if (sig_state->sig_info[se->signum]) {
169                                 talloc_free(sig_state->sig_info[se->signum]);
170                                 sig_state->sig_info[se->signum] = NULL;
171                         }
172                 }
173 #endif
174         }
175
176         return 0;
177 }
178
179 /*
180   this is part of the pipe hack needed to avoid the signal race condition
181 */
182 static void signal_pipe_handler(struct tevent_context *ev, struct tevent_fd *fde, 
183                                 uint16_t flags, void *_private)
184 {
185         char c[16];
186         /* its non-blocking, doesn't matter if we read too much */
187         (void) read(fde->fd, c, sizeof(c));
188 }
189
190 /*
191   add a signal event
192   return NULL on failure (memory allocation error)
193 */
194 struct tevent_signal *tevent_common_add_signal(struct tevent_context *ev,
195                                                TALLOC_CTX *mem_ctx,
196                                                int signum,
197                                                int sa_flags,
198                                                tevent_signal_handler_t handler,
199                                                void *private_data,
200                                                const char *handler_name,
201                                                const char *location)
202 {
203         struct tevent_signal *se;
204         struct tevent_common_signal_list *sl;
205         sigset_t set, oldset;
206
207         if (signum >= TEVENT_NUM_SIGNALS) {
208                 errno = EINVAL;
209                 return NULL;
210         }
211
212         /* the sig_state needs to be on a global context as it can last across
213            multiple event contexts */
214         if (sig_state == NULL) {
215                 sig_state = talloc_zero(NULL, struct tevent_sig_state);
216                 if (sig_state == NULL) {
217                         return NULL;
218                 }
219         }
220
221         se = talloc(mem_ctx?mem_ctx:ev, struct tevent_signal);
222         if (se == NULL) return NULL;
223
224         se->event_ctx           = ev;
225         se->signum              = signum;
226         se->sa_flags            = sa_flags;
227         se->handler             = handler;
228         se->private_data        = private_data;
229         se->handler_name        = handler_name;
230         se->location            = location;
231         se->additional_data     = NULL;
232
233         sl = talloc(se, struct tevent_common_signal_list);
234         if (!sl) {
235                 talloc_free(se);
236                 return NULL;
237         }
238         sl->se = se;
239         se->additional_data     = sl;
240
241         /* Ensure, no matter the destruction order, that we always have a handle on the global sig_state */
242         if (!talloc_reference(se, sig_state)) {
243                 talloc_free(se);
244                 return NULL;
245         }
246
247         /* we need to setup the pipe hack handler if not already
248            setup */
249         if (ev->pipe_fde == NULL) {
250                 if (pipe(ev->pipe_fds) == -1) {
251                         talloc_free(se);
252                         return NULL;
253                 }
254                 ev_set_blocking(ev->pipe_fds[0], false);
255                 ev_set_blocking(ev->pipe_fds[1], false);
256                 ev->pipe_fde = tevent_add_fd(ev, ev, ev->pipe_fds[0],
257                                              TEVENT_FD_READ,
258                                              signal_pipe_handler, NULL);
259                 if (!ev->pipe_fde) {
260                         close(ev->pipe_fds[0]);
261                         close(ev->pipe_fds[1]);
262                         talloc_free(se);
263                         return NULL;
264                 }
265         }
266
267         /* only install a signal handler if not already installed */
268         if (sig_state->sig_handlers[signum] == NULL) {
269                 struct sigaction act;
270                 ZERO_STRUCT(act);
271                 act.sa_handler = tevent_common_signal_handler;
272                 act.sa_flags = sa_flags;
273 #ifdef SA_SIGINFO
274                 if (sa_flags & SA_SIGINFO) {
275                         act.sa_handler   = NULL;
276                         act.sa_sigaction = tevent_common_signal_handler_info;
277                         if (sig_state->sig_info[signum] == NULL) {
278                                 sig_state->sig_info[signum] =
279                                         talloc_zero_array(sig_state, siginfo_t,
280                                                           TEVENT_SA_INFO_QUEUE_COUNT);
281                                 if (sig_state->sig_info[signum] == NULL) {
282                                         talloc_free(se);
283                                         return NULL;
284                                 }
285                         }
286                 }
287 #endif
288                 sig_state->oldact[signum] = talloc(sig_state, struct sigaction);
289                 if (sig_state->oldact[signum] == NULL) {
290                         talloc_free(se);
291                         return NULL;                    
292                 }
293                 if (sigaction(signum, &act, sig_state->oldact[signum]) == -1) {
294                         talloc_free(se);
295                         return NULL;
296                 }
297         }
298
299         DLIST_ADD(se->event_ctx->signal_events, se);
300
301         /* Make sure the signal doesn't come in while we're mangling list. */
302         sigemptyset(&set);
303         sigaddset(&set, signum);
304         sigprocmask(SIG_BLOCK, &set, &oldset);
305         DLIST_ADD(sig_state->sig_handlers[signum], sl);
306         sigprocmask(SIG_SETMASK, &oldset, NULL);
307
308         talloc_set_destructor(se, tevent_signal_destructor);
309         talloc_set_destructor(sl, tevent_common_signal_list_destructor);
310
311         return se;
312 }
313
314 struct tevent_se_exists {
315         struct tevent_se_exists **myself;
316 };
317
318 static int tevent_se_exists_destructor(struct tevent_se_exists *s)
319 {
320         *s->myself = NULL;
321         return 0;
322 }
323
324 /*
325   check if a signal is pending
326   return != 0 if a signal was pending
327 */
328 int tevent_common_check_signal(struct tevent_context *ev)
329 {
330         int i;
331
332         if (!sig_state || !TEVENT_SIG_PENDING(sig_state->got_signal)) {
333                 return 0;
334         }
335         
336         for (i=0;i<TEVENT_NUM_SIGNALS+1;i++) {
337                 struct tevent_common_signal_list *sl, *next;
338                 struct tevent_sigcounter counter = sig_state->signal_count[i];
339                 uint32_t count = tevent_sig_count(counter);
340 #ifdef SA_SIGINFO
341                 /* Ensure we null out any stored siginfo_t entries
342                  * after processing for debugging purposes. */
343                 bool clear_processed_siginfo = false;
344 #endif
345
346                 if (count == 0) {
347                         continue;
348                 }
349                 for (sl=sig_state->sig_handlers[i];sl;sl=next) {
350                         struct tevent_signal *se = sl->se;
351                         struct tevent_se_exists *exists;
352
353                         next = sl->next;
354
355                         /*
356                          * We have to be careful to not touch "se"
357                          * after it was deleted in its handler. Thus
358                          * we allocate a child whose destructor will
359                          * tell by nulling out itself that its parent
360                          * is gone.
361                          */
362                         exists = talloc(se, struct tevent_se_exists);
363                         if (exists == NULL) {
364                                 continue;
365                         }
366                         exists->myself = &exists;
367                         talloc_set_destructor(
368                                 exists, tevent_se_exists_destructor);
369
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                                         if (!exists) {
387                                                 break;
388                                         }
389                                 }
390 #ifdef SA_RESETHAND
391                                 if (exists && (se->sa_flags & SA_RESETHAND)) {
392                                         talloc_free(se);
393                                 }
394 #endif
395                                 talloc_free(exists);
396                                 continue;
397                         }
398 #endif
399                         se->handler(ev, se, i, count, NULL, se->private_data);
400 #ifdef SA_RESETHAND
401                         if (exists && (se->sa_flags & SA_RESETHAND)) {
402                                 talloc_free(se);
403                         }
404 #endif
405                         talloc_free(exists);
406                 }
407
408 #ifdef SA_SIGINFO
409                 if (clear_processed_siginfo) {
410                         uint32_t j;
411                         for (j=0;j<count;j++) {
412                                 uint32_t ofs = (counter.seen + j)
413                                         % TEVENT_SA_INFO_QUEUE_COUNT;
414                                 memset((void*)&sig_state->sig_info[i][ofs],
415                                         '\0',
416                                         sizeof(siginfo_t));
417                         }
418                 }
419 #endif
420
421                 TEVENT_SIG_SEEN(sig_state->signal_count[i], count);
422                 TEVENT_SIG_SEEN(sig_state->got_signal, count);
423
424 #ifdef SA_SIGINFO
425                 if (TEVENT_SIG_PENDING(sig_state->sig_blocked[i])) {
426                         /* We'd filled the queue, unblock the
427                            signal now the queue is empty again.
428                            Note we MUST do this after the
429                            TEVENT_SIG_SEEN(sig_state->signal_count[i], count)
430                            call to prevent a new signal running
431                            out of room in the sig_state->sig_info[i][]
432                            ring buffer. */
433                         sigset_t set;
434                         sigemptyset(&set);
435                         sigaddset(&set, i);
436                         TEVENT_SIG_SEEN(sig_state->sig_blocked[i],
437                                  tevent_sig_count(sig_state->sig_blocked[i]));
438                         sigprocmask(SIG_UNBLOCK, &set, NULL);
439                 }
440 #endif
441         }
442
443         return 1;
444 }
445
446 void tevent_cleanup_pending_signal_handlers(struct tevent_signal *se)
447 {
448         struct tevent_common_signal_list *sl;
449         sl = talloc_get_type(se->additional_data,
450                              struct tevent_common_signal_list);
451
452         tevent_common_signal_list_destructor(sl);
453
454         if (sig_state->sig_handlers[se->signum] == NULL) {
455                 if (sig_state->oldact[se->signum]) {
456                         sigaction(se->signum, sig_state->oldact[se->signum], NULL);
457                         sig_state->oldact[se->signum] = NULL;
458                 }
459         }
460         return;
461 }