dns.c 32 KB

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