copy changelog to releasenotes
[tor.git] / src / or / buffers.c
blob603da1bb6e79b767de956b99df6aecd971917f12
1 /* Copyright (c) 2001 Matej Pfajfar.
2 * Copyright (c) 2001-2004, Roger Dingledine.
3 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
4 * Copyright (c) 2007-2016, The Tor Project, Inc. */
5 /* See LICENSE for licensing information */
7 /**
8 * \file buffers.c
9 * \brief Implements a generic buffer interface.
11 * A buf_t is a (fairly) opaque byte-oriented FIFO that can read to or flush
12 * from memory, sockets, file descriptors, TLS connections, or another buf_t.
13 * Buffers are implemented as linked lists of memory chunks.
15 * All socket-backed and TLS-based connection_t objects have a pair of
16 * buffers: one for incoming data, and one for outcoming data. These are fed
17 * and drained from functions in connection.c, trigged by events that are
18 * monitored in main.c.
20 * This module has basic support for reading and writing on buf_t objects. It
21 * also contains specialized functions for handling particular protocols
22 * on a buf_t backend, including SOCKS (used in connection_edge.c), Tor cells
23 * (used in connection_or.c and channeltls.c), HTTP (used in directory.c), and
24 * line-oriented communication (used in control.c).
25 **/
26 #define BUFFERS_PRIVATE
27 #include "or.h"
28 #include "addressmap.h"
29 #include "buffers.h"
30 #include "config.h"
31 #include "connection_edge.h"
32 #include "connection_or.h"
33 #include "control.h"
34 #include "reasons.h"
35 #include "ext_orport.h"
36 #include "util.h"
37 #include "torlog.h"
38 #ifdef HAVE_UNISTD_H
39 #include <unistd.h>
40 #endif
42 //#define PARANOIA
44 #ifdef PARANOIA
45 /** Helper: If PARANOIA is defined, assert that the buffer in local variable
46 * <b>buf</b> is well-formed. */
47 #define check() STMT_BEGIN assert_buf_ok(buf); STMT_END
48 #else
49 #define check() STMT_NIL
50 #endif
52 /* Implementation notes:
54 * After flirting with memmove, and dallying with ring-buffers, we're finally
55 * getting up to speed with the 1970s and implementing buffers as a linked
56 * list of small chunks. Each buffer has such a list; data is removed from
57 * the head of the list, and added at the tail. The list is singly linked,
58 * and the buffer keeps a pointer to the head and the tail.
60 * Every chunk, except the tail, contains at least one byte of data. Data in
61 * each chunk is contiguous.
63 * When you need to treat the first N characters on a buffer as a contiguous
64 * string, use the buf_pullup function to make them so. Don't do this more
65 * than necessary.
67 * The major free Unix kernels have handled buffers like this since, like,
68 * forever.
71 static void socks_request_set_socks5_error(socks_request_t *req,
72 socks5_reply_status_t reason);
74 static int parse_socks(const char *data, size_t datalen, socks_request_t *req,
75 int log_sockstype, int safe_socks, ssize_t *drain_out,
76 size_t *want_length_out);
77 static int parse_socks_client(const uint8_t *data, size_t datalen,
78 int state, char **reason,
79 ssize_t *drain_out);
81 /* Chunk manipulation functions */
83 #define CHUNK_HEADER_LEN STRUCT_OFFSET(chunk_t, mem[0])
85 /* We leave this many NUL bytes at the end of the buffer. */
86 #define SENTINEL_LEN 4
88 /* Header size plus NUL bytes at the end */
89 #define CHUNK_OVERHEAD (CHUNK_HEADER_LEN + SENTINEL_LEN)
91 /** Return the number of bytes needed to allocate a chunk to hold
92 * <b>memlen</b> bytes. */
93 #define CHUNK_ALLOC_SIZE(memlen) (CHUNK_OVERHEAD + (memlen))
94 /** Return the number of usable bytes in a chunk allocated with
95 * malloc(<b>memlen</b>). */
96 #define CHUNK_SIZE_WITH_ALLOC(memlen) ((memlen) - CHUNK_OVERHEAD)
98 #define DEBUG_SENTINEL
100 #ifdef DEBUG_SENTINEL
101 #define DBG_S(s) s
102 #else
103 #define DBG_S(s) (void)0
104 #endif
106 #define CHUNK_SET_SENTINEL(chunk, alloclen) do { \
107 uint8_t *a = (uint8_t*) &(chunk)->mem[(chunk)->memlen]; \
108 DBG_S(uint8_t *b = &((uint8_t*)(chunk))[(alloclen)-SENTINEL_LEN]); \
109 DBG_S(tor_assert(a == b)); \
110 memset(a,0,SENTINEL_LEN); \
111 } while (0)
113 /** Return the next character in <b>chunk</b> onto which data can be appended.
114 * If the chunk is full, this might be off the end of chunk->mem. */
115 static inline char *
116 CHUNK_WRITE_PTR(chunk_t *chunk)
118 return chunk->data + chunk->datalen;
121 /** Return the number of bytes that can be written onto <b>chunk</b> without
122 * running out of space. */
123 static inline size_t
124 CHUNK_REMAINING_CAPACITY(const chunk_t *chunk)
126 return (chunk->mem + chunk->memlen) - (chunk->data + chunk->datalen);
129 /** Move all bytes stored in <b>chunk</b> to the front of <b>chunk</b>->mem,
130 * to free up space at the end. */
131 static inline void
132 chunk_repack(chunk_t *chunk)
134 if (chunk->datalen && chunk->data != &chunk->mem[0]) {
135 memmove(chunk->mem, chunk->data, chunk->datalen);
137 chunk->data = &chunk->mem[0];
140 /** Keep track of total size of allocated chunks for consistency asserts */
141 static size_t total_bytes_allocated_in_chunks = 0;
142 static void
143 buf_chunk_free_unchecked(chunk_t *chunk)
145 if (!chunk)
146 return;
147 #ifdef DEBUG_CHUNK_ALLOC
148 tor_assert(CHUNK_ALLOC_SIZE(chunk->memlen) == chunk->DBG_alloc);
149 #endif
150 tor_assert(total_bytes_allocated_in_chunks >=
151 CHUNK_ALLOC_SIZE(chunk->memlen));
152 total_bytes_allocated_in_chunks -= CHUNK_ALLOC_SIZE(chunk->memlen);
153 tor_free(chunk);
155 static inline chunk_t *
156 chunk_new_with_alloc_size(size_t alloc)
158 chunk_t *ch;
159 ch = tor_malloc(alloc);
160 ch->next = NULL;
161 ch->datalen = 0;
162 #ifdef DEBUG_CHUNK_ALLOC
163 ch->DBG_alloc = alloc;
164 #endif
165 ch->memlen = CHUNK_SIZE_WITH_ALLOC(alloc);
166 total_bytes_allocated_in_chunks += alloc;
167 ch->data = &ch->mem[0];
168 CHUNK_SET_SENTINEL(ch, alloc);
169 return ch;
172 /** Expand <b>chunk</b> until it can hold <b>sz</b> bytes, and return a
173 * new pointer to <b>chunk</b>. Old pointers are no longer valid. */
174 static inline chunk_t *
175 chunk_grow(chunk_t *chunk, size_t sz)
177 off_t offset;
178 const size_t memlen_orig = chunk->memlen;
179 const size_t orig_alloc = CHUNK_ALLOC_SIZE(memlen_orig);
180 const size_t new_alloc = CHUNK_ALLOC_SIZE(sz);
181 tor_assert(sz > chunk->memlen);
182 offset = chunk->data - chunk->mem;
183 chunk = tor_realloc(chunk, new_alloc);
184 chunk->memlen = sz;
185 chunk->data = chunk->mem + offset;
186 #ifdef DEBUG_CHUNK_ALLOC
187 tor_assert(chunk->DBG_alloc == orig_alloc);
188 chunk->DBG_alloc = new_alloc;
189 #endif
190 total_bytes_allocated_in_chunks += new_alloc - orig_alloc;
191 CHUNK_SET_SENTINEL(chunk, new_alloc);
192 return chunk;
195 /** If a read onto the end of a chunk would be smaller than this number, then
196 * just start a new chunk. */
197 #define MIN_READ_LEN 8
198 /** Every chunk should take up at least this many bytes. */
199 #define MIN_CHUNK_ALLOC 256
200 /** No chunk should take up more than this many bytes. */
201 #define MAX_CHUNK_ALLOC 65536
203 /** Return the allocation size we'd like to use to hold <b>target</b>
204 * bytes. */
205 STATIC size_t
206 preferred_chunk_size(size_t target)
208 tor_assert(target <= SIZE_T_CEILING - CHUNK_OVERHEAD);
209 if (CHUNK_ALLOC_SIZE(target) >= MAX_CHUNK_ALLOC)
210 return CHUNK_ALLOC_SIZE(target);
211 size_t sz = MIN_CHUNK_ALLOC;
212 while (CHUNK_SIZE_WITH_ALLOC(sz) < target) {
213 sz <<= 1;
215 return sz;
218 /** Collapse data from the first N chunks from <b>buf</b> into buf->head,
219 * growing it as necessary, until buf->head has the first <b>bytes</b> bytes
220 * of data from the buffer, or until buf->head has all the data in <b>buf</b>.
222 STATIC void
223 buf_pullup(buf_t *buf, size_t bytes)
225 chunk_t *dest, *src;
226 size_t capacity;
227 if (!buf->head)
228 return;
230 check();
231 if (buf->datalen < bytes)
232 bytes = buf->datalen;
234 capacity = bytes;
235 if (buf->head->datalen >= bytes)
236 return;
238 if (buf->head->memlen >= capacity) {
239 /* We don't need to grow the first chunk, but we might need to repack it.*/
240 size_t needed = capacity - buf->head->datalen;
241 if (CHUNK_REMAINING_CAPACITY(buf->head) < needed)
242 chunk_repack(buf->head);
243 tor_assert(CHUNK_REMAINING_CAPACITY(buf->head) >= needed);
244 } else {
245 chunk_t *newhead;
246 size_t newsize;
247 /* We need to grow the chunk. */
248 chunk_repack(buf->head);
249 newsize = CHUNK_SIZE_WITH_ALLOC(preferred_chunk_size(capacity));
250 newhead = chunk_grow(buf->head, newsize);
251 tor_assert(newhead->memlen >= capacity);
252 if (newhead != buf->head) {
253 if (buf->tail == buf->head)
254 buf->tail = newhead;
255 buf->head = newhead;
259 dest = buf->head;
260 while (dest->datalen < bytes) {
261 size_t n = bytes - dest->datalen;
262 src = dest->next;
263 tor_assert(src);
264 if (n >= src->datalen) {
265 memcpy(CHUNK_WRITE_PTR(dest), src->data, src->datalen);
266 dest->datalen += src->datalen;
267 dest->next = src->next;
268 if (buf->tail == src)
269 buf->tail = dest;
270 buf_chunk_free_unchecked(src);
271 } else {
272 memcpy(CHUNK_WRITE_PTR(dest), src->data, n);
273 dest->datalen += n;
274 src->data += n;
275 src->datalen -= n;
276 tor_assert(dest->datalen == bytes);
280 check();
283 #ifdef TOR_UNIT_TESTS
284 /* Return the data from the first chunk of buf in cp, and its length in sz. */
285 void
286 buf_get_first_chunk_data(const buf_t *buf, const char **cp, size_t *sz)
288 if (!buf || !buf->head) {
289 *cp = NULL;
290 *sz = 0;
291 } else {
292 *cp = buf->head->data;
293 *sz = buf->head->datalen;
297 /* Write sz bytes from cp into a newly allocated buffer buf.
298 * Returns NULL when passed a NULL cp or zero sz.
299 * Asserts on failure: only for use in unit tests.
300 * buf must be freed using buf_free(). */
301 buf_t *
302 buf_new_with_data(const char *cp, size_t sz)
304 /* Validate arguments */
305 if (!cp || sz <= 0) {
306 return NULL;
309 tor_assert(sz < SSIZE_T_CEILING);
311 /* Allocate a buffer */
312 buf_t *buf = buf_new_with_capacity(sz);
313 tor_assert(buf);
314 assert_buf_ok(buf);
315 tor_assert(!buf->head);
317 /* Allocate a chunk that is sz bytes long */
318 buf->head = chunk_new_with_alloc_size(CHUNK_ALLOC_SIZE(sz));
319 buf->tail = buf->head;
320 tor_assert(buf->head);
321 assert_buf_ok(buf);
322 tor_assert(buf_allocation(buf) >= sz);
324 /* Copy the data and size the buffers */
325 tor_assert(sz <= buf_slack(buf));
326 tor_assert(sz <= CHUNK_REMAINING_CAPACITY(buf->head));
327 memcpy(&buf->head->mem[0], cp, sz);
328 buf->datalen = sz;
329 buf->head->datalen = sz;
330 buf->head->data = &buf->head->mem[0];
331 assert_buf_ok(buf);
333 /* Make sure everything is large enough */
334 tor_assert(buf_allocation(buf) >= sz);
335 tor_assert(buf_allocation(buf) >= buf_datalen(buf) + buf_slack(buf));
336 /* Does the buffer implementation allocate more than the requested size?
337 * (for example, by rounding up). If so, these checks will fail. */
338 tor_assert(buf_datalen(buf) == sz);
339 tor_assert(buf_slack(buf) == 0);
341 return buf;
343 #endif
345 /** Remove the first <b>n</b> bytes from buf. */
346 static inline void
347 buf_remove_from_front(buf_t *buf, size_t n)
349 tor_assert(buf->datalen >= n);
350 while (n) {
351 tor_assert(buf->head);
352 if (buf->head->datalen > n) {
353 buf->head->datalen -= n;
354 buf->head->data += n;
355 buf->datalen -= n;
356 return;
357 } else {
358 chunk_t *victim = buf->head;
359 n -= victim->datalen;
360 buf->datalen -= victim->datalen;
361 buf->head = victim->next;
362 if (buf->tail == victim)
363 buf->tail = NULL;
364 buf_chunk_free_unchecked(victim);
367 check();
370 /** Create and return a new buf with default chunk capacity <b>size</b>.
372 buf_t *
373 buf_new_with_capacity(size_t size)
375 buf_t *b = buf_new();
376 b->default_chunk_size = preferred_chunk_size(size);
377 return b;
380 /** Allocate and return a new buffer with default capacity. */
381 buf_t *
382 buf_new(void)
384 buf_t *buf = tor_malloc_zero(sizeof(buf_t));
385 buf->magic = BUFFER_MAGIC;
386 buf->default_chunk_size = 4096;
387 return buf;
390 size_t
391 buf_get_default_chunk_size(const buf_t *buf)
393 return buf->default_chunk_size;
396 /** Remove all data from <b>buf</b>. */
397 void
398 buf_clear(buf_t *buf)
400 chunk_t *chunk, *next;
401 buf->datalen = 0;
402 for (chunk = buf->head; chunk; chunk = next) {
403 next = chunk->next;
404 buf_chunk_free_unchecked(chunk);
406 buf->head = buf->tail = NULL;
409 /** Return the number of bytes stored in <b>buf</b> */
410 MOCK_IMPL(size_t,
411 buf_datalen, (const buf_t *buf))
413 return buf->datalen;
416 /** Return the total length of all chunks used in <b>buf</b>. */
417 size_t
418 buf_allocation(const buf_t *buf)
420 size_t total = 0;
421 const chunk_t *chunk;
422 for (chunk = buf->head; chunk; chunk = chunk->next) {
423 total += CHUNK_ALLOC_SIZE(chunk->memlen);
425 return total;
428 /** Return the number of bytes that can be added to <b>buf</b> without
429 * performing any additional allocation. */
430 size_t
431 buf_slack(const buf_t *buf)
433 if (!buf->tail)
434 return 0;
435 else
436 return CHUNK_REMAINING_CAPACITY(buf->tail);
439 /** Release storage held by <b>buf</b>. */
440 void
441 buf_free(buf_t *buf)
443 if (!buf)
444 return;
446 buf_clear(buf);
447 buf->magic = 0xdeadbeef;
448 tor_free(buf);
451 /** Return a new copy of <b>in_chunk</b> */
452 static chunk_t *
453 chunk_copy(const chunk_t *in_chunk)
455 chunk_t *newch = tor_memdup(in_chunk, CHUNK_ALLOC_SIZE(in_chunk->memlen));
456 total_bytes_allocated_in_chunks += CHUNK_ALLOC_SIZE(in_chunk->memlen);
457 #ifdef DEBUG_CHUNK_ALLOC
458 newch->DBG_alloc = CHUNK_ALLOC_SIZE(in_chunk->memlen);
459 #endif
460 newch->next = NULL;
461 if (in_chunk->data) {
462 off_t offset = in_chunk->data - in_chunk->mem;
463 newch->data = newch->mem + offset;
465 return newch;
468 /** Return a new copy of <b>buf</b> */
469 buf_t *
470 buf_copy(const buf_t *buf)
472 chunk_t *ch;
473 buf_t *out = buf_new();
474 out->default_chunk_size = buf->default_chunk_size;
475 for (ch = buf->head; ch; ch = ch->next) {
476 chunk_t *newch = chunk_copy(ch);
477 if (out->tail) {
478 out->tail->next = newch;
479 out->tail = newch;
480 } else {
481 out->head = out->tail = newch;
484 out->datalen = buf->datalen;
485 return out;
488 /** Append a new chunk with enough capacity to hold <b>capacity</b> bytes to
489 * the tail of <b>buf</b>. If <b>capped</b>, don't allocate a chunk bigger
490 * than MAX_CHUNK_ALLOC. */
491 static chunk_t *
492 buf_add_chunk_with_capacity(buf_t *buf, size_t capacity, int capped)
494 chunk_t *chunk;
496 if (CHUNK_ALLOC_SIZE(capacity) < buf->default_chunk_size) {
497 chunk = chunk_new_with_alloc_size(buf->default_chunk_size);
498 } else if (capped && CHUNK_ALLOC_SIZE(capacity) > MAX_CHUNK_ALLOC) {
499 chunk = chunk_new_with_alloc_size(MAX_CHUNK_ALLOC);
500 } else {
501 chunk = chunk_new_with_alloc_size(preferred_chunk_size(capacity));
504 chunk->inserted_time = (uint32_t)monotime_coarse_absolute_msec();
506 if (buf->tail) {
507 tor_assert(buf->head);
508 buf->tail->next = chunk;
509 buf->tail = chunk;
510 } else {
511 tor_assert(!buf->head);
512 buf->head = buf->tail = chunk;
514 check();
515 return chunk;
518 /** Return the age of the oldest chunk in the buffer <b>buf</b>, in
519 * milliseconds. Requires the current monotonic time, in truncated msec,
520 * as its input <b>now</b>.
522 uint32_t
523 buf_get_oldest_chunk_timestamp(const buf_t *buf, uint32_t now)
525 if (buf->head) {
526 return now - buf->head->inserted_time;
527 } else {
528 return 0;
532 size_t
533 buf_get_total_allocation(void)
535 return total_bytes_allocated_in_chunks;
538 /** Read up to <b>at_most</b> bytes from the socket <b>fd</b> into
539 * <b>chunk</b> (which must be on <b>buf</b>). If we get an EOF, set
540 * *<b>reached_eof</b> to 1. Return -1 on error, 0 on eof or blocking,
541 * and the number of bytes read otherwise. */
542 static inline int
543 read_to_chunk(buf_t *buf, chunk_t *chunk, tor_socket_t fd, size_t at_most,
544 int *reached_eof, int *socket_error)
546 ssize_t read_result;
547 if (at_most > CHUNK_REMAINING_CAPACITY(chunk))
548 at_most = CHUNK_REMAINING_CAPACITY(chunk);
549 read_result = tor_socket_recv(fd, CHUNK_WRITE_PTR(chunk), at_most, 0);
551 if (read_result < 0) {
552 int e = tor_socket_errno(fd);
553 if (!ERRNO_IS_EAGAIN(e)) { /* it's a real error */
554 #ifdef _WIN32
555 if (e == WSAENOBUFS)
556 log_warn(LD_NET,"recv() failed: WSAENOBUFS. Not enough ram?");
557 #endif
558 *socket_error = e;
559 return -1;
561 return 0; /* would block. */
562 } else if (read_result == 0) {
563 log_debug(LD_NET,"Encountered eof on fd %d", (int)fd);
564 *reached_eof = 1;
565 return 0;
566 } else { /* actually got bytes. */
567 buf->datalen += read_result;
568 chunk->datalen += read_result;
569 log_debug(LD_NET,"Read %ld bytes. %d on inbuf.", (long)read_result,
570 (int)buf->datalen);
571 tor_assert(read_result < INT_MAX);
572 return (int)read_result;
576 /** As read_to_chunk(), but return (negative) error code on error, blocking,
577 * or TLS, and the number of bytes read otherwise. */
578 static inline int
579 read_to_chunk_tls(buf_t *buf, chunk_t *chunk, tor_tls_t *tls,
580 size_t at_most)
582 int read_result;
584 tor_assert(CHUNK_REMAINING_CAPACITY(chunk) >= at_most);
585 read_result = tor_tls_read(tls, CHUNK_WRITE_PTR(chunk), at_most);
586 if (read_result < 0)
587 return read_result;
588 buf->datalen += read_result;
589 chunk->datalen += read_result;
590 return read_result;
593 /** Read from socket <b>s</b>, writing onto end of <b>buf</b>. Read at most
594 * <b>at_most</b> bytes, growing the buffer as necessary. If recv() returns 0
595 * (because of EOF), set *<b>reached_eof</b> to 1 and return 0. Return -1 on
596 * error; else return the number of bytes read.
598 /* XXXX indicate "read blocked" somehow? */
600 read_to_buf(tor_socket_t s, size_t at_most, buf_t *buf, int *reached_eof,
601 int *socket_error)
603 /* XXXX It's stupid to overload the return values for these functions:
604 * "error status" and "number of bytes read" are not mutually exclusive.
606 int r = 0;
607 size_t total_read = 0;
609 check();
610 tor_assert(reached_eof);
611 tor_assert(SOCKET_OK(s));
613 if (BUG(buf->datalen >= INT_MAX))
614 return -1;
615 if (BUG(buf->datalen >= INT_MAX - at_most))
616 return -1;
618 while (at_most > total_read) {
619 size_t readlen = at_most - total_read;
620 chunk_t *chunk;
621 if (!buf->tail || CHUNK_REMAINING_CAPACITY(buf->tail) < MIN_READ_LEN) {
622 chunk = buf_add_chunk_with_capacity(buf, at_most, 1);
623 if (readlen > chunk->memlen)
624 readlen = chunk->memlen;
625 } else {
626 size_t cap = CHUNK_REMAINING_CAPACITY(buf->tail);
627 chunk = buf->tail;
628 if (cap < readlen)
629 readlen = cap;
632 r = read_to_chunk(buf, chunk, s, readlen, reached_eof, socket_error);
633 check();
634 if (r < 0)
635 return r; /* Error */
636 tor_assert(total_read+r < INT_MAX);
637 total_read += r;
638 if ((size_t)r < readlen) { /* eof, block, or no more to read. */
639 break;
642 return (int)total_read;
645 /** As read_to_buf, but reads from a TLS connection, and returns a TLS
646 * status value rather than the number of bytes read.
648 * Using TLS on OR connections complicates matters in two ways.
650 * First, a TLS stream has its own read buffer independent of the
651 * connection's read buffer. (TLS needs to read an entire frame from
652 * the network before it can decrypt any data. Thus, trying to read 1
653 * byte from TLS can require that several KB be read from the network
654 * and decrypted. The extra data is stored in TLS's decrypt buffer.)
655 * Because the data hasn't been read by Tor (it's still inside the TLS),
656 * this means that sometimes a connection "has stuff to read" even when
657 * poll() didn't return POLLIN. The tor_tls_get_pending_bytes function is
658 * used in connection.c to detect TLS objects with non-empty internal
659 * buffers and read from them again.
661 * Second, the TLS stream's events do not correspond directly to network
662 * events: sometimes, before a TLS stream can read, the network must be
663 * ready to write -- or vice versa.
666 read_to_buf_tls(tor_tls_t *tls, size_t at_most, buf_t *buf)
668 int r = 0;
669 size_t total_read = 0;
671 check_no_tls_errors();
673 check();
675 if (BUG(buf->datalen >= INT_MAX))
676 return -1;
677 if (BUG(buf->datalen >= INT_MAX - at_most))
678 return -1;
680 while (at_most > total_read) {
681 size_t readlen = at_most - total_read;
682 chunk_t *chunk;
683 if (!buf->tail || CHUNK_REMAINING_CAPACITY(buf->tail) < MIN_READ_LEN) {
684 chunk = buf_add_chunk_with_capacity(buf, at_most, 1);
685 if (readlen > chunk->memlen)
686 readlen = chunk->memlen;
687 } else {
688 size_t cap = CHUNK_REMAINING_CAPACITY(buf->tail);
689 chunk = buf->tail;
690 if (cap < readlen)
691 readlen = cap;
694 r = read_to_chunk_tls(buf, chunk, tls, readlen);
695 check();
696 if (r < 0)
697 return r; /* Error */
698 tor_assert(total_read+r < INT_MAX);
699 total_read += r;
700 if ((size_t)r < readlen) /* eof, block, or no more to read. */
701 break;
703 return (int)total_read;
706 /** Helper for flush_buf(): try to write <b>sz</b> bytes from chunk
707 * <b>chunk</b> of buffer <b>buf</b> onto socket <b>s</b>. On success, deduct
708 * the bytes written from *<b>buf_flushlen</b>. Return the number of bytes
709 * written on success, 0 on blocking, -1 on failure.
711 static inline int
712 flush_chunk(tor_socket_t s, buf_t *buf, chunk_t *chunk, size_t sz,
713 size_t *buf_flushlen)
715 ssize_t write_result;
717 if (sz > chunk->datalen)
718 sz = chunk->datalen;
719 write_result = tor_socket_send(s, chunk->data, sz, 0);
721 if (write_result < 0) {
722 int e = tor_socket_errno(s);
723 if (!ERRNO_IS_EAGAIN(e)) { /* it's a real error */
724 #ifdef _WIN32
725 if (e == WSAENOBUFS)
726 log_warn(LD_NET,"write() failed: WSAENOBUFS. Not enough ram?");
727 #endif
728 return -1;
730 log_debug(LD_NET,"write() would block, returning.");
731 return 0;
732 } else {
733 *buf_flushlen -= write_result;
734 buf_remove_from_front(buf, write_result);
735 tor_assert(write_result < INT_MAX);
736 return (int)write_result;
740 /** Helper for flush_buf_tls(): try to write <b>sz</b> bytes from chunk
741 * <b>chunk</b> of buffer <b>buf</b> onto socket <b>s</b>. (Tries to write
742 * more if there is a forced pending write size.) On success, deduct the
743 * bytes written from *<b>buf_flushlen</b>. Return the number of bytes
744 * written on success, and a TOR_TLS error code on failure or blocking.
746 static inline int
747 flush_chunk_tls(tor_tls_t *tls, buf_t *buf, chunk_t *chunk,
748 size_t sz, size_t *buf_flushlen)
750 int r;
751 size_t forced;
752 char *data;
754 forced = tor_tls_get_forced_write_size(tls);
755 if (forced > sz)
756 sz = forced;
757 if (chunk) {
758 data = chunk->data;
759 tor_assert(sz <= chunk->datalen);
760 } else {
761 data = NULL;
762 tor_assert(sz == 0);
764 r = tor_tls_write(tls, data, sz);
765 if (r < 0)
766 return r;
767 if (*buf_flushlen > (size_t)r)
768 *buf_flushlen -= r;
769 else
770 *buf_flushlen = 0;
771 buf_remove_from_front(buf, r);
772 log_debug(LD_NET,"flushed %d bytes, %d ready to flush, %d remain.",
773 r,(int)*buf_flushlen,(int)buf->datalen);
774 return r;
777 /** Write data from <b>buf</b> to the socket <b>s</b>. Write at most
778 * <b>sz</b> bytes, decrement *<b>buf_flushlen</b> by
779 * the number of bytes actually written, and remove the written bytes
780 * from the buffer. Return the number of bytes written on success,
781 * -1 on failure. Return 0 if write() would block.
784 flush_buf(tor_socket_t s, buf_t *buf, size_t sz, size_t *buf_flushlen)
786 /* XXXX It's stupid to overload the return values for these functions:
787 * "error status" and "number of bytes flushed" are not mutually exclusive.
789 int r;
790 size_t flushed = 0;
791 tor_assert(buf_flushlen);
792 tor_assert(SOCKET_OK(s));
793 tor_assert(*buf_flushlen <= buf->datalen);
794 tor_assert(sz <= *buf_flushlen);
796 check();
797 while (sz) {
798 size_t flushlen0;
799 tor_assert(buf->head);
800 if (buf->head->datalen >= sz)
801 flushlen0 = sz;
802 else
803 flushlen0 = buf->head->datalen;
805 r = flush_chunk(s, buf, buf->head, flushlen0, buf_flushlen);
806 check();
807 if (r < 0)
808 return r;
809 flushed += r;
810 sz -= r;
811 if (r == 0 || (size_t)r < flushlen0) /* can't flush any more now. */
812 break;
814 tor_assert(flushed < INT_MAX);
815 return (int)flushed;
818 /** As flush_buf(), but writes data to a TLS connection. Can write more than
819 * <b>flushlen</b> bytes.
822 flush_buf_tls(tor_tls_t *tls, buf_t *buf, size_t flushlen,
823 size_t *buf_flushlen)
825 int r;
826 size_t flushed = 0;
827 ssize_t sz;
828 tor_assert(buf_flushlen);
829 tor_assert(*buf_flushlen <= buf->datalen);
830 tor_assert(flushlen <= *buf_flushlen);
831 sz = (ssize_t) flushlen;
833 /* we want to let tls write even if flushlen is zero, because it might
834 * have a partial record pending */
835 check_no_tls_errors();
837 check();
838 do {
839 size_t flushlen0;
840 if (buf->head) {
841 if ((ssize_t)buf->head->datalen >= sz)
842 flushlen0 = sz;
843 else
844 flushlen0 = buf->head->datalen;
845 } else {
846 flushlen0 = 0;
849 r = flush_chunk_tls(tls, buf, buf->head, flushlen0, buf_flushlen);
850 check();
851 if (r < 0)
852 return r;
853 flushed += r;
854 sz -= r;
855 if (r == 0) /* Can't flush any more now. */
856 break;
857 } while (sz > 0);
858 tor_assert(flushed < INT_MAX);
859 return (int)flushed;
862 /** Append <b>string_len</b> bytes from <b>string</b> to the end of
863 * <b>buf</b>.
865 * Return the new length of the buffer on success, -1 on failure.
868 write_to_buf(const char *string, size_t string_len, buf_t *buf)
870 if (!string_len)
871 return (int)buf->datalen;
872 check();
874 if (BUG(buf->datalen >= INT_MAX))
875 return -1;
876 if (BUG(buf->datalen >= INT_MAX - string_len))
877 return -1;
879 while (string_len) {
880 size_t copy;
881 if (!buf->tail || !CHUNK_REMAINING_CAPACITY(buf->tail))
882 buf_add_chunk_with_capacity(buf, string_len, 1);
884 copy = CHUNK_REMAINING_CAPACITY(buf->tail);
885 if (copy > string_len)
886 copy = string_len;
887 memcpy(CHUNK_WRITE_PTR(buf->tail), string, copy);
888 string_len -= copy;
889 string += copy;
890 buf->datalen += copy;
891 buf->tail->datalen += copy;
894 check();
895 tor_assert(buf->datalen < INT_MAX);
896 return (int)buf->datalen;
899 /** Helper: copy the first <b>string_len</b> bytes from <b>buf</b>
900 * onto <b>string</b>.
902 static inline void
903 peek_from_buf(char *string, size_t string_len, const buf_t *buf)
905 chunk_t *chunk;
907 tor_assert(string);
908 /* make sure we don't ask for too much */
909 tor_assert(string_len <= buf->datalen);
910 /* assert_buf_ok(buf); */
912 chunk = buf->head;
913 while (string_len) {
914 size_t copy = string_len;
915 tor_assert(chunk);
916 if (chunk->datalen < copy)
917 copy = chunk->datalen;
918 memcpy(string, chunk->data, copy);
919 string_len -= copy;
920 string += copy;
921 chunk = chunk->next;
925 /** Remove <b>string_len</b> bytes from the front of <b>buf</b>, and store
926 * them into <b>string</b>. Return the new buffer size. <b>string_len</b>
927 * must be \<= the number of bytes on the buffer.
930 fetch_from_buf(char *string, size_t string_len, buf_t *buf)
932 /* There must be string_len bytes in buf; write them onto string,
933 * then memmove buf back (that is, remove them from buf).
935 * Return the number of bytes still on the buffer. */
937 check();
938 peek_from_buf(string, string_len, buf);
939 buf_remove_from_front(buf, string_len);
940 check();
941 tor_assert(buf->datalen < INT_MAX);
942 return (int)buf->datalen;
945 /** True iff the cell command <b>command</b> is one that implies a
946 * variable-length cell in Tor link protocol <b>linkproto</b>. */
947 static inline int
948 cell_command_is_var_length(uint8_t command, int linkproto)
950 /* If linkproto is v2 (2), CELL_VERSIONS is the only variable-length cells
951 * work as implemented here. If it's 1, there are no variable-length cells.
952 * Tor does not support other versions right now, and so can't negotiate
953 * them.
955 switch (linkproto) {
956 case 1:
957 /* Link protocol version 1 has no variable-length cells. */
958 return 0;
959 case 2:
960 /* In link protocol version 2, VERSIONS is the only variable-length cell */
961 return command == CELL_VERSIONS;
962 case 0:
963 case 3:
964 default:
965 /* In link protocol version 3 and later, and in version "unknown",
966 * commands 128 and higher indicate variable-length. VERSIONS is
967 * grandfathered in. */
968 return command == CELL_VERSIONS || command >= 128;
972 /** Check <b>buf</b> for a variable-length cell according to the rules of link
973 * protocol version <b>linkproto</b>. If one is found, pull it off the buffer
974 * and assign a newly allocated var_cell_t to *<b>out</b>, and return 1.
975 * Return 0 if whatever is on the start of buf_t is not a variable-length
976 * cell. Return 1 and set *<b>out</b> to NULL if there seems to be the start
977 * of a variable-length cell on <b>buf</b>, but the whole thing isn't there
978 * yet. */
980 fetch_var_cell_from_buf(buf_t *buf, var_cell_t **out, int linkproto)
982 char hdr[VAR_CELL_MAX_HEADER_SIZE];
983 var_cell_t *result;
984 uint8_t command;
985 uint16_t length;
986 const int wide_circ_ids = linkproto >= MIN_LINK_PROTO_FOR_WIDE_CIRC_IDS;
987 const int circ_id_len = get_circ_id_size(wide_circ_ids);
988 const unsigned header_len = get_var_cell_header_size(wide_circ_ids);
989 check();
990 *out = NULL;
991 if (buf->datalen < header_len)
992 return 0;
993 peek_from_buf(hdr, header_len, buf);
995 command = get_uint8(hdr + circ_id_len);
996 if (!(cell_command_is_var_length(command, linkproto)))
997 return 0;
999 length = ntohs(get_uint16(hdr + circ_id_len + 1));
1000 if (buf->datalen < (size_t)(header_len+length))
1001 return 1;
1002 result = var_cell_new(length);
1003 result->command = command;
1004 if (wide_circ_ids)
1005 result->circ_id = ntohl(get_uint32(hdr));
1006 else
1007 result->circ_id = ntohs(get_uint16(hdr));
1009 buf_remove_from_front(buf, header_len);
1010 peek_from_buf((char*) result->payload, length, buf);
1011 buf_remove_from_front(buf, length);
1012 check();
1014 *out = result;
1015 return 1;
1018 /** Move up to *<b>buf_flushlen</b> bytes from <b>buf_in</b> to
1019 * <b>buf_out</b>, and modify *<b>buf_flushlen</b> appropriately.
1020 * Return the number of bytes actually copied.
1023 move_buf_to_buf(buf_t *buf_out, buf_t *buf_in, size_t *buf_flushlen)
1025 /* We can do way better here, but this doesn't turn up in any profiles. */
1026 char b[4096];
1027 size_t cp, len;
1029 if (BUG(buf_out->datalen >= INT_MAX))
1030 return -1;
1031 if (BUG(buf_out->datalen >= INT_MAX - *buf_flushlen))
1032 return -1;
1034 len = *buf_flushlen;
1035 if (len > buf_in->datalen)
1036 len = buf_in->datalen;
1038 cp = len; /* Remember the number of bytes we intend to copy. */
1039 tor_assert(cp < INT_MAX);
1040 while (len) {
1041 /* This isn't the most efficient implementation one could imagine, since
1042 * it does two copies instead of 1, but I kinda doubt that this will be
1043 * critical path. */
1044 size_t n = len > sizeof(b) ? sizeof(b) : len;
1045 fetch_from_buf(b, n, buf_in);
1046 write_to_buf(b, n, buf_out);
1047 len -= n;
1049 *buf_flushlen -= cp;
1050 return (int)cp;
1053 /** Internal structure: represents a position in a buffer. */
1054 typedef struct buf_pos_t {
1055 const chunk_t *chunk; /**< Which chunk are we pointing to? */
1056 int pos;/**< Which character inside the chunk's data are we pointing to? */
1057 size_t chunk_pos; /**< Total length of all previous chunks. */
1058 } buf_pos_t;
1060 /** Initialize <b>out</b> to point to the first character of <b>buf</b>.*/
1061 static void
1062 buf_pos_init(const buf_t *buf, buf_pos_t *out)
1064 out->chunk = buf->head;
1065 out->pos = 0;
1066 out->chunk_pos = 0;
1069 /** Advance <b>out</b> to the first appearance of <b>ch</b> at the current
1070 * position of <b>out</b>, or later. Return -1 if no instances are found;
1071 * otherwise returns the absolute position of the character. */
1072 static off_t
1073 buf_find_pos_of_char(char ch, buf_pos_t *out)
1075 const chunk_t *chunk;
1076 int pos;
1077 tor_assert(out);
1078 if (out->chunk) {
1079 if (out->chunk->datalen) {
1080 tor_assert(out->pos < (off_t)out->chunk->datalen);
1081 } else {
1082 tor_assert(out->pos == 0);
1085 pos = out->pos;
1086 for (chunk = out->chunk; chunk; chunk = chunk->next) {
1087 char *cp = memchr(chunk->data+pos, ch, chunk->datalen - pos);
1088 if (cp) {
1089 out->chunk = chunk;
1090 tor_assert(cp - chunk->data < INT_MAX);
1091 out->pos = (int)(cp - chunk->data);
1092 return out->chunk_pos + out->pos;
1093 } else {
1094 out->chunk_pos += chunk->datalen;
1095 pos = 0;
1098 return -1;
1101 /** Advance <b>pos</b> by a single character, if there are any more characters
1102 * in the buffer. Returns 0 on success, -1 on failure. */
1103 static inline int
1104 buf_pos_inc(buf_pos_t *pos)
1106 ++pos->pos;
1107 if (pos->pos == (off_t)pos->chunk->datalen) {
1108 if (!pos->chunk->next)
1109 return -1;
1110 pos->chunk_pos += pos->chunk->datalen;
1111 pos->chunk = pos->chunk->next;
1112 pos->pos = 0;
1114 return 0;
1117 /** Return true iff the <b>n</b>-character string in <b>s</b> appears
1118 * (verbatim) at <b>pos</b>. */
1119 static int
1120 buf_matches_at_pos(const buf_pos_t *pos, const char *s, size_t n)
1122 buf_pos_t p;
1123 if (!n)
1124 return 1;
1126 memcpy(&p, pos, sizeof(p));
1128 while (1) {
1129 char ch = p.chunk->data[p.pos];
1130 if (ch != *s)
1131 return 0;
1132 ++s;
1133 /* If we're out of characters that don't match, we match. Check this
1134 * _before_ we test incrementing pos, in case we're at the end of the
1135 * string. */
1136 if (--n == 0)
1137 return 1;
1138 if (buf_pos_inc(&p)<0)
1139 return 0;
1143 /** Return the first position in <b>buf</b> at which the <b>n</b>-character
1144 * string <b>s</b> occurs, or -1 if it does not occur. */
1145 STATIC int
1146 buf_find_string_offset(const buf_t *buf, const char *s, size_t n)
1148 buf_pos_t pos;
1149 buf_pos_init(buf, &pos);
1150 while (buf_find_pos_of_char(*s, &pos) >= 0) {
1151 if (buf_matches_at_pos(&pos, s, n)) {
1152 tor_assert(pos.chunk_pos + pos.pos < INT_MAX);
1153 return (int)(pos.chunk_pos + pos.pos);
1154 } else {
1155 if (buf_pos_inc(&pos)<0)
1156 return -1;
1159 return -1;
1163 * Scan the HTTP headers in the <b>headerlen</b>-byte memory range at
1164 * <b>headers</b>, looking for a "Content-Length" header. Try to set
1165 * *<b>result_out</b> to the numeric value of that header if possible.
1166 * Return -1 if the header was malformed, 0 if it was missing, and 1 if
1167 * it was present and well-formed.
1169 STATIC int
1170 buf_http_find_content_length(const char *headers, size_t headerlen,
1171 size_t *result_out)
1173 const char *p, *newline;
1174 char *len_str, *eos=NULL;
1175 size_t remaining, result;
1176 int ok;
1177 *result_out = 0; /* The caller shouldn't look at this unless the
1178 * return value is 1, but let's prevent confusion */
1180 #define CONTENT_LENGTH "\r\nContent-Length: "
1181 p = (char*) tor_memstr(headers, headerlen, CONTENT_LENGTH);
1182 if (p == NULL)
1183 return 0;
1185 tor_assert(p >= headers && p < headers+headerlen);
1186 remaining = (headers+headerlen)-p;
1187 p += strlen(CONTENT_LENGTH);
1188 remaining -= strlen(CONTENT_LENGTH);
1190 newline = memchr(p, '\n', remaining);
1191 if (newline == NULL)
1192 return -1;
1194 len_str = tor_memdup_nulterm(p, newline-p);
1195 /* We limit the size to INT_MAX because other parts of the buffer.c
1196 * code don't like buffers to be any bigger than that. */
1197 result = (size_t) tor_parse_uint64(len_str, 10, 0, INT_MAX, &ok, &eos);
1198 if (eos && !tor_strisspace(eos)) {
1199 ok = 0;
1200 } else {
1201 *result_out = result;
1203 tor_free(len_str);
1205 return ok ? 1 : -1;
1208 /** There is a (possibly incomplete) http statement on <b>buf</b>, of the
1209 * form "\%s\\r\\n\\r\\n\%s", headers, body. (body may contain NULs.)
1210 * If a) the headers include a Content-Length field and all bytes in
1211 * the body are present, or b) there's no Content-Length field and
1212 * all headers are present, then:
1214 * - strdup headers into <b>*headers_out</b>, and NUL-terminate it.
1215 * - memdup body into <b>*body_out</b>, and NUL-terminate it.
1216 * - Then remove them from <b>buf</b>, and return 1.
1218 * - If headers or body is NULL, discard that part of the buf.
1219 * - If a headers or body doesn't fit in the arg, return -1.
1220 * (We ensure that the headers or body don't exceed max len,
1221 * _even if_ we're planning to discard them.)
1222 * - If force_complete is true, then succeed even if not all of the
1223 * content has arrived.
1225 * Else, change nothing and return 0.
1228 fetch_from_buf_http(buf_t *buf,
1229 char **headers_out, size_t max_headerlen,
1230 char **body_out, size_t *body_used, size_t max_bodylen,
1231 int force_complete)
1233 char *headers;
1234 size_t headerlen, bodylen, contentlen=0;
1235 int crlf_offset;
1236 int r;
1238 check();
1239 if (!buf->head)
1240 return 0;
1242 crlf_offset = buf_find_string_offset(buf, "\r\n\r\n", 4);
1243 if (crlf_offset > (int)max_headerlen ||
1244 (crlf_offset < 0 && buf->datalen > max_headerlen)) {
1245 log_debug(LD_HTTP,"headers too long.");
1246 return -1;
1247 } else if (crlf_offset < 0) {
1248 log_debug(LD_HTTP,"headers not all here yet.");
1249 return 0;
1251 /* Okay, we have a full header. Make sure it all appears in the first
1252 * chunk. */
1253 if ((int)buf->head->datalen < crlf_offset + 4)
1254 buf_pullup(buf, crlf_offset+4);
1255 headerlen = crlf_offset + 4;
1257 headers = buf->head->data;
1258 bodylen = buf->datalen - headerlen;
1259 log_debug(LD_HTTP,"headerlen %d, bodylen %d.", (int)headerlen, (int)bodylen);
1261 if (max_headerlen <= headerlen) {
1262 log_warn(LD_HTTP,"headerlen %d larger than %d. Failing.",
1263 (int)headerlen, (int)max_headerlen-1);
1264 return -1;
1266 if (max_bodylen <= bodylen) {
1267 log_warn(LD_HTTP,"bodylen %d larger than %d. Failing.",
1268 (int)bodylen, (int)max_bodylen-1);
1269 return -1;
1272 r = buf_http_find_content_length(headers, headerlen, &contentlen);
1273 if (r == -1) {
1274 log_warn(LD_PROTOCOL, "Content-Length is bogus; maybe "
1275 "someone is trying to crash us.");
1276 return -1;
1277 } else if (r == 1) {
1278 /* if content-length is malformed, then our body length is 0. fine. */
1279 log_debug(LD_HTTP,"Got a contentlen of %d.",(int)contentlen);
1280 if (bodylen < contentlen) {
1281 if (!force_complete) {
1282 log_debug(LD_HTTP,"body not all here yet.");
1283 return 0; /* not all there yet */
1286 if (bodylen > contentlen) {
1287 bodylen = contentlen;
1288 log_debug(LD_HTTP,"bodylen reduced to %d.",(int)bodylen);
1290 } else {
1291 tor_assert(r == 0);
1292 /* Leave bodylen alone */
1295 /* all happy. copy into the appropriate places, and return 1 */
1296 if (headers_out) {
1297 *headers_out = tor_malloc(headerlen+1);
1298 fetch_from_buf(*headers_out, headerlen, buf);
1299 (*headers_out)[headerlen] = 0; /* NUL terminate it */
1301 if (body_out) {
1302 tor_assert(body_used);
1303 *body_used = bodylen;
1304 *body_out = tor_malloc(bodylen+1);
1305 fetch_from_buf(*body_out, bodylen, buf);
1306 (*body_out)[bodylen] = 0; /* NUL terminate it */
1308 check();
1309 return 1;
1313 * Wait this many seconds before warning the user about using SOCKS unsafely
1314 * again (requires that WarnUnsafeSocks is turned on). */
1315 #define SOCKS_WARN_INTERVAL 5
1317 /** Warn that the user application has made an unsafe socks request using
1318 * protocol <b>socks_protocol</b> on port <b>port</b>. Don't warn more than
1319 * once per SOCKS_WARN_INTERVAL, unless <b>safe_socks</b> is set. */
1320 static void
1321 log_unsafe_socks_warning(int socks_protocol, const char *address,
1322 uint16_t port, int safe_socks)
1324 static ratelim_t socks_ratelim = RATELIM_INIT(SOCKS_WARN_INTERVAL);
1326 const or_options_t *options = get_options();
1327 if (! options->WarnUnsafeSocks)
1328 return;
1329 if (safe_socks) {
1330 log_fn_ratelim(&socks_ratelim, LOG_WARN, LD_APP,
1331 "Your application (using socks%d to port %d) is giving "
1332 "Tor only an IP address. Applications that do DNS resolves "
1333 "themselves may leak information. Consider using Socks4A "
1334 "(e.g. via privoxy or socat) instead. For more information, "
1335 "please see https://wiki.torproject.org/TheOnionRouter/"
1336 "TorFAQ#SOCKSAndDNS.%s",
1337 socks_protocol,
1338 (int)port,
1339 safe_socks ? " Rejecting." : "");
1341 control_event_client_status(LOG_WARN,
1342 "DANGEROUS_SOCKS PROTOCOL=SOCKS%d ADDRESS=%s:%d",
1343 socks_protocol, address, (int)port);
1346 /** Do not attempt to parse socks messages longer than this. This value is
1347 * actually significantly higher than the longest possible socks message. */
1348 #define MAX_SOCKS_MESSAGE_LEN 512
1350 /** Return a new socks_request_t. */
1351 socks_request_t *
1352 socks_request_new(void)
1354 return tor_malloc_zero(sizeof(socks_request_t));
1357 /** Free all storage held in the socks_request_t <b>req</b>. */
1358 void
1359 socks_request_free(socks_request_t *req)
1361 if (!req)
1362 return;
1363 if (req->username) {
1364 memwipe(req->username, 0x10, req->usernamelen);
1365 tor_free(req->username);
1367 if (req->password) {
1368 memwipe(req->password, 0x04, req->passwordlen);
1369 tor_free(req->password);
1371 memwipe(req, 0xCC, sizeof(socks_request_t));
1372 tor_free(req);
1375 /** There is a (possibly incomplete) socks handshake on <b>buf</b>, of one
1376 * of the forms
1377 * - socks4: "socksheader username\\0"
1378 * - socks4a: "socksheader username\\0 destaddr\\0"
1379 * - socks5 phase one: "version #methods methods"
1380 * - socks5 phase two: "version command 0 addresstype..."
1381 * If it's a complete and valid handshake, and destaddr fits in
1382 * MAX_SOCKS_ADDR_LEN bytes, then pull the handshake off the buf,
1383 * assign to <b>req</b>, and return 1.
1385 * If it's invalid or too big, return -1.
1387 * Else it's not all there yet, leave buf alone and return 0.
1389 * If you want to specify the socks reply, write it into <b>req->reply</b>
1390 * and set <b>req->replylen</b>, else leave <b>req->replylen</b> alone.
1392 * If <b>log_sockstype</b> is non-zero, then do a notice-level log of whether
1393 * the connection is possibly leaking DNS requests locally or not.
1395 * If <b>safe_socks</b> is true, then reject unsafe socks protocols.
1397 * If returning 0 or -1, <b>req->address</b> and <b>req->port</b> are
1398 * undefined.
1401 fetch_from_buf_socks(buf_t *buf, socks_request_t *req,
1402 int log_sockstype, int safe_socks)
1404 int res;
1405 ssize_t n_drain;
1406 size_t want_length = 128;
1408 if (buf->datalen < 2) /* version and another byte */
1409 return 0;
1411 do {
1412 n_drain = 0;
1413 buf_pullup(buf, want_length);
1414 tor_assert(buf->head && buf->head->datalen >= 2);
1415 want_length = 0;
1417 res = parse_socks(buf->head->data, buf->head->datalen, req, log_sockstype,
1418 safe_socks, &n_drain, &want_length);
1420 if (n_drain < 0)
1421 buf_clear(buf);
1422 else if (n_drain > 0)
1423 buf_remove_from_front(buf, n_drain);
1425 } while (res == 0 && buf->head && want_length < buf->datalen &&
1426 buf->datalen >= 2);
1428 return res;
1431 /** The size of the header of an Extended ORPort message: 2 bytes for
1432 * COMMAND, 2 bytes for BODYLEN */
1433 #define EXT_OR_CMD_HEADER_SIZE 4
1435 /** Read <b>buf</b>, which should contain an Extended ORPort message
1436 * from a transport proxy. If well-formed, create and populate
1437 * <b>out</b> with the Extended ORport message. Return 0 if the
1438 * buffer was incomplete, 1 if it was well-formed and -1 if we
1439 * encountered an error while parsing it. */
1441 fetch_ext_or_command_from_buf(buf_t *buf, ext_or_cmd_t **out)
1443 char hdr[EXT_OR_CMD_HEADER_SIZE];
1444 uint16_t len;
1446 check();
1447 if (buf->datalen < EXT_OR_CMD_HEADER_SIZE)
1448 return 0;
1449 peek_from_buf(hdr, sizeof(hdr), buf);
1450 len = ntohs(get_uint16(hdr+2));
1451 if (buf->datalen < (unsigned)len + EXT_OR_CMD_HEADER_SIZE)
1452 return 0;
1453 *out = ext_or_cmd_new(len);
1454 (*out)->cmd = ntohs(get_uint16(hdr));
1455 (*out)->len = len;
1456 buf_remove_from_front(buf, EXT_OR_CMD_HEADER_SIZE);
1457 fetch_from_buf((*out)->body, len, buf);
1458 return 1;
1461 /** Create a SOCKS5 reply message with <b>reason</b> in its REP field and
1462 * have Tor send it as error response to <b>req</b>.
1464 static void
1465 socks_request_set_socks5_error(socks_request_t *req,
1466 socks5_reply_status_t reason)
1468 req->replylen = 10;
1469 memset(req->reply,0,10);
1471 req->reply[0] = 0x05; // VER field.
1472 req->reply[1] = reason; // REP field.
1473 req->reply[3] = 0x01; // ATYP field.
1476 /** Implementation helper to implement fetch_from_*_socks. Instead of looking
1477 * at a buffer's contents, we look at the <b>datalen</b> bytes of data in
1478 * <b>data</b>. Instead of removing data from the buffer, we set
1479 * <b>drain_out</b> to the amount of data that should be removed (or -1 if the
1480 * buffer should be cleared). Instead of pulling more data into the first
1481 * chunk of the buffer, we set *<b>want_length_out</b> to the number of bytes
1482 * we'd like to see in the input buffer, if they're available. */
1483 static int
1484 parse_socks(const char *data, size_t datalen, socks_request_t *req,
1485 int log_sockstype, int safe_socks, ssize_t *drain_out,
1486 size_t *want_length_out)
1488 unsigned int len;
1489 char tmpbuf[TOR_ADDR_BUF_LEN+1];
1490 tor_addr_t destaddr;
1491 uint32_t destip;
1492 uint8_t socksver;
1493 char *next, *startaddr;
1494 unsigned char usernamelen, passlen;
1495 struct in_addr in;
1497 if (datalen < 2) {
1498 /* We always need at least 2 bytes. */
1499 *want_length_out = 2;
1500 return 0;
1503 if (req->socks_version == 5 && !req->got_auth) {
1504 /* See if we have received authentication. Strictly speaking, we should
1505 also check whether we actually negotiated username/password
1506 authentication. But some broken clients will send us authentication
1507 even if we negotiated SOCKS_NO_AUTH. */
1508 if (*data == 1) { /* username/pass version 1 */
1509 /* Format is: authversion [1 byte] == 1
1510 usernamelen [1 byte]
1511 username [usernamelen bytes]
1512 passlen [1 byte]
1513 password [passlen bytes] */
1514 usernamelen = (unsigned char)*(data + 1);
1515 if (datalen < 2u + usernamelen + 1u) {
1516 *want_length_out = 2u + usernamelen + 1u;
1517 return 0;
1519 passlen = (unsigned char)*(data + 2u + usernamelen);
1520 if (datalen < 2u + usernamelen + 1u + passlen) {
1521 *want_length_out = 2u + usernamelen + 1u + passlen;
1522 return 0;
1524 req->replylen = 2; /* 2 bytes of response */
1525 req->reply[0] = 1; /* authversion == 1 */
1526 req->reply[1] = 0; /* authentication successful */
1527 log_debug(LD_APP,
1528 "socks5: Accepted username/password without checking.");
1529 if (usernamelen) {
1530 req->username = tor_memdup(data+2u, usernamelen);
1531 req->usernamelen = usernamelen;
1533 if (passlen) {
1534 req->password = tor_memdup(data+3u+usernamelen, passlen);
1535 req->passwordlen = passlen;
1537 *drain_out = 2u + usernamelen + 1u + passlen;
1538 req->got_auth = 1;
1539 *want_length_out = 7; /* Minimal socks5 command. */
1540 return 0;
1541 } else if (req->auth_type == SOCKS_USER_PASS) {
1542 /* unknown version byte */
1543 log_warn(LD_APP, "Socks5 username/password version %d not recognized; "
1544 "rejecting.", (int)*data);
1545 return -1;
1549 socksver = *data;
1551 switch (socksver) { /* which version of socks? */
1552 case 5: /* socks5 */
1554 if (req->socks_version != 5) { /* we need to negotiate a method */
1555 unsigned char nummethods = (unsigned char)*(data+1);
1556 int have_user_pass, have_no_auth;
1557 int r=0;
1558 tor_assert(!req->socks_version);
1559 if (datalen < 2u+nummethods) {
1560 *want_length_out = 2u+nummethods;
1561 return 0;
1563 if (!nummethods)
1564 return -1;
1565 req->replylen = 2; /* 2 bytes of response */
1566 req->reply[0] = 5; /* socks5 reply */
1567 have_user_pass = (memchr(data+2, SOCKS_USER_PASS, nummethods) !=NULL);
1568 have_no_auth = (memchr(data+2, SOCKS_NO_AUTH, nummethods) !=NULL);
1569 if (have_user_pass && !(have_no_auth && req->socks_prefer_no_auth)) {
1570 req->auth_type = SOCKS_USER_PASS;
1571 req->reply[1] = SOCKS_USER_PASS; /* tell client to use "user/pass"
1572 auth method */
1573 req->socks_version = 5; /* remember we've already negotiated auth */
1574 log_debug(LD_APP,"socks5: accepted method 2 (username/password)");
1575 r=0;
1576 } else if (have_no_auth) {
1577 req->reply[1] = SOCKS_NO_AUTH; /* tell client to use "none" auth
1578 method */
1579 req->socks_version = 5; /* remember we've already negotiated auth */
1580 log_debug(LD_APP,"socks5: accepted method 0 (no authentication)");
1581 r=0;
1582 } else {
1583 log_warn(LD_APP,
1584 "socks5: offered methods don't include 'no auth' or "
1585 "username/password. Rejecting.");
1586 req->reply[1] = '\xFF'; /* reject all methods */
1587 r=-1;
1589 /* Remove packet from buf. Some SOCKS clients will have sent extra
1590 * junk at this point; let's hope it's an authentication message. */
1591 *drain_out = 2u + nummethods;
1593 return r;
1595 if (req->auth_type != SOCKS_NO_AUTH && !req->got_auth) {
1596 log_warn(LD_APP,
1597 "socks5: negotiated authentication, but none provided");
1598 return -1;
1600 /* we know the method; read in the request */
1601 log_debug(LD_APP,"socks5: checking request");
1602 if (datalen < 7) {/* basic info plus >=1 for addr plus 2 for port */
1603 *want_length_out = 7;
1604 return 0; /* not yet */
1606 req->command = (unsigned char) *(data+1);
1607 if (req->command != SOCKS_COMMAND_CONNECT &&
1608 req->command != SOCKS_COMMAND_RESOLVE &&
1609 req->command != SOCKS_COMMAND_RESOLVE_PTR) {
1610 /* not a connect or resolve or a resolve_ptr? we don't support it. */
1611 socks_request_set_socks5_error(req,SOCKS5_COMMAND_NOT_SUPPORTED);
1613 log_warn(LD_APP,"socks5: command %d not recognized. Rejecting.",
1614 req->command);
1615 return -1;
1617 switch (*(data+3)) { /* address type */
1618 case 1: /* IPv4 address */
1619 case 4: /* IPv6 address */ {
1620 const int is_v6 = *(data+3) == 4;
1621 const unsigned addrlen = is_v6 ? 16 : 4;
1622 log_debug(LD_APP,"socks5: ipv4 address type");
1623 if (datalen < 6+addrlen) {/* ip/port there? */
1624 *want_length_out = 6+addrlen;
1625 return 0; /* not yet */
1628 if (is_v6)
1629 tor_addr_from_ipv6_bytes(&destaddr, data+4);
1630 else
1631 tor_addr_from_ipv4n(&destaddr, get_uint32(data+4));
1633 tor_addr_to_str(tmpbuf, &destaddr, sizeof(tmpbuf), 1);
1635 if (strlen(tmpbuf)+1 > MAX_SOCKS_ADDR_LEN) {
1636 socks_request_set_socks5_error(req, SOCKS5_GENERAL_ERROR);
1637 log_warn(LD_APP,
1638 "socks5 IP takes %d bytes, which doesn't fit in %d. "
1639 "Rejecting.",
1640 (int)strlen(tmpbuf)+1,(int)MAX_SOCKS_ADDR_LEN);
1641 return -1;
1643 strlcpy(req->address,tmpbuf,sizeof(req->address));
1644 req->port = ntohs(get_uint16(data+4+addrlen));
1645 *drain_out = 6+addrlen;
1646 if (req->command != SOCKS_COMMAND_RESOLVE_PTR &&
1647 !addressmap_have_mapping(req->address,0)) {
1648 log_unsafe_socks_warning(5, req->address, req->port, safe_socks);
1649 if (safe_socks) {
1650 socks_request_set_socks5_error(req, SOCKS5_NOT_ALLOWED);
1651 return -1;
1654 return 1;
1656 case 3: /* fqdn */
1657 log_debug(LD_APP,"socks5: fqdn address type");
1658 if (req->command == SOCKS_COMMAND_RESOLVE_PTR) {
1659 socks_request_set_socks5_error(req,
1660 SOCKS5_ADDRESS_TYPE_NOT_SUPPORTED);
1661 log_warn(LD_APP, "socks5 received RESOLVE_PTR command with "
1662 "hostname type. Rejecting.");
1663 return -1;
1665 len = (unsigned char)*(data+4);
1666 if (datalen < 7+len) { /* addr/port there? */
1667 *want_length_out = 7+len;
1668 return 0; /* not yet */
1670 if (len+1 > MAX_SOCKS_ADDR_LEN) {
1671 socks_request_set_socks5_error(req, SOCKS5_GENERAL_ERROR);
1672 log_warn(LD_APP,
1673 "socks5 hostname is %d bytes, which doesn't fit in "
1674 "%d. Rejecting.", len+1,MAX_SOCKS_ADDR_LEN);
1675 return -1;
1677 memcpy(req->address,data+5,len);
1678 req->address[len] = 0;
1679 req->port = ntohs(get_uint16(data+5+len));
1680 *drain_out = 5+len+2;
1682 if (string_is_valid_ipv4_address(req->address) ||
1683 string_is_valid_ipv6_address(req->address)) {
1684 log_unsafe_socks_warning(5,req->address,req->port,safe_socks);
1686 if (safe_socks) {
1687 socks_request_set_socks5_error(req, SOCKS5_NOT_ALLOWED);
1688 return -1;
1690 } else if (!string_is_valid_hostname(req->address)) {
1691 socks_request_set_socks5_error(req, SOCKS5_GENERAL_ERROR);
1693 log_warn(LD_PROTOCOL,
1694 "Your application (using socks5 to port %d) gave Tor "
1695 "a malformed hostname: %s. Rejecting the connection.",
1696 req->port, escaped_safe_str_client(req->address));
1697 return -1;
1699 if (log_sockstype)
1700 log_notice(LD_APP,
1701 "Your application (using socks5 to port %d) instructed "
1702 "Tor to take care of the DNS resolution itself if "
1703 "necessary. This is good.", req->port);
1704 return 1;
1705 default: /* unsupported */
1706 socks_request_set_socks5_error(req,
1707 SOCKS5_ADDRESS_TYPE_NOT_SUPPORTED);
1708 log_warn(LD_APP,"socks5: unsupported address type %d. Rejecting.",
1709 (int) *(data+3));
1710 return -1;
1712 tor_assert(0);
1713 case 4: { /* socks4 */
1714 enum {socks4, socks4a} socks4_prot = socks4a;
1715 const char *authstart, *authend;
1716 /* http://ss5.sourceforge.net/socks4.protocol.txt */
1717 /* http://ss5.sourceforge.net/socks4A.protocol.txt */
1719 req->socks_version = 4;
1720 if (datalen < SOCKS4_NETWORK_LEN) {/* basic info available? */
1721 *want_length_out = SOCKS4_NETWORK_LEN;
1722 return 0; /* not yet */
1724 // buf_pullup(buf, 1280);
1725 req->command = (unsigned char) *(data+1);
1726 if (req->command != SOCKS_COMMAND_CONNECT &&
1727 req->command != SOCKS_COMMAND_RESOLVE) {
1728 /* not a connect or resolve? we don't support it. (No resolve_ptr with
1729 * socks4.) */
1730 log_warn(LD_APP,"socks4: command %d not recognized. Rejecting.",
1731 req->command);
1732 return -1;
1735 req->port = ntohs(get_uint16(data+2));
1736 destip = ntohl(get_uint32(data+4));
1737 if ((!req->port && req->command!=SOCKS_COMMAND_RESOLVE) || !destip) {
1738 log_warn(LD_APP,"socks4: Port or DestIP is zero. Rejecting.");
1739 return -1;
1741 if (destip >> 8) {
1742 log_debug(LD_APP,"socks4: destip not in form 0.0.0.x.");
1743 in.s_addr = htonl(destip);
1744 tor_inet_ntoa(&in,tmpbuf,sizeof(tmpbuf));
1745 if (strlen(tmpbuf)+1 > MAX_SOCKS_ADDR_LEN) {
1746 log_debug(LD_APP,"socks4 addr (%d bytes) too long. Rejecting.",
1747 (int)strlen(tmpbuf));
1748 return -1;
1750 log_debug(LD_APP,
1751 "socks4: successfully read destip (%s)",
1752 safe_str_client(tmpbuf));
1753 socks4_prot = socks4;
1756 authstart = data + SOCKS4_NETWORK_LEN;
1757 next = memchr(authstart, 0,
1758 datalen-SOCKS4_NETWORK_LEN);
1759 if (!next) {
1760 if (datalen >= 1024) {
1761 log_debug(LD_APP, "Socks4 user name too long; rejecting.");
1762 return -1;
1764 log_debug(LD_APP,"socks4: Username not here yet.");
1765 *want_length_out = datalen+1024; /* More than we need, but safe */
1766 return 0;
1768 authend = next;
1769 tor_assert(next < data+datalen);
1771 startaddr = NULL;
1772 if (socks4_prot != socks4a &&
1773 !addressmap_have_mapping(tmpbuf,0)) {
1774 log_unsafe_socks_warning(4, tmpbuf, req->port, safe_socks);
1776 if (safe_socks)
1777 return -1;
1779 if (socks4_prot == socks4a) {
1780 if (next+1 == data+datalen) {
1781 log_debug(LD_APP,"socks4: No part of destaddr here yet.");
1782 *want_length_out = datalen + 1024; /* More than we need, but safe */
1783 return 0;
1785 startaddr = next+1;
1786 next = memchr(startaddr, 0, data + datalen - startaddr);
1787 if (!next) {
1788 if (datalen >= 1024) {
1789 log_debug(LD_APP,"socks4: Destaddr too long.");
1790 return -1;
1792 log_debug(LD_APP,"socks4: Destaddr not all here yet.");
1793 *want_length_out = datalen + 1024; /* More than we need, but safe */
1794 return 0;
1796 if (MAX_SOCKS_ADDR_LEN <= next-startaddr) {
1797 log_warn(LD_APP,"socks4: Destaddr too long. Rejecting.");
1798 return -1;
1800 // tor_assert(next < buf->cur+buf->datalen);
1802 if (log_sockstype)
1803 log_notice(LD_APP,
1804 "Your application (using socks4a to port %d) instructed "
1805 "Tor to take care of the DNS resolution itself if "
1806 "necessary. This is good.", req->port);
1808 log_debug(LD_APP,"socks4: Everything is here. Success.");
1809 strlcpy(req->address, startaddr ? startaddr : tmpbuf,
1810 sizeof(req->address));
1811 if (!tor_strisprint(req->address) || strchr(req->address,'\"')) {
1812 log_warn(LD_PROTOCOL,
1813 "Your application (using socks4 to port %d) gave Tor "
1814 "a malformed hostname: %s. Rejecting the connection.",
1815 req->port, escaped_safe_str_client(req->address));
1816 return -1;
1818 if (authend != authstart) {
1819 req->got_auth = 1;
1820 req->usernamelen = authend - authstart;
1821 req->username = tor_memdup(authstart, authend - authstart);
1823 /* next points to the final \0 on inbuf */
1824 *drain_out = next - data + 1;
1825 return 1;
1827 case 'G': /* get */
1828 case 'H': /* head */
1829 case 'P': /* put/post */
1830 case 'C': /* connect */
1831 strlcpy((char*)req->reply,
1832 "HTTP/1.0 501 Tor is not an HTTP Proxy\r\n"
1833 "Content-Type: text/html; charset=iso-8859-1\r\n\r\n"
1834 "<html>\n"
1835 "<head>\n"
1836 "<title>Tor is not an HTTP Proxy</title>\n"
1837 "</head>\n"
1838 "<body>\n"
1839 "<h1>Tor is not an HTTP Proxy</h1>\n"
1840 "<p>\n"
1841 "It appears you have configured your web browser to use Tor as an HTTP proxy."
1842 "\n"
1843 "This is not correct: Tor is a SOCKS proxy, not an HTTP proxy.\n"
1844 "Please configure your client accordingly.\n"
1845 "</p>\n"
1846 "<p>\n"
1847 "See <a href=\"https://www.torproject.org/documentation.html\">"
1848 "https://www.torproject.org/documentation.html</a> for more "
1849 "information.\n"
1850 "<!-- Plus this comment, to make the body response more than 512 bytes, so "
1851 " IE will be willing to display it. Comment comment comment comment "
1852 " comment comment comment comment comment comment comment comment.-->\n"
1853 "</p>\n"
1854 "</body>\n"
1855 "</html>\n"
1856 , MAX_SOCKS_REPLY_LEN);
1857 req->replylen = strlen((char*)req->reply)+1;
1858 /* fall through */
1859 default: /* version is not socks4 or socks5 */
1860 log_warn(LD_APP,
1861 "Socks version %d not recognized. (Tor is not an http proxy.)",
1862 *(data));
1864 /* Tell the controller the first 8 bytes. */
1865 char *tmp = tor_strndup(data, datalen < 8 ? datalen : 8);
1866 control_event_client_status(LOG_WARN,
1867 "SOCKS_UNKNOWN_PROTOCOL DATA=\"%s\"",
1868 escaped(tmp));
1869 tor_free(tmp);
1871 return -1;
1875 /** Inspect a reply from SOCKS server stored in <b>buf</b> according
1876 * to <b>state</b>, removing the protocol data upon success. Return 0 on
1877 * incomplete response, 1 on success and -1 on error, in which case
1878 * <b>reason</b> is set to a descriptive message (free() when finished
1879 * with it).
1881 * As a special case, 2 is returned when user/pass is required
1882 * during SOCKS5 handshake and user/pass is configured.
1885 fetch_from_buf_socks_client(buf_t *buf, int state, char **reason)
1887 ssize_t drain = 0;
1888 int r;
1889 if (buf->datalen < 2)
1890 return 0;
1892 buf_pullup(buf, MAX_SOCKS_MESSAGE_LEN);
1893 tor_assert(buf->head && buf->head->datalen >= 2);
1895 r = parse_socks_client((uint8_t*)buf->head->data, buf->head->datalen,
1896 state, reason, &drain);
1897 if (drain > 0)
1898 buf_remove_from_front(buf, drain);
1899 else if (drain < 0)
1900 buf_clear(buf);
1902 return r;
1905 /** Implementation logic for fetch_from_*_socks_client. */
1906 static int
1907 parse_socks_client(const uint8_t *data, size_t datalen,
1908 int state, char **reason,
1909 ssize_t *drain_out)
1911 unsigned int addrlen;
1912 *drain_out = 0;
1913 if (datalen < 2)
1914 return 0;
1916 switch (state) {
1917 case PROXY_SOCKS4_WANT_CONNECT_OK:
1918 /* Wait for the complete response */
1919 if (datalen < 8)
1920 return 0;
1922 if (data[1] != 0x5a) {
1923 *reason = tor_strdup(socks4_response_code_to_string(data[1]));
1924 return -1;
1927 /* Success */
1928 *drain_out = 8;
1929 return 1;
1931 case PROXY_SOCKS5_WANT_AUTH_METHOD_NONE:
1932 /* we don't have any credentials */
1933 if (data[1] != 0x00) {
1934 *reason = tor_strdup("server doesn't support any of our "
1935 "available authentication methods");
1936 return -1;
1939 log_info(LD_NET, "SOCKS 5 client: continuing without authentication");
1940 *drain_out = -1;
1941 return 1;
1943 case PROXY_SOCKS5_WANT_AUTH_METHOD_RFC1929:
1944 /* we have a username and password. return 1 if we can proceed without
1945 * providing authentication, or 2 otherwise. */
1946 switch (data[1]) {
1947 case 0x00:
1948 log_info(LD_NET, "SOCKS 5 client: we have auth details but server "
1949 "doesn't require authentication.");
1950 *drain_out = -1;
1951 return 1;
1952 case 0x02:
1953 log_info(LD_NET, "SOCKS 5 client: need authentication.");
1954 *drain_out = -1;
1955 return 2;
1956 /* fall through */
1959 *reason = tor_strdup("server doesn't support any of our available "
1960 "authentication methods");
1961 return -1;
1963 case PROXY_SOCKS5_WANT_AUTH_RFC1929_OK:
1964 /* handle server reply to rfc1929 authentication */
1965 if (data[1] != 0x00) {
1966 *reason = tor_strdup("authentication failed");
1967 return -1;
1970 log_info(LD_NET, "SOCKS 5 client: authentication successful.");
1971 *drain_out = -1;
1972 return 1;
1974 case PROXY_SOCKS5_WANT_CONNECT_OK:
1975 /* response is variable length. BND.ADDR, etc, isn't needed
1976 * (don't bother with buf_pullup()), but make sure to eat all
1977 * the data used */
1979 /* wait for address type field to arrive */
1980 if (datalen < 4)
1981 return 0;
1983 switch (data[3]) {
1984 case 0x01: /* ip4 */
1985 addrlen = 4;
1986 break;
1987 case 0x04: /* ip6 */
1988 addrlen = 16;
1989 break;
1990 case 0x03: /* fqdn (can this happen here?) */
1991 if (datalen < 5)
1992 return 0;
1993 addrlen = 1 + data[4];
1994 break;
1995 default:
1996 *reason = tor_strdup("invalid response to connect request");
1997 return -1;
2000 /* wait for address and port */
2001 if (datalen < 6 + addrlen)
2002 return 0;
2004 if (data[1] != 0x00) {
2005 *reason = tor_strdup(socks5_response_code_to_string(data[1]));
2006 return -1;
2009 *drain_out = 6 + addrlen;
2010 return 1;
2013 /* shouldn't get here... */
2014 tor_assert(0);
2016 return -1;
2019 /** Return 1 iff buf looks more like it has an (obsolete) v0 controller
2020 * command on it than any valid v1 controller command. */
2022 peek_buf_has_control0_command(buf_t *buf)
2024 if (buf->datalen >= 4) {
2025 char header[4];
2026 uint16_t cmd;
2027 peek_from_buf(header, sizeof(header), buf);
2028 cmd = ntohs(get_uint16(header+2));
2029 if (cmd <= 0x14)
2030 return 1; /* This is definitely not a v1 control command. */
2032 return 0;
2035 /** Return the index within <b>buf</b> at which <b>ch</b> first appears,
2036 * or -1 if <b>ch</b> does not appear on buf. */
2037 static off_t
2038 buf_find_offset_of_char(buf_t *buf, char ch)
2040 chunk_t *chunk;
2041 off_t offset = 0;
2042 for (chunk = buf->head; chunk; chunk = chunk->next) {
2043 char *cp = memchr(chunk->data, ch, chunk->datalen);
2044 if (cp)
2045 return offset + (cp - chunk->data);
2046 else
2047 offset += chunk->datalen;
2049 return -1;
2052 /** Try to read a single LF-terminated line from <b>buf</b>, and write it
2053 * (including the LF), NUL-terminated, into the *<b>data_len</b> byte buffer
2054 * at <b>data_out</b>. Set *<b>data_len</b> to the number of bytes in the
2055 * line, not counting the terminating NUL. Return 1 if we read a whole line,
2056 * return 0 if we don't have a whole line yet, and return -1 if the line
2057 * length exceeds *<b>data_len</b>.
2060 fetch_from_buf_line(buf_t *buf, char *data_out, size_t *data_len)
2062 size_t sz;
2063 off_t offset;
2065 if (!buf->head)
2066 return 0;
2068 offset = buf_find_offset_of_char(buf, '\n');
2069 if (offset < 0)
2070 return 0;
2071 sz = (size_t) offset;
2072 if (sz+2 > *data_len) {
2073 *data_len = sz + 2;
2074 return -1;
2076 fetch_from_buf(data_out, sz+1, buf);
2077 data_out[sz+1] = '\0';
2078 *data_len = sz+1;
2079 return 1;
2082 /** Compress on uncompress the <b>data_len</b> bytes in <b>data</b> using the
2083 * zlib state <b>state</b>, appending the result to <b>buf</b>. If
2084 * <b>done</b> is true, flush the data in the state and finish the
2085 * compression/uncompression. Return -1 on failure, 0 on success. */
2087 write_to_buf_zlib(buf_t *buf, tor_zlib_state_t *state,
2088 const char *data, size_t data_len,
2089 int done)
2091 char *next;
2092 size_t old_avail, avail;
2093 int over = 0;
2095 do {
2096 int need_new_chunk = 0;
2097 if (!buf->tail || ! CHUNK_REMAINING_CAPACITY(buf->tail)) {
2098 size_t cap = data_len / 4;
2099 buf_add_chunk_with_capacity(buf, cap, 1);
2101 next = CHUNK_WRITE_PTR(buf->tail);
2102 avail = old_avail = CHUNK_REMAINING_CAPACITY(buf->tail);
2103 switch (tor_zlib_process(state, &next, &avail, &data, &data_len, done)) {
2104 case TOR_ZLIB_DONE:
2105 over = 1;
2106 break;
2107 case TOR_ZLIB_ERR:
2108 return -1;
2109 case TOR_ZLIB_OK:
2110 if (data_len == 0)
2111 over = 1;
2112 break;
2113 case TOR_ZLIB_BUF_FULL:
2114 if (avail) {
2115 /* Zlib says we need more room (ZLIB_BUF_FULL). Start a new chunk
2116 * automatically, whether were going to or not. */
2117 need_new_chunk = 1;
2119 break;
2121 buf->datalen += old_avail - avail;
2122 buf->tail->datalen += old_avail - avail;
2123 if (need_new_chunk) {
2124 buf_add_chunk_with_capacity(buf, data_len/4, 1);
2127 } while (!over);
2128 check();
2129 return 0;
2132 /** Set *<b>output</b> to contain a copy of the data in *<b>input</b> */
2134 buf_set_to_copy(buf_t **output,
2135 const buf_t *input)
2137 if (*output)
2138 buf_free(*output);
2139 *output = buf_copy(input);
2140 return 0;
2143 /** Log an error and exit if <b>buf</b> is corrupted.
2145 void
2146 assert_buf_ok(buf_t *buf)
2148 tor_assert(buf);
2149 tor_assert(buf->magic == BUFFER_MAGIC);
2151 if (! buf->head) {
2152 tor_assert(!buf->tail);
2153 tor_assert(buf->datalen == 0);
2154 } else {
2155 chunk_t *ch;
2156 size_t total = 0;
2157 tor_assert(buf->tail);
2158 for (ch = buf->head; ch; ch = ch->next) {
2159 total += ch->datalen;
2160 tor_assert(ch->datalen <= ch->memlen);
2161 tor_assert(ch->data >= &ch->mem[0]);
2162 tor_assert(ch->data <= &ch->mem[0]+ch->memlen);
2163 if (ch->data == &ch->mem[0]+ch->memlen) {
2164 static int warned = 0;
2165 if (! warned) {
2166 log_warn(LD_BUG, "Invariant violation in buf.c related to #15083");
2167 warned = 1;
2170 tor_assert(ch->data+ch->datalen <= &ch->mem[0] + ch->memlen);
2171 if (!ch->next)
2172 tor_assert(ch == buf->tail);
2174 tor_assert(buf->datalen == total);