dns.c 16 KB

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