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