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 */
6 const char buffers_c_id
[] =
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.
19 #undef CHECK_AFTER_RESIZE
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)
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)
42 #define check() do { assert_buf_ok(buf); } while (0)
44 #define check() do { } while (0)
52 #define BUFFER_MAGIC 0xB0FFF312u
53 /** A resizeable buffer, optimized for reading and writing. */
55 uint32_t magic
; /**< Magic cookie for debugging: Must be set to
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
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.
83 buf_normalize(buf_t
*buf
)
86 if (buf
->cur
+ buf
->datalen
<= buf
->mem
+buf
->len
) {
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
;
103 /** Return the point in the buffer where the next byte will get stored. */
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
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. */
122 _buf_offset(buf_t
*buf
, char *cp
)
125 return cp
- buf
->cur
;
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->mem</b>. Otherwise, set *<b>more_len</b> to 0.
137 _split_range(buf_t
*buf
, char *at
, size_t *len
,
140 char *eos
= at
+ *len
;
142 if (eos
>= (buf
->mem
+ buf
->len
)) {
143 *more_len
= eos
- (buf
->mem
+ buf
->len
);
150 /** Change a buffer's capacity. <b>new_capacity</b> must be \>=
153 buf_resize(buf_t
*buf
, size_t new_capacity
)
156 #ifdef CHECK_AFTER_RESIZE
159 tor_assert(buf
->datalen
<= new_capacity
);
160 tor_assert(new_capacity
);
162 #ifdef CHECK_AFTER_RESIZE
164 tmp
= tor_malloc(buf
->datalen
);
165 tmp2
= tor_malloc(buf
->datalen
);
166 peek_from_buf(tmp
, buf
->datalen
, buf
);
169 if (buf
->len
== new_capacity
)
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
) {
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
,
186 offset
-= (buf
->len
-new_capacity
);
188 /* The data doesn't wrap around, but it does extend beyond the new
190 * mem[offset] ... mem[offset+datalen-1] (the data)
192 memmove(buf
->mem
, buf
->cur
, buf
->datalen
);
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
&&
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
);
208 buf
->mem
= buf
->cur
= newmem
;
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
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
,
231 buf
->cur
+= new_capacity
-buf
->len
;
233 buf
->len
= new_capacity
;
235 #ifdef CHECK_AFTER_RESIZE
237 peek_from_buf(tmp2
, buf
->datalen
, buf
);
238 if (memcmp(tmp
, tmp2
, buf
->datalen
)) {
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
251 buf_ensure_capacity(buf_t
*buf
, size_t capacity
)
254 if (buf
->len
>= capacity
) /* Don't grow if we're already big enough. */
256 if (capacity
> MAX_BUF_SIZE
) /* Don't grow past the maximum. */
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
)
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
);
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>->highwater, but never smaller than
275 * MIN_LAZY_SHRINK_SIZE.
278 buf_shrink(buf_t
*buf
)
283 while (buf
->highwater
< (new_len
>>2) && new_len
> MIN_LAZY_SHRINK_SIZE
*2)
286 buf
->highwater
= buf
->datalen
;
287 if (new_len
== buf
->len
)
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. */
297 buf_remove_from_front(buf_t
*buf
, size_t n
)
299 tor_assert(buf
->datalen
>= n
);
303 buf
->cur
= _wrap_ptr(buf
, buf
->cur
+n
);
310 /** Make sure that the memory in buf ends with a zero byte. */
312 buf_nul_terminate(buf_t
*buf
)
314 if (buf_ensure_capacity(buf
,buf
->datalen
+1)<0)
316 *_buf_end(buf
) = '\0';
320 /** Create and return a new buf with capacity <b>size</b>. */
322 buf_new_with_capacity(size_t size
)
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
);
331 buf_total_alloc
+= size
;
336 /** Allocate and return a new buffer with default capacity. */
340 return buf_new_with_capacity(INITIAL_BUF_SIZE
);
343 /** Remove all data from <b>buf</b>. */
345 buf_clear(buf_t
*buf
)
347 buf_total_used
-= buf
->datalen
;
352 /** Return the number of bytes stored in <b>buf</b> */
354 buf_datalen(const buf_t
*buf
)
359 /** Return the maximum bytes that can be stored in <b>buf</b> before buf
360 * needs to resize. */
362 buf_capacity(const buf_t
*buf
)
367 /** For testing only: Return a pointer to the raw memory stored in
370 _buf_peek_raw_buffer(const buf_t
*buf
)
375 /** Release storage held by <b>buf</b>. */
381 buf
->magic
= 0xDEADBEEF;
382 oldmem
= RAW_MEM(buf
->mem
);
384 buf_total_alloc
-= buf
->len
;
385 buf_total_used
-= buf
->datalen
;
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
396 read_to_buf_impl(int s
, size_t at_most
, buf_t
*buf
,
397 char *pos
, int *reached_eof
)
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 */
408 return 0; /* would block. */
409 } else if (read_result
== 0) {
410 debug(LD_NET
,"Encountered eof");
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
,
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
431 read_to_buf(int s
, size_t at_most
, buf_t
*buf
, int *reached_eof
)
437 /* assert_buf_ok(buf); */
438 tor_assert(reached_eof
);
441 if (buf_ensure_capacity(buf
,buf
->datalen
+at_most
))
444 if (at_most
+ buf
->datalen
> buf
->len
)
445 at_most
= buf
->len
- buf
->datalen
; /* take the min of the two */
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
);
455 if (r
< 0 || (size_t)r
< at_most
) {
456 return r
; /* Either error, eof, block, or no more to read. */
461 tor_assert(_buf_end(buf
) == buf
->mem
);
462 r2
= read_to_buf_impl(s
, at_start
, buf
, buf
->mem
, reached_eof
);
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,
480 read_to_buf_tls_impl(tor_tls_t
*tls
, size_t at_most
, buf_t
*buf
, char *next
)
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
),
487 r
= tor_tls_read(tls
, next
, at_most
);
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
));
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
)
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
),
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
;
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
);
546 if (r
< 0 || (size_t)r
< at_most
)
547 return r
; /* Either error, eof, block, or no more to read. */
551 tor_assert(_buf_end(buf
) == buf
->mem
);
552 r2
= read_to_buf_tls_impl(tls
, at_start
, buf
, buf
->mem
);
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.
568 flush_buf_impl(int s
, buf_t
*buf
, size_t sz
, size_t *buf_flushlen
)
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 */
578 debug(LD_NET
,"write() would block, returning.");
581 *buf_flushlen
-= write_result
;
582 buf_remove_from_front(buf
, 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
)
598 size_t flushlen0
, flushlen1
;
600 /* assert_buf_ok(buf); */
601 tor_assert(buf_flushlen
);
603 tor_assert(*buf_flushlen
<= buf
->datalen
);
604 tor_assert(sz
<= *buf_flushlen
);
606 if (sz
== 0) /* nothing to flush */
610 _split_range(buf
, buf
->cur
, &flushlen0
, &flushlen1
);
612 r
= flush_buf_impl(s
, buf
, flushlen0
, buf_flushlen
);
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. */
622 tor_assert(buf
->cur
== buf
->mem
);
623 r
= flush_buf_impl(s
, buf
, flushlen1
, buf_flushlen
);
625 debug(LD_NET
,"%d: flushed %d bytes, %d ready to flush, %d remain.",
626 s
,r
,(int)*buf_flushlen
,(int)buf
->datalen
);
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.
640 flush_buf_tls_impl(tor_tls_t
*tls
, buf_t
*buf
, size_t sz
, size_t *buf_flushlen
)
644 r
= tor_tls_write(tls
, buf
->cur
, sz
);
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
);
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
)
662 size_t flushlen0
, flushlen1
;
663 /* assert_buf_ok(buf); */
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();
674 _split_range(buf
, buf
->cur
, &flushlen0
, &flushlen1
);
676 r
= flush_buf_tls_impl(tls
, buf
, flushlen0
, buf_flushlen
);
678 if (r
< 0 || (size_t)r
< flushlen0
)
679 return r
; /* Error, or can't flush any more now. */
683 tor_assert(buf
->cur
== buf
->mem
);
684 r
= flush_buf_tls_impl(tls
, buf
, flushlen1
, buf_flushlen
);
693 /** Append <b>string_len</b> bytes from <b>string</b> to the end of
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
)
704 /* append string to buf (growing as needed, return -1 if "too big")
705 * return total number of bytes on the buf
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
));
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
;
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
);
738 /** Helper: copy the first <b>string_len</b> bytes from <b>buf</b>
739 * onto <b>string</b>.
742 peek_from_buf(char *string
, size_t string_len
, buf_t
*buf
)
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. */
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
);
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. */
777 peek_from_buf(string
, string_len
, buf
);
778 buf_remove_from_front(buf
, string_len
);
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
,
808 char *headers
, *body
, *p
;
809 size_t headerlen
, bodylen
, contentlen
;
811 /* assert_buf_ok(buf); */
814 if (buf_nul_terminate(buf
)<0) {
815 warn(LD_BUG
,"Couldn't nul-terminate buffer");
819 body
= strstr(headers
,"\r\n\r\n");
821 debug(LD_HTTP
,"headers not all here yet.");
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);
834 if (max_bodylen
<= bodylen
) {
835 warn(LD_HTTP
,"bodylen %d larger than %d. Failing.",
836 (int)bodylen
, (int)max_bodylen
-1);
840 #define CONTENT_LENGTH "\r\nContent-Length: "
841 p
= strstr(headers
, CONTENT_LENGTH
);
844 i
= atoi(p
+strlen(CONTENT_LENGTH
));
846 warn(LD_PROTOCOL
, "Content-Length is less than zero; it looks like "
847 "someone is trying to crash us.");
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 */
866 *headers_out
= tor_malloc(headerlen
+1);
867 memcpy(*headers_out
,buf
->cur
,headerlen
);
868 (*headers_out
)[headerlen
] = 0; /* null terminate it */
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
);
881 /** There is a (possibly incomplete) socks handshake on <b>buf</b>, of one
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
905 fetch_from_buf_socks(buf_t
*buf
, socks_request_t
*req
, int log_sockstype
)
908 char tmpbuf
[INET_NTOA_BUF_LEN
];
910 enum {socks4
, socks4a
} socks4_prot
= socks4a
;
911 char *next
, *startaddr
;
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 */
922 switch (*(buf
->cur
)) { /* which version of socks? */
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
)
931 if (!nummethods
|| !memchr(buf
->cur
+2, 0, nummethods
)) {
933 "socks5: offered methods don't include 'no auth'. Rejecting.");
934 req
->replylen
= 2; /* 2 bytes of response */
936 req
->reply
[1] = '\xFF'; /* reject all methods */
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");
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.",
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
) {
971 "socks5 IP takes %d bytes, which doesn't fit in %d. Rejecting.",
972 (int)strlen(tmpbuf
)+1,(int)MAX_SOCKS_ADDR_LEN
);
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)
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
);
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);
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
);
1008 default: /* unsupported */
1009 warn(LD_APP
,"socks5: unsupported address type %d. Rejecting.",
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.",
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.");
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
));
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
);
1053 debug(LD_APP
,"socks4: Username not here yet.");
1056 tor_assert(next
< buf
->cur
+buf
->datalen
);
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.");
1074 next
= memchr(startaddr
, 0, buf
->cur
+buf
->datalen
-startaddr
);
1076 debug(LD_APP
,"socks4: Destaddr not all here yet.");
1079 if (MAX_SOCKS_ADDR_LEN
<= next
-startaddr
) {
1080 warn(LD_APP
,"socks4: Destaddr too long. Rejecting.");
1083 tor_assert(next
< buf
->cur
+buf
->datalen
);
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);
1097 case 'H': /* head */
1098 case 'P': /* put/post */
1099 case 'C': /* connect */
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"
1105 "<title>Tor is not an HTTP Proxy</title>\n"
1108 "<h1>Tor is not an HTTP Proxy</h1>\n"
1110 "It appears you have configured your web browser to use Tor as an HTTP proxy."
1112 "This is not correct: Tor is a SOCKS proxy, not an HTTP proxy.\n"
1113 "Please configure your client accordingly.\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"
1124 , MAX_SOCKS_REPLY_LEN
);
1125 req
->replylen
= strlen(req
->reply
)+1;
1127 default: /* version is not socks4 or socks5 */
1129 "Socks version %d not recognized. (Tor is not an http proxy.)",
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
)
1156 tor_assert(len_out
);
1157 tor_assert(type_out
);
1158 tor_assert(body_out
);
1163 if (buf
->datalen
< 4)
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
)
1173 if (buf
->datalen
< 4 + (unsigned)msglen
)
1178 buf_remove_from_front(buf
, 4);
1180 *body_out
= tor_malloc(msglen
+1);
1181 fetch_from_buf(*body_out
, msglen
, buf
);
1182 (*body_out
)[msglen
] = '\0';
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. */
1191 find_char_on_buf(buf_t
*buf
, char *start
, size_t len
, char c
)
1195 _split_range(buf
, start
, &len
, &len_rest
);
1196 cp
= memchr(buf
->cur
, c
, len
);
1197 if (cp
|| !len_rest
)
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. */
1205 find_crlf_on_buf(buf_t
*buf
, char *cp
)
1209 size_t remaining
= buf
->datalen
- _buf_offset(buf
,cp
);
1210 cp
= find_char_on_buf(buf
, cp
, remaining
, '\r');
1213 next
= _wrap_ptr(buf
, cp
+1);
1214 if (next
== _buf_end(buf
))
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
)
1233 /* Look for a CRLF. */
1234 if (!(eol
= find_crlf_on_buf(buf
, buf
->cur
))) {
1237 sz
= _buf_offset(buf
, eol
);
1238 if (sz
+3 > *data_len
) {
1242 fetch_from_buf(data_out
, sz
+2, buf
);
1243 data_out
[sz
+2] = '\0';
1248 /** Log an error and exit if <b>buf</b> is corrupted.
1251 assert_buf_ok(buf_t
*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
);
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
);