dns.c 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299
  1. /* Copyright 2003-2004 Roger Dingledine.
  2. * Copyright 2004-2006 Roger Dingledine, Nick Mathewson. */
  3. /* See LICENSE for licensing information */
  4. /* $Id$ */
  5. const char dns_c_id[] =
  6. "$Id$";
  7. /**
  8. * \file dns.c
  9. * \brief Implements a local cache for DNS results for Tor servers.
  10. * We provide two asynchrounous backend implementations:
  11. * 1) A farm of 'DNS worker' threads or processes to perform DNS lookups for
  12. * onion routers and cache the results.
  13. * 2) A wrapper around Adam Langley's eventdns.c code, to send requests
  14. * to the nameservers asynchronously.
  15. * (We can't just use gethostbyname() and friends because we really need to
  16. * be nonblocking.)
  17. **/
  18. #include "or.h"
  19. #include "../common/ht.h"
  20. #ifdef USE_EVENTDNS
  21. #include "eventdns.h"
  22. #endif
  23. /** Longest hostname we're willing to resolve. */
  24. #define MAX_ADDRESSLEN 256
  25. /** Maximum DNS processes to spawn. */
  26. #define MAX_DNSWORKERS 100
  27. /** Minimum DNS processes to spawn. */
  28. #define MIN_DNSWORKERS 3
  29. /** If more than this many processes are idle, shut down the extras. */
  30. #define MAX_IDLE_DNSWORKERS 10
  31. /** How long will we wait for an answer from the resolver before we decide
  32. * that the resolver is wedged? */
  33. #define RESOLVE_MAX_TIMEOUT 300
  34. /** Possible outcomes from hostname lookup: permanent failure,
  35. * transient (retryable) failure, and success. */
  36. #define DNS_RESOLVE_FAILED_TRANSIENT 1
  37. #define DNS_RESOLVE_FAILED_PERMANENT 2
  38. #define DNS_RESOLVE_SUCCEEDED 3
  39. #ifndef USE_EVENTDNS
  40. /** How many dnsworkers we have running right now. */
  41. static int num_dnsworkers=0;
  42. /** How many of the running dnsworkers have an assigned task right now. */
  43. static int num_dnsworkers_busy=0;
  44. /** When did we last rotate the dnsworkers? */
  45. static time_t last_rotation_time=0;
  46. #endif
  47. /** Linked list of connections waiting for a DNS answer. */
  48. typedef struct pending_connection_t {
  49. edge_connection_t *conn;
  50. struct pending_connection_t *next;
  51. } pending_connection_t;
  52. #define CACHED_RESOLVE_MAGIC 0x1234F00D
  53. /* Possible states for a cached resolve_t */
  54. /** We are waiting for the resolver system to tell us an answer here.
  55. * When we get one, or when we time out, the state of this cached_resolve_t
  56. * will become "DONE" and we'll possibly add a CACHED_VALID or a CACHED_FAILED
  57. * entry. This cached_resolve_t will be in the hash table so that we will
  58. * know not to launch more requests for this addr, but rather to add more
  59. * connections to the pending list for the addr. */
  60. #define CACHE_STATE_PENDING 0
  61. /** This used to be a pending cached_resolve_t, and we got an answer for it.
  62. * Now we're waiting for this cached_resolve_t to expire. This should
  63. * have no pending connections, and should not appear in the hash table. */
  64. #define CACHE_STATE_DONE 1
  65. /** We are caching an answer for this address. This should have no pending
  66. * connections, and should appear in the hash table. */
  67. #define CACHE_STATE_CACHED_VALID 2
  68. /** We are caching a failure for this address. This should have no pending
  69. * connections, and should appear in the hash table */
  70. #define CACHE_STATE_CACHED_FAILED 3
  71. /** A DNS request: possibly completed, possibly pending; cached_resolve
  72. * structs are stored at the OR side in a hash table, and as a linked
  73. * list from oldest to newest.
  74. */
  75. typedef struct cached_resolve_t {
  76. HT_ENTRY(cached_resolve_t) node;
  77. uint32_t magic;
  78. char address[MAX_ADDRESSLEN]; /**< The hostname to be resolved. */
  79. uint32_t addr; /**< IPv4 addr for <b>address</b>. */
  80. uint8_t state; /**< Is this cached entry pending/done/valid/failed? */
  81. time_t expire; /**< Remove items from cache after this time. */
  82. uint32_t ttl; /**< What TTL did the nameserver tell us? */
  83. pending_connection_t *pending_connections;
  84. } cached_resolve_t;
  85. static void purge_expired_resolves(uint32_t now);
  86. static void dns_found_answer(const char *address, uint32_t addr, char outcome,
  87. uint32_t ttl);
  88. static void send_resolved_cell(edge_connection_t *conn, uint8_t answer_type);
  89. static int launch_resolve(edge_connection_t *exitconn);
  90. #ifndef USE_EVENTDNS
  91. static int dnsworker_main(void *data);
  92. static int spawn_dnsworker(void);
  93. static int spawn_enough_dnsworkers(void);
  94. #endif
  95. static void assert_cache_ok(void);
  96. static void assert_resolve_ok(cached_resolve_t *resolve);
  97. /** Hash table of cached_resolve objects. */
  98. static HT_HEAD(cache_map, cached_resolve_t) cache_root;
  99. /** Function to compare hashed resolves on their addresses; used to
  100. * implement hash tables. */
  101. static INLINE int
  102. cached_resolves_eq(cached_resolve_t *a, cached_resolve_t *b)
  103. {
  104. /* make this smarter one day? */
  105. assert_resolve_ok(a); // Not b; b may be just a search.
  106. return !strncmp(a->address, b->address, MAX_ADDRESSLEN);
  107. }
  108. static INLINE unsigned int
  109. cached_resolve_hash(cached_resolve_t *a)
  110. {
  111. return ht_string_hash(a->address);
  112. }
  113. HT_PROTOTYPE(cache_map, cached_resolve_t, node, cached_resolve_hash,
  114. cached_resolves_eq);
  115. HT_GENERATE(cache_map, cached_resolve_t, node, cached_resolve_hash,
  116. cached_resolves_eq, 0.6, malloc, realloc, free);
  117. /** Initialize the DNS cache. */
  118. static void
  119. init_cache_map(void)
  120. {
  121. HT_INIT(&cache_root);
  122. }
  123. #ifdef USE_EVENTDNS
  124. static void
  125. eventdns_log_cb(const char *msg)
  126. {
  127. if (!strcmpstart(msg, "Resolve requested for") &&
  128. get_options()->SafeLogging) {
  129. log(LOG_INFO, LD_EXIT, "eventdns: Resolve requested.");
  130. return;
  131. }
  132. log(LOG_INFO, LD_EXIT, "eventdns: %s", msg);
  133. }
  134. #endif
  135. /** Initialize the DNS subsystem; called by the OR process. */
  136. void
  137. dns_init(void)
  138. {
  139. init_cache_map();
  140. dnsworkers_rotate();
  141. #ifdef USE_EVENTDNS
  142. {
  143. or_options_t *options = get_options();
  144. eventdns_set_log_fn(eventdns_log_cb);
  145. if (options->Nameservers && smartlist_len(options->Nameservers)) {
  146. log_info(LD_EXIT, "Configuring nameservers from Tor configuration");
  147. SMARTLIST_FOREACH(options->Nameservers, const char *, ip,
  148. {
  149. struct in_addr in;
  150. if (tor_inet_aton(ip, &in)) {
  151. log_info(LD_EXIT, "Adding nameserver '%s'", ip);
  152. eventdns_nameserver_add(in.s_addr);
  153. }
  154. });
  155. } else {
  156. #ifdef MS_WINDOWS
  157. eventdns_config_windows_nameservers();
  158. #else
  159. log_info(LD_EXIT, "Parsing /etc/resolv.conf");
  160. eventdns_resolv_conf_parse(DNS_OPTION_NAMESERVERS|DNS_OPTION_MISC,
  161. "/etc/resolv.conf");
  162. #endif
  163. }
  164. }
  165. #endif
  166. }
  167. uint32_t
  168. dns_clip_ttl(uint32_t ttl)
  169. {
  170. if (ttl < MIN_DNS_TTL)
  171. return MIN_DNS_TTL;
  172. else if (ttl > MAX_DNS_TTL)
  173. return MAX_DNS_TTL;
  174. else
  175. return ttl;
  176. }
  177. static uint32_t
  178. dns_get_expiry_ttl(uint32_t ttl)
  179. {
  180. if (ttl < MIN_DNS_TTL)
  181. return MIN_DNS_TTL;
  182. else if (ttl > MAX_DNS_ENTRY_AGE)
  183. return MAX_DNS_ENTRY_AGE;
  184. else
  185. return ttl;
  186. }
  187. /** Helper: free storage held by an entry in the DNS cache. */
  188. static void
  189. _free_cached_resolve(cached_resolve_t *r)
  190. {
  191. while (r->pending_connections) {
  192. pending_connection_t *victim = r->pending_connections;
  193. r->pending_connections = victim->next;
  194. tor_free(victim);
  195. }
  196. r->magic = 0xFF00FF00;
  197. tor_free(r);
  198. }
  199. /** Compare two cached_resolve_t pointers by expiry time, and return
  200. * less-than-zero, zero, or greater-than-zero as appropriate. Used for
  201. * the priority queue implementation. */
  202. static int
  203. _compare_cached_resolves_by_expiry(const void *_a, const void *_b)
  204. {
  205. const cached_resolve_t *a = _a, *b = _b;
  206. if (a->expire < b->expire)
  207. return -1;
  208. else if (a->expire == b->expire)
  209. return 0;
  210. else
  211. return 1;
  212. }
  213. /** Priority queue of cached_resolve_t objects to let us know when they
  214. * will expire. */
  215. static smartlist_t *cached_resolve_pqueue = NULL;
  216. /** Set an expiry time for a cached_resolve_t, and add it to the expiry
  217. * priority queue */
  218. static void
  219. set_expiry(cached_resolve_t *resolve, time_t expires)
  220. {
  221. tor_assert(resolve && resolve->expire == 0);
  222. if (!cached_resolve_pqueue)
  223. cached_resolve_pqueue = smartlist_create();
  224. resolve->expire = expires;
  225. smartlist_pqueue_add(cached_resolve_pqueue,
  226. _compare_cached_resolves_by_expiry,
  227. resolve);
  228. }
  229. /** Free all storage held in the DNS cache */
  230. void
  231. dns_free_all(void)
  232. {
  233. cached_resolve_t **ptr, **next, *item;
  234. for (ptr = HT_START(cache_map, &cache_root); ptr != NULL; ptr = next) {
  235. item = *ptr;
  236. next = HT_NEXT_RMV(cache_map, &cache_root, ptr);
  237. _free_cached_resolve(item);
  238. }
  239. HT_CLEAR(cache_map, &cache_root);
  240. if (cached_resolve_pqueue)
  241. smartlist_free(cached_resolve_pqueue);
  242. cached_resolve_pqueue = NULL;
  243. }
  244. /** Remove every cached_resolve whose <b>expire</b> time is before <b>now</b>
  245. * from the cache. */
  246. static void
  247. purge_expired_resolves(uint32_t now)
  248. {
  249. cached_resolve_t *resolve, *removed;
  250. pending_connection_t *pend;
  251. edge_connection_t *pendconn;
  252. assert_cache_ok();
  253. if (!cached_resolve_pqueue)
  254. return;
  255. while (smartlist_len(cached_resolve_pqueue)) {
  256. resolve = smartlist_get(cached_resolve_pqueue, 0);
  257. if (resolve->expire > now)
  258. break;
  259. smartlist_pqueue_pop(cached_resolve_pqueue,
  260. _compare_cached_resolves_by_expiry);
  261. if (resolve->state == CACHE_STATE_PENDING) {
  262. log_debug(LD_EXIT,
  263. "Expiring a dns resolve %s that's still pending. Forgot to cull"
  264. " it? DNS resolve didn't tell us about the timeout?",
  265. escaped_safe_str(resolve->address));
  266. } else if (resolve->state == CACHE_STATE_CACHED_VALID ||
  267. resolve->state == CACHE_STATE_CACHED_FAILED) {
  268. log_debug(LD_EXIT,
  269. "Forgetting old cached resolve (address %s, expires %lu)",
  270. escaped_safe_str(resolve->address),
  271. (unsigned long)resolve->expire);
  272. tor_assert(!resolve->pending_connections);
  273. } else {
  274. tor_assert(resolve->state == CACHE_STATE_DONE);
  275. tor_assert(!resolve->pending_connections);
  276. }
  277. if (resolve->pending_connections) {
  278. log_debug(LD_EXIT,
  279. "Closing pending connections on timed-out DNS resolve!");
  280. tor_fragile_assert();
  281. while (resolve->pending_connections) {
  282. pend = resolve->pending_connections;
  283. resolve->pending_connections = pend->next;
  284. /* Connections should only be pending if they have no socket. */
  285. tor_assert(pend->conn->_base.s == -1);
  286. pendconn = pend->conn;
  287. connection_edge_end(pendconn, END_STREAM_REASON_TIMEOUT,
  288. pendconn->cpath_layer);
  289. circuit_detach_stream(circuit_get_by_edge_conn(pendconn), pendconn);
  290. connection_free(TO_CONN(pendconn));
  291. tor_free(pend);
  292. }
  293. }
  294. if (resolve->state == CACHE_STATE_CACHED_VALID ||
  295. resolve->state == CACHE_STATE_CACHED_FAILED ||
  296. resolve->state == CACHE_STATE_PENDING) {
  297. removed = HT_REMOVE(cache_map, &cache_root, resolve);
  298. if (removed != resolve) {
  299. log_err(LD_BUG, "The expired resolve we purged didn't match any in"
  300. " the cache. Tried to purge %s (%p); instead got %s (%p).",
  301. resolve->address, resolve,
  302. removed ? removed->address : "NULL", remove);
  303. }
  304. tor_assert(removed == resolve);
  305. resolve->magic = 0xF0BBF0BB;
  306. tor_free(resolve);
  307. } else {
  308. /* This should be in state DONE. Make sure it's not in the cache. */
  309. cached_resolve_t *tmp = HT_FIND(cache_map, &cache_root, resolve);
  310. tor_assert(tmp != resolve);
  311. }
  312. }
  313. assert_cache_ok();
  314. }
  315. /** Send a response to the RESOLVE request of a connection. answer_type must
  316. * be one of RESOLVED_TYPE_(IPV4|ERROR|ERROR_TRANSIENT) */
  317. static void
  318. send_resolved_cell(edge_connection_t *conn, uint8_t answer_type)
  319. {
  320. char buf[RELAY_PAYLOAD_SIZE];
  321. size_t buflen;
  322. uint32_t ttl;
  323. buf[0] = answer_type;
  324. ttl = dns_clip_ttl(conn->address_ttl);
  325. switch (answer_type)
  326. {
  327. case RESOLVED_TYPE_IPV4:
  328. buf[1] = 4;
  329. set_uint32(buf+2, htonl(conn->_base.addr));
  330. set_uint32(buf+6, htonl(ttl));
  331. buflen = 10;
  332. break;
  333. case RESOLVED_TYPE_ERROR_TRANSIENT:
  334. case RESOLVED_TYPE_ERROR:
  335. {
  336. const char *errmsg = "Error resolving hostname";
  337. int msglen = strlen(errmsg);
  338. buf[1] = msglen;
  339. strlcpy(buf+2, errmsg, sizeof(buf)-2);
  340. set_uint32(buf+2+msglen, htonl(ttl));
  341. buflen = 6+msglen;
  342. break;
  343. }
  344. default:
  345. tor_assert(0);
  346. }
  347. connection_edge_send_command(conn, circuit_get_by_edge_conn(conn),
  348. RELAY_COMMAND_RESOLVED, buf, buflen,
  349. conn->cpath_layer);
  350. }
  351. /** See if we have a cache entry for <b>exitconn</b>-\>address. if so,
  352. * if resolve valid, put it into <b>exitconn</b>-\>addr and return 1.
  353. * If resolve failed, unlink exitconn if needed, free it, and return -1.
  354. *
  355. * Else, if seen before and pending, add conn to the pending list,
  356. * and return 0.
  357. *
  358. * Else, if not seen before, add conn to pending list, hand to
  359. * dns farm, and return 0.
  360. */
  361. int
  362. dns_resolve(edge_connection_t *exitconn)
  363. {
  364. cached_resolve_t *resolve;
  365. cached_resolve_t search;
  366. pending_connection_t *pending_connection;
  367. struct in_addr in;
  368. circuit_t *circ;
  369. uint32_t now = time(NULL);
  370. assert_connection_ok(TO_CONN(exitconn), 0);
  371. tor_assert(exitconn->_base.s == -1);
  372. assert_cache_ok();
  373. /* first check if exitconn->_base.address is an IP. If so, we already
  374. * know the answer. */
  375. if (tor_inet_aton(exitconn->_base.address, &in) != 0) {
  376. exitconn->_base.addr = ntohl(in.s_addr);
  377. exitconn->address_ttl = DEFAULT_DNS_TTL;
  378. if (exitconn->_base.purpose == EXIT_PURPOSE_RESOLVE)
  379. send_resolved_cell(exitconn, RESOLVED_TYPE_IPV4);
  380. return 1;
  381. }
  382. /* then take this opportunity to see if there are any expired
  383. * resolves in the hash table. */
  384. purge_expired_resolves(now);
  385. /* lower-case exitconn->_base.address, so it's in canonical form */
  386. tor_strlower(exitconn->_base.address);
  387. /* now check the hash table to see if 'address' is already there. */
  388. strlcpy(search.address, exitconn->_base.address, sizeof(search.address));
  389. resolve = HT_FIND(cache_map, &cache_root, &search);
  390. if (resolve && resolve->expire > now) { /* already there */
  391. switch (resolve->state) {
  392. case CACHE_STATE_PENDING:
  393. /* add us to the pending list */
  394. pending_connection = tor_malloc_zero(
  395. sizeof(pending_connection_t));
  396. pending_connection->conn = exitconn;
  397. pending_connection->next = resolve->pending_connections;
  398. resolve->pending_connections = pending_connection;
  399. log_debug(LD_EXIT,"Connection (fd %d) waiting for pending DNS "
  400. "resolve of %s", exitconn->_base.s,
  401. escaped_safe_str(exitconn->_base.address));
  402. exitconn->_base.state = EXIT_CONN_STATE_RESOLVING;
  403. return 0;
  404. case CACHE_STATE_CACHED_VALID:
  405. exitconn->_base.addr = resolve->addr;
  406. exitconn->address_ttl = resolve->ttl;
  407. log_debug(LD_EXIT,"Connection (fd %d) found cached answer for %s",
  408. exitconn->_base.s,
  409. escaped_safe_str(exitconn->_base.address));
  410. if (exitconn->_base.purpose == EXIT_PURPOSE_RESOLVE)
  411. send_resolved_cell(exitconn, RESOLVED_TYPE_IPV4);
  412. return 1;
  413. case CACHE_STATE_CACHED_FAILED:
  414. log_debug(LD_EXIT,"Connection (fd %d) found cached error for %s",
  415. exitconn->_base.s,
  416. escaped_safe_str(exitconn->_base.address));
  417. if (exitconn->_base.purpose == EXIT_PURPOSE_RESOLVE)
  418. send_resolved_cell(exitconn, RESOLVED_TYPE_ERROR);
  419. circ = circuit_get_by_edge_conn(exitconn);
  420. if (circ)
  421. circuit_detach_stream(circ, exitconn);
  422. if (!exitconn->_base.marked_for_close)
  423. connection_free(TO_CONN(exitconn));
  424. return -1;
  425. case CACHE_STATE_DONE:
  426. log_err(LD_BUG, "Found a 'DONE' dns resolve still in the cache.");
  427. tor_fragile_assert();
  428. }
  429. tor_assert(0);
  430. }
  431. /* not there, need to add it */
  432. resolve = tor_malloc_zero(sizeof(cached_resolve_t));
  433. resolve->magic = CACHED_RESOLVE_MAGIC;
  434. resolve->state = CACHE_STATE_PENDING;
  435. strlcpy(resolve->address, exitconn->_base.address, sizeof(resolve->address));
  436. /* add this connection to the pending list */
  437. pending_connection = tor_malloc_zero(sizeof(pending_connection_t));
  438. pending_connection->conn = exitconn;
  439. resolve->pending_connections = pending_connection;
  440. exitconn->_base.state = EXIT_CONN_STATE_RESOLVING;
  441. /* Add this resolve to the cache and priority queue. */
  442. HT_INSERT(cache_map, &cache_root, resolve);
  443. set_expiry(resolve, now + RESOLVE_MAX_TIMEOUT);
  444. log_debug(LD_EXIT,"Launching %s.",
  445. escaped_safe_str(exitconn->_base.address));
  446. assert_cache_ok();
  447. return launch_resolve(exitconn);
  448. }
  449. /** Log an error and abort if conn is waiting for a DNS resolve.
  450. */
  451. void
  452. assert_connection_edge_not_dns_pending(edge_connection_t *conn)
  453. {
  454. pending_connection_t *pend;
  455. cached_resolve_t **resolve;
  456. HT_FOREACH(resolve, cache_map, &cache_root) {
  457. for (pend = (*resolve)->pending_connections;
  458. pend;
  459. pend = pend->next) {
  460. tor_assert(pend->conn != conn);
  461. }
  462. }
  463. }
  464. /** Log an error and abort if any connection waiting for a DNS resolve is
  465. * corrupted. */
  466. void
  467. assert_all_pending_dns_resolves_ok(void)
  468. {
  469. pending_connection_t *pend;
  470. cached_resolve_t **resolve;
  471. HT_FOREACH(resolve, cache_map, &cache_root) {
  472. for (pend = (*resolve)->pending_connections;
  473. pend;
  474. pend = pend->next) {
  475. assert_connection_ok(TO_CONN(pend->conn), 0);
  476. tor_assert(pend->conn->_base.s == -1);
  477. tor_assert(!connection_in_array(TO_CONN(pend->conn)));
  478. }
  479. }
  480. }
  481. /** Remove <b>conn</b> from the list of connections waiting for conn-\>address.
  482. */
  483. void
  484. connection_dns_remove(edge_connection_t *conn)
  485. {
  486. pending_connection_t *pend, *victim;
  487. cached_resolve_t search;
  488. cached_resolve_t *resolve;
  489. tor_assert(conn->_base.type == CONN_TYPE_EXIT);
  490. tor_assert(conn->_base.state == EXIT_CONN_STATE_RESOLVING);
  491. strlcpy(search.address, conn->_base.address, sizeof(search.address));
  492. resolve = HT_FIND(cache_map, &cache_root, &search);
  493. if (!resolve) {
  494. log_notice(LD_BUG, "Address %s is not pending. Dropping.",
  495. escaped_safe_str(conn->_base.address));
  496. return;
  497. }
  498. tor_assert(resolve->pending_connections);
  499. assert_connection_ok(TO_CONN(conn),0);
  500. pend = resolve->pending_connections;
  501. if (pend->conn == conn) {
  502. resolve->pending_connections = pend->next;
  503. tor_free(pend);
  504. log_debug(LD_EXIT, "First connection (fd %d) no longer waiting "
  505. "for resolve of %s",
  506. conn->_base.s, escaped_safe_str(conn->_base.address));
  507. return;
  508. } else {
  509. for ( ; pend->next; pend = pend->next) {
  510. if (pend->next->conn == conn) {
  511. victim = pend->next;
  512. pend->next = victim->next;
  513. tor_free(victim);
  514. log_debug(LD_EXIT,
  515. "Connection (fd %d) no longer waiting for resolve of %s",
  516. conn->_base.s, escaped_safe_str(conn->_base.address));
  517. return; /* more are pending */
  518. }
  519. }
  520. tor_assert(0); /* not reachable unless onlyconn not in pending list */
  521. }
  522. }
  523. /** Mark all connections waiting for <b>address</b> for close. Then cancel
  524. * the resolve for <b>address</b> itself, and remove any cached results for
  525. * <b>address</b> from the cache.
  526. */
  527. void
  528. dns_cancel_pending_resolve(char *address) //XXXX NM CHECKME.
  529. {
  530. pending_connection_t *pend;
  531. cached_resolve_t search;
  532. cached_resolve_t *resolve, *tmp;
  533. edge_connection_t *pendconn;
  534. circuit_t *circ;
  535. strlcpy(search.address, address, sizeof(search.address));
  536. resolve = HT_FIND(cache_map, &cache_root, &search);
  537. if (!resolve || resolve->state != CACHE_STATE_PENDING) {
  538. log_notice(LD_BUG,"Address %s is not pending. Dropping.",
  539. escaped_safe_str(address));
  540. return;
  541. }
  542. if (!resolve->pending_connections) {
  543. /* XXX this should never trigger, but sometimes it does */
  544. log_warn(LD_BUG,
  545. "Bug: Address %s is pending but has no pending connections!",
  546. escaped_safe_str(address));
  547. tor_fragile_assert();
  548. return;
  549. }
  550. tor_assert(resolve->pending_connections);
  551. tor_assert(! resolve->expire);
  552. /* mark all pending connections to fail */
  553. log_debug(LD_EXIT,
  554. "Failing all connections waiting on DNS resolve of %s",
  555. escaped_safe_str(address));
  556. while (resolve->pending_connections) {
  557. pend = resolve->pending_connections;
  558. pend->conn->_base.state = EXIT_CONN_STATE_RESOLVEFAILED;
  559. pendconn = pend->conn;
  560. assert_connection_ok(TO_CONN(pendconn), 0);
  561. tor_assert(pendconn->_base.s == -1);
  562. if (!pendconn->_base.marked_for_close) {
  563. connection_edge_end(pendconn, END_STREAM_REASON_RESOURCELIMIT,
  564. pendconn->cpath_layer);
  565. }
  566. circ = circuit_get_by_edge_conn(pendconn);
  567. if (circ)
  568. circuit_detach_stream(circ, pendconn);
  569. connection_free(TO_CONN(pendconn));
  570. resolve->pending_connections = pend->next;
  571. tor_free(pend);
  572. }
  573. tmp = HT_REMOVE(cache_map, &cache_root, resolve);
  574. if (tmp != resolve) {
  575. log_err(LD_BUG, "The cancelled resolve we purged didn't match any in"
  576. " the cache. Tried to purge %s (%p); instead got %s (%p).",
  577. resolve->address, resolve,
  578. tmp ? tmp->address : "NULL", tmp);
  579. }
  580. tor_assert(tmp == resolve);
  581. resolve->magic = 0xABABABAB;
  582. tor_free(resolve);
  583. }
  584. static void
  585. add_answer_to_cache(const char *address, uint32_t addr, char outcome,
  586. uint32_t ttl)
  587. {
  588. cached_resolve_t *resolve;
  589. if (outcome == DNS_RESOLVE_FAILED_TRANSIENT)
  590. return;
  591. resolve = tor_malloc_zero(sizeof(cached_resolve_t));
  592. resolve->magic = CACHED_RESOLVE_MAGIC;
  593. resolve->state = (outcome == DNS_RESOLVE_SUCCEEDED) ?
  594. CACHE_STATE_CACHED_VALID : CACHE_STATE_CACHED_FAILED;
  595. strlcpy(resolve->address, address, sizeof(resolve->address));
  596. resolve->addr = addr;
  597. resolve->ttl = ttl;
  598. assert_resolve_ok(resolve);
  599. HT_INSERT(cache_map, &cache_root, resolve);
  600. set_expiry(resolve, time(NULL) + dns_get_expiry_ttl(ttl));
  601. }
  602. /** Called on the OR side when a DNS worker tells us the outcome of a DNS
  603. * resolve: tell all pending connections about the result of the lookup, and
  604. * cache the value. (<b>address</b> is a NUL-terminated string containing the
  605. * address to look up; <b>addr</b> is an IPv4 address in host order;
  606. * <b>outcome</b> is one of
  607. * DNS_RESOLVE_{FAILED_TRANSIENT|FAILED_PERMANENT|SUCCEEDED}.
  608. */
  609. static void
  610. dns_found_answer(const char *address, uint32_t addr, char outcome,
  611. uint32_t ttl)
  612. {
  613. pending_connection_t *pend;
  614. cached_resolve_t search;
  615. cached_resolve_t *resolve, *removed;
  616. edge_connection_t *pendconn;
  617. circuit_t *circ;
  618. assert_cache_ok();
  619. strlcpy(search.address, address, sizeof(search.address));
  620. resolve = HT_FIND(cache_map, &cache_root, &search);
  621. if (!resolve) {
  622. log_info(LD_EXIT,"Resolved unasked address %s; caching anyway.",
  623. escaped_safe_str(address));
  624. add_answer_to_cache(address, addr, outcome, ttl);
  625. return;
  626. }
  627. assert_resolve_ok(resolve);
  628. if (resolve->state != CACHE_STATE_PENDING) {
  629. /* XXXX Maybe update addr? or check addr for consistency? Or let
  630. * VALID replace FAILED? */
  631. log_notice(LD_EXIT, "Resolved %s which was already resolved; ignoring",
  632. escaped_safe_str(address));
  633. tor_assert(resolve->pending_connections == NULL);
  634. return;
  635. }
  636. /* Removed this assertion: in fact, we'll sometimes get a double answer
  637. * to the same question. This can happen when we ask one worker to resolve
  638. * X.Y.Z., then we cancel the request, and then we ask another worker to
  639. * resolve X.Y.Z. */
  640. /* tor_assert(resolve->state == CACHE_STATE_PENDING); */
  641. while (resolve->pending_connections) {
  642. pend = resolve->pending_connections;
  643. pendconn = pend->conn; /* don't pass complex things to the
  644. connection_mark_for_close macro */
  645. assert_connection_ok(TO_CONN(pendconn),time(NULL));
  646. pendconn->_base.addr = addr;
  647. pendconn->address_ttl = ttl;
  648. if (outcome != DNS_RESOLVE_SUCCEEDED) {
  649. /* prevent double-remove. */
  650. pendconn->_base.state = EXIT_CONN_STATE_RESOLVEFAILED;
  651. if (pendconn->_base.purpose == EXIT_PURPOSE_CONNECT) {
  652. connection_edge_end(pendconn, END_STREAM_REASON_RESOLVEFAILED,
  653. pendconn->cpath_layer);
  654. /* This detach must happen after we send the end cell. */
  655. circuit_detach_stream(circuit_get_by_edge_conn(pendconn), pendconn);
  656. } else {
  657. send_resolved_cell(pendconn, RESOLVED_TYPE_ERROR);
  658. /* This detach must happen after we send the resolved cell. */
  659. circuit_detach_stream(circuit_get_by_edge_conn(pendconn), pendconn);
  660. }
  661. connection_free(TO_CONN(pendconn));
  662. } else {
  663. if (pendconn->_base.purpose == EXIT_PURPOSE_CONNECT) {
  664. /* prevent double-remove. */
  665. pend->conn->_base.state = EXIT_CONN_STATE_CONNECTING;
  666. circ = circuit_get_by_edge_conn(pend->conn);
  667. tor_assert(circ);
  668. tor_assert(!CIRCUIT_IS_ORIGIN(circ));
  669. /* unlink pend->conn from resolving_streams, */
  670. circuit_detach_stream(circ, pend->conn);
  671. /* and link it to n_streams */
  672. pend->conn->next_stream = TO_OR_CIRCUIT(circ)->n_streams;
  673. pend->conn->on_circuit = circ;
  674. TO_OR_CIRCUIT(circ)->n_streams = pend->conn;
  675. connection_exit_connect(pend->conn);
  676. } else {
  677. /* prevent double-remove. This isn't really an accurate state,
  678. * but it does the right thing. */
  679. pendconn->_base.state = EXIT_CONN_STATE_RESOLVEFAILED;
  680. send_resolved_cell(pendconn, RESOLVED_TYPE_IPV4);
  681. circ = circuit_get_by_edge_conn(pendconn);
  682. tor_assert(circ);
  683. circuit_detach_stream(circ, pendconn);
  684. connection_free(TO_CONN(pendconn));
  685. }
  686. }
  687. resolve->pending_connections = pend->next;
  688. tor_free(pend);
  689. }
  690. resolve->state = CACHE_STATE_DONE;
  691. removed = HT_REMOVE(cache_map, &cache_root, &search);
  692. if (removed != resolve) {
  693. log_err(LD_BUG, "The pending resolve we found wasn't removable from"
  694. " the cache. Tried to purge %s (%p); instead got %s (%p).",
  695. resolve->address, resolve,
  696. removed ? removed->address : "NULL", removed);
  697. }
  698. assert_resolve_ok(resolve);
  699. assert_cache_ok();
  700. add_answer_to_cache(address, addr, outcome, ttl);
  701. assert_cache_ok();
  702. }
  703. #ifndef USE_EVENTDNS
  704. /** Find or spawn a dns worker process to handle resolving
  705. * <b>exitconn</b>-\>address; tell that dns worker to begin resolving.
  706. */
  707. static int
  708. launch_resolve(edge_connection_t *exitconn)
  709. {
  710. connection_t *dnsconn;
  711. unsigned char len;
  712. tor_assert(exitconn->_base.state == EXIT_CONN_STATE_RESOLVING);
  713. assert_connection_ok(TO_CONN(exitconn), 0);
  714. tor_assert(exitconn->_base.s == -1);
  715. /* respawn here, to be sure there are enough */
  716. if (spawn_enough_dnsworkers() < 0) {
  717. goto err;
  718. }
  719. dnsconn = connection_get_by_type_state(CONN_TYPE_DNSWORKER,
  720. DNSWORKER_STATE_IDLE);
  721. if (!dnsconn) {
  722. log_warn(LD_EXIT,"no idle dns workers. Failing.");
  723. if (exitconn->_base.purpose == EXIT_PURPOSE_RESOLVE)
  724. send_resolved_cell(exitconn, RESOLVED_TYPE_ERROR_TRANSIENT);
  725. goto err;
  726. }
  727. log_debug(LD_EXIT,
  728. "Connection (fd %d) needs to resolve %s; assigning "
  729. "to DNSWorker (fd %d)", exitconn->_base.s,
  730. escaped_safe_str(exitconn->_base.address), dnsconn->s);
  731. tor_free(dnsconn->address);
  732. dnsconn->address = tor_strdup(exitconn->_base.address);
  733. dnsconn->state = DNSWORKER_STATE_BUSY;
  734. /* touch the lastwritten timestamp, since that's how we check to
  735. * see how long it's been since we asked the question, and sometimes
  736. * we check before the first call to connection_handle_write(). */
  737. dnsconn->timestamp_lastwritten = time(NULL);
  738. num_dnsworkers_busy++;
  739. len = strlen(dnsconn->address);
  740. connection_write_to_buf((char*)&len, 1, dnsconn);
  741. connection_write_to_buf(dnsconn->address, len, dnsconn);
  742. return 0;
  743. err:
  744. /* also sends end and frees */
  745. dns_cancel_pending_resolve(exitconn->_base.address);
  746. return -1;
  747. }
  748. /******************************************************************/
  749. /*
  750. * Connection between OR and dnsworker
  751. */
  752. /** Write handler: called when we've pushed a request to a dnsworker. */
  753. int
  754. connection_dns_finished_flushing(connection_t *conn)
  755. {
  756. tor_assert(conn);
  757. tor_assert(conn->type == CONN_TYPE_DNSWORKER);
  758. connection_stop_writing(conn);
  759. return 0;
  760. }
  761. int
  762. connection_dns_reached_eof(connection_t *conn)
  763. {
  764. log_warn(LD_EXIT,"Read eof. Worker died unexpectedly.");
  765. if (conn->state == DNSWORKER_STATE_BUSY) {
  766. /* don't cancel the resolve here -- it would be cancelled in
  767. * connection_about_to_close_connection(), since conn is still
  768. * in state BUSY
  769. */
  770. num_dnsworkers_busy--;
  771. }
  772. num_dnsworkers--;
  773. connection_mark_for_close(conn);
  774. return 0;
  775. }
  776. /** Read handler: called when we get data from a dnsworker. See
  777. * if we have a complete answer. If so, call dns_found_answer on the
  778. * result. If not, wait. Returns 0. */
  779. int
  780. connection_dns_process_inbuf(connection_t *conn)
  781. {
  782. char success;
  783. uint32_t addr;
  784. int ttl;
  785. tor_assert(conn);
  786. tor_assert(conn->type == CONN_TYPE_DNSWORKER);
  787. if (conn->state != DNSWORKER_STATE_BUSY && buf_datalen(conn->inbuf)) {
  788. log_warn(LD_BUG,
  789. "Bug: read data (%d bytes) from an idle dns worker (fd %d, "
  790. "address %s). Please report.", (int)buf_datalen(conn->inbuf),
  791. conn->s, escaped_safe_str(conn->address));
  792. tor_fragile_assert();
  793. /* Pull it off the buffer anyway, or it will just stay there.
  794. * Keep pulling things off because sometimes we get several
  795. * answers at once (!). */
  796. while (buf_datalen(conn->inbuf)) {
  797. connection_fetch_from_buf(&success,1,conn);
  798. connection_fetch_from_buf((char *)&addr,sizeof(uint32_t),conn);
  799. log_warn(LD_EXIT,"Discarding idle dns answer (success %d, addr %d.)",
  800. success, addr);
  801. }
  802. return 0;
  803. }
  804. if (buf_datalen(conn->inbuf) < 5) /* entire answer available? */
  805. return 0; /* not yet */
  806. tor_assert(conn->state == DNSWORKER_STATE_BUSY);
  807. tor_assert(buf_datalen(conn->inbuf) == 5);
  808. connection_fetch_from_buf(&success,1,conn);
  809. connection_fetch_from_buf((char *)&addr,sizeof(uint32_t),conn);
  810. log_debug(LD_EXIT, "DNSWorker (fd %d) returned answer for %s",
  811. conn->s, escaped_safe_str(conn->address));
  812. tor_assert(success >= DNS_RESOLVE_FAILED_TRANSIENT);
  813. tor_assert(success <= DNS_RESOLVE_SUCCEEDED);
  814. ttl = (success == DNS_RESOLVE_FAILED_TRANSIENT) ? 0 : MAX_DNS_ENTRY_AGE;
  815. dns_found_answer(conn->address, ntohl(addr), success, ttl);
  816. tor_free(conn->address);
  817. conn->address = tor_strdup("<idle>");
  818. conn->state = DNSWORKER_STATE_IDLE;
  819. num_dnsworkers_busy--;
  820. if (conn->timestamp_created < last_rotation_time) {
  821. connection_mark_for_close(conn);
  822. num_dnsworkers--;
  823. spawn_enough_dnsworkers();
  824. }
  825. return 0;
  826. }
  827. /** Close and re-open all idle dnsworkers; schedule busy ones to be closed
  828. * and re-opened once they're no longer busy.
  829. **/
  830. void
  831. dnsworkers_rotate(void)
  832. {
  833. connection_t *dnsconn;
  834. while ((dnsconn = connection_get_by_type_state(CONN_TYPE_DNSWORKER,
  835. DNSWORKER_STATE_IDLE))) {
  836. connection_mark_for_close(dnsconn);
  837. num_dnsworkers--;
  838. }
  839. last_rotation_time = time(NULL);
  840. if (server_mode(get_options()))
  841. spawn_enough_dnsworkers();
  842. }
  843. /** Implementation for DNS workers; this code runs in a separate
  844. * execution context. It takes as its argument an fdarray as returned
  845. * by socketpair(), and communicates via fdarray[1]. The protocol is
  846. * as follows:
  847. * - The OR says:
  848. * - ADDRESSLEN [1 byte]
  849. * - ADDRESS [ADDRESSLEN bytes]
  850. * - The DNS worker does the lookup, and replies:
  851. * - OUTCOME [1 byte]
  852. * - IP [4 bytes]
  853. *
  854. * OUTCOME is one of DNS_RESOLVE_{FAILED_TRANSIENT|FAILED_PERMANENT|SUCCEEDED}.
  855. * IP is in host order.
  856. *
  857. * The dnsworker runs indefinitely, until its connection is closed or an error
  858. * occurs.
  859. */
  860. static int
  861. dnsworker_main(void *data)
  862. {
  863. char address[MAX_ADDRESSLEN];
  864. unsigned char address_len;
  865. char *log_address;
  866. char answer[5];
  867. uint32_t ip;
  868. int *fdarray = data;
  869. int fd;
  870. int result;
  871. /* log_fn(LOG_NOTICE,"After spawn: fdarray @%d has %d:%d", (int)fdarray,
  872. * fdarray[0],fdarray[1]); */
  873. fd = fdarray[1]; /* this side is ours */
  874. #ifndef TOR_IS_MULTITHREADED
  875. tor_close_socket(fdarray[0]); /* this is the side of the socketpair the
  876. * parent uses */
  877. tor_free_all(1); /* so the child doesn't hold the parent's fd's open */
  878. handle_signals(0); /* ignore interrupts from the keyboard, etc */
  879. #endif
  880. tor_free(data);
  881. for (;;) {
  882. int r;
  883. if ((r = recv(fd, &address_len, 1, 0)) != 1) {
  884. if (r == 0) {
  885. log_info(LD_EXIT,"DNS worker exiting because Tor process closed "
  886. "connection (either pruned idle dnsworker or died).");
  887. } else {
  888. log_info(LD_EXIT,"DNS worker exiting because of error on connection "
  889. "to Tor process.");
  890. log_info(LD_EXIT,"(Error on %d was %s)", fd,
  891. tor_socket_strerror(tor_socket_errno(fd)));
  892. }
  893. tor_close_socket(fd);
  894. crypto_thread_cleanup();
  895. spawn_exit();
  896. }
  897. if (address_len && read_all(fd, address, address_len, 1) != address_len) {
  898. log_err(LD_BUG,"read hostname failed. Child exiting.");
  899. tor_close_socket(fd);
  900. crypto_thread_cleanup();
  901. spawn_exit();
  902. }
  903. address[address_len] = 0; /* nul terminate it */
  904. log_address = esc_for_log(safe_str(address));
  905. result = tor_lookup_hostname(address, &ip);
  906. /* Make 0.0.0.0 an error, so that we can use "0" to mean "no addr") */
  907. if (!ip)
  908. result = -1;
  909. switch (result) {
  910. case 1:
  911. /* XXX result can never be 1, because we set it to -1 above on error */
  912. log_info(LD_NET,"Could not resolve dest addr %s (transient).",
  913. log_address);
  914. answer[0] = DNS_RESOLVE_FAILED_TRANSIENT;
  915. break;
  916. case -1:
  917. log_info(LD_NET,"Could not resolve dest addr %s (permanent).",
  918. log_address);
  919. answer[0] = DNS_RESOLVE_FAILED_PERMANENT;
  920. break;
  921. case 0:
  922. log_info(LD_NET,"Resolved address %s.", log_address);
  923. answer[0] = DNS_RESOLVE_SUCCEEDED;
  924. break;
  925. }
  926. tor_free(log_address);
  927. set_uint32(answer+1, ip);
  928. if (write_all(fd, answer, 5, 1) != 5) {
  929. log_err(LD_NET,"writing answer failed. Child exiting.");
  930. tor_close_socket(fd);
  931. crypto_thread_cleanup();
  932. spawn_exit();
  933. }
  934. }
  935. return 0; /* windows wants this function to return an int */
  936. }
  937. /** Launch a new DNS worker; return 0 on success, -1 on failure.
  938. */
  939. static int
  940. spawn_dnsworker(void)
  941. {
  942. int *fdarray;
  943. int fd;
  944. connection_t *conn;
  945. int err;
  946. fdarray = tor_malloc(sizeof(int)*2);
  947. if ((err = tor_socketpair(AF_UNIX, SOCK_STREAM, 0, fdarray)) < 0) {
  948. log_warn(LD_NET, "Couldn't construct socketpair: %s",
  949. tor_socket_strerror(-err));
  950. tor_free(fdarray);
  951. return -1;
  952. }
  953. tor_assert(fdarray[0] >= 0);
  954. tor_assert(fdarray[1] >= 0);
  955. /* log_fn(LOG_NOTICE,"Before spawn: fdarray @%d has %d:%d",
  956. (int)fdarray, fdarray[0],fdarray[1]); */
  957. fd = fdarray[0]; /* We copy this out here, since dnsworker_main may free
  958. * fdarray */
  959. spawn_func(dnsworker_main, (void*)fdarray);
  960. log_debug(LD_EXIT,"just spawned a dns worker.");
  961. #ifndef TOR_IS_MULTITHREADED
  962. tor_close_socket(fdarray[1]); /* don't need the worker's side of the pipe */
  963. tor_free(fdarray);
  964. #endif
  965. conn = connection_new(CONN_TYPE_DNSWORKER);
  966. set_socket_nonblocking(fd);
  967. /* set up conn so it's got all the data we need to remember */
  968. conn->s = fd;
  969. conn->address = tor_strdup("<unused>");
  970. if (connection_add(conn) < 0) { /* no space, forget it */
  971. log_warn(LD_NET,"connection_add failed. Giving up.");
  972. connection_free(conn); /* this closes fd */
  973. return -1;
  974. }
  975. conn->state = DNSWORKER_STATE_IDLE;
  976. connection_start_reading(conn);
  977. return 0; /* success */
  978. }
  979. /** If we have too many or too few DNS workers, spawn or kill some.
  980. * Return 0 if we are happy, return -1 if we tried to spawn more but
  981. * we couldn't.
  982. */
  983. static int
  984. spawn_enough_dnsworkers(void)
  985. {
  986. int num_dnsworkers_needed; /* aim to have 1 more than needed,
  987. * but no less than min and no more than max */
  988. connection_t *dnsconn;
  989. /* XXX This may not be the best strategy. Maybe we should queue pending
  990. * requests until the old ones finish or time out: otherwise, if the
  991. * connection requests come fast enough, we never get any DNS done. -NM
  992. *
  993. * XXX But if we queue them, then the adversary can pile even more
  994. * queries onto us, blocking legitimate requests for even longer. Maybe
  995. * we should compromise and only kill if it's been at it for more than,
  996. * e.g., 2 seconds. -RD
  997. */
  998. if (num_dnsworkers_busy == MAX_DNSWORKERS) {
  999. /* We always want at least one worker idle.
  1000. * So find the oldest busy worker and kill it.
  1001. */
  1002. dnsconn = connection_get_by_type_state_lastwritten(CONN_TYPE_DNSWORKER,
  1003. DNSWORKER_STATE_BUSY);
  1004. tor_assert(dnsconn);
  1005. log_warn(LD_EXIT, "%d DNS workers are spawned; all are busy. Killing one.",
  1006. MAX_DNSWORKERS);
  1007. connection_mark_for_close(dnsconn);
  1008. num_dnsworkers_busy--;
  1009. num_dnsworkers--;
  1010. }
  1011. if (num_dnsworkers_busy >= MIN_DNSWORKERS)
  1012. num_dnsworkers_needed = num_dnsworkers_busy+1;
  1013. else
  1014. num_dnsworkers_needed = MIN_DNSWORKERS;
  1015. while (num_dnsworkers < num_dnsworkers_needed) {
  1016. if (spawn_dnsworker() < 0) {
  1017. log_warn(LD_EXIT,"Spawn failed. Will try again later.");
  1018. return -1;
  1019. }
  1020. num_dnsworkers++;
  1021. }
  1022. while (num_dnsworkers > num_dnsworkers_busy+MAX_IDLE_DNSWORKERS) {
  1023. /* too many idle? */
  1024. /* cull excess workers */
  1025. log_info(LD_EXIT,"%d of %d dnsworkers are idle. Killing one.",
  1026. num_dnsworkers-num_dnsworkers_busy, num_dnsworkers);
  1027. dnsconn = connection_get_by_type_state(CONN_TYPE_DNSWORKER,
  1028. DNSWORKER_STATE_IDLE);
  1029. tor_assert(dnsconn);
  1030. connection_mark_for_close(dnsconn);
  1031. num_dnsworkers--;
  1032. }
  1033. return 0;
  1034. }
  1035. #else /* !USE_EVENTDNS */
  1036. static int
  1037. eventdns_err_is_transient(int err)
  1038. {
  1039. switch (err)
  1040. {
  1041. case DNS_ERR_SERVERFAILED:
  1042. case DNS_ERR_TRUNCATED:
  1043. case DNS_ERR_TIMEOUT:
  1044. return 1;
  1045. default:
  1046. return 0;
  1047. }
  1048. }
  1049. void
  1050. dnsworkers_rotate(void)
  1051. {
  1052. }
  1053. int
  1054. connection_dns_finished_flushing(connection_t *conn)
  1055. {
  1056. (void)conn;
  1057. tor_assert(0);
  1058. return 0;
  1059. }
  1060. int
  1061. connection_dns_process_inbuf(connection_t *conn)
  1062. {
  1063. (void)conn;
  1064. tor_assert(0);
  1065. return 0;
  1066. }
  1067. int
  1068. connection_dns_reached_eof(connection_t *conn)
  1069. {
  1070. (void)conn;
  1071. tor_assert(0);
  1072. return 0;
  1073. }
  1074. static void
  1075. eventdns_callback(int result, char type, int count, int ttl, void *addresses,
  1076. void *arg)
  1077. {
  1078. char *string_address = arg;
  1079. int status = DNS_RESOLVE_FAILED_PERMANENT;
  1080. uint32_t addr = 0;
  1081. if (result == DNS_ERR_NONE) {
  1082. if (type == DNS_IPv4_A && count) {
  1083. char answer_buf[INET_NTOA_BUF_LEN+1];
  1084. struct in_addr in;
  1085. uint32_t *addrs = addresses;
  1086. in.s_addr = addrs[0];
  1087. addr = ntohl(addrs[0]);
  1088. status = DNS_RESOLVE_SUCCEEDED;
  1089. tor_inet_ntoa(&in, answer_buf, sizeof(answer_buf));
  1090. log_debug(LD_EXIT, "eventdns said that %s resolves to %s",
  1091. escaped_safe_str(string_address),
  1092. escaped_safe_str(answer_buf));
  1093. } else if (count) {
  1094. log_warn(LD_EXIT, "eventdns returned only non-IPv4 answers for %s.",
  1095. escaped_safe_str(string_address));
  1096. } else {
  1097. log_warn(LD_BUG, "eventdns returned no addresses or error for %s!",
  1098. escaped_safe_str(string_address));
  1099. }
  1100. } else {
  1101. if (eventdns_err_is_transient(result))
  1102. status = DNS_RESOLVE_FAILED_TRANSIENT;
  1103. }
  1104. dns_found_answer(string_address, addr, status, ttl);
  1105. tor_free(string_address);
  1106. }
  1107. static int
  1108. launch_resolve(edge_connection_t *exitconn)
  1109. {
  1110. char *addr = tor_strdup(exitconn->_base.address);
  1111. int r;
  1112. log_info(LD_EXIT, "Launching eventdns request for %s",
  1113. escaped_safe_str(exitconn->_base.address));
  1114. r = eventdns_resolve(exitconn->_base.address, DNS_QUERY_NO_SEARCH,
  1115. eventdns_callback, addr);
  1116. if (r) {
  1117. log_warn(LD_EXIT, "eventdns rejected address %s: error %d.",
  1118. escaped_safe_str(addr), r);
  1119. if (exitconn->_base.purpose == EXIT_PURPOSE_RESOLVE) {
  1120. if (eventdns_err_is_transient(r))
  1121. send_resolved_cell(exitconn, RESOLVED_TYPE_ERROR_TRANSIENT);
  1122. else {
  1123. exitconn->address_ttl = DEFAULT_DNS_TTL;
  1124. send_resolved_cell(exitconn, RESOLVED_TYPE_ERROR);
  1125. }
  1126. }
  1127. dns_cancel_pending_resolve(addr);/* also sends end and frees */
  1128. tor_free(addr);
  1129. }
  1130. return r ? -1 : 0;
  1131. }
  1132. #endif /* USE_EVENTDNS */
  1133. static void
  1134. assert_resolve_ok(cached_resolve_t *resolve)
  1135. {
  1136. tor_assert(resolve);
  1137. tor_assert(resolve->magic == CACHED_RESOLVE_MAGIC);
  1138. tor_assert(strlen(resolve->address) < MAX_ADDRESSLEN);
  1139. tor_assert(tor_strisnonupper(resolve->address));
  1140. if (resolve->state != CACHE_STATE_PENDING) {
  1141. tor_assert(!resolve->pending_connections);
  1142. }
  1143. if (resolve->state == CACHE_STATE_PENDING ||
  1144. resolve->state == CACHE_STATE_DONE) {
  1145. tor_assert(!resolve->ttl);
  1146. tor_assert(!resolve->addr);
  1147. }
  1148. }
  1149. static void
  1150. assert_cache_ok(void)
  1151. {
  1152. cached_resolve_t **resolve;
  1153. int bad_rep = _cache_map_HT_REP_IS_BAD(&cache_root);
  1154. if (bad_rep) {
  1155. log_err(LD_BUG, "Bad rep type %d on dns cache hash table", bad_rep);
  1156. tor_assert(!bad_rep);
  1157. }
  1158. HT_FOREACH(resolve, cache_map, &cache_root) {
  1159. assert_resolve_ok(*resolve);
  1160. tor_assert((*resolve)->state != CACHE_STATE_DONE);
  1161. }
  1162. if (!cached_resolve_pqueue)
  1163. return;
  1164. smartlist_pqueue_assert_ok(cached_resolve_pqueue,
  1165. _compare_cached_resolves_by_expiry);
  1166. }