don't crash
[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 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 SA_INFO_QUEUE_COUNT 64
41
42 struct sigcounter {
43         uint32_t count;
44         uint32_t seen;
45 };
46
47 #define SIG_INCREMENT(s) (s).count++
48 #define SIG_SEEN(s, n) (s).seen += (n)
49 #define 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 sig_state {
60         struct tevent_common_signal_list *sig_handlers[NUM_SIGNALS+1];
61         struct sigaction *oldact[NUM_SIGNALS+1];
62         struct sigcounter signal_count[NUM_SIGNALS+1];
63         struct 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[NUM_SIGNALS+1];
67         struct sigcounter sig_blocked[NUM_SIGNALS+1];
68 #endif
69 } *sig_state;
70
71 /*
72   return number of sigcounter events not processed yet
73 */
74 static uint32_t sig_count(struct 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         SIG_INCREMENT(sig_state->signal_count[signum]);
91         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 != ev) {
96                         ev = sl->se->event_ctx;
97                         if (!ev) continue;
98                         if (!ev->pipe_fds) continue;
99                         /* doesn't matter if this pipe overflows */
100                         res = write(ev->pipe_fds[1], &c, 1);
101                 }
102         }
103
104         errno = saved_errno;
105 }
106
107 #ifdef SA_SIGINFO
108 /*
109   signal handler with SA_SIGINFO - redirects to registered signals
110 */
111 static void tevent_common_signal_handler_info(int signum, siginfo_t *info,
112                                               void *uctx)
113 {
114         uint32_t count = sig_count(sig_state->signal_count[signum]);
115         /* sig_state->signal_count[signum].seen % SA_INFO_QUEUE_COUNT
116          * is the base of the unprocessed signals in the ringbuffer. */
117         uint32_t ofs = (sig_state->signal_count[signum].seen + count) %
118                                 SA_INFO_QUEUE_COUNT;
119         sig_state->sig_info[signum][ofs] = *info;
120
121         tevent_common_signal_handler(signum);
122
123         /* handle SA_SIGINFO */
124         if (count+1 == SA_INFO_QUEUE_COUNT) {
125                 /* we've filled the info array - block this signal until
126                    these ones are delivered */
127                 sigset_t set;
128                 sigemptyset(&set);
129                 sigaddset(&set, signum);
130                 sigprocmask(SIG_BLOCK, &set, NULL);
131                 SIG_INCREMENT(sig_state->sig_blocked[signum]);
132         }
133 }
134 #endif
135
136 static int tevent_common_signal_list_destructor(struct tevent_common_signal_list *sl)
137 {
138         DLIST_REMOVE(sig_state->sig_handlers[sl->se->signum], sl);
139         return 0;
140 }
141
142 /*
143   destroy a signal event
144 */
145 static int tevent_signal_destructor(struct tevent_signal *se)
146 {
147         struct tevent_common_signal_list *sl;
148         sl = talloc_get_type(se->additional_data,
149                              struct tevent_common_signal_list);
150
151         if (se->event_ctx) {
152                 DLIST_REMOVE(se->event_ctx->signal_events, se);
153         }
154
155         talloc_free(sl);
156
157         if (sig_state->sig_handlers[se->signum] == NULL) {
158                 /* restore old handler, if any */
159                 sigaction(se->signum, sig_state->oldact[se->signum], NULL);
160                 sig_state->oldact[se->signum] = NULL;
161 #ifdef SA_SIGINFO
162                 if (se->sa_flags & SA_SIGINFO) {
163                         talloc_free(sig_state->sig_info[se->signum]);
164                         sig_state->sig_info[se->signum] = NULL;
165                 }
166 #endif
167         }
168
169         return 0;
170 }
171
172 /*
173   this is part of the pipe hack needed to avoid the signal race condition
174 */
175 static void signal_pipe_handler(struct tevent_context *ev, struct tevent_fd *fde, 
176                                 uint16_t flags, void *_private)
177 {
178         char c[16];
179         ssize_t res;
180         /* its non-blocking, doesn't matter if we read too much */
181         res = read(fde->fd, c, sizeof(c));
182 }
183
184 /*
185   add a signal event
186   return NULL on failure (memory allocation error)
187 */
188 struct tevent_signal *tevent_common_add_signal(struct tevent_context *ev,
189                                                TALLOC_CTX *mem_ctx,
190                                                int signum,
191                                                int sa_flags,
192                                                tevent_signal_handler_t handler,
193                                                void *private_data,
194                                                const char *handler_name,
195                                                const char *location)
196 {
197         struct tevent_signal *se;
198         struct tevent_common_signal_list *sl;
199         sigset_t set, oldset;
200
201         if (signum >= NUM_SIGNALS) {
202                 errno = EINVAL;
203                 return NULL;
204         }
205
206         /* the sig_state needs to be on a global context as it can last across
207            multiple event contexts */
208         if (sig_state == NULL) {
209                 sig_state = talloc_zero(talloc_autofree_context(), struct sig_state);
210                 if (sig_state == NULL) {
211                         return NULL;
212                 }
213         }
214
215         se = talloc(mem_ctx?mem_ctx:ev, struct tevent_signal);
216         if (se == NULL) return NULL;
217
218         se->event_ctx           = ev;
219         se->signum              = signum;
220         se->sa_flags            = sa_flags;
221         se->handler             = handler;
222         se->private_data        = private_data;
223         se->handler_name        = handler_name;
224         se->location            = location;
225         se->additional_data     = NULL;
226
227         sl = talloc(se, struct tevent_common_signal_list);
228         if (!sl) {
229                 talloc_free(se);
230                 return NULL;
231         }
232         sl->se = se;
233         se->additional_data     = sl;
234
235         /* Ensure, no matter the destruction order, that we always have a handle on the global sig_state */
236         if (!talloc_reference(se, sig_state)) {
237                 talloc_free(se);
238                 return NULL;
239         }
240
241         /* we need to setup the pipe hack handler if not already
242            setup */
243         if (ev->pipe_fde == NULL) {
244                 if (pipe(ev->pipe_fds) == -1) {
245                         talloc_free(se);
246                         return NULL;
247                 }
248                 ev_set_blocking(ev->pipe_fds[0], false);
249                 ev_set_blocking(ev->pipe_fds[1], false);
250                 ev->pipe_fde = tevent_add_fd(ev, ev, ev->pipe_fds[0],
251                                              TEVENT_FD_READ,
252                                              signal_pipe_handler, NULL);
253                 if (!ev->pipe_fde) {
254                         close(ev->pipe_fds[0]);
255                         close(ev->pipe_fds[1]);
256                         talloc_free(se);
257                         return NULL;
258                 }
259         }
260
261         /* only install a signal handler if not already installed */
262         if (sig_state->sig_handlers[signum] == NULL) {
263                 struct sigaction act;
264                 ZERO_STRUCT(act);
265                 act.sa_handler = tevent_common_signal_handler;
266                 act.sa_flags = sa_flags;
267 #ifdef SA_SIGINFO
268                 if (sa_flags & SA_SIGINFO) {
269                         act.sa_handler   = NULL;
270                         act.sa_sigaction = tevent_common_signal_handler_info;
271                         if (sig_state->sig_info[signum] == NULL) {
272                                 sig_state->sig_info[signum] = talloc_zero_array(sig_state, siginfo_t, SA_INFO_QUEUE_COUNT);
273                                 if (sig_state->sig_info[signum] == NULL) {
274                                         talloc_free(se);
275                                         return NULL;
276                                 }
277                         }
278                 }
279 #endif
280                 sig_state->oldact[signum] = talloc(sig_state, struct sigaction);
281                 if (sig_state->oldact[signum] == NULL) {
282                         talloc_free(se);
283                         return NULL;                    
284                 }
285                 if (sigaction(signum, &act, sig_state->oldact[signum]) == -1) {
286                         talloc_free(se);
287                         return NULL;
288                 }
289         }
290
291         DLIST_ADD(se->event_ctx->signal_events, se);
292
293         /* Make sure the signal doesn't come in while we're mangling list. */
294         sigemptyset(&set);
295         sigaddset(&set, signum);
296         sigprocmask(SIG_BLOCK, &set, &oldset);
297         DLIST_ADD(sig_state->sig_handlers[signum], sl);
298         sigprocmask(SIG_SETMASK, &oldset, NULL);
299
300         talloc_set_destructor(se, tevent_signal_destructor);
301         talloc_set_destructor(sl, tevent_common_signal_list_destructor);
302
303         return se;
304 }
305
306
307 /*
308   check if a signal is pending
309   return != 0 if a signal was pending
310 */
311 int tevent_common_check_signal(struct tevent_context *ev)
312 {
313         int i;
314
315         if (!sig_state || !SIG_PENDING(sig_state->got_signal)) {
316                 return 0;
317         }
318         
319         for (i=0;i<NUM_SIGNALS+1;i++) {
320                 struct tevent_common_signal_list *sl, *next;
321                 struct sigcounter counter = sig_state->signal_count[i];
322                 uint32_t count = sig_count(counter);
323 #ifdef SA_SIGINFO
324                 /* Ensure we null out any stored siginfo_t entries
325                  * after processing for debugging purposes. */
326                 bool clear_processed_siginfo = false;
327 #endif
328
329                 if (count == 0) {
330                         continue;
331                 }
332                 for (sl=sig_state->sig_handlers[i];sl;sl=next) {
333                         struct tevent_signal *se = sl->se;
334                         next = sl->next;
335 #ifdef SA_SIGINFO
336                         if (se->sa_flags & SA_SIGINFO) {
337                                 uint32_t j;
338
339                                 clear_processed_siginfo = true;
340
341                                 for (j=0;j<count;j++) {
342                                         /* sig_state->signal_count[i].seen
343                                          * % SA_INFO_QUEUE_COUNT is
344                                          * the base position of the unprocessed
345                                          * signals in the ringbuffer. */
346                                         uint32_t ofs = (counter.seen + j)
347                                                 % SA_INFO_QUEUE_COUNT;
348                                         se->handler(ev, se, i, 1,
349                                                     (void*)&sig_state->sig_info[i][ofs], 
350                                                     se->private_data);
351                                 }
352                                 if (se->sa_flags & SA_RESETHAND) {
353                                         talloc_free(se);
354                                 }
355                                 continue;
356                         }
357 #endif
358                         se->handler(ev, se, i, count, NULL, se->private_data);
359                         if (se->sa_flags & SA_RESETHAND) {
360                                 talloc_free(se);
361                         }
362                 }
363
364 #ifdef SA_SIGINFO
365                 if (clear_processed_siginfo) {
366                         uint32_t j;
367                         for (j=0;j<count;j++) {
368                                 uint32_t ofs = (counter.seen + j)
369                                         % SA_INFO_QUEUE_COUNT;
370                                 memset((void*)&sig_state->sig_info[i][ofs],
371                                         '\0',
372                                         sizeof(siginfo_t));
373                         }
374                 }
375 #endif
376
377                 SIG_SEEN(sig_state->signal_count[i], count);
378                 SIG_SEEN(sig_state->got_signal, count);
379
380 #ifdef SA_SIGINFO
381                 if (SIG_PENDING(sig_state->sig_blocked[i])) {
382                         /* We'd filled the queue, unblock the
383                            signal now the queue is empty again.
384                            Note we MUST do this after the
385                            SIG_SEEN(sig_state->signal_count[i], count)
386                            call to prevent a new signal running
387                            out of room in the sig_state->sig_info[i][]
388                            ring buffer. */
389                         sigset_t set;
390                         sigemptyset(&set);
391                         sigaddset(&set, i);
392                         SIG_SEEN(sig_state->sig_blocked[i],
393                                  sig_count(sig_state->sig_blocked[i]));
394                         sigprocmask(SIG_UNBLOCK, &set, NULL);
395                 }
396 #endif
397         }
398
399         return 1;
400 }