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