xref: /libevent-2.1.12/buffer.c (revision a8769ef1)
1 /*
2  * Copyright (c) 2002-2007 Niels Provos <[email protected]>
3  * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. The name of the author may not be used to endorse or promote products
14  *    derived from this software without specific prior written permission.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
17  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
18  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
19  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
20  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
21  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
22  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
23  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
25  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26  */
27 
28 #include "event2/event-config.h"
29 #include "evconfig-private.h"
30 
31 #ifdef _WIN32
32 #include <winsock2.h>
33 #include <windows.h>
34 #include <io.h>
35 #endif
36 
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.
40  */
41 #endif
42 
43 #include <sys/types.h>
44 
45 #ifdef EVENT__HAVE_SYS_TIME_H
46 #include <sys/time.h>
47 #endif
48 
49 #ifdef EVENT__HAVE_SYS_SOCKET_H
50 #include <sys/socket.h>
51 #endif
52 
53 #ifdef EVENT__HAVE_SYS_UIO_H
54 #include <sys/uio.h>
55 #endif
56 
57 #ifdef EVENT__HAVE_SYS_IOCTL_H
58 #include <sys/ioctl.h>
59 #endif
60 
61 #ifdef EVENT__HAVE_SYS_MMAN_H
62 #include <sys/mman.h>
63 #endif
64 
65 #ifdef EVENT__HAVE_SYS_SENDFILE_H
66 #include <sys/sendfile.h>
67 #endif
68 #ifdef EVENT__HAVE_SYS_STAT_H
69 #include <sys/stat.h>
70 #endif
71 
72 
73 #include <errno.h>
74 #include <stdio.h>
75 #include <stdlib.h>
76 #include <string.h>
77 #ifdef EVENT__HAVE_STDARG_H
78 #include <stdarg.h>
79 #endif
80 #ifdef EVENT__HAVE_UNISTD_H
81 #include <unistd.h>
82 #endif
83 #include <limits.h>
84 
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 
99 /* some systems do not have MAP_FAILED */
100 #ifndef MAP_FAILED
101 #define MAP_FAILED	((void *)-1)
102 #endif
103 
104 /* send file support */
105 #if defined(EVENT__HAVE_SYS_SENDFILE_H) && defined(EVENT__HAVE_SENDFILE) && defined(__linux__)
106 #define USE_SENDFILE		1
107 #define SENDFILE_IS_LINUX	1
108 #elif defined(EVENT__HAVE_SENDFILE) && defined(__FreeBSD__)
109 #define USE_SENDFILE		1
110 #define SENDFILE_IS_FREEBSD	1
111 #elif defined(EVENT__HAVE_SENDFILE) && defined(__APPLE__)
112 #define USE_SENDFILE		1
113 #define SENDFILE_IS_MACOSX	1
114 #elif defined(EVENT__HAVE_SENDFILE) && defined(__sun__) && defined(__svr4__)
115 #define USE_SENDFILE		1
116 #define SENDFILE_IS_SOLARIS	1
117 #endif
118 
119 /* Mask of user-selectable callback flags. */
120 #define EVBUFFER_CB_USER_FLAGS	    0xffff
121 /* Mask of all internal-use-only flags. */
122 #define EVBUFFER_CB_INTERNAL_FLAGS  0xffff0000
123 
124 /* Flag set if the callback is using the cb_obsolete function pointer  */
125 #define EVBUFFER_CB_OBSOLETE	       0x00040000
126 
127 /* evbuffer_chain support */
128 #define CHAIN_SPACE_PTR(ch) ((ch)->buffer + (ch)->misalign + (ch)->off)
129 #define CHAIN_SPACE_LEN(ch) ((ch)->flags & EVBUFFER_IMMUTABLE ? \
130 	    0 : (ch)->buffer_len - ((ch)->misalign + (ch)->off))
131 
132 #define CHAIN_PINNED(ch)  (((ch)->flags & EVBUFFER_MEM_PINNED_ANY) != 0)
133 #define CHAIN_PINNED_R(ch)  (((ch)->flags & EVBUFFER_MEM_PINNED_R) != 0)
134 
135 /* evbuffer_ptr support */
136 #define PTR_NOT_FOUND(ptr) do {			\
137 	(ptr)->pos = -1;					\
138 	(ptr)->internal_.chain = NULL;		\
139 	(ptr)->internal_.pos_in_chain = 0;	\
140 } while (0)
141 
142 static void evbuffer_chain_align(struct evbuffer_chain *chain);
143 static int evbuffer_chain_should_realign(struct evbuffer_chain *chain,
144     size_t datalen);
145 static void evbuffer_deferred_callback(struct event_callback *cb, void *arg);
146 static int evbuffer_ptr_memcmp(const struct evbuffer *buf,
147     const struct evbuffer_ptr *pos, const char *mem, size_t len);
148 static struct evbuffer_chain *evbuffer_expand_singlechain(struct evbuffer *buf,
149     size_t datlen);
150 static int evbuffer_ptr_subtract(struct evbuffer *buf, struct evbuffer_ptr *pos,
151     size_t howfar);
152 static int evbuffer_file_segment_materialize(struct evbuffer_file_segment *seg);
153 static inline void evbuffer_chain_incref(struct evbuffer_chain *chain);
154 
155 static struct evbuffer_chain *
156 evbuffer_chain_new(size_t size)
157 {
158 	struct evbuffer_chain *chain;
159 	size_t to_alloc;
160 
161 	if (size > EVBUFFER_CHAIN_MAX - EVBUFFER_CHAIN_SIZE)
162 		return (NULL);
163 
164 	size += EVBUFFER_CHAIN_SIZE;
165 
166 	/* get the next largest memory that can hold the buffer */
167 	if (size < EVBUFFER_CHAIN_MAX / 2) {
168 		to_alloc = MIN_BUFFER_SIZE;
169 		while (to_alloc < size) {
170 			to_alloc <<= 1;
171 		}
172 	} else {
173 		to_alloc = size;
174 	}
175 
176 	/* we get everything in one chunk */
177 	if ((chain = mm_malloc(to_alloc)) == NULL)
178 		return (NULL);
179 
180 	memset(chain, 0, EVBUFFER_CHAIN_SIZE);
181 
182 	chain->buffer_len = to_alloc - EVBUFFER_CHAIN_SIZE;
183 
184 	/* this way we can manipulate the buffer to different addresses,
185 	 * which is required for mmap for example.
186 	 */
187 	chain->buffer = EVBUFFER_CHAIN_EXTRA(unsigned char, chain);
188 
189 	chain->refcnt = 1;
190 
191 	return (chain);
192 }
193 
194 static inline void
195 evbuffer_chain_free(struct evbuffer_chain *chain)
196 {
197 	EVUTIL_ASSERT(chain->refcnt > 0);
198 	if (--chain->refcnt > 0) {
199 		/* chain is still referenced by other chains */
200 		return;
201 	}
202 
203 	if (CHAIN_PINNED(chain)) {
204 		/* will get freed once no longer dangling */
205 		chain->refcnt++;
206 		chain->flags |= EVBUFFER_DANGLING;
207 		return;
208 	}
209 
210 	/* safe to release chain, it's either a referencing
211 	 * chain or all references to it have been freed */
212 	if (chain->flags & EVBUFFER_REFERENCE) {
213 		struct evbuffer_chain_reference *info =
214 		    EVBUFFER_CHAIN_EXTRA(
215 			    struct evbuffer_chain_reference,
216 			    chain);
217 		if (info->cleanupfn)
218 			(*info->cleanupfn)(chain->buffer,
219 			    chain->buffer_len,
220 			    info->extra);
221 	}
222 	if (chain->flags & EVBUFFER_FILESEGMENT) {
223 		struct evbuffer_chain_file_segment *info =
224 		    EVBUFFER_CHAIN_EXTRA(
225 			    struct evbuffer_chain_file_segment,
226 			    chain);
227 		if (info->segment) {
228 #ifdef _WIN32
229 			if (info->segment->is_mapping)
230 				UnmapViewOfFile(chain->buffer);
231 #endif
232 			evbuffer_file_segment_free(info->segment);
233 		}
234 	}
235 	if (chain->flags & EVBUFFER_MULTICAST) {
236 		struct evbuffer_multicast_parent *info =
237 		    EVBUFFER_CHAIN_EXTRA(
238 			    struct evbuffer_multicast_parent,
239 			    chain);
240 		/* referencing chain is being freed, decrease
241 		 * refcounts of source chain and associated
242 		 * evbuffer (which get freed once both reach
243 		 * zero) */
244 		EVUTIL_ASSERT(info->source != NULL);
245 		EVUTIL_ASSERT(info->parent != NULL);
246 		EVBUFFER_LOCK(info->source);
247 		evbuffer_chain_free(info->parent);
248 		evbuffer_decref_and_unlock_(info->source);
249 	}
250 
251 	mm_free(chain);
252 }
253 
254 static void
255 evbuffer_free_all_chains(struct evbuffer_chain *chain)
256 {
257 	struct evbuffer_chain *next;
258 	for (; chain; chain = next) {
259 		next = chain->next;
260 		evbuffer_chain_free(chain);
261 	}
262 }
263 
264 #ifndef NDEBUG
265 static int
266 evbuffer_chains_all_empty(struct evbuffer_chain *chain)
267 {
268 	for (; chain; chain = chain->next) {
269 		if (chain->off)
270 			return 0;
271 	}
272 	return 1;
273 }
274 #else
275 /* The definition is needed for EVUTIL_ASSERT, which uses sizeof to avoid
276 "unused variable" warnings. */
277 static inline int evbuffer_chains_all_empty(struct evbuffer_chain *chain) {
278 	return 1;
279 }
280 #endif
281 
282 /* Free all trailing chains in 'buf' that are neither pinned nor empty, prior
283  * to replacing them all with a new chain.  Return a pointer to the place
284  * where the new chain will go.
285  *
286  * Internal; requires lock.  The caller must fix up buf->last and buf->first
287  * as needed; they might have been freed.
288  */
289 static struct evbuffer_chain **
290 evbuffer_free_trailing_empty_chains(struct evbuffer *buf)
291 {
292 	struct evbuffer_chain **ch = buf->last_with_datap;
293 	/* Find the first victim chain.  It might be *last_with_datap */
294 	while ((*ch) && ((*ch)->off != 0 || CHAIN_PINNED(*ch)))
295 		ch = &(*ch)->next;
296 	if (*ch) {
297 		EVUTIL_ASSERT(evbuffer_chains_all_empty(*ch));
298 		evbuffer_free_all_chains(*ch);
299 		*ch = NULL;
300 	}
301 	return ch;
302 }
303 
304 /* Add a single chain 'chain' to the end of 'buf', freeing trailing empty
305  * chains as necessary.  Requires lock.  Does not schedule callbacks.
306  */
307 static void
308 evbuffer_chain_insert(struct evbuffer *buf,
309     struct evbuffer_chain *chain)
310 {
311 	ASSERT_EVBUFFER_LOCKED(buf);
312 	if (*buf->last_with_datap == NULL) {
313 		/* There are no chains data on the buffer at all. */
314 		EVUTIL_ASSERT(buf->last_with_datap == &buf->first);
315 		EVUTIL_ASSERT(buf->first == NULL);
316 		buf->first = buf->last = chain;
317 	} else {
318 		struct evbuffer_chain **chp;
319 		chp = evbuffer_free_trailing_empty_chains(buf);
320 		*chp = chain;
321 		if (chain->off)
322 			buf->last_with_datap = chp;
323 		buf->last = chain;
324 	}
325 	buf->total_len += chain->off;
326 }
327 
328 static inline struct evbuffer_chain *
329 evbuffer_chain_insert_new(struct evbuffer *buf, size_t datlen)
330 {
331 	struct evbuffer_chain *chain;
332 	if ((chain = evbuffer_chain_new(datlen)) == NULL)
333 		return NULL;
334 	evbuffer_chain_insert(buf, chain);
335 	return chain;
336 }
337 
338 void
339 evbuffer_chain_pin_(struct evbuffer_chain *chain, unsigned flag)
340 {
341 	EVUTIL_ASSERT((chain->flags & flag) == 0);
342 	chain->flags |= flag;
343 }
344 
345 void
346 evbuffer_chain_unpin_(struct evbuffer_chain *chain, unsigned flag)
347 {
348 	EVUTIL_ASSERT((chain->flags & flag) != 0);
349 	chain->flags &= ~flag;
350 	if (chain->flags & EVBUFFER_DANGLING)
351 		evbuffer_chain_free(chain);
352 }
353 
354 static inline void
355 evbuffer_chain_incref(struct evbuffer_chain *chain)
356 {
357     ++chain->refcnt;
358 }
359 
360 struct evbuffer *
361 evbuffer_new(void)
362 {
363 	struct evbuffer *buffer;
364 
365 	buffer = mm_calloc(1, sizeof(struct evbuffer));
366 	if (buffer == NULL)
367 		return (NULL);
368 
369 	LIST_INIT(&buffer->callbacks);
370 	buffer->refcnt = 1;
371 	buffer->last_with_datap = &buffer->first;
372 
373 	return (buffer);
374 }
375 
376 int
377 evbuffer_set_flags(struct evbuffer *buf, ev_uint64_t flags)
378 {
379 	EVBUFFER_LOCK(buf);
380 	buf->flags |= (ev_uint32_t)flags;
381 	EVBUFFER_UNLOCK(buf);
382 	return 0;
383 }
384 
385 int
386 evbuffer_clear_flags(struct evbuffer *buf, ev_uint64_t flags)
387 {
388 	EVBUFFER_LOCK(buf);
389 	buf->flags &= ~(ev_uint32_t)flags;
390 	EVBUFFER_UNLOCK(buf);
391 	return 0;
392 }
393 
394 void
395 evbuffer_incref_(struct evbuffer *buf)
396 {
397 	EVBUFFER_LOCK(buf);
398 	++buf->refcnt;
399 	EVBUFFER_UNLOCK(buf);
400 }
401 
402 void
403 evbuffer_incref_and_lock_(struct evbuffer *buf)
404 {
405 	EVBUFFER_LOCK(buf);
406 	++buf->refcnt;
407 }
408 
409 int
410 evbuffer_defer_callbacks(struct evbuffer *buffer, struct event_base *base)
411 {
412 	EVBUFFER_LOCK(buffer);
413 	buffer->cb_queue = base;
414 	buffer->deferred_cbs = 1;
415 	event_deferred_cb_init_(&buffer->deferred,
416 	    event_base_get_npriorities(base) / 2,
417 	    evbuffer_deferred_callback, buffer);
418 	EVBUFFER_UNLOCK(buffer);
419 	return 0;
420 }
421 
422 int
423 evbuffer_enable_locking(struct evbuffer *buf, void *lock)
424 {
425 #ifdef EVENT__DISABLE_THREAD_SUPPORT
426 	return -1;
427 #else
428 	if (buf->lock)
429 		return -1;
430 
431 	if (!lock) {
432 		EVTHREAD_ALLOC_LOCK(lock, EVTHREAD_LOCKTYPE_RECURSIVE);
433 		if (!lock)
434 			return -1;
435 		buf->lock = lock;
436 		buf->own_lock = 1;
437 	} else {
438 		buf->lock = lock;
439 		buf->own_lock = 0;
440 	}
441 
442 	return 0;
443 #endif
444 }
445 
446 void
447 evbuffer_set_parent_(struct evbuffer *buf, struct bufferevent *bev)
448 {
449 	EVBUFFER_LOCK(buf);
450 	buf->parent = bev;
451 	EVBUFFER_UNLOCK(buf);
452 }
453 
454 static void
455 evbuffer_run_callbacks(struct evbuffer *buffer, int running_deferred)
456 {
457 	struct evbuffer_cb_entry *cbent, *next;
458 	struct evbuffer_cb_info info;
459 	size_t new_size;
460 	ev_uint32_t mask, masked_val;
461 	int clear = 1;
462 
463 	if (running_deferred) {
464 		mask = EVBUFFER_CB_NODEFER|EVBUFFER_CB_ENABLED;
465 		masked_val = EVBUFFER_CB_ENABLED;
466 	} else if (buffer->deferred_cbs) {
467 		mask = EVBUFFER_CB_NODEFER|EVBUFFER_CB_ENABLED;
468 		masked_val = EVBUFFER_CB_NODEFER|EVBUFFER_CB_ENABLED;
469 		/* Don't zero-out n_add/n_del, since the deferred callbacks
470 		   will want to see them. */
471 		clear = 0;
472 	} else {
473 		mask = EVBUFFER_CB_ENABLED;
474 		masked_val = EVBUFFER_CB_ENABLED;
475 	}
476 
477 	ASSERT_EVBUFFER_LOCKED(buffer);
478 
479 	if (LIST_EMPTY(&buffer->callbacks)) {
480 		buffer->n_add_for_cb = buffer->n_del_for_cb = 0;
481 		return;
482 	}
483 	if (buffer->n_add_for_cb == 0 && buffer->n_del_for_cb == 0)
484 		return;
485 
486 	new_size = buffer->total_len;
487 	info.orig_size = new_size + buffer->n_del_for_cb - buffer->n_add_for_cb;
488 	info.n_added = buffer->n_add_for_cb;
489 	info.n_deleted = buffer->n_del_for_cb;
490 	if (clear) {
491 		buffer->n_add_for_cb = 0;
492 		buffer->n_del_for_cb = 0;
493 	}
494 	for (cbent = LIST_FIRST(&buffer->callbacks);
495 	     cbent != LIST_END(&buffer->callbacks);
496 	     cbent = next) {
497 		/* Get the 'next' pointer now in case this callback decides
498 		 * to remove itself or something. */
499 		next = LIST_NEXT(cbent, next);
500 
501 		if ((cbent->flags & mask) != masked_val)
502 			continue;
503 
504 		if ((cbent->flags & EVBUFFER_CB_OBSOLETE))
505 			cbent->cb.cb_obsolete(buffer,
506 			    info.orig_size, new_size, cbent->cbarg);
507 		else
508 			cbent->cb.cb_func(buffer, &info, cbent->cbarg);
509 	}
510 }
511 
512 void
513 evbuffer_invoke_callbacks_(struct evbuffer *buffer)
514 {
515 	if (LIST_EMPTY(&buffer->callbacks)) {
516 		buffer->n_add_for_cb = buffer->n_del_for_cb = 0;
517 		return;
518 	}
519 
520 	if (buffer->deferred_cbs) {
521 		if (event_deferred_cb_schedule_(buffer->cb_queue, &buffer->deferred)) {
522 			evbuffer_incref_and_lock_(buffer);
523 			if (buffer->parent)
524 				bufferevent_incref_(buffer->parent);
525 		}
526 		EVBUFFER_UNLOCK(buffer);
527 	}
528 
529 	evbuffer_run_callbacks(buffer, 0);
530 }
531 
532 static void
533 evbuffer_deferred_callback(struct event_callback *cb, void *arg)
534 {
535 	struct bufferevent *parent = NULL;
536 	struct evbuffer *buffer = arg;
537 
538 	/* XXXX It would be better to run these callbacks without holding the
539 	 * lock */
540 	EVBUFFER_LOCK(buffer);
541 	parent = buffer->parent;
542 	evbuffer_run_callbacks(buffer, 1);
543 	evbuffer_decref_and_unlock_(buffer);
544 	if (parent)
545 		bufferevent_decref_(parent);
546 }
547 
548 static void
549 evbuffer_remove_all_callbacks(struct evbuffer *buffer)
550 {
551 	struct evbuffer_cb_entry *cbent;
552 
553 	while ((cbent = LIST_FIRST(&buffer->callbacks))) {
554 		LIST_REMOVE(cbent, next);
555 		mm_free(cbent);
556 	}
557 }
558 
559 void
560 evbuffer_decref_and_unlock_(struct evbuffer *buffer)
561 {
562 	struct evbuffer_chain *chain, *next;
563 	ASSERT_EVBUFFER_LOCKED(buffer);
564 
565 	EVUTIL_ASSERT(buffer->refcnt > 0);
566 
567 	if (--buffer->refcnt > 0) {
568 		EVBUFFER_UNLOCK(buffer);
569 		return;
570 	}
571 
572 	for (chain = buffer->first; chain != NULL; chain = next) {
573 		next = chain->next;
574 		evbuffer_chain_free(chain);
575 	}
576 	evbuffer_remove_all_callbacks(buffer);
577 	if (buffer->deferred_cbs)
578 		event_deferred_cb_cancel_(buffer->cb_queue, &buffer->deferred);
579 
580 	EVBUFFER_UNLOCK(buffer);
581 	if (buffer->own_lock)
582 		EVTHREAD_FREE_LOCK(buffer->lock, EVTHREAD_LOCKTYPE_RECURSIVE);
583 	mm_free(buffer);
584 }
585 
586 void
587 evbuffer_free(struct evbuffer *buffer)
588 {
589 	EVBUFFER_LOCK(buffer);
590 	evbuffer_decref_and_unlock_(buffer);
591 }
592 
593 void
594 evbuffer_lock(struct evbuffer *buf)
595 {
596 	EVBUFFER_LOCK(buf);
597 }
598 
599 void
600 evbuffer_unlock(struct evbuffer *buf)
601 {
602 	EVBUFFER_UNLOCK(buf);
603 }
604 
605 size_t
606 evbuffer_get_length(const struct evbuffer *buffer)
607 {
608 	size_t result;
609 
610 	EVBUFFER_LOCK(buffer);
611 
612 	result = (buffer->total_len);
613 
614 	EVBUFFER_UNLOCK(buffer);
615 
616 	return result;
617 }
618 
619 size_t
620 evbuffer_get_contiguous_space(const struct evbuffer *buf)
621 {
622 	struct evbuffer_chain *chain;
623 	size_t result;
624 
625 	EVBUFFER_LOCK(buf);
626 	chain = buf->first;
627 	result = (chain != NULL ? chain->off : 0);
628 	EVBUFFER_UNLOCK(buf);
629 
630 	return result;
631 }
632 
633 size_t
634 evbuffer_add_iovec(struct evbuffer * buf, struct evbuffer_iovec * vec, int n_vec) {
635 	int n;
636 	size_t res;
637 	size_t to_alloc;
638 
639 	EVBUFFER_LOCK(buf);
640 
641 	res = to_alloc = 0;
642 
643 	for (n = 0; n < n_vec; n++) {
644 		to_alloc += vec[n].iov_len;
645 	}
646 
647 	if (evbuffer_expand_fast_(buf, to_alloc, 2) < 0) {
648 		goto done;
649 	}
650 
651 	for (n = 0; n < n_vec; n++) {
652 		/* XXX each 'add' call here does a bunch of setup that's
653 		 * obviated by evbuffer_expand_fast_, and some cleanup that we
654 		 * would like to do only once.  Instead we should just extract
655 		 * the part of the code that's needed. */
656 
657 		if (evbuffer_add(buf, vec[n].iov_base, vec[n].iov_len) < 0) {
658 			goto done;
659 		}
660 
661 		res += vec[n].iov_len;
662 	}
663 
664 done:
665     EVBUFFER_UNLOCK(buf);
666     return res;
667 }
668 
669 int
670 evbuffer_reserve_space(struct evbuffer *buf, ev_ssize_t size,
671     struct evbuffer_iovec *vec, int n_vecs)
672 {
673 	struct evbuffer_chain *chain, **chainp;
674 	int n = -1;
675 
676 	EVBUFFER_LOCK(buf);
677 	if (buf->freeze_end)
678 		goto done;
679 	if (n_vecs < 1)
680 		goto done;
681 	if (n_vecs == 1) {
682 		if ((chain = evbuffer_expand_singlechain(buf, size)) == NULL)
683 			goto done;
684 
685 		vec[0].iov_base = CHAIN_SPACE_PTR(chain);
686 		vec[0].iov_len = (size_t) CHAIN_SPACE_LEN(chain);
687 		EVUTIL_ASSERT(size<0 || (size_t)vec[0].iov_len >= (size_t)size);
688 		n = 1;
689 	} else {
690 		if (evbuffer_expand_fast_(buf, size, n_vecs)<0)
691 			goto done;
692 		n = evbuffer_read_setup_vecs_(buf, size, vec, n_vecs,
693 				&chainp, 0);
694 	}
695 
696 done:
697 	EVBUFFER_UNLOCK(buf);
698 	return n;
699 
700 }
701 
702 static int
703 advance_last_with_data(struct evbuffer *buf)
704 {
705 	int n = 0;
706 	ASSERT_EVBUFFER_LOCKED(buf);
707 
708 	if (!*buf->last_with_datap)
709 		return 0;
710 
711 	while ((*buf->last_with_datap)->next && (*buf->last_with_datap)->next->off) {
712 		buf->last_with_datap = &(*buf->last_with_datap)->next;
713 		++n;
714 	}
715 	return n;
716 }
717 
718 int
719 evbuffer_commit_space(struct evbuffer *buf,
720     struct evbuffer_iovec *vec, int n_vecs)
721 {
722 	struct evbuffer_chain *chain, **firstchainp, **chainp;
723 	int result = -1;
724 	size_t added = 0;
725 	int i;
726 
727 	EVBUFFER_LOCK(buf);
728 
729 	if (buf->freeze_end)
730 		goto done;
731 	if (n_vecs == 0) {
732 		result = 0;
733 		goto done;
734 	} else if (n_vecs == 1 &&
735 	    (buf->last && vec[0].iov_base == (void*)CHAIN_SPACE_PTR(buf->last))) {
736 		/* The user only got or used one chain; it might not
737 		 * be the first one with space in it. */
738 		if ((size_t)vec[0].iov_len > (size_t)CHAIN_SPACE_LEN(buf->last))
739 			goto done;
740 		buf->last->off += vec[0].iov_len;
741 		added = vec[0].iov_len;
742 		if (added)
743 			advance_last_with_data(buf);
744 		goto okay;
745 	}
746 
747 	/* Advance 'firstchain' to the first chain with space in it. */
748 	firstchainp = buf->last_with_datap;
749 	if (!*firstchainp)
750 		goto done;
751 	if (CHAIN_SPACE_LEN(*firstchainp) == 0) {
752 		firstchainp = &(*firstchainp)->next;
753 	}
754 
755 	chain = *firstchainp;
756 	/* pass 1: make sure that the pointers and lengths of vecs[] are in
757 	 * bounds before we try to commit anything. */
758 	for (i=0; i<n_vecs; ++i) {
759 		if (!chain)
760 			goto done;
761 		if (vec[i].iov_base != (void*)CHAIN_SPACE_PTR(chain) ||
762 		    (size_t)vec[i].iov_len > CHAIN_SPACE_LEN(chain))
763 			goto done;
764 		chain = chain->next;
765 	}
766 	/* pass 2: actually adjust all the chains. */
767 	chainp = firstchainp;
768 	for (i=0; i<n_vecs; ++i) {
769 		(*chainp)->off += vec[i].iov_len;
770 		added += vec[i].iov_len;
771 		if (vec[i].iov_len) {
772 			buf->last_with_datap = chainp;
773 		}
774 		chainp = &(*chainp)->next;
775 	}
776 
777 okay:
778 	buf->total_len += added;
779 	buf->n_add_for_cb += added;
780 	result = 0;
781 	evbuffer_invoke_callbacks_(buf);
782 
783 done:
784 	EVBUFFER_UNLOCK(buf);
785 	return result;
786 }
787 
788 static inline int
789 HAS_PINNED_R(struct evbuffer *buf)
790 {
791 	return (buf->last && CHAIN_PINNED_R(buf->last));
792 }
793 
794 static inline void
795 ZERO_CHAIN(struct evbuffer *dst)
796 {
797 	ASSERT_EVBUFFER_LOCKED(dst);
798 	dst->first = NULL;
799 	dst->last = NULL;
800 	dst->last_with_datap = &(dst)->first;
801 	dst->total_len = 0;
802 }
803 
804 /* Prepares the contents of src to be moved to another buffer by removing
805  * read-pinned chains. The first pinned chain is saved in first, and the
806  * last in last. If src has no read-pinned chains, first and last are set
807  * to NULL. */
808 static int
809 PRESERVE_PINNED(struct evbuffer *src, struct evbuffer_chain **first,
810 		struct evbuffer_chain **last)
811 {
812 	struct evbuffer_chain *chain, **pinned;
813 
814 	ASSERT_EVBUFFER_LOCKED(src);
815 
816 	if (!HAS_PINNED_R(src)) {
817 		*first = *last = NULL;
818 		return 0;
819 	}
820 
821 	pinned = src->last_with_datap;
822 	if (!CHAIN_PINNED_R(*pinned))
823 		pinned = &(*pinned)->next;
824 	EVUTIL_ASSERT(CHAIN_PINNED_R(*pinned));
825 	chain = *first = *pinned;
826 	*last = src->last;
827 
828 	/* If there's data in the first pinned chain, we need to allocate
829 	 * a new chain and copy the data over. */
830 	if (chain->off) {
831 		struct evbuffer_chain *tmp;
832 
833 		EVUTIL_ASSERT(pinned == src->last_with_datap);
834 		tmp = evbuffer_chain_new(chain->off);
835 		if (!tmp)
836 			return -1;
837 		memcpy(tmp->buffer, chain->buffer + chain->misalign,
838 			chain->off);
839 		tmp->off = chain->off;
840 		*src->last_with_datap = tmp;
841 		src->last = tmp;
842 		chain->misalign += chain->off;
843 		chain->off = 0;
844 	} else {
845 		src->last = *src->last_with_datap;
846 		*pinned = NULL;
847 	}
848 
849 	return 0;
850 }
851 
852 static inline void
853 RESTORE_PINNED(struct evbuffer *src, struct evbuffer_chain *pinned,
854 		struct evbuffer_chain *last)
855 {
856 	ASSERT_EVBUFFER_LOCKED(src);
857 
858 	if (!pinned) {
859 		ZERO_CHAIN(src);
860 		return;
861 	}
862 
863 	src->first = pinned;
864 	src->last = last;
865 	src->last_with_datap = &src->first;
866 	src->total_len = 0;
867 }
868 
869 static inline void
870 COPY_CHAIN(struct evbuffer *dst, struct evbuffer *src)
871 {
872 	ASSERT_EVBUFFER_LOCKED(dst);
873 	ASSERT_EVBUFFER_LOCKED(src);
874 	dst->first = src->first;
875 	if (src->last_with_datap == &src->first)
876 		dst->last_with_datap = &dst->first;
877 	else
878 		dst->last_with_datap = src->last_with_datap;
879 	dst->last = src->last;
880 	dst->total_len = src->total_len;
881 }
882 
883 static void
884 APPEND_CHAIN(struct evbuffer *dst, struct evbuffer *src)
885 {
886 	ASSERT_EVBUFFER_LOCKED(dst);
887 	ASSERT_EVBUFFER_LOCKED(src);
888 	dst->last->next = src->first;
889 	if (src->last_with_datap == &src->first)
890 		dst->last_with_datap = &dst->last->next;
891 	else
892 		dst->last_with_datap = src->last_with_datap;
893 	dst->last = src->last;
894 	dst->total_len += src->total_len;
895 }
896 
897 static inline void
898 APPEND_CHAIN_MULTICAST(struct evbuffer *dst, struct evbuffer *src)
899 {
900 	struct evbuffer_chain *tmp;
901 	struct evbuffer_chain *chain = src->first;
902 	struct evbuffer_multicast_parent *extra;
903 
904 	ASSERT_EVBUFFER_LOCKED(dst);
905 	ASSERT_EVBUFFER_LOCKED(src);
906 
907 	for (; chain; chain = chain->next) {
908 		if (!chain->off || chain->flags & EVBUFFER_DANGLING) {
909 			/* skip empty chains */
910 			continue;
911 		}
912 
913 		tmp = evbuffer_chain_new(sizeof(struct evbuffer_multicast_parent));
914 		if (!tmp) {
915 			event_warn("%s: out of memory", __func__);
916 			return;
917 		}
918 		extra = EVBUFFER_CHAIN_EXTRA(struct evbuffer_multicast_parent, tmp);
919 		/* reference evbuffer containing source chain so it
920 		 * doesn't get released while the chain is still
921 		 * being referenced to */
922 		evbuffer_incref_(src);
923 		extra->source = src;
924 		/* reference source chain which now becomes immutable */
925 		evbuffer_chain_incref(chain);
926 		extra->parent = chain;
927 		chain->flags |= EVBUFFER_IMMUTABLE;
928 		tmp->buffer_len = chain->buffer_len;
929 		tmp->misalign = chain->misalign;
930 		tmp->off = chain->off;
931 		tmp->flags |= EVBUFFER_MULTICAST|EVBUFFER_IMMUTABLE;
932 		tmp->buffer = chain->buffer;
933 		evbuffer_chain_insert(dst, tmp);
934 	}
935 }
936 
937 static void
938 PREPEND_CHAIN(struct evbuffer *dst, struct evbuffer *src)
939 {
940 	ASSERT_EVBUFFER_LOCKED(dst);
941 	ASSERT_EVBUFFER_LOCKED(src);
942 	src->last->next = dst->first;
943 	dst->first = src->first;
944 	dst->total_len += src->total_len;
945 	if (*dst->last_with_datap == NULL) {
946 		if (src->last_with_datap == &(src)->first)
947 			dst->last_with_datap = &dst->first;
948 		else
949 			dst->last_with_datap = src->last_with_datap;
950 	} else if (dst->last_with_datap == &dst->first) {
951 		dst->last_with_datap = &src->last->next;
952 	}
953 }
954 
955 int
956 evbuffer_add_buffer(struct evbuffer *outbuf, struct evbuffer *inbuf)
957 {
958 	struct evbuffer_chain *pinned, *last;
959 	size_t in_total_len, out_total_len;
960 	int result = 0;
961 
962 	EVBUFFER_LOCK2(inbuf, outbuf);
963 	in_total_len = inbuf->total_len;
964 	out_total_len = outbuf->total_len;
965 
966 	if (in_total_len == 0 || outbuf == inbuf)
967 		goto done;
968 
969 	if (outbuf->freeze_end || inbuf->freeze_start) {
970 		result = -1;
971 		goto done;
972 	}
973 
974 	if (PRESERVE_PINNED(inbuf, &pinned, &last) < 0) {
975 		result = -1;
976 		goto done;
977 	}
978 
979 	if (out_total_len == 0) {
980 		/* There might be an empty chain at the start of outbuf; free
981 		 * it. */
982 		evbuffer_free_all_chains(outbuf->first);
983 		COPY_CHAIN(outbuf, inbuf);
984 	} else {
985 		APPEND_CHAIN(outbuf, inbuf);
986 	}
987 
988 	RESTORE_PINNED(inbuf, pinned, last);
989 
990 	inbuf->n_del_for_cb += in_total_len;
991 	outbuf->n_add_for_cb += in_total_len;
992 
993 	evbuffer_invoke_callbacks_(inbuf);
994 	evbuffer_invoke_callbacks_(outbuf);
995 
996 done:
997 	EVBUFFER_UNLOCK2(inbuf, outbuf);
998 	return result;
999 }
1000 
1001 int
1002 evbuffer_add_buffer_reference(struct evbuffer *outbuf, struct evbuffer *inbuf)
1003 {
1004 	size_t in_total_len, out_total_len;
1005 	struct evbuffer_chain *chain;
1006 	int result = 0;
1007 
1008 	EVBUFFER_LOCK2(inbuf, outbuf);
1009 	in_total_len = inbuf->total_len;
1010 	out_total_len = outbuf->total_len;
1011 	chain = inbuf->first;
1012 
1013 	if (in_total_len == 0)
1014 		goto done;
1015 
1016 	if (outbuf->freeze_end || outbuf == inbuf) {
1017 		result = -1;
1018 		goto done;
1019 	}
1020 
1021 	for (; chain; chain = chain->next) {
1022 		if ((chain->flags & (EVBUFFER_FILESEGMENT|EVBUFFER_SENDFILE|EVBUFFER_MULTICAST)) != 0) {
1023 			/* chain type can not be referenced */
1024 			result = -1;
1025 			goto done;
1026 		}
1027 	}
1028 
1029 	if (out_total_len == 0) {
1030 		/* There might be an empty chain at the start of outbuf; free
1031 		 * it. */
1032 		evbuffer_free_all_chains(outbuf->first);
1033 	}
1034 	APPEND_CHAIN_MULTICAST(outbuf, inbuf);
1035 
1036 	outbuf->n_add_for_cb += in_total_len;
1037 	evbuffer_invoke_callbacks_(outbuf);
1038 
1039 done:
1040 	EVBUFFER_UNLOCK2(inbuf, outbuf);
1041 	return result;
1042 }
1043 
1044 int
1045 evbuffer_prepend_buffer(struct evbuffer *outbuf, struct evbuffer *inbuf)
1046 {
1047 	struct evbuffer_chain *pinned, *last;
1048 	size_t in_total_len, out_total_len;
1049 	int result = 0;
1050 
1051 	EVBUFFER_LOCK2(inbuf, outbuf);
1052 
1053 	in_total_len = inbuf->total_len;
1054 	out_total_len = outbuf->total_len;
1055 
1056 	if (!in_total_len || inbuf == outbuf)
1057 		goto done;
1058 
1059 	if (outbuf->freeze_start || inbuf->freeze_start) {
1060 		result = -1;
1061 		goto done;
1062 	}
1063 
1064 	if (PRESERVE_PINNED(inbuf, &pinned, &last) < 0) {
1065 		result = -1;
1066 		goto done;
1067 	}
1068 
1069 	if (out_total_len == 0) {
1070 		/* There might be an empty chain at the start of outbuf; free
1071 		 * it. */
1072 		evbuffer_free_all_chains(outbuf->first);
1073 		COPY_CHAIN(outbuf, inbuf);
1074 	} else {
1075 		PREPEND_CHAIN(outbuf, inbuf);
1076 	}
1077 
1078 	RESTORE_PINNED(inbuf, pinned, last);
1079 
1080 	inbuf->n_del_for_cb += in_total_len;
1081 	outbuf->n_add_for_cb += in_total_len;
1082 
1083 	evbuffer_invoke_callbacks_(inbuf);
1084 	evbuffer_invoke_callbacks_(outbuf);
1085 done:
1086 	EVBUFFER_UNLOCK2(inbuf, outbuf);
1087 	return result;
1088 }
1089 
1090 int
1091 evbuffer_drain(struct evbuffer *buf, size_t len)
1092 {
1093 	struct evbuffer_chain *chain, *next;
1094 	size_t remaining, old_len;
1095 	int result = 0;
1096 
1097 	EVBUFFER_LOCK(buf);
1098 	old_len = buf->total_len;
1099 
1100 	if (old_len == 0)
1101 		goto done;
1102 
1103 	if (buf->freeze_start) {
1104 		result = -1;
1105 		goto done;
1106 	}
1107 
1108 	if (len >= old_len && !HAS_PINNED_R(buf)) {
1109 		len = old_len;
1110 		for (chain = buf->first; chain != NULL; chain = next) {
1111 			next = chain->next;
1112 			evbuffer_chain_free(chain);
1113 		}
1114 
1115 		ZERO_CHAIN(buf);
1116 	} else {
1117 		if (len >= old_len)
1118 			len = old_len;
1119 
1120 		buf->total_len -= len;
1121 		remaining = len;
1122 		for (chain = buf->first;
1123 		     remaining >= chain->off;
1124 		     chain = next) {
1125 			next = chain->next;
1126 			remaining -= chain->off;
1127 
1128 			if (chain == *buf->last_with_datap) {
1129 				buf->last_with_datap = &buf->first;
1130 			}
1131 			if (&chain->next == buf->last_with_datap)
1132 				buf->last_with_datap = &buf->first;
1133 
1134 			if (CHAIN_PINNED_R(chain)) {
1135 				EVUTIL_ASSERT(remaining == 0);
1136 				chain->misalign += chain->off;
1137 				chain->off = 0;
1138 				break;
1139 			} else
1140 				evbuffer_chain_free(chain);
1141 		}
1142 
1143 		buf->first = chain;
1144 		EVUTIL_ASSERT(chain && remaining <= chain->off);
1145 		chain->misalign += remaining;
1146 		chain->off -= remaining;
1147 	}
1148 
1149 	buf->n_del_for_cb += len;
1150 	/* Tell someone about changes in this buffer */
1151 	evbuffer_invoke_callbacks_(buf);
1152 
1153 done:
1154 	EVBUFFER_UNLOCK(buf);
1155 	return result;
1156 }
1157 
1158 /* Reads data from an event buffer and drains the bytes read */
1159 int
1160 evbuffer_remove(struct evbuffer *buf, void *data_out, size_t datlen)
1161 {
1162 	ev_ssize_t n;
1163 	EVBUFFER_LOCK(buf);
1164 	n = evbuffer_copyout_from(buf, NULL, data_out, datlen);
1165 	if (n > 0) {
1166 		if (evbuffer_drain(buf, n)<0)
1167 			n = -1;
1168 	}
1169 	EVBUFFER_UNLOCK(buf);
1170 	return (int)n;
1171 }
1172 
1173 ev_ssize_t
1174 evbuffer_copyout(struct evbuffer *buf, void *data_out, size_t datlen)
1175 {
1176 	return evbuffer_copyout_from(buf, NULL, data_out, datlen);
1177 }
1178 
1179 ev_ssize_t
1180 evbuffer_copyout_from(struct evbuffer *buf, const struct evbuffer_ptr *pos,
1181     void *data_out, size_t datlen)
1182 {
1183 	/*XXX fails badly on sendfile case. */
1184 	struct evbuffer_chain *chain;
1185 	char *data = data_out;
1186 	size_t nread;
1187 	ev_ssize_t result = 0;
1188 	size_t pos_in_chain;
1189 
1190 	EVBUFFER_LOCK(buf);
1191 
1192 	if (pos) {
1193 		if (datlen > (size_t)(EV_SSIZE_MAX - pos->pos)) {
1194 			result = -1;
1195 			goto done;
1196 		}
1197 		chain = pos->internal_.chain;
1198 		pos_in_chain = pos->internal_.pos_in_chain;
1199 		if (datlen + pos->pos > buf->total_len)
1200 			datlen = buf->total_len - pos->pos;
1201 	} else {
1202 		chain = buf->first;
1203 		pos_in_chain = 0;
1204 		if (datlen > buf->total_len)
1205 			datlen = buf->total_len;
1206 	}
1207 
1208 
1209 	if (datlen == 0)
1210 		goto done;
1211 
1212 	if (buf->freeze_start) {
1213 		result = -1;
1214 		goto done;
1215 	}
1216 
1217 	nread = datlen;
1218 
1219 	while (datlen && datlen >= chain->off - pos_in_chain) {
1220 		size_t copylen = chain->off - pos_in_chain;
1221 		memcpy(data,
1222 		    chain->buffer + chain->misalign + pos_in_chain,
1223 		    copylen);
1224 		data += copylen;
1225 		datlen -= copylen;
1226 
1227 		chain = chain->next;
1228 		pos_in_chain = 0;
1229 		EVUTIL_ASSERT(chain || datlen==0);
1230 	}
1231 
1232 	if (datlen) {
1233 		EVUTIL_ASSERT(chain);
1234 		EVUTIL_ASSERT(datlen+pos_in_chain <= chain->off);
1235 
1236 		memcpy(data, chain->buffer + chain->misalign + pos_in_chain,
1237 		    datlen);
1238 	}
1239 
1240 	result = nread;
1241 done:
1242 	EVBUFFER_UNLOCK(buf);
1243 	return result;
1244 }
1245 
1246 /* reads data from the src buffer to the dst buffer, avoids memcpy as
1247  * possible. */
1248 /*  XXXX should return ev_ssize_t */
1249 int
1250 evbuffer_remove_buffer(struct evbuffer *src, struct evbuffer *dst,
1251     size_t datlen)
1252 {
1253 	/*XXX We should have an option to force this to be zero-copy.*/
1254 
1255 	/*XXX can fail badly on sendfile case. */
1256 	struct evbuffer_chain *chain, *previous;
1257 	size_t nread = 0;
1258 	int result;
1259 
1260 	EVBUFFER_LOCK2(src, dst);
1261 
1262 	chain = previous = src->first;
1263 
1264 	if (datlen == 0 || dst == src) {
1265 		result = 0;
1266 		goto done;
1267 	}
1268 
1269 	if (dst->freeze_end || src->freeze_start) {
1270 		result = -1;
1271 		goto done;
1272 	}
1273 
1274 	/* short-cut if there is no more data buffered */
1275 	if (datlen >= src->total_len) {
1276 		datlen = src->total_len;
1277 		evbuffer_add_buffer(dst, src);
1278 		result = (int)datlen; /*XXXX should return ev_ssize_t*/
1279 		goto done;
1280 	}
1281 
1282 	/* removes chains if possible */
1283 	while (chain->off <= datlen) {
1284 		/* We can't remove the last with data from src unless we
1285 		 * remove all chains, in which case we would have done the if
1286 		 * block above */
1287 		EVUTIL_ASSERT(chain != *src->last_with_datap);
1288 		nread += chain->off;
1289 		datlen -= chain->off;
1290 		previous = chain;
1291 		if (src->last_with_datap == &chain->next)
1292 			src->last_with_datap = &src->first;
1293 		chain = chain->next;
1294 	}
1295 
1296 	if (nread) {
1297 		/* we can remove the chain */
1298 		struct evbuffer_chain **chp;
1299 		chp = evbuffer_free_trailing_empty_chains(dst);
1300 
1301 		if (dst->first == NULL) {
1302 			dst->first = src->first;
1303 		} else {
1304 			*chp = src->first;
1305 		}
1306 		dst->last = previous;
1307 		previous->next = NULL;
1308 		src->first = chain;
1309 		advance_last_with_data(dst);
1310 
1311 		dst->total_len += nread;
1312 		dst->n_add_for_cb += nread;
1313 	}
1314 
1315 	/* we know that there is more data in the src buffer than
1316 	 * we want to read, so we manually drain the chain */
1317 	evbuffer_add(dst, chain->buffer + chain->misalign, datlen);
1318 	chain->misalign += datlen;
1319 	chain->off -= datlen;
1320 	nread += datlen;
1321 
1322 	/* You might think we would want to increment dst->n_add_for_cb
1323 	 * here too.  But evbuffer_add above already took care of that.
1324 	 */
1325 	src->total_len -= nread;
1326 	src->n_del_for_cb += nread;
1327 
1328 	if (nread) {
1329 		evbuffer_invoke_callbacks_(dst);
1330 		evbuffer_invoke_callbacks_(src);
1331 	}
1332 	result = (int)nread;/*XXXX should change return type */
1333 
1334 done:
1335 	EVBUFFER_UNLOCK2(src, dst);
1336 	return result;
1337 }
1338 
1339 unsigned char *
1340 evbuffer_pullup(struct evbuffer *buf, ev_ssize_t size)
1341 {
1342 	struct evbuffer_chain *chain, *next, *tmp, *last_with_data;
1343 	unsigned char *buffer, *result = NULL;
1344 	ev_ssize_t remaining;
1345 	int removed_last_with_data = 0;
1346 	int removed_last_with_datap = 0;
1347 
1348 	EVBUFFER_LOCK(buf);
1349 
1350 	chain = buf->first;
1351 
1352 	if (size < 0)
1353 		size = buf->total_len;
1354 	/* if size > buf->total_len, we cannot guarantee to the user that she
1355 	 * is going to have a long enough buffer afterwards; so we return
1356 	 * NULL */
1357 	if (size == 0 || (size_t)size > buf->total_len)
1358 		goto done;
1359 
1360 	/* No need to pull up anything; the first size bytes are
1361 	 * already here. */
1362 	if (chain->off >= (size_t)size) {
1363 		result = chain->buffer + chain->misalign;
1364 		goto done;
1365 	}
1366 
1367 	/* Make sure that none of the chains we need to copy from is pinned. */
1368 	remaining = size - chain->off;
1369 	EVUTIL_ASSERT(remaining >= 0);
1370 	for (tmp=chain->next; tmp; tmp=tmp->next) {
1371 		if (CHAIN_PINNED(tmp))
1372 			goto done;
1373 		if (tmp->off >= (size_t)remaining)
1374 			break;
1375 		remaining -= tmp->off;
1376 	}
1377 
1378 	if (CHAIN_PINNED(chain)) {
1379 		size_t old_off = chain->off;
1380 		if (CHAIN_SPACE_LEN(chain) < size - chain->off) {
1381 			/* not enough room at end of chunk. */
1382 			goto done;
1383 		}
1384 		buffer = CHAIN_SPACE_PTR(chain);
1385 		tmp = chain;
1386 		tmp->off = size;
1387 		size -= old_off;
1388 		chain = chain->next;
1389 	} else if (chain->buffer_len - chain->misalign >= (size_t)size) {
1390 		/* already have enough space in the first chain */
1391 		size_t old_off = chain->off;
1392 		buffer = chain->buffer + chain->misalign + chain->off;
1393 		tmp = chain;
1394 		tmp->off = size;
1395 		size -= old_off;
1396 		chain = chain->next;
1397 	} else {
1398 		if ((tmp = evbuffer_chain_new(size)) == NULL) {
1399 			event_warn("%s: out of memory", __func__);
1400 			goto done;
1401 		}
1402 		buffer = tmp->buffer;
1403 		tmp->off = size;
1404 		buf->first = tmp;
1405 	}
1406 
1407 	/* TODO(niels): deal with buffers that point to NULL like sendfile */
1408 
1409 	/* Copy and free every chunk that will be entirely pulled into tmp */
1410 	last_with_data = *buf->last_with_datap;
1411 	for (; chain != NULL && (size_t)size >= chain->off; chain = next) {
1412 		next = chain->next;
1413 
1414 		memcpy(buffer, chain->buffer + chain->misalign, chain->off);
1415 		size -= chain->off;
1416 		buffer += chain->off;
1417 		if (chain == last_with_data)
1418 			removed_last_with_data = 1;
1419 		if (&chain->next == buf->last_with_datap)
1420 			removed_last_with_datap = 1;
1421 
1422 		evbuffer_chain_free(chain);
1423 	}
1424 
1425 	if (chain != NULL) {
1426 		memcpy(buffer, chain->buffer + chain->misalign, size);
1427 		chain->misalign += size;
1428 		chain->off -= size;
1429 	} else {
1430 		buf->last = tmp;
1431 	}
1432 
1433 	tmp->next = chain;
1434 
1435 	if (removed_last_with_data) {
1436 		buf->last_with_datap = &buf->first;
1437 	} else if (removed_last_with_datap) {
1438 		if (buf->first->next && buf->first->next->off)
1439 			buf->last_with_datap = &buf->first->next;
1440 		else
1441 			buf->last_with_datap = &buf->first;
1442 	}
1443 
1444 	result = (tmp->buffer + tmp->misalign);
1445 
1446 done:
1447 	EVBUFFER_UNLOCK(buf);
1448 	return result;
1449 }
1450 
1451 /*
1452  * Reads a line terminated by either '\r\n', '\n\r' or '\r' or '\n'.
1453  * The returned buffer needs to be freed by the called.
1454  */
1455 char *
1456 evbuffer_readline(struct evbuffer *buffer)
1457 {
1458 	return evbuffer_readln(buffer, NULL, EVBUFFER_EOL_ANY);
1459 }
1460 
1461 static inline ev_ssize_t
1462 evbuffer_strchr(struct evbuffer_ptr *it, const char chr)
1463 {
1464 	struct evbuffer_chain *chain = it->internal_.chain;
1465 	size_t i = it->internal_.pos_in_chain;
1466 	while (chain != NULL) {
1467 		char *buffer = (char *)chain->buffer + chain->misalign;
1468 		char *cp = memchr(buffer+i, chr, chain->off-i);
1469 		if (cp) {
1470 			it->internal_.chain = chain;
1471 			it->internal_.pos_in_chain = cp - buffer;
1472 			it->pos += (cp - buffer - i);
1473 			return it->pos;
1474 		}
1475 		it->pos += chain->off - i;
1476 		i = 0;
1477 		chain = chain->next;
1478 	}
1479 
1480 	return (-1);
1481 }
1482 
1483 static inline char *
1484 find_eol_char(char *s, size_t len)
1485 {
1486 #define CHUNK_SZ 128
1487 	/* Lots of benchmarking found this approach to be faster in practice
1488 	 * than doing two memchrs over the whole buffer, doin a memchr on each
1489 	 * char of the buffer, or trying to emulate memchr by hand. */
1490 	char *s_end, *cr, *lf;
1491 	s_end = s+len;
1492 	while (s < s_end) {
1493 		size_t chunk = (s + CHUNK_SZ < s_end) ? CHUNK_SZ : (s_end - s);
1494 		cr = memchr(s, '\r', chunk);
1495 		lf = memchr(s, '\n', chunk);
1496 		if (cr) {
1497 			if (lf && lf < cr)
1498 				return lf;
1499 			return cr;
1500 		} else if (lf) {
1501 			return lf;
1502 		}
1503 		s += CHUNK_SZ;
1504 	}
1505 
1506 	return NULL;
1507 #undef CHUNK_SZ
1508 }
1509 
1510 static ev_ssize_t
1511 evbuffer_find_eol_char(struct evbuffer_ptr *it)
1512 {
1513 	struct evbuffer_chain *chain = it->internal_.chain;
1514 	size_t i = it->internal_.pos_in_chain;
1515 	while (chain != NULL) {
1516 		char *buffer = (char *)chain->buffer + chain->misalign;
1517 		char *cp = find_eol_char(buffer+i, chain->off-i);
1518 		if (cp) {
1519 			it->internal_.chain = chain;
1520 			it->internal_.pos_in_chain = cp - buffer;
1521 			it->pos += (cp - buffer) - i;
1522 			return it->pos;
1523 		}
1524 		it->pos += chain->off - i;
1525 		i = 0;
1526 		chain = chain->next;
1527 	}
1528 
1529 	return (-1);
1530 }
1531 
1532 static inline int
1533 evbuffer_strspn(
1534 	struct evbuffer_ptr *ptr, const char *chrset)
1535 {
1536 	int count = 0;
1537 	struct evbuffer_chain *chain = ptr->internal_.chain;
1538 	size_t i = ptr->internal_.pos_in_chain;
1539 
1540 	if (!chain)
1541 		return 0;
1542 
1543 	while (1) {
1544 		char *buffer = (char *)chain->buffer + chain->misalign;
1545 		for (; i < chain->off; ++i) {
1546 			const char *p = chrset;
1547 			while (*p) {
1548 				if (buffer[i] == *p++)
1549 					goto next;
1550 			}
1551 			ptr->internal_.chain = chain;
1552 			ptr->internal_.pos_in_chain = i;
1553 			ptr->pos += count;
1554 			return count;
1555 		next:
1556 			++count;
1557 		}
1558 		i = 0;
1559 
1560 		if (! chain->next) {
1561 			ptr->internal_.chain = chain;
1562 			ptr->internal_.pos_in_chain = i;
1563 			ptr->pos += count;
1564 			return count;
1565 		}
1566 
1567 		chain = chain->next;
1568 	}
1569 }
1570 
1571 
1572 static inline int
1573 evbuffer_getchr(struct evbuffer_ptr *it)
1574 {
1575 	struct evbuffer_chain *chain = it->internal_.chain;
1576 	size_t off = it->internal_.pos_in_chain;
1577 
1578 	if (chain == NULL)
1579 		return -1;
1580 
1581 	return (unsigned char)chain->buffer[chain->misalign + off];
1582 }
1583 
1584 struct evbuffer_ptr
1585 evbuffer_search_eol(struct evbuffer *buffer,
1586     struct evbuffer_ptr *start, size_t *eol_len_out,
1587     enum evbuffer_eol_style eol_style)
1588 {
1589 	struct evbuffer_ptr it, it2;
1590 	size_t extra_drain = 0;
1591 	int ok = 0;
1592 
1593 	/* Avoid locking in trivial edge cases */
1594 	if (start && start->internal_.chain == NULL) {
1595 		PTR_NOT_FOUND(&it);
1596 		if (eol_len_out)
1597 			*eol_len_out = extra_drain;
1598 		return it;
1599 	}
1600 
1601 	EVBUFFER_LOCK(buffer);
1602 
1603 	if (start) {
1604 		memcpy(&it, start, sizeof(it));
1605 	} else {
1606 		it.pos = 0;
1607 		it.internal_.chain = buffer->first;
1608 		it.internal_.pos_in_chain = 0;
1609 	}
1610 
1611 	/* the eol_style determines our first stop character and how many
1612 	 * characters we are going to drain afterwards. */
1613 	switch (eol_style) {
1614 	case EVBUFFER_EOL_ANY:
1615 		if (evbuffer_find_eol_char(&it) < 0)
1616 			goto done;
1617 		memcpy(&it2, &it, sizeof(it));
1618 		extra_drain = evbuffer_strspn(&it2, "\r\n");
1619 		break;
1620 	case EVBUFFER_EOL_CRLF_STRICT: {
1621 		it = evbuffer_search(buffer, "\r\n", 2, &it);
1622 		if (it.pos < 0)
1623 			goto done;
1624 		extra_drain = 2;
1625 		break;
1626 	}
1627 	case EVBUFFER_EOL_CRLF: {
1628 		ev_ssize_t start_pos = it.pos;
1629 		/* Look for a LF ... */
1630 		if (evbuffer_strchr(&it, '\n') < 0)
1631 			goto done;
1632 		extra_drain = 1;
1633 		/* ... optionally preceeded by a CR. */
1634 		if (it.pos == start_pos)
1635 			break; /* If the first character is \n, don't back up */
1636 		/* This potentially does an extra linear walk over the first
1637 		 * few chains.  Probably, that's not too expensive unless you
1638 		 * have a really pathological setup. */
1639 		memcpy(&it2, &it, sizeof(it));
1640 		if (evbuffer_ptr_subtract(buffer, &it2, 1)<0)
1641 			break;
1642 		if (evbuffer_getchr(&it2) == '\r') {
1643 			memcpy(&it, &it2, sizeof(it));
1644 			extra_drain = 2;
1645 		}
1646 		break;
1647 	}
1648 	case EVBUFFER_EOL_LF:
1649 		if (evbuffer_strchr(&it, '\n') < 0)
1650 			goto done;
1651 		extra_drain = 1;
1652 		break;
1653 	case EVBUFFER_EOL_NUL:
1654 		if (evbuffer_strchr(&it, '\0') < 0)
1655 			goto done;
1656 		extra_drain = 1;
1657 		break;
1658 	default:
1659 		goto done;
1660 	}
1661 
1662 	ok = 1;
1663 done:
1664 	EVBUFFER_UNLOCK(buffer);
1665 
1666 	if (!ok)
1667 		PTR_NOT_FOUND(&it);
1668 	if (eol_len_out)
1669 		*eol_len_out = extra_drain;
1670 
1671 	return it;
1672 }
1673 
1674 char *
1675 evbuffer_readln(struct evbuffer *buffer, size_t *n_read_out,
1676 		enum evbuffer_eol_style eol_style)
1677 {
1678 	struct evbuffer_ptr it;
1679 	char *line;
1680 	size_t n_to_copy=0, extra_drain=0;
1681 	char *result = NULL;
1682 
1683 	EVBUFFER_LOCK(buffer);
1684 
1685 	if (buffer->freeze_start) {
1686 		goto done;
1687 	}
1688 
1689 	it = evbuffer_search_eol(buffer, NULL, &extra_drain, eol_style);
1690 	if (it.pos < 0)
1691 		goto done;
1692 	n_to_copy = it.pos;
1693 
1694 	if ((line = mm_malloc(n_to_copy+1)) == NULL) {
1695 		event_warn("%s: out of memory", __func__);
1696 		goto done;
1697 	}
1698 
1699 	evbuffer_remove(buffer, line, n_to_copy);
1700 	line[n_to_copy] = '\0';
1701 
1702 	evbuffer_drain(buffer, extra_drain);
1703 	result = line;
1704 done:
1705 	EVBUFFER_UNLOCK(buffer);
1706 
1707 	if (n_read_out)
1708 		*n_read_out = result ? n_to_copy : 0;
1709 
1710 	return result;
1711 }
1712 
1713 #define EVBUFFER_CHAIN_MAX_AUTO_SIZE 4096
1714 
1715 /* Adds data to an event buffer */
1716 
1717 int
1718 evbuffer_add(struct evbuffer *buf, const void *data_in, size_t datlen)
1719 {
1720 	struct evbuffer_chain *chain, *tmp;
1721 	const unsigned char *data = data_in;
1722 	size_t remain, to_alloc;
1723 	int result = -1;
1724 
1725 	EVBUFFER_LOCK(buf);
1726 
1727 	if (buf->freeze_end) {
1728 		goto done;
1729 	}
1730 	/* Prevent buf->total_len overflow */
1731 	if (datlen > EV_SIZE_MAX - buf->total_len) {
1732 		goto done;
1733 	}
1734 
1735 	if (*buf->last_with_datap == NULL) {
1736 		chain = buf->last;
1737 	} else {
1738 		chain = *buf->last_with_datap;
1739 	}
1740 
1741 	/* If there are no chains allocated for this buffer, allocate one
1742 	 * big enough to hold all the data. */
1743 	if (chain == NULL) {
1744 		chain = evbuffer_chain_new(datlen);
1745 		if (!chain)
1746 			goto done;
1747 		evbuffer_chain_insert(buf, chain);
1748 	}
1749 
1750 	if ((chain->flags & EVBUFFER_IMMUTABLE) == 0) {
1751 		/* Always true for mutable buffers */
1752 		EVUTIL_ASSERT(chain->misalign >= 0 &&
1753 		    (ev_uint64_t)chain->misalign <= EVBUFFER_CHAIN_MAX);
1754 		remain = chain->buffer_len - (size_t)chain->misalign - chain->off;
1755 		if (remain >= datlen) {
1756 			/* there's enough space to hold all the data in the
1757 			 * current last chain */
1758 			memcpy(chain->buffer + chain->misalign + chain->off,
1759 			    data, datlen);
1760 			chain->off += datlen;
1761 			buf->total_len += datlen;
1762 			buf->n_add_for_cb += datlen;
1763 			goto out;
1764 		} else if (!CHAIN_PINNED(chain) &&
1765 		    evbuffer_chain_should_realign(chain, datlen)) {
1766 			/* we can fit the data into the misalignment */
1767 			evbuffer_chain_align(chain);
1768 
1769 			memcpy(chain->buffer + chain->off, data, datlen);
1770 			chain->off += datlen;
1771 			buf->total_len += datlen;
1772 			buf->n_add_for_cb += datlen;
1773 			goto out;
1774 		}
1775 	} else {
1776 		/* we cannot write any data to the last chain */
1777 		remain = 0;
1778 	}
1779 
1780 	/* we need to add another chain */
1781 	to_alloc = chain->buffer_len;
1782 	if (to_alloc <= EVBUFFER_CHAIN_MAX_AUTO_SIZE/2)
1783 		to_alloc <<= 1;
1784 	if (datlen > to_alloc)
1785 		to_alloc = datlen;
1786 	tmp = evbuffer_chain_new(to_alloc);
1787 	if (tmp == NULL)
1788 		goto done;
1789 
1790 	if (remain) {
1791 		memcpy(chain->buffer + chain->misalign + chain->off,
1792 		    data, remain);
1793 		chain->off += remain;
1794 		buf->total_len += remain;
1795 		buf->n_add_for_cb += remain;
1796 	}
1797 
1798 	data += remain;
1799 	datlen -= remain;
1800 
1801 	memcpy(tmp->buffer, data, datlen);
1802 	tmp->off = datlen;
1803 	evbuffer_chain_insert(buf, tmp);
1804 	buf->n_add_for_cb += datlen;
1805 
1806 out:
1807 	evbuffer_invoke_callbacks_(buf);
1808 	result = 0;
1809 done:
1810 	EVBUFFER_UNLOCK(buf);
1811 	return result;
1812 }
1813 
1814 int
1815 evbuffer_prepend(struct evbuffer *buf, const void *data, size_t datlen)
1816 {
1817 	struct evbuffer_chain *chain, *tmp;
1818 	int result = -1;
1819 
1820 	EVBUFFER_LOCK(buf);
1821 
1822 	if (buf->freeze_start) {
1823 		goto done;
1824 	}
1825 	if (datlen > EV_SIZE_MAX - buf->total_len) {
1826 		goto done;
1827 	}
1828 
1829 	chain = buf->first;
1830 
1831 	if (chain == NULL) {
1832 		chain = evbuffer_chain_new(datlen);
1833 		if (!chain)
1834 			goto done;
1835 		evbuffer_chain_insert(buf, chain);
1836 	}
1837 
1838 	/* we cannot touch immutable buffers */
1839 	if ((chain->flags & EVBUFFER_IMMUTABLE) == 0) {
1840 		/* Always true for mutable buffers */
1841 		EVUTIL_ASSERT(chain->misalign >= 0 &&
1842 		    (ev_uint64_t)chain->misalign <= EVBUFFER_CHAIN_MAX);
1843 
1844 		/* If this chain is empty, we can treat it as
1845 		 * 'empty at the beginning' rather than 'empty at the end' */
1846 		if (chain->off == 0)
1847 			chain->misalign = chain->buffer_len;
1848 
1849 		if ((size_t)chain->misalign >= datlen) {
1850 			/* we have enough space to fit everything */
1851 			memcpy(chain->buffer + chain->misalign - datlen,
1852 			    data, datlen);
1853 			chain->off += datlen;
1854 			chain->misalign -= datlen;
1855 			buf->total_len += datlen;
1856 			buf->n_add_for_cb += datlen;
1857 			goto out;
1858 		} else if (chain->misalign) {
1859 			/* we can only fit some of the data. */
1860 			memcpy(chain->buffer,
1861 			    (char*)data + datlen - chain->misalign,
1862 			    (size_t)chain->misalign);
1863 			chain->off += (size_t)chain->misalign;
1864 			buf->total_len += (size_t)chain->misalign;
1865 			buf->n_add_for_cb += (size_t)chain->misalign;
1866 			datlen -= (size_t)chain->misalign;
1867 			chain->misalign = 0;
1868 		}
1869 	}
1870 
1871 	/* we need to add another chain */
1872 	if ((tmp = evbuffer_chain_new(datlen)) == NULL)
1873 		goto done;
1874 	buf->first = tmp;
1875 	if (buf->last_with_datap == &buf->first)
1876 		buf->last_with_datap = &tmp->next;
1877 
1878 	tmp->next = chain;
1879 
1880 	tmp->off = datlen;
1881 	EVUTIL_ASSERT(datlen <= tmp->buffer_len);
1882 	tmp->misalign = tmp->buffer_len - datlen;
1883 
1884 	memcpy(tmp->buffer + tmp->misalign, data, datlen);
1885 	buf->total_len += datlen;
1886 	buf->n_add_for_cb += (size_t)chain->misalign;
1887 
1888 out:
1889 	evbuffer_invoke_callbacks_(buf);
1890 	result = 0;
1891 done:
1892 	EVBUFFER_UNLOCK(buf);
1893 	return result;
1894 }
1895 
1896 /** Helper: realigns the memory in chain->buffer so that misalign is 0. */
1897 static void
1898 evbuffer_chain_align(struct evbuffer_chain *chain)
1899 {
1900 	EVUTIL_ASSERT(!(chain->flags & EVBUFFER_IMMUTABLE));
1901 	EVUTIL_ASSERT(!(chain->flags & EVBUFFER_MEM_PINNED_ANY));
1902 	memmove(chain->buffer, chain->buffer + chain->misalign, chain->off);
1903 	chain->misalign = 0;
1904 }
1905 
1906 #define MAX_TO_COPY_IN_EXPAND 4096
1907 #define MAX_TO_REALIGN_IN_EXPAND 2048
1908 
1909 /** Helper: return true iff we should realign chain to fit datalen bytes of
1910     data in it. */
1911 static int
1912 evbuffer_chain_should_realign(struct evbuffer_chain *chain,
1913     size_t datlen)
1914 {
1915 	return chain->buffer_len - chain->off >= datlen &&
1916 	    (chain->off < chain->buffer_len / 2) &&
1917 	    (chain->off <= MAX_TO_REALIGN_IN_EXPAND);
1918 }
1919 
1920 /* Expands the available space in the event buffer to at least datlen, all in
1921  * a single chunk.  Return that chunk. */
1922 static struct evbuffer_chain *
1923 evbuffer_expand_singlechain(struct evbuffer *buf, size_t datlen)
1924 {
1925 	struct evbuffer_chain *chain, **chainp;
1926 	struct evbuffer_chain *result = NULL;
1927 	ASSERT_EVBUFFER_LOCKED(buf);
1928 
1929 	chainp = buf->last_with_datap;
1930 
1931 	/* XXX If *chainp is no longer writeable, but has enough space in its
1932 	 * misalign, this might be a bad idea: we could still use *chainp, not
1933 	 * (*chainp)->next. */
1934 	if (*chainp && CHAIN_SPACE_LEN(*chainp) == 0)
1935 		chainp = &(*chainp)->next;
1936 
1937 	/* 'chain' now points to the first chain with writable space (if any)
1938 	 * We will either use it, realign it, replace it, or resize it. */
1939 	chain = *chainp;
1940 
1941 	if (chain == NULL ||
1942 	    (chain->flags & (EVBUFFER_IMMUTABLE|EVBUFFER_MEM_PINNED_ANY))) {
1943 		/* We can't use the last_with_data chain at all.  Just add a
1944 		 * new one that's big enough. */
1945 		goto insert_new;
1946 	}
1947 
1948 	/* If we can fit all the data, then we don't have to do anything */
1949 	if (CHAIN_SPACE_LEN(chain) >= datlen) {
1950 		result = chain;
1951 		goto ok;
1952 	}
1953 
1954 	/* If the chain is completely empty, just replace it by adding a new
1955 	 * empty chain. */
1956 	if (chain->off == 0) {
1957 		goto insert_new;
1958 	}
1959 
1960 	/* If the misalignment plus the remaining space fulfills our data
1961 	 * needs, we could just force an alignment to happen.  Afterwards, we
1962 	 * have enough space.  But only do this if we're saving a lot of space
1963 	 * and not moving too much data.  Otherwise the space savings are
1964 	 * probably offset by the time lost in copying.
1965 	 */
1966 	if (evbuffer_chain_should_realign(chain, datlen)) {
1967 		evbuffer_chain_align(chain);
1968 		result = chain;
1969 		goto ok;
1970 	}
1971 
1972 	/* At this point, we can either resize the last chunk with space in
1973 	 * it, use the next chunk after it, or   If we add a new chunk, we waste
1974 	 * CHAIN_SPACE_LEN(chain) bytes in the former last chunk.  If we
1975 	 * resize, we have to copy chain->off bytes.
1976 	 */
1977 
1978 	/* Would expanding this chunk be affordable and worthwhile? */
1979 	if (CHAIN_SPACE_LEN(chain) < chain->buffer_len / 8 ||
1980 	    chain->off > MAX_TO_COPY_IN_EXPAND ||
1981 	    (datlen < EVBUFFER_CHAIN_MAX &&
1982 		EVBUFFER_CHAIN_MAX - datlen >= chain->off)) {
1983 		/* It's not worth resizing this chain. Can the next one be
1984 		 * used? */
1985 		if (chain->next && CHAIN_SPACE_LEN(chain->next) >= datlen) {
1986 			/* Yes, we can just use the next chain (which should
1987 			 * be empty. */
1988 			result = chain->next;
1989 			goto ok;
1990 		} else {
1991 			/* No; append a new chain (which will free all
1992 			 * terminal empty chains.) */
1993 			goto insert_new;
1994 		}
1995 	} else {
1996 		/* Okay, we're going to try to resize this chain: Not doing so
1997 		 * would waste at least 1/8 of its current allocation, and we
1998 		 * can do so without having to copy more than
1999 		 * MAX_TO_COPY_IN_EXPAND bytes. */
2000 		/* figure out how much space we need */
2001 		size_t length = chain->off + datlen;
2002 		struct evbuffer_chain *tmp = evbuffer_chain_new(length);
2003 		if (tmp == NULL)
2004 			goto err;
2005 
2006 		/* copy the data over that we had so far */
2007 		tmp->off = chain->off;
2008 		memcpy(tmp->buffer, chain->buffer + chain->misalign,
2009 		    chain->off);
2010 		/* fix up the list */
2011 		EVUTIL_ASSERT(*chainp == chain);
2012 		result = *chainp = tmp;
2013 
2014 		if (buf->last == chain)
2015 			buf->last = tmp;
2016 
2017 		tmp->next = chain->next;
2018 		evbuffer_chain_free(chain);
2019 		goto ok;
2020 	}
2021 
2022 insert_new:
2023 	result = evbuffer_chain_insert_new(buf, datlen);
2024 	if (!result)
2025 		goto err;
2026 ok:
2027 	EVUTIL_ASSERT(result);
2028 	EVUTIL_ASSERT(CHAIN_SPACE_LEN(result) >= datlen);
2029 err:
2030 	return result;
2031 }
2032 
2033 /* Make sure that datlen bytes are available for writing in the last n
2034  * chains.  Never copies or moves data. */
2035 int
2036 evbuffer_expand_fast_(struct evbuffer *buf, size_t datlen, int n)
2037 {
2038 	struct evbuffer_chain *chain = buf->last, *tmp, *next;
2039 	size_t avail;
2040 	int used;
2041 
2042 	ASSERT_EVBUFFER_LOCKED(buf);
2043 	EVUTIL_ASSERT(n >= 2);
2044 
2045 	if (chain == NULL || (chain->flags & EVBUFFER_IMMUTABLE)) {
2046 		/* There is no last chunk, or we can't touch the last chunk.
2047 		 * Just add a new chunk. */
2048 		chain = evbuffer_chain_new(datlen);
2049 		if (chain == NULL)
2050 			return (-1);
2051 
2052 		evbuffer_chain_insert(buf, chain);
2053 		return (0);
2054 	}
2055 
2056 	used = 0; /* number of chains we're using space in. */
2057 	avail = 0; /* how much space they have. */
2058 	/* How many bytes can we stick at the end of buffer as it is?  Iterate
2059 	 * over the chains at the end of the buffer, tring to see how much
2060 	 * space we have in the first n. */
2061 	for (chain = *buf->last_with_datap; chain; chain = chain->next) {
2062 		if (chain->off) {
2063 			size_t space = (size_t) CHAIN_SPACE_LEN(chain);
2064 			EVUTIL_ASSERT(chain == *buf->last_with_datap);
2065 			if (space) {
2066 				avail += space;
2067 				++used;
2068 			}
2069 		} else {
2070 			/* No data in chain; realign it. */
2071 			chain->misalign = 0;
2072 			avail += chain->buffer_len;
2073 			++used;
2074 		}
2075 		if (avail >= datlen) {
2076 			/* There is already enough space.  Just return */
2077 			return (0);
2078 		}
2079 		if (used == n)
2080 			break;
2081 	}
2082 
2083 	/* There wasn't enough space in the first n chains with space in
2084 	 * them. Either add a new chain with enough space, or replace all
2085 	 * empty chains with one that has enough space, depending on n. */
2086 	if (used < n) {
2087 		/* The loop ran off the end of the chains before it hit n
2088 		 * chains; we can add another. */
2089 		EVUTIL_ASSERT(chain == NULL);
2090 
2091 		tmp = evbuffer_chain_new(datlen - avail);
2092 		if (tmp == NULL)
2093 			return (-1);
2094 
2095 		buf->last->next = tmp;
2096 		buf->last = tmp;
2097 		/* (we would only set last_with_data if we added the first
2098 		 * chain. But if the buffer had no chains, we would have
2099 		 * just allocated a new chain earlier) */
2100 		return (0);
2101 	} else {
2102 		/* Nuke _all_ the empty chains. */
2103 		int rmv_all = 0; /* True iff we removed last_with_data. */
2104 		chain = *buf->last_with_datap;
2105 		if (!chain->off) {
2106 			EVUTIL_ASSERT(chain == buf->first);
2107 			rmv_all = 1;
2108 			avail = 0;
2109 		} else {
2110 			/* can't overflow, since only mutable chains have
2111 			 * huge misaligns. */
2112 			avail = (size_t) CHAIN_SPACE_LEN(chain);
2113 			chain = chain->next;
2114 		}
2115 
2116 
2117 		for (; chain; chain = next) {
2118 			next = chain->next;
2119 			EVUTIL_ASSERT(chain->off == 0);
2120 			evbuffer_chain_free(chain);
2121 		}
2122 		EVUTIL_ASSERT(datlen >= avail);
2123 		tmp = evbuffer_chain_new(datlen - avail);
2124 		if (tmp == NULL) {
2125 			if (rmv_all) {
2126 				ZERO_CHAIN(buf);
2127 			} else {
2128 				buf->last = *buf->last_with_datap;
2129 				(*buf->last_with_datap)->next = NULL;
2130 			}
2131 			return (-1);
2132 		}
2133 
2134 		if (rmv_all) {
2135 			buf->first = buf->last = tmp;
2136 			buf->last_with_datap = &buf->first;
2137 		} else {
2138 			(*buf->last_with_datap)->next = tmp;
2139 			buf->last = tmp;
2140 		}
2141 		return (0);
2142 	}
2143 }
2144 
2145 int
2146 evbuffer_expand(struct evbuffer *buf, size_t datlen)
2147 {
2148 	struct evbuffer_chain *chain;
2149 
2150 	EVBUFFER_LOCK(buf);
2151 	chain = evbuffer_expand_singlechain(buf, datlen);
2152 	EVBUFFER_UNLOCK(buf);
2153 	return chain ? 0 : -1;
2154 }
2155 
2156 /*
2157  * Reads data from a file descriptor into a buffer.
2158  */
2159 
2160 #if defined(EVENT__HAVE_SYS_UIO_H) || defined(_WIN32)
2161 #define USE_IOVEC_IMPL
2162 #endif
2163 
2164 #ifdef USE_IOVEC_IMPL
2165 
2166 #ifdef EVENT__HAVE_SYS_UIO_H
2167 /* number of iovec we use for writev, fragmentation is going to determine
2168  * how much we end up writing */
2169 
2170 #define DEFAULT_WRITE_IOVEC 128
2171 
2172 #if defined(UIO_MAXIOV) && UIO_MAXIOV < DEFAULT_WRITE_IOVEC
2173 #define NUM_WRITE_IOVEC UIO_MAXIOV
2174 #elif defined(IOV_MAX) && IOV_MAX < DEFAULT_WRITE_IOVEC
2175 #define NUM_WRITE_IOVEC IOV_MAX
2176 #else
2177 #define NUM_WRITE_IOVEC DEFAULT_WRITE_IOVEC
2178 #endif
2179 
2180 #define IOV_TYPE struct iovec
2181 #define IOV_PTR_FIELD iov_base
2182 #define IOV_LEN_FIELD iov_len
2183 #define IOV_LEN_TYPE size_t
2184 #else
2185 #define NUM_WRITE_IOVEC 16
2186 #define IOV_TYPE WSABUF
2187 #define IOV_PTR_FIELD buf
2188 #define IOV_LEN_FIELD len
2189 #define IOV_LEN_TYPE unsigned long
2190 #endif
2191 #endif
2192 #define NUM_READ_IOVEC 4
2193 
2194 #define EVBUFFER_MAX_READ	4096
2195 
2196 /** Helper function to figure out which space to use for reading data into
2197     an evbuffer.  Internal use only.
2198 
2199     @param buf The buffer to read into
2200     @param howmuch How much we want to read.
2201     @param vecs An array of two or more iovecs or WSABUFs.
2202     @param n_vecs_avail The length of vecs
2203     @param chainp A pointer to a variable to hold the first chain we're
2204       reading into.
2205     @param exact Boolean: if true, we do not provide more than 'howmuch'
2206       space in the vectors, even if more space is available.
2207     @return The number of buffers we're using.
2208  */
2209 int
2210 evbuffer_read_setup_vecs_(struct evbuffer *buf, ev_ssize_t howmuch,
2211     struct evbuffer_iovec *vecs, int n_vecs_avail,
2212     struct evbuffer_chain ***chainp, int exact)
2213 {
2214 	struct evbuffer_chain *chain;
2215 	struct evbuffer_chain **firstchainp;
2216 	size_t so_far;
2217 	int i;
2218 	ASSERT_EVBUFFER_LOCKED(buf);
2219 
2220 	if (howmuch < 0)
2221 		return -1;
2222 
2223 	so_far = 0;
2224 	/* Let firstchain be the first chain with any space on it */
2225 	firstchainp = buf->last_with_datap;
2226 	if (CHAIN_SPACE_LEN(*firstchainp) == 0) {
2227 		firstchainp = &(*firstchainp)->next;
2228 	}
2229 
2230 	chain = *firstchainp;
2231 	for (i = 0; i < n_vecs_avail && so_far < (size_t)howmuch; ++i) {
2232 		size_t avail = (size_t) CHAIN_SPACE_LEN(chain);
2233 		if (avail > (howmuch - so_far) && exact)
2234 			avail = howmuch - so_far;
2235 		vecs[i].iov_base = CHAIN_SPACE_PTR(chain);
2236 		vecs[i].iov_len = avail;
2237 		so_far += avail;
2238 		chain = chain->next;
2239 	}
2240 
2241 	*chainp = firstchainp;
2242 	return i;
2243 }
2244 
2245 static int
2246 get_n_bytes_readable_on_socket(evutil_socket_t fd)
2247 {
2248 #if defined(FIONREAD) && defined(_WIN32)
2249 	unsigned long lng = EVBUFFER_MAX_READ;
2250 	if (ioctlsocket(fd, FIONREAD, &lng) < 0)
2251 		return -1;
2252 	/* Can overflow, but mostly harmlessly. XXXX */
2253 	return (int)lng;
2254 #elif defined(FIONREAD)
2255 	int n = EVBUFFER_MAX_READ;
2256 	if (ioctl(fd, FIONREAD, &n) < 0)
2257 		return -1;
2258 	return n;
2259 #else
2260 	return EVBUFFER_MAX_READ;
2261 #endif
2262 }
2263 
2264 /* TODO(niels): should this function return ev_ssize_t and take ev_ssize_t
2265  * as howmuch? */
2266 int
2267 evbuffer_read(struct evbuffer *buf, evutil_socket_t fd, int howmuch)
2268 {
2269 	struct evbuffer_chain **chainp;
2270 	int n;
2271 	int result;
2272 
2273 #ifdef USE_IOVEC_IMPL
2274 	int nvecs, i, remaining;
2275 #else
2276 	struct evbuffer_chain *chain;
2277 	unsigned char *p;
2278 #endif
2279 
2280 	EVBUFFER_LOCK(buf);
2281 
2282 	if (buf->freeze_end) {
2283 		result = -1;
2284 		goto done;
2285 	}
2286 
2287 	n = get_n_bytes_readable_on_socket(fd);
2288 	if (n <= 0 || n > EVBUFFER_MAX_READ)
2289 		n = EVBUFFER_MAX_READ;
2290 	if (howmuch < 0 || howmuch > n)
2291 		howmuch = n;
2292 
2293 #ifdef USE_IOVEC_IMPL
2294 	/* Since we can use iovecs, we're willing to use the last
2295 	 * NUM_READ_IOVEC chains. */
2296 	if (evbuffer_expand_fast_(buf, howmuch, NUM_READ_IOVEC) == -1) {
2297 		result = -1;
2298 		goto done;
2299 	} else {
2300 		IOV_TYPE vecs[NUM_READ_IOVEC];
2301 #ifdef EVBUFFER_IOVEC_IS_NATIVE_
2302 		nvecs = evbuffer_read_setup_vecs_(buf, howmuch, vecs,
2303 		    NUM_READ_IOVEC, &chainp, 1);
2304 #else
2305 		/* We aren't using the native struct iovec.  Therefore,
2306 		   we are on win32. */
2307 		struct evbuffer_iovec ev_vecs[NUM_READ_IOVEC];
2308 		nvecs = evbuffer_read_setup_vecs_(buf, howmuch, ev_vecs, 2,
2309 		    &chainp, 1);
2310 
2311 		for (i=0; i < nvecs; ++i)
2312 			WSABUF_FROM_EVBUFFER_IOV(&vecs[i], &ev_vecs[i]);
2313 #endif
2314 
2315 #ifdef _WIN32
2316 		{
2317 			DWORD bytesRead;
2318 			DWORD flags=0;
2319 			if (WSARecv(fd, vecs, nvecs, &bytesRead, &flags, NULL, NULL)) {
2320 				/* The read failed. It might be a close,
2321 				 * or it might be an error. */
2322 				if (WSAGetLastError() == WSAECONNABORTED)
2323 					n = 0;
2324 				else
2325 					n = -1;
2326 			} else
2327 				n = bytesRead;
2328 		}
2329 #else
2330 		n = readv(fd, vecs, nvecs);
2331 #endif
2332 	}
2333 
2334 #else /*!USE_IOVEC_IMPL*/
2335 	/* If we don't have FIONREAD, we might waste some space here */
2336 	/* XXX we _will_ waste some space here if there is any space left
2337 	 * over on buf->last. */
2338 	if ((chain = evbuffer_expand_singlechain(buf, howmuch)) == NULL) {
2339 		result = -1;
2340 		goto done;
2341 	}
2342 
2343 	/* We can append new data at this point */
2344 	p = chain->buffer + chain->misalign + chain->off;
2345 
2346 #ifndef _WIN32
2347 	n = read(fd, p, howmuch);
2348 #else
2349 	n = recv(fd, p, howmuch, 0);
2350 #endif
2351 #endif /* USE_IOVEC_IMPL */
2352 
2353 	if (n == -1) {
2354 		result = -1;
2355 		goto done;
2356 	}
2357 	if (n == 0) {
2358 		result = 0;
2359 		goto done;
2360 	}
2361 
2362 #ifdef USE_IOVEC_IMPL
2363 	remaining = n;
2364 	for (i=0; i < nvecs; ++i) {
2365 		/* can't overflow, since only mutable chains have
2366 		 * huge misaligns. */
2367 		size_t space = (size_t) CHAIN_SPACE_LEN(*chainp);
2368 		/* XXXX This is a kludge that can waste space in perverse
2369 		 * situations. */
2370 		if (space > EVBUFFER_CHAIN_MAX)
2371 			space = EVBUFFER_CHAIN_MAX;
2372 		if ((ev_ssize_t)space < remaining) {
2373 			(*chainp)->off += space;
2374 			remaining -= (int)space;
2375 		} else {
2376 			(*chainp)->off += remaining;
2377 			buf->last_with_datap = chainp;
2378 			break;
2379 		}
2380 		chainp = &(*chainp)->next;
2381 	}
2382 #else
2383 	chain->off += n;
2384 	advance_last_with_data(buf);
2385 #endif
2386 	buf->total_len += n;
2387 	buf->n_add_for_cb += n;
2388 
2389 	/* Tell someone about changes in this buffer */
2390 	evbuffer_invoke_callbacks_(buf);
2391 	result = n;
2392 done:
2393 	EVBUFFER_UNLOCK(buf);
2394 	return result;
2395 }
2396 
2397 #ifdef USE_IOVEC_IMPL
2398 static inline int
2399 evbuffer_write_iovec(struct evbuffer *buffer, evutil_socket_t fd,
2400     ev_ssize_t howmuch)
2401 {
2402 	IOV_TYPE iov[NUM_WRITE_IOVEC];
2403 	struct evbuffer_chain *chain = buffer->first;
2404 	int n, i = 0;
2405 
2406 	if (howmuch < 0)
2407 		return -1;
2408 
2409 	ASSERT_EVBUFFER_LOCKED(buffer);
2410 	/* XXX make this top out at some maximal data length?  if the
2411 	 * buffer has (say) 1MB in it, split over 128 chains, there's
2412 	 * no way it all gets written in one go. */
2413 	while (chain != NULL && i < NUM_WRITE_IOVEC && howmuch) {
2414 #ifdef USE_SENDFILE
2415 		/* we cannot write the file info via writev */
2416 		if (chain->flags & EVBUFFER_SENDFILE)
2417 			break;
2418 #endif
2419 		iov[i].IOV_PTR_FIELD = (void *) (chain->buffer + chain->misalign);
2420 		if ((size_t)howmuch >= chain->off) {
2421 			/* XXXcould be problematic when windows supports mmap*/
2422 			iov[i++].IOV_LEN_FIELD = (IOV_LEN_TYPE)chain->off;
2423 			howmuch -= chain->off;
2424 		} else {
2425 			/* XXXcould be problematic when windows supports mmap*/
2426 			iov[i++].IOV_LEN_FIELD = (IOV_LEN_TYPE)howmuch;
2427 			break;
2428 		}
2429 		chain = chain->next;
2430 	}
2431 	if (! i)
2432 		return 0;
2433 
2434 #ifdef _WIN32
2435 	{
2436 		DWORD bytesSent;
2437 		if (WSASend(fd, iov, i, &bytesSent, 0, NULL, NULL))
2438 			n = -1;
2439 		else
2440 			n = bytesSent;
2441 	}
2442 #else
2443 	n = writev(fd, iov, i);
2444 #endif
2445 	return (n);
2446 }
2447 #endif
2448 
2449 #ifdef USE_SENDFILE
2450 static inline int
2451 evbuffer_write_sendfile(struct evbuffer *buffer, evutil_socket_t dest_fd,
2452     ev_ssize_t howmuch)
2453 {
2454 	struct evbuffer_chain *chain = buffer->first;
2455 	struct evbuffer_chain_file_segment *info =
2456 	    EVBUFFER_CHAIN_EXTRA(struct evbuffer_chain_file_segment,
2457 		chain);
2458 	const int source_fd = info->segment->fd;
2459 #if defined(SENDFILE_IS_MACOSX) || defined(SENDFILE_IS_FREEBSD)
2460 	int res;
2461 	ev_off_t len = chain->off;
2462 #elif defined(SENDFILE_IS_LINUX) || defined(SENDFILE_IS_SOLARIS)
2463 	ev_ssize_t res;
2464 	ev_off_t offset = chain->misalign;
2465 #endif
2466 
2467 	ASSERT_EVBUFFER_LOCKED(buffer);
2468 
2469 #if defined(SENDFILE_IS_MACOSX)
2470 	res = sendfile(source_fd, dest_fd, chain->misalign, &len, NULL, 0);
2471 	if (res == -1 && !EVUTIL_ERR_RW_RETRIABLE(errno))
2472 		return (-1);
2473 
2474 	return (len);
2475 #elif defined(SENDFILE_IS_FREEBSD)
2476 	res = sendfile(source_fd, dest_fd, chain->misalign, chain->off, NULL, &len, 0);
2477 	if (res == -1 && !EVUTIL_ERR_RW_RETRIABLE(errno))
2478 		return (-1);
2479 
2480 	return (len);
2481 #elif defined(SENDFILE_IS_LINUX)
2482 	/* TODO(niels): implement splice */
2483 	res = sendfile(dest_fd, source_fd, &offset, chain->off);
2484 	if (res == -1 && EVUTIL_ERR_RW_RETRIABLE(errno)) {
2485 		/* if this is EAGAIN or EINTR return 0; otherwise, -1 */
2486 		return (0);
2487 	}
2488 	return (res);
2489 #elif defined(SENDFILE_IS_SOLARIS)
2490 	{
2491 		const off_t offset_orig = offset;
2492 		res = sendfile(dest_fd, source_fd, &offset, chain->off);
2493 		if (res == -1 && EVUTIL_ERR_RW_RETRIABLE(errno)) {
2494 			if (offset - offset_orig)
2495 				return offset - offset_orig;
2496 			/* if this is EAGAIN or EINTR and no bytes were
2497 			 * written, return 0 */
2498 			return (0);
2499 		}
2500 		return (res);
2501 	}
2502 #endif
2503 }
2504 #endif
2505 
2506 int
2507 evbuffer_write_atmost(struct evbuffer *buffer, evutil_socket_t fd,
2508     ev_ssize_t howmuch)
2509 {
2510 	int n = -1;
2511 
2512 	EVBUFFER_LOCK(buffer);
2513 
2514 	if (buffer->freeze_start) {
2515 		goto done;
2516 	}
2517 
2518 	if (howmuch < 0 || (size_t)howmuch > buffer->total_len)
2519 		howmuch = buffer->total_len;
2520 
2521 	if (howmuch > 0) {
2522 #ifdef USE_SENDFILE
2523 		struct evbuffer_chain *chain = buffer->first;
2524 		if (chain != NULL && (chain->flags & EVBUFFER_SENDFILE))
2525 			n = evbuffer_write_sendfile(buffer, fd, howmuch);
2526 		else {
2527 #endif
2528 #ifdef USE_IOVEC_IMPL
2529 		n = evbuffer_write_iovec(buffer, fd, howmuch);
2530 #elif defined(_WIN32)
2531 		/* XXX(nickm) Don't disable this code until we know if
2532 		 * the WSARecv code above works. */
2533 		void *p = evbuffer_pullup(buffer, howmuch);
2534 		EVUTIL_ASSERT(p || !howmuch);
2535 		n = send(fd, p, howmuch, 0);
2536 #else
2537 		void *p = evbuffer_pullup(buffer, howmuch);
2538 		EVUTIL_ASSERT(p || !howmuch);
2539 		n = write(fd, p, howmuch);
2540 #endif
2541 #ifdef USE_SENDFILE
2542 		}
2543 #endif
2544 	}
2545 
2546 	if (n > 0)
2547 		evbuffer_drain(buffer, n);
2548 
2549 done:
2550 	EVBUFFER_UNLOCK(buffer);
2551 	return (n);
2552 }
2553 
2554 int
2555 evbuffer_write(struct evbuffer *buffer, evutil_socket_t fd)
2556 {
2557 	return evbuffer_write_atmost(buffer, fd, -1);
2558 }
2559 
2560 unsigned char *
2561 evbuffer_find(struct evbuffer *buffer, const unsigned char *what, size_t len)
2562 {
2563 	unsigned char *search;
2564 	struct evbuffer_ptr ptr;
2565 
2566 	EVBUFFER_LOCK(buffer);
2567 
2568 	ptr = evbuffer_search(buffer, (const char *)what, len, NULL);
2569 	if (ptr.pos < 0) {
2570 		search = NULL;
2571 	} else {
2572 		search = evbuffer_pullup(buffer, ptr.pos + len);
2573 		if (search)
2574 			search += ptr.pos;
2575 	}
2576 	EVBUFFER_UNLOCK(buffer);
2577 	return search;
2578 }
2579 
2580 /* Subract <b>howfar</b> from the position of <b>pos</b> within
2581  * <b>buf</b>. Returns 0 on success, -1 on failure.
2582  *
2583  * This isn't exposed yet, because of potential inefficiency issues.
2584  * Maybe it should be. */
2585 static int
2586 evbuffer_ptr_subtract(struct evbuffer *buf, struct evbuffer_ptr *pos,
2587     size_t howfar)
2588 {
2589 	if (pos->pos < 0)
2590 		return -1;
2591 	if (howfar > (size_t)pos->pos)
2592 		return -1;
2593 	if (pos->internal_.chain && howfar <= pos->internal_.pos_in_chain) {
2594 		pos->internal_.pos_in_chain -= howfar;
2595 		pos->pos -= howfar;
2596 		return 0;
2597 	} else {
2598 		const size_t newpos = pos->pos - howfar;
2599 		/* Here's the inefficient part: it walks over the
2600 		 * chains until we hit newpos. */
2601 		return evbuffer_ptr_set(buf, pos, newpos, EVBUFFER_PTR_SET);
2602 	}
2603 }
2604 
2605 int
2606 evbuffer_ptr_set(struct evbuffer *buf, struct evbuffer_ptr *pos,
2607     size_t position, enum evbuffer_ptr_how how)
2608 {
2609 	size_t left = position;
2610 	struct evbuffer_chain *chain = NULL;
2611 	int result = 0;
2612 
2613 	EVBUFFER_LOCK(buf);
2614 
2615 	switch (how) {
2616 	case EVBUFFER_PTR_SET:
2617 		chain = buf->first;
2618 		pos->pos = position;
2619 		position = 0;
2620 		break;
2621 	case EVBUFFER_PTR_ADD:
2622 		/* this avoids iterating over all previous chains if
2623 		   we just want to advance the position */
2624 		if (pos->pos < 0 || EV_SIZE_MAX - position < (size_t)pos->pos) {
2625 			EVBUFFER_UNLOCK(buf);
2626 			return -1;
2627 		}
2628 		chain = pos->internal_.chain;
2629 		pos->pos += position;
2630 		position = pos->internal_.pos_in_chain;
2631 		break;
2632 	}
2633 
2634 	EVUTIL_ASSERT(EV_SIZE_MAX - left >= position);
2635 	while (chain && position + left >= chain->off) {
2636 		left -= chain->off - position;
2637 		chain = chain->next;
2638 		position = 0;
2639 	}
2640 	if (chain) {
2641 		pos->internal_.chain = chain;
2642 		pos->internal_.pos_in_chain = position + left;
2643 	} else if (left == 0) {
2644 		/* The first byte in the (nonexistent) chain after the last chain */
2645 		pos->internal_.chain = NULL;
2646 		pos->internal_.pos_in_chain = 0;
2647 	} else {
2648 		PTR_NOT_FOUND(pos);
2649 		result = -1;
2650 	}
2651 
2652 	EVBUFFER_UNLOCK(buf);
2653 
2654 	return result;
2655 }
2656 
2657 /**
2658    Compare the bytes in buf at position pos to the len bytes in mem.  Return
2659    less than 0, 0, or greater than 0 as memcmp.
2660  */
2661 static int
2662 evbuffer_ptr_memcmp(const struct evbuffer *buf, const struct evbuffer_ptr *pos,
2663     const char *mem, size_t len)
2664 {
2665 	struct evbuffer_chain *chain;
2666 	size_t position;
2667 	int r;
2668 
2669 	ASSERT_EVBUFFER_LOCKED(buf);
2670 
2671 	if (pos->pos < 0 ||
2672 	    EV_SIZE_MAX - len < (size_t)pos->pos ||
2673 	    pos->pos + len > buf->total_len)
2674 		return -1;
2675 
2676 	chain = pos->internal_.chain;
2677 	position = pos->internal_.pos_in_chain;
2678 	while (len && chain) {
2679 		size_t n_comparable;
2680 		if (len + position > chain->off)
2681 			n_comparable = chain->off - position;
2682 		else
2683 			n_comparable = len;
2684 		r = memcmp(chain->buffer + chain->misalign + position, mem,
2685 		    n_comparable);
2686 		if (r)
2687 			return r;
2688 		mem += n_comparable;
2689 		len -= n_comparable;
2690 		position = 0;
2691 		chain = chain->next;
2692 	}
2693 
2694 	return 0;
2695 }
2696 
2697 struct evbuffer_ptr
2698 evbuffer_search(struct evbuffer *buffer, const char *what, size_t len, const struct evbuffer_ptr *start)
2699 {
2700 	return evbuffer_search_range(buffer, what, len, start, NULL);
2701 }
2702 
2703 struct evbuffer_ptr
2704 evbuffer_search_range(struct evbuffer *buffer, const char *what, size_t len, const struct evbuffer_ptr *start, const struct evbuffer_ptr *end)
2705 {
2706 	struct evbuffer_ptr pos;
2707 	struct evbuffer_chain *chain, *last_chain = NULL;
2708 	const unsigned char *p;
2709 	char first;
2710 
2711 	EVBUFFER_LOCK(buffer);
2712 
2713 	if (start) {
2714 		memcpy(&pos, start, sizeof(pos));
2715 		chain = pos.internal_.chain;
2716 	} else {
2717 		pos.pos = 0;
2718 		chain = pos.internal_.chain = buffer->first;
2719 		pos.internal_.pos_in_chain = 0;
2720 	}
2721 
2722 	if (end)
2723 		last_chain = end->internal_.chain;
2724 
2725 	if (!len || len > EV_SSIZE_MAX)
2726 		goto done;
2727 
2728 	first = what[0];
2729 
2730 	while (chain) {
2731 		const unsigned char *start_at =
2732 		    chain->buffer + chain->misalign +
2733 		    pos.internal_.pos_in_chain;
2734 		p = memchr(start_at, first,
2735 		    chain->off - pos.internal_.pos_in_chain);
2736 		if (p) {
2737 			pos.pos += p - start_at;
2738 			pos.internal_.pos_in_chain += p - start_at;
2739 			if (!evbuffer_ptr_memcmp(buffer, &pos, what, len)) {
2740 				if (end && pos.pos + (ev_ssize_t)len > end->pos)
2741 					goto not_found;
2742 				else
2743 					goto done;
2744 			}
2745 			++pos.pos;
2746 			++pos.internal_.pos_in_chain;
2747 			if (pos.internal_.pos_in_chain == chain->off) {
2748 				chain = pos.internal_.chain = chain->next;
2749 				pos.internal_.pos_in_chain = 0;
2750 			}
2751 		} else {
2752 			if (chain == last_chain)
2753 				goto not_found;
2754 			pos.pos += chain->off - pos.internal_.pos_in_chain;
2755 			chain = pos.internal_.chain = chain->next;
2756 			pos.internal_.pos_in_chain = 0;
2757 		}
2758 	}
2759 
2760 not_found:
2761 	PTR_NOT_FOUND(&pos);
2762 done:
2763 	EVBUFFER_UNLOCK(buffer);
2764 	return pos;
2765 }
2766 
2767 int
2768 evbuffer_peek(struct evbuffer *buffer, ev_ssize_t len,
2769     struct evbuffer_ptr *start_at,
2770     struct evbuffer_iovec *vec, int n_vec)
2771 {
2772 	struct evbuffer_chain *chain;
2773 	int idx = 0;
2774 	ev_ssize_t len_so_far = 0;
2775 
2776 	/* Avoid locking in trivial edge cases */
2777 	if (start_at && start_at->internal_.chain == NULL)
2778 		return 0;
2779 
2780 	EVBUFFER_LOCK(buffer);
2781 
2782 	if (start_at) {
2783 		chain = start_at->internal_.chain;
2784 		len_so_far = chain->off
2785 		    - start_at->internal_.pos_in_chain;
2786 		idx = 1;
2787 		if (n_vec > 0) {
2788 			vec[0].iov_base = chain->buffer + chain->misalign
2789 			    + start_at->internal_.pos_in_chain;
2790 			vec[0].iov_len = len_so_far;
2791 		}
2792 		chain = chain->next;
2793 	} else {
2794 		chain = buffer->first;
2795 	}
2796 
2797 	if (n_vec == 0 && len < 0) {
2798 		/* If no vectors are provided and they asked for "everything",
2799 		 * pretend they asked for the actual available amount. */
2800 		len = buffer->total_len;
2801 		if (start_at) {
2802 			len -= start_at->pos;
2803 		}
2804 	}
2805 
2806 	while (chain) {
2807 		if (len >= 0 && len_so_far >= len)
2808 			break;
2809 		if (idx<n_vec) {
2810 			vec[idx].iov_base = chain->buffer + chain->misalign;
2811 			vec[idx].iov_len = chain->off;
2812 		} else if (len<0) {
2813 			break;
2814 		}
2815 		++idx;
2816 		len_so_far += chain->off;
2817 		chain = chain->next;
2818 	}
2819 
2820 	EVBUFFER_UNLOCK(buffer);
2821 
2822 	return idx;
2823 }
2824 
2825 
2826 int
2827 evbuffer_add_vprintf(struct evbuffer *buf, const char *fmt, va_list ap)
2828 {
2829 	char *buffer;
2830 	size_t space;
2831 	int sz, result = -1;
2832 	va_list aq;
2833 	struct evbuffer_chain *chain;
2834 
2835 
2836 	EVBUFFER_LOCK(buf);
2837 
2838 	if (buf->freeze_end) {
2839 		goto done;
2840 	}
2841 
2842 	/* make sure that at least some space is available */
2843 	if ((chain = evbuffer_expand_singlechain(buf, 64)) == NULL)
2844 		goto done;
2845 
2846 	for (;;) {
2847 #if 0
2848 		size_t used = chain->misalign + chain->off;
2849 		buffer = (char *)chain->buffer + chain->misalign + chain->off;
2850 		EVUTIL_ASSERT(chain->buffer_len >= used);
2851 		space = chain->buffer_len - used;
2852 #endif
2853 		buffer = (char*) CHAIN_SPACE_PTR(chain);
2854 		space = (size_t) CHAIN_SPACE_LEN(chain);
2855 
2856 #ifndef va_copy
2857 #define	va_copy(dst, src)	memcpy(&(dst), &(src), sizeof(va_list))
2858 #endif
2859 		va_copy(aq, ap);
2860 
2861 		sz = evutil_vsnprintf(buffer, space, fmt, aq);
2862 
2863 		va_end(aq);
2864 
2865 		if (sz < 0)
2866 			goto done;
2867 		if (INT_MAX >= EVBUFFER_CHAIN_MAX &&
2868 		    (size_t)sz >= EVBUFFER_CHAIN_MAX)
2869 			goto done;
2870 		if ((size_t)sz < space) {
2871 			chain->off += sz;
2872 			buf->total_len += sz;
2873 			buf->n_add_for_cb += sz;
2874 
2875 			advance_last_with_data(buf);
2876 			evbuffer_invoke_callbacks_(buf);
2877 			result = sz;
2878 			goto done;
2879 		}
2880 		if ((chain = evbuffer_expand_singlechain(buf, sz + 1)) == NULL)
2881 			goto done;
2882 	}
2883 	/* NOTREACHED */
2884 
2885 done:
2886 	EVBUFFER_UNLOCK(buf);
2887 	return result;
2888 }
2889 
2890 int
2891 evbuffer_add_printf(struct evbuffer *buf, const char *fmt, ...)
2892 {
2893 	int res = -1;
2894 	va_list ap;
2895 
2896 	va_start(ap, fmt);
2897 	res = evbuffer_add_vprintf(buf, fmt, ap);
2898 	va_end(ap);
2899 
2900 	return (res);
2901 }
2902 
2903 int
2904 evbuffer_add_reference(struct evbuffer *outbuf,
2905     const void *data, size_t datlen,
2906     evbuffer_ref_cleanup_cb cleanupfn, void *extra)
2907 {
2908 	struct evbuffer_chain *chain;
2909 	struct evbuffer_chain_reference *info;
2910 	int result = -1;
2911 
2912 	chain = evbuffer_chain_new(sizeof(struct evbuffer_chain_reference));
2913 	if (!chain)
2914 		return (-1);
2915 	chain->flags |= EVBUFFER_REFERENCE | EVBUFFER_IMMUTABLE;
2916 	chain->buffer = (unsigned char *)data;
2917 	chain->buffer_len = datlen;
2918 	chain->off = datlen;
2919 
2920 	info = EVBUFFER_CHAIN_EXTRA(struct evbuffer_chain_reference, chain);
2921 	info->cleanupfn = cleanupfn;
2922 	info->extra = extra;
2923 
2924 	EVBUFFER_LOCK(outbuf);
2925 	if (outbuf->freeze_end) {
2926 		/* don't call chain_free; we do not want to actually invoke
2927 		 * the cleanup function */
2928 		mm_free(chain);
2929 		goto done;
2930 	}
2931 	evbuffer_chain_insert(outbuf, chain);
2932 	outbuf->n_add_for_cb += datlen;
2933 
2934 	evbuffer_invoke_callbacks_(outbuf);
2935 
2936 	result = 0;
2937 done:
2938 	EVBUFFER_UNLOCK(outbuf);
2939 
2940 	return result;
2941 }
2942 
2943 /* TODO(niels): we may want to add to automagically convert to mmap, in
2944  * case evbuffer_remove() or evbuffer_pullup() are being used.
2945  */
2946 struct evbuffer_file_segment *
2947 evbuffer_file_segment_new(
2948 	int fd, ev_off_t offset, ev_off_t length, unsigned flags)
2949 {
2950 	struct evbuffer_file_segment *seg =
2951 	    mm_calloc(sizeof(struct evbuffer_file_segment), 1);
2952 	if (!seg)
2953 		return NULL;
2954 	seg->refcnt = 1;
2955 	seg->fd = fd;
2956 	seg->flags = flags;
2957 	seg->file_offset = offset;
2958 	seg->cleanup_cb = NULL;
2959 	seg->cleanup_cb_arg = NULL;
2960 #ifdef _WIN32
2961 #ifndef lseek
2962 #define lseek _lseeki64
2963 #endif
2964 #ifndef fstat
2965 #define fstat _fstat
2966 #endif
2967 #ifndef stat
2968 #define stat _stat
2969 #endif
2970 #endif
2971 	if (length == -1) {
2972 		struct stat st;
2973 		if (fstat(fd, &st) < 0)
2974 			goto err;
2975 		length = st.st_size;
2976 	}
2977 	seg->length = length;
2978 
2979 	if (offset < 0 || length < 0 ||
2980 	    ((ev_uint64_t)length > EVBUFFER_CHAIN_MAX) ||
2981 	    (ev_uint64_t)offset > (ev_uint64_t)(EVBUFFER_CHAIN_MAX - length))
2982 		goto err;
2983 
2984 #if defined(USE_SENDFILE)
2985 	if (!(flags & EVBUF_FS_DISABLE_SENDFILE)) {
2986 		seg->can_sendfile = 1;
2987 		goto done;
2988 	}
2989 #endif
2990 
2991 	if (evbuffer_file_segment_materialize(seg)<0)
2992 		goto err;
2993 
2994 #if defined(USE_SENDFILE)
2995 done:
2996 #endif
2997 	if (!(flags & EVBUF_FS_DISABLE_LOCKING)) {
2998 		EVTHREAD_ALLOC_LOCK(seg->lock, 0);
2999 	}
3000 	return seg;
3001 err:
3002 	mm_free(seg);
3003 	return NULL;
3004 }
3005 
3006 #ifdef EVENT__HAVE_MMAP
3007 static long
3008 get_page_size(void)
3009 {
3010 #ifdef SC_PAGE_SIZE
3011 	return sysconf(SC_PAGE_SIZE);
3012 #elif defined(_SC_PAGE_SIZE)
3013 	return sysconf(_SC_PAGE_SIZE);
3014 #else
3015 	return 1;
3016 #endif
3017 }
3018 #endif
3019 
3020 /* DOCDOC */
3021 /* Requires lock */
3022 static int
3023 evbuffer_file_segment_materialize(struct evbuffer_file_segment *seg)
3024 {
3025 	const unsigned flags = seg->flags;
3026 	const int fd = seg->fd;
3027 	const ev_off_t length = seg->length;
3028 	const ev_off_t offset = seg->file_offset;
3029 
3030 	if (seg->contents)
3031 		return 0; /* already materialized */
3032 
3033 #if defined(EVENT__HAVE_MMAP)
3034 	if (!(flags & EVBUF_FS_DISABLE_MMAP)) {
3035 		off_t offset_rounded = 0, offset_leftover = 0;
3036 		void *mapped;
3037 		if (offset) {
3038 			/* mmap implementations don't generally like us
3039 			 * to have an offset that isn't a round  */
3040 			long page_size = get_page_size();
3041 			if (page_size == -1)
3042 				goto err;
3043 			offset_leftover = offset % page_size;
3044 			offset_rounded = offset - offset_leftover;
3045 		}
3046 		mapped = mmap(NULL, length + offset_leftover,
3047 		    PROT_READ,
3048 #ifdef MAP_NOCACHE
3049 		    MAP_NOCACHE | /* ??? */
3050 #endif
3051 #ifdef MAP_FILE
3052 		    MAP_FILE |
3053 #endif
3054 		    MAP_PRIVATE,
3055 		    fd, offset_rounded);
3056 		if (mapped == MAP_FAILED) {
3057 			event_warn("%s: mmap(%d, %d, %zu) failed",
3058 			    __func__, fd, 0, (size_t)(offset + length));
3059 		} else {
3060 			seg->mapping = mapped;
3061 			seg->contents = (char*)mapped+offset_leftover;
3062 			seg->mmap_offset = 0;
3063 			seg->is_mapping = 1;
3064 			goto done;
3065 		}
3066 	}
3067 #endif
3068 #ifdef _WIN32
3069 	if (!(flags & EVBUF_FS_DISABLE_MMAP)) {
3070 		intptr_t h = _get_osfhandle(fd);
3071 		HANDLE m;
3072 		ev_uint64_t total_size = length+offset;
3073 		if ((HANDLE)h == INVALID_HANDLE_VALUE)
3074 			goto err;
3075 		m = CreateFileMapping((HANDLE)h, NULL, PAGE_READONLY,
3076 		    (total_size >> 32), total_size & 0xfffffffful,
3077 		    NULL);
3078 		if (m != INVALID_HANDLE_VALUE) { /* Does h leak? */
3079 			seg->mapping_handle = m;
3080 			seg->mmap_offset = offset;
3081 			seg->is_mapping = 1;
3082 			goto done;
3083 		}
3084 	}
3085 #endif
3086 	{
3087 		ev_off_t start_pos = lseek(fd, 0, SEEK_CUR), pos;
3088 		ev_off_t read_so_far = 0;
3089 		char *mem;
3090 		int e;
3091 		ev_ssize_t n = 0;
3092 		if (!(mem = mm_malloc(length)))
3093 			goto err;
3094 		if (start_pos < 0) {
3095 			mm_free(mem);
3096 			goto err;
3097 		}
3098 		if (lseek(fd, offset, SEEK_SET) < 0) {
3099 			mm_free(mem);
3100 			goto err;
3101 		}
3102 		while (read_so_far < length) {
3103 			n = read(fd, mem+read_so_far, length-read_so_far);
3104 			if (n <= 0)
3105 				break;
3106 			read_so_far += n;
3107 		}
3108 
3109 		e = errno;
3110 		pos = lseek(fd, start_pos, SEEK_SET);
3111 		if (n < 0 || (n == 0 && length > read_so_far)) {
3112 			mm_free(mem);
3113 			errno = e;
3114 			goto err;
3115 		} else if (pos < 0) {
3116 			mm_free(mem);
3117 			goto err;
3118 		}
3119 
3120 		seg->contents = mem;
3121 	}
3122 
3123 done:
3124 	return 0;
3125 err:
3126 	return -1;
3127 }
3128 
3129 void evbuffer_file_segment_add_cleanup_cb(struct evbuffer_file_segment *seg,
3130 	evbuffer_file_segment_cleanup_cb cb, void* arg)
3131 {
3132 	EVUTIL_ASSERT(seg->refcnt > 0);
3133 	seg->cleanup_cb = cb;
3134 	seg->cleanup_cb_arg = arg;
3135 }
3136 
3137 void
3138 evbuffer_file_segment_free(struct evbuffer_file_segment *seg)
3139 {
3140 	int refcnt;
3141 	EVLOCK_LOCK(seg->lock, 0);
3142 	refcnt = --seg->refcnt;
3143 	EVLOCK_UNLOCK(seg->lock, 0);
3144 	if (refcnt > 0)
3145 		return;
3146 	EVUTIL_ASSERT(refcnt == 0);
3147 
3148 	if (seg->is_mapping) {
3149 #ifdef _WIN32
3150 		CloseHandle(seg->mapping_handle);
3151 #elif defined (EVENT__HAVE_MMAP)
3152 		off_t offset_leftover;
3153 		offset_leftover = seg->file_offset % get_page_size();
3154 		if (munmap(seg->mapping, seg->length + offset_leftover) == -1)
3155 			event_warn("%s: munmap failed", __func__);
3156 #endif
3157 	} else if (seg->contents) {
3158 		mm_free(seg->contents);
3159 	}
3160 
3161 	if ((seg->flags & EVBUF_FS_CLOSE_ON_FREE) && seg->fd >= 0) {
3162 		close(seg->fd);
3163 	}
3164 
3165 	if (seg->cleanup_cb) {
3166 		(*seg->cleanup_cb)((struct evbuffer_file_segment const*)seg,
3167 		    seg->flags, seg->cleanup_cb_arg);
3168 		seg->cleanup_cb = NULL;
3169 		seg->cleanup_cb_arg = NULL;
3170 	}
3171 
3172 	EVTHREAD_FREE_LOCK(seg->lock, 0);
3173 	mm_free(seg);
3174 }
3175 
3176 int
3177 evbuffer_add_file_segment(struct evbuffer *buf,
3178     struct evbuffer_file_segment *seg, ev_off_t offset, ev_off_t length)
3179 {
3180 	struct evbuffer_chain *chain;
3181 	struct evbuffer_chain_file_segment *extra;
3182 	int can_use_sendfile = 0;
3183 
3184 	EVBUFFER_LOCK(buf);
3185 	EVLOCK_LOCK(seg->lock, 0);
3186 	if (buf->flags & EVBUFFER_FLAG_DRAINS_TO_FD) {
3187 		can_use_sendfile = 1;
3188 	} else {
3189 		if (!seg->contents) {
3190 			if (evbuffer_file_segment_materialize(seg)<0) {
3191 				EVLOCK_UNLOCK(seg->lock, 0);
3192 				EVBUFFER_UNLOCK(buf);
3193 				return -1;
3194 			}
3195 		}
3196 	}
3197 	++seg->refcnt;
3198 	EVLOCK_UNLOCK(seg->lock, 0);
3199 
3200 	if (buf->freeze_end)
3201 		goto err;
3202 
3203 	if (length < 0) {
3204 		if (offset > seg->length)
3205 			goto err;
3206 		length = seg->length - offset;
3207 	}
3208 
3209 	/* Can we actually add this? */
3210 	if (offset+length > seg->length)
3211 		goto err;
3212 
3213 	chain = evbuffer_chain_new(sizeof(struct evbuffer_chain_file_segment));
3214 	if (!chain)
3215 		goto err;
3216 	extra = EVBUFFER_CHAIN_EXTRA(struct evbuffer_chain_file_segment, chain);
3217 
3218 	chain->flags |= EVBUFFER_IMMUTABLE|EVBUFFER_FILESEGMENT;
3219 	if (can_use_sendfile && seg->can_sendfile) {
3220 		chain->flags |= EVBUFFER_SENDFILE;
3221 		chain->misalign = seg->file_offset + offset;
3222 		chain->off = length;
3223 		chain->buffer_len = chain->misalign + length;
3224 	} else if (seg->is_mapping) {
3225 #ifdef _WIN32
3226 		ev_uint64_t total_offset = seg->mmap_offset+offset;
3227 		ev_uint64_t offset_rounded=0, offset_remaining=0;
3228 		LPVOID data;
3229 		if (total_offset) {
3230 			SYSTEM_INFO si;
3231 			memset(&si, 0, sizeof(si)); /* cargo cult */
3232 			GetSystemInfo(&si);
3233 			offset_remaining = total_offset % si.dwAllocationGranularity;
3234 			offset_rounded = total_offset - offset_remaining;
3235 		}
3236 		data = MapViewOfFile(
3237 			seg->mapping_handle,
3238 			FILE_MAP_READ,
3239 			offset_rounded >> 32,
3240 			offset_rounded & 0xfffffffful,
3241 			length + offset_remaining);
3242 		if (data == NULL) {
3243 			mm_free(chain);
3244 			goto err;
3245 		}
3246 		chain->buffer = (unsigned char*) data;
3247 		chain->buffer_len = length+offset_remaining;
3248 		chain->misalign = offset_remaining;
3249 		chain->off = length;
3250 #else
3251 		chain->buffer = (unsigned char*)(seg->contents + offset);
3252 		chain->buffer_len = length;
3253 		chain->off = length;
3254 #endif
3255 	} else {
3256 		chain->buffer = (unsigned char*)(seg->contents + offset);
3257 		chain->buffer_len = length;
3258 		chain->off = length;
3259 	}
3260 
3261 	extra->segment = seg;
3262 	buf->n_add_for_cb += length;
3263 	evbuffer_chain_insert(buf, chain);
3264 
3265 	evbuffer_invoke_callbacks_(buf);
3266 
3267 	EVBUFFER_UNLOCK(buf);
3268 
3269 	return 0;
3270 err:
3271 	EVBUFFER_UNLOCK(buf);
3272 	evbuffer_file_segment_free(seg); /* Lowers the refcount */
3273 	return -1;
3274 }
3275 
3276 int
3277 evbuffer_add_file(struct evbuffer *buf, int fd, ev_off_t offset, ev_off_t length)
3278 {
3279 	struct evbuffer_file_segment *seg;
3280 	unsigned flags = EVBUF_FS_CLOSE_ON_FREE;
3281 	int r;
3282 
3283 	seg = evbuffer_file_segment_new(fd, offset, length, flags);
3284 	if (!seg)
3285 		return -1;
3286 	r = evbuffer_add_file_segment(buf, seg, 0, length);
3287 	if (r == 0)
3288 		evbuffer_file_segment_free(seg);
3289 	return r;
3290 }
3291 
3292 void
3293 evbuffer_setcb(struct evbuffer *buffer, evbuffer_cb cb, void *cbarg)
3294 {
3295 	EVBUFFER_LOCK(buffer);
3296 
3297 	if (!LIST_EMPTY(&buffer->callbacks))
3298 		evbuffer_remove_all_callbacks(buffer);
3299 
3300 	if (cb) {
3301 		struct evbuffer_cb_entry *ent =
3302 		    evbuffer_add_cb(buffer, NULL, cbarg);
3303 		ent->cb.cb_obsolete = cb;
3304 		ent->flags |= EVBUFFER_CB_OBSOLETE;
3305 	}
3306 	EVBUFFER_UNLOCK(buffer);
3307 }
3308 
3309 struct evbuffer_cb_entry *
3310 evbuffer_add_cb(struct evbuffer *buffer, evbuffer_cb_func cb, void *cbarg)
3311 {
3312 	struct evbuffer_cb_entry *e;
3313 	if (! (e = mm_calloc(1, sizeof(struct evbuffer_cb_entry))))
3314 		return NULL;
3315 	EVBUFFER_LOCK(buffer);
3316 	e->cb.cb_func = cb;
3317 	e->cbarg = cbarg;
3318 	e->flags = EVBUFFER_CB_ENABLED;
3319 	LIST_INSERT_HEAD(&buffer->callbacks, e, next);
3320 	EVBUFFER_UNLOCK(buffer);
3321 	return e;
3322 }
3323 
3324 int
3325 evbuffer_remove_cb_entry(struct evbuffer *buffer,
3326 			 struct evbuffer_cb_entry *ent)
3327 {
3328 	EVBUFFER_LOCK(buffer);
3329 	LIST_REMOVE(ent, next);
3330 	EVBUFFER_UNLOCK(buffer);
3331 	mm_free(ent);
3332 	return 0;
3333 }
3334 
3335 int
3336 evbuffer_remove_cb(struct evbuffer *buffer, evbuffer_cb_func cb, void *cbarg)
3337 {
3338 	struct evbuffer_cb_entry *cbent;
3339 	int result = -1;
3340 	EVBUFFER_LOCK(buffer);
3341 	LIST_FOREACH(cbent, &buffer->callbacks, next) {
3342 		if (cb == cbent->cb.cb_func && cbarg == cbent->cbarg) {
3343 			result = evbuffer_remove_cb_entry(buffer, cbent);
3344 			goto done;
3345 		}
3346 	}
3347 done:
3348 	EVBUFFER_UNLOCK(buffer);
3349 	return result;
3350 }
3351 
3352 int
3353 evbuffer_cb_set_flags(struct evbuffer *buffer,
3354 		      struct evbuffer_cb_entry *cb, ev_uint32_t flags)
3355 {
3356 	/* the user isn't allowed to mess with these. */
3357 	flags &= ~EVBUFFER_CB_INTERNAL_FLAGS;
3358 	EVBUFFER_LOCK(buffer);
3359 	cb->flags |= flags;
3360 	EVBUFFER_UNLOCK(buffer);
3361 	return 0;
3362 }
3363 
3364 int
3365 evbuffer_cb_clear_flags(struct evbuffer *buffer,
3366 		      struct evbuffer_cb_entry *cb, ev_uint32_t flags)
3367 {
3368 	/* the user isn't allowed to mess with these. */
3369 	flags &= ~EVBUFFER_CB_INTERNAL_FLAGS;
3370 	EVBUFFER_LOCK(buffer);
3371 	cb->flags &= ~flags;
3372 	EVBUFFER_UNLOCK(buffer);
3373 	return 0;
3374 }
3375 
3376 int
3377 evbuffer_freeze(struct evbuffer *buffer, int start)
3378 {
3379 	EVBUFFER_LOCK(buffer);
3380 	if (start)
3381 		buffer->freeze_start = 1;
3382 	else
3383 		buffer->freeze_end = 1;
3384 	EVBUFFER_UNLOCK(buffer);
3385 	return 0;
3386 }
3387 
3388 int
3389 evbuffer_unfreeze(struct evbuffer *buffer, int start)
3390 {
3391 	EVBUFFER_LOCK(buffer);
3392 	if (start)
3393 		buffer->freeze_start = 0;
3394 	else
3395 		buffer->freeze_end = 0;
3396 	EVBUFFER_UNLOCK(buffer);
3397 	return 0;
3398 }
3399 
3400 #if 0
3401 void
3402 evbuffer_cb_suspend(struct evbuffer *buffer, struct evbuffer_cb_entry *cb)
3403 {
3404 	if (!(cb->flags & EVBUFFER_CB_SUSPENDED)) {
3405 		cb->size_before_suspend = evbuffer_get_length(buffer);
3406 		cb->flags |= EVBUFFER_CB_SUSPENDED;
3407 	}
3408 }
3409 
3410 void
3411 evbuffer_cb_unsuspend(struct evbuffer *buffer, struct evbuffer_cb_entry *cb)
3412 {
3413 	if ((cb->flags & EVBUFFER_CB_SUSPENDED)) {
3414 		unsigned call = (cb->flags & EVBUFFER_CB_CALL_ON_UNSUSPEND);
3415 		size_t sz = cb->size_before_suspend;
3416 		cb->flags &= ~(EVBUFFER_CB_SUSPENDED|
3417 			       EVBUFFER_CB_CALL_ON_UNSUSPEND);
3418 		cb->size_before_suspend = 0;
3419 		if (call && (cb->flags & EVBUFFER_CB_ENABLED)) {
3420 			cb->cb(buffer, sz, evbuffer_get_length(buffer), cb->cbarg);
3421 		}
3422 	}
3423 }
3424 #endif
3425 
3426 int
3427 evbuffer_get_callbacks_(struct evbuffer *buffer, struct event_callback **cbs,
3428     int max_cbs)
3429 {
3430 	int r = 0;
3431 	EVBUFFER_LOCK(buffer);
3432 	if (buffer->deferred_cbs) {
3433 		if (max_cbs < 1) {
3434 			r = -1;
3435 			goto done;
3436 		}
3437 		cbs[0] = &buffer->deferred;
3438 		r = 1;
3439 	}
3440 done:
3441 	EVBUFFER_UNLOCK(buffer);
3442 	return r;
3443 }
3444