dns.c 29 KB

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