buffers.c 55 KB

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