dns.c 36 KB

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