dns.c 17 KB

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