dns.c 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446
  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 *question, uint32_t answer);
  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 question[MAX_ADDRESSLEN]; /* the hostname to be resolved */
  29. uint32_t answer; /* 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. SPLAY_HEAD(cache_tree, cached_resolve) cache_root;
  39. static int compare_cached_resolves(struct cached_resolve *a, struct cached_resolve *b) {
  40. /* make this smarter one day? */
  41. return strncasecmp(a->question, b->question, MAX_ADDRESSLEN);
  42. }
  43. SPLAY_PROTOTYPE(cache_tree, cached_resolve, node, compare_cached_resolves);
  44. SPLAY_GENERATE(cache_tree, cached_resolve, node, compare_cached_resolves);
  45. static void init_cache_tree(void) {
  46. SPLAY_INIT(&cache_root);
  47. }
  48. void dns_init(void) {
  49. init_cache_tree();
  50. spawn_enough_dnsworkers();
  51. }
  52. static struct cached_resolve *oldest_cached_resolve = NULL; /* linked list, */
  53. static struct cached_resolve *newest_cached_resolve = NULL; /* oldest to newest */
  54. static void purge_expired_resolves(uint32_t now) {
  55. struct cached_resolve *resolve;
  56. /* this is fast because the linked list
  57. * oldest_cached_resolve is ordered by when they came in.
  58. */
  59. while(oldest_cached_resolve && (oldest_cached_resolve->expire < now)) {
  60. resolve = oldest_cached_resolve;
  61. log(LOG_DEBUG,"Forgetting old cached resolve (expires %d)", resolve->expire);
  62. oldest_cached_resolve = resolve->next;
  63. if(!oldest_cached_resolve) /* if there are no more, */
  64. newest_cached_resolve = NULL; /* then make sure the list's tail knows that too */
  65. SPLAY_REMOVE(cache_tree, &cache_root, resolve);
  66. free(resolve);
  67. }
  68. }
  69. /* See if the question 'exitconn->address' has been answered. if so,
  70. * if resolve valid, put it into exitconn->addr and return 1.
  71. * If resolve failed, return -1.
  72. *
  73. * Else, if seen before and pending, add conn to the pending list,
  74. * and return 0.
  75. *
  76. * Else, if not seen before, add conn to pending list, hand to
  77. * dns farm, and return 0.
  78. */
  79. int dns_resolve(connection_t *exitconn) {
  80. struct cached_resolve *resolve;
  81. struct cached_resolve search;
  82. struct pending_connection_t *pending_connection;
  83. uint32_t now = time(NULL);
  84. /* first take this opportunity to see if there are any expired
  85. resolves in the tree.*/
  86. purge_expired_resolves(now);
  87. /* now check the tree to see if 'question' is already there. */
  88. strncpy(search.question, exitconn->address, MAX_ADDRESSLEN);
  89. resolve = SPLAY_FIND(cache_tree, &cache_root, &search);
  90. if(resolve) { /* already there */
  91. switch(resolve->state) {
  92. case CACHE_STATE_PENDING:
  93. /* add us to the pending list */
  94. pending_connection = tor_malloc(sizeof(struct pending_connection_t));
  95. pending_connection->conn = exitconn;
  96. pending_connection->next = resolve->pending_connections;
  97. resolve->pending_connections = pending_connection;
  98. return 0;
  99. case CACHE_STATE_VALID:
  100. exitconn->addr = resolve->answer;
  101. return 1;
  102. case CACHE_STATE_FAILED:
  103. return -1;
  104. }
  105. } else { /* need to add it */
  106. resolve = tor_malloc(sizeof(struct cached_resolve));
  107. memset(resolve, 0, sizeof(struct cached_resolve));
  108. resolve->state = CACHE_STATE_PENDING;
  109. resolve->expire = now + 100; /* XXX for testing. when we're confident, switch it back */
  110. // resolve->expire = now + 86400; /* now + 1 day */
  111. strncpy(resolve->question, exitconn->address, MAX_ADDRESSLEN);
  112. /* add us to the pending list */
  113. pending_connection = tor_malloc(sizeof(struct pending_connection_t));
  114. pending_connection->conn = exitconn;
  115. pending_connection->next = resolve->pending_connections;
  116. resolve->pending_connections = pending_connection;
  117. /* add us to the linked list of resolves */
  118. if (!oldest_cached_resolve) {
  119. oldest_cached_resolve = resolve;
  120. } else {
  121. newest_cached_resolve->next = resolve;
  122. }
  123. newest_cached_resolve = resolve;
  124. SPLAY_INSERT(cache_tree, &cache_root, resolve);
  125. return assign_to_dnsworker(exitconn);
  126. }
  127. assert(0);
  128. return 0; /* not reached; keep gcc happy */
  129. }
  130. static int assign_to_dnsworker(connection_t *exitconn) {
  131. connection_t *dnsconn;
  132. unsigned char len;
  133. spawn_enough_dnsworkers(); /* respawn here, to be sure there are enough */
  134. dnsconn = connection_get_by_type_state(CONN_TYPE_DNSWORKER, DNSWORKER_STATE_IDLE);
  135. if(!dnsconn) {
  136. log_fn(LOG_WARN,"no idle dns workers. Failing.");
  137. dns_cancel_pending_resolve(exitconn->address, NULL);
  138. return -1;
  139. }
  140. dnsconn->address = tor_strdup(exitconn->address);
  141. dnsconn->state = DNSWORKER_STATE_BUSY;
  142. num_dnsworkers_busy++;
  143. len = strlen(dnsconn->address);
  144. connection_write_to_buf(&len, 1, dnsconn);
  145. connection_write_to_buf(dnsconn->address, len, dnsconn);
  146. // log_fn(LOG_DEBUG,"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_WARN,"Question '%s' is not pending. 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. /*ENDCLOSE*/ 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_WARN,"Answer to unasked question '%s'? Dropping.", question);
  217. return;
  218. }
  219. assert(resolve->state == CACHE_STATE_PENDING);
  220. /* XXX sometimes this still gets triggered. :( */
  221. resolve->answer = ntohl(answer);
  222. if(resolve->answer)
  223. resolve->state = CACHE_STATE_VALID;
  224. else
  225. resolve->state = CACHE_STATE_FAILED;
  226. while(resolve->pending_connections) {
  227. pend = resolve->pending_connections;
  228. pend->conn->addr = resolve->answer;
  229. if(resolve->state == CACHE_STATE_FAILED || connection_exit_connect(pend->conn) < 0) {
  230. /*ENDCLOSE*/ pend->conn->marked_for_close = 1;
  231. }
  232. resolve->pending_connections = pend->next;
  233. free(pend);
  234. }
  235. }
  236. /******************************************************************/
  237. int connection_dns_finished_flushing(connection_t *conn) {
  238. assert(conn && conn->type == CONN_TYPE_DNSWORKER);
  239. connection_stop_writing(conn);
  240. return 0;
  241. }
  242. int connection_dns_process_inbuf(connection_t *conn) {
  243. uint32_t answer;
  244. assert(conn && conn->type == CONN_TYPE_DNSWORKER);
  245. if(conn->inbuf_reached_eof) {
  246. log_fn(LOG_WARN,"Read eof. Worker dying.");
  247. if(conn->state == DNSWORKER_STATE_BUSY) {
  248. dns_cancel_pending_resolve(conn->address, NULL);
  249. num_dnsworkers_busy--;
  250. }
  251. num_dnsworkers--;
  252. return -1;
  253. }
  254. assert(conn->state == DNSWORKER_STATE_BUSY);
  255. if(buf_datalen(conn->inbuf) < 4) /* entire answer available? */
  256. return 0; /* not yet */
  257. assert(buf_datalen(conn->inbuf) == 4);
  258. connection_fetch_from_buf((char*)&answer,sizeof(answer),conn);
  259. dns_found_answer(conn->address, answer);
  260. free(conn->address);
  261. conn->address = NULL;
  262. conn->state = DNSWORKER_STATE_IDLE;
  263. num_dnsworkers_busy--;
  264. return 0;
  265. }
  266. int dnsworker_main(void *data) {
  267. char question[MAX_ADDRESSLEN];
  268. unsigned char question_len;
  269. struct hostent *rent;
  270. int *fdarray = data;
  271. int fd;
  272. close(fdarray[0]); /* this is the side of the socketpair the parent uses */
  273. fd = fdarray[1]; /* this side is ours */
  274. for(;;) {
  275. if(read(fd, &question_len, 1) != 1) {
  276. log_fn(LOG_ERR,"read length failed. Child exiting.");
  277. spawn_exit();
  278. }
  279. assert(question_len > 0);
  280. if(read_all(fd, question, question_len) != question_len) {
  281. log_fn(LOG_ERR,"read hostname failed. Child exiting.");
  282. spawn_exit();
  283. }
  284. question[question_len] = 0; /* null terminate it */
  285. rent = gethostbyname(question);
  286. if (!rent) {
  287. log_fn(LOG_INFO,"Could not resolve dest addr %s. Returning nulls.",question);
  288. if(write_all(fd, "\0\0\0\0", 4) != 4) {
  289. log_fn(LOG_ERR,"writing nulls failed. Child exiting.");
  290. spawn_exit();
  291. }
  292. } else {
  293. assert(rent->h_length == 4); /* break to remind us if we move away from ipv4 */
  294. if(write_all(fd, rent->h_addr, 4) != 4) {
  295. log_fn(LOG_INFO,"writing answer failed. Child exiting.");
  296. spawn_exit();
  297. }
  298. log_fn(LOG_INFO,"Answered question '%s'.",question);
  299. }
  300. }
  301. return 0; /* windows wants this function to return an int */
  302. }
  303. static int spawn_dnsworker(void) {
  304. int fd[2];
  305. connection_t *conn;
  306. if(tor_socketpair(AF_UNIX, SOCK_STREAM, 0, fd) < 0) {
  307. perror("socketpair");
  308. exit(1);
  309. }
  310. spawn_func(dnsworker_main, (void*)fd);
  311. log_fn(LOG_DEBUG,"just spawned a worker.");
  312. close(fd[1]); /* we don't need the worker's side of the pipe */
  313. conn = connection_new(CONN_TYPE_DNSWORKER);
  314. set_socket_nonblocking(fd[0]);
  315. /* set up conn so it's got all the data we need to remember */
  316. conn->s = fd[0];
  317. conn->address = tor_strdup("localhost");
  318. if(connection_add(conn) < 0) { /* no space, forget it */
  319. log_fn(LOG_WARN,"connection_add failed. Giving up.");
  320. connection_free(conn); /* this closes fd[0] */
  321. return -1;
  322. }
  323. conn->state = DNSWORKER_STATE_IDLE;
  324. connection_start_reading(conn);
  325. return 0; /* success */
  326. }
  327. static void spawn_enough_dnsworkers(void) {
  328. int num_dnsworkers_needed; /* aim to have 1 more than needed,
  329. * but no less than min and no more than max */
  330. connection_t *dnsconn;
  331. if(num_dnsworkers_busy == MAX_DNSWORKERS) {
  332. /* We always want at least one worker idle.
  333. * So find the oldest busy worker and kill it.
  334. */
  335. dnsconn = connection_get_by_type_state_lastwritten(CONN_TYPE_DNSWORKER, DNSWORKER_STATE_BUSY);
  336. assert(dnsconn);
  337. /* tell the exit connection that it's failed */
  338. dns_cancel_pending_resolve(dnsconn->address, NULL);
  339. dnsconn->marked_for_close = 1;
  340. num_dnsworkers_busy--;
  341. num_dnsworkers--;
  342. }
  343. if(num_dnsworkers_busy >= MIN_DNSWORKERS)
  344. num_dnsworkers_needed = num_dnsworkers_busy+1;
  345. else
  346. num_dnsworkers_needed = MIN_DNSWORKERS;
  347. while(num_dnsworkers < num_dnsworkers_needed) {
  348. if(spawn_dnsworker() < 0) {
  349. log(LOG_WARN,"spawn_enough_dnsworkers(): spawn failed!");
  350. return;
  351. }
  352. num_dnsworkers++;
  353. }
  354. while(num_dnsworkers > num_dnsworkers_needed+MAX_IDLE_DNSWORKERS) { /* too many idle? */
  355. /* cull excess workers */
  356. dnsconn = connection_get_by_type_state(CONN_TYPE_DNSWORKER, DNSWORKER_STATE_IDLE);
  357. assert(dnsconn);
  358. dnsconn->marked_for_close = 1;
  359. num_dnsworkers--;
  360. }
  361. }
  362. /*
  363. Local Variables:
  364. mode:c
  365. indent-tabs-mode:nil
  366. c-basic-offset:2
  367. End:
  368. */