buffers.c 29 KB

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