e004e42a37bbbe14c7b6b0332b57d7e2f2ff29ac
[metze/samba/wip.git] / lib / tevent / tevent.h
1 /* 
2    Unix SMB/CIFS implementation.
3
4    generalised event loop handling
5
6    Copyright (C) Andrew Tridgell 2005
7    Copyright (C) Stefan Metzmacher 2005-2009
8    Copyright (C) Volker Lendecke 2008
9
10      ** NOTE! The following LGPL license applies to the tevent
11      ** library. This does NOT imply that all of Samba is released
12      ** under the LGPL
13
14    This library is free software; you can redistribute it and/or
15    modify it under the terms of the GNU Lesser General Public
16    License as published by the Free Software Foundation; either
17    version 3 of the License, or (at your option) any later version.
18
19    This library is distributed in the hope that it will be useful,
20    but WITHOUT ANY WARRANTY; without even the implied warranty of
21    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
22    Lesser General Public License for more details.
23
24    You should have received a copy of the GNU Lesser General Public
25    License along with this library; if not, see <http://www.gnu.org/licenses/>.
26 */
27
28 #ifndef __TEVENT_H__
29 #define __TEVENT_H__
30
31 #include <stdint.h>
32 #include <stdbool.h>
33 #include <talloc.h>
34 #include <sys/time.h>
35 #include <stdbool.h>
36
37 struct tevent_context;
38 struct tevent_ops;
39 struct tevent_fd;
40 struct tevent_timer;
41 struct tevent_immediate;
42 struct tevent_signal;
43 struct tevent_thread_proxy;
44 struct tevent_threaded_context;
45
46 /**
47  * @defgroup tevent The tevent API
48  *
49  * The tevent low-level API
50  *
51  * This API provides the public interface to manage events in the tevent
52  * mainloop. Functions are provided for managing low-level events such
53  * as timer events, fd events and signal handling.
54  *
55  * @{
56  */
57
58 /* event handler types */
59 /**
60  * Called when a file descriptor monitored by tevent has
61  * data to be read or written on it.
62  */
63 typedef void (*tevent_fd_handler_t)(struct tevent_context *ev,
64                                     struct tevent_fd *fde,
65                                     uint16_t flags,
66                                     void *private_data);
67
68 /**
69  * Called when tevent is ceasing the monitoring of a file descriptor.
70  */
71 typedef void (*tevent_fd_close_fn_t)(struct tevent_context *ev,
72                                      struct tevent_fd *fde,
73                                      int fd,
74                                      void *private_data);
75
76 /**
77  * Called when a tevent timer has fired.
78  */
79 typedef void (*tevent_timer_handler_t)(struct tevent_context *ev,
80                                        struct tevent_timer *te,
81                                        struct timeval current_time,
82                                        void *private_data);
83
84 /**
85  * Called when a tevent immediate event is invoked.
86  */
87 typedef void (*tevent_immediate_handler_t)(struct tevent_context *ctx,
88                                            struct tevent_immediate *im,
89                                            void *private_data);
90
91 /**
92  * Called after tevent detects the specified signal.
93  */
94 typedef void (*tevent_signal_handler_t)(struct tevent_context *ev,
95                                         struct tevent_signal *se,
96                                         int signum,
97                                         int count,
98                                         void *siginfo,
99                                         void *private_data);
100
101 /**
102  * @brief Create a event_context structure.
103  *
104  * This must be the first events call, and all subsequent calls pass this
105  * event_context as the first element. Event handlers also receive this as
106  * their first argument.
107  *
108  * @param[in]  mem_ctx  The memory context to use.
109  *
110  * @return              An allocated tevent context, NULL on error.
111  *
112  * @see tevent_context_init()
113  */
114 struct tevent_context *tevent_context_init(TALLOC_CTX *mem_ctx);
115
116 /**
117  * @brief Create a event_context structure and select a specific backend.
118  *
119  * This must be the first events call, and all subsequent calls pass this
120  * event_context as the first element. Event handlers also receive this as
121  * their first argument.
122  *
123  * @param[in]  mem_ctx  The memory context to use.
124  *
125  * @param[in]  name     The name of the backend to use.
126  *
127  * @return              An allocated tevent context, NULL on error.
128  */
129 struct tevent_context *tevent_context_init_byname(TALLOC_CTX *mem_ctx, const char *name);
130
131 /**
132  * @brief Create a custom event context
133  *
134  * @param[in]  mem_ctx  The memory context to use.
135  * @param[in]  ops      The function pointer table of the backend.
136  * @param[in]  additional_data  The additional/private data to this instance
137  *
138  * @return              An allocated tevent context, NULL on error.
139  *
140  */
141 struct tevent_context *tevent_context_init_ops(TALLOC_CTX *mem_ctx,
142                                                const struct tevent_ops *ops,
143                                                void *additional_data);
144
145 /**
146  * @brief List available backends.
147  *
148  * @param[in]  mem_ctx  The memory context to use.
149  *
150  * @return              A string vector with a terminating NULL element, NULL
151  *                      on error.
152  */
153 const char **tevent_backend_list(TALLOC_CTX *mem_ctx);
154
155 /**
156  * @brief Set the default tevent backend.
157  *
158  * @param[in]  backend  The name of the backend to set.
159  */
160 void tevent_set_default_backend(const char *backend);
161
162 #define TEVENT_FEATURE_FD_SUPPORT       0x00000001
163 #define TEVENT_FEATURE_TIMER_SUPPORT    0x00000002
164 #define TEVENT_FEATURE_SIGNAL_SUPPORT   0x00000004
165 #define TEVENT_FEATURE_AIO_SUPPORT      0x00000008
166
167 bool tevent_have_features(struct tevent_context *ev, uint32_t features);
168
169 #ifdef DOXYGEN
170 /**
171  * @brief Add a file descriptor based event.
172  *
173  * @param[in]  ev       The event context to work on.
174  *
175  * @param[in]  mem_ctx  The talloc memory context to use.
176  *
177  * @param[in]  fd       The file descriptor to base the event on.
178  *
179  * @param[in]  flags    #TEVENT_FD_READ or #TEVENT_FD_WRITE
180  *
181  * @param[in]  handler  The callback handler for the event.
182  *
183  * @param[in]  private_data  The private data passed to the callback handler.
184  *
185  * @return              The file descriptor based event, NULL on error.
186  *
187  * @note To cancel the monitoring of a file descriptor, call talloc_free()
188  * on the object returned by this function.
189  *
190  * @note The caller should avoid closing the file descriptor before
191  * calling talloc_free()! Otherwise the behaviour is undefined which
192  * might result in crashes. See https://bugzilla.samba.org/show_bug.cgi?id=11141
193  * for an example.
194  */
195 struct tevent_fd *tevent_add_fd(struct tevent_context *ev,
196                                 TALLOC_CTX *mem_ctx,
197                                 int fd,
198                                 uint16_t flags,
199                                 tevent_fd_handler_t handler,
200                                 void *private_data);
201 #else
202 struct tevent_fd *_tevent_add_fd(struct tevent_context *ev,
203                                  TALLOC_CTX *mem_ctx,
204                                  int fd,
205                                  uint16_t flags,
206                                  tevent_fd_handler_t handler,
207                                  void *private_data,
208                                  const char *handler_name,
209                                  const char *location);
210 #define tevent_add_fd(ev, mem_ctx, fd, flags, handler, private_data) \
211         _tevent_add_fd(ev, mem_ctx, fd, flags, handler, private_data, \
212                        #handler, __location__)
213 #endif
214
215 #ifdef DOXYGEN
216 /**
217  * @brief Add a timed event
218  *
219  * @param[in]  ev       The event context to work on.
220  *
221  * @param[in]  mem_ctx  The talloc memory context to use.
222  *
223  * @param[in]  next_event  Timeval specifying the absolute time to fire this
224  * event. This is not an offset.
225  *
226  * @param[in]  handler  The callback handler for the event.
227  *
228  * @param[in]  private_data  The private data passed to the callback handler.
229  *
230  * @return The newly-created timer event, or NULL on error.
231  *
232  * @note To cancel a timer event before it fires, call talloc_free() on the
233  * event returned from this function. This event is automatically
234  * talloc_free()-ed after its event handler files, if it hasn't been freed yet.
235  *
236  * @note Unlike some mainloops, tevent timers are one-time events. To set up
237  * a recurring event, it is necessary to call tevent_add_timer() again during
238  * the handler processing.
239  *
240  * @note Due to the internal mainloop processing, a timer set to run
241  * immediately will do so after any other pending timers fire, but before
242  * any further file descriptor or signal handling events fire. Callers should
243  * not rely on this behavior!
244  */
245 struct tevent_timer *tevent_add_timer(struct tevent_context *ev,
246                                       TALLOC_CTX *mem_ctx,
247                                       struct timeval next_event,
248                                       tevent_timer_handler_t handler,
249                                       void *private_data);
250 #else
251 struct tevent_timer *_tevent_add_timer(struct tevent_context *ev,
252                                        TALLOC_CTX *mem_ctx,
253                                        struct timeval next_event,
254                                        tevent_timer_handler_t handler,
255                                        void *private_data,
256                                        const char *handler_name,
257                                        const char *location);
258 #define tevent_add_timer(ev, mem_ctx, next_event, handler, private_data) \
259         _tevent_add_timer(ev, mem_ctx, next_event, handler, private_data, \
260                           #handler, __location__)
261 #endif
262
263 #ifdef DOXYGEN
264 /**
265  * Initialize an immediate event object
266  *
267  * This object can be used to trigger an event to occur immediately after
268  * returning from the current event (before any other event occurs)
269  *
270  * @param[in] mem_ctx  The talloc memory context to use as the parent
271  *
272  * @return An empty tevent_immediate object. Use tevent_schedule_immediate
273  * to populate and use it.
274  *
275  * @note Available as of tevent 0.9.8
276  */
277 struct tevent_immediate *tevent_create_immediate(TALLOC_CTX *mem_ctx);
278 #else
279 struct tevent_immediate *_tevent_create_immediate(TALLOC_CTX *mem_ctx,
280                                                   const char *location);
281 #define tevent_create_immediate(mem_ctx) \
282         _tevent_create_immediate(mem_ctx, __location__)
283 #endif
284
285 #ifdef DOXYGEN
286
287 /**
288  * Schedule an event for immediate execution. This event will occur
289  * immediately after returning from the current event (before any other
290  * event occurs)
291  *
292  * @param[in] im       The tevent_immediate object to populate and use
293  * @param[in] ctx      The tevent_context to run this event
294  * @param[in] handler  The event handler to run when this event fires
295  * @param[in] private_data  Data to pass to the event handler
296  */
297 void tevent_schedule_immediate(struct tevent_immediate *im,
298                 struct tevent_context *ctx,
299                 tevent_immediate_handler_t handler,
300                 void *private_data);
301 #else
302 void _tevent_schedule_immediate(struct tevent_immediate *im,
303                                 struct tevent_context *ctx,
304                                 tevent_immediate_handler_t handler,
305                                 void *private_data,
306                                 const char *handler_name,
307                                 const char *location);
308 #define tevent_schedule_immediate(im, ctx, handler, private_data) \
309         _tevent_schedule_immediate(im, ctx, handler, private_data, \
310                                    #handler, __location__);
311 #endif
312
313 #ifdef DOXYGEN
314 /**
315  * @brief Add a tevent signal handler
316  *
317  * tevent_add_signal() creates a new event for handling a signal the next
318  * time through the mainloop. It implements a very simple traditional signal
319  * handler whose only purpose is to add the handler event into the mainloop.
320  *
321  * @param[in]  ev       The event context to work on.
322  *
323  * @param[in]  mem_ctx  The talloc memory context to use.
324  *
325  * @param[in]  signum   The signal to trap
326  *
327  * @param[in]  handler  The callback handler for the signal.
328  *
329  * @param[in]  sa_flags sigaction flags for this signal handler.
330  *
331  * @param[in]  private_data  The private data passed to the callback handler.
332  *
333  * @return The newly-created signal handler event, or NULL on error.
334  *
335  * @note To cancel a signal handler, call talloc_free() on the event returned
336  * from this function.
337  *
338  * @see tevent_num_signals, tevent_sa_info_queue_count
339  */
340 struct tevent_signal *tevent_add_signal(struct tevent_context *ev,
341                      TALLOC_CTX *mem_ctx,
342                      int signum,
343                      int sa_flags,
344                      tevent_signal_handler_t handler,
345                      void *private_data);
346 #else
347 struct tevent_signal *_tevent_add_signal(struct tevent_context *ev,
348                                          TALLOC_CTX *mem_ctx,
349                                          int signum,
350                                          int sa_flags,
351                                          tevent_signal_handler_t handler,
352                                          void *private_data,
353                                          const char *handler_name,
354                                          const char *location);
355 #define tevent_add_signal(ev, mem_ctx, signum, sa_flags, handler, private_data) \
356         _tevent_add_signal(ev, mem_ctx, signum, sa_flags, handler, private_data, \
357                            #handler, __location__)
358 #endif
359
360 /**
361  * @brief the number of supported signals
362  *
363  * This returns value of the configure time TEVENT_NUM_SIGNALS constant.
364  *
365  * The 'signum' argument of tevent_add_signal() must be less than
366  * TEVENT_NUM_SIGNALS.
367  *
368  * @see tevent_add_signal
369  */
370 size_t tevent_num_signals(void);
371
372 /**
373  * @brief the number of pending realtime signals
374  *
375  * This returns value of TEVENT_SA_INFO_QUEUE_COUNT.
376  *
377  * The tevent internals remember the last TEVENT_SA_INFO_QUEUE_COUNT
378  * siginfo_t structures for SA_SIGINFO signals. If the system generates
379  * more some signals get lost.
380  *
381  * @see tevent_add_signal
382  */
383 size_t tevent_sa_info_queue_count(void);
384
385 #ifdef DOXYGEN
386 /**
387  * @brief Pass a single time through the mainloop
388  *
389  * This will process any appropriate signal, immediate, fd and timer events
390  *
391  * @param[in]  ev The event context to process
392  *
393  * @return Zero on success, nonzero if an internal error occurred
394  */
395 int tevent_loop_once(struct tevent_context *ev);
396 #else
397 int _tevent_loop_once(struct tevent_context *ev, const char *location);
398 #define tevent_loop_once(ev) \
399         _tevent_loop_once(ev, __location__)
400 #endif
401
402 #ifdef DOXYGEN
403 /**
404  * @brief Run the mainloop
405  *
406  * The mainloop will run until there are no events remaining to be processed
407  *
408  * @param[in]  ev The event context to process
409  *
410  * @return Zero if all events have been processed. Nonzero if an internal
411  * error occurred.
412  */
413 int tevent_loop_wait(struct tevent_context *ev);
414 #else
415 int _tevent_loop_wait(struct tevent_context *ev, const char *location);
416 #define tevent_loop_wait(ev) \
417         _tevent_loop_wait(ev, __location__)
418 #endif
419
420
421 /**
422  * Assign a function to run when a tevent_fd is freed
423  *
424  * This function is a destructor for the tevent_fd. It does not automatically
425  * close the file descriptor. If this is the desired behavior, then it must be
426  * performed by the close_fn.
427  *
428  * @param[in] fde       File descriptor event on which to set the destructor
429  * @param[in] close_fn  Destructor to execute when fde is freed
430  */
431 void tevent_fd_set_close_fn(struct tevent_fd *fde,
432                             tevent_fd_close_fn_t close_fn);
433
434 /**
435  * Automatically close the file descriptor when the tevent_fd is freed
436  *
437  * This function calls close(fd) internally.
438  *
439  * @param[in] fde  File descriptor event to auto-close
440  */
441 void tevent_fd_set_auto_close(struct tevent_fd *fde);
442
443 /**
444  * Return the flags set on this file descriptor event
445  *
446  * @param[in] fde  File descriptor event to query
447  *
448  * @return The flags set on the event. See #TEVENT_FD_READ and
449  * #TEVENT_FD_WRITE
450  */
451 uint16_t tevent_fd_get_flags(struct tevent_fd *fde);
452
453 /**
454  * Set flags on a file descriptor event
455  *
456  * @param[in] fde    File descriptor event to set
457  * @param[in] flags  Flags to set on the event. See #TEVENT_FD_READ and
458  * #TEVENT_FD_WRITE
459  */
460 void tevent_fd_set_flags(struct tevent_fd *fde, uint16_t flags);
461
462 /**
463  * Query whether tevent supports signal handling
464  *
465  * @param[in] ev  An initialized tevent context
466  *
467  * @return True if this platform and tevent context support signal handling
468  */
469 bool tevent_signal_support(struct tevent_context *ev);
470
471 void tevent_set_abort_fn(void (*abort_fn)(const char *reason));
472
473 /* bits for file descriptor event flags */
474
475 /**
476  * Monitor a file descriptor for data to be read
477  */
478 #define TEVENT_FD_READ 1
479 /**
480  * Monitor a file descriptor for writeability
481  */
482 #define TEVENT_FD_WRITE 2
483
484 /**
485  * Convenience function for declaring a tevent_fd writable
486  */
487 #define TEVENT_FD_WRITEABLE(fde) \
488         tevent_fd_set_flags(fde, tevent_fd_get_flags(fde) | TEVENT_FD_WRITE)
489
490 /**
491  * Convenience function for declaring a tevent_fd readable
492  */
493 #define TEVENT_FD_READABLE(fde) \
494         tevent_fd_set_flags(fde, tevent_fd_get_flags(fde) | TEVENT_FD_READ)
495
496 /**
497  * Convenience function for declaring a tevent_fd non-writable
498  */
499 #define TEVENT_FD_NOT_WRITEABLE(fde) \
500         tevent_fd_set_flags(fde, tevent_fd_get_flags(fde) & ~TEVENT_FD_WRITE)
501
502 /**
503  * Convenience function for declaring a tevent_fd non-readable
504  */
505 #define TEVENT_FD_NOT_READABLE(fde) \
506         tevent_fd_set_flags(fde, tevent_fd_get_flags(fde) & ~TEVENT_FD_READ)
507
508 /**
509  * Debug level of tevent
510  */
511 enum tevent_debug_level {
512         TEVENT_DEBUG_FATAL,
513         TEVENT_DEBUG_ERROR,
514         TEVENT_DEBUG_WARNING,
515         TEVENT_DEBUG_TRACE
516 };
517
518 /**
519  * @brief The tevent debug callbac.
520  *
521  * @param[in]  context  The memory context to use.
522  *
523  * @param[in]  level    The debug level.
524  *
525  * @param[in]  fmt      The format string.
526  *
527  * @param[in]  ap       The arguments for the format string.
528  */
529 typedef void (*tevent_debug_fn)(void *context,
530                                 enum tevent_debug_level level,
531                                 const char *fmt,
532                                 va_list ap) PRINTF_ATTRIBUTE(3,0);
533
534 /**
535  * Set destination for tevent debug messages
536  *
537  * @param[in] ev        Event context to debug
538  * @param[in] debug     Function to handle output printing
539  * @param[in] context   The context to pass to the debug function.
540  *
541  * @return Always returns 0 as of version 0.9.8
542  *
543  * @note Default is to emit no debug messages
544  */
545 int tevent_set_debug(struct tevent_context *ev,
546                      tevent_debug_fn debug,
547                      void *context);
548
549 /**
550  * Designate stderr for debug message output
551  *
552  * @param[in] ev     Event context to debug
553  *
554  * @note This function will only output TEVENT_DEBUG_FATAL, TEVENT_DEBUG_ERROR
555  * and TEVENT_DEBUG_WARNING messages. For TEVENT_DEBUG_TRACE, please define a
556  * function for tevent_set_debug()
557  */
558 int tevent_set_debug_stderr(struct tevent_context *ev);
559
560 enum tevent_trace_point {
561         /**
562          * Corresponds to a trace point just before waiting
563          */
564         TEVENT_TRACE_BEFORE_WAIT,
565         /**
566          * Corresponds to a trace point just after waiting
567          */
568         TEVENT_TRACE_AFTER_WAIT,
569 #define TEVENT_HAS_LOOP_ONCE_TRACE_POINTS 1
570         /**
571          * Corresponds to a trace point just before calling
572          * the loop_once() backend function.
573          */
574         TEVENT_TRACE_BEFORE_LOOP_ONCE,
575         /**
576          * Corresponds to a trace point right after the
577          * loop_once() backend function has returned.
578          */
579         TEVENT_TRACE_AFTER_LOOP_ONCE,
580 };
581
582 typedef void (*tevent_trace_callback_t)(enum tevent_trace_point,
583                                         void *private_data);
584
585 /**
586  * Register a callback to be called at certain trace points
587  *
588  * @param[in] ev             Event context
589  * @param[in] cb             Trace callback
590  * @param[in] private_data   Data to be passed to callback
591  *
592  * @note The callback will be called at trace points defined by
593  * tevent_trace_point.  Call with NULL to reset.
594  */
595 void tevent_set_trace_callback(struct tevent_context *ev,
596                                tevent_trace_callback_t cb,
597                                void *private_data);
598
599 /**
600  * Retrieve the current trace callback
601  *
602  * @param[in] ev             Event context
603  * @param[out] cb            Registered trace callback
604  * @param[out] private_data  Registered data to be passed to callback
605  *
606  * @note This can be used to allow one component that wants to
607  * register a callback to respect the callback that another component
608  * has already registered.
609  */
610 void tevent_get_trace_callback(struct tevent_context *ev,
611                                tevent_trace_callback_t *cb,
612                                void *private_data);
613
614 /**
615  * @}
616  */
617
618 /**
619  * @defgroup tevent_request The tevent request functions.
620  * @ingroup tevent
621  *
622  * A tevent_req represents an asynchronous computation.
623  *
624  * The tevent_req group of API calls is the recommended way of
625  * programming async computations within tevent. In particular the
626  * file descriptor (tevent_add_fd) and timer (tevent_add_timed) events
627  * are considered too low-level to be used in larger computations. To
628  * read and write from and to sockets, Samba provides two calls on top
629  * of tevent_add_fd: tstream_read_packet_send/recv and tstream_writev_send/recv.
630  * These requests are much easier to compose than the low-level event
631  * handlers called from tevent_add_fd.
632  *
633  * A lot of the simplicity tevent_req has brought to the notoriously
634  * hairy async programming came via a set of conventions that every
635  * async computation programmed should follow. One central piece of
636  * these conventions is the naming of routines and variables.
637  *
638  * Every async computation needs a name (sensibly called "computation"
639  * down from here). From this name quite a few naming conventions are
640  * derived.
641  *
642  * Every computation that requires local state needs a
643  * @code
644  * struct computation_state {
645  *     int local_var;
646  * };
647  * @endcode
648  * Even if no local variables are required, such a state struct should
649  * be created containing a dummy variable. Quite a few helper
650  * functions and macros (for example tevent_req_create()) assume such
651  * a state struct.
652  *
653  * An async computation is started by a computation_send
654  * function. When it is finished, its result can be received by a
655  * computation_recv function. For an example how to set up an async
656  * computation, see the code example in the documentation for
657  * tevent_req_create() and tevent_req_post(). The prototypes for _send
658  * and _recv functions should follow some conventions:
659  *
660  * @code
661  * struct tevent_req *computation_send(TALLOC_CTX *mem_ctx,
662  *                                     struct tevent_req *ev,
663  *                                     ... further args);
664  * int computation_recv(struct tevent_req *req, ... further output args);
665  * @endcode
666  *
667  * The "int" result of computation_recv() depends on the result the
668  * sync version of the function would have, "int" is just an example
669  * here.
670  *
671  * Another important piece of the conventions is that the program flow
672  * is interrupted as little as possible. Because a blocking
673  * sub-computation requires that the flow needs to continue in a
674  * separate function that is the logical sequel of some computation,
675  * it should lexically follow sending off the blocking
676  * sub-computation. Setting the callback function via
677  * tevent_req_set_callback() requires referencing a function lexically
678  * below the call to tevent_req_set_callback(), forward declarations
679  * are required. A lot of the async computations thus begin with a
680  * sequence of declarations such as
681  *
682  * @code
683  * static void computation_step1_done(struct tevent_req *subreq);
684  * static void computation_step2_done(struct tevent_req *subreq);
685  * static void computation_step3_done(struct tevent_req *subreq);
686  * @endcode
687  *
688  * It really helps readability a lot to do these forward declarations,
689  * because the lexically sequential program flow makes the async
690  * computations almost as clear to read as a normal, sync program
691  * flow.
692  *
693  * It is up to the user of the async computation to talloc_free it
694  * after it has finished. If an async computation should be aborted,
695  * the tevent_req structure can be talloc_free'ed. After it has
696  * finished, it should talloc_free'ed by the API user.
697  *
698  * @{
699  */
700
701 /**
702  * An async request moves from TEVENT_REQ_INIT to
703  * TEVENT_REQ_IN_PROGRESS. All other states are valid after a request
704  * has finished.
705  */
706 enum tevent_req_state {
707         /**
708          * We are creating the request
709          */
710         TEVENT_REQ_INIT,
711         /**
712          * We are waiting the request to complete
713          */
714         TEVENT_REQ_IN_PROGRESS,
715         /**
716          * The request is finished successfully
717          */
718         TEVENT_REQ_DONE,
719         /**
720          * A user error has occurred. The user error has been
721          * indicated by tevent_req_error(), it can be retrieved via
722          * tevent_req_is_error().
723          */
724         TEVENT_REQ_USER_ERROR,
725         /**
726          * Request timed out after the timeout set by tevent_req_set_endtime.
727          */
728         TEVENT_REQ_TIMED_OUT,
729         /**
730          * An internal allocation has failed, or tevent_req_nomem has
731          * been given a NULL pointer as the first argument.
732          */
733         TEVENT_REQ_NO_MEMORY,
734         /**
735          * The request has been received by the caller. No further
736          * action is valid.
737          */
738         TEVENT_REQ_RECEIVED
739 };
740
741 /**
742  * @brief An async request
743  */
744 struct tevent_req;
745
746 /**
747  * @brief A tevent request callback function.
748  *
749  * @param[in]  req      The tevent async request which executed this callback.
750  */
751 typedef void (*tevent_req_fn)(struct tevent_req *req);
752
753 /**
754  * @brief Set an async request callback.
755  *
756  * See the documentation of tevent_req_post() for an example how this
757  * is supposed to be used.
758  *
759  * @param[in]  req      The async request to set the callback.
760  *
761  * @param[in]  fn       The callback function to set.
762  *
763  * @param[in]  pvt      A pointer to private data to pass to the async request
764  *                      callback.
765  */
766 void tevent_req_set_callback(struct tevent_req *req, tevent_req_fn fn, void *pvt);
767
768 #ifdef DOXYGEN
769 /**
770  * @brief Get the private data cast to the given type for a callback from
771  *        a tevent request structure.
772  *
773  * @code
774  * static void computation_done(struct tevent_req *subreq) {
775  *     struct tevent_req *req = tevent_req_callback_data(subreq, struct tevent_req);
776  *     struct computation_state *state = tevent_req_data(req, struct computation_state);
777  *     .... more things, eventually maybe call tevent_req_done(req);
778  * }
779  * @endcode
780  *
781  * @param[in]  req      The structure to get the callback data from.
782  *
783  * @param[in]  type     The type of the private callback data to get.
784  *
785  * @return              The type casted private data set NULL if not set.
786  */
787 void *tevent_req_callback_data(struct tevent_req *req, #type);
788 #else
789 void *_tevent_req_callback_data(struct tevent_req *req);
790 #define tevent_req_callback_data(_req, _type) \
791         talloc_get_type_abort(_tevent_req_callback_data(_req), _type)
792 #endif
793
794 #ifdef DOXYGEN
795 /**
796  * @brief Get the private data for a callback from a tevent request structure.
797  *
798  * @param[in]  req      The structure to get the callback data from.
799  *
800  * @param[in]  req      The structure to get the data from.
801  *
802  * @return              The private data or NULL if not set.
803  */
804 void *tevent_req_callback_data_void(struct tevent_req *req);
805 #else
806 #define tevent_req_callback_data_void(_req) \
807         _tevent_req_callback_data(_req)
808 #endif
809
810 #ifdef DOXYGEN
811 /**
812  * @brief Get the private data from a tevent request structure.
813  *
814  * When the tevent_req has been created by tevent_req_create, the
815  * result of tevent_req_data() is the state variable created by
816  * tevent_req_create() as a child of the req.
817  *
818  * @param[in]  req      The structure to get the private data from.
819  *
820  * @param[in]  type     The type of the private data
821  *
822  * @return              The private data or NULL if not set.
823  */
824 void *tevent_req_data(struct tevent_req *req, #type);
825 #else
826 void *_tevent_req_data(struct tevent_req *req);
827 #define tevent_req_data(_req, _type) \
828         talloc_get_type_abort(_tevent_req_data(_req), _type)
829 #endif
830
831 /**
832  * @brief The print function which can be set for a tevent async request.
833  *
834  * @param[in]  req      The tevent async request.
835  *
836  * @param[in]  ctx      A talloc memory context which can be uses to allocate
837  *                      memory.
838  *
839  * @return              An allocated string buffer to print.
840  *
841  * Example:
842  * @code
843  *   static char *my_print(struct tevent_req *req, TALLOC_CTX *mem_ctx)
844  *   {
845  *     struct my_data *data = tevent_req_data(req, struct my_data);
846  *     char *result;
847  *
848  *     result = tevent_req_default_print(mem_ctx, req);
849  *     if (result == NULL) {
850  *       return NULL;
851  *     }
852  *
853  *     return talloc_asprintf_append_buffer(result, "foo=%d, bar=%d",
854  *       data->foo, data->bar);
855  *   }
856  * @endcode
857  */
858 typedef char *(*tevent_req_print_fn)(struct tevent_req *req, TALLOC_CTX *ctx);
859
860 /**
861  * @brief This function sets a print function for the given request.
862  *
863  * This function can be used to setup a print function for the given request.
864  * This will be triggered if the tevent_req_print() function was
865  * called on the given request.
866  *
867  * @param[in]  req      The request to use.
868  *
869  * @param[in]  fn       A pointer to the print function
870  *
871  * @note This function should only be used for debugging.
872  */
873 void tevent_req_set_print_fn(struct tevent_req *req, tevent_req_print_fn fn);
874
875 /**
876  * @brief The default print function for creating debug messages.
877  *
878  * The function should not be used by users of the async API,
879  * but custom print function can use it and append custom text
880  * to the string.
881  *
882  * @param[in]  req      The request to be printed.
883  *
884  * @param[in]  mem_ctx  The memory context for the result.
885  *
886  * @return              Text representation of request.
887  *
888  */
889 char *tevent_req_default_print(struct tevent_req *req, TALLOC_CTX *mem_ctx);
890
891 /**
892  * @brief Print an tevent_req structure in debug messages.
893  *
894  * This function should be used by callers of the async API.
895  *
896  * @param[in]  mem_ctx  The memory context for the result.
897  *
898  * @param[in] req       The request to be printed.
899  *
900  * @return              Text representation of request.
901  */
902 char *tevent_req_print(TALLOC_CTX *mem_ctx, struct tevent_req *req);
903
904 /**
905  * @brief A typedef for a cancel function for a tevent request.
906  *
907  * @param[in]  req      The tevent request calling this function.
908  *
909  * @return              True if the request could be canceled, false if not.
910  */
911 typedef bool (*tevent_req_cancel_fn)(struct tevent_req *req);
912
913 /**
914  * @brief This function sets a cancel function for the given tevent request.
915  *
916  * This function can be used to setup a cancel function for the given request.
917  * This will be triggered if the tevent_req_cancel() function was
918  * called on the given request.
919  *
920  * @param[in]  req      The request to use.
921  *
922  * @param[in]  fn       A pointer to the cancel function.
923  */
924 void tevent_req_set_cancel_fn(struct tevent_req *req, tevent_req_cancel_fn fn);
925
926 #ifdef DOXYGEN
927 /**
928  * @brief Try to cancel the given tevent request.
929  *
930  * This function can be used to cancel the given request.
931  *
932  * It is only possible to cancel a request when the implementation
933  * has registered a cancel function via the tevent_req_set_cancel_fn().
934  *
935  * @param[in]  req      The request to use.
936  *
937  * @return              This function returns true is the request is cancelable,
938  *                      othererwise false is returned.
939  *
940  * @note Even if the function returns true, the caller need to wait
941  *       for the function to complete normally.
942  *       Only the _recv() function of the given request indicates
943  *       if the request was really canceled.
944  */
945 bool tevent_req_cancel(struct tevent_req *req);
946 #else
947 bool _tevent_req_cancel(struct tevent_req *req, const char *location);
948 #define tevent_req_cancel(req) \
949         _tevent_req_cancel(req, __location__)
950 #endif
951
952 /**
953  * @brief A typedef for a cleanup function for a tevent request.
954  *
955  * @param[in]  req       The tevent request calling this function.
956  *
957  * @param[in]  req_state The current tevent_req_state.
958  *
959  */
960 typedef void (*tevent_req_cleanup_fn)(struct tevent_req *req,
961                                       enum tevent_req_state req_state);
962
963 /**
964  * @brief This function sets a cleanup function for the given tevent request.
965  *
966  * This function can be used to setup a cleanup function for the given request.
967  * This will be triggered when the tevent_req_done() or tevent_req_error()
968  * function was called, before notifying the callers callback function,
969  * and also before scheduling the deferred trigger.
970  *
971  * This might be useful if more than one tevent_req belong together
972  * and need to finish both requests at the same time.
973  *
974  * The cleanup function is able to call tevent_req_done() or tevent_req_error()
975  * recursively, the cleanup function is only triggered the first time.
976  *
977  * The cleanup function is also called by tevent_req_received()
978  * (possibly triggered from tevent_req_destructor()) before destroying
979  * the private data of the tevent_req.
980  *
981  * @param[in]  req      The request to use.
982  *
983  * @param[in]  fn       A pointer to the cancel function.
984  */
985 void tevent_req_set_cleanup_fn(struct tevent_req *req, tevent_req_cleanup_fn fn);
986
987 #ifdef DOXYGEN
988 /**
989  * @brief Create an async tevent request.
990  *
991  * The new async request will be initialized in state TEVENT_REQ_IN_PROGRESS.
992  *
993  * @code
994  * struct tevent_req *req;
995  * struct computation_state *state;
996  * req = tevent_req_create(mem_ctx, &state, struct computation_state);
997  * @endcode
998  *
999  * Tevent_req_create() allocates and zeros the state variable as a talloc
1000  * child of its result. The state variable should be used as the talloc
1001  * parent for all temporary variables that are allocated during the async
1002  * computation. This way, when the user of the async computation frees
1003  * the request, the state as a talloc child will be free'd along with
1004  * all the temporary variables hanging off the state.
1005  *
1006  * @param[in] mem_ctx   The memory context for the result.
1007  * @param[in] pstate    Pointer to the private request state.
1008  * @param[in] type      The name of the request.
1009  *
1010  * @return              A new async request. NULL on error.
1011  */
1012 struct tevent_req *tevent_req_create(TALLOC_CTX *mem_ctx,
1013                                      void **pstate, #type);
1014 #else
1015 struct tevent_req *_tevent_req_create(TALLOC_CTX *mem_ctx,
1016                                       void *pstate,
1017                                       size_t state_size,
1018                                       const char *type,
1019                                       const char *location);
1020
1021 #define tevent_req_create(_mem_ctx, _pstate, _type) \
1022         _tevent_req_create((_mem_ctx), (_pstate), sizeof(_type), \
1023                            #_type, __location__)
1024 #endif
1025
1026 /**
1027  * @brief Set a timeout for an async request.
1028  *
1029  * @param[in]  req      The request to set the timeout for.
1030  *
1031  * @param[in]  ev       The event context to use for the timer.
1032  *
1033  * @param[in]  endtime  The endtime of the request.
1034  *
1035  * @return              True if succeeded, false if not.
1036  */
1037 bool tevent_req_set_endtime(struct tevent_req *req,
1038                             struct tevent_context *ev,
1039                             struct timeval endtime);
1040
1041 #ifdef DOXYGEN
1042 /**
1043  * @brief Call the notify callback of the given tevent request manually.
1044  *
1045  * @param[in]  req      The tevent request to call the notify function from.
1046  *
1047  * @see tevent_req_set_callback()
1048  */
1049 void tevent_req_notify_callback(struct tevent_req *req);
1050 #else
1051 void _tevent_req_notify_callback(struct tevent_req *req, const char *location);
1052 #define tevent_req_notify_callback(req)         \
1053         _tevent_req_notify_callback(req, __location__)
1054 #endif
1055
1056 #ifdef DOXYGEN
1057 /**
1058  * @brief An async request has successfully finished.
1059  *
1060  * This function is to be used by implementors of async requests. When a
1061  * request is successfully finished, this function calls the user's completion
1062  * function.
1063  *
1064  * @param[in]  req       The finished request.
1065  */
1066 void tevent_req_done(struct tevent_req *req);
1067 #else
1068 void _tevent_req_done(struct tevent_req *req,
1069                       const char *location);
1070 #define tevent_req_done(req) \
1071         _tevent_req_done(req, __location__)
1072 #endif
1073
1074 #ifdef DOXYGEN
1075 /**
1076  * @brief An async request has seen an error.
1077  *
1078  * This function is to be used by implementors of async requests. When a
1079  * request can not successfully completed, the implementation should call this
1080  * function with the appropriate status code.
1081  *
1082  * If error is 0 the function returns false and does nothing more.
1083  *
1084  * @param[in]  req      The request with an error.
1085  *
1086  * @param[in]  error    The error code.
1087  *
1088  * @return              On success true is returned, false if error is 0.
1089  *
1090  * @code
1091  * int error = first_function();
1092  * if (tevent_req_error(req, error)) {
1093  *      return;
1094  * }
1095  *
1096  * error = second_function();
1097  * if (tevent_req_error(req, error)) {
1098  *      return;
1099  * }
1100  *
1101  * tevent_req_done(req);
1102  * return;
1103  * @endcode
1104  */
1105 bool tevent_req_error(struct tevent_req *req,
1106                       uint64_t error);
1107 #else
1108 bool _tevent_req_error(struct tevent_req *req,
1109                        uint64_t error,
1110                        const char *location);
1111 #define tevent_req_error(req, error) \
1112         _tevent_req_error(req, error, __location__)
1113 #endif
1114
1115 #ifdef DOXYGEN
1116 /**
1117  * @brief Helper function for nomem check.
1118  *
1119  * Convenience helper to easily check alloc failure within a callback
1120  * implementing the next step of an async request.
1121  *
1122  * @param[in]  p        The pointer to be checked.
1123  *
1124  * @param[in]  req      The request being processed.
1125  *
1126  * @code
1127  * p = talloc(mem_ctx, bla);
1128  * if (tevent_req_nomem(p, req)) {
1129  *      return;
1130  * }
1131  * @endcode
1132  */
1133 bool tevent_req_nomem(const void *p,
1134                       struct tevent_req *req);
1135 #else
1136 bool _tevent_req_nomem(const void *p,
1137                        struct tevent_req *req,
1138                        const char *location);
1139 #define tevent_req_nomem(p, req) \
1140         _tevent_req_nomem(p, req, __location__)
1141 #endif
1142
1143 #ifdef DOXYGEN
1144 /**
1145  * @brief Indicate out of memory to a request
1146  *
1147  * @param[in]  req      The request being processed.
1148  */
1149 void tevent_req_oom(struct tevent_req *req);
1150 #else
1151 void _tevent_req_oom(struct tevent_req *req,
1152                      const char *location);
1153 #define tevent_req_oom(req) \
1154         _tevent_req_oom(req, __location__)
1155 #endif
1156
1157 /**
1158  * @brief Finish a request before the caller had the change to set the callback.
1159  *
1160  * An implementation of an async request might find that it can either finish
1161  * the request without waiting for an external event, or it can not even start
1162  * the engine. To present the illusion of a callback to the user of the API,
1163  * the implementation can call this helper function which triggers an
1164  * immediate event. This way the caller can use the same calling
1165  * conventions, independent of whether the request was actually deferred.
1166  *
1167  * @code
1168  * struct tevent_req *computation_send(TALLOC_CTX *mem_ctx,
1169  *                                     struct tevent_context *ev)
1170  * {
1171  *     struct tevent_req *req, *subreq;
1172  *     struct computation_state *state;
1173  *     req = tevent_req_create(mem_ctx, &state, struct computation_state);
1174  *     if (req == NULL) {
1175  *         return NULL;
1176  *     }
1177  *     subreq = subcomputation_send(state, ev);
1178  *     if (tevent_req_nomem(subreq, req)) {
1179  *         return tevent_req_post(req, ev);
1180  *     }
1181  *     tevent_req_set_callback(subreq, computation_done, req);
1182  *     return req;
1183  * }
1184  * @endcode
1185  *
1186  * @param[in]  req      The finished request.
1187  *
1188  * @param[in]  ev       The tevent_context for the immediate event.
1189  *
1190  * @return              The given request will be returned.
1191  */
1192 struct tevent_req *tevent_req_post(struct tevent_req *req,
1193                                    struct tevent_context *ev);
1194
1195 /**
1196  * @brief Finish multiple requests within one function
1197  *
1198  * Normally tevent_req_notify_callback() and all wrappers
1199  * (e.g. tevent_req_done() and tevent_req_error())
1200  * need to be the last thing an event handler should call.
1201  * This is because the callback is likely to destroy the
1202  * context of the current function.
1203  *
1204  * If a function wants to notify more than one caller,
1205  * it is dangerous if it just triggers multiple callbacks
1206  * in a row. With tevent_req_defer_callback() it is possible
1207  * to set an event context that will be used to defer the callback
1208  * via an immediate event (similar to tevent_req_post()).
1209  *
1210  * @code
1211  * struct complete_state {
1212  *       struct tevent_context *ev;
1213  *
1214  *       struct tevent_req **reqs;
1215  * };
1216  *
1217  * void complete(struct complete_state *state)
1218  * {
1219  *       size_t i, c = talloc_array_length(state->reqs);
1220  *
1221  *       for (i=0; i < c; i++) {
1222  *            tevent_req_defer_callback(state->reqs[i], state->ev);
1223  *            tevent_req_done(state->reqs[i]);
1224  *       }
1225  * }
1226  * @endcode
1227  *
1228  * @param[in]  req      The finished request.
1229  *
1230  * @param[in]  ev       The tevent_context for the immediate event.
1231  *
1232  * @return              The given request will be returned.
1233  */
1234 void tevent_req_defer_callback(struct tevent_req *req,
1235                                struct tevent_context *ev);
1236
1237 /**
1238  * @brief Check if the given request is still in progress.
1239  *
1240  * It is typically used by sync wrapper functions.
1241  *
1242  * @param[in]  req      The request to poll.
1243  *
1244  * @return              The boolean form of "is in progress".
1245  */
1246 bool tevent_req_is_in_progress(struct tevent_req *req);
1247
1248 /**
1249  * @brief Actively poll for the given request to finish.
1250  *
1251  * This function is typically used by sync wrapper functions.
1252  *
1253  * @param[in]  req      The request to poll.
1254  *
1255  * @param[in]  ev       The tevent_context to be used.
1256  *
1257  * @return              On success true is returned. If a critical error has
1258  *                      happened in the tevent loop layer false is returned.
1259  *                      This is not the return value of the given request!
1260  *
1261  * @note This should only be used if the given tevent context was created by the
1262  * caller, to avoid event loop nesting.
1263  *
1264  * @code
1265  * req = tstream_writev_queue_send(mem_ctx,
1266  *                                 ev_ctx,
1267  *                                 tstream,
1268  *                                 send_queue,
1269  *                                 iov, 2);
1270  * ok = tevent_req_poll(req, tctx->ev);
1271  * rc = tstream_writev_queue_recv(req, &sys_errno);
1272  * TALLOC_FREE(req);
1273  * @endcode
1274  */
1275 bool tevent_req_poll(struct tevent_req *req,
1276                      struct tevent_context *ev);
1277
1278 /**
1279  * @brief Get the tevent request state and the actual error set by
1280  * tevent_req_error.
1281  *
1282  * @code
1283  * int computation_recv(struct tevent_req *req, uint64_t *perr)
1284  * {
1285  *     enum tevent_req_state state;
1286  *     uint64_t err;
1287  *     if (tevent_req_is_error(req, &state, &err)) {
1288  *         *perr = err;
1289  *         return -1;
1290  *     }
1291  *     return 0;
1292  * }
1293  * @endcode
1294  *
1295  * @param[in]  req      The tevent request to get the error from.
1296  *
1297  * @param[out] state    A pointer to store the tevent request error state.
1298  *
1299  * @param[out] error    A pointer to store the error set by tevent_req_error().
1300  *
1301  * @return              True if the function could set error and state, false
1302  *                      otherwise.
1303  *
1304  * @see tevent_req_error()
1305  */
1306 bool tevent_req_is_error(struct tevent_req *req,
1307                          enum tevent_req_state *state,
1308                          uint64_t *error);
1309
1310 /**
1311  * @brief Use as the last action of a _recv() function.
1312  *
1313  * This function destroys the attached private data.
1314  *
1315  * @param[in]  req      The finished request.
1316  */
1317 void tevent_req_received(struct tevent_req *req);
1318
1319 /**
1320  * @brief Create a tevent subrequest at a given time.
1321  *
1322  * The idea is that always the same syntax for tevent requests.
1323  *
1324  * @param[in]  mem_ctx  The talloc memory context to use.
1325  *
1326  * @param[in]  ev       The event handle to setup the request.
1327  *
1328  * @param[in]  wakeup_time The time to wakeup and execute the request.
1329  *
1330  * @return              The new subrequest, NULL on error.
1331  *
1332  * Example:
1333  * @code
1334  *   static void my_callback_wakeup_done(tevent_req *subreq)
1335  *   {
1336  *     struct tevent_req *req = tevent_req_callback_data(subreq,
1337  *                              struct tevent_req);
1338  *     bool ok;
1339  *
1340  *     ok = tevent_wakeup_recv(subreq);
1341  *     TALLOC_FREE(subreq);
1342  *     if (!ok) {
1343  *         tevent_req_error(req, -1);
1344  *         return;
1345  *     }
1346  *     ...
1347  *   }
1348  * @endcode
1349  *
1350  * @code
1351  *   subreq = tevent_wakeup_send(mem_ctx, ev, wakeup_time);
1352  *   if (tevent_req_nomem(subreq, req)) {
1353  *     return false;
1354  *   }
1355  *   tevent_set_callback(subreq, my_callback_wakeup_done, req);
1356  * @endcode
1357  *
1358  * @see tevent_wakeup_recv()
1359  */
1360 struct tevent_req *tevent_wakeup_send(TALLOC_CTX *mem_ctx,
1361                                       struct tevent_context *ev,
1362                                       struct timeval wakeup_time);
1363
1364 /**
1365  * @brief Check if the wakeup has been correctly executed.
1366  *
1367  * This function needs to be called in the callback function set after calling
1368  * tevent_wakeup_send().
1369  *
1370  * @param[in]  req      The tevent request to check.
1371  *
1372  * @return              True on success, false otherwise.
1373  *
1374  * @see tevent_wakeup_recv()
1375  */
1376 bool tevent_wakeup_recv(struct tevent_req *req);
1377
1378 /* @} */
1379
1380 /**
1381  * @defgroup tevent_helpers The tevent helper functions
1382  * @ingroup tevent
1383  *
1384  * @todo description
1385  *
1386  * @{
1387  */
1388
1389 /**
1390  * @brief Compare two timeval values.
1391  *
1392  * @param[in]  tv1      The first timeval value to compare.
1393  *
1394  * @param[in]  tv2      The second timeval value to compare.
1395  *
1396  * @return              0 if they are equal.
1397  *                      1 if the first time is greater than the second.
1398  *                      -1 if the first time is smaller than the second.
1399  */
1400 int tevent_timeval_compare(const struct timeval *tv1,
1401                            const struct timeval *tv2);
1402
1403 /**
1404  * @brief Get a zero timeval value.
1405  *
1406  * @return              A zero timeval value.
1407  */
1408 struct timeval tevent_timeval_zero(void);
1409
1410 /**
1411  * @brief Get a timeval value for the current time.
1412  *
1413  * @return              A timeval value with the current time.
1414  */
1415 struct timeval tevent_timeval_current(void);
1416
1417 /**
1418  * @brief Get a timeval structure with the given values.
1419  *
1420  * @param[in]  secs     The seconds to set.
1421  *
1422  * @param[in]  usecs    The microseconds to set.
1423  *
1424  * @return              A timeval structure with the given values.
1425  */
1426 struct timeval tevent_timeval_set(uint32_t secs, uint32_t usecs);
1427
1428 /**
1429  * @brief Get the difference between two timeval values.
1430  *
1431  * @param[in]  tv1      The first timeval.
1432  *
1433  * @param[in]  tv2      The second timeval.
1434  *
1435  * @return              A timeval structure with the difference between the
1436  *                      first and the second value.
1437  */
1438 struct timeval tevent_timeval_until(const struct timeval *tv1,
1439                                     const struct timeval *tv2);
1440
1441 /**
1442  * @brief Check if a given timeval structure is zero.
1443  *
1444  * @param[in]  tv       The timeval to check if it is zero.
1445  *
1446  * @return              True if it is zero, false otherwise.
1447  */
1448 bool tevent_timeval_is_zero(const struct timeval *tv);
1449
1450 /**
1451  * @brief Add the given amount of time to a timeval structure.
1452  *
1453  * @param[in]  tv        The timeval structure to add the time.
1454  *
1455  * @param[in]  secs      The seconds to add to the timeval.
1456  *
1457  * @param[in]  usecs     The microseconds to add to the timeval.
1458  *
1459  * @return               The timeval structure with the new time.
1460  */
1461 struct timeval tevent_timeval_add(const struct timeval *tv, uint32_t secs,
1462                                   uint32_t usecs);
1463
1464 /**
1465  * @brief Get a timeval in the future with a specified offset from now.
1466  *
1467  * @param[in]  secs     The seconds of the offset from now.
1468  *
1469  * @param[in]  usecs    The microseconds of the offset from now.
1470  *
1471  * @return              A timval with the given offset in the future.
1472  */
1473 struct timeval tevent_timeval_current_ofs(uint32_t secs, uint32_t usecs);
1474
1475 /* @} */
1476
1477
1478 /**
1479  * @defgroup tevent_queue The tevent queue functions
1480  * @ingroup tevent
1481  *
1482  * A tevent_queue is used to queue up async requests that must be
1483  * serialized. For example writing buffers into a socket must be
1484  * serialized. Writing a large lump of data into a socket can require
1485  * multiple write(2) or send(2) system calls. If more than one async
1486  * request is outstanding to write large buffers into a socket, every
1487  * request must individually be completed before the next one begins,
1488  * even if multiple syscalls are required.
1489  *
1490  * Take a look at @ref tevent_queue_tutorial for more details.
1491  * @{
1492  */
1493
1494 struct tevent_queue;
1495 struct tevent_queue_entry;
1496
1497 #ifdef DOXYGEN
1498 /**
1499  * @brief Create and start a tevent queue.
1500  *
1501  * @param[in]  mem_ctx  The talloc memory context to allocate the queue.
1502  *
1503  * @param[in]  name     The name to use to identify the queue.
1504  *
1505  * @return              An allocated tevent queue on success, NULL on error.
1506  *
1507  * @see tevent_queue_start()
1508  * @see tevent_queue_stop()
1509  */
1510 struct tevent_queue *tevent_queue_create(TALLOC_CTX *mem_ctx,
1511                                          const char *name);
1512 #else
1513 struct tevent_queue *_tevent_queue_create(TALLOC_CTX *mem_ctx,
1514                                           const char *name,
1515                                           const char *location);
1516
1517 #define tevent_queue_create(_mem_ctx, _name) \
1518         _tevent_queue_create((_mem_ctx), (_name), __location__)
1519 #endif
1520
1521 /**
1522  * @brief A callback trigger function run by the queue.
1523  *
1524  * @param[in]  req      The tevent request the trigger function is executed on.
1525  *
1526  * @param[in]  private_data The private data pointer specified by
1527  *                          tevent_queue_add().
1528  *
1529  * @see tevent_queue_add()
1530  * @see tevent_queue_add_entry()
1531  * @see tevent_queue_add_optimize_empty()
1532  */
1533 typedef void (*tevent_queue_trigger_fn_t)(struct tevent_req *req,
1534                                           void *private_data);
1535
1536 /**
1537  * @brief Add a tevent request to the queue.
1538  *
1539  * @param[in]  queue    The queue to add the request.
1540  *
1541  * @param[in]  ev       The event handle to use for the request.
1542  *
1543  * @param[in]  req      The tevent request to add to the queue.
1544  *
1545  * @param[in]  trigger  The function triggered by the queue when the request
1546  *                      is called. Since tevent 0.9.14 it's possible to
1547  *                      pass NULL, in order to just add a "blocker" to the
1548  *                      queue.
1549  *
1550  * @param[in]  private_data The private data passed to the trigger function.
1551  *
1552  * @return              True if the request has been successfully added, false
1553  *                      otherwise.
1554  */
1555 bool tevent_queue_add(struct tevent_queue *queue,
1556                       struct tevent_context *ev,
1557                       struct tevent_req *req,
1558                       tevent_queue_trigger_fn_t trigger,
1559                       void *private_data);
1560
1561 /**
1562  * @brief Add a tevent request to the queue.
1563  *
1564  * The request can be removed from the queue by calling talloc_free()
1565  * (or a similar function) on the returned queue entry. This
1566  * is the only difference to tevent_queue_add().
1567  *
1568  * @param[in]  queue    The queue to add the request.
1569  *
1570  * @param[in]  ev       The event handle to use for the request.
1571  *
1572  * @param[in]  req      The tevent request to add to the queue.
1573  *
1574  * @param[in]  trigger  The function triggered by the queue when the request
1575  *                      is called. Since tevent 0.9.14 it's possible to
1576  *                      pass NULL, in order to just add a "blocker" to the
1577  *                      queue.
1578  *
1579  * @param[in]  private_data The private data passed to the trigger function.
1580  *
1581  * @return              a pointer to the tevent_queue_entry if the request
1582  *                      has been successfully added, NULL otherwise.
1583  *
1584  * @see tevent_queue_add()
1585  * @see tevent_queue_add_optimize_empty()
1586  */
1587 struct tevent_queue_entry *tevent_queue_add_entry(
1588                                         struct tevent_queue *queue,
1589                                         struct tevent_context *ev,
1590                                         struct tevent_req *req,
1591                                         tevent_queue_trigger_fn_t trigger,
1592                                         void *private_data);
1593
1594 /**
1595  * @brief Add a tevent request to the queue using a possible optimization.
1596  *
1597  * This tries to optimize for the empty queue case and may calls
1598  * the trigger function directly. This is the only difference compared
1599  * to tevent_queue_add_entry().
1600  *
1601  * The caller needs to be prepared that the trigger function has
1602  * already called tevent_req_notify_callback(), tevent_req_error(),
1603  * tevent_req_done() or a similar function.
1604  *
1605  * The request can be removed from the queue by calling talloc_free()
1606  * (or a similar function) on the returned queue entry.
1607  *
1608  * @param[in]  queue    The queue to add the request.
1609  *
1610  * @param[in]  ev       The event handle to use for the request.
1611  *
1612  * @param[in]  req      The tevent request to add to the queue.
1613  *
1614  * @param[in]  trigger  The function triggered by the queue when the request
1615  *                      is called. Since tevent 0.9.14 it's possible to
1616  *                      pass NULL, in order to just add a "blocker" to the
1617  *                      queue.
1618  *
1619  * @param[in]  private_data The private data passed to the trigger function.
1620  *
1621  * @return              a pointer to the tevent_queue_entry if the request
1622  *                      has been successfully added, NULL otherwise.
1623  *
1624  * @see tevent_queue_add()
1625  * @see tevent_queue_add_entry()
1626  */
1627 struct tevent_queue_entry *tevent_queue_add_optimize_empty(
1628                                         struct tevent_queue *queue,
1629                                         struct tevent_context *ev,
1630                                         struct tevent_req *req,
1631                                         tevent_queue_trigger_fn_t trigger,
1632                                         void *private_data);
1633
1634 /**
1635  * @brief Start a tevent queue.
1636  *
1637  * The queue is started by default.
1638  *
1639  * @param[in]  queue    The queue to start.
1640  */
1641 void tevent_queue_start(struct tevent_queue *queue);
1642
1643 /**
1644  * @brief Stop a tevent queue.
1645  *
1646  * The queue is started by default.
1647  *
1648  * @param[in]  queue    The queue to stop.
1649  */
1650 void tevent_queue_stop(struct tevent_queue *queue);
1651
1652 /**
1653  * @brief Get the length of the queue.
1654  *
1655  * @param[in]  queue    The queue to get the length from.
1656  *
1657  * @return              The number of elements.
1658  */
1659 size_t tevent_queue_length(struct tevent_queue *queue);
1660
1661 /**
1662  * @brief Is the tevent queue running.
1663  *
1664  * The queue is started by default.
1665  *
1666  * @param[in]  queue    The queue.
1667  *
1668  * @return              Wether the queue is running or not..
1669  */
1670 bool tevent_queue_running(struct tevent_queue *queue);
1671
1672 /**
1673  * @brief Create a tevent subrequest that waits in a tevent_queue
1674  *
1675  * The idea is that always the same syntax for tevent requests.
1676  *
1677  * @param[in]  mem_ctx  The talloc memory context to use.
1678  *
1679  * @param[in]  ev       The event handle to setup the request.
1680  *
1681  * @param[in]  queue    The queue to wait in.
1682  *
1683  * @return              The new subrequest, NULL on error.
1684  *
1685  * @see tevent_queue_wait_recv()
1686  */
1687 struct tevent_req *tevent_queue_wait_send(TALLOC_CTX *mem_ctx,
1688                                           struct tevent_context *ev,
1689                                           struct tevent_queue *queue);
1690
1691 /**
1692  * @brief Check if we no longer need to wait in the queue.
1693  *
1694  * This function needs to be called in the callback function set after calling
1695  * tevent_queue_wait_send().
1696  *
1697  * @param[in]  req      The tevent request to check.
1698  *
1699  * @return              True on success, false otherwise.
1700  *
1701  * @see tevent_queue_wait_send()
1702  */
1703 bool tevent_queue_wait_recv(struct tevent_req *req);
1704
1705 typedef int (*tevent_nesting_hook)(struct tevent_context *ev,
1706                                    void *private_data,
1707                                    uint32_t level,
1708                                    bool begin,
1709                                    void *stack_ptr,
1710                                    const char *location);
1711
1712 /**
1713  * @brief Create a tevent_thread_proxy for message passing between threads.
1714  *
1715  * The tevent_context must have been allocated on the NULL
1716  * talloc context, and talloc_disable_null_tracking() must
1717  * have been called.
1718  *
1719  * @param[in]  dest_ev_ctx      The tevent_context to receive events.
1720  *
1721  * @return              An allocated tevent_thread_proxy, NULL on error.
1722  *                      If tevent was compiled without PTHREAD support
1723  *                      NULL is always returned and errno set to ENOSYS.
1724  *
1725  * @see tevent_thread_proxy_schedule()
1726  */
1727 struct tevent_thread_proxy *tevent_thread_proxy_create(
1728                 struct tevent_context *dest_ev_ctx);
1729
1730 /**
1731  * @brief Schedule an immediate event on an event context from another thread.
1732  *
1733  * Causes dest_ev_ctx, being run by another thread, to receive an
1734  * immediate event calling the handler with the *pp_private parameter.
1735  *
1736  * *pp_im must be a pointer to an immediate event talloced on a context owned
1737  * by the calling thread, or the NULL context. Ownership will
1738  * be transferred to the tevent_thread_proxy and *pp_im will be returned as NULL.
1739  *
1740  * *pp_private_data must be a talloced area of memory with no destructors.
1741  * Ownership of this memory will be transferred to the tevent library and
1742  * *pp_private_data will be set to NULL on successful completion of
1743  * the call. Set pp_private to NULL if no parameter transfer
1744  * needed (a pure callback). This is an asynchronous request, caller
1745  * does not wait for callback to be completed before returning.
1746  *
1747  * @param[in]  tp               The tevent_thread_proxy to use.
1748  *
1749  * @param[in]  pp_im            Pointer to immediate event pointer.
1750  *
1751  * @param[in]  handler          The function that will be called.
1752  *
1753  * @param[in]  pp_private_data  The talloced memory to transfer.
1754  *
1755  * @see tevent_thread_proxy_create()
1756  */
1757 void tevent_thread_proxy_schedule(struct tevent_thread_proxy *tp,
1758                                   struct tevent_immediate **pp_im,
1759                                   tevent_immediate_handler_t handler,
1760                                   void *pp_private_data);
1761
1762 /*
1763  * @brief Create a context for threaded activation of immediates
1764  *
1765  * A tevent_treaded_context provides a link into an event
1766  * context. Using tevent_threaded_schedule_immediate, it is possible
1767  * to activate an immediate event from within a thread.
1768  *
1769  * It is the duty of the caller of tevent_threaded_context_create() to
1770  * keep the event context around longer than any
1771  * tevent_threaded_context. tevent will abort if ev is talllc_free'ed
1772  * with an active tevent_threaded_context.
1773  *
1774  * If tevent is build without pthread support, this always returns
1775  * NULL with errno=ENOSYS.
1776  *
1777  * @param[in]  mem_ctx  The talloc memory context to use.
1778  * @param[in]  ev       The event context to link this to.
1779  * @return              The threaded context, or NULL with errno set.
1780  *
1781  * @see tevent_threaded_schedule_immediate()
1782  *
1783  * @note Available as of tevent 0.9.30
1784  */
1785 struct tevent_threaded_context *tevent_threaded_context_create(
1786         TALLOC_CTX *mem_ctx, struct tevent_context *ev);
1787
1788 #ifdef DOXYGEN
1789 /*
1790  * @brief Activate an immediate from a thread
1791  *
1792  * Activate an immediate from within a thread.
1793  *
1794  * This routine does not watch out for talloc hierarchies. This means
1795  * that it is highly recommended to create the tevent_immediate in the
1796  * thread owning tctx, allocate a threaded job description for the
1797  * thread, hand over both pointers to a helper thread and not touch it
1798  * in the main thread at all anymore.
1799  *
1800  * tevent_threaded_schedule_immediate is intended as a job completion
1801  * indicator for simple threaded helpers.
1802  *
1803  * Please be aware that tevent_threaded_schedule_immediate is very
1804  * picky about its arguments: An immediate may not already be
1805  * activated and the handler must exist. With
1806  * tevent_threaded_schedule_immediate memory ownership is transferred
1807  * to the main thread holding the tevent context behind tctx, the
1808  * helper thread can't access it anymore.
1809  *
1810  * @param[in]  tctx     The threaded context to go through
1811  * @param[in]  im       The immediate event to activate
1812  * @param[in]  handler  The immediate handler to call in the main thread
1813  * @param[in]  private_data Pointer for the immediate handler
1814  *
1815  * @see tevent_threaded_context_create()
1816  *
1817  * @note Available as of tevent 0.9.30
1818  */
1819 void tevent_threaded_schedule_immediate(struct tevent_threaded_context *tctx,
1820                                         struct tevent_immediate *im,
1821                                         tevent_immediate_handler_t handler,
1822                                         void *private_data);
1823 #else
1824 void _tevent_threaded_schedule_immediate(struct tevent_threaded_context *tctx,
1825                                          struct tevent_immediate *im,
1826                                          tevent_immediate_handler_t handler,
1827                                          void *private_data,
1828                                          const char *handler_name,
1829                                          const char *location);
1830 #define tevent_threaded_schedule_immediate(tctx, im, handler, private_data) \
1831         _tevent_threaded_schedule_immediate(tctx, im, handler, private_data, \
1832                                    #handler, __location__);
1833 #endif
1834
1835 #ifdef TEVENT_DEPRECATED
1836 #ifndef _DEPRECATED_
1837 #ifdef HAVE___ATTRIBUTE__
1838 #define _DEPRECATED_ __attribute__ ((deprecated))
1839 #else
1840 #define _DEPRECATED_
1841 #endif
1842 #endif
1843 void tevent_loop_allow_nesting(struct tevent_context *ev) _DEPRECATED_;
1844 void tevent_loop_set_nesting_hook(struct tevent_context *ev,
1845                                   tevent_nesting_hook hook,
1846                                   void *private_data) _DEPRECATED_;
1847 int _tevent_loop_until(struct tevent_context *ev,
1848                        bool (*finished)(void *private_data),
1849                        void *private_data,
1850                        const char *location) _DEPRECATED_;
1851 #define tevent_loop_until(ev, finished, private_data) \
1852         _tevent_loop_until(ev, finished, private_data, __location__)
1853 #endif
1854
1855 int tevent_re_initialise(struct tevent_context *ev);
1856
1857 /* @} */
1858
1859 /**
1860  * @defgroup tevent_ops The tevent operation functions
1861  * @ingroup tevent
1862  *
1863  * The following structure and registration functions are exclusively
1864  * needed for people writing and pluggin a different event engine.
1865  * There is nothing useful for normal tevent user in here.
1866  * @{
1867  */
1868
1869 struct tevent_ops {
1870         /* context init */
1871         int (*context_init)(struct tevent_context *ev);
1872
1873         /* fd_event functions */
1874         struct tevent_fd *(*add_fd)(struct tevent_context *ev,
1875                                     TALLOC_CTX *mem_ctx,
1876                                     int fd, uint16_t flags,
1877                                     tevent_fd_handler_t handler,
1878                                     void *private_data,
1879                                     const char *handler_name,
1880                                     const char *location);
1881         void (*set_fd_close_fn)(struct tevent_fd *fde,
1882                                 tevent_fd_close_fn_t close_fn);
1883         uint16_t (*get_fd_flags)(struct tevent_fd *fde);
1884         void (*set_fd_flags)(struct tevent_fd *fde, uint16_t flags);
1885
1886         /* timed_event functions */
1887         struct tevent_timer *(*add_timer)(struct tevent_context *ev,
1888                                           TALLOC_CTX *mem_ctx,
1889                                           struct timeval next_event,
1890                                           tevent_timer_handler_t handler,
1891                                           void *private_data,
1892                                           const char *handler_name,
1893                                           const char *location);
1894
1895         /* immediate event functions */
1896         void (*schedule_immediate)(struct tevent_immediate *im,
1897                                    struct tevent_context *ev,
1898                                    tevent_immediate_handler_t handler,
1899                                    void *private_data,
1900                                    const char *handler_name,
1901                                    const char *location);
1902
1903         /* signal functions */
1904         struct tevent_signal *(*add_signal)(struct tevent_context *ev,
1905                                             TALLOC_CTX *mem_ctx,
1906                                             int signum, int sa_flags,
1907                                             tevent_signal_handler_t handler,
1908                                             void *private_data,
1909                                             const char *handler_name,
1910                                             const char *location);
1911
1912         /* loop functions */
1913         int (*loop_once)(struct tevent_context *ev, const char *location);
1914         int (*loop_wait)(struct tevent_context *ev, const char *location);
1915 };
1916
1917 bool tevent_register_backend(const char *name, const struct tevent_ops *ops);
1918
1919 /* @} */
1920
1921 /**
1922  * @defgroup tevent_compat The tevent compatibility functions
1923  * @ingroup tevent
1924  *
1925  * The following definitions are usueful only for compatibility with the
1926  * implementation originally developed within the samba4 code and will be
1927  * soon removed. Please NEVER use in new code.
1928  *
1929  * @todo Ignore it?
1930  *
1931  * @{
1932  */
1933
1934 #ifdef TEVENT_COMPAT_DEFINES
1935
1936 #define event_context   tevent_context
1937 #define event_ops       tevent_ops
1938 #define fd_event        tevent_fd
1939 #define timed_event     tevent_timer
1940 #define signal_event    tevent_signal
1941
1942 #define event_fd_handler_t      tevent_fd_handler_t
1943 #define event_timed_handler_t   tevent_timer_handler_t
1944 #define event_signal_handler_t  tevent_signal_handler_t
1945
1946 #define event_context_init(mem_ctx) \
1947         tevent_context_init(mem_ctx)
1948
1949 #define event_context_init_byname(mem_ctx, name) \
1950         tevent_context_init_byname(mem_ctx, name)
1951
1952 #define event_backend_list(mem_ctx) \
1953         tevent_backend_list(mem_ctx)
1954
1955 #define event_set_default_backend(backend) \
1956         tevent_set_default_backend(backend)
1957
1958 #define event_add_fd(ev, mem_ctx, fd, flags, handler, private_data) \
1959         tevent_add_fd(ev, mem_ctx, fd, flags, handler, private_data)
1960
1961 #define event_add_timed(ev, mem_ctx, next_event, handler, private_data) \
1962         tevent_add_timer(ev, mem_ctx, next_event, handler, private_data)
1963
1964 #define event_add_signal(ev, mem_ctx, signum, sa_flags, handler, private_data) \
1965         tevent_add_signal(ev, mem_ctx, signum, sa_flags, handler, private_data)
1966
1967 #define event_loop_once(ev) \
1968         tevent_loop_once(ev)
1969
1970 #define event_loop_wait(ev) \
1971         tevent_loop_wait(ev)
1972
1973 #define event_get_fd_flags(fde) \
1974         tevent_fd_get_flags(fde)
1975
1976 #define event_set_fd_flags(fde, flags) \
1977         tevent_fd_set_flags(fde, flags)
1978
1979 #define EVENT_FD_READ           TEVENT_FD_READ
1980 #define EVENT_FD_WRITE          TEVENT_FD_WRITE
1981
1982 #define EVENT_FD_WRITEABLE(fde) \
1983         TEVENT_FD_WRITEABLE(fde)
1984
1985 #define EVENT_FD_READABLE(fde) \
1986         TEVENT_FD_READABLE(fde)
1987
1988 #define EVENT_FD_NOT_WRITEABLE(fde) \
1989         TEVENT_FD_NOT_WRITEABLE(fde)
1990
1991 #define EVENT_FD_NOT_READABLE(fde) \
1992         TEVENT_FD_NOT_READABLE(fde)
1993
1994 #define ev_debug_level          tevent_debug_level
1995
1996 #define EV_DEBUG_FATAL          TEVENT_DEBUG_FATAL
1997 #define EV_DEBUG_ERROR          TEVENT_DEBUG_ERROR
1998 #define EV_DEBUG_WARNING        TEVENT_DEBUG_WARNING
1999 #define EV_DEBUG_TRACE          TEVENT_DEBUG_TRACE
2000
2001 #define ev_set_debug(ev, debug, context) \
2002         tevent_set_debug(ev, debug, context)
2003
2004 #define ev_set_debug_stderr(_ev) tevent_set_debug_stderr(ev)
2005
2006 #endif /* TEVENT_COMPAT_DEFINES */
2007
2008 /* @} */
2009
2010 #endif /* __TEVENT_H__ */