dns.c 28 KB

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