dns.c 38 KB

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