buffers.c 24 KB

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