• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2000-2007 Niels Provos <provos@citi.umich.edu>
3  * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. The name of the author may not be used to endorse or promote products
14  *    derived from this software without specific prior written permission.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
17  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
18  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
19  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
20  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
21  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
22  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
23  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
25  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26  */
27 #ifndef _EVENT2_EVENT_H_
28 #define _EVENT2_EVENT_H_
29 
30 /**
31    @mainpage
32 
33   @section intro Introduction
34 
35   Libevent is an event notification library for developing scalable network
36   servers.  The Libevent API provides a mechanism to execute a callback
37   function when a specific event occurs on a file descriptor or after a
38   timeout has been reached. Furthermore, Libevent also support callbacks due
39   to signals or regular timeouts.
40 
41   Libevent is meant to replace the event loop found in event driven network
42   servers. An application just needs to call event_dispatch() and then add or
43   remove events dynamically without having to change the event loop.
44 
45 
46   Currently, Libevent supports /dev/poll, kqueue(2), select(2), poll(2),
47   epoll(4), and evports. The internal event mechanism is completely
48   independent of the exposed event API, and a simple update of Libevent can
49   provide new functionality without having to redesign the applications. As a
50   result, Libevent allows for portable application development and provides
51   the most scalable event notification mechanism available on an operating
52   system.  Libevent can also be used for multithreaded programs.  Libevent
53   should compile on Linux, *BSD, Mac OS X, Solaris and, Windows.
54 
55   @section usage Standard usage
56 
57   Every program that uses Libevent must inclurde the <event2/event.h>
58   header, and pass the -levent flag to the linker.  (You can instead link
59   -levent_core if you only want the main event and buffered IO-based code,
60   and don't want to link any protocol code.)
61 
62   @section setup Library setup
63 
64   Before you call any other Libevent functions, you need to set up the
65   library.  If you're going to use Libevent from multiple threads in a
66   multithreaded application, you need to initialize thread support --
67   typically by using evthread_use_pthreads() or
68   evthread_use_windows_threads().  See <event2/thread.h> for more
69   information.
70 
71   This is also the point where you can replace Libevent's memory
72   management functions with event_set_mem_functions, and enable debug mode
73   with event_enable_debug_mode().
74 
75   @section base Creating an event base
76 
77   Next, you need to create an event_base structure, using event_base_new()
78   or event_base_new_with_config().  The event_base is responsible for
79   keeping track of which events are "pending" (that is to say, being
80   watched to see if they become active) and which events are "active".
81   Every event is associated with a single event_base.
82 
83   @section event Event notification
84 
85   For each file descriptor that you wish to monitor, you must create an
86   event structure with event_new().  (You may also declare an event
87   structure and call event_assign() to initialize the members of the
88   structure.)  To enable notification, you add the structure to the list
89   of monitored events by calling event_add().  The event structure must
90   remain allocated as long as it is active, so it should generally be
91   allocated on the heap.
92 
93   @section loop Dispaching evets.
94 
95   Finally, you call event_base_dispatch() to loop and dispatch events.
96   You can also use event_base_loop() for more fine-grained control.
97 
98   Currently, only one thread can be dispatching a given event_base at a
99   time.  If you want to run events in multiple threads at once, you can
100   either have a single event_base whose events add work to a work queue,
101   or you can create multiple event_base objects.
102 
103   @section bufferevent I/O Buffers
104 
105   Libevent provides a buffered I/O abstraction on top of the regular event
106   callbacks. This abstraction is called a bufferevent. A bufferevent
107   provides input and output buffers that get filled and drained
108   automatically. The user of a buffered event no longer deals directly
109   with the I/O, but instead is reading from input and writing to output
110   buffers.
111 
112   Once initialized via bufferevent_socket_new(), the bufferevent structure
113   can be used repeatedly with bufferevent_enable() and
114   bufferevent_disable().  Instead of reading and writing directly to a
115   socket, you would call bufferevent_read() and bufferevent_write().
116 
117   When read enabled the bufferevent will try to read from the file descriptor
118   and call the read callback. The write callback is executed whenever the
119   output buffer is drained below the write low watermark, which is 0 by
120   default.
121 
122   See <event2/bufferevent*.h> for more information.
123 
124   @section timers Timers
125 
126   Libevent can also be used to create timers that invoke a callback after a
127   certain amount of time has expired. The evtimer_new() function returns
128   an event struct to use as a timer. To activate the timer, call
129   evtimer_add(). Timers can be deactivated by calling evtimer_del().
130 
131   @section evdns Asynchronous DNS resolution
132 
133   Libevent provides an asynchronous DNS resolver that should be used instead
134   of the standard DNS resolver functions.  See the <event2/dns.h>
135   functions for more detail.
136 
137   @section evhttp Event-driven HTTP servers
138 
139   Libevent provides a very simple event-driven HTTP server that can be
140   embedded in your program and used to service HTTP requests.
141 
142   To use this capability, you need to include the <event2/http.h> header in your
143   program.  See that header for more information.
144 
145   @section evrpc A framework for RPC servers and clients
146 
147   Libevent provides a framework for creating RPC servers and clients.  It
148   takes care of marshaling and unmarshaling all data structures.
149 
150   @section api API Reference
151 
152   To browse the complete documentation of the libevent API, click on any of
153   the following links.
154 
155   event2/event.h
156   The primary libevent header
157 
158   event2/thread.h
159   Functions for use by multithreaded programs
160 
161   event2/buffer.h and event2/bufferevent.h
162   Buffer management for network reading and writing
163 
164   event2/util.h
165   Utility functions for portable nonblocking network code
166 
167   event2/dns.h
168   Asynchronous DNS resolution
169 
170   event2/http.h
171   An embedded libevent-based HTTP server
172 
173   event2/rpc.h
174   A framework for creating RPC servers and clients
175 
176  */
177 
178 /** @file event2/event.h
179 
180   Core functions for waiting for and receiving events, and using event bases.
181 */
182 
183 #ifdef __cplusplus
184 extern "C" {
185 #endif
186 
187 #include <event2/event-config.h>
188 #ifdef _EVENT_HAVE_SYS_TYPES_H
189 #include <sys/types.h>
190 #endif
191 #ifdef _EVENT_HAVE_SYS_TIME_H
192 #include <sys/time.h>
193 #endif
194 
195 #include <stdio.h>
196 
197 /* For int types. */
198 #include <event2/util.h>
199 
200 /**
201  * Structure to hold information and state for a Libevent dispatch loop.
202  *
203  * The event_base lies at the center of Libevent; every application will
204  * have one.  It keeps track of all pending and active events, and
205  * notifies your application of the active ones.
206  *
207  * This is an opaque structure; you can allocate one using
208  * event_base_new() or event_base_new_with_config().
209  *
210  * @see event_base_new(), event_base_free(), event_base_loop(),
211  *    event_base_new_with_config()
212  */
213 struct event_base
214 #ifdef _EVENT_IN_DOXYGEN
215 {/*Empty body so that doxygen will generate documentation here.*/}
216 #endif
217 ;
218 
219 /**
220  * @struct event
221  *
222  * Structure to represent a single event.
223  *
224  * An event can have some underlying condition it represents: a socket
225  * becoming readable or writeable (or both), or a signal becoming raised.
226  * (An event that represents no underlying condition is still useful: you
227  * can use one to implement a timer, or to communicate between threads.)
228  *
229  * Generally, you can create events with event_new(), then make them
230  * pending with event_add().  As your event_base runs, it will run the
231  * callbacks of an events whose conditions are triggered.  When you
232  * longer want the event, free it with event_free().
233  *
234  * In more depth:
235  *
236  * An event may be "pending" (one whose condition we are watching),
237  * "active" (one whose condition has triggered and whose callback is about
238  * to run), neither, or both.  Events come into existence via
239  * event_assign() or event_new(), and are then neither active nor pending.
240  *
241  * To make an event pending, pass it to event_add().  When doing so, you
242  * can also set a timeout for the event.
243  *
244  * Events become active during an event_base_loop() call when either their
245  * condition has triggered, or when their timeout has elapsed.  You can
246  * also activate an event manually using event_active().  The even_base
247  * loop will run the callbacks of active events; after it has done so, it
248  * marks them as no longer active.
249  *
250  * You can make an event non-pending by passing it to event_del().  This
251  * also makes the event non-active.
252  *
253  * Events can be "persistent" or "non-persistent".  A non-persistent event
254  * becomes non-pending as soon as it is triggered: thus, it only runs at
255  * most once per call to event_add().  A persistent event remains pending
256  * even when it becomes active: you'll need to event_del() it manually in
257  * order to make it non-pending.  When a persistent event with a timeout
258  * becomes active, its timeout is reset: this means you can use persistent
259  * events to implement periodic timeouts.
260  *
261  * This should be treated as an opaque structure; you should never read or
262  * write any of its fields directly.  For backward compatibility with old
263  * code, it is defined in the event2/event_struct.h header; including this
264  * header may make your code incompatible with other versions of Libevent.
265  *
266  * @see event_new(), event_free(), event_assign(), event_get_assignment(),
267  *    event_add(), event_del(), event_active(), event_pending(),
268  *    event_get_fd(), event_get_base(), event_get_events(),
269  *    event_get_callback(), event_get_callback_arg(),
270  *    event_priority_set()
271  */
272 struct event
273 #ifdef _EVENT_IN_DOXYGEN
274 {/*Empty body so that doxygen will generate documentation here.*/}
275 #endif
276 ;
277 
278 /**
279  * Configuration for an event_base.
280  *
281  * There are many options that can be used to alter the behavior and
282  * implementation of an event_base.  To avoid having to pass them all in a
283  * complex many-argument constructor, we provide an abstract data type
284  * wrhere you set up configation information before passing it to
285  * event_base_new_with_config().
286  *
287  * @see event_config_new(), event_config_free(), event_base_new_with_config(),
288  *   event_config_avoid_method(), event_config_require_features(),
289  *   event_config_set_flag(), event_config_set_num_cpus_hint()
290  */
291 struct event_config
292 #ifdef _EVENT_IN_DOXYGEN
293 {/*Empty body so that doxygen will generate documentation here.*/}
294 #endif
295 ;
296 
297 /**
298  * Enable some relatively expensive debugging checks in Libevent that
299  * would normally be turned off.  Generally, these checks cause code that
300  * would otherwise crash mysteriously to fail earlier with an assertion
301  * failure.  Note that this method MUST be called before any events or
302  * event_bases have been created.
303  *
304  * Debug mode can currently catch the following errors:
305  *    An event is re-assigned while it is added
306  *    Any function is called on a non-assigned event
307  *
308  * Note that debugging mode uses memory to track every event that has been
309  * initialized (via event_assign, event_set, or event_new) but not yet
310  * released (via event_free or event_debug_unassign).  If you want to use
311  * debug mode, and you find yourself running out of memory, you will need
312  * to use event_debug_unassign to explicitly stop tracking events that
313  * are no longer considered set-up.
314  *
315  * @see event_debug_unassign()
316  */
317 void event_enable_debug_mode(void);
318 
319 /**
320  * When debugging mode is enabled, informs Libevent that an event should no
321  * longer be considered as assigned. When debugging mode is not enabled, does
322  * nothing.
323  *
324  * This function must only be called on a non-added event.
325  *
326  * @see event_enable_debug_mode()
327  */
328 void event_debug_unassign(struct event *);
329 
330 /**
331  * Create and return a new event_base to use with the rest of Libevent.
332  *
333  * @return a new event_base on success, or NULL on failure.
334  *
335  * @see event_base_free(), event_base_new_with_config()
336  */
337 struct event_base *event_base_new(void);
338 
339 /**
340   Reinitialize the event base after a fork
341 
342   Some event mechanisms do not survive across fork.   The event base needs
343   to be reinitialized with the event_reinit() function.
344 
345   @param base the event base that needs to be re-initialized
346   @return 0 if successful, or -1 if some events could not be re-added.
347   @see event_base_new()
348 */
349 int event_reinit(struct event_base *base);
350 
351 /**
352    Event dispatching loop
353 
354   This loop will run the event base until either there are no more pending or
355   active, or until something calls event_base_loopbreak() or
356   event_base_loopexit().
357 
358   @param base the event_base structure returned by event_base_new() or
359      event_base_new_with_config()
360   @return 0 if successful, -1 if an error occurred, or 1 if we exited because
361      no events were pending or active.
362   @see event_base_loop()
363  */
364 int event_base_dispatch(struct event_base *);
365 
366 /**
367  Get the kernel event notification mechanism used by Libevent.
368 
369  @param eb the event_base structure returned by event_base_new()
370  @return a string identifying the kernel event mechanism (kqueue, epoll, etc.)
371  */
372 const char *event_base_get_method(const struct event_base *);
373 
374 /**
375    Gets all event notification mechanisms supported by Libevent.
376 
377    This functions returns the event mechanism in order preferred by
378    Libevent.  Note that this list will include all backends that
379    Libevent has compiled-in support for, and will not necessarily check
380    your OS to see whether it has the required resources.
381 
382    @return an array with pointers to the names of support methods.
383      The end of the array is indicated by a NULL pointer.  If an
384      error is encountered NULL is returned.
385 */
386 const char **event_get_supported_methods(void);
387 
388 /**
389    Allocates a new event configuration object.
390 
391    The event configuration object can be used to change the behavior of
392    an event base.
393 
394    @return an event_config object that can be used to store configuration, or
395      NULL if an error is encountered.
396    @see event_base_new_with_config(), event_config_free(), event_config
397 */
398 struct event_config *event_config_new(void);
399 
400 /**
401    Deallocates all memory associated with an event configuration object
402 
403    @param cfg the event configuration object to be freed.
404 */
405 void event_config_free(struct event_config *cfg);
406 
407 /**
408    Enters an event method that should be avoided into the configuration.
409 
410    This can be used to avoid event mechanisms that do not support certain
411    file descriptor types, or for debugging to avoid certain event
412    mechanisms.  An application can make use of multiple event bases to
413    accommodate incompatible file descriptor types.
414 
415    @param cfg the event configuration object
416    @param method the name of the event method to avoid
417    @return 0 on success, -1 on failure.
418 */
419 int event_config_avoid_method(struct event_config *cfg, const char *method);
420 
421 /**
422    A flag used to describe which features an event_base (must) provide.
423 
424    Because of OS limitations, not every Libevent backend supports every
425    possible feature.  You can use this type with
426    event_config_require_features() to tell Libevent to only proceed if your
427    event_base implements a given feature, and you can receive this type from
428    event_base_get_features() to see which features are available.
429 */
430 enum event_method_feature {
431     /** Require an event method that allows edge-triggered events with EV_ET. */
432     EV_FEATURE_ET = 0x01,
433     /** Require an event method where having one event triggered among
434      * many is [approximately] an O(1) operation. This excludes (for
435      * example) select and poll, which are approximately O(N) for N
436      * equal to the total number of possible events. */
437     EV_FEATURE_O1 = 0x02,
438     /** Require an event method that allows file descriptors as well as
439      * sockets. */
440     EV_FEATURE_FDS = 0x04
441 };
442 
443 /**
444    A flag passed to event_config_set_flag().
445 
446     These flags change the behavior of an allocated event_base.
447 
448     @see event_config_set_flag(), event_base_new_with_config(),
449        event_method_feature
450  */
451 enum event_base_config_flag {
452 	/** Do not allocate a lock for the event base, even if we have
453 	    locking set up. */
454 	EVENT_BASE_FLAG_NOLOCK = 0x01,
455 	/** Do not check the EVENT_* environment variables when configuring
456 	    an event_base  */
457 	EVENT_BASE_FLAG_IGNORE_ENV = 0x02,
458 	/** Windows only: enable the IOCP dispatcher at startup
459 
460 	    If this flag is set then bufferevent_socket_new() and
461 	    evconn_listener_new() will use IOCP-backed implementations
462 	    instead of the usual select-based one on Windows.
463 	 */
464 	EVENT_BASE_FLAG_STARTUP_IOCP = 0x04,
465 	/** Instead of checking the current time every time the event loop is
466 	    ready to run timeout callbacks, check after each timeout callback.
467 	 */
468 	EVENT_BASE_FLAG_NO_CACHE_TIME = 0x08,
469 
470 	/** If we are using the epoll backend, this flag says that it is
471 	    safe to use Libevent's internal change-list code to batch up
472 	    adds and deletes in order to try to do as few syscalls as
473 	    possible.  Setting this flag can make your code run faster, but
474 	    it may trigger a Linux bug: it is not safe to use this flag
475 	    if you have any fds cloned by dup() or its variants.  Doing so
476 	    will produce strange and hard-to-diagnose bugs.
477 
478 	    This flag can also be activated by settnig the
479 	    EVENT_EPOLL_USE_CHANGELIST environment variable.
480 
481 	    This flag has no effect if you wind up using a backend other than
482 	    epoll.
483 	 */
484 	EVENT_BASE_FLAG_EPOLL_USE_CHANGELIST = 0x10
485 };
486 
487 /**
488    Return a bitmask of the features implemented by an event base.  This
489    will be a bitwise OR of one or more of the values of
490    event_method_feature
491 
492    @see event_method_feature
493  */
494 int event_base_get_features(const struct event_base *base);
495 
496 /**
497    Enters a required event method feature that the application demands.
498 
499    Note that not every feature or combination of features is supported
500    on every platform.  Code that requests features should be prepared
501    to handle the case where event_base_new_with_config() returns NULL, as in:
502    <pre>
503      event_config_require_features(cfg, EV_FEATURE_ET);
504      base = event_base_new_with_config(cfg);
505      if (base == NULL) {
506        // We can't get edge-triggered behavior here.
507        event_config_require_features(cfg, 0);
508        base = event_base_new_with_config(cfg);
509      }
510    </pre>
511 
512    @param cfg the event configuration object
513    @param feature a bitfield of one or more event_method_feature values.
514           Replaces values from previous calls to this function.
515    @return 0 on success, -1 on failure.
516    @see event_method_feature, event_base_new_with_config()
517 */
518 int event_config_require_features(struct event_config *cfg, int feature);
519 
520 /**
521  * Sets one or more flags to configure what parts of the eventual event_base
522  * will be initialized, and how they'll work.
523  *
524  * @see event_base_config_flags, event_base_new_with_config()
525  **/
526 int event_config_set_flag(struct event_config *cfg, int flag);
527 
528 /**
529  * Records a hint for the number of CPUs in the system. This is used for
530  * tuning thread pools, etc, for optimal performance.  In Libevent 2.0,
531  * it is only on Windows, and only when IOCP is in use.
532  *
533  * @param cfg the event configuration object
534  * @param cpus the number of cpus
535  * @return 0 on success, -1 on failure.
536  */
537 int event_config_set_num_cpus_hint(struct event_config *cfg, int cpus);
538 
539 /**
540   Initialize the event API.
541 
542   Use event_base_new_with_config() to initialize a new event base, taking
543   the specified configuration under consideration.  The configuration object
544   can currently be used to avoid certain event notification mechanisms.
545 
546   @param cfg the event configuration object
547   @return an initialized event_base that can be used to registering events,
548      or NULL if no event base can be created with the requested event_config.
549   @see event_base_new(), event_base_free(), event_init(), event_assign()
550 */
551 struct event_base *event_base_new_with_config(const struct event_config *);
552 
553 /**
554   Deallocate all memory associated with an event_base, and free the base.
555 
556   Note that this function will not close any fds or free any memory passed
557   to event_new as the argument to callback.
558 
559   @param eb an event_base to be freed
560  */
561 void event_base_free(struct event_base *);
562 
563 /** @name Log severities
564  */
565 /**@{*/
566 #define EVENT_LOG_DEBUG 0
567 #define EVENT_LOG_MSG   1
568 #define EVENT_LOG_WARN  2
569 #define EVENT_LOG_ERR   3
570 /**@}*/
571 
572 /* Obsolete names: these are deprecated, but older programs might use them.
573  * They violate the reserved-identifier namespace. */
574 #define _EVENT_LOG_DEBUG EVENT_LOG_DEBUG
575 #define _EVENT_LOG_MSG EVENT_LOG_MSG
576 #define _EVENT_LOG_WARN EVENT_LOG_WARN
577 #define _EVENT_LOG_ERR EVENT_LOG_ERR
578 
579 /**
580   A callback function used to intercept Libevent's log messages.
581 
582   @see event_set_log_callback
583  */
584 typedef void (*event_log_cb)(int severity, const char *msg);
585 /**
586   Redirect Libevent's log messages.
587 
588   @param cb a function taking two arguments: an integer severity between
589      _EVENT_LOG_DEBUG and _EVENT_LOG_ERR, and a string.  If cb is NULL,
590 	 then the default log is used.
591 
592   NOTE: The function you provide *must not* call any other libevent
593   functionality.  Doing so can produce undefined behavior.
594   */
595 void event_set_log_callback(event_log_cb cb);
596 
597 /**
598    A function to be called if Libevent encounters a fatal internal error.
599 
600    @see event_set_fatal_callback
601  */
602 typedef void (*event_fatal_cb)(int err);
603 
604 /**
605  Override Libevent's behavior in the event of a fatal internal error.
606 
607  By default, Libevent will call exit(1) if a programming error makes it
608  impossible to continue correct operation.  This function allows you to supply
609  another callback instead.  Note that if the function is ever invoked,
610  something is wrong with your program, or with Libevent: any subsequent calls
611  to Libevent may result in undefined behavior.
612 
613  Libevent will (almost) always log an _EVENT_LOG_ERR message before calling
614  this function; look at the last log message to see why Libevent has died.
615  */
616 void event_set_fatal_callback(event_fatal_cb cb);
617 
618 /**
619   Associate a different event base with an event.
620 
621   The event to be associated must not be currently active or pending.
622 
623   @param eb the event base
624   @param ev the event
625   @return 0 on success, -1 on failure.
626  */
627 int event_base_set(struct event_base *, struct event *);
628 
629 /** @name Loop flags
630 
631     These flags control the behavior of event_base_loop().
632  */
633 /**@{*/
634 /** Block until we have an active event, then exit once all active events
635  * have had their callbacks run. */
636 #define EVLOOP_ONCE	0x01
637 /** Do not block: see which events are ready now, run the callbacks
638  * of the highest-priority ones, then exit. */
639 #define EVLOOP_NONBLOCK	0x02
640 /**@}*/
641 
642 /**
643   Wait for events to become active, and run their callbacks.
644 
645   This is a more flexible version of event_base_dispatch().
646 
647   By default, this loop will run the event base until either there are no more
648   pending or active events, or until something calls event_base_loopbreak() or
649   event_base_loopexit().  You can override this behavior with the 'flags'
650   argument.
651 
652   @param eb the event_base structure returned by event_base_new() or
653      event_base_new_with_config()
654   @param flags any combination of EVLOOP_ONCE | EVLOOP_NONBLOCK
655   @return 0 if successful, -1 if an error occurred, or 1 if we exited because
656      no events were pending or active.
657   @see event_base_loopexit(), event_base_dispatch(), EVLOOP_ONCE,
658      EVLOOP_NONBLOCK
659   */
660 int event_base_loop(struct event_base *, int);
661 
662 /**
663   Exit the event loop after the specified time
664 
665   The next event_base_loop() iteration after the given timer expires will
666   complete normally (handling all queued events) then exit without
667   blocking for events again.
668 
669   Subsequent invocations of event_base_loop() will proceed normally.
670 
671   @param eb the event_base structure returned by event_init()
672   @param tv the amount of time after which the loop should terminate,
673     or NULL to exit after running all currently active events.
674   @return 0 if successful, or -1 if an error occurred
675   @see event_base_loopbreak()
676  */
677 int event_base_loopexit(struct event_base *, const struct timeval *);
678 
679 /**
680   Abort the active event_base_loop() immediately.
681 
682   event_base_loop() will abort the loop after the next event is completed;
683   event_base_loopbreak() is typically invoked from this event's callback.
684   This behavior is analogous to the "break;" statement.
685 
686   Subsequent invocations of event_loop() will proceed normally.
687 
688   @param eb the event_base structure returned by event_init()
689   @return 0 if successful, or -1 if an error occurred
690   @see event_base_loopexit()
691  */
692 int event_base_loopbreak(struct event_base *);
693 
694 /**
695   Checks if the event loop was told to exit by event_loopexit().
696 
697   This function will return true for an event_base at every point after
698   event_loopexit() is called, until the event loop is next entered.
699 
700   @param eb the event_base structure returned by event_init()
701   @return true if event_base_loopexit() was called on this event base,
702     or 0 otherwise
703   @see event_base_loopexit()
704   @see event_base_got_break()
705  */
706 int event_base_got_exit(struct event_base *);
707 
708 /**
709   Checks if the event loop was told to abort immediately by event_loopbreak().
710 
711   This function will return true for an event_base at every point after
712   event_loopbreak() is called, until the event loop is next entered.
713 
714   @param eb the event_base structure returned by event_init()
715   @return true if event_base_loopbreak() was called on this event base,
716     or 0 otherwise
717   @see event_base_loopbreak()
718   @see event_base_got_exit()
719  */
720 int event_base_got_break(struct event_base *);
721 
722 /**
723  * @name event flags
724  *
725  * Flags to pass to event_new(), event_assign(), event_pending(), and
726  * anything else with an argument of the form "short events"
727  */
728 /**@{*/
729 /** Indicates that a timeout has occurred.  It's not necessary to pass
730  * this flag to event_for new()/event_assign() to get a timeout. */
731 #define EV_TIMEOUT	0x01
732 /** Wait for a socket or FD to become readable */
733 #define EV_READ		0x02
734 /** Wait for a socket or FD to become writeable */
735 #define EV_WRITE	0x04
736 /** Wait for a POSIX signal to be raised*/
737 #define EV_SIGNAL	0x08
738 /**
739  * Persistent event: won't get removed automatically when activated.
740  *
741  * When a persistent event with a timeout becomes activated, its timeout
742  * is reset to 0.
743  */
744 #define EV_PERSIST	0x10
745 /** Select edge-triggered behavior, if supported by the backend. */
746 #define EV_ET       0x20
747 /**@}*/
748 
749 /**
750    @name evtimer_* macros
751 
752     Aliases for working with one-shot timer events */
753 /**@{*/
754 #define evtimer_assign(ev, b, cb, arg) \
755 	event_assign((ev), (b), -1, 0, (cb), (arg))
756 #define evtimer_new(b, cb, arg)	       event_new((b), -1, 0, (cb), (arg))
757 #define evtimer_add(ev, tv)		event_add((ev), (tv))
758 #define evtimer_del(ev)			event_del(ev)
759 #define evtimer_pending(ev, tv)		event_pending((ev), EV_TIMEOUT, (tv))
760 #define evtimer_initialized(ev)		event_initialized(ev)
761 /**@}*/
762 
763 /**
764    @name evsignal_* macros
765 
766    Aliases for working with signal events
767  */
768 /**@{*/
769 #define evsignal_add(ev, tv)		event_add((ev), (tv))
770 #define evsignal_assign(ev, b, x, cb, arg)			\
771 	event_assign((ev), (b), (x), EV_SIGNAL|EV_PERSIST, cb, (arg))
772 #define evsignal_new(b, x, cb, arg)				\
773 	event_new((b), (x), EV_SIGNAL|EV_PERSIST, (cb), (arg))
774 #define evsignal_del(ev)		event_del(ev)
775 #define evsignal_pending(ev, tv)	event_pending((ev), EV_SIGNAL, (tv))
776 #define evsignal_initialized(ev)	event_initialized(ev)
777 /**@}*/
778 
779 /**
780    A callback function for an event.
781 
782    It receives three arguments:
783 
784    @param fd An fd or signal
785    @param events One or more EV_* flags
786    @param arg A user-supplied argument.
787 
788    @see event_new()
789  */
790 typedef void (*event_callback_fn)(evutil_socket_t, short, void *);
791 
792 /**
793   Allocate and asssign a new event structure, ready to be added.
794 
795   The function event_new() returns a new event that can be used in
796   future calls to event_add() and event_del().  The fd and events
797   arguments determine which conditions will trigger the event; the
798   callback and callback_arg arguments tell Libevent what to do when the
799   event becomes active.
800 
801   If events contains one of EV_READ, EV_WRITE, or EV_READ|EV_WRITE, then
802   fd is a file descriptor or socket that should get monitored for
803   readiness to read, readiness to write, or readiness for either operation
804   (respectively).  If events contains EV_SIGNAL, then fd is a signal
805   number to wait for.  If events contains none of those flags, then the
806   event can be triggered only by a timeout or by manual activation with
807   event_active(): In this case, fd must be -1.
808 
809   The EV_PERSIST flag can also be passed in the events argument: it makes
810   event_add() persistent until event_del() is called.
811 
812   The EV_ET flag is compatible with EV_READ and EV_WRITE, and supported
813   only by certain backends.  It tells Libevent to use edge-triggered
814   events.
815 
816   The EV_TIMEOUT flag has no effect here.
817 
818   It is okay to have multiple events all listening on the same fds; but
819   they must either all be edge-triggered, or all not be edge triggerd.
820 
821   When the event becomes active, the event loop will run the provided
822   callbuck function, with three arguments.  The first will be the provided
823   fd value.  The second will be a bitfield of the events that triggered:
824   EV_READ, EV_WRITE, or EV_SIGNAL.  Here the EV_TIMEOUT flag indicates
825   that a timeout occurred, and EV_ET indicates that an edge-triggered
826   event occurred.  The third event will be the callback_arg pointer that
827   you provide.
828 
829   @param base the event base to which the event should be attached.
830   @param fd the file descriptor or signal to be monitored, or -1.
831   @param events desired events to monitor: bitfield of EV_READ, EV_WRITE,
832       EV_SIGNAL, EV_PERSIST, EV_ET.
833   @param callback callback function to be invoked when the event occurs
834   @param callback_arg an argument to be passed to the callback function
835 
836   @return a newly allocated struct event that must later be freed with
837     event_free().
838   @see event_free(), event_add(), event_del(), event_assign()
839  */
840 struct event *event_new(struct event_base *, evutil_socket_t, short, event_callback_fn, void *);
841 
842 
843 /**
844   Prepare a new, already-allocated event structure to be added.
845 
846   The function event_assign() prepares the event structure ev to be used
847   in future calls to event_add() and event_del().  Unlike event_new(), it
848   doesn't allocate memory itself: it requires that you have already
849   allocated a struct event, probably on the heap.  Doing this will
850   typically make your code depend on the size of the event structure, and
851   thereby create incompatibility with future versions of Libevent.
852 
853   The easiest way to avoid this problem is just to use event_new() and
854   event_free() instead.
855 
856   A slightly harder way to future-proof your code is to use
857   event_get_struct_event_size() to determine the required size of an event
858   at runtime.
859 
860   Note that it is NOT safe to call this function on an event that is
861   active or pending.  Doing so WILL corrupt internal data structures in
862   Libevent, and lead to strange, hard-to-diagnose bugs.  You _can_ use
863   event_assign to change an existing event, but only if it is not active
864   or pending!
865 
866   The arguments for this function, and the behavior of the events that it
867   makes, are as for event_new().
868 
869   @param ev an event struct to be modified
870   @param base the event base to which ev should be attached.
871   @param fd the file descriptor to be monitored
872   @param events desired events to monitor; can be EV_READ and/or EV_WRITE
873   @param callback callback function to be invoked when the event occurs
874   @param callback_arg an argument to be passed to the callback function
875 
876   @return 0 if success, or -1 on invalid arguments.
877 
878   @see event_new(), event_add(), event_del(), event_base_once(),
879     event_get_struct_event_size()
880   */
881 int event_assign(struct event *, struct event_base *, evutil_socket_t, short, event_callback_fn, void *);
882 
883 /**
884    Deallocate a struct event * returned by event_new().
885 
886    If the event is pending or active, first make it non-pending and
887    non-active.
888  */
889 void event_free(struct event *);
890 
891 /**
892   Schedule a one-time event
893 
894   The function event_base_once() is similar to event_set().  However, it
895   schedules a callback to be called exactly once, and does not require the
896   caller to prepare an event structure.
897 
898   Note that in Libevent 2.0 and earlier, if the event is never triggered,
899   the internal memory used to hold it will never be freed.  This may be
900   fixed in a later version of Libevent.
901 
902   @param base an event_base
903   @param fd a file descriptor to monitor, or -1 for no fd.
904   @param events event(s) to monitor; can be any of EV_READ |
905          EV_WRITE, or EV_TIMEOUT
906   @param callback callback function to be invoked when the event occurs
907   @param arg an argument to be passed to the callback function
908   @param timeout the maximum amount of time to wait for the event. NULL
909          makes an EV_READ/EV_WRITE event make forever; NULL makes an
910         EV_TIMEOUT event succees immediately.
911   @return 0 if successful, or -1 if an error occurred
912  */
913 int event_base_once(struct event_base *, evutil_socket_t, short, event_callback_fn, void *, const struct timeval *);
914 
915 /**
916   Add an event to the set of pending events.
917 
918   The function event_add() schedules the execution of the ev event when the
919   event specified in event_assign()/event_new() occurs, or when the time
920   specified in timeout has elapesed.  If atimeout is NULL, no timeout
921   occurs and the function will only be
922   called if a matching event occurs.  The event in the
923   ev argument must be already initialized by event_assign() or event_new()
924   and may not be used
925   in calls to event_assign() until it is no longer pending.
926 
927   If the event in the ev argument already has a scheduled timeout, calling
928   event_add() replaces the old timeout with the new one, or clears the old
929   timeout if the timeout argument is NULL.
930 
931   @param ev an event struct initialized via event_set()
932   @param timeout the maximum amount of time to wait for the event, or NULL
933          to wait forever
934   @return 0 if successful, or -1 if an error occurred
935   @see event_del(), event_assign(), event_new()
936   */
937 int event_add(struct event *ev, const struct timeval *timeout);
938 
939 /**
940   Remove an event from the set of monitored events.
941 
942   The function event_del() will cancel the event in the argument ev.  If the
943   event has already executed or has never been added the call will have no
944   effect.
945 
946   @param ev an event struct to be removed from the working set
947   @return 0 if successful, or -1 if an error occurred
948   @see event_add()
949  */
950 int event_del(struct event *);
951 
952 
953 /**
954   Make an event active.
955 
956   You can use this function on a pending or a non-pending event to make it
957   active, so that its callback will be run by event_base_dispatch() or
958   event_base_loop().
959 
960   One common use in multithreaded programs is to wake the thread running
961   event_base_loop() from another thread.
962 
963   @param ev an event to make active.
964   @param res a set of flags to pass to the event's callback.
965   @param ncalls an obsolete argument: this is ignored.
966  **/
967 void event_active(struct event *ev, int res, short ncalls);
968 
969 /**
970   Checks if a specific event is pending or scheduled.
971 
972   @param ev an event struct previously passed to event_add()
973   @param events the requested event type; any of EV_TIMEOUT|EV_READ|
974          EV_WRITE|EV_SIGNAL
975   @param tv if this field is not NULL, and the event has a timeout,
976          this field is set to hold the time at which the timeout will
977 	 expire.
978 
979   @return true if the event is pending on any of the events in 'what', (that
980   is to say, it has been added), or 0 if the event is not added.
981  */
982 int event_pending(const struct event *ev, short events, struct timeval *tv);
983 
984 
985 /**
986   Test if an event structure might be initialized.
987 
988   The event_initialized() function can be used to check if an event has been
989   initialized.
990 
991   Warning: This function is only useful for distinguishing a a zeroed-out
992     piece of memory from an initialized event, it can easily be confused by
993     uninitialized memory.  Thus, it should ONLY be used to distinguish an
994     initialized event from zero.
995 
996   @param ev an event structure to be tested
997   @return 1 if the structure might be initialized, or 0 if it has not been
998           initialized
999  */
1000 int event_initialized(const struct event *ev);
1001 
1002 /**
1003    Get the signal number assigned to a signal event
1004 */
1005 #define event_get_signal(ev) ((int)event_get_fd(ev))
1006 
1007 /**
1008    Get the socket or signal assigned to an event, or -1 if the event has
1009    no socket.
1010 */
1011 evutil_socket_t event_get_fd(const struct event *ev);
1012 
1013 /**
1014    Get the event_base associated with an event.
1015 */
1016 struct event_base *event_get_base(const struct event *ev);
1017 
1018 /**
1019    Return the events (EV_READ, EV_WRITE, etc) assigned to an event.
1020 */
1021 short event_get_events(const struct event *ev);
1022 
1023 /**
1024    Return the callback assigned to an event.
1025 */
1026 event_callback_fn event_get_callback(const struct event *ev);
1027 
1028 /**
1029    Return the callback argument assigned to an event.
1030 */
1031 void *event_get_callback_arg(const struct event *ev);
1032 
1033 /**
1034    Extract _all_ of arguments given to construct a given event.  The
1035    event_base is copied into *base_out, the fd is copied into *fd_out, and so
1036    on.
1037 
1038    If any of the "_out" arguments is NULL, it will be ignored.
1039  */
1040 void event_get_assignment(const struct event *event,
1041     struct event_base **base_out, evutil_socket_t *fd_out, short *events_out,
1042     event_callback_fn *callback_out, void **arg_out);
1043 
1044 /**
1045    Return the size of struct event that the Libevent library was compiled
1046    with.
1047 
1048    This will be NO GREATER than sizeof(struct event) if you're running with
1049    the same version of Libevent that your application was built with, but
1050    otherwise might not.
1051 
1052    Note that it might be SMALLER than sizeof(struct event) if some future
1053    version of Libevent adds extra padding to the end of struct event.
1054    We might do this to help ensure ABI-compatibility between different
1055    versions of Libevent.
1056  */
1057 size_t event_get_struct_event_size(void);
1058 
1059 /**
1060    Get the Libevent version.
1061 
1062    Note that this will give you the version of the library that you're
1063    currently linked against, not the version of the headers that you've
1064    compiled against.
1065 
1066    @return a string containing the version number of Libevent
1067 */
1068 const char *event_get_version(void);
1069 
1070 /**
1071    Return a numeric representation of Libevent's version.
1072 
1073    Note that this will give you the version of the library that you're
1074    currently linked against, not the version of the headers you've used to
1075    compile.
1076 
1077    The format uses one byte each for the major, minor, and patchlevel parts of
1078    the version number.  The low-order byte is unused.  For example, version
1079    2.0.1-alpha has a numeric representation of 0x02000100
1080 */
1081 ev_uint32_t event_get_version_number(void);
1082 
1083 /** As event_get_version, but gives the version of Libevent's headers. */
1084 #define LIBEVENT_VERSION _EVENT_VERSION
1085 /** As event_get_version_number, but gives the version number of Libevent's
1086  * headers. */
1087 #define LIBEVENT_VERSION_NUMBER _EVENT_NUMERIC_VERSION
1088 
1089 /** Largest number of priorities that Libevent can support. */
1090 #define EVENT_MAX_PRIORITIES 256
1091 /**
1092   Set the number of different event priorities
1093 
1094   By default Libevent schedules all active events with the same priority.
1095   However, some time it is desirable to process some events with a higher
1096   priority than others.  For that reason, Libevent supports strict priority
1097   queues.  Active events with a lower priority are always processed before
1098   events with a higher priority.
1099 
1100   The number of different priorities can be set initially with the
1101   event_base_priority_init() function.  This function should be called
1102   before the first call to event_base_dispatch().  The
1103   event_priority_set() function can be used to assign a priority to an
1104   event.  By default, Libevent assigns the middle priority to all events
1105   unless their priority is explicitly set.
1106 
1107   Note that urgent-priority events can starve less-urgent events: after
1108   running all urgent-priority callbacks, Libevent checks for more urgent
1109   events again, before running less-urgent events.  Less-urgent events
1110   will not have their callbacks run until there are no events more urgent
1111   than them that want to be active.
1112 
1113   @param eb the event_base structure returned by event_base_new()
1114   @param npriorities the maximum number of priorities
1115   @return 0 if successful, or -1 if an error occurred
1116   @see event_priority_set()
1117  */
1118 int	event_base_priority_init(struct event_base *, int);
1119 
1120 /**
1121   Assign a priority to an event.
1122 
1123   @param ev an event struct
1124   @param priority the new priority to be assigned
1125   @return 0 if successful, or -1 if an error occurred
1126   @see event_priority_init()
1127   */
1128 int	event_priority_set(struct event *, int);
1129 
1130 /**
1131    Prepare an event_base to use a large number of timeouts with the same
1132    duration.
1133 
1134    Libevent's default scheduling algorithm is optimized for having a large
1135    number of timeouts with their durations more or less randomly
1136    distributed.  But if you have a large number of timeouts that all have
1137    the same duration (for example, if you have a large number of
1138    connections that all have a 10-second timeout), then you can improve
1139    Libevent's performance by telling Libevent about it.
1140 
1141    To do this, call this function with the common duration.  It will return a
1142    pointer to a different, opaque timeout value.  (Don't depend on its actual
1143    contents!)  When you use this timeout value in event_add(), Libevent will
1144    schedule the event more efficiently.
1145 
1146    (This optimization probably will not be worthwhile until you have thousands
1147    or tens of thousands of events with the same timeout.)
1148  */
1149 const struct timeval *event_base_init_common_timeout(struct event_base *base,
1150     const struct timeval *duration);
1151 
1152 #if !defined(_EVENT_DISABLE_MM_REPLACEMENT) || defined(_EVENT_IN_DOXYGEN)
1153 /**
1154  Override the functions that Libevent uses for memory management.
1155 
1156  Usually, Libevent uses the standard libc functions malloc, realloc, and
1157  free to allocate memory.  Passing replacements for those functions to
1158  event_set_mem_functions() overrides this behavior.
1159 
1160  Note that all memory returned from Libevent will be allocated by the
1161  replacement functions rather than by malloc() and realloc().  Thus, if you
1162  have replaced those functions, it will not be appropriate to free() memory
1163  that you get from Libevent.  Instead, you must use the free_fn replacement
1164  that you provided.
1165 
1166  Note also that if you are going to call this function, you should do so
1167  before any call to any Libevent function that does allocation.
1168  Otherwise, those funtions will allocate their memory using malloc(), but
1169  then later free it using your provided free_fn.
1170 
1171  @param malloc_fn A replacement for malloc.
1172  @param realloc_fn A replacement for realloc
1173  @param free_fn A replacement for free.
1174  **/
1175 void event_set_mem_functions(
1176 	void *(*malloc_fn)(size_t sz),
1177 	void *(*realloc_fn)(void *ptr, size_t sz),
1178 	void (*free_fn)(void *ptr));
1179 /** This definition is present if Libevent was built with support for
1180     event_set_mem_functions() */
1181 #define EVENT_SET_MEM_FUNCTIONS_IMPLEMENTED
1182 #endif
1183 
1184 void event_base_dump_events(struct event_base *, FILE *);
1185 
1186 /** Sets 'tv' to the current time (as returned by gettimeofday()),
1187     looking at the cached value in 'base' if possible, and calling
1188     gettimeofday() or clock_gettime() as appropriate if there is no
1189     cached time.
1190 
1191     Generally, this value will only be cached while actually
1192     processing event callbacks, and may be very inaccuate if your
1193     callbacks take a long time to execute.
1194 
1195     Returns 0 on success, negative on failure.
1196  */
1197 int event_base_gettimeofday_cached(struct event_base *base,
1198     struct timeval *tv);
1199 
1200 #ifdef __cplusplus
1201 }
1202 #endif
1203 
1204 #endif /* _EVENT2_EVENT_H_ */
1205