dns.c 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575
  1. /* Copyright 2003 Roger Dingledine. */
  2. /* See LICENSE for licensing information */
  3. /* $Id$ */
  4. /* See http://elvin.dstc.com/ListArchive/elvin-dev/archive/2001/09/msg00027.html
  5. * for some approaches to asynchronous dns. We will want to switch once one of
  6. * them becomes more commonly available.
  7. */
  8. #include "or.h"
  9. #include "tree.h"
  10. extern or_options_t options; /* command-line and config-file options */
  11. #define MAX_ADDRESSLEN 256
  12. #define MAX_DNSWORKERS 50
  13. #define MIN_DNSWORKERS 3
  14. #define MAX_IDLE_DNSWORKERS 10
  15. #define DNS_RESOLVE_FAILED_TRANSIENT 1
  16. #define DNS_RESOLVE_FAILED_PERMANENT 2
  17. #define DNS_RESOLVE_SUCCEEDED 3
  18. int num_dnsworkers=0;
  19. int num_dnsworkers_busy=0;
  20. struct pending_connection_t {
  21. struct connection_t *conn;
  22. struct pending_connection_t *next;
  23. };
  24. struct cached_resolve {
  25. SPLAY_ENTRY(cached_resolve) node;
  26. char address[MAX_ADDRESSLEN]; /* the hostname to be resolved */
  27. uint32_t addr; /* in host order. I know I'm horrible for assuming ipv4 */
  28. char state; /* 0 is pending; 1 means answer is valid; 2 means resolve failed */
  29. #define CACHE_STATE_PENDING 0
  30. #define CACHE_STATE_VALID 1
  31. #define CACHE_STATE_FAILED 2
  32. uint32_t expire; /* remove untouched items from cache after some time? */
  33. struct pending_connection_t *pending_connections;
  34. struct cached_resolve *next;
  35. };
  36. static void purge_expired_resolves(uint32_t now);
  37. static int assign_to_dnsworker(connection_t *exitconn);
  38. static void dns_purge_resolve(struct cached_resolve *resolve);
  39. static void dns_found_answer(char *address, uint32_t addr, char outcome);
  40. int dnsworker_main(void *data);
  41. static int spawn_dnsworker(void);
  42. static void spawn_enough_dnsworkers(void);
  43. static SPLAY_HEAD(cache_tree, cached_resolve) cache_root;
  44. static int compare_cached_resolves(struct cached_resolve *a,
  45. struct cached_resolve *b) {
  46. /* make this smarter one day? */
  47. return strncasecmp(a->address, b->address, MAX_ADDRESSLEN);
  48. }
  49. SPLAY_PROTOTYPE(cache_tree, cached_resolve, node, compare_cached_resolves);
  50. SPLAY_GENERATE(cache_tree, cached_resolve, node, compare_cached_resolves);
  51. static void init_cache_tree(void) {
  52. SPLAY_INIT(&cache_root);
  53. }
  54. void dns_init(void) {
  55. init_cache_tree();
  56. spawn_enough_dnsworkers();
  57. }
  58. static struct cached_resolve *oldest_cached_resolve = NULL; /* linked list, */
  59. static struct cached_resolve *newest_cached_resolve = NULL; /* oldest to newest */
  60. static void purge_expired_resolves(uint32_t now) {
  61. struct cached_resolve *resolve;
  62. /* this is fast because the linked list
  63. * oldest_cached_resolve is ordered by when they came in.
  64. */
  65. while(oldest_cached_resolve && (oldest_cached_resolve->expire < now)) {
  66. resolve = oldest_cached_resolve;
  67. log(LOG_DEBUG,"Forgetting old cached resolve (expires %lu)", (unsigned long)resolve->expire);
  68. if(resolve->state == CACHE_STATE_PENDING) {
  69. log_fn(LOG_WARN,"Expiring a dns resolve that's still pending. Forgot to cull it?");
  70. /* XXX if resolve->pending_connections is used, then we're probably
  71. * introducing bugs by closing resolve without notifying those streams.
  72. */
  73. }
  74. oldest_cached_resolve = resolve->next;
  75. if(!oldest_cached_resolve) /* if there are no more, */
  76. newest_cached_resolve = NULL; /* then make sure the list's tail knows that too */
  77. SPLAY_REMOVE(cache_tree, &cache_root, resolve);
  78. tor_free(resolve);
  79. }
  80. }
  81. /* See if we have a cache entry for 'exitconn->address'. if so,
  82. * if resolve valid, put it into exitconn->addr and return 1.
  83. * If resolve failed, return -1.
  84. *
  85. * Else, if seen before and pending, add conn to the pending list,
  86. * and return 0.
  87. *
  88. * Else, if not seen before, add conn to pending list, hand to
  89. * dns farm, and return 0.
  90. */
  91. int dns_resolve(connection_t *exitconn) {
  92. struct cached_resolve *resolve;
  93. struct cached_resolve search;
  94. struct pending_connection_t *pending_connection;
  95. struct in_addr in;
  96. uint32_t now = time(NULL);
  97. assert_connection_ok(exitconn, 0);
  98. /* XXX leave disabled for dirservers so we can find the conn-munging bug */
  99. if(!options.DirPort) {
  100. /* first check if exitconn->address is an IP. If so, we already
  101. * know the answer. */
  102. if (tor_inet_aton(exitconn->address, &in) != 0) {
  103. exitconn->addr = ntohl(in.s_addr);
  104. return 1;
  105. }
  106. }
  107. /* then take this opportunity to see if there are any expired
  108. * resolves in the tree. */
  109. purge_expired_resolves(now);
  110. /* now check the tree to see if 'address' is already there. */
  111. strncpy(search.address, exitconn->address, MAX_ADDRESSLEN);
  112. search.address[MAX_ADDRESSLEN-1] = 0;
  113. resolve = SPLAY_FIND(cache_tree, &cache_root, &search);
  114. if(resolve) { /* already there */
  115. switch(resolve->state) {
  116. case CACHE_STATE_PENDING:
  117. /* add us to the pending list */
  118. pending_connection = tor_malloc(sizeof(struct pending_connection_t));
  119. pending_connection->conn = exitconn;
  120. pending_connection->next = resolve->pending_connections;
  121. resolve->pending_connections = pending_connection;
  122. log_fn(LOG_DEBUG,"Connection (fd %d) waiting for pending DNS resolve of '%s'",
  123. exitconn->s, exitconn->address);
  124. return 0;
  125. case CACHE_STATE_VALID:
  126. exitconn->addr = resolve->addr;
  127. log_fn(LOG_DEBUG,"Connection (fd %d) found cached answer for '%s'",
  128. exitconn->s, exitconn->address);
  129. return 1;
  130. case CACHE_STATE_FAILED:
  131. return -1;
  132. }
  133. assert(0);
  134. }
  135. /* not there, need to add it */
  136. resolve = tor_malloc_zero(sizeof(struct cached_resolve));
  137. resolve->state = CACHE_STATE_PENDING;
  138. resolve->expire = now + MAX_DNS_ENTRY_AGE;
  139. strncpy(resolve->address, exitconn->address, MAX_ADDRESSLEN);
  140. resolve->address[MAX_ADDRESSLEN-1] = 0;
  141. /* add us to the pending list */
  142. pending_connection = tor_malloc(sizeof(struct pending_connection_t));
  143. pending_connection->conn = exitconn;
  144. pending_connection->next = NULL;
  145. resolve->pending_connections = pending_connection;
  146. /* add us to the linked list of resolves */
  147. if (!oldest_cached_resolve) {
  148. oldest_cached_resolve = resolve;
  149. } else {
  150. newest_cached_resolve->next = resolve;
  151. }
  152. newest_cached_resolve = resolve;
  153. SPLAY_INSERT(cache_tree, &cache_root, resolve);
  154. return assign_to_dnsworker(exitconn);
  155. }
  156. static int assign_to_dnsworker(connection_t *exitconn) {
  157. connection_t *dnsconn;
  158. unsigned char len;
  159. spawn_enough_dnsworkers(); /* respawn here, to be sure there are enough */
  160. dnsconn = connection_get_by_type_state(CONN_TYPE_DNSWORKER, DNSWORKER_STATE_IDLE);
  161. if(!dnsconn) {
  162. log_fn(LOG_WARN,"no idle dns workers. Failing.");
  163. dns_cancel_pending_resolve(exitconn->address);
  164. return -1;
  165. }
  166. log_fn(LOG_DEBUG, "Connection (fd %d) needs to resolve '%s'; assigning to DNSWorker (fd %d)",
  167. exitconn->s, exitconn->address, dnsconn->s);
  168. tor_free(dnsconn->address);
  169. dnsconn->address = tor_strdup(exitconn->address);
  170. dnsconn->state = DNSWORKER_STATE_BUSY;
  171. num_dnsworkers_busy++;
  172. len = strlen(dnsconn->address);
  173. connection_write_to_buf(&len, 1, dnsconn);
  174. connection_write_to_buf(dnsconn->address, len, dnsconn);
  175. // log_fn(LOG_DEBUG,"submitted '%s'", exitconn->address);
  176. return 0;
  177. }
  178. void connection_dns_remove(connection_t *conn)
  179. {
  180. struct pending_connection_t *pend, *victim;
  181. struct cached_resolve search;
  182. struct cached_resolve *resolve;
  183. strncpy(search.address, conn->address, MAX_ADDRESSLEN);
  184. search.address[MAX_ADDRESSLEN-1] = 0;
  185. resolve = SPLAY_FIND(cache_tree, &cache_root, &search);
  186. if(!resolve) {
  187. log_fn(LOG_WARN,"Address '%s' is not pending. Dropping.", conn->address);
  188. return;
  189. }
  190. assert(resolve->pending_connections);
  191. assert_connection_ok(conn,0);
  192. pend = resolve->pending_connections;
  193. if(pend->conn == conn) {
  194. resolve->pending_connections = pend->next;
  195. tor_free(pend);
  196. log_fn(LOG_DEBUG, "First connection (fd %d) no longer waiting for resolve of '%s'",
  197. conn->s, conn->address);
  198. return;
  199. } else {
  200. for( ; pend->next; pend = pend->next) {
  201. if(pend->next->conn == conn) {
  202. victim = pend->next;
  203. pend->next = victim->next;
  204. tor_free(victim);
  205. log_fn(LOG_DEBUG, "Connection (fd %d) no longer waiting for resolve of '%s'",
  206. conn->s, conn->address);
  207. return; /* more are pending */
  208. }
  209. }
  210. assert(0); /* not reachable unless onlyconn not in pending list */
  211. }
  212. }
  213. void assert_connection_edge_not_dns_pending(connection_t *conn) {
  214. struct pending_connection_t *pend;
  215. struct cached_resolve *resolve;
  216. SPLAY_FOREACH(resolve, cache_tree, &cache_root) {
  217. for(pend = resolve->pending_connections;
  218. pend;
  219. pend = pend->next) {
  220. assert(pend->conn != conn);
  221. }
  222. }
  223. }
  224. /* Cancel all pending connections. Then cancel the resolve itself,
  225. * and remove the 'struct cached_resolve' from the cache.
  226. */
  227. void dns_cancel_pending_resolve(char *address) {
  228. struct pending_connection_t *pend;
  229. struct cached_resolve search;
  230. struct cached_resolve *resolve;
  231. connection_t *pendconn;
  232. strncpy(search.address, address, MAX_ADDRESSLEN);
  233. search.address[MAX_ADDRESSLEN-1] = 0;
  234. resolve = SPLAY_FIND(cache_tree, &cache_root, &search);
  235. if(!resolve) {
  236. log_fn(LOG_WARN,"Address '%s' is not pending. Dropping.", address);
  237. return;
  238. }
  239. assert(resolve->pending_connections);
  240. /* mark all pending connections to fail */
  241. log_fn(LOG_DEBUG, "Failing all connections waiting on DNS resolve of '%s'",
  242. address);
  243. while(resolve->pending_connections) {
  244. pend = resolve->pending_connections;
  245. /* So that mark_for_close doesn't double-remove the connection. */
  246. pend->conn->state = EXIT_CONN_STATE_RESOLVEFAILED;
  247. pendconn = pend->conn; /* don't pass complex things to the
  248. connection_mark_for_close macro */
  249. connection_mark_for_close(pendconn, END_STREAM_REASON_MISC);
  250. resolve->pending_connections = pend->next;
  251. tor_free(pend);
  252. }
  253. dns_purge_resolve(resolve);
  254. }
  255. static void dns_purge_resolve(struct cached_resolve *resolve) {
  256. struct cached_resolve *tmp;
  257. /* remove resolve from the linked list */
  258. if(resolve == oldest_cached_resolve) {
  259. oldest_cached_resolve = resolve->next;
  260. if(oldest_cached_resolve == NULL)
  261. newest_cached_resolve = NULL;
  262. } else {
  263. /* FFFF make it a doubly linked list if this becomes too slow */
  264. for(tmp=oldest_cached_resolve; tmp && tmp->next != resolve; tmp=tmp->next) ;
  265. assert(tmp); /* it's got to be in the list, or we screwed up somewhere else */
  266. tmp->next = resolve->next; /* unlink it */
  267. if(newest_cached_resolve == resolve)
  268. newest_cached_resolve = tmp;
  269. }
  270. /* remove resolve from the tree */
  271. SPLAY_REMOVE(cache_tree, &cache_root, resolve);
  272. tor_free(resolve);
  273. }
  274. static void dns_found_answer(char *address, uint32_t addr, char outcome) {
  275. struct pending_connection_t *pend;
  276. struct cached_resolve search;
  277. struct cached_resolve *resolve;
  278. connection_t *pendconn;
  279. strncpy(search.address, address, MAX_ADDRESSLEN);
  280. search.address[MAX_ADDRESSLEN-1] = 0;
  281. resolve = SPLAY_FIND(cache_tree, &cache_root, &search);
  282. if(!resolve) {
  283. log_fn(LOG_INFO,"Resolved unasked address '%s'? Dropping.", address);
  284. /* XXX Why drop? Just because we don't care now doesn't mean we shouldn't
  285. * XXX cache the result for later. */
  286. return;
  287. }
  288. if (resolve->state != CACHE_STATE_PENDING) {
  289. log_fn(LOG_WARN, "Resolved '%s' which was already resolved; ignoring",
  290. address);
  291. return;
  292. }
  293. /* Removed this assertion: in fact, we'll sometimes get a double answer
  294. * to the same question. This can happen when we ask one worker to resolve
  295. * X.Y.Z., then we cancel the request, and then we ask another worker to
  296. * resolve X.Y.Z. */
  297. /* assert(resolve->state == CACHE_STATE_PENDING); */
  298. resolve->addr = ntohl(addr);
  299. if(outcome == DNS_RESOLVE_SUCCEEDED)
  300. resolve->state = CACHE_STATE_VALID;
  301. else
  302. resolve->state = CACHE_STATE_FAILED;
  303. while(resolve->pending_connections) {
  304. pend = resolve->pending_connections;
  305. assert_connection_ok(pend->conn,time(NULL));
  306. pend->conn->addr = resolve->addr;
  307. if(resolve->state == CACHE_STATE_FAILED) {
  308. /* prevent double-remove */
  309. pend->conn->state = EXIT_CONN_STATE_RESOLVEFAILED;
  310. pendconn = pend->conn; /* don't pass complex things to the
  311. connection_mark_for_close macro */
  312. connection_mark_for_close(pendconn, END_STREAM_REASON_RESOLVEFAILED);
  313. } else {
  314. connection_exit_connect(pend->conn);
  315. }
  316. resolve->pending_connections = pend->next;
  317. tor_free(pend);
  318. }
  319. if(outcome == DNS_RESOLVE_FAILED_TRANSIENT) { /* remove from cache */
  320. dns_purge_resolve(resolve);
  321. }
  322. }
  323. /******************************************************************/
  324. int connection_dns_finished_flushing(connection_t *conn) {
  325. assert(conn && conn->type == CONN_TYPE_DNSWORKER);
  326. connection_stop_writing(conn);
  327. return 0;
  328. }
  329. int connection_dns_process_inbuf(connection_t *conn) {
  330. char success;
  331. uint32_t addr;
  332. assert(conn && conn->type == CONN_TYPE_DNSWORKER);
  333. if(conn->inbuf_reached_eof) {
  334. log_fn(LOG_WARN,"Read eof. Worker died unexpectedly.");
  335. if(conn->state == DNSWORKER_STATE_BUSY) {
  336. dns_cancel_pending_resolve(conn->address);
  337. num_dnsworkers_busy--;
  338. }
  339. num_dnsworkers--;
  340. connection_mark_for_close(conn,0);
  341. return 0;
  342. }
  343. assert(conn->state == DNSWORKER_STATE_BUSY);
  344. if(buf_datalen(conn->inbuf) < 5) /* entire answer available? */
  345. return 0; /* not yet */
  346. assert(buf_datalen(conn->inbuf) == 5);
  347. connection_fetch_from_buf(&success,1,conn);
  348. connection_fetch_from_buf((char *)&addr,sizeof(uint32_t),conn);
  349. log_fn(LOG_DEBUG, "DNSWorker (fd %d) returned answer for '%s'",
  350. conn->s, conn->address);
  351. assert(success >= DNS_RESOLVE_FAILED_TRANSIENT);
  352. assert(success <= DNS_RESOLVE_SUCCEEDED);
  353. dns_found_answer(conn->address, addr, success);
  354. tor_free(conn->address);
  355. conn->address = tor_strdup("<idle>");
  356. conn->state = DNSWORKER_STATE_IDLE;
  357. num_dnsworkers_busy--;
  358. return 0;
  359. }
  360. int dnsworker_main(void *data) {
  361. char address[MAX_ADDRESSLEN];
  362. unsigned char address_len;
  363. char answer[5];
  364. struct hostent *rent;
  365. int *fdarray = data;
  366. int fd;
  367. close(fdarray[0]); /* this is the side of the socketpair the parent uses */
  368. fd = fdarray[1]; /* this side is ours */
  369. #ifndef MS_WINDOWS
  370. connection_free_all(); /* so the child doesn't hold the parent's fd's open */
  371. #endif
  372. for(;;) {
  373. if(recv(fd, &address_len, 1, 0) != 1) {
  374. log_fn(LOG_INFO,"dnsworker exiting because tor process died.");
  375. spawn_exit();
  376. }
  377. assert(address_len > 0);
  378. if(read_all(fd, address, address_len, 1) != address_len) {
  379. log_fn(LOG_ERR,"read hostname failed. Child exiting.");
  380. spawn_exit();
  381. }
  382. address[address_len] = 0; /* null terminate it */
  383. rent = gethostbyname(address);
  384. if (!rent) {
  385. if(h_errno == TRY_AGAIN) { /* transient error -- don't cache it */
  386. log_fn(LOG_INFO,"Could not resolve dest addr %s (transient).",address);
  387. answer[0] = DNS_RESOLVE_FAILED_TRANSIENT;
  388. } else { /* permanent error, can be cached */
  389. log_fn(LOG_INFO,"Could not resolve dest addr %s (permanent).",address);
  390. answer[0] = DNS_RESOLVE_FAILED_PERMANENT;
  391. }
  392. memset(answer+1,0,4);
  393. } else {
  394. assert(rent->h_length == 4); /* break to remind us if we move away from ipv4 */
  395. answer[0] = DNS_RESOLVE_SUCCEEDED;
  396. memcpy(answer+1, rent->h_addr, 4);
  397. log_fn(LOG_INFO,"Resolved address '%s'.",address);
  398. }
  399. if(write_all(fd, answer, 5, 1) != 5) {
  400. log_fn(LOG_ERR,"writing answer failed. Child exiting.");
  401. spawn_exit();
  402. }
  403. }
  404. return 0; /* windows wants this function to return an int */
  405. }
  406. static int spawn_dnsworker(void) {
  407. int fd[2];
  408. connection_t *conn;
  409. if(tor_socketpair(AF_UNIX, SOCK_STREAM, 0, fd) < 0) {
  410. log(LOG_ERR, "Couldn't construct socketpair: %s", strerror(errno));
  411. exit(1);
  412. }
  413. spawn_func(dnsworker_main, (void*)fd);
  414. log_fn(LOG_DEBUG,"just spawned a worker.");
  415. close(fd[1]); /* we don't need the worker's side of the pipe */
  416. conn = connection_new(CONN_TYPE_DNSWORKER);
  417. set_socket_nonblocking(fd[0]);
  418. /* set up conn so it's got all the data we need to remember */
  419. conn->s = fd[0];
  420. conn->address = tor_strdup("<unused>");
  421. if(connection_add(conn) < 0) { /* no space, forget it */
  422. log_fn(LOG_WARN,"connection_add failed. Giving up.");
  423. connection_free(conn); /* this closes fd[0] */
  424. return -1;
  425. }
  426. conn->state = DNSWORKER_STATE_IDLE;
  427. connection_start_reading(conn);
  428. return 0; /* success */
  429. }
  430. static void spawn_enough_dnsworkers(void) {
  431. int num_dnsworkers_needed; /* aim to have 1 more than needed,
  432. * but no less than min and no more than max */
  433. connection_t *dnsconn;
  434. /* XXX This may not be the best strategy. Maybe we should queue pending
  435. * requests until the old ones finish or time out: otherwise, if
  436. * the connection requests come fast enough, we never get any DNS done. -NM
  437. * XXX But if we queue them, then the adversary can pile even more
  438. * queries onto us, blocking legitimate requests for even longer.
  439. * Maybe we should compromise and only kill if it's been at it for
  440. * more than, e.g., 2 seconds. -RD
  441. */
  442. if(num_dnsworkers_busy == MAX_DNSWORKERS) {
  443. /* We always want at least one worker idle.
  444. * So find the oldest busy worker and kill it.
  445. */
  446. dnsconn = connection_get_by_type_state_lastwritten(CONN_TYPE_DNSWORKER,
  447. DNSWORKER_STATE_BUSY);
  448. assert(dnsconn);
  449. log_fn(LOG_WARN, "%d DNS workers are spawned; all are busy. Killing one.",
  450. MAX_DNSWORKERS);
  451. connection_mark_for_close(dnsconn,0);
  452. num_dnsworkers_busy--;
  453. num_dnsworkers--;
  454. }
  455. if(num_dnsworkers_busy >= MIN_DNSWORKERS)
  456. num_dnsworkers_needed = num_dnsworkers_busy+1;
  457. else
  458. num_dnsworkers_needed = MIN_DNSWORKERS;
  459. while(num_dnsworkers < num_dnsworkers_needed) {
  460. if(spawn_dnsworker() < 0) {
  461. log(LOG_WARN,"spawn_enough_dnsworkers(): spawn failed!");
  462. return;
  463. }
  464. num_dnsworkers++;
  465. }
  466. while(num_dnsworkers > num_dnsworkers_busy+MAX_IDLE_DNSWORKERS) { /* too many idle? */
  467. /* cull excess workers */
  468. log_fn(LOG_WARN,"%d of %d dnsworkers are idle. Killing one.",
  469. num_dnsworkers-num_dnsworkers_needed, num_dnsworkers);
  470. dnsconn = connection_get_by_type_state(CONN_TYPE_DNSWORKER, DNSWORKER_STATE_IDLE);
  471. assert(dnsconn);
  472. connection_mark_for_close(dnsconn,0);
  473. num_dnsworkers--;
  474. }
  475. }
  476. /*
  477. Local Variables:
  478. mode:c
  479. indent-tabs-mode:nil
  480. c-basic-offset:2
  481. End:
  482. */