xref: /libevent-2.1.12/include/event2/buffer.h (revision 26041a8e)
1 /*
2  * Copyright (c) 2007-2010 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_
27 #define _EVENT2_BUFFER_H_
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 #ifdef __cplusplus
76 extern "C" {
77 #endif
78 
79 #include <event2/event-config.h>
80 #include <stdarg.h>
81 #ifdef _EVENT_HAVE_SYS_TYPES_H
82 #include <sys/types.h>
83 #endif
84 #ifdef _EVENT_HAVE_SYS_UIO_H
85 #include <sys/uio.h>
86 #endif
87 #include <event2/util.h>
88 
89 /**
90    An evbuffer is an opaque data type for efficiently buffering data to be
91    sent or received on the network.
92 
93    @see event2/event.h for more information
94 */
95 struct evbuffer
96 #ifdef _EVENT_IN_DOXYGEN
97 {}
98 #endif
99 ;
100 
101 /**
102     Pointer to a position within an evbuffer.
103 
104     Used when repeatedly searching through a buffer.  Calling any function
105     that modifies or re-packs the buffer contents may invalidate all
106     evbuffer_ptrs for that buffer.  Do not modify these values except with
107     evbuffer_ptr_set.
108 
109     Used when repeatedly searching through a buffer.  Calls to any function
110     that modifies or re-packs the buffer contents may invalidate all
111     evbuffer_ptrs for that buffer.  Do not modify these values except with
112     evbuffer_ptr_set.
113 
114     An evbuffer_ptr can represent any position from the start of a buffer up
115     to a position immediately after the end of a buffer.
116 
117     @see evbuffer_ptr_set()
118  */
119 struct evbuffer_ptr {
120 	ev_ssize_t pos;
121 
122 	/* Do not alter or rely on the values of fields: they are for internal
123 	 * use */
124 	struct {
125 		void *chain;
126 		size_t pos_in_chain;
127 	} _internal;
128 };
129 
130 /** Describes a single extent of memory inside an evbuffer.  Used for
131     direct-access functions.
132 
133     @see evbuffer_reserve_space, evbuffer_commit_space, evbuffer_peek
134  */
135 #ifdef _EVENT_HAVE_SYS_UIO_H
136 #define evbuffer_iovec iovec
137 /* Internal use -- defined only if we are using the native struct iovec */
138 #define _EVBUFFER_IOVEC_IS_NATIVE
139 #else
140 struct evbuffer_iovec {
141 	/** The start of the extent of memory. */
142 	void *iov_base;
143 	/** The length of the extent of memory. */
144 	size_t iov_len;
145 };
146 #endif
147 
148 /**
149   Allocate storage for a new evbuffer.
150 
151   @return a pointer to a newly allocated evbuffer struct, or NULL if an error
152 	occurred
153  */
154 struct evbuffer *evbuffer_new(void);
155 
156 /**
157   Deallocate storage for an evbuffer.
158 
159   @param buf pointer to the evbuffer to be freed
160  */
161 void evbuffer_free(struct evbuffer *buf);
162 
163 /**
164    Enable locking on an evbuffer so that it can safely be used by multiple
165    threads at the same time.
166 
167    NOTE: when locking is enabled, the lock will be held when callbacks are
168    invoked.  This could result in deadlock if you aren't careful.  Plan
169    accordingly!
170 
171    @param buf An evbuffer to make lockable.
172    @param lock A lock object, or NULL if we should allocate our own.
173    @return 0 on success, -1 on failure.
174  */
175 int evbuffer_enable_locking(struct evbuffer *buf, void *lock);
176 
177 /**
178    Acquire the lock on an evbuffer.  Has no effect if locking was not enabled
179    with evbuffer_enable_locking.
180 */
181 void evbuffer_lock(struct evbuffer *buf);
182 
183 /**
184    Release the lock on an evbuffer.  Has no effect if locking was not enabled
185    with evbuffer_enable_locking.
186 */
187 void evbuffer_unlock(struct evbuffer *buf);
188 
189 /**
190   Returns the total number of bytes stored in the evbuffer
191 
192   @param buf pointer to the evbuffer
193   @return the number of bytes stored in the evbuffer
194 */
195 size_t evbuffer_get_length(const struct evbuffer *buf);
196 
197 /**
198    Returns the number of contiguous available bytes in the first buffer chain.
199 
200    This is useful when processing data that might be split into multiple
201    chains, or that might all be in the first chain.  Calls to
202    evbuffer_pullup() that cause reallocation and copying of data can thus be
203    avoided.
204 
205    @param buf pointer to the evbuffer
206    @return 0 if no data is available, otherwise the number of available bytes
207      in the first buffer chain.
208 */
209 size_t evbuffer_get_contiguous_space(const struct evbuffer *buf);
210 
211 /**
212   Expands the available space in an evbuffer.
213 
214   Expands the available space in the evbuffer to at least datlen, so that
215   appending datlen additional bytes will not require any new allocations.
216 
217   @param buf the evbuffer to be expanded
218   @param datlen the new minimum length requirement
219   @return 0 if successful, or -1 if an error occurred
220 */
221 int evbuffer_expand(struct evbuffer *buf, size_t datlen);
222 
223 /**
224    Reserves space in the last chain or chains of an evbuffer.
225 
226    Makes space available in the last chain or chains of an evbuffer that can
227    be arbitrarily written to by a user.  The space does not become
228    available for reading until it has been committed with
229    evbuffer_commit_space().
230 
231    The space is made available as one or more extents, represented by
232    an initial pointer and a length.  You can force the memory to be
233    available as only one extent.  Allowing more extents, however, makes the
234    function more efficient.
235 
236    Multiple subsequent calls to this function will make the same space
237    available until evbuffer_commit_space() has been called.
238 
239    It is an error to do anything that moves around the buffer's internal
240    memory structures before committing the space.
241 
242    NOTE: The code currently does not ever use more than two extents.
243    This may change in future versions.
244 
245    @param buf the evbuffer in which to reserve space.
246    @param size how much space to make available, at minimum.  The
247       total length of the extents may be greater than the requested
248       length.
249    @param vec an array of one or more evbuffer_iovec structures to
250       hold pointers to the reserved extents of memory.
251    @param n_vec The length of the vec array.  Must be at least 1;
252        2 is more efficient.
253    @return the number of provided extents, or -1 on error.
254    @see evbuffer_commit_space()
255 */
256 int
257 evbuffer_reserve_space(struct evbuffer *buf, ev_ssize_t size,
258     struct evbuffer_iovec *vec, int n_vec);
259 
260 /**
261    Commits previously reserved space.
262 
263    Commits some of the space previously reserved with
264    evbuffer_reserve_space().  It then becomes available for reading.
265 
266    This function may return an error if the pointer in the extents do
267    not match those returned from evbuffer_reserve_space, or if data
268    has been added to the buffer since the space was reserved.
269 
270    If you want to commit less data than you got reserved space for,
271    modify the iov_len pointer of the appropriate extent to a smaller
272    value.  Note that you may have received more space than you
273    requested if it was available!
274 
275    @param buf the evbuffer in which to reserve space.
276    @param vec one or two extents returned by evbuffer_reserve_space.
277    @param n_vecs the number of extents.
278    @return 0 on success, -1 on error
279    @see evbuffer_reserve_space()
280 */
281 int evbuffer_commit_space(struct evbuffer *buf,
282     struct evbuffer_iovec *vec, int n_vecs);
283 
284 /**
285   Append data to the end of an evbuffer.
286 
287   @param buf the evbuffer to be appended to
288   @param data pointer to the beginning of the data buffer
289   @param datlen the number of bytes to be copied from the data buffer
290   @return 0 on success, -1 on failure.
291  */
292 int evbuffer_add(struct evbuffer *buf, const void *data, size_t datlen);
293 
294 
295 /**
296   Read data from an evbuffer and drain the bytes read.
297 
298   If more bytes are requested than are available in the evbuffer, we
299   only extract as many bytes as were available.
300 
301   @param buf the evbuffer to be read from
302   @param data the destination buffer to store the result
303   @param datlen the maximum size of the destination buffer
304   @return the number of bytes read, or -1 if we can't drain the buffer.
305  */
306 int evbuffer_remove(struct evbuffer *buf, void *data, size_t datlen);
307 
308 /**
309   Read data from an evbuffer, and leave the buffer unchanged.
310 
311   If more bytes are requested than are available in the evbuffer, we
312   only extract as many bytes as were available.
313 
314   @param buf the evbuffer to be read from
315   @param data_out the destination buffer to store the result
316   @param datlen the maximum size of the destination buffer
317   @return the number of bytes read, or -1 if we can't drain the buffer.
318  */
319 ev_ssize_t evbuffer_copyout(struct evbuffer *buf, void *data_out, size_t datlen);
320 
321 /**
322   Read data from an evbuffer into another evbuffer, draining
323   the bytes from the source buffer.  This function avoids copy
324   operations to the extent possible.
325 
326   If more bytes are requested than are available in src, the src
327   buffer is drained completely.
328 
329   @param src the evbuffer to be read from
330   @param dst the destination evbuffer to store the result into
331   @param datlen the maximum numbers of bytes to transfer
332   @return the number of bytes read
333  */
334 int evbuffer_remove_buffer(struct evbuffer *src, struct evbuffer *dst,
335     size_t datlen);
336 
337 /** Used to tell evbuffer_readln what kind of line-ending to look for.
338  */
339 enum evbuffer_eol_style {
340 	/** Any sequence of CR and LF characters is acceptable as an
341 	 * EOL.
342 	 *
343 	 * Note that this style can produce ambiguous results: the
344 	 * sequence "CRLF" will be treated as a single EOL if it is
345 	 * all in the buffer at once, but if you first read a CR from
346 	 * the network and later read an LF from the network, it will
347 	 * be treated as two EOLs.
348 	 */
349 	EVBUFFER_EOL_ANY,
350 	/** An EOL is an LF, optionally preceded by a CR.  This style is
351 	 * most useful for implementing text-based internet protocols. */
352 	EVBUFFER_EOL_CRLF,
353 	/** An EOL is a CR followed by an LF. */
354 	EVBUFFER_EOL_CRLF_STRICT,
355 	/** An EOL is a LF. */
356 	EVBUFFER_EOL_LF
357 };
358 
359 /**
360  * Read a single line from an evbuffer.
361  *
362  * Reads a line terminated by an EOL as determined by the evbuffer_eol_style
363  * argument.  Returns a newly allocated nul-terminated string; the caller must
364  * free the returned value.  The EOL is not included in the returned string.
365  *
366  * @param buffer the evbuffer to read from
367  * @param n_read_out if non-NULL, points to a size_t that is set to the
368  *       number of characters in the returned string.  This is useful for
369  *       strings that can contain NUL characters.
370  * @param eol_style the style of line-ending to use.
371  * @return pointer to a single line, or NULL if an error occurred
372  */
373 char *evbuffer_readln(struct evbuffer *buffer, size_t *n_read_out,
374     enum evbuffer_eol_style eol_style);
375 
376 /**
377   Move all data from one evbuffer into another evbuffer.
378 
379   This is a destructive add.  The data from one buffer moves into
380   the other buffer.  However, no unnecessary memory copies occur.
381 
382   @param outbuf the output buffer
383   @param inbuf the input buffer
384   @return 0 if successful, or -1 if an error occurred
385 
386   @see evbuffer_remove_buffer()
387  */
388 int evbuffer_add_buffer(struct evbuffer *outbuf, struct evbuffer *inbuf);
389 
390 /**
391   Copy data from one evbuffer into another evbuffer.
392 
393   This is a non-destructive add.  The data from one buffer is copied
394   into the other buffer.  However, no unnecessary memory copies occur.
395 
396   Note that buffers already containing buffer references can't be added
397   to other buffers.
398 
399   @param outbuf the output buffer
400   @param inbuf the input buffer
401   @return 0 if successful, or -1 if an error occurred
402  */
403 int evbuffer_add_buffer_reference(struct evbuffer *outbuf,
404     struct evbuffer *inbuf);
405 
406 /**
407    A cleanup function for a piece of memory added to an evbuffer by
408    reference.
409 
410    @see evbuffer_add_reference()
411  */
412 typedef void (*evbuffer_ref_cleanup_cb)(const void *data,
413     size_t datalen, void *extra);
414 
415 /**
416   Reference memory into an evbuffer without copying.
417 
418   The memory needs to remain valid until all the added data has been
419   read.  This function keeps just a reference to the memory without
420   actually incurring the overhead of a copy.
421 
422   @param outbuf the output buffer
423   @param data the memory to reference
424   @param datlen how memory to reference
425   @param cleanupfn callback to be invoked when the memory is no longer
426 	referenced by this evbuffer.
427   @param cleanupfn_arg optional argument to the cleanup callback
428   @return 0 if successful, or -1 if an error occurred
429  */
430 int evbuffer_add_reference(struct evbuffer *outbuf,
431     const void *data, size_t datlen,
432     evbuffer_ref_cleanup_cb cleanupfn, void *cleanupfn_arg);
433 
434 /**
435   Copy data from a file into the evbuffer for writing to a socket.
436 
437   This function avoids unnecessary data copies between userland and
438   kernel.  Where available, it uses sendfile or splice; failing those,
439   it tries to use mmap.
440 
441   The function owns the resulting file descriptor and will close it
442   when finished transferring data.
443 
444   The results of using evbuffer_remove() or evbuffer_pullup() on
445   evbuffers whose data was added using this function are undefined.
446 
447   For more fine-grained control, use evbuffer_add_file_segment.
448 
449   @param outbuf the output buffer
450   @param fd the file descriptor
451   @param offset the offset from which to read data
452   @param length how much data to read, or -1 to read as much as possible.
453     (-1 requires that 'fd' support fstat.)
454   @return 0 if successful, or -1 if an error occurred
455 */
456 
457 int evbuffer_add_file(struct evbuffer *outbuf, int fd, ev_off_t offset,
458     ev_off_t length);
459 
460 /**
461   An evbuffer_file_segment holds a reference to a range of a file --
462   possibly the whole file! -- for use in writing from an evbuffer to a
463   socket.  It could be implemented with mmap, sendfile, splice, or (if all
464   else fails) by just pulling all the data into RAM.  A single
465   evbuffer_file_segment can be added more than once, and to more than one
466   evbuffer.
467  */
468 struct evbuffer_file_segment;
469 
470 /**
471     Flag for creating evbuffer_file_segment: If this flag is set, then when
472     the evbuffer_file_segment is freed and no longer in use by any
473     evbuffer, the underlying fd is closed.
474  */
475 #define EVBUF_FS_CLOSE_ON_FREE    0x01
476 /**
477    Flag for creating evbuffer_file_segment: Disable memory-map based
478    implementations.
479  */
480 #define EVBUF_FS_DISABLE_MMAP     0x02
481 /**
482    Flag for creating evbuffer_file_segment: Disable direct fd-to-fd
483    implementations (including sendfile and splice).
484 
485    You might want to use this option if data needs to be taken from the
486    evbuffer by any means other than writing it to the network: the sendfile
487    backend is fast, but it only works for sending files directly to the
488    network.
489  */
490 #define EVBUF_FS_DISABLE_SENDFILE 0x04
491 /**
492    Flag for creating evbuffer_file_segment: Do not allocate a lock for this
493    segment.  If this option is set, then neither the segment nor any
494    evbuffer it is added to may ever be accessed from more than one thread
495    at a time.
496  */
497 #define EVBUF_FS_DISABLE_LOCKING  0x08
498 
499 /**
500    Create and return a new evbuffer_file_segment for reading data from a
501    file and sending it out via an evbuffer.
502 
503    This function avoids unnecessary data copies between userland and
504    kernel.  Where available, it uses sendfile or splice.
505 
506    The file descriptor must not be closed so long as any evbuffer is using
507    this segment.
508 
509    The results of using evbuffer_remove() or evbuffer_pullup() or any other
510    function that reads bytes from an evbuffer on any evbuffer containing
511    the newly returned segment are undefined, unless you pass the
512    EVBUF_FS_DISABLE_SENDFILE flag to this function.
513 
514    @param fd an open file to read from.
515    @param offset an index within the file at which to start reading
516    @param length how much data to read, or -1 to read as much as possible.
517       (-1 requires that 'fd' support fstat.)
518    @param flags any number of the EVBUF_FS_* flags
519    @return a new evbuffer_file_segment, or NULL on failure.
520  **/
521 struct evbuffer_file_segment *evbuffer_file_segment_new(
522 	int fd, ev_off_t offset, ev_off_t length, unsigned flags);
523 
524 /**
525    Free an evbuffer_file_segment
526 
527    It is safe to call this function even if the segment has been added to
528    one or more evbuffers.  The evbuffer_file_segment will not be freed
529    until no more references to it exist.
530  */
531 void evbuffer_file_segment_free(struct evbuffer_file_segment *seg);
532 
533 /**
534    Insert some or all of an evbuffer_file_segment at the end of an evbuffer
535 
536    Note that the offset and length parameters of this function have a
537    different meaning from those provided to evbuffer_file_segment_new: When
538    you create the segment, the offset is the offset _within the file_, and
539    the length is the length _of the segment_, whereas when you add a
540    segment to an evbuffer, the offset is _within the segment_ and the
541    length is the length of the _part of the segment you want to use.
542 
543    In other words, if you have a 10 KiB file, and you create an
544    evbuffer_file_segment for it with offset 20 and length 1000, it will
545    refer to bytes 20..1019 inclusive.  If you then pass this segment to
546    evbuffer_add_file_segment and specify an offset of 20 and a length of
547    50, you will be adding bytes 40..99 inclusive.
548 
549    @param buf the evbuffer to append to
550    @param seg the segment to add
551    @param offset the offset within the segment to start from
552    @param length the amount of data to add, or -1 to add it all.
553    @return 0 on success, -1 on failure.
554  */
555 int evbuffer_add_file_segment(struct evbuffer *buf,
556     struct evbuffer_file_segment *seg, ev_off_t offset, ev_off_t length);
557 
558 /**
559   Append a formatted string to the end of an evbuffer.
560 
561   The string is formated as printf.
562 
563   @param buf the evbuffer that will be appended to
564   @param fmt a format string
565   @param ... arguments that will be passed to printf(3)
566   @return The number of bytes added if successful, or -1 if an error occurred.
567 
568   @see evutil_printf(), evbuffer_add_vprintf()
569  */
570 int evbuffer_add_printf(struct evbuffer *buf, const char *fmt, ...)
571 #ifdef __GNUC__
572   __attribute__((format(printf, 2, 3)))
573 #endif
574 ;
575 
576 /**
577   Append a va_list formatted string to the end of an evbuffer.
578 
579   @param buf the evbuffer that will be appended to
580   @param fmt a format string
581   @param ap a varargs va_list argument array that will be passed to vprintf(3)
582   @return The number of bytes added if successful, or -1 if an error occurred.
583  */
584 int evbuffer_add_vprintf(struct evbuffer *buf, const char *fmt, va_list ap);
585 
586 
587 /**
588   Remove a specified number of bytes data from the beginning of an evbuffer.
589 
590   @param buf the evbuffer to be drained
591   @param len the number of bytes to drain from the beginning of the buffer
592   @return 0 on success, -1 on failure.
593  */
594 int evbuffer_drain(struct evbuffer *buf, size_t len);
595 
596 
597 /**
598   Write the contents of an evbuffer to a file descriptor.
599 
600   The evbuffer will be drained after the bytes have been successfully written.
601 
602   @param buffer the evbuffer to be written and drained
603   @param fd the file descriptor to be written to
604   @return the number of bytes written, or -1 if an error occurred
605   @see evbuffer_read()
606  */
607 int evbuffer_write(struct evbuffer *buffer, evutil_socket_t fd);
608 
609 /**
610   Write some of the contents of an evbuffer to a file descriptor.
611 
612   The evbuffer will be drained after the bytes have been successfully written.
613 
614   @param buffer the evbuffer to be written and drained
615   @param fd the file descriptor to be written to
616   @param howmuch the largest allowable number of bytes to write, or -1
617 	to write as many bytes as we can.
618   @return the number of bytes written, or -1 if an error occurred
619   @see evbuffer_read()
620  */
621 int evbuffer_write_atmost(struct evbuffer *buffer, evutil_socket_t fd,
622 						  ev_ssize_t howmuch);
623 
624 /**
625   Read from a file descriptor and store the result in an evbuffer.
626 
627   @param buffer the evbuffer to store the result
628   @param fd the file descriptor to read from
629   @param howmuch the number of bytes to be read
630   @return the number of bytes read, or -1 if an error occurred
631   @see evbuffer_write()
632  */
633 int evbuffer_read(struct evbuffer *buffer, evutil_socket_t fd, int howmuch);
634 
635 /**
636    Search for a string within an evbuffer.
637 
638    @param buffer the evbuffer to be searched
639    @param what the string to be searched for
640    @param len the length of the search string
641    @param start NULL or a pointer to a valid struct evbuffer_ptr.
642    @return a struct evbuffer_ptr whose 'pos' field has the offset of the
643      first occurrence of the string in the buffer after 'start'.  The 'pos'
644      field of the result is -1 if the string was not found.
645  */
646 struct evbuffer_ptr evbuffer_search(struct evbuffer *buffer, const char *what, size_t len, const struct evbuffer_ptr *start);
647 
648 /**
649    Search for a string within part of an evbuffer.
650 
651    @param buffer the evbuffer to be searched
652    @param what the string to be searched for
653    @param len the length of the search string
654    @param start NULL or a pointer to a valid struct evbuffer_ptr that
655      indicates where we should start searching.
656    @param end NULL or a pointer to a valid struct evbuffer_ptr that
657      indicates where we should stop searching.
658    @return a struct evbuffer_ptr whose 'pos' field has the offset of the
659      first occurrence of the string in the buffer after 'start'.  The 'pos'
660      field of the result is -1 if the string was not found.
661  */
662 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);
663 
664 /**
665    Defines how to adjust an evbuffer_ptr by evbuffer_ptr_set()
666 
667    @see evbuffer_ptr_set() */
668 enum evbuffer_ptr_how {
669 	/** Sets the pointer to the position; can be called on with an
670 	    uninitialized evbuffer_ptr. */
671 	EVBUFFER_PTR_SET,
672 	/** Advances the pointer by adding to the current position. */
673 	EVBUFFER_PTR_ADD
674 };
675 
676 /**
677    Sets the search pointer in the buffer to position.
678 
679    There are two ways to use this function: you can call
680       evbuffer_ptr_set(buf, &pos, N, EVBUFFER_PTR_SET)
681    to move 'pos' to a position 'N' bytes after the start of the buffer, or
682       evbuffer_ptr_set(buf, &pos, N, EVBUFFER_PTR_SET)
683    to move 'pos' forward by 'N' bytes.
684 
685    If evbuffer_ptr is not initialized, this function can only be called
686    with EVBUFFER_PTR_SET.
687 
688    An evbuffer_ptr can represent any position from the start of the buffer to
689    a position immediately after the end of the buffer.
690 
691    @param buffer the evbuffer to be search
692    @param ptr a pointer to a struct evbuffer_ptr
693    @param position the position at which to start the next search
694    @param how determines how the pointer should be manipulated.
695    @returns 0 on success or -1 otherwise
696 */
697 int
698 evbuffer_ptr_set(struct evbuffer *buffer, struct evbuffer_ptr *ptr,
699     size_t position, enum evbuffer_ptr_how how);
700 
701 /**
702    Search for an end-of-line string within an evbuffer.
703 
704    @param buffer the evbuffer to be searched
705    @param start NULL or a pointer to a valid struct evbuffer_ptr to start
706       searching at.
707    @param eol_len_out If non-NULL, the pointed-to value will be set to
708       the length of the end-of-line string.
709    @param eol_style The kind of EOL to look for; see evbuffer_readln() for
710       more information
711    @return a struct evbuffer_ptr whose 'pos' field has the offset of the
712      first occurrence EOL in the buffer after 'start'.  The 'pos'
713      field of the result is -1 if the string was not found.
714  */
715 struct evbuffer_ptr evbuffer_search_eol(struct evbuffer *buffer,
716     struct evbuffer_ptr *start, size_t *eol_len_out,
717     enum evbuffer_eol_style eol_style);
718 
719 /** Function to peek at data inside an evbuffer without removing it or
720     copying it out.
721 
722     Pointers to the data are returned by filling the 'vec_out' array
723     with pointers to one or more extents of data inside the buffer.
724 
725     The total data in the extents that you get back may be more than
726     you requested (if there is more data last extent than you asked
727     for), or less (if you do not provide enough evbuffer_iovecs, or if
728     the buffer does not have as much data as you asked to see).
729 
730     @param buffer the evbuffer to peek into,
731     @param len the number of bytes to try to peek.  If negative, we
732        will try to fill as much of vec_out as we can.
733     @param start_at an evbuffer_ptr indicating the point at which we
734        should start looking for data.  NULL means, "At the start of the
735        buffer."
736     @param vec_out an array of evbuffer_iovec
737     @param n_vec the length of vec_out.  If 0, we only count how many
738        extents would be necessary to point to the requested amount of
739        data.
740     @return The number of extents needed.  This may be less than n_vec
741        if we didn't need all the evbuffer_iovecs we were given, or more
742        than n_vec if we would need more to return all the data that was
743        requested.
744  */
745 int evbuffer_peek(struct evbuffer *buffer, ev_ssize_t len,
746     struct evbuffer_ptr *start_at,
747     struct evbuffer_iovec *vec_out, int n_vec);
748 
749 
750 /** Structure passed to an evbuffer_cb_func evbuffer callback
751 
752     @see evbuffer_cb_func, evbuffer_add_cb()
753  */
754 struct evbuffer_cb_info {
755 	/** The number of bytes in this evbuffer when callbacks were last
756 	 * invoked. */
757 	size_t orig_size;
758 	/** The number of bytes added since callbacks were last invoked. */
759 	size_t n_added;
760 	/** The number of bytes removed since callbacks were last invoked. */
761 	size_t n_deleted;
762 };
763 
764 /** Type definition for a callback that is invoked whenever data is added or
765     removed from an evbuffer.
766 
767     An evbuffer may have one or more callbacks set at a time.  The order
768     in which they are executed is undefined.
769 
770     A callback function may add more callbacks, or remove itself from the
771     list of callbacks, or add or remove data from the buffer.  It may not
772     remove another callback from the list.
773 
774     If a callback adds or removes data from the buffer or from another
775     buffer, this can cause a recursive invocation of your callback or
776     other callbacks.  If you ask for an infinite loop, you might just get
777     one: watch out!
778 
779     @param buffer the buffer whose size has changed
780     @param info a structure describing how the buffer changed.
781     @param arg a pointer to user data
782 */
783 typedef void (*evbuffer_cb_func)(struct evbuffer *buffer, const struct evbuffer_cb_info *info, void *arg);
784 
785 struct evbuffer_cb_entry;
786 /** Add a new callback to an evbuffer.
787 
788   Subsequent calls to evbuffer_add_cb() add new callbacks.  To remove this
789   callback, call evbuffer_remove_cb or evbuffer_remove_cb_entry.
790 
791   @param buffer the evbuffer to be monitored
792   @param cb the callback function to invoke when the evbuffer is modified,
793 	or NULL to remove all callbacks.
794   @param cbarg an argument to be provided to the callback function
795   @return a handle to the callback on success, or NULL on failure.
796  */
797 struct evbuffer_cb_entry *evbuffer_add_cb(struct evbuffer *buffer, evbuffer_cb_func cb, void *cbarg);
798 
799 /** Remove a callback from an evbuffer, given a handle returned from
800     evbuffer_add_cb.
801 
802     Calling this function invalidates the handle.
803 
804     @return 0 if a callback was removed, or -1 if no matching callback was
805     found.
806  */
807 int evbuffer_remove_cb_entry(struct evbuffer *buffer,
808 			     struct evbuffer_cb_entry *ent);
809 
810 /** Remove a callback from an evbuffer, given the function and argument
811     used to add it.
812 
813     @return 0 if a callback was removed, or -1 if no matching callback was
814     found.
815  */
816 int evbuffer_remove_cb(struct evbuffer *buffer, evbuffer_cb_func cb, void *cbarg);
817 
818 /** If this flag is not set, then a callback is temporarily disabled, and
819  * should not be invoked.
820  *
821  * @see evbuffer_cb_set_flags(), evbuffer_cb_clear_flags()
822  */
823 #define EVBUFFER_CB_ENABLED 1
824 
825 /** Change the flags that are set for a callback on a buffer by adding more.
826 
827     @param buffer the evbuffer that the callback is watching.
828     @param cb the callback whose status we want to change.
829     @param flags EVBUFFER_CB_ENABLED to re-enable the callback.
830     @return 0 on success, -1 on failure.
831  */
832 int evbuffer_cb_set_flags(struct evbuffer *buffer,
833 			  struct evbuffer_cb_entry *cb, ev_uint32_t flags);
834 
835 /** Change the flags that are set for a callback on a buffer by removing some
836 
837     @param buffer the evbuffer that the callback is watching.
838     @param cb the callback whose status we want to change.
839     @param flags EVBUFFER_CB_ENABLED to disable the callback.
840     @return 0 on success, -1 on failure.
841  */
842 int evbuffer_cb_clear_flags(struct evbuffer *buffer,
843 			  struct evbuffer_cb_entry *cb, ev_uint32_t flags);
844 
845 #if 0
846 /** Postpone calling a given callback until unsuspend is called later.
847 
848     This is different from disabling the callback, since the callback will get
849 	invoked later if the buffer size changes between now and when we unsuspend
850 	it.
851 
852 	@param the buffer that the callback is watching.
853 	@param cb the callback we want to suspend.
854  */
855 void evbuffer_cb_suspend(struct evbuffer *buffer, struct evbuffer_cb_entry *cb);
856 /** Stop postponing a callback that we postponed with evbuffer_cb_suspend.
857 
858 	If data was added to or removed from the buffer while the callback was
859 	suspended, the callback will get called once now.
860 
861 	@param the buffer that the callback is watching.
862 	@param cb the callback we want to stop suspending.
863  */
864 void evbuffer_cb_unsuspend(struct evbuffer *buffer, struct evbuffer_cb_entry *cb);
865 #endif
866 
867 /**
868   Makes the data at the begging of an evbuffer contiguous.
869 
870   @param buf the evbuffer to make contiguous
871   @param size the number of bytes to make contiguous, or -1 to make the
872 	entire buffer contiguous.
873   @return a pointer to the contiguous memory array
874 */
875 
876 unsigned char *evbuffer_pullup(struct evbuffer *buf, ev_ssize_t size);
877 
878 /**
879   Prepends data to the beginning of the evbuffer
880 
881   @param buf the evbuffer to which to prepend data
882   @param data a pointer to the memory to prepend
883   @param size the number of bytes to prepend
884   @return 0 if successful, or -1 otherwise
885 */
886 
887 int evbuffer_prepend(struct evbuffer *buf, const void *data, size_t size);
888 
889 /**
890   Prepends all data from the src evbuffer to the beginning of the dst
891   evbuffer.
892 
893   @param dst the evbuffer to which to prepend data
894   @param src the evbuffer to prepend; it will be emptied as a result
895   @return 0 if successful, or -1 otherwise
896 */
897 int evbuffer_prepend_buffer(struct evbuffer *dst, struct evbuffer* src);
898 
899 /**
900    Prevent calls that modify an evbuffer from succeeding. A buffer may
901    frozen at the front, at the back, or at both the front and the back.
902 
903    If the front of a buffer is frozen, operations that drain data from
904    the front of the buffer, or that prepend data to the buffer, will
905    fail until it is unfrozen.   If the back a buffer is frozen, operations
906    that append data from the buffer will fail until it is unfrozen.
907 
908    @param buf The buffer to freeze
909    @param at_front If true, we freeze the front of the buffer.  If false,
910       we freeze the back.
911    @return 0 on success, -1 on failure.
912 */
913 int evbuffer_freeze(struct evbuffer *buf, int at_front);
914 /**
915    Re-enable calls that modify an evbuffer.
916 
917    @param buf The buffer to un-freeze
918    @param at_front If true, we unfreeze the front of the buffer.  If false,
919       we unfreeze the back.
920    @return 0 on success, -1 on failure.
921  */
922 int evbuffer_unfreeze(struct evbuffer *buf, int at_front);
923 
924 struct event_base;
925 /**
926    Force all the callbacks on an evbuffer to be run, not immediately after
927    the evbuffer is altered, but instead from inside the event loop.
928 
929    This can be used to serialize all the callbacks to a single thread
930    of execution.
931  */
932 int evbuffer_defer_callbacks(struct evbuffer *buffer, struct event_base *base);
933 
934 #ifdef __cplusplus
935 }
936 #endif
937 
938 #endif /* _EVENT2_BUFFER_H_ */
939