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