2 * Copyright (c) 2002-2007 Niels Provos <provos@citi.umich.edu>
3 * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
13 * 3. The name of the author may not be used to endorse or promote products
14 * derived from this software without specific prior written permission.
16 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
17 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
18 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
19 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
20 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
21 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
22 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
23 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
25 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28 #include "event2/event-config.h"
29 #include "evconfig-private.h"
37 #ifdef EVENT__HAVE_VASPRINTF
38 /* If we have vasprintf, we need to define _GNU_SOURCE before we include
39 * stdio.h. This comes from evconfig-private.h.
43 #include <sys/types.h>
45 #ifdef EVENT__HAVE_SYS_TIME_H
49 #ifdef EVENT__HAVE_SYS_SOCKET_H
50 #include <sys/socket.h>
53 #ifdef EVENT__HAVE_SYS_UIO_H
57 #ifdef EVENT__HAVE_SYS_IOCTL_H
58 #include <sys/ioctl.h>
61 #ifdef EVENT__HAVE_SYS_MMAN_H
65 #ifdef EVENT__HAVE_SYS_SENDFILE_H
66 #include <sys/sendfile.h>
68 #ifdef EVENT__HAVE_SYS_STAT_H
77 #ifdef EVENT__HAVE_STDARG_H
80 #ifdef EVENT__HAVE_UNISTD_H
85 #include "event2/event.h"
86 #include "event2/buffer.h"
87 #include "event2/buffer_compat.h"
88 #include "event2/bufferevent.h"
89 #include "event2/bufferevent_compat.h"
90 #include "event2/bufferevent_struct.h"
91 #include "event2/thread.h"
92 #include "log-internal.h"
93 #include "mm-internal.h"
94 #include "util-internal.h"
95 #include "evthread-internal.h"
96 #include "evbuffer-internal.h"
97 #include "bufferevent-internal.h"
98 #include "event-internal.h"
100 /* some systems do not have MAP_FAILED */
102 #define MAP_FAILED ((void *)-1)
105 /* send file support */
106 #if defined(EVENT__HAVE_SYS_SENDFILE_H) && defined(EVENT__HAVE_SENDFILE) && defined(__linux__)
107 #define USE_SENDFILE 1
108 #define SENDFILE_IS_LINUX 1
109 #elif defined(EVENT__HAVE_SENDFILE) && defined(__FreeBSD__)
110 #define USE_SENDFILE 1
111 #define SENDFILE_IS_FREEBSD 1
112 #elif defined(EVENT__HAVE_SENDFILE) && defined(__APPLE__)
113 #define USE_SENDFILE 1
114 #define SENDFILE_IS_MACOSX 1
115 #elif defined(EVENT__HAVE_SENDFILE) && defined(__sun__) && defined(__svr4__)
116 #define USE_SENDFILE 1
117 #define SENDFILE_IS_SOLARIS 1
120 /* Mask of user-selectable callback flags. */
121 #define EVBUFFER_CB_USER_FLAGS 0xffff
122 /* Mask of all internal-use-only flags. */
123 #define EVBUFFER_CB_INTERNAL_FLAGS 0xffff0000
125 /* Flag set if the callback is using the cb_obsolete function pointer */
126 #define EVBUFFER_CB_OBSOLETE 0x00040000
128 /* evbuffer_chain support */
129 #define CHAIN_SPACE_PTR(ch) ((ch)->buffer + (ch)->misalign + (ch)->off)
130 #define CHAIN_SPACE_LEN(ch) ((ch)->flags & EVBUFFER_IMMUTABLE ? \
131 0 : (ch)->buffer_len - ((ch)->misalign + (ch)->off))
133 #define CHAIN_PINNED(ch) (((ch)->flags & EVBUFFER_MEM_PINNED_ANY) != 0)
134 #define CHAIN_PINNED_R(ch) (((ch)->flags & EVBUFFER_MEM_PINNED_R) != 0)
136 /* evbuffer_ptr support */
137 #define PTR_NOT_FOUND(ptr) do { \
139 (ptr)->internal_.chain = NULL; \
140 (ptr)->internal_.pos_in_chain = 0; \
143 static void evbuffer_chain_align(struct evbuffer_chain *chain);
144 static int evbuffer_chain_should_realign(struct evbuffer_chain *chain,
146 static void evbuffer_deferred_callback(struct event_callback *cb, void *arg);
147 static int evbuffer_ptr_memcmp(const struct evbuffer *buf,
148 const struct evbuffer_ptr *pos, const char *mem, size_t len);
149 static struct evbuffer_chain *evbuffer_expand_singlechain(struct evbuffer *buf,
151 static int evbuffer_ptr_subtract(struct evbuffer *buf, struct evbuffer_ptr *pos,
153 static int evbuffer_file_segment_materialize(struct evbuffer_file_segment *seg);
154 static inline void evbuffer_chain_incref(struct evbuffer_chain *chain);
156 static struct evbuffer_chain *
157 evbuffer_chain_new(size_t size)
159 struct evbuffer_chain *chain;
162 if (size > EVBUFFER_CHAIN_MAX - EVBUFFER_CHAIN_SIZE)
165 size += EVBUFFER_CHAIN_SIZE;
167 /* get the next largest memory that can hold the buffer */
168 if (size < EVBUFFER_CHAIN_MAX / 2) {
169 to_alloc = MIN_BUFFER_SIZE;
170 while (to_alloc < size) {
177 /* we get everything in one chunk */
178 if ((chain = mm_malloc(to_alloc)) == NULL)
181 memset(chain, 0, EVBUFFER_CHAIN_SIZE);
183 chain->buffer_len = to_alloc - EVBUFFER_CHAIN_SIZE;
185 /* this way we can manipulate the buffer to different addresses,
186 * which is required for mmap for example.
188 chain->buffer = EVBUFFER_CHAIN_EXTRA(unsigned char, chain);
196 evbuffer_chain_free(struct evbuffer_chain *chain)
198 EVUTIL_ASSERT(chain->refcnt > 0);
199 if (--chain->refcnt > 0) {
200 /* chain is still referenced by other chains */
204 if (CHAIN_PINNED(chain)) {
205 /* will get freed once no longer dangling */
207 chain->flags |= EVBUFFER_DANGLING;
211 /* safe to release chain, it's either a referencing
212 * chain or all references to it have been freed */
213 if (chain->flags & EVBUFFER_REFERENCE) {
214 struct evbuffer_chain_reference *info =
215 EVBUFFER_CHAIN_EXTRA(
216 struct evbuffer_chain_reference,
219 (*info->cleanupfn)(chain->buffer,
223 if (chain->flags & EVBUFFER_FILESEGMENT) {
224 struct evbuffer_chain_file_segment *info =
225 EVBUFFER_CHAIN_EXTRA(
226 struct evbuffer_chain_file_segment,
230 if (info->segment->is_mapping)
231 UnmapViewOfFile(chain->buffer);
233 evbuffer_file_segment_free(info->segment);
236 if (chain->flags & EVBUFFER_MULTICAST) {
237 struct evbuffer_multicast_parent *info =
238 EVBUFFER_CHAIN_EXTRA(
239 struct evbuffer_multicast_parent,
241 /* referencing chain is being freed, decrease
242 * refcounts of source chain and associated
243 * evbuffer (which get freed once both reach
245 EVUTIL_ASSERT(info->source != NULL);
246 EVUTIL_ASSERT(info->parent != NULL);
247 EVBUFFER_LOCK(info->source);
248 evbuffer_chain_free(info->parent);
249 evbuffer_decref_and_unlock_(info->source);
256 evbuffer_free_all_chains(struct evbuffer_chain *chain)
258 struct evbuffer_chain *next;
259 for (; chain; chain = next) {
261 evbuffer_chain_free(chain);
267 evbuffer_chains_all_empty(struct evbuffer_chain *chain)
269 for (; chain; chain = chain->next) {
276 /* The definition is needed for EVUTIL_ASSERT, which uses sizeof to avoid
277 "unused variable" warnings. */
278 static inline int evbuffer_chains_all_empty(struct evbuffer_chain *chain) {
283 /* Free all trailing chains in 'buf' that are neither pinned nor empty, prior
284 * to replacing them all with a new chain. Return a pointer to the place
285 * where the new chain will go.
287 * Internal; requires lock. The caller must fix up buf->last and buf->first
288 * as needed; they might have been freed.
290 static struct evbuffer_chain **
291 evbuffer_free_trailing_empty_chains(struct evbuffer *buf)
293 struct evbuffer_chain **ch = buf->last_with_datap;
294 /* Find the first victim chain. It might be *last_with_datap */
295 while ((*ch) && ((*ch)->off != 0 || CHAIN_PINNED(*ch)))
298 EVUTIL_ASSERT(evbuffer_chains_all_empty(*ch));
299 evbuffer_free_all_chains(*ch);
305 /* Add a single chain 'chain' to the end of 'buf', freeing trailing empty
306 * chains as necessary. Requires lock. Does not schedule callbacks.
309 evbuffer_chain_insert(struct evbuffer *buf,
310 struct evbuffer_chain *chain)
312 ASSERT_EVBUFFER_LOCKED(buf);
313 if (*buf->last_with_datap == NULL) {
314 /* There are no chains data on the buffer at all. */
315 EVUTIL_ASSERT(buf->last_with_datap == &buf->first);
316 EVUTIL_ASSERT(buf->first == NULL);
317 buf->first = buf->last = chain;
319 struct evbuffer_chain **chp;
320 chp = evbuffer_free_trailing_empty_chains(buf);
323 buf->last_with_datap = chp;
326 buf->total_len += chain->off;
329 static inline struct evbuffer_chain *
330 evbuffer_chain_insert_new(struct evbuffer *buf, size_t datlen)
332 struct evbuffer_chain *chain;
333 if ((chain = evbuffer_chain_new(datlen)) == NULL)
335 evbuffer_chain_insert(buf, chain);
340 evbuffer_chain_pin_(struct evbuffer_chain *chain, unsigned flag)
342 EVUTIL_ASSERT((chain->flags & flag) == 0);
343 chain->flags |= flag;
347 evbuffer_chain_unpin_(struct evbuffer_chain *chain, unsigned flag)
349 EVUTIL_ASSERT((chain->flags & flag) != 0);
350 chain->flags &= ~flag;
351 if (chain->flags & EVBUFFER_DANGLING)
352 evbuffer_chain_free(chain);
356 evbuffer_chain_incref(struct evbuffer_chain *chain)
364 struct evbuffer *buffer;
366 buffer = mm_calloc(1, sizeof(struct evbuffer));
370 LIST_INIT(&buffer->callbacks);
372 buffer->last_with_datap = &buffer->first;
378 evbuffer_set_flags(struct evbuffer *buf, ev_uint64_t flags)
381 buf->flags |= (ev_uint32_t)flags;
382 EVBUFFER_UNLOCK(buf);
387 evbuffer_clear_flags(struct evbuffer *buf, ev_uint64_t flags)
390 buf->flags &= ~(ev_uint32_t)flags;
391 EVBUFFER_UNLOCK(buf);
396 evbuffer_incref_(struct evbuffer *buf)
400 EVBUFFER_UNLOCK(buf);
404 evbuffer_incref_and_lock_(struct evbuffer *buf)
411 evbuffer_defer_callbacks(struct evbuffer *buffer, struct event_base *base)
413 EVBUFFER_LOCK(buffer);
414 buffer->cb_queue = base;
415 buffer->deferred_cbs = 1;
416 event_deferred_cb_init_(&buffer->deferred,
417 event_base_get_npriorities(base) / 2,
418 evbuffer_deferred_callback, buffer);
419 EVBUFFER_UNLOCK(buffer);
424 evbuffer_enable_locking(struct evbuffer *buf, void *lock)
426 #ifdef EVENT__DISABLE_THREAD_SUPPORT
433 EVTHREAD_ALLOC_LOCK(lock, EVTHREAD_LOCKTYPE_RECURSIVE);
448 evbuffer_set_parent_(struct evbuffer *buf, struct bufferevent *bev)
452 EVBUFFER_UNLOCK(buf);
456 evbuffer_run_callbacks(struct evbuffer *buffer, int running_deferred)
458 struct evbuffer_cb_entry *cbent, *next;
459 struct evbuffer_cb_info info;
461 ev_uint32_t mask, masked_val;
464 if (running_deferred) {
465 mask = EVBUFFER_CB_NODEFER|EVBUFFER_CB_ENABLED;
466 masked_val = EVBUFFER_CB_ENABLED;
467 } else if (buffer->deferred_cbs) {
468 mask = EVBUFFER_CB_NODEFER|EVBUFFER_CB_ENABLED;
469 masked_val = EVBUFFER_CB_NODEFER|EVBUFFER_CB_ENABLED;
470 /* Don't zero-out n_add/n_del, since the deferred callbacks
471 will want to see them. */
474 mask = EVBUFFER_CB_ENABLED;
475 masked_val = EVBUFFER_CB_ENABLED;
478 ASSERT_EVBUFFER_LOCKED(buffer);
480 if (LIST_EMPTY(&buffer->callbacks)) {
481 buffer->n_add_for_cb = buffer->n_del_for_cb = 0;
484 if (buffer->n_add_for_cb == 0 && buffer->n_del_for_cb == 0)
487 new_size = buffer->total_len;
488 info.orig_size = new_size + buffer->n_del_for_cb - buffer->n_add_for_cb;
489 info.n_added = buffer->n_add_for_cb;
490 info.n_deleted = buffer->n_del_for_cb;
492 buffer->n_add_for_cb = 0;
493 buffer->n_del_for_cb = 0;
495 for (cbent = LIST_FIRST(&buffer->callbacks);
496 cbent != LIST_END(&buffer->callbacks);
498 /* Get the 'next' pointer now in case this callback decides
499 * to remove itself or something. */
500 next = LIST_NEXT(cbent, next);
502 if ((cbent->flags & mask) != masked_val)
505 if ((cbent->flags & EVBUFFER_CB_OBSOLETE))
506 cbent->cb.cb_obsolete(buffer,
507 info.orig_size, new_size, cbent->cbarg);
509 cbent->cb.cb_func(buffer, &info, cbent->cbarg);
514 evbuffer_invoke_callbacks_(struct evbuffer *buffer)
516 if (LIST_EMPTY(&buffer->callbacks)) {
517 buffer->n_add_for_cb = buffer->n_del_for_cb = 0;
521 if (buffer->deferred_cbs) {
522 if (event_deferred_cb_schedule_(buffer->cb_queue, &buffer->deferred)) {
523 evbuffer_incref_and_lock_(buffer);
525 bufferevent_incref_(buffer->parent);
526 EVBUFFER_UNLOCK(buffer);
530 evbuffer_run_callbacks(buffer, 0);
534 evbuffer_deferred_callback(struct event_callback *cb, void *arg)
536 struct bufferevent *parent = NULL;
537 struct evbuffer *buffer = arg;
539 /* XXXX It would be better to run these callbacks without holding the
541 EVBUFFER_LOCK(buffer);
542 parent = buffer->parent;
543 evbuffer_run_callbacks(buffer, 1);
544 evbuffer_decref_and_unlock_(buffer);
546 bufferevent_decref_(parent);
550 evbuffer_remove_all_callbacks(struct evbuffer *buffer)
552 struct evbuffer_cb_entry *cbent;
554 while ((cbent = LIST_FIRST(&buffer->callbacks))) {
555 LIST_REMOVE(cbent, next);
561 evbuffer_decref_and_unlock_(struct evbuffer *buffer)
563 struct evbuffer_chain *chain, *next;
564 ASSERT_EVBUFFER_LOCKED(buffer);
566 EVUTIL_ASSERT(buffer->refcnt > 0);
568 if (--buffer->refcnt > 0) {
569 EVBUFFER_UNLOCK(buffer);
573 for (chain = buffer->first; chain != NULL; chain = next) {
575 evbuffer_chain_free(chain);
577 evbuffer_remove_all_callbacks(buffer);
578 if (buffer->deferred_cbs)
579 event_deferred_cb_cancel_(buffer->cb_queue, &buffer->deferred);
581 EVBUFFER_UNLOCK(buffer);
582 if (buffer->own_lock)
583 EVTHREAD_FREE_LOCK(buffer->lock, EVTHREAD_LOCKTYPE_RECURSIVE);
588 evbuffer_free(struct evbuffer *buffer)
590 EVBUFFER_LOCK(buffer);
591 evbuffer_decref_and_unlock_(buffer);
595 evbuffer_lock(struct evbuffer *buf)
601 evbuffer_unlock(struct evbuffer *buf)
603 EVBUFFER_UNLOCK(buf);
607 evbuffer_get_length(const struct evbuffer *buffer)
611 EVBUFFER_LOCK(buffer);
613 result = (buffer->total_len);
615 EVBUFFER_UNLOCK(buffer);
621 evbuffer_get_contiguous_space(const struct evbuffer *buf)
623 struct evbuffer_chain *chain;
628 result = (chain != NULL ? chain->off : 0);
629 EVBUFFER_UNLOCK(buf);
635 evbuffer_add_iovec(struct evbuffer * buf, struct evbuffer_iovec * vec, int n_vec) {
644 for (n = 0; n < n_vec; n++) {
645 to_alloc += vec[n].iov_len;
648 if (evbuffer_expand_fast_(buf, to_alloc, 2) < 0) {
652 for (n = 0; n < n_vec; n++) {
653 /* XXX each 'add' call here does a bunch of setup that's
654 * obviated by evbuffer_expand_fast_, and some cleanup that we
655 * would like to do only once. Instead we should just extract
656 * the part of the code that's needed. */
658 if (evbuffer_add(buf, vec[n].iov_base, vec[n].iov_len) < 0) {
662 res += vec[n].iov_len;
666 EVBUFFER_UNLOCK(buf);
671 evbuffer_reserve_space(struct evbuffer *buf, ev_ssize_t size,
672 struct evbuffer_iovec *vec, int n_vecs)
674 struct evbuffer_chain *chain, **chainp;
683 if ((chain = evbuffer_expand_singlechain(buf, size)) == NULL)
686 vec[0].iov_base = (void *)CHAIN_SPACE_PTR(chain);
687 vec[0].iov_len = (size_t)CHAIN_SPACE_LEN(chain);
688 EVUTIL_ASSERT(size<0 || (size_t)vec[0].iov_len >= (size_t)size);
691 if (evbuffer_expand_fast_(buf, size, n_vecs)<0)
693 n = evbuffer_read_setup_vecs_(buf, size, vec, n_vecs,
698 EVBUFFER_UNLOCK(buf);
704 advance_last_with_data(struct evbuffer *buf)
707 struct evbuffer_chain **chainp = buf->last_with_datap;
709 ASSERT_EVBUFFER_LOCKED(buf);
714 while ((*chainp)->next) {
715 chainp = &(*chainp)->next;
717 buf->last_with_datap = chainp;
724 evbuffer_commit_space(struct evbuffer *buf,
725 struct evbuffer_iovec *vec, int n_vecs)
727 struct evbuffer_chain *chain, **firstchainp, **chainp;
739 } else if (n_vecs == 1 &&
740 (buf->last && vec[0].iov_base == (void *)CHAIN_SPACE_PTR(buf->last))) {
741 /* The user only got or used one chain; it might not
742 * be the first one with space in it. */
743 if ((size_t)vec[0].iov_len > (size_t)CHAIN_SPACE_LEN(buf->last))
745 buf->last->off += vec[0].iov_len;
746 added = vec[0].iov_len;
748 advance_last_with_data(buf);
752 /* Advance 'firstchain' to the first chain with space in it. */
753 firstchainp = buf->last_with_datap;
756 if (CHAIN_SPACE_LEN(*firstchainp) == 0) {
757 firstchainp = &(*firstchainp)->next;
760 chain = *firstchainp;
761 /* pass 1: make sure that the pointers and lengths of vecs[] are in
762 * bounds before we try to commit anything. */
763 for (i=0; i<n_vecs; ++i) {
766 if (vec[i].iov_base != (void *)CHAIN_SPACE_PTR(chain) ||
767 (size_t)vec[i].iov_len > CHAIN_SPACE_LEN(chain))
771 /* pass 2: actually adjust all the chains. */
772 chainp = firstchainp;
773 for (i=0; i<n_vecs; ++i) {
774 (*chainp)->off += vec[i].iov_len;
775 added += vec[i].iov_len;
776 if (vec[i].iov_len) {
777 buf->last_with_datap = chainp;
779 chainp = &(*chainp)->next;
783 buf->total_len += added;
784 buf->n_add_for_cb += added;
786 evbuffer_invoke_callbacks_(buf);
789 EVBUFFER_UNLOCK(buf);
794 HAS_PINNED_R(struct evbuffer *buf)
796 return (buf->last && CHAIN_PINNED_R(buf->last));
800 ZERO_CHAIN(struct evbuffer *dst)
802 ASSERT_EVBUFFER_LOCKED(dst);
805 dst->last_with_datap = &(dst)->first;
809 /* Prepares the contents of src to be moved to another buffer by removing
810 * read-pinned chains. The first pinned chain is saved in first, and the
811 * last in last. If src has no read-pinned chains, first and last are set
814 PRESERVE_PINNED(struct evbuffer *src, struct evbuffer_chain **first,
815 struct evbuffer_chain **last)
817 struct evbuffer_chain *chain, **pinned;
819 ASSERT_EVBUFFER_LOCKED(src);
821 if (!HAS_PINNED_R(src)) {
822 *first = *last = NULL;
826 pinned = src->last_with_datap;
827 if (!CHAIN_PINNED_R(*pinned))
828 pinned = &(*pinned)->next;
829 EVUTIL_ASSERT(CHAIN_PINNED_R(*pinned));
830 chain = *first = *pinned;
833 /* If there's data in the first pinned chain, we need to allocate
834 * a new chain and copy the data over. */
836 struct evbuffer_chain *tmp;
838 EVUTIL_ASSERT(pinned == src->last_with_datap);
839 tmp = evbuffer_chain_new(chain->off);
842 memcpy(tmp->buffer, chain->buffer + chain->misalign,
844 tmp->off = chain->off;
845 *src->last_with_datap = tmp;
847 chain->misalign += chain->off;
850 src->last = *src->last_with_datap;
858 RESTORE_PINNED(struct evbuffer *src, struct evbuffer_chain *pinned,
859 struct evbuffer_chain *last)
861 ASSERT_EVBUFFER_LOCKED(src);
870 src->last_with_datap = &src->first;
875 COPY_CHAIN(struct evbuffer *dst, struct evbuffer *src)
877 ASSERT_EVBUFFER_LOCKED(dst);
878 ASSERT_EVBUFFER_LOCKED(src);
879 dst->first = src->first;
880 if (src->last_with_datap == &src->first)
881 dst->last_with_datap = &dst->first;
883 dst->last_with_datap = src->last_with_datap;
884 dst->last = src->last;
885 dst->total_len = src->total_len;
889 APPEND_CHAIN(struct evbuffer *dst, struct evbuffer *src)
891 struct evbuffer_chain **chp;
893 ASSERT_EVBUFFER_LOCKED(dst);
894 ASSERT_EVBUFFER_LOCKED(src);
896 chp = evbuffer_free_trailing_empty_chains(dst);
899 if (src->last_with_datap == &src->first)
900 dst->last_with_datap = chp;
902 dst->last_with_datap = src->last_with_datap;
903 dst->last = src->last;
904 dst->total_len += src->total_len;
908 APPEND_CHAIN_MULTICAST(struct evbuffer *dst, struct evbuffer *src)
910 struct evbuffer_chain *tmp;
911 struct evbuffer_chain *chain = src->first;
912 struct evbuffer_multicast_parent *extra;
914 ASSERT_EVBUFFER_LOCKED(dst);
915 ASSERT_EVBUFFER_LOCKED(src);
917 for (; chain; chain = chain->next) {
918 if (!chain->off || chain->flags & EVBUFFER_DANGLING) {
919 /* skip empty chains */
923 tmp = evbuffer_chain_new(sizeof(struct evbuffer_multicast_parent));
925 event_warn("%s: out of memory", __func__);
928 extra = EVBUFFER_CHAIN_EXTRA(struct evbuffer_multicast_parent, tmp);
929 /* reference evbuffer containing source chain so it
930 * doesn't get released while the chain is still
931 * being referenced to */
932 evbuffer_incref_(src);
934 /* reference source chain which now becomes immutable */
935 evbuffer_chain_incref(chain);
936 extra->parent = chain;
937 chain->flags |= EVBUFFER_IMMUTABLE;
938 tmp->buffer_len = chain->buffer_len;
939 tmp->misalign = chain->misalign;
940 tmp->off = chain->off;
941 tmp->flags |= EVBUFFER_MULTICAST|EVBUFFER_IMMUTABLE;
942 tmp->buffer = chain->buffer;
943 evbuffer_chain_insert(dst, tmp);
948 PREPEND_CHAIN(struct evbuffer *dst, struct evbuffer *src)
950 ASSERT_EVBUFFER_LOCKED(dst);
951 ASSERT_EVBUFFER_LOCKED(src);
952 src->last->next = dst->first;
953 dst->first = src->first;
954 dst->total_len += src->total_len;
955 if (*dst->last_with_datap == NULL) {
956 if (src->last_with_datap == &(src)->first)
957 dst->last_with_datap = &dst->first;
959 dst->last_with_datap = src->last_with_datap;
960 } else if (dst->last_with_datap == &dst->first) {
961 dst->last_with_datap = &src->last->next;
966 evbuffer_add_buffer(struct evbuffer *outbuf, struct evbuffer *inbuf)
968 struct evbuffer_chain *pinned, *last;
969 size_t in_total_len, out_total_len;
972 EVBUFFER_LOCK2(inbuf, outbuf);
973 in_total_len = inbuf->total_len;
974 out_total_len = outbuf->total_len;
976 if (in_total_len == 0 || outbuf == inbuf)
979 if (outbuf->freeze_end || inbuf->freeze_start) {
984 if (PRESERVE_PINNED(inbuf, &pinned, &last) < 0) {
989 if (out_total_len == 0) {
990 /* There might be an empty chain at the start of outbuf; free
992 evbuffer_free_all_chains(outbuf->first);
993 COPY_CHAIN(outbuf, inbuf);
995 APPEND_CHAIN(outbuf, inbuf);
998 RESTORE_PINNED(inbuf, pinned, last);
1000 inbuf->n_del_for_cb += in_total_len;
1001 outbuf->n_add_for_cb += in_total_len;
1003 evbuffer_invoke_callbacks_(inbuf);
1004 evbuffer_invoke_callbacks_(outbuf);
1007 EVBUFFER_UNLOCK2(inbuf, outbuf);
1012 evbuffer_add_buffer_reference(struct evbuffer *outbuf, struct evbuffer *inbuf)
1014 size_t in_total_len, out_total_len;
1015 struct evbuffer_chain *chain;
1018 EVBUFFER_LOCK2(inbuf, outbuf);
1019 in_total_len = inbuf->total_len;
1020 out_total_len = outbuf->total_len;
1021 chain = inbuf->first;
1023 if (in_total_len == 0)
1026 if (outbuf->freeze_end || outbuf == inbuf) {
1031 for (; chain; chain = chain->next) {
1032 if ((chain->flags & (EVBUFFER_FILESEGMENT|EVBUFFER_SENDFILE|EVBUFFER_MULTICAST)) != 0) {
1033 /* chain type can not be referenced */
1039 if (out_total_len == 0) {
1040 /* There might be an empty chain at the start of outbuf; free
1042 evbuffer_free_all_chains(outbuf->first);
1044 APPEND_CHAIN_MULTICAST(outbuf, inbuf);
1046 outbuf->n_add_for_cb += in_total_len;
1047 evbuffer_invoke_callbacks_(outbuf);
1050 EVBUFFER_UNLOCK2(inbuf, outbuf);
1055 evbuffer_prepend_buffer(struct evbuffer *outbuf, struct evbuffer *inbuf)
1057 struct evbuffer_chain *pinned, *last;
1058 size_t in_total_len, out_total_len;
1061 EVBUFFER_LOCK2(inbuf, outbuf);
1063 in_total_len = inbuf->total_len;
1064 out_total_len = outbuf->total_len;
1066 if (!in_total_len || inbuf == outbuf)
1069 if (outbuf->freeze_start || inbuf->freeze_start) {
1074 if (PRESERVE_PINNED(inbuf, &pinned, &last) < 0) {
1079 if (out_total_len == 0) {
1080 /* There might be an empty chain at the start of outbuf; free
1082 evbuffer_free_all_chains(outbuf->first);
1083 COPY_CHAIN(outbuf, inbuf);
1085 PREPEND_CHAIN(outbuf, inbuf);
1088 RESTORE_PINNED(inbuf, pinned, last);
1090 inbuf->n_del_for_cb += in_total_len;
1091 outbuf->n_add_for_cb += in_total_len;
1093 evbuffer_invoke_callbacks_(inbuf);
1094 evbuffer_invoke_callbacks_(outbuf);
1096 EVBUFFER_UNLOCK2(inbuf, outbuf);
1101 evbuffer_drain(struct evbuffer *buf, size_t len)
1103 struct evbuffer_chain *chain, *next;
1104 size_t remaining, old_len;
1108 old_len = buf->total_len;
1113 if (buf->freeze_start) {
1118 if (len >= old_len && !HAS_PINNED_R(buf)) {
1120 for (chain = buf->first; chain != NULL; chain = next) {
1122 evbuffer_chain_free(chain);
1130 buf->total_len -= len;
1132 for (chain = buf->first;
1133 remaining >= chain->off;
1136 remaining -= chain->off;
1138 if (chain == *buf->last_with_datap) {
1139 buf->last_with_datap = &buf->first;
1141 if (&chain->next == buf->last_with_datap)
1142 buf->last_with_datap = &buf->first;
1144 if (CHAIN_PINNED_R(chain)) {
1145 EVUTIL_ASSERT(remaining == 0);
1146 chain->misalign += chain->off;
1150 evbuffer_chain_free(chain);
1154 EVUTIL_ASSERT(remaining <= chain->off);
1155 chain->misalign += remaining;
1156 chain->off -= remaining;
1159 buf->n_del_for_cb += len;
1160 /* Tell someone about changes in this buffer */
1161 evbuffer_invoke_callbacks_(buf);
1164 EVBUFFER_UNLOCK(buf);
1168 /* Reads data from an event buffer and drains the bytes read */
1170 evbuffer_remove(struct evbuffer *buf, void *data_out, size_t datlen)
1174 n = evbuffer_copyout_from(buf, NULL, data_out, datlen);
1176 if (evbuffer_drain(buf, n)<0)
1179 EVBUFFER_UNLOCK(buf);
1184 evbuffer_copyout(struct evbuffer *buf, void *data_out, size_t datlen)
1186 return evbuffer_copyout_from(buf, NULL, data_out, datlen);
1190 evbuffer_copyout_from(struct evbuffer *buf, const struct evbuffer_ptr *pos,
1191 void *data_out, size_t datlen)
1193 /*XXX fails badly on sendfile case. */
1194 struct evbuffer_chain *chain;
1195 char *data = data_out;
1197 ev_ssize_t result = 0;
1198 size_t pos_in_chain;
1203 if (datlen > (size_t)(EV_SSIZE_MAX - pos->pos)) {
1207 chain = pos->internal_.chain;
1208 pos_in_chain = pos->internal_.pos_in_chain;
1209 if (datlen + pos->pos > buf->total_len)
1210 datlen = buf->total_len - pos->pos;
1214 if (datlen > buf->total_len)
1215 datlen = buf->total_len;
1222 if (buf->freeze_start) {
1229 while (datlen && datlen >= chain->off - pos_in_chain) {
1230 size_t copylen = chain->off - pos_in_chain;
1232 chain->buffer + chain->misalign + pos_in_chain,
1237 chain = chain->next;
1239 EVUTIL_ASSERT(chain || datlen==0);
1243 EVUTIL_ASSERT(chain);
1244 EVUTIL_ASSERT(datlen+pos_in_chain <= chain->off);
1246 memcpy(data, chain->buffer + chain->misalign + pos_in_chain,
1252 EVBUFFER_UNLOCK(buf);
1256 /* reads data from the src buffer to the dst buffer, avoids memcpy as
1258 /* XXXX should return ev_ssize_t */
1260 evbuffer_remove_buffer(struct evbuffer *src, struct evbuffer *dst,
1263 /*XXX We should have an option to force this to be zero-copy.*/
1265 /*XXX can fail badly on sendfile case. */
1266 struct evbuffer_chain *chain, *previous;
1270 EVBUFFER_LOCK2(src, dst);
1272 chain = previous = src->first;
1274 if (datlen == 0 || dst == src) {
1279 if (dst->freeze_end || src->freeze_start) {
1284 /* short-cut if there is no more data buffered */
1285 if (datlen >= src->total_len) {
1286 datlen = src->total_len;
1287 evbuffer_add_buffer(dst, src);
1288 result = (int)datlen; /*XXXX should return ev_ssize_t*/
1292 /* removes chains if possible */
1293 while (chain->off <= datlen) {
1294 /* We can't remove the last with data from src unless we
1295 * remove all chains, in which case we would have done the if
1297 EVUTIL_ASSERT(chain != *src->last_with_datap);
1298 nread += chain->off;
1299 datlen -= chain->off;
1301 if (src->last_with_datap == &chain->next)
1302 src->last_with_datap = &src->first;
1303 chain = chain->next;
1306 if (chain != src->first) {
1307 /* we can remove the chain */
1308 struct evbuffer_chain **chp;
1309 chp = evbuffer_free_trailing_empty_chains(dst);
1311 if (dst->first == NULL) {
1312 dst->first = src->first;
1316 dst->last = previous;
1317 previous->next = NULL;
1319 advance_last_with_data(dst);
1321 dst->total_len += nread;
1322 dst->n_add_for_cb += nread;
1325 /* we know that there is more data in the src buffer than
1326 * we want to read, so we manually drain the chain */
1327 evbuffer_add(dst, chain->buffer + chain->misalign, datlen);
1328 chain->misalign += datlen;
1329 chain->off -= datlen;
1332 /* You might think we would want to increment dst->n_add_for_cb
1333 * here too. But evbuffer_add above already took care of that.
1335 src->total_len -= nread;
1336 src->n_del_for_cb += nread;
1339 evbuffer_invoke_callbacks_(dst);
1340 evbuffer_invoke_callbacks_(src);
1342 result = (int)nread;/*XXXX should change return type */
1345 EVBUFFER_UNLOCK2(src, dst);
1350 evbuffer_pullup(struct evbuffer *buf, ev_ssize_t size)
1352 struct evbuffer_chain *chain, *next, *tmp, *last_with_data;
1353 unsigned char *buffer, *result = NULL;
1354 ev_ssize_t remaining;
1355 int removed_last_with_data = 0;
1356 int removed_last_with_datap = 0;
1363 size = buf->total_len;
1364 /* if size > buf->total_len, we cannot guarantee to the user that she
1365 * is going to have a long enough buffer afterwards; so we return
1367 if (size == 0 || (size_t)size > buf->total_len)
1370 /* No need to pull up anything; the first size bytes are
1372 if (chain->off >= (size_t)size) {
1373 result = chain->buffer + chain->misalign;
1377 /* Make sure that none of the chains we need to copy from is pinned. */
1378 remaining = size - chain->off;
1379 EVUTIL_ASSERT(remaining >= 0);
1380 for (tmp=chain->next; tmp; tmp=tmp->next) {
1381 if (CHAIN_PINNED(tmp))
1383 if (tmp->off >= (size_t)remaining)
1385 remaining -= tmp->off;
1388 if (CHAIN_PINNED(chain)) {
1389 size_t old_off = chain->off;
1390 if (CHAIN_SPACE_LEN(chain) < size - chain->off) {
1391 /* not enough room at end of chunk. */
1394 buffer = CHAIN_SPACE_PTR(chain);
1398 chain = chain->next;
1399 } else if (chain->buffer_len - chain->misalign >= (size_t)size) {
1400 /* already have enough space in the first chain */
1401 size_t old_off = chain->off;
1402 buffer = chain->buffer + chain->misalign + chain->off;
1406 chain = chain->next;
1408 if ((tmp = evbuffer_chain_new(size)) == NULL) {
1409 event_warn("%s: out of memory", __func__);
1412 buffer = tmp->buffer;
1417 /* TODO(niels): deal with buffers that point to NULL like sendfile */
1419 /* Copy and free every chunk that will be entirely pulled into tmp */
1420 last_with_data = *buf->last_with_datap;
1421 for (; chain != NULL && (size_t)size >= chain->off; chain = next) {
1424 memcpy(buffer, chain->buffer + chain->misalign, chain->off);
1426 buffer += chain->off;
1427 if (chain == last_with_data)
1428 removed_last_with_data = 1;
1429 if (&chain->next == buf->last_with_datap)
1430 removed_last_with_datap = 1;
1432 evbuffer_chain_free(chain);
1435 if (chain != NULL) {
1436 memcpy(buffer, chain->buffer + chain->misalign, size);
1437 chain->misalign += size;
1445 if (removed_last_with_data) {
1446 buf->last_with_datap = &buf->first;
1447 } else if (removed_last_with_datap) {
1448 if (buf->first->next && buf->first->next->off)
1449 buf->last_with_datap = &buf->first->next;
1451 buf->last_with_datap = &buf->first;
1454 result = (tmp->buffer + tmp->misalign);
1457 EVBUFFER_UNLOCK(buf);
1462 * Reads a line terminated by either '\r\n', '\n\r' or '\r' or '\n'.
1463 * The returned buffer needs to be freed by the called.
1466 evbuffer_readline(struct evbuffer *buffer)
1468 return evbuffer_readln(buffer, NULL, EVBUFFER_EOL_ANY);
1471 static inline ev_ssize_t
1472 evbuffer_strchr(struct evbuffer_ptr *it, const char chr)
1474 struct evbuffer_chain *chain = it->internal_.chain;
1475 size_t i = it->internal_.pos_in_chain;
1476 while (chain != NULL) {
1477 char *buffer = (char *)chain->buffer + chain->misalign;
1478 char *cp = memchr(buffer+i, chr, chain->off-i);
1480 it->internal_.chain = chain;
1481 it->internal_.pos_in_chain = cp - buffer;
1482 it->pos += (cp - buffer - i);
1485 it->pos += chain->off - i;
1487 chain = chain->next;
1493 static inline char *
1494 find_eol_char(char *s, size_t len)
1496 #define CHUNK_SZ 128
1497 /* Lots of benchmarking found this approach to be faster in practice
1498 * than doing two memchrs over the whole buffer, doin a memchr on each
1499 * char of the buffer, or trying to emulate memchr by hand. */
1500 char *s_end, *cr, *lf;
1503 size_t chunk = (s + CHUNK_SZ < s_end) ? CHUNK_SZ : (s_end - s);
1504 cr = memchr(s, '\r', chunk);
1505 lf = memchr(s, '\n', chunk);
1521 evbuffer_find_eol_char(struct evbuffer_ptr *it)
1523 struct evbuffer_chain *chain = it->internal_.chain;
1524 size_t i = it->internal_.pos_in_chain;
1525 while (chain != NULL) {
1526 char *buffer = (char *)chain->buffer + chain->misalign;
1527 char *cp = find_eol_char(buffer+i, chain->off-i);
1529 it->internal_.chain = chain;
1530 it->internal_.pos_in_chain = cp - buffer;
1531 it->pos += (cp - buffer) - i;
1534 it->pos += chain->off - i;
1536 chain = chain->next;
1542 static inline size_t
1544 struct evbuffer_ptr *ptr, const char *chrset)
1547 struct evbuffer_chain *chain = ptr->internal_.chain;
1548 size_t i = ptr->internal_.pos_in_chain;
1554 char *buffer = (char *)chain->buffer + chain->misalign;
1555 for (; i < chain->off; ++i) {
1556 const char *p = chrset;
1558 if (buffer[i] == *p++)
1561 ptr->internal_.chain = chain;
1562 ptr->internal_.pos_in_chain = i;
1570 if (! chain->next) {
1571 ptr->internal_.chain = chain;
1572 ptr->internal_.pos_in_chain = i;
1577 chain = chain->next;
1583 evbuffer_getchr(struct evbuffer_ptr *it)
1585 struct evbuffer_chain *chain = it->internal_.chain;
1586 size_t off = it->internal_.pos_in_chain;
1591 return (unsigned char)chain->buffer[chain->misalign + off];
1595 evbuffer_search_eol(struct evbuffer *buffer,
1596 struct evbuffer_ptr *start, size_t *eol_len_out,
1597 enum evbuffer_eol_style eol_style)
1599 struct evbuffer_ptr it, it2;
1600 size_t extra_drain = 0;
1603 /* Avoid locking in trivial edge cases */
1604 if (start && start->internal_.chain == NULL) {
1607 *eol_len_out = extra_drain;
1611 EVBUFFER_LOCK(buffer);
1614 memcpy(&it, start, sizeof(it));
1617 it.internal_.chain = buffer->first;
1618 it.internal_.pos_in_chain = 0;
1621 /* the eol_style determines our first stop character and how many
1622 * characters we are going to drain afterwards. */
1623 switch (eol_style) {
1624 case EVBUFFER_EOL_ANY:
1625 if (evbuffer_find_eol_char(&it) < 0)
1627 memcpy(&it2, &it, sizeof(it));
1628 extra_drain = evbuffer_strspn(&it2, "\r\n");
1630 case EVBUFFER_EOL_CRLF_STRICT: {
1631 it = evbuffer_search(buffer, "\r\n", 2, &it);
1637 case EVBUFFER_EOL_CRLF: {
1638 ev_ssize_t start_pos = it.pos;
1639 /* Look for a LF ... */
1640 if (evbuffer_strchr(&it, '\n') < 0)
1643 /* ... optionally preceeded by a CR. */
1644 if (it.pos == start_pos)
1645 break; /* If the first character is \n, don't back up */
1646 /* This potentially does an extra linear walk over the first
1647 * few chains. Probably, that's not too expensive unless you
1648 * have a really pathological setup. */
1649 memcpy(&it2, &it, sizeof(it));
1650 if (evbuffer_ptr_subtract(buffer, &it2, 1)<0)
1652 if (evbuffer_getchr(&it2) == '\r') {
1653 memcpy(&it, &it2, sizeof(it));
1658 case EVBUFFER_EOL_LF:
1659 if (evbuffer_strchr(&it, '\n') < 0)
1663 case EVBUFFER_EOL_NUL:
1664 if (evbuffer_strchr(&it, '\0') < 0)
1674 EVBUFFER_UNLOCK(buffer);
1679 *eol_len_out = extra_drain;
1685 evbuffer_readln(struct evbuffer *buffer, size_t *n_read_out,
1686 enum evbuffer_eol_style eol_style)
1688 struct evbuffer_ptr it;
1690 size_t n_to_copy=0, extra_drain=0;
1691 char *result = NULL;
1693 EVBUFFER_LOCK(buffer);
1695 if (buffer->freeze_start) {
1699 it = evbuffer_search_eol(buffer, NULL, &extra_drain, eol_style);
1704 if ((line = mm_malloc(n_to_copy+1)) == NULL) {
1705 event_warn("%s: out of memory", __func__);
1709 evbuffer_remove(buffer, line, n_to_copy);
1710 line[n_to_copy] = '\0';
1712 evbuffer_drain(buffer, extra_drain);
1715 EVBUFFER_UNLOCK(buffer);
1718 *n_read_out = result ? n_to_copy : 0;
1723 #define EVBUFFER_CHAIN_MAX_AUTO_SIZE 4096
1725 /* Adds data to an event buffer */
1728 evbuffer_add(struct evbuffer *buf, const void *data_in, size_t datlen)
1730 struct evbuffer_chain *chain, *tmp;
1731 const unsigned char *data = data_in;
1732 size_t remain, to_alloc;
1737 if (buf->freeze_end) {
1740 /* Prevent buf->total_len overflow */
1741 if (datlen > EV_SIZE_MAX - buf->total_len) {
1745 if (*buf->last_with_datap == NULL) {
1748 chain = *buf->last_with_datap;
1751 /* If there are no chains allocated for this buffer, allocate one
1752 * big enough to hold all the data. */
1753 if (chain == NULL) {
1754 chain = evbuffer_chain_new(datlen);
1757 evbuffer_chain_insert(buf, chain);
1760 if ((chain->flags & EVBUFFER_IMMUTABLE) == 0) {
1761 /* Always true for mutable buffers */
1762 EVUTIL_ASSERT(chain->misalign >= 0 &&
1763 (ev_uint64_t)chain->misalign <= EVBUFFER_CHAIN_MAX);
1764 remain = chain->buffer_len - (size_t)chain->misalign - chain->off;
1765 if (remain >= datlen) {
1766 /* there's enough space to hold all the data in the
1767 * current last chain */
1768 memcpy(chain->buffer + chain->misalign + chain->off,
1770 chain->off += datlen;
1771 buf->total_len += datlen;
1772 buf->n_add_for_cb += datlen;
1774 } else if (!CHAIN_PINNED(chain) &&
1775 evbuffer_chain_should_realign(chain, datlen)) {
1776 /* we can fit the data into the misalignment */
1777 evbuffer_chain_align(chain);
1779 memcpy(chain->buffer + chain->off, data, datlen);
1780 chain->off += datlen;
1781 buf->total_len += datlen;
1782 buf->n_add_for_cb += datlen;
1786 /* we cannot write any data to the last chain */
1790 /* we need to add another chain */
1791 to_alloc = chain->buffer_len;
1792 if (to_alloc <= EVBUFFER_CHAIN_MAX_AUTO_SIZE/2)
1794 if (datlen > to_alloc)
1796 tmp = evbuffer_chain_new(to_alloc);
1801 memcpy(chain->buffer + chain->misalign + chain->off,
1803 chain->off += remain;
1804 buf->total_len += remain;
1805 buf->n_add_for_cb += remain;
1811 memcpy(tmp->buffer, data, datlen);
1813 evbuffer_chain_insert(buf, tmp);
1814 buf->n_add_for_cb += datlen;
1817 evbuffer_invoke_callbacks_(buf);
1820 EVBUFFER_UNLOCK(buf);
1825 evbuffer_prepend(struct evbuffer *buf, const void *data, size_t datlen)
1827 struct evbuffer_chain *chain, *tmp;
1836 if (buf->freeze_start) {
1839 if (datlen > EV_SIZE_MAX - buf->total_len) {
1845 if (chain == NULL) {
1846 chain = evbuffer_chain_new(datlen);
1849 evbuffer_chain_insert(buf, chain);
1852 /* we cannot touch immutable buffers */
1853 if ((chain->flags & EVBUFFER_IMMUTABLE) == 0) {
1854 /* Always true for mutable buffers */
1855 EVUTIL_ASSERT(chain->misalign >= 0 &&
1856 (ev_uint64_t)chain->misalign <= EVBUFFER_CHAIN_MAX);
1858 /* If this chain is empty, we can treat it as
1859 * 'empty at the beginning' rather than 'empty at the end' */
1860 if (chain->off == 0)
1861 chain->misalign = chain->buffer_len;
1863 if ((size_t)chain->misalign >= datlen) {
1864 /* we have enough space to fit everything */
1865 memcpy(chain->buffer + chain->misalign - datlen,
1867 chain->off += datlen;
1868 chain->misalign -= datlen;
1869 buf->total_len += datlen;
1870 buf->n_add_for_cb += datlen;
1872 } else if (chain->misalign) {
1873 /* we can only fit some of the data. */
1874 memcpy(chain->buffer,
1875 (char*)data + datlen - chain->misalign,
1876 (size_t)chain->misalign);
1877 chain->off += (size_t)chain->misalign;
1878 buf->total_len += (size_t)chain->misalign;
1879 buf->n_add_for_cb += (size_t)chain->misalign;
1880 datlen -= (size_t)chain->misalign;
1881 chain->misalign = 0;
1885 /* we need to add another chain */
1886 if ((tmp = evbuffer_chain_new(datlen)) == NULL)
1889 if (buf->last_with_datap == &buf->first && chain->off)
1890 buf->last_with_datap = &tmp->next;
1895 EVUTIL_ASSERT(datlen <= tmp->buffer_len);
1896 tmp->misalign = tmp->buffer_len - datlen;
1898 memcpy(tmp->buffer + tmp->misalign, data, datlen);
1899 buf->total_len += datlen;
1900 buf->n_add_for_cb += datlen;
1903 evbuffer_invoke_callbacks_(buf);
1906 EVBUFFER_UNLOCK(buf);
1910 /** Helper: realigns the memory in chain->buffer so that misalign is 0. */
1912 evbuffer_chain_align(struct evbuffer_chain *chain)
1914 EVUTIL_ASSERT(!(chain->flags & EVBUFFER_IMMUTABLE));
1915 EVUTIL_ASSERT(!(chain->flags & EVBUFFER_MEM_PINNED_ANY));
1916 memmove(chain->buffer, chain->buffer + chain->misalign, chain->off);
1917 chain->misalign = 0;
1920 #define MAX_TO_COPY_IN_EXPAND 4096
1921 #define MAX_TO_REALIGN_IN_EXPAND 2048
1923 /** Helper: return true iff we should realign chain to fit datalen bytes of
1926 evbuffer_chain_should_realign(struct evbuffer_chain *chain,
1929 return chain->buffer_len - chain->off >= datlen &&
1930 (chain->off < chain->buffer_len / 2) &&
1931 (chain->off <= MAX_TO_REALIGN_IN_EXPAND);
1934 /* Expands the available space in the event buffer to at least datlen, all in
1935 * a single chunk. Return that chunk. */
1936 static struct evbuffer_chain *
1937 evbuffer_expand_singlechain(struct evbuffer *buf, size_t datlen)
1939 struct evbuffer_chain *chain, **chainp;
1940 struct evbuffer_chain *result = NULL;
1941 ASSERT_EVBUFFER_LOCKED(buf);
1943 chainp = buf->last_with_datap;
1945 /* XXX If *chainp is no longer writeable, but has enough space in its
1946 * misalign, this might be a bad idea: we could still use *chainp, not
1947 * (*chainp)->next. */
1948 if (*chainp && CHAIN_SPACE_LEN(*chainp) == 0)
1949 chainp = &(*chainp)->next;
1951 /* 'chain' now points to the first chain with writable space (if any)
1952 * We will either use it, realign it, replace it, or resize it. */
1955 if (chain == NULL ||
1956 (chain->flags & (EVBUFFER_IMMUTABLE|EVBUFFER_MEM_PINNED_ANY))) {
1957 /* We can't use the last_with_data chain at all. Just add a
1958 * new one that's big enough. */
1962 /* If we can fit all the data, then we don't have to do anything */
1963 if (CHAIN_SPACE_LEN(chain) >= datlen) {
1968 /* If the chain is completely empty, just replace it by adding a new
1970 if (chain->off == 0) {
1974 /* If the misalignment plus the remaining space fulfills our data
1975 * needs, we could just force an alignment to happen. Afterwards, we
1976 * have enough space. But only do this if we're saving a lot of space
1977 * and not moving too much data. Otherwise the space savings are
1978 * probably offset by the time lost in copying.
1980 if (evbuffer_chain_should_realign(chain, datlen)) {
1981 evbuffer_chain_align(chain);
1986 /* At this point, we can either resize the last chunk with space in
1987 * it, use the next chunk after it, or If we add a new chunk, we waste
1988 * CHAIN_SPACE_LEN(chain) bytes in the former last chunk. If we
1989 * resize, we have to copy chain->off bytes.
1992 /* Would expanding this chunk be affordable and worthwhile? */
1993 if (CHAIN_SPACE_LEN(chain) < chain->buffer_len / 8 ||
1994 chain->off > MAX_TO_COPY_IN_EXPAND ||
1995 datlen >= (EVBUFFER_CHAIN_MAX - chain->off)) {
1996 /* It's not worth resizing this chain. Can the next one be
1998 if (chain->next && CHAIN_SPACE_LEN(chain->next) >= datlen) {
1999 /* Yes, we can just use the next chain (which should
2001 result = chain->next;
2004 /* No; append a new chain (which will free all
2005 * terminal empty chains.) */
2009 /* Okay, we're going to try to resize this chain: Not doing so
2010 * would waste at least 1/8 of its current allocation, and we
2011 * can do so without having to copy more than
2012 * MAX_TO_COPY_IN_EXPAND bytes. */
2013 /* figure out how much space we need */
2014 size_t length = chain->off + datlen;
2015 struct evbuffer_chain *tmp = evbuffer_chain_new(length);
2019 /* copy the data over that we had so far */
2020 tmp->off = chain->off;
2021 memcpy(tmp->buffer, chain->buffer + chain->misalign,
2023 /* fix up the list */
2024 EVUTIL_ASSERT(*chainp == chain);
2025 result = *chainp = tmp;
2027 if (buf->last == chain)
2030 tmp->next = chain->next;
2031 evbuffer_chain_free(chain);
2036 result = evbuffer_chain_insert_new(buf, datlen);
2040 EVUTIL_ASSERT(result);
2041 EVUTIL_ASSERT(CHAIN_SPACE_LEN(result) >= datlen);
2046 /* Make sure that datlen bytes are available for writing in the last n
2047 * chains. Never copies or moves data. */
2049 evbuffer_expand_fast_(struct evbuffer *buf, size_t datlen, int n)
2051 struct evbuffer_chain *chain = buf->last, *tmp, *next;
2055 ASSERT_EVBUFFER_LOCKED(buf);
2056 EVUTIL_ASSERT(n >= 2);
2058 if (chain == NULL || (chain->flags & EVBUFFER_IMMUTABLE)) {
2059 /* There is no last chunk, or we can't touch the last chunk.
2060 * Just add a new chunk. */
2061 chain = evbuffer_chain_new(datlen);
2065 evbuffer_chain_insert(buf, chain);
2069 used = 0; /* number of chains we're using space in. */
2070 avail = 0; /* how much space they have. */
2071 /* How many bytes can we stick at the end of buffer as it is? Iterate
2072 * over the chains at the end of the buffer, tring to see how much
2073 * space we have in the first n. */
2074 for (chain = *buf->last_with_datap; chain; chain = chain->next) {
2076 size_t space = (size_t) CHAIN_SPACE_LEN(chain);
2077 EVUTIL_ASSERT(chain == *buf->last_with_datap);
2083 /* No data in chain; realign it. */
2084 chain->misalign = 0;
2085 avail += chain->buffer_len;
2088 if (avail >= datlen) {
2089 /* There is already enough space. Just return */
2096 /* There wasn't enough space in the first n chains with space in
2097 * them. Either add a new chain with enough space, or replace all
2098 * empty chains with one that has enough space, depending on n. */
2100 /* The loop ran off the end of the chains before it hit n
2101 * chains; we can add another. */
2102 EVUTIL_ASSERT(chain == NULL);
2104 tmp = evbuffer_chain_new(datlen - avail);
2108 buf->last->next = tmp;
2110 /* (we would only set last_with_data if we added the first
2111 * chain. But if the buffer had no chains, we would have
2112 * just allocated a new chain earlier) */
2115 /* Nuke _all_ the empty chains. */
2116 int rmv_all = 0; /* True iff we removed last_with_data. */
2117 chain = *buf->last_with_datap;
2119 EVUTIL_ASSERT(chain == buf->first);
2123 /* can't overflow, since only mutable chains have
2124 * huge misaligns. */
2125 avail = (size_t) CHAIN_SPACE_LEN(chain);
2126 chain = chain->next;
2130 for (; chain; chain = next) {
2132 EVUTIL_ASSERT(chain->off == 0);
2133 evbuffer_chain_free(chain);
2135 EVUTIL_ASSERT(datlen >= avail);
2136 tmp = evbuffer_chain_new(datlen - avail);
2141 buf->last = *buf->last_with_datap;
2142 (*buf->last_with_datap)->next = NULL;
2148 buf->first = buf->last = tmp;
2149 buf->last_with_datap = &buf->first;
2151 (*buf->last_with_datap)->next = tmp;
2159 evbuffer_expand(struct evbuffer *buf, size_t datlen)
2161 struct evbuffer_chain *chain;
2164 chain = evbuffer_expand_singlechain(buf, datlen);
2165 EVBUFFER_UNLOCK(buf);
2166 return chain ? 0 : -1;
2170 * Reads data from a file descriptor into a buffer.
2173 #if defined(EVENT__HAVE_SYS_UIO_H) || defined(_WIN32)
2174 #define USE_IOVEC_IMPL
2177 #ifdef USE_IOVEC_IMPL
2179 #ifdef EVENT__HAVE_SYS_UIO_H
2180 /* number of iovec we use for writev, fragmentation is going to determine
2181 * how much we end up writing */
2183 #define DEFAULT_WRITE_IOVEC 128
2185 #if defined(UIO_MAXIOV) && UIO_MAXIOV < DEFAULT_WRITE_IOVEC
2186 #define NUM_WRITE_IOVEC UIO_MAXIOV
2187 #elif defined(IOV_MAX) && IOV_MAX < DEFAULT_WRITE_IOVEC
2188 #define NUM_WRITE_IOVEC IOV_MAX
2190 #define NUM_WRITE_IOVEC DEFAULT_WRITE_IOVEC
2193 #define IOV_TYPE struct iovec
2194 #define IOV_PTR_FIELD iov_base
2195 #define IOV_LEN_FIELD iov_len
2196 #define IOV_LEN_TYPE size_t
2198 #define NUM_WRITE_IOVEC 16
2199 #define IOV_TYPE WSABUF
2200 #define IOV_PTR_FIELD buf
2201 #define IOV_LEN_FIELD len
2202 #define IOV_LEN_TYPE unsigned long
2205 #define NUM_READ_IOVEC 4
2207 #define EVBUFFER_MAX_READ 4096
2209 /** Helper function to figure out which space to use for reading data into
2210 an evbuffer. Internal use only.
2212 @param buf The buffer to read into
2213 @param howmuch How much we want to read.
2214 @param vecs An array of two or more iovecs or WSABUFs.
2215 @param n_vecs_avail The length of vecs
2216 @param chainp A pointer to a variable to hold the first chain we're
2218 @param exact Boolean: if true, we do not provide more than 'howmuch'
2219 space in the vectors, even if more space is available.
2220 @return The number of buffers we're using.
2223 evbuffer_read_setup_vecs_(struct evbuffer *buf, ev_ssize_t howmuch,
2224 struct evbuffer_iovec *vecs, int n_vecs_avail,
2225 struct evbuffer_chain ***chainp, int exact)
2227 struct evbuffer_chain *chain;
2228 struct evbuffer_chain **firstchainp;
2231 ASSERT_EVBUFFER_LOCKED(buf);
2237 /* Let firstchain be the first chain with any space on it */
2238 firstchainp = buf->last_with_datap;
2239 EVUTIL_ASSERT(*firstchainp);
2240 if (CHAIN_SPACE_LEN(*firstchainp) == 0) {
2241 firstchainp = &(*firstchainp)->next;
2244 chain = *firstchainp;
2245 EVUTIL_ASSERT(chain);
2246 for (i = 0; i < n_vecs_avail && so_far < (size_t)howmuch; ++i) {
2247 size_t avail = (size_t) CHAIN_SPACE_LEN(chain);
2248 if (avail > (howmuch - so_far) && exact)
2249 avail = howmuch - so_far;
2250 vecs[i].iov_base = (void *)CHAIN_SPACE_PTR(chain);
2251 vecs[i].iov_len = avail;
2253 chain = chain->next;
2256 *chainp = firstchainp;
2261 get_n_bytes_readable_on_socket(evutil_socket_t fd)
2263 #if defined(FIONREAD) && defined(_WIN32)
2264 unsigned long lng = EVBUFFER_MAX_READ;
2265 if (ioctlsocket(fd, FIONREAD, &lng) < 0)
2267 /* Can overflow, but mostly harmlessly. XXXX */
2269 #elif defined(FIONREAD)
2270 int n = EVBUFFER_MAX_READ;
2271 if (ioctl(fd, FIONREAD, &n) < 0)
2275 return EVBUFFER_MAX_READ;
2279 /* TODO(niels): should this function return ev_ssize_t and take ev_ssize_t
2282 evbuffer_read(struct evbuffer *buf, evutil_socket_t fd, int howmuch)
2284 struct evbuffer_chain **chainp;
2288 #ifdef USE_IOVEC_IMPL
2289 int nvecs, i, remaining;
2291 struct evbuffer_chain *chain;
2297 if (buf->freeze_end) {
2302 n = get_n_bytes_readable_on_socket(fd);
2303 if (n <= 0 || n > EVBUFFER_MAX_READ)
2304 n = EVBUFFER_MAX_READ;
2305 if (howmuch < 0 || howmuch > n)
2308 #ifdef USE_IOVEC_IMPL
2309 /* Since we can use iovecs, we're willing to use the last
2310 * NUM_READ_IOVEC chains. */
2311 if (evbuffer_expand_fast_(buf, howmuch, NUM_READ_IOVEC) == -1) {
2315 IOV_TYPE vecs[NUM_READ_IOVEC];
2316 #ifdef EVBUFFER_IOVEC_IS_NATIVE_
2317 nvecs = evbuffer_read_setup_vecs_(buf, howmuch, vecs,
2318 NUM_READ_IOVEC, &chainp, 1);
2320 /* We aren't using the native struct iovec. Therefore,
2322 struct evbuffer_iovec ev_vecs[NUM_READ_IOVEC];
2323 nvecs = evbuffer_read_setup_vecs_(buf, howmuch, ev_vecs, 2,
2326 for (i=0; i < nvecs; ++i)
2327 WSABUF_FROM_EVBUFFER_IOV(&vecs[i], &ev_vecs[i]);
2334 if (WSARecv(fd, vecs, nvecs, &bytesRead, &flags, NULL, NULL)) {
2335 /* The read failed. It might be a close,
2336 * or it might be an error. */
2337 if (WSAGetLastError() == WSAECONNABORTED)
2345 n = readv(fd, vecs, nvecs);
2349 #else /*!USE_IOVEC_IMPL*/
2350 /* If we don't have FIONREAD, we might waste some space here */
2351 /* XXX we _will_ waste some space here if there is any space left
2352 * over on buf->last. */
2353 if ((chain = evbuffer_expand_singlechain(buf, howmuch)) == NULL) {
2358 /* We can append new data at this point */
2359 p = chain->buffer + chain->misalign + chain->off;
2362 n = read(fd, p, howmuch);
2364 n = recv(fd, p, howmuch, 0);
2366 #endif /* USE_IOVEC_IMPL */
2377 #ifdef USE_IOVEC_IMPL
2379 for (i=0; i < nvecs; ++i) {
2380 /* can't overflow, since only mutable chains have
2381 * huge misaligns. */
2382 size_t space = (size_t) CHAIN_SPACE_LEN(*chainp);
2383 /* XXXX This is a kludge that can waste space in perverse
2385 if (space > EVBUFFER_CHAIN_MAX)
2386 space = EVBUFFER_CHAIN_MAX;
2387 if ((ev_ssize_t)space < remaining) {
2388 (*chainp)->off += space;
2389 remaining -= (int)space;
2391 (*chainp)->off += remaining;
2392 buf->last_with_datap = chainp;
2395 chainp = &(*chainp)->next;
2399 advance_last_with_data(buf);
2401 buf->total_len += n;
2402 buf->n_add_for_cb += n;
2404 /* Tell someone about changes in this buffer */
2405 evbuffer_invoke_callbacks_(buf);
2408 EVBUFFER_UNLOCK(buf);
2412 #ifdef USE_IOVEC_IMPL
2414 evbuffer_write_iovec(struct evbuffer *buffer, evutil_socket_t fd,
2417 IOV_TYPE iov[NUM_WRITE_IOVEC];
2418 struct evbuffer_chain *chain = buffer->first;
2424 ASSERT_EVBUFFER_LOCKED(buffer);
2425 /* XXX make this top out at some maximal data length? if the
2426 * buffer has (say) 1MB in it, split over 128 chains, there's
2427 * no way it all gets written in one go. */
2428 while (chain != NULL && i < NUM_WRITE_IOVEC && howmuch) {
2430 /* we cannot write the file info via writev */
2431 if (chain->flags & EVBUFFER_SENDFILE)
2434 iov[i].IOV_PTR_FIELD = (void *) (chain->buffer + chain->misalign);
2435 if ((size_t)howmuch >= chain->off) {
2436 /* XXXcould be problematic when windows supports mmap*/
2437 iov[i++].IOV_LEN_FIELD = (IOV_LEN_TYPE)chain->off;
2438 howmuch -= chain->off;
2440 /* XXXcould be problematic when windows supports mmap*/
2441 iov[i++].IOV_LEN_FIELD = (IOV_LEN_TYPE)howmuch;
2444 chain = chain->next;
2452 if (WSASend(fd, iov, i, &bytesSent, 0, NULL, NULL))
2458 n = writev(fd, iov, i);
2466 evbuffer_write_sendfile(struct evbuffer *buffer, evutil_socket_t dest_fd,
2469 struct evbuffer_chain *chain = buffer->first;
2470 struct evbuffer_chain_file_segment *info =
2471 EVBUFFER_CHAIN_EXTRA(struct evbuffer_chain_file_segment,
2473 const int source_fd = info->segment->fd;
2474 #if defined(SENDFILE_IS_MACOSX) || defined(SENDFILE_IS_FREEBSD)
2476 ev_off_t len = chain->off;
2477 #elif defined(SENDFILE_IS_LINUX) || defined(SENDFILE_IS_SOLARIS)
2479 off_t offset = chain->misalign;
2482 ASSERT_EVBUFFER_LOCKED(buffer);
2484 #if defined(SENDFILE_IS_MACOSX)
2485 res = sendfile(source_fd, dest_fd, chain->misalign, &len, NULL, 0);
2486 if (res == -1 && !EVUTIL_ERR_RW_RETRIABLE(errno))
2490 #elif defined(SENDFILE_IS_FREEBSD)
2491 res = sendfile(source_fd, dest_fd, chain->misalign, chain->off, NULL, &len, 0);
2492 if (res == -1 && !EVUTIL_ERR_RW_RETRIABLE(errno))
2496 #elif defined(SENDFILE_IS_LINUX)
2497 /* TODO(niels): implement splice */
2498 res = sendfile(dest_fd, source_fd, &offset, chain->off);
2499 if (res == -1 && EVUTIL_ERR_RW_RETRIABLE(errno)) {
2500 /* if this is EAGAIN or EINTR return 0; otherwise, -1 */
2504 #elif defined(SENDFILE_IS_SOLARIS)
2506 const off_t offset_orig = offset;
2507 res = sendfile(dest_fd, source_fd, &offset, chain->off);
2508 if (res == -1 && EVUTIL_ERR_RW_RETRIABLE(errno)) {
2509 if (offset - offset_orig)
2510 return offset - offset_orig;
2511 /* if this is EAGAIN or EINTR and no bytes were
2512 * written, return 0 */
2522 evbuffer_write_atmost(struct evbuffer *buffer, evutil_socket_t fd,
2527 EVBUFFER_LOCK(buffer);
2529 if (buffer->freeze_start) {
2533 if (howmuch < 0 || (size_t)howmuch > buffer->total_len)
2534 howmuch = buffer->total_len;
2538 struct evbuffer_chain *chain = buffer->first;
2539 if (chain != NULL && (chain->flags & EVBUFFER_SENDFILE))
2540 n = evbuffer_write_sendfile(buffer, fd, howmuch);
2543 #ifdef USE_IOVEC_IMPL
2544 n = evbuffer_write_iovec(buffer, fd, howmuch);
2545 #elif defined(_WIN32)
2546 /* XXX(nickm) Don't disable this code until we know if
2547 * the WSARecv code above works. */
2548 void *p = evbuffer_pullup(buffer, howmuch);
2549 EVUTIL_ASSERT(p || !howmuch);
2550 n = send(fd, p, howmuch, 0);
2552 void *p = evbuffer_pullup(buffer, howmuch);
2553 EVUTIL_ASSERT(p || !howmuch);
2554 n = write(fd, p, howmuch);
2562 evbuffer_drain(buffer, n);
2565 EVBUFFER_UNLOCK(buffer);
2570 evbuffer_write(struct evbuffer *buffer, evutil_socket_t fd)
2572 return evbuffer_write_atmost(buffer, fd, -1);
2576 evbuffer_find(struct evbuffer *buffer, const unsigned char *what, size_t len)
2578 unsigned char *search;
2579 struct evbuffer_ptr ptr;
2581 EVBUFFER_LOCK(buffer);
2583 ptr = evbuffer_search(buffer, (const char *)what, len, NULL);
2587 search = evbuffer_pullup(buffer, ptr.pos + len);
2591 EVBUFFER_UNLOCK(buffer);
2595 /* Subract <b>howfar</b> from the position of <b>pos</b> within
2596 * <b>buf</b>. Returns 0 on success, -1 on failure.
2598 * This isn't exposed yet, because of potential inefficiency issues.
2599 * Maybe it should be. */
2601 evbuffer_ptr_subtract(struct evbuffer *buf, struct evbuffer_ptr *pos,
2606 if (howfar > (size_t)pos->pos)
2608 if (pos->internal_.chain && howfar <= pos->internal_.pos_in_chain) {
2609 pos->internal_.pos_in_chain -= howfar;
2613 const size_t newpos = pos->pos - howfar;
2614 /* Here's the inefficient part: it walks over the
2615 * chains until we hit newpos. */
2616 return evbuffer_ptr_set(buf, pos, newpos, EVBUFFER_PTR_SET);
2621 evbuffer_ptr_set(struct evbuffer *buf, struct evbuffer_ptr *pos,
2622 size_t position, enum evbuffer_ptr_how how)
2624 size_t left = position;
2625 struct evbuffer_chain *chain = NULL;
2631 case EVBUFFER_PTR_SET:
2633 pos->pos = position;
2636 case EVBUFFER_PTR_ADD:
2637 /* this avoids iterating over all previous chains if
2638 we just want to advance the position */
2639 if (pos->pos < 0 || EV_SIZE_MAX - position < (size_t)pos->pos) {
2640 EVBUFFER_UNLOCK(buf);
2643 chain = pos->internal_.chain;
2644 pos->pos += position;
2645 position = pos->internal_.pos_in_chain;
2649 EVUTIL_ASSERT(EV_SIZE_MAX - left >= position);
2650 while (chain && position + left >= chain->off) {
2651 left -= chain->off - position;
2652 chain = chain->next;
2656 pos->internal_.chain = chain;
2657 pos->internal_.pos_in_chain = position + left;
2658 } else if (left == 0) {
2659 /* The first byte in the (nonexistent) chain after the last chain */
2660 pos->internal_.chain = NULL;
2661 pos->internal_.pos_in_chain = 0;
2667 EVBUFFER_UNLOCK(buf);
2673 Compare the bytes in buf at position pos to the len bytes in mem. Return
2674 less than 0, 0, or greater than 0 as memcmp.
2677 evbuffer_ptr_memcmp(const struct evbuffer *buf, const struct evbuffer_ptr *pos,
2678 const char *mem, size_t len)
2680 struct evbuffer_chain *chain;
2684 ASSERT_EVBUFFER_LOCKED(buf);
2687 EV_SIZE_MAX - len < (size_t)pos->pos ||
2688 pos->pos + len > buf->total_len)
2691 chain = pos->internal_.chain;
2692 position = pos->internal_.pos_in_chain;
2693 while (len && chain) {
2694 size_t n_comparable;
2695 if (len + position > chain->off)
2696 n_comparable = chain->off - position;
2699 r = memcmp(chain->buffer + chain->misalign + position, mem,
2703 mem += n_comparable;
2704 len -= n_comparable;
2706 chain = chain->next;
2713 evbuffer_search(struct evbuffer *buffer, const char *what, size_t len, const struct evbuffer_ptr *start)
2715 return evbuffer_search_range(buffer, what, len, start, NULL);
2719 evbuffer_search_range(struct evbuffer *buffer, const char *what, size_t len, const struct evbuffer_ptr *start, const struct evbuffer_ptr *end)
2721 struct evbuffer_ptr pos;
2722 struct evbuffer_chain *chain, *last_chain = NULL;
2723 const unsigned char *p;
2726 EVBUFFER_LOCK(buffer);
2729 memcpy(&pos, start, sizeof(pos));
2730 chain = pos.internal_.chain;
2733 chain = pos.internal_.chain = buffer->first;
2734 pos.internal_.pos_in_chain = 0;
2738 last_chain = end->internal_.chain;
2740 if (!len || len > EV_SSIZE_MAX)
2746 const unsigned char *start_at =
2747 chain->buffer + chain->misalign +
2748 pos.internal_.pos_in_chain;
2749 p = memchr(start_at, first,
2750 chain->off - pos.internal_.pos_in_chain);
2752 pos.pos += p - start_at;
2753 pos.internal_.pos_in_chain += p - start_at;
2754 if (!evbuffer_ptr_memcmp(buffer, &pos, what, len)) {
2755 if (end && pos.pos + (ev_ssize_t)len > end->pos)
2761 ++pos.internal_.pos_in_chain;
2762 if (pos.internal_.pos_in_chain == chain->off) {
2763 chain = pos.internal_.chain = chain->next;
2764 pos.internal_.pos_in_chain = 0;
2767 if (chain == last_chain)
2769 pos.pos += chain->off - pos.internal_.pos_in_chain;
2770 chain = pos.internal_.chain = chain->next;
2771 pos.internal_.pos_in_chain = 0;
2776 PTR_NOT_FOUND(&pos);
2778 EVBUFFER_UNLOCK(buffer);
2783 evbuffer_peek(struct evbuffer *buffer, ev_ssize_t len,
2784 struct evbuffer_ptr *start_at,
2785 struct evbuffer_iovec *vec, int n_vec)
2787 struct evbuffer_chain *chain;
2789 ev_ssize_t len_so_far = 0;
2791 /* Avoid locking in trivial edge cases */
2792 if (start_at && start_at->internal_.chain == NULL)
2795 EVBUFFER_LOCK(buffer);
2798 chain = start_at->internal_.chain;
2799 len_so_far = chain->off
2800 - start_at->internal_.pos_in_chain;
2803 vec[0].iov_base = (void *)(chain->buffer + chain->misalign
2804 + start_at->internal_.pos_in_chain);
2805 vec[0].iov_len = len_so_far;
2807 chain = chain->next;
2809 chain = buffer->first;
2812 if (n_vec == 0 && len < 0) {
2813 /* If no vectors are provided and they asked for "everything",
2814 * pretend they asked for the actual available amount. */
2815 len = buffer->total_len;
2817 len -= start_at->pos;
2822 if (len >= 0 && len_so_far >= len)
2825 vec[idx].iov_base = (void *)(chain->buffer + chain->misalign);
2826 vec[idx].iov_len = chain->off;
2831 len_so_far += chain->off;
2832 chain = chain->next;
2835 EVBUFFER_UNLOCK(buffer);
2842 evbuffer_add_vprintf(struct evbuffer *buf, const char *fmt, va_list ap)
2846 int sz, result = -1;
2848 struct evbuffer_chain *chain;
2853 if (buf->freeze_end) {
2857 /* make sure that at least some space is available */
2858 if ((chain = evbuffer_expand_singlechain(buf, 64)) == NULL)
2863 size_t used = chain->misalign + chain->off;
2864 buffer = (char *)chain->buffer + chain->misalign + chain->off;
2865 EVUTIL_ASSERT(chain->buffer_len >= used);
2866 space = chain->buffer_len - used;
2868 buffer = (char*) CHAIN_SPACE_PTR(chain);
2869 space = (size_t) CHAIN_SPACE_LEN(chain);
2872 #define va_copy(dst, src) memcpy(&(dst), &(src), sizeof(va_list))
2876 sz = evutil_vsnprintf(buffer, space, fmt, aq);
2882 if (INT_MAX >= EVBUFFER_CHAIN_MAX &&
2883 (size_t)sz >= EVBUFFER_CHAIN_MAX)
2885 if ((size_t)sz < space) {
2887 buf->total_len += sz;
2888 buf->n_add_for_cb += sz;
2890 advance_last_with_data(buf);
2891 evbuffer_invoke_callbacks_(buf);
2895 if ((chain = evbuffer_expand_singlechain(buf, sz + 1)) == NULL)
2901 EVBUFFER_UNLOCK(buf);
2906 evbuffer_add_printf(struct evbuffer *buf, const char *fmt, ...)
2912 res = evbuffer_add_vprintf(buf, fmt, ap);
2919 evbuffer_add_reference(struct evbuffer *outbuf,
2920 const void *data, size_t datlen,
2921 evbuffer_ref_cleanup_cb cleanupfn, void *extra)
2923 struct evbuffer_chain *chain;
2924 struct evbuffer_chain_reference *info;
2927 chain = evbuffer_chain_new(sizeof(struct evbuffer_chain_reference));
2930 chain->flags |= EVBUFFER_REFERENCE | EVBUFFER_IMMUTABLE;
2931 chain->buffer = (unsigned char *)data;
2932 chain->buffer_len = datlen;
2933 chain->off = datlen;
2935 info = EVBUFFER_CHAIN_EXTRA(struct evbuffer_chain_reference, chain);
2936 info->cleanupfn = cleanupfn;
2937 info->extra = extra;
2939 EVBUFFER_LOCK(outbuf);
2940 if (outbuf->freeze_end) {
2941 /* don't call chain_free; we do not want to actually invoke
2942 * the cleanup function */
2946 evbuffer_chain_insert(outbuf, chain);
2947 outbuf->n_add_for_cb += datlen;
2949 evbuffer_invoke_callbacks_(outbuf);
2953 EVBUFFER_UNLOCK(outbuf);
2958 /* TODO(niels): we may want to add to automagically convert to mmap, in
2959 * case evbuffer_remove() or evbuffer_pullup() are being used.
2961 struct evbuffer_file_segment *
2962 evbuffer_file_segment_new(
2963 int fd, ev_off_t offset, ev_off_t length, unsigned flags)
2965 struct evbuffer_file_segment *seg =
2966 mm_calloc(sizeof(struct evbuffer_file_segment), 1);
2972 seg->file_offset = offset;
2973 seg->cleanup_cb = NULL;
2974 seg->cleanup_cb_arg = NULL;
2977 #define lseek _lseeki64
2980 #define fstat _fstat
2988 if (fstat(fd, &st) < 0)
2990 length = st.st_size;
2992 seg->length = length;
2994 if (offset < 0 || length < 0 ||
2995 ((ev_uint64_t)length > EVBUFFER_CHAIN_MAX) ||
2996 (ev_uint64_t)offset > (ev_uint64_t)(EVBUFFER_CHAIN_MAX - length))
2999 #if defined(USE_SENDFILE)
3000 if (!(flags & EVBUF_FS_DISABLE_SENDFILE)) {
3001 seg->can_sendfile = 1;
3006 if (evbuffer_file_segment_materialize(seg)<0)
3009 #if defined(USE_SENDFILE)
3012 if (!(flags & EVBUF_FS_DISABLE_LOCKING)) {
3013 EVTHREAD_ALLOC_LOCK(seg->lock, 0);
3021 #ifdef EVENT__HAVE_MMAP
3026 return sysconf(SC_PAGE_SIZE);
3027 #elif defined(_SC_PAGE_SIZE)
3028 return sysconf(_SC_PAGE_SIZE);
3038 evbuffer_file_segment_materialize(struct evbuffer_file_segment *seg)
3040 const unsigned flags = seg->flags;
3041 const int fd = seg->fd;
3042 const ev_off_t length = seg->length;
3043 const ev_off_t offset = seg->file_offset;
3046 return 0; /* already materialized */
3048 #if defined(EVENT__HAVE_MMAP)
3049 if (!(flags & EVBUF_FS_DISABLE_MMAP)) {
3050 off_t offset_rounded = 0, offset_leftover = 0;
3053 /* mmap implementations don't generally like us
3054 * to have an offset that isn't a round */
3055 long page_size = get_page_size();
3056 if (page_size == -1)
3058 offset_leftover = offset % page_size;
3059 offset_rounded = offset - offset_leftover;
3061 mapped = mmap(NULL, length + offset_leftover,
3064 MAP_NOCACHE | /* ??? */
3070 fd, offset_rounded);
3071 if (mapped == MAP_FAILED) {
3072 event_warn("%s: mmap(%d, %d, %zu) failed",
3073 __func__, fd, 0, (size_t)(offset + length));
3075 seg->mapping = mapped;
3076 seg->contents = (char*)mapped+offset_leftover;
3077 seg->mmap_offset = 0;
3078 seg->is_mapping = 1;
3084 if (!(flags & EVBUF_FS_DISABLE_MMAP)) {
3085 intptr_t h = _get_osfhandle(fd);
3087 ev_uint64_t total_size = length+offset;
3088 if ((HANDLE)h == INVALID_HANDLE_VALUE)
3090 m = CreateFileMapping((HANDLE)h, NULL, PAGE_READONLY,
3091 (total_size >> 32), total_size & 0xfffffffful,
3093 if (m != INVALID_HANDLE_VALUE) { /* Does h leak? */
3094 seg->mapping_handle = m;
3095 seg->mmap_offset = offset;
3096 seg->is_mapping = 1;
3102 ev_off_t start_pos = lseek(fd, 0, SEEK_CUR), pos;
3103 ev_off_t read_so_far = 0;
3107 if (!(mem = mm_malloc(length)))
3109 if (start_pos < 0) {
3113 if (lseek(fd, offset, SEEK_SET) < 0) {
3117 while (read_so_far < length) {
3118 n = read(fd, mem+read_so_far, length-read_so_far);
3125 pos = lseek(fd, start_pos, SEEK_SET);
3126 if (n < 0 || (n == 0 && length > read_so_far)) {
3130 } else if (pos < 0) {
3135 seg->contents = mem;
3144 void evbuffer_file_segment_add_cleanup_cb(struct evbuffer_file_segment *seg,
3145 evbuffer_file_segment_cleanup_cb cb, void* arg)
3147 EVUTIL_ASSERT(seg->refcnt > 0);
3148 seg->cleanup_cb = cb;
3149 seg->cleanup_cb_arg = arg;
3153 evbuffer_file_segment_free(struct evbuffer_file_segment *seg)
3156 EVLOCK_LOCK(seg->lock, 0);
3157 refcnt = --seg->refcnt;
3158 EVLOCK_UNLOCK(seg->lock, 0);
3161 EVUTIL_ASSERT(refcnt == 0);
3163 if (seg->is_mapping) {
3165 CloseHandle(seg->mapping_handle);
3166 #elif defined (EVENT__HAVE_MMAP)
3167 off_t offset_leftover;
3168 offset_leftover = seg->file_offset % get_page_size();
3169 if (munmap(seg->mapping, seg->length + offset_leftover) == -1)
3170 event_warn("%s: munmap failed", __func__);
3172 } else if (seg->contents) {
3173 mm_free(seg->contents);
3176 if ((seg->flags & EVBUF_FS_CLOSE_ON_FREE) && seg->fd >= 0) {
3180 if (seg->cleanup_cb) {
3181 (*seg->cleanup_cb)((struct evbuffer_file_segment const*)seg,
3182 seg->flags, seg->cleanup_cb_arg);
3183 seg->cleanup_cb = NULL;
3184 seg->cleanup_cb_arg = NULL;
3187 EVTHREAD_FREE_LOCK(seg->lock, 0);
3192 evbuffer_add_file_segment(struct evbuffer *buf,
3193 struct evbuffer_file_segment *seg, ev_off_t offset, ev_off_t length)
3195 struct evbuffer_chain *chain;
3196 struct evbuffer_chain_file_segment *extra;
3197 int can_use_sendfile = 0;
3200 EVLOCK_LOCK(seg->lock, 0);
3201 if (buf->flags & EVBUFFER_FLAG_DRAINS_TO_FD) {
3202 can_use_sendfile = 1;
3204 if (!seg->contents) {
3205 if (evbuffer_file_segment_materialize(seg)<0) {
3206 EVLOCK_UNLOCK(seg->lock, 0);
3207 EVBUFFER_UNLOCK(buf);
3213 EVLOCK_UNLOCK(seg->lock, 0);
3215 if (buf->freeze_end)
3219 if (offset > seg->length)
3221 length = seg->length - offset;
3224 /* Can we actually add this? */
3225 if (offset+length > seg->length)
3228 chain = evbuffer_chain_new(sizeof(struct evbuffer_chain_file_segment));
3231 extra = EVBUFFER_CHAIN_EXTRA(struct evbuffer_chain_file_segment, chain);
3233 chain->flags |= EVBUFFER_IMMUTABLE|EVBUFFER_FILESEGMENT;
3234 if (can_use_sendfile && seg->can_sendfile) {
3235 chain->flags |= EVBUFFER_SENDFILE;
3236 chain->misalign = seg->file_offset + offset;
3237 chain->off = length;
3238 chain->buffer_len = chain->misalign + length;
3239 } else if (seg->is_mapping) {
3241 ev_uint64_t total_offset = seg->mmap_offset+offset;
3242 ev_uint64_t offset_rounded=0, offset_remaining=0;
3246 memset(&si, 0, sizeof(si)); /* cargo cult */
3248 offset_remaining = total_offset % si.dwAllocationGranularity;
3249 offset_rounded = total_offset - offset_remaining;
3251 data = MapViewOfFile(
3252 seg->mapping_handle,
3254 offset_rounded >> 32,
3255 offset_rounded & 0xfffffffful,
3256 length + offset_remaining);
3261 chain->buffer = (unsigned char*) data;
3262 chain->buffer_len = length+offset_remaining;
3263 chain->misalign = offset_remaining;
3264 chain->off = length;
3266 chain->buffer = (unsigned char*)(seg->contents + offset);
3267 chain->buffer_len = length;
3268 chain->off = length;
3271 chain->buffer = (unsigned char*)(seg->contents + offset);
3272 chain->buffer_len = length;
3273 chain->off = length;
3276 extra->segment = seg;
3277 buf->n_add_for_cb += length;
3278 evbuffer_chain_insert(buf, chain);
3280 evbuffer_invoke_callbacks_(buf);
3282 EVBUFFER_UNLOCK(buf);
3286 EVBUFFER_UNLOCK(buf);
3287 evbuffer_file_segment_free(seg); /* Lowers the refcount */
3292 evbuffer_add_file(struct evbuffer *buf, int fd, ev_off_t offset, ev_off_t length)
3294 struct evbuffer_file_segment *seg;
3295 unsigned flags = EVBUF_FS_CLOSE_ON_FREE;
3298 seg = evbuffer_file_segment_new(fd, offset, length, flags);
3301 r = evbuffer_add_file_segment(buf, seg, 0, length);
3303 evbuffer_file_segment_free(seg);
3308 evbuffer_setcb(struct evbuffer *buffer, evbuffer_cb cb, void *cbarg)
3310 EVBUFFER_LOCK(buffer);
3312 if (!LIST_EMPTY(&buffer->callbacks))
3313 evbuffer_remove_all_callbacks(buffer);
3316 struct evbuffer_cb_entry *ent =
3317 evbuffer_add_cb(buffer, NULL, cbarg);
3319 EVBUFFER_UNLOCK(buffer);
3322 ent->cb.cb_obsolete = cb;
3323 ent->flags |= EVBUFFER_CB_OBSOLETE;
3325 EVBUFFER_UNLOCK(buffer);
3329 struct evbuffer_cb_entry *
3330 evbuffer_add_cb(struct evbuffer *buffer, evbuffer_cb_func cb, void *cbarg)
3332 struct evbuffer_cb_entry *e;
3333 if (! (e = mm_calloc(1, sizeof(struct evbuffer_cb_entry))))
3335 EVBUFFER_LOCK(buffer);
3338 e->flags = EVBUFFER_CB_ENABLED;
3339 LIST_INSERT_HEAD(&buffer->callbacks, e, next);
3340 EVBUFFER_UNLOCK(buffer);
3345 evbuffer_remove_cb_entry(struct evbuffer *buffer,
3346 struct evbuffer_cb_entry *ent)
3348 EVBUFFER_LOCK(buffer);
3349 LIST_REMOVE(ent, next);
3350 EVBUFFER_UNLOCK(buffer);
3356 evbuffer_remove_cb(struct evbuffer *buffer, evbuffer_cb_func cb, void *cbarg)
3358 struct evbuffer_cb_entry *cbent;
3360 EVBUFFER_LOCK(buffer);
3361 LIST_FOREACH(cbent, &buffer->callbacks, next) {
3362 if (cb == cbent->cb.cb_func && cbarg == cbent->cbarg) {
3363 result = evbuffer_remove_cb_entry(buffer, cbent);
3368 EVBUFFER_UNLOCK(buffer);
3373 evbuffer_cb_set_flags(struct evbuffer *buffer,
3374 struct evbuffer_cb_entry *cb, ev_uint32_t flags)
3376 /* the user isn't allowed to mess with these. */
3377 flags &= ~EVBUFFER_CB_INTERNAL_FLAGS;
3378 EVBUFFER_LOCK(buffer);
3380 EVBUFFER_UNLOCK(buffer);
3385 evbuffer_cb_clear_flags(struct evbuffer *buffer,
3386 struct evbuffer_cb_entry *cb, ev_uint32_t flags)
3388 /* the user isn't allowed to mess with these. */
3389 flags &= ~EVBUFFER_CB_INTERNAL_FLAGS;
3390 EVBUFFER_LOCK(buffer);
3391 cb->flags &= ~flags;
3392 EVBUFFER_UNLOCK(buffer);
3397 evbuffer_freeze(struct evbuffer *buffer, int start)
3399 EVBUFFER_LOCK(buffer);
3401 buffer->freeze_start = 1;
3403 buffer->freeze_end = 1;
3404 EVBUFFER_UNLOCK(buffer);
3409 evbuffer_unfreeze(struct evbuffer *buffer, int start)
3411 EVBUFFER_LOCK(buffer);
3413 buffer->freeze_start = 0;
3415 buffer->freeze_end = 0;
3416 EVBUFFER_UNLOCK(buffer);
3422 evbuffer_cb_suspend(struct evbuffer *buffer, struct evbuffer_cb_entry *cb)
3424 if (!(cb->flags & EVBUFFER_CB_SUSPENDED)) {
3425 cb->size_before_suspend = evbuffer_get_length(buffer);
3426 cb->flags |= EVBUFFER_CB_SUSPENDED;
3431 evbuffer_cb_unsuspend(struct evbuffer *buffer, struct evbuffer_cb_entry *cb)
3433 if ((cb->flags & EVBUFFER_CB_SUSPENDED)) {
3434 unsigned call = (cb->flags & EVBUFFER_CB_CALL_ON_UNSUSPEND);
3435 size_t sz = cb->size_before_suspend;
3436 cb->flags &= ~(EVBUFFER_CB_SUSPENDED|
3437 EVBUFFER_CB_CALL_ON_UNSUSPEND);
3438 cb->size_before_suspend = 0;
3439 if (call && (cb->flags & EVBUFFER_CB_ENABLED)) {
3440 cb->cb(buffer, sz, evbuffer_get_length(buffer), cb->cbarg);
3447 evbuffer_get_callbacks_(struct evbuffer *buffer, struct event_callback **cbs,
3451 EVBUFFER_LOCK(buffer);
3452 if (buffer->deferred_cbs) {
3457 cbs[0] = &buffer->deferred;
3461 EVBUFFER_UNLOCK(buffer);