buffers.c 40 KB

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