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