event.h 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212
  1. /*
  2. * Copyright (c) 2000-2007 Niels Provos <provos@citi.umich.edu>
  3. * All rights reserved.
  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 _EVENT_H_
  28. #define _EVENT_H_
  29. /** @mainpage
  30. @section intro Introduction
  31. libevent is an event notification library for developing scalable network
  32. servers. The libevent API provides a mechanism to execute a callback
  33. function when a specific event occurs on a file descriptor or after a
  34. timeout has been reached. Furthermore, libevent also support callbacks due
  35. to signals or regular timeouts.
  36. libevent is meant to replace the event loop found in event driven network
  37. servers. An application just needs to call event_dispatch() and then add or
  38. remove events dynamically without having to change the event loop.
  39. Currently, libevent supports /dev/poll, kqueue(2), select(2), poll(2) and
  40. epoll(4). It also has experimental support for real-time signals. The
  41. internal event mechanism is completely independent of the exposed event API,
  42. and a simple update of libevent can provide new functionality without having
  43. to redesign the applications. As a result, Libevent allows for portable
  44. application development and provides the most scalable event notification
  45. mechanism available on an operating system. Libevent can also be used for
  46. multi-threaded aplications; see Steven Grimm's explanation. Libevent should
  47. compile on Linux, *BSD, Mac OS X, Solaris and Windows.
  48. @section usage Standard usage
  49. Every program that uses libevent must include the <event.h> header, and pass
  50. the -levent flag to the linker. Before using any of the functions in the
  51. library, you must call event_init() or event_base_new() to perform one-time
  52. initialization of the libevent library.
  53. @section event Event notification
  54. For each file descriptor that you wish to monitor, you must declare an event
  55. structure and call event_set() to initialize the members of the structure.
  56. To enable notification, you add the structure to the list of monitored
  57. events by calling event_add(). The event structure must remain allocated as
  58. long as it is active, so it should be allocated on the heap. Finally, you
  59. call event_dispatch() to loop and dispatch events.
  60. @section bufferevent I/O Buffers
  61. libevent provides an abstraction on top of the regular event callbacks. This
  62. abstraction is called a buffered event. A buffered event provides input and
  63. output buffers that get filled and drained automatically. The user of a
  64. buffered event no longer deals directly with the I/O, but instead is reading
  65. from input and writing to output buffers.
  66. Once initialized via bufferevent_new(), the bufferevent structure can be
  67. used repeatedly with bufferevent_enable() and bufferevent_disable().
  68. Instead of reading and writing directly to a socket, you would call
  69. bufferevent_read() and bufferevent_write().
  70. When read enabled the bufferevent will try to read from the file descriptor
  71. and call the read callback. The write callback is executed whenever the
  72. output buffer is drained below the write low watermark, which is 0 by
  73. default.
  74. @section timers Timers
  75. libevent can also be used to create timers that invoke a callback after a
  76. certain amount of time has expired. The evtimer_set() function prepares an
  77. event struct to be used as a timer. To activate the timer, call
  78. evtimer_add(). Timers can be deactivated by calling evtimer_del().
  79. @section timeouts Timeouts
  80. In addition to simple timers, libevent can assign timeout events to file
  81. descriptors that are triggered whenever a certain amount of time has passed
  82. with no activity on a file descriptor. The timeout_set() function
  83. initializes an event struct for use as a timeout. Once initialized, the
  84. event must be activated by using timeout_add(). To cancel the timeout, call
  85. timeout_del().
  86. @section evdns Asynchronous DNS resolution
  87. libevent provides an asynchronous DNS resolver that should be used instead
  88. of the standard DNS resolver functions. These functions can be imported by
  89. including the <evdns.h> header in your program. Before using any of the
  90. resolver functions, you must call evdns_init() to initialize the library. To
  91. convert a hostname to an IP address, you call the evdns_resolve_ipv4()
  92. function. To perform a reverse lookup, you would call the
  93. evdns_resolve_reverse() function. All of these functions use callbacks to
  94. avoid blocking while the lookup is performed.
  95. @section evhttp Event-driven HTTP servers
  96. libevent provides a very simple event-driven HTTP server that can be
  97. embedded in your program and used to service HTTP requests.
  98. To use this capability, you need to include the <evhttp.h> header in your
  99. program. You create the server by calling evhttp_new(). Add addresses and
  100. ports to listen on with evhttp_bind_socket(). You then register one or more
  101. callbacks to handle incoming requests. Each URI can be assigned a callback
  102. via the evhttp_set_cb() function. A generic callback function can also be
  103. registered via evhttp_set_gencb(); this callback will be invoked if no other
  104. callbacks have been registered for a given URI.
  105. @section evrpc A framework for RPC servers and clients
  106. libevents provides a framework for creating RPC servers and clients. It
  107. takes care of marshaling and unmarshaling all data structures.
  108. @section api API Reference
  109. To browse the complete documentation of the libevent API, click on any of
  110. the following links.
  111. event.h
  112. The primary libevent header
  113. evdns.h
  114. Asynchronous DNS resolution
  115. evhttp.h
  116. An embedded libevent-based HTTP server
  117. evrpc.h
  118. A framework for creating RPC servers and clients
  119. */
  120. /** @file event.h
  121. A library for writing event-driven network servers
  122. */
  123. #ifdef __cplusplus
  124. extern "C" {
  125. #endif
  126. #include "event-config.h"
  127. #ifdef _EVENT_HAVE_SYS_TYPES_H
  128. #include <sys/types.h>
  129. #endif
  130. #ifdef _EVENT_HAVE_SYS_TIME_H
  131. #include <sys/time.h>
  132. #endif
  133. #ifdef _EVENT_HAVE_STDINT_H
  134. #include <stdint.h>
  135. #endif
  136. #include <stdarg.h>
  137. /* For int types. */
  138. #include "evutil.h"
  139. #ifdef WIN32
  140. #define WIN32_LEAN_AND_MEAN
  141. #include <windows.h>
  142. #undef WIN32_LEAN_AND_MEAN
  143. typedef unsigned char u_char;
  144. typedef unsigned short u_short;
  145. #endif
  146. #define EVLIST_TIMEOUT 0x01
  147. #define EVLIST_INSERTED 0x02
  148. #define EVLIST_SIGNAL 0x04
  149. #define EVLIST_ACTIVE 0x08
  150. #define EVLIST_INTERNAL 0x10
  151. #define EVLIST_INIT 0x80
  152. /* EVLIST_X_ Private space: 0x1000-0xf000 */
  153. #define EVLIST_ALL (0xf000 | 0x9f)
  154. #define EV_TIMEOUT 0x01
  155. #define EV_READ 0x02
  156. #define EV_WRITE 0x04
  157. #define EV_SIGNAL 0x08
  158. #define EV_PERSIST 0x10 /* Persistant event */
  159. /* Fix so that ppl dont have to run with <sys/queue.h> */
  160. #ifndef TAILQ_ENTRY
  161. #define _EVENT_DEFINED_TQENTRY
  162. #define TAILQ_ENTRY(type) \
  163. struct { \
  164. struct type *tqe_next; /* next element */ \
  165. struct type **tqe_prev; /* address of previous next element */ \
  166. }
  167. #endif /* !TAILQ_ENTRY */
  168. struct event_base;
  169. #ifndef EVENT_NO_STRUCT
  170. struct event {
  171. TAILQ_ENTRY (event) ev_next;
  172. TAILQ_ENTRY (event) ev_active_next;
  173. TAILQ_ENTRY (event) ev_signal_next;
  174. unsigned int min_heap_idx; /* for managing timeouts */
  175. struct event_base *ev_base;
  176. int ev_fd;
  177. short ev_events;
  178. short ev_ncalls;
  179. short *ev_pncalls; /* Allows deletes in callback */
  180. struct timeval ev_timeout;
  181. int ev_pri; /* smaller numbers are higher priority */
  182. void (*ev_callback)(int, short, void *arg);
  183. void *ev_arg;
  184. int ev_res; /* result passed to event callback */
  185. int ev_flags;
  186. };
  187. #else
  188. struct event;
  189. #endif
  190. #define EVENT_SIGNAL(ev) (int)(ev)->ev_fd
  191. #define EVENT_FD(ev) (int)(ev)->ev_fd
  192. /*
  193. * Key-Value pairs. Can be used for HTTP headers but also for
  194. * query argument parsing.
  195. */
  196. struct evkeyval {
  197. TAILQ_ENTRY(evkeyval) next;
  198. char *key;
  199. char *value;
  200. };
  201. #ifdef _EVENT_DEFINED_TQENTRY
  202. #undef TAILQ_ENTRY
  203. struct event_list;
  204. struct evkeyvalq;
  205. #undef _EVENT_DEFINED_TQENTRY
  206. #else
  207. TAILQ_HEAD (event_list, event);
  208. TAILQ_HEAD (evkeyvalq, evkeyval);
  209. #endif /* _EVENT_DEFINED_TQENTRY */
  210. /**
  211. Initialize the event API.
  212. Use event_base_new() to initialize a new event base, but does not set
  213. the current_base global. If using only event_base_new(), each event
  214. added must have an event base set with event_base_set()
  215. @see event_base_set(), event_base_free(), event_init()
  216. */
  217. struct event_base *event_base_new(void);
  218. /**
  219. Initialize the event API.
  220. The event API needs to be initialized with event_init() before it can be
  221. used. Sets the current_base global representing the default base for
  222. events that have no base associated with them.
  223. @see event_base_set(), event_base_new()
  224. */
  225. struct event_base *event_init(void);
  226. /**
  227. Reinitialized the event base after a fork
  228. Some event mechanisms do not survive across fork. The event base needs
  229. to be reinitialized with the event_reinit() function.
  230. @param base the event base that needs to be re-initialized
  231. @return 0 if successful, or -1 if some events could not be re-added.
  232. @see event_base_new(), event_init()
  233. */
  234. int event_reinit(struct event_base *base);
  235. /**
  236. Loop to process events.
  237. In order to process events, an application needs to call
  238. event_dispatch(). This function only returns on error, and should
  239. replace the event core of the application program.
  240. @see event_base_dispatch()
  241. */
  242. int event_dispatch(void);
  243. /**
  244. Threadsafe event dispatching loop.
  245. @param eb the event_base structure returned by event_init()
  246. @see event_init(), event_dispatch()
  247. */
  248. int event_base_dispatch(struct event_base *);
  249. /**
  250. Get the kernel event notification mechanism used by libevent.
  251. @param eb the event_base structure returned by event_base_new()
  252. @return a string identifying the kernel event mechanism (kqueue, epoll, etc.)
  253. */
  254. const char *event_base_get_method(struct event_base *);
  255. /**
  256. Deallocate all memory associated with an event_base, and free the base.
  257. Note that this function will not close any fds or free any memory passed
  258. to event_set as the argument to callback.
  259. @param eb an event_base to be freed
  260. */
  261. void event_base_free(struct event_base *);
  262. #define _EVENT_LOG_DEBUG 0
  263. #define _EVENT_LOG_MSG 1
  264. #define _EVENT_LOG_WARN 2
  265. #define _EVENT_LOG_ERR 3
  266. typedef void (*event_log_cb)(int severity, const char *msg);
  267. /**
  268. Redirect libevent's log messages.
  269. @param cb a function taking two arguments: an integer severity between
  270. _EVENT_LOG_DEBUG and _EVENT_LOG_ERR, and a string. If cb is NULL,
  271. then the default log is used.
  272. */
  273. void event_set_log_callback(event_log_cb cb);
  274. /**
  275. Associate a different event base with an event.
  276. @param eb the event base
  277. @param ev the event
  278. */
  279. int event_base_set(struct event_base *, struct event *);
  280. /**
  281. event_loop() flags
  282. */
  283. /*@{*/
  284. #define EVLOOP_ONCE 0x01 /**< Block at most once. */
  285. #define EVLOOP_NONBLOCK 0x02 /**< Do not block. */
  286. /*@}*/
  287. /**
  288. Handle events.
  289. This is a more flexible version of event_dispatch().
  290. @param flags any combination of EVLOOP_ONCE | EVLOOP_NONBLOCK
  291. @return 0 if successful, -1 if an error occurred, or 1 if no events were
  292. registered.
  293. @see event_loopexit(), event_base_loop()
  294. */
  295. int event_loop(int);
  296. /**
  297. Handle events (threadsafe version).
  298. This is a more flexible version of event_base_dispatch().
  299. @param eb the event_base structure returned by event_init()
  300. @param flags any combination of EVLOOP_ONCE | EVLOOP_NONBLOCK
  301. @return 0 if successful, -1 if an error occurred, or 1 if no events were
  302. registered.
  303. @see event_loopexit(), event_base_loop()
  304. */
  305. int event_base_loop(struct event_base *, int);
  306. /**
  307. Exit the event loop after the specified time.
  308. The next event_loop() iteration after the given timer expires will
  309. complete normally (handling all queued events) then exit without
  310. blocking for events again.
  311. Subsequent invocations of event_loop() will proceed normally.
  312. @param tv the amount of time after which the loop should terminate.
  313. @return 0 if successful, or -1 if an error occurred
  314. @see event_loop(), event_base_loop(), event_base_loopexit()
  315. */
  316. int event_loopexit(const struct timeval *);
  317. /**
  318. Exit the event loop after the specified time (threadsafe variant).
  319. The next event_base_loop() iteration after the given timer expires will
  320. complete normally (handling all queued events) then exit without
  321. blocking for events again.
  322. Subsequent invocations of event_base_loop() will proceed normally.
  323. @param eb the event_base structure returned by event_init()
  324. @param tv the amount of time after which the loop should terminate.
  325. @return 0 if successful, or -1 if an error occurred
  326. @see event_loopexit()
  327. */
  328. int event_base_loopexit(struct event_base *, const struct timeval *);
  329. /**
  330. Abort the active event_loop() immediately.
  331. event_loop() will abort the loop after the next event is completed;
  332. event_loopbreak() is typically invoked from this event's callback.
  333. This behavior is analogous to the "break;" statement.
  334. Subsequent invocations of event_loop() will proceed normally.
  335. @return 0 if successful, or -1 if an error occurred
  336. @see event_base_loopbreak(), event_loopexit()
  337. */
  338. int event_loopbreak(void);
  339. /**
  340. Abort the active event_base_loop() immediately.
  341. event_base_loop() will abort the loop after the next event is completed;
  342. event_base_loopbreak() is typically invoked from this event's callback.
  343. This behavior is analogous to the "break;" statement.
  344. Subsequent invocations of event_loop() will proceed normally.
  345. @param eb the event_base structure returned by event_init()
  346. @return 0 if successful, or -1 if an error occurred
  347. @see event_base_loopexit
  348. */
  349. int event_base_loopbreak(struct event_base *);
  350. /**
  351. Add a timer event.
  352. @param ev the event struct
  353. @param tv timeval struct
  354. */
  355. #define evtimer_add(ev, tv) event_add(ev, tv)
  356. /**
  357. Define a timer event.
  358. @param ev event struct to be modified
  359. @param cb callback function
  360. @param arg argument that will be passed to the callback function
  361. */
  362. #define evtimer_set(ev, cb, arg) event_set(ev, -1, 0, cb, arg)
  363. /**
  364. * Delete a timer event.
  365. *
  366. * @param ev the event struct to be disabled
  367. */
  368. #define evtimer_del(ev) event_del(ev)
  369. #define evtimer_pending(ev, tv) event_pending(ev, EV_TIMEOUT, tv)
  370. #define evtimer_initialized(ev) ((ev)->ev_flags & EVLIST_INIT)
  371. /**
  372. * Add a timeout event.
  373. *
  374. * @param ev the event struct to be disabled
  375. * @param tv the timeout value, in seconds
  376. */
  377. #define timeout_add(ev, tv) event_add(ev, tv)
  378. /**
  379. * Define a timeout event.
  380. *
  381. * @param ev the event struct to be defined
  382. * @param cb the callback to be invoked when the timeout expires
  383. * @param arg the argument to be passed to the callback
  384. */
  385. #define timeout_set(ev, cb, arg) event_set(ev, -1, 0, cb, arg)
  386. /**
  387. * Disable a timeout event.
  388. *
  389. * @param ev the timeout event to be disabled
  390. */
  391. #define timeout_del(ev) event_del(ev)
  392. #define timeout_pending(ev, tv) event_pending(ev, EV_TIMEOUT, tv)
  393. #define timeout_initialized(ev) ((ev)->ev_flags & EVLIST_INIT)
  394. #define signal_add(ev, tv) event_add(ev, tv)
  395. #define signal_set(ev, x, cb, arg) \
  396. event_set(ev, x, EV_SIGNAL|EV_PERSIST, cb, arg)
  397. #define signal_del(ev) event_del(ev)
  398. #define signal_pending(ev, tv) event_pending(ev, EV_SIGNAL, tv)
  399. #define signal_initialized(ev) ((ev)->ev_flags & EVLIST_INIT)
  400. /**
  401. Prepare an event structure to be added.
  402. The function event_set() prepares the event structure ev to be used in
  403. future calls to event_add() and event_del(). The event will be prepared to
  404. call the function specified by the fn argument with an int argument
  405. indicating the file descriptor, a short argument indicating the type of
  406. event, and a void * argument given in the arg argument. The fd indicates
  407. the file descriptor that should be monitored for events. The events can be
  408. either EV_READ, EV_WRITE, or both. Indicating that an application can read
  409. or write from the file descriptor respectively without blocking.
  410. The function fn will be called with the file descriptor that triggered the
  411. event and the type of event which will be either EV_TIMEOUT, EV_SIGNAL,
  412. EV_READ, or EV_WRITE. The additional flag EV_PERSIST makes an event_add()
  413. persistent until event_del() has been called.
  414. @param ev an event struct to be modified
  415. @param fd the file descriptor to be monitored
  416. @param event desired events to monitor; can be EV_READ and/or EV_WRITE
  417. @param fn callback function to be invoked when the event occurs
  418. @param arg an argument to be passed to the callback function
  419. @see event_add(), event_del(), event_once()
  420. */
  421. void event_set(struct event *, int, short, void (*)(int, short, void *), void *);
  422. /**
  423. Schedule a one-time event to occur.
  424. The function event_once() is similar to event_set(). However, it schedules
  425. a callback to be called exactly once and does not require the caller to
  426. prepare an event structure.
  427. @param fd a file descriptor to monitor
  428. @param events event(s) to monitor; can be any of EV_TIMEOUT | EV_READ |
  429. EV_WRITE
  430. @param callback callback function to be invoked when the event occurs
  431. @param arg an argument to be passed to the callback function
  432. @param timeout the maximum amount of time to wait for the event, or NULL
  433. to wait forever
  434. @return 0 if successful, or -1 if an error occurred
  435. @see event_set()
  436. */
  437. int event_once(int, short, void (*)(int, short, void *), void *,
  438. const struct timeval *);
  439. /**
  440. Schedule a one-time event (threadsafe variant)
  441. The function event_base_once() is similar to event_set(). However, it
  442. schedules a callback to be called exactly once and does not require the
  443. caller to prepare an event structure.
  444. @param base an event_base returned by event_init()
  445. @param fd a file descriptor to monitor
  446. @param events event(s) to monitor; can be any of EV_TIMEOUT | EV_READ |
  447. EV_WRITE
  448. @param callback callback function to be invoked when the event occurs
  449. @param arg an argument to be passed to the callback function
  450. @param timeout the maximum amount of time to wait for the event, or NULL
  451. to wait forever
  452. @return 0 if successful, or -1 if an error occurred
  453. @see event_once()
  454. */
  455. int event_base_once(struct event_base *base, int fd, short events,
  456. void (*callback)(int, short, void *), void *arg,
  457. const struct timeval *timeout);
  458. /**
  459. Add an event to the set of monitored events.
  460. The function event_add() schedules the execution of the ev event when the
  461. event specified in event_set() occurs or in at least the time specified in
  462. the tv. If tv is NULL, no timeout occurs and the function will only be
  463. called if a matching event occurs on the file descriptor. The event in the
  464. ev argument must be already initialized by event_set() and may not be used
  465. in calls to event_set() until it has timed out or been removed with
  466. event_del(). If the event in the ev argument already has a scheduled
  467. timeout, the old timeout will be replaced by the new one.
  468. @param ev an event struct initialized via event_set()
  469. @param timeout the maximum amount of time to wait for the event, or NULL
  470. to wait forever
  471. @return 0 if successful, or -1 if an error occurred
  472. @see event_del(), event_set()
  473. */
  474. int event_add(struct event *ev, const struct timeval *timeout);
  475. /**
  476. Remove an event from the set of monitored events.
  477. The function event_del() will cancel the event in the argument ev. If the
  478. event has already executed or has never been added the call will have no
  479. effect.
  480. @param ev an event struct to be removed from the working set
  481. @return 0 if successful, or -1 if an error occurred
  482. @see event_add()
  483. */
  484. int event_del(struct event *);
  485. void event_active(struct event *, int, short);
  486. /**
  487. Checks if a specific event is pending or scheduled.
  488. @param ev an event struct previously passed to event_add()
  489. @param event the requested event type; any of EV_TIMEOUT|EV_READ|
  490. EV_WRITE|EV_SIGNAL
  491. @param tv an alternate timeout (FIXME - is this true?)
  492. @return 1 if the event is pending, or 0 if the event has not occurred
  493. */
  494. int event_pending(struct event *ev, short event, struct timeval *tv);
  495. /**
  496. Test if an event structure has been initialized.
  497. The event_initialized() macro can be used to check if an event has been
  498. initialized.
  499. @param ev an event structure to be tested
  500. @return 1 if the structure has been initialized, or 0 if it has not been
  501. initialized
  502. */
  503. #ifdef WIN32
  504. #define event_initialized(ev) ((ev)->ev_flags & EVLIST_INIT && (ev)->ev_fd != (int)INVALID_HANDLE_VALUE)
  505. #else
  506. #define event_initialized(ev) ((ev)->ev_flags & EVLIST_INIT)
  507. #endif
  508. /**
  509. Get the libevent version number.
  510. @return a string containing the version number of libevent
  511. */
  512. const char *event_get_version(void);
  513. /**
  514. Get the kernel event notification mechanism used by libevent.
  515. @return a string identifying the kernel event mechanism (kqueue, epoll, etc.)
  516. */
  517. const char *event_get_method(void);
  518. /**
  519. Set the number of different event priorities.
  520. By default libevent schedules all active events with the same priority.
  521. However, some time it is desirable to process some events with a higher
  522. priority than others. For that reason, libevent supports strict priority
  523. queues. Active events with a lower priority are always processed before
  524. events with a higher priority.
  525. The number of different priorities can be set initially with the
  526. event_priority_init() function. This function should be called before the
  527. first call to event_dispatch(). The event_priority_set() function can be
  528. used to assign a priority to an event. By default, libevent assigns the
  529. middle priority to all events unless their priority is explicitly set.
  530. @param npriorities the maximum number of priorities
  531. @return 0 if successful, or -1 if an error occurred
  532. @see event_base_priority_init(), event_priority_set()
  533. */
  534. int event_priority_init(int);
  535. /**
  536. Set the number of different event priorities (threadsafe variant).
  537. See the description of event_priority_init() for more information.
  538. @param eb the event_base structure returned by event_init()
  539. @param npriorities the maximum number of priorities
  540. @return 0 if successful, or -1 if an error occurred
  541. @see event_priority_init(), event_priority_set()
  542. */
  543. int event_base_priority_init(struct event_base *, int);
  544. /**
  545. Assign a priority to an event.
  546. @param ev an event struct
  547. @param priority the new priority to be assigned
  548. @return 0 if successful, or -1 if an error occurred
  549. @see event_priority_init()
  550. */
  551. int event_priority_set(struct event *, int);
  552. /* These functions deal with buffering input and output */
  553. struct evbuffer {
  554. u_char *buffer;
  555. u_char *orig_buffer;
  556. size_t misalign;
  557. size_t totallen;
  558. size_t off;
  559. void (*cb)(struct evbuffer *, size_t, size_t, void *);
  560. void *cbarg;
  561. };
  562. /* Just for error reporting - use other constants otherwise */
  563. #define EVBUFFER_READ 0x01
  564. #define EVBUFFER_WRITE 0x02
  565. #define EVBUFFER_EOF 0x10
  566. #define EVBUFFER_ERROR 0x20
  567. #define EVBUFFER_TIMEOUT 0x40
  568. struct bufferevent;
  569. typedef void (*evbuffercb)(struct bufferevent *, void *);
  570. typedef void (*everrorcb)(struct bufferevent *, short what, void *);
  571. struct event_watermark {
  572. size_t low;
  573. size_t high;
  574. };
  575. #ifndef EVENT_NO_STRUCT
  576. struct bufferevent {
  577. struct event_base *ev_base;
  578. struct event ev_read;
  579. struct event ev_write;
  580. struct evbuffer *input;
  581. struct evbuffer *output;
  582. struct event_watermark wm_read;
  583. struct event_watermark wm_write;
  584. evbuffercb readcb;
  585. evbuffercb writecb;
  586. everrorcb errorcb;
  587. void *cbarg;
  588. int timeout_read; /* in seconds */
  589. int timeout_write; /* in seconds */
  590. short enabled; /* events that are currently enabled */
  591. };
  592. #endif
  593. /**
  594. Create a new bufferevent.
  595. libevent provides an abstraction on top of the regular event callbacks.
  596. This abstraction is called a buffered event. A buffered event provides
  597. input and output buffers that get filled and drained automatically. The
  598. user of a buffered event no longer deals directly with the I/O, but
  599. instead is reading from input and writing to output buffers.
  600. Once initialized, the bufferevent structure can be used repeatedly with
  601. bufferevent_enable() and bufferevent_disable().
  602. When read enabled the bufferevent will try to read from the file descriptor
  603. and call the read callback. The write callback is executed whenever the
  604. output buffer is drained below the write low watermark, which is 0 by
  605. default.
  606. If multiple bases are in use, bufferevent_base_set() must be called before
  607. enabling the bufferevent for the first time.
  608. @param fd the file descriptor from which data is read and written to.
  609. This file descriptor is not allowed to be a pipe(2).
  610. @param readcb callback to invoke when there is data to be read, or NULL if
  611. no callback is desired
  612. @param writecb callback to invoke when the file descriptor is ready for
  613. writing, or NULL if no callback is desired
  614. @param errorcb callback to invoke when there is an error on the file
  615. descriptor
  616. @param cbarg an argument that will be supplied to each of the callbacks
  617. (readcb, writecb, and errorcb)
  618. @return a pointer to a newly allocated bufferevent struct, or NULL if an
  619. error occurred
  620. @see bufferevent_base_set(), bufferevent_free()
  621. */
  622. struct bufferevent *bufferevent_new(int fd,
  623. evbuffercb readcb, evbuffercb writecb, everrorcb errorcb, void *cbarg);
  624. /**
  625. Assign a bufferevent to a specific event_base.
  626. @param base an event_base returned by event_init()
  627. @param bufev a bufferevent struct returned by bufferevent_new()
  628. @return 0 if successful, or -1 if an error occurred
  629. @see bufferevent_new()
  630. */
  631. int bufferevent_base_set(struct event_base *base, struct bufferevent *bufev);
  632. /**
  633. Assign a priority to a bufferevent.
  634. @param bufev a bufferevent struct
  635. @param pri the priority to be assigned
  636. @return 0 if successful, or -1 if an error occurred
  637. */
  638. int bufferevent_priority_set(struct bufferevent *bufev, int pri);
  639. /**
  640. Deallocate the storage associated with a bufferevent structure.
  641. @param bufev the bufferevent structure to be freed.
  642. */
  643. void bufferevent_free(struct bufferevent *bufev);
  644. /**
  645. Changes the callbacks for a bufferevent.
  646. @param bufev the bufferevent object for which to change callbacks
  647. @param readcb callback to invoke when there is data to be read, or NULL if
  648. no callback is desired
  649. @param writecb callback to invoke when the file descriptor is ready for
  650. writing, or NULL if no callback is desired
  651. @param errorcb callback to invoke when there is an error on the file
  652. descriptor
  653. @param cbarg an argument that will be supplied to each of the callbacks
  654. (readcb, writecb, and errorcb)
  655. @see bufferevent_new()
  656. */
  657. void bufferevent_setcb(struct bufferevent *bufev,
  658. evbuffercb readcb, evbuffercb writecb, everrorcb errorcb, void *cbarg);
  659. /**
  660. Changes the file descriptor on which the bufferevent operates.
  661. @param bufev the bufferevent object for which to change the file descriptor
  662. @param fd the file descriptor to operate on
  663. */
  664. void bufferevent_setfd(struct bufferevent *bufev, int fd);
  665. /**
  666. Write data to a bufferevent buffer.
  667. The bufferevent_write() function can be used to write data to the file
  668. descriptor. The data is appended to the output buffer and written to the
  669. descriptor automatically as it becomes available for writing.
  670. @param bufev the bufferevent to be written to
  671. @param data a pointer to the data to be written
  672. @param size the length of the data, in bytes
  673. @return 0 if successful, or -1 if an error occurred
  674. @see bufferevent_write_buffer()
  675. */
  676. int bufferevent_write(struct bufferevent *bufev,
  677. const void *data, size_t size);
  678. /**
  679. Write data from an evbuffer to a bufferevent buffer. The evbuffer is
  680. being drained as a result.
  681. @param bufev the bufferevent to be written to
  682. @param buf the evbuffer to be written
  683. @return 0 if successful, or -1 if an error occurred
  684. @see bufferevent_write()
  685. */
  686. int bufferevent_write_buffer(struct bufferevent *bufev, struct evbuffer *buf);
  687. /**
  688. Read data from a bufferevent buffer.
  689. The bufferevent_read() function is used to read data from the input buffer.
  690. @param bufev the bufferevent to be read from
  691. @param data pointer to a buffer that will store the data
  692. @param size the size of the data buffer, in bytes
  693. @return the amount of data read, in bytes.
  694. */
  695. size_t bufferevent_read(struct bufferevent *bufev, void *data, size_t size);
  696. /**
  697. Enable a bufferevent.
  698. @param bufev the bufferevent to be enabled
  699. @param event any combination of EV_READ | EV_WRITE.
  700. @return 0 if successful, or -1 if an error occurred
  701. @see bufferevent_disable()
  702. */
  703. int bufferevent_enable(struct bufferevent *bufev, short event);
  704. /**
  705. Disable a bufferevent.
  706. @param bufev the bufferevent to be disabled
  707. @param event any combination of EV_READ | EV_WRITE.
  708. @return 0 if successful, or -1 if an error occurred
  709. @see bufferevent_enable()
  710. */
  711. int bufferevent_disable(struct bufferevent *bufev, short event);
  712. /**
  713. Set the read and write timeout for a buffered event.
  714. @param bufev the bufferevent to be modified
  715. @param timeout_read the read timeout
  716. @param timeout_write the write timeout
  717. */
  718. void bufferevent_settimeout(struct bufferevent *bufev,
  719. int timeout_read, int timeout_write);
  720. /**
  721. Sets the watermarks for read and write events.
  722. On input, a bufferevent does not invoke the user read callback unless
  723. there is at least low watermark data in the buffer. If the read buffer
  724. is beyond the high watermark, the buffevent stops reading from the network.
  725. On output, the user write callback is invoked whenever the buffered data
  726. falls below the low watermark.
  727. @param bufev the bufferevent to be modified
  728. @param events EV_READ, EV_WRITE or both
  729. @param lowmark the lower watermark to set
  730. @param highmark the high watermark to set
  731. */
  732. void bufferevent_setwatermark(struct bufferevent *bufev, short events,
  733. size_t lowmark, size_t highmark);
  734. #define EVBUFFER_LENGTH(x) (x)->off
  735. #define EVBUFFER_DATA(x) (x)->buffer
  736. #define EVBUFFER_INPUT(x) (x)->input
  737. #define EVBUFFER_OUTPUT(x) (x)->output
  738. /**
  739. Allocate storage for a new evbuffer.
  740. @return a pointer to a newly allocated evbuffer struct, or NULL if an error
  741. occurred
  742. */
  743. struct evbuffer *evbuffer_new(void);
  744. /**
  745. Deallocate storage for an evbuffer.
  746. @param pointer to the evbuffer to be freed
  747. */
  748. void evbuffer_free(struct evbuffer *);
  749. /**
  750. Expands the available space in an event buffer.
  751. Expands the available space in the event buffer to at least datlen
  752. @param buf the event buffer to be expanded
  753. @param datlen the new minimum length requirement
  754. @return 0 if successful, or -1 if an error occurred
  755. */
  756. int evbuffer_expand(struct evbuffer *, size_t);
  757. /**
  758. Append data to the end of an evbuffer.
  759. @param buf the event buffer to be appended to
  760. @param data pointer to the beginning of the data buffer
  761. @param datlen the number of bytes to be copied from the data buffer
  762. */
  763. int evbuffer_add(struct evbuffer *, const void *, size_t);
  764. /**
  765. Read data from an event buffer and drain the bytes read.
  766. @param buf the event buffer to be read from
  767. @param data the destination buffer to store the result
  768. @param datlen the maximum size of the destination buffer
  769. @return the number of bytes read
  770. */
  771. int evbuffer_remove(struct evbuffer *, void *, size_t);
  772. /**
  773. * Read a single line from an event buffer.
  774. *
  775. * Reads a line terminated by either '\r\n', '\n\r' or '\r' or '\n'.
  776. * The returned buffer needs to be freed by the caller.
  777. *
  778. * @param buffer the evbuffer to read from
  779. * @return pointer to a single line, or NULL if an error occurred
  780. */
  781. char *evbuffer_readline(struct evbuffer *);
  782. /** Used to tell evbuffer_readln what kind of line-ending to look for.
  783. */
  784. enum evbuffer_eol_style {
  785. /** Any sequence of CR and LF characters is acceptable as an EOL. */
  786. EVBUFFER_EOL_ANY,
  787. /** An EOL is an LF, optionally preceded by a CR. This style is
  788. * most useful for implementing text-based internet protocols. */
  789. EVBUFFER_EOL_CRLF,
  790. /** An EOL is a CR followed by an LF. */
  791. EVBUFFER_EOL_CRLF_STRICT,
  792. /** An EOL is a LF. */
  793. EVBUFFER_EOL_LF
  794. };
  795. /**
  796. * Read a single line from an event buffer.
  797. *
  798. * Reads a line terminated by an EOL as determined by the evbuffer_eol_style
  799. * argument. Returns a newly allocated nul-terminated string; the caller must
  800. * free the returned value. The EOL is not included in the returned string.
  801. *
  802. * @param buffer the evbuffer to read from
  803. * @param n_read_out if non-NULL, points to a size_t that is set to the
  804. * number of characters in the returned string. This is useful for
  805. * strings that can contain NUL characters.
  806. * @param eol_style the style of line-ending to use.
  807. * @return pointer to a single line, or NULL if an error occurred
  808. */
  809. char *evbuffer_readln(struct evbuffer *buffer, size_t *n_read_out,
  810. enum evbuffer_eol_style eol_style);
  811. /**
  812. Move data from one evbuffer into another evbuffer.
  813. This is a destructive add. The data from one buffer moves into
  814. the other buffer. The destination buffer is expanded as needed.
  815. @param outbuf the output buffer
  816. @param inbuf the input buffer
  817. @return 0 if successful, or -1 if an error occurred
  818. */
  819. int evbuffer_add_buffer(struct evbuffer *, struct evbuffer *);
  820. /**
  821. Append a formatted string to the end of an evbuffer.
  822. @param buf the evbuffer that will be appended to
  823. @param fmt a format string
  824. @param ... arguments that will be passed to printf(3)
  825. @return The number of bytes added if successful, or -1 if an error occurred.
  826. */
  827. int evbuffer_add_printf(struct evbuffer *, const char *fmt, ...)
  828. #ifdef __GNUC__
  829. __attribute__((format(printf, 2, 3)))
  830. #endif
  831. ;
  832. /**
  833. Append a va_list formatted string to the end of an evbuffer.
  834. @param buf the evbuffer that will be appended to
  835. @param fmt a format string
  836. @param ap a varargs va_list argument array that will be passed to vprintf(3)
  837. @return The number of bytes added if successful, or -1 if an error occurred.
  838. */
  839. int evbuffer_add_vprintf(struct evbuffer *, const char *fmt, va_list ap);
  840. /**
  841. Remove a specified number of bytes data from the beginning of an evbuffer.
  842. @param buf the evbuffer to be drained
  843. @param len the number of bytes to drain from the beginning of the buffer
  844. */
  845. void evbuffer_drain(struct evbuffer *, size_t);
  846. /**
  847. Write the contents of an evbuffer to a file descriptor.
  848. The evbuffer will be drained after the bytes have been successfully written.
  849. @param buffer the evbuffer to be written and drained
  850. @param fd the file descriptor to be written to
  851. @return the number of bytes written, or -1 if an error occurred
  852. @see evbuffer_read()
  853. */
  854. int evbuffer_write(struct evbuffer *, int);
  855. /**
  856. Read from a file descriptor and store the result in an evbuffer.
  857. @param buf the evbuffer to store the result
  858. @param fd the file descriptor to read from
  859. @param howmuch the number of bytes to be read
  860. @return the number of bytes read, or -1 if an error occurred
  861. @see evbuffer_write()
  862. */
  863. int evbuffer_read(struct evbuffer *, int, int);
  864. /**
  865. Find a string within an evbuffer.
  866. @param buffer the evbuffer to be searched
  867. @param what the string to be searched for
  868. @param len the length of the search string
  869. @return a pointer to the beginning of the search string, or NULL if the search failed.
  870. */
  871. u_char *evbuffer_find(struct evbuffer *, const u_char *, size_t);
  872. /**
  873. Set a callback to invoke when the evbuffer is modified.
  874. @param buffer the evbuffer to be monitored
  875. @param cb the callback function to invoke when the evbuffer is modified
  876. @param cbarg an argument to be provided to the callback function
  877. */
  878. void evbuffer_setcb(struct evbuffer *, void (*)(struct evbuffer *, size_t, size_t, void *), void *);
  879. /*
  880. * Marshaling tagged data - We assume that all tags are inserted in their
  881. * numeric order - so that unknown tags will always be higher than the
  882. * known ones - and we can just ignore the end of an event buffer.
  883. */
  884. void evtag_init(void);
  885. void evtag_marshal(struct evbuffer *evbuf, ev_uint32_t tag, const void *data,
  886. ev_uint32_t len);
  887. /**
  888. Encode an integer and store it in an evbuffer.
  889. We encode integer's by nibbles; the first nibble contains the number
  890. of significant nibbles - 1; this allows us to encode up to 64-bit
  891. integers. This function is byte-order independent.
  892. @param evbuf evbuffer to store the encoded number
  893. @param number a 32-bit integer
  894. */
  895. void encode_int(struct evbuffer *evbuf, ev_uint32_t number);
  896. void evtag_marshal_int(struct evbuffer *evbuf, ev_uint32_t tag,
  897. ev_uint32_t integer);
  898. void evtag_marshal_string(struct evbuffer *buf, ev_uint32_t tag,
  899. const char *string);
  900. void evtag_marshal_timeval(struct evbuffer *evbuf, ev_uint32_t tag,
  901. struct timeval *tv);
  902. int evtag_unmarshal(struct evbuffer *src, ev_uint32_t *ptag,
  903. struct evbuffer *dst);
  904. int evtag_peek(struct evbuffer *evbuf, ev_uint32_t *ptag);
  905. int evtag_peek_length(struct evbuffer *evbuf, ev_uint32_t *plength);
  906. int evtag_payload_length(struct evbuffer *evbuf, ev_uint32_t *plength);
  907. int evtag_consume(struct evbuffer *evbuf);
  908. int evtag_unmarshal_int(struct evbuffer *evbuf, ev_uint32_t need_tag,
  909. ev_uint32_t *pinteger);
  910. int evtag_unmarshal_fixed(struct evbuffer *src, ev_uint32_t need_tag,
  911. void *data, size_t len);
  912. int evtag_unmarshal_string(struct evbuffer *evbuf, ev_uint32_t need_tag,
  913. char **pstring);
  914. int evtag_unmarshal_timeval(struct evbuffer *evbuf, ev_uint32_t need_tag,
  915. struct timeval *ptv);
  916. #ifdef __cplusplus
  917. }
  918. #endif
  919. #endif /* _EVENT_H_ */