dns.c 59 KB

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