dns.c 30 KB

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