buffers.c 53 KB

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