dns.c 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447
  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. free(dnsconn->address);
  141. dnsconn->address = tor_strdup(exitconn->address);
  142. dnsconn->state = DNSWORKER_STATE_BUSY;
  143. num_dnsworkers_busy++;
  144. len = strlen(dnsconn->address);
  145. connection_write_to_buf(&len, 1, dnsconn);
  146. connection_write_to_buf(dnsconn->address, len, dnsconn);
  147. // log_fn(LOG_DEBUG,"submitted '%s'", exitconn->address);
  148. return 0;
  149. }
  150. /* if onlyconn is NULL, cancel the whole thing. if onlyconn is defined,
  151. * then remove onlyconn from the pending list, and if the pending list
  152. * is now empty, cancel the whole thing.
  153. */
  154. void dns_cancel_pending_resolve(char *question, connection_t *onlyconn) {
  155. struct pending_connection_t *pend, *victim;
  156. struct cached_resolve search;
  157. struct cached_resolve *resolve, *tmp;
  158. strncpy(search.question, question, MAX_ADDRESSLEN);
  159. resolve = SPLAY_FIND(cache_tree, &cache_root, &search);
  160. if(!resolve) {
  161. log_fn(LOG_WARN,"Question '%s' is not pending. Dropping.", question);
  162. return;
  163. }
  164. assert(resolve->state == CACHE_STATE_PENDING);
  165. assert(resolve->pending_connections);
  166. if(onlyconn) {
  167. pend = resolve->pending_connections;
  168. if(pend->conn == onlyconn) {
  169. resolve->pending_connections = pend->next;
  170. free(pend);
  171. if(resolve->pending_connections) /* more pending, don't cancel it */
  172. return;
  173. } else {
  174. for( ; pend->next; pend = pend->next) {
  175. if(pend->next->conn == onlyconn) {
  176. victim = pend->next;
  177. pend->next = victim->next;
  178. free(victim);
  179. return; /* more are pending */
  180. }
  181. }
  182. assert(0); /* not reachable unless onlyconn not in pending list */
  183. }
  184. } else {
  185. /* mark all pending connections to fail */
  186. while(resolve->pending_connections) {
  187. pend = resolve->pending_connections;
  188. /*ENDCLOSE*/ pend->conn->marked_for_close = 1;
  189. resolve->pending_connections = pend->next;
  190. free(pend);
  191. }
  192. }
  193. /* remove resolve from the linked list */
  194. if(resolve == oldest_cached_resolve) {
  195. oldest_cached_resolve = resolve->next;
  196. if(oldest_cached_resolve == NULL)
  197. newest_cached_resolve = NULL;
  198. } else {
  199. /* FFFF make it a doubly linked list if this becomes too slow */
  200. for(tmp=oldest_cached_resolve; tmp && tmp->next != resolve; tmp=tmp->next) ;
  201. assert(tmp); /* it's got to be in the list, or we screwed up somewhere else */
  202. tmp->next = resolve->next; /* unlink it */
  203. if(newest_cached_resolve == resolve)
  204. newest_cached_resolve = tmp;
  205. }
  206. /* remove resolve from the tree */
  207. SPLAY_REMOVE(cache_tree, &cache_root, resolve);
  208. free(resolve);
  209. }
  210. static void dns_found_answer(char *question, uint32_t answer) {
  211. struct pending_connection_t *pend;
  212. struct cached_resolve search;
  213. struct cached_resolve *resolve;
  214. strncpy(search.question, question, MAX_ADDRESSLEN);
  215. resolve = SPLAY_FIND(cache_tree, &cache_root, &search);
  216. if(!resolve) {
  217. log_fn(LOG_WARN,"Answer to unasked question '%s'? Dropping.", question);
  218. return;
  219. }
  220. assert(resolve->state == CACHE_STATE_PENDING);
  221. /* XXX sometimes this still gets triggered. :( */
  222. resolve->answer = ntohl(answer);
  223. if(resolve->answer)
  224. resolve->state = CACHE_STATE_VALID;
  225. else
  226. resolve->state = CACHE_STATE_FAILED;
  227. while(resolve->pending_connections) {
  228. pend = resolve->pending_connections;
  229. pend->conn->addr = resolve->answer;
  230. if(resolve->state == CACHE_STATE_FAILED || connection_exit_connect(pend->conn) < 0) {
  231. /*ENDCLOSE*/ pend->conn->marked_for_close = 1;
  232. }
  233. resolve->pending_connections = pend->next;
  234. free(pend);
  235. }
  236. }
  237. /******************************************************************/
  238. int connection_dns_finished_flushing(connection_t *conn) {
  239. assert(conn && conn->type == CONN_TYPE_DNSWORKER);
  240. connection_stop_writing(conn);
  241. return 0;
  242. }
  243. int connection_dns_process_inbuf(connection_t *conn) {
  244. uint32_t answer;
  245. assert(conn && conn->type == CONN_TYPE_DNSWORKER);
  246. if(conn->inbuf_reached_eof) {
  247. log_fn(LOG_WARN,"Read eof. Worker dying.");
  248. if(conn->state == DNSWORKER_STATE_BUSY) {
  249. dns_cancel_pending_resolve(conn->address, NULL);
  250. num_dnsworkers_busy--;
  251. }
  252. num_dnsworkers--;
  253. return -1;
  254. }
  255. assert(conn->state == DNSWORKER_STATE_BUSY);
  256. if(buf_datalen(conn->inbuf) < 4) /* entire answer available? */
  257. return 0; /* not yet */
  258. assert(buf_datalen(conn->inbuf) == 4);
  259. connection_fetch_from_buf((char*)&answer,sizeof(answer),conn);
  260. dns_found_answer(conn->address, answer);
  261. free(conn->address);
  262. conn->address = strdup("<idle>");
  263. conn->state = DNSWORKER_STATE_IDLE;
  264. num_dnsworkers_busy--;
  265. return 0;
  266. }
  267. int dnsworker_main(void *data) {
  268. char question[MAX_ADDRESSLEN];
  269. unsigned char question_len;
  270. struct hostent *rent;
  271. int *fdarray = data;
  272. int fd;
  273. close(fdarray[0]); /* this is the side of the socketpair the parent uses */
  274. fd = fdarray[1]; /* this side is ours */
  275. for(;;) {
  276. if(read(fd, &question_len, 1) != 1) {
  277. log_fn(LOG_ERR,"read length failed. Child exiting.");
  278. spawn_exit();
  279. }
  280. assert(question_len > 0);
  281. if(read_all(fd, question, question_len) != question_len) {
  282. log_fn(LOG_ERR,"read hostname failed. Child exiting.");
  283. spawn_exit();
  284. }
  285. question[question_len] = 0; /* null terminate it */
  286. rent = gethostbyname(question);
  287. if (!rent) {
  288. log_fn(LOG_INFO,"Could not resolve dest addr %s. Returning nulls.",question);
  289. if(write_all(fd, "\0\0\0\0", 4) != 4) {
  290. log_fn(LOG_ERR,"writing nulls failed. Child exiting.");
  291. spawn_exit();
  292. }
  293. } else {
  294. assert(rent->h_length == 4); /* break to remind us if we move away from ipv4 */
  295. if(write_all(fd, rent->h_addr, 4) != 4) {
  296. log_fn(LOG_INFO,"writing answer failed. Child exiting.");
  297. spawn_exit();
  298. }
  299. log_fn(LOG_INFO,"Answered question '%s'.",question);
  300. }
  301. }
  302. return 0; /* windows wants this function to return an int */
  303. }
  304. static int spawn_dnsworker(void) {
  305. int fd[2];
  306. connection_t *conn;
  307. if(tor_socketpair(AF_UNIX, SOCK_STREAM, 0, fd) < 0) {
  308. log(LOG_ERR, "Couldn't construct socketpair: %s", strerror(errno));
  309. exit(1);
  310. }
  311. spawn_func(dnsworker_main, (void*)fd);
  312. log_fn(LOG_DEBUG,"just spawned a worker.");
  313. close(fd[1]); /* we don't need the worker's side of the pipe */
  314. conn = connection_new(CONN_TYPE_DNSWORKER);
  315. set_socket_nonblocking(fd[0]);
  316. /* set up conn so it's got all the data we need to remember */
  317. conn->s = fd[0];
  318. conn->address = tor_strdup("<unused>");
  319. if(connection_add(conn) < 0) { /* no space, forget it */
  320. log_fn(LOG_WARN,"connection_add failed. Giving up.");
  321. connection_free(conn); /* this closes fd[0] */
  322. return -1;
  323. }
  324. conn->state = DNSWORKER_STATE_IDLE;
  325. connection_start_reading(conn);
  326. return 0; /* success */
  327. }
  328. static void spawn_enough_dnsworkers(void) {
  329. int num_dnsworkers_needed; /* aim to have 1 more than needed,
  330. * but no less than min and no more than max */
  331. connection_t *dnsconn;
  332. if(num_dnsworkers_busy == MAX_DNSWORKERS) {
  333. /* We always want at least one worker idle.
  334. * So find the oldest busy worker and kill it.
  335. */
  336. dnsconn = connection_get_by_type_state_lastwritten(CONN_TYPE_DNSWORKER, DNSWORKER_STATE_BUSY);
  337. assert(dnsconn);
  338. /* tell the exit connection that it's failed */
  339. dns_cancel_pending_resolve(dnsconn->address, NULL);
  340. dnsconn->marked_for_close = 1;
  341. num_dnsworkers_busy--;
  342. num_dnsworkers--;
  343. }
  344. if(num_dnsworkers_busy >= MIN_DNSWORKERS)
  345. num_dnsworkers_needed = num_dnsworkers_busy+1;
  346. else
  347. num_dnsworkers_needed = MIN_DNSWORKERS;
  348. while(num_dnsworkers < num_dnsworkers_needed) {
  349. if(spawn_dnsworker() < 0) {
  350. log(LOG_WARN,"spawn_enough_dnsworkers(): spawn failed!");
  351. return;
  352. }
  353. num_dnsworkers++;
  354. }
  355. while(num_dnsworkers > num_dnsworkers_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_dnsworkers--;
  361. }
  362. }
  363. /*
  364. Local Variables:
  365. mode:c
  366. indent-tabs-mode:nil
  367. c-basic-offset:2
  368. End:
  369. */