xref: /openbsd/lib/libevent/event.h (revision 756da5e0)
1 /*	$OpenBSD: event.h,v 1.31 2019/04/29 17:11:51 tobias Exp $	*/
2 
3 /*
4  * Copyright (c) 2000-2007 Niels Provos <provos@citi.umich.edu>
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. The name of the author may not be used to endorse or promote products
16  *    derived from this software without specific prior written permission.
17  *
18  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
19  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
20  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
21  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
22  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
23  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
24  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
27  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28  */
29 #ifndef _EVENT_H_
30 #define _EVENT_H_
31 
32 /** @mainpage
33 
34   @section intro Introduction
35 
36   libevent is an event notification library for developing scalable network
37   servers.  The libevent API provides a mechanism to execute a callback
38   function when a specific event occurs on a file descriptor or after a
39   timeout has been reached. Furthermore, libevent also support callbacks due
40   to signals or regular timeouts.
41 
42   libevent is meant to replace the event loop found in event driven network
43   servers. An application just needs to call event_dispatch() and then add or
44   remove events dynamically without having to change the event loop.
45 
46   Currently, libevent supports /dev/poll, kqueue(2), select(2), poll(2) and
47   epoll(4). It also has experimental support for real-time signals. The
48   internal event mechanism is completely independent of the exposed event API,
49   and a simple update of libevent can provide new functionality without having
50   to redesign the applications. As a result, Libevent allows for portable
51   application development and provides the most scalable event notification
52   mechanism available on an operating system. Libevent can also be used for
53   multi-threaded applications; see Steven Grimm's explanation. Libevent should
54   compile on Linux, *BSD, Mac OS X, Solaris and Windows.
55 
56   @section usage Standard usage
57 
58   Every program that uses libevent must include the <event.h> header, and pass
59   the -levent flag to the linker.  Before using any of the functions in the
60   library, you must call event_init() or event_base_new() to perform one-time
61   initialization of the libevent library.
62 
63   @section event Event notification
64 
65   For each file descriptor that you wish to monitor, you must declare an event
66   structure and call event_set() to initialize the members of the structure.
67   To enable notification, you add the structure to the list of monitored
68   events by calling event_add().  The event structure must remain allocated as
69   long as it is active, so it should be allocated on the heap. Finally, you
70   call event_dispatch() to loop and dispatch events.
71 
72   @section bufferevent I/O Buffers
73 
74   libevent provides an abstraction on top of the regular event callbacks. This
75   abstraction is called a buffered event. A buffered event provides input and
76   output buffers that get filled and drained automatically. The user of a
77   buffered event no longer deals directly with the I/O, but instead is reading
78   from input and writing to output buffers.
79 
80   Once initialized via bufferevent_new(), the bufferevent structure can be
81   used repeatedly with bufferevent_enable() and bufferevent_disable().
82   Instead of reading and writing directly to a socket, you would call
83   bufferevent_read() and bufferevent_write().
84 
85   When read enabled the bufferevent will try to read from the file descriptor
86   and call the read callback. The write callback is executed whenever the
87   output buffer is drained below the write low watermark, which is 0 by
88   default.
89 
90   @section timers Timers
91 
92   libevent can also be used to create timers that invoke a callback after a
93   certain amount of time has expired. The evtimer_set() function prepares an
94   event struct to be used as a timer. To activate the timer, call
95   evtimer_add(). Timers can be deactivated by calling evtimer_del().
96 
97   @section timeouts Timeouts
98 
99   In addition to simple timers, libevent can assign timeout events to file
100   descriptors that are triggered whenever a certain amount of time has passed
101   with no activity on a file descriptor.  The timeout_set() function
102   initializes an event struct for use as a timeout. Once initialized, the
103   event must be activated by using timeout_add().  To cancel the timeout, call
104   timeout_del().
105 
106   @section evdns Asynchronous DNS resolution
107 
108   libevent provides an asynchronous DNS resolver that should be used instead
109   of the standard DNS resolver functions.  These functions can be imported by
110   including the <evdns.h> header in your program. Before using any of the
111   resolver functions, you must call evdns_init() to initialize the library. To
112   convert a hostname to an IP address, you call the evdns_resolve_ipv4()
113   function.  To perform a reverse lookup, you would call the
114   evdns_resolve_reverse() function.  All of these functions use callbacks to
115   avoid blocking while the lookup is performed.
116 
117   @section evhttp Event-driven HTTP servers
118 
119   libevent provides a very simple event-driven HTTP server that can be
120   embedded in your program and used to service HTTP requests.
121 
122   To use this capability, you need to include the <evhttp.h> header in your
123   program.  You create the server by calling evhttp_new(). Add addresses and
124   ports to listen on with evhttp_bind_socket(). You then register one or more
125   callbacks to handle incoming requests.  Each URI can be assigned a callback
126   via the evhttp_set_cb() function.  A generic callback function can also be
127   registered via evhttp_set_gencb(); this callback will be invoked if no other
128   callbacks have been registered for a given URI.
129 
130   @section evrpc A framework for RPC servers and clients
131 
132   libevents provides a framework for creating RPC servers and clients.  It
133   takes care of marshaling and unmarshaling all data structures.
134 
135   @section api API Reference
136 
137   To browse the complete documentation of the libevent API, click on any of
138   the following links.
139 
140   event.h
141   The primary libevent header
142 
143   evdns.h
144   Asynchronous DNS resolution
145 
146   evhttp.h
147   An embedded libevent-based HTTP server
148 
149   evrpc.h
150   A framework for creating RPC servers and clients
151 
152  */
153 
154 /** @file event.h
155 
156   A library for writing event-driven network servers
157 
158  */
159 
160 #ifdef __cplusplus
161 extern "C" {
162 #endif
163 
164 #include <sys/types.h>
165 #include <sys/time.h>
166 #include <sys/queue.h>
167 
168 #include <stdarg.h>
169 #include <stdint.h>
170 
171 #define ev_uint64_t uint64_t
172 #define ev_int64_t int64_t
173 #define ev_uint32_t uint32_t
174 #define ev_uint16_t uint16_t
175 #define ev_uint8_t uint8_t
176 
177 #define EVLIST_TIMEOUT	0x01
178 #define EVLIST_INSERTED	0x02
179 #define EVLIST_SIGNAL	0x04
180 #define EVLIST_ACTIVE	0x08
181 #define EVLIST_INTERNAL	0x10
182 #define EVLIST_INIT	0x80
183 
184 /* EVLIST_X_ Private space: 0x1000-0xf000 */
185 #define EVLIST_ALL	(0xf000 | 0x9f)
186 
187 #define EV_TIMEOUT	0x01
188 #define EV_READ		0x02
189 #define EV_WRITE	0x04
190 #define EV_SIGNAL	0x08
191 #define EV_PERSIST	0x10	/* Persistent event */
192 
193 struct event_base;
194 #ifndef EVENT_NO_STRUCT
195 struct event {
196 	TAILQ_ENTRY (event) ev_next;
197 	TAILQ_ENTRY (event) ev_active_next;
198 	TAILQ_ENTRY (event) ev_signal_next;
199 	size_t min_heap_idx;	/* for managing timeouts */
200 
201 	struct event_base *ev_base;
202 
203 	int ev_fd;
204 	short ev_events;
205 	short ev_ncalls;
206 	short *ev_pncalls;	/* Allows deletes in callback */
207 
208 	struct timeval ev_timeout;
209 
210 	int ev_pri;		/* smaller numbers are higher priority */
211 
212 	void (*ev_callback)(int, short, void *arg);
213 	void *ev_arg;
214 
215 	int ev_res;		/* result passed to event callback */
216 	int ev_flags;
217 };
218 #else
219 struct event;
220 #endif
221 
222 #define EVENT_SIGNAL(ev)	(int)(ev)->ev_fd
223 #define EVENT_FD(ev)		(int)(ev)->ev_fd
224 
225 /*
226  * Key-Value pairs.  Can be used for HTTP headers but also for
227  * query argument parsing.
228  */
229 struct evkeyval {
230 	TAILQ_ENTRY(evkeyval) next;
231 
232 	char *key;
233 	char *value;
234 };
235 
236 TAILQ_HEAD (event_list, event);
237 TAILQ_HEAD (evkeyvalq, evkeyval);
238 
239 /**
240   Initialize the event API.
241 
242   Use event_base_new() to initialize a new event base, but does not set
243   the current_base global.   If using only event_base_new(), each event
244   added must have an event base set with event_base_set()
245 
246   @see event_base_set(), event_base_free(), event_init()
247  */
248 struct event_base *event_base_new(void);
249 
250 /**
251   Initialize the event API.
252 
253   The event API needs to be initialized with event_init() before it can be
254   used.  Sets the current_base global representing the default base for
255   events that have no base associated with them.
256 
257   @see event_base_set(), event_base_new()
258  */
259 struct event_base *event_init(void);
260 
261 /**
262   Reinitialized the event base after a fork
263 
264   Some event mechanisms do not survive across fork.   The event base needs
265   to be reinitialized with the event_reinit() function.
266 
267   @param base the event base that needs to be re-initialized
268   @return 0 if successful, or -1 if some events could not be re-added.
269   @see event_base_new(), event_init()
270 */
271 int event_reinit(struct event_base *base);
272 
273 /**
274   Loop to process events.
275 
276   In order to process events, an application needs to call
277   event_dispatch().  This function only returns on error, and should
278   replace the event core of the application program.
279 
280   @see event_base_dispatch()
281  */
282 int event_dispatch(void);
283 
284 
285 /**
286   Threadsafe event dispatching loop.
287 
288   @param eb the event_base structure returned by event_init()
289   @see event_init(), event_dispatch()
290  */
291 int event_base_dispatch(struct event_base *);
292 
293 
294 /**
295  Get the kernel event notification mechanism used by libevent.
296 
297  @param eb the event_base structure returned by event_base_new()
298  @return a string identifying the kernel event mechanism (kqueue, epoll, etc.)
299  */
300 const char *event_base_get_method(struct event_base *);
301 
302 
303 /**
304   Deallocate all memory associated with an event_base, and free the base.
305 
306   Note that this function will not close any fds or free any memory passed
307   to event_set as the argument to callback.
308 
309   @param eb an event_base to be freed
310  */
311 void event_base_free(struct event_base *);
312 
313 
314 #define _EVENT_LOG_DEBUG 0
315 #define _EVENT_LOG_MSG   1
316 #define _EVENT_LOG_WARN  2
317 #define _EVENT_LOG_ERR   3
318 typedef void (*event_log_cb)(int severity, const char *msg);
319 /**
320   Redirect libevent's log messages.
321 
322   @param cb a function taking two arguments: an integer severity between
323      _EVENT_LOG_DEBUG and _EVENT_LOG_ERR, and a string.  If cb is NULL,
324 	 then the default log is used.
325   */
326 void event_set_log_callback(event_log_cb cb);
327 
328 /**
329   Associate a different event base with an event.
330 
331   @param eb the event base
332   @param ev the event
333  */
334 int event_base_set(struct event_base *, struct event *);
335 
336 /**
337  event_loop() flags
338  */
339 /*@{*/
340 #define EVLOOP_ONCE	0x01	/**< Block at most once. */
341 #define EVLOOP_NONBLOCK	0x02	/**< Do not block. */
342 /*@}*/
343 
344 /**
345   Handle events.
346 
347   This is a more flexible version of event_dispatch().
348 
349   @param flags any combination of EVLOOP_ONCE | EVLOOP_NONBLOCK
350   @return 0 if successful, -1 if an error occurred, or 1 if no events were
351     registered.
352   @see event_loopexit(), event_base_loop()
353 */
354 int event_loop(int);
355 
356 /**
357   Handle events (threadsafe version).
358 
359   This is a more flexible version of event_base_dispatch().
360 
361   @param eb the event_base structure returned by event_init()
362   @param flags any combination of EVLOOP_ONCE | EVLOOP_NONBLOCK
363   @return 0 if successful, -1 if an error occurred, or 1 if no events were
364     registered.
365   @see event_loopexit(), event_base_loop()
366   */
367 int event_base_loop(struct event_base *, int);
368 
369 /**
370   Exit the event loop after the specified time.
371 
372   The next event_loop() iteration after the given timer expires will
373   complete normally (handling all queued events) then exit without
374   blocking for events again.
375 
376   Subsequent invocations of event_loop() will proceed normally.
377 
378   @param tv the amount of time after which the loop should terminate.
379   @return 0 if successful, or -1 if an error occurred
380   @see event_loop(), event_base_loop(), event_base_loopexit()
381   */
382 int event_loopexit(const struct timeval *);
383 
384 
385 /**
386   Exit the event loop after the specified time (threadsafe variant).
387 
388   The next event_base_loop() iteration after the given timer expires will
389   complete normally (handling all queued events) then exit without
390   blocking for events again.
391 
392   Subsequent invocations of event_base_loop() will proceed normally.
393 
394   @param eb the event_base structure returned by event_init()
395   @param tv the amount of time after which the loop should terminate.
396   @return 0 if successful, or -1 if an error occurred
397   @see event_loopexit()
398  */
399 int event_base_loopexit(struct event_base *, const struct timeval *);
400 
401 /**
402   Abort the active event_loop() immediately.
403 
404   event_loop() will abort the loop after the next event is completed;
405   event_loopbreak() is typically invoked from this event's callback.
406   This behavior is analogous to the "break;" statement.
407 
408   Subsequent invocations of event_loop() will proceed normally.
409 
410   @return 0 if successful, or -1 if an error occurred
411   @see event_base_loopbreak(), event_loopexit()
412  */
413 int event_loopbreak(void);
414 
415 /**
416   Abort the active event_base_loop() immediately.
417 
418   event_base_loop() will abort the loop after the next event is completed;
419   event_base_loopbreak() is typically invoked from this event's callback.
420   This behavior is analogous to the "break;" statement.
421 
422   Subsequent invocations of event_loop() will proceed normally.
423 
424   @param eb the event_base structure returned by event_init()
425   @return 0 if successful, or -1 if an error occurred
426   @see event_base_loopexit
427  */
428 int event_base_loopbreak(struct event_base *);
429 
430 
431 /**
432   Add a timer event.
433 
434   @param ev the event struct
435   @param tv timeval struct
436  */
437 #define evtimer_add(ev, tv)		event_add(ev, tv)
438 
439 
440 /**
441   Define a timer event.
442 
443   @param ev event struct to be modified
444   @param cb callback function
445   @param arg argument that will be passed to the callback function
446  */
447 #define evtimer_set(ev, cb, arg)	event_set(ev, -1, 0, cb, arg)
448 
449 
450 /**
451  * Delete a timer event.
452  *
453  * @param ev the event struct to be disabled
454  */
455 #define evtimer_del(ev)			event_del(ev)
456 #define evtimer_pending(ev, tv)		event_pending(ev, EV_TIMEOUT, tv)
457 #define evtimer_initialized(ev)		((ev)->ev_flags & EVLIST_INIT)
458 
459 #ifdef EVENT_DEPRECATED
460 /*
461  * timeout_* are collision-prone names for macros, and they are
462  * deprecated. Define EVENT_DEPRECATED to expose them anyway.
463  *
464  * It is recommended evtimer_* be used instead.
465  */
466 
467 /**
468  * Add a timeout event.
469  *
470  * @param ev the event struct to be disabled
471  * @param tv the timeout value, in seconds
472  */
473 #define timeout_add(ev, tv)		event_add(ev, tv)
474 
475 
476 /**
477  * Define a timeout event.
478  *
479  * @param ev the event struct to be defined
480  * @param cb the callback to be invoked when the timeout expires
481  * @param arg the argument to be passed to the callback
482  */
483 #define timeout_set(ev, cb, arg)	event_set(ev, -1, 0, cb, arg)
484 
485 
486 /**
487  * Disable a timeout event.
488  *
489  * @param ev the timeout event to be disabled
490  */
491 #define timeout_del(ev)			event_del(ev)
492 
493 #define timeout_pending(ev, tv)		event_pending(ev, EV_TIMEOUT, tv)
494 #define timeout_initialized(ev)		((ev)->ev_flags & EVLIST_INIT)
495 
496 #endif /* EVENT_DEPRECATED */
497 
498 #define signal_add(ev, tv)		event_add(ev, tv)
499 #define signal_set(ev, x, cb, arg)	\
500 	event_set(ev, x, EV_SIGNAL|EV_PERSIST, cb, arg)
501 #define signal_del(ev)			event_del(ev)
502 #define signal_pending(ev, tv)		event_pending(ev, EV_SIGNAL, tv)
503 #define signal_initialized(ev)		((ev)->ev_flags & EVLIST_INIT)
504 
505 /**
506   Prepare an event structure to be added.
507 
508   The function event_set() prepares the event structure ev to be used in
509   future calls to event_add() and event_del().  The event will be prepared to
510   call the function specified by the fn argument with an int argument
511   indicating the file descriptor, a short argument indicating the type of
512   event, and a void * argument given in the arg argument.  The fd indicates
513   the file descriptor that should be monitored for events.  The events can be
514   either EV_READ, EV_WRITE, or both.  Indicating that an application can read
515   or write from the file descriptor respectively without blocking.
516 
517   The function fn will be called with the file descriptor that triggered the
518   event and the type of event which will be either EV_TIMEOUT, EV_SIGNAL,
519   EV_READ, or EV_WRITE.  The additional flag EV_PERSIST makes an event_add()
520   persistent until event_del() has been called.
521 
522   @param ev an event struct to be modified
523   @param fd the file descriptor to be monitored
524   @param event desired events to monitor; can be EV_READ and/or EV_WRITE
525   @param fn callback function to be invoked when the event occurs
526   @param arg an argument to be passed to the callback function
527 
528   @see event_add(), event_del(), event_once()
529 
530  */
531 void event_set(struct event *, int, short, void (*)(int, short, void *), void *);
532 
533 /**
534   Schedule a one-time event to occur.
535 
536   The function event_once() is similar to event_set().  However, it schedules
537   a callback to be called exactly once and does not require the caller to
538   prepare an event structure.
539 
540   @param fd a file descriptor to monitor
541   @param events event(s) to monitor; can be any of EV_TIMEOUT | EV_READ |
542          EV_WRITE
543   @param callback callback function to be invoked when the event occurs
544   @param arg an argument to be passed to the callback function
545   @param timeout the maximum amount of time to wait for the event, or NULL
546          to wait forever
547   @return 0 if successful, or -1 if an error occurred
548   @see event_set()
549 
550  */
551 int event_once(int, short, void (*)(int, short, void *), void *,
552     const struct timeval *);
553 
554 
555 /**
556   Schedule a one-time event (threadsafe variant)
557 
558   The function event_base_once() is similar to event_set().  However, it
559   schedules a callback to be called exactly once and does not require the
560   caller to prepare an event structure.
561 
562   @param base an event_base returned by event_init()
563   @param fd a file descriptor to monitor
564   @param events event(s) to monitor; can be any of EV_TIMEOUT | EV_READ |
565          EV_WRITE
566   @param callback callback function to be invoked when the event occurs
567   @param arg an argument to be passed to the callback function
568   @param timeout the maximum amount of time to wait for the event, or NULL
569          to wait forever
570   @return 0 if successful, or -1 if an error occurred
571   @see event_once()
572  */
573 int event_base_once(struct event_base *base, int fd, short events,
574     void (*callback)(int, short, void *), void *arg,
575     const struct timeval *timeout);
576 
577 
578 /**
579   Add an event to the set of monitored events.
580 
581   The function event_add() schedules the execution of the ev event when the
582   event specified in event_set() occurs or in at least the time specified in
583   the tv.  If tv is NULL, no timeout occurs and the function will only be
584   called if a matching event occurs on the file descriptor.  The event in the
585   ev argument must be already initialized by event_set() and may not be used
586   in calls to event_set() until it has timed out or been removed with
587   event_del().  If the event in the ev argument already has a scheduled
588   timeout, the old timeout will be replaced by the new one.
589 
590   @param ev an event struct initialized via event_set()
591   @param timeout the maximum amount of time to wait for the event, or NULL
592          to wait forever
593   @return 0 if successful, or -1 if an error occurred
594   @see event_del(), event_set()
595   */
596 int event_add(struct event *ev, const struct timeval *timeout);
597 
598 
599 /**
600   Remove an event from the set of monitored events.
601 
602   The function event_del() will cancel the event in the argument ev.  If the
603   event has already executed or has never been added the call will have no
604   effect.
605 
606   @param ev an event struct to be removed from the working set
607   @return 0 if successful, or -1 if an error occurred
608   @see event_add()
609  */
610 int event_del(struct event *);
611 
612 void event_active(struct event *, int, short);
613 
614 
615 /**
616   Checks if a specific event is pending or scheduled.
617 
618   @param ev an event struct previously passed to event_add()
619   @param event the requested event type; any of EV_TIMEOUT|EV_READ|
620          EV_WRITE|EV_SIGNAL
621   @param tv an alternate timeout (FIXME - is this true?)
622 
623   @return 1 if the event is pending, or 0 if the event has not occurred
624 
625  */
626 int event_pending(struct event *ev, short event, struct timeval *tv);
627 
628 
629 /**
630   Test if an event structure has been initialized.
631 
632   The event_initialized() macro can be used to check if an event has been
633   initialized.
634 
635   @param ev an event structure to be tested
636   @return 1 if the structure has been initialized, or 0 if it has not been
637          initialized
638  */
639 #define event_initialized(ev)		((ev)->ev_flags & EVLIST_INIT)
640 
641 
642 /**
643   Get the libevent version number.
644 
645   @return a string containing the version number of libevent
646  */
647 const char *event_get_version(void);
648 
649 
650 /**
651   Get the kernel event notification mechanism used by libevent.
652 
653   @return a string identifying the kernel event mechanism (kqueue, epoll, etc.)
654  */
655 const char *event_get_method(void);
656 
657 
658 /**
659   Set the number of different event priorities.
660 
661   By default libevent schedules all active events with the same priority.
662   However, some time it is desirable to process some events with a higher
663   priority than others.  For that reason, libevent supports strict priority
664   queues.  Active events with a lower priority are always processed before
665   events with a higher priority.
666 
667   The number of different priorities can be set initially with the
668   event_priority_init() function.  This function should be called before the
669   first call to event_dispatch().  The event_priority_set() function can be
670   used to assign a priority to an event.  By default, libevent assigns the
671   middle priority to all events unless their priority is explicitly set.
672 
673   @param npriorities the maximum number of priorities
674   @return 0 if successful, or -1 if an error occurred
675   @see event_base_priority_init(), event_priority_set()
676 
677  */
678 int	event_priority_init(int);
679 
680 
681 /**
682   Set the number of different event priorities (threadsafe variant).
683 
684   See the description of event_priority_init() for more information.
685 
686   @param eb the event_base structure returned by event_init()
687   @param npriorities the maximum number of priorities
688   @return 0 if successful, or -1 if an error occurred
689   @see event_priority_init(), event_priority_set()
690  */
691 int	event_base_priority_init(struct event_base *, int);
692 
693 
694 /**
695   Assign a priority to an event.
696 
697   @param ev an event struct
698   @param priority the new priority to be assigned
699   @return 0 if successful, or -1 if an error occurred
700   @see event_priority_init()
701   */
702 int	event_priority_set(struct event *, int);
703 
704 
705 /* Simple helpers for ASR async resolution API. */
706 
707 /* We don't want to pull asr.h here */
708 struct asr_query;
709 struct asr_result;
710 
711 struct event_asr;
712 
713 /**
714  * Schedule an async query to run in the libevent event loop, and trigger
715  * a callback when done. Returns an opaque async event handle.
716  */
717 struct event_asr * event_asr_run(struct asr_query *,
718     void (*)(struct asr_result *, void *), void *);
719 
720 /**
721  * Cancel a running async query associated to an handle.
722  */
723 void event_asr_abort(struct event_asr *);
724 
725 
726 /* These functions deal with buffering input and output */
727 
728 struct evbuffer {
729 	u_char *buffer;
730 	u_char *orig_buffer;
731 
732 	size_t misalign;
733 	size_t totallen;
734 	size_t off;
735 
736 	void (*cb)(struct evbuffer *, size_t, size_t, void *);
737 	void *cbarg;
738 };
739 
740 /* Just for error reporting - use other constants otherwise */
741 #define EVBUFFER_READ		0x01
742 #define EVBUFFER_WRITE		0x02
743 #define EVBUFFER_EOF		0x10
744 #define EVBUFFER_ERROR		0x20
745 #define EVBUFFER_TIMEOUT	0x40
746 
747 struct bufferevent;
748 typedef void (*evbuffercb)(struct bufferevent *, void *);
749 typedef void (*everrorcb)(struct bufferevent *, short what, void *);
750 
751 struct event_watermark {
752 	size_t low;
753 	size_t high;
754 };
755 
756 #ifndef EVENT_NO_STRUCT
757 struct bufferevent {
758 	struct event_base *ev_base;
759 
760 	struct event ev_read;
761 	struct event ev_write;
762 
763 	struct evbuffer *input;
764 	struct evbuffer *output;
765 
766 	struct event_watermark wm_read;
767 	struct event_watermark wm_write;
768 
769 	evbuffercb readcb;
770 	evbuffercb writecb;
771 	everrorcb errorcb;
772 	void *cbarg;
773 
774 	int timeout_read;	/* in seconds */
775 	int timeout_write;	/* in seconds */
776 
777 	short enabled;	/* events that are currently enabled */
778 };
779 #endif
780 
781 /**
782   Create a new bufferevent.
783 
784   libevent provides an abstraction on top of the regular event callbacks.
785   This abstraction is called a buffered event.  A buffered event provides
786   input and output buffers that get filled and drained automatically.  The
787   user of a buffered event no longer deals directly with the I/O, but
788   instead is reading from input and writing to output buffers.
789 
790   Once initialized, the bufferevent structure can be used repeatedly with
791   bufferevent_enable() and bufferevent_disable().
792 
793   When read enabled the bufferevent will try to read from the file descriptor
794   and call the read callback.  The write callback is executed whenever the
795   output buffer is drained below the write low watermark, which is 0 by
796   default.
797 
798   If multiple bases are in use, bufferevent_base_set() must be called before
799   enabling the bufferevent for the first time.
800 
801   @param fd the file descriptor from which data is read and written to.
802          This file descriptor is not allowed to be a pipe(2).
803   @param readcb callback to invoke when there is data to be read, or NULL if
804          no callback is desired
805   @param writecb callback to invoke when the file descriptor is ready for
806          writing, or NULL if no callback is desired
807   @param errorcb callback to invoke when there is an error on the file
808          descriptor
809   @param cbarg an argument that will be supplied to each of the callbacks
810          (readcb, writecb, and errorcb)
811   @return a pointer to a newly allocated bufferevent struct, or NULL if an
812          error occurred
813   @see bufferevent_base_set(), bufferevent_free()
814   */
815 struct bufferevent *bufferevent_new(int fd,
816     evbuffercb readcb, evbuffercb writecb, everrorcb errorcb, void *cbarg);
817 
818 
819 /**
820   Assign a bufferevent to a specific event_base.
821 
822   @param base an event_base returned by event_init()
823   @param bufev a bufferevent struct returned by bufferevent_new()
824   @return 0 if successful, or -1 if an error occurred
825   @see bufferevent_new()
826  */
827 int bufferevent_base_set(struct event_base *base, struct bufferevent *bufev);
828 
829 
830 /**
831   Assign a priority to a bufferevent.
832 
833   @param bufev a bufferevent struct
834   @param pri the priority to be assigned
835   @return 0 if successful, or -1 if an error occurred
836   */
837 int bufferevent_priority_set(struct bufferevent *bufev, int pri);
838 
839 
840 /**
841   Deallocate the storage associated with a bufferevent structure.
842 
843   @param bufev the bufferevent structure to be freed.
844   */
845 void bufferevent_free(struct bufferevent *bufev);
846 
847 
848 /**
849   Changes the callbacks for a bufferevent.
850 
851   @param bufev the bufferevent object for which to change callbacks
852   @param readcb callback to invoke when there is data to be read, or NULL if
853          no callback is desired
854   @param writecb callback to invoke when the file descriptor is ready for
855          writing, or NULL if no callback is desired
856   @param errorcb callback to invoke when there is an error on the file
857          descriptor
858   @param cbarg an argument that will be supplied to each of the callbacks
859          (readcb, writecb, and errorcb)
860   @see bufferevent_new()
861   */
862 void bufferevent_setcb(struct bufferevent *bufev,
863     evbuffercb readcb, evbuffercb writecb, everrorcb errorcb, void *cbarg);
864 
865 /**
866   Changes the file descriptor on which the bufferevent operates.
867 
868   @param bufev the bufferevent object for which to change the file descriptor
869   @param fd the file descriptor to operate on
870 */
871 void bufferevent_setfd(struct bufferevent *bufev, int fd);
872 
873 /**
874   Write data to a bufferevent buffer.
875 
876   The bufferevent_write() function can be used to write data to the file
877   descriptor.  The data is appended to the output buffer and written to the
878   descriptor automatically as it becomes available for writing.
879 
880   @param bufev the bufferevent to be written to
881   @param data a pointer to the data to be written
882   @param size the length of the data, in bytes
883   @return 0 if successful, or -1 if an error occurred
884   @see bufferevent_write_buffer()
885   */
886 int bufferevent_write(struct bufferevent *bufev,
887     const void *data, size_t size);
888 
889 
890 /**
891   Write data from an evbuffer to a bufferevent buffer.  The evbuffer is
892   being drained as a result.
893 
894   @param bufev the bufferevent to be written to
895   @param buf the evbuffer to be written
896   @return 0 if successful, or -1 if an error occurred
897   @see bufferevent_write()
898  */
899 int bufferevent_write_buffer(struct bufferevent *bufev, struct evbuffer *buf);
900 
901 
902 /**
903   Read data from a bufferevent buffer.
904 
905   The bufferevent_read() function is used to read data from the input buffer.
906 
907   @param bufev the bufferevent to be read from
908   @param data pointer to a buffer that will store the data
909   @param size the size of the data buffer, in bytes
910   @return the amount of data read, in bytes.
911  */
912 size_t bufferevent_read(struct bufferevent *bufev, void *data, size_t size);
913 
914 /**
915   Enable a bufferevent.
916 
917   @param bufev the bufferevent to be enabled
918   @param event any combination of EV_READ | EV_WRITE.
919   @return 0 if successful, or -1 if an error occurred
920   @see bufferevent_disable()
921  */
922 int bufferevent_enable(struct bufferevent *bufev, short event);
923 
924 
925 /**
926   Disable a bufferevent.
927 
928   @param bufev the bufferevent to be disabled
929   @param event any combination of EV_READ | EV_WRITE.
930   @return 0 if successful, or -1 if an error occurred
931   @see bufferevent_enable()
932  */
933 int bufferevent_disable(struct bufferevent *bufev, short event);
934 
935 
936 /**
937   Set the read and write timeout for a buffered event.
938 
939   @param bufev the bufferevent to be modified
940   @param timeout_read the read timeout
941   @param timeout_write the write timeout
942  */
943 void bufferevent_settimeout(struct bufferevent *bufev,
944     int timeout_read, int timeout_write);
945 
946 
947 /**
948   Sets the watermarks for read and write events.
949 
950   On input, a bufferevent does not invoke the user read callback unless
951   there is at least low watermark data in the buffer.   If the read buffer
952   is beyond the high watermark, the buffevent stops reading from the network.
953 
954   On output, the user write callback is invoked whenever the buffered data
955   falls below the low watermark.
956 
957   @param bufev the bufferevent to be modified
958   @param events EV_READ, EV_WRITE or both
959   @param lowmark the lower watermark to set
960   @param highmark the high watermark to set
961 */
962 
963 void bufferevent_setwatermark(struct bufferevent *bufev, short events,
964     size_t lowmark, size_t highmark);
965 
966 #define EVBUFFER_LENGTH(x)	(x)->off
967 #define EVBUFFER_DATA(x)	(x)->buffer
968 #define EVBUFFER_INPUT(x)	(x)->input
969 #define EVBUFFER_OUTPUT(x)	(x)->output
970 
971 
972 /**
973   Allocate storage for a new evbuffer.
974 
975   @return a pointer to a newly allocated evbuffer struct, or NULL if an error
976          occurred
977  */
978 struct evbuffer *evbuffer_new(void);
979 
980 
981 /**
982   Deallocate storage for an evbuffer.
983 
984   @param pointer to the evbuffer to be freed
985  */
986 void evbuffer_free(struct evbuffer *);
987 
988 
989 /**
990   Expands the available space in an event buffer.
991 
992   Expands the available space in the event buffer to at least datlen
993 
994   @param buf the event buffer to be expanded
995   @param datlen the new minimum length requirement
996   @return 0 if successful, or -1 if an error occurred
997 */
998 int evbuffer_expand(struct evbuffer *, size_t);
999 
1000 
1001 /**
1002   Append data to the end of an evbuffer.
1003 
1004   @param buf the event buffer to be appended to
1005   @param data pointer to the beginning of the data buffer
1006   @param datlen the number of bytes to be copied from the data buffer
1007  */
1008 int evbuffer_add(struct evbuffer *, const void *, size_t);
1009 
1010 
1011 
1012 /**
1013   Read data from an event buffer and drain the bytes read.
1014 
1015   @param buf the event buffer to be read from
1016   @param data the destination buffer to store the result
1017   @param datlen the maximum size of the destination buffer
1018   @return the number of bytes read
1019  */
1020 int evbuffer_remove(struct evbuffer *, void *, size_t);
1021 
1022 
1023 /**
1024  * Read a single line from an event buffer.
1025  *
1026  * Reads a line terminated by either '\r\n', '\n\r' or '\r' or '\n'.
1027  * The returned buffer needs to be freed by the caller.
1028  *
1029  * @param buffer the evbuffer to read from
1030  * @return pointer to a single line, or NULL if an error occurred
1031  */
1032 char *evbuffer_readline(struct evbuffer *);
1033 
1034 
1035 /** Used to tell evbuffer_readln what kind of line-ending to look for.
1036  */
1037 enum evbuffer_eol_style {
1038 	/** Any sequence of CR and LF characters is acceptable as an EOL. */
1039 	EVBUFFER_EOL_ANY,
1040 	/** An EOL is an LF, optionally preceded by a CR.  This style is
1041 	 * most useful for implementing text-based internet protocols. */
1042 	EVBUFFER_EOL_CRLF,
1043 	/** An EOL is a CR followed by an LF. */
1044 	EVBUFFER_EOL_CRLF_STRICT,
1045 	/** An EOL is a LF. */
1046         EVBUFFER_EOL_LF
1047 };
1048 
1049 /**
1050  * Read a single line from an event buffer.
1051  *
1052  * Reads a line terminated by an EOL as determined by the evbuffer_eol_style
1053  * argument.  Returns a newly allocated nul-terminated string; the caller must
1054  * free the returned value.  The EOL is not included in the returned string.
1055  *
1056  * @param buffer the evbuffer to read from
1057  * @param n_read_out if non-NULL, points to a size_t that is set to the
1058  *       number of characters in the returned string.  This is useful for
1059  *       strings that can contain NUL characters.
1060  * @param eol_style the style of line-ending to use.
1061  * @return pointer to a single line, or NULL if an error occurred
1062  */
1063 char *evbuffer_readln(struct evbuffer *buffer, size_t *n_read_out,
1064     enum evbuffer_eol_style eol_style);
1065 
1066 
1067 /**
1068   Move data from one evbuffer into another evbuffer.
1069 
1070   This is a destructive add.  The data from one buffer moves into
1071   the other buffer. The destination buffer is expanded as needed.
1072 
1073   @param outbuf the output buffer
1074   @param inbuf the input buffer
1075   @return 0 if successful, or -1 if an error occurred
1076  */
1077 int evbuffer_add_buffer(struct evbuffer *, struct evbuffer *);
1078 
1079 
1080 /**
1081   Append a formatted string to the end of an evbuffer.
1082 
1083   @param buf the evbuffer that will be appended to
1084   @param fmt a format string
1085   @param ... arguments that will be passed to printf(3)
1086   @return The number of bytes added if successful, or -1 if an error occurred.
1087  */
1088 int evbuffer_add_printf(struct evbuffer *, const char *fmt, ...)
1089 #ifdef __GNUC__
1090   __attribute__((format(printf, 2, 3)))
1091 #endif
1092 ;
1093 
1094 
1095 /**
1096   Append a va_list formatted string to the end of an evbuffer.
1097 
1098   @param buf the evbuffer that will be appended to
1099   @param fmt a format string
1100   @param ap a varargs va_list argument array that will be passed to vprintf(3)
1101   @return The number of bytes added if successful, or -1 if an error occurred.
1102  */
1103 int evbuffer_add_vprintf(struct evbuffer *, const char *fmt, va_list ap);
1104 
1105 
1106 /**
1107   Remove a specified number of bytes data from the beginning of an evbuffer.
1108 
1109   @param buf the evbuffer to be drained
1110   @param len the number of bytes to drain from the beginning of the buffer
1111  */
1112 void evbuffer_drain(struct evbuffer *, size_t);
1113 
1114 
1115 /**
1116   Write the contents of an evbuffer to a file descriptor.
1117 
1118   The evbuffer will be drained after the bytes have been successfully written.
1119 
1120   @param buffer the evbuffer to be written and drained
1121   @param fd the file descriptor to be written to
1122   @return the number of bytes written, or -1 if an error occurred
1123   @see evbuffer_read()
1124  */
1125 int evbuffer_write(struct evbuffer *, int);
1126 
1127 
1128 /**
1129   Read from a file descriptor and store the result in an evbuffer.
1130 
1131   @param buf the evbuffer to store the result
1132   @param fd the file descriptor to read from
1133   @param howmuch the number of bytes to be read
1134   @return the number of bytes read, or -1 if an error occurred
1135   @see evbuffer_write()
1136  */
1137 int evbuffer_read(struct evbuffer *, int, int);
1138 
1139 
1140 /**
1141   Find a string within an evbuffer.
1142 
1143   @param buffer the evbuffer to be searched
1144   @param what the string to be searched for
1145   @param len the length of the search string
1146   @return a pointer to the beginning of the search string, or NULL if the search failed.
1147  */
1148 u_char *evbuffer_find(struct evbuffer *, const u_char *, size_t);
1149 
1150 /**
1151   Set a callback to invoke when the evbuffer is modified.
1152 
1153   @param buffer the evbuffer to be monitored
1154   @param cb the callback function to invoke when the evbuffer is modified
1155   @param cbarg an argument to be provided to the callback function
1156  */
1157 void evbuffer_setcb(struct evbuffer *, void (*)(struct evbuffer *, size_t, size_t, void *), void *);
1158 
1159 /*
1160  * Marshaling tagged data - We assume that all tags are inserted in their
1161  * numeric order - so that unknown tags will always be higher than the
1162  * known ones - and we can just ignore the end of an event buffer.
1163  */
1164 
1165 void evtag_init(void);
1166 
1167 void evtag_marshal(struct evbuffer *evbuf, ev_uint32_t tag, const void *data,
1168     ev_uint32_t len);
1169 
1170 /**
1171   Encode an integer and store it in an evbuffer.
1172 
1173   We encode integer's by nibbles; the first nibble contains the number
1174   of significant nibbles - 1;  this allows us to encode up to 64-bit
1175   integers.  This function is byte-order independent.
1176 
1177   @param evbuf evbuffer to store the encoded number
1178   @param number a 32-bit integer
1179  */
1180 void encode_int(struct evbuffer *evbuf, ev_uint32_t number);
1181 
1182 void evtag_marshal_int(struct evbuffer *evbuf, ev_uint32_t tag,
1183     ev_uint32_t integer);
1184 
1185 void evtag_marshal_string(struct evbuffer *buf, ev_uint32_t tag,
1186     const char *string);
1187 
1188 void evtag_marshal_timeval(struct evbuffer *evbuf, ev_uint32_t tag,
1189     struct timeval *tv);
1190 
1191 int evtag_unmarshal(struct evbuffer *src, ev_uint32_t *ptag,
1192     struct evbuffer *dst);
1193 int evtag_peek(struct evbuffer *evbuf, ev_uint32_t *ptag);
1194 int evtag_peek_length(struct evbuffer *evbuf, ev_uint32_t *plength);
1195 int evtag_payload_length(struct evbuffer *evbuf, ev_uint32_t *plength);
1196 int evtag_consume(struct evbuffer *evbuf);
1197 
1198 int evtag_unmarshal_int(struct evbuffer *evbuf, ev_uint32_t need_tag,
1199     ev_uint32_t *pinteger);
1200 
1201 int evtag_unmarshal_fixed(struct evbuffer *src, ev_uint32_t need_tag,
1202     void *data, size_t len);
1203 
1204 int evtag_unmarshal_string(struct evbuffer *evbuf, ev_uint32_t need_tag,
1205     char **pstring);
1206 
1207 int evtag_unmarshal_timeval(struct evbuffer *evbuf, ev_uint32_t need_tag,
1208     struct timeval *ptv);
1209 
1210 #define _EVENT_VERSION "1.4.15-stable"
1211 
1212 #ifdef __cplusplus
1213 }
1214 #endif
1215 
1216 #endif /* _EVENT_H_ */
1217