buffers.c 52 KB

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