The FreeRADIUS server $Id: a4e7f8c94e8038b7627bcf52356b7ed15955c1d7 $
Loading...
Searching...
No Matches
event.c
Go to the documentation of this file.
1/*
2 * This program is free software; you can redistribute it and/or modify
3 * it under the terms of the GNU General Public License as published by
4 * the Free Software Foundation; either version 2 of the License, or
5 * (at your option) any later version.
6 *
7 * This program is distributed in the hope that it will be useful,
8 * but WITHOUT ANY WARRANTY; without even the implied warranty of
9 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10 * GNU General Public License for more details.
11 *
12 * You should have received a copy of the GNU General Public License
13 * along with this program; if not, write to the Free Software
14 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
15 */
16
17/** Wrapper around libkqueue to make managing events easier
18 *
19 * Non-thread-safe event handling specific to FreeRADIUS.
20 *
21 * By non-thread-safe we mean multiple threads can't insert/delete
22 * events concurrently into the same event list without synchronization.
23 *
24 * @file src/lib/util/event.c
25 *
26 * @copyright 2007-2016 The FreeRADIUS server project
27 * @copyright 2016 Arran Cudbard-Bell (a.cudbardb@freeradius.org)
28 * @copyright 2007 Alan DeKok (aland@freeradius.org)
29 */
30RCSID("$Id: 681e7297e9d61326d64d80561913749ca7f1ca2a $")
31
32#define _EVENT_LIST_PRIVATE 1
34
35#include <freeradius-devel/util/dlist.h>
36#include <freeradius-devel/util/event.h>
37#include <freeradius-devel/util/log.h>
38#include <freeradius-devel/util/rb.h>
39#include <freeradius-devel/util/strerror.h>
40#include <freeradius-devel/util/syserror.h>
41#include <freeradius-devel/util/token.h>
42#include <freeradius-devel/util/atexit.h>
43
44#include <sys/stat.h>
45#include <sys/wait.h>
46#ifdef __linux__
47#include <sys/inotify.h>
48#endif
49
50#ifdef NDEBUG
51/*
52 * Turn off documentation warnings as file/line
53 * args aren't used for non-debug builds.
54 */
55DIAG_OFF_OPTIONAL(documentation)
56#endif
57
58#define FR_EV_BATCH_FDS (256)
59
60DIAG_OFF(unused-macros)
61#define fr_time() static_assert(0, "Use el->time for event loop timing")
62DIAG_ON(unused-macros)
63
64#if !defined(SO_GET_FILTER) && defined(SO_ATTACH_FILTER)
65# define SO_GET_FILTER SO_ATTACH_FILTER
66#endif
67
69#ifdef EVFILT_AIO
70 { L("EVFILT_AIO"), EVFILT_AIO },
71#endif
72#ifdef EVFILT_EXCEPT
73 { L("EVFILT_EXCEPT"), EVFILT_EXCEPT },
74#endif
75#ifdef EVFILT_MACHPORT
76 { L("EVFILT_MACHPORT"), EVFILT_MACHPORT },
77#endif
78 { L("EVFILT_PROC"), EVFILT_PROC },
79 { L("EVFILT_READ"), EVFILT_READ },
80 { L("EVFILT_SIGNAL"), EVFILT_SIGNAL },
81 { L("EVFILT_TIMER"), EVFILT_TIMER },
82 { L("EVFILT_VNODE"), EVFILT_VNODE },
83 { L("EVFILT_WRITE"), EVFILT_WRITE }
84};
86
87#ifdef EVFILT_LIBKQUEUE
88static int log_conf_kq;
89#endif
90
91typedef enum : uint8_t {
92 FR_EVENT_FD_SOCKET = 1, //!< is a socket.
93 FR_EVENT_FD_FILE = 2, //!< is a file.
94 FR_EVENT_FD_DIRECTORY = 4, //!< is a directory.
95
96#ifdef SO_GET_FILTER
98#endif
100
101typedef enum : uint8_t {
103
104 FR_EVENT_FUNC_IDX_FILTER, //!< Sign flip is performed i.e. -1 = 0The filter is used
105 //// as the index in the ev to func index.
106 FR_EVENT_FUNC_IDX_FFLAGS //!< The bit position of the flags in FFLAGS
107 ///< is used to provide the index.
108 ///< i.e. 0x01 -> 0, 0x02 -> 1, 0x08 -> 3 etc..
110
111#ifndef SO_GET_FILTER
112# define FR_EVENT_FD_PCAP 0
113#endif
114
115/** Specifies a mapping between a function pointer in a structure and its respective event
116 *
117 * If the function pointer at the specified offset is set, then a matching event
118 * will be added.
119 *
120 * If the function pointer is NULL, then any existing events will be removed.
121 */
122typedef struct {
123 size_t offset; //!< Offset of function pointer in structure.
124 char const *name; //!< Name of the event.
125 int16_t filter; //!< Filter to apply.
126 uint16_t flags; //!< Flags to use for inserting event.
127 uint32_t fflags; //!< fflags to pass to filter.
128#ifdef __linux__
129 uint32_t inotify_mask; //!< inotify mask for this event.
130#endif
131 int type; //!< Type this filter applies to.
132 bool coalesce; //!< Coalesce this map with the next.
134
135typedef struct {
136 fr_event_func_idx_type_t idx_type; //!< What type of index we use for
137 ///< event to function mapping.
138 fr_event_func_map_entry_t *func_to_ev; //!< Function -> Event maps coalesced, out of order.
139 fr_event_func_map_entry_t **ev_to_func; //!< Function -> Event maps in index order.
141
145 .func_to_ev = (fr_event_func_map_entry_t[]){
146 {
147 .offset = offsetof(fr_event_io_func_t, read),
148 .name = "read",
149 .filter = EVFILT_READ,
150 .flags = EV_ADD | EV_ENABLE,
151#ifdef NOTE_NONE
152 .fflags = NOTE_NONE,
153#else
154 .fflags = 0,
155#endif
157 },
158 {
159 .offset = offsetof(fr_event_io_func_t, write),
160 .name = "write",
161 .filter = EVFILT_WRITE,
162 .flags = EV_ADD | EV_ENABLE,
163 .fflags = 0,
165 },
166 { 0 }
167 }
168 },
170 .idx_type = FR_EVENT_FUNC_IDX_FFLAGS,
171 .func_to_ev = (fr_event_func_map_entry_t[]){
172 {
173 .offset = offsetof(fr_event_vnode_func_t, delete),
174 .name = "delete",
175 .filter = EVFILT_VNODE,
176 .flags = EV_ADD | EV_ENABLE | EV_CLEAR,
177 .fflags = NOTE_DELETE,
178#ifdef __linux__
179 .inotify_mask = IN_ATTRIB | IN_DELETE_SELF,
180#endif
182 .coalesce = true
183 },
184 {
185 .offset = offsetof(fr_event_vnode_func_t, write),
186 .name = "write",
187 .filter = EVFILT_VNODE,
188 .flags = EV_ADD | EV_ENABLE | EV_CLEAR,
189 .fflags = NOTE_WRITE,
190#ifdef __linux__
191 .inotify_mask = IN_MODIFY,
192#endif
193 .type = FR_EVENT_FD_FILE,
194 .coalesce = true
195 },
196 {
197 .offset = offsetof(fr_event_vnode_func_t, extend),
198 .name = "extend",
199 .filter = EVFILT_VNODE,
200 .flags = EV_ADD | EV_ENABLE | EV_CLEAR,
201 .fflags = NOTE_EXTEND,
202#ifdef __linux__
203 .inotify_mask = IN_CREATE,
204#endif
206 .coalesce = true
207 },
208 {
209 .offset = offsetof(fr_event_vnode_func_t, attrib),
210 .name = "attrib",
211 .filter = EVFILT_VNODE,
212 .flags = EV_ADD | EV_ENABLE | EV_CLEAR,
213 .fflags = NOTE_ATTRIB,
214#ifdef __linux__
215 .inotify_mask = IN_ATTRIB,
216#endif
217 .type = FR_EVENT_FD_FILE,
218 .coalesce = true
219 },
220 {
221 .offset = offsetof(fr_event_vnode_func_t, link),
222 .name = "link",
223 .filter = EVFILT_VNODE,
224 .flags = EV_ADD | EV_ENABLE | EV_CLEAR,
225 .fflags = NOTE_LINK,
226#ifdef __linux__
227 .inotify_mask = IN_ATTRIB,
228#endif
229 .type = FR_EVENT_FD_FILE,
230 .coalesce = true
231 },
232 {
233 .offset = offsetof(fr_event_vnode_func_t, rename),
234 .name = "rename",
235 .filter = EVFILT_VNODE,
236 .flags = EV_ADD | EV_ENABLE | EV_CLEAR,
237 .fflags = NOTE_RENAME,
238#ifdef __linux__
239 .inotify_mask = IN_MOVE_SELF,
240#endif
241 .type = FR_EVENT_FD_FILE,
242 .coalesce = true
243 },
244#ifdef NOTE_REVOKE
245 {
246 .offset = offsetof(fr_event_vnode_func_t, revoke),
247 .name = "revoke",
248 .filter = EVFILT_VNODE,
249 .flags = EV_ADD | EV_ENABLE | EV_CLEAR,
250 .fflags = NOTE_REVOKE,
251 .type = FR_EVENT_FD_FILE,
252 .coalesce = true
253 },
254#endif
255#ifdef NOTE_FUNLOCK
256 {
257 .offset = offsetof(fr_event_vnode_func_t, funlock),
258 .name = "funlock",
259 .filter = EVFILT_VNODE,
260 .flags = EV_ADD | EV_ENABLE | EV_CLEAR,
261 .fflags = NOTE_FUNLOCK,
262 .type = FR_EVENT_FD_FILE,
263 .coalesce = true
264 },
265#endif
266 { 0 }
267 }
268 }
269};
270
272 { L("directory"), FR_EVENT_FD_DIRECTORY },
273 { L("file"), FR_EVENT_FD_FILE },
274 { L("pcap"), FR_EVENT_FD_PCAP },
275 { L("socket"), FR_EVENT_FD_SOCKET }
276};
278
279/** A file descriptor/filter event
280 *
281 */
283 fr_rb_node_t node; //!< Entry in the tree of file descriptor handles.
284 ///< this should really go away and we should pass around
285 ///< handles directly.
286
287 fr_event_list_t *el; //!< Event list this event belongs to.
289 int fd; //!< File descriptor we're listening for events on.
290
291 fr_event_fd_type_t type; //!< Type of events we're interested in.
292
293 int sock_type; //!< The type of socket SOCK_STREAM, SOCK_RAW etc...
294
295 fr_event_funcs_t active; //!< Active filter functions.
296 fr_event_funcs_t stored; //!< Stored (set, but inactive) filter functions.
297
298 fr_event_error_cb_t error; //!< Callback for when an error occurs on the FD.
299
300 fr_event_func_map_t const *map; //!< Function map between #fr_event_funcs_t and kevent filters.
301
302 bool is_registered; //!< Whether this fr_event_fd_t's FD has been registered with
303 ///< kevent. Mostly for debugging.
304
305 void *uctx; //!< Context pointer to pass to each file descriptor callback.
306 TALLOC_CTX *linked_ctx; //!< talloc ctx this event was bound to.
307
308 fr_dlist_t entry; //!< Entry in free list.
309
310#ifndef NDEBUG
311 uintptr_t armour; //!< protection flag from being deleted.
312#endif
313
314#ifndef NDEBUG
315 char const *file; //!< Source file this event was last updated in.
316 int line; //!< Line this event was last updated on.
317#endif
318};
319
321 fr_event_list_t *el; //!< Event list this event belongs to.
322
323 bool is_registered; //!< Whether this user event has been registered
324 ///< with the event loop.
325
326 pid_t pid; //!< child to wait for
328
329 fr_event_pid_cb_t callback; //!< callback to run when the child exits
330 void *uctx; //!< Context pointer to pass to each file descriptor callback.
331
332 /** Fields that are only used if we're being triggered by a user event
333 */
334 struct {
335 fr_event_user_t *ev; //!< Fallback user event we use to raise a PID event when
336 ///< a race occurs with kevent.
337 int status; //!< Status we got from waitid.
339#ifndef NDEBUG
340 char const *file; //!< Source file this event was last updated in.
341 int line; //!< Line this event was last updated on.
342#endif
343};
344
345/** Hold additional information for automatically reaped PIDs
346 */
347typedef struct {
348 fr_event_list_t *el; //!< Event list this event belongs to.
349 fr_event_pid_t const *pid_ev; //!< pid_ev this reaper is bound to.
350
351 fr_dlist_t entry; //!< If the fr_event_pid is in the detached, reap state,
352 ///< it's inserted into a list associated with the event.
353 //!< We then send SIGKILL, and forcefully reap the process
354 ///< on exit.
355
356 fr_event_pid_cb_t callback; //!< callback to run when the child exits
357 void *uctx; //!< Context pointer to pass to each file descriptor callback.
359
360/** Callbacks for kevent() user events
361 *
362 */
364 fr_event_list_t *el; //!< Event list this event belongs to.
365
366 bool is_registered; //!< Whether this user event has been registered
367 ///< with the event loop.
368
369 fr_event_user_cb_t callback; //!< The callback to call.
370 void *uctx; //!< Context for the callback.
371
372#ifndef NDEBUG
373 char const *file; //!< Source file this event was last updated in.
374 int line; //!< Line this event was last updated on.
375#endif
376};
377
378#ifdef __linux__
379struct fr_event_file_watch {
380 fr_event_list_t *el; //!< Event list this event belongs to.
381
382 int fd; //!< fd for the file / directory being watched.
383 char const *name; //!< Name of file / directory being watched.
384
385 int in_fd; //!< fd that inotify will report events on.
386 fr_event_fd_t *fd_ev; //!< Kqueue event for reads from inotify fd.
387 int wd; //!< watch descriptor from inotify_add_watch.
388
389 fr_event_vnode_func_t funcs; //!< Callback functions
390 void *uctx; //!< Context for the callback functions
391};
392#endif
393
394/** Callbacks to perform when the event handler is about to check the events
395 *
396 */
397typedef struct {
398 fr_dlist_t entry; //!< Linked list of callback.
399 fr_event_status_cb_t callback; //!< The callback to call.
400 void *uctx; //!< Context for the callback.
402
403/** Callbacks to perform after all timers and FDs have been checked
404 *
405 */
406typedef struct {
407 fr_dlist_t entry; //!< Linked list of callback.
408 fr_event_post_cb_t callback; //!< The callback to call.
409 void *uctx; //!< Context for the callback.
411
412/** Stores all information relating to an event list
413 *
414 */
416 struct fr_event_list_pub_s pub; //!< Next event list in the chain.
417 fr_rb_tree_t *fds; //!< Tree used to track FDs with filters in kqueue.
418
419 int will_exit; //!< Will exit on next call to fr_event_corral.
420 int exit; //!< If non-zero event loop will prevent the addition
421 ///< of new events, and will return immediately
422 ///< from the corral/service function.
423
424 bool dispatch; //!< Whether the event list is currently dispatching events.
425
426 int num_fd_events; //!< Number of events in this event list.
427
428 int kq; //!< instance associated with this event list.
429
430 fr_dlist_head_t pre_callbacks; //!< callbacks when we may be idle...
431 fr_dlist_head_t post_callbacks; //!< post-processing callbacks
432
433 fr_dlist_head_t pid_to_reap; //!< A list of all orphaned child processes we're
434 ///< waiting to reap.
435
436 struct kevent events[FR_EV_BATCH_FDS]; /* so it doesn't go on the stack every time */
437
438 bool in_handler; //!< Deletes should be deferred until after the
439 ///< handlers complete.
440
441 fr_dlist_head_t fd_to_free; //!< File descriptor events pending deletion.
442
443#ifdef WITH_EVENT_DEBUG
444 fr_timer_t *report; //!< Report event.
445#endif
446};
447
449{
450 switch (map->idx_type) {
451 default:
452 return;
453
454 /*
455 * - Figure out the lowest filter value
456 * - Invert it
457 * - Allocate an array
458 * - Populate the array
459 */
461 {
462 int low = 0;
464
465 for (entry = map->func_to_ev; entry->name; entry++) if (entry->filter < low) low = entry->filter;
466
467 map->ev_to_func = talloc_zero_array(NULL, fr_event_func_map_entry_t *, ~low + 1);
468 if (unlikely(!map->ev_to_func)) abort();
469
470 for (entry = map->func_to_ev; entry->name; entry++) map->ev_to_func[~entry->filter] = entry;
471 }
472 break;
473
474 /*
475 * - Figure out the highest bit position
476 * - Allocate an array
477 * - Populate the array
478 */
480 {
481 uint8_t high = 0, pos;
483
484 for (entry = map->func_to_ev; entry->name; entry++) {
485 pos = fr_high_bit_pos(entry->fflags);
486 if (pos > high) high = pos;
487 }
488
489 map->ev_to_func = talloc_zero_array(NULL, fr_event_func_map_entry_t *, high);
490 if (unlikely(!map->ev_to_func)) abort();
491
492 for (entry = map->func_to_ev; entry->name; entry++) {
493 typeof_field(fr_event_func_map_entry_t, fflags) fflags = entry->fflags;
494
495 /*
496 * Multiple notes can be associated
497 * with the same function. fflags & (fflags - 1)
498 * clears the lowest set bit.
499 */
500 while (fflags) {
501 map->ev_to_func[fr_low_bit_pos(fflags) - 1] = entry;
502 fflags &= fflags - 1;
503 }
504 }
505 }
506 break;
507 }
508}
509
510/** Figure out which function to call given a kevent
511 *
512 * This function should be called in a loop until it returns NULL.
513 *
514 * @param[in] ef File descriptor state handle.
515 * @param[in] filter from the kevent.
516 * @param[in,out] fflags from the kevent. Each call will return the function
517 * from the next most significant NOTE_*, with each
518 * NOTE_* before unset from fflags.
519 * @return
520 * - NULL there are no more callbacks to call.
521 * - The next callback to call.
522 */
523static inline CC_HINT(always_inline) fr_event_fd_cb_t event_fd_func(fr_event_fd_t *ef, int *filter, uint32_t *fflags)
524{
525 fr_event_func_map_t const *map = ef->map;
526
527#define GET_FUNC(_ef, _offset) *((fr_event_fd_cb_t const *)((uint8_t const *)&(_ef)->active + _offset))
528
529 switch (map->idx_type) {
530 default:
531 fr_assert_fail("Invalid index type %u", map->idx_type);
532 return NULL;
533
535 {
536 int idx;
537
538 if (!*filter) return NULL;
539
540 idx = ~*filter; /* Consume the filter */
541 *filter = 0;
542
543 return GET_FUNC(ef, map->ev_to_func[idx]->offset);
544 }
545
547 {
548 uint32_t our_fflags = *fflags;
549 uint8_t pos = fr_high_bit_pos(our_fflags);
550
551 if (!pos) return NULL; /* No more fflags to consume */
552 pos -= 1; /* Saves an array element */
553
554 *fflags = our_fflags & ~(UINT32_C(1) << pos); /* Consume the knote */
555
556 return GET_FUNC(ef, map->ev_to_func[pos]->offset);
557 }
558 }
559}
560
561/** Compare two file descriptor handles
562 *
563 * @param[in] one the first file descriptor handle.
564 * @param[in] two the second file descriptor handle.
565 * @return CMP(one, two)
566 */
567static fr_cmp_ret_t fr_event_fd_cmp(void const *one, void const *two)
568{
569 fr_event_fd_t const *a = one, *b = two;
570
571 CMP_RETURN(a, b, fd);
572
573 return CMP(a->filter, b->filter);
574}
575
576/** Return the number of file descriptors is_registered with this event loop
577 *
578 */
580{
581 if (unlikely(!el)) return 0;
582
583 return fr_rb_num_elements(el->fds);
584}
585
586/** Return the number of timer events currently scheduled
587 *
588 * @param[in] el to return timer events for.
589 * @return number of timer events.
590 */
592{
593 if (unlikely(!el)) return 0;
594
596}
597
598/** Return the kq associated with an event list.
599 *
600 * @param[in] el to return timer events for.
601 * @return kq
602 */
604{
605 if (unlikely(!el)) return -1;
606
607 return el->kq;
608}
609
610/** Get the current server time according to the event list
611 *
612 * If the event list is currently dispatching events, we return the time
613 * this iteration of the event list started.
614 *
615 * If the event list is not currently dispatching events, we return the
616 * current system time.
617 *
618 * @param[in] el to get time from.
619 * @return the current time according to the event list.
620 */
622{
623 return el->pub.tl->time();
624}
625
626/** Placeholder callback to avoid branches in service loop
627 *
628 * This is set in place of any NULL function pointers, so that the event loop doesn't
629 * SEGV if a filter callback function is unset between corral and service.
630 */
631static void fr_event_fd_noop(UNUSED fr_event_list_t *el, UNUSED int fd, UNUSED int flags, UNUSED void *uctx)
632{
633 return;
634}
635
636/** Build a new evset based on function pointers present
637 *
638 * @note The contents of active functions may be inconsistent if this function errors. But the
639 * only time that will occur is if the caller passed invalid arguments.
640 *
641 * @param[in] el we're building events for.
642 * @param[out] out_kev where to write the evset.
643 * @param[in] outlen length of output buffer.
644 * @param[out] active The set of function pointers with active filters.
645 * @param[in] ef event to insert.
646 * @param[in] new Functions to map to filters.
647 * @param[in] prev Previous set of functions mapped to filters.
648 * @return
649 * - >= 0 the number of changes written to out.
650 * - < 0 an error occurred.
651 */
653#ifndef WITH_EVENT_DEBUG
654 UNUSED
655#endif
657 struct kevent out_kev[], size_t outlen, fr_event_funcs_t *active,
658 fr_event_fd_t *ef,
659 fr_event_funcs_t const *new, fr_event_funcs_t const *prev)
660{
661 struct kevent *out = out_kev, *end = out + outlen;
662 fr_event_func_map_entry_t const *map;
663 struct kevent add[10], *add_p = add;
664 size_t i;
665
666 EVENT_DEBUG("%p - Building new evset for FD %i (new %p, prev %p)", el, ef->fd, new, prev);
667
668 /*
669 * Iterate over the function map, setting/unsetting
670 * filters and filter flags.
671 */
672 for (map = ef->map->func_to_ev; map->name; map++) {
673 bool has_current_func = false;
674 bool has_prev_func = false;
675 uint32_t current_fflags = 0;
676 uint32_t prev_fflags = 0;
677
678 do {
679 fr_event_fd_cb_t prev_func;
680 fr_event_fd_cb_t new_func;
681
682 /*
683 * If the previous value was the 'noop'
684 * callback, it's identical to being unset.
685 */
686 prev_func = *(fr_event_fd_cb_t const *)((uint8_t const *)prev + map->offset);
687 if (prev_func && (prev_func != fr_event_fd_noop)) {
688 EVENT_DEBUG("\t%s prev set (%p)", map->name, prev_func);
689 prev_fflags |= map->fflags;
690 has_prev_func = true;
691 } else {
692 EVENT_DEBUG("\t%s prev unset", map->name);
693 }
694
695 new_func = *(fr_event_fd_cb_t const *)((uint8_t const *)new + map->offset);
696 if (new_func && (new_func != fr_event_fd_noop)) {
697 EVENT_DEBUG("\t%s curr set (%p)", map->name, new_func);
698 current_fflags |= map->fflags;
699 has_current_func = true;
700
701 /*
702 * Check the filter will work for the
703 * type of file descriptor specified.
704 */
705 if (!(map->type & ef->type)) {
706 fr_strerror_printf("kevent %s (%s), can't be applied to fd of type %s",
707 map->name,
710 map->type, "<INVALID>"));
711 return -1;
712 }
713
714 /*
715 * Mark this filter function as active
716 */
717 memcpy((uint8_t *)active + map->offset, (uint8_t const *)new + map->offset,
718 sizeof(fr_event_fd_cb_t));
719 } else {
720 EVENT_DEBUG("\t%s curr unset", map->name);
721
722 /*
723 * Mark this filter function as inactive
724 * by setting it to the 'noop' callback.
725 */
726 *((fr_event_fd_cb_t *)((uint8_t *)active + map->offset)) = fr_event_fd_noop;
727 }
728
729 if (!(map + 1)->coalesce) break;
730 map++;
731 } while (1);
732
733 if (out >= end) {
734 fr_strerror_const("Out of memory to store kevent filters");
735 return -1;
736 }
737
738 /*
739 * Upsert if we add a function or change the flags.
740 */
741 if (has_current_func &&
742 (!has_prev_func || (current_fflags != prev_fflags))) {
743 if ((size_t)(add_p - add) >= (NUM_ELEMENTS(add))) {
744 fr_strerror_const("Out of memory to store kevent EV_ADD filters");
745 return -1;
746 }
747 EVENT_DEBUG("\tEV_SET EV_ADD filter %s (%i), flags %i, fflags %i",
749 map->filter, map->flags, current_fflags);
750 EV_SET(add_p++, ef->fd, map->filter, map->flags, current_fflags, 0, ef);
751
752 /*
753 * Delete if we remove a function.
754 */
755 } else if (!has_current_func && has_prev_func) {
756 EVENT_DEBUG("\tEV_SET EV_DELETE filter %s (%i), flags %i, fflags %i",
758 map->filter, EV_DELETE, 0);
759 EV_SET(out++, ef->fd, map->filter, EV_DELETE, 0, 0, ef);
760 }
761 }
762
763 /*
764 * kevent is fine with adds/deletes in the same operation
765 * on the same file descriptor, but libkqueue doesn't do
766 * any kind of coalescing or ordering so you get an EEXIST
767 * error.
768 */
769 for (i = 0; i < (size_t)(add_p - add); i++) memcpy(out++, &add[i], sizeof(*out));
770
771 return out - out_kev;
772}
773
774/** Discover the type of a file descriptor
775 *
776 * This function writes the result of the discovery to the ef->type,
777 * and ef->sock_type fields.
778 *
779 * @param[out] ef to write type data to.
780 * @param[in] fd to discover the type of.
781 * @return
782 * - 0 on success.
783 * - -1 on failure.
784 */
785static int fr_event_fd_type_set(fr_event_fd_t *ef, int fd)
786{
787 socklen_t opt_len = sizeof(ef->sock_type);
788
789 /*
790 * It's a socket or PCAP socket
791 */
792 if (getsockopt(fd, SOL_SOCKET, SO_TYPE, &ef->sock_type, &opt_len) == 0) {
793#ifdef SO_GET_FILTER
794 uint8_t unused_filter;
795
796 /*
797 * With a zero length the kernel reports the length of
798 * the attached filter in opt_len and does not write
799 * the buffer. See sk_get_filter() in
800 * github.com/torvalds/linux/blob/4a4852376e3a2727ea40e61143d6d7c22bb6dfad/net/core/filter.c#L11668-L11669
801 * The call below passes a buffer anyway, because the
802 * static analyser's model of getsockopt() rejects NULL.
803 */
804 opt_len = 0;
805 if (unlikely(getsockopt(fd, SOL_SOCKET, SO_ATTACH_FILTER, &unused_filter, &opt_len) < 0)) {
806 fr_strerror_printf("Failed determining PF status: %s", fr_syserror(errno));
807 return -1;
808 }
809 if (opt_len) {
811 } else
812#endif
813 {
815 }
816
817 /*
818 * It's a file or directory
819 */
820 } else {
821 struct stat buf;
822
823 if (errno != ENOTSOCK) {
824 fr_strerror_printf("Failed retrieving socket type: %s", fr_syserror(errno));
825 return -1;
826 }
827
828 if (fstat(fd, &buf) < 0) {
829 fr_strerror_printf("Failed calling stat() on file: %s", fr_syserror(errno));
830 return -1;
831 }
832
833 if (S_ISDIR(buf.st_mode)) {
835 } else {
837 }
838 }
839 ef->fd = fd;
840
841 return 0;
842}
843
844/** Remove a file descriptor from the event loop and rbtree but don't explicitly free it
845 *
846 *
847 * @param[in] ef to remove.
848 * @return
849 * - 0 on success.
850 * - -1 on error;
851 */
853{
854 struct kevent evset[10];
855 ssize_t count = 0;
856 fr_event_list_t *el = ef->el;
857 fr_event_funcs_t funcs;
858
859 /*
860 * Already been removed from the various trees and
861 * the event loop.
862 */
863 if (ef->is_registered) {
864 memset(&funcs, 0, sizeof(funcs));
865
866 fr_assert(ef->armour == 0);
867
868 /*
869 * If this fails, it's a pretty catastrophic error.
870 */
871 count = fr_event_build_evset(el, evset, sizeof(evset)/sizeof(*evset),
872 &ef->active, ef, &funcs, &ef->active);
873 if (count > 0) {
874 int ret;
875
876 /*
877 * If this fails, assert on debug builds.
878 */
879 ret = kevent(el->kq, evset, (int)count, NULL, 0, NULL);
880 if (!fr_cond_assert_msg(ret >= 0,
881 "FD %i was closed without being removed from the KQ: %s",
882 ef->fd, fr_syserror(errno))) {
883 return -1; /* Prevent the free, and leave the fd in the trees */
884 }
885 }
886
887 fr_rb_delete(el->fds, ef);
888 ef->is_registered = false;
889 }
890
891 /*
892 * Insert into the deferred free list, event will be
893 * freed later.
894 */
895 if (el->in_handler) {
896 /*
897 * Don't allow the same event to be
898 * inserted into the free list multiple
899 * times.
900 *
901 * This can happen if the same ef is
902 * delivered by multiple filters, i.e.
903 * if EVFILT_READ and EVFILT_WRITE
904 * were both high, and both handlers
905 * attempted to delete the event
906 * we'd need to prevent the event being
907 * inserted into the free list multiple
908 * times.
909 */
911 return -1; /* Will be freed later */
912 } else if (fr_dlist_entry_in_list(&ef->entry)) {
914 }
915
916 return 0;
917}
918
919/** Move a file descriptor event from one event list to another
920 *
921 * FIXME - Move suspended events too.
922 *
923 * @note Any pending events will not be transferred.
924 *
925 * @param[in] dst Event list to move file descriptor event to.
926 * @param[in] src Event list to move file descriptor from.
927 * @param[in] fd of the event to move.
928 * @param[in] filter of the event to move.
929 * @return
930 * - 0 on success.
931 * - -1 on failure. The event will remain active in the src list.
932 */
934 fr_event_list_t *dst, fr_event_list_t *src, int fd, fr_event_filter_t filter)
935{
936 fr_event_fd_t *ef;
937 int ret;
938
939 if (fr_event_loop_exiting(dst)) {
940 fr_strerror_const("Destination event loop exiting");
941 return -1;
942 }
943
944 /*
945 * Ensure this exists
946 */
947 fr_rb_find((void **)&ef, src->fds, &(fr_event_fd_t){ .fd = fd, .filter = filter });
948 if (unlikely(!ef)) {
949 fr_strerror_printf("No events are registered for fd %i", fd);
950 return -1;
951 }
952
954 ef->linked_ctx, NULL,
955 dst, ef->fd, ef->filter, &ef->active, ef->error, ef->uctx);
956 if (ret < 0) return -1;
957
958 (void)fr_event_fd_delete(src, ef->fd, ef->filter);
959
960 return ret;
961}
962
963
964/** Suspend/resume a subset of filters
965 *
966 * This function trades producing useful errors for speed.
967 *
968 * An example of suspending the read filter for an FD would be:
969 @code {.c}
970 static fr_event_update_t pause_read[] = {
971 FR_EVENT_SUSPEND(fr_event_io_func_t, read),
972 { 0 }
973 }
974
975 fr_event_filter_update(el, fd, FR_EVENT_FILTER_IO, pause_read);
976 @endcode
977 *
978 * @param[in] el to update descriptor in.
979 * @param[in] fd to update filters for.
980 * @param[in] filter The type of filter to update.
981 * @param[in] updates An array of updates to toggle filters on/off without removing
982 * the callback function.
983 */
985 fr_event_list_t *el, int fd, fr_event_filter_t filter, fr_event_update_t const updates[])
986{
987 fr_event_fd_t *ef;
988 size_t i;
989 fr_event_funcs_t curr_active, curr_stored;
990 struct kevent evset[10];
991 ssize_t count = 0;
992
993 fr_rb_find((void **)&ef, el->fds, &(fr_event_fd_t){ .fd = fd, .filter = filter });
994 if (unlikely(!ef)) {
995 fr_strerror_printf("No events are registered for fd %i", fd);
996 return -1;
997 }
998
999#ifndef NDEBUG
1000 ef->file = file;
1001 ef->line = line;
1002#endif
1003
1004 /*
1005 * Cheapest way of ensuring this function can error without
1006 * leaving everything in an inconsistent state.
1007 */
1008 memcpy(&curr_active, &ef->active, sizeof(curr_active));
1009 memcpy(&curr_stored, &ef->stored, sizeof(curr_stored));
1010
1011 /*
1012 * Apply modifications to our copies of the active/stored array.
1013 */
1014 for (i = 0; updates[i].op; i++) {
1015 switch (updates[i].op) {
1016 default:
1018 fr_assert(ef->armour == 0); /* can't suspect protected FDs */
1019 memcpy((uint8_t *)&ef->stored + updates[i].offset,
1020 (uint8_t *)&ef->active + updates[i].offset, sizeof(fr_event_fd_cb_t));
1021 memset((uint8_t *)&ef->active + updates[i].offset, 0, sizeof(fr_event_fd_cb_t));
1022 break;
1023
1024 case FR_EVENT_OP_RESUME:
1025 memcpy((uint8_t *)&ef->active + updates[i].offset,
1026 (uint8_t *)&ef->stored + updates[i].offset, sizeof(fr_event_fd_cb_t));
1027 memset((uint8_t *)&ef->stored + updates[i].offset, 0, sizeof(fr_event_fd_cb_t));
1028 break;
1029 }
1030 }
1031
1032 count = fr_event_build_evset(el, evset, sizeof(evset)/sizeof(*evset), &ef->active,
1033 ef, &ef->active, &curr_active);
1034 if (unlikely(count < 0)) {
1035 error:
1036 memcpy(&ef->active, &curr_active, sizeof(curr_active));
1037 memcpy(&ef->stored, &curr_stored, sizeof(curr_stored));
1038 return -1;
1039 }
1040
1041 if (count && unlikely(kevent(el->kq, evset, (int)count, NULL, 0, NULL) < 0)) {
1042 fr_strerror_printf("Failed updating filters for FD %i: %s", ef->fd, fr_syserror(errno));
1043 goto error;
1044 }
1045
1046 return 0;
1047}
1048
1049/** Insert a filter for the specified fd
1050 *
1051 * @param[in] ctx to bind lifetime of the event to.
1052 * @param[out] ef_out Previously allocated ef, or NULL.
1053 * @param[in] el to insert fd callback into.
1054 * @param[in] fd to install filters for.
1055 * @param[in] filter one of the #fr_event_filter_t values.
1056 * @param[in] funcs Structure containing callback functions. If a function pointer
1057 * is set, the equivalent kevent filter will be installed.
1058 * @param[in] error function to call when an error occurs on the fd.
1059 * @param[in] uctx to pass to handler.
1060 */
1062 TALLOC_CTX *ctx, fr_event_fd_t **ef_out,
1063 fr_event_list_t *el, int fd,
1064 fr_event_filter_t filter,
1065 void *funcs, fr_event_error_cb_t error,
1066 void *uctx)
1067{
1068 ssize_t count;
1069 fr_event_fd_t *ef;
1070 fr_event_funcs_t active;
1071 struct kevent evset[10];
1072
1073 if (unlikely(!el)) {
1074 fr_strerror_const("Invalid argument: NULL event list");
1075 return -1;
1076 }
1077
1078 if (unlikely(fd < 0)) {
1079 fr_strerror_printf("Invalid arguments: Bad FD %i", fd);
1080 return -1;
1081 }
1082
1083 if (unlikely(el->exit)) {
1084 if (ef_out && *ef_out) TALLOC_FREE(*ef_out);
1085 return 0;
1086 }
1087
1088 if (!ef_out || !*ef_out) {
1089 fr_rb_find((void **)&ef, el->fds, &(fr_event_fd_t){ .fd = fd, .filter = filter });
1090 } else {
1091 ef = *ef_out;
1092 fr_assert((fd < 0) || (ef->fd == fd));
1093 }
1094
1095 /*
1096 * Need to free the event to change the talloc link.
1097 *
1098 * This is generally bad. If you hit this
1099 * code path you probably screwed up somewhere.
1100 */
1101 if (unlikely(ef && (ef->linked_ctx != ctx))) TALLOC_FREE(ef);
1102
1103 /*
1104 * No pre-existing event. Allocate an entry
1105 * for insertion into the rbtree.
1106 */
1107 if (!ef) {
1108 ef = talloc_zero(el->fds, fr_event_fd_t);
1109 if (unlikely(!ef)) {
1110 fr_strerror_const("Out of memory");
1111 return -1;
1112 }
1113 talloc_set_destructor(ef, _event_fd_delete);
1114
1115 /*
1116 * Bind the lifetime of the event to the specified
1117 * talloc ctx. If the talloc ctx is freed, the
1118 * event will also be freed.
1119 */
1120 if (ctx != el) talloc_link_ctx(ctx, ef);
1121 ef->linked_ctx = ctx;
1122 ef->el = el;
1123
1124 /*
1125 * Determine what type of file descriptor
1126 * this is.
1127 */
1128 if (fr_event_fd_type_set(ef, fd) < 0) {
1129 free:
1130 talloc_free(ef);
1131 return -1;
1132 }
1133
1134 /*
1135 * Check the filter value is valid
1136 */
1137 if ((filter > (NUM_ELEMENTS(filter_maps) - 1))) {
1138 not_supported:
1139 fr_strerror_printf("Filter %u not supported", filter);
1140 goto free;
1141 }
1142 ef->map = &filter_maps[filter];
1143 if (ef->map->idx_type == FR_EVENT_FUNC_IDX_NONE) goto not_supported;
1144
1145 count = fr_event_build_evset(el, evset, sizeof(evset)/sizeof(*evset),
1146 &ef->active, ef, funcs, &ef->active);
1147 if (count < 0) goto free;
1148 if (count && (unlikely(kevent(el->kq, evset, (int)count, NULL, 0, NULL) < 0))) {
1149 fr_strerror_printf("Failed inserting filters for FD %i: %s", fd, fr_syserror(errno));
1150 goto free;
1151 }
1152
1153 ef->filter = filter;
1154 fr_rb_insert(el->fds, ef);
1155 ef->is_registered = true;
1156
1157 /*
1158 * Pre-existing event, update the filters and
1159 * functions associated with the file descriptor.
1160 */
1161 } else {
1162 fr_assert(ef->is_registered == true);
1163
1164 /*
1165 * Take a copy of the current set of active
1166 * functions, so we can error out in a
1167 * consistent state.
1168 */
1169 memcpy(&active, &ef->active, sizeof(ef->active));
1170
1171 fr_assert((ef->armour == 0) || ef->active.io.read);
1172
1173 count = fr_event_build_evset(el, evset, sizeof(evset)/sizeof(*evset),
1174 &ef->active, ef, funcs, &ef->active);
1175 if (count < 0) {
1176 error:
1177 memcpy(&ef->active, &active, sizeof(ef->active));
1178 return -1;
1179 }
1180 if (count && (unlikely(kevent(el->kq, evset, (int)count, NULL, 0, NULL) < 0))) {
1181 fr_strerror_printf("Failed modifying filters for FD %i: %s", fd, fr_syserror(errno));
1182 goto error;
1183 }
1184
1185 /*
1186 * Clear any previously suspended functions
1187 */
1188 memset(&ef->stored, 0, sizeof(ef->stored));
1189 }
1190
1191#ifndef NDEBUG
1192 ef->file = file;
1193 ef->line = line;
1194#endif
1195 ef->error = error;
1196 ef->uctx = uctx;
1197
1198 if (ef_out) *ef_out = ef;
1199
1200 return 0;
1201}
1202
1203/** Associate I/O callbacks with a file descriptor
1204 *
1205 * @param[in] ctx to bind lifetime of the event to.
1206 * @param[out] ef_out Where to store the output event
1207 * @param[in] el to insert fd callback into.
1208 * @param[in] fd to install filters for.
1209 * @param[in] read_fn function to call when fd is readable.
1210 * @param[in] write_fn function to call when fd is writable.
1211 * @param[in] error function to call when an error occurs on the fd.
1212 * @param[in] uctx to pass to handler.
1213 * @return
1214 * - 0 on success.
1215 * - -1 on failure.
1216 */
1218 TALLOC_CTX *ctx, fr_event_fd_t **ef_out, fr_event_list_t *el, int fd,
1219 fr_event_fd_cb_t read_fn,
1220 fr_event_fd_cb_t write_fn,
1221 fr_event_error_cb_t error,
1222 void *uctx)
1223{
1224 fr_event_io_func_t funcs = { .read = read_fn, .write = write_fn };
1225
1226 if (unlikely(!read_fn && !write_fn)) {
1227 fr_strerror_const("Invalid arguments: All callbacks are NULL");
1228 return -1;
1229 }
1230
1232 ctx, ef_out, el, fd, FR_EVENT_FILTER_IO, &funcs, error, uctx);
1233}
1234
1235/** Remove a file descriptor from the event loop
1236 *
1237 * @param[in] el to remove file descriptor from.
1238 * @param[in] fd to remove.
1239 * @param[in] filter The type of filter to remove.
1240 * @return
1241 * - 0 if file descriptor was removed.
1242 * - <0 on error.
1243 */
1245{
1246 fr_event_fd_t *ef;
1247
1248 fr_rb_find((void **)&ef, el->fds, &(fr_event_fd_t){ .fd = fd, .filter = filter });
1249 if (unlikely(!ef)) {
1250 fr_strerror_printf("No events are registered for fd %d, filter %u", fd, filter);
1251 return -1;
1252 }
1253
1254 return fr_event_fd_delete_handle(ef);
1255}
1256
1257/** Remove a file descriptor from the event loop, by handle
1258 *
1259 * Lets a caller holding the handle from #fr_event_fd_insert remove exactly the
1260 * event it inserted, without a lookup and without having to still know the fd
1261 * and filter it was inserted with.
1262 *
1263 * @param[in] ef to remove, as returned by #fr_event_fd_insert or
1264 * #fr_event_fd_handle.
1265 * @return
1266 * - 0 if file descriptor was removed.
1267 * - <0 on error.
1268 */
1270{
1271 /*
1272 * Free will normally fail if it's
1273 * a deferred free. There is a special
1274 * case for kevent failures though.
1275 *
1276 * We distinguish between the two by
1277 * looking to see if the ef is still
1278 * in the even tree.
1279 *
1280 * Talloc returning -1 guarantees the
1281 * memory has not been freed.
1282 */
1283 if ((talloc_free(ef) == -1) && ef->is_registered) return -1;
1284
1285 return 0;
1286}
1287
1288/** Get the opaque event handle from a file descriptor
1289 *
1290 * @param[in] el to search for fd/filter in.
1291 * @param[in] fd to search for.
1292 * @param[in] filter to search for.
1293 * @return
1294 * - NULL if no event could be found.
1295 * - The opaque handle representing an fd event.
1296 */
1298{
1299 fr_event_fd_t *ef;
1300
1301 fr_rb_find((void **)&ef, el->fds, &(fr_event_fd_t){ .fd = fd, .filter = filter });
1302 if (unlikely(!ef)) {
1303 fr_strerror_printf("No events are registered for fd %i", fd);
1304 return NULL;
1305 }
1306
1307 return ef;
1308}
1309
1310/** Returns the appropriate callback function for a given event
1311 *
1312 * @param[in] ef the event filter fd handle.
1313 * @param[in] kq_filter If the callbacks are indexed by filter.
1314 * @param[in] kq_fflags If the callbacks are indexed by NOTES (fflags).
1315 * @return
1316 * - NULL if no event it associated with the given ef/kq_filter or kq_fflags combo.
1317 * - The callback that would be called if an event with this filter/fflag combo was received.
1318 */
1320{
1321 return event_fd_func(ef, &kq_filter, &kq_fflags);
1322}
1323
1324/** Returns the uctx associated with an fr_event_fd_t handle
1325 *
1326 */
1328{
1329 return ef->uctx;
1330}
1331
1332#ifndef NDEBUG
1333/** Armour an FD
1334 *
1335 * @param[in] el to remove file descriptor from.
1336 * @param[in] fd to remove.
1337 * @param[in] filter The type of filter to remove.
1338 * @param[in] armour The armour to add.
1339 * @return
1340 * - 0 if file descriptor was armoured
1341 * - <0 on error.
1342 */
1343int fr_event_fd_armour(fr_event_list_t *el, int fd, fr_event_filter_t filter, uintptr_t armour)
1344{
1345 fr_event_fd_t *ef;
1346
1347 fr_rb_find((void **)&ef, el->fds, &(fr_event_fd_t){ .fd = fd, .filter = filter });
1348 if (unlikely(!ef)) {
1349 fr_strerror_printf("No events are registered for fd %i", fd);
1350 return -1;
1351 }
1352
1353 if (ef->armour != 0) {
1354 fr_strerror_printf("FD %i is already armoured", fd);
1355 return -1;
1356 }
1357
1358 ef->armour = armour;
1359
1360 return 0;
1361}
1362
1363/** Unarmour an FD
1364 *
1365 * @param[in] el to remove file descriptor from.
1366 * @param[in] fd to remove.
1367 * @param[in] filter The type of filter to remove.
1368 * @param[in] armour The armour to remove
1369 * @return
1370 * - 0 if file descriptor was unarmoured
1371 * - <0 on error.
1372 */
1373int fr_event_fd_unarmour(fr_event_list_t *el, int fd, fr_event_filter_t filter, uintptr_t armour)
1374{
1375 fr_event_fd_t *ef;
1376
1377 fr_rb_find((void **)&ef, el->fds, &(fr_event_fd_t){ .fd = fd, .filter = filter });
1378 if (unlikely(!ef)) {
1379 fr_strerror_printf("No events are registered for fd %i", fd);
1380 return -1;
1381 }
1382
1383 fr_assert(ef->armour == armour);
1384
1385 ef->armour = 0;
1386 return 0;
1387}
1388#endif
1389
1390/** Remove PID wait event from kevent if the fr_event_pid_t is freed
1391 *
1392 * @param[in] ev to free.
1393 * @return 0
1394 */
1396{
1397 struct kevent evset;
1398
1399 if (ev->parent) *ev->parent = NULL;
1400 if (!ev->is_registered || (ev->pid < 0)) return 0; /* already deleted from kevent */
1401
1402 EVENT_DEBUG("%p - Disabling event for PID %u - %p was freed", ev->el, (unsigned int)ev->pid, ev);
1403
1404 EV_SET(&evset, ev->pid, EVFILT_PROC, EV_DELETE, NOTE_EXIT, 0, ev);
1405
1406 (void) kevent(ev->el->kq, &evset, 1, NULL, 0, NULL);
1407
1408 return 0;
1409}
1410
1411/** Evaluate a EVFILT_PROC event
1412 *
1413 */
1414CC_NO_UBSAN(function) /* UBSAN: false positive - Public/private version of fr_event_list_t trips -fsanitize=function */
1415static inline CC_HINT(always_inline)
1416void event_pid_eval(fr_event_list_t *el, struct kevent *kev)
1417{
1418 pid_t pid;
1419 fr_event_pid_t *ev;
1420 fr_event_pid_cb_t callback;
1421 void *uctx;
1422
1423 EVENT_DEBUG("%p - PID %u exited with status %i",
1424 el, (unsigned int)kev->ident, (unsigned int)kev->data);
1425
1426 ev = talloc_get_type_abort((void *)kev->udata, fr_event_pid_t);
1427
1428 fr_assert(ev->pid == (pid_t) kev->ident);
1429 fr_assert((kev->fflags & NOTE_EXIT) != 0);
1430
1431 pid = ev->pid;
1432 callback = ev->callback;
1433 uctx = ev->uctx;
1434
1435 ev->is_registered = false; /* so we won't hit kevent again when it's freed */
1436
1437 /*
1438 * Delete the event before calling it.
1439 *
1440 * This also sets the parent pointer
1441 * to NULL, so the thing that started
1442 * monitoring the process knows the
1443 * handle is no longer valid.
1444 *
1445 * EVFILT_PROC NOTE_EXIT events are always
1446 * oneshot no matter what flags we pass,
1447 * so we're just reflecting the state of
1448 * the kqueue.
1449 */
1450 talloc_free(ev);
1451
1452 if (callback) callback(el, pid, (int) kev->data, uctx);
1453}
1454
1455/** Called on the next loop through the event loop when inserting an EVFILT_PROC event fails
1456 *
1457 * This is just a trampoleen function which takes the user event and simulates
1458 * an EVFILT_PROC event from it.
1459 *
1460 * @param[in] el That received the event.
1461 * @param[in] uctx An fr_event_pid_t to process.
1462 */
1464{
1465 fr_event_pid_t *ev = talloc_get_type_abort(uctx, fr_event_pid_t);
1466
1467 EVENT_DEBUG("%p - PID %ld exited early, triggered through user event", el, (long)ev->pid);
1468
1469 /*
1470 * Simulate a real struct kevent with the values we
1471 * recorded in fr_event_pid_wait.
1472 */
1473 event_pid_eval(el, &(struct kevent){ .ident = ev->pid, .data = ev->early_exit.status, .fflags = NOTE_EXIT, .udata = ev });
1474}
1475
1476/** Insert a PID event into an event list
1477 *
1478 * @note The talloc parent of the memory returned in ev_p must not be changed.
1479 * If the lifetime of the event needs to be bound to another context
1480 * this function should be called with the existing event pointed to by
1481 * ev_p.
1482 *
1483 * @param[in] ctx to bind lifetime of the event to.
1484 * @param[in] el to insert event into.
1485 * @param[in,out] ev_p If not NULL modify this event instead of creating a new one. This is a parent
1486 * in a temporal sense, not in a memory structure or dependency sense.
1487 * @param[in] pid child PID to wait for
1488 * @param[in] callback function to execute if the event fires.
1489 * @param[in] uctx user data to pass to the event.
1490 * @return
1491 * - 0 on success.
1492 * - -1 on failure.
1493 */
1495 TALLOC_CTX *ctx, fr_event_list_t *el, fr_event_pid_t const **ev_p,
1496 pid_t pid, fr_event_pid_cb_t callback, void *uctx)
1497{
1498 fr_event_pid_t *ev;
1499 struct kevent evset;
1500
1501 ev = talloc(ctx, fr_event_pid_t);
1502 if (unlikely(ev == NULL)) {
1503 fr_strerror_const("Out of memory");
1504 return -1;
1505 }
1506 *ev = (fr_event_pid_t) {
1507 .el = el,
1508 .pid = pid,
1509 .callback = callback,
1510 .uctx = uctx,
1511 .parent = ev_p,
1512#ifndef NDEBUG
1513 .file = file,
1514 .line = line,
1515#endif
1516 };
1517 talloc_set_destructor(ev, _event_pid_free);
1518
1519 /*
1520 * macOS only, on FreeBSD NOTE_EXIT always provides
1521 * the status anyway.
1522 */
1523#ifndef NOTE_EXITSTATUS
1524#define NOTE_EXITSTATUS (0)
1525#endif
1526
1527 EVENT_DEBUG("%p - Adding exit waiter for PID %u", el, (unsigned int)pid);
1528
1529 EV_SET(&evset, pid, EVFILT_PROC, EV_ADD | EV_ONESHOT, NOTE_EXIT | NOTE_EXITSTATUS, 0, ev);
1530 ev->is_registered = true;
1531
1532 /*
1533 * This deals with the race where the process exited
1534 * before we could add it to the kqueue.
1535 *
1536 * Unless our caller is broken, the process should
1537 * still be available for reaping, so we check
1538 * waitid to see if there is a pending process and
1539 * then call the callback as kqueue would have done.
1540 */
1541 if (unlikely(kevent(el->kq, &evset, 1, NULL, 0, NULL) < 0)) {
1542 siginfo_t info;
1543 int ret;
1544
1545 /*
1546 * Ensure we don't accidentally pick up the error
1547 * from kevent.
1548 */
1550
1551 ev->is_registered = false;
1552
1553 /*
1554 * If the child exited before kevent() was
1555 * called, we need to get its status via
1556 * waitid().
1557 *
1558 * We don't reap the process here to emulate
1559 * what kqueue does (notify but not reap).
1560 *
1561 * waitid returns >0 on success, 0 if the
1562 * process is still running, and -1 on failure.
1563 *
1564 * If we get a 0, then that's extremely strange
1565 * as adding the kevent failed for a reason
1566 * other than the process already having exited.
1567 *
1568 * On Linux waitid will always return 1 to
1569 * indicate the process exited.
1570 *
1571 * On macOS we seem to get a mix of 1 or 0,
1572 * even if the si_code is one of the values
1573 * we'd consider to indicate that the process
1574 * had completed.
1575 */
1576 ret = waitid(P_PID, pid, &info, WEXITED | WNOHANG | WNOWAIT);
1577 if (ret > 0) {
1578 static fr_table_num_sorted_t const si_codes[] = {
1579 { L("exited"), CLD_EXITED },
1580 { L("killed"), CLD_KILLED },
1581 { L("dumped"), CLD_DUMPED },
1582 { L("trapped"), CLD_TRAPPED },
1583 { L("stopped"), CLD_STOPPED },
1584 { L("continued"), CLD_CONTINUED }
1585 };
1586 static size_t si_codes_len = NUM_ELEMENTS(si_codes);
1587
1588 switch (info.si_code) {
1589 case CLD_EXITED:
1590 case CLD_KILLED:
1591 case CLD_DUMPED:
1592 EVENT_DEBUG("%p - PID %ld early exit - code %s (%d), status %d",
1593 el, (long)pid, fr_table_str_by_value(si_codes, info.si_code, "<UNKOWN>"),
1594 info.si_code, info.si_status);
1595
1596 /*
1597 * Record the status for later
1598 */
1599 ev->early_exit.status = info.si_status;
1600
1601 /*
1602 * The user event acts as a surrogate for
1603 * an EVFILT_PROC event, and will be evaluated
1604 * during the next loop through the event loop.
1605 *
1606 * It will be automatically deleted when the
1607 * fr_event_pid_t is freed.
1608 *
1609 * Previously we tried to evaluate the proc
1610 * callback here directly, but this lead to
1611 * multiple problems, the biggest being that
1612 * setting requests back to resumable failed
1613 * because they were not yet yielded,
1614 * leading to hangs.
1615 */
1616 early_exit:
1617 if (fr_event_user_insert(ev, el, &ev->early_exit.ev, true, _fr_event_pid_early_exit, ev) < 0) {
1618 fr_strerror_printf_push("Failed adding wait for PID %ld, and failed adding "
1619 "backup user event", (long) pid);
1620 error:
1621 talloc_free(ev);
1622 return -1;
1623 }
1624 break;
1625
1626 default:
1627 fr_strerror_printf("Unexpected code %s (%d) whilst waiting on PID %ld",
1628 fr_table_str_by_value(si_codes, info.si_code, "<UNKOWN>"),
1629 info.si_code, (long) pid);
1630
1631 goto error;
1632 }
1633 /*
1634 * Failed adding waiter for process, but process has not completed...
1635 *
1636 * This weird, but seems to happen on macOS occasionally.
1637 *
1638 * Add an event to run early exit...
1639 *
1640 * Man pages for waitid say if it returns 0 the info struct can be in
1641 * a nondeterministic state, so there's nothing more to do.
1642 */
1643 } else if (ret == 0) {
1644 goto early_exit;
1645 } else {
1646 /*
1647 * Print this error here, so that the caller gets
1648 * the error from kevent(), and not waitpid().
1649 */
1650 fr_strerror_printf_push("Failed adding waiter for PID %ld - kevent %s",
1651 (long) pid, fr_syserror(evset.data));
1652 fr_strerror_printf_push("waitid() for PID %ld returned %s",
1653 (long) pid, fr_syserror(errno));
1654 goto error;
1655 }
1656 }
1657
1658 /*
1659 * Sometimes the caller doesn't care about getting the
1660 * PID. But we still want to clean it up.
1661 */
1662 if (ev_p) *ev_p = ev;
1663
1664 return 0;
1665}
1666
1667/** Saves some boilerplate...
1668 *
1669 */
1670CC_NO_UBSAN(function) /* UBSAN: false positive - Public/private version of fr_event_list_t trips -fsanitize=function */
1671static inline CC_HINT(always_inline)
1672void event_list_reap_run_callback(fr_event_pid_reap_t *reap, pid_t pid, int status)
1673{
1674 if (reap->callback) reap->callback(reap->el, pid, status, reap->uctx);
1675}
1676
1677/** Does the actual reaping of PIDs
1678 *
1679 */
1680static void _fr_event_pid_reap_cb(UNUSED fr_event_list_t *el, pid_t pid, int status, void *uctx)
1681{
1682 fr_event_pid_reap_t *reap = talloc_get_type_abort(uctx, fr_event_pid_reap_t);
1683
1684 waitpid(pid, &status, WNOHANG); /* Don't block the process if there's a logic error somewhere */
1685
1686 EVENT_DEBUG("%s - Reaper reaped PID %u, status %u - %p", __FUNCTION__, pid, status, reap);
1687
1688 event_list_reap_run_callback(reap, pid, status);
1689
1690 talloc_free(reap);
1691}
1692
1694{
1695 /*
1696 * Clear out the entry in the pid_to_reap
1697 * list if the event was inserted.
1698 */
1699 if (fr_dlist_entry_in_list(&reap->entry)) {
1700 EVENT_DEBUG("%s - Removing entry from pid_to_reap %i - %p", __FUNCTION__,
1701 reap->pid_ev ? reap->pid_ev->pid : -1, reap);
1702 fr_dlist_remove(&reap->el->pid_to_reap, reap);
1703 }
1704
1705 return 0;
1706}
1707
1708/** Asynchronously wait for a PID to exit, then reap it
1709 *
1710 * This is intended to be used when we no longer care about a process
1711 * exiting, but we still want to clean up its state so we don't have
1712 * zombie processes sticking around.
1713 *
1714 * @param[in] el to use to reap the process.
1715 * @param[in] pid to reap.
1716 * @param[in] callback to call when the process is reaped.
1717 * May be NULL.
1718 * @param[in] uctx to pass to callback.
1719 * @return
1720 * - -1 if we couldn't find the process or it has already exited/been reaped.
1721 * - 0 on success (we setup a process handler).
1722 */
1724{
1725 int ret;
1726 fr_event_pid_reap_t *reap;
1727
1728 reap = talloc_zero(NULL, fr_event_pid_reap_t);
1729 if (unlikely(!reap)) {
1730 fr_strerror_const("Out of memory");
1731 return -1;
1732 }
1733 talloc_set_destructor(reap, _fr_event_reap_free);
1734
1736 if (ret < 0) {
1737 talloc_free(reap);
1738 return ret;
1739 }
1740
1741 reap->el = el;
1742 reap->callback = callback;
1743 reap->uctx = uctx;
1744
1745 EVENT_DEBUG("%s - Adding reaper for PID %u - %p", __FUNCTION__, pid, reap);
1746
1748
1749 return ret;
1750}
1751
1752/** Send a signal to all the processes we have in our reap list, and reap them
1753 *
1754 * @param[in] el containing the processes to reap.
1755 * @param[in] timeout how long to wait before we signal the processes.
1756 * @param[in] signal to send to processes. Should be a fatal signal.
1757 * @return The number of processes reaped.
1758 */
1760{
1761 unsigned int processed = fr_dlist_num_elements(&el->pid_to_reap);
1762 fr_event_pid_reap_t *reap = NULL;
1763
1764 /*
1765 * If we've got a timeout, our best option
1766 * is to use a kqueue instance to monitor
1767 * for process exit.
1768 */
1770 int status;
1771 struct kevent evset;
1772 int waiting = 0;
1773 int kq = kqueue();
1774 fr_time_t now, start = el->pub.tl->time(), end = fr_time_add(start, timeout);
1775
1776 if (unlikely(kq < 0)) goto force;
1777
1779 if (!i->pid_ev) {
1780 EVENT_DEBUG("%p - %s - Reaper already called (logic error)... - %p",
1781 el, __FUNCTION__, i);
1782
1783 event_list_reap_run_callback(i, -1, SIGKILL);
1784 talloc_free(i);
1785 continue;
1786 }
1787
1788 /*
1789 * See if any processes have exited already
1790 */
1791 if (waitpid(i->pid_ev->pid, &status, WNOHANG) == i->pid_ev->pid) { /* reap */
1792 EVENT_DEBUG("%p - %s - Reaper PID %u already exited - %p",
1793 el, __FUNCTION__, i->pid_ev->pid, i);
1794 event_list_reap_run_callback(i, i->pid_ev->pid, SIGKILL);
1795 talloc_free(i);
1796 continue;
1797 }
1798
1799 /*
1800 * Add the rest to a temporary event loop
1801 */
1802 EV_SET(&evset, i->pid_ev->pid, EVFILT_PROC, EV_ADD, NOTE_EXIT, 0, i);
1803 if (kevent(kq, &evset, 1, NULL, 0, NULL) < 0) {
1804 EVENT_DEBUG("%p - %s - Failed adding reaper PID %u to tmp event loop - %p",
1805 el, __FUNCTION__, i->pid_ev->pid, i);
1806 event_list_reap_run_callback(i, i->pid_ev->pid, SIGKILL);
1807 talloc_free(i);
1808 continue;
1809 }
1810 waiting++;
1811 }
1812
1813 /*
1814 * Keep draining process exits as they come in...
1815 */
1816 while ((waiting > 0) && fr_time_gt(end, (now = el->pub.tl->time()))) {
1817 struct kevent kev;
1818 int ret;
1819
1820 ret = kevent(kq, NULL, 0, &kev, 1, &fr_time_delta_to_timespec(fr_time_sub(end, now)));
1821 switch (ret) {
1822 default:
1823 EVENT_DEBUG("%p - %s - Reaper tmp loop error %s, forcing process reaping",
1824 el, __FUNCTION__, fr_syserror(errno));
1825 close(kq);
1826 goto force;
1827
1828 case 0:
1829 EVENT_DEBUG("%p - %s - Reaper timeout waiting for process exit, forcing process reaping",
1830 el, __FUNCTION__);
1831 close(kq);
1832 goto force;
1833
1834 case 1:
1835 reap = talloc_get_type_abort(kev.udata, fr_event_pid_reap_t);
1836
1837 EVENT_DEBUG("%p - %s - Reaper reaped PID %u, status %u - %p",
1838 el, __FUNCTION__, (unsigned int)kev.ident, (unsigned int)kev.data, reap);
1839 waitpid(reap->pid_ev->pid, &status, WNOHANG); /* reap */
1840
1841 event_list_reap_run_callback(reap, reap->pid_ev->pid, status);
1842 talloc_free(reap);
1843 break;
1844 }
1845 waiting--;
1846 }
1847
1848 close(kq);
1849 }
1850
1851force:
1852 /*
1853 * Deal with any lingering reap requests
1854 */
1855 while ((reap = fr_dlist_head(&el->pid_to_reap))) {
1856 int status;
1857
1858 EVENT_DEBUG("%s - Reaper forcefully reaping PID %u - %p", __FUNCTION__, reap->pid_ev->pid, reap);
1859
1860 if (kill(reap->pid_ev->pid, signal) < 0) {
1861 /*
1862 * Make sure we don't hang if the
1863 * process has actually exited.
1864 *
1865 * We could check for ESRCH but it's
1866 * not clear if that'd be returned
1867 * for a PID in the unreaped state
1868 * or not...
1869 */
1870 waitpid(reap->pid_ev->pid, &status, WNOHANG);
1871 event_list_reap_run_callback(reap, reap->pid_ev->pid, status);
1872 talloc_free(reap);
1873 continue;
1874 }
1875
1876 /*
1877 * Wait until the child process exits
1878 */
1879 waitpid(reap->pid_ev->pid, &status, 0);
1880 event_list_reap_run_callback(reap, reap->pid_ev->pid, status);
1881 talloc_free(reap);
1882 }
1883
1884 return processed;
1885}
1886
1887/** Memory will not be freed if we fail to remove the event from the kqueue
1888 *
1889 * It's easier to debug memory leaks with modern tooling than it is
1890 * to determine why we get random failures and event leaks inside of kqueue.
1891 *
1892 * @return
1893 * - 0 on success.
1894 * - -1 on failure.
1895 */
1897{
1898 if (ev->is_registered) {
1899 struct kevent evset;
1900
1901 EV_SET(&evset, (uintptr_t)ev, EVFILT_USER, EV_DELETE, 0, 0, 0);
1902
1903 if (unlikely(kevent(ev->el->kq, &evset, 1, NULL, 0, NULL) < 0)) {
1904 fr_strerror_printf("Failed removing user event - kevent %s", fr_syserror(evset.flags));
1905 return -1;
1906 }
1907 ev->is_registered = false;
1908 }
1909
1910 return 0;
1911}
1912
1913CC_NO_UBSAN(function) /* UBSAN: false positive - Public/private version of fr_event_list_t trips -fsanitize=function */
1914static inline CC_HINT(always_inline)
1915void event_user_eval(fr_event_list_t *el, struct kevent *kev)
1916{
1917 fr_event_user_t *ev;
1918
1919 /*
1920 * This is just a "wakeup" event, which
1921 * is always ignored.
1922 */
1923 if (kev->ident == 0) return;
1924
1925 ev = talloc_get_type_abort((void *)kev->ident, fr_event_user_t);
1926 fr_assert((uintptr_t)ev == kev->ident);
1927
1928 ev->callback(el, ev->uctx);
1929}
1930
1931/** Add a user callback to the event list.
1932 *
1933 * @param[in] ctx to allocate the event in.
1934 * @param[in] el Containing the timer events.
1935 * @param[out] ev_p Where to write a pointer.
1936 * @param[in] trigger Whether the user event is triggered initially.
1937 * @param[in] callback for EVFILT_USER.
1938 * @param[in] uctx for the callback.
1939 * @return
1940 * - 0 on success.
1941 * - -1 on error.
1942 */
1944 TALLOC_CTX *ctx, fr_event_list_t *el, fr_event_user_t **ev_p,
1945 bool trigger, fr_event_user_cb_t callback, void *uctx)
1946{
1947 fr_event_user_t *ev;
1948 struct kevent evset;
1949
1950 ev = talloc(ctx, fr_event_user_t);
1951 if (unlikely(ev == NULL)) {
1952 fr_strerror_const("Out of memory");
1953 return -1;
1954 }
1955 *ev = (fr_event_user_t) {
1956 .el = el,
1957 .callback = callback,
1958 .uctx = uctx,
1959#ifndef NDEBUG
1960 .file = file,
1961 .line = line,
1962#endif
1963 };
1964
1965 EV_SET(&evset, (uintptr_t)ev,
1966 EVFILT_USER, EV_ADD | EV_DISPATCH, 0, 0, ev);
1967
1968 if (unlikely(kevent(el->kq, &evset, 1, NULL, 0, NULL) < 0)) {
1969 fr_strerror_printf("Failed adding user event - kevent %s", fr_syserror(evset.flags));
1970 talloc_free(ev);
1971 return -1;
1972 }
1973 ev->is_registered = true;
1974 talloc_set_destructor(ev, _event_user_delete);
1975
1976 /*
1977 * NOTE_TRIGGER passed with EV_ADD is not delivered everywhere.
1978 * FreeBSD clears fflags before attaching a new knote, and
1979 * libkqueue on Linux never raises the eventfd when it creates
1980 * the knote. So the initial trigger is a separate change,
1981 * made once the event exists.
1982 */
1983 if (trigger && (unlikely(fr_event_user_trigger(ev) < 0))) {
1984 talloc_free(ev);
1985 return -1;
1986 }
1987
1988 if (ev_p) *ev_p = ev;
1989
1990 return 0;
1991}
1992
1993/** Trigger a user event
1994 *
1995 * @param[in] ev Handle for the user event.
1996 * @return
1997 * - 0 on success.
1998 * - -1 on error.
1999 */
2001{
2002 struct kevent evset;
2003
2004 /*
2005 * The event was registered with EV_DISPATCH, which makes
2006 * kqueue auto-disable it each time it fires. A plain
2007 * NOTE_TRIGGER on a disabled event is accepted by the kernel
2008 * but not delivered to userspace until the event is
2009 * re-enabled, so we pass EV_ENABLE alongside the trigger to
2010 * re-arm it atomically. Without this, the second and
2011 * subsequent trigger calls would silently never wake the
2012 * consumer.
2013 */
2014 EV_SET(&evset, (uintptr_t)ev, EVFILT_USER, EV_ENABLE, NOTE_TRIGGER, 0, NULL);
2015
2016 if (unlikely(kevent(ev->el->kq, &evset, 1, NULL, 0, NULL) < 0)) {
2017 fr_strerror_printf("Failed triggering user event - kevent %s", fr_syserror(evset.flags));
2018 return -1;
2019 }
2020
2021 return 0;
2022}
2023
2024/** Add a pre-event callback to the event list.
2025 *
2026 * Events are serviced in insert order. i.e. insert A, B, we then
2027 * have A running before B.
2028 *
2029 * @param[in] el Containing the timer events.
2030 * @param[in] callback The pre-processing callback.
2031 * @param[in] uctx for the callback.
2032 * @return
2033 * - < 0 on error
2034 * - 0 on success
2035 */
2037{
2038 fr_event_pre_t *pre;
2039
2040 pre = talloc(el, fr_event_pre_t);
2041 pre->callback = callback;
2042 pre->uctx = uctx;
2043
2045
2046 return 0;
2047}
2048
2049/** Delete a pre-event callback from the event list.
2050 *
2051 * @param[in] el Containing the timer events.
2052 * @param[in] callback The pre-processing callback.
2053 * @param[in] uctx for the callback.
2054 * @return
2055 * - < 0 on error
2056 * - 0 on success
2057 */
2059{
2061 if ((pre->callback == callback) &&
2062 (pre->uctx == uctx)) {
2064 return talloc_free(pre);
2065 }
2066 }
2067
2068 return -1;
2069}
2070
2071/** Add a post-event callback to the event list.
2072 *
2073 * Events are serviced in insert order. i.e. insert A, B, we then
2074 * have A running before B.
2075 *
2076 * @param[in] el Containing the timer events.
2077 * @param[in] callback The post-processing callback.
2078 * @param[in] uctx for the callback.
2079 * @return
2080 * - < 0 on error
2081 * - 0 on success
2082 */
2084{
2085 fr_event_post_t *post;
2086
2087 post = talloc(el, fr_event_post_t);
2088 if (!post) return -1;
2089 post->callback = callback;
2090 post->uctx = uctx;
2091
2093
2094 return 0;
2095}
2096
2097/** Delete a post-event callback from the event list.
2098 *
2099 * @param[in] el Containing the timer events.
2100 * @param[in] callback The post-processing callback.
2101 * @param[in] uctx for the callback.
2102 * @return
2103 * - < 0 on error
2104 * - 0 on success
2105 */
2107{
2109 if ((post->callback == callback) &&
2110 (post->uctx == uctx)) {
2112 return talloc_free(post);
2113 }
2114 }
2115
2116 return -1;
2117}
2118
2119/** Gather outstanding timer and file descriptor events
2120 *
2121 * @param[in] el to process events for.
2122 * @param[in] now The current time.
2123 * @param[in] wait if true, block on the kevent() call until a timer or file descriptor event occurs.
2124 * @return
2125 * - <0 error, or the event loop is exiting
2126 * - the number of outstanding I/O events, +1 if at least one timer will fire.
2127 */
2129{
2130 fr_time_delta_t when, *wake;
2131 struct timespec ts_when, *ts_wake;
2132 int num_fd_events;
2133 bool timer_event_ready = false;
2134 fr_time_t next;
2135
2136 el->num_fd_events = 0;
2137
2138 if (el->will_exit || el->exit) {
2139 el->exit = el->will_exit;
2140
2141 fr_strerror_const("Event loop exiting");
2142 return -1;
2143 }
2144
2145 /*
2146 * By default we wait for 0ns, which means returning
2147 * immediately from kevent().
2148 */
2149 when = fr_time_delta_wrap(0);
2150 wake = &when;
2151
2152 /*
2153 * See when we have to wake up. Either now, if the timer
2154 * events are in the past. Or, we wait for a future
2155 * timer event.
2156 */
2157 next = fr_timer_list_when(el->pub.tl);
2158 if (fr_time_neq(next, fr_time_wrap(0))) {
2159 if (fr_time_lteq(next, now)) {
2160 timer_event_ready = true;
2161
2162 } else if (wait) {
2163 when = fr_time_sub(next, now);
2164
2165 } /* else we're not waiting, leave "when == 0" */
2166
2167 } else if (wait) {
2168 /*
2169 * We're asked to wait, but there's no timer
2170 * event. We can then sleep forever.
2171 */
2172 wake = NULL;
2173 }
2174
2175 /*
2176 * Run the status callbacks. It may tell us that the
2177 * application has more work to do, in which case we
2178 * re-set the timeout to be instant.
2179 *
2180 * We only run these callbacks if the caller is otherwise
2181 * idle.
2182 */
2183 if (wait) {
2185 if (pre->callback(now, wake ? *wake : fr_time_delta_wrap(0), pre->uctx) > 0) {
2186 wake = &when;
2187 when = fr_time_delta_wrap(0);
2188 }
2189 }
2190 }
2191
2192 /*
2193 * Wake is the delta between el->now
2194 * (the event loops view of the current time)
2195 * and when the event should occur.
2196 */
2197 if (wake) {
2198 ts_when = fr_time_delta_to_timespec(when);
2199 ts_wake = &ts_when;
2200 } else {
2201 ts_wake = NULL;
2202 }
2203
2204 /*
2205 * Populate el->events with the list of I/O events
2206 * that occurred since this function was last called
2207 * or wait for the next timer event.
2208 */
2209 num_fd_events = kevent(el->kq, NULL, 0, el->events, FR_EV_BATCH_FDS, ts_wake);
2210
2211 /*
2212 * Interrupt is different from timeout / FD events.
2213 */
2214 if (unlikely(num_fd_events < 0)) {
2215 if (errno == EINTR) {
2216 return 0;
2217 } else {
2218 fr_strerror_printf("Failed calling kevent: %s", fr_syserror(errno));
2219 return -1;
2220 }
2221 }
2222
2223 el->num_fd_events = num_fd_events;
2224
2225 EVENT_DEBUG("%p - %s - kevent returned %u FD events", el, __FUNCTION__, el->num_fd_events);
2226
2227 /*
2228 * If there are no FD events, we must have woken up from a timer
2229 */
2230 if (!num_fd_events) {
2231 if (wait) timer_event_ready = true;
2232 }
2233 /*
2234 * The caller doesn't really care what the value of the
2235 * return code is. Just that it's greater than zero if
2236 * events needs servicing.
2237 *
2238 * num_fd_events > 0 - if kevent() returns FD events
2239 * timer_event_ready > 0 - if there were timers ready BEFORE or AFTER calling kevent()
2240 */
2241 return num_fd_events + timer_event_ready;
2242}
2243
2244CC_NO_UBSAN(function) /* UBSAN: false positive - public vs private fr_event_list_t trips --fsanitize=function*/
2245static inline CC_HINT(always_inline)
2246void event_callback(fr_event_list_t *el, fr_event_fd_t *ef, int *filter, int flags, uint32_t *fflags)
2247{
2248 fr_event_fd_cb_t fd_cb;
2249
2250 while ((fd_cb = event_fd_func(ef, filter, fflags))) {
2251 fd_cb(el, ef->fd, flags, ef->uctx);
2252 }
2253}
2254
2255/** Service any outstanding timer or file descriptor events
2256 *
2257 * @param[in] el containing events to service.
2258 */
2259CC_NO_UBSAN(function) /* UBSAN: false positive - Public/private version of fr_event_list_t trips -fsanitize=function */
2260static inline CC_HINT(always_inline)
2261void event_service(fr_event_list_t *el, bool fd_events)
2262{
2263 fr_timer_list_t *etl = el->pub.tl;
2264 int i;
2265 fr_event_post_t *post;
2266 fr_time_t when, now;
2267
2268 if (unlikely(el->exit)) return;
2269
2270 EVENT_DEBUG("%p - %s - Servicing %u FD events", el, __FUNCTION__, el->num_fd_events);
2271
2272 /*
2273 * Run all of the file descriptor events.
2274 */
2275 el->in_handler = true;
2276 for (i = 0; i < el->num_fd_events; i++) {
2277 /*
2278 * Process any user events
2279 */
2280 switch (el->events[i].filter) {
2281 case EVFILT_USER:
2282 event_user_eval(el, &el->events[i]);
2283 continue;
2284
2285 /*
2286 * Process proc events
2287 */
2288 case EVFILT_PROC:
2289 event_pid_eval(el, &el->events[i]);
2290 continue;
2291
2292 /*
2293 * Process various types of file descriptor events
2294 */
2295 default:
2296 /*
2297 * fd_events is a constant in each caller, so the check is removed from fr_event_service().
2298 */
2299 if (!fd_events) continue;
2300 {
2301 fr_event_fd_t *ef = talloc_get_type_abort(el->events[i].udata, fr_event_fd_t);
2302 int fd_errno = 0;
2303
2304 uint32_t fflags = el->events[i].fflags; /* mutable */
2305 int filter = el->events[i].filter;
2306 int flags = el->events[i].flags;
2307
2308 if (!ef->is_registered) continue; /* Was deleted between corral and service */
2309
2310 if (unlikely(flags & EV_ERROR)) {
2311 fd_errno = el->events[i].data;
2312 ev_error:
2313 /*
2314 * Call the error handler, but only if the socket hasn't been deleted at EOF
2315 * below.
2316 */
2317 if (ef->is_registered && ef->error) ef->error(el, ef->fd, flags, fd_errno, ef->uctx);
2318 TALLOC_FREE(ef);
2319 continue;
2320 }
2321
2322 /*
2323 * EOF can indicate we've actually reached
2324 * the end of a file, but for sockets it usually
2325 * indicates the other end of the connection
2326 * has gone away.
2327 */
2328 if (flags & EV_EOF) {
2329 /*
2330 * This is fine, the callback will get notified
2331 * via the flags field.
2332 */
2333 if (ef->type == FR_EVENT_FD_FILE) goto service;
2334#if defined(__linux__) && defined(SO_GET_FILTER)
2335 /*
2336 * There seems to be an issue with the
2337 * ioctl(...SIOCNQ...) call libkqueue
2338 * uses to determine the number of bytes
2339 * readable. When ioctl returns, the number
2340 * of bytes available is set to zero, which
2341 * libkqueue interprets as EOF.
2342 *
2343 * As a workaround, if we're not reading
2344 * a file, and are operating on a raw socket
2345 * with a packet filter attached, we ignore
2346 * the EOF flag and continue.
2347 */
2348 if ((ef->sock_type == SOCK_RAW) && (ef->type == FR_EVENT_FD_PCAP)) goto service;
2349#endif
2350
2351 /*
2352 * If we see an EV_EOF flag that means the
2353 * read side of the socket has been closed
2354 * but there may still be pending data.
2355 *
2356 * Dispatch the read event and then error.
2357 */
2358 if ((el->events[i].filter == EVFILT_READ) && (el->events[i].data > 0)) {
2359 event_callback(el, ef, &filter, flags, &fflags);
2360 }
2361
2362 fd_errno = el->events[i].fflags;
2363
2364 goto ev_error;
2365 }
2366
2367 service:
2368#ifndef NDEBUG
2369 EVENT_DEBUG("Running event for fd %d, from %s[%d]", ef->fd, ef->file, ef->line);
2370#endif
2371
2372 /*
2373 * Service the event_fd events
2374 */
2375 event_callback(el, ef, &filter, flags, &fflags);
2376 }
2377 }
2378 }
2379
2380 /*
2381 * Process any deferred frees performed
2382 * by the I/O handlers.
2383 *
2384 * The events are removed from the FD rbtree
2385 * and kevent immediately, but frees are
2386 * deferred to allow stale events to be
2387 * skipped sans SEGV.
2388 */
2389 el->in_handler = false; /* Allow events to be deleted */
2390 {
2391 fr_event_fd_t *ef;
2392
2393 while ((ef = fr_dlist_head(&el->fd_to_free))) talloc_free(ef);
2394 }
2395
2396 /*
2397 * We must call el->time() again here, else the event
2398 * list's time gets updated too infrequently, and we
2399 * can end up with a situation where timers are
2400 * serviced much later than they should be, which can
2401 * cause strange interaction effects, spurious calls
2402 * to kevent, and busy loops.
2403 */
2404 now = etl->time();
2405
2406 /*
2407 * Run all of the timer events. Note that these can add
2408 * new timers!
2409 */
2411 int ret;
2412
2413 when = now;
2414
2415 ret = fr_timer_list_run(etl, &when);
2416 if (!fr_cond_assert(ret >= 0)) { /* catastrophic error, trigger event loop exit */
2417 el->exit = 1;
2418 return;
2419 }
2420
2421 EVENT_DEBUG("%p - %s - Serviced %u timer(s)", el, __FUNCTION__, (unsigned int)ret);
2422 }
2423
2424 now = etl->time();
2425
2426 /*
2427 * Run all of the post-processing events.
2428 */
2429 for (post = fr_dlist_head(&el->post_callbacks);
2430 post != NULL;
2431 post = fr_dlist_next(&el->post_callbacks, post)) {
2432 post->callback(el, now, post->uctx);
2433 }
2434}
2435
2436/** Service any outstanding timer or file descriptor events
2437 *
2438 * @param[in] el containing events to service.
2439 */
2440CC_NO_UBSAN(function) /* UBSAN: false positive - Public/private version of fr_event_list_t trips -fsanitize=function */
2442{
2443 event_service(el, true);
2444}
2445
2446/** Service any outstanding user, PID, and timer events, but not file descriptor events
2447 *
2448 * @param[in] el containing events to service.
2449 */
2450CC_NO_UBSAN(function) /* UBSAN: false positive - Public/private version of fr_event_list_t trips -fsanitize=function */
2452{
2453 event_service(el, false);
2454}
2455
2456/** Signal an event loop exit with the specified code
2457 *
2458 * The event loop will complete its current iteration, and then exit with the specified code.
2459 *
2460 * @param[in] el to signal to exit.
2461 * @param[in] code for #fr_event_loop to return.
2462 */
2464{
2465 if (unlikely(!el)) return;
2466
2467 el->will_exit = code;
2468}
2469
2470/** Check to see whether the event loop is in the process of exiting
2471 *
2472 * @param[in] el to check.
2473 */
2475{
2476 return ((el->will_exit != 0) || (el->exit != 0));
2477}
2478
2479/** Run an event loop
2480 *
2481 * @note Will not return until #fr_event_loop_exit is called.
2482 *
2483 * @param[in] el to start processing.
2484 */
2485CC_HINT(flatten) int fr_event_loop(fr_event_list_t *el)
2486{
2487 el->will_exit = el->exit = 0;
2488
2489 el->dispatch = true;
2490 while (!el->exit) {
2491 if (unlikely(fr_event_corral(el, el->pub.tl->time(), true)) < 0) break;
2493 }
2494
2495 /*
2496 * Give processes five seconds to exit.
2497 * This means any triggers that we may
2498 * have issued when the server exited
2499 * have a chance to complete.
2500 */
2502 el->dispatch = false;
2503
2504 return el->exit;
2505}
2506
2507/** Run an event loop during shutdown
2508 *
2509 * Don't run the FD events, as we're shutting down. Instead, run only user events, PID events, timers, pre /
2510 * post callbacks, which let the network and the workers clean up themselves.
2511 *
2512 * This function is otherwise the same as #fr_event_loop. We don't want to read or write connections which
2513 * are being closed.
2514 *
2515 * A file descriptor which is always ready makes kevent() return at once, so the loop does not sleep while
2516 * such a file descriptor is open. The loop ends when #fr_event_loop_exit is called, which the close events
2517 * do.
2518 *
2519 * @note Will not return until #fr_event_loop_exit is called.
2520 *
2521 * @param[in] el to start processing.
2522 */
2524{
2525 el->will_exit = el->exit = 0;
2526
2527 el->dispatch = true;
2528 while (!el->exit) {
2529 if (unlikely(fr_event_corral(el, el->pub.tl->time(), true)) < 0) break;
2531 }
2532
2534 el->dispatch = false;
2535
2536 return el->exit;
2537}
2538
2539/** Cleanup an event list
2540 *
2541 * Frees/destroys any resources associated with an event list
2542 *
2543 * @param[in] el to free resources for.
2544 */
2546{
2548
2549 talloc_free_children(el);
2550
2551 if (el->kq >= 0) close(el->kq);
2552
2553 return 0;
2554}
2555
2556/** Free any memory we allocated for indexes
2557 *
2558 */
2559static int _event_free_indexes(UNUSED void *uctx)
2560{
2561 unsigned int i;
2562
2563 for (i = 0; i < NUM_ELEMENTS(filter_maps); i++) if (talloc_free(filter_maps[i].ev_to_func) < 0) return -1;
2564 return 0;
2565}
2566
2567static int _event_build_indexes(UNUSED void *uctx)
2568{
2569 unsigned int i;
2570
2572 return 0;
2573}
2574
2575#ifdef EVFILT_LIBKQUEUE
2576/** kqueue logging wrapper function
2577 *
2578 */
2579static CC_HINT(format (printf, 1, 2)) CC_HINT(nonnull)
2580void _event_kqueue_log(char const *fmt, ...)
2581{
2582 va_list ap;
2583
2584 va_start(ap, fmt);
2585 fr_vlog(&default_log, L_DBG, __FILE__, __LINE__, fmt, ap);
2586 va_end(ap);
2587}
2588
2589/** If we're building with libkqueue, and at debug level 4 or higher, enable libkqueue debugging output
2590 *
2591 * This requires a debug build of libkqueue
2592 */
2593static int _event_kqueue_logging(UNUSED void *uctx)
2594{
2595 struct kevent kev, receipt;
2596
2597 log_conf_kq = kqueue();
2598 if (unlikely(log_conf_kq < 0)) {
2599 fr_strerror_const("Failed initialising logging configuration kqueue");
2600 return -1;
2601 }
2602
2603 EV_SET(&kev, 0, EVFILT_LIBKQUEUE, EV_ADD, NOTE_DEBUG_FUNC, (intptr_t)_event_kqueue_log, NULL);
2604 if (kevent(log_conf_kq, &kev, 1, &receipt, 1, &(struct timespec){}) != 1) {
2605 close(log_conf_kq);
2606 log_conf_kq = -1;
2607 return 1;
2608 }
2609
2610 if (fr_debug_lvl >= L_DBG_LVL_3) {
2611 EV_SET(&kev, 0, EVFILT_LIBKQUEUE, EV_ADD, NOTE_DEBUG, 1, NULL);
2612 if (kevent(log_conf_kq, &kev, 1, &receipt, 1, &(struct timespec){}) != 1) {
2613 fr_strerror_const("Failed enabling libkqueue debug logging");
2614 close(log_conf_kq);
2615 log_conf_kq = -1;
2616 return -1;
2617 }
2618 }
2619
2620 return 0;
2621}
2622
2623static int _event_kqueue_logging_stop(UNUSED void *uctx)
2624{
2625 struct kevent kev, receipt;
2626
2627 if (log_conf_kq < 0) return 0;
2628
2629 EV_SET(&kev, 0, EVFILT_LIBKQUEUE, EV_ADD, NOTE_DEBUG_FUNC, 0, NULL);
2630 (void)kevent(log_conf_kq, &kev, 1, &receipt, 1, &(struct timespec){});
2631
2632 close(log_conf_kq);
2633 log_conf_kq = -1;
2634
2635 return 0;
2636}
2637#endif
2638
2639/** Initialise a new event list
2640 *
2641 * @param[in] ctx to allocate memory in.
2642 * @param[in] status callback, called on each iteration of the event list.
2643 * @param[in] status_uctx context for the status callback
2644 * @return
2645 * - A pointer to a new event list on success (free with talloc_free).
2646 * - NULL on error.
2647 */
2648fr_event_list_t *fr_event_list_alloc(TALLOC_CTX *ctx, fr_event_status_cb_t status, void *status_uctx)
2649{
2651 struct kevent kev;
2652 int ret;
2653
2654 /*
2655 * Build the map indexes the first time this
2656 * function is called.
2657 */
2658 fr_atexit_global_once_ret(&ret, _event_build_indexes, _event_free_indexes, NULL);
2659#ifdef EVFILT_LIBKQUEUE
2660 fr_atexit_global_once_ret(&ret, _event_kqueue_logging, _event_kqueue_logging_stop, NULL);
2661#endif
2662
2663 el = talloc_zero(ctx, fr_event_list_t);
2664 if (!fr_cond_assert(el)) {
2665 fr_strerror_const("Out of memory");
2666 return NULL;
2667 }
2668 el->kq = -1; /* So destructor can be used before kqueue() provides us with fd */
2669 talloc_set_destructor(el, _event_list_free);
2670
2672 if (!el->pub.tl) {
2673 fr_strerror_const("Failed allocating timer list");
2674 error:
2675 talloc_free(el);
2676 return NULL;
2677 }
2678
2680 if (!el->fds) {
2681 fr_strerror_const("Failed allocating FD tree");
2682 goto error;
2683 }
2684
2685 el->kq = kqueue();
2686 if (el->kq < 0) {
2687 fr_strerror_printf("Failed allocating kqueue: %s", fr_syserror(errno));
2688 goto error;
2689 }
2690
2695 if (status) (void) fr_event_pre_insert(el, status, status_uctx);
2696
2697 /*
2698 * Set our "exit" callback as ident 0.
2699 */
2700 EV_SET(&kev, 0, EVFILT_USER, EV_ADD | EV_CLEAR, NOTE_FFNOP, 0, NULL);
2701 if (kevent(el->kq, &kev, 1, NULL, 0, NULL) < 0) {
2702 fr_strerror_printf("Failed adding exit callback to kqueue: %s", fr_syserror(errno));
2703 goto error;
2704 }
2705
2706 return el;
2707}
2708
2709#ifdef __linux__
2710/*
2711 * The kqueue API takes an FD, but inotify requires a filename.
2712 * libkqueue uses /proc/PID/fd/# to look up the FD -> filename mapping.
2713 *
2714 * However, if you start the server as "root", and then swap to "radiusd",
2715 * /proc/PID will be owned by "root" for security reasons. The only way
2716 * to make /proc/PID owned by "radiusd" is to set the DUMPABLE flag.
2717 *
2718 * To avoid this requirement, this API allows inotify events to be
2719 * registered rather than using libkqueue with filter EVFILT_VNODE
2720 */
2721
2722 /** Read a single inotify event
2723 */
2724static int inotify_event_read(struct inotify_event *ev, size_t len, int fd)
2725{
2726 ssize_t size;
2727 size_t want = sizeof(struct inotify_event);
2728
2729 for (;;) {
2730 if (len < want) {
2731 fr_strerror_printf("Needed %zu bytes have %zu bytes", want, len);
2732 return (-1);
2733 }
2734
2735 /*
2736 * The size of each inotify event is variable, due to the
2737 * last structure member being a variable length array.
2738 *
2739 * To ensure that we only read one event, we start with the
2740 * read length being the base structure size and increment
2741 * it by that length each time errno is EINVAL - which
2742 * occurs when read is called with a buffer size less than
2743 * required.
2744 */
2745 size = read(fd, ev, want);
2746 if (size < 0) {
2747 switch (errno) {
2748 case EINVAL:
2749 want += sizeof(struct inotify_event);
2750 continue;
2751
2752 case EINTR:
2753 continue;
2754
2755 case EAGAIN:
2756 return 0;
2757
2758 default:
2759 fr_strerror_printf("Inotify read returned %s", fr_syserror(errno));
2760 return -1;
2761 }
2762 }
2763 break;
2764 }
2765
2766 return 1;
2767}
2768
2769/** Callback run when the inotify fd receives notification of an event.
2770 */
2771static void _file_watch_event_read(fr_event_list_t *el, int fd, UNUSED int flags, void *uctx)
2772{
2773 fr_event_file_watch_t *ev = talloc_get_type_abort(uctx, fr_event_file_watch_t);
2774 uint8_t buff[sizeof(struct inotify_event) + NAME_MAX + 1] __attribute__ ((aligned(__alignof__(struct inotify_event))));
2775 struct inotify_event *event = (struct inotify_event*) buff;
2776 uint32_t merged_mask = 0;
2777 bool delete = false;
2778
2779 /*
2780 * Read all the events reported by inotify and
2781 * merge the reported mask values.
2782 */
2783 for (;;) {
2784 int ret = inotify_event_read(event, sizeof(buff), fd);
2785 if (ret < 0) return;
2786 if (ret == 0) break;
2787
2788 if (event->mask & IN_IGNORED) continue;
2789
2790 merged_mask |= event->mask;
2791 }
2792
2793 /*
2794 * Delete events which just remove a link return IN_ATTRIB rather than IN_DELETE_SELF
2795 * Use stat to see if the file has been deleted.
2796 */
2797 if (merged_mask & IN_ATTRIB) {
2798 struct stat sb;
2799 if ((stat(ev->name, &sb) < 0) && (errno == ENOENT)) delete = true;
2800 }
2801
2802 if (((merged_mask & IN_DELETE_SELF) || delete) && ev->funcs.delete) {
2803 ev->funcs.delete(el, ev->fd, NOTE_DELETE, ev->uctx);
2804 }
2805 if ((merged_mask & IN_MODIFY) && ev->funcs.write) {
2806 ev->funcs.write(el, ev->fd, NOTE_WRITE, ev->uctx);
2807 }
2808 if ((merged_mask & IN_CREATE) && ev->funcs.extend) {
2809 ev->funcs.extend(el, ev->fd, NOTE_EXTEND, ev->uctx);
2810 }
2811 if ((merged_mask & IN_ATTRIB) && ev->funcs.link) {
2812 ev->funcs.link(el, ev->fd, NOTE_LINK, ev->uctx);
2813 }
2814 if ((merged_mask & IN_MOVE_SELF) && ev->funcs.rename) {
2815 ev->funcs.rename(el, ev->fd, NOTE_LINK, ev->uctx);
2816 }
2817}
2818
2819/** Tidy up a file watch event
2820 */
2821static int _file_watch_free(fr_event_file_watch_t *ev) {
2822 (void) fr_event_fd_delete(ev->el, ev->in_fd, FR_EVENT_FILTER_IO);
2823 if (ev->wd) inotify_rm_watch(ev->in_fd, ev->wd);
2824 close(ev->in_fd);
2825 return 0;
2826}
2827
2828/** Register a new file watch event
2829 */
2830int fr_event_file_watch_insert(TALLOC_CTX *ctx, fr_event_file_watch_t **ev_out, fr_event_list_t *el,
2831 int fd, char const *filename, fr_event_vnode_func_t *funcs, void *uctx)
2832{
2833 uint32_t mask = 0;
2835 fr_event_fd_cb_t const *func;
2837
2838 ev = talloc(ctx, fr_event_file_watch_t);
2839 if (!ev) return -1;
2840
2841 *ev = (fr_event_file_watch_t) {
2842 .funcs = *funcs,
2843 .el = el,
2844 .fd = fd,
2845 .name = filename,
2846 .uctx = uctx
2847 };
2848
2849 ev->in_fd = inotify_init1(IN_CLOEXEC | IN_NONBLOCK);
2850 if (ev->in_fd < 0){
2851 error:
2852 talloc_free(ev);
2853 return -1;
2854 }
2855
2856 talloc_set_destructor(ev, _file_watch_free);
2857
2858 /*
2859 * Determine the inotify mask from the callback functions defined
2860 */
2861 for (map = filter_maps[FR_EVENT_FILTER_VNODE].func_to_ev; map->name; map++) {
2862 func = (fr_event_fd_cb_t const *)((uint8_t const *)funcs + map->offset);
2863 if (!(*func)) continue;
2864
2865 mask |= map->inotify_mask;
2866 }
2867
2868 ev->wd = inotify_add_watch(ev->in_fd, filename, mask);
2869 if (ev->wd < 0) goto error;
2870
2871 if (fr_event_fd_insert(ev, &ev->fd_ev, el, ev->in_fd, _file_watch_event_read, NULL, NULL, ev) < 0) goto error;
2872 if (ev_out) *ev_out = ev;
2873
2874 return 0;
2875}
2876
2877/** Delete a file watch event
2878 */
2879int fr_event_file_watch_delete(fr_event_file_watch_t *ev)
2880{
2881 if (talloc_free(ev) < 0) return -1;
2882 return 0;
2883}
2884#endif
2885
2886#ifndef NDEBUG
2887#define EVENT_EMPTY_MAX_PRINT (10)
2888
2889/** Print the file descriptor events which remain in an event list
2890 *
2891 * At most EVENT_EMPTY_MAX_PRINT events are printed, followed by a count of the events which were not printed.
2892 *
2893 * @param[in] el to print the file descriptor events of.
2894 */
2896{
2897 uint64_t total = fr_event_list_num_fds(el);
2898 unsigned int shown = 0;
2899
2900 FR_FAULT_LOG("Event list %p has %" PRIu64 " file descriptors remaining", el, total);
2901
2903 if (shown >= EVENT_EMPTY_MAX_PRINT) break;
2904
2905 FR_FAULT_LOG(" fd %d allocated at %s[%d]", ef->fd, ef->file, ef->line);
2906 shown++;
2907 }}
2908
2909 if (total > shown) FR_FAULT_LOG(" ... and %" PRIu64 " more file descriptors", total - shown);
2910}
2911
2912/** Assert that an event list has no file descriptors and no timer events
2913 *
2914 * If the event list has either, print up to EVENT_EMPTY_MAX_PRINT of each by file and line, and then assert.
2915 *
2916 * Only built when fr_assert() is active, i.e. when NDEBUG is not defined. Otherwise event.h defines
2917 * fr_event_list_empty() as a macro which does nothing.
2918 *
2919 * @param[in] el to check.
2920 */
2922{
2924
2926
2928}
2929#endif
2930#ifdef TESTING
2931/*
2932 * cc -g -I .. -c rb.c -o rbtree.o && cc -g -I .. -c isaac.c -o isaac.o && cc -DTESTING -I .. -c event.c -o event_mine.o && cc event_mine.o rbtree.o isaac.o -o event
2933 *
2934 * ./event
2935 *
2936 * And hit CTRL-S to stop the output, CTRL-Q to continue.
2937 * It normally alternates printing the time and sleeping,
2938 * but when you hit CTRL-S/CTRL-Q, you should see a number
2939 * of events run right after each other.
2940 *
2941 * OR
2942 *
2943 * valgrind --tool=memcheck --leak-check=full --show-reachable=yes ./event
2944 */
2945
2946static void print_time(void *ctx)
2947{
2948 fr_time_t when;
2949 int64_t usec;
2950
2951 when = *(fr_time_t *) ctx;
2952 usec = fr_time_to_usec(when);
2953
2954 printf("%d.%06d\n", usec / USEC, usec % USEC);
2955 fflush(stdout);
2956}
2957
2958static fr_randctx rand_pool;
2959
2960static uint32_t event_rand(void)
2961{
2962 uint32_t num;
2963
2964 num = rand_pool.randrsl[rand_pool.randcnt++];
2965 if (rand_pool.randcnt == 256) {
2966 fr_isaac(&rand_pool);
2967 rand_pool.randcnt = 0;
2968 }
2969
2970 return num;
2971}
2972
2973
2974#define MAX 100
2975int main(int argc, char **argv)
2976{
2977 int i, rcode;
2978 fr_time_t array[MAX];
2979 fr_time_t now, when;
2981
2982 el = fr_event_list_alloc(NULL, NULL);
2983 if (!el) fr_exit_now(1);
2984
2985 memset(&rand_pool, 0, sizeof(rand_pool));
2986 rand_pool.randrsl[1] = time(NULL);
2987
2988 fr_rand_init(&rand_pool, 1);
2989 rand_pool.randcnt = 0;
2990
2991 array[0] = el->time();
2992 for (i = 1; i < MAX; i++) {
2993 array[i] = array[i - 1];
2994 array[i] += event_rand() & 0xffff;
2995
2996 fr_timer_at(NULL, el, array[i], false, print_time, array[i]);
2997 }
2998
2999 while (fr_event_list_num_timers(el)) {
3000 now = el->time();
3001 when = now;
3002 if (!fr_timer_run(el, &when)) {
3003 int delay = (when - now) / 1000; /* nanoseconds to microseconds */
3004
3005 printf("\tsleep %d microseconds\n", delay);
3006 fflush(stdout);
3007 usleep(delay);
3008 }
3009 }
3010
3011 talloc_free(el);
3012
3013 return 0;
3014}
3015#endif
int const char * file
Definition acutest.h:855
va_end(args)
static int const char * fmt
Definition acutest.h:638
void int line
Definition acutest.h:810
va_start(args, fmt)
#define RCSID(id)
Definition build.h:609
#define DIAG_OFF_OPTIONAL(_x)
Definition build.h:583
#define L(_str)
Helper for initialising arrays of string literals.
Definition build.h:245
#define typeof_field(_type, _field)
Typeof field.
Definition build.h:210
#define DIAG_ON(_x)
Definition build.h:582
#define CC_NO_UBSAN(_sanitize)
Definition build.h:540
#define CMP_RETURN(_a, _b, _field)
Return if the comparison is not 0 (is unequal)
Definition build.h:139
#define CMP(_a, _b)
Same as CMP_PREFER_SMALLER use when you don't really care about ordering, you just want an ordering.
Definition build.h:130
#define unlikely(_x)
Definition build.h:492
#define NDEBUG_LOCATION_VALS
Definition build.h:362
#define NDEBUG_LOCATION_ARGS
Pass caller information to the function.
Definition build.h:361
#define UNUSED
Definition build.h:415
#define NUM_ELEMENTS(_t)
Definition build.h:443
#define DIAG_OFF(_x)
Definition build.h:581
fr_cmp_ret_t
Result of an ordering comparison.
Definition build.h:113
#define fr_cond_assert(_x)
Calls panic_action ifndef NDEBUG, else logs error and evaluates to value of _x.
Definition debug.h:177
#define fr_assert_fail(_msg,...)
Calls panic_action ifndef NDEBUG, else logs error.
Definition debug.h:254
#define FR_FAULT_LOG(_fmt,...)
Definition debug.h:52
#define fr_cond_assert_msg(_x, _fmt,...)
Calls panic_action ifndef NDEBUG, else logs error and evaluates to value of _x.
Definition debug.h:194
#define fr_exit_now(_x)
Exit without calling atexit() handlers, producing a log message in debug builds.
Definition debug.h:272
int main(int argc, char **argv)
Definition dhcpclient.c:530
static void * fr_dlist_head(fr_dlist_head_t const *list_head)
Return the HEAD item of a list or NULL if the list is empty.
Definition dlist.h:468
#define fr_dlist_foreach(_list_head, _type, _iter)
Iterate over the contents of a list.
Definition dlist.h:98
static void * fr_dlist_remove(fr_dlist_head_t *list_head, void *ptr)
Remove an item from the list.
Definition dlist.h:620
static bool fr_dlist_entry_in_list(fr_dlist_t const *entry)
Check if a list entry is part of a list.
Definition dlist.h:145
static unsigned int fr_dlist_num_elements(fr_dlist_head_t const *head)
Return the number of elements in the dlist.
Definition dlist.h:921
static int fr_dlist_insert_tail(fr_dlist_head_t *list_head, void *ptr)
Insert an item into the tail of a list.
Definition dlist.h:360
#define fr_dlist_talloc_init(_head, _type, _field)
Initialise the head structure of a doubly linked list.
Definition dlist.h:257
static void * fr_dlist_next(fr_dlist_head_t const *list_head, void const *ptr)
Get the next item in a list.
Definition dlist.h:537
Head of a doubly linked list.
Definition dlist.h:51
Entry in a doubly linked list.
Definition dlist.h:41
#define fr_event_fd_insert(...)
Definition event.h:251
fr_event_fd_cb_t write
The file was written to.
Definition event.h:201
fr_event_io_func_t io
Read/write functions.
Definition event.h:218
struct fr_event_user_s fr_event_user_t
An opaque user event handle.
Definition event.h:78
void(* fr_event_fd_cb_t)(fr_event_list_t *el, int fd, int flags, void *uctx)
Called when an IO event occurs on a file descriptor.
Definition event.h:154
size_t offset
Offset of function in func struct.
Definition event.h:101
fr_timer_list_t * tl
The timer list associated with this event loop.
Definition event.h:47
struct fr_event_pid fr_event_pid_t
An opaque PID status handle.
Definition event.h:74
fr_event_fd_cb_t read
Callback for when data is available.
Definition event.h:193
void(* fr_event_pid_cb_t)(fr_event_list_t *el, pid_t pid, int status, void *uctx)
Called when a child process has exited.
Definition event.h:173
void(* fr_event_error_cb_t)(fr_event_list_t *el, int fd, int flags, int fd_errno, void *uctx)
Called when an IO error event occurs on a file descriptor.
Definition event.h:164
@ FR_EVENT_OP_SUSPEND
Temporarily remove the relevant filter from kevent.
Definition event.h:94
@ FR_EVENT_OP_RESUME
Reinsert the filter into kevent.
Definition event.h:95
fr_event_filter_t
The type of filter to install for an FD.
Definition event.h:86
@ FR_EVENT_FILTER_VNODE
Filter for vnode subfilters.
Definition event.h:88
@ FR_EVENT_FILTER_IO
Combined filter for read/write functions/.
Definition event.h:87
int(* fr_event_status_cb_t)(fr_time_t now, fr_time_delta_t wake, void *uctx)
Called after each event loop cycle.
Definition event.h:145
void(* fr_event_post_cb_t)(fr_event_list_t *el, fr_time_t now, void *uctx)
Called when a post event fires.
Definition event.h:188
fr_event_op_t op
Operation to perform on function/filter.
Definition event.h:102
void(* fr_event_user_cb_t)(fr_event_list_t *el, void *uctx)
Called when a user kevent occurs.
Definition event.h:180
#define EVENT_DEBUG(...)
Definition event.h:65
void fr_event_list_empty(fr_event_list_t *el)
#define fr_event_user_insert(_ctx, _el, _ev_p, _trigger, _callback, _uctx)
Definition event.h:285
struct fr_event_file_watch fr_event_file_watch_t
An opaque file watch handle.
Definition event.h:82
Callbacks for the FR_EVENT_FILTER_IO filter.
Definition event.h:192
Public event list structure.
Definition event.h:46
Structure describing a modification to a filter's state.
Definition event.h:100
Callbacks for the FR_EVENT_FILTER_VNODE filter.
Definition event.h:199
Union of all filter functions.
Definition event.h:217
free(array)
talloc_free(hp)
void fr_isaac(fr_randctx *ctx)
Definition isaac.c:46
fr_dlist_head_t pre_callbacks
callbacks when we may be idle...
Definition event.c:430
int fr_event_loop_finalize(fr_event_list_t *el)
Run an event loop during shutdown.
Definition event.c:2523
void fr_event_service(fr_event_list_t *el)
Service any outstanding timer or file descriptor events.
Definition event.c:2441
fr_dlist_head_t post_callbacks
post-processing callbacks
Definition event.c:431
static fr_event_func_map_t filter_maps[]
Definition event.c:142
static void event_service(fr_event_list_t *el, bool fd_events)
Service any outstanding timer or file descriptor events.
Definition event.c:2261
static fr_event_fd_cb_t event_fd_func(fr_event_fd_t *ef, int *filter, uint32_t *fflags)
Figure out which function to call given a kevent.
Definition event.c:523
static int fr_event_fd_type_set(fr_event_fd_t *ef, int fd)
Discover the type of a file descriptor.
Definition event.c:785
fr_event_func_map_entry_t * func_to_ev
Function -> Event maps coalesced, out of order.
Definition event.c:138
fr_event_error_cb_t error
Callback for when an error occurs on the FD.
Definition event.c:298
char const * file
Source file this event was last updated in.
Definition event.c:340
fr_event_pid_cb_t callback
callback to run when the child exits
Definition event.c:356
fr_event_funcs_t stored
Stored (set, but inactive) filter functions.
Definition event.c:296
static ssize_t fr_event_build_evset(UNUSED fr_event_list_t *el, struct kevent out_kev[], size_t outlen, fr_event_funcs_t *active, fr_event_fd_t *ef, fr_event_funcs_t const *new, fr_event_funcs_t const *prev)
Build a new evset based on function pointers present.
Definition event.c:652
fr_rb_tree_t * fds
Tree used to track FDs with filters in kqueue.
Definition event.c:417
bool is_registered
Whether this fr_event_fd_t's FD has been registered with kevent.
Definition event.c:302
char const * file
Source file this event was last updated in.
Definition event.c:315
fr_time_t fr_event_list_time(fr_event_list_t *el)
Get the current server time according to the event list.
Definition event.c:621
int fr_event_pre_delete(fr_event_list_t *el, fr_event_status_cb_t callback, void *uctx)
Delete a pre-event callback from the event list.
Definition event.c:2058
static void event_callback(fr_event_list_t *el, fr_event_fd_t *ef, int *filter, int flags, uint32_t *fflags)
Definition event.c:2246
fr_event_list_t * el
Event list this event belongs to.
Definition event.c:321
static void event_list_reap_run_callback(fr_event_pid_reap_t *reap, pid_t pid, int status)
Saves some boilerplate...
Definition event.c:1672
int line
Line this event was last updated on.
Definition event.c:374
static int _event_fd_delete(fr_event_fd_t *ef)
Remove a file descriptor from the event loop and rbtree but don't explicitly free it.
Definition event.c:852
int _fr_event_pid_reap(NDEBUG_LOCATION_ARGS fr_event_list_t *el, pid_t pid, fr_event_pid_cb_t callback, void *uctx)
Asynchronously wait for a PID to exit, then reap it.
Definition event.c:1723
fr_event_filter_t filter
Definition event.c:288
#define FR_EVENT_FD_PCAP
Definition event.c:112
void * uctx
Context pointer to pass to each file descriptor callback.
Definition event.c:357
fr_event_status_cb_t callback
The callback to call.
Definition event.c:399
static void _fr_event_pid_reap_cb(UNUSED fr_event_list_t *el, pid_t pid, int status, void *uctx)
Does the actual reaping of PIDs.
Definition event.c:1680
int line
Line this event was last updated on.
Definition event.c:341
static size_t kevent_filter_table_len
Definition event.c:85
int fr_event_fd_delete_handle(fr_event_fd_t *ef)
Remove a file descriptor from the event loop, by handle.
Definition event.c:1269
struct fr_event_list_pub_s pub
Next event list in the chain.
Definition event.c:416
int _fr_event_user_insert(NDEBUG_LOCATION_ARGS TALLOC_CTX *ctx, fr_event_list_t *el, fr_event_user_t **ev_p, bool trigger, fr_event_user_cb_t callback, void *uctx)
Add a user callback to the event list.
Definition event.c:1943
fr_event_fd_type_t type
Type of events we're interested in.
Definition event.c:291
static fr_table_num_sorted_t const fr_event_fd_type_table[]
Definition event.c:271
static fr_cmp_ret_t fr_event_fd_cmp(void const *one, void const *two)
Compare two file descriptor handles.
Definition event.c:567
static size_t fr_event_fd_type_table_len
Definition event.c:277
uint16_t flags
Flags to use for inserting event.
Definition event.c:126
fr_event_pid_cb_t callback
callback to run when the child exits
Definition event.c:329
static int _event_list_free(fr_event_list_t *el)
Cleanup an event list.
Definition event.c:2545
bool dispatch
Whether the event list is currently dispatching events.
Definition event.c:424
fr_dlist_head_t fd_to_free
File descriptor events pending deletion.
Definition event.c:441
fr_event_func_idx_type_t
Definition event.c:101
@ FR_EVENT_FUNC_IDX_FILTER
Sign flip is performed i.e. -1 = 0The filter is used / as the index in the ev to func index.
Definition event.c:104
@ FR_EVENT_FUNC_IDX_NONE
Definition event.c:102
@ FR_EVENT_FUNC_IDX_FFLAGS
The bit position of the flags in FFLAGS is used to provide the index.
Definition event.c:106
bool coalesce
Coalesce this map with the next.
Definition event.c:132
fr_dlist_t entry
Entry in free list.
Definition event.c:308
int fr_event_corral(fr_event_list_t *el, fr_time_t now, bool wait)
Gather outstanding timer and file descriptor events.
Definition event.c:2128
static int _event_free_indexes(UNUSED void *uctx)
Free any memory we allocated for indexes.
Definition event.c:2559
void * uctx
Context for the callback.
Definition event.c:409
bool is_registered
Whether this user event has been registered with the event loop.
Definition event.c:366
int type
Type this filter applies to.
Definition event.c:131
uint64_t fr_event_list_num_timers(fr_event_list_t *el)
Return the number of timer events currently scheduled.
Definition event.c:591
fr_event_func_map_t const * map
Function map between fr_event_funcs_t and kevent filters.
Definition event.c:300
void * uctx
Context for the callback.
Definition event.c:400
fr_event_post_cb_t callback
The callback to call.
Definition event.c:408
int _fr_event_pid_wait(NDEBUG_LOCATION_ARGS TALLOC_CTX *ctx, fr_event_list_t *el, fr_event_pid_t const **ev_p, pid_t pid, fr_event_pid_cb_t callback, void *uctx)
Insert a PID event into an event list.
Definition event.c:1494
char const * name
Name of the event.
Definition event.c:124
int line
Line this event was last updated on.
Definition event.c:316
uintptr_t armour
protection flag from being deleted.
Definition event.c:311
fr_event_user_cb_t callback
The callback to call.
Definition event.c:369
int fr_event_fd_unarmour(fr_event_list_t *el, int fd, fr_event_filter_t filter, uintptr_t armour)
Unarmour an FD.
Definition event.c:1373
int sock_type
The type of socket SOCK_STREAM, SOCK_RAW etc...
Definition event.c:293
fr_dlist_head_t pid_to_reap
A list of all orphaned child processes we're waiting to reap.
Definition event.c:433
uint64_t fr_event_list_num_fds(fr_event_list_t *el)
Return the number of file descriptors is_registered with this event loop.
Definition event.c:579
#define EVENT_EMPTY_MAX_PRINT
Definition event.c:2887
int fr_event_post_delete(fr_event_list_t *el, fr_event_post_cb_t callback, void *uctx)
Delete a post-event callback from the event list.
Definition event.c:2106
void * uctx
Context pointer to pass to each file descriptor callback.
Definition event.c:305
struct fr_event_pid::@157 early_exit
Fields that are only used if we're being triggered by a user event.
fr_event_func_idx_type_t idx_type
What type of index we use for event to function mapping.
Definition event.c:136
#define GET_FUNC(_ef, _offset)
void * fr_event_fd_uctx(fr_event_fd_t *ef)
Returns the uctx associated with an fr_event_fd_t handle.
Definition event.c:1327
static int _fr_event_reap_free(fr_event_pid_reap_t *reap)
Definition event.c:1693
int kq
instance associated with this event list.
Definition event.c:428
pid_t pid
child to wait for
Definition event.c:326
static void event_pid_eval(fr_event_list_t *el, struct kevent *kev)
Evaluate a EVFILT_PROC event.
Definition event.c:1416
int fr_event_list_kq(fr_event_list_t *el)
Return the kq associated with an event list.
Definition event.c:603
void * uctx
Context for the callback.
Definition event.c:370
bool is_registered
Whether this user event has been registered with the event loop.
Definition event.c:323
fr_event_list_t * el
Event list this event belongs to.
Definition event.c:364
int will_exit
Will exit on next call to fr_event_corral.
Definition event.c:419
static int _event_build_indexes(UNUSED void *uctx)
Definition event.c:2567
unsigned int fr_event_list_reap_signal(fr_event_list_t *el, fr_time_delta_t timeout, int signal)
Send a signal to all the processes we have in our reap list, and reap them.
Definition event.c:1759
int16_t filter
Filter to apply.
Definition event.c:125
fr_event_list_t * fr_event_list_alloc(TALLOC_CTX *ctx, fr_event_status_cb_t status, void *status_uctx)
Initialise a new event list.
Definition event.c:2648
fr_event_fd_cb_t fr_event_fd_cb(fr_event_fd_t *ef, int kq_filter, uint32_t kq_fflags)
Returns the appropriate callback function for a given event.
Definition event.c:1319
static void event_fd_func_index_build(fr_event_func_map_t *map)
Definition event.c:448
static void fr_event_fd_noop(UNUSED fr_event_list_t *el, UNUSED int fd, UNUSED int flags, UNUSED void *uctx)
Placeholder callback to avoid branches in service loop.
Definition event.c:631
fr_dlist_t entry
If the fr_event_pid is in the detached, reap state, it's inserted into a list associated with the eve...
Definition event.c:351
bool fr_event_loop_exiting(fr_event_list_t *el)
Check to see whether the event loop is in the process of exiting.
Definition event.c:2474
fr_dlist_t entry
Linked list of callback.
Definition event.c:398
int _fr_event_filter_update(NDEBUG_LOCATION_ARGS fr_event_list_t *el, int fd, fr_event_filter_t filter, fr_event_update_t const updates[])
Suspend/resume a subset of filters.
Definition event.c:984
char const * file
Source file this event was last updated in.
Definition event.c:373
int num_fd_events
Number of events in this event list.
Definition event.c:426
int _fr_event_fd_move(NDEBUG_LOCATION_ARGS fr_event_list_t *dst, fr_event_list_t *src, int fd, fr_event_filter_t filter)
Move a file descriptor event from one event list to another.
Definition event.c:933
fr_event_func_map_entry_t ** ev_to_func
Function -> Event maps in index order.
Definition event.c:139
int _fr_event_fd_insert(NDEBUG_LOCATION_ARGS TALLOC_CTX *ctx, fr_event_fd_t **ef_out, fr_event_list_t *el, int fd, fr_event_fd_cb_t read_fn, fr_event_fd_cb_t write_fn, fr_event_error_cb_t error, void *uctx)
Associate I/O callbacks with a file descriptor.
Definition event.c:1217
fr_event_pid_t const * pid_ev
pid_ev this reaper is bound to.
Definition event.c:349
fr_event_funcs_t active
Active filter functions.
Definition event.c:295
int fr_event_pre_insert(fr_event_list_t *el, fr_event_status_cb_t callback, void *uctx)
Add a pre-event callback to the event list.
Definition event.c:2036
static void _fr_event_pid_early_exit(fr_event_list_t *el, void *uctx)
Called on the next loop through the event loop when inserting an EVFILT_PROC event fails.
Definition event.c:1463
static void event_user_eval(fr_event_list_t *el, struct kevent *kev)
Definition event.c:1915
static void event_service_finalize(fr_event_list_t *el)
Service any outstanding user, PID, and timer events, but not file descriptor events.
Definition event.c:2451
int exit
If non-zero event loop will prevent the addition of new events, and will return immediately from the ...
Definition event.c:420
fr_event_list_t * el
Event list this event belongs to.
Definition event.c:287
static fr_table_num_sorted_t const kevent_filter_table[]
Definition event.c:68
TALLOC_CTX * linked_ctx
talloc ctx this event was bound to.
Definition event.c:306
void fr_event_loop_exit(fr_event_list_t *el, int code)
Signal an event loop exit with the specified code.
Definition event.c:2463
#define FR_EV_BATCH_FDS
Definition event.c:58
void * uctx
Context pointer to pass to each file descriptor callback.
Definition event.c:330
static int _event_pid_free(fr_event_pid_t *ev)
Remove PID wait event from kevent if the fr_event_pid_t is freed.
Definition event.c:1395
fr_event_list_t * el
Event list this event belongs to.
Definition event.c:348
int fd
File descriptor we're listening for events on.
Definition event.c:289
size_t offset
Offset of function pointer in structure.
Definition event.c:123
int fr_event_fd_delete(fr_event_list_t *el, int fd, fr_event_filter_t filter)
Remove a file descriptor from the event loop.
Definition event.c:1244
fr_dlist_t entry
Linked list of callback.
Definition event.c:407
int fr_event_loop(fr_event_list_t *el)
Run an event loop.
Definition event.c:2485
int fr_event_user_trigger(fr_event_user_t *ev)
Trigger a user event.
Definition event.c:2000
fr_event_fd_t * fr_event_fd_handle(fr_event_list_t *el, int fd, fr_event_filter_t filter)
Get the opaque event handle from a file descriptor.
Definition event.c:1297
static void event_list_print_remaining_fds(fr_event_list_t *el)
Print the file descriptor events which remain in an event list.
Definition event.c:2895
fr_rb_node_t node
Entry in the tree of file descriptor handles.
Definition event.c:283
int _fr_event_filter_insert(NDEBUG_LOCATION_ARGS TALLOC_CTX *ctx, fr_event_fd_t **ef_out, fr_event_list_t *el, int fd, fr_event_filter_t filter, void *funcs, fr_event_error_cb_t error, void *uctx)
Insert a filter for the specified fd.
Definition event.c:1061
#define NOTE_EXITSTATUS
int fr_event_post_insert(fr_event_list_t *el, fr_event_post_cb_t callback, void *uctx)
Add a post-event callback to the event list.
Definition event.c:2083
fr_event_pid_t const ** parent
Definition event.c:327
static int _event_user_delete(fr_event_user_t *ev)
Memory will not be freed if we fail to remove the event from the kqueue.
Definition event.c:1896
struct kevent events[FR_EV_BATCH_FDS]
Definition event.c:436
int fr_event_fd_armour(fr_event_list_t *el, int fd, fr_event_filter_t filter, uintptr_t armour)
Armour an FD.
Definition event.c:1343
fr_event_fd_type_t
Definition event.c:91
@ FR_EVENT_FD_FILE
is a file.
Definition event.c:93
@ FR_EVENT_FD_DIRECTORY
is a directory.
Definition event.c:94
@ FR_EVENT_FD_SOCKET
is a socket.
Definition event.c:92
bool in_handler
Deletes should be deferred until after the handlers complete.
Definition event.c:438
uint32_t fflags
fflags to pass to filter.
Definition event.c:127
A file descriptor/filter event.
Definition event.c:282
Specifies a mapping between a function pointer in a structure and its respective event.
Definition event.c:122
Stores all information relating to an event list.
Definition event.c:415
Hold additional information for automatically reaped PIDs.
Definition event.c:347
Callbacks to perform after all timers and FDs have been checked.
Definition event.c:406
Callbacks to perform when the event handler is about to check the events.
Definition event.c:397
Callbacks for kevent() user events.
Definition event.c:363
int fr_debug_lvl
Definition log.c:41
fr_log_t default_log
Definition log.c:308
@ L_DBG_LVL_3
3rd highest priority debug messages (-xxx | -Xx).
Definition log.h:69
#define fr_vlog(_log, _lvl, _file, _line, _fmt, _ap)
Definition log.h:166
@ L_DBG
Only displayed when debugging is enabled.
Definition log.h:56
static uint8_t fr_low_bit_pos(uint64_t num)
Find the lowest order high bit in an unsigned 64 bit integer.
Definition math.h:113
static uint8_t fr_high_bit_pos(uint64_t num)
Find the highest order high bit in an unsigned 64 bit integer.
Definition math.h:94
unsigned short uint16_t
unsigned int uint32_t
long int ssize_t
unsigned char uint8_t
unsigned long int size_t
#define fr_assert(_expr)
Definition rad_assert.h:37
void fr_rand_init(void)
Definition rand.c:33
uint32_t randrsl[256]
Definition rand.h:40
uint32_t randcnt
Definition rand.h:39
uint32_t fr_rb_num_elements(fr_rb_tree_t *tree)
Return how many nodes there are in a tree.
Definition rb.c:807
int fr_rb_find(void **found, fr_rb_tree_t const *tree, void const *data)
Find an element in the tree, returning the data, not the node.
Definition rb.c:586
int fr_rb_delete(fr_rb_tree_t *tree, void const *data)
Remove node and free data (if a free function was specified)
Definition rb.c:767
int fr_rb_insert(fr_rb_tree_t *tree, void const *data)
Insert data into a tree.
Definition rb.c:637
#define fr_rb_inline_talloc_alloc(_ctx, _type, _field, _data_cmp, _data_free)
Allocs a red black that verifies elements are of a specific talloc type.
Definition rb.h:244
#define fr_rb_inorder_foreach(_tree, _type, _iter)
Definition rb.h:330
The main red black tree structure.
Definition rb.h:71
static uint32_t mask
Definition rbmonkey.c:39
static char const * name
static char buff[sizeof("18446744073709551615")+3]
Definition size_tests.c:37
return count
Definition module.c:155
char const * fr_syserror(int num)
Guaranteed to be thread-safe version of strerror.
Definition syserror.c:243
#define fr_table_str_by_value(_table, _number, _def)
Convert an integer to a string.
Definition table.h:804
An element in a lexicographically sorted array of name to num mappings.
Definition table.h:49
int talloc_link_ctx(TALLOC_CTX *parent, TALLOC_CTX *child)
Link two different parent and child contexts, so the child is freed before the parent.
Definition talloc.c:168
#define fr_time_delta_to_timespec(_delta)
Convert a delta to a timespec.
Definition time.h:684
static fr_time_delta_t fr_time_delta_from_sec(int64_t sec)
Definition time.h:599
#define fr_time_delta_wrap(_time)
Definition time.h:152
#define fr_time_wrap(_time)
Definition time.h:145
#define fr_time_lteq(_a, _b)
Definition time.h:240
#define fr_time_delta_ispos(_a)
Definition time.h:290
static int64_t fr_time_to_usec(fr_time_t when)
Convert an fr_time_t (internal time) to number of usec since the unix epoch (wallclock time)
Definition time.h:719
#define fr_time_add(_a, _b)
Add a time/time delta together.
Definition time.h:196
#define fr_time_gt(_a, _b)
Definition time.h:237
#define USEC
Definition time.h:380
#define fr_time_sub(_a, _b)
Subtract one time from another.
Definition time.h:229
#define fr_time_neq(_a, _b)
Definition time.h:242
A time delta, a difference in time measured in nanoseconds.
Definition time.h:80
"server local" time.
Definition time.h:69
void fr_timer_list_empty(fr_timer_list_t *tl)
Assert that a timer list has no events.
Definition timer.c:1279
int fr_timer_list_run(fr_timer_list_t *tl, fr_time_t *when)
Execute any pending events in the event loop.
Definition timer.c:974
uint64_t fr_timer_list_num_events(fr_timer_list_t *tl)
Return number of pending events.
Definition timer.c:1198
fr_time_t fr_timer_list_when(fr_timer_list_t *tl)
Return the time of the next event.
Definition timer.c:1319
fr_timer_list_t * fr_timer_list_lst_alloc(TALLOC_CTX *ctx, fr_timer_list_t *parent)
Allocate a new lst based timer list.
Definition timer.c:1413
An event timer list.
Definition timer.c:65
A timer event.
Definition timer.c:100
#define fr_timer_at(...)
Definition timer.h:81
int trigger(unlang_interpret_t *intp, CONF_SECTION const *cs, CONF_PAIR **trigger_cp, char const *name, bool rate_limit, fr_pair_list_t *args, void const *uctx)
Execute a trigger - call an executable to process an event.
Definition trigger.c:160
static fr_event_list_t * el
#define add(_type, _out, _in)
Definition stats.c:187
void fr_strerror_clear(void)
Clears all pending messages from the talloc pools.
Definition strerror.c:581
#define fr_strerror_printf(_fmt,...)
Log to thread local error buffer.
Definition strerror.h:64
#define fr_strerror_printf_push(_fmt,...)
Add a message to an existing stack of messages at the tail.
Definition strerror.h:84
#define fr_strerror_const(_msg)
Definition strerror.h:223
static fr_sbuff_err_t char ** out
Definition value.h:1061
static fr_sbuff_err_t char size_t * len
Definition value.h:1061
int nonnull(2, 5))