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