dns.c 67 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033
  1. /* Copyright 2003-2004 Roger Dingledine.
  2. * Copyright 2004-2007 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. /** DOCDOC */
  62. #define CACHED_RESOLVE_MAGIC 0x1234F00D
  63. /* Possible states for a cached resolve_t */
  64. /** We are waiting for the resolver system to tell us an answer here.
  65. * When we get one, or when we time out, the state of this cached_resolve_t
  66. * will become "DONE" and we'll possibly add a CACHED_VALID or a CACHED_FAILED
  67. * entry. This cached_resolve_t will be in the hash table so that we will
  68. * know not to launch more requests for this addr, but rather to add more
  69. * connections to the pending list for the addr. */
  70. #define CACHE_STATE_PENDING 0
  71. /** This used to be a pending cached_resolve_t, and we got an answer for it.
  72. * Now we're waiting for this cached_resolve_t to expire. This should
  73. * have no pending connections, and should not appear in the hash table. */
  74. #define CACHE_STATE_DONE 1
  75. /** We are caching an answer for this address. This should have no pending
  76. * connections, and should appear in the hash table. */
  77. #define CACHE_STATE_CACHED_VALID 2
  78. /** We are caching a failure for this address. This should have no pending
  79. * connections, and should appear in the hash table */
  80. #define CACHE_STATE_CACHED_FAILED 3
  81. /** A DNS request: possibly completed, possibly pending; cached_resolve
  82. * structs are stored at the OR side in a hash table, and as a linked
  83. * list from oldest to newest.
  84. */
  85. typedef struct cached_resolve_t {
  86. HT_ENTRY(cached_resolve_t) node;
  87. uint32_t magic;
  88. char address[MAX_ADDRESSLEN]; /**< The hostname to be resolved. */
  89. union {
  90. uint32_t addr; /**< IPv4 addr for <b>address</b>. */
  91. char *hostname; /**< Hostname for <b>address</b> (if a reverse lookup) */
  92. } result;
  93. uint8_t state; /**< Is this cached entry pending/done/valid/failed? */
  94. uint8_t is_reverse; /**< Is this a reverse (addr-to-hostname) lookup? */
  95. time_t expire; /**< Remove items from cache after this time. */
  96. uint32_t ttl; /**< What TTL did the nameserver tell us? */
  97. /** Connections that want to know when we get an answer for this resolve. */
  98. pending_connection_t *pending_connections;
  99. } cached_resolve_t;
  100. static void purge_expired_resolves(time_t now);
  101. static void dns_found_answer(const char *address, int is_reverse,
  102. uint32_t addr, const char *hostname, char outcome,
  103. uint32_t ttl);
  104. static void send_resolved_cell(edge_connection_t *conn, or_circuit_t *circ,
  105. uint8_t answer_type);
  106. static int launch_resolve(edge_connection_t *exitconn, or_circuit_t *circ);
  107. #ifndef USE_EVENTDNS
  108. static void dnsworkers_rotate(void);
  109. static void dnsworker_main(void *data);
  110. static int spawn_dnsworker(void);
  111. static int spawn_enough_dnsworkers(void);
  112. #else
  113. static void add_wildcarded_test_address(const char *address);
  114. static int configure_nameservers(int force);
  115. static int answer_is_wildcarded(const char *ip);
  116. #endif
  117. #ifdef DEBUG_DNS_CACHE
  118. static void _assert_cache_ok(void);
  119. #define assert_cache_ok() _assert_cache_ok()
  120. #else
  121. #define assert_cache_ok() do {} while (0)
  122. #endif
  123. static void assert_resolve_ok(cached_resolve_t *resolve);
  124. /** Hash table of cached_resolve objects. */
  125. static HT_HEAD(cache_map, cached_resolve_t) cache_root;
  126. /** Function to compare hashed resolves on their addresses; used to
  127. * implement hash tables. */
  128. static INLINE int
  129. cached_resolves_eq(cached_resolve_t *a, cached_resolve_t *b)
  130. {
  131. /* make this smarter one day? */
  132. assert_resolve_ok(a); // Not b; b may be just a search.
  133. return !strncmp(a->address, b->address, MAX_ADDRESSLEN);
  134. }
  135. /** Hash function for cached_resolve objects */
  136. static INLINE unsigned int
  137. cached_resolve_hash(cached_resolve_t *a)
  138. {
  139. return ht_string_hash(a->address);
  140. }
  141. HT_PROTOTYPE(cache_map, cached_resolve_t, node, cached_resolve_hash,
  142. cached_resolves_eq);
  143. HT_GENERATE(cache_map, cached_resolve_t, node, cached_resolve_hash,
  144. cached_resolves_eq, 0.6, malloc, realloc, free);
  145. /** Initialize the DNS cache. */
  146. static void
  147. init_cache_map(void)
  148. {
  149. HT_INIT(cache_map, &cache_root);
  150. }
  151. #ifdef USE_EVENTDNS
  152. /** Helper: called by eventdns when eventdns wants to log something. */
  153. static void
  154. evdns_log_cb(int warn, const char *msg)
  155. {
  156. const char *cp;
  157. static int all_down = 0;
  158. int severity = warn ? LOG_WARN : LOG_INFO;
  159. if (!strcmpstart(msg, "Resolve requested for") &&
  160. get_options()->SafeLogging) {
  161. log(LOG_INFO, LD_EXIT, "eventdns: Resolve requested.");
  162. return;
  163. } else if (!strcmpstart(msg, "Search: ")) {
  164. return;
  165. }
  166. if (!strcmpstart(msg, "Nameserver ") && (cp=strstr(msg, " has failed: "))) {
  167. char *ns = tor_strndup(msg+11, cp-(msg+11));
  168. const char *err = strchr(cp, ':'+2);
  169. /* Don't warn about a single failed nameserver; we'll warn with 'all
  170. * nameservers have failed' if we're completely out of nameservers;
  171. * otherwise, the situation is tolerable. */
  172. severity = LOG_INFO;
  173. control_event_server_status(LOG_NOTICE,
  174. "NAMESERVER_STATUS NS=%s STATUS=DOWN ERR=%s",
  175. ns, escaped(err));
  176. tor_free(ns);
  177. } else if (!strcmpstart(msg, "Nameserver ") &&
  178. (cp=strstr(msg, " is back up"))) {
  179. char *ns = tor_strndup(msg+11, cp-(msg+11));
  180. severity = (all_down && warn) ? LOG_NOTICE : LOG_INFO;
  181. all_down = 0;
  182. control_event_server_status(LOG_NOTICE,
  183. "NAMESERVER_STATUS NS=%s STATUS=UP", ns);
  184. tor_free(ns);
  185. } else if (!strcmp(msg, "All nameservers have failed")) {
  186. control_event_server_status(LOG_WARN, "NAMESERVER_ALL_DOWN");
  187. all_down = 1;
  188. }
  189. log(severity, LD_EXIT, "eventdns: %s", msg);
  190. }
  191. #endif
  192. /** Initialize the DNS subsystem; called by the OR process. */
  193. int
  194. dns_init(void)
  195. {
  196. init_cache_map();
  197. #ifdef USE_EVENTDNS
  198. if (server_mode(get_options()))
  199. return configure_nameservers(1);
  200. #else
  201. dnsworkers_rotate();
  202. #endif
  203. return 0;
  204. }
  205. /** Called when DNS-related options change (or may have changed). Returns -1
  206. * on failure, 0 on success. */
  207. int
  208. dns_reset(void)
  209. {
  210. #ifdef USE_EVENTDNS
  211. or_options_t *options = get_options();
  212. if (! server_mode(options)) {
  213. evdns_clear_nameservers_and_suspend();
  214. evdns_search_clear();
  215. nameservers_configured = 0;
  216. tor_free(resolv_conf_fname);
  217. resolv_conf_mtime = 0;
  218. } else {
  219. if (configure_nameservers(0) < 0)
  220. return -1;
  221. }
  222. #else
  223. dnsworkers_rotate();
  224. #endif
  225. return 0;
  226. }
  227. /** Helper: Given a TTL from a DNS response, determine what TTL to give the
  228. * OP that asked us to resolve it. */
  229. uint32_t
  230. dns_clip_ttl(uint32_t ttl)
  231. {
  232. if (ttl < MIN_DNS_TTL)
  233. return MIN_DNS_TTL;
  234. else if (ttl > MAX_DNS_TTL)
  235. return MAX_DNS_TTL;
  236. else
  237. return ttl;
  238. }
  239. /** Helper: Given a TTL from a DNS response, determine how long to hold it in
  240. * our cache. */
  241. static uint32_t
  242. dns_get_expiry_ttl(uint32_t ttl)
  243. {
  244. if (ttl < MIN_DNS_TTL)
  245. return MIN_DNS_TTL;
  246. else if (ttl > MAX_DNS_ENTRY_AGE)
  247. return MAX_DNS_ENTRY_AGE;
  248. else
  249. return ttl;
  250. }
  251. /** Helper: free storage held by an entry in the DNS cache. */
  252. static void
  253. _free_cached_resolve(cached_resolve_t *r)
  254. {
  255. while (r->pending_connections) {
  256. pending_connection_t *victim = r->pending_connections;
  257. r->pending_connections = victim->next;
  258. tor_free(victim);
  259. }
  260. if (r->is_reverse)
  261. tor_free(r->result.hostname);
  262. r->magic = 0xFF00FF00;
  263. tor_free(r);
  264. }
  265. /** Compare two cached_resolve_t pointers by expiry time, and return
  266. * less-than-zero, zero, or greater-than-zero as appropriate. Used for
  267. * the priority queue implementation. */
  268. static int
  269. _compare_cached_resolves_by_expiry(const void *_a, const void *_b)
  270. {
  271. const cached_resolve_t *a = _a, *b = _b;
  272. return a->expire - b->expire;
  273. }
  274. /** Priority queue of cached_resolve_t objects to let us know when they
  275. * will expire. */
  276. static smartlist_t *cached_resolve_pqueue = NULL;
  277. /** Set an expiry time for a cached_resolve_t, and add it to the expiry
  278. * priority queue */
  279. static void
  280. set_expiry(cached_resolve_t *resolve, time_t expires)
  281. {
  282. tor_assert(resolve && resolve->expire == 0);
  283. if (!cached_resolve_pqueue)
  284. cached_resolve_pqueue = smartlist_create();
  285. resolve->expire = expires;
  286. smartlist_pqueue_add(cached_resolve_pqueue,
  287. _compare_cached_resolves_by_expiry,
  288. resolve);
  289. }
  290. /** Free all storage held in the DNS cache and related structures. */
  291. void
  292. dns_free_all(void)
  293. {
  294. cached_resolve_t **ptr, **next, *item;
  295. assert_cache_ok();
  296. if (cached_resolve_pqueue) {
  297. SMARTLIST_FOREACH(cached_resolve_pqueue, cached_resolve_t *, res,
  298. {
  299. if (res->state == CACHE_STATE_DONE)
  300. _free_cached_resolve(res);
  301. });
  302. }
  303. for (ptr = HT_START(cache_map, &cache_root); ptr != NULL; ptr = next) {
  304. item = *ptr;
  305. next = HT_NEXT_RMV(cache_map, &cache_root, ptr);
  306. _free_cached_resolve(item);
  307. }
  308. HT_CLEAR(cache_map, &cache_root);
  309. if (cached_resolve_pqueue)
  310. smartlist_free(cached_resolve_pqueue);
  311. cached_resolve_pqueue = NULL;
  312. #ifdef USE_EVENTDNS
  313. tor_free(resolv_conf_fname);
  314. #endif
  315. }
  316. /** Remove every cached_resolve whose <b>expire</b> time is before <b>now</b>
  317. * from the cache. */
  318. static void
  319. purge_expired_resolves(time_t now)
  320. {
  321. cached_resolve_t *resolve, *removed;
  322. pending_connection_t *pend;
  323. edge_connection_t *pendconn;
  324. assert_cache_ok();
  325. if (!cached_resolve_pqueue)
  326. return;
  327. while (smartlist_len(cached_resolve_pqueue)) {
  328. resolve = smartlist_get(cached_resolve_pqueue, 0);
  329. if (resolve->expire > now)
  330. break;
  331. smartlist_pqueue_pop(cached_resolve_pqueue,
  332. _compare_cached_resolves_by_expiry);
  333. if (resolve->state == CACHE_STATE_PENDING) {
  334. log_debug(LD_EXIT,
  335. "Expiring a dns resolve %s that's still pending. Forgot to "
  336. "cull it? DNS resolve didn't tell us about the timeout?",
  337. escaped_safe_str(resolve->address));
  338. } else if (resolve->state == CACHE_STATE_CACHED_VALID ||
  339. resolve->state == CACHE_STATE_CACHED_FAILED) {
  340. log_debug(LD_EXIT,
  341. "Forgetting old cached resolve (address %s, expires %lu)",
  342. escaped_safe_str(resolve->address),
  343. (unsigned long)resolve->expire);
  344. tor_assert(!resolve->pending_connections);
  345. } else {
  346. tor_assert(resolve->state == CACHE_STATE_DONE);
  347. tor_assert(!resolve->pending_connections);
  348. }
  349. if (resolve->pending_connections) {
  350. log_debug(LD_EXIT,
  351. "Closing pending connections on timed-out DNS resolve!");
  352. tor_fragile_assert();
  353. while (resolve->pending_connections) {
  354. pend = resolve->pending_connections;
  355. resolve->pending_connections = pend->next;
  356. /* Connections should only be pending if they have no socket. */
  357. tor_assert(pend->conn->_base.s == -1);
  358. pendconn = pend->conn;
  359. connection_edge_end(pendconn, END_STREAM_REASON_TIMEOUT,
  360. pendconn->cpath_layer);
  361. circuit_detach_stream(circuit_get_by_edge_conn(pendconn), pendconn);
  362. connection_free(TO_CONN(pendconn));
  363. tor_free(pend);
  364. }
  365. }
  366. if (resolve->state == CACHE_STATE_CACHED_VALID ||
  367. resolve->state == CACHE_STATE_CACHED_FAILED ||
  368. resolve->state == CACHE_STATE_PENDING) {
  369. removed = HT_REMOVE(cache_map, &cache_root, resolve);
  370. if (removed != resolve) {
  371. log_err(LD_BUG, "The expired resolve we purged didn't match any in"
  372. " the cache. Tried to purge %s (%p); instead got %s (%p).",
  373. resolve->address, (void*)resolve,
  374. removed ? removed->address : "NULL", (void*)remove);
  375. }
  376. tor_assert(removed == resolve);
  377. if (resolve->is_reverse)
  378. tor_free(resolve->result.hostname);
  379. resolve->magic = 0xF0BBF0BB;
  380. tor_free(resolve);
  381. } else {
  382. /* This should be in state DONE. Make sure it's not in the cache. */
  383. cached_resolve_t *tmp = HT_FIND(cache_map, &cache_root, resolve);
  384. tor_assert(tmp != resolve);
  385. }
  386. }
  387. assert_cache_ok();
  388. }
  389. /** Send a response to the RESOLVE request of a connection.
  390. * <b>answer_type</b> must be one of
  391. * RESOLVED_TYPE_(IPV4|ERROR|ERROR_TRANSIENT).
  392. *
  393. * If <b>circ</b> is provided, and we have a cached answer, send the
  394. * answer back along circ; otherwise, send the answer back along
  395. * <b>conn</b>'s attached circuit.
  396. */
  397. static void
  398. send_resolved_cell(edge_connection_t *conn, or_circuit_t *circ,
  399. uint8_t answer_type)
  400. {
  401. char buf[RELAY_PAYLOAD_SIZE];
  402. size_t buflen;
  403. uint32_t ttl;
  404. buf[0] = answer_type;
  405. ttl = dns_clip_ttl(conn->address_ttl);
  406. switch (answer_type)
  407. {
  408. case RESOLVED_TYPE_IPV4:
  409. buf[1] = 4;
  410. set_uint32(buf+2, htonl(conn->_base.addr));
  411. set_uint32(buf+6, htonl(ttl));
  412. buflen = 10;
  413. break;
  414. case RESOLVED_TYPE_ERROR_TRANSIENT:
  415. case RESOLVED_TYPE_ERROR:
  416. {
  417. const char *errmsg = "Error resolving hostname";
  418. int msglen = strlen(errmsg);
  419. buf[1] = msglen;
  420. strlcpy(buf+2, errmsg, sizeof(buf)-2);
  421. set_uint32(buf+2+msglen, htonl(ttl));
  422. buflen = 6+msglen;
  423. break;
  424. }
  425. default:
  426. tor_assert(0);
  427. return;
  428. }
  429. // log_notice(LD_EXIT, "Sending a regular RESOLVED reply: ");
  430. if (!circ) {
  431. circuit_t *tmp = circuit_get_by_edge_conn(conn);
  432. if (! CIRCUIT_IS_ORIGIN(tmp))
  433. circ = TO_OR_CIRCUIT(tmp);
  434. }
  435. connection_edge_send_command(conn, TO_CIRCUIT(circ),
  436. RELAY_COMMAND_RESOLVED, buf, buflen,
  437. conn->cpath_layer);
  438. }
  439. /** Send a response to the RESOLVE request of a connection for an in-addr.arpa
  440. * address on connection <b>conn</b> which yielded the result <b>hostname</b>.
  441. * The answer type will be RESOLVED_HOSTNAME.
  442. *
  443. * If <b>circ</b> is provided, and we have a cached answer, send the
  444. * answer back along circ; otherwise, send the answer back along
  445. * <b>conn</b>'s attached circuit.
  446. */
  447. static void
  448. send_resolved_hostname_cell(edge_connection_t *conn, or_circuit_t *circ,
  449. const char *hostname)
  450. {
  451. char buf[RELAY_PAYLOAD_SIZE];
  452. size_t buflen;
  453. uint32_t ttl;
  454. size_t namelen = strlen(hostname);
  455. tor_assert(hostname);
  456. tor_assert(namelen < 256);
  457. ttl = dns_clip_ttl(conn->address_ttl);
  458. buf[0] = RESOLVED_TYPE_HOSTNAME;
  459. buf[1] = (uint8_t)namelen;
  460. memcpy(buf+2, hostname, namelen);
  461. set_uint32(buf+2+namelen, htonl(ttl));
  462. buflen = 2+namelen+4;
  463. if (!circ) {
  464. circuit_t *tmp = circuit_get_by_edge_conn(conn);
  465. if (! CIRCUIT_IS_ORIGIN(tmp))
  466. circ = TO_OR_CIRCUIT(tmp);
  467. }
  468. // log_notice(LD_EXIT, "Sending a reply RESOLVED reply: %s", hostname);
  469. connection_edge_send_command(conn, TO_CIRCUIT(circ),
  470. RELAY_COMMAND_RESOLVED, buf, buflen,
  471. conn->cpath_layer);
  472. // log_notice(LD_EXIT, "Sent");
  473. }
  474. /** Given a lower-case <b>address</b>, check to see whether it's a
  475. * 1.2.3.4.in-addr.arpa address used for reverse lookups. If so,
  476. * parse it and place the address in <b>in</b> if present. Return 1 on success;
  477. * 0 if the address is not in in-addr.arpa format, and -1 if the address is
  478. * malformed. */
  479. static int
  480. parse_inaddr_arpa_address(const char *address, struct in_addr *in)
  481. {
  482. char buf[INET_NTOA_BUF_LEN];
  483. char *cp;
  484. size_t len;
  485. struct in_addr inaddr;
  486. cp = strstr(address, ".in-addr.arpa");
  487. if (!cp || *(cp+strlen(".in-addr.arpa")))
  488. return 0; /* not an .in-addr.arpa address */
  489. len = cp - address;
  490. if (len >= INET_NTOA_BUF_LEN)
  491. return -1; /* Too long. */
  492. memcpy(buf, address, len);
  493. buf[len] = '\0';
  494. if (tor_inet_aton(buf, &inaddr) == 0)
  495. return -1; /* malformed. */
  496. if (in) {
  497. uint32_t a;
  498. /* reverse the bytes */
  499. a = ( ((inaddr.s_addr & 0x000000fful) << 24)
  500. |((inaddr.s_addr & 0x0000ff00ul) << 8)
  501. |((inaddr.s_addr & 0x00ff0000ul) >> 8)
  502. |((inaddr.s_addr & 0xff000000ul) >> 24));
  503. inaddr.s_addr = a;
  504. memcpy(in, &inaddr, sizeof(inaddr));
  505. }
  506. return 1;
  507. }
  508. /** See if we have a cache entry for <b>exitconn</b>-\>address. if so,
  509. * if resolve valid, put it into <b>exitconn</b>-\>addr and return 1.
  510. * If resolve failed, unlink exitconn if needed, free it, and return -1.
  511. *
  512. * If <b>oncirc</b> is provided, and this is a resolve request, we have
  513. * a cached answer, send the answer back along oncirc; otherwise, send
  514. * the answer back along <b>exitconn</b>'s attached circuit.
  515. *
  516. * Else, if seen before and pending, add conn to the pending list,
  517. * and return 0.
  518. *
  519. * Else, if not seen before, add conn to pending list, hand to
  520. * dns farm, and return 0.
  521. */
  522. int
  523. dns_resolve(edge_connection_t *exitconn, or_circuit_t *oncirc)
  524. {
  525. cached_resolve_t *resolve;
  526. cached_resolve_t search;
  527. pending_connection_t *pending_connection;
  528. circuit_t *circ;
  529. struct in_addr in;
  530. time_t now = time(NULL);
  531. int is_reverse = 0, is_resolve, r;
  532. assert_connection_ok(TO_CONN(exitconn), 0);
  533. tor_assert(exitconn->_base.s == -1);
  534. assert_cache_ok();
  535. is_resolve = exitconn->_base.purpose == EXIT_PURPOSE_RESOLVE;
  536. /* first check if exitconn->_base.address is an IP. If so, we already
  537. * know the answer. */
  538. if (tor_inet_aton(exitconn->_base.address, &in) != 0) {
  539. exitconn->_base.addr = ntohl(in.s_addr);
  540. exitconn->address_ttl = DEFAULT_DNS_TTL;
  541. if (is_resolve)
  542. send_resolved_cell(exitconn, oncirc, RESOLVED_TYPE_IPV4);
  543. return 1;
  544. }
  545. if (address_is_invalid_destination(exitconn->_base.address, 0)) {
  546. log(LOG_PROTOCOL_WARN, LD_EXIT,
  547. "Rejecting invalid destination address %s",
  548. escaped_safe_str(exitconn->_base.address));
  549. if (is_resolve)
  550. send_resolved_cell(exitconn, oncirc, RESOLVED_TYPE_ERROR);
  551. /* XXXX012 send error in connect case? -NM */
  552. circ = circuit_get_by_edge_conn(exitconn);
  553. if (circ)
  554. circuit_detach_stream(circ, exitconn);
  555. if (!exitconn->_base.marked_for_close)
  556. connection_free(TO_CONN(exitconn));
  557. return -1;
  558. }
  559. /* then take this opportunity to see if there are any expired
  560. * resolves in the hash table. */
  561. purge_expired_resolves(now);
  562. /* lower-case exitconn->_base.address, so it's in canonical form */
  563. tor_strlower(exitconn->_base.address);
  564. /* Check whether this is a reverse lookup. If it's malformed, or it's a
  565. * .in-addr.arpa address but this isn't a resolve request, kill the
  566. * connection.
  567. */
  568. if ((r = parse_inaddr_arpa_address(exitconn->_base.address, NULL)) != 0) {
  569. if (r == 1)
  570. is_reverse = 1;
  571. #ifdef USE_EVENTDNS
  572. if (!is_reverse || !is_resolve) {
  573. if (!is_reverse)
  574. log_info(LD_EXIT, "Bad .in-addr.arpa address \"%s\"; sending error.",
  575. escaped_safe_str(exitconn->_base.address));
  576. else if (!is_resolve)
  577. log_info(LD_EXIT,
  578. "Attempt to connect to a .in-addr.arpa address \"%s\"; "
  579. "sending error.",
  580. escaped_safe_str(exitconn->_base.address));
  581. #else
  582. if (1) {
  583. log_info(LD_PROTOCOL, "Dnsworker code does not support in-addr.arpa "
  584. "domain, but received a request for \"%s\"; sending error.",
  585. escaped_safe_str(exitconn->_base.address));
  586. #endif
  587. if (exitconn->_base.purpose == EXIT_PURPOSE_RESOLVE)
  588. send_resolved_cell(exitconn, oncirc, RESOLVED_TYPE_ERROR);
  589. circ = circuit_get_by_edge_conn(exitconn);
  590. if (circ)
  591. circuit_detach_stream(circ, exitconn);
  592. if (!exitconn->_base.marked_for_close)
  593. connection_free(TO_CONN(exitconn));
  594. return -1;
  595. }
  596. //log_notice(LD_EXIT, "Looks like an address %s",
  597. //exitconn->_base.address);
  598. }
  599. /* now check the hash table to see if 'address' is already there. */
  600. strlcpy(search.address, exitconn->_base.address, sizeof(search.address));
  601. resolve = HT_FIND(cache_map, &cache_root, &search);
  602. if (resolve && resolve->expire > now) { /* already there */
  603. switch (resolve->state) {
  604. case CACHE_STATE_PENDING:
  605. /* add us to the pending list */
  606. pending_connection = tor_malloc_zero(
  607. sizeof(pending_connection_t));
  608. pending_connection->conn = exitconn;
  609. pending_connection->next = resolve->pending_connections;
  610. resolve->pending_connections = pending_connection;
  611. log_debug(LD_EXIT,"Connection (fd %d) waiting for pending DNS "
  612. "resolve of %s", exitconn->_base.s,
  613. escaped_safe_str(exitconn->_base.address));
  614. exitconn->_base.state = EXIT_CONN_STATE_RESOLVING;
  615. return 0;
  616. case CACHE_STATE_CACHED_VALID:
  617. log_debug(LD_EXIT,"Connection (fd %d) found cached answer for %s",
  618. exitconn->_base.s,
  619. escaped_safe_str(resolve->address));
  620. exitconn->address_ttl = resolve->ttl;
  621. if (resolve->is_reverse) {
  622. tor_assert(is_resolve);
  623. send_resolved_hostname_cell(exitconn, oncirc,
  624. resolve->result.hostname);
  625. } else {
  626. exitconn->_base.addr = resolve->result.addr;
  627. if (is_resolve)
  628. send_resolved_cell(exitconn, oncirc, RESOLVED_TYPE_IPV4);
  629. }
  630. return 1;
  631. case CACHE_STATE_CACHED_FAILED:
  632. log_debug(LD_EXIT,"Connection (fd %d) found cached error for %s",
  633. exitconn->_base.s,
  634. escaped_safe_str(exitconn->_base.address));
  635. /* XXXX012 send back indication of failure for connect case? -NM*/
  636. if (is_resolve)
  637. send_resolved_cell(exitconn, oncirc, RESOLVED_TYPE_ERROR);
  638. circ = circuit_get_by_edge_conn(exitconn);
  639. if (circ)
  640. circuit_detach_stream(circ, exitconn);
  641. if (!exitconn->_base.marked_for_close)
  642. connection_free(TO_CONN(exitconn));
  643. return -1;
  644. case CACHE_STATE_DONE:
  645. log_err(LD_BUG, "Found a 'DONE' dns resolve still in the cache.");
  646. tor_fragile_assert();
  647. }
  648. tor_assert(0);
  649. }
  650. /* not there, need to add it */
  651. resolve = tor_malloc_zero(sizeof(cached_resolve_t));
  652. resolve->magic = CACHED_RESOLVE_MAGIC;
  653. resolve->state = CACHE_STATE_PENDING;
  654. resolve->is_reverse = is_reverse;
  655. strlcpy(resolve->address, exitconn->_base.address, sizeof(resolve->address));
  656. /* add this connection to the pending list */
  657. pending_connection = tor_malloc_zero(sizeof(pending_connection_t));
  658. pending_connection->conn = exitconn;
  659. resolve->pending_connections = pending_connection;
  660. exitconn->_base.state = EXIT_CONN_STATE_RESOLVING;
  661. /* Add this resolve to the cache and priority queue. */
  662. HT_INSERT(cache_map, &cache_root, resolve);
  663. set_expiry(resolve, now + RESOLVE_MAX_TIMEOUT);
  664. log_debug(LD_EXIT,"Launching %s.",
  665. escaped_safe_str(exitconn->_base.address));
  666. assert_cache_ok();
  667. return launch_resolve(exitconn, oncirc);
  668. }
  669. /** Log an error and abort if conn is waiting for a DNS resolve.
  670. */
  671. void
  672. assert_connection_edge_not_dns_pending(edge_connection_t *conn)
  673. {
  674. pending_connection_t *pend;
  675. cached_resolve_t **resolve;
  676. HT_FOREACH(resolve, cache_map, &cache_root) {
  677. for (pend = (*resolve)->pending_connections;
  678. pend;
  679. pend = pend->next) {
  680. tor_assert(pend->conn != conn);
  681. }
  682. }
  683. }
  684. /** Log an error and abort if any connection waiting for a DNS resolve is
  685. * corrupted. */
  686. void
  687. assert_all_pending_dns_resolves_ok(void)
  688. {
  689. pending_connection_t *pend;
  690. cached_resolve_t **resolve;
  691. HT_FOREACH(resolve, cache_map, &cache_root) {
  692. for (pend = (*resolve)->pending_connections;
  693. pend;
  694. pend = pend->next) {
  695. assert_connection_ok(TO_CONN(pend->conn), 0);
  696. tor_assert(pend->conn->_base.s == -1);
  697. tor_assert(!connection_in_array(TO_CONN(pend->conn)));
  698. }
  699. }
  700. }
  701. /** Remove <b>conn</b> from the list of connections waiting for conn-\>address.
  702. */
  703. void
  704. connection_dns_remove(edge_connection_t *conn)
  705. {
  706. pending_connection_t *pend, *victim;
  707. cached_resolve_t search;
  708. cached_resolve_t *resolve;
  709. tor_assert(conn->_base.type == CONN_TYPE_EXIT);
  710. tor_assert(conn->_base.state == EXIT_CONN_STATE_RESOLVING);
  711. strlcpy(search.address, conn->_base.address, sizeof(search.address));
  712. resolve = HT_FIND(cache_map, &cache_root, &search);
  713. if (!resolve) {
  714. log_notice(LD_BUG, "Address %s is not pending. Dropping.",
  715. escaped_safe_str(conn->_base.address));
  716. return;
  717. }
  718. tor_assert(resolve->pending_connections);
  719. assert_connection_ok(TO_CONN(conn),0);
  720. pend = resolve->pending_connections;
  721. if (pend->conn == conn) {
  722. resolve->pending_connections = pend->next;
  723. tor_free(pend);
  724. log_debug(LD_EXIT, "First connection (fd %d) no longer waiting "
  725. "for resolve of %s",
  726. conn->_base.s, escaped_safe_str(conn->_base.address));
  727. return;
  728. } else {
  729. for ( ; pend->next; pend = pend->next) {
  730. if (pend->next->conn == conn) {
  731. victim = pend->next;
  732. pend->next = victim->next;
  733. tor_free(victim);
  734. log_debug(LD_EXIT,
  735. "Connection (fd %d) no longer waiting for resolve of %s",
  736. conn->_base.s, escaped_safe_str(conn->_base.address));
  737. return; /* more are pending */
  738. }
  739. }
  740. tor_assert(0); /* not reachable unless onlyconn not in pending list */
  741. }
  742. }
  743. /** Mark all connections waiting for <b>address</b> for close. Then cancel
  744. * the resolve for <b>address</b> itself, and remove any cached results for
  745. * <b>address</b> from the cache.
  746. */
  747. void
  748. dns_cancel_pending_resolve(const char *address)
  749. {
  750. pending_connection_t *pend;
  751. cached_resolve_t search;
  752. cached_resolve_t *resolve, *tmp;
  753. edge_connection_t *pendconn;
  754. circuit_t *circ;
  755. strlcpy(search.address, address, sizeof(search.address));
  756. resolve = HT_FIND(cache_map, &cache_root, &search);
  757. if (!resolve || resolve->state != CACHE_STATE_PENDING) {
  758. log_notice(LD_BUG,"Address %s is not pending. Dropping.",
  759. escaped_safe_str(address));
  760. return;
  761. }
  762. if (!resolve->pending_connections) {
  763. /* XXX this should never trigger, but sometimes it does */
  764. log_warn(LD_BUG,
  765. "Bug: Address %s is pending but has no pending connections!",
  766. escaped_safe_str(address));
  767. tor_fragile_assert();
  768. return;
  769. }
  770. tor_assert(resolve->pending_connections);
  771. /* mark all pending connections to fail */
  772. log_debug(LD_EXIT,
  773. "Failing all connections waiting on DNS resolve of %s",
  774. escaped_safe_str(address));
  775. while (resolve->pending_connections) {
  776. pend = resolve->pending_connections;
  777. pend->conn->_base.state = EXIT_CONN_STATE_RESOLVEFAILED;
  778. pendconn = pend->conn;
  779. assert_connection_ok(TO_CONN(pendconn), 0);
  780. tor_assert(pendconn->_base.s == -1);
  781. if (!pendconn->_base.marked_for_close) {
  782. connection_edge_end(pendconn, END_STREAM_REASON_RESOURCELIMIT,
  783. pendconn->cpath_layer);
  784. }
  785. circ = circuit_get_by_edge_conn(pendconn);
  786. if (circ)
  787. circuit_detach_stream(circ, pendconn);
  788. connection_free(TO_CONN(pendconn));
  789. resolve->pending_connections = pend->next;
  790. tor_free(pend);
  791. }
  792. tmp = HT_REMOVE(cache_map, &cache_root, resolve);
  793. if (tmp != resolve) {
  794. log_err(LD_BUG, "The cancelled resolve we purged didn't match any in"
  795. " the cache. Tried to purge %s (%p); instead got %s (%p).",
  796. resolve->address, (void*)resolve,
  797. tmp ? tmp->address : "NULL", (void*)tmp);
  798. }
  799. tor_assert(tmp == resolve);
  800. resolve->state = CACHE_STATE_DONE;
  801. }
  802. /** Helper: adds an entry to the DNS cache mapping <b>address</b> to the ipv4
  803. * address <b>addr</b> (if is_reverse is 0) or the hostname <b>hostname</b> (if
  804. * is_reverse is 1). <b>ttl</b> is a cache ttl; <b>outcome</b> is one of
  805. * DNS_RESOLVE_{FAILED_TRANSIENT|FAILED_PERMANENT|SUCCEEDED}.
  806. **/
  807. static void
  808. add_answer_to_cache(const char *address, int is_reverse, uint32_t addr,
  809. const char *hostname, char outcome, uint32_t ttl)
  810. {
  811. cached_resolve_t *resolve;
  812. if (outcome == DNS_RESOLVE_FAILED_TRANSIENT)
  813. return;
  814. //log_notice(LD_EXIT, "Adding to cache: %s -> %s (%lx, %s), %d",
  815. // address, is_reverse?"(reverse)":"", (unsigned long)addr,
  816. // hostname?hostname:"NULL",(int)outcome);
  817. resolve = tor_malloc_zero(sizeof(cached_resolve_t));
  818. resolve->magic = CACHED_RESOLVE_MAGIC;
  819. resolve->state = (outcome == DNS_RESOLVE_SUCCEEDED) ?
  820. CACHE_STATE_CACHED_VALID : CACHE_STATE_CACHED_FAILED;
  821. strlcpy(resolve->address, address, sizeof(resolve->address));
  822. resolve->is_reverse = is_reverse;
  823. if (is_reverse) {
  824. if (outcome == DNS_RESOLVE_SUCCEEDED) {
  825. tor_assert(hostname);
  826. resolve->result.hostname = tor_strdup(hostname);
  827. } else {
  828. tor_assert(! hostname);
  829. resolve->result.hostname = NULL;
  830. }
  831. } else {
  832. tor_assert(!hostname);
  833. resolve->result.addr = addr;
  834. }
  835. resolve->ttl = ttl;
  836. assert_resolve_ok(resolve);
  837. HT_INSERT(cache_map, &cache_root, resolve);
  838. set_expiry(resolve, time(NULL) + dns_get_expiry_ttl(ttl));
  839. }
  840. /** Return true iff <b>address</b> is one of the addresses we use to verify
  841. * that well-known sites aren't being hijacked by our DNS servers. */
  842. static INLINE int
  843. is_test_address(const char *address)
  844. {
  845. or_options_t *options = get_options();
  846. return options->ServerDNSTestAddresses &&
  847. smartlist_string_isin_case(options->ServerDNSTestAddresses, address);
  848. }
  849. /** Called on the OR side when a DNS worker or the eventdns library tells us
  850. * the outcome of a DNS resolve: tell all pending connections about the result
  851. * of the lookup, and cache the value. (<b>address</b> is a NUL-terminated
  852. * string containing the address to look up; <b>addr</b> is an IPv4 address in
  853. * host order; <b>outcome</b> is one of
  854. * DNS_RESOLVE_{FAILED_TRANSIENT|FAILED_PERMANENT|SUCCEEDED}.
  855. */
  856. static void
  857. dns_found_answer(const char *address, int is_reverse, uint32_t addr,
  858. const char *hostname, char outcome, uint32_t ttl)
  859. {
  860. pending_connection_t *pend;
  861. cached_resolve_t search;
  862. cached_resolve_t *resolve, *removed;
  863. edge_connection_t *pendconn;
  864. circuit_t *circ;
  865. assert_cache_ok();
  866. strlcpy(search.address, address, sizeof(search.address));
  867. resolve = HT_FIND(cache_map, &cache_root, &search);
  868. if (!resolve) {
  869. int is_test_addr = is_test_address(address);
  870. if (!is_test_addr)
  871. log_info(LD_EXIT,"Resolved unasked address %s; caching anyway.",
  872. escaped_safe_str(address));
  873. add_answer_to_cache(address, is_reverse, addr, hostname, outcome, ttl);
  874. return;
  875. }
  876. assert_resolve_ok(resolve);
  877. if (resolve->state != CACHE_STATE_PENDING) {
  878. /* XXXX Maybe update addr? or check addr for consistency? Or let
  879. * VALID replace FAILED? */
  880. int is_test_addr = is_test_address(address);
  881. if (!is_test_addr)
  882. log_notice(LD_EXIT,
  883. "Resolved %s which was already resolved; ignoring",
  884. escaped_safe_str(address));
  885. tor_assert(resolve->pending_connections == NULL);
  886. return;
  887. }
  888. /* Removed this assertion: in fact, we'll sometimes get a double answer
  889. * to the same question. This can happen when we ask one worker to resolve
  890. * X.Y.Z., then we cancel the request, and then we ask another worker to
  891. * resolve X.Y.Z. */
  892. /* tor_assert(resolve->state == CACHE_STATE_PENDING); */
  893. while (resolve->pending_connections) {
  894. pend = resolve->pending_connections;
  895. pendconn = pend->conn; /* don't pass complex things to the
  896. connection_mark_for_close macro */
  897. assert_connection_ok(TO_CONN(pendconn),time(NULL));
  898. pendconn->_base.addr = addr;
  899. pendconn->address_ttl = ttl;
  900. if (outcome != DNS_RESOLVE_SUCCEEDED) {
  901. /* prevent double-remove. */
  902. pendconn->_base.state = EXIT_CONN_STATE_RESOLVEFAILED;
  903. if (pendconn->_base.purpose == EXIT_PURPOSE_CONNECT) {
  904. connection_edge_end(pendconn, END_STREAM_REASON_RESOLVEFAILED,
  905. pendconn->cpath_layer);
  906. /* This detach must happen after we send the end cell. */
  907. circuit_detach_stream(circuit_get_by_edge_conn(pendconn), pendconn);
  908. } else {
  909. send_resolved_cell(pendconn, NULL, RESOLVED_TYPE_ERROR);
  910. /* This detach must happen after we send the resolved cell. */
  911. circuit_detach_stream(circuit_get_by_edge_conn(pendconn), pendconn);
  912. }
  913. connection_free(TO_CONN(pendconn));
  914. } else {
  915. if (pendconn->_base.purpose == EXIT_PURPOSE_CONNECT) {
  916. tor_assert(!is_reverse);
  917. /* prevent double-remove. */
  918. pend->conn->_base.state = EXIT_CONN_STATE_CONNECTING;
  919. circ = circuit_get_by_edge_conn(pend->conn);
  920. tor_assert(circ);
  921. tor_assert(!CIRCUIT_IS_ORIGIN(circ));
  922. /* unlink pend->conn from resolving_streams, */
  923. circuit_detach_stream(circ, pend->conn);
  924. /* and link it to n_streams */
  925. pend->conn->next_stream = TO_OR_CIRCUIT(circ)->n_streams;
  926. pend->conn->on_circuit = circ;
  927. TO_OR_CIRCUIT(circ)->n_streams = pend->conn;
  928. connection_exit_connect(pend->conn);
  929. } else {
  930. /* prevent double-remove. This isn't really an accurate state,
  931. * but it does the right thing. */
  932. pendconn->_base.state = EXIT_CONN_STATE_RESOLVEFAILED;
  933. if (is_reverse)
  934. send_resolved_hostname_cell(pendconn, NULL, hostname);
  935. else
  936. send_resolved_cell(pendconn, NULL, RESOLVED_TYPE_IPV4);
  937. circ = circuit_get_by_edge_conn(pendconn);
  938. tor_assert(circ);
  939. circuit_detach_stream(circ, pendconn);
  940. connection_free(TO_CONN(pendconn));
  941. }
  942. }
  943. resolve->pending_connections = pend->next;
  944. tor_free(pend);
  945. }
  946. resolve->state = CACHE_STATE_DONE;
  947. removed = HT_REMOVE(cache_map, &cache_root, &search);
  948. if (removed != resolve) {
  949. log_err(LD_BUG, "The pending resolve we found wasn't removable from"
  950. " the cache. Tried to purge %s (%p); instead got %s (%p).",
  951. resolve->address, (void*)resolve,
  952. removed ? removed->address : "NULL", (void*)removed);
  953. }
  954. assert_resolve_ok(resolve);
  955. assert_cache_ok();
  956. add_answer_to_cache(address, is_reverse, addr, hostname, outcome, ttl);
  957. assert_cache_ok();
  958. }
  959. #ifndef USE_EVENTDNS
  960. /** Find or spawn a dns worker process to handle resolving
  961. * <b>exitconn</b>-\>address; tell that dns worker to begin resolving.
  962. */
  963. static int
  964. launch_resolve(edge_connection_t *exitconn, or_circuit_t *circ)
  965. {
  966. connection_t *dnsconn;
  967. unsigned char len;
  968. tor_assert(exitconn->_base.state == EXIT_CONN_STATE_RESOLVING);
  969. assert_connection_ok(TO_CONN(exitconn), 0);
  970. tor_assert(exitconn->_base.s == -1);
  971. /* respawn here, to be sure there are enough */
  972. if (spawn_enough_dnsworkers() < 0) {
  973. goto err;
  974. }
  975. dnsconn = connection_get_by_type_state(CONN_TYPE_DNSWORKER,
  976. DNSWORKER_STATE_IDLE);
  977. if (!dnsconn) {
  978. log_warn(LD_EXIT,"no idle dns workers. Failing.");
  979. if (exitconn->_base.purpose == EXIT_PURPOSE_RESOLVE)
  980. send_resolved_cell(exitconn, circ, RESOLVED_TYPE_ERROR_TRANSIENT);
  981. goto err;
  982. }
  983. log_debug(LD_EXIT,
  984. "Connection (fd %d) needs to resolve %s; assigning "
  985. "to DNSWorker (fd %d)", exitconn->_base.s,
  986. escaped_safe_str(exitconn->_base.address), dnsconn->s);
  987. tor_free(dnsconn->address);
  988. dnsconn->address = tor_strdup(exitconn->_base.address);
  989. dnsconn->state = DNSWORKER_STATE_BUSY;
  990. /* touch the lastwritten timestamp, since that's how we check to
  991. * see how long it's been since we asked the question, and sometimes
  992. * we check before the first call to connection_handle_write(). */
  993. dnsconn->timestamp_lastwritten = time(NULL);
  994. num_dnsworkers_busy++;
  995. len = strlen(dnsconn->address);
  996. connection_write_to_buf((char*)&len, 1, dnsconn);
  997. connection_write_to_buf(dnsconn->address, len, dnsconn);
  998. return 0;
  999. err:
  1000. /* also sends end and frees */
  1001. dns_cancel_pending_resolve(exitconn->_base.address);
  1002. return -1;
  1003. }
  1004. /******************************************************************/
  1005. /*
  1006. * Connection between OR and dnsworker
  1007. */
  1008. /** Write handler: called when we've pushed a request to a dnsworker. */
  1009. int
  1010. connection_dns_finished_flushing(connection_t *conn)
  1011. {
  1012. tor_assert(conn);
  1013. tor_assert(conn->type == CONN_TYPE_DNSWORKER);
  1014. connection_stop_writing(conn);
  1015. return 0;
  1016. }
  1017. /** Called when a connection to a dnsworker hits an EOF; this only happens
  1018. * when a dnsworker dies unexpectedly. */
  1019. int
  1020. connection_dns_reached_eof(connection_t *conn)
  1021. {
  1022. log_warn(LD_EXIT,"Read eof. DNS worker died unexpectedly.");
  1023. if (conn->state == DNSWORKER_STATE_BUSY) {
  1024. /* don't cancel the resolve here -- it would be cancelled in
  1025. * connection_about_to_close_connection(), since conn is still
  1026. * in state BUSY
  1027. */
  1028. num_dnsworkers_busy--;
  1029. }
  1030. num_dnsworkers--;
  1031. connection_mark_for_close(conn);
  1032. return 0;
  1033. }
  1034. /** Read handler: called when we get data from a dnsworker. See
  1035. * if we have a complete answer. If so, call dns_found_answer on the
  1036. * result. If not, wait. Returns 0. */
  1037. int
  1038. connection_dns_process_inbuf(connection_t *conn)
  1039. {
  1040. char success;
  1041. uint32_t addr;
  1042. int ttl;
  1043. tor_assert(conn);
  1044. tor_assert(conn->type == CONN_TYPE_DNSWORKER);
  1045. if (conn->state != DNSWORKER_STATE_BUSY && buf_datalen(conn->inbuf)) {
  1046. log_warn(LD_BUG,
  1047. "Bug: read data (%d bytes) from an idle dns worker (fd %d, "
  1048. "address %s). Please report.", (int)buf_datalen(conn->inbuf),
  1049. conn->s, escaped_safe_str(conn->address));
  1050. tor_fragile_assert();
  1051. /* Pull it off the buffer anyway, or it will just stay there.
  1052. * Keep pulling things off because sometimes we get several
  1053. * answers at once (!). */
  1054. while (buf_datalen(conn->inbuf)) {
  1055. connection_fetch_from_buf(&success,1,conn);
  1056. connection_fetch_from_buf((char *)&addr,sizeof(uint32_t),conn);
  1057. log_warn(LD_EXIT,"Discarding idle dns answer (success %d, addr %d.)",
  1058. success, addr);
  1059. }
  1060. return 0;
  1061. }
  1062. if (buf_datalen(conn->inbuf) < 5) /* entire answer available? */
  1063. return 0; /* not yet */
  1064. tor_assert(conn->state == DNSWORKER_STATE_BUSY);
  1065. tor_assert(buf_datalen(conn->inbuf) == 5);
  1066. connection_fetch_from_buf(&success,1,conn);
  1067. connection_fetch_from_buf((char *)&addr,sizeof(uint32_t),conn);
  1068. log_debug(LD_EXIT, "DNSWorker (fd %d) returned answer for %s",
  1069. conn->s, escaped_safe_str(conn->address));
  1070. tor_assert(success >= DNS_RESOLVE_FAILED_TRANSIENT);
  1071. tor_assert(success <= DNS_RESOLVE_SUCCEEDED);
  1072. ttl = (success == DNS_RESOLVE_FAILED_TRANSIENT) ? 0 : MAX_DNS_ENTRY_AGE;
  1073. dns_found_answer(conn->address, 0, ntohl(addr), NULL, success, ttl);
  1074. tor_free(conn->address);
  1075. conn->address = tor_strdup("<idle>");
  1076. conn->state = DNSWORKER_STATE_IDLE;
  1077. num_dnsworkers_busy--;
  1078. if (conn->timestamp_created < last_rotation_time) {
  1079. connection_mark_for_close(conn);
  1080. num_dnsworkers--;
  1081. spawn_enough_dnsworkers();
  1082. }
  1083. return 0;
  1084. }
  1085. /** Close and re-open all idle dnsworkers; schedule busy ones to be closed
  1086. * and re-opened once they're no longer busy.
  1087. **/
  1088. static void
  1089. dnsworkers_rotate(void)
  1090. {
  1091. connection_t *dnsconn;
  1092. while ((dnsconn = connection_get_by_type_state(CONN_TYPE_DNSWORKER,
  1093. DNSWORKER_STATE_IDLE))) {
  1094. connection_mark_for_close(dnsconn);
  1095. num_dnsworkers--;
  1096. }
  1097. last_rotation_time = time(NULL);
  1098. if (server_mode(get_options()))
  1099. spawn_enough_dnsworkers();
  1100. }
  1101. /** Implementation for DNS workers; this code runs in a separate
  1102. * execution context. It takes as its argument an fdarray as returned
  1103. * by socketpair(), and communicates via fdarray[1]. The protocol is
  1104. * as follows:
  1105. * - The OR says:
  1106. * - ADDRESSLEN [1 byte]
  1107. * - ADDRESS [ADDRESSLEN bytes]
  1108. * - The DNS worker does the lookup, and replies:
  1109. * - OUTCOME [1 byte]
  1110. * - IP [4 bytes]
  1111. *
  1112. * OUTCOME is one of DNS_RESOLVE_{FAILED_TRANSIENT|FAILED_PERMANENT|SUCCEEDED}.
  1113. * IP is in host order.
  1114. *
  1115. * The dnsworker runs indefinitely, until its connection is closed or an error
  1116. * occurs.
  1117. */
  1118. static void
  1119. dnsworker_main(void *data)
  1120. {
  1121. char address[MAX_ADDRESSLEN+1]; /* Plus a byte for a final '.' */
  1122. unsigned char address_len;
  1123. char *log_address;
  1124. char answer[5];
  1125. uint32_t ip;
  1126. int *fdarray = data;
  1127. int fd;
  1128. int result;
  1129. int search = get_options()->ServerDNSSearchDomains;
  1130. /* log_fn(LOG_NOTICE,"After spawn: fdarray @%d has %d:%d", (int)fdarray,
  1131. * fdarray[0],fdarray[1]); */
  1132. fd = fdarray[1]; /* this side is ours */
  1133. #ifndef TOR_IS_MULTITHREADED
  1134. tor_close_socket(fdarray[0]); /* this is the side of the socketpair the
  1135. * parent uses */
  1136. tor_free_all(1); /* so the child doesn't hold the parent's fd's open */
  1137. handle_signals(0); /* ignore interrupts from the keyboard, etc */
  1138. #endif
  1139. tor_free(data);
  1140. for (;;) {
  1141. int r;
  1142. if ((r = recv(fd, &address_len, 1, 0)) != 1) {
  1143. if (r == 0) {
  1144. log_info(LD_EXIT,"DNS worker exiting because Tor process closed "
  1145. "connection (either pruned idle dnsworker or died).");
  1146. } else {
  1147. log_info(LD_EXIT,"DNS worker exiting because of error on connection "
  1148. "to Tor process.");
  1149. log_info(LD_EXIT,"(Error on %d was %s)", fd,
  1150. tor_socket_strerror(tor_socket_errno(fd)));
  1151. }
  1152. tor_close_socket(fd);
  1153. crypto_thread_cleanup();
  1154. spawn_exit();
  1155. }
  1156. if (address_len && read_all(fd, address, address_len, 1) != address_len) {
  1157. log_err(LD_BUG,"read hostname failed. Child exiting.");
  1158. tor_close_socket(fd);
  1159. crypto_thread_cleanup();
  1160. spawn_exit();
  1161. }
  1162. /* Add a period to prevent local domain search, and NUL-terminate. */
  1163. if (address[address_len-1] != '.' && !search) {
  1164. address[address_len] = '.';
  1165. address[address_len+1] = '\0';
  1166. } else {
  1167. address[address_len] = '\0';
  1168. }
  1169. log_address = esc_for_log(safe_str(address));
  1170. result = tor_lookup_hostname(address, &ip);
  1171. /* Make 0.0.0.0 an error, so that we can use "0" to mean "no addr") */
  1172. if (!ip)
  1173. result = -1;
  1174. switch (result) {
  1175. case 1:
  1176. /* XXX result can never be 1, because we set it to -1 above on error */
  1177. log_info(LD_NET,"Could not resolve dest addr %s (transient)",
  1178. log_address);
  1179. answer[0] = DNS_RESOLVE_FAILED_TRANSIENT;
  1180. break;
  1181. case -1:
  1182. log_info(LD_NET,"Could not resolve dest addr %s (permanent)",
  1183. log_address);
  1184. answer[0] = DNS_RESOLVE_FAILED_PERMANENT;
  1185. break;
  1186. case 0:
  1187. log_info(LD_NET,"Resolved address %s", log_address);
  1188. answer[0] = DNS_RESOLVE_SUCCEEDED;
  1189. break;
  1190. }
  1191. tor_free(log_address);
  1192. set_uint32(answer+1, ip);
  1193. if (write_all(fd, answer, 5, 1) != 5) {
  1194. log_err(LD_NET,"writing answer failed. Child exiting.");
  1195. tor_close_socket(fd);
  1196. crypto_thread_cleanup();
  1197. spawn_exit();
  1198. }
  1199. }
  1200. }
  1201. /** Launch a new DNS worker; return 0 on success, -1 on failure.
  1202. */
  1203. static int
  1204. spawn_dnsworker(void)
  1205. {
  1206. int *fdarray;
  1207. int fd;
  1208. connection_t *conn;
  1209. int err;
  1210. fdarray = tor_malloc(sizeof(int)*2);
  1211. if ((err = tor_socketpair(AF_UNIX, SOCK_STREAM, 0, fdarray)) < 0) {
  1212. log_warn(LD_NET, "Couldn't construct socketpair for dns worker: %s",
  1213. tor_socket_strerror(-err));
  1214. tor_free(fdarray);
  1215. return -1;
  1216. }
  1217. tor_assert(fdarray[0] >= 0);
  1218. tor_assert(fdarray[1] >= 0);
  1219. /* log_fn(LOG_NOTICE,"Before spawn: fdarray @%d has %d:%d",
  1220. (int)fdarray, fdarray[0],fdarray[1]); */
  1221. fd = fdarray[0]; /* We copy this out here, since dnsworker_main may free
  1222. * fdarray */
  1223. spawn_func((void*) dnsworker_main, (void*)fdarray);
  1224. log_debug(LD_EXIT,"just spawned a dns worker.");
  1225. #ifndef TOR_IS_MULTITHREADED
  1226. tor_close_socket(fdarray[1]); /* don't need the worker's side of the pipe */
  1227. tor_free(fdarray);
  1228. #endif
  1229. conn = connection_new(CONN_TYPE_DNSWORKER);
  1230. set_socket_nonblocking(fd);
  1231. /* set up conn so it's got all the data we need to remember */
  1232. conn->s = fd;
  1233. conn->address = tor_strdup("<unused>");
  1234. if (connection_add(conn) < 0) { /* no space, forget it */
  1235. log_warn(LD_NET,"connection_add for dnsworker failed. Giving up.");
  1236. connection_free(conn); /* this closes fd */
  1237. return -1;
  1238. }
  1239. conn->state = DNSWORKER_STATE_IDLE;
  1240. connection_start_reading(conn);
  1241. return 0; /* success */
  1242. }
  1243. /** If we have too many or too few DNS workers, spawn or kill some.
  1244. * Return 0 if we are happy, return -1 if we tried to spawn more but
  1245. * we couldn't.
  1246. */
  1247. static int
  1248. spawn_enough_dnsworkers(void)
  1249. {
  1250. int num_dnsworkers_needed; /* aim to have 1 more than needed,
  1251. * but no less than min and no more than max */
  1252. connection_t *dnsconn;
  1253. /* XXX This may not be the best strategy. Maybe we should queue pending
  1254. * requests until the old ones finish or time out: otherwise, if the
  1255. * connection requests come fast enough, we never get any DNS done. -NM
  1256. *
  1257. * XXX But if we queue them, then the adversary can pile even more
  1258. * queries onto us, blocking legitimate requests for even longer. Maybe
  1259. * we should compromise and only kill if it's been at it for more than,
  1260. * e.g., 2 seconds. -RD
  1261. */
  1262. if (num_dnsworkers_busy == MAX_DNSWORKERS) {
  1263. /* We always want at least one worker idle.
  1264. * So find the oldest busy worker and kill it.
  1265. */
  1266. dnsconn = connection_get_by_type_state_lastwritten(CONN_TYPE_DNSWORKER,
  1267. DNSWORKER_STATE_BUSY);
  1268. tor_assert(dnsconn);
  1269. log_warn(LD_EXIT, "%d DNS workers are spawned; all are busy. Killing one.",
  1270. MAX_DNSWORKERS);
  1271. connection_mark_for_close(dnsconn);
  1272. num_dnsworkers_busy--;
  1273. num_dnsworkers--;
  1274. }
  1275. if (num_dnsworkers_busy >= MIN_DNSWORKERS)
  1276. num_dnsworkers_needed = num_dnsworkers_busy+1;
  1277. else
  1278. num_dnsworkers_needed = MIN_DNSWORKERS;
  1279. while (num_dnsworkers < num_dnsworkers_needed) {
  1280. if (spawn_dnsworker() < 0) {
  1281. log_warn(LD_EXIT,"DNS worker spawn failed. Will try again later.");
  1282. return -1;
  1283. }
  1284. num_dnsworkers++;
  1285. }
  1286. while (num_dnsworkers > num_dnsworkers_busy+MAX_IDLE_DNSWORKERS) {
  1287. /* too many idle? */
  1288. /* cull excess workers */
  1289. log_info(LD_EXIT,"%d of %d dnsworkers are idle. Killing one.",
  1290. num_dnsworkers-num_dnsworkers_busy, num_dnsworkers);
  1291. dnsconn = connection_get_by_type_state(CONN_TYPE_DNSWORKER,
  1292. DNSWORKER_STATE_IDLE);
  1293. tor_assert(dnsconn);
  1294. connection_mark_for_close(dnsconn);
  1295. num_dnsworkers--;
  1296. }
  1297. return 0;
  1298. }
  1299. void
  1300. dns_launch_correctness_checks(void)
  1301. {
  1302. }
  1303. int
  1304. dns_seems_to_be_broken(void)
  1305. {
  1306. return 0;
  1307. }
  1308. void
  1309. dns_reset_correctness_checks(void)
  1310. {
  1311. }
  1312. #else /* !USE_EVENTDNS */
  1313. /** Eventdns helper: return true iff the eventdns result <b>err</b> is
  1314. * a transient failure. */
  1315. static int
  1316. evdns_err_is_transient(int err)
  1317. {
  1318. switch (err)
  1319. {
  1320. case DNS_ERR_SERVERFAILED:
  1321. case DNS_ERR_TRUNCATED:
  1322. case DNS_ERR_TIMEOUT:
  1323. return 1;
  1324. default:
  1325. return 0;
  1326. }
  1327. }
  1328. /* Dummy function; never called with eventdns enabled. */
  1329. int
  1330. connection_dns_finished_flushing(connection_t *conn)
  1331. {
  1332. (void)conn;
  1333. tor_assert(0);
  1334. return 0;
  1335. }
  1336. /* Dummy function; never called with eventdns enabled. */
  1337. int
  1338. connection_dns_process_inbuf(connection_t *conn)
  1339. {
  1340. (void)conn;
  1341. tor_assert(0);
  1342. return 0;
  1343. }
  1344. /* Dummy function; never called with eventdns enabled. */
  1345. int
  1346. connection_dns_reached_eof(connection_t *conn)
  1347. {
  1348. (void)conn;
  1349. tor_assert(0);
  1350. return 0;
  1351. }
  1352. /** Configure eventdns nameservers if force is true, or if the configuration
  1353. * has changed since the last time we called this function. On Unix, this
  1354. * reads from options->ServerDNSResolvConfFile or /etc/resolv.conf; on
  1355. * Windows, this reads from options->ServerDNSResolvConfFile or the registry.
  1356. * Return 0 on success or -1 on failure. */
  1357. static int
  1358. configure_nameservers(int force)
  1359. {
  1360. or_options_t *options;
  1361. const char *conf_fname;
  1362. struct stat st;
  1363. options = get_options();
  1364. conf_fname = options->ServerDNSResolvConfFile;
  1365. #ifndef MS_WINDOWS
  1366. if (!conf_fname)
  1367. conf_fname = "/etc/resolv.conf";
  1368. #endif
  1369. evdns_set_log_fn(evdns_log_cb);
  1370. if (conf_fname) {
  1371. if (stat(conf_fname, &st)) {
  1372. log_warn(LD_EXIT, "Unable to stat resolver configuration in '%s': %s",
  1373. conf_fname, strerror(errno));
  1374. return -1;
  1375. }
  1376. if (!force && resolv_conf_fname && !strcmp(conf_fname,resolv_conf_fname)
  1377. && st.st_mtime == resolv_conf_mtime) {
  1378. log_info(LD_EXIT, "No change to '%s'", conf_fname);
  1379. return 0;
  1380. }
  1381. if (nameservers_configured) {
  1382. evdns_search_clear();
  1383. evdns_clear_nameservers_and_suspend();
  1384. }
  1385. log_info(LD_EXIT, "Parsing resolver configuration in '%s'", conf_fname);
  1386. if (evdns_resolv_conf_parse(DNS_OPTIONS_ALL, conf_fname)) {
  1387. log_warn(LD_EXIT, "Unable to parse '%s', or no nameservers in '%s'",
  1388. conf_fname, conf_fname);
  1389. return -1;
  1390. }
  1391. if (evdns_count_nameservers() == 0) {
  1392. log_warn(LD_EXIT, "Unable to find any nameservers in '%s'.", conf_fname);
  1393. return -1;
  1394. }
  1395. tor_free(resolv_conf_fname);
  1396. resolv_conf_fname = tor_strdup(conf_fname);
  1397. resolv_conf_mtime = st.st_mtime;
  1398. if (nameservers_configured)
  1399. evdns_resume();
  1400. }
  1401. #ifdef MS_WINDOWS
  1402. else {
  1403. if (nameservers_configured) {
  1404. evdns_search_clear();
  1405. evdns_clear_nameservers_and_suspend();
  1406. }
  1407. if (evdns_config_windows_nameservers()) {
  1408. log_warn(LD_EXIT,"Could not config nameservers.");
  1409. return -1;
  1410. }
  1411. if (evdns_count_nameservers() == 0) {
  1412. log_warn(LD_EXIT, "Unable to find any platform nameservers in "
  1413. "your Windows configuration. Perhaps you should list a "
  1414. "ServerDNSResolvConfFile file in your torrc?");
  1415. return -1;
  1416. }
  1417. if (nameservers_configured)
  1418. evdns_resume();
  1419. tor_free(resolv_conf_fname);
  1420. resolv_conf_mtime = 0;
  1421. }
  1422. #endif
  1423. if (evdns_count_nameservers() == 1) {
  1424. evdns_set_option("max-timeouts:", "16", DNS_OPTIONS_ALL);
  1425. evdns_set_option("timeout:", "10", DNS_OPTIONS_ALL);
  1426. } else {
  1427. evdns_set_option("max-timeouts:", "3", DNS_OPTIONS_ALL);
  1428. evdns_set_option("timeout:", "5", DNS_OPTIONS_ALL);
  1429. }
  1430. dns_servers_relaunch_checks();
  1431. nameservers_configured = 1;
  1432. return 0;
  1433. }
  1434. /** For eventdns: Called when we get an answer for a request we launched.
  1435. * See eventdns.h for arguments; 'arg' holds the address we tried to resolve.
  1436. */
  1437. static void
  1438. evdns_callback(int result, char type, int count, int ttl, void *addresses,
  1439. void *arg)
  1440. {
  1441. char *string_address = arg;
  1442. int is_reverse = 0;
  1443. int status = DNS_RESOLVE_FAILED_PERMANENT;
  1444. uint32_t addr = 0;
  1445. const char *hostname = NULL;
  1446. int was_wildcarded = 0;
  1447. if (result == DNS_ERR_NONE) {
  1448. if (type == DNS_IPv4_A && count) {
  1449. char answer_buf[INET_NTOA_BUF_LEN+1];
  1450. struct in_addr in;
  1451. char *escaped_address;
  1452. uint32_t *addrs = addresses;
  1453. in.s_addr = addrs[0];
  1454. addr = ntohl(addrs[0]);
  1455. status = DNS_RESOLVE_SUCCEEDED;
  1456. tor_inet_ntoa(&in, answer_buf, sizeof(answer_buf));
  1457. escaped_address = esc_for_log(string_address);
  1458. if (answer_is_wildcarded(answer_buf)) {
  1459. log_debug(LD_EXIT, "eventdns said that %s resolves to ISP-hijacked "
  1460. "address %s; treating as a failure.",
  1461. safe_str(escaped_address),
  1462. escaped_safe_str(answer_buf));
  1463. was_wildcarded = 1;
  1464. addr = 0;
  1465. status = DNS_RESOLVE_FAILED_PERMANENT;
  1466. } else {
  1467. log_debug(LD_EXIT, "eventdns said that %s resolves to %s",
  1468. safe_str(escaped_address),
  1469. escaped_safe_str(answer_buf));
  1470. }
  1471. tor_free(escaped_address);
  1472. } else if (type == DNS_PTR && count) {
  1473. char *escaped_address;
  1474. is_reverse = 1;
  1475. hostname = ((char**)addresses)[0];
  1476. status = DNS_RESOLVE_SUCCEEDED;
  1477. escaped_address = esc_for_log(string_address);
  1478. log_debug(LD_EXIT, "eventdns said that %s resolves to %s",
  1479. safe_str(escaped_address),
  1480. escaped_safe_str(hostname));
  1481. tor_free(escaped_address);
  1482. } else if (count) {
  1483. log_warn(LD_EXIT, "eventdns returned only non-IPv4 answers for %s.",
  1484. escaped_safe_str(string_address));
  1485. } else {
  1486. log_warn(LD_BUG, "eventdns returned no addresses or error for %s!",
  1487. escaped_safe_str(string_address));
  1488. }
  1489. } else {
  1490. if (evdns_err_is_transient(result))
  1491. status = DNS_RESOLVE_FAILED_TRANSIENT;
  1492. }
  1493. if (was_wildcarded) {
  1494. if (is_test_address(string_address)) {
  1495. /* Ick. We're getting redirected on known-good addresses. Our DNS
  1496. * server must really hate us. */
  1497. add_wildcarded_test_address(string_address);
  1498. }
  1499. }
  1500. if (result != DNS_ERR_SHUTDOWN)
  1501. dns_found_answer(string_address, is_reverse, addr, hostname, status, ttl);
  1502. tor_free(string_address);
  1503. }
  1504. /** For eventdns: start resolving as necessary to find the target for
  1505. * <b>exitconn</b> */
  1506. static int
  1507. launch_resolve(edge_connection_t *exitconn, or_circuit_t *circ)
  1508. {
  1509. char *addr = tor_strdup(exitconn->_base.address);
  1510. struct in_addr in;
  1511. int r;
  1512. int options = get_options()->ServerDNSSearchDomains ? 0
  1513. : DNS_QUERY_NO_SEARCH;
  1514. /* What? Nameservers not configured? Sounds like a bug. */
  1515. if (!nameservers_configured) {
  1516. log_warn(LD_EXIT, "Harmless bug: nameservers not configured, but resolve "
  1517. "launched. Configuring.");
  1518. if (configure_nameservers(1) < 0)
  1519. return -1;
  1520. }
  1521. r = parse_inaddr_arpa_address(exitconn->_base.address, &in);
  1522. if (r == 0) {
  1523. log_info(LD_EXIT, "Launching eventdns request for %s",
  1524. escaped_safe_str(exitconn->_base.address));
  1525. r = evdns_resolve_ipv4(exitconn->_base.address, options,
  1526. evdns_callback, addr);
  1527. } else if (r == 1) {
  1528. log_info(LD_EXIT, "Launching eventdns reverse request for %s",
  1529. escaped_safe_str(exitconn->_base.address));
  1530. r = evdns_resolve_reverse(&in, DNS_QUERY_NO_SEARCH,
  1531. evdns_callback, addr);
  1532. } else if (r == -1) {
  1533. log_warn(LD_BUG, "Somehow a malformed in-addr.arpa address reached here.");
  1534. }
  1535. if (r) {
  1536. log_warn(LD_EXIT, "eventdns rejected address %s: error %d.",
  1537. escaped_safe_str(addr), r);
  1538. if (exitconn->_base.purpose == EXIT_PURPOSE_RESOLVE) {
  1539. if (evdns_err_is_transient(r))
  1540. send_resolved_cell(exitconn, circ, RESOLVED_TYPE_ERROR_TRANSIENT);
  1541. else {
  1542. exitconn->address_ttl = DEFAULT_DNS_TTL;
  1543. send_resolved_cell(exitconn, circ, RESOLVED_TYPE_ERROR);
  1544. }
  1545. }
  1546. dns_cancel_pending_resolve(addr); /* also sends end and frees */
  1547. tor_free(addr);
  1548. }
  1549. return r ? -1 : 0;
  1550. }
  1551. /** How many requests for bogus addresses have we launched so far? */
  1552. static int n_wildcard_requests = 0;
  1553. /** Map from dotted-quad IP address in response to an int holding how many
  1554. * times we've seen it for a randomly generated (hopefully bogus) address. It
  1555. * would be easier to use definitely-invalid addresses (as specified by
  1556. * RFC2606), but see comment in dns_launch_wildcard_checks(). */
  1557. static strmap_t *dns_wildcard_response_count = NULL;
  1558. /** If present, a list of dotted-quad IP addresses that we are pretty sure our
  1559. * nameserver wants to return in response to requests for nonexistent domains.
  1560. */
  1561. static smartlist_t *dns_wildcard_list = NULL;
  1562. /** True iff we've logged about a single address getting wildcarded.
  1563. * Subsequent warnings will be less severe. */
  1564. static int dns_wildcard_one_notice_given = 0;
  1565. /** True iff we've warned that our DNS server is wildcarding too many failures.
  1566. */
  1567. static int dns_wildcard_notice_given = 0;
  1568. /** List of supposedly good addresses that are getting wildcarded to the
  1569. * same addresses as nonexistent addresses. */
  1570. static smartlist_t *dns_wildcarded_test_address_list = NULL;
  1571. /** True iff we've warned about a test address getting wildcarded */
  1572. static int dns_wildcarded_test_address_notice_given = 0;
  1573. /** True iff all addresses seem to be getting wildcarded. */
  1574. static int dns_is_completely_invalid = 0;
  1575. /** Called when we see <b>id</b> (a dotted quad) in response to a request for
  1576. * a hopefully bogus address. */
  1577. static void
  1578. wildcard_increment_answer(const char *id)
  1579. {
  1580. int *ip;
  1581. if (!dns_wildcard_response_count)
  1582. dns_wildcard_response_count = strmap_new();
  1583. ip = strmap_get(dns_wildcard_response_count, id); // may be null (0)
  1584. if (!ip) {
  1585. ip = tor_malloc_zero(sizeof(int));
  1586. strmap_set(dns_wildcard_response_count, id, ip);
  1587. }
  1588. ++*ip;
  1589. if (*ip > 5 && n_wildcard_requests > 10) {
  1590. if (!dns_wildcard_list) dns_wildcard_list = smartlist_create();
  1591. if (!smartlist_string_isin(dns_wildcard_list, id)) {
  1592. log(dns_wildcard_notice_given ? LOG_INFO : LOG_NOTICE, LD_EXIT,
  1593. "Your DNS provider has given \"%s\" as an answer for %d different "
  1594. "invalid addresses. Apparently they are hijacking DNS failures. "
  1595. "I'll try to correct for this by treating future occurrences of "
  1596. "\"%s\" as 'not found'.", id, *ip, id);
  1597. smartlist_add(dns_wildcard_list, tor_strdup(id));
  1598. }
  1599. if (!dns_wildcard_notice_given)
  1600. control_event_server_status(LOG_NOTICE, "DNS_HIJACKED");
  1601. dns_wildcard_notice_given = 1;
  1602. }
  1603. }
  1604. /** Note that a single test address (one believed to be good) seems to be
  1605. * getting redirected to the same IP as failures are. */
  1606. static void
  1607. add_wildcarded_test_address(const char *address)
  1608. {
  1609. int n, n_test_addrs;
  1610. if (!dns_wildcarded_test_address_list)
  1611. dns_wildcarded_test_address_list = smartlist_create();
  1612. if (smartlist_string_isin_case(dns_wildcarded_test_address_list, address))
  1613. return;
  1614. n_test_addrs = get_options()->ServerDNSTestAddresses ?
  1615. smartlist_len(get_options()->ServerDNSTestAddresses) : 0;
  1616. smartlist_add(dns_wildcarded_test_address_list, tor_strdup(address));
  1617. n = smartlist_len(dns_wildcarded_test_address_list);
  1618. if (n > n_test_addrs/2) {
  1619. log(dns_wildcarded_test_address_notice_given ? LOG_INFO : LOG_NOTICE,
  1620. LD_EXIT, "Your DNS provider tried to redirect \"%s\" to a junk "
  1621. "address. It has done this with %d test addresses so far. I'm "
  1622. "going to stop being an exit node for now, since our DNS seems so "
  1623. "broken.", address, n);
  1624. if (!dns_is_completely_invalid) {
  1625. dns_is_completely_invalid = 1;
  1626. mark_my_descriptor_dirty();
  1627. }
  1628. if (!dns_wildcarded_test_address_notice_given)
  1629. control_event_server_status(LOG_WARN, "DNS_USELESS");
  1630. dns_wildcarded_test_address_notice_given = 1;
  1631. }
  1632. }
  1633. /** Callback function when we get an answer (possibly failing) for a request
  1634. * for a (hopefully) nonexistent domain. */
  1635. static void
  1636. evdns_wildcard_check_callback(int result, char type, int count, int ttl,
  1637. void *addresses, void *arg)
  1638. {
  1639. (void)ttl;
  1640. ++n_wildcard_requests;
  1641. if (result == DNS_ERR_NONE && type == DNS_IPv4_A && count) {
  1642. uint32_t *addrs = addresses;
  1643. int i;
  1644. char *string_address = arg;
  1645. for (i = 0; i < count; ++i) {
  1646. char answer_buf[INET_NTOA_BUF_LEN+1];
  1647. struct in_addr in;
  1648. in.s_addr = addrs[i];
  1649. tor_inet_ntoa(&in, answer_buf, sizeof(answer_buf));
  1650. wildcard_increment_answer(answer_buf);
  1651. }
  1652. log(dns_wildcard_one_notice_given ? LOG_INFO : LOG_NOTICE, LD_EXIT,
  1653. "Your DNS provider gave an answer for \"%s\", which "
  1654. "is not supposed to exist. Apparently they are hijacking "
  1655. "DNS failures. Trying to correct for this. We've noticed %d possibly "
  1656. "bad addresses so far.",
  1657. string_address, strmap_size(dns_wildcard_response_count));
  1658. dns_wildcard_one_notice_given = 1;
  1659. }
  1660. tor_free(arg);
  1661. }
  1662. /** Launch a single request for a nonexistent hostname consisting of between
  1663. * <b>min_len</b> and <b>max_len</b> random (plausible) characters followed by
  1664. * <b>suffix</b> */
  1665. static void
  1666. launch_wildcard_check(int min_len, int max_len, const char *suffix)
  1667. {
  1668. char random_bytes[20], name[64], *addr;
  1669. size_t len;
  1670. int r;
  1671. len = min_len + crypto_rand_int(max_len-min_len+1);
  1672. if (crypto_rand(random_bytes, sizeof(random_bytes)) < 0)
  1673. return;
  1674. base32_encode(name, sizeof(name), random_bytes, sizeof(random_bytes));
  1675. name[len] = '\0';
  1676. strlcat(name, suffix, sizeof(name));
  1677. addr = tor_strdup(name);
  1678. r = evdns_resolve_ipv4(name, DNS_QUERY_NO_SEARCH,
  1679. evdns_wildcard_check_callback, addr);
  1680. if (r)
  1681. tor_free(addr);
  1682. }
  1683. /** Launch attempts to resolve a bunch of known-good addresses (configured in
  1684. * ServerDNSTestAddresses). [Callback for a libevent timer] */
  1685. static void
  1686. launch_test_addresses(int fd, short event, void *args)
  1687. {
  1688. or_options_t *options = get_options();
  1689. (void)fd;
  1690. (void)event;
  1691. (void)args;
  1692. log_info(LD_EXIT, "Launching checks to see whether our nameservers like to "
  1693. "hijack *everything*.");
  1694. /* This situation is worse than the failure-hijacking situation. When this
  1695. * happens, we're no good for DNS requests at all, and we shouldn't really
  1696. * be an exit server.*/
  1697. if (!options->ServerDNSTestAddresses)
  1698. return;
  1699. SMARTLIST_FOREACH(options->ServerDNSTestAddresses, const char *, address,
  1700. {
  1701. evdns_resolve_ipv4(address, DNS_QUERY_NO_SEARCH, evdns_callback,
  1702. tor_strdup(address));
  1703. });
  1704. }
  1705. #define N_WILDCARD_CHECKS 2
  1706. /** Launch DNS requests for a few nonexistent hostnames and a few well-known
  1707. * hostnames, and see if we can catch our nameserver trying to hijack them and
  1708. * map them to a stupid "I couldn't find ggoogle.com but maybe you'd like to
  1709. * buy these lovely encyclopedias" page. */
  1710. static void
  1711. dns_launch_wildcard_checks(void)
  1712. {
  1713. int i;
  1714. log_info(LD_EXIT, "Launching checks to see whether our nameservers like "
  1715. "to hijack DNS failures.");
  1716. for (i = 0; i < N_WILDCARD_CHECKS; ++i) {
  1717. /* RFC2606 reserves these. Sadly, some DNS hijackers, in a silly attempt
  1718. * to 'comply' with rfc2606, refrain from giving A records for these.
  1719. * This is the standards-compliance equivalent of making sure that your
  1720. * crackhouse's elevator inspection certificate is up to date.
  1721. */
  1722. launch_wildcard_check(2, 16, ".invalid");
  1723. launch_wildcard_check(2, 16, ".test");
  1724. /* These will break specs if there are ever any number of
  1725. * 8+-character top-level domains. */
  1726. launch_wildcard_check(8, 16, "");
  1727. /* Try some random .com/org/net domains. This will work fine so long as
  1728. * not too many resolve to the same place. */
  1729. launch_wildcard_check(8, 16, ".com");
  1730. launch_wildcard_check(8, 16, ".org");
  1731. launch_wildcard_check(8, 16, ".net");
  1732. }
  1733. }
  1734. /** If appropriate, start testing whether our DNS servers tend to lie to
  1735. * us. */
  1736. void
  1737. dns_launch_correctness_checks(void)
  1738. {
  1739. static struct event launch_event;
  1740. struct timeval timeout;
  1741. if (!get_options()->ServerDNSDetectHijacking)
  1742. return;
  1743. dns_launch_wildcard_checks();
  1744. /* Wait a while before launching requests for test addresses, so we can
  1745. * get the results from checking for wildcarding. */
  1746. evtimer_set(&launch_event, launch_test_addresses, NULL);
  1747. timeout.tv_sec = 30;
  1748. timeout.tv_usec = 0;
  1749. evtimer_add(&launch_event, &timeout);
  1750. }
  1751. /** Return true iff our DNS servers lie to us too much to be trustd. */
  1752. int
  1753. dns_seems_to_be_broken(void)
  1754. {
  1755. return dns_is_completely_invalid;
  1756. }
  1757. /** Forget what we've previously learned about our DNS servers' correctness. */
  1758. void
  1759. dns_reset_correctness_checks(void)
  1760. {
  1761. if (dns_wildcard_response_count) {
  1762. strmap_free(dns_wildcard_response_count, _tor_free);
  1763. dns_wildcard_response_count = NULL;
  1764. }
  1765. n_wildcard_requests = 0;
  1766. if (dns_wildcard_list) {
  1767. SMARTLIST_FOREACH(dns_wildcard_list, char *, cp, tor_free(cp));
  1768. smartlist_clear(dns_wildcard_list);
  1769. }
  1770. if (dns_wildcarded_test_address_list) {
  1771. SMARTLIST_FOREACH(dns_wildcarded_test_address_list, char *, cp,
  1772. tor_free(cp));
  1773. smartlist_clear(dns_wildcarded_test_address_list);
  1774. }
  1775. dns_wildcard_one_notice_given = dns_wildcard_notice_given =
  1776. dns_wildcarded_test_address_notice_given = dns_is_completely_invalid = 0;
  1777. }
  1778. /** Return true iff we have noticed that the dotted-quad <b>ip</b> has been
  1779. * returned in response to requests for nonexistent hostnames. */
  1780. static int
  1781. answer_is_wildcarded(const char *ip)
  1782. {
  1783. return dns_wildcard_list && smartlist_string_isin(dns_wildcard_list, ip);
  1784. }
  1785. #endif /* USE_EVENTDNS */
  1786. /** Exit with an assertion if <b>resolve</b> is corrupt. */
  1787. static void
  1788. assert_resolve_ok(cached_resolve_t *resolve)
  1789. {
  1790. tor_assert(resolve);
  1791. tor_assert(resolve->magic == CACHED_RESOLVE_MAGIC);
  1792. tor_assert(strlen(resolve->address) < MAX_ADDRESSLEN);
  1793. tor_assert(tor_strisnonupper(resolve->address));
  1794. if (resolve->state != CACHE_STATE_PENDING) {
  1795. tor_assert(!resolve->pending_connections);
  1796. }
  1797. if (resolve->state == CACHE_STATE_PENDING ||
  1798. resolve->state == CACHE_STATE_DONE) {
  1799. tor_assert(!resolve->ttl);
  1800. if (resolve->is_reverse)
  1801. tor_assert(!resolve->result.hostname);
  1802. else
  1803. tor_assert(!resolve->result.addr);
  1804. }
  1805. }
  1806. #ifdef DEBUG_DNS_CACHE
  1807. /** Exit with an assertion if the DNS cache is corrupt. */
  1808. static void
  1809. _assert_cache_ok(void)
  1810. {
  1811. cached_resolve_t **resolve;
  1812. int bad_rep = _cache_map_HT_REP_IS_BAD(&cache_root);
  1813. if (bad_rep) {
  1814. log_err(LD_BUG, "Bad rep type %d on dns cache hash table", bad_rep);
  1815. tor_assert(!bad_rep);
  1816. }
  1817. HT_FOREACH(resolve, cache_map, &cache_root) {
  1818. assert_resolve_ok(*resolve);
  1819. tor_assert((*resolve)->state != CACHE_STATE_DONE);
  1820. }
  1821. if (!cached_resolve_pqueue)
  1822. return;
  1823. smartlist_pqueue_assert_ok(cached_resolve_pqueue,
  1824. _compare_cached_resolves_by_expiry);
  1825. SMARTLIST_FOREACH(cached_resolve_pqueue, cached_resolve_t *, res,
  1826. {
  1827. if (res->state == CACHE_STATE_DONE) {
  1828. cached_resolve_t *found = HT_FIND(cache_map, &cache_root, res);
  1829. tor_assert(!found || found != res);
  1830. } else {
  1831. cached_resolve_t *found = HT_FIND(cache_map, &cache_root, res);
  1832. tor_assert(found);
  1833. }
  1834. });
  1835. }
  1836. #endif