buffers.c 52 KB

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