buffers.c 37 KB

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