dns.c 40 KB

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