Stupid cut-and-paste bug.
[tor.git] / src / or / buffers.c
blob3e2a2b1a86ded8a3c21d1f280fc7ead0ae89a687
1 /* Copyright 2001 Matej Pfajfar.
2 * Copyright 2001-2004 Roger Dingledine.
3 * Copyright 2004-2005 Roger Dingledine, Nick Mathewson. */
4 /* See LICENSE for licensing information */
5 /* $Id$ */
6 const char buffers_c_id[] =
7 "$Id$";
9 /**
10 * \file buffers.c
11 * \brief Implements a generic buffer interface. Buffers are
12 * fairly opaque string holders that can read to or flush from:
13 * memory, file descriptors, or TLS connections.
14 **/
16 #include "or.h"
18 #define SENTINELS
19 #undef CHECK_AFTER_RESIZE
20 #undef PARANOIA
21 #undef NOINLINE
23 #ifdef SENTINELS
24 /* If SENTINELS is defined, check for attempts to write beyond the
25 * end/before the start of the buffer.
27 #define START_MAGIC 0x70370370u
28 #define END_MAGIC 0xA0B0C0D0u
29 #define RAW_MEM(m) ((void*)(((char*)m)-4))
30 #define GUARDED_MEM(m) ((void*)(((char*)m)+4))
31 #define ALLOC_LEN(ln) ((ln)+8)
32 #define SET_GUARDS(m, ln) \
33 do { set_uint32((m)-4,START_MAGIC); set_uint32((m)+ln,END_MAGIC); } while (0)
34 #else
35 #define RAW_MEM(m) (m)
36 #define GUARDED_MEM(m) (m)
37 #define ALLOC_LEN(ln) (ln)
38 #define SET_GUARDS(m,ln) do {} while (0)
39 #endif
41 #ifdef PARANOIA
42 #define check() do { assert_buf_ok(buf); } while (0)
43 #else
44 #define check() do { } while (0)
45 #endif
47 #ifdef NOINLINE
48 #undef INLINE
49 #define INLINE
50 #endif
52 #define BUFFER_MAGIC 0xB0FFF312u
53 /** A resizeable buffer, optimized for reading and writing. */
54 struct buf_t {
55 uint32_t magic; /**< Magic cookie for debugging: Must be set to
56 * BUFFER_MAGIC */
57 char *mem; /**< Storage for data in the buffer */
58 char *cur; /**< The first byte used for storing data in the buffer. */
59 size_t highwater; /**< Largest observed datalen since last buf_shrink */
60 size_t len; /**< Maximum amount of data that <b>mem</b> can hold. */
61 size_t datalen; /**< Number of bytes currently in <b>mem</b>. */
64 uint64_t buf_total_used = 0;
65 uint64_t buf_total_alloc = 0;
67 /** Size, in bytes, for newly allocated buffers. Should be a power of 2. */
68 #define INITIAL_BUF_SIZE (4*1024)
69 /** Size, in bytes, for minimum 'shrink' size for buffers. Buffers may start
70 * out smaller than this, but they will never autoshrink to less
71 * than this size. */
72 #define MIN_GREEDY_SHRINK_SIZE (16*1024)
73 #define MIN_LAZY_SHRINK_SIZE (4*1024)
75 static INLINE void peek_from_buf(char *string, size_t string_len, buf_t *buf);
77 /** If the contents of buf wrap around the end of the allocated space,
78 * malloc a new buf and copy the contents in starting at the
79 * beginning. This operation is relatively expensive, so it shouldn't
80 * be used e.g. for every single read or write.
82 static void
83 buf_normalize(buf_t *buf)
85 check();
86 if (buf->cur + buf->datalen <= buf->mem+buf->len) {
87 return;
88 } else {
89 char *newmem, *oldmem;
90 size_t sz = (buf->mem+buf->len)-buf->cur;
91 warn(LD_BUG, "Unexpected non-normalized buffer.");
92 newmem = GUARDED_MEM(tor_malloc(ALLOC_LEN(buf->len)));
93 SET_GUARDS(newmem, buf->len);
94 memcpy(newmem, buf->cur, sz);
95 memcpy(newmem+sz, buf->mem, buf->datalen-sz);
96 oldmem = RAW_MEM(buf->mem);
97 tor_free(oldmem); /* Can't use tor_free directly. */
98 buf->mem = buf->cur = newmem;
99 check();
103 /** Return the point in the buffer where the next byte will get stored. */
104 static INLINE char *
105 _buf_end(buf_t *buf)
107 char *next = buf->cur + buf->datalen;
108 char *end = buf->mem + buf->len;
109 return (next < end) ? next : (next - buf->len);
112 /** If the pointer <b>cp</b> has passed beyond the end of the buffer, wrap it
113 * around. */
114 static INLINE char *
115 _wrap_ptr(buf_t *buf, char *cp)
117 return (cp >= buf->mem + buf->len) ? (cp - buf->len) : cp;
120 /** Return the offset of <b>cp</b> within the buffer. */
121 static INLINE int
122 _buf_offset(buf_t *buf, char *cp)
124 if (cp >= buf->cur)
125 return cp - buf->cur;
126 else
127 /* return (cp - buf->mem) + buf->mem+buf->len - buf->cur */
128 return cp + buf->len - buf->cur;
131 /** If the range of *<b>len</b> bytes starting at <b>at</b> wraps around the
132 * end of the buffer, then set *<b>len</b> to the number of bytes starting
133 * at <b>at</b>, and set *<b>more_len</b> to the number of bytes starting
134 * at <b>buf-&gt;mem</b>. Otherwise, set *<b>more_len</b> to 0.
136 static INLINE void
137 _split_range(buf_t *buf, char *at, size_t *len,
138 size_t *more_len)
140 char *eos = at + *len;
141 check();
142 if (eos >= (buf->mem + buf->len)) {
143 *more_len = eos - (buf->mem + buf->len);
144 *len -= *more_len;
145 } else {
146 *more_len = 0;
150 /** Change a buffer's capacity. <b>new_capacity</b> must be \>=
151 * buf->datalen. */
152 static void
153 buf_resize(buf_t *buf, size_t new_capacity)
155 off_t offset;
156 #ifdef CHECK_AFTER_RESIZE
157 char *tmp, *tmp2;
158 #endif
159 tor_assert(buf->datalen <= new_capacity);
160 tor_assert(new_capacity);
162 #ifdef CHECK_AFTER_RESIZE
163 assert_buf_ok(buf);
164 tmp = tor_malloc(buf->datalen);
165 tmp2 = tor_malloc(buf->datalen);
166 peek_from_buf(tmp, buf->datalen, buf);
167 #endif
169 if (buf->len == new_capacity)
170 return;
172 offset = buf->cur - buf->mem;
173 if (offset + buf->datalen > new_capacity) {
174 /* We need to move stuff before we shrink. */
175 if (offset + buf->datalen > buf->len) {
176 /* We have:
178 * mem[0] ... mem[datalen-(len-offset)] (end of data)
179 * mem[offset] ... mem[len-1] (the start of the data)
181 * We're shrinking the buffer by (len-new_capacity) bytes, so we need
182 * to move the start portion back by that many bytes.
184 memmove(buf->cur-(buf->len-new_capacity), buf->cur,
185 buf->len-offset);
186 offset -= (buf->len-new_capacity);
187 } else {
188 /* The data doesn't wrap around, but it does extend beyond the new
189 * buffer length:
190 * mem[offset] ... mem[offset+datalen-1] (the data)
192 memmove(buf->mem, buf->cur, buf->datalen);
193 offset = 0;
197 /* XXX Some play code to throw away old buffers sometimes rather
198 * than constantly reallocing them; just in case this is our memory
199 * problem. It looks for now like it isn't, so disabled. -RD */
200 if (0 && new_capacity == MIN_LAZY_SHRINK_SIZE &&
201 !buf->datalen &&
202 buf->len >= 1<<16) {
203 /* don't realloc; free and malloc */
204 char *oldmem, *newmem = GUARDED_MEM(tor_malloc(ALLOC_LEN(new_capacity)));
205 SET_GUARDS(newmem, new_capacity);
206 oldmem = RAW_MEM(buf->mem);
207 tor_free(oldmem);
208 buf->mem = buf->cur = newmem;
209 } else {
210 buf->mem = GUARDED_MEM(tor_realloc(RAW_MEM(buf->mem),
211 ALLOC_LEN(new_capacity)));
212 SET_GUARDS(buf->mem, new_capacity);
213 buf->cur = buf->mem+offset;
215 buf_total_alloc += new_capacity;
216 buf_total_alloc -= buf->len;
218 if (offset + buf->datalen > buf->len) {
219 /* We need to move data now that we are done growing. The buffer
220 * now contains:
222 * mem[0] ... mem[datalen-(len-offset)] (end of data)
223 * mem[offset] ... mem[len-1] (the start of the data)
224 * mem[len]...mem[new_capacity] (empty space)
226 * We're growing by (new_capacity-len) bytes, so we need to move the
227 * end portion forward by that many bytes.
229 memmove(buf->cur+(new_capacity-buf->len), buf->cur,
230 buf->len-offset);
231 buf->cur += new_capacity-buf->len;
233 buf->len = new_capacity;
235 #ifdef CHECK_AFTER_RESIZE
236 assert_buf_ok(buf);
237 peek_from_buf(tmp2, buf->datalen, buf);
238 if (memcmp(tmp, tmp2, buf->datalen)) {
239 tor_assert(0);
241 tor_free(tmp);
242 tor_free(tmp2);
243 #endif
246 /** If the buffer is not large enough to hold <b>capacity</b> bytes, resize
247 * it so that it can. (The new size will be a power of 2 times the old
248 * size.)
250 static INLINE int
251 buf_ensure_capacity(buf_t *buf, size_t capacity)
253 size_t new_len;
254 if (buf->len >= capacity) /* Don't grow if we're already big enough. */
255 return 0;
256 if (capacity > MAX_BUF_SIZE) /* Don't grow past the maximum. */
257 return -1;
258 /* Find the smallest new_len equal to (2**X)*len for some X; such that
259 * new_len is at least capacity.
261 new_len = buf->len*2;
262 while (new_len < capacity)
263 new_len *= 2;
264 /* Resize the buffer. */
265 debug(LD_MM,"Growing buffer from %d to %d bytes.",
266 (int)buf->len, (int)new_len);
267 buf_resize(buf,new_len);
268 return 0;
271 /** Resize buf so it won't hold extra memory that we haven't been
272 * using lately (that is, since the last time we called buf_shrink).
273 * Try to shrink the buf until it is the largest factor of two that
274 * can contain <b>buf</b>-&gt;highwater, but never smaller than
275 * MIN_LAZY_SHRINK_SIZE.
277 void
278 buf_shrink(buf_t *buf)
280 size_t new_len;
282 new_len = buf->len;
283 while (buf->highwater < (new_len>>2) && new_len > MIN_LAZY_SHRINK_SIZE*2)
284 new_len >>= 1;
286 buf->highwater = buf->datalen;
287 if (new_len == buf->len)
288 return;
290 debug(LD_MM,"Shrinking buffer from %d to %d bytes.",
291 (int)buf->len, (int)new_len);
292 buf_resize(buf, new_len);
295 /** Remove the first <b>n</b> bytes from buf. */
296 static INLINE void
297 buf_remove_from_front(buf_t *buf, size_t n)
299 tor_assert(buf->datalen >= n);
300 buf->datalen -= n;
301 buf_total_used -= n;
302 if (buf->datalen) {
303 buf->cur = _wrap_ptr(buf, buf->cur+n);
304 } else {
305 buf->cur = buf->mem;
307 check();
310 /** Make sure that the memory in buf ends with a zero byte. */
311 static INLINE int
312 buf_nul_terminate(buf_t *buf)
314 if (buf_ensure_capacity(buf,buf->datalen+1)<0)
315 return -1;
316 *_buf_end(buf) = '\0';
317 return 0;
320 /** Create and return a new buf with capacity <b>size</b>. */
321 buf_t *
322 buf_new_with_capacity(size_t size)
324 buf_t *buf;
325 buf = tor_malloc_zero(sizeof(buf_t));
326 buf->magic = BUFFER_MAGIC;
327 buf->cur = buf->mem = GUARDED_MEM(tor_malloc(ALLOC_LEN(size)));
328 SET_GUARDS(buf->mem, size);
329 buf->len = size;
331 buf_total_alloc += size;
332 assert_buf_ok(buf);
333 return buf;
336 /** Allocate and return a new buffer with default capacity. */
337 buf_t *
338 buf_new(void)
340 return buf_new_with_capacity(INITIAL_BUF_SIZE);
343 /** Remove all data from <b>buf</b>. */
344 void
345 buf_clear(buf_t *buf)
347 buf_total_used -= buf->datalen;
348 buf->datalen = 0;
349 buf->cur = buf->mem;
352 /** Return the number of bytes stored in <b>buf</b> */
353 size_t
354 buf_datalen(const buf_t *buf)
356 return buf->datalen;
359 /** Return the maximum bytes that can be stored in <b>buf</b> before buf
360 * needs to resize. */
361 size_t
362 buf_capacity(const buf_t *buf)
364 return buf->len;
367 /** For testing only: Return a pointer to the raw memory stored in
368 * <b>buf</b>. */
369 const char *
370 _buf_peek_raw_buffer(const buf_t *buf)
372 return buf->cur;
375 /** Release storage held by <b>buf</b>. */
376 void
377 buf_free(buf_t *buf)
379 char *oldmem;
380 assert_buf_ok(buf);
381 buf->magic = 0xDEADBEEF;
382 oldmem = RAW_MEM(buf->mem);
383 tor_free(oldmem);
384 buf_total_alloc -= buf->len;
385 buf_total_used -= buf->datalen;
386 tor_free(buf);
389 /** Helper for read_to_buf(): read no more than at_most bytes from
390 * socket s into buffer buf, starting at the position pos. (Does not
391 * check for overflow.) Set *reached_eof to true on EOF. Return
392 * number of bytes read on success, 0 if the read would block, -1 on
393 * failure.
395 static INLINE int
396 read_to_buf_impl(int s, size_t at_most, buf_t *buf,
397 char *pos, int *reached_eof)
399 int read_result;
401 // log_fn(LOG_DEBUG,"reading at most %d bytes.",at_most);
402 read_result = recv(s, pos, at_most, 0);
403 if (read_result < 0) {
404 int e = tor_socket_errno(s);
405 if (!ERRNO_IS_EAGAIN(e)) { /* it's a real error */
406 return -1;
408 return 0; /* would block. */
409 } else if (read_result == 0) {
410 debug(LD_NET,"Encountered eof");
411 *reached_eof = 1;
412 return 0;
413 } else { /* we read some bytes */
414 buf->datalen += read_result;
415 buf_total_used += read_result;
416 if (buf->datalen > buf->highwater)
417 buf->highwater = buf->datalen;
418 debug(LD_NET,"Read %d bytes. %d on inbuf.",read_result,
419 (int)buf->datalen);
420 return read_result;
424 /** Read from socket <b>s</b>, writing onto end of <b>buf</b>. Read at most
425 * <b>at_most</b> bytes, resizing the buffer as necessary. If recv()
426 * returns 0, set *<b>reached_eof</b> to 1 and return 0. Return -1 on error;
427 * else return the number of bytes read. Return 0 if recv() would
428 * block.
431 read_to_buf(int s, size_t at_most, buf_t *buf, int *reached_eof)
433 int r;
434 char *next;
435 size_t at_start;
437 /* assert_buf_ok(buf); */
438 tor_assert(reached_eof);
439 tor_assert(s>=0);
441 if (buf_ensure_capacity(buf,buf->datalen+at_most))
442 return -1;
444 if (at_most + buf->datalen > buf->len)
445 at_most = buf->len - buf->datalen; /* take the min of the two */
447 if (at_most == 0)
448 return 0; /* we shouldn't read anything */
450 next = _buf_end(buf);
451 _split_range(buf, next, &at_most, &at_start);
453 r = read_to_buf_impl(s, at_most, buf, next, reached_eof);
454 check();
455 if (r < 0 || (size_t)r < at_most) {
456 return r; /* Either error, eof, block, or no more to read. */
459 if (at_start) {
460 int r2;
461 tor_assert(_buf_end(buf) == buf->mem);
462 r2 = read_to_buf_impl(s, at_start, buf, buf->mem, reached_eof);
463 check();
464 if (r2 < 0) {
465 return r2;
466 } else {
467 r += r2;
470 return r;
473 /** Helper for read_to_buf_tls(): read no more than <b>at_most</b>
474 * bytes from the TLS connection <b>tls</b> into buffer <b>buf</b>,
475 * starting at the position <b>next</b>. (Does not check for overflow.)
476 * Return number of bytes read on success, 0 if the read would block,
477 * -1 on failure.
479 static INLINE int
480 read_to_buf_tls_impl(tor_tls_t *tls, size_t at_most, buf_t *buf, char *next)
482 int r;
484 debug(LD_NET,"before: %d on buf, %d pending, at_most %d.",
485 (int)buf_datalen(buf), (int)tor_tls_get_pending_bytes(tls),
486 (int)at_most);
487 r = tor_tls_read(tls, next, at_most);
488 if (r<0)
489 return r;
490 buf->datalen += r;
491 buf_total_used += r;
492 if (buf->datalen > buf->highwater)
493 buf->highwater = buf->datalen;
494 debug(LD_NET,"Read %d bytes. %d on inbuf; %d pending",r,
495 (int)buf->datalen,(int)tor_tls_get_pending_bytes(tls));
496 return r;
499 /** As read_to_buf, but reads from a TLS connection.
501 * Using TLS on OR connections complicates matters in two ways.
503 * First, a TLS stream has its own read buffer independent of the
504 * connection's read buffer. (TLS needs to read an entire frame from
505 * the network before it can decrypt any data. Thus, trying to read 1
506 * byte from TLS can require that several KB be read from the network
507 * and decrypted. The extra data is stored in TLS's decrypt buffer.)
508 * Because the data hasn't been read by Tor (it's still inside the TLS),
509 * this means that sometimes a connection "has stuff to read" even when
510 * poll() didn't return POLLIN. The tor_tls_get_pending_bytes function is
511 * used in connection.c to detect TLS objects with non-empty internal
512 * buffers and read from them again.
514 * Second, the TLS stream's events do not correspond directly to network
515 * events: sometimes, before a TLS stream can read, the network must be
516 * ready to write -- or vice versa.
519 read_to_buf_tls(tor_tls_t *tls, size_t at_most, buf_t *buf)
521 int r;
522 char *next;
523 size_t at_start;
525 tor_assert(tls);
526 assert_buf_ok(buf);
528 debug(LD_NET,"start: %d on buf, %d pending, at_most %d.",
529 (int)buf_datalen(buf), (int)tor_tls_get_pending_bytes(tls),
530 (int)at_most);
532 if (buf_ensure_capacity(buf, at_most+buf->datalen))
533 return TOR_TLS_ERROR;
535 if (at_most + buf->datalen > buf->len)
536 at_most = buf->len - buf->datalen;
538 if (at_most == 0)
539 return 0;
541 next = _buf_end(buf);
542 _split_range(buf, next, &at_most, &at_start);
544 r = read_to_buf_tls_impl(tls, at_most, buf, next);
545 check();
546 if (r < 0 || (size_t)r < at_most)
547 return r; /* Either error, eof, block, or no more to read. */
549 if (at_start) {
550 int r2;
551 tor_assert(_buf_end(buf) == buf->mem);
552 r2 = read_to_buf_tls_impl(tls, at_start, buf, buf->mem);
553 check();
554 if (r2 < 0)
555 return r2;
556 else
557 r += r2;
559 return r;
562 /** Helper for flush_buf(): try to write <b>sz</b> bytes from buffer
563 * <b>buf</b> onto socket <b>s</b>. On success, deduct the bytes written
564 * from *<b>buf_flushlen</b>.
565 * Return the number of bytes written on success, -1 on failure.
567 static INLINE int
568 flush_buf_impl(int s, buf_t *buf, size_t sz, size_t *buf_flushlen)
570 int write_result;
572 write_result = send(s, buf->cur, sz, 0);
573 if (write_result < 0) {
574 int e = tor_socket_errno(s);
575 if (!ERRNO_IS_EAGAIN(e)) { /* it's a real error */
576 return -1;
578 debug(LD_NET,"write() would block, returning.");
579 return 0;
580 } else {
581 *buf_flushlen -= write_result;
582 buf_remove_from_front(buf, write_result);
583 return write_result;
587 /** Write data from <b>buf</b> to the socket <b>s</b>. Write at most
588 * <b>sz</b> bytes, decrement *<b>buf_flushlen</b> by
589 * the number of bytes actually written, and remove the written bytes
590 * from the buffer. Return the number of bytes written on success,
591 * -1 on failure. Return 0 if write() would block.
594 flush_buf(int s, buf_t *buf, size_t sz, size_t *buf_flushlen)
596 int r;
597 size_t flushed = 0;
598 size_t flushlen0, flushlen1;
600 /* assert_buf_ok(buf); */
601 tor_assert(buf_flushlen);
602 tor_assert(s>=0);
603 tor_assert(*buf_flushlen <= buf->datalen);
604 tor_assert(sz <= *buf_flushlen);
606 if (sz == 0) /* nothing to flush */
607 return 0;
609 flushlen0 = sz;
610 _split_range(buf, buf->cur, &flushlen0, &flushlen1);
612 r = flush_buf_impl(s, buf, flushlen0, buf_flushlen);
613 check();
615 debug(LD_NET,"%d: flushed %d bytes, %d ready to flush, %d remain.",
616 s,r,(int)*buf_flushlen,(int)buf->datalen);
617 if (r < 0 || (size_t)r < flushlen0)
618 return r; /* Error, or can't flush any more now. */
619 flushed = r;
621 if (flushlen1) {
622 tor_assert(buf->cur == buf->mem);
623 r = flush_buf_impl(s, buf, flushlen1, buf_flushlen);
624 check();
625 debug(LD_NET,"%d: flushed %d bytes, %d ready to flush, %d remain.",
626 s,r,(int)*buf_flushlen,(int)buf->datalen);
627 if (r<0)
628 return r;
629 flushed += r;
631 return flushed;
634 /** Helper for flush_buf_tls(): try to write <b>sz</b> bytes from buffer
635 * <b>buf</b> onto TLS object <b>tls</b>. On success, deduct the bytes
636 * written from *<b>buf_flushlen</b>.
637 * Return the number of bytes written on success, -1 on failure.
639 static INLINE int
640 flush_buf_tls_impl(tor_tls_t *tls, buf_t *buf, size_t sz, size_t *buf_flushlen)
642 int r;
644 r = tor_tls_write(tls, buf->cur, sz);
645 if (r < 0) {
646 return r;
648 *buf_flushlen -= r;
649 buf_remove_from_front(buf, r);
650 debug(LD_NET,"flushed %d bytes, %d ready to flush, %d remain.",
651 r,(int)*buf_flushlen,(int)buf->datalen);
652 return r;
655 /** As flush_buf(), but writes data to a TLS connection.
658 flush_buf_tls(tor_tls_t *tls, buf_t *buf, size_t sz, size_t *buf_flushlen)
660 int r;
661 size_t flushed=0;
662 size_t flushlen0, flushlen1;
663 /* assert_buf_ok(buf); */
664 tor_assert(tls);
665 tor_assert(buf_flushlen);
666 tor_assert(*buf_flushlen <= buf->datalen);
667 tor_assert(sz <= *buf_flushlen);
669 /* we want to let tls write even if flushlen is zero, because it might
670 * have a partial record pending */
671 check_no_tls_errors();
673 flushlen0 = sz;
674 _split_range(buf, buf->cur, &flushlen0, &flushlen1);
676 r = flush_buf_tls_impl(tls, buf, flushlen0, buf_flushlen);
677 check();
678 if (r < 0 || (size_t)r < flushlen0)
679 return r; /* Error, or can't flush any more now. */
680 flushed = r;
682 if (flushlen1) {
683 tor_assert(buf->cur == buf->mem);
684 r = flush_buf_tls_impl(tls, buf, flushlen1, buf_flushlen);
685 check();
686 if (r<0)
687 return r;
688 flushed += r;
690 return flushed;
693 /** Append <b>string_len</b> bytes from <b>string</b> to the end of
694 * <b>buf</b>.
696 * Return the new length of the buffer on success, -1 on failure.
699 write_to_buf(const char *string, size_t string_len, buf_t *buf)
701 char *next;
702 size_t len2;
704 /* append string to buf (growing as needed, return -1 if "too big")
705 * return total number of bytes on the buf
708 tor_assert(string);
709 /* assert_buf_ok(buf); */
711 if (buf_ensure_capacity(buf, buf->datalen+string_len)) {
712 warn(LD_MM, "buflen too small, can't hold %d bytes.",
713 (int)(buf->datalen+string_len));
714 return -1;
717 next = _buf_end(buf);
718 _split_range(buf, next, &string_len, &len2);
720 memcpy(next, string, string_len);
721 buf->datalen += string_len;
722 buf_total_used += string_len;
724 if (len2) {
725 tor_assert(_buf_end(buf) == buf->mem);
726 memcpy(buf->mem, string+string_len, len2);
727 buf->datalen += len2;
728 buf_total_used += len2;
730 if (buf->datalen > buf->highwater)
731 buf->highwater = buf->datalen;
732 debug(LD_NET,"added %d bytes to buf (now %d total).",
733 (int)string_len, (int)buf->datalen);
734 check();
735 return buf->datalen;
738 /** Helper: copy the first <b>string_len</b> bytes from <b>buf</b>
739 * onto <b>string</b>.
741 static INLINE void
742 peek_from_buf(char *string, size_t string_len, buf_t *buf)
744 size_t len2;
746 /* There must be string_len bytes in buf; write them onto string,
747 * then memmove buf back (that is, remove them from buf).
749 * Return the number of bytes still on the buffer. */
751 tor_assert(string);
752 /* make sure we don't ask for too much */
753 tor_assert(string_len <= buf->datalen);
754 /* assert_buf_ok(buf); */
756 _split_range(buf, buf->cur, &string_len, &len2);
758 memcpy(string, buf->cur, string_len);
759 if (len2) {
760 memcpy(string+string_len,buf->mem,len2);
764 /** Remove <b>string_len</b> bytes from the front of <b>buf</b>, and store
765 * them into <b>string</b>. Return the new buffer size. <b>string_len</b>
766 * must be \<= the number of bytes on the buffer.
769 fetch_from_buf(char *string, size_t string_len, buf_t *buf)
771 /* There must be string_len bytes in buf; write them onto string,
772 * then memmove buf back (that is, remove them from buf).
774 * Return the number of bytes still on the buffer. */
776 check();
777 peek_from_buf(string, string_len, buf);
778 buf_remove_from_front(buf, string_len);
779 check();
780 return buf->datalen;
783 /** There is a (possibly incomplete) http statement on <b>buf</b>, of the
784 * form "\%s\\r\\n\\r\\n\%s", headers, body. (body may contain nuls.)
785 * If a) the headers include a Content-Length field and all bytes in
786 * the body are present, or b) there's no Content-Length field and
787 * all headers are present, then:
789 * - strdup headers into <b>*headers_out</b>, and nul-terminate it.
790 * - memdup body into <b>*body_out</b>, and nul-terminate it.
791 * - Then remove them from <b>buf</b>, and return 1.
793 * - If headers or body is NULL, discard that part of the buf.
794 * - If a headers or body doesn't fit in the arg, return -1.
795 * (We ensure that the headers or body don't exceed max len,
796 * _even if_ we're planning to discard them.)
797 * - If force_complete is true, then succeed even if not all of the
798 * content has arrived.
800 * Else, change nothing and return 0.
803 fetch_from_buf_http(buf_t *buf,
804 char **headers_out, size_t max_headerlen,
805 char **body_out, size_t *body_used, size_t max_bodylen,
806 int force_complete)
808 char *headers, *body, *p;
809 size_t headerlen, bodylen, contentlen;
811 /* assert_buf_ok(buf); */
812 buf_normalize(buf);
814 if (buf_nul_terminate(buf)<0) {
815 warn(LD_BUG,"Couldn't nul-terminate buffer");
816 return -1;
818 headers = buf->cur;
819 body = strstr(headers,"\r\n\r\n");
820 if (!body) {
821 debug(LD_HTTP,"headers not all here yet.");
822 return 0;
824 body += 4; /* Skip the the CRLFCRLF */
825 headerlen = body-headers; /* includes the CRLFCRLF */
826 bodylen = buf->datalen - headerlen;
827 debug(LD_HTTP,"headerlen %d, bodylen %d.", (int)headerlen, (int)bodylen);
829 if (max_headerlen <= headerlen) {
830 warn(LD_HTTP,"headerlen %d larger than %d. Failing.",
831 (int)headerlen, (int)max_headerlen-1);
832 return -1;
834 if (max_bodylen <= bodylen) {
835 warn(LD_HTTP,"bodylen %d larger than %d. Failing.",
836 (int)bodylen, (int)max_bodylen-1);
837 return -1;
840 #define CONTENT_LENGTH "\r\nContent-Length: "
841 p = strstr(headers, CONTENT_LENGTH);
842 if (p) {
843 int i;
844 i = atoi(p+strlen(CONTENT_LENGTH));
845 if (i < 0) {
846 warn(LD_PROTOCOL, "Content-Length is less than zero; it looks like "
847 "someone is trying to crash us.");
848 return -1;
850 contentlen = i;
851 /* if content-length is malformed, then our body length is 0. fine. */
852 debug(LD_HTTP,"Got a contentlen of %d.",(int)contentlen);
853 if (bodylen < contentlen) {
854 if (!force_complete) {
855 debug(LD_HTTP,"body not all here yet.");
856 return 0; /* not all there yet */
859 if (bodylen > contentlen) {
860 bodylen = contentlen;
861 debug(LD_HTTP,"bodylen reduced to %d.",(int)bodylen);
864 /* all happy. copy into the appropriate places, and return 1 */
865 if (headers_out) {
866 *headers_out = tor_malloc(headerlen+1);
867 memcpy(*headers_out,buf->cur,headerlen);
868 (*headers_out)[headerlen] = 0; /* null terminate it */
870 if (body_out) {
871 tor_assert(body_used);
872 *body_used = bodylen;
873 *body_out = tor_malloc(bodylen+1);
874 memcpy(*body_out,buf->cur+headerlen,bodylen);
875 (*body_out)[bodylen] = 0; /* null terminate it */
877 buf_remove_from_front(buf, headerlen+bodylen);
878 return 1;
881 /** There is a (possibly incomplete) socks handshake on <b>buf</b>, of one
882 * of the forms
883 * - socks4: "socksheader username\\0"
884 * - socks4a: "socksheader username\\0 destaddr\\0"
885 * - socks5 phase one: "version #methods methods"
886 * - socks5 phase two: "version command 0 addresstype..."
887 * If it's a complete and valid handshake, and destaddr fits in
888 * MAX_SOCKS_ADDR_LEN bytes, then pull the handshake off the buf,
889 * assign to <b>req</b>, and return 1.
891 * If it's invalid or too big, return -1.
893 * Else it's not all there yet, leave buf alone and return 0.
895 * If you want to specify the socks reply, write it into <b>req->reply</b>
896 * and set <b>req->replylen</b>, else leave <b>req->replylen</b> alone.
898 * If <b>log_sockstype</b> is non-zero, then do a notice-level log of whether
899 * the connection is possibly leaking DNS requests locally or not.
901 * If returning 0 or -1, <b>req->address</b> and <b>req->port</b> are
902 * undefined.
905 fetch_from_buf_socks(buf_t *buf, socks_request_t *req, int log_sockstype)
907 unsigned char len;
908 char tmpbuf[INET_NTOA_BUF_LEN];
909 uint32_t destip;
910 enum {socks4, socks4a} socks4_prot = socks4a;
911 char *next, *startaddr;
912 struct in_addr in;
914 /* If the user connects with socks4 or the wrong variant of socks5,
915 * then log a warning to let him know that it might be unwise. */
916 static int have_warned_about_unsafe_socks = 0;
918 if (buf->datalen < 2) /* version and another byte */
919 return 0;
920 buf_normalize(buf);
922 switch (*(buf->cur)) { /* which version of socks? */
924 case 5: /* socks5 */
926 if (req->socks_version != 5) { /* we need to negotiate a method */
927 unsigned char nummethods = (unsigned char)*(buf->cur+1);
928 tor_assert(!req->socks_version);
929 if (buf->datalen < 2u+nummethods)
930 return 0;
931 if (!nummethods || !memchr(buf->cur+2, 0, nummethods)) {
932 warn(LD_APP,
933 "socks5: offered methods don't include 'no auth'. Rejecting.");
934 req->replylen = 2; /* 2 bytes of response */
935 req->reply[0] = 5;
936 req->reply[1] = '\xFF'; /* reject all methods */
937 return -1;
939 buf_remove_from_front(buf,2+nummethods); /* remove packet from buf */
941 req->replylen = 2; /* 2 bytes of response */
942 req->reply[0] = 5; /* socks5 reply */
943 req->reply[1] = SOCKS5_SUCCEEDED;
944 req->socks_version = 5; /* remember we've already negotiated auth */
945 debug(LD_APP,"socks5: accepted method 0");
946 return 0;
948 /* we know the method; read in the request */
949 debug(LD_APP,"socks5: checking request");
950 if (buf->datalen < 8) /* basic info plus >=2 for addr plus 2 for port */
951 return 0; /* not yet */
952 req->command = (unsigned char) *(buf->cur+1);
953 if (req->command != SOCKS_COMMAND_CONNECT &&
954 req->command != SOCKS_COMMAND_RESOLVE) {
955 /* not a connect or resolve? we don't support it. */
956 warn(LD_APP,"socks5: command %d not recognized. Rejecting.",
957 req->command);
958 return -1;
960 switch (*(buf->cur+3)) { /* address type */
961 case 1: /* IPv4 address */
962 debug(LD_APP,"socks5: ipv4 address type");
963 if (buf->datalen < 10) /* ip/port there? */
964 return 0; /* not yet */
966 destip = ntohl(*(uint32_t*)(buf->cur+4));
967 in.s_addr = htonl(destip);
968 tor_inet_ntoa(&in,tmpbuf,sizeof(tmpbuf));
969 if (strlen(tmpbuf)+1 > MAX_SOCKS_ADDR_LEN) {
970 warn(LD_APP,
971 "socks5 IP takes %d bytes, which doesn't fit in %d. Rejecting.",
972 (int)strlen(tmpbuf)+1,(int)MAX_SOCKS_ADDR_LEN);
973 return -1;
975 strlcpy(req->address,tmpbuf,sizeof(req->address));
976 req->port = ntohs(*(uint16_t*)(buf->cur+8));
977 buf_remove_from_front(buf, 10);
978 if (!address_is_in_virtual_range(req->address) &&
979 !have_warned_about_unsafe_socks) {
980 warn(LD_APP,"Your application (using socks5 on port %d) is giving "
981 "Tor only an IP address. Applications that do DNS resolves "
982 "themselves may leak information. Consider using Socks4A "
983 "(e.g. via privoxy or socat) instead. For more information, "
984 "please see http://wiki.noreply.org/noreply/TheOnionRouter/"
985 "TorFAQ#SOCKSAndDNS", req->port);
986 // have_warned_about_unsafe_socks = 1; // (for now, warn every time)
988 return 1;
989 case 3: /* fqdn */
990 debug(LD_APP,"socks5: fqdn address type");
991 len = (unsigned char)*(buf->cur+4);
992 if (buf->datalen < 7u+len) /* addr/port there? */
993 return 0; /* not yet */
994 if (len+1 > MAX_SOCKS_ADDR_LEN) {
995 warn(LD_APP, "socks5 hostname is %d bytes, which doesn't fit in "
996 "%d. Rejecting.", len+1,MAX_SOCKS_ADDR_LEN);
997 return -1;
999 memcpy(req->address,buf->cur+5,len);
1000 req->address[len] = 0;
1001 req->port = ntohs(get_uint16(buf->cur+5+len));
1002 buf_remove_from_front(buf, 5+len+2);
1003 if (log_sockstype)
1004 notice(LD_APP, "Your application (using socks5 on port %d) gave "
1005 "Tor a hostname, which means Tor will do the DNS resolve "
1006 "for you. This is good.", req->port);
1007 return 1;
1008 default: /* unsupported */
1009 warn(LD_APP,"socks5: unsupported address type %d. Rejecting.",
1010 *(buf->cur+3));
1011 return -1;
1013 tor_assert(0);
1014 case 4: /* socks4 */
1015 /* http://archive.socks.permeo.com/protocol/socks4.protocol */
1016 /* http://archive.socks.permeo.com/protocol/socks4a.protocol */
1018 req->socks_version = 4;
1019 if (buf->datalen < SOCKS4_NETWORK_LEN) /* basic info available? */
1020 return 0; /* not yet */
1022 req->command = (unsigned char) *(buf->cur+1);
1023 if (req->command != SOCKS_COMMAND_CONNECT &&
1024 req->command != SOCKS_COMMAND_RESOLVE) {
1025 /* not a connect or resolve? we don't support it. */
1026 warn(LD_APP,"socks4: command %d not recognized. Rejecting.",
1027 req->command);
1028 return -1;
1031 req->port = ntohs(*(uint16_t*)(buf->cur+2));
1032 destip = ntohl(*(uint32_t*)(buf->mem+4));
1033 if ((!req->port && req->command!=SOCKS_COMMAND_RESOLVE) || !destip) {
1034 warn(LD_APP,"socks4: Port or DestIP is zero. Rejecting.");
1035 return -1;
1037 if (destip >> 8) {
1038 debug(LD_APP,"socks4: destip not in form 0.0.0.x.");
1039 in.s_addr = htonl(destip);
1040 tor_inet_ntoa(&in,tmpbuf,sizeof(tmpbuf));
1041 if (strlen(tmpbuf)+1 > MAX_SOCKS_ADDR_LEN) {
1042 debug(LD_APP,"socks4 addr (%d bytes) too long. Rejecting.",
1043 (int)strlen(tmpbuf));
1044 return -1;
1046 debug(LD_APP,"socks4: successfully read destip (%s)",safe_str(tmpbuf));
1047 socks4_prot = socks4;
1050 next = memchr(buf->cur+SOCKS4_NETWORK_LEN, 0,
1051 buf->datalen-SOCKS4_NETWORK_LEN);
1052 if (!next) {
1053 debug(LD_APP,"socks4: Username not here yet.");
1054 return 0;
1056 tor_assert(next < buf->cur+buf->datalen);
1058 startaddr = NULL;
1059 if (socks4_prot != socks4a &&
1060 !address_is_in_virtual_range(tmpbuf) &&
1061 !have_warned_about_unsafe_socks) {
1062 warn(LD_APP,"Your application (using socks4 on port %d) is giving Tor "
1063 "only an IP address. Applications that do DNS resolves "
1064 "themselves may leak information. Consider using Socks4A (e.g. "
1065 "via privoxy or socat) instead.", req->port);
1066 // have_warned_about_unsafe_socks = 1; // (for now, warn every time)
1068 if (socks4_prot == socks4a) {
1069 if (next+1 == buf->cur+buf->datalen) {
1070 debug(LD_APP,"socks4: No part of destaddr here yet.");
1071 return 0;
1073 startaddr = next+1;
1074 next = memchr(startaddr, 0, buf->cur+buf->datalen-startaddr);
1075 if (!next) {
1076 debug(LD_APP,"socks4: Destaddr not all here yet.");
1077 return 0;
1079 if (MAX_SOCKS_ADDR_LEN <= next-startaddr) {
1080 warn(LD_APP,"socks4: Destaddr too long. Rejecting.");
1081 return -1;
1083 tor_assert(next < buf->cur+buf->datalen);
1084 if (log_sockstype)
1085 notice(LD_APP, "Your application (using socks4a on port %d) gave "
1086 "Tor a hostname, which means Tor will do the DNS resolve "
1087 "for you. This is good.", req->port);
1089 debug(LD_APP,"socks4: Everything is here. Success.");
1090 strlcpy(req->address, startaddr ? startaddr : tmpbuf,
1091 sizeof(req->address));
1092 /* next points to the final \0 on inbuf */
1093 buf_remove_from_front(buf, next-buf->cur+1);
1094 return 1;
1096 case 'G': /* get */
1097 case 'H': /* head */
1098 case 'P': /* put/post */
1099 case 'C': /* connect */
1100 strlcpy(req->reply,
1101 "HTTP/1.0 501 Tor is not an HTTP Proxy\r\n"
1102 "Content-Type: text/html; charset=iso-8859-1\r\n\r\n"
1103 "<html>\n"
1104 "<head>\n"
1105 "<title>Tor is not an HTTP Proxy</title>\n"
1106 "</head>\n"
1107 "<body>\n"
1108 "<h1>Tor is not an HTTP Proxy</h1>\n"
1109 "<p>\n"
1110 "It appears you have configured your web browser to use Tor as an HTTP proxy."
1111 "\n"
1112 "This is not correct: Tor is a SOCKS proxy, not an HTTP proxy.\n"
1113 "Please configure your client accordingly.\n"
1114 "</p>\n"
1115 "<p>\n"
1116 "See <a href=\"http://tor.eff.org/documentation.html\">"
1117 "http://tor.eff.org/documentation.html</a> for more information.\n"
1118 "<!-- Plus this comment, to make the body response more than 512 bytes, so "
1119 " IE will be willing to display it. Comment comment comment comment "
1120 " comment comment comment comment comment comment comment comment.-->\n"
1121 "</p>\n"
1122 "</body>\n"
1123 "</html>\n"
1124 , MAX_SOCKS_REPLY_LEN);
1125 req->replylen = strlen(req->reply)+1;
1126 /* fall through */
1127 default: /* version is not socks4 or socks5 */
1128 warn(LD_APP,
1129 "Socks version %d not recognized. (Tor is not an http proxy.)",
1130 *(buf->cur));
1131 return -1;
1135 #define CONTROL_CMD_FRAGMENTHEADER 0x0010
1136 #define CONTROL_CMD_FRAGMENT 0x0011
1137 /** If there is a complete version 0 control message waiting on buf, then store
1138 * its contents into *<b>type_out</b>, store its body's length into
1139 * *<b>len_out</b>, allocate and store a string for its body into
1140 * *<b>body_out</b>, and return 1. (body_out will always be NUL-terminated,
1141 * even if the control message body doesn't end with NUL.)
1143 * If there is not a complete control message waiting, return 0.
1145 * Return -1 on error; return -2 on "seems to be control protocol v1."
1148 fetch_from_buf_control0(buf_t *buf, uint32_t *len_out, uint16_t *type_out,
1149 char **body_out, int check_for_v1)
1151 uint32_t msglen;
1152 uint16_t type;
1153 char tmp[4];
1155 tor_assert(buf);
1156 tor_assert(len_out);
1157 tor_assert(type_out);
1158 tor_assert(body_out);
1160 *len_out = 0;
1161 *body_out = NULL;
1163 if (buf->datalen < 4)
1164 return 0;
1166 peek_from_buf(tmp, 4, buf);
1168 msglen = ntohs(get_uint16(tmp));
1169 type = ntohs(get_uint16(tmp+2));
1170 if (type > 255 && check_for_v1)
1171 return -2;
1173 if (buf->datalen < 4 + (unsigned)msglen)
1174 return 0;
1176 *len_out = msglen;
1177 *type_out = type;
1178 buf_remove_from_front(buf, 4);
1179 if (msglen) {
1180 *body_out = tor_malloc(msglen+1);
1181 fetch_from_buf(*body_out, msglen, buf);
1182 (*body_out)[msglen] = '\0';
1184 return 1;
1187 /** Helper: return a pointer to the first instance of <b>c</b> in the
1188 * <b>len</b>characters after <b>start</b> on <b>buf</b>. Return NULL if the
1189 * character isn't found. */
1190 static char *
1191 find_char_on_buf(buf_t *buf, char *start, size_t len, char c)
1193 size_t len_rest;
1194 char *cp;
1195 _split_range(buf, start, &len, &len_rest);
1196 cp = memchr(buf->cur, c, len);
1197 if (cp || !len_rest)
1198 return cp;
1199 return memchr(buf->mem, c, len_rest);
1202 /** Helper: return a pointer to the first CRLF after cp on <b>buf</b>. Return
1203 * NULL if no CRLF is found. */
1204 static char *
1205 find_crlf_on_buf(buf_t *buf, char *cp)
1207 char *next;
1208 while (1) {
1209 size_t remaining = buf->datalen - _buf_offset(buf,cp);
1210 cp = find_char_on_buf(buf, cp, remaining, '\r');
1211 if (!cp)
1212 return NULL;
1213 next = _wrap_ptr(buf, cp+1);
1214 if (next == _buf_end(buf))
1215 return NULL;
1216 if (*next == '\n')
1217 return cp;
1218 cp = next;
1222 /** Try to read a single CRLF-terminated line from <b>buf</b>, and write it,
1223 * NUL-terminated, into the *<b>data_len</b> byte buffer at <b>data_out</b>.
1224 * Set *<b>data_len</b> to the number of bytes in the line, not counting the
1225 * terminating NUL. Return 1 if we read a whole line, return 0 if we don't
1226 * have a whole line yet, and return -1 if we we need to grow the buffer.
1229 fetch_from_buf_line(buf_t *buf, char *data_out, size_t *data_len)
1231 char *eol;
1232 size_t sz;
1233 /* Look for a CRLF. */
1234 if (!(eol = find_crlf_on_buf(buf, buf->cur))) {
1235 return 0;
1237 sz = _buf_offset(buf, eol);
1238 if (sz+3 > *data_len) {
1239 *data_len = sz+3;
1240 return -1;
1242 fetch_from_buf(data_out, sz+2, buf);
1243 data_out[sz+2] = '\0';
1244 *data_len = sz+2;
1245 return 1;
1248 /** Log an error and exit if <b>buf</b> is corrupted.
1250 void
1251 assert_buf_ok(buf_t *buf)
1253 tor_assert(buf);
1254 tor_assert(buf->magic == BUFFER_MAGIC);
1255 tor_assert(buf->mem);
1256 tor_assert(buf->highwater <= buf->len);
1257 tor_assert(buf->datalen <= buf->highwater);
1258 #ifdef SENTINELS
1260 uint32_t u32 = get_uint32(buf->mem - 4);
1261 tor_assert(u32 == START_MAGIC);
1262 u32 = get_uint32(buf->mem + buf->len);
1263 tor_assert(u32 == END_MAGIC);
1265 #endif