xref: /freebsd/contrib/libevent/include/event2/bufferevent.h (revision 5ca8e32633c4ffbbcd6762e5888b6a4ba0708c6c)
1 /*
2  * Copyright (c) 2000-2007 Niels Provos <provos@citi.umich.edu>
3  * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. The name of the author may not be used to endorse or promote products
14  *    derived from this software without specific prior written permission.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
17  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
18  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
19  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
20  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
21  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
22  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
23  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
25  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26  */
27 #ifndef EVENT2_BUFFEREVENT_H_INCLUDED_
28 #define EVENT2_BUFFEREVENT_H_INCLUDED_
29 
30 /**
31    @file event2/bufferevent.h
32 
33   Functions for buffering data for network sending or receiving.  Bufferevents
34   are higher level than evbuffers: each has an underlying evbuffer for reading
35   and one for writing, and callbacks that are invoked under certain
36   circumstances.
37 
38   A bufferevent provides input and output buffers that get filled and
39   drained automatically.  The user of a bufferevent no longer deals
40   directly with the I/O, but instead is reading from input and writing
41   to output buffers.
42 
43   Once initialized, the bufferevent structure can be used repeatedly
44   with bufferevent_enable() and bufferevent_disable().
45 
46   When reading is enabled, the bufferevent will try to read from the
47   file descriptor onto its input buffer, and call the read callback.
48   When writing is enabled, the bufferevent will try to write data onto its
49   file descriptor when the output buffer has enough data, and call the write
50   callback when the output buffer is sufficiently drained.
51 
52   Bufferevents come in several flavors, including:
53 
54   <dl>
55     <dt>Socket-based bufferevents</dt>
56       <dd>A bufferevent that reads and writes data onto a network
57           socket. Created with bufferevent_socket_new().</dd>
58 
59     <dt>Paired bufferevents</dt>
60       <dd>A pair of bufferevents that send and receive data to one
61           another without touching the network.  Created with
62           bufferevent_pair_new().</dd>
63 
64     <dt>Filtering bufferevents</dt>
65        <dd>A bufferevent that transforms data, and sends or receives it
66           over another underlying bufferevent.  Created with
67           bufferevent_filter_new().</dd>
68 
69     <dt>SSL-backed bufferevents</dt>
70       <dd>A bufferevent that uses the openssl library to send and
71           receive data over an encrypted connection. Created with
72 	  bufferevent_openssl_socket_new() or
73 	  bufferevent_openssl_filter_new().</dd>
74   </dl>
75  */
76 
77 #include <event2/visibility.h>
78 
79 #ifdef __cplusplus
80 extern "C" {
81 #endif
82 
83 #include <event2/event-config.h>
84 #ifdef EVENT__HAVE_SYS_TYPES_H
85 #include <sys/types.h>
86 #endif
87 #ifdef EVENT__HAVE_SYS_TIME_H
88 #include <sys/time.h>
89 #endif
90 
91 /* For int types. */
92 #include <event2/util.h>
93 
94 /** @name Bufferevent event codes
95 
96     These flags are passed as arguments to a bufferevent's event callback.
97 
98     @{
99 */
100 #define BEV_EVENT_READING	0x01	/**< error encountered while reading */
101 #define BEV_EVENT_WRITING	0x02	/**< error encountered while writing */
102 #define BEV_EVENT_EOF		0x10	/**< eof file reached */
103 #define BEV_EVENT_ERROR		0x20	/**< unrecoverable error encountered */
104 #define BEV_EVENT_TIMEOUT	0x40	/**< user-specified timeout reached */
105 #define BEV_EVENT_CONNECTED	0x80	/**< connect operation finished. */
106 /**@}*/
107 
108 /**
109    An opaque type for handling buffered IO
110 
111    @see event2/bufferevent.h
112  */
113 struct bufferevent
114 #ifdef EVENT_IN_DOXYGEN_
115 {}
116 #endif
117 ;
118 struct event_base;
119 struct evbuffer;
120 struct sockaddr;
121 
122 /**
123    A read or write callback for a bufferevent.
124 
125    The read callback is triggered when new data arrives in the input
126    buffer and the amount of readable data exceed the low watermark
127    which is 0 by default.
128 
129    The write callback is triggered if the write buffer has been
130    exhausted or fell below its low watermark.
131 
132    @param bev the bufferevent that triggered the callback
133    @param ctx the user-specified context for this bufferevent
134  */
135 typedef void (*bufferevent_data_cb)(struct bufferevent *bev, void *ctx);
136 
137 /**
138    An event/error callback for a bufferevent.
139 
140    The event callback is triggered if either an EOF condition or another
141    unrecoverable error was encountered.
142 
143    For bufferevents with deferred callbacks, this is a bitwise OR of all errors
144    that have happened on the bufferevent since the last callback invocation.
145 
146    @param bev the bufferevent for which the error condition was reached
147    @param what a conjunction of flags: BEV_EVENT_READING or BEV_EVENT_WRITING
148 	  to indicate if the error was encountered on the read or write path,
149 	  and one of the following flags: BEV_EVENT_EOF, BEV_EVENT_ERROR,
150 	  BEV_EVENT_TIMEOUT, BEV_EVENT_CONNECTED.
151 
152    @param ctx the user-specified context for this bufferevent
153 */
154 typedef void (*bufferevent_event_cb)(struct bufferevent *bev, short what, void *ctx);
155 
156 /** Options that can be specified when creating a bufferevent */
157 enum bufferevent_options {
158 	/** If set, we close the underlying file
159 	 * descriptor/bufferevent/whatever when this bufferevent is freed. */
160 	BEV_OPT_CLOSE_ON_FREE = (1<<0),
161 
162 	/** If set, and threading is enabled, operations on this bufferevent
163 	 * are protected by a lock */
164 	BEV_OPT_THREADSAFE = (1<<1),
165 
166 	/** If set, callbacks are run deferred in the event loop. */
167 	BEV_OPT_DEFER_CALLBACKS = (1<<2),
168 
169 	/** If set, callbacks are executed without locks being held on the
170 	* bufferevent.  This option currently requires that
171 	* BEV_OPT_DEFER_CALLBACKS also be set; a future version of Libevent
172 	* might remove the requirement.*/
173 	BEV_OPT_UNLOCK_CALLBACKS = (1<<3)
174 };
175 
176 /**
177   Create a new socket bufferevent over an existing socket.
178 
179   @param base the event base to associate with the new bufferevent.
180   @param fd the file descriptor from which data is read and written to.
181 	    This file descriptor is not allowed to be a pipe(2).
182 	    It is safe to set the fd to -1, so long as you later
183 	    set it with bufferevent_setfd or bufferevent_socket_connect().
184   @param options Zero or more BEV_OPT_* flags
185   @return a pointer to a newly allocated bufferevent struct, or NULL if an
186 	  error occurred
187   @see bufferevent_free()
188   */
189 EVENT2_EXPORT_SYMBOL
190 struct bufferevent *bufferevent_socket_new(struct event_base *base, evutil_socket_t fd, int options);
191 
192 /**
193    Launch a connect() attempt with a socket-based bufferevent.
194 
195    When the connect succeeds, the eventcb will be invoked with
196    BEV_EVENT_CONNECTED set.
197 
198    If the bufferevent does not already have a socket set, we allocate a new
199    socket here and make it nonblocking before we begin.
200 
201    If no address is provided, we assume that the socket is already connecting,
202    and configure the bufferevent so that a BEV_EVENT_CONNECTED event will be
203    yielded when it is done connecting.
204 
205    @param bufev an existing bufferevent allocated with
206        bufferevent_socket_new().
207    @param addr the address we should connect to
208    @param socklen The length of the address
209    @return 0 on success, -1 on failure.
210  */
211 EVENT2_EXPORT_SYMBOL
212 int bufferevent_socket_connect(struct bufferevent *, const struct sockaddr *, int);
213 
214 struct evdns_base;
215 /**
216    Resolve the hostname 'hostname' and connect to it as with
217    bufferevent_socket_connect().
218 
219    @param bufev An existing bufferevent allocated with bufferevent_socket_new()
220    @param evdns_base Optionally, an evdns_base to use for resolving hostnames
221       asynchronously. May be set to NULL for a blocking resolve.
222    @param family A preferred address family to resolve addresses to, or
223       AF_UNSPEC for no preference.  Only AF_INET, AF_INET6, and AF_UNSPEC are
224       supported.
225    @param hostname The hostname to resolve; see below for notes on recognized
226       formats
227    @param port The port to connect to on the resolved address.
228    @return 0 if successful, -1 on failure.
229 
230    Recognized hostname formats are:
231 
232        www.example.com	(hostname)
233        1.2.3.4		(ipv4address)
234        ::1		(ipv6address)
235        [::1]		([ipv6address])
236 
237    Performance note: If you do not provide an evdns_base, this function
238    may block while it waits for a DNS response.	 This is probably not
239    what you want.
240  */
241 EVENT2_EXPORT_SYMBOL
242 int bufferevent_socket_connect_hostname(struct bufferevent *,
243     struct evdns_base *, int, const char *, int);
244 
245 /**
246    Return the error code for the last failed DNS lookup attempt made by
247    bufferevent_socket_connect_hostname().
248 
249    @param bev The bufferevent object.
250    @return DNS error code.
251    @see evutil_gai_strerror()
252 */
253 EVENT2_EXPORT_SYMBOL
254 int bufferevent_socket_get_dns_error(struct bufferevent *bev);
255 
256 /**
257   Assign a bufferevent to a specific event_base.
258 
259   NOTE that only socket bufferevents support this function.
260 
261   @param base an event_base returned by event_init()
262   @param bufev a bufferevent struct returned by bufferevent_new()
263      or bufferevent_socket_new()
264   @return 0 if successful, or -1 if an error occurred
265   @see bufferevent_new()
266  */
267 EVENT2_EXPORT_SYMBOL
268 int bufferevent_base_set(struct event_base *base, struct bufferevent *bufev);
269 
270 /**
271    Return the event_base used by a bufferevent
272 */
273 EVENT2_EXPORT_SYMBOL
274 struct event_base *bufferevent_get_base(struct bufferevent *bev);
275 
276 /**
277   Assign a priority to a bufferevent.
278 
279   Only supported for socket bufferevents.
280 
281   @param bufev a bufferevent struct
282   @param pri the priority to be assigned
283   @return 0 if successful, or -1 if an error occurred
284   */
285 EVENT2_EXPORT_SYMBOL
286 int bufferevent_priority_set(struct bufferevent *bufev, int pri);
287 
288 /**
289    Return the priority of a bufferevent.
290 
291    Only supported for socket bufferevents
292  */
293 EVENT2_EXPORT_SYMBOL
294 int bufferevent_get_priority(const struct bufferevent *bufev);
295 
296 /**
297   Deallocate the storage associated with a bufferevent structure.
298 
299   If there is pending data to write on the bufferevent, it probably won't be
300   flushed before the bufferevent is freed.
301 
302   @param bufev the bufferevent structure to be freed.
303   */
304 EVENT2_EXPORT_SYMBOL
305 void bufferevent_free(struct bufferevent *bufev);
306 
307 
308 /**
309   Changes the callbacks for a bufferevent.
310 
311   @param bufev the bufferevent object for which to change callbacks
312   @param readcb callback to invoke when there is data to be read, or NULL if
313 	 no callback is desired
314   @param writecb callback to invoke when the file descriptor is ready for
315 	 writing, or NULL if no callback is desired
316   @param eventcb callback to invoke when there is an event on the file
317 	 descriptor
318   @param cbarg an argument that will be supplied to each of the callbacks
319 	 (readcb, writecb, and errorcb)
320   @see bufferevent_new()
321   */
322 EVENT2_EXPORT_SYMBOL
323 void bufferevent_setcb(struct bufferevent *bufev,
324     bufferevent_data_cb readcb, bufferevent_data_cb writecb,
325     bufferevent_event_cb eventcb, void *cbarg);
326 
327 /**
328  Retrieves the callbacks for a bufferevent.
329 
330  @param bufev the bufferevent to examine.
331  @param readcb_ptr if readcb_ptr is nonnull, *readcb_ptr is set to the current
332     read callback for the bufferevent.
333  @param writecb_ptr if writecb_ptr is nonnull, *writecb_ptr is set to the
334     current write callback for the bufferevent.
335  @param eventcb_ptr if eventcb_ptr is nonnull, *eventcb_ptr is set to the
336     current event callback for the bufferevent.
337  @param cbarg_ptr if cbarg_ptr is nonnull, *cbarg_ptr is set to the current
338     callback argument for the bufferevent.
339  @see buffervent_setcb()
340 */
341 EVENT2_EXPORT_SYMBOL
342 void bufferevent_getcb(struct bufferevent *bufev,
343     bufferevent_data_cb *readcb_ptr,
344     bufferevent_data_cb *writecb_ptr,
345     bufferevent_event_cb *eventcb_ptr,
346     void **cbarg_ptr);
347 
348 /**
349   Changes the file descriptor on which the bufferevent operates.
350   Not supported for all bufferevent types.
351 
352   @param bufev the bufferevent object for which to change the file descriptor
353   @param fd the file descriptor to operate on
354 */
355 EVENT2_EXPORT_SYMBOL
356 int bufferevent_setfd(struct bufferevent *bufev, evutil_socket_t fd);
357 
358 /**
359    Returns the file descriptor associated with a bufferevent, or -1 if
360    no file descriptor is associated with the bufferevent.
361  */
362 EVENT2_EXPORT_SYMBOL
363 evutil_socket_t bufferevent_getfd(struct bufferevent *bufev);
364 
365 /**
366    Returns the underlying bufferevent associated with a bufferevent (if
367    the bufferevent is a wrapper), or NULL if there is no underlying bufferevent.
368  */
369 EVENT2_EXPORT_SYMBOL
370 struct bufferevent *bufferevent_get_underlying(struct bufferevent *bufev);
371 
372 /**
373   Write data to a bufferevent buffer.
374 
375   The bufferevent_write() function can be used to write data to the file
376   descriptor.  The data is appended to the output buffer and written to the
377   descriptor automatically as it becomes available for writing.
378 
379   @param bufev the bufferevent to be written to
380   @param data a pointer to the data to be written
381   @param size the length of the data, in bytes
382   @return 0 if successful, or -1 if an error occurred
383   @see bufferevent_write_buffer()
384   */
385 EVENT2_EXPORT_SYMBOL
386 int bufferevent_write(struct bufferevent *bufev,
387     const void *data, size_t size);
388 
389 
390 /**
391   Write data from an evbuffer to a bufferevent buffer.	The evbuffer is
392   being drained as a result.
393 
394   @param bufev the bufferevent to be written to
395   @param buf the evbuffer to be written
396   @return 0 if successful, or -1 if an error occurred
397   @see bufferevent_write()
398  */
399 EVENT2_EXPORT_SYMBOL
400 int bufferevent_write_buffer(struct bufferevent *bufev, struct evbuffer *buf);
401 
402 
403 /**
404   Read data from a bufferevent buffer.
405 
406   The bufferevent_read() function is used to read data from the input buffer.
407 
408   @param bufev the bufferevent to be read from
409   @param data pointer to a buffer that will store the data
410   @param size the size of the data buffer, in bytes
411   @return the amount of data read, in bytes.
412  */
413 EVENT2_EXPORT_SYMBOL
414 size_t bufferevent_read(struct bufferevent *bufev, void *data, size_t size);
415 
416 /**
417   Read data from a bufferevent buffer into an evbuffer.	 This avoids
418   memory copies.
419 
420   @param bufev the bufferevent to be read from
421   @param buf the evbuffer to which to add data
422   @return 0 if successful, or -1 if an error occurred.
423  */
424 EVENT2_EXPORT_SYMBOL
425 int bufferevent_read_buffer(struct bufferevent *bufev, struct evbuffer *buf);
426 
427 /**
428    Returns the input buffer.
429 
430    The user MUST NOT set the callback on this buffer.
431 
432    @param bufev the bufferevent from which to get the evbuffer
433    @return the evbuffer object for the input buffer
434  */
435 
436 EVENT2_EXPORT_SYMBOL
437 struct evbuffer *bufferevent_get_input(struct bufferevent *bufev);
438 
439 /**
440    Returns the output buffer.
441 
442    The user MUST NOT set the callback on this buffer.
443 
444    When filters are being used, the filters need to be manually
445    triggered if the output buffer was manipulated.
446 
447    @param bufev the bufferevent from which to get the evbuffer
448    @return the evbuffer object for the output buffer
449  */
450 
451 EVENT2_EXPORT_SYMBOL
452 struct evbuffer *bufferevent_get_output(struct bufferevent *bufev);
453 
454 /**
455   Enable a bufferevent.
456 
457   @param bufev the bufferevent to be enabled
458   @param event any combination of EV_READ | EV_WRITE.
459   @return 0 if successful, or -1 if an error occurred
460   @see bufferevent_disable()
461  */
462 EVENT2_EXPORT_SYMBOL
463 int bufferevent_enable(struct bufferevent *bufev, short event);
464 
465 /**
466   Disable a bufferevent.
467 
468   @param bufev the bufferevent to be disabled
469   @param event any combination of EV_READ | EV_WRITE.
470   @return 0 if successful, or -1 if an error occurred
471   @see bufferevent_enable()
472  */
473 EVENT2_EXPORT_SYMBOL
474 int bufferevent_disable(struct bufferevent *bufev, short event);
475 
476 /**
477    Return the events that are enabled on a given bufferevent.
478 
479    @param bufev the bufferevent to inspect
480    @return A combination of EV_READ | EV_WRITE
481  */
482 EVENT2_EXPORT_SYMBOL
483 short bufferevent_get_enabled(struct bufferevent *bufev);
484 
485 /**
486   Set the read and write timeout for a bufferevent.
487 
488   A bufferevent's timeout will fire the first time that the indicated
489   amount of time has elapsed since a successful read or write operation,
490   during which the bufferevent was trying to read or write.
491 
492   (In other words, if reading or writing is disabled, or if the
493   bufferevent's read or write operation has been suspended because
494   there's no data to write, or not enough bandwidth, or so on, the
495   timeout isn't active.  The timeout only becomes active when we we're
496   willing to actually read or write.)
497 
498   Calling bufferevent_enable or setting a timeout for a bufferevent
499   whose timeout is already pending resets its timeout.
500 
501   If the timeout elapses, the corresponding operation (EV_READ or
502   EV_WRITE) becomes disabled until you re-enable it again.  The
503   bufferevent's event callback is called with the
504   BEV_EVENT_TIMEOUT|BEV_EVENT_READING or
505   BEV_EVENT_TIMEOUT|BEV_EVENT_WRITING.
506 
507   @param bufev the bufferevent to be modified
508   @param timeout_read the read timeout, or NULL
509   @param timeout_write the write timeout, or NULL
510  */
511 EVENT2_EXPORT_SYMBOL
512 int bufferevent_set_timeouts(struct bufferevent *bufev,
513     const struct timeval *timeout_read, const struct timeval *timeout_write);
514 
515 /**
516   Sets the watermarks for read and write events.
517 
518   On input, a bufferevent does not invoke the user read callback unless
519   there is at least low watermark data in the buffer.	If the read buffer
520   is beyond the high watermark, the bufferevent stops reading from the network.
521   But be aware that bufferevent input/read buffer can overrun high watermark
522   limit (typical example is openssl bufferevent), so you should not relay in
523   this.
524 
525   On output, the user write callback is invoked whenever the buffered data
526   falls below the low watermark.  Filters that write to this bufev will try
527   not to write more bytes to this buffer than the high watermark would allow,
528   except when flushing.
529 
530   @param bufev the bufferevent to be modified
531   @param events EV_READ, EV_WRITE or both
532   @param lowmark the lower watermark to set
533   @param highmark the high watermark to set
534 */
535 
536 EVENT2_EXPORT_SYMBOL
537 void bufferevent_setwatermark(struct bufferevent *bufev, short events,
538     size_t lowmark, size_t highmark);
539 
540 /**
541   Retrieves the watermarks for read or write events.
542   Returns non-zero if events contains not only EV_READ or EV_WRITE.
543   Returns zero if events equal EV_READ or EV_WRITE
544 
545   @param bufev the bufferevent to be examined
546   @param events EV_READ or EV_WRITE
547   @param lowmark receives the lower watermark if not NULL
548   @param highmark receives the high watermark if not NULL
549 */
550 EVENT2_EXPORT_SYMBOL
551 int bufferevent_getwatermark(struct bufferevent *bufev, short events,
552     size_t *lowmark, size_t *highmark);
553 
554 /**
555    Acquire the lock on a bufferevent.  Has no effect if locking was not
556    enabled with BEV_OPT_THREADSAFE.
557  */
558 EVENT2_EXPORT_SYMBOL
559 void bufferevent_lock(struct bufferevent *bufev);
560 
561 /**
562    Release the lock on a bufferevent.  Has no effect if locking was not
563    enabled with BEV_OPT_THREADSAFE.
564  */
565 EVENT2_EXPORT_SYMBOL
566 void bufferevent_unlock(struct bufferevent *bufev);
567 
568 
569 /**
570  * Public interface to manually increase the reference count of a bufferevent
571  * this is useful in situations where a user may reference the bufferevent
572  * somewhere else (unknown to libevent)
573  *
574  * @param bufev the bufferevent to increase the refcount on
575  *
576  */
577 EVENT2_EXPORT_SYMBOL
578 void bufferevent_incref(struct bufferevent *bufev);
579 
580 /**
581  * Public interface to manually decrement the reference count of a bufferevent
582  *
583  * Warning: make sure you know what you're doing. This is mainly used in
584  * conjunction with bufferevent_incref(). This will free up all data associated
585  * with a bufferevent if the reference count hits 0.
586  *
587  * @param bufev the bufferevent to decrement the refcount on
588  *
589  * @return 1 if the bufferevent was freed, otherwise 0 (still referenced)
590  */
591 EVENT2_EXPORT_SYMBOL
592 int bufferevent_decref(struct bufferevent *bufev);
593 
594 /**
595    Flags that can be passed into filters to let them know how to
596    deal with the incoming data.
597 */
598 enum bufferevent_flush_mode {
599 	/** usually set when processing data */
600 	BEV_NORMAL = 0,
601 
602 	/** want to checkpoint all data sent. */
603 	BEV_FLUSH = 1,
604 
605 	/** encountered EOF on read or done sending data */
606 	BEV_FINISHED = 2
607 };
608 
609 /**
610    Triggers the bufferevent to produce more data if possible.
611 
612    @param bufev the bufferevent object
613    @param iotype either EV_READ or EV_WRITE or both.
614    @param mode either BEV_NORMAL or BEV_FLUSH or BEV_FINISHED
615    @return -1 on failure, 0 if no data was produces, 1 if data was produced
616  */
617 EVENT2_EXPORT_SYMBOL
618 int bufferevent_flush(struct bufferevent *bufev,
619     short iotype,
620     enum bufferevent_flush_mode mode);
621 
622 /**
623    Flags for bufferevent_trigger(_event) that modify when and how to trigger
624    the callback.
625 */
626 enum bufferevent_trigger_options {
627 	/** trigger the callback regardless of the watermarks */
628 	BEV_TRIG_IGNORE_WATERMARKS = (1<<16),
629 
630 	/** defer even if the callbacks are not */
631 	BEV_TRIG_DEFER_CALLBACKS = BEV_OPT_DEFER_CALLBACKS
632 
633 	/* (Note: for internal reasons, these need to be disjoint from
634 	 * bufferevent_options, except when they mean the same thing. */
635 };
636 
637 /**
638    Triggers bufferevent data callbacks.
639 
640    The function will honor watermarks unless options contain
641    BEV_TRIG_IGNORE_WATERMARKS. If the options contain BEV_OPT_DEFER_CALLBACKS,
642    the callbacks are deferred.
643 
644    @param bufev the bufferevent object
645    @param iotype either EV_READ or EV_WRITE or both.
646    @param options
647  */
648 EVENT2_EXPORT_SYMBOL
649 void bufferevent_trigger(struct bufferevent *bufev, short iotype,
650     int options);
651 
652 /**
653    Triggers the bufferevent event callback.
654 
655    If the options contain BEV_OPT_DEFER_CALLBACKS, the callbacks are deferred.
656 
657    @param bufev the bufferevent object
658    @param what the flags to pass onto the event callback
659    @param options
660  */
661 EVENT2_EXPORT_SYMBOL
662 void bufferevent_trigger_event(struct bufferevent *bufev, short what,
663     int options);
664 
665 /**
666    @name Filtering support
667 
668    @{
669 */
670 /**
671    Values that filters can return.
672  */
673 enum bufferevent_filter_result {
674 	/** everything is okay */
675 	BEV_OK = 0,
676 
677 	/** the filter needs to read more data before output */
678 	BEV_NEED_MORE = 1,
679 
680 	/** the filter encountered a critical error, no further data
681 	    can be processed. */
682 	BEV_ERROR = 2
683 };
684 
685 /** A callback function to implement a filter for a bufferevent.
686 
687     @param src An evbuffer to drain data from.
688     @param dst An evbuffer to add data to.
689     @param limit A suggested upper bound of bytes to write to dst.
690        The filter may ignore this value, but doing so means that
691        it will overflow the high-water mark associated with dst.
692        -1 means "no limit".
693     @param mode Whether we should write data as may be convenient
694        (BEV_NORMAL), or flush as much data as we can (BEV_FLUSH),
695        or flush as much as we can, possibly including an end-of-stream
696        marker (BEV_FINISH).
697     @param ctx A user-supplied pointer.
698 
699     @return BEV_OK if we wrote some data; BEV_NEED_MORE if we can't
700        produce any more output until we get some input; and BEV_ERROR
701        on an error.
702  */
703 typedef enum bufferevent_filter_result (*bufferevent_filter_cb)(
704     struct evbuffer *src, struct evbuffer *dst, ev_ssize_t dst_limit,
705     enum bufferevent_flush_mode mode, void *ctx);
706 
707 /**
708    Allocate a new filtering bufferevent on top of an existing bufferevent.
709 
710    @param underlying the underlying bufferevent.
711    @param input_filter The filter to apply to data we read from the underlying
712      bufferevent
713    @param output_filter The filer to apply to data we write to the underlying
714      bufferevent
715    @param options A bitfield of bufferevent options.
716    @param free_context A function to use to free the filter context when
717      this bufferevent is freed.
718    @param ctx A context pointer to pass to the filter functions.
719  */
720 EVENT2_EXPORT_SYMBOL
721 struct bufferevent *
722 bufferevent_filter_new(struct bufferevent *underlying,
723 		       bufferevent_filter_cb input_filter,
724 		       bufferevent_filter_cb output_filter,
725 		       int options,
726 		       void (*free_context)(void *),
727 		       void *ctx);
728 /**@}*/
729 
730 /**
731    Allocate a pair of linked bufferevents.  The bufferevents behave as would
732    two bufferevent_sock instances connected to opposite ends of a
733    socketpair(), except that no internal socketpair is allocated.
734 
735    @param base The event base to associate with the socketpair.
736    @param options A set of options for this bufferevent
737    @param pair A pointer to an array to hold the two new bufferevent objects.
738    @return 0 on success, -1 on failure.
739  */
740 EVENT2_EXPORT_SYMBOL
741 int bufferevent_pair_new(struct event_base *base, int options,
742     struct bufferevent *pair[2]);
743 
744 /**
745    Given one bufferevent returned by bufferevent_pair_new(), returns the
746    other one if it still exists.  Otherwise returns NULL.
747  */
748 EVENT2_EXPORT_SYMBOL
749 struct bufferevent *bufferevent_pair_get_partner(struct bufferevent *bev);
750 
751 /**
752    Abstract type used to configure rate-limiting on a bufferevent or a group
753    of bufferevents.
754  */
755 struct ev_token_bucket_cfg;
756 
757 /**
758    A group of bufferevents which are configured to respect the same rate
759    limit.
760 */
761 struct bufferevent_rate_limit_group;
762 
763 /** Maximum configurable rate- or burst-limit. */
764 #define EV_RATE_LIMIT_MAX EV_SSIZE_MAX
765 
766 /**
767    Initialize and return a new object to configure the rate-limiting behavior
768    of bufferevents.
769 
770    @param read_rate The maximum number of bytes to read per tick on
771      average.
772    @param read_burst The maximum number of bytes to read in any single tick.
773    @param write_rate The maximum number of bytes to write per tick on
774      average.
775    @param write_burst The maximum number of bytes to write in any single tick.
776    @param tick_len The length of a single tick.	 Defaults to one second.
777      Any fractions of a millisecond are ignored.
778 
779    Note that all rate-limits hare are currently best-effort: future versions
780    of Libevent may implement them more tightly.
781  */
782 EVENT2_EXPORT_SYMBOL
783 struct ev_token_bucket_cfg *ev_token_bucket_cfg_new(
784 	size_t read_rate, size_t read_burst,
785 	size_t write_rate, size_t write_burst,
786 	const struct timeval *tick_len);
787 
788 /** Free all storage held in 'cfg'.
789 
790     Note: 'cfg' is not currently reference-counted; it is not safe to free it
791     until no bufferevent is using it.
792  */
793 EVENT2_EXPORT_SYMBOL
794 void ev_token_bucket_cfg_free(struct ev_token_bucket_cfg *cfg);
795 
796 /**
797    Set the rate-limit of a the bufferevent 'bev' to the one specified in
798    'cfg'.  If 'cfg' is NULL, disable any per-bufferevent rate-limiting on
799    'bev'.
800 
801    Note that only some bufferevent types currently respect rate-limiting.
802    They are: socket-based bufferevents (normal and IOCP-based), and SSL-based
803    bufferevents.
804 
805    Return 0 on success, -1 on failure.
806  */
807 EVENT2_EXPORT_SYMBOL
808 int bufferevent_set_rate_limit(struct bufferevent *bev,
809     struct ev_token_bucket_cfg *cfg);
810 
811 /**
812    Create a new rate-limit group for bufferevents.  A rate-limit group
813    constrains the maximum number of bytes sent and received, in toto,
814    by all of its bufferevents.
815 
816    @param base An event_base to run any necessary timeouts for the group.
817       Note that all bufferevents in the group do not necessarily need to share
818       this event_base.
819    @param cfg The rate-limit for this group.
820 
821    Note that all rate-limits hare are currently best-effort: future versions
822    of Libevent may implement them more tightly.
823 
824    Note also that only some bufferevent types currently respect rate-limiting.
825    They are: socket-based bufferevents (normal and IOCP-based), and SSL-based
826    bufferevents.
827  */
828 EVENT2_EXPORT_SYMBOL
829 struct bufferevent_rate_limit_group *bufferevent_rate_limit_group_new(
830 	struct event_base *base,
831 	const struct ev_token_bucket_cfg *cfg);
832 /**
833    Change the rate-limiting settings for a given rate-limiting group.
834 
835    Return 0 on success, -1 on failure.
836 */
837 EVENT2_EXPORT_SYMBOL
838 int bufferevent_rate_limit_group_set_cfg(
839 	struct bufferevent_rate_limit_group *,
840 	const struct ev_token_bucket_cfg *);
841 
842 /**
843    Change the smallest quantum we're willing to allocate to any single
844    bufferevent in a group for reading or writing at a time.
845 
846    The rationale is that, because of TCP/IP protocol overheads and kernel
847    behavior, if a rate-limiting group is so tight on bandwidth that you're
848    only willing to send 1 byte per tick per bufferevent, you might instead
849    want to batch up the reads and writes so that you send N bytes per
850    1/N of the bufferevents (chosen at random) each tick, so you still wind
851    up send 1 byte per tick per bufferevent on average, but you don't send
852    so many tiny packets.
853 
854    The default min-share is currently 64 bytes.
855 
856    Returns 0 on success, -1 on failure.
857  */
858 EVENT2_EXPORT_SYMBOL
859 int bufferevent_rate_limit_group_set_min_share(
860 	struct bufferevent_rate_limit_group *, size_t);
861 
862 /**
863    Free a rate-limiting group.  The group must have no members when
864    this function is called.
865 */
866 EVENT2_EXPORT_SYMBOL
867 void bufferevent_rate_limit_group_free(struct bufferevent_rate_limit_group *);
868 
869 /**
870    Add 'bev' to the list of bufferevents whose aggregate reading and writing
871    is restricted by 'g'.  If 'g' is NULL, remove 'bev' from its current group.
872 
873    A bufferevent may belong to no more than one rate-limit group at a time.
874    If 'bev' is already a member of a group, it will be removed from its old
875    group before being added to 'g'.
876 
877    Return 0 on success and -1 on failure.
878  */
879 EVENT2_EXPORT_SYMBOL
880 int bufferevent_add_to_rate_limit_group(struct bufferevent *bev,
881     struct bufferevent_rate_limit_group *g);
882 
883 /** Remove 'bev' from its current rate-limit group (if any). */
884 EVENT2_EXPORT_SYMBOL
885 int bufferevent_remove_from_rate_limit_group(struct bufferevent *bev);
886 
887 /**
888    Set the size limit for single read operation.
889 
890    Set to 0 for a reasonable default.
891 
892    Return 0 on success and -1 on failure.
893  */
894 EVENT2_EXPORT_SYMBOL
895 int bufferevent_set_max_single_read(struct bufferevent *bev, size_t size);
896 
897 /**
898    Set the size limit for single write operation.
899 
900    Set to 0 for a reasonable default.
901 
902    Return 0 on success and -1 on failure.
903  */
904 EVENT2_EXPORT_SYMBOL
905 int bufferevent_set_max_single_write(struct bufferevent *bev, size_t size);
906 
907 /** Get the current size limit for single read operation. */
908 EVENT2_EXPORT_SYMBOL
909 ev_ssize_t bufferevent_get_max_single_read(struct bufferevent *bev);
910 
911 /** Get the current size limit for single write operation. */
912 EVENT2_EXPORT_SYMBOL
913 ev_ssize_t bufferevent_get_max_single_write(struct bufferevent *bev);
914 
915 /**
916    @name Rate limit inspection
917 
918    Return the current read or write bucket size for a bufferevent.
919    If it is not configured with a per-bufferevent ratelimit, return
920    EV_SSIZE_MAX.  This function does not inspect the group limit, if any.
921    Note that it can return a negative value if the bufferevent has been
922    made to read or write more than its limit.
923 
924    @{
925  */
926 EVENT2_EXPORT_SYMBOL
927 ev_ssize_t bufferevent_get_read_limit(struct bufferevent *bev);
928 EVENT2_EXPORT_SYMBOL
929 ev_ssize_t bufferevent_get_write_limit(struct bufferevent *bev);
930 /*@}*/
931 
932 EVENT2_EXPORT_SYMBOL
933 ev_ssize_t bufferevent_get_max_to_read(struct bufferevent *bev);
934 EVENT2_EXPORT_SYMBOL
935 ev_ssize_t bufferevent_get_max_to_write(struct bufferevent *bev);
936 
937 EVENT2_EXPORT_SYMBOL
938 const struct ev_token_bucket_cfg *bufferevent_get_token_bucket_cfg(const struct bufferevent * bev);
939 
940 /**
941    @name Group Rate limit inspection
942 
943    Return the read or write bucket size for a bufferevent rate limit
944    group.  Note that it can return a negative value if bufferevents in
945    the group have been made to read or write more than their limits.
946 
947    @{
948  */
949 EVENT2_EXPORT_SYMBOL
950 ev_ssize_t bufferevent_rate_limit_group_get_read_limit(
951 	struct bufferevent_rate_limit_group *);
952 EVENT2_EXPORT_SYMBOL
953 ev_ssize_t bufferevent_rate_limit_group_get_write_limit(
954 	struct bufferevent_rate_limit_group *);
955 /*@}*/
956 
957 /**
958    @name Rate limit manipulation
959 
960    Subtract a number of bytes from a bufferevent's read or write bucket.
961    The decrement value can be negative, if you want to manually refill
962    the bucket.	If the change puts the bucket above or below zero, the
963    bufferevent will resume or suspend reading writing as appropriate.
964    These functions make no change in the buckets for the bufferevent's
965    group, if any.
966 
967    Returns 0 on success, -1 on internal error.
968 
969    @{
970  */
971 EVENT2_EXPORT_SYMBOL
972 int bufferevent_decrement_read_limit(struct bufferevent *bev, ev_ssize_t decr);
973 EVENT2_EXPORT_SYMBOL
974 int bufferevent_decrement_write_limit(struct bufferevent *bev, ev_ssize_t decr);
975 /*@}*/
976 
977 /**
978    @name Group rate limit manipulation
979 
980    Subtract a number of bytes from a bufferevent rate-limiting group's
981    read or write bucket.  The decrement value can be negative, if you
982    want to manually refill the bucket.	If the change puts the bucket
983    above or below zero, the bufferevents in the group will resume or
984    suspend reading writing as appropriate.
985 
986    Returns 0 on success, -1 on internal error.
987 
988    @{
989  */
990 EVENT2_EXPORT_SYMBOL
991 int bufferevent_rate_limit_group_decrement_read(
992 	struct bufferevent_rate_limit_group *, ev_ssize_t);
993 EVENT2_EXPORT_SYMBOL
994 int bufferevent_rate_limit_group_decrement_write(
995 	struct bufferevent_rate_limit_group *, ev_ssize_t);
996 /*@}*/
997 
998 
999 /**
1000  * Inspect the total bytes read/written on a group.
1001  *
1002  * Set the variable pointed to by total_read_out to the total number of bytes
1003  * ever read on grp, and the variable pointed to by total_written_out to the
1004  * total number of bytes ever written on grp. */
1005 EVENT2_EXPORT_SYMBOL
1006 void bufferevent_rate_limit_group_get_totals(
1007     struct bufferevent_rate_limit_group *grp,
1008     ev_uint64_t *total_read_out, ev_uint64_t *total_written_out);
1009 
1010 /**
1011  * Reset the total bytes read/written on a group.
1012  *
1013  * Reset the number of bytes read or written on grp as given by
1014  * bufferevent_rate_limit_group_reset_totals(). */
1015 EVENT2_EXPORT_SYMBOL
1016 void
1017 bufferevent_rate_limit_group_reset_totals(
1018 	struct bufferevent_rate_limit_group *grp);
1019 
1020 #ifdef __cplusplus
1021 }
1022 #endif
1023 
1024 #endif /* EVENT2_BUFFEREVENT_H_INCLUDED_ */
1025