dns.c 26 KB

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