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