Coverage Report

Created: 2026-07-16 07:07

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