buffers.c 42 KB

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