dns.c 42 KB

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