dns.c 30 KB

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