Home | History | Annotate | Line # | Download | only in dist
buffer.c revision 1.1.1.1.8.1
      1 /*	$NetBSD: buffer.c,v 1.1.1.1.8.1 2015/02/04 04:38:19 snj Exp $	*/
      2 /*
      3  * Copyright (c) 2002, 2003 Niels Provos <provos (at) citi.umich.edu>
      4  * All rights reserved.
      5  *
      6  * Redistribution and use in source and binary forms, with or without
      7  * modification, are permitted provided that the following conditions
      8  * are met:
      9  * 1. Redistributions of source code must retain the above copyright
     10  *    notice, this list of conditions and the following disclaimer.
     11  * 2. Redistributions in binary form must reproduce the above copyright
     12  *    notice, this list of conditions and the following disclaimer in the
     13  *    documentation and/or other materials provided with the distribution.
     14  * 3. The name of the author may not be used to endorse or promote products
     15  *    derived from this software without specific prior written permission.
     16  *
     17  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
     18  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
     19  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
     20  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
     21  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
     22  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
     23  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
     24  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
     25  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
     26  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
     27  */
     28 
     29 #ifdef HAVE_CONFIG_H
     30 #include "config.h"
     31 #endif
     32 
     33 #ifdef WIN32
     34 #include <winsock2.h>
     35 #include <windows.h>
     36 #endif
     37 
     38 #ifdef HAVE_VASPRINTF
     39 /* If we have vasprintf, we need to define this before we include stdio.h. */
     40 #define _GNU_SOURCE
     41 #endif
     42 
     43 #include <sys/types.h>
     44 
     45 #ifdef HAVE_SYS_TIME_H
     46 #include <sys/time.h>
     47 #endif
     48 
     49 #ifdef HAVE_SYS_IOCTL_H
     50 #include <sys/ioctl.h>
     51 #endif
     52 
     53 #include <assert.h>
     54 #include <errno.h>
     55 #include <stdio.h>
     56 #include <stdlib.h>
     57 #include <string.h>
     58 #ifdef HAVE_STDARG_H
     59 #include <stdarg.h>
     60 #endif
     61 #ifdef HAVE_UNISTD_H
     62 #include <unistd.h>
     63 #endif
     64 
     65 #include "event.h"
     66 #include "config.h"
     67 #include "evutil.h"
     68 
     69 struct evbuffer *
     70 evbuffer_new(void)
     71 {
     72 	struct evbuffer *buffer;
     73 
     74 	buffer = calloc(1, sizeof(struct evbuffer));
     75 
     76 	return (buffer);
     77 }
     78 
     79 void
     80 evbuffer_free(struct evbuffer *buffer)
     81 {
     82 	if (buffer->orig_buffer != NULL)
     83 		free(buffer->orig_buffer);
     84 	free(buffer);
     85 }
     86 
     87 /*
     88  * This is a destructive add.  The data from one buffer moves into
     89  * the other buffer.
     90  */
     91 
     92 #define SWAP(x,y) do { \
     93 	(x)->buffer = (y)->buffer; \
     94 	(x)->orig_buffer = (y)->orig_buffer; \
     95 	(x)->misalign = (y)->misalign; \
     96 	(x)->totallen = (y)->totallen; \
     97 	(x)->off = (y)->off; \
     98 } while (0)
     99 
    100 int
    101 evbuffer_add_buffer(struct evbuffer *outbuf, struct evbuffer *inbuf)
    102 {
    103 	int res;
    104 
    105 	/* Short cut for better performance */
    106 	if (outbuf->off == 0) {
    107 		struct evbuffer tmp;
    108 		size_t oldoff = inbuf->off;
    109 
    110 		/* Swap them directly */
    111 		SWAP(&tmp, outbuf);
    112 		SWAP(outbuf, inbuf);
    113 		SWAP(inbuf, &tmp);
    114 
    115 		/*
    116 		 * Optimization comes with a price; we need to notify the
    117 		 * buffer if necessary of the changes. oldoff is the amount
    118 		 * of data that we transfered from inbuf to outbuf
    119 		 */
    120 		if (inbuf->off != oldoff && inbuf->cb != NULL)
    121 			(*inbuf->cb)(inbuf, oldoff, inbuf->off, inbuf->cbarg);
    122 		if (oldoff && outbuf->cb != NULL)
    123 			(*outbuf->cb)(outbuf, 0, oldoff, outbuf->cbarg);
    124 
    125 		return (0);
    126 	}
    127 
    128 	res = evbuffer_add(outbuf, inbuf->buffer, inbuf->off);
    129 	if (res == 0) {
    130 		/* We drain the input buffer on success */
    131 		evbuffer_drain(inbuf, inbuf->off);
    132 	}
    133 
    134 	return (res);
    135 }
    136 
    137 int
    138 evbuffer_add_vprintf(struct evbuffer *buf, const char *fmt, va_list ap)
    139 {
    140 	char *buffer;
    141 	size_t space;
    142 	size_t oldoff = buf->off;
    143 	int sz;
    144 	va_list aq;
    145 
    146 	/* make sure that at least some space is available */
    147 	if (evbuffer_expand(buf, 64) < 0)
    148 		return (-1);
    149 	for (;;) {
    150 		size_t used = buf->misalign + buf->off;
    151 		buffer = (char *)buf->buffer + buf->off;
    152 		assert(buf->totallen >= used);
    153 		space = buf->totallen - used;
    154 
    155 #ifndef va_copy
    156 #define	va_copy(dst, src)	memcpy(&(dst), &(src), sizeof(va_list))
    157 #endif
    158 		va_copy(aq, ap);
    159 
    160 		sz = evutil_vsnprintf(buffer, space, fmt, aq);
    161 
    162 		va_end(aq);
    163 
    164 		if (sz < 0)
    165 			return (-1);
    166 		if ((size_t)sz < space) {
    167 			buf->off += sz;
    168 			if (buf->cb != NULL)
    169 				(*buf->cb)(buf, oldoff, buf->off, buf->cbarg);
    170 			return (sz);
    171 		}
    172 		if (evbuffer_expand(buf, sz + 1) == -1)
    173 			return (-1);
    174 
    175 	}
    176 	/* NOTREACHED */
    177 }
    178 
    179 int
    180 evbuffer_add_printf(struct evbuffer *buf, const char *fmt, ...)
    181 {
    182 	int res = -1;
    183 	va_list ap;
    184 
    185 	va_start(ap, fmt);
    186 	res = evbuffer_add_vprintf(buf, fmt, ap);
    187 	va_end(ap);
    188 
    189 	return (res);
    190 }
    191 
    192 /* Reads data from an event buffer and drains the bytes read */
    193 
    194 int
    195 evbuffer_remove(struct evbuffer *buf, void *data, size_t datlen)
    196 {
    197 	size_t nread = datlen;
    198 	if (nread >= buf->off)
    199 		nread = buf->off;
    200 
    201 	memcpy(data, buf->buffer, nread);
    202 	evbuffer_drain(buf, nread);
    203 
    204 	return (nread);
    205 }
    206 
    207 /*
    208  * Reads a line terminated by either '\r\n', '\n\r' or '\r' or '\n'.
    209  * The returned buffer needs to be freed by the called.
    210  */
    211 
    212 char *
    213 evbuffer_readline(struct evbuffer *buffer)
    214 {
    215 	u_char *data = EVBUFFER_DATA(buffer);
    216 	size_t len = EVBUFFER_LENGTH(buffer);
    217 	char *line;
    218 	unsigned int i;
    219 
    220 	for (i = 0; i < len; i++) {
    221 		if (data[i] == '\r' || data[i] == '\n')
    222 			break;
    223 	}
    224 
    225 	if (i == len)
    226 		return (NULL);
    227 
    228 	if ((line = malloc(i + 1)) == NULL) {
    229 		fprintf(stderr, "%s: out of memory\n", __func__);
    230 		evbuffer_drain(buffer, i);
    231 		return (NULL);
    232 	}
    233 
    234 	memcpy(line, data, i);
    235 	line[i] = '\0';
    236 
    237 	/*
    238 	 * Some protocols terminate a line with '\r\n', so check for
    239 	 * that, too.
    240 	 */
    241 	if ( i < len - 1 ) {
    242 		char fch = data[i], sch = data[i+1];
    243 
    244 		/* Drain one more character if needed */
    245 		if ( (sch == '\r' || sch == '\n') && sch != fch )
    246 			i += 1;
    247 	}
    248 
    249 	evbuffer_drain(buffer, i + 1);
    250 
    251 	return (line);
    252 }
    253 
    254 /* Adds data to an event buffer */
    255 
    256 static void
    257 evbuffer_align(struct evbuffer *buf)
    258 {
    259 	memmove(buf->orig_buffer, buf->buffer, buf->off);
    260 	buf->buffer = buf->orig_buffer;
    261 	buf->misalign = 0;
    262 }
    263 
    264 #ifndef SIZE_MAX
    265 #define SIZE_MAX ((size_t)-1)
    266 #endif
    267 
    268 /* Expands the available space in the event buffer to at least datlen */
    269 
    270 int
    271 evbuffer_expand(struct evbuffer *buf, size_t datlen)
    272 {
    273 	size_t used = buf->misalign + buf->off;
    274 
    275 	assert(buf->totallen >= used);
    276 
    277 	/* If we can fit all the data, then we don't have to do anything */
    278 	if (buf->totallen - used >= datlen)
    279 		return (0);
    280 	/* If we would need to overflow to fit this much data, we can't
    281 	 * do anything. */
    282 	if (datlen > SIZE_MAX - buf->off)
    283 		return (-1);
    284 
    285 	/*
    286 	 * If the misalignment fulfills our data needs, we just force an
    287 	 * alignment to happen.  Afterwards, we have enough space.
    288 	 */
    289 	if (buf->totallen - buf->off >= datlen) {
    290 		evbuffer_align(buf);
    291 	} else {
    292 		void *newbuf;
    293 		size_t length = buf->totallen;
    294 		size_t need = buf->off + datlen;
    295 
    296 		if (length < 256)
    297 			length = 256;
    298 		if (need < SIZE_MAX / 2) {
    299 			while (length < need) {
    300 				length <<= 1;
    301 			}
    302 		} else {
    303 			length = need;
    304 		}
    305 
    306 		if (buf->orig_buffer != buf->buffer)
    307 			evbuffer_align(buf);
    308 		if ((newbuf = realloc(buf->buffer, length)) == NULL)
    309 			return (-1);
    310 
    311 		buf->orig_buffer = buf->buffer = newbuf;
    312 		buf->totallen = length;
    313 	}
    314 
    315 	return (0);
    316 }
    317 
    318 int
    319 evbuffer_add(struct evbuffer *buf, const void *data, size_t datlen)
    320 {
    321 	size_t used = buf->misalign + buf->off;
    322 	size_t oldoff = buf->off;
    323 
    324 	if (buf->totallen - used < datlen) {
    325 		if (evbuffer_expand(buf, datlen) == -1)
    326 			return (-1);
    327 	}
    328 
    329 	memcpy(buf->buffer + buf->off, data, datlen);
    330 	buf->off += datlen;
    331 
    332 	if (datlen && buf->cb != NULL)
    333 		(*buf->cb)(buf, oldoff, buf->off, buf->cbarg);
    334 
    335 	return (0);
    336 }
    337 
    338 void
    339 evbuffer_drain(struct evbuffer *buf, size_t len)
    340 {
    341 	size_t oldoff = buf->off;
    342 
    343 	if (len >= buf->off) {
    344 		buf->off = 0;
    345 		buf->buffer = buf->orig_buffer;
    346 		buf->misalign = 0;
    347 		goto done;
    348 	}
    349 
    350 	buf->buffer += len;
    351 	buf->misalign += len;
    352 
    353 	buf->off -= len;
    354 
    355  done:
    356 	/* Tell someone about changes in this buffer */
    357 	if (buf->off != oldoff && buf->cb != NULL)
    358 		(*buf->cb)(buf, oldoff, buf->off, buf->cbarg);
    359 
    360 }
    361 
    362 /*
    363  * Reads data from a file descriptor into a buffer.
    364  */
    365 
    366 #define EVBUFFER_MAX_READ	4096
    367 
    368 int
    369 evbuffer_read(struct evbuffer *buf, int fd, int howmuch)
    370 {
    371 	u_char *p;
    372 	size_t oldoff = buf->off;
    373 	int n = EVBUFFER_MAX_READ;
    374 
    375 #if defined(FIONREAD)
    376 #ifdef WIN32
    377 	long lng = n;
    378 	if (ioctlsocket(fd, FIONREAD, &lng) == -1 || (n=lng) == 0) {
    379 #else
    380 	if (ioctl(fd, FIONREAD, &n) == -1 || n == 0) {
    381 #endif
    382 		n = EVBUFFER_MAX_READ;
    383 	} else if (n > EVBUFFER_MAX_READ && n > howmuch) {
    384 		/*
    385 		 * It's possible that a lot of data is available for
    386 		 * reading.  We do not want to exhaust resources
    387 		 * before the reader has a chance to do something
    388 		 * about it.  If the reader does not tell us how much
    389 		 * data we should read, we artifically limit it.
    390 		 */
    391 		if ((size_t)n > buf->totallen << 2)
    392 			n = buf->totallen << 2;
    393 		if (n < EVBUFFER_MAX_READ)
    394 			n = EVBUFFER_MAX_READ;
    395 	}
    396 #endif
    397 	if (howmuch < 0 || howmuch > n)
    398 		howmuch = n;
    399 
    400 	/* If we don't have FIONREAD, we might waste some space here */
    401 	if (evbuffer_expand(buf, howmuch) == -1)
    402 		return (-1);
    403 
    404 	/* We can append new data at this point */
    405 	p = buf->buffer + buf->off;
    406 
    407 #ifndef WIN32
    408 	n = read(fd, p, howmuch);
    409 #else
    410 	n = recv(fd, p, howmuch, 0);
    411 #endif
    412 	if (n == -1)
    413 		return (-1);
    414 	if (n == 0)
    415 		return (0);
    416 
    417 	buf->off += n;
    418 
    419 	/* Tell someone about changes in this buffer */
    420 	if (buf->off != oldoff && buf->cb != NULL)
    421 		(*buf->cb)(buf, oldoff, buf->off, buf->cbarg);
    422 
    423 	return (n);
    424 }
    425 
    426 int
    427 evbuffer_write(struct evbuffer *buffer, int fd)
    428 {
    429 	int n;
    430 
    431 #ifndef WIN32
    432 	n = write(fd, buffer->buffer, buffer->off);
    433 #else
    434 	n = send(fd, buffer->buffer, buffer->off, 0);
    435 #endif
    436 	if (n == -1)
    437 		return (-1);
    438 	if (n == 0)
    439 		return (0);
    440 	evbuffer_drain(buffer, n);
    441 
    442 	return (n);
    443 }
    444 
    445 u_char *
    446 evbuffer_find(struct evbuffer *buffer, const u_char *what, size_t len)
    447 {
    448 	u_char *search = buffer->buffer, *end = search + buffer->off;
    449 	u_char *p;
    450 
    451 	while (search < end &&
    452 	    (p = memchr(search, *what, end - search)) != NULL) {
    453 		if (p + len > end)
    454 			break;
    455 		if (memcmp(p, what, len) == 0)
    456 			return (p);
    457 		search = p + 1;
    458 	}
    459 
    460 	return (NULL);
    461 }
    462 
    463 void evbuffer_setcb(struct evbuffer *buffer,
    464     void (*cb)(struct evbuffer *, size_t, size_t, void *),
    465     void *cbarg)
    466 {
    467 	buffer->cb = cb;
    468 	buffer->cbarg = cbarg;
    469 }
    470