dns.c 32 KB

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