dns.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445
  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_workers=0;
  15. int num_workers_busy=0;
  16. static int dns_assign_to_worker(connection_t *exitconn);
  17. static void dns_found_answer(char *question, uint32_t answer);
  18. int dnsworker_main(void *data);
  19. static int dns_spawn_worker(void);
  20. static void spawn_enough_workers(void);
  21. struct pending_connection_t {
  22. struct connection_t *conn;
  23. struct pending_connection_t *next;
  24. };
  25. struct cached_resolve {
  26. SPLAY_ENTRY(cached_resolve) node;
  27. char question[MAX_ADDRESSLEN]; /* the hostname to be resolved */
  28. uint32_t answer; /* in host order. I know I'm horrible for assuming ipv4 */
  29. char state; /* 0 is pending; 1 means answer is valid; 2 means resolve failed */
  30. #define CACHE_STATE_PENDING 0
  31. #define CACHE_STATE_VALID 1
  32. #define CACHE_STATE_FAILED 2
  33. uint32_t expire; /* remove untouched items from cache after some time? */
  34. struct pending_connection_t *pending_connections;
  35. struct cached_resolve *next;
  36. };
  37. SPLAY_HEAD(cache_tree, cached_resolve) cache_root;
  38. static int compare_cached_resolves(struct cached_resolve *a, struct cached_resolve *b) {
  39. /* make this smarter one day? */
  40. return strncasecmp(a->question, b->question, MAX_ADDRESSLEN);
  41. }
  42. SPLAY_PROTOTYPE(cache_tree, cached_resolve, node, compare_cached_resolves);
  43. SPLAY_GENERATE(cache_tree, cached_resolve, node, compare_cached_resolves);
  44. static void init_cache_tree(void) {
  45. SPLAY_INIT(&cache_root);
  46. }
  47. void dns_init(void) {
  48. init_cache_tree();
  49. spawn_enough_workers();
  50. }
  51. static struct cached_resolve *oldest_cached_resolve = NULL; /* linked list, */
  52. static struct cached_resolve *newest_cached_resolve = NULL; /* oldest to newest */
  53. /* See if the question 'exitconn->address' has been answered. if so,
  54. * if resolve valid, put it into exitconn->addr and exec to
  55. * connection_exit_connect. If resolve failed, return -1.
  56. *
  57. * Else, if seen before and pending, add conn to the pending list,
  58. * and return 0.
  59. *
  60. * Else, if not seen before, add conn to pending list, hand to
  61. * dns farm, and return 0.
  62. */
  63. int dns_resolve(connection_t *exitconn) {
  64. struct cached_resolve *resolve;
  65. struct cached_resolve search;
  66. struct pending_connection_t *pending_connection;
  67. uint32_t now = time(NULL);
  68. /* first take this opportunity to see if there are any expired
  69. * resolves in the tree. this is fast because the linked list
  70. * oldest_cached_resolve is ordered by when they came in.
  71. */
  72. while(oldest_cached_resolve && (oldest_cached_resolve->expire < now)) {
  73. resolve = oldest_cached_resolve;
  74. log(LOG_DEBUG,"Forgetting old cached resolve (expires %d)", resolve->expire);
  75. oldest_cached_resolve = resolve->next;
  76. if(!oldest_cached_resolve) /* if there are no more, */
  77. newest_cached_resolve = NULL; /* then make sure the list's tail knows that too */
  78. SPLAY_REMOVE(cache_tree, &cache_root, resolve);
  79. free(resolve);
  80. }
  81. /* now check the tree to see if 'question' is already there. */
  82. strncpy(search.question, exitconn->address, MAX_ADDRESSLEN);
  83. resolve = SPLAY_FIND(cache_tree, &cache_root, &search);
  84. if(resolve) { /* already there */
  85. switch(resolve->state) {
  86. case CACHE_STATE_PENDING:
  87. /* add us to the pending list */
  88. pending_connection = tor_malloc(sizeof(struct pending_connection_t));
  89. pending_connection->conn = exitconn;
  90. pending_connection->next = resolve->pending_connections;
  91. resolve->pending_connections = pending_connection;
  92. return 0;
  93. case CACHE_STATE_VALID:
  94. exitconn->addr = resolve->answer;
  95. return connection_exit_connect(exitconn);
  96. case CACHE_STATE_FAILED:
  97. return -1;
  98. }
  99. } else { /* need to add it */
  100. resolve = tor_malloc(sizeof(struct cached_resolve));
  101. memset(resolve, 0, sizeof(struct cached_resolve));
  102. resolve->state = CACHE_STATE_PENDING;
  103. resolve->expire = now + 100; /* XXX for testing. when we're confident, switch it back */
  104. // resolve->expire = now + 86400; /* now + 1 day */
  105. strncpy(resolve->question, exitconn->address, MAX_ADDRESSLEN);
  106. /* add us to the pending list */
  107. pending_connection = tor_malloc(sizeof(struct pending_connection_t));
  108. pending_connection->conn = exitconn;
  109. pending_connection->next = resolve->pending_connections;
  110. resolve->pending_connections = pending_connection;
  111. /* add us to the linked list of resolves */
  112. if (!oldest_cached_resolve) {
  113. oldest_cached_resolve = resolve;
  114. } else {
  115. newest_cached_resolve->next = resolve;
  116. }
  117. newest_cached_resolve = resolve;
  118. SPLAY_INSERT(cache_tree, &cache_root, resolve);
  119. return dns_assign_to_worker(exitconn);
  120. }
  121. assert(0);
  122. return 0; /* not reached; keep gcc happy */
  123. }
  124. static int dns_assign_to_worker(connection_t *exitconn) {
  125. connection_t *dnsconn;
  126. unsigned char len;
  127. spawn_enough_workers(); /* respawn here, to be sure there are enough */
  128. dnsconn = connection_get_by_type_state(CONN_TYPE_DNSWORKER, DNSWORKER_STATE_IDLE);
  129. if(!dnsconn) {
  130. log(LOG_INFO,"dns_assign_to_worker(): no idle dns workers. Failing.");
  131. dns_cancel_pending_resolve(exitconn->address, NULL);
  132. return -1;
  133. }
  134. dnsconn->address = strdup(exitconn->address);
  135. dnsconn->state = DNSWORKER_STATE_BUSY;
  136. num_workers_busy++;
  137. len = strlen(dnsconn->address);
  138. /* FFFF we should have it retry if the first worker bombs out */
  139. if(connection_write_to_buf(&len, 1, dnsconn) < 0 ||
  140. connection_write_to_buf(dnsconn->address, len, dnsconn) < 0) {
  141. log(LOG_NOTICE,"dns_assign_to_worker(): Write failed. Closing worker and failing resolve.");
  142. dnsconn->marked_for_close = 1;
  143. dns_cancel_pending_resolve(exitconn->address, NULL);
  144. return -1;
  145. }
  146. // log(LOG_DEBUG,"dns_assign_to_worker(): submitted '%s'", exitconn->address);
  147. return 0;
  148. }
  149. /* if onlyconn is NULL, cancel the whole thing. if onlyconn is defined,
  150. * then remove onlyconn from the pending list, and if the pending list
  151. * is now empty, cancel the whole thing.
  152. */
  153. void dns_cancel_pending_resolve(char *question, connection_t *onlyconn) {
  154. struct pending_connection_t *pend, *victim;
  155. struct cached_resolve search;
  156. struct cached_resolve *resolve, *tmp;
  157. strncpy(search.question, question, MAX_ADDRESSLEN);
  158. resolve = SPLAY_FIND(cache_tree, &cache_root, &search);
  159. if(!resolve) {
  160. log_fn(LOG_INFO,"Answer to unasked question '%s'? Dropping.", question);
  161. return;
  162. }
  163. assert(resolve->state == CACHE_STATE_PENDING);
  164. assert(resolve->pending_connections);
  165. if(onlyconn) {
  166. pend = resolve->pending_connections;
  167. if(pend->conn == onlyconn) {
  168. resolve->pending_connections = pend->next;
  169. free(pend);
  170. if(resolve->pending_connections) /* more pending, don't cancel it */
  171. return;
  172. } else {
  173. for( ; pend->next; pend = pend->next) {
  174. if(pend->next->conn == onlyconn) {
  175. victim = pend->next;
  176. pend->next = victim->next;
  177. free(victim);
  178. return; /* more are pending */
  179. }
  180. }
  181. assert(0); /* not reachable unless onlyconn not in pending list */
  182. }
  183. } else {
  184. /* mark all pending connections to fail */
  185. while(resolve->pending_connections) {
  186. pend = resolve->pending_connections;
  187. pend->conn->marked_for_close = 1;
  188. resolve->pending_connections = pend->next;
  189. free(pend);
  190. }
  191. }
  192. /* remove resolve from the linked list */
  193. if(resolve == oldest_cached_resolve) {
  194. oldest_cached_resolve = resolve->next;
  195. if(oldest_cached_resolve == NULL)
  196. newest_cached_resolve = NULL;
  197. } else {
  198. /* FFFF make it a doubly linked list if this becomes too slow */
  199. for(tmp=oldest_cached_resolve; tmp && tmp->next != resolve; tmp=tmp->next) ;
  200. assert(tmp); /* it's got to be in the list, or we screwed up somewhere else */
  201. tmp->next = resolve->next; /* unlink it */
  202. if(newest_cached_resolve == resolve)
  203. newest_cached_resolve = tmp;
  204. }
  205. /* remove resolve from the tree */
  206. SPLAY_REMOVE(cache_tree, &cache_root, resolve);
  207. free(resolve);
  208. }
  209. static void dns_found_answer(char *question, uint32_t answer) {
  210. struct pending_connection_t *pend;
  211. struct cached_resolve search;
  212. struct cached_resolve *resolve;
  213. strncpy(search.question, question, MAX_ADDRESSLEN);
  214. resolve = SPLAY_FIND(cache_tree, &cache_root, &search);
  215. if(!resolve) {
  216. log_fn(LOG_INFO,"Answer to unasked question '%s'? Dropping.", question);
  217. return;
  218. }
  219. assert(resolve->state == CACHE_STATE_PENDING);
  220. resolve->answer = ntohl(answer);
  221. if(resolve->answer)
  222. resolve->state = CACHE_STATE_VALID;
  223. else
  224. resolve->state = CACHE_STATE_FAILED;
  225. while(resolve->pending_connections) {
  226. pend = resolve->pending_connections;
  227. pend->conn->addr = resolve->answer;
  228. if(resolve->state == CACHE_STATE_FAILED || connection_exit_connect(pend->conn) < 0) {
  229. pend->conn->marked_for_close = 1;
  230. }
  231. resolve->pending_connections = pend->next;
  232. free(pend);
  233. }
  234. }
  235. /******************************************************************/
  236. int connection_dns_finished_flushing(connection_t *conn) {
  237. assert(conn && conn->type == CONN_TYPE_DNSWORKER);
  238. connection_stop_writing(conn);
  239. return 0;
  240. }
  241. int connection_dns_process_inbuf(connection_t *conn) {
  242. uint32_t answer;
  243. assert(conn && conn->type == CONN_TYPE_DNSWORKER);
  244. if(conn->inbuf_reached_eof) {
  245. log(LOG_ERR,"connection_dnsworker_process_inbuf(): Read eof. Worker dying.");
  246. if(conn->state == DNSWORKER_STATE_BUSY)
  247. dns_cancel_pending_resolve(conn->address, NULL);
  248. return -1;
  249. }
  250. assert(conn->state == DNSWORKER_STATE_BUSY);
  251. if(conn->inbuf_datalen < 4) /* entire answer available? */
  252. return 0; /* not yet */
  253. assert(conn->inbuf_datalen == 4);
  254. connection_fetch_from_buf((char*)&answer,sizeof(answer),conn);
  255. dns_found_answer(conn->address, answer);
  256. free(conn->address);
  257. conn->address = NULL;
  258. conn->state = DNSWORKER_STATE_IDLE;
  259. num_workers_busy--;
  260. return 0;
  261. }
  262. int dnsworker_main(void *data) {
  263. char question[MAX_ADDRESSLEN];
  264. unsigned char question_len;
  265. struct hostent *rent;
  266. int fd;
  267. int *fdarray = data;
  268. close(fdarray[0]); /* this is the side of the socketpair the parent uses */
  269. fd = fdarray[1]; /* this side is ours */
  270. for(;;) {
  271. if(read(fd, &question_len, 1) != 1) {
  272. log(LOG_INFO,"dnsworker_main(): read length failed. Exiting.");
  273. spawn_exit();
  274. }
  275. assert(question_len > 0);
  276. if(read(fd, question, question_len) != question_len) {
  277. log(LOG_INFO,"dnsworker_main(): read hostname failed. Exiting.");
  278. spawn_exit();
  279. }
  280. question[question_len] = 0; /* null terminate it */
  281. rent = gethostbyname(question);
  282. if (!rent) {
  283. log(LOG_INFO,"dnsworker_main(): Could not resolve dest addr %s. Returning nulls.",question);
  284. /* XXX it's conceivable write could return 1 through 3. but that's never gonna happen, right? */
  285. if(write(fd, "\0\0\0\0", 4) != 4) {
  286. log(LOG_INFO,"dnsworker_main(): writing nulls failed. Exiting.");
  287. spawn_exit();
  288. }
  289. } else {
  290. assert(rent->h_length == 4); /* break to remind us if we move away from ipv4 */
  291. if(write(fd, rent->h_addr, 4) != 4) {
  292. log(LOG_INFO,"dnsworker_main(): writing answer failed. Exiting.");
  293. spawn_exit();
  294. }
  295. log(LOG_INFO,"dnsworker_main(): Answered question '%s'.",question);
  296. }
  297. }
  298. return 0; /* windows wants this function to return an int */
  299. }
  300. static int dns_spawn_worker(void) {
  301. int fd[2];
  302. connection_t *conn;
  303. if(socketpair(AF_UNIX, SOCK_STREAM, 0, fd) < 0) {
  304. perror("socketpair");
  305. exit(1);
  306. }
  307. spawn_func(dnsworker_main, (void*)fd);
  308. log(LOG_DEBUG,"dns_spawn_worker(): just spawned a worker.");
  309. close(fd[1]); /* we don't need the worker's side of the pipe */
  310. conn = connection_new(CONN_TYPE_DNSWORKER);
  311. if(!conn) {
  312. close(fd[0]);
  313. return -1;
  314. }
  315. set_socket_nonblocking(fd[0]);
  316. /* set up conn so it's got all the data we need to remember */
  317. conn->receiver_bucket = -1; /* non-cell connections don't do receiver buckets */
  318. conn->bandwidth = -1;
  319. conn->s = fd[0];
  320. if(connection_add(conn) < 0) { /* no space, forget it */
  321. log(LOG_INFO,"dns_spawn_worker(): connection_add failed. Giving up.");
  322. connection_free(conn); /* this closes fd[0] */
  323. return -1;
  324. }
  325. conn->state = DNSWORKER_STATE_IDLE;
  326. connection_start_reading(conn);
  327. return 0; /* success */
  328. }
  329. static void spawn_enough_workers(void) {
  330. int num_workers_needed; /* aim to have 1 more than needed,
  331. * but no less than min and no more than max */
  332. connection_t *dnsconn;
  333. if(num_workers_busy == MAX_DNSWORKERS) {
  334. /* We always want at least one worker idle.
  335. * So find the oldest busy worker and kill it.
  336. */
  337. dnsconn = connection_get_by_type_state_lastwritten(CONN_TYPE_DNSWORKER, DNSWORKER_STATE_BUSY);
  338. assert(dnsconn);
  339. /* tell the exit connection that it's failed */
  340. dns_cancel_pending_resolve(dnsconn->address, NULL);
  341. dnsconn->marked_for_close = 1;
  342. num_workers_busy--;
  343. }
  344. if(num_workers_busy >= MIN_DNSWORKERS)
  345. num_workers_needed = num_workers_busy+1;
  346. else
  347. num_workers_needed = MIN_DNSWORKERS;
  348. while(num_workers < num_workers_needed) {
  349. if(dns_spawn_worker() < 0) {
  350. log(LOG_ERR,"spawn_enough_workers(): spawn failed!");
  351. return;
  352. }
  353. num_workers++;
  354. }
  355. while(num_workers > num_workers_needed+MAX_IDLE_DNSWORKERS) { /* too many idle? */
  356. /* cull excess workers */
  357. dnsconn = connection_get_by_type_state(CONN_TYPE_DNSWORKER, DNSWORKER_STATE_IDLE);
  358. assert(dnsconn);
  359. dnsconn->marked_for_close = 1;
  360. num_workers--;
  361. }
  362. }
  363. /*
  364. Local Variables:
  365. mode:c
  366. indent-tabs-mode:nil
  367. c-basic-offset:2
  368. End:
  369. */