buffers.c 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921
  1. /* Copyright (c) 2001 Matej Pfajfar.
  2. * Copyright (c) 2001-2004, Roger Dingledine.
  3. n * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  4. * Copyright (c) 2007-2018, The Tor Project, Inc. */
  5. /* See LICENSE for licensing information */
  6. /**
  7. * \file buffers.c
  8. * \brief Implements a generic buffer interface.
  9. *
  10. * A buf_t is a (fairly) opaque byte-oriented FIFO that can read to or flush
  11. * from memory, sockets, file descriptors, TLS connections, or another buf_t.
  12. * Buffers are implemented as linked lists of memory chunks.
  13. *
  14. * All socket-backed and TLS-based connection_t objects have a pair of
  15. * buffers: one for incoming data, and one for outcoming data. These are fed
  16. * and drained from functions in connection.c, trigged by events that are
  17. * monitored in main.c.
  18. **/
  19. #define BUFFERS_PRIVATE
  20. #include "orconfig.h"
  21. #include <stddef.h>
  22. #include "lib/container/buffers.h"
  23. #include "lib/cc/torint.h"
  24. #include "lib/log/torlog.h"
  25. #include "lib/log/util_bug.h"
  26. #include "lib/ctime/di_ops.h"
  27. #include "lib/malloc/util_malloc.h"
  28. #include "lib/string/printf.h"
  29. #include "lib/time/compat_time.h"
  30. #ifdef HAVE_UNISTD_H
  31. #include <unistd.h>
  32. #endif
  33. #include <stdlib.h>
  34. #include <string.h>
  35. //#define PARANOIA
  36. #ifdef PARANOIA
  37. /** Helper: If PARANOIA is defined, assert that the buffer in local variable
  38. * <b>buf</b> is well-formed. */
  39. #define check() STMT_BEGIN buf_assert_ok(buf); STMT_END
  40. #else
  41. #define check() STMT_NIL
  42. #endif /* defined(PARANOIA) */
  43. /* Implementation notes:
  44. *
  45. * After flirting with memmove, and dallying with ring-buffers, we're finally
  46. * getting up to speed with the 1970s and implementing buffers as a linked
  47. * list of small chunks. Each buffer has such a list; data is removed from
  48. * the head of the list, and added at the tail. The list is singly linked,
  49. * and the buffer keeps a pointer to the head and the tail.
  50. *
  51. * Every chunk, except the tail, contains at least one byte of data. Data in
  52. * each chunk is contiguous.
  53. *
  54. * When you need to treat the first N characters on a buffer as a contiguous
  55. * string, use the buf_pullup function to make them so. Don't do this more
  56. * than necessary.
  57. *
  58. * The major free Unix kernels have handled buffers like this since, like,
  59. * forever.
  60. */
  61. /* Chunk manipulation functions */
  62. #define CHUNK_HEADER_LEN offsetof(chunk_t, mem[0])
  63. /* We leave this many NUL bytes at the end of the buffer. */
  64. #ifdef DISABLE_MEMORY_SENTINELS
  65. #define SENTINEL_LEN 0
  66. #else
  67. #define SENTINEL_LEN 4
  68. #endif
  69. /* Header size plus NUL bytes at the end */
  70. #define CHUNK_OVERHEAD (CHUNK_HEADER_LEN + SENTINEL_LEN)
  71. /** Return the number of bytes needed to allocate a chunk to hold
  72. * <b>memlen</b> bytes. */
  73. #define CHUNK_ALLOC_SIZE(memlen) (CHUNK_OVERHEAD + (memlen))
  74. /** Return the number of usable bytes in a chunk allocated with
  75. * malloc(<b>memlen</b>). */
  76. #define CHUNK_SIZE_WITH_ALLOC(memlen) ((memlen) - CHUNK_OVERHEAD)
  77. #define DEBUG_SENTINEL
  78. #if defined(DEBUG_SENTINEL) && !defined(DISABLE_MEMORY_SENTINELS)
  79. #define DBG_S(s) s
  80. #else
  81. #define DBG_S(s) (void)0
  82. #endif
  83. #ifdef DISABLE_MEMORY_SENTINELS
  84. #define CHUNK_SET_SENTINEL(chunk, alloclen) STMT_NIL
  85. #else
  86. #define CHUNK_SET_SENTINEL(chunk, alloclen) do { \
  87. uint8_t *a = (uint8_t*) &(chunk)->mem[(chunk)->memlen]; \
  88. DBG_S(uint8_t *b = &((uint8_t*)(chunk))[(alloclen)-SENTINEL_LEN]); \
  89. DBG_S(tor_assert(a == b)); \
  90. memset(a,0,SENTINEL_LEN); \
  91. } while (0)
  92. #endif /* defined(DISABLE_MEMORY_SENTINELS) */
  93. /** Move all bytes stored in <b>chunk</b> to the front of <b>chunk</b>->mem,
  94. * to free up space at the end. */
  95. static inline void
  96. chunk_repack(chunk_t *chunk)
  97. {
  98. if (chunk->datalen && chunk->data != &chunk->mem[0]) {
  99. memmove(chunk->mem, chunk->data, chunk->datalen);
  100. }
  101. chunk->data = &chunk->mem[0];
  102. }
  103. /** Keep track of total size of allocated chunks for consistency asserts */
  104. static size_t total_bytes_allocated_in_chunks = 0;
  105. static void
  106. buf_chunk_free_unchecked(chunk_t *chunk)
  107. {
  108. if (!chunk)
  109. return;
  110. #ifdef DEBUG_CHUNK_ALLOC
  111. tor_assert(CHUNK_ALLOC_SIZE(chunk->memlen) == chunk->DBG_alloc);
  112. #endif
  113. tor_assert(total_bytes_allocated_in_chunks >=
  114. CHUNK_ALLOC_SIZE(chunk->memlen));
  115. total_bytes_allocated_in_chunks -= CHUNK_ALLOC_SIZE(chunk->memlen);
  116. tor_free(chunk);
  117. }
  118. static inline chunk_t *
  119. chunk_new_with_alloc_size(size_t alloc)
  120. {
  121. chunk_t *ch;
  122. ch = tor_malloc(alloc);
  123. ch->next = NULL;
  124. ch->datalen = 0;
  125. #ifdef DEBUG_CHUNK_ALLOC
  126. ch->DBG_alloc = alloc;
  127. #endif
  128. ch->memlen = CHUNK_SIZE_WITH_ALLOC(alloc);
  129. total_bytes_allocated_in_chunks += alloc;
  130. ch->data = &ch->mem[0];
  131. CHUNK_SET_SENTINEL(ch, alloc);
  132. return ch;
  133. }
  134. /** Expand <b>chunk</b> until it can hold <b>sz</b> bytes, and return a
  135. * new pointer to <b>chunk</b>. Old pointers are no longer valid. */
  136. static inline chunk_t *
  137. chunk_grow(chunk_t *chunk, size_t sz)
  138. {
  139. off_t offset;
  140. const size_t memlen_orig = chunk->memlen;
  141. const size_t orig_alloc = CHUNK_ALLOC_SIZE(memlen_orig);
  142. const size_t new_alloc = CHUNK_ALLOC_SIZE(sz);
  143. tor_assert(sz > chunk->memlen);
  144. offset = chunk->data - chunk->mem;
  145. chunk = tor_realloc(chunk, new_alloc);
  146. chunk->memlen = sz;
  147. chunk->data = chunk->mem + offset;
  148. #ifdef DEBUG_CHUNK_ALLOC
  149. tor_assert(chunk->DBG_alloc == orig_alloc);
  150. chunk->DBG_alloc = new_alloc;
  151. #endif
  152. total_bytes_allocated_in_chunks += new_alloc - orig_alloc;
  153. CHUNK_SET_SENTINEL(chunk, new_alloc);
  154. return chunk;
  155. }
  156. /** Every chunk should take up at least this many bytes. */
  157. #define MIN_CHUNK_ALLOC 256
  158. /** No chunk should take up more than this many bytes. */
  159. #define MAX_CHUNK_ALLOC 65536
  160. /** Return the allocation size we'd like to use to hold <b>target</b>
  161. * bytes. */
  162. size_t
  163. buf_preferred_chunk_size(size_t target)
  164. {
  165. tor_assert(target <= SIZE_T_CEILING - CHUNK_OVERHEAD);
  166. if (CHUNK_ALLOC_SIZE(target) >= MAX_CHUNK_ALLOC)
  167. return CHUNK_ALLOC_SIZE(target);
  168. size_t sz = MIN_CHUNK_ALLOC;
  169. while (CHUNK_SIZE_WITH_ALLOC(sz) < target) {
  170. sz <<= 1;
  171. }
  172. return sz;
  173. }
  174. /** Collapse data from the first N chunks from <b>buf</b> into buf->head,
  175. * growing it as necessary, until buf->head has the first <b>bytes</b> bytes
  176. * of data from the buffer, or until buf->head has all the data in <b>buf</b>.
  177. *
  178. * Set *<b>head_out</b> to point to the first byte of available data, and
  179. * *<b>len_out</b> to the number of bytes of data available at
  180. * *<b>head_out</b>. Note that *<b>len_out</b> may be more or less than
  181. * <b>bytes</b>, depending on the number of bytes available.
  182. */
  183. void
  184. buf_pullup(buf_t *buf, size_t bytes, const char **head_out, size_t *len_out)
  185. {
  186. chunk_t *dest, *src;
  187. size_t capacity;
  188. if (!buf->head) {
  189. *head_out = NULL;
  190. *len_out = 0;
  191. return;
  192. }
  193. check();
  194. if (buf->datalen < bytes)
  195. bytes = buf->datalen;
  196. capacity = bytes;
  197. if (buf->head->datalen >= bytes) {
  198. *head_out = buf->head->data;
  199. *len_out = buf->head->datalen;
  200. return;
  201. }
  202. if (buf->head->memlen >= capacity) {
  203. /* We don't need to grow the first chunk, but we might need to repack it.*/
  204. size_t needed = capacity - buf->head->datalen;
  205. if (CHUNK_REMAINING_CAPACITY(buf->head) < needed)
  206. chunk_repack(buf->head);
  207. tor_assert(CHUNK_REMAINING_CAPACITY(buf->head) >= needed);
  208. } else {
  209. chunk_t *newhead;
  210. size_t newsize;
  211. /* We need to grow the chunk. */
  212. chunk_repack(buf->head);
  213. newsize = CHUNK_SIZE_WITH_ALLOC(buf_preferred_chunk_size(capacity));
  214. newhead = chunk_grow(buf->head, newsize);
  215. tor_assert(newhead->memlen >= capacity);
  216. if (newhead != buf->head) {
  217. if (buf->tail == buf->head)
  218. buf->tail = newhead;
  219. buf->head = newhead;
  220. }
  221. }
  222. dest = buf->head;
  223. while (dest->datalen < bytes) {
  224. size_t n = bytes - dest->datalen;
  225. src = dest->next;
  226. tor_assert(src);
  227. if (n >= src->datalen) {
  228. memcpy(CHUNK_WRITE_PTR(dest), src->data, src->datalen);
  229. dest->datalen += src->datalen;
  230. dest->next = src->next;
  231. if (buf->tail == src)
  232. buf->tail = dest;
  233. buf_chunk_free_unchecked(src);
  234. } else {
  235. memcpy(CHUNK_WRITE_PTR(dest), src->data, n);
  236. dest->datalen += n;
  237. src->data += n;
  238. src->datalen -= n;
  239. tor_assert(dest->datalen == bytes);
  240. }
  241. }
  242. check();
  243. *head_out = buf->head->data;
  244. *len_out = buf->head->datalen;
  245. }
  246. #ifdef TOR_UNIT_TESTS
  247. /* Write sz bytes from cp into a newly allocated buffer buf.
  248. * Returns NULL when passed a NULL cp or zero sz.
  249. * Asserts on failure: only for use in unit tests.
  250. * buf must be freed using buf_free(). */
  251. buf_t *
  252. buf_new_with_data(const char *cp, size_t sz)
  253. {
  254. /* Validate arguments */
  255. if (!cp || sz <= 0) {
  256. return NULL;
  257. }
  258. tor_assert(sz < SSIZE_T_CEILING);
  259. /* Allocate a buffer */
  260. buf_t *buf = buf_new_with_capacity(sz);
  261. tor_assert(buf);
  262. buf_assert_ok(buf);
  263. tor_assert(!buf->head);
  264. /* Allocate a chunk that is sz bytes long */
  265. buf->head = chunk_new_with_alloc_size(CHUNK_ALLOC_SIZE(sz));
  266. buf->tail = buf->head;
  267. tor_assert(buf->head);
  268. buf_assert_ok(buf);
  269. tor_assert(buf_allocation(buf) >= sz);
  270. /* Copy the data and size the buffers */
  271. tor_assert(sz <= buf_slack(buf));
  272. tor_assert(sz <= CHUNK_REMAINING_CAPACITY(buf->head));
  273. memcpy(&buf->head->mem[0], cp, sz);
  274. buf->datalen = sz;
  275. buf->head->datalen = sz;
  276. buf->head->data = &buf->head->mem[0];
  277. buf_assert_ok(buf);
  278. /* Make sure everything is large enough */
  279. tor_assert(buf_allocation(buf) >= sz);
  280. tor_assert(buf_allocation(buf) >= buf_datalen(buf) + buf_slack(buf));
  281. /* Does the buffer implementation allocate more than the requested size?
  282. * (for example, by rounding up). If so, these checks will fail. */
  283. tor_assert(buf_datalen(buf) == sz);
  284. tor_assert(buf_slack(buf) == 0);
  285. return buf;
  286. }
  287. #endif /* defined(TOR_UNIT_TESTS) */
  288. /** Remove the first <b>n</b> bytes from buf. */
  289. void
  290. buf_drain(buf_t *buf, size_t n)
  291. {
  292. tor_assert(buf->datalen >= n);
  293. while (n) {
  294. tor_assert(buf->head);
  295. if (buf->head->datalen > n) {
  296. buf->head->datalen -= n;
  297. buf->head->data += n;
  298. buf->datalen -= n;
  299. return;
  300. } else {
  301. chunk_t *victim = buf->head;
  302. n -= victim->datalen;
  303. buf->datalen -= victim->datalen;
  304. buf->head = victim->next;
  305. if (buf->tail == victim)
  306. buf->tail = NULL;
  307. buf_chunk_free_unchecked(victim);
  308. }
  309. }
  310. check();
  311. }
  312. /** Create and return a new buf with default chunk capacity <b>size</b>.
  313. */
  314. buf_t *
  315. buf_new_with_capacity(size_t size)
  316. {
  317. buf_t *b = buf_new();
  318. b->default_chunk_size = buf_preferred_chunk_size(size);
  319. return b;
  320. }
  321. /** Allocate and return a new buffer with default capacity. */
  322. buf_t *
  323. buf_new(void)
  324. {
  325. buf_t *buf = tor_malloc_zero(sizeof(buf_t));
  326. buf->magic = BUFFER_MAGIC;
  327. buf->default_chunk_size = 4096;
  328. return buf;
  329. }
  330. size_t
  331. buf_get_default_chunk_size(const buf_t *buf)
  332. {
  333. return buf->default_chunk_size;
  334. }
  335. /** Remove all data from <b>buf</b>. */
  336. void
  337. buf_clear(buf_t *buf)
  338. {
  339. chunk_t *chunk, *next;
  340. buf->datalen = 0;
  341. for (chunk = buf->head; chunk; chunk = next) {
  342. next = chunk->next;
  343. buf_chunk_free_unchecked(chunk);
  344. }
  345. buf->head = buf->tail = NULL;
  346. }
  347. /** Return the number of bytes stored in <b>buf</b> */
  348. MOCK_IMPL(size_t,
  349. buf_datalen, (const buf_t *buf))
  350. {
  351. return buf->datalen;
  352. }
  353. /** Return the total length of all chunks used in <b>buf</b>. */
  354. size_t
  355. buf_allocation(const buf_t *buf)
  356. {
  357. size_t total = 0;
  358. const chunk_t *chunk;
  359. for (chunk = buf->head; chunk; chunk = chunk->next) {
  360. total += CHUNK_ALLOC_SIZE(chunk->memlen);
  361. }
  362. return total;
  363. }
  364. /** Return the number of bytes that can be added to <b>buf</b> without
  365. * performing any additional allocation. */
  366. size_t
  367. buf_slack(const buf_t *buf)
  368. {
  369. if (!buf->tail)
  370. return 0;
  371. else
  372. return CHUNK_REMAINING_CAPACITY(buf->tail);
  373. }
  374. /** Release storage held by <b>buf</b>. */
  375. void
  376. buf_free_(buf_t *buf)
  377. {
  378. if (!buf)
  379. return;
  380. buf_clear(buf);
  381. buf->magic = 0xdeadbeef;
  382. tor_free(buf);
  383. }
  384. /** Return a new copy of <b>in_chunk</b> */
  385. static chunk_t *
  386. chunk_copy(const chunk_t *in_chunk)
  387. {
  388. chunk_t *newch = tor_memdup(in_chunk, CHUNK_ALLOC_SIZE(in_chunk->memlen));
  389. total_bytes_allocated_in_chunks += CHUNK_ALLOC_SIZE(in_chunk->memlen);
  390. #ifdef DEBUG_CHUNK_ALLOC
  391. newch->DBG_alloc = CHUNK_ALLOC_SIZE(in_chunk->memlen);
  392. #endif
  393. newch->next = NULL;
  394. if (in_chunk->data) {
  395. off_t offset = in_chunk->data - in_chunk->mem;
  396. newch->data = newch->mem + offset;
  397. }
  398. return newch;
  399. }
  400. /** Return a new copy of <b>buf</b> */
  401. buf_t *
  402. buf_copy(const buf_t *buf)
  403. {
  404. chunk_t *ch;
  405. buf_t *out = buf_new();
  406. out->default_chunk_size = buf->default_chunk_size;
  407. for (ch = buf->head; ch; ch = ch->next) {
  408. chunk_t *newch = chunk_copy(ch);
  409. if (out->tail) {
  410. out->tail->next = newch;
  411. out->tail = newch;
  412. } else {
  413. out->head = out->tail = newch;
  414. }
  415. }
  416. out->datalen = buf->datalen;
  417. return out;
  418. }
  419. /** Append a new chunk with enough capacity to hold <b>capacity</b> bytes to
  420. * the tail of <b>buf</b>. If <b>capped</b>, don't allocate a chunk bigger
  421. * than MAX_CHUNK_ALLOC. */
  422. chunk_t *
  423. buf_add_chunk_with_capacity(buf_t *buf, size_t capacity, int capped)
  424. {
  425. chunk_t *chunk;
  426. if (CHUNK_ALLOC_SIZE(capacity) < buf->default_chunk_size) {
  427. chunk = chunk_new_with_alloc_size(buf->default_chunk_size);
  428. } else if (capped && CHUNK_ALLOC_SIZE(capacity) > MAX_CHUNK_ALLOC) {
  429. chunk = chunk_new_with_alloc_size(MAX_CHUNK_ALLOC);
  430. } else {
  431. chunk = chunk_new_with_alloc_size(buf_preferred_chunk_size(capacity));
  432. }
  433. chunk->inserted_time = monotime_coarse_get_stamp();
  434. if (buf->tail) {
  435. tor_assert(buf->head);
  436. buf->tail->next = chunk;
  437. buf->tail = chunk;
  438. } else {
  439. tor_assert(!buf->head);
  440. buf->head = buf->tail = chunk;
  441. }
  442. check();
  443. return chunk;
  444. }
  445. /** Return the age of the oldest chunk in the buffer <b>buf</b>, in
  446. * timestamp units. Requires the current monotonic timestamp as its
  447. * input <b>now</b>.
  448. */
  449. uint32_t
  450. buf_get_oldest_chunk_timestamp(const buf_t *buf, uint32_t now)
  451. {
  452. if (buf->head) {
  453. return now - buf->head->inserted_time;
  454. } else {
  455. return 0;
  456. }
  457. }
  458. size_t
  459. buf_get_total_allocation(void)
  460. {
  461. return total_bytes_allocated_in_chunks;
  462. }
  463. /** Append <b>string_len</b> bytes from <b>string</b> to the end of
  464. * <b>buf</b>.
  465. *
  466. * Return the new length of the buffer on success, -1 on failure.
  467. */
  468. int
  469. buf_add(buf_t *buf, const char *string, size_t string_len)
  470. {
  471. if (!string_len)
  472. return (int)buf->datalen;
  473. check();
  474. if (BUG(buf->datalen >= INT_MAX))
  475. return -1;
  476. if (BUG(buf->datalen >= INT_MAX - string_len))
  477. return -1;
  478. while (string_len) {
  479. size_t copy;
  480. if (!buf->tail || !CHUNK_REMAINING_CAPACITY(buf->tail))
  481. buf_add_chunk_with_capacity(buf, string_len, 1);
  482. copy = CHUNK_REMAINING_CAPACITY(buf->tail);
  483. if (copy > string_len)
  484. copy = string_len;
  485. memcpy(CHUNK_WRITE_PTR(buf->tail), string, copy);
  486. string_len -= copy;
  487. string += copy;
  488. buf->datalen += copy;
  489. buf->tail->datalen += copy;
  490. }
  491. check();
  492. tor_assert(buf->datalen < INT_MAX);
  493. return (int)buf->datalen;
  494. }
  495. /** Add a nul-terminated <b>string</b> to <b>buf</b>, not including the
  496. * terminating NUL. */
  497. void
  498. buf_add_string(buf_t *buf, const char *string)
  499. {
  500. buf_add(buf, string, strlen(string));
  501. }
  502. /** As tor_snprintf, but write the results into a buf_t */
  503. void
  504. buf_add_printf(buf_t *buf, const char *format, ...)
  505. {
  506. va_list ap;
  507. va_start(ap,format);
  508. buf_add_vprintf(buf, format, ap);
  509. va_end(ap);
  510. }
  511. /** As tor_vsnprintf, but write the results into a buf_t. */
  512. void
  513. buf_add_vprintf(buf_t *buf, const char *format, va_list args)
  514. {
  515. /* XXXX Faster implementations are easy enough, but let's optimize later */
  516. char *tmp;
  517. tor_vasprintf(&tmp, format, args);
  518. buf_add(buf, tmp, strlen(tmp));
  519. tor_free(tmp);
  520. }
  521. /** Return a heap-allocated string containing the contents of <b>buf</b>, plus
  522. * a NUL byte. If <b>sz_out</b> is provided, set *<b>sz_out</b> to the length
  523. * of the returned string, not including the terminating NUL. */
  524. char *
  525. buf_extract(buf_t *buf, size_t *sz_out)
  526. {
  527. tor_assert(buf);
  528. size_t sz = buf_datalen(buf);
  529. char *result;
  530. result = tor_malloc(sz+1);
  531. buf_peek(buf, result, sz);
  532. result[sz] = 0;
  533. if (sz_out)
  534. *sz_out = sz;
  535. return result;
  536. }
  537. /** Helper: copy the first <b>string_len</b> bytes from <b>buf</b>
  538. * onto <b>string</b>.
  539. */
  540. void
  541. buf_peek(const buf_t *buf, char *string, size_t string_len)
  542. {
  543. chunk_t *chunk;
  544. tor_assert(string);
  545. /* make sure we don't ask for too much */
  546. tor_assert(string_len <= buf->datalen);
  547. /* buf_assert_ok(buf); */
  548. chunk = buf->head;
  549. while (string_len) {
  550. size_t copy = string_len;
  551. tor_assert(chunk);
  552. if (chunk->datalen < copy)
  553. copy = chunk->datalen;
  554. memcpy(string, chunk->data, copy);
  555. string_len -= copy;
  556. string += copy;
  557. chunk = chunk->next;
  558. }
  559. }
  560. /** Remove <b>string_len</b> bytes from the front of <b>buf</b>, and store
  561. * them into <b>string</b>. Return the new buffer size. <b>string_len</b>
  562. * must be \<= the number of bytes on the buffer.
  563. */
  564. int
  565. buf_get_bytes(buf_t *buf, char *string, size_t string_len)
  566. {
  567. /* There must be string_len bytes in buf; write them onto string,
  568. * then memmove buf back (that is, remove them from buf).
  569. *
  570. * Return the number of bytes still on the buffer. */
  571. check();
  572. buf_peek(buf, string, string_len);
  573. buf_drain(buf, string_len);
  574. check();
  575. tor_assert(buf->datalen < INT_MAX);
  576. return (int)buf->datalen;
  577. }
  578. /** Move up to *<b>buf_flushlen</b> bytes from <b>buf_in</b> to
  579. * <b>buf_out</b>, and modify *<b>buf_flushlen</b> appropriately.
  580. * Return the number of bytes actually copied.
  581. */
  582. int
  583. buf_move_to_buf(buf_t *buf_out, buf_t *buf_in, size_t *buf_flushlen)
  584. {
  585. /* We can do way better here, but this doesn't turn up in any profiles. */
  586. char b[4096];
  587. size_t cp, len;
  588. if (BUG(buf_out->datalen >= INT_MAX))
  589. return -1;
  590. if (BUG(buf_out->datalen >= INT_MAX - *buf_flushlen))
  591. return -1;
  592. len = *buf_flushlen;
  593. if (len > buf_in->datalen)
  594. len = buf_in->datalen;
  595. cp = len; /* Remember the number of bytes we intend to copy. */
  596. tor_assert(cp < INT_MAX);
  597. while (len) {
  598. /* This isn't the most efficient implementation one could imagine, since
  599. * it does two copies instead of 1, but I kinda doubt that this will be
  600. * critical path. */
  601. size_t n = len > sizeof(b) ? sizeof(b) : len;
  602. buf_get_bytes(buf_in, b, n);
  603. buf_add(buf_out, b, n);
  604. len -= n;
  605. }
  606. *buf_flushlen -= cp;
  607. return (int)cp;
  608. }
  609. /** Moves all data from <b>buf_in</b> to <b>buf_out</b>, without copying.
  610. */
  611. void
  612. buf_move_all(buf_t *buf_out, buf_t *buf_in)
  613. {
  614. tor_assert(buf_out);
  615. if (!buf_in)
  616. return;
  617. if (buf_out->head == NULL) {
  618. buf_out->head = buf_in->head;
  619. buf_out->tail = buf_in->tail;
  620. } else {
  621. buf_out->tail->next = buf_in->head;
  622. buf_out->tail = buf_in->tail;
  623. }
  624. buf_out->datalen += buf_in->datalen;
  625. buf_in->head = buf_in->tail = NULL;
  626. buf_in->datalen = 0;
  627. }
  628. /** Internal structure: represents a position in a buffer. */
  629. typedef struct buf_pos_t {
  630. const chunk_t *chunk; /**< Which chunk are we pointing to? */
  631. int pos;/**< Which character inside the chunk's data are we pointing to? */
  632. size_t chunk_pos; /**< Total length of all previous chunks. */
  633. } buf_pos_t;
  634. /** Initialize <b>out</b> to point to the first character of <b>buf</b>.*/
  635. static void
  636. buf_pos_init(const buf_t *buf, buf_pos_t *out)
  637. {
  638. out->chunk = buf->head;
  639. out->pos = 0;
  640. out->chunk_pos = 0;
  641. }
  642. /** Advance <b>out</b> to the first appearance of <b>ch</b> at the current
  643. * position of <b>out</b>, or later. Return -1 if no instances are found;
  644. * otherwise returns the absolute position of the character. */
  645. static off_t
  646. buf_find_pos_of_char(char ch, buf_pos_t *out)
  647. {
  648. const chunk_t *chunk;
  649. int pos;
  650. tor_assert(out);
  651. if (out->chunk) {
  652. if (out->chunk->datalen) {
  653. tor_assert(out->pos < (off_t)out->chunk->datalen);
  654. } else {
  655. tor_assert(out->pos == 0);
  656. }
  657. }
  658. pos = out->pos;
  659. for (chunk = out->chunk; chunk; chunk = chunk->next) {
  660. char *cp = memchr(chunk->data+pos, ch, chunk->datalen - pos);
  661. if (cp) {
  662. out->chunk = chunk;
  663. tor_assert(cp - chunk->data < INT_MAX);
  664. out->pos = (int)(cp - chunk->data);
  665. return out->chunk_pos + out->pos;
  666. } else {
  667. out->chunk_pos += chunk->datalen;
  668. pos = 0;
  669. }
  670. }
  671. return -1;
  672. }
  673. /** Advance <b>pos</b> by a single character, if there are any more characters
  674. * in the buffer. Returns 0 on success, -1 on failure. */
  675. static inline int
  676. buf_pos_inc(buf_pos_t *pos)
  677. {
  678. ++pos->pos;
  679. if (pos->pos == (off_t)pos->chunk->datalen) {
  680. if (!pos->chunk->next)
  681. return -1;
  682. pos->chunk_pos += pos->chunk->datalen;
  683. pos->chunk = pos->chunk->next;
  684. pos->pos = 0;
  685. }
  686. return 0;
  687. }
  688. /** Return true iff the <b>n</b>-character string in <b>s</b> appears
  689. * (verbatim) at <b>pos</b>. */
  690. static int
  691. buf_matches_at_pos(const buf_pos_t *pos, const char *s, size_t n)
  692. {
  693. buf_pos_t p;
  694. if (!n)
  695. return 1;
  696. memcpy(&p, pos, sizeof(p));
  697. while (1) {
  698. char ch = p.chunk->data[p.pos];
  699. if (ch != *s)
  700. return 0;
  701. ++s;
  702. /* If we're out of characters that don't match, we match. Check this
  703. * _before_ we test incrementing pos, in case we're at the end of the
  704. * string. */
  705. if (--n == 0)
  706. return 1;
  707. if (buf_pos_inc(&p)<0)
  708. return 0;
  709. }
  710. }
  711. /** Return the first position in <b>buf</b> at which the <b>n</b>-character
  712. * string <b>s</b> occurs, or -1 if it does not occur. */
  713. int
  714. buf_find_string_offset(const buf_t *buf, const char *s, size_t n)
  715. {
  716. buf_pos_t pos;
  717. buf_pos_init(buf, &pos);
  718. while (buf_find_pos_of_char(*s, &pos) >= 0) {
  719. if (buf_matches_at_pos(&pos, s, n)) {
  720. tor_assert(pos.chunk_pos + pos.pos < INT_MAX);
  721. return (int)(pos.chunk_pos + pos.pos);
  722. } else {
  723. if (buf_pos_inc(&pos)<0)
  724. return -1;
  725. }
  726. }
  727. return -1;
  728. }
  729. /** Return 1 iff <b>buf</b> starts with <b>cmd</b>. <b>cmd</b> must be a null
  730. * terminated string, of no more than PEEK_BUF_STARTSWITH_MAX bytes. */
  731. int
  732. buf_peek_startswith(const buf_t *buf, const char *cmd)
  733. {
  734. char tmp[PEEK_BUF_STARTSWITH_MAX];
  735. size_t clen = strlen(cmd);
  736. if (clen == 0)
  737. return 1;
  738. if (BUG(clen > sizeof(tmp)))
  739. return 0;
  740. if (buf->datalen < clen)
  741. return 0;
  742. buf_peek(buf, tmp, clen);
  743. return fast_memeq(tmp, cmd, clen);
  744. }
  745. /** Return the index within <b>buf</b> at which <b>ch</b> first appears,
  746. * or -1 if <b>ch</b> does not appear on buf. */
  747. static off_t
  748. buf_find_offset_of_char(buf_t *buf, char ch)
  749. {
  750. chunk_t *chunk;
  751. off_t offset = 0;
  752. for (chunk = buf->head; chunk; chunk = chunk->next) {
  753. char *cp = memchr(chunk->data, ch, chunk->datalen);
  754. if (cp)
  755. return offset + (cp - chunk->data);
  756. else
  757. offset += chunk->datalen;
  758. }
  759. return -1;
  760. }
  761. /** Try to read a single LF-terminated line from <b>buf</b>, and write it
  762. * (including the LF), NUL-terminated, into the *<b>data_len</b> byte buffer
  763. * at <b>data_out</b>. Set *<b>data_len</b> to the number of bytes in the
  764. * line, not counting the terminating NUL. Return 1 if we read a whole line,
  765. * return 0 if we don't have a whole line yet, and return -1 if the line
  766. * length exceeds *<b>data_len</b>.
  767. */
  768. int
  769. buf_get_line(buf_t *buf, char *data_out, size_t *data_len)
  770. {
  771. size_t sz;
  772. off_t offset;
  773. if (!buf->head)
  774. return 0;
  775. offset = buf_find_offset_of_char(buf, '\n');
  776. if (offset < 0)
  777. return 0;
  778. sz = (size_t) offset;
  779. if (sz+2 > *data_len) {
  780. *data_len = sz + 2;
  781. return -1;
  782. }
  783. buf_get_bytes(buf, data_out, sz+1);
  784. data_out[sz+1] = '\0';
  785. *data_len = sz+1;
  786. return 1;
  787. }
  788. /** Set *<b>output</b> to contain a copy of the data in *<b>input</b> */
  789. int
  790. buf_set_to_copy(buf_t **output,
  791. const buf_t *input)
  792. {
  793. if (*output)
  794. buf_free(*output);
  795. *output = buf_copy(input);
  796. return 0;
  797. }
  798. /** Log an error and exit if <b>buf</b> is corrupted.
  799. */
  800. void
  801. buf_assert_ok(buf_t *buf)
  802. {
  803. tor_assert(buf);
  804. tor_assert(buf->magic == BUFFER_MAGIC);
  805. if (! buf->head) {
  806. tor_assert(!buf->tail);
  807. tor_assert(buf->datalen == 0);
  808. } else {
  809. chunk_t *ch;
  810. size_t total = 0;
  811. tor_assert(buf->tail);
  812. for (ch = buf->head; ch; ch = ch->next) {
  813. total += ch->datalen;
  814. tor_assert(ch->datalen <= ch->memlen);
  815. tor_assert(ch->data >= &ch->mem[0]);
  816. tor_assert(ch->data <= &ch->mem[0]+ch->memlen);
  817. if (ch->data == &ch->mem[0]+ch->memlen) {
  818. /* LCOV_EXCL_START */
  819. static int warned = 0;
  820. if (! warned) {
  821. log_warn(LD_BUG, "Invariant violation in buf.c related to #15083");
  822. warned = 1;
  823. }
  824. /* LCOV_EXCL_STOP */
  825. }
  826. tor_assert(ch->data+ch->datalen <= &ch->mem[0] + ch->memlen);
  827. if (!ch->next)
  828. tor_assert(ch == buf->tail);
  829. }
  830. tor_assert(buf->datalen == total);
  831. }
  832. }