dns.c 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795
  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. pending_connection->next = NULL;
  219. resolve->pending_connections = pending_connection;
  220. exitconn->state = EXIT_CONN_STATE_RESOLVING;
  221. /* add us to the linked list of resolves */
  222. if (!oldest_cached_resolve) {
  223. oldest_cached_resolve = resolve;
  224. } else {
  225. newest_cached_resolve->next = resolve;
  226. }
  227. newest_cached_resolve = resolve;
  228. SPLAY_INSERT(cache_tree, &cache_root, resolve);
  229. return assign_to_dnsworker(exitconn);
  230. }
  231. /** Find or spawn a dns worker process to handle resolving
  232. * <b>exitconn</b>-\>address; tell that dns worker to begin resolving.
  233. */
  234. static int assign_to_dnsworker(connection_t *exitconn) {
  235. connection_t *dnsconn;
  236. unsigned char len;
  237. tor_assert(exitconn->state == EXIT_CONN_STATE_RESOLVING);
  238. tor_assert(exitconn->s == -1);
  239. spawn_enough_dnsworkers(); /* respawn here, to be sure there are enough */
  240. dnsconn = connection_get_by_type_state(CONN_TYPE_DNSWORKER, DNSWORKER_STATE_IDLE);
  241. if(!dnsconn) {
  242. log_fn(LOG_WARN,"no idle dns workers. Failing.");
  243. dns_cancel_pending_resolve(exitconn->address);
  244. send_resolved_cell(exitconn, RESOLVED_TYPE_ERROR_TRANSIENT);
  245. return -1;
  246. }
  247. log_fn(LOG_DEBUG, "Connection (fd %d) needs to resolve '%s'; assigning to DNSWorker (fd %d)",
  248. exitconn->s, exitconn->address, dnsconn->s);
  249. tor_free(dnsconn->address);
  250. dnsconn->address = tor_strdup(exitconn->address);
  251. dnsconn->state = DNSWORKER_STATE_BUSY;
  252. num_dnsworkers_busy++;
  253. len = strlen(dnsconn->address);
  254. connection_write_to_buf(&len, 1, dnsconn);
  255. connection_write_to_buf(dnsconn->address, len, dnsconn);
  256. // log_fn(LOG_DEBUG,"submitted '%s'", exitconn->address);
  257. return 0;
  258. }
  259. /** Remove <b>conn</b> from the list of connections waiting for conn-\>address.
  260. */
  261. void connection_dns_remove(connection_t *conn)
  262. {
  263. struct pending_connection_t *pend, *victim;
  264. struct cached_resolve search;
  265. struct cached_resolve *resolve;
  266. tor_assert(conn->type == CONN_TYPE_EXIT);
  267. tor_assert(conn->state == EXIT_CONN_STATE_RESOLVING);
  268. strncpy(search.address, conn->address, MAX_ADDRESSLEN);
  269. search.address[MAX_ADDRESSLEN-1] = 0;
  270. resolve = SPLAY_FIND(cache_tree, &cache_root, &search);
  271. if(!resolve) {
  272. log_fn(LOG_WARN,"Address '%s' is not pending. Dropping.", conn->address);
  273. return;
  274. }
  275. tor_assert(resolve->pending_connections);
  276. assert_connection_ok(conn,0);
  277. pend = resolve->pending_connections;
  278. if(pend->conn == conn) {
  279. resolve->pending_connections = pend->next;
  280. tor_free(pend);
  281. log_fn(LOG_DEBUG, "First connection (fd %d) no longer waiting for resolve of '%s'",
  282. conn->s, conn->address);
  283. return;
  284. } else {
  285. for( ; pend->next; pend = pend->next) {
  286. if(pend->next->conn == conn) {
  287. victim = pend->next;
  288. pend->next = victim->next;
  289. tor_free(victim);
  290. log_fn(LOG_DEBUG, "Connection (fd %d) no longer waiting for resolve of '%s'",
  291. conn->s, conn->address);
  292. return; /* more are pending */
  293. }
  294. }
  295. tor_assert(0); /* not reachable unless onlyconn not in pending list */
  296. }
  297. }
  298. /** Log an error and abort if conn is waiting for a DNS resolve.
  299. */
  300. void assert_connection_edge_not_dns_pending(connection_t *conn) {
  301. struct pending_connection_t *pend;
  302. struct cached_resolve *resolve;
  303. SPLAY_FOREACH(resolve, cache_tree, &cache_root) {
  304. for(pend = resolve->pending_connections;
  305. pend;
  306. pend = pend->next) {
  307. tor_assert(pend->conn != conn);
  308. }
  309. }
  310. }
  311. /** Log an error and abort if any connection waiting for a DNS resolve is
  312. * corrupted. */
  313. void assert_all_pending_dns_resolves_ok(void) {
  314. struct pending_connection_t *pend;
  315. struct cached_resolve *resolve;
  316. SPLAY_FOREACH(resolve, cache_tree, &cache_root) {
  317. for(pend = resolve->pending_connections;
  318. pend;
  319. pend = pend->next) {
  320. assert_connection_ok(pend->conn, 0);
  321. tor_assert(pend->conn->s == -1);
  322. tor_assert(!connection_in_array(pend->conn));
  323. }
  324. }
  325. }
  326. /** Mark all connections waiting for <b>address</b> for close. Then cancel
  327. * the resolve for <b>address</b> itself, and remove any cached results for
  328. * <b>address</b> from the cache.
  329. */
  330. void dns_cancel_pending_resolve(char *address) {
  331. struct pending_connection_t *pend;
  332. struct cached_resolve search;
  333. struct cached_resolve *resolve;
  334. connection_t *pendconn;
  335. strncpy(search.address, address, MAX_ADDRESSLEN);
  336. search.address[MAX_ADDRESSLEN-1] = 0;
  337. resolve = SPLAY_FIND(cache_tree, &cache_root, &search);
  338. if(!resolve) {
  339. log_fn(LOG_WARN,"Address '%s' is not pending. Dropping.", address);
  340. return;
  341. }
  342. tor_assert(resolve->pending_connections);
  343. /* mark all pending connections to fail */
  344. log_fn(LOG_DEBUG, "Failing all connections waiting on DNS resolve of '%s'",
  345. address);
  346. while(resolve->pending_connections) {
  347. pend = resolve->pending_connections;
  348. pend->conn->state = EXIT_CONN_STATE_RESOLVEFAILED;
  349. pendconn = pend->conn;
  350. tor_assert(pendconn->s == -1);
  351. if(!pendconn->marked_for_close) {
  352. connection_edge_end(pendconn, END_STREAM_REASON_MISC, pendconn->cpath_layer);
  353. }
  354. circuit_detach_stream(circuit_get_by_conn(pendconn), pendconn);
  355. connection_free(pendconn);
  356. resolve->pending_connections = pend->next;
  357. tor_free(pend);
  358. }
  359. dns_purge_resolve(resolve);
  360. }
  361. /** Remove <b>resolve</b> from the cache.
  362. */
  363. static void dns_purge_resolve(struct cached_resolve *resolve) {
  364. struct cached_resolve *tmp;
  365. /* remove resolve from the linked list */
  366. if(resolve == oldest_cached_resolve) {
  367. oldest_cached_resolve = resolve->next;
  368. if(oldest_cached_resolve == NULL)
  369. newest_cached_resolve = NULL;
  370. } else {
  371. /* FFFF make it a doubly linked list if this becomes too slow */
  372. for(tmp=oldest_cached_resolve; tmp && tmp->next != resolve; tmp=tmp->next) ;
  373. tor_assert(tmp); /* it's got to be in the list, or we screwed up somewhere else */
  374. tmp->next = resolve->next; /* unlink it */
  375. if(newest_cached_resolve == resolve)
  376. newest_cached_resolve = tmp;
  377. }
  378. /* remove resolve from the tree */
  379. SPLAY_REMOVE(cache_tree, &cache_root, resolve);
  380. tor_free(resolve);
  381. }
  382. /** Called on the OR side when a DNS worker tells us the outcome of a DNS
  383. * resolve: tell all pending connections about the result of the lookup, and
  384. * cache the value. (<b>address</b> is a NUL-terminated string containing the
  385. * address to look up; <b>addr</b> is an IPv4 address in host order;
  386. * <b>outcome</b> is one of
  387. * DNS_RESOLVE_{FAILED_TRANSIENT|FAILED_PERMANENT|SUCCEEDED}.
  388. */
  389. static void dns_found_answer(char *address, uint32_t addr, char outcome) {
  390. struct pending_connection_t *pend;
  391. struct cached_resolve search;
  392. struct cached_resolve *resolve;
  393. connection_t *pendconn;
  394. circuit_t *circ;
  395. strncpy(search.address, address, MAX_ADDRESSLEN);
  396. search.address[MAX_ADDRESSLEN-1] = 0;
  397. resolve = SPLAY_FIND(cache_tree, &cache_root, &search);
  398. if(!resolve) {
  399. log_fn(LOG_INFO,"Resolved unasked address '%s'? Dropping.", address);
  400. /* XXX Why drop? Just because we don't care now doesn't mean we shouldn't
  401. * XXX cache the result for later. */
  402. return;
  403. }
  404. if (resolve->state != CACHE_STATE_PENDING) {
  405. /* XXXX Maybe update addr? or check addr for consistency? Or let
  406. * VALID replace FAILED? */
  407. log_fn(LOG_WARN, "Resolved '%s' which was already resolved; ignoring",
  408. address);
  409. tor_assert(resolve->pending_connections == NULL);
  410. return;
  411. }
  412. /* Removed this assertion: in fact, we'll sometimes get a double answer
  413. * to the same question. This can happen when we ask one worker to resolve
  414. * X.Y.Z., then we cancel the request, and then we ask another worker to
  415. * resolve X.Y.Z. */
  416. /* tor_assert(resolve->state == CACHE_STATE_PENDING); */
  417. resolve->addr = ntohl(addr);
  418. if(outcome == DNS_RESOLVE_SUCCEEDED)
  419. resolve->state = CACHE_STATE_VALID;
  420. else
  421. resolve->state = CACHE_STATE_FAILED;
  422. while(resolve->pending_connections) {
  423. pend = resolve->pending_connections;
  424. assert_connection_ok(pend->conn,time(NULL));
  425. pend->conn->addr = resolve->addr;
  426. pendconn = pend->conn; /* don't pass complex things to the
  427. connection_mark_for_close macro */
  428. if(resolve->state == CACHE_STATE_FAILED) {
  429. /* prevent double-remove. */
  430. pendconn->state = EXIT_CONN_STATE_RESOLVEFAILED;
  431. if (pendconn->purpose == EXIT_PURPOSE_CONNECT) {
  432. connection_edge_end(pendconn, END_STREAM_REASON_RESOLVEFAILED, pendconn->cpath_layer);
  433. /* This detach must happen after we send the end cell. */
  434. circuit_detach_stream(circuit_get_by_conn(pendconn), pendconn);
  435. } else {
  436. send_resolved_cell(pendconn, RESOLVED_TYPE_ERROR);
  437. /* This detach must happen after we send the resolved cell. */
  438. circuit_detach_stream(circuit_get_by_conn(pendconn), pendconn);
  439. }
  440. connection_free(pendconn);
  441. } else {
  442. if (pendconn->purpose == EXIT_PURPOSE_CONNECT) {
  443. /* prevent double-remove. */
  444. pend->conn->state = EXIT_CONN_STATE_CONNECTING;
  445. circ = circuit_get_by_conn(pend->conn);
  446. tor_assert(circ);
  447. /* unlink pend->conn from resolving_streams, */
  448. circuit_detach_stream(circ, pend->conn);
  449. /* and link it to n_streams */
  450. pend->conn->next_stream = circ->n_streams;
  451. circ->n_streams = pend->conn;
  452. connection_exit_connect(pend->conn);
  453. } else {
  454. /* prevent double-remove. This isn't really an accurate state,
  455. * but it does the right thing. */
  456. pendconn->state = EXIT_CONN_STATE_RESOLVEFAILED;
  457. send_resolved_cell(pendconn, RESOLVED_TYPE_IPV4);
  458. circ = circuit_get_by_conn(pendconn);
  459. tor_assert(circ);
  460. circuit_detach_stream(circ, pendconn);
  461. connection_free(pendconn);
  462. }
  463. }
  464. resolve->pending_connections = pend->next;
  465. tor_free(pend);
  466. }
  467. if(outcome == DNS_RESOLVE_FAILED_TRANSIENT) { /* remove from cache */
  468. dns_purge_resolve(resolve);
  469. }
  470. }
  471. /******************************************************************/
  472. /*
  473. * Connection between OR and dnsworker
  474. */
  475. /** Write handler: called when we've pushed a request to a dnsworker. */
  476. int connection_dns_finished_flushing(connection_t *conn) {
  477. tor_assert(conn && conn->type == CONN_TYPE_DNSWORKER);
  478. connection_stop_writing(conn);
  479. return 0;
  480. }
  481. /** Read handler: called when we get data from a dnsworker. If the
  482. * connection is closed, mark the dnsworker as dead. Otherwise, see
  483. * if we have a complete answer. If so, call dns_found_answer on the
  484. * result. If not, wait. Returns 0. */
  485. int connection_dns_process_inbuf(connection_t *conn) {
  486. char success;
  487. uint32_t addr;
  488. tor_assert(conn && conn->type == CONN_TYPE_DNSWORKER);
  489. if(conn->inbuf_reached_eof) {
  490. log_fn(LOG_WARN,"Read eof. Worker died unexpectedly.");
  491. if(conn->state == DNSWORKER_STATE_BUSY) {
  492. dns_cancel_pending_resolve(conn->address);
  493. num_dnsworkers_busy--;
  494. }
  495. num_dnsworkers--;
  496. connection_mark_for_close(conn);
  497. return 0;
  498. }
  499. if(conn->state != DNSWORKER_STATE_BUSY) {
  500. log_fn(LOG_WARN,"Bug: poll() indicated than an idle dns worker was readable. Please report.");
  501. return 0;
  502. }
  503. if(buf_datalen(conn->inbuf) < 5) /* entire answer available? */
  504. return 0; /* not yet */
  505. tor_assert(conn->state == DNSWORKER_STATE_BUSY);
  506. tor_assert(buf_datalen(conn->inbuf) == 5);
  507. connection_fetch_from_buf(&success,1,conn);
  508. connection_fetch_from_buf((char *)&addr,sizeof(uint32_t),conn);
  509. log_fn(LOG_DEBUG, "DNSWorker (fd %d) returned answer for '%s'",
  510. conn->s, conn->address);
  511. tor_assert(success >= DNS_RESOLVE_FAILED_TRANSIENT);
  512. tor_assert(success <= DNS_RESOLVE_SUCCEEDED);
  513. dns_found_answer(conn->address, addr, success);
  514. tor_free(conn->address);
  515. conn->address = tor_strdup("<idle>");
  516. conn->state = DNSWORKER_STATE_IDLE;
  517. num_dnsworkers_busy--;
  518. if (conn->timestamp_created < last_rotation_time) {
  519. connection_mark_for_close(conn);
  520. num_dnsworkers--;
  521. spawn_enough_dnsworkers();
  522. }
  523. return 0;
  524. }
  525. /** Close and re-open all idle dnsworkers; schedule busy ones to be closed
  526. * and re-opened once they're no longer busy.
  527. **/
  528. void dnsworkers_rotate(void)
  529. {
  530. connection_t *dnsconn;
  531. while ((dnsconn = connection_get_by_type_state(CONN_TYPE_DNSWORKER,
  532. DNSWORKER_STATE_IDLE))) {
  533. connection_mark_for_close(dnsconn);
  534. num_dnsworkers--;
  535. }
  536. last_rotation_time = time(NULL);
  537. spawn_enough_dnsworkers();
  538. }
  539. /** Implementation for DNS workers; this code runs in a separate
  540. * execution context. It takes as its argument an fdarray as returned
  541. * by socketpair(), and communicates via fdarray[1]. The protocol is
  542. * as follows:
  543. * - The OR says:
  544. * - ADDRESSLEN [1 byte]
  545. * - ADDRESS [ADDRESSLEN bytes]
  546. * - The DNS worker does the lookup, and replies:
  547. * - OUTCOME [1 byte]
  548. * - IP [4 bytes]
  549. *
  550. * OUTCOME is one of DNS_RESOLVE_{FAILED_TRANSIENT|FAILED_PERMANENT|SUCCEEDED}.
  551. * IP is in host order.
  552. *
  553. * The dnsworker runs indefinitely, until its connection is closed or an error
  554. * occurs.
  555. */
  556. static int dnsworker_main(void *data) {
  557. char address[MAX_ADDRESSLEN];
  558. unsigned char address_len;
  559. char answer[5];
  560. uint32_t ip;
  561. int *fdarray = data;
  562. int fd;
  563. int result;
  564. tor_close_socket(fdarray[0]); /* this is the side of the socketpair the parent uses */
  565. fd = fdarray[1]; /* this side is ours */
  566. #ifndef MS_WINDOWS
  567. connection_free_all(); /* so the child doesn't hold the parent's fd's open */
  568. #endif
  569. handle_signals(0); /* ignore interrupts from the keyboard, etc */
  570. for(;;) {
  571. if(recv(fd, &address_len, 1, 0) != 1) {
  572. log_fn(LOG_INFO,"dnsworker exiting because tor process closed connection (either pruned idle dnsworker or died).");
  573. spawn_exit();
  574. }
  575. if(address_len && read_all(fd, address, address_len, 1) != address_len) {
  576. log_fn(LOG_ERR,"read hostname failed. Child exiting.");
  577. spawn_exit();
  578. }
  579. address[address_len] = 0; /* null terminate it */
  580. result = tor_lookup_hostname(address, &ip);
  581. /* Make 0.0.0.0 an error, so that we can use "0" to mean "no addr") */
  582. if (!ip)
  583. result = -1;
  584. switch (result) {
  585. case 1:
  586. /* XXX008 result can never be 1, because we set it to -1 above on error */
  587. log_fn(LOG_INFO,"Could not resolve dest addr %s (transient).",address);
  588. answer[0] = DNS_RESOLVE_FAILED_TRANSIENT;
  589. break;
  590. case -1:
  591. log_fn(LOG_INFO,"Could not resolve dest addr %s (permanent).",address);
  592. answer[0] = DNS_RESOLVE_FAILED_PERMANENT;
  593. break;
  594. case 0:
  595. log_fn(LOG_INFO,"Resolved address '%s'.",address);
  596. answer[0] = DNS_RESOLVE_SUCCEEDED;
  597. break;
  598. }
  599. set_uint32(answer+1, ip);
  600. if(write_all(fd, answer, 5, 1) != 5) {
  601. log_fn(LOG_ERR,"writing answer failed. Child exiting.");
  602. spawn_exit();
  603. }
  604. }
  605. return 0; /* windows wants this function to return an int */
  606. }
  607. /** Launch a new DNS worker; return 0 on success, -1 on failure.
  608. */
  609. static int spawn_dnsworker(void) {
  610. int fd[2];
  611. connection_t *conn;
  612. if(tor_socketpair(AF_UNIX, SOCK_STREAM, 0, fd) < 0) {
  613. log(LOG_ERR, "Couldn't construct socketpair: %s",
  614. tor_socket_strerror(tor_socket_errno(-1)));
  615. tor_cleanup();
  616. exit(1);
  617. }
  618. spawn_func(dnsworker_main, (void*)fd);
  619. log_fn(LOG_DEBUG,"just spawned a worker.");
  620. tor_close_socket(fd[1]); /* we don't need the worker's side of the pipe */
  621. conn = connection_new(CONN_TYPE_DNSWORKER);
  622. set_socket_nonblocking(fd[0]);
  623. /* set up conn so it's got all the data we need to remember */
  624. conn->s = fd[0];
  625. conn->address = tor_strdup("<unused>");
  626. if(connection_add(conn) < 0) { /* no space, forget it */
  627. log_fn(LOG_WARN,"connection_add failed. Giving up.");
  628. connection_free(conn); /* this closes fd[0] */
  629. return -1;
  630. }
  631. conn->state = DNSWORKER_STATE_IDLE;
  632. connection_start_reading(conn);
  633. return 0; /* success */
  634. }
  635. /** If we have too many or too few DNS workers, spawn or kill some.
  636. */
  637. static void spawn_enough_dnsworkers(void) {
  638. int num_dnsworkers_needed; /* aim to have 1 more than needed,
  639. * but no less than min and no more than max */
  640. connection_t *dnsconn;
  641. /* XXX This may not be the best strategy. Maybe we should queue pending
  642. * requests until the old ones finish or time out: otherwise, if
  643. * the connection requests come fast enough, we never get any DNS done. -NM
  644. * XXX But if we queue them, then the adversary can pile even more
  645. * queries onto us, blocking legitimate requests for even longer.
  646. * Maybe we should compromise and only kill if it's been at it for
  647. * more than, e.g., 2 seconds. -RD
  648. */
  649. if(num_dnsworkers_busy == MAX_DNSWORKERS) {
  650. /* We always want at least one worker idle.
  651. * So find the oldest busy worker and kill it.
  652. */
  653. dnsconn = connection_get_by_type_state_lastwritten(CONN_TYPE_DNSWORKER,
  654. DNSWORKER_STATE_BUSY);
  655. tor_assert(dnsconn);
  656. log_fn(LOG_WARN, "%d DNS workers are spawned; all are busy. Killing one.",
  657. MAX_DNSWORKERS);
  658. connection_mark_for_close(dnsconn);
  659. num_dnsworkers_busy--;
  660. num_dnsworkers--;
  661. }
  662. if(num_dnsworkers_busy >= MIN_DNSWORKERS)
  663. num_dnsworkers_needed = num_dnsworkers_busy+1;
  664. else
  665. num_dnsworkers_needed = MIN_DNSWORKERS;
  666. while(num_dnsworkers < num_dnsworkers_needed) {
  667. if(spawn_dnsworker() < 0) {
  668. log(LOG_WARN,"spawn_enough_dnsworkers(): spawn failed!");
  669. return;
  670. }
  671. num_dnsworkers++;
  672. }
  673. while(num_dnsworkers > num_dnsworkers_busy+MAX_IDLE_DNSWORKERS) { /* too many idle? */
  674. /* cull excess workers */
  675. log_fn(LOG_WARN,"%d of %d dnsworkers are idle. Killing one.",
  676. num_dnsworkers-num_dnsworkers_needed, num_dnsworkers);
  677. dnsconn = connection_get_by_type_state(CONN_TYPE_DNSWORKER, DNSWORKER_STATE_IDLE);
  678. tor_assert(dnsconn);
  679. connection_mark_for_close(dnsconn);
  680. num_dnsworkers--;
  681. }
  682. }
  683. /*
  684. Local Variables:
  685. mode:c
  686. indent-tabs-mode:nil
  687. c-basic-offset:2
  688. End:
  689. */