buffers.c 54 KB

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