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