xref: /freebsd/contrib/ntp/sntp/libevent/include/event2/buffer.h (revision 49a26c1f9368c5c1106c9d018c3f553dc07042e4)
1 /*
2  * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  * 1. Redistributions of source code must retain the above copyright
8  *    notice, this list of conditions and the following disclaimer.
9  * 2. Redistributions in binary form must reproduce the above copyright
10  *    notice, this list of conditions and the following disclaimer in the
11  *    documentation and/or other materials provided with the distribution.
12  * 3. The name of the author may not be used to endorse or promote products
13  *    derived from this software without specific prior written permission.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
16  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
17  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
18  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
19  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
20  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
21  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
22  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
24  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25  */
26 #ifndef EVENT2_BUFFER_H_INCLUDED_
27 #define EVENT2_BUFFER_H_INCLUDED_
28 
29 /** @file event2/buffer.h
30 
31   Functions for buffering data for network sending or receiving.
32 
33   An evbuffer can be used for preparing data before sending it to
34   the network or conversely for reading data from the network.
35   Evbuffers try to avoid memory copies as much as possible.  As a
36   result, evbuffers can be used to pass data around without actually
37   incurring the overhead of copying the data.
38 
39   A new evbuffer can be allocated with evbuffer_new(), and can be
40   freed with evbuffer_free().  Most users will be using evbuffers via
41   the bufferevent interface.  To access a bufferevent's evbuffers, use
42   bufferevent_get_input() and bufferevent_get_output().
43 
44   There are several guidelines for using evbuffers.
45 
46   - if you already know how much data you are going to add as a result
47     of calling evbuffer_add() multiple times, it makes sense to use
48     evbuffer_expand() first to make sure that enough memory is allocated
49     before hand.
50 
51   - evbuffer_add_buffer() adds the contents of one buffer to the other
52     without incurring any unnecessary memory copies.
53 
54   - evbuffer_add() and evbuffer_add_buffer() do not mix very well:
55     if you use them, you will wind up with fragmented memory in your
56 	buffer.
57 
58   - For high-performance code, you may want to avoid copying data into and out
59     of buffers.  You can skip the copy step by using
60     evbuffer_reserve_space()/evbuffer_commit_space() when writing into a
61     buffer, and evbuffer_peek() when reading.
62 
63   In Libevent 2.0 and later, evbuffers are represented using a linked
64   list of memory chunks, with pointers to the first and last chunk in
65   the chain.
66 
67   As the contents of an evbuffer can be stored in multiple different
68   memory blocks, it cannot be accessed directly.  Instead, evbuffer_pullup()
69   can be used to force a specified number of bytes to be contiguous. This
70   will cause memory reallocation and memory copies if the data is split
71   across multiple blocks.  It is more efficient, however, to use
72   evbuffer_peek() if you don't require that the memory to be contiguous.
73  */
74 
75 #include <event2/visibility.h>
76 
77 #ifdef __cplusplus
78 extern "C" {
79 #endif
80 
81 #include <event2/event-config.h>
82 #include <stdarg.h>
83 #ifdef EVENT__HAVE_SYS_TYPES_H
84 #include <sys/types.h>
85 #endif
86 #ifdef EVENT__HAVE_SYS_UIO_H
87 #include <sys/uio.h>
88 #endif
89 #include <event2/util.h>
90 
91 /**
92    An evbuffer is an opaque data type for efficiently buffering data to be
93    sent or received on the network.
94 
95    @see event2/event.h for more information
96 */
97 struct evbuffer
98 #ifdef EVENT_IN_DOXYGEN_
99 {}
100 #endif
101 ;
102 
103 /**
104     Pointer to a position within an evbuffer.
105 
106     Used when repeatedly searching through a buffer.  Calling any function
107     that modifies or re-packs the buffer contents may invalidate all
108     evbuffer_ptrs for that buffer.  Do not modify these values except with
109     evbuffer_ptr_set.
110 
111     Used when repeatedly searching through a buffer.  Calls to any function
112     that modifies or re-packs the buffer contents may invalidate all
113     evbuffer_ptrs for that buffer.  Do not modify these values except with
114     evbuffer_ptr_set.
115 
116     An evbuffer_ptr can represent any position from the start of a buffer up
117     to a position immediately after the end of a buffer.
118 
119     @see evbuffer_ptr_set()
120  */
121 struct evbuffer_ptr {
122 	ev_ssize_t pos;
123 
124 	/* Do not alter or rely on the values of fields: they are for internal
125 	 * use */
126 	struct {
127 		void *chain;
128 		size_t pos_in_chain;
129 	} internal_;
130 };
131 
132 /** Describes a single extent of memory inside an evbuffer.  Used for
133     direct-access functions.
134 
135     @see evbuffer_reserve_space, evbuffer_commit_space, evbuffer_peek
136  */
137 #ifdef EVENT__HAVE_SYS_UIO_H
138 #define evbuffer_iovec iovec
139 /* Internal use -- defined only if we are using the native struct iovec */
140 #define EVBUFFER_IOVEC_IS_NATIVE_
141 #else
142 struct evbuffer_iovec {
143 	/** The start of the extent of memory. */
144 	void *iov_base;
145 	/** The length of the extent of memory. */
146 	size_t iov_len;
147 };
148 #endif
149 
150 /**
151   Allocate storage for a new evbuffer.
152 
153   @return a pointer to a newly allocated evbuffer struct, or NULL if an error
154 	occurred
155  */
156 EVENT2_EXPORT_SYMBOL
157 struct evbuffer *evbuffer_new(void);
158 /**
159   Deallocate storage for an evbuffer.
160 
161   @param buf pointer to the evbuffer to be freed
162  */
163 EVENT2_EXPORT_SYMBOL
164 void evbuffer_free(struct evbuffer *buf);
165 
166 /**
167    Enable locking on an evbuffer so that it can safely be used by multiple
168    threads at the same time.
169 
170    NOTE: when locking is enabled, the lock will be held when callbacks are
171    invoked.  This could result in deadlock if you aren't careful.  Plan
172    accordingly!
173 
174    @param buf An evbuffer to make lockable.
175    @param lock A lock object, or NULL if we should allocate our own.
176    @return 0 on success, -1 on failure.
177  */
178 EVENT2_EXPORT_SYMBOL
179 int evbuffer_enable_locking(struct evbuffer *buf, void *lock);
180 
181 /**
182    Acquire the lock on an evbuffer.  Has no effect if locking was not enabled
183    with evbuffer_enable_locking.
184 */
185 EVENT2_EXPORT_SYMBOL
186 void evbuffer_lock(struct evbuffer *buf);
187 
188 /**
189    Release the lock on an evbuffer.  Has no effect if locking was not enabled
190    with evbuffer_enable_locking.
191 */
192 EVENT2_EXPORT_SYMBOL
193 void evbuffer_unlock(struct evbuffer *buf);
194 
195 
196 /** If this flag is set, then we will not use evbuffer_peek(),
197  * evbuffer_remove(), evbuffer_remove_buffer(), and so on to read bytes
198  * from this buffer: we'll only take bytes out of this buffer by
199  * writing them to the network (as with evbuffer_write_atmost), by
200  * removing them without observing them (as with evbuffer_drain),
201  * or by copying them all out at once (as with evbuffer_add_buffer).
202  *
203  * Using this option allows the implementation to use sendfile-based
204  * operations for evbuffer_add_file(); see that function for more
205  * information.
206  *
207  * This flag is on by default for bufferevents that can take advantage
208  * of it; you should never actually need to set it on a bufferevent's
209  * output buffer.
210  */
211 #define EVBUFFER_FLAG_DRAINS_TO_FD 1
212 
213 /** Change the flags that are set for an evbuffer by adding more.
214  *
215  * @param buffer the evbuffer that the callback is watching.
216  * @param cb the callback whose status we want to change.
217  * @param flags One or more EVBUFFER_FLAG_* options
218  * @return 0 on success, -1 on failure.
219  */
220 EVENT2_EXPORT_SYMBOL
221 int evbuffer_set_flags(struct evbuffer *buf, ev_uint64_t flags);
222 /** Change the flags that are set for an evbuffer by removing some.
223  *
224  * @param buffer the evbuffer that the callback is watching.
225  * @param cb the callback whose status we want to change.
226  * @param flags One or more EVBUFFER_FLAG_* options
227  * @return 0 on success, -1 on failure.
228  */
229 EVENT2_EXPORT_SYMBOL
230 int evbuffer_clear_flags(struct evbuffer *buf, ev_uint64_t flags);
231 
232 /**
233   Returns the total number of bytes stored in the evbuffer
234 
235   @param buf pointer to the evbuffer
236   @return the number of bytes stored in the evbuffer
237 */
238 EVENT2_EXPORT_SYMBOL
239 size_t evbuffer_get_length(const struct evbuffer *buf);
240 
241 /**
242    Returns the number of contiguous available bytes in the first buffer chain.
243 
244    This is useful when processing data that might be split into multiple
245    chains, or that might all be in the first chain.  Calls to
246    evbuffer_pullup() that cause reallocation and copying of data can thus be
247    avoided.
248 
249    @param buf pointer to the evbuffer
250    @return 0 if no data is available, otherwise the number of available bytes
251      in the first buffer chain.
252 */
253 EVENT2_EXPORT_SYMBOL
254 size_t evbuffer_get_contiguous_space(const struct evbuffer *buf);
255 
256 /**
257   Expands the available space in an evbuffer.
258 
259   Expands the available space in the evbuffer to at least datlen, so that
260   appending datlen additional bytes will not require any new allocations.
261 
262   @param buf the evbuffer to be expanded
263   @param datlen the new minimum length requirement
264   @return 0 if successful, or -1 if an error occurred
265 */
266 EVENT2_EXPORT_SYMBOL
267 int evbuffer_expand(struct evbuffer *buf, size_t datlen);
268 
269 /**
270    Reserves space in the last chain or chains of an evbuffer.
271 
272    Makes space available in the last chain or chains of an evbuffer that can
273    be arbitrarily written to by a user.  The space does not become
274    available for reading until it has been committed with
275    evbuffer_commit_space().
276 
277    The space is made available as one or more extents, represented by
278    an initial pointer and a length.  You can force the memory to be
279    available as only one extent.  Allowing more extents, however, makes the
280    function more efficient.
281 
282    Multiple subsequent calls to this function will make the same space
283    available until evbuffer_commit_space() has been called.
284 
285    It is an error to do anything that moves around the buffer's internal
286    memory structures before committing the space.
287 
288    NOTE: The code currently does not ever use more than two extents.
289    This may change in future versions.
290 
291    @param buf the evbuffer in which to reserve space.
292    @param size how much space to make available, at minimum.  The
293       total length of the extents may be greater than the requested
294       length.
295    @param vec an array of one or more evbuffer_iovec structures to
296       hold pointers to the reserved extents of memory.
297    @param n_vec The length of the vec array.  Must be at least 1;
298        2 is more efficient.
299    @return the number of provided extents, or -1 on error.
300    @see evbuffer_commit_space()
301 */
302 EVENT2_EXPORT_SYMBOL
303 int
304 evbuffer_reserve_space(struct evbuffer *buf, ev_ssize_t size,
305     struct evbuffer_iovec *vec, int n_vec);
306 
307 /**
308    Commits previously reserved space.
309 
310    Commits some of the space previously reserved with
311    evbuffer_reserve_space().  It then becomes available for reading.
312 
313    This function may return an error if the pointer in the extents do
314    not match those returned from evbuffer_reserve_space, or if data
315    has been added to the buffer since the space was reserved.
316 
317    If you want to commit less data than you got reserved space for,
318    modify the iov_len pointer of the appropriate extent to a smaller
319    value.  Note that you may have received more space than you
320    requested if it was available!
321 
322    @param buf the evbuffer in which to reserve space.
323    @param vec one or two extents returned by evbuffer_reserve_space.
324    @param n_vecs the number of extents.
325    @return 0 on success, -1 on error
326    @see evbuffer_reserve_space()
327 */
328 EVENT2_EXPORT_SYMBOL
329 int evbuffer_commit_space(struct evbuffer *buf,
330     struct evbuffer_iovec *vec, int n_vecs);
331 
332 /**
333   Append data to the end of an evbuffer.
334 
335   @param buf the evbuffer to be appended to
336   @param data pointer to the beginning of the data buffer
337   @param datlen the number of bytes to be copied from the data buffer
338   @return 0 on success, -1 on failure.
339  */
340 EVENT2_EXPORT_SYMBOL
341 int evbuffer_add(struct evbuffer *buf, const void *data, size_t datlen);
342 
343 
344 /**
345   Read data from an evbuffer and drain the bytes read.
346 
347   If more bytes are requested than are available in the evbuffer, we
348   only extract as many bytes as were available.
349 
350   @param buf the evbuffer to be read from
351   @param data the destination buffer to store the result
352   @param datlen the maximum size of the destination buffer
353   @return the number of bytes read, or -1 if we can't drain the buffer.
354  */
355 EVENT2_EXPORT_SYMBOL
356 int evbuffer_remove(struct evbuffer *buf, void *data, size_t datlen);
357 
358 /**
359   Read data from an evbuffer, and leave the buffer unchanged.
360 
361   If more bytes are requested than are available in the evbuffer, we
362   only extract as many bytes as were available.
363 
364   @param buf the evbuffer to be read from
365   @param data_out the destination buffer to store the result
366   @param datlen the maximum size of the destination buffer
367   @return the number of bytes read, or -1 if we can't drain the buffer.
368  */
369 EVENT2_EXPORT_SYMBOL
370 ev_ssize_t evbuffer_copyout(struct evbuffer *buf, void *data_out, size_t datlen);
371 
372 /**
373   Read data from the middle of an evbuffer, and leave the buffer unchanged.
374 
375   If more bytes are requested than are available in the evbuffer, we
376   only extract as many bytes as were available.
377 
378   @param buf the evbuffer to be read from
379   @param pos the position to start reading from
380   @param data_out the destination buffer to store the result
381   @param datlen the maximum size of the destination buffer
382   @return the number of bytes read, or -1 if we can't drain the buffer.
383  */
384 EVENT2_EXPORT_SYMBOL
385 ev_ssize_t evbuffer_copyout_from(struct evbuffer *buf, const struct evbuffer_ptr *pos, void *data_out, size_t datlen);
386 
387 /**
388   Read data from an evbuffer into another evbuffer, draining
389   the bytes from the source buffer.  This function avoids copy
390   operations to the extent possible.
391 
392   If more bytes are requested than are available in src, the src
393   buffer is drained completely.
394 
395   @param src the evbuffer to be read from
396   @param dst the destination evbuffer to store the result into
397   @param datlen the maximum numbers of bytes to transfer
398   @return the number of bytes read
399  */
400 EVENT2_EXPORT_SYMBOL
401 int evbuffer_remove_buffer(struct evbuffer *src, struct evbuffer *dst,
402     size_t datlen);
403 
404 /** Used to tell evbuffer_readln what kind of line-ending to look for.
405  */
406 enum evbuffer_eol_style {
407 	/** Any sequence of CR and LF characters is acceptable as an
408 	 * EOL.
409 	 *
410 	 * Note that this style can produce ambiguous results: the
411 	 * sequence "CRLF" will be treated as a single EOL if it is
412 	 * all in the buffer at once, but if you first read a CR from
413 	 * the network and later read an LF from the network, it will
414 	 * be treated as two EOLs.
415 	 */
416 	EVBUFFER_EOL_ANY,
417 	/** An EOL is an LF, optionally preceded by a CR.  This style is
418 	 * most useful for implementing text-based internet protocols. */
419 	EVBUFFER_EOL_CRLF,
420 	/** An EOL is a CR followed by an LF. */
421 	EVBUFFER_EOL_CRLF_STRICT,
422 	/** An EOL is a LF. */
423 	EVBUFFER_EOL_LF,
424 	/** An EOL is a NUL character (that is, a single byte with value 0) */
425 	EVBUFFER_EOL_NUL
426 };
427 
428 /**
429  * Read a single line from an evbuffer.
430  *
431  * Reads a line terminated by an EOL as determined by the evbuffer_eol_style
432  * argument.  Returns a newly allocated nul-terminated string; the caller must
433  * free the returned value.  The EOL is not included in the returned string.
434  *
435  * @param buffer the evbuffer to read from
436  * @param n_read_out if non-NULL, points to a size_t that is set to the
437  *       number of characters in the returned string.  This is useful for
438  *       strings that can contain NUL characters.
439  * @param eol_style the style of line-ending to use.
440  * @return pointer to a single line, or NULL if an error occurred
441  */
442 EVENT2_EXPORT_SYMBOL
443 char *evbuffer_readln(struct evbuffer *buffer, size_t *n_read_out,
444     enum evbuffer_eol_style eol_style);
445 
446 /**
447   Move all data from one evbuffer into another evbuffer.
448 
449   This is a destructive add.  The data from one buffer moves into
450   the other buffer.  However, no unnecessary memory copies occur.
451 
452   @param outbuf the output buffer
453   @param inbuf the input buffer
454   @return 0 if successful, or -1 if an error occurred
455 
456   @see evbuffer_remove_buffer()
457  */
458 EVENT2_EXPORT_SYMBOL
459 int evbuffer_add_buffer(struct evbuffer *outbuf, struct evbuffer *inbuf);
460 
461 /**
462   Copy data from one evbuffer into another evbuffer.
463 
464   This is a non-destructive add.  The data from one buffer is copied
465   into the other buffer.  However, no unnecessary memory copies occur.
466 
467   Note that buffers already containing buffer references can't be added
468   to other buffers.
469 
470   @param outbuf the output buffer
471   @param inbuf the input buffer
472   @return 0 if successful, or -1 if an error occurred
473  */
474 EVENT2_EXPORT_SYMBOL
475 int evbuffer_add_buffer_reference(struct evbuffer *outbuf,
476     struct evbuffer *inbuf);
477 
478 /**
479    A cleanup function for a piece of memory added to an evbuffer by
480    reference.
481 
482    @see evbuffer_add_reference()
483  */
484 typedef void (*evbuffer_ref_cleanup_cb)(const void *data,
485     size_t datalen, void *extra);
486 
487 /**
488   Reference memory into an evbuffer without copying.
489 
490   The memory needs to remain valid until all the added data has been
491   read.  This function keeps just a reference to the memory without
492   actually incurring the overhead of a copy.
493 
494   @param outbuf the output buffer
495   @param data the memory to reference
496   @param datlen how memory to reference
497   @param cleanupfn callback to be invoked when the memory is no longer
498 	referenced by this evbuffer.
499   @param cleanupfn_arg optional argument to the cleanup callback
500   @return 0 if successful, or -1 if an error occurred
501  */
502 EVENT2_EXPORT_SYMBOL
503 int evbuffer_add_reference(struct evbuffer *outbuf,
504     const void *data, size_t datlen,
505     evbuffer_ref_cleanup_cb cleanupfn, void *cleanupfn_arg);
506 
507 /**
508   Copy data from a file into the evbuffer for writing to a socket.
509 
510   This function avoids unnecessary data copies between userland and
511   kernel.  If sendfile is available and the EVBUFFER_FLAG_DRAINS_TO_FD
512   flag is set, it uses those functions.  Otherwise, it tries to use
513   mmap (or CreateFileMapping on Windows).
514 
515   The function owns the resulting file descriptor and will close it
516   when finished transferring data.
517 
518   The results of using evbuffer_remove() or evbuffer_pullup() on
519   evbuffers whose data was added using this function are undefined.
520 
521   For more fine-grained control, use evbuffer_add_file_segment.
522 
523   @param outbuf the output buffer
524   @param fd the file descriptor
525   @param offset the offset from which to read data
526   @param length how much data to read, or -1 to read as much as possible.
527     (-1 requires that 'fd' support fstat.)
528   @return 0 if successful, or -1 if an error occurred
529 */
530 
531 EVENT2_EXPORT_SYMBOL
532 int evbuffer_add_file(struct evbuffer *outbuf, int fd, ev_off_t offset,
533     ev_off_t length);
534 
535 /**
536   An evbuffer_file_segment holds a reference to a range of a file --
537   possibly the whole file! -- for use in writing from an evbuffer to a
538   socket.  It could be implemented with mmap, sendfile, splice, or (if all
539   else fails) by just pulling all the data into RAM.  A single
540   evbuffer_file_segment can be added more than once, and to more than one
541   evbuffer.
542  */
543 struct evbuffer_file_segment;
544 
545 /**
546     Flag for creating evbuffer_file_segment: If this flag is set, then when
547     the evbuffer_file_segment is freed and no longer in use by any
548     evbuffer, the underlying fd is closed.
549  */
550 #define EVBUF_FS_CLOSE_ON_FREE    0x01
551 /**
552    Flag for creating evbuffer_file_segment: Disable memory-map based
553    implementations.
554  */
555 #define EVBUF_FS_DISABLE_MMAP     0x02
556 /**
557    Flag for creating evbuffer_file_segment: Disable direct fd-to-fd
558    implementations (including sendfile and splice).
559 
560    You might want to use this option if data needs to be taken from the
561    evbuffer by any means other than writing it to the network: the sendfile
562    backend is fast, but it only works for sending files directly to the
563    network.
564  */
565 #define EVBUF_FS_DISABLE_SENDFILE 0x04
566 /**
567    Flag for creating evbuffer_file_segment: Do not allocate a lock for this
568    segment.  If this option is set, then neither the segment nor any
569    evbuffer it is added to may ever be accessed from more than one thread
570    at a time.
571  */
572 #define EVBUF_FS_DISABLE_LOCKING  0x08
573 
574 /**
575    A cleanup function for a evbuffer_file_segment added to an evbuffer
576    for reference.
577  */
578 typedef void (*evbuffer_file_segment_cleanup_cb)(
579     struct evbuffer_file_segment const* seg, int flags, void* arg);
580 
581 /**
582    Create and return a new evbuffer_file_segment for reading data from a
583    file and sending it out via an evbuffer.
584 
585    This function avoids unnecessary data copies between userland and
586    kernel.  Where available, it uses sendfile or splice.
587 
588    The file descriptor must not be closed so long as any evbuffer is using
589    this segment.
590 
591    The results of using evbuffer_remove() or evbuffer_pullup() or any other
592    function that reads bytes from an evbuffer on any evbuffer containing
593    the newly returned segment are undefined, unless you pass the
594    EVBUF_FS_DISABLE_SENDFILE flag to this function.
595 
596    @param fd an open file to read from.
597    @param offset an index within the file at which to start reading
598    @param length how much data to read, or -1 to read as much as possible.
599       (-1 requires that 'fd' support fstat.)
600    @param flags any number of the EVBUF_FS_* flags
601    @return a new evbuffer_file_segment, or NULL on failure.
602  **/
603 EVENT2_EXPORT_SYMBOL
604 struct evbuffer_file_segment *evbuffer_file_segment_new(
605 	int fd, ev_off_t offset, ev_off_t length, unsigned flags);
606 
607 /**
608    Free an evbuffer_file_segment
609 
610    It is safe to call this function even if the segment has been added to
611    one or more evbuffers.  The evbuffer_file_segment will not be freed
612    until no more references to it exist.
613  */
614 EVENT2_EXPORT_SYMBOL
615 void evbuffer_file_segment_free(struct evbuffer_file_segment *seg);
616 
617 /**
618    Add cleanup callback and argument for the callback to an
619    evbuffer_file_segment.
620 
621    The cleanup callback will be invoked when no more references to the
622    evbuffer_file_segment exist.
623  **/
624 EVENT2_EXPORT_SYMBOL
625 void evbuffer_file_segment_add_cleanup_cb(struct evbuffer_file_segment *seg,
626 	evbuffer_file_segment_cleanup_cb cb, void* arg);
627 
628 /**
629    Insert some or all of an evbuffer_file_segment at the end of an evbuffer
630 
631    Note that the offset and length parameters of this function have a
632    different meaning from those provided to evbuffer_file_segment_new: When
633    you create the segment, the offset is the offset _within the file_, and
634    the length is the length _of the segment_, whereas when you add a
635    segment to an evbuffer, the offset is _within the segment_ and the
636    length is the length of the _part of the segment you want to use.
637 
638    In other words, if you have a 10 KiB file, and you create an
639    evbuffer_file_segment for it with offset 20 and length 1000, it will
640    refer to bytes 20..1019 inclusive.  If you then pass this segment to
641    evbuffer_add_file_segment and specify an offset of 20 and a length of
642    50, you will be adding bytes 40..99 inclusive.
643 
644    @param buf the evbuffer to append to
645    @param seg the segment to add
646    @param offset the offset within the segment to start from
647    @param length the amount of data to add, or -1 to add it all.
648    @return 0 on success, -1 on failure.
649  */
650 EVENT2_EXPORT_SYMBOL
651 int evbuffer_add_file_segment(struct evbuffer *buf,
652     struct evbuffer_file_segment *seg, ev_off_t offset, ev_off_t length);
653 
654 /**
655   Append a formatted string to the end of an evbuffer.
656 
657   The string is formated as printf.
658 
659   @param buf the evbuffer that will be appended to
660   @param fmt a format string
661   @param ... arguments that will be passed to printf(3)
662   @return The number of bytes added if successful, or -1 if an error occurred.
663 
664   @see evutil_printf(), evbuffer_add_vprintf()
665  */
666 EVENT2_EXPORT_SYMBOL
667 int evbuffer_add_printf(struct evbuffer *buf, const char *fmt, ...)
668 #ifdef __GNUC__
669   __attribute__((format(printf, 2, 3)))
670 #endif
671 ;
672 
673 /**
674   Append a va_list formatted string to the end of an evbuffer.
675 
676   @param buf the evbuffer that will be appended to
677   @param fmt a format string
678   @param ap a varargs va_list argument array that will be passed to vprintf(3)
679   @return The number of bytes added if successful, or -1 if an error occurred.
680  */
681 EVENT2_EXPORT_SYMBOL
682 int evbuffer_add_vprintf(struct evbuffer *buf, const char *fmt, va_list ap)
683 #ifdef __GNUC__
684 	__attribute__((format(printf, 2, 0)))
685 #endif
686 ;
687 
688 
689 /**
690   Remove a specified number of bytes data from the beginning of an evbuffer.
691 
692   @param buf the evbuffer to be drained
693   @param len the number of bytes to drain from the beginning of the buffer
694   @return 0 on success, -1 on failure.
695  */
696 EVENT2_EXPORT_SYMBOL
697 int evbuffer_drain(struct evbuffer *buf, size_t len);
698 
699 
700 /**
701   Write the contents of an evbuffer to a file descriptor.
702 
703   The evbuffer will be drained after the bytes have been successfully written.
704 
705   @param buffer the evbuffer to be written and drained
706   @param fd the file descriptor to be written to
707   @return the number of bytes written, or -1 if an error occurred
708   @see evbuffer_read()
709  */
710 EVENT2_EXPORT_SYMBOL
711 int evbuffer_write(struct evbuffer *buffer, evutil_socket_t fd);
712 
713 /**
714   Write some of the contents of an evbuffer to a file descriptor.
715 
716   The evbuffer will be drained after the bytes have been successfully written.
717 
718   @param buffer the evbuffer to be written and drained
719   @param fd the file descriptor to be written to
720   @param howmuch the largest allowable number of bytes to write, or -1
721 	to write as many bytes as we can.
722   @return the number of bytes written, or -1 if an error occurred
723   @see evbuffer_read()
724  */
725 EVENT2_EXPORT_SYMBOL
726 int evbuffer_write_atmost(struct evbuffer *buffer, evutil_socket_t fd,
727 						  ev_ssize_t howmuch);
728 
729 /**
730   Read from a file descriptor and store the result in an evbuffer.
731 
732   @param buffer the evbuffer to store the result
733   @param fd the file descriptor to read from
734   @param howmuch the number of bytes to be read
735   @return the number of bytes read, or -1 if an error occurred
736   @see evbuffer_write()
737  */
738 EVENT2_EXPORT_SYMBOL
739 int evbuffer_read(struct evbuffer *buffer, evutil_socket_t fd, int howmuch);
740 
741 /**
742    Search for a string within an evbuffer.
743 
744    @param buffer the evbuffer to be searched
745    @param what the string to be searched for
746    @param len the length of the search string
747    @param start NULL or a pointer to a valid struct evbuffer_ptr.
748    @return a struct evbuffer_ptr whose 'pos' field has the offset of the
749      first occurrence of the string in the buffer after 'start'.  The 'pos'
750      field of the result is -1 if the string was not found.
751  */
752 EVENT2_EXPORT_SYMBOL
753 struct evbuffer_ptr evbuffer_search(struct evbuffer *buffer, const char *what, size_t len, const struct evbuffer_ptr *start);
754 
755 /**
756    Search for a string within part of an evbuffer.
757 
758    @param buffer the evbuffer to be searched
759    @param what the string to be searched for
760    @param len the length of the search string
761    @param start NULL or a pointer to a valid struct evbuffer_ptr that
762      indicates where we should start searching.
763    @param end NULL or a pointer to a valid struct evbuffer_ptr that
764      indicates where we should stop searching.
765    @return a struct evbuffer_ptr whose 'pos' field has the offset of the
766      first occurrence of the string in the buffer after 'start'.  The 'pos'
767      field of the result is -1 if the string was not found.
768  */
769 EVENT2_EXPORT_SYMBOL
770 struct evbuffer_ptr evbuffer_search_range(struct evbuffer *buffer, const char *what, size_t len, const struct evbuffer_ptr *start, const struct evbuffer_ptr *end);
771 
772 /**
773    Defines how to adjust an evbuffer_ptr by evbuffer_ptr_set()
774 
775    @see evbuffer_ptr_set() */
776 enum evbuffer_ptr_how {
777 	/** Sets the pointer to the position; can be called on with an
778 	    uninitialized evbuffer_ptr. */
779 	EVBUFFER_PTR_SET,
780 	/** Advances the pointer by adding to the current position. */
781 	EVBUFFER_PTR_ADD
782 };
783 
784 /**
785    Sets the search pointer in the buffer to position.
786 
787    There are two ways to use this function: you can call
788       evbuffer_ptr_set(buf, &pos, N, EVBUFFER_PTR_SET)
789    to move 'pos' to a position 'N' bytes after the start of the buffer, or
790       evbuffer_ptr_set(buf, &pos, N, EVBUFFER_PTR_SET)
791    to move 'pos' forward by 'N' bytes.
792 
793    If evbuffer_ptr is not initialized, this function can only be called
794    with EVBUFFER_PTR_SET.
795 
796    An evbuffer_ptr can represent any position from the start of the buffer to
797    a position immediately after the end of the buffer.
798 
799    @param buffer the evbuffer to be search
800    @param ptr a pointer to a struct evbuffer_ptr
801    @param position the position at which to start the next search
802    @param how determines how the pointer should be manipulated.
803    @returns 0 on success or -1 otherwise
804 */
805 EVENT2_EXPORT_SYMBOL
806 int
807 evbuffer_ptr_set(struct evbuffer *buffer, struct evbuffer_ptr *ptr,
808     size_t position, enum evbuffer_ptr_how how);
809 
810 /**
811    Search for an end-of-line string within an evbuffer.
812 
813    @param buffer the evbuffer to be searched
814    @param start NULL or a pointer to a valid struct evbuffer_ptr to start
815       searching at.
816    @param eol_len_out If non-NULL, the pointed-to value will be set to
817       the length of the end-of-line string.
818    @param eol_style The kind of EOL to look for; see evbuffer_readln() for
819       more information
820    @return a struct evbuffer_ptr whose 'pos' field has the offset of the
821      first occurrence EOL in the buffer after 'start'.  The 'pos'
822      field of the result is -1 if the string was not found.
823  */
824 EVENT2_EXPORT_SYMBOL
825 struct evbuffer_ptr evbuffer_search_eol(struct evbuffer *buffer,
826     struct evbuffer_ptr *start, size_t *eol_len_out,
827     enum evbuffer_eol_style eol_style);
828 
829 /** Function to peek at data inside an evbuffer without removing it or
830     copying it out.
831 
832     Pointers to the data are returned by filling the 'vec_out' array
833     with pointers to one or more extents of data inside the buffer.
834 
835     The total data in the extents that you get back may be more than
836     you requested (if there is more data last extent than you asked
837     for), or less (if you do not provide enough evbuffer_iovecs, or if
838     the buffer does not have as much data as you asked to see).
839 
840     @param buffer the evbuffer to peek into,
841     @param len the number of bytes to try to peek.  If len is negative, we
842        will try to fill as much of vec_out as we can.  If len is negative
843        and vec_out is not provided, we return the number of evbuffer_iovecs
844        that would be needed to get all the data in the buffer.
845     @param start_at an evbuffer_ptr indicating the point at which we
846        should start looking for data.  NULL means, "At the start of the
847        buffer."
848     @param vec_out an array of evbuffer_iovec
849     @param n_vec the length of vec_out.  If 0, we only count how many
850        extents would be necessary to point to the requested amount of
851        data.
852     @return The number of extents needed.  This may be less than n_vec
853        if we didn't need all the evbuffer_iovecs we were given, or more
854        than n_vec if we would need more to return all the data that was
855        requested.
856  */
857 EVENT2_EXPORT_SYMBOL
858 int evbuffer_peek(struct evbuffer *buffer, ev_ssize_t len,
859     struct evbuffer_ptr *start_at,
860     struct evbuffer_iovec *vec_out, int n_vec);
861 
862 
863 /** Structure passed to an evbuffer_cb_func evbuffer callback
864 
865     @see evbuffer_cb_func, evbuffer_add_cb()
866  */
867 struct evbuffer_cb_info {
868 	/** The number of bytes in this evbuffer when callbacks were last
869 	 * invoked. */
870 	size_t orig_size;
871 	/** The number of bytes added since callbacks were last invoked. */
872 	size_t n_added;
873 	/** The number of bytes removed since callbacks were last invoked. */
874 	size_t n_deleted;
875 };
876 
877 /** Type definition for a callback that is invoked whenever data is added or
878     removed from an evbuffer.
879 
880     An evbuffer may have one or more callbacks set at a time.  The order
881     in which they are executed is undefined.
882 
883     A callback function may add more callbacks, or remove itself from the
884     list of callbacks, or add or remove data from the buffer.  It may not
885     remove another callback from the list.
886 
887     If a callback adds or removes data from the buffer or from another
888     buffer, this can cause a recursive invocation of your callback or
889     other callbacks.  If you ask for an infinite loop, you might just get
890     one: watch out!
891 
892     @param buffer the buffer whose size has changed
893     @param info a structure describing how the buffer changed.
894     @param arg a pointer to user data
895 */
896 typedef void (*evbuffer_cb_func)(struct evbuffer *buffer, const struct evbuffer_cb_info *info, void *arg);
897 
898 struct evbuffer_cb_entry;
899 /** Add a new callback to an evbuffer.
900 
901   Subsequent calls to evbuffer_add_cb() add new callbacks.  To remove this
902   callback, call evbuffer_remove_cb or evbuffer_remove_cb_entry.
903 
904   @param buffer the evbuffer to be monitored
905   @param cb the callback function to invoke when the evbuffer is modified,
906 	or NULL to remove all callbacks.
907   @param cbarg an argument to be provided to the callback function
908   @return a handle to the callback on success, or NULL on failure.
909  */
910 EVENT2_EXPORT_SYMBOL
911 struct evbuffer_cb_entry *evbuffer_add_cb(struct evbuffer *buffer, evbuffer_cb_func cb, void *cbarg);
912 
913 /** Remove a callback from an evbuffer, given a handle returned from
914     evbuffer_add_cb.
915 
916     Calling this function invalidates the handle.
917 
918     @return 0 if a callback was removed, or -1 if no matching callback was
919     found.
920  */
921 EVENT2_EXPORT_SYMBOL
922 int evbuffer_remove_cb_entry(struct evbuffer *buffer,
923 			     struct evbuffer_cb_entry *ent);
924 
925 /** Remove a callback from an evbuffer, given the function and argument
926     used to add it.
927 
928     @return 0 if a callback was removed, or -1 if no matching callback was
929     found.
930  */
931 EVENT2_EXPORT_SYMBOL
932 int evbuffer_remove_cb(struct evbuffer *buffer, evbuffer_cb_func cb, void *cbarg);
933 
934 /** If this flag is not set, then a callback is temporarily disabled, and
935  * should not be invoked.
936  *
937  * @see evbuffer_cb_set_flags(), evbuffer_cb_clear_flags()
938  */
939 #define EVBUFFER_CB_ENABLED 1
940 
941 /** Change the flags that are set for a callback on a buffer by adding more.
942 
943     @param buffer the evbuffer that the callback is watching.
944     @param cb the callback whose status we want to change.
945     @param flags EVBUFFER_CB_ENABLED to re-enable the callback.
946     @return 0 on success, -1 on failure.
947  */
948 EVENT2_EXPORT_SYMBOL
949 int evbuffer_cb_set_flags(struct evbuffer *buffer,
950 			  struct evbuffer_cb_entry *cb, ev_uint32_t flags);
951 
952 /** Change the flags that are set for a callback on a buffer by removing some
953 
954     @param buffer the evbuffer that the callback is watching.
955     @param cb the callback whose status we want to change.
956     @param flags EVBUFFER_CB_ENABLED to disable the callback.
957     @return 0 on success, -1 on failure.
958  */
959 EVENT2_EXPORT_SYMBOL
960 int evbuffer_cb_clear_flags(struct evbuffer *buffer,
961 			  struct evbuffer_cb_entry *cb, ev_uint32_t flags);
962 
963 #if 0
964 /** Postpone calling a given callback until unsuspend is called later.
965 
966     This is different from disabling the callback, since the callback will get
967 	invoked later if the buffer size changes between now and when we unsuspend
968 	it.
969 
970 	@param the buffer that the callback is watching.
971 	@param cb the callback we want to suspend.
972  */
973 EVENT2_EXPORT_SYMBOL
974 void evbuffer_cb_suspend(struct evbuffer *buffer, struct evbuffer_cb_entry *cb);
975 /** Stop postponing a callback that we postponed with evbuffer_cb_suspend.
976 
977 	If data was added to or removed from the buffer while the callback was
978 	suspended, the callback will get called once now.
979 
980 	@param the buffer that the callback is watching.
981 	@param cb the callback we want to stop suspending.
982  */
983 EVENT2_EXPORT_SYMBOL
984 void evbuffer_cb_unsuspend(struct evbuffer *buffer, struct evbuffer_cb_entry *cb);
985 #endif
986 
987 /**
988   Makes the data at the beginning of an evbuffer contiguous.
989 
990   @param buf the evbuffer to make contiguous
991   @param size the number of bytes to make contiguous, or -1 to make the
992 	entire buffer contiguous.
993   @return a pointer to the contiguous memory array, or NULL if param size
994 	requested more data than is present in the buffer.
995 */
996 
997 EVENT2_EXPORT_SYMBOL
998 unsigned char *evbuffer_pullup(struct evbuffer *buf, ev_ssize_t size);
999 
1000 /**
1001   Prepends data to the beginning of the evbuffer
1002 
1003   @param buf the evbuffer to which to prepend data
1004   @param data a pointer to the memory to prepend
1005   @param size the number of bytes to prepend
1006   @return 0 if successful, or -1 otherwise
1007 */
1008 
1009 EVENT2_EXPORT_SYMBOL
1010 int evbuffer_prepend(struct evbuffer *buf, const void *data, size_t size);
1011 
1012 /**
1013   Prepends all data from the src evbuffer to the beginning of the dst
1014   evbuffer.
1015 
1016   @param dst the evbuffer to which to prepend data
1017   @param src the evbuffer to prepend; it will be emptied as a result
1018   @return 0 if successful, or -1 otherwise
1019 */
1020 EVENT2_EXPORT_SYMBOL
1021 int evbuffer_prepend_buffer(struct evbuffer *dst, struct evbuffer* src);
1022 
1023 /**
1024    Prevent calls that modify an evbuffer from succeeding. A buffer may
1025    frozen at the front, at the back, or at both the front and the back.
1026 
1027    If the front of a buffer is frozen, operations that drain data from
1028    the front of the buffer, or that prepend data to the buffer, will
1029    fail until it is unfrozen.   If the back a buffer is frozen, operations
1030    that append data from the buffer will fail until it is unfrozen.
1031 
1032    @param buf The buffer to freeze
1033    @param at_front If true, we freeze the front of the buffer.  If false,
1034       we freeze the back.
1035    @return 0 on success, -1 on failure.
1036 */
1037 EVENT2_EXPORT_SYMBOL
1038 int evbuffer_freeze(struct evbuffer *buf, int at_front);
1039 /**
1040    Re-enable calls that modify an evbuffer.
1041 
1042    @param buf The buffer to un-freeze
1043    @param at_front If true, we unfreeze the front of the buffer.  If false,
1044       we unfreeze the back.
1045    @return 0 on success, -1 on failure.
1046  */
1047 EVENT2_EXPORT_SYMBOL
1048 int evbuffer_unfreeze(struct evbuffer *buf, int at_front);
1049 
1050 struct event_base;
1051 /**
1052    Force all the callbacks on an evbuffer to be run, not immediately after
1053    the evbuffer is altered, but instead from inside the event loop.
1054 
1055    This can be used to serialize all the callbacks to a single thread
1056    of execution.
1057  */
1058 EVENT2_EXPORT_SYMBOL
1059 int evbuffer_defer_callbacks(struct evbuffer *buffer, struct event_base *base);
1060 
1061 /**
1062   Append data from 1 or more iovec's to an evbuffer
1063 
1064   Calculates the number of bytes needed for an iovec structure and guarantees
1065   all data will fit into a single chain. Can be used in lieu of functionality
1066   which calls evbuffer_add() constantly before being used to increase
1067   performance.
1068 
1069   @param buffer the destination buffer
1070   @param vec the source iovec
1071   @param n_vec the number of iovec structures.
1072   @return the number of bytes successfully written to the output buffer.
1073 */
1074 EVENT2_EXPORT_SYMBOL
1075 size_t evbuffer_add_iovec(struct evbuffer * buffer, struct evbuffer_iovec * vec, int n_vec);
1076 
1077 #ifdef __cplusplus
1078 }
1079 #endif
1080 
1081 #endif /* EVENT2_BUFFER_H_INCLUDED_ */
1082