dns.c 26 KB

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