buffers.c 36 KB

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