buffers.c 38 KB

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