buffers.c 54 KB

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