buffers.c 55 KB

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