buffers.c 54 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770
  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-2008, The Tor Project, Inc. */
  5. /* See LICENSE for licensing information */
  6. /* $Id$ */
  7. const char buffers_c_id[] =
  8. "$Id$";
  9. /**
  10. * \file buffers.c
  11. * \brief Implements a generic interface buffer. Buffers are
  12. * fairly opaque string holders that can read to or flush from:
  13. * memory, file descriptors, or TLS connections.
  14. **/
  15. #define BUFFERS_PRIVATE
  16. #include "or.h"
  17. #ifdef HAVE_UNISTD_H
  18. #include <unistd.h>
  19. #endif
  20. #ifdef HAVE_SYS_UIO_H
  21. #include <sys/uio.h>
  22. #endif
  23. //#define PARANOIA
  24. //#define NOINLINE
  25. #ifdef PARANOIA
  26. /** Helper: If PARANOIA is defined, assert that the buffer in local variable
  27. * <b>buf</b> is well-formed. */
  28. #define check() STMT_BEGIN assert_buf_ok(buf); STMT_END
  29. #else
  30. #define check() STMT_NIL
  31. #endif
  32. #ifdef NOINLINE
  33. #undef INLINE
  34. #define INLINE
  35. #endif
  36. /* Implementation notes:
  37. *
  38. * After flirting with memmove, and dallying with ring-buffers, we're finally
  39. * getting up to speed with the 1970s and implementing buffers as a linked
  40. * list of small chunks. Each buffer has such a list; data is removed from
  41. * the head of the list, and added at the tail. The list is singly linked,
  42. * and the buffer keeps a pointer to the head and the tail.
  43. *
  44. * Every chunk, except the tail, contains at least one byte of data. Data in
  45. * each chunk is contiguous.
  46. *
  47. * When you need to treat the first N characters on a buffer as a contiguous
  48. * string, use the buf_pullup function to make them so. Don't do this more
  49. * than necessary.
  50. *
  51. * The major free Unix kernels have handled buffers like this since, like,
  52. * forever.
  53. */
  54. /* Chunk manipulation functions */
  55. /** A single chunk on a buffer or in a freelist. */
  56. typedef struct chunk_t {
  57. struct chunk_t *next; /**< The next chunk on the buffer or freelist. */
  58. size_t datalen; /**< The number of bytes stored in this chunk */
  59. size_t memlen; /**< The number of usable bytes of storage in <b>mem</b>. */
  60. char *data; /**< A pointer to the first byte of data stored in <b>mem</b>. */
  61. char mem[1]; /**< The actual memory used for storage in this chunk. May be
  62. * more than one byte long. */
  63. } chunk_t;
  64. #define CHUNK_HEADER_LEN STRUCT_OFFSET(chunk_t, mem[0])
  65. /** Return the number of bytes needed to allocate a chunk to hold
  66. * <b>memlen</b> bytes. */
  67. #define CHUNK_ALLOC_SIZE(memlen) (CHUNK_HEADER_LEN + (memlen))
  68. /** Return the number of usable bytes in a chunk allocated with
  69. * malloc(<b>memlen</b>). */
  70. #define CHUNK_SIZE_WITH_ALLOC(memlen) ((memlen) - CHUNK_HEADER_LEN)
  71. /** Return the next character in <b>chunk</b> onto which data can be appended.
  72. * If the chunk is full, this might be off the end of chunk->mem. */
  73. static INLINE char *
  74. CHUNK_WRITE_PTR(chunk_t *chunk)
  75. {
  76. return chunk->data + chunk->datalen;
  77. }
  78. /** Return the number of bytes that can be written onto <b>chunk</b> without
  79. * running out of space. */
  80. static INLINE size_t
  81. CHUNK_REMAINING_CAPACITY(const chunk_t *chunk)
  82. {
  83. return (chunk->mem + chunk->memlen) - (chunk->data + chunk->datalen);
  84. }
  85. /** Move all bytes stored in <b>chunk</b> to the front of <b>chunk</b>->mem,
  86. * to free up space at the end. */
  87. static INLINE void
  88. chunk_repack(chunk_t *chunk)
  89. {
  90. if (chunk->datalen && chunk->data != &chunk->mem[0]) {
  91. memmove(chunk->mem, chunk->data, chunk->datalen);
  92. }
  93. chunk->data = &chunk->mem[0];
  94. }
  95. #ifdef ENABLE_BUF_FREELISTS
  96. /** A freelist of chunks. */
  97. typedef struct chunk_freelist_t {
  98. size_t alloc_size; /**< What size chunks does this freelist hold? */
  99. int max_length; /**< Never allow more than this number of chunks in the
  100. * freelist. */
  101. int slack; /**< When trimming the freelist, leave this number of extra
  102. * chunks beyond lowest_length.*/
  103. int cur_length; /**< How many chunks on the freelist now? */
  104. int lowest_length; /**< What's the smallest value of cur_length since the
  105. * last time we cleaned this freelist? */
  106. uint64_t n_alloc;
  107. uint64_t n_free;
  108. uint64_t n_hit;
  109. chunk_t *head; /**< First chunk on the freelist. */
  110. } chunk_freelist_t;
  111. /** Macro to help define freelists. */
  112. #define FL(a,m,s) { a, m, s, 0, 0, 0, 0, 0, NULL }
  113. /** Static array of freelists, sorted by alloc_len, terminated by an entry
  114. * with alloc_size of 0. */
  115. static chunk_freelist_t freelists[] = {
  116. FL(4096, 256, 8), FL(8192, 128, 4), FL(16384, 64, 4), FL(32768, 32, 2),
  117. FL(0, 0, 0)
  118. };
  119. #undef FL
  120. /** How many times have we looked for a chunk of a size that no freelist
  121. * could help with? */
  122. static uint64_t n_freelist_miss = 0;
  123. static void assert_freelist_ok(chunk_freelist_t *fl);
  124. /** Return the freelist to hold chunks of size <b>alloc</b>, or NULL if
  125. * no freelist exists for that size. */
  126. static INLINE chunk_freelist_t *
  127. get_freelist(size_t alloc)
  128. {
  129. int i;
  130. for (i=0; freelists[i].alloc_size <= alloc; ++i) {
  131. if (freelists[i].alloc_size == alloc) {
  132. return &freelists[i];
  133. }
  134. }
  135. return NULL;
  136. }
  137. /** Deallocate a chunk or put it on a freelist */
  138. static void
  139. chunk_free(chunk_t *chunk)
  140. {
  141. size_t alloc = CHUNK_ALLOC_SIZE(chunk->memlen);
  142. chunk_freelist_t *freelist = get_freelist(alloc);
  143. if (freelist && freelist->cur_length < freelist->max_length) {
  144. chunk->next = freelist->head;
  145. freelist->head = chunk;
  146. ++freelist->cur_length;
  147. } else {
  148. if (freelist)
  149. ++freelist->n_free;
  150. tor_free(chunk);
  151. }
  152. }
  153. /** Allocate a new chunk with a given allocation size, or get one from the
  154. * freelist. Note that a chunk with allocation size A can actualy hold only
  155. * CHUNK_SIZE_WITH_ALLOC(A) bytes in its mem field. */
  156. static INLINE chunk_t *
  157. chunk_new_with_alloc_size(size_t alloc)
  158. {
  159. chunk_t *ch;
  160. chunk_freelist_t *freelist;
  161. tor_assert(alloc >= sizeof(chunk_t));
  162. freelist = get_freelist(alloc);
  163. if (freelist && freelist->head) {
  164. ch = freelist->head;
  165. freelist->head = ch->next;
  166. if (--freelist->cur_length < freelist->lowest_length)
  167. freelist->lowest_length = freelist->cur_length;
  168. ++freelist->n_hit;
  169. } else {
  170. /* XXXX take advantage of tor_malloc_roundup, once we know how that
  171. * affects freelists. */
  172. if (freelist)
  173. ++freelist->n_alloc;
  174. else
  175. ++n_freelist_miss;
  176. ch = tor_malloc(alloc);
  177. }
  178. ch->next = NULL;
  179. ch->datalen = 0;
  180. ch->memlen = CHUNK_SIZE_WITH_ALLOC(alloc);
  181. ch->data = &ch->mem[0];
  182. return ch;
  183. }
  184. #else
  185. static void
  186. chunk_free(chunk_t *chunk)
  187. {
  188. tor_free(chunk);
  189. }
  190. static INLINE chunk_t *
  191. chunk_new_with_alloc_size(size_t alloc)
  192. {
  193. chunk_t *ch;
  194. ch = tor_malloc_roundup(&alloc);
  195. ch->next = NULL;
  196. ch->datalen = 0;
  197. ch->memlen = CHUNK_SIZE_WITH_ALLOC(alloc);
  198. ch->data = &ch->mem[0];
  199. return ch;
  200. }
  201. #endif
  202. /** Expand <b>chunk</b> until it can hold <b>sz</b> bytes, and return a
  203. * new pointer to <b>chunk</b>. Old pointers are no longer valid. */
  204. static INLINE chunk_t *
  205. chunk_grow(chunk_t *chunk, size_t sz)
  206. {
  207. off_t offset;
  208. tor_assert(sz > chunk->memlen);
  209. offset = chunk->data - chunk->mem;
  210. chunk = tor_realloc(chunk, CHUNK_ALLOC_SIZE(sz));
  211. chunk->memlen = sz;
  212. chunk->data = chunk->mem + offset;
  213. return chunk;
  214. }
  215. /** If a read onto the end of a chunk would be smaller than this number, then
  216. * just start a new chunk. */
  217. #define MIN_READ_LEN 8
  218. /** Every chunk should take up at least this many bytes. */
  219. #define MIN_CHUNK_ALLOC 256
  220. /** No chunk should take up more than this many bytes. */
  221. #define MAX_CHUNK_ALLOC 65536
  222. /** Return the allocation size we'd like to use to hold <b>target</b>
  223. * bytes. */
  224. static INLINE size_t
  225. preferred_chunk_size(size_t target)
  226. {
  227. size_t sz = MIN_CHUNK_ALLOC;
  228. while (CHUNK_SIZE_WITH_ALLOC(sz) < target) {
  229. sz <<= 1;
  230. }
  231. return sz;
  232. }
  233. /** Remove from the freelists most chunks that have not been used since the
  234. * last call to buf_shrink_freelists(). */
  235. void
  236. buf_shrink_freelists(int free_all)
  237. {
  238. #ifdef ENABLE_BUF_FREELISTS
  239. int i;
  240. for (i = 0; freelists[i].alloc_size; ++i) {
  241. int slack = freelists[i].slack;
  242. assert_freelist_ok(&freelists[i]);
  243. if (free_all || freelists[i].lowest_length > slack) {
  244. int n_to_free = free_all ? freelists[i].cur_length :
  245. (freelists[i].lowest_length - slack);
  246. int n_to_skip = freelists[i].cur_length - n_to_free;
  247. int new_length = n_to_skip;
  248. chunk_t **chp = &freelists[i].head;
  249. chunk_t *chunk;
  250. log_info(LD_MM, "Cleaning freelist for %d-byte chunks: keeping %d, "
  251. "dropping %d.",
  252. (int)freelists[i].alloc_size, n_to_skip, n_to_free);
  253. while (n_to_skip) {
  254. tor_assert((*chp)->next);
  255. chp = &(*chp)->next;
  256. --n_to_skip;
  257. }
  258. chunk = *chp;
  259. *chp = NULL;
  260. while (chunk) {
  261. chunk_t *next = chunk->next;
  262. tor_free(chunk);
  263. chunk = next;
  264. --n_to_free;
  265. ++freelists[i].n_free;
  266. }
  267. tor_assert(!n_to_free);
  268. freelists[i].cur_length = new_length;
  269. }
  270. freelists[i].lowest_length = freelists[i].cur_length;
  271. assert_freelist_ok(&freelists[i]);
  272. }
  273. #else
  274. (void) free_all;
  275. #endif
  276. }
  277. /** Describe the current status of the freelists at log level <b>severity</b>.
  278. */
  279. void
  280. buf_dump_freelist_sizes(int severity)
  281. {
  282. #ifdef ENABLE_BUF_FREELISTS
  283. int i;
  284. log(severity, LD_MM, "====== Buffer freelists:");
  285. for (i = 0; freelists[i].alloc_size; ++i) {
  286. uint64_t total = ((uint64_t)freelists[i].cur_length) *
  287. freelists[i].alloc_size;
  288. log(severity, LD_MM,
  289. U64_FORMAT" bytes in %d %d-byte chunks ["U64_FORMAT
  290. " misses; "U64_FORMAT" frees; "U64_FORMAT" hits]",
  291. U64_PRINTF_ARG(total),
  292. freelists[i].cur_length, (int)freelists[i].alloc_size,
  293. U64_PRINTF_ARG(freelists[i].n_alloc),
  294. U64_PRINTF_ARG(freelists[i].n_free),
  295. U64_PRINTF_ARG(freelists[i].n_hit));
  296. }
  297. log(severity, LD_MM, U64_FORMAT" allocations in non-freelist sizes",
  298. U64_PRINTF_ARG(n_freelist_miss));
  299. #else
  300. (void)severity;
  301. #endif
  302. }
  303. /** Magic value for buf_t.magic, to catch pointer errors. */
  304. #define BUFFER_MAGIC 0xB0FFF312u
  305. /** A resizeable buffer, optimized for reading and writing. */
  306. struct buf_t {
  307. uint32_t magic; /**< Magic cookie for debugging: Must be set to
  308. * BUFFER_MAGIC. */
  309. size_t datalen; /**< How many bytes is this buffer holding right now? */
  310. size_t default_chunk_size; /**< Don't allocate any chunks smaller than
  311. * this for this buffer. */
  312. chunk_t *head; /**< First chunk in the list, or NULL for none. */
  313. chunk_t *tail; /**< Last chunk in the list, or NULL for none. */
  314. };
  315. /** Collapse data from the first N chunks from <b>buf</b> into buf->head,
  316. * growing it as necessary, until buf->head has the first <b>bytes</b> bytes
  317. * of data from the buffer, or until buf->head has all the data in <b>buf</b>.
  318. *
  319. * If <b>nulterminate</b> is true, ensure that there is a 0 byte in
  320. * buf->head->mem right after all the data. */
  321. static void
  322. buf_pullup(buf_t *buf, size_t bytes, int nulterminate)
  323. {
  324. chunk_t *dest, *src;
  325. size_t capacity;
  326. if (!buf->head)
  327. return;
  328. check();
  329. if (buf->datalen < bytes)
  330. bytes = buf->datalen;
  331. if (nulterminate) {
  332. capacity = bytes + 1;
  333. if (buf->head->datalen >= bytes && CHUNK_REMAINING_CAPACITY(buf->head)) {
  334. *CHUNK_WRITE_PTR(buf->head) = '\0';
  335. return;
  336. }
  337. } else {
  338. capacity = bytes;
  339. if (buf->head->datalen >= bytes)
  340. return;
  341. }
  342. if (buf->head->memlen >= capacity) {
  343. /* We don't need to grow the first chunk, but we might need to repack it.*/
  344. if (CHUNK_REMAINING_CAPACITY(buf->head) < capacity-buf->datalen)
  345. chunk_repack(buf->head);
  346. tor_assert(CHUNK_REMAINING_CAPACITY(buf->head) >= capacity-buf->datalen);
  347. } else {
  348. chunk_t *newhead;
  349. size_t newsize;
  350. /* We need to grow the chunk. */
  351. chunk_repack(buf->head);
  352. newsize = CHUNK_SIZE_WITH_ALLOC(preferred_chunk_size(capacity));
  353. newhead = chunk_grow(buf->head, newsize);
  354. tor_assert(newhead->memlen >= capacity);
  355. if (newhead != buf->head) {
  356. if (buf->tail == buf->head)
  357. buf->tail = newhead;
  358. buf->head = newhead;
  359. }
  360. }
  361. dest = buf->head;
  362. while (dest->datalen < bytes) {
  363. size_t n = bytes - dest->datalen;
  364. src = dest->next;
  365. tor_assert(src);
  366. if (n > src->datalen) {
  367. memcpy(CHUNK_WRITE_PTR(dest), src->data, src->datalen);
  368. dest->datalen += src->datalen;
  369. dest->next = src->next;
  370. if (buf->tail == src)
  371. buf->tail = dest;
  372. chunk_free(src);
  373. } else {
  374. memcpy(CHUNK_WRITE_PTR(dest), src->data, n);
  375. dest->datalen += n;
  376. src->data += n;
  377. src->datalen -= n;
  378. tor_assert(dest->datalen == bytes);
  379. }
  380. }
  381. if (nulterminate) {
  382. tor_assert(CHUNK_REMAINING_CAPACITY(buf->head));
  383. *CHUNK_WRITE_PTR(buf->head) = '\0';
  384. }
  385. check();
  386. }
  387. /** Resize buf so it won't hold extra memory that we haven't been
  388. * using lately.
  389. */
  390. void
  391. buf_shrink(buf_t *buf)
  392. {
  393. (void)buf;
  394. }
  395. /** Remove the first <b>n</b> bytes from buf. */
  396. static INLINE void
  397. buf_remove_from_front(buf_t *buf, size_t n)
  398. {
  399. tor_assert(buf->datalen >= n);
  400. while (n) {
  401. tor_assert(buf->head);
  402. if (buf->head->datalen > n) {
  403. buf->head->datalen -= n;
  404. buf->head->data += n;
  405. buf->datalen -= n;
  406. return;
  407. } else {
  408. chunk_t *victim = buf->head;
  409. n -= victim->datalen;
  410. buf->datalen -= victim->datalen;
  411. buf->head = victim->next;
  412. if (buf->tail == victim)
  413. buf->tail = NULL;
  414. chunk_free(victim);
  415. }
  416. }
  417. check();
  418. }
  419. /** Create and return a new buf with default chunk capacity <b>size</b>.
  420. */
  421. buf_t *
  422. buf_new_with_capacity(size_t size)
  423. {
  424. buf_t *b = buf_new();
  425. b->default_chunk_size = preferred_chunk_size(size);
  426. return b;
  427. }
  428. /** Allocate and return a new buffer with default capacity. */
  429. buf_t *
  430. buf_new(void)
  431. {
  432. buf_t *buf = tor_malloc_zero(sizeof(buf_t));
  433. buf->magic = BUFFER_MAGIC;
  434. buf->default_chunk_size = 4096;
  435. return buf;
  436. }
  437. /** Remove all data from <b>buf</b>. */
  438. void
  439. buf_clear(buf_t *buf)
  440. {
  441. chunk_t *chunk, *next;
  442. buf->datalen = 0;
  443. for (chunk = buf->head; chunk; chunk = next) {
  444. next = chunk->next;
  445. chunk_free(chunk);
  446. }
  447. buf->head = buf->tail = NULL;
  448. }
  449. /** Return the number of bytes stored in <b>buf</b> */
  450. size_t
  451. buf_datalen(const buf_t *buf)
  452. {
  453. return buf->datalen;
  454. }
  455. /** Return the total length of all chunks used in <b>buf</b>. */
  456. size_t
  457. buf_allocation(const buf_t *buf)
  458. {
  459. size_t total = 0;
  460. const chunk_t *chunk;
  461. for (chunk = buf->head; chunk; chunk = chunk->next) {
  462. total += chunk->memlen;
  463. }
  464. return total;
  465. }
  466. /** Return the number of bytes that can be added to <b>buf</b> without
  467. * performing any additional allocation. */
  468. size_t
  469. buf_slack(const buf_t *buf)
  470. {
  471. if (!buf->tail)
  472. return 0;
  473. else
  474. return CHUNK_REMAINING_CAPACITY(buf->tail);
  475. }
  476. /** Release storage held by <b>buf</b>. */
  477. void
  478. buf_free(buf_t *buf)
  479. {
  480. buf_clear(buf);
  481. buf->magic = 0xdeadbeef;
  482. tor_free(buf);
  483. }
  484. /** Append a new chunk with enough capacity to hold <b>capacity</b> bytes to
  485. * the tail of <b>buf</b>. If <b>capped</b>, don't allocate a chunk bigger
  486. * than MAX_CHUNK_ALLOC. */
  487. static chunk_t *
  488. buf_add_chunk_with_capacity(buf_t *buf, size_t capacity, int capped)
  489. {
  490. chunk_t *chunk;
  491. if (CHUNK_ALLOC_SIZE(capacity) < buf->default_chunk_size) {
  492. chunk = chunk_new_with_alloc_size(buf->default_chunk_size);
  493. } else if (capped && CHUNK_ALLOC_SIZE(capacity) > MAX_CHUNK_ALLOC) {
  494. chunk = chunk_new_with_alloc_size(MAX_CHUNK_ALLOC);
  495. } else {
  496. chunk = chunk_new_with_alloc_size(preferred_chunk_size(capacity));
  497. }
  498. if (buf->tail) {
  499. tor_assert(buf->head);
  500. buf->tail->next = chunk;
  501. buf->tail = chunk;
  502. } else {
  503. tor_assert(!buf->head);
  504. buf->head = buf->tail = chunk;
  505. }
  506. check();
  507. return chunk;
  508. }
  509. /** DOCDOC */
  510. #define N_IOV 3
  511. /** Read up to <b>at_most</b> bytes from the socket <b>fd</b> into
  512. * <b>chunk</b> (which must be on <b>buf</b>). If we get an EOF, set
  513. * *<b>reached_eof</b> to 1. Return -1 on error, 0 on eof or blocking,
  514. * and the number of bytes read otherwise. */
  515. static INLINE int
  516. read_to_chunk(buf_t *buf, chunk_t *chunk, int fd, size_t at_most,
  517. int *reached_eof, int *socket_error)
  518. {
  519. ssize_t read_result;
  520. #if 0 && defined(HAVE_READV) && !defined(WIN32)
  521. struct iovec iov[N_IOV];
  522. int i;
  523. size_t remaining = at_most;
  524. for (i=0; chunk && i < N_IOV && remaining; ++i) {
  525. iov[i].iov_base = CHUNK_WRITE_PTR(chunk);
  526. if (remaining > CHUNK_REMAINING_CAPACITY(chunk))
  527. iov[i].iov_len = CHUNK_REMAINING_CAPACITY(chunk);
  528. else
  529. iov[i].iov_len = remaining;
  530. remaining -= iov[i].iov_len;
  531. chunk = chunk->next;
  532. }
  533. read_result = readv(fd, iov, i);
  534. #else
  535. if (at_most > CHUNK_REMAINING_CAPACITY(chunk))
  536. at_most = CHUNK_REMAINING_CAPACITY(chunk);
  537. read_result = tor_socket_recv(fd, CHUNK_WRITE_PTR(chunk), at_most, 0);
  538. #endif
  539. if (read_result < 0) {
  540. int e = tor_socket_errno(fd);
  541. if (!ERRNO_IS_EAGAIN(e)) { /* it's a real error */
  542. #ifdef MS_WINDOWS
  543. if (e == WSAENOBUFS)
  544. log_warn(LD_NET,"recv() failed: WSAENOBUFS. Not enough ram?");
  545. #endif
  546. *socket_error = e;
  547. return -1;
  548. }
  549. return 0; /* would block. */
  550. } else if (read_result == 0) {
  551. log_debug(LD_NET,"Encountered eof on fd %d", (int)fd);
  552. *reached_eof = 1;
  553. return 0;
  554. } else { /* actually got bytes. */
  555. buf->datalen += read_result;
  556. #if 0 && defined(HAVE_READV) && !defined(WIN32)
  557. while ((size_t)read_result > CHUNK_REMAINING_CAPACITY(chunk)) {
  558. chunk->datalen += CHUNK_REMAINING_CAPACITY(chunk);
  559. read_result -= CHUNK_REMAINING_CAPACITY(chunk);
  560. chunk = chunk->next;
  561. tor_assert(chunk);
  562. }
  563. #endif
  564. chunk->datalen += read_result;
  565. log_debug(LD_NET,"Read %ld bytes. %d on inbuf.", (long)read_result,
  566. (int)buf->datalen);
  567. tor_assert(read_result < INT_MAX);
  568. return (int)read_result;
  569. }
  570. }
  571. /** As read_to_chunk(), but return (negative) error code on error, blocking,
  572. * or TLS, and the number of bytes read otherwise. */
  573. static INLINE int
  574. read_to_chunk_tls(buf_t *buf, chunk_t *chunk, tor_tls_t *tls,
  575. size_t at_most)
  576. {
  577. int read_result;
  578. tor_assert(CHUNK_REMAINING_CAPACITY(chunk) >= at_most);
  579. read_result = tor_tls_read(tls, CHUNK_WRITE_PTR(chunk), at_most);
  580. if (read_result < 0)
  581. return read_result;
  582. buf->datalen += read_result;
  583. chunk->datalen += read_result;
  584. return read_result;
  585. }
  586. /** Read from socket <b>s</b>, writing onto end of <b>buf</b>. Read at most
  587. * <b>at_most</b> bytes, growing the buffer as necessary. If recv() returns 0
  588. * (because of EOF), set *<b>reached_eof</b> to 1 and return 0. Return -1 on
  589. * error; else return the number of bytes read.
  590. */
  591. /* XXXX021 indicate "read blocked" somehow? */
  592. int
  593. read_to_buf(int s, size_t at_most, buf_t *buf, int *reached_eof,
  594. int *socket_error)
  595. {
  596. /* XXXX021 It's stupid to overload the return values for these functions:
  597. * "error status" and "number of bytes read" are not mutually exclusive.
  598. */
  599. int r = 0;
  600. size_t total_read = 0;
  601. check();
  602. tor_assert(reached_eof);
  603. tor_assert(s >= 0);
  604. while (at_most > total_read) {
  605. size_t readlen = at_most - total_read;
  606. chunk_t *chunk;
  607. if (!buf->tail || CHUNK_REMAINING_CAPACITY(buf->tail) < MIN_READ_LEN) {
  608. chunk = buf_add_chunk_with_capacity(buf, at_most, 1);
  609. if (readlen > chunk->memlen)
  610. readlen = chunk->memlen;
  611. } else {
  612. size_t cap = CHUNK_REMAINING_CAPACITY(buf->tail);
  613. chunk = buf->tail;
  614. if (cap < readlen)
  615. readlen = cap;
  616. }
  617. r = read_to_chunk(buf, chunk, s, readlen, reached_eof, socket_error);
  618. check();
  619. if (r < 0)
  620. return r; /* Error */
  621. tor_assert(total_read+r < INT_MAX);
  622. total_read += r;
  623. if ((size_t)r < readlen) { /* eof, block, or no more to read. */
  624. break;
  625. }
  626. }
  627. return (int)total_read;
  628. }
  629. /** As read_to_buf, but reads from a TLS connection, and returns a TLS
  630. * status value rather than the number of bytes read.
  631. *
  632. * Using TLS on OR connections complicates matters in two ways.
  633. *
  634. * First, a TLS stream has its own read buffer independent of the
  635. * connection's read buffer. (TLS needs to read an entire frame from
  636. * the network before it can decrypt any data. Thus, trying to read 1
  637. * byte from TLS can require that several KB be read from the network
  638. * and decrypted. The extra data is stored in TLS's decrypt buffer.)
  639. * Because the data hasn't been read by Tor (it's still inside the TLS),
  640. * this means that sometimes a connection "has stuff to read" even when
  641. * poll() didn't return POLLIN. The tor_tls_get_pending_bytes function is
  642. * used in connection.c to detect TLS objects with non-empty internal
  643. * buffers and read from them again.
  644. *
  645. * Second, the TLS stream's events do not correspond directly to network
  646. * events: sometimes, before a TLS stream can read, the network must be
  647. * ready to write -- or vice versa.
  648. */
  649. int
  650. read_to_buf_tls(tor_tls_t *tls, size_t at_most, buf_t *buf)
  651. {
  652. int r = 0;
  653. size_t total_read = 0;
  654. check();
  655. while (at_most > total_read) {
  656. size_t readlen = at_most - total_read;
  657. chunk_t *chunk;
  658. if (!buf->tail || CHUNK_REMAINING_CAPACITY(buf->tail) < MIN_READ_LEN) {
  659. chunk = buf_add_chunk_with_capacity(buf, at_most, 1);
  660. if (readlen > chunk->memlen)
  661. readlen = chunk->memlen;
  662. } else {
  663. size_t cap = CHUNK_REMAINING_CAPACITY(buf->tail);
  664. chunk = buf->tail;
  665. if (cap < readlen)
  666. readlen = cap;
  667. }
  668. r = read_to_chunk_tls(buf, chunk, tls, readlen);
  669. check();
  670. if (r < 0)
  671. return r; /* Error */
  672. tor_assert(total_read+r < INT_MAX);
  673. total_read += r;
  674. if ((size_t)r < readlen) /* eof, block, or no more to read. */
  675. break;
  676. }
  677. return (int)total_read;
  678. }
  679. /** Helper for flush_buf(): try to write <b>sz</b> bytes from chunk
  680. * <b>chunk</b> of buffer <b>buf</b> onto socket <b>s</b>. On success, deduct
  681. * the bytes written from *<b>buf_flushlen</b>. Return the number of bytes
  682. * written on success, 0 on blocking, -1 on failure.
  683. */
  684. static INLINE int
  685. flush_chunk(int s, buf_t *buf, chunk_t *chunk, size_t sz,
  686. size_t *buf_flushlen)
  687. {
  688. ssize_t write_result;
  689. #if 0 && defined(HAVE_WRITEV) && !defined(WIN32)
  690. struct iovec iov[N_IOV];
  691. int i;
  692. size_t remaining = sz;
  693. for (i=0; chunk && i < N_IOV && remaining; ++i) {
  694. iov[i].iov_base = chunk->data;
  695. if (remaining > chunk->datalen)
  696. iov[i].iov_len = chunk->datalen;
  697. else
  698. iov[i].iov_len = remaining;
  699. remaining -= iov[i].iov_len;
  700. chunk = chunk->next;
  701. }
  702. write_result = writev(s, iov, i);
  703. #else
  704. if (sz > chunk->datalen)
  705. sz = chunk->datalen;
  706. write_result = tor_socket_send(s, chunk->data, sz, 0);
  707. #endif
  708. if (write_result < 0) {
  709. int e = tor_socket_errno(s);
  710. if (!ERRNO_IS_EAGAIN(e)) { /* it's a real error */
  711. #ifdef MS_WINDOWS
  712. if (e == WSAENOBUFS)
  713. log_warn(LD_NET,"write() failed: WSAENOBUFS. Not enough ram?");
  714. #endif
  715. return -1;
  716. }
  717. log_debug(LD_NET,"write() would block, returning.");
  718. return 0;
  719. } else {
  720. *buf_flushlen -= write_result;
  721. buf_remove_from_front(buf, write_result);
  722. tor_assert(write_result < INT_MAX);
  723. return (int)write_result;
  724. }
  725. }
  726. /** Helper for flush_buf_tls(): try to write <b>sz</b> bytes from chunk
  727. * <b>chunk</b> of buffer <b>buf</b> onto socket <b>s</b>. (Tries to write
  728. * more if there is a forced pending write size.) On success, deduct the
  729. * bytes written from *<b>buf_flushlen</b>. Return the number of bytes
  730. * written on success, and a TOR_TLS error code on failue or blocking.
  731. */
  732. static INLINE int
  733. flush_chunk_tls(tor_tls_t *tls, buf_t *buf, chunk_t *chunk,
  734. size_t sz, size_t *buf_flushlen)
  735. {
  736. int r;
  737. size_t forced;
  738. char *data;
  739. forced = tor_tls_get_forced_write_size(tls);
  740. if (forced > sz)
  741. sz = forced;
  742. if (chunk) {
  743. data = chunk->data;
  744. tor_assert(sz <= chunk->datalen);
  745. } else {
  746. data = NULL;
  747. tor_assert(sz == 0);
  748. }
  749. r = tor_tls_write(tls, data, sz);
  750. if (r < 0)
  751. return r;
  752. if (*buf_flushlen > (size_t)r)
  753. *buf_flushlen -= r;
  754. else
  755. *buf_flushlen = 0;
  756. buf_remove_from_front(buf, r);
  757. log_debug(LD_NET,"flushed %d bytes, %d ready to flush, %d remain.",
  758. r,(int)*buf_flushlen,(int)buf->datalen);
  759. return r;
  760. }
  761. /** Write data from <b>buf</b> to the socket <b>s</b>. Write at most
  762. * <b>sz</b> bytes, decrement *<b>buf_flushlen</b> by
  763. * the number of bytes actually written, and remove the written bytes
  764. * from the buffer. Return the number of bytes written on success,
  765. * -1 on failure. Return 0 if write() would block.
  766. */
  767. int
  768. flush_buf(int s, buf_t *buf, size_t sz, size_t *buf_flushlen)
  769. {
  770. /* XXXX021 It's stupid to overload the return values for these functions:
  771. * "error status" and "number of bytes flushed" are not mutually exclusive.
  772. */
  773. int r;
  774. size_t flushed = 0;
  775. tor_assert(buf_flushlen);
  776. tor_assert(s >= 0);
  777. tor_assert(*buf_flushlen <= buf->datalen);
  778. tor_assert(sz <= *buf_flushlen);
  779. check();
  780. while (sz) {
  781. size_t flushlen0;
  782. tor_assert(buf->head);
  783. if (buf->head->datalen >= sz)
  784. flushlen0 = sz;
  785. else
  786. flushlen0 = buf->head->datalen;
  787. r = flush_chunk(s, buf, buf->head, flushlen0, buf_flushlen);
  788. check();
  789. if (r < 0)
  790. return r;
  791. flushed += r;
  792. sz -= r;
  793. if (r == 0 || (size_t)r < flushlen0) /* can't flush any more now. */
  794. break;
  795. }
  796. tor_assert(flushed < INT_MAX);
  797. return (int)flushed;
  798. }
  799. /** As flush_buf(), but writes data to a TLS connection. Can write more than
  800. * <b>flushlen</b> bytes.
  801. */
  802. int
  803. flush_buf_tls(tor_tls_t *tls, buf_t *buf, size_t flushlen,
  804. size_t *buf_flushlen)
  805. {
  806. int r;
  807. size_t flushed = 0;
  808. ssize_t sz;
  809. tor_assert(buf_flushlen);
  810. tor_assert(*buf_flushlen <= buf->datalen);
  811. tor_assert(flushlen <= *buf_flushlen);
  812. sz = (ssize_t) flushlen;
  813. /* we want to let tls write even if flushlen is zero, because it might
  814. * have a partial record pending */
  815. check_no_tls_errors();
  816. check();
  817. do {
  818. size_t flushlen0;
  819. if (buf->head) {
  820. if ((ssize_t)buf->head->datalen >= sz)
  821. flushlen0 = sz;
  822. else
  823. flushlen0 = buf->head->datalen;
  824. } else {
  825. flushlen0 = 0;
  826. }
  827. r = flush_chunk_tls(tls, buf, buf->head, flushlen0, buf_flushlen);
  828. check();
  829. if (r < 0)
  830. return r;
  831. flushed += r;
  832. sz -= r;
  833. if (r == 0) /* Can't flush any more now. */
  834. break;
  835. } while (sz > 0);
  836. tor_assert(flushed < INT_MAX);
  837. return (int)flushed;
  838. }
  839. /** Append <b>string_len</b> bytes from <b>string</b> to the end of
  840. * <b>buf</b>.
  841. *
  842. * Return the new length of the buffer on success, -1 on failure.
  843. */
  844. int
  845. write_to_buf(const char *string, size_t string_len, buf_t *buf)
  846. {
  847. if (!string_len)
  848. return (int)buf->datalen;
  849. check();
  850. while (string_len) {
  851. size_t copy;
  852. if (!buf->tail || !CHUNK_REMAINING_CAPACITY(buf->tail))
  853. buf_add_chunk_with_capacity(buf, string_len, 1);
  854. copy = CHUNK_REMAINING_CAPACITY(buf->tail);
  855. if (copy > string_len)
  856. copy = string_len;
  857. memcpy(CHUNK_WRITE_PTR(buf->tail), string, copy);
  858. string_len -= copy;
  859. string += copy;
  860. buf->datalen += copy;
  861. buf->tail->datalen += copy;
  862. }
  863. check();
  864. tor_assert(buf->datalen < INT_MAX);
  865. return (int)buf->datalen;
  866. }
  867. /** Helper: copy the first <b>string_len</b> bytes from <b>buf</b>
  868. * onto <b>string</b>.
  869. */
  870. static INLINE void
  871. peek_from_buf(char *string, size_t string_len, const buf_t *buf)
  872. {
  873. chunk_t *chunk;
  874. tor_assert(string);
  875. /* make sure we don't ask for too much */
  876. tor_assert(string_len <= buf->datalen);
  877. /* assert_buf_ok(buf); */
  878. chunk = buf->head;
  879. while (string_len) {
  880. size_t copy = string_len;
  881. tor_assert(chunk);
  882. if (chunk->datalen < copy)
  883. copy = chunk->datalen;
  884. memcpy(string, chunk->data, copy);
  885. string_len -= copy;
  886. string += copy;
  887. chunk = chunk->next;
  888. }
  889. }
  890. /** Remove <b>string_len</b> bytes from the front of <b>buf</b>, and store
  891. * them into <b>string</b>. Return the new buffer size. <b>string_len</b>
  892. * must be \<= the number of bytes on the buffer.
  893. */
  894. int
  895. fetch_from_buf(char *string, size_t string_len, buf_t *buf)
  896. {
  897. /* There must be string_len bytes in buf; write them onto string,
  898. * then memmove buf back (that is, remove them from buf).
  899. *
  900. * Return the number of bytes still on the buffer. */
  901. check();
  902. peek_from_buf(string, string_len, buf);
  903. buf_remove_from_front(buf, string_len);
  904. check();
  905. tor_assert(buf->datalen < INT_MAX);
  906. return (int)buf->datalen;
  907. }
  908. /** Check <b>buf</b> for a variable-length cell according to the rules of link
  909. * protocol version <b>linkproto</b>. If one is found, pull it off the buffer
  910. * and assign a newly allocated var_cell_t to *<b>out</b>, and return 1.
  911. * Return 0 if whatever is on the start of buf_t is not a variable-length
  912. * cell. Return 1 and set *<b>out</b> to NULL if there seems to be the start
  913. * of a variable-length cell on <b>buf</b>, but the whole thing isn't there
  914. * yet. */
  915. int
  916. fetch_var_cell_from_buf(buf_t *buf, var_cell_t **out, int linkproto)
  917. {
  918. char hdr[VAR_CELL_HEADER_SIZE];
  919. var_cell_t *result;
  920. uint8_t command;
  921. uint16_t length;
  922. /* If linkproto is unknown (0) or v2 (2), variable-length cells work as
  923. * implemented here. If it's 1, there are no variable-length cells. Tor
  924. * does not support other versions right now, and so can't negotiate them.
  925. */
  926. if (linkproto == 1)
  927. return 0;
  928. check();
  929. *out = NULL;
  930. if (buf->datalen < VAR_CELL_HEADER_SIZE)
  931. return 0;
  932. peek_from_buf(hdr, sizeof(hdr), buf);
  933. command = get_uint8(hdr+2);
  934. if (!(CELL_COMMAND_IS_VAR_LENGTH(command)))
  935. return 0;
  936. length = ntohs(get_uint16(hdr+3));
  937. if (buf->datalen < (size_t)(VAR_CELL_HEADER_SIZE+length))
  938. return 1;
  939. result = var_cell_new(length);
  940. result->command = command;
  941. result->circ_id = ntohs(get_uint16(hdr));
  942. buf_remove_from_front(buf, VAR_CELL_HEADER_SIZE);
  943. peek_from_buf(result->payload, length, buf);
  944. buf_remove_from_front(buf, length);
  945. check();
  946. *out = result;
  947. return 1;
  948. }
  949. /** Move up to *<b>buf_flushlen</b> bytes from <b>buf_in</b> to
  950. * <b>buf_out</b>, and modify *<b>buf_flushlen</b> appropriately.
  951. * Return the number of bytes actually copied.
  952. */
  953. int
  954. move_buf_to_buf(buf_t *buf_out, buf_t *buf_in, size_t *buf_flushlen)
  955. {
  956. /* XXXX we can do way better here, but this doesn't turn up in any
  957. * profiles. */
  958. char b[4096];
  959. size_t cp, len;
  960. len = *buf_flushlen;
  961. if (len > buf_in->datalen)
  962. len = buf_in->datalen;
  963. cp = len; /* Remember the number of bytes we intend to copy. */
  964. tor_assert(cp < INT_MAX);
  965. while (len) {
  966. /* This isn't the most efficient implementation one could imagine, since
  967. * it does two copies instead of 1, but I kinda doubt that this will be
  968. * critical path. */
  969. size_t n = len > sizeof(b) ? sizeof(b) : len;
  970. fetch_from_buf(b, n, buf_in);
  971. write_to_buf(b, n, buf_out);
  972. len -= n;
  973. }
  974. *buf_flushlen -= cp;
  975. return (int)cp;
  976. }
  977. /** Internal structure: represents a position in a buffer. */
  978. typedef struct buf_pos_t {
  979. const chunk_t *chunk; /**< Which chunk are we pointing to? */
  980. int pos;/**< Which character inside the chunk's data are we pointing to? */
  981. size_t chunk_pos; /**< Total length of all previous chunks. */
  982. } buf_pos_t;
  983. /** Initialize <b>out</b> to point to the first character of <b>buf</b>.*/
  984. static void
  985. buf_pos_init(const buf_t *buf, buf_pos_t *out)
  986. {
  987. out->chunk = buf->head;
  988. out->pos = 0;
  989. out->chunk_pos = 0;
  990. }
  991. /** Advance <b>out</b> to the first appearance of <b>ch</b> at the current
  992. * position of <b>out</b>, or later. Return -1 if no instances are found;
  993. * otherwise returns the absolute position of the character. */
  994. static off_t
  995. buf_find_pos_of_char(char ch, buf_pos_t *out)
  996. {
  997. const chunk_t *chunk;
  998. int pos;
  999. tor_assert(out);
  1000. if (out->chunk) {
  1001. if (out->chunk->datalen) {
  1002. tor_assert(out->pos < (off_t)out->chunk->datalen);
  1003. } else {
  1004. tor_assert(out->pos == 0);
  1005. }
  1006. }
  1007. pos = out->pos;
  1008. for (chunk = out->chunk; chunk; chunk = chunk->next) {
  1009. char *cp = memchr(chunk->data+pos, ch, chunk->datalen - pos);
  1010. if (cp) {
  1011. out->chunk = chunk;
  1012. tor_assert(cp - chunk->data < INT_MAX);
  1013. out->pos = (int)(cp - chunk->data);
  1014. return out->chunk_pos + out->pos;
  1015. } else {
  1016. out->chunk_pos += chunk->datalen;
  1017. pos = 0;
  1018. }
  1019. }
  1020. return -1;
  1021. }
  1022. /** Advance <b>pos</b> by a single character, if there are any more characters
  1023. * in the buffer. Returns 0 on sucess, -1 on failure. */
  1024. static INLINE int
  1025. buf_pos_inc(buf_pos_t *pos)
  1026. {
  1027. ++pos->pos;
  1028. if (pos->pos == (off_t)pos->chunk->datalen) {
  1029. if (!pos->chunk->next)
  1030. return -1;
  1031. pos->chunk_pos += pos->chunk->datalen;
  1032. pos->chunk = pos->chunk->next;
  1033. pos->pos = 0;
  1034. }
  1035. return 0;
  1036. }
  1037. /** Return true iff the <b>n</b>-character string in <b>s</b> appears
  1038. * (verbatim) at <b>pos</b>. */
  1039. static int
  1040. buf_matches_at_pos(const buf_pos_t *pos, const char *s, size_t n)
  1041. {
  1042. buf_pos_t p;
  1043. if (!n)
  1044. return 1;
  1045. memcpy(&p, pos, sizeof(p));
  1046. while (1) {
  1047. char ch = p.chunk->data[p.pos];
  1048. if (ch != *s)
  1049. return 0;
  1050. ++s;
  1051. /* If we're out of characters that don't match, we match. Check this
  1052. * _before_ we test incrementing pos, in case we're at the end of the
  1053. * string. */
  1054. if (--n == 0)
  1055. return 1;
  1056. if (buf_pos_inc(&p)<0)
  1057. return 0;
  1058. }
  1059. }
  1060. /** Return the first position in <b>buf</b> at which the <b>n</b>-character
  1061. * string <b>s</b> occurs, or -1 if it does not occur. */
  1062. /*private*/ int
  1063. buf_find_string_offset(const buf_t *buf, const char *s, size_t n)
  1064. {
  1065. buf_pos_t pos;
  1066. buf_pos_init(buf, &pos);
  1067. while (buf_find_pos_of_char(*s, &pos) >= 0) {
  1068. if (buf_matches_at_pos(&pos, s, n)) {
  1069. tor_assert(pos.chunk_pos + pos.pos < INT_MAX);
  1070. return (int)(pos.chunk_pos + pos.pos);
  1071. } else {
  1072. if (buf_pos_inc(&pos)<0)
  1073. return -1;
  1074. }
  1075. }
  1076. return -1;
  1077. }
  1078. /** There is a (possibly incomplete) http statement on <b>buf</b>, of the
  1079. * form "\%s\\r\\n\\r\\n\%s", headers, body. (body may contain nuls.)
  1080. * If a) the headers include a Content-Length field and all bytes in
  1081. * the body are present, or b) there's no Content-Length field and
  1082. * all headers are present, then:
  1083. *
  1084. * - strdup headers into <b>*headers_out</b>, and nul-terminate it.
  1085. * - memdup body into <b>*body_out</b>, and nul-terminate it.
  1086. * - Then remove them from <b>buf</b>, and return 1.
  1087. *
  1088. * - If headers or body is NULL, discard that part of the buf.
  1089. * - If a headers or body doesn't fit in the arg, return -1.
  1090. * (We ensure that the headers or body don't exceed max len,
  1091. * _even if_ we're planning to discard them.)
  1092. * - If force_complete is true, then succeed even if not all of the
  1093. * content has arrived.
  1094. *
  1095. * Else, change nothing and return 0.
  1096. */
  1097. int
  1098. fetch_from_buf_http(buf_t *buf,
  1099. char **headers_out, size_t max_headerlen,
  1100. char **body_out, size_t *body_used, size_t max_bodylen,
  1101. int force_complete)
  1102. {
  1103. char *headers, *p;
  1104. size_t headerlen, bodylen, contentlen;
  1105. int crlf_offset;
  1106. check();
  1107. if (!buf->head)
  1108. return 0;
  1109. crlf_offset = buf_find_string_offset(buf, "\r\n\r\n", 4);
  1110. if (crlf_offset > (int)max_headerlen ||
  1111. (crlf_offset < 0 && buf->datalen > max_headerlen)) {
  1112. log_debug(LD_HTTP,"headers too long.");
  1113. return -1;
  1114. } else if (crlf_offset < 0) {
  1115. log_debug(LD_HTTP,"headers not all here yet.");
  1116. return 0;
  1117. }
  1118. /* Okay, we have a full header. Make sure it all appears in the first
  1119. * chunk. */
  1120. if ((int)buf->head->datalen < crlf_offset + 4)
  1121. buf_pullup(buf, crlf_offset+4, 0);
  1122. headerlen = crlf_offset + 4;
  1123. headers = buf->head->data;
  1124. bodylen = buf->datalen - headerlen;
  1125. log_debug(LD_HTTP,"headerlen %d, bodylen %d.", (int)headerlen, (int)bodylen);
  1126. if (max_headerlen <= headerlen) {
  1127. log_warn(LD_HTTP,"headerlen %d larger than %d. Failing.",
  1128. (int)headerlen, (int)max_headerlen-1);
  1129. return -1;
  1130. }
  1131. if (max_bodylen <= bodylen) {
  1132. log_warn(LD_HTTP,"bodylen %d larger than %d. Failing.",
  1133. (int)bodylen, (int)max_bodylen-1);
  1134. return -1;
  1135. }
  1136. #define CONTENT_LENGTH "\r\nContent-Length: "
  1137. p = (char*) tor_memstr(headers, headerlen, CONTENT_LENGTH);
  1138. if (p) {
  1139. int i;
  1140. i = atoi(p+strlen(CONTENT_LENGTH));
  1141. if (i < 0) {
  1142. log_warn(LD_PROTOCOL, "Content-Length is less than zero; it looks like "
  1143. "someone is trying to crash us.");
  1144. return -1;
  1145. }
  1146. contentlen = i;
  1147. /* if content-length is malformed, then our body length is 0. fine. */
  1148. log_debug(LD_HTTP,"Got a contentlen of %d.",(int)contentlen);
  1149. if (bodylen < contentlen) {
  1150. if (!force_complete) {
  1151. log_debug(LD_HTTP,"body not all here yet.");
  1152. return 0; /* not all there yet */
  1153. }
  1154. }
  1155. if (bodylen > contentlen) {
  1156. bodylen = contentlen;
  1157. log_debug(LD_HTTP,"bodylen reduced to %d.",(int)bodylen);
  1158. }
  1159. }
  1160. /* all happy. copy into the appropriate places, and return 1 */
  1161. if (headers_out) {
  1162. *headers_out = tor_malloc(headerlen+1);
  1163. fetch_from_buf(*headers_out, headerlen, buf);
  1164. (*headers_out)[headerlen] = 0; /* nul terminate it */
  1165. }
  1166. if (body_out) {
  1167. tor_assert(body_used);
  1168. *body_used = bodylen;
  1169. *body_out = tor_malloc(bodylen+1);
  1170. fetch_from_buf(*body_out, bodylen, buf);
  1171. (*body_out)[bodylen] = 0; /* nul terminate it */
  1172. }
  1173. check();
  1174. return 1;
  1175. }
  1176. /** There is a (possibly incomplete) socks handshake on <b>buf</b>, of one
  1177. * of the forms
  1178. * - socks4: "socksheader username\\0"
  1179. * - socks4a: "socksheader username\\0 destaddr\\0"
  1180. * - socks5 phase one: "version #methods methods"
  1181. * - socks5 phase two: "version command 0 addresstype..."
  1182. * If it's a complete and valid handshake, and destaddr fits in
  1183. * MAX_SOCKS_ADDR_LEN bytes, then pull the handshake off the buf,
  1184. * assign to <b>req</b>, and return 1.
  1185. *
  1186. * If it's invalid or too big, return -1.
  1187. *
  1188. * Else it's not all there yet, leave buf alone and return 0.
  1189. *
  1190. * If you want to specify the socks reply, write it into <b>req->reply</b>
  1191. * and set <b>req->replylen</b>, else leave <b>req->replylen</b> alone.
  1192. *
  1193. * If <b>log_sockstype</b> is non-zero, then do a notice-level log of whether
  1194. * the connection is possibly leaking DNS requests locally or not.
  1195. *
  1196. * If <b>safe_socks</b> is true, then reject unsafe socks protocols.
  1197. *
  1198. * If returning 0 or -1, <b>req->address</b> and <b>req->port</b> are
  1199. * undefined.
  1200. */
  1201. int
  1202. fetch_from_buf_socks(buf_t *buf, socks_request_t *req,
  1203. int log_sockstype, int safe_socks)
  1204. {
  1205. unsigned int len;
  1206. char tmpbuf[TOR_ADDR_BUF_LEN+1];
  1207. tor_addr_t destaddr;
  1208. uint32_t destip;
  1209. uint8_t socksver;
  1210. enum {socks4, socks4a} socks4_prot = socks4a;
  1211. char *next, *startaddr;
  1212. struct in_addr in;
  1213. /* If the user connects with socks4 or the wrong variant of socks5,
  1214. * then log a warning to let him know that it might be unwise. */
  1215. static int have_warned_about_unsafe_socks = 0;
  1216. if (buf->datalen < 2) /* version and another byte */
  1217. return 0;
  1218. buf_pullup(buf, 128, 0);
  1219. tor_assert(buf->head && buf->head->datalen >= 2);
  1220. socksver = *buf->head->data;
  1221. switch (socksver) { /* which version of socks? */
  1222. case 5: /* socks5 */
  1223. if (req->socks_version != 5) { /* we need to negotiate a method */
  1224. unsigned char nummethods = (unsigned char)*(buf->head->data+1);
  1225. tor_assert(!req->socks_version);
  1226. if (buf->datalen < 2u+nummethods)
  1227. return 0;
  1228. buf_pullup(buf, 2u+nummethods, 0);
  1229. if (!nummethods || !memchr(buf->head->data+2, 0, nummethods)) {
  1230. log_warn(LD_APP,
  1231. "socks5: offered methods don't include 'no auth'. "
  1232. "Rejecting.");
  1233. req->replylen = 2; /* 2 bytes of response */
  1234. req->reply[0] = 5;
  1235. req->reply[1] = '\xFF'; /* reject all methods */
  1236. return -1;
  1237. }
  1238. /* remove packet from buf. also remove any other extraneous
  1239. * bytes, to support broken socks clients. */
  1240. buf_clear(buf);
  1241. req->replylen = 2; /* 2 bytes of response */
  1242. req->reply[0] = 5; /* socks5 reply */
  1243. req->reply[1] = 0; /* tell client to use "none" auth method */
  1244. req->socks_version = 5; /* remember we've already negotiated auth */
  1245. log_debug(LD_APP,"socks5: accepted method 0");
  1246. return 0;
  1247. }
  1248. /* we know the method; read in the request */
  1249. log_debug(LD_APP,"socks5: checking request");
  1250. if (buf->datalen < 8) /* basic info plus >=2 for addr plus 2 for port */
  1251. return 0; /* not yet */
  1252. tor_assert(buf->head->datalen >= 8);
  1253. req->command = (unsigned char) *(buf->head->data+1);
  1254. if (req->command != SOCKS_COMMAND_CONNECT &&
  1255. req->command != SOCKS_COMMAND_RESOLVE &&
  1256. req->command != SOCKS_COMMAND_RESOLVE_PTR) {
  1257. /* not a connect or resolve or a resolve_ptr? we don't support it. */
  1258. log_warn(LD_APP,"socks5: command %d not recognized. Rejecting.",
  1259. req->command);
  1260. return -1;
  1261. }
  1262. switch (*(buf->head->data+3)) { /* address type */
  1263. case 1: /* IPv4 address */
  1264. case 4: /* IPv6 address */ {
  1265. const int is_v6 = *(buf->head->data+3) == 4;
  1266. const unsigned addrlen = is_v6 ? 16 : 4;
  1267. log_debug(LD_APP,"socks5: ipv4 address type");
  1268. if (buf->datalen < 6+addrlen) /* ip/port there? */
  1269. return 0; /* not yet */
  1270. if (is_v6)
  1271. tor_addr_from_ipv6_bytes(&destaddr, buf->head->data+4);
  1272. else
  1273. tor_addr_from_ipv4n(&destaddr, get_uint32(buf->head->data+4));
  1274. tor_addr_to_str(tmpbuf, &destaddr, sizeof(tmpbuf), 1);
  1275. if (strlen(tmpbuf)+1 > MAX_SOCKS_ADDR_LEN) {
  1276. log_warn(LD_APP,
  1277. "socks5 IP takes %d bytes, which doesn't fit in %d. "
  1278. "Rejecting.",
  1279. (int)strlen(tmpbuf)+1,(int)MAX_SOCKS_ADDR_LEN);
  1280. return -1;
  1281. }
  1282. strlcpy(req->address,tmpbuf,sizeof(req->address));
  1283. req->port = ntohs(get_uint16(buf->head->data+4+addrlen));
  1284. buf_remove_from_front(buf, 6+addrlen);
  1285. if (req->command != SOCKS_COMMAND_RESOLVE_PTR &&
  1286. !addressmap_have_mapping(req->address,0) &&
  1287. !have_warned_about_unsafe_socks) {
  1288. log_warn(LD_APP,
  1289. "Your application (using socks5 to port %d) is giving "
  1290. "Tor only an IP address. Applications that do DNS resolves "
  1291. "themselves may leak information. Consider using Socks4A "
  1292. "(e.g. via privoxy or socat) instead. For more information, "
  1293. "please see http://wiki.noreply.org/noreply/TheOnionRouter/"
  1294. "TorFAQ#SOCKSAndDNS.%s", req->port,
  1295. safe_socks ? " Rejecting." : "");
  1296. /*have_warned_about_unsafe_socks = 1;*/
  1297. /*(for now, warn every time)*/
  1298. control_event_client_status(LOG_WARN,
  1299. "DANGEROUS_SOCKS PROTOCOL=SOCKS5 ADDRESS=%s:%d",
  1300. req->address, req->port);
  1301. if (safe_socks)
  1302. return -1;
  1303. }
  1304. return 1;
  1305. }
  1306. case 3: /* fqdn */
  1307. log_debug(LD_APP,"socks5: fqdn address type");
  1308. if (req->command == SOCKS_COMMAND_RESOLVE_PTR) {
  1309. log_warn(LD_APP, "socks5 received RESOLVE_PTR command with "
  1310. "hostname type. Rejecting.");
  1311. return -1;
  1312. }
  1313. len = (unsigned char)*(buf->head->data+4);
  1314. if (buf->datalen < 7+len) /* addr/port there? */
  1315. return 0; /* not yet */
  1316. buf_pullup(buf, 7+len, 0);
  1317. tor_assert(buf->head->datalen >= 7+len);
  1318. if (len+1 > MAX_SOCKS_ADDR_LEN) {
  1319. log_warn(LD_APP,
  1320. "socks5 hostname is %d bytes, which doesn't fit in "
  1321. "%d. Rejecting.", len+1,MAX_SOCKS_ADDR_LEN);
  1322. return -1;
  1323. }
  1324. memcpy(req->address,buf->head->data+5,len);
  1325. req->address[len] = 0;
  1326. req->port = ntohs(get_uint16(buf->head->data+5+len));
  1327. buf_remove_from_front(buf, 5+len+2);
  1328. if (!tor_strisprint(req->address) || strchr(req->address,'\"')) {
  1329. log_warn(LD_PROTOCOL,
  1330. "Your application (using socks5 to port %d) gave Tor "
  1331. "a malformed hostname: %s. Rejecting the connection.",
  1332. req->port, escaped(req->address));
  1333. return -1;
  1334. }
  1335. if (log_sockstype)
  1336. log_notice(LD_APP,
  1337. "Your application (using socks5 to port %d) gave "
  1338. "Tor a hostname, which means Tor will do the DNS resolve "
  1339. "for you. This is good.", req->port);
  1340. return 1;
  1341. default: /* unsupported */
  1342. log_warn(LD_APP,"socks5: unsupported address type %d. Rejecting.",
  1343. (int) *(buf->head->data+3));
  1344. return -1;
  1345. }
  1346. tor_assert(0);
  1347. case 4: /* socks4 */
  1348. /* http://archive.socks.permeo.com/protocol/socks4.protocol */
  1349. /* http://archive.socks.permeo.com/protocol/socks4a.protocol */
  1350. req->socks_version = 4;
  1351. if (buf->datalen < SOCKS4_NETWORK_LEN) /* basic info available? */
  1352. return 0; /* not yet */
  1353. buf_pullup(buf, 1280, 0);
  1354. req->command = (unsigned char) *(buf->head->data+1);
  1355. if (req->command != SOCKS_COMMAND_CONNECT &&
  1356. req->command != SOCKS_COMMAND_RESOLVE) {
  1357. /* not a connect or resolve? we don't support it. (No resolve_ptr with
  1358. * socks4.) */
  1359. log_warn(LD_APP,"socks4: command %d not recognized. Rejecting.",
  1360. req->command);
  1361. return -1;
  1362. }
  1363. req->port = ntohs(*(uint16_t*)(buf->head->data+2));
  1364. destip = ntohl(*(uint32_t*)(buf->head->data+4));
  1365. if ((!req->port && req->command!=SOCKS_COMMAND_RESOLVE) || !destip) {
  1366. log_warn(LD_APP,"socks4: Port or DestIP is zero. Rejecting.");
  1367. return -1;
  1368. }
  1369. if (destip >> 8) {
  1370. log_debug(LD_APP,"socks4: destip not in form 0.0.0.x.");
  1371. in.s_addr = htonl(destip);
  1372. tor_inet_ntoa(&in,tmpbuf,sizeof(tmpbuf));
  1373. if (strlen(tmpbuf)+1 > MAX_SOCKS_ADDR_LEN) {
  1374. log_debug(LD_APP,"socks4 addr (%d bytes) too long. Rejecting.",
  1375. (int)strlen(tmpbuf));
  1376. return -1;
  1377. }
  1378. log_debug(LD_APP,
  1379. "socks4: successfully read destip (%s)", safe_str(tmpbuf));
  1380. socks4_prot = socks4;
  1381. }
  1382. next = memchr(buf->head->data+SOCKS4_NETWORK_LEN, 0,
  1383. buf->head->datalen-SOCKS4_NETWORK_LEN);
  1384. if (!next) {
  1385. if (buf->head->datalen >= 1024) {
  1386. log_debug(LD_APP, "Socks4 user name too long; rejecting.");
  1387. return -1;
  1388. }
  1389. log_debug(LD_APP,"socks4: Username not here yet.");
  1390. return 0;
  1391. }
  1392. tor_assert(next < CHUNK_WRITE_PTR(buf->head));
  1393. startaddr = NULL;
  1394. if (socks4_prot != socks4a &&
  1395. !addressmap_have_mapping(tmpbuf,0) &&
  1396. !have_warned_about_unsafe_socks) {
  1397. log_warn(LD_APP,
  1398. "Your application (using socks4 to port %d) is giving Tor "
  1399. "only an IP address. Applications that do DNS resolves "
  1400. "themselves may leak information. Consider using Socks4A "
  1401. "(e.g. via privoxy or socat) instead. For more information, "
  1402. "please see http://wiki.noreply.org/noreply/TheOnionRouter/"
  1403. "TorFAQ#SOCKSAndDNS.%s", req->port,
  1404. safe_socks ? " Rejecting." : "");
  1405. /*have_warned_about_unsafe_socks = 1;*/ /*(for now, warn every time)*/
  1406. control_event_client_status(LOG_WARN,
  1407. "DANGEROUS_SOCKS PROTOCOL=SOCKS4 ADDRESS=%s:%d",
  1408. tmpbuf, req->port);
  1409. if (safe_socks)
  1410. return -1;
  1411. }
  1412. if (socks4_prot == socks4a) {
  1413. if (next+1 == CHUNK_WRITE_PTR(buf->head)) {
  1414. log_debug(LD_APP,"socks4: No part of destaddr here yet.");
  1415. return 0;
  1416. }
  1417. startaddr = next+1;
  1418. next = memchr(startaddr, 0, CHUNK_WRITE_PTR(buf->head)-startaddr);
  1419. if (!next) {
  1420. if (buf->head->datalen >= 1024) {
  1421. log_debug(LD_APP,"socks4: Destaddr too long.");
  1422. return -1;
  1423. }
  1424. log_debug(LD_APP,"socks4: Destaddr not all here yet.");
  1425. return 0;
  1426. }
  1427. if (MAX_SOCKS_ADDR_LEN <= next-startaddr) {
  1428. log_warn(LD_APP,"socks4: Destaddr too long. Rejecting.");
  1429. return -1;
  1430. }
  1431. // tor_assert(next < buf->cur+buf->datalen);
  1432. if (log_sockstype)
  1433. log_notice(LD_APP,
  1434. "Your application (using socks4a to port %d) gave "
  1435. "Tor a hostname, which means Tor will do the DNS resolve "
  1436. "for you. This is good.", req->port);
  1437. }
  1438. log_debug(LD_APP,"socks4: Everything is here. Success.");
  1439. strlcpy(req->address, startaddr ? startaddr : tmpbuf,
  1440. sizeof(req->address));
  1441. if (!tor_strisprint(req->address) || strchr(req->address,'\"')) {
  1442. log_warn(LD_PROTOCOL,
  1443. "Your application (using socks4 to port %d) gave Tor "
  1444. "a malformed hostname: %s. Rejecting the connection.",
  1445. req->port, escaped(req->address));
  1446. return -1;
  1447. }
  1448. /* next points to the final \0 on inbuf */
  1449. buf_remove_from_front(buf, next - buf->head->data + 1);
  1450. return 1;
  1451. case 'G': /* get */
  1452. case 'H': /* head */
  1453. case 'P': /* put/post */
  1454. case 'C': /* connect */
  1455. strlcpy(req->reply,
  1456. "HTTP/1.0 501 Tor is not an HTTP Proxy\r\n"
  1457. "Content-Type: text/html; charset=iso-8859-1\r\n\r\n"
  1458. "<html>\n"
  1459. "<head>\n"
  1460. "<title>Tor is not an HTTP Proxy</title>\n"
  1461. "</head>\n"
  1462. "<body>\n"
  1463. "<h1>Tor is not an HTTP Proxy</h1>\n"
  1464. "<p>\n"
  1465. "It appears you have configured your web browser to use Tor as an HTTP proxy."
  1466. "\n"
  1467. "This is not correct: Tor is a SOCKS proxy, not an HTTP proxy.\n"
  1468. "Please configure your client accordingly.\n"
  1469. "</p>\n"
  1470. "<p>\n"
  1471. "See <a href=\"https://www.torproject.org/documentation.html\">"
  1472. "https://www.torproject.org/documentation.html</a> for more "
  1473. "information.\n"
  1474. "<!-- Plus this comment, to make the body response more than 512 bytes, so "
  1475. " IE will be willing to display it. Comment comment comment comment "
  1476. " comment comment comment comment comment comment comment comment.-->\n"
  1477. "</p>\n"
  1478. "</body>\n"
  1479. "</html>\n"
  1480. , MAX_SOCKS_REPLY_LEN);
  1481. req->replylen = strlen(req->reply)+1;
  1482. /* fall through */
  1483. default: /* version is not socks4 or socks5 */
  1484. log_warn(LD_APP,
  1485. "Socks version %d not recognized. (Tor is not an http proxy.)",
  1486. *(buf->head->data));
  1487. {
  1488. char *tmp = tor_strndup(buf->head->data, 8); /*XXXX what if longer?*/
  1489. control_event_client_status(LOG_WARN,
  1490. "SOCKS_UNKNOWN_PROTOCOL DATA=\"%s\"",
  1491. escaped(tmp));
  1492. tor_free(tmp);
  1493. }
  1494. return -1;
  1495. }
  1496. }
  1497. /** Return 1 iff buf looks more like it has an (obsolete) v0 controller
  1498. * command on it than any valid v1 controller command. */
  1499. int
  1500. peek_buf_has_control0_command(buf_t *buf)
  1501. {
  1502. if (buf->datalen >= 4) {
  1503. char header[4];
  1504. uint16_t cmd;
  1505. peek_from_buf(header, sizeof(header), buf);
  1506. cmd = ntohs(get_uint16(header+2));
  1507. if (cmd <= 0x14)
  1508. return 1; /* This is definitely not a v1 control command. */
  1509. }
  1510. return 0;
  1511. }
  1512. /** Return the index within <b>buf</b> at which <b>ch</b> first appears,
  1513. * or -1 if <b>ch</b> does not appear on buf. */
  1514. static off_t
  1515. buf_find_offset_of_char(buf_t *buf, char ch)
  1516. {
  1517. chunk_t *chunk;
  1518. off_t offset = 0;
  1519. for (chunk = buf->head; chunk; chunk = chunk->next) {
  1520. char *cp = memchr(chunk->data, ch, chunk->datalen);
  1521. if (cp)
  1522. return offset + (cp - chunk->data);
  1523. else
  1524. offset += chunk->datalen;
  1525. }
  1526. return -1;
  1527. }
  1528. /** Try to read a single LF-terminated line from <b>buf</b>, and write it,
  1529. * NUL-terminated, into the *<b>data_len</b> byte buffer at <b>data_out</b>.
  1530. * Set *<b>data_len</b> to the number of bytes in the line, not counting the
  1531. * terminating NUL. Return 1 if we read a whole line, return 0 if we don't
  1532. * have a whole line yet, and return -1 if the line length exceeds
  1533. * *<b>data_len</b>.
  1534. */
  1535. int
  1536. fetch_from_buf_line(buf_t *buf, char *data_out, size_t *data_len)
  1537. {
  1538. size_t sz;
  1539. off_t offset;
  1540. if (!buf->head)
  1541. return 0;
  1542. offset = buf_find_offset_of_char(buf, '\n');
  1543. if (offset < 0)
  1544. return 0;
  1545. sz = (size_t) offset;
  1546. if (sz+2 > *data_len) {
  1547. *data_len = sz + 2;
  1548. return -1;
  1549. }
  1550. fetch_from_buf(data_out, sz+1, buf);
  1551. data_out[sz+1] = '\0';
  1552. *data_len = sz+1;
  1553. return 1;
  1554. }
  1555. /** Compress on uncompress the <b>data_len</b> bytes in <b>data</b> using the
  1556. * zlib state <b>state</b>, appending the result to <b>buf</b>. If
  1557. * <b>done</b> is true, flush the data in the state and finish the
  1558. * compression/uncompression. Return -1 on failure, 0 on success. */
  1559. int
  1560. write_to_buf_zlib(buf_t *buf, tor_zlib_state_t *state,
  1561. const char *data, size_t data_len,
  1562. int done)
  1563. {
  1564. char *next;
  1565. size_t old_avail, avail;
  1566. int over = 0;
  1567. do {
  1568. int need_new_chunk = 0;
  1569. if (!buf->tail || ! CHUNK_REMAINING_CAPACITY(buf->tail)) {
  1570. size_t cap = data_len / 4;
  1571. buf_add_chunk_with_capacity(buf, cap, 1);
  1572. }
  1573. next = CHUNK_WRITE_PTR(buf->tail);
  1574. avail = old_avail = CHUNK_REMAINING_CAPACITY(buf->tail);
  1575. switch (tor_zlib_process(state, &next, &avail, &data, &data_len, done)) {
  1576. case TOR_ZLIB_DONE:
  1577. over = 1;
  1578. break;
  1579. case TOR_ZLIB_ERR:
  1580. return -1;
  1581. case TOR_ZLIB_OK:
  1582. if (data_len == 0)
  1583. over = 1;
  1584. break;
  1585. case TOR_ZLIB_BUF_FULL:
  1586. if (avail) {
  1587. /* Zlib says we need more room (ZLIB_BUF_FULL). Start a new chunk
  1588. * automatically, whether were going to or not. */
  1589. need_new_chunk = 1;
  1590. }
  1591. break;
  1592. }
  1593. buf->datalen += old_avail - avail;
  1594. buf->tail->datalen += old_avail - avail;
  1595. if (need_new_chunk) {
  1596. buf_add_chunk_with_capacity(buf, data_len/4, 1);
  1597. }
  1598. } while (!over);
  1599. check();
  1600. return 0;
  1601. }
  1602. /** Log an error and exit if <b>buf</b> is corrupted.
  1603. */
  1604. void
  1605. assert_buf_ok(buf_t *buf)
  1606. {
  1607. tor_assert(buf);
  1608. tor_assert(buf->magic == BUFFER_MAGIC);
  1609. if (! buf->head) {
  1610. tor_assert(!buf->tail);
  1611. tor_assert(buf->datalen == 0);
  1612. } else {
  1613. chunk_t *ch;
  1614. size_t total = 0;
  1615. tor_assert(buf->tail);
  1616. for (ch = buf->head; ch; ch = ch->next) {
  1617. total += ch->datalen;
  1618. tor_assert(ch->datalen <= ch->memlen);
  1619. tor_assert(ch->data >= &ch->mem[0]);
  1620. tor_assert(ch->data < &ch->mem[0]+ch->memlen);
  1621. tor_assert(ch->data+ch->datalen <= &ch->mem[0] + ch->memlen);
  1622. if (!ch->next)
  1623. tor_assert(ch == buf->tail);
  1624. }
  1625. tor_assert(buf->datalen == total);
  1626. }
  1627. }
  1628. #ifdef ENABLE_BUF_FREELISTS
  1629. /** Log an error and exit if <b>fl</b> is corrupted.
  1630. */
  1631. static void
  1632. assert_freelist_ok(chunk_freelist_t *fl)
  1633. {
  1634. chunk_t *ch;
  1635. int n;
  1636. tor_assert(fl->alloc_size > 0);
  1637. n = 0;
  1638. for (ch = fl->head; ch; ch = ch->next) {
  1639. tor_assert(CHUNK_ALLOC_SIZE(ch->memlen) == fl->alloc_size);
  1640. ++n;
  1641. }
  1642. tor_assert(n == fl->cur_length);
  1643. tor_assert(n >= fl->lowest_length);
  1644. tor_assert(n <= fl->max_length);
  1645. }
  1646. #endif