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