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