dns.c 26 KB

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