buffers.c 29 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067
  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 assert_buf_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. assert_buf_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. assert_buf_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. assert_buf_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_remove_from_front(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. read_to_buf(tor_socket_t s, size_t at_most, buf_t *buf, int *reached_eof,
  503. int *socket_error)
  504. {
  505. /* XXXX It's stupid to overload the return values for these functions:
  506. * "error status" and "number of bytes read" are not mutually exclusive.
  507. */
  508. int r = 0;
  509. size_t total_read = 0;
  510. check();
  511. tor_assert(reached_eof);
  512. tor_assert(SOCKET_OK(s));
  513. if (BUG(buf->datalen >= INT_MAX))
  514. return -1;
  515. if (BUG(buf->datalen >= INT_MAX - at_most))
  516. return -1;
  517. while (at_most > total_read) {
  518. size_t readlen = at_most - total_read;
  519. chunk_t *chunk;
  520. if (!buf->tail || CHUNK_REMAINING_CAPACITY(buf->tail) < MIN_READ_LEN) {
  521. chunk = buf_add_chunk_with_capacity(buf, at_most, 1);
  522. if (readlen > chunk->memlen)
  523. readlen = chunk->memlen;
  524. } else {
  525. size_t cap = CHUNK_REMAINING_CAPACITY(buf->tail);
  526. chunk = buf->tail;
  527. if (cap < readlen)
  528. readlen = cap;
  529. }
  530. r = read_to_chunk(buf, chunk, s, readlen, reached_eof, socket_error);
  531. check();
  532. if (r < 0)
  533. return r; /* Error */
  534. tor_assert(total_read+r < INT_MAX);
  535. total_read += r;
  536. if ((size_t)r < readlen) { /* eof, block, or no more to read. */
  537. break;
  538. }
  539. }
  540. return (int)total_read;
  541. }
  542. /** Helper for flush_buf(): try to write <b>sz</b> bytes from chunk
  543. * <b>chunk</b> of buffer <b>buf</b> onto socket <b>s</b>. On success, deduct
  544. * the bytes written from *<b>buf_flushlen</b>. Return the number of bytes
  545. * written on success, 0 on blocking, -1 on failure.
  546. */
  547. static inline int
  548. flush_chunk(tor_socket_t s, buf_t *buf, chunk_t *chunk, size_t sz,
  549. size_t *buf_flushlen)
  550. {
  551. ssize_t write_result;
  552. if (sz > chunk->datalen)
  553. sz = chunk->datalen;
  554. write_result = tor_socket_send(s, chunk->data, sz, 0);
  555. if (write_result < 0) {
  556. int e = tor_socket_errno(s);
  557. if (!ERRNO_IS_EAGAIN(e)) { /* it's a real error */
  558. #ifdef _WIN32
  559. if (e == WSAENOBUFS)
  560. log_warn(LD_NET,"write() failed: WSAENOBUFS. Not enough ram?");
  561. #endif
  562. return -1;
  563. }
  564. log_debug(LD_NET,"write() would block, returning.");
  565. return 0;
  566. } else {
  567. *buf_flushlen -= write_result;
  568. buf_remove_from_front(buf, write_result);
  569. tor_assert(write_result < INT_MAX);
  570. return (int)write_result;
  571. }
  572. }
  573. /** Write data from <b>buf</b> to the socket <b>s</b>. Write at most
  574. * <b>sz</b> bytes, decrement *<b>buf_flushlen</b> by
  575. * the number of bytes actually written, and remove the written bytes
  576. * from the buffer. Return the number of bytes written on success,
  577. * -1 on failure. Return 0 if write() would block.
  578. */
  579. int
  580. flush_buf(tor_socket_t s, buf_t *buf, size_t sz, size_t *buf_flushlen)
  581. {
  582. /* XXXX It's stupid to overload the return values for these functions:
  583. * "error status" and "number of bytes flushed" are not mutually exclusive.
  584. */
  585. int r;
  586. size_t flushed = 0;
  587. tor_assert(buf_flushlen);
  588. tor_assert(SOCKET_OK(s));
  589. tor_assert(*buf_flushlen <= buf->datalen);
  590. tor_assert(sz <= *buf_flushlen);
  591. check();
  592. while (sz) {
  593. size_t flushlen0;
  594. tor_assert(buf->head);
  595. if (buf->head->datalen >= sz)
  596. flushlen0 = sz;
  597. else
  598. flushlen0 = buf->head->datalen;
  599. r = flush_chunk(s, buf, buf->head, flushlen0, buf_flushlen);
  600. check();
  601. if (r < 0)
  602. return r;
  603. flushed += r;
  604. sz -= r;
  605. if (r == 0 || (size_t)r < flushlen0) /* can't flush any more now. */
  606. break;
  607. }
  608. tor_assert(flushed < INT_MAX);
  609. return (int)flushed;
  610. }
  611. /** Append <b>string_len</b> bytes from <b>string</b> to the end of
  612. * <b>buf</b>.
  613. *
  614. * Return the new length of the buffer on success, -1 on failure.
  615. */
  616. int
  617. write_to_buf(const char *string, size_t string_len, buf_t *buf)
  618. {
  619. if (!string_len)
  620. return (int)buf->datalen;
  621. check();
  622. if (BUG(buf->datalen >= INT_MAX))
  623. return -1;
  624. if (BUG(buf->datalen >= INT_MAX - string_len))
  625. return -1;
  626. while (string_len) {
  627. size_t copy;
  628. if (!buf->tail || !CHUNK_REMAINING_CAPACITY(buf->tail))
  629. buf_add_chunk_with_capacity(buf, string_len, 1);
  630. copy = CHUNK_REMAINING_CAPACITY(buf->tail);
  631. if (copy > string_len)
  632. copy = string_len;
  633. memcpy(CHUNK_WRITE_PTR(buf->tail), string, copy);
  634. string_len -= copy;
  635. string += copy;
  636. buf->datalen += copy;
  637. buf->tail->datalen += copy;
  638. }
  639. check();
  640. tor_assert(buf->datalen < INT_MAX);
  641. return (int)buf->datalen;
  642. }
  643. /** Helper: copy the first <b>string_len</b> bytes from <b>buf</b>
  644. * onto <b>string</b>.
  645. */
  646. void
  647. peek_from_buf(char *string, size_t string_len, const buf_t *buf)
  648. {
  649. chunk_t *chunk;
  650. tor_assert(string);
  651. /* make sure we don't ask for too much */
  652. tor_assert(string_len <= buf->datalen);
  653. /* assert_buf_ok(buf); */
  654. chunk = buf->head;
  655. while (string_len) {
  656. size_t copy = string_len;
  657. tor_assert(chunk);
  658. if (chunk->datalen < copy)
  659. copy = chunk->datalen;
  660. memcpy(string, chunk->data, copy);
  661. string_len -= copy;
  662. string += copy;
  663. chunk = chunk->next;
  664. }
  665. }
  666. /** Remove <b>string_len</b> bytes from the front of <b>buf</b>, and store
  667. * them into <b>string</b>. Return the new buffer size. <b>string_len</b>
  668. * must be \<= the number of bytes on the buffer.
  669. */
  670. int
  671. fetch_from_buf(char *string, size_t string_len, buf_t *buf)
  672. {
  673. /* There must be string_len bytes in buf; write them onto string,
  674. * then memmove buf back (that is, remove them from buf).
  675. *
  676. * Return the number of bytes still on the buffer. */
  677. check();
  678. peek_from_buf(string, string_len, buf);
  679. buf_remove_from_front(buf, string_len);
  680. check();
  681. tor_assert(buf->datalen < INT_MAX);
  682. return (int)buf->datalen;
  683. }
  684. /** Move up to *<b>buf_flushlen</b> bytes from <b>buf_in</b> to
  685. * <b>buf_out</b>, and modify *<b>buf_flushlen</b> appropriately.
  686. * Return the number of bytes actually copied.
  687. */
  688. int
  689. move_buf_to_buf(buf_t *buf_out, buf_t *buf_in, size_t *buf_flushlen)
  690. {
  691. /* We can do way better here, but this doesn't turn up in any profiles. */
  692. char b[4096];
  693. size_t cp, len;
  694. if (BUG(buf_out->datalen >= INT_MAX))
  695. return -1;
  696. if (BUG(buf_out->datalen >= INT_MAX - *buf_flushlen))
  697. return -1;
  698. len = *buf_flushlen;
  699. if (len > buf_in->datalen)
  700. len = buf_in->datalen;
  701. cp = len; /* Remember the number of bytes we intend to copy. */
  702. tor_assert(cp < INT_MAX);
  703. while (len) {
  704. /* This isn't the most efficient implementation one could imagine, since
  705. * it does two copies instead of 1, but I kinda doubt that this will be
  706. * critical path. */
  707. size_t n = len > sizeof(b) ? sizeof(b) : len;
  708. fetch_from_buf(b, n, buf_in);
  709. write_to_buf(b, n, buf_out);
  710. len -= n;
  711. }
  712. *buf_flushlen -= cp;
  713. return (int)cp;
  714. }
  715. /** Internal structure: represents a position in a buffer. */
  716. typedef struct buf_pos_t {
  717. const chunk_t *chunk; /**< Which chunk are we pointing to? */
  718. int pos;/**< Which character inside the chunk's data are we pointing to? */
  719. size_t chunk_pos; /**< Total length of all previous chunks. */
  720. } buf_pos_t;
  721. /** Initialize <b>out</b> to point to the first character of <b>buf</b>.*/
  722. static void
  723. buf_pos_init(const buf_t *buf, buf_pos_t *out)
  724. {
  725. out->chunk = buf->head;
  726. out->pos = 0;
  727. out->chunk_pos = 0;
  728. }
  729. /** Advance <b>out</b> to the first appearance of <b>ch</b> at the current
  730. * position of <b>out</b>, or later. Return -1 if no instances are found;
  731. * otherwise returns the absolute position of the character. */
  732. static off_t
  733. buf_find_pos_of_char(char ch, buf_pos_t *out)
  734. {
  735. const chunk_t *chunk;
  736. int pos;
  737. tor_assert(out);
  738. if (out->chunk) {
  739. if (out->chunk->datalen) {
  740. tor_assert(out->pos < (off_t)out->chunk->datalen);
  741. } else {
  742. tor_assert(out->pos == 0);
  743. }
  744. }
  745. pos = out->pos;
  746. for (chunk = out->chunk; chunk; chunk = chunk->next) {
  747. char *cp = memchr(chunk->data+pos, ch, chunk->datalen - pos);
  748. if (cp) {
  749. out->chunk = chunk;
  750. tor_assert(cp - chunk->data < INT_MAX);
  751. out->pos = (int)(cp - chunk->data);
  752. return out->chunk_pos + out->pos;
  753. } else {
  754. out->chunk_pos += chunk->datalen;
  755. pos = 0;
  756. }
  757. }
  758. return -1;
  759. }
  760. /** Advance <b>pos</b> by a single character, if there are any more characters
  761. * in the buffer. Returns 0 on success, -1 on failure. */
  762. static inline int
  763. buf_pos_inc(buf_pos_t *pos)
  764. {
  765. ++pos->pos;
  766. if (pos->pos == (off_t)pos->chunk->datalen) {
  767. if (!pos->chunk->next)
  768. return -1;
  769. pos->chunk_pos += pos->chunk->datalen;
  770. pos->chunk = pos->chunk->next;
  771. pos->pos = 0;
  772. }
  773. return 0;
  774. }
  775. /** Return true iff the <b>n</b>-character string in <b>s</b> appears
  776. * (verbatim) at <b>pos</b>. */
  777. static int
  778. buf_matches_at_pos(const buf_pos_t *pos, const char *s, size_t n)
  779. {
  780. buf_pos_t p;
  781. if (!n)
  782. return 1;
  783. memcpy(&p, pos, sizeof(p));
  784. while (1) {
  785. char ch = p.chunk->data[p.pos];
  786. if (ch != *s)
  787. return 0;
  788. ++s;
  789. /* If we're out of characters that don't match, we match. Check this
  790. * _before_ we test incrementing pos, in case we're at the end of the
  791. * string. */
  792. if (--n == 0)
  793. return 1;
  794. if (buf_pos_inc(&p)<0)
  795. return 0;
  796. }
  797. }
  798. /** Return the first position in <b>buf</b> at which the <b>n</b>-character
  799. * string <b>s</b> occurs, or -1 if it does not occur. */
  800. int
  801. buf_find_string_offset(const buf_t *buf, const char *s, size_t n)
  802. {
  803. buf_pos_t pos;
  804. buf_pos_init(buf, &pos);
  805. while (buf_find_pos_of_char(*s, &pos) >= 0) {
  806. if (buf_matches_at_pos(&pos, s, n)) {
  807. tor_assert(pos.chunk_pos + pos.pos < INT_MAX);
  808. return (int)(pos.chunk_pos + pos.pos);
  809. } else {
  810. if (buf_pos_inc(&pos)<0)
  811. return -1;
  812. }
  813. }
  814. return -1;
  815. }
  816. /** Return 1 iff <b>buf</b> starts with <b>cmd</b>. <b>cmd</b> must be a null
  817. * terminated string, of no more than PEEK_BUF_STARTSWITH_MAX bytes. */
  818. int
  819. peek_buf_startswith(const buf_t *buf, const char *cmd)
  820. {
  821. char tmp[PEEK_BUF_STARTSWITH_MAX];
  822. size_t clen = strlen(cmd);
  823. if (BUG(clen > sizeof(tmp)))
  824. return 0;
  825. if (buf->datalen < clen)
  826. return 0;
  827. peek_from_buf(tmp, clen, buf);
  828. return fast_memeq(tmp, cmd, clen);
  829. }
  830. /** Return the index within <b>buf</b> at which <b>ch</b> first appears,
  831. * or -1 if <b>ch</b> does not appear on buf. */
  832. static off_t
  833. buf_find_offset_of_char(buf_t *buf, char ch)
  834. {
  835. chunk_t *chunk;
  836. off_t offset = 0;
  837. for (chunk = buf->head; chunk; chunk = chunk->next) {
  838. char *cp = memchr(chunk->data, ch, chunk->datalen);
  839. if (cp)
  840. return offset + (cp - chunk->data);
  841. else
  842. offset += chunk->datalen;
  843. }
  844. return -1;
  845. }
  846. /** Try to read a single LF-terminated line from <b>buf</b>, and write it
  847. * (including the LF), NUL-terminated, into the *<b>data_len</b> byte buffer
  848. * at <b>data_out</b>. Set *<b>data_len</b> to the number of bytes in the
  849. * line, not counting the terminating NUL. Return 1 if we read a whole line,
  850. * return 0 if we don't have a whole line yet, and return -1 if the line
  851. * length exceeds *<b>data_len</b>.
  852. */
  853. int
  854. fetch_from_buf_line(buf_t *buf, char *data_out, size_t *data_len)
  855. {
  856. size_t sz;
  857. off_t offset;
  858. if (!buf->head)
  859. return 0;
  860. offset = buf_find_offset_of_char(buf, '\n');
  861. if (offset < 0)
  862. return 0;
  863. sz = (size_t) offset;
  864. if (sz+2 > *data_len) {
  865. *data_len = sz + 2;
  866. return -1;
  867. }
  868. fetch_from_buf(data_out, sz+1, buf);
  869. data_out[sz+1] = '\0';
  870. *data_len = sz+1;
  871. return 1;
  872. }
  873. /** Compress on uncompress the <b>data_len</b> bytes in <b>data</b> using the
  874. * compression state <b>state</b>, appending the result to <b>buf</b>. If
  875. * <b>done</b> is true, flush the data in the state and finish the
  876. * compression/uncompression. Return -1 on failure, 0 on success. */
  877. int
  878. write_to_buf_compress(buf_t *buf, tor_compress_state_t *state,
  879. const char *data, size_t data_len,
  880. const int done)
  881. {
  882. char *next;
  883. size_t old_avail, avail;
  884. int over = 0;
  885. do {
  886. int need_new_chunk = 0;
  887. if (!buf->tail || ! CHUNK_REMAINING_CAPACITY(buf->tail)) {
  888. size_t cap = data_len / 4;
  889. buf_add_chunk_with_capacity(buf, cap, 1);
  890. }
  891. next = CHUNK_WRITE_PTR(buf->tail);
  892. avail = old_avail = CHUNK_REMAINING_CAPACITY(buf->tail);
  893. switch (tor_compress_process(state, &next, &avail,
  894. &data, &data_len, done)) {
  895. case TOR_COMPRESS_DONE:
  896. over = 1;
  897. break;
  898. case TOR_COMPRESS_ERROR:
  899. return -1;
  900. case TOR_COMPRESS_OK:
  901. if (data_len == 0) {
  902. tor_assert_nonfatal(!done);
  903. over = 1;
  904. }
  905. break;
  906. case TOR_COMPRESS_BUFFER_FULL:
  907. if (avail) {
  908. /* The compression module says we need more room
  909. * (TOR_COMPRESS_BUFFER_FULL). Start a new chunk automatically,
  910. * whether were going to or not. */
  911. need_new_chunk = 1;
  912. }
  913. if (data_len == 0 && !done) {
  914. /* We've consumed all the input data, though, so there's no
  915. * point in forging ahead right now. */
  916. over = 1;
  917. }
  918. break;
  919. }
  920. buf->datalen += old_avail - avail;
  921. buf->tail->datalen += old_avail - avail;
  922. if (need_new_chunk) {
  923. buf_add_chunk_with_capacity(buf, data_len/4, 1);
  924. }
  925. } while (!over);
  926. check();
  927. return 0;
  928. }
  929. /** Set *<b>output</b> to contain a copy of the data in *<b>input</b> */
  930. int
  931. buf_set_to_copy(buf_t **output,
  932. const buf_t *input)
  933. {
  934. if (*output)
  935. buf_free(*output);
  936. *output = buf_copy(input);
  937. return 0;
  938. }
  939. /** Log an error and exit if <b>buf</b> is corrupted.
  940. */
  941. void
  942. assert_buf_ok(buf_t *buf)
  943. {
  944. tor_assert(buf);
  945. tor_assert(buf->magic == BUFFER_MAGIC);
  946. if (! buf->head) {
  947. tor_assert(!buf->tail);
  948. tor_assert(buf->datalen == 0);
  949. } else {
  950. chunk_t *ch;
  951. size_t total = 0;
  952. tor_assert(buf->tail);
  953. for (ch = buf->head; ch; ch = ch->next) {
  954. total += ch->datalen;
  955. tor_assert(ch->datalen <= ch->memlen);
  956. tor_assert(ch->data >= &ch->mem[0]);
  957. tor_assert(ch->data <= &ch->mem[0]+ch->memlen);
  958. if (ch->data == &ch->mem[0]+ch->memlen) {
  959. static int warned = 0;
  960. if (! warned) {
  961. log_warn(LD_BUG, "Invariant violation in buf.c related to #15083");
  962. warned = 1;
  963. }
  964. }
  965. tor_assert(ch->data+ch->datalen <= &ch->mem[0] + ch->memlen);
  966. if (!ch->next)
  967. tor_assert(ch == buf->tail);
  968. }
  969. tor_assert(buf->datalen == total);
  970. }
  971. }