dns.c 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981
  1. /* Copyright 2003-2004 Roger Dingledine.
  2. * Copyright 2004-2005 Roger Dingledine, Nick Mathewson. */
  3. /* See LICENSE for licensing information */
  4. /* $Id$ */
  5. const char dns_c_id[] =
  6. "$Id$";
  7. /**
  8. * \file dns.c
  9. * \brief Implements a farm of 'DNS worker' threads or processes to
  10. * perform DNS lookups for onion routers and cache the results.
  11. * [This needs to be done in the background because of the lack of a
  12. * good, ubiquitous asynchronous DNS implementation.]
  13. **/
  14. /* See
  15. * http://elvin.dstc.com/ListArchive/elvin-dev/archive/2001/09/msg00027.html
  16. * for some approaches to asynchronous dns. We will want to switch once one of
  17. * them becomes more commonly available.
  18. */
  19. #include "or.h"
  20. #include "../common/ht.h"
  21. /** Longest hostname we're willing to resolve. */
  22. #define MAX_ADDRESSLEN 256
  23. /** Maximum DNS processes to spawn. */
  24. #define MAX_DNSWORKERS 100
  25. /** Minimum DNS processes to spawn. */
  26. #define MIN_DNSWORKERS 3
  27. /** If more than this many processes are idle, shut down the extras. */
  28. #define MAX_IDLE_DNSWORKERS 10
  29. /** Possible outcomes from hostname lookup: permanent failure,
  30. * transient (retryable) failure, and success. */
  31. #define DNS_RESOLVE_FAILED_TRANSIENT 1
  32. #define DNS_RESOLVE_FAILED_PERMANENT 2
  33. #define DNS_RESOLVE_SUCCEEDED 3
  34. /** How many dnsworkers we have running right now. */
  35. static int num_dnsworkers=0;
  36. /** How many of the running dnsworkers have an assigned task right now. */
  37. static int num_dnsworkers_busy=0;
  38. /** When did we last rotate the dnsworkers? */
  39. static time_t last_rotation_time=0;
  40. /** Linked list of connections waiting for a DNS answer. */
  41. typedef struct pending_connection_t {
  42. connection_t *conn;
  43. struct pending_connection_t *next;
  44. } pending_connection_t;
  45. /** A DNS request: possibly completed, possibly pending; cached_resolve
  46. * structs are stored at the OR side in a hash table, and as a linked
  47. * list from oldest to newest.
  48. */
  49. typedef struct cached_resolve_t {
  50. HT_ENTRY(cached_resolve_t) node;
  51. char address[MAX_ADDRESSLEN]; /**< The hostname to be resolved. */
  52. uint32_t addr; /**< IPv4 addr for <b>address</b>. */
  53. char state; /**< 0 is pending; 1 means answer is valid; 2 means resolve
  54. * failed. */
  55. #define CACHE_STATE_PENDING 0
  56. #define CACHE_STATE_VALID 1
  57. #define CACHE_STATE_FAILED 2
  58. uint32_t expire; /**< Remove items from cache after this time. */
  59. pending_connection_t *pending_connections;
  60. struct cached_resolve_t *next;
  61. } cached_resolve_t;
  62. static void purge_expired_resolves(uint32_t now);
  63. static int assign_to_dnsworker(connection_t *exitconn);
  64. static void dns_purge_resolve(cached_resolve_t *resolve);
  65. static void dns_found_answer(char *address, uint32_t addr, char outcome);
  66. static int dnsworker_main(void *data);
  67. static int spawn_dnsworker(void);
  68. static int spawn_enough_dnsworkers(void);
  69. static void send_resolved_cell(connection_t *conn, uint8_t answer_type);
  70. /** Hash table of cached_resolve objects. */
  71. static HT_HEAD(cache_map, cached_resolve_t) cache_root;
  72. /** Function to compare hashed resolves on their addresses; used to
  73. * implement hash tables. */
  74. static INLINE int
  75. cached_resolves_eq(cached_resolve_t *a, cached_resolve_t *b)
  76. {
  77. /* make this smarter one day? */
  78. return !strncmp(a->address, b->address, MAX_ADDRESSLEN);
  79. }
  80. static INLINE unsigned int
  81. cached_resolve_hash(cached_resolve_t *a)
  82. {
  83. return ht_string_hash(a->address);
  84. }
  85. HT_PROTOTYPE(cache_map, cached_resolve_t, node, cached_resolve_hash,
  86. cached_resolves_eq);
  87. HT_GENERATE(cache_map, cached_resolve_t, node, cached_resolve_hash,
  88. cached_resolves_eq, 0.6, malloc, realloc, free);
  89. /** Initialize the DNS cache. */
  90. static void
  91. init_cache_map(void)
  92. {
  93. HT_INIT(&cache_root);
  94. }
  95. /** Initialize the DNS subsystem; called by the OR process. */
  96. void
  97. dns_init(void)
  98. {
  99. init_cache_map();
  100. dnsworkers_rotate();
  101. }
  102. /** Helper: free storage held by an entry in the DNS cache. */
  103. static void
  104. _free_cached_resolve(cached_resolve_t *r)
  105. {
  106. while (r->pending_connections) {
  107. pending_connection_t *victim = r->pending_connections;
  108. r->pending_connections = victim->next;
  109. tor_free(victim);
  110. }
  111. tor_free(r);
  112. }
  113. /** Free all storage held in the DNS cache */
  114. void
  115. dns_free_all(void)
  116. {
  117. cached_resolve_t **ptr, **next, *item;
  118. for (ptr = HT_START(cache_map, &cache_root); ptr != NULL; ptr = next) {
  119. item = *ptr;
  120. next = HT_NEXT_RMV(cache_map, &cache_root, ptr);
  121. _free_cached_resolve(item);
  122. }
  123. HT_CLEAR(cache_map, &cache_root);
  124. }
  125. /** Linked list of resolved addresses, oldest to newest. */
  126. static cached_resolve_t *oldest_cached_resolve = NULL;
  127. static cached_resolve_t *newest_cached_resolve = NULL;
  128. /** Remove every cached_resolve whose <b>expire</b> time is before <b>now</b>
  129. * from the cache. */
  130. static void
  131. purge_expired_resolves(uint32_t now)
  132. {
  133. cached_resolve_t *resolve;
  134. pending_connection_t *pend;
  135. connection_t *pendconn;
  136. /* this is fast because the linked list
  137. * oldest_cached_resolve is ordered by when they came in.
  138. */
  139. while (oldest_cached_resolve && (oldest_cached_resolve->expire < now)) {
  140. resolve = oldest_cached_resolve;
  141. debug(LD_EXIT,"Forgetting old cached resolve (address %s, expires %lu)",
  142. safe_str(resolve->address), (unsigned long)resolve->expire);
  143. if (resolve->state == CACHE_STATE_PENDING) {
  144. debug(LD_EXIT,"Bug: Expiring a dns resolve ('%s') that's still pending."
  145. " Forgot to cull it?", safe_str(resolve->address));
  146. tor_fragile_assert();
  147. }
  148. if (resolve->pending_connections) {
  149. debug(LD_EXIT, "Closing pending connections on expiring DNS resolve!");
  150. tor_fragile_assert();
  151. while (resolve->pending_connections) {
  152. pend = resolve->pending_connections;
  153. resolve->pending_connections = pend->next;
  154. /* Connections should only be pending if they have no socket. */
  155. tor_assert(pend->conn->s == -1);
  156. pendconn = pend->conn;
  157. connection_edge_end(pendconn, END_STREAM_REASON_TIMEOUT,
  158. pendconn->cpath_layer);
  159. circuit_detach_stream(circuit_get_by_edge_conn(pendconn), pendconn);
  160. connection_free(pendconn);
  161. tor_free(pend);
  162. }
  163. }
  164. oldest_cached_resolve = resolve->next;
  165. if (!oldest_cached_resolve) /* if there are no more, */
  166. newest_cached_resolve = NULL; /* then make sure the list's tail knows
  167. * that too */
  168. HT_REMOVE(cache_map, &cache_root, resolve);
  169. tor_free(resolve);
  170. }
  171. }
  172. /** Send a response to the RESOVLE request of a connection. answer_type must
  173. * be one of RESOLVED_TYPE_(IPV4|ERROR|ERROR_TRANSIENT) */
  174. static void
  175. send_resolved_cell(connection_t *conn, uint8_t answer_type)
  176. {
  177. char buf[RELAY_PAYLOAD_SIZE];
  178. size_t buflen;
  179. buf[0] = answer_type;
  180. switch (answer_type)
  181. {
  182. case RESOLVED_TYPE_IPV4:
  183. buf[1] = 4;
  184. set_uint32(buf+2, htonl(conn->addr));
  185. set_uint32(buf+6, htonl(MAX_DNS_ENTRY_AGE)); /*XXXX send a real TTL*/
  186. buflen = 10;
  187. break;
  188. case RESOLVED_TYPE_ERROR_TRANSIENT:
  189. case RESOLVED_TYPE_ERROR:
  190. {
  191. const char *errmsg = "Error resolving hostname";
  192. int msglen = strlen(errmsg);
  193. int ttl = (answer_type == RESOLVED_TYPE_ERROR ? MAX_DNS_ENTRY_AGE : 0);
  194. buf[1] = msglen;
  195. strlcpy(buf+2, errmsg, sizeof(buf)-2);
  196. set_uint32(buf+2+msglen, htonl((uint32_t)ttl));
  197. buflen = 6+msglen;
  198. break;
  199. }
  200. default:
  201. tor_assert(0);
  202. }
  203. connection_edge_send_command(conn, circuit_get_by_edge_conn(conn),
  204. RELAY_COMMAND_RESOLVED, buf, buflen,
  205. conn->cpath_layer);
  206. }
  207. /** Link <b>r</b> into the hash table of address-to-result mappings, and add it
  208. * to the linked list of resolves-by-age. */
  209. static void
  210. insert_resolve(cached_resolve_t *r)
  211. {
  212. /* add us to the linked list of resolves */
  213. if (!oldest_cached_resolve) {
  214. oldest_cached_resolve = r;
  215. } else {
  216. newest_cached_resolve->next = r;
  217. }
  218. newest_cached_resolve = r;
  219. HT_INSERT(cache_map, &cache_root, r);
  220. }
  221. /** See if we have a cache entry for <b>exitconn</b>-\>address. if so,
  222. * if resolve valid, put it into <b>exitconn</b>-\>addr and return 1.
  223. * If resolve failed, unlink exitconn if needed, free it, and return -1.
  224. *
  225. * Else, if seen before and pending, add conn to the pending list,
  226. * and return 0.
  227. *
  228. * Else, if not seen before, add conn to pending list, hand to
  229. * dns farm, and return 0.
  230. */
  231. int
  232. dns_resolve(connection_t *exitconn)
  233. {
  234. cached_resolve_t *resolve;
  235. cached_resolve_t search;
  236. pending_connection_t *pending_connection;
  237. struct in_addr in;
  238. circuit_t *circ;
  239. uint32_t now = time(NULL);
  240. assert_connection_ok(exitconn, 0);
  241. tor_assert(exitconn->s == -1);
  242. /* first check if exitconn->address is an IP. If so, we already
  243. * know the answer. */
  244. if (tor_inet_aton(exitconn->address, &in) != 0) {
  245. exitconn->addr = ntohl(in.s_addr);
  246. if (exitconn->purpose == EXIT_PURPOSE_RESOLVE)
  247. send_resolved_cell(exitconn, RESOLVED_TYPE_IPV4);
  248. return 1;
  249. }
  250. /* then take this opportunity to see if there are any expired
  251. * resolves in the hash table. */
  252. purge_expired_resolves(now);
  253. /* lower-case exitconn->address, so it's in canonical form */
  254. tor_strlower(exitconn->address);
  255. /* now check the hash table to see if 'address' is already there. */
  256. strlcpy(search.address, exitconn->address, sizeof(search.address));
  257. resolve = HT_FIND(cache_map, &cache_root, &search);
  258. if (resolve) { /* already there */
  259. switch (resolve->state) {
  260. case CACHE_STATE_PENDING:
  261. /* add us to the pending list */
  262. pending_connection = tor_malloc_zero(
  263. sizeof(pending_connection_t));
  264. pending_connection->conn = exitconn;
  265. pending_connection->next = resolve->pending_connections;
  266. resolve->pending_connections = pending_connection;
  267. debug(LD_EXIT,"Connection (fd %d) waiting for pending DNS "
  268. "resolve of '%s'",
  269. exitconn->s, safe_str(exitconn->address));
  270. exitconn->state = EXIT_CONN_STATE_RESOLVING;
  271. return 0;
  272. case CACHE_STATE_VALID:
  273. exitconn->addr = resolve->addr;
  274. debug(LD_EXIT,"Connection (fd %d) found cached answer for '%s'",
  275. exitconn->s, safe_str(exitconn->address));
  276. if (exitconn->purpose == EXIT_PURPOSE_RESOLVE)
  277. send_resolved_cell(exitconn, RESOLVED_TYPE_IPV4);
  278. return 1;
  279. case CACHE_STATE_FAILED:
  280. debug(LD_EXIT,"Connection (fd %d) found cached error for '%s'",
  281. exitconn->s, safe_str(exitconn->address));
  282. if (exitconn->purpose == EXIT_PURPOSE_RESOLVE)
  283. send_resolved_cell(exitconn, RESOLVED_TYPE_ERROR);
  284. circ = circuit_get_by_edge_conn(exitconn);
  285. if (circ)
  286. circuit_detach_stream(circ, exitconn);
  287. if (!exitconn->marked_for_close)
  288. connection_free(exitconn);
  289. return -1;
  290. }
  291. tor_assert(0);
  292. }
  293. /* not there, need to add it */
  294. resolve = tor_malloc_zero(sizeof(cached_resolve_t));
  295. resolve->state = CACHE_STATE_PENDING;
  296. resolve->expire = now + MAX_DNS_ENTRY_AGE;
  297. strlcpy(resolve->address, exitconn->address, sizeof(resolve->address));
  298. /* add us to the pending list */
  299. pending_connection = tor_malloc_zero(sizeof(pending_connection_t));
  300. pending_connection->conn = exitconn;
  301. resolve->pending_connections = pending_connection;
  302. exitconn->state = EXIT_CONN_STATE_RESOLVING;
  303. insert_resolve(resolve);
  304. return assign_to_dnsworker(exitconn);
  305. }
  306. /** Find or spawn a dns worker process to handle resolving
  307. * <b>exitconn</b>-\>address; tell that dns worker to begin resolving.
  308. */
  309. static int
  310. assign_to_dnsworker(connection_t *exitconn)
  311. {
  312. connection_t *dnsconn;
  313. unsigned char len;
  314. tor_assert(exitconn->state == EXIT_CONN_STATE_RESOLVING);
  315. tor_assert(exitconn->s == -1);
  316. /* respawn here, to be sure there are enough */
  317. if (spawn_enough_dnsworkers() < 0) {
  318. goto err;
  319. }
  320. dnsconn = connection_get_by_type_state(CONN_TYPE_DNSWORKER,
  321. DNSWORKER_STATE_IDLE);
  322. if (!dnsconn) {
  323. warn(LD_EXIT,"no idle dns workers. Failing.");
  324. if (exitconn->purpose == EXIT_PURPOSE_RESOLVE)
  325. send_resolved_cell(exitconn, RESOLVED_TYPE_ERROR_TRANSIENT);
  326. goto err;
  327. }
  328. debug(LD_EXIT,
  329. "Connection (fd %d) needs to resolve '%s'; assigning "
  330. "to DNSWorker (fd %d)",
  331. exitconn->s, safe_str(exitconn->address), dnsconn->s);
  332. tor_free(dnsconn->address);
  333. dnsconn->address = tor_strdup(exitconn->address);
  334. dnsconn->state = DNSWORKER_STATE_BUSY;
  335. num_dnsworkers_busy++;
  336. len = strlen(dnsconn->address);
  337. connection_write_to_buf((char*)&len, 1, dnsconn);
  338. connection_write_to_buf(dnsconn->address, len, dnsconn);
  339. return 0;
  340. err:
  341. dns_cancel_pending_resolve(exitconn->address); /* also sends end and frees */
  342. return -1;
  343. }
  344. /** Remove <b>conn</b> from the list of connections waiting for conn-\>address.
  345. */
  346. void
  347. connection_dns_remove(connection_t *conn)
  348. {
  349. pending_connection_t *pend, *victim;
  350. cached_resolve_t search;
  351. cached_resolve_t *resolve;
  352. tor_assert(conn->type == CONN_TYPE_EXIT);
  353. tor_assert(conn->state == EXIT_CONN_STATE_RESOLVING);
  354. strlcpy(search.address, conn->address, sizeof(search.address));
  355. resolve = HT_FIND(cache_map, &cache_root, &search);
  356. if (!resolve) {
  357. /* XXXX RD This *is* a bug, right? -NM */
  358. notice(LD_BUG, "Address '%s' is not pending. Dropping.",
  359. safe_str(conn->address));
  360. return;
  361. }
  362. tor_assert(resolve->pending_connections);
  363. assert_connection_ok(conn,0);
  364. pend = resolve->pending_connections;
  365. if (pend->conn == conn) {
  366. resolve->pending_connections = pend->next;
  367. tor_free(pend);
  368. debug(LD_EXIT, "First connection (fd %d) no longer waiting for resolve "
  369. "of '%s'",
  370. conn->s, safe_str(conn->address));
  371. return;
  372. } else {
  373. for ( ; pend->next; pend = pend->next) {
  374. if (pend->next->conn == conn) {
  375. victim = pend->next;
  376. pend->next = victim->next;
  377. tor_free(victim);
  378. debug(LD_EXIT, "Connection (fd %d) no longer waiting for resolve "
  379. "of '%s'",
  380. conn->s, safe_str(conn->address));
  381. return; /* more are pending */
  382. }
  383. }
  384. tor_assert(0); /* not reachable unless onlyconn not in pending list */
  385. }
  386. }
  387. /** Log an error and abort if conn is waiting for a DNS resolve.
  388. */
  389. void
  390. assert_connection_edge_not_dns_pending(connection_t *conn)
  391. {
  392. pending_connection_t *pend;
  393. cached_resolve_t **resolve;
  394. HT_FOREACH(resolve, cache_map, &cache_root) {
  395. for (pend = (*resolve)->pending_connections;
  396. pend;
  397. pend = pend->next) {
  398. tor_assert(pend->conn != conn);
  399. }
  400. }
  401. }
  402. /** Log an error and abort if any connection waiting for a DNS resolve is
  403. * corrupted. */
  404. void
  405. assert_all_pending_dns_resolves_ok(void)
  406. {
  407. pending_connection_t *pend;
  408. cached_resolve_t **resolve;
  409. HT_FOREACH(resolve, cache_map, &cache_root) {
  410. for (pend = (*resolve)->pending_connections;
  411. pend;
  412. pend = pend->next) {
  413. assert_connection_ok(pend->conn, 0);
  414. tor_assert(pend->conn->s == -1);
  415. tor_assert(!connection_in_array(pend->conn));
  416. }
  417. }
  418. }
  419. /** Mark all connections waiting for <b>address</b> for close. Then cancel
  420. * the resolve for <b>address</b> itself, and remove any cached results for
  421. * <b>address</b> from the cache.
  422. */
  423. void
  424. dns_cancel_pending_resolve(char *address)
  425. {
  426. pending_connection_t *pend;
  427. cached_resolve_t search;
  428. cached_resolve_t *resolve;
  429. connection_t *pendconn;
  430. circuit_t *circ;
  431. strlcpy(search.address, address, sizeof(search.address));
  432. resolve = HT_FIND(cache_map, &cache_root, &search);
  433. if (!resolve) {
  434. /* XXXX RD This *is* a bug, right? -NM */
  435. notice(LD_BUG,"Address '%s' is not pending. Dropping.", safe_str(address));
  436. return;
  437. }
  438. if (!resolve->pending_connections) {
  439. /* XXX this should never trigger, but sometimes it does */
  440. warn(LD_BUG,"Bug: Address '%s' is pending but has no pending connections!",
  441. safe_str(address));
  442. tor_fragile_assert();
  443. return;
  444. }
  445. tor_assert(resolve->pending_connections);
  446. /* mark all pending connections to fail */
  447. debug(LD_EXIT, "Failing all connections waiting on DNS resolve of '%s'",
  448. safe_str(address));
  449. while (resolve->pending_connections) {
  450. pend = resolve->pending_connections;
  451. pend->conn->state = EXIT_CONN_STATE_RESOLVEFAILED;
  452. pendconn = pend->conn;
  453. tor_assert(pendconn->s == -1);
  454. if (!pendconn->marked_for_close) {
  455. connection_edge_end(pendconn, END_STREAM_REASON_RESOURCELIMIT,
  456. pendconn->cpath_layer);
  457. }
  458. circ = circuit_get_by_edge_conn(pendconn);
  459. if (circ)
  460. circuit_detach_stream(circ, pendconn);
  461. connection_free(pendconn);
  462. resolve->pending_connections = pend->next;
  463. tor_free(pend);
  464. }
  465. dns_purge_resolve(resolve);
  466. }
  467. /** Remove <b>resolve</b> from the cache.
  468. */
  469. static void
  470. dns_purge_resolve(cached_resolve_t *resolve)
  471. {
  472. cached_resolve_t *tmp;
  473. /* remove resolve from the linked list */
  474. if (resolve == oldest_cached_resolve) {
  475. oldest_cached_resolve = resolve->next;
  476. if (oldest_cached_resolve == NULL)
  477. newest_cached_resolve = NULL;
  478. } else {
  479. /* FFFF make it a doubly linked list if this becomes too slow */
  480. for (tmp=oldest_cached_resolve; tmp && tmp->next != resolve; tmp=tmp->next)
  481. ;
  482. tor_assert(tmp); /* it's got to be in the list, or we screwed up somewhere
  483. * else */
  484. tmp->next = resolve->next; /* unlink it */
  485. if (newest_cached_resolve == resolve)
  486. newest_cached_resolve = tmp;
  487. }
  488. /* remove resolve from the map */
  489. HT_REMOVE(cache_map, &cache_root, resolve);
  490. tor_free(resolve);
  491. }
  492. /** Called on the OR side when a DNS worker tells us the outcome of a DNS
  493. * resolve: tell all pending connections about the result of the lookup, and
  494. * cache the value. (<b>address</b> is a NUL-terminated string containing the
  495. * address to look up; <b>addr</b> is an IPv4 address in host order;
  496. * <b>outcome</b> is one of
  497. * DNS_RESOLVE_{FAILED_TRANSIENT|FAILED_PERMANENT|SUCCEEDED}.
  498. */
  499. static void
  500. dns_found_answer(char *address, uint32_t addr, char outcome)
  501. {
  502. pending_connection_t *pend;
  503. cached_resolve_t search;
  504. cached_resolve_t *resolve;
  505. connection_t *pendconn;
  506. circuit_t *circ;
  507. strlcpy(search.address, address, sizeof(search.address));
  508. resolve = HT_FIND(cache_map, &cache_root, &search);
  509. if (!resolve) {
  510. info(LD_EXIT,"Resolved unasked address '%s'; caching anyway.",
  511. safe_str(address));
  512. resolve = tor_malloc_zero(sizeof(cached_resolve_t));
  513. resolve->state = (outcome == DNS_RESOLVE_SUCCEEDED) ?
  514. CACHE_STATE_VALID : CACHE_STATE_FAILED;
  515. resolve->addr = addr;
  516. resolve->expire = time(NULL) + MAX_DNS_ENTRY_AGE;
  517. insert_resolve(resolve);
  518. return;
  519. }
  520. if (resolve->state != CACHE_STATE_PENDING) {
  521. /* XXXX Maybe update addr? or check addr for consistency? Or let
  522. * VALID replace FAILED? */
  523. notice(LD_EXIT, "Resolved '%s' which was already resolved; ignoring",
  524. safe_str(address));
  525. tor_assert(resolve->pending_connections == NULL);
  526. return;
  527. }
  528. /* Removed this assertion: in fact, we'll sometimes get a double answer
  529. * to the same question. This can happen when we ask one worker to resolve
  530. * X.Y.Z., then we cancel the request, and then we ask another worker to
  531. * resolve X.Y.Z. */
  532. /* tor_assert(resolve->state == CACHE_STATE_PENDING); */
  533. resolve->addr = addr;
  534. if (outcome == DNS_RESOLVE_SUCCEEDED)
  535. resolve->state = CACHE_STATE_VALID;
  536. else
  537. resolve->state = CACHE_STATE_FAILED;
  538. while (resolve->pending_connections) {
  539. pend = resolve->pending_connections;
  540. assert_connection_ok(pend->conn,time(NULL));
  541. pend->conn->addr = resolve->addr;
  542. pendconn = pend->conn; /* don't pass complex things to the
  543. connection_mark_for_close macro */
  544. if (resolve->state == CACHE_STATE_FAILED) {
  545. /* prevent double-remove. */
  546. pendconn->state = EXIT_CONN_STATE_RESOLVEFAILED;
  547. if (pendconn->purpose == EXIT_PURPOSE_CONNECT) {
  548. connection_edge_end(pendconn, END_STREAM_REASON_RESOLVEFAILED,
  549. pendconn->cpath_layer);
  550. /* This detach must happen after we send the end cell. */
  551. circuit_detach_stream(circuit_get_by_edge_conn(pendconn), pendconn);
  552. } else {
  553. send_resolved_cell(pendconn, RESOLVED_TYPE_ERROR);
  554. /* This detach must happen after we send the resolved cell. */
  555. circuit_detach_stream(circuit_get_by_edge_conn(pendconn), pendconn);
  556. }
  557. connection_free(pendconn);
  558. } else {
  559. if (pendconn->purpose == EXIT_PURPOSE_CONNECT) {
  560. /* prevent double-remove. */
  561. pend->conn->state = EXIT_CONN_STATE_CONNECTING;
  562. circ = circuit_get_by_edge_conn(pend->conn);
  563. tor_assert(circ);
  564. /* unlink pend->conn from resolving_streams, */
  565. circuit_detach_stream(circ, pend->conn);
  566. /* and link it to n_streams */
  567. pend->conn->next_stream = circ->n_streams;
  568. pend->conn->on_circuit = circ;
  569. circ->n_streams = pend->conn;
  570. connection_exit_connect(pend->conn);
  571. } else {
  572. /* prevent double-remove. This isn't really an accurate state,
  573. * but it does the right thing. */
  574. pendconn->state = EXIT_CONN_STATE_RESOLVEFAILED;
  575. send_resolved_cell(pendconn, RESOLVED_TYPE_IPV4);
  576. circ = circuit_get_by_edge_conn(pendconn);
  577. tor_assert(circ);
  578. circuit_detach_stream(circ, pendconn);
  579. connection_free(pendconn);
  580. }
  581. }
  582. resolve->pending_connections = pend->next;
  583. tor_free(pend);
  584. }
  585. if (outcome == DNS_RESOLVE_FAILED_TRANSIENT) { /* remove from cache */
  586. dns_purge_resolve(resolve);
  587. }
  588. }
  589. /******************************************************************/
  590. /*
  591. * Connection between OR and dnsworker
  592. */
  593. /** Write handler: called when we've pushed a request to a dnsworker. */
  594. int
  595. connection_dns_finished_flushing(connection_t *conn)
  596. {
  597. tor_assert(conn);
  598. tor_assert(conn->type == CONN_TYPE_DNSWORKER);
  599. connection_stop_writing(conn);
  600. return 0;
  601. }
  602. int
  603. connection_dns_reached_eof(connection_t *conn)
  604. {
  605. warn(LD_EXIT,"Read eof. Worker died unexpectedly.");
  606. if (conn->state == DNSWORKER_STATE_BUSY) {
  607. /* don't cancel the resolve here -- it would be cancelled in
  608. * connection_about_to_close_connection(), since conn is still
  609. * in state BUSY
  610. */
  611. num_dnsworkers_busy--;
  612. }
  613. num_dnsworkers--;
  614. connection_mark_for_close(conn);
  615. return 0;
  616. }
  617. /** Read handler: called when we get data from a dnsworker. See
  618. * if we have a complete answer. If so, call dns_found_answer on the
  619. * result. If not, wait. Returns 0. */
  620. int
  621. connection_dns_process_inbuf(connection_t *conn)
  622. {
  623. char success;
  624. uint32_t addr;
  625. tor_assert(conn);
  626. tor_assert(conn->type == CONN_TYPE_DNSWORKER);
  627. if (conn->state != DNSWORKER_STATE_BUSY && buf_datalen(conn->inbuf)) {
  628. warn(LD_BUG,"Bug: read data (%d bytes) from an idle dns worker (fd %d, "
  629. "address '%s'). Please report.",
  630. (int)buf_datalen(conn->inbuf), conn->s, safe_str(conn->address));
  631. tor_fragile_assert();
  632. /* Pull it off the buffer anyway, or it will just stay there.
  633. * Keep pulling things off because sometimes we get several
  634. * answers at once (!). */
  635. while (buf_datalen(conn->inbuf)) {
  636. connection_fetch_from_buf(&success,1,conn);
  637. connection_fetch_from_buf((char *)&addr,sizeof(uint32_t),conn);
  638. warn(LD_EXIT,"Discarding idle dns answer (success %d, addr %d.)",
  639. success, addr); // XXX safe_str
  640. }
  641. return 0;
  642. }
  643. if (buf_datalen(conn->inbuf) < 5) /* entire answer available? */
  644. return 0; /* not yet */
  645. tor_assert(conn->state == DNSWORKER_STATE_BUSY);
  646. tor_assert(buf_datalen(conn->inbuf) == 5);
  647. connection_fetch_from_buf(&success,1,conn);
  648. connection_fetch_from_buf((char *)&addr,sizeof(uint32_t),conn);
  649. debug(LD_EXIT, "DNSWorker (fd %d) returned answer for '%s'",
  650. conn->s, safe_str(conn->address));
  651. tor_assert(success >= DNS_RESOLVE_FAILED_TRANSIENT);
  652. tor_assert(success <= DNS_RESOLVE_SUCCEEDED);
  653. dns_found_answer(conn->address, ntohl(addr), success);
  654. tor_free(conn->address);
  655. conn->address = tor_strdup("<idle>");
  656. conn->state = DNSWORKER_STATE_IDLE;
  657. num_dnsworkers_busy--;
  658. if (conn->timestamp_created < last_rotation_time) {
  659. connection_mark_for_close(conn);
  660. num_dnsworkers--;
  661. spawn_enough_dnsworkers();
  662. }
  663. return 0;
  664. }
  665. /** Close and re-open all idle dnsworkers; schedule busy ones to be closed
  666. * and re-opened once they're no longer busy.
  667. **/
  668. void
  669. dnsworkers_rotate(void)
  670. {
  671. connection_t *dnsconn;
  672. while ((dnsconn = connection_get_by_type_state(CONN_TYPE_DNSWORKER,
  673. DNSWORKER_STATE_IDLE))) {
  674. connection_mark_for_close(dnsconn);
  675. num_dnsworkers--;
  676. }
  677. last_rotation_time = time(NULL);
  678. if (server_mode(get_options()))
  679. spawn_enough_dnsworkers();
  680. }
  681. /** Implementation for DNS workers; this code runs in a separate
  682. * execution context. It takes as its argument an fdarray as returned
  683. * by socketpair(), and communicates via fdarray[1]. The protocol is
  684. * as follows:
  685. * - The OR says:
  686. * - ADDRESSLEN [1 byte]
  687. * - ADDRESS [ADDRESSLEN bytes]
  688. * - The DNS worker does the lookup, and replies:
  689. * - OUTCOME [1 byte]
  690. * - IP [4 bytes]
  691. *
  692. * OUTCOME is one of DNS_RESOLVE_{FAILED_TRANSIENT|FAILED_PERMANENT|SUCCEEDED}.
  693. * IP is in host order.
  694. *
  695. * The dnsworker runs indefinitely, until its connection is closed or an error
  696. * occurs.
  697. */
  698. static int
  699. dnsworker_main(void *data)
  700. {
  701. char address[MAX_ADDRESSLEN];
  702. unsigned char address_len;
  703. char answer[5];
  704. uint32_t ip;
  705. int *fdarray = data;
  706. int fd;
  707. int result;
  708. /* log_fn(LOG_NOTICE,"After spawn: fdarray @%d has %d:%d", (int)fdarray,
  709. * fdarray[0],fdarray[1]); */
  710. fd = fdarray[1]; /* this side is ours */
  711. #ifndef TOR_IS_MULTITHREADED
  712. tor_close_socket(fdarray[0]); /* this is the side of the socketpair the
  713. * parent uses */
  714. tor_free_all(1); /* so the child doesn't hold the parent's fd's open */
  715. handle_signals(0); /* ignore interrupts from the keyboard, etc */
  716. #endif
  717. tor_free(data);
  718. for (;;) {
  719. int r;
  720. if ((r = recv(fd, &address_len, 1, 0)) != 1) {
  721. if (r == 0) {
  722. info(LD_EXIT,"DNS worker exiting because Tor process closed "
  723. "connection (either pruned idle dnsworker or died).");
  724. } else {
  725. info(LD_EXIT,"DNS worker exiting because of error on connection "
  726. "to Tor process.");
  727. info(LD_EXIT,"(Error on %d was %s)", fd,
  728. tor_socket_strerror(tor_socket_errno(fd)));
  729. }
  730. tor_close_socket(fd);
  731. crypto_thread_cleanup();
  732. spawn_exit();
  733. }
  734. if (address_len && read_all(fd, address, address_len, 1) != address_len) {
  735. err(LD_BUG,"read hostname failed. Child exiting.");
  736. tor_close_socket(fd);
  737. crypto_thread_cleanup();
  738. spawn_exit();
  739. }
  740. address[address_len] = 0; /* null terminate it */
  741. result = tor_lookup_hostname(address, &ip);
  742. /* Make 0.0.0.0 an error, so that we can use "0" to mean "no addr") */
  743. if (!ip)
  744. result = -1;
  745. switch (result) {
  746. case 1:
  747. /* XXX result can never be 1, because we set it to -1 above on error */
  748. info(LD_NET,"Could not resolve dest addr %s (transient).",
  749. safe_str(address));
  750. answer[0] = DNS_RESOLVE_FAILED_TRANSIENT;
  751. break;
  752. case -1:
  753. info(LD_NET,"Could not resolve dest addr %s (permanent).",
  754. safe_str(address));
  755. answer[0] = DNS_RESOLVE_FAILED_PERMANENT;
  756. break;
  757. case 0:
  758. info(LD_NET,"Resolved address '%s'.",safe_str(address));
  759. answer[0] = DNS_RESOLVE_SUCCEEDED;
  760. break;
  761. }
  762. set_uint32(answer+1, ip);
  763. if (write_all(fd, answer, 5, 1) != 5) {
  764. err(LD_NET,"writing answer failed. Child exiting.");
  765. tor_close_socket(fd);
  766. crypto_thread_cleanup();
  767. spawn_exit();
  768. }
  769. }
  770. return 0; /* windows wants this function to return an int */
  771. }
  772. /** Launch a new DNS worker; return 0 on success, -1 on failure.
  773. */
  774. static int
  775. spawn_dnsworker(void)
  776. {
  777. int *fdarray;
  778. int fd;
  779. connection_t *conn;
  780. int err;
  781. fdarray = tor_malloc(sizeof(int)*2);
  782. if ((err = tor_socketpair(AF_UNIX, SOCK_STREAM, 0, fdarray)) < 0) {
  783. warn(LD_NET, "Couldn't construct socketpair: %s",
  784. tor_socket_strerror(-err));
  785. tor_free(fdarray);
  786. return -1;
  787. }
  788. /* log_fn(LOG_NOTICE,"Before spawn: fdarray @%d has %d:%d",
  789. (int)fdarray, fdarray[0],fdarray[1]); */
  790. fd = fdarray[0]; /* We copy this out here, since dnsworker_main may free
  791. * fdarray */
  792. spawn_func(dnsworker_main, (void*)fdarray);
  793. debug(LD_EXIT,"just spawned a worker.");
  794. #ifndef TOR_IS_MULTITHREADED
  795. tor_close_socket(fdarray[1]); /* don't need the worker's side of the pipe */
  796. tor_free(fdarray);
  797. #endif
  798. conn = connection_new(CONN_TYPE_DNSWORKER);
  799. set_socket_nonblocking(fd);
  800. /* set up conn so it's got all the data we need to remember */
  801. conn->s = fd;
  802. conn->address = tor_strdup("<unused>");
  803. if (connection_add(conn) < 0) { /* no space, forget it */
  804. warn(LD_NET,"connection_add failed. Giving up.");
  805. connection_free(conn); /* this closes fd */
  806. return -1;
  807. }
  808. conn->state = DNSWORKER_STATE_IDLE;
  809. connection_start_reading(conn);
  810. return 0; /* success */
  811. }
  812. /** If we have too many or too few DNS workers, spawn or kill some.
  813. * Return 0 if we are happy, return -1 if we tried to spawn more but
  814. * we couldn't.
  815. */
  816. static int
  817. spawn_enough_dnsworkers(void)
  818. {
  819. int num_dnsworkers_needed; /* aim to have 1 more than needed,
  820. * but no less than min and no more than max */
  821. connection_t *dnsconn;
  822. /* XXX This may not be the best strategy. Maybe we should queue pending
  823. * requests until the old ones finish or time out: otherwise, if the
  824. * connection requests come fast enough, we never get any DNS done. -NM
  825. *
  826. * XXX But if we queue them, then the adversary can pile even more
  827. * queries onto us, blocking legitimate requests for even longer. Maybe
  828. * we should compromise and only kill if it's been at it for more than,
  829. * e.g., 2 seconds. -RD
  830. */
  831. if (num_dnsworkers_busy == MAX_DNSWORKERS) {
  832. /* We always want at least one worker idle.
  833. * So find the oldest busy worker and kill it.
  834. */
  835. dnsconn = connection_get_by_type_state_lastwritten(CONN_TYPE_DNSWORKER,
  836. DNSWORKER_STATE_BUSY);
  837. tor_assert(dnsconn);
  838. warn(LD_EXIT, "%d DNS workers are spawned; all are busy. Killing one.",
  839. MAX_DNSWORKERS);
  840. connection_mark_for_close(dnsconn);
  841. num_dnsworkers_busy--;
  842. num_dnsworkers--;
  843. }
  844. if (num_dnsworkers_busy >= MIN_DNSWORKERS)
  845. num_dnsworkers_needed = num_dnsworkers_busy+1;
  846. else
  847. num_dnsworkers_needed = MIN_DNSWORKERS;
  848. while (num_dnsworkers < num_dnsworkers_needed) {
  849. if (spawn_dnsworker() < 0) {
  850. warn(LD_EXIT,"Spawn failed. Will try again later.");
  851. return -1;
  852. }
  853. num_dnsworkers++;
  854. }
  855. while (num_dnsworkers > num_dnsworkers_busy+MAX_IDLE_DNSWORKERS) {
  856. /* too many idle? */
  857. /* cull excess workers */
  858. info(LD_EXIT,"%d of %d dnsworkers are idle. Killing one.",
  859. num_dnsworkers-num_dnsworkers_busy, num_dnsworkers);
  860. dnsconn = connection_get_by_type_state(CONN_TYPE_DNSWORKER,
  861. DNSWORKER_STATE_IDLE);
  862. tor_assert(dnsconn);
  863. connection_mark_for_close(dnsconn);
  864. num_dnsworkers--;
  865. }
  866. return 0;
  867. }