dns.c 66 KB

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