buffers.c 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699
  1. /* Copyright 2001 Matej Pfajfar.
  2. * Copyright 2001-2004 Roger Dingledine.
  3. * Copyright 2004 Roger Dingledine, Nick Mathewson. */
  4. /* See LICENSE for licensing information */
  5. /* $Id$ */
  6. const char buffers_c_id[] = "$Id$";
  7. /**
  8. * \file buffers.c
  9. * \brief Abstractions for buffered IO.
  10. **/
  11. #include "or.h"
  12. #define BUFFER_MAGIC 0xB0FFF312u
  13. struct buf_t {
  14. uint32_t magic; /**< Magic cookie for debugging: Must be set to BUFFER_MAGIC */
  15. char *mem; /**< Storage for data in the buffer */
  16. size_t len; /**< Maximum amount of data that <b>mem</b> can hold. */
  17. size_t datalen; /**< Number of bytes currently in <b>mem</b>. */
  18. };
  19. /** Size, in bytes, for newly allocated buffers. Should be a power of 2. */
  20. #define INITIAL_BUF_SIZE (4*1024)
  21. /** Maximum size, in bytes, for resized buffers. */
  22. #define MAX_BUF_SIZE (1024*1024*10)
  23. /** Size, in bytes, for minimum 'shrink' size for buffers. Buffers may start
  24. * out smaller than this, but they will never autoshrink to less
  25. * than this size. */
  26. #define MIN_BUF_SHRINK_SIZE (16*1024)
  27. /** Change a buffer's capacity. <b>new_capacity</b> must be \<= buf->datalen. */
  28. static INLINE void buf_resize(buf_t *buf, size_t new_capacity)
  29. {
  30. tor_assert(buf->datalen <= new_capacity);
  31. tor_assert(new_capacity);
  32. buf->mem = tor_realloc(buf->mem, new_capacity);
  33. buf->len = new_capacity;
  34. }
  35. /** If the buffer is not large enough to hold <b>capacity</b> bytes, resize
  36. * it so that it can. (The new size will be a power of 2 times the old
  37. * size.)
  38. */
  39. static INLINE int buf_ensure_capacity(buf_t *buf, size_t capacity)
  40. {
  41. size_t new_len;
  42. if (buf->len >= capacity) /* Don't grow if we're already big enough. */
  43. return 0;
  44. if (capacity > MAX_BUF_SIZE) /* Don't grow past the maximum. */
  45. return -1;
  46. /* Find the smallest new_len equal to (2**X)*len for some X; such that
  47. * new_len is at least capacity.
  48. */
  49. new_len = buf->len*2;
  50. while (new_len < capacity)
  51. new_len *= 2;
  52. /* Resize the buffer. */
  53. log_fn(LOG_DEBUG,"Growing buffer from %d to %d bytes.",
  54. (int)buf->len, (int)new_len);
  55. buf_resize(buf,new_len);
  56. return 0;
  57. }
  58. /** If the buffer is at least 2*MIN_BUF_SHRINK_SIZE bytes in capacity,
  59. * and if the buffer is less than 1/4 full, shrink the buffer until
  60. * one of the above no longer holds. (We shrink the buffer by
  61. * dividing by powers of 2.)
  62. */
  63. static INLINE void buf_shrink_if_underfull(buf_t *buf) {
  64. size_t new_len;
  65. /* If the buffer is at least .25 full, or if shrinking the buffer would
  66. * put it under MIN_BUF_SHRINK_SIZE, don't do it. */
  67. if (buf->datalen >= buf->len/4 || buf->len < 2*MIN_BUF_SHRINK_SIZE)
  68. return;
  69. /* Shrink new_len by powers of 2 until: datalen is at least 1/4 of
  70. * new_len, OR shrinking new_len more would put it under
  71. * MIN_BUF_SHRINK_SIZE.
  72. */
  73. new_len = buf->len / 2;
  74. while (buf->datalen < new_len/4 && new_len/2 > MIN_BUF_SHRINK_SIZE)
  75. new_len /= 2;
  76. log_fn(LOG_DEBUG,"Shrinking buffer from %d to %d bytes.",
  77. (int)buf->len, (int)new_len);
  78. buf_resize(buf, new_len);
  79. }
  80. /** Remove the first <b>n</b> bytes from buf.
  81. */
  82. static INLINE void buf_remove_from_front(buf_t *buf, size_t n) {
  83. tor_assert(buf->datalen >= n);
  84. buf->datalen -= n;
  85. memmove(buf->mem, buf->mem+n, buf->datalen);
  86. buf_shrink_if_underfull(buf);
  87. }
  88. /** Make sure that the memory in buf ends with a zero byte. */
  89. static INLINE int buf_nul_terminate(buf_t *buf)
  90. {
  91. if (buf_ensure_capacity(buf,buf->datalen+1)<0)
  92. return -1;
  93. buf->mem[buf->datalen] = '\0';
  94. return 0;
  95. }
  96. /** Create and return a new buf with capacity <b>size</b>.
  97. */
  98. buf_t *buf_new_with_capacity(size_t size) {
  99. buf_t *buf;
  100. buf = tor_malloc(sizeof(buf_t));
  101. buf->magic = BUFFER_MAGIC;
  102. buf->mem = tor_malloc(size);
  103. buf->len = size;
  104. buf->datalen = 0;
  105. // memset(buf->mem,0,size);
  106. assert_buf_ok(buf);
  107. return buf;
  108. }
  109. /** Allocate and return a new buffer with default capacity. */
  110. buf_t *buf_new()
  111. {
  112. return buf_new_with_capacity(INITIAL_BUF_SIZE);
  113. }
  114. /** Remove all data from <b>buf</b> */
  115. void buf_clear(buf_t *buf)
  116. {
  117. buf->datalen = 0;
  118. }
  119. /** Return the number of bytes stored in <b>buf</b> */
  120. size_t buf_datalen(const buf_t *buf)
  121. {
  122. return buf->datalen;
  123. }
  124. /** Return the maximum bytes that can be stored in <b>buf</b> before buf
  125. * needs to resize. */
  126. size_t buf_capacity(const buf_t *buf)
  127. {
  128. return buf->len;
  129. }
  130. /** For testing only: Return a pointer to the raw memory stored in <b>buf</b>.
  131. */
  132. const char *_buf_peek_raw_buffer(const buf_t *buf)
  133. {
  134. return buf->mem;
  135. }
  136. /** Release storage held by <b>buf</b>.
  137. */
  138. void buf_free(buf_t *buf) {
  139. assert_buf_ok(buf);
  140. buf->magic = 0xDEADBEEF;
  141. tor_free(buf->mem);
  142. tor_free(buf);
  143. }
  144. /** Read from socket <b>s</b>, writing onto end of <b>buf</b>. Read at most
  145. * <b>at_most</b> bytes, resizing the buffer as necessary. If recv()
  146. * returns 0, set <b>*reached_eof</b> to 1 and return 0. Return -1 on error;
  147. * else return the number of bytes read. Return 0 if recv() would
  148. * block.
  149. */
  150. int read_to_buf(int s, size_t at_most, buf_t *buf, int *reached_eof) {
  151. int read_result;
  152. assert_buf_ok(buf);
  153. tor_assert(reached_eof);
  154. tor_assert(s>=0);
  155. if (buf_ensure_capacity(buf,buf->datalen+at_most))
  156. return -1;
  157. if (at_most + buf->datalen > buf->len)
  158. at_most = buf->len - buf->datalen; /* take the min of the two */
  159. if (at_most == 0)
  160. return 0; /* we shouldn't read anything */
  161. // log_fn(LOG_DEBUG,"reading at most %d bytes.",at_most);
  162. read_result = recv(s, buf->mem+buf->datalen, at_most, 0);
  163. if (read_result < 0) {
  164. int e = tor_socket_errno(s);
  165. if (!ERRNO_IS_EAGAIN(e)) { /* it's a real error */
  166. return -1;
  167. }
  168. return 0; /* would block. */
  169. } else if (read_result == 0) {
  170. log_fn(LOG_DEBUG,"Encountered eof");
  171. *reached_eof = 1;
  172. return 0;
  173. } else { /* we read some bytes */
  174. buf->datalen += read_result;
  175. log_fn(LOG_DEBUG,"Read %d bytes. %d on inbuf.",read_result,
  176. (int)buf->datalen);
  177. return read_result;
  178. }
  179. }
  180. /** As read_to_buf, but reads from a TLS connection.
  181. */
  182. int read_to_buf_tls(tor_tls *tls, size_t at_most, buf_t *buf) {
  183. int r;
  184. tor_assert(tls);
  185. assert_buf_ok(buf);
  186. log_fn(LOG_DEBUG,"start: %d on buf, %d pending, at_most %d.",
  187. (int)buf_datalen(buf), (int)tor_tls_get_pending_bytes(tls),
  188. (int)at_most);
  189. if (buf_ensure_capacity(buf, at_most+buf->datalen))
  190. return TOR_TLS_ERROR;
  191. if (at_most + buf->datalen > buf->len)
  192. at_most = buf->len - buf->datalen;
  193. if (at_most == 0)
  194. return 0;
  195. log_fn(LOG_DEBUG,"before: %d on buf, %d pending, at_most %d.",
  196. (int)buf_datalen(buf), (int)tor_tls_get_pending_bytes(tls),
  197. (int)at_most);
  198. assert_no_tls_errors();
  199. r = tor_tls_read(tls, buf->mem+buf->datalen, at_most);
  200. if (r<0)
  201. return r;
  202. buf->datalen += r;
  203. log_fn(LOG_DEBUG,"Read %d bytes. %d on inbuf; %d pending",r,
  204. (int)buf->datalen,(int)tor_tls_get_pending_bytes(tls));
  205. return r;
  206. }
  207. /** Write data from <b>buf</b> to the socket <b>s</b>. Write at most
  208. * <b>*buf_flushlen</b> bytes, decrement <b>*buf_flushlen</b> by
  209. * the number of bytes actually written, and remove the written bytes
  210. * from the buffer. Return the number of bytes written on success,
  211. * -1 on failure. Return 0 if write() would block.
  212. */
  213. int flush_buf(int s, buf_t *buf, size_t *buf_flushlen)
  214. {
  215. int write_result;
  216. assert_buf_ok(buf);
  217. tor_assert(buf_flushlen);
  218. tor_assert(s>=0);
  219. tor_assert(*buf_flushlen <= buf->datalen);
  220. if (*buf_flushlen == 0) /* nothing to flush */
  221. return 0;
  222. write_result = send(s, buf->mem, *buf_flushlen, 0);
  223. if (write_result < 0) {
  224. int e = tor_socket_errno(s);
  225. if (!ERRNO_IS_EAGAIN(e)) { /* it's a real error */
  226. return -1;
  227. }
  228. log_fn(LOG_DEBUG,"write() would block, returning.");
  229. return 0;
  230. } else {
  231. *buf_flushlen -= write_result;
  232. log_fn(LOG_DEBUG,"%d: flushed %d bytes, %d ready to flush, %d remain.",
  233. s,write_result,(int)*buf_flushlen,(int)buf->datalen);
  234. buf_remove_from_front(buf, write_result);
  235. return write_result;
  236. }
  237. }
  238. /** As flush_buf, but writes data to a TLS connection.
  239. */
  240. int flush_buf_tls(tor_tls *tls, buf_t *buf, size_t *buf_flushlen)
  241. {
  242. int r;
  243. assert_buf_ok(buf);
  244. tor_assert(tls);
  245. tor_assert(buf_flushlen);
  246. /* we want to let tls write even if flushlen is zero, because it might
  247. * have a partial record pending */
  248. r = tor_tls_write(tls, buf->mem, *buf_flushlen);
  249. if (r < 0) {
  250. return r;
  251. }
  252. *buf_flushlen -= r;
  253. buf_remove_from_front(buf, r);
  254. log_fn(LOG_DEBUG,"flushed %d bytes, %d ready to flush, %d remain.",
  255. r,(int)*buf_flushlen,(int)buf->datalen);
  256. return r;
  257. }
  258. /** Append <b>string_len</b> bytes from <b>string</b> to the end of
  259. * <b>buf</b>.
  260. *
  261. * Return the new length of the buffer on success, -1 on failure.
  262. */
  263. int write_to_buf(const char *string, size_t string_len, buf_t *buf) {
  264. /* append string to buf (growing as needed, return -1 if "too big")
  265. * return total number of bytes on the buf
  266. */
  267. tor_assert(string);
  268. assert_buf_ok(buf);
  269. if (buf_ensure_capacity(buf, buf->datalen+string_len)) {
  270. log_fn(LOG_WARN, "buflen too small, can't hold %d bytes.", (int)(buf->datalen+string_len));
  271. return -1;
  272. }
  273. memcpy(buf->mem+buf->datalen, string, string_len);
  274. buf->datalen += string_len;
  275. log_fn(LOG_DEBUG,"added %d bytes to buf (now %d total).",(int)string_len, (int)buf->datalen);
  276. return buf->datalen;
  277. }
  278. /** Remove <b>string_len</b> bytes from the front of <b>buf</b>, and store them
  279. * into <b>string</b>. Return the new buffer size. <b>string_len</b> must be \<=
  280. * the number of bytes on the buffer.
  281. */
  282. int fetch_from_buf(char *string, size_t string_len, buf_t *buf) {
  283. /* There must be string_len bytes in buf; write them onto string,
  284. * then memmove buf back (that is, remove them from buf).
  285. *
  286. * Return the number of bytes still on the buffer. */
  287. tor_assert(string);
  288. tor_assert(string_len <= buf->datalen); /* make sure we don't ask for too much */
  289. assert_buf_ok(buf);
  290. memcpy(string,buf->mem,string_len);
  291. buf_remove_from_front(buf, string_len);
  292. return buf->datalen;
  293. }
  294. /** There is a (possibly incomplete) http statement on <b>buf</b>, of the
  295. * form "\%s\\r\\n\\r\\n\%s", headers, body. (body may contain nuls.)
  296. * If a) the headers include a Content-Length field and all bytes in
  297. * the body are present, or b) there's no Content-Length field and
  298. * all headers are present, then:
  299. *
  300. * - strdup headers into <b>*headers_out</b>, and nul-terminate it.
  301. * - memdup body into <b>*body_out</b>, and nul-terminate it.
  302. * - Then remove them from <b>buf</b>, and return 1.
  303. *
  304. * - If headers or body is NULL, discard that part of the buf.
  305. * - If a headers or body doesn't fit in the arg, return -1.
  306. * (We ensure that the headers or body don't exceed max len,
  307. * _even if_ we're planning to discard them.)
  308. *
  309. * Else, change nothing and return 0.
  310. */
  311. int fetch_from_buf_http(buf_t *buf,
  312. char **headers_out, size_t max_headerlen,
  313. char **body_out, size_t *body_used, size_t max_bodylen) {
  314. char *headers, *body, *p;
  315. size_t headerlen, bodylen, contentlen;
  316. assert_buf_ok(buf);
  317. headers = buf->mem;
  318. if (buf_nul_terminate(buf)<0) {
  319. log_fn(LOG_WARN,"Couldn't nul-terminate buffer");
  320. return -1;
  321. }
  322. body = strstr(headers,"\r\n\r\n");
  323. if (!body) {
  324. log_fn(LOG_DEBUG,"headers not all here yet.");
  325. return 0;
  326. }
  327. body += 4; /* Skip the the CRLFCRLF */
  328. headerlen = body-headers; /* includes the CRLFCRLF */
  329. bodylen = buf->datalen - headerlen;
  330. log_fn(LOG_DEBUG,"headerlen %d, bodylen %d.", (int)headerlen, (int)bodylen);
  331. if (max_headerlen <= headerlen) {
  332. log_fn(LOG_WARN,"headerlen %d larger than %d. Failing.", (int)headerlen,
  333. (int)max_headerlen-1);
  334. return -1;
  335. }
  336. if (max_bodylen <= bodylen) {
  337. log_fn(LOG_WARN,"bodylen %d larger than %d. Failing.", (int)bodylen, (int)max_bodylen-1);
  338. return -1;
  339. }
  340. #define CONTENT_LENGTH "\r\nContent-Length: "
  341. p = strstr(headers, CONTENT_LENGTH);
  342. if (p) {
  343. int i;
  344. i = atoi(p+strlen(CONTENT_LENGTH));
  345. if (i < 0) {
  346. log_fn(LOG_WARN, "Content-Length is less than zero; it looks like someone is trying to crash us.");
  347. return -1;
  348. }
  349. contentlen = i;
  350. /* if content-length is malformed, then our body length is 0. fine. */
  351. log_fn(LOG_DEBUG,"Got a contentlen of %d.",(int)contentlen);
  352. if (bodylen < contentlen) {
  353. log_fn(LOG_DEBUG,"body not all here yet.");
  354. return 0; /* not all there yet */
  355. }
  356. if (bodylen > contentlen) {
  357. bodylen = contentlen;
  358. log_fn(LOG_DEBUG,"bodylen reduced to %d.",(int)bodylen);
  359. }
  360. }
  361. /* all happy. copy into the appropriate places, and return 1 */
  362. if (headers_out) {
  363. *headers_out = tor_malloc(headerlen+1);
  364. memcpy(*headers_out,buf->mem,headerlen);
  365. (*headers_out)[headerlen] = 0; /* null terminate it */
  366. }
  367. if (body_out) {
  368. tor_assert(body_used);
  369. *body_used = bodylen;
  370. *body_out = tor_malloc(bodylen+1);
  371. memcpy(*body_out,buf->mem+headerlen,bodylen);
  372. (*body_out)[bodylen] = 0; /* null terminate it */
  373. }
  374. buf_remove_from_front(buf, headerlen+bodylen);
  375. return 1;
  376. }
  377. /** There is a (possibly incomplete) socks handshake on <b>buf</b>, of one
  378. * of the forms
  379. * - socks4: "socksheader username\\0"
  380. * - socks4a: "socksheader username\\0 destaddr\\0"
  381. * - socks5 phase one: "version #methods methods"
  382. * - socks5 phase two: "version command 0 addresstype..."
  383. * If it's a complete and valid handshake, and destaddr fits in
  384. * MAX_SOCKS_ADDR_LEN bytes, then pull the handshake off the buf,
  385. * assign to <b>req</b>, and return 1.
  386. *
  387. * If it's invalid or too big, return -1.
  388. *
  389. * Else it's not all there yet, leave buf alone and return 0.
  390. *
  391. * If you want to specify the socks reply, write it into <b>req->reply</b>
  392. * and set <b>req->replylen</b>, else leave <b>req->replylen</b> alone.
  393. *
  394. * If returning 0 or -1, <b>req->address</b> and <b>req->port</b> are undefined.
  395. */
  396. int fetch_from_buf_socks(buf_t *buf, socks_request_t *req) {
  397. unsigned char len;
  398. char *tmpbuf=NULL;
  399. uint32_t destip;
  400. enum {socks4, socks4a} socks4_prot = socks4a;
  401. char *next, *startaddr;
  402. struct in_addr in;
  403. /* If the user connects with socks4 or the wrong variant of socks5,
  404. * then log a warning to let him know that it might be unwise. */
  405. static int have_warned_about_unsafe_socks = 0;
  406. if (buf->datalen < 2) /* version and another byte */
  407. return 0;
  408. switch (*(buf->mem)) { /* which version of socks? */
  409. case 5: /* socks5 */
  410. if (req->socks_version != 5) { /* we need to negotiate a method */
  411. unsigned char nummethods = (unsigned char)*(buf->mem+1);
  412. tor_assert(!req->socks_version);
  413. if (buf->datalen < 2u+nummethods)
  414. return 0;
  415. if (!nummethods || !memchr(buf->mem+2, 0, nummethods)) {
  416. log_fn(LOG_WARN,"socks5: offered methods don't include 'no auth'. Rejecting.");
  417. req->replylen = 2; /* 2 bytes of response */
  418. req->reply[0] = 5; /* socks5 reply */
  419. req->reply[1] = '\xFF'; /* reject all methods */
  420. return -1;
  421. }
  422. buf_remove_from_front(buf,2+nummethods);/* remove packet from buf */
  423. req->replylen = 2; /* 2 bytes of response */
  424. req->reply[0] = 5; /* socks5 reply */
  425. req->reply[1] = 0; /* choose the 'no auth' method */
  426. req->socks_version = 5; /* remember that we've already negotiated auth */
  427. log_fn(LOG_DEBUG,"socks5: accepted method 0");
  428. return 0;
  429. }
  430. /* we know the method; read in the request */
  431. log_fn(LOG_DEBUG,"socks5: checking request");
  432. if (buf->datalen < 8) /* basic info plus >=2 for addr plus 2 for port */
  433. return 0; /* not yet */
  434. req->command = (unsigned char) *(buf->mem+1);
  435. if (req->command != SOCKS_COMMAND_CONNECT &&
  436. req->command != SOCKS_COMMAND_RESOLVE) {
  437. /* not a connect or resolve? we don't support it. */
  438. log_fn(LOG_WARN,"socks5: command %d not recognized. Rejecting.",
  439. req->command);
  440. return -1;
  441. }
  442. switch (*(buf->mem+3)) { /* address type */
  443. case 1: /* IPv4 address */
  444. log_fn(LOG_DEBUG,"socks5: ipv4 address type");
  445. if (buf->datalen < 10) /* ip/port there? */
  446. return 0; /* not yet */
  447. destip = ntohl(*(uint32_t*)(buf->mem+4));
  448. in.s_addr = htonl(destip);
  449. tmpbuf = inet_ntoa(in);
  450. if (strlen(tmpbuf)+1 > MAX_SOCKS_ADDR_LEN) {
  451. log_fn(LOG_WARN,"socks5 IP takes %d bytes, which doesn't fit in %d. Rejecting.",
  452. (int)strlen(tmpbuf)+1,(int)MAX_SOCKS_ADDR_LEN);
  453. return -1;
  454. }
  455. strlcpy(req->address,tmpbuf,sizeof(req->address));
  456. req->port = ntohs(*(uint16_t*)(buf->mem+8));
  457. buf_remove_from_front(buf, 10);
  458. if (!have_warned_about_unsafe_socks) {
  459. log_fn(LOG_WARN,"Your application (using socks5 on port %d) is giving Tor only an IP address. Applications that do DNS resolves themselves may leak information. Consider using Socks4A (e.g. via privoxy or socat) instead.", req->port);
  460. // have_warned_about_unsafe_socks = 1; // (for now, warn every time)
  461. }
  462. return 1;
  463. case 3: /* fqdn */
  464. log_fn(LOG_DEBUG,"socks5: fqdn address type");
  465. len = (unsigned char)*(buf->mem+4);
  466. if (buf->datalen < 7u+len) /* addr/port there? */
  467. return 0; /* not yet */
  468. if (len+1 > MAX_SOCKS_ADDR_LEN) {
  469. log_fn(LOG_WARN,"socks5 hostname is %d bytes, which doesn't fit in %d. Rejecting.",
  470. len+1,MAX_SOCKS_ADDR_LEN);
  471. return -1;
  472. }
  473. memcpy(req->address,buf->mem+5,len);
  474. req->address[len] = 0;
  475. req->port = ntohs(get_uint16(buf->mem+5+len));
  476. buf_remove_from_front(buf, 5+len+2);
  477. return 1;
  478. default: /* unsupported */
  479. log_fn(LOG_WARN,"socks5: unsupported address type %d. Rejecting.",*(buf->mem+3));
  480. return -1;
  481. }
  482. tor_assert(0);
  483. case 4: /* socks4 */
  484. /* http://archive.socks.permeo.com/protocol/socks4.protocol */
  485. /* http://archive.socks.permeo.com/protocol/socks4a.protocol */
  486. req->socks_version = 4;
  487. if (buf->datalen < SOCKS4_NETWORK_LEN) /* basic info available? */
  488. return 0; /* not yet */
  489. req->command = (unsigned char) *(buf->mem+1);
  490. if (req->command != SOCKS_COMMAND_CONNECT &&
  491. req->command != SOCKS_COMMAND_RESOLVE) {
  492. /* not a connect or resolve? we don't support it. */
  493. log_fn(LOG_WARN,"socks4: command %d not recognized. Rejecting.",
  494. req->command);
  495. return -1;
  496. }
  497. req->port = ntohs(*(uint16_t*)(buf->mem+2));
  498. destip = ntohl(*(uint32_t*)(buf->mem+4));
  499. if ((!req->port && req->command!=SOCKS_COMMAND_RESOLVE) || !destip) {
  500. log_fn(LOG_WARN,"socks4: Port or DestIP is zero. Rejecting.");
  501. return -1;
  502. }
  503. if (destip >> 8) {
  504. log_fn(LOG_DEBUG,"socks4: destip not in form 0.0.0.x.");
  505. in.s_addr = htonl(destip);
  506. tmpbuf = inet_ntoa(in);
  507. if (strlen(tmpbuf)+1 > MAX_SOCKS_ADDR_LEN) {
  508. log_fn(LOG_WARN,"socks4 addr (%d bytes) too long. Rejecting.",
  509. (int)strlen(tmpbuf));
  510. return -1;
  511. }
  512. log_fn(LOG_DEBUG,"socks4: successfully read destip (%s)", tmpbuf);
  513. socks4_prot = socks4;
  514. }
  515. next = memchr(buf->mem+SOCKS4_NETWORK_LEN, 0,
  516. buf->datalen-SOCKS4_NETWORK_LEN);
  517. if (!next) {
  518. log_fn(LOG_DEBUG,"socks4: Username not here yet.");
  519. return 0;
  520. }
  521. tor_assert(next < buf->mem+buf->datalen);
  522. startaddr = NULL;
  523. if (socks4_prot != socks4a && !have_warned_about_unsafe_socks) {
  524. log_fn(LOG_WARN,"Your application (using socks4 on port %d) is giving Tor only an IP address. Applications that do DNS resolves themselves may leak information. Consider using Socks4A (e.g. via privoxy or socat) instead.", req->port);
  525. // have_warned_about_unsafe_socks = 1; // (for now, warn every time)
  526. }
  527. if (socks4_prot == socks4a) {
  528. if (next+1 == buf->mem+buf->datalen) {
  529. log_fn(LOG_DEBUG,"socks4: No part of destaddr here yet.");
  530. return 0;
  531. }
  532. startaddr = next+1;
  533. next = memchr(startaddr, 0, buf->mem+buf->datalen-startaddr);
  534. if (!next) {
  535. log_fn(LOG_DEBUG,"socks4: Destaddr not all here yet.");
  536. return 0;
  537. }
  538. if (MAX_SOCKS_ADDR_LEN <= next-startaddr) {
  539. log_fn(LOG_WARN,"socks4: Destaddr too long. Rejecting.");
  540. return -1;
  541. }
  542. tor_assert(next < buf->mem+buf->datalen);
  543. }
  544. log_fn(LOG_DEBUG,"socks4: Everything is here. Success.");
  545. strlcpy(req->address, startaddr ? startaddr : tmpbuf,
  546. sizeof(req->address));
  547. buf_remove_from_front(buf, next-buf->mem+1); /* next points to the final \0 on inbuf */
  548. return 1;
  549. case 'G': /* get */
  550. case 'H': /* head */
  551. case 'P': /* put/post */
  552. case 'C': /* connect */
  553. strlcpy(req->reply,
  554. "HTTP/1.0 501 Tor is not an HTTP Proxy\r\n"
  555. "Content-Type: text/html; charset=iso-8859-1\r\n\r\n"
  556. "<html>\n"
  557. "<head>\n"
  558. "<title>Tor is not an HTTP Proxy</title>\n"
  559. "</head>\n"
  560. "<body>\n"
  561. "<h1>Tor is not an HTTP Proxy</h1>\n"
  562. "<p>\n"
  563. "It appears you have configured your web browser to use Tor as an HTTP Proxy.\n"
  564. "This is not correct: Tor provides a SOCKS proxy. Please configure your\n"
  565. "client accordingly.\n"
  566. "</p>\n"
  567. "<p>\n"
  568. "See <a href=\"http://tor.eff.org/doc/tor-doc.html#installing\">http://tor.eff.org/doc/tor-doc.html#installing</a> for more information.\n"
  569. "<!-- Plus this comment, to make the body response more than 512 bytes, so IE will be willing to display it. Comment comment comment comment comment comment comment comment comment comment comment comment.-->\n"
  570. "</p>\n"
  571. "</body>\n"
  572. "</html>\n"
  573. , MAX_SOCKS_REPLY_LEN);
  574. req->replylen = strlen(req->reply)+1;
  575. /* fall through */
  576. default: /* version is not socks4 or socks5 */
  577. log_fn(LOG_WARN,"Socks version %d not recognized. (Tor is not an http proxy.)",
  578. *(buf->mem));
  579. return -1;
  580. }
  581. }
  582. /** If there is a complete control message waiting on buf, then store
  583. * its contents into *<b>type_out</b>, store its body's length into
  584. * *<b>len_out</b>, allocate and store a string for its body into
  585. * *<b>body_out</b>, and return -1. (body_out will always be NUL-terminated,
  586. * even if the control message body doesn't end with NUL.)
  587. *
  588. * If there is not a complete control message waiting, return 0.
  589. *
  590. * Return -1 on error.
  591. */
  592. int fetch_from_buf_control(buf_t *buf, uint16_t *len_out, uint16_t *type_out,
  593. char **body_out)
  594. {
  595. uint16_t len;
  596. tor_assert(buf);
  597. tor_assert(len_out);
  598. tor_assert(type_out);
  599. tor_assert(body_out);
  600. if (buf->datalen < 4)
  601. return 0;
  602. len = ntohs(get_uint16(buf->mem));
  603. if (buf->datalen < 4 + (unsigned)len)
  604. return 0;
  605. *len_out = len;
  606. *type_out = ntohs(get_uint16(buf->mem+2));
  607. if (len) {
  608. *body_out = tor_malloc(len+1);
  609. memcpy(*body_out, buf->mem+4, len);
  610. (*body_out)[len] = '\0';
  611. } else {
  612. *body_out = NULL;
  613. }
  614. buf_remove_from_front(buf, 4+len);
  615. return 1;
  616. }
  617. /** Log an error and exit if <b>buf</b> is corrupted.
  618. */
  619. void assert_buf_ok(buf_t *buf)
  620. {
  621. tor_assert(buf);
  622. tor_assert(buf->magic == BUFFER_MAGIC);
  623. tor_assert(buf->mem);
  624. tor_assert(buf->datalen <= buf->len);
  625. }