dns.c 27 KB

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