buffers.c 47 KB

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