dns.c 46 KB

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