buffers.c 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530
  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. /** Try to read a single LF-terminated line from <b>buf</b>, and write it,
  1297. * NUL-terminated, into the *<b>data_len</b> byte buffer at <b>data_out</b>.
  1298. * Set *<b>data_len</b> to the number of bytes in the line, not counting the
  1299. * terminating NUL. Return 1 if we read a whole line, return 0 if we don't
  1300. * have a whole line yet, and return -1 if the line length exceeds
  1301. * *<b>data_len</b>.
  1302. */
  1303. int
  1304. fetch_from_buf_line(buf_t *buf, char *data_out, size_t *data_len)
  1305. {
  1306. char *cp;
  1307. size_t sz;
  1308. if (!buf->head)
  1309. return 0;
  1310. /* XXXX020 pull up less aggressively. And implement setting *data_len
  1311. * properly in cases where we return -1. */
  1312. buf_pullup(buf, *data_len, 0);
  1313. cp = memchr(buf->head->data, '\n', buf->head->datalen);
  1314. if (!cp) {
  1315. return 0;
  1316. }
  1317. sz = cp - buf->head->data;
  1318. if (sz+2 > *data_len) {
  1319. *data_len = sz+2;
  1320. return -1;
  1321. }
  1322. fetch_from_buf(data_out, sz+1, buf);
  1323. data_out[sz+1] = '\0';
  1324. *data_len = sz+1;
  1325. return 1;
  1326. }
  1327. /** Compress on uncompress the <b>data_len</b> bytes in <b>data</b> using the
  1328. * zlib state <b>state</b>, appending the result to <b>buf</b>. If
  1329. * <b>done</b> is true, flush the data in the state and finish the
  1330. * compression/uncompression. Return -1 on failure, 0 on success. */
  1331. int
  1332. write_to_buf_zlib(buf_t *buf, tor_zlib_state_t *state,
  1333. const char *data, size_t data_len,
  1334. int done)
  1335. {
  1336. char *next;
  1337. size_t old_avail, avail;
  1338. int over = 0;
  1339. do {
  1340. int need_new_chunk = 0;
  1341. if (!buf->tail || ! CHUNK_REMAINING_CAPACITY(buf->tail)) {
  1342. size_t cap = data_len / 4;
  1343. if (cap > MAX_CHUNK_ALLOC) /* Add a function for this. */
  1344. cap = MAX_CHUNK_ALLOC;
  1345. buf_add_chunk_with_capacity(buf, cap);
  1346. }
  1347. next = CHUNK_WRITE_PTR(buf->tail);
  1348. avail = old_avail = CHUNK_REMAINING_CAPACITY(buf->tail);
  1349. switch (tor_zlib_process(state, &next, &avail, &data, &data_len, done)) {
  1350. case TOR_ZLIB_DONE:
  1351. over = 1;
  1352. break;
  1353. case TOR_ZLIB_ERR:
  1354. return -1;
  1355. case TOR_ZLIB_OK:
  1356. if (data_len == 0)
  1357. over = 1;
  1358. break;
  1359. case TOR_ZLIB_BUF_FULL:
  1360. if (avail) {
  1361. /* Zlib says we need more room (ZLIB_BUF_FULL). Start a new chunk
  1362. * automatically, whether were going to or not. */
  1363. need_new_chunk = 1;
  1364. }
  1365. break;
  1366. }
  1367. buf->datalen += old_avail - avail;
  1368. buf->tail->datalen += old_avail - avail;
  1369. if (need_new_chunk) {
  1370. buf_add_chunk_with_capacity(buf, data_len/4);
  1371. }
  1372. } while (!over);
  1373. check();
  1374. return 0;
  1375. }
  1376. /** Log an error and exit if <b>buf</b> is corrupted.
  1377. */
  1378. void
  1379. assert_buf_ok(buf_t *buf)
  1380. {
  1381. tor_assert(buf);
  1382. tor_assert(buf->magic == BUFFER_MAGIC);
  1383. if (! buf->head) {
  1384. tor_assert(!buf->tail);
  1385. tor_assert(buf->datalen == 0);
  1386. } else {
  1387. chunk_t *ch;
  1388. size_t total = 0;
  1389. tor_assert(buf->tail);
  1390. for (ch = buf->head; ch; ch = ch->next) {
  1391. total += ch->datalen;
  1392. tor_assert(ch->datalen <= ch->memlen);
  1393. tor_assert(ch->data >= &ch->mem[0]);
  1394. tor_assert(ch->data < &ch->mem[0]+ch->memlen);
  1395. tor_assert(ch->data+ch->datalen <= &ch->mem[0] + ch->memlen);
  1396. if (!ch->next)
  1397. tor_assert(ch == buf->tail);
  1398. }
  1399. tor_assert(buf->datalen == total);
  1400. }
  1401. }
  1402. /** Log an error and exit if <b>fl</b> is corrupted.
  1403. */
  1404. static void
  1405. assert_freelist_ok(chunk_freelist_t *fl)
  1406. {
  1407. chunk_t *ch;
  1408. int n;
  1409. tor_assert(fl->alloc_size > 0);
  1410. n = 0;
  1411. for (ch = fl->head; ch; ch = ch->next) {
  1412. tor_assert(CHUNK_ALLOC_SIZE(ch->memlen) == fl->alloc_size);
  1413. ++n;
  1414. }
  1415. tor_assert(n == fl->cur_length);
  1416. tor_assert(n >= fl->lowest_length);
  1417. tor_assert(n <= fl->max_length);
  1418. }