dns.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481
  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. log_fn(LOG_DEBUG,"Connection (fd %d) waiting for pending DNS resolve of '%s'",
  99. exitconn->s, exitconn->address);
  100. return 0;
  101. case CACHE_STATE_VALID:
  102. exitconn->addr = resolve->answer;
  103. log_fn(LOG_DEBUG,"Connection (fd %d) found cached answer for '%s'",
  104. exitconn->s, exitconn->address);
  105. return 1;
  106. case CACHE_STATE_FAILED:
  107. return -1;
  108. }
  109. } else { /* need to add it */
  110. resolve = tor_malloc(sizeof(struct cached_resolve));
  111. memset(resolve, 0, sizeof(struct cached_resolve));
  112. resolve->state = CACHE_STATE_PENDING;
  113. resolve->expire = now + 100; /* XXX for testing. when we're confident, switch it back */
  114. // resolve->expire = now + 86400; /* now + 1 day */
  115. strncpy(resolve->question, exitconn->address, MAX_ADDRESSLEN);
  116. /* add us to the pending list */
  117. pending_connection = tor_malloc(sizeof(struct pending_connection_t));
  118. pending_connection->conn = exitconn;
  119. pending_connection->next = resolve->pending_connections;
  120. resolve->pending_connections = pending_connection;
  121. /* add us to the linked list of resolves */
  122. if (!oldest_cached_resolve) {
  123. oldest_cached_resolve = resolve;
  124. } else {
  125. newest_cached_resolve->next = resolve;
  126. }
  127. newest_cached_resolve = resolve;
  128. SPLAY_INSERT(cache_tree, &cache_root, resolve);
  129. return assign_to_dnsworker(exitconn);
  130. }
  131. assert(0);
  132. return 0; /* not reached; keep gcc happy */
  133. }
  134. static int assign_to_dnsworker(connection_t *exitconn) {
  135. connection_t *dnsconn;
  136. unsigned char len;
  137. spawn_enough_dnsworkers(); /* respawn here, to be sure there are enough */
  138. dnsconn = connection_get_by_type_state(CONN_TYPE_DNSWORKER, DNSWORKER_STATE_IDLE);
  139. if(!dnsconn) {
  140. log_fn(LOG_WARN,"no idle dns workers. Failing.");
  141. dns_cancel_pending_resolve(exitconn->address, NULL);
  142. return -1;
  143. }
  144. log_fn(LOG_DEBUG, "Connection (fd %d) needs to resolve '%s'; assigning to DNSWorker (fd %d)",
  145. exitconn->s, exitconn->address, dnsconn->s);
  146. free(dnsconn->address);
  147. dnsconn->address = tor_strdup(exitconn->address);
  148. dnsconn->state = DNSWORKER_STATE_BUSY;
  149. num_dnsworkers_busy++;
  150. len = strlen(dnsconn->address);
  151. connection_write_to_buf(&len, 1, dnsconn);
  152. connection_write_to_buf(dnsconn->address, len, dnsconn);
  153. // log_fn(LOG_DEBUG,"submitted '%s'", exitconn->address);
  154. return 0;
  155. }
  156. /* if onlyconn is NULL, cancel the whole thing. if onlyconn is defined,
  157. * then remove onlyconn from the pending list, and if the pending list
  158. * is now empty, cancel the whole thing.
  159. */
  160. void dns_cancel_pending_resolve(char *question, connection_t *onlyconn) {
  161. struct pending_connection_t *pend, *victim;
  162. struct cached_resolve search;
  163. struct cached_resolve *resolve, *tmp;
  164. strncpy(search.question, question, MAX_ADDRESSLEN);
  165. resolve = SPLAY_FIND(cache_tree, &cache_root, &search);
  166. if(!resolve) {
  167. log_fn(LOG_WARN,"Question '%s' is not pending. Dropping.", question);
  168. return;
  169. }
  170. assert(resolve->state == CACHE_STATE_PENDING);
  171. assert(resolve->pending_connections);
  172. if(onlyconn) {
  173. pend = resolve->pending_connections;
  174. if(pend->conn == onlyconn) {
  175. resolve->pending_connections = pend->next;
  176. free(pend);
  177. if(resolve->pending_connections) {/* more pending, don't cancel it */
  178. log_fn(LOG_DEBUG, "Connection (fd %d) no longer waiting for resolve of '%s'",
  179. onlyconn->s, question);
  180. return;
  181. }
  182. } else {
  183. for( ; pend->next; pend = pend->next) {
  184. if(pend->next->conn == onlyconn) {
  185. victim = pend->next;
  186. pend->next = victim->next;
  187. free(victim);
  188. log_fn(LOG_DEBUG, "Connection (fd %d) no longer waiting for resolve of '%s'",
  189. onlyconn->s, question);
  190. return; /* more are pending */
  191. }
  192. }
  193. assert(0); /* not reachable unless onlyconn not in pending list */
  194. }
  195. } else {
  196. /* mark all pending connections to fail */
  197. log_fn(LOG_DEBUG, "Failing all connections waiting on DNS resolve of '%s'",
  198. question);
  199. while(resolve->pending_connections) {
  200. pend = resolve->pending_connections;
  201. connection_edge_end(pend->conn, END_STREAM_REASON_MISC, NULL);
  202. resolve->pending_connections = pend->next;
  203. free(pend);
  204. }
  205. }
  206. /* remove resolve from the linked list */
  207. if(resolve == oldest_cached_resolve) {
  208. oldest_cached_resolve = resolve->next;
  209. if(oldest_cached_resolve == NULL)
  210. newest_cached_resolve = NULL;
  211. } else {
  212. /* FFFF make it a doubly linked list if this becomes too slow */
  213. for(tmp=oldest_cached_resolve; tmp && tmp->next != resolve; tmp=tmp->next) ;
  214. assert(tmp); /* it's got to be in the list, or we screwed up somewhere else */
  215. tmp->next = resolve->next; /* unlink it */
  216. if(newest_cached_resolve == resolve)
  217. newest_cached_resolve = tmp;
  218. }
  219. /* remove resolve from the tree */
  220. SPLAY_REMOVE(cache_tree, &cache_root, resolve);
  221. free(resolve);
  222. }
  223. static void dns_found_answer(char *question, uint32_t answer) {
  224. struct pending_connection_t *pend;
  225. struct cached_resolve search;
  226. struct cached_resolve *resolve;
  227. strncpy(search.question, question, MAX_ADDRESSLEN);
  228. resolve = SPLAY_FIND(cache_tree, &cache_root, &search);
  229. if(!resolve) {
  230. log_fn(LOG_WARN,"Answer to unasked question '%s'? Dropping.", question);
  231. /* XXX Why drop? Just because we don't care now doesn't mean we shouldn't
  232. * XXX cache the result for later. */
  233. return;
  234. }
  235. if (resolve->state != CACHE_STATE_PENDING) {
  236. log_fn(LOG_WARN, "Duplicate answer to question '%s'; ignoring",
  237. question);
  238. return;
  239. }
  240. /* Removed this assertion: in fact, we'll sometimes get a double answer
  241. * to the same question. This can happen when we ask one worker to resolve
  242. * X.Y.Z., then we cancel the request, and then we ask another worker to
  243. * resolve X.Y.Z. */
  244. /* assert(resolve->state == CACHE_STATE_PENDING); */
  245. resolve->answer = ntohl(answer);
  246. if(resolve->answer)
  247. resolve->state = CACHE_STATE_VALID;
  248. else
  249. resolve->state = CACHE_STATE_FAILED;
  250. while(resolve->pending_connections) {
  251. pend = resolve->pending_connections;
  252. pend->conn->addr = resolve->answer;
  253. if(resolve->state == CACHE_STATE_FAILED)
  254. connection_edge_end(pend->conn, END_STREAM_REASON_RESOLVEFAILED, NULL);
  255. else
  256. connection_exit_connect(pend->conn);
  257. resolve->pending_connections = pend->next;
  258. free(pend);
  259. }
  260. }
  261. /******************************************************************/
  262. int connection_dns_finished_flushing(connection_t *conn) {
  263. assert(conn && conn->type == CONN_TYPE_DNSWORKER);
  264. connection_stop_writing(conn);
  265. return 0;
  266. }
  267. int connection_dns_process_inbuf(connection_t *conn) {
  268. uint32_t answer;
  269. assert(conn && conn->type == CONN_TYPE_DNSWORKER);
  270. if(conn->inbuf_reached_eof) {
  271. log_fn(LOG_WARN,"Read eof. Worker dying.");
  272. if(conn->state == DNSWORKER_STATE_BUSY) {
  273. dns_cancel_pending_resolve(conn->address, NULL);
  274. num_dnsworkers_busy--;
  275. }
  276. num_dnsworkers--;
  277. return -1;
  278. }
  279. assert(conn->state == DNSWORKER_STATE_BUSY);
  280. if(buf_datalen(conn->inbuf) < 4) /* entire answer available? */
  281. return 0; /* not yet */
  282. assert(buf_datalen(conn->inbuf) == 4);
  283. connection_fetch_from_buf((char*)&answer,sizeof(answer),conn);
  284. log_fn(LOG_DEBUG, "DNSWorker (fd %d) returned answer for '%s'",
  285. conn->s, conn->address);
  286. dns_found_answer(conn->address, answer);
  287. free(conn->address);
  288. conn->address = strdup("<idle>");
  289. conn->state = DNSWORKER_STATE_IDLE;
  290. num_dnsworkers_busy--;
  291. return 0;
  292. }
  293. int dnsworker_main(void *data) {
  294. char question[MAX_ADDRESSLEN];
  295. unsigned char question_len;
  296. struct hostent *rent;
  297. int *fdarray = data;
  298. int fd;
  299. close(fdarray[0]); /* this is the side of the socketpair the parent uses */
  300. fd = fdarray[1]; /* this side is ours */
  301. for(;;) {
  302. if(read(fd, &question_len, 1) != 1) {
  303. log_fn(LOG_ERR,"read length failed. Child exiting.");
  304. spawn_exit();
  305. }
  306. assert(question_len > 0);
  307. if(read_all(fd, question, question_len) != question_len) {
  308. log_fn(LOG_ERR,"read hostname failed. Child exiting.");
  309. spawn_exit();
  310. }
  311. question[question_len] = 0; /* null terminate it */
  312. rent = gethostbyname(question);
  313. if (!rent) {
  314. log_fn(LOG_INFO,"Could not resolve dest addr %s. Returning nulls.",question);
  315. if(write_all(fd, "\0\0\0\0", 4) != 4) {
  316. log_fn(LOG_ERR,"writing nulls failed. Child exiting.");
  317. spawn_exit();
  318. }
  319. } else {
  320. assert(rent->h_length == 4); /* break to remind us if we move away from ipv4 */
  321. if(write_all(fd, rent->h_addr, 4) != 4) {
  322. log_fn(LOG_INFO,"writing answer failed. Child exiting.");
  323. spawn_exit();
  324. }
  325. log_fn(LOG_INFO,"Answered question '%s'.",question);
  326. }
  327. }
  328. return 0; /* windows wants this function to return an int */
  329. }
  330. static int spawn_dnsworker(void) {
  331. int fd[2];
  332. connection_t *conn;
  333. if(tor_socketpair(AF_UNIX, SOCK_STREAM, 0, fd) < 0) {
  334. log(LOG_ERR, "Couldn't construct socketpair: %s", strerror(errno));
  335. exit(1);
  336. }
  337. spawn_func(dnsworker_main, (void*)fd);
  338. log_fn(LOG_DEBUG,"just spawned a worker.");
  339. close(fd[1]); /* we don't need the worker's side of the pipe */
  340. conn = connection_new(CONN_TYPE_DNSWORKER);
  341. set_socket_nonblocking(fd[0]);
  342. /* set up conn so it's got all the data we need to remember */
  343. conn->s = fd[0];
  344. conn->address = tor_strdup("<unused>");
  345. if(connection_add(conn) < 0) { /* no space, forget it */
  346. log_fn(LOG_WARN,"connection_add failed. Giving up.");
  347. connection_free(conn); /* this closes fd[0] */
  348. return -1;
  349. }
  350. conn->state = DNSWORKER_STATE_IDLE;
  351. connection_start_reading(conn);
  352. return 0; /* success */
  353. }
  354. static void spawn_enough_dnsworkers(void) {
  355. int num_dnsworkers_needed; /* aim to have 1 more than needed,
  356. * but no less than min and no more than max */
  357. connection_t *dnsconn;
  358. /* XXX This may not be the best strategy. Maybe we should queue pending
  359. * XXX requests until the old ones finish or time out: otherwise, if
  360. * XXX the connection requests come fast enough, we never get any DNS done.
  361. */
  362. if(num_dnsworkers_busy == MAX_DNSWORKERS) {
  363. /* We always want at least one worker idle.
  364. * So find the oldest busy worker and kill it.
  365. */
  366. dnsconn = connection_get_by_type_state_lastwritten(CONN_TYPE_DNSWORKER, DNSWORKER_STATE_BUSY);
  367. assert(dnsconn);
  368. log_fn(LOG_DEBUG, "Max DNS workers spawned; all are busy. Killing one.");
  369. /* tell the exit connection that it's failed */
  370. dns_cancel_pending_resolve(dnsconn->address, NULL);
  371. dnsconn->marked_for_close = 1;
  372. num_dnsworkers_busy--;
  373. num_dnsworkers--;
  374. }
  375. if(num_dnsworkers_busy >= MIN_DNSWORKERS)
  376. num_dnsworkers_needed = num_dnsworkers_busy+1;
  377. else
  378. num_dnsworkers_needed = MIN_DNSWORKERS;
  379. while(num_dnsworkers < num_dnsworkers_needed) {
  380. if(spawn_dnsworker() < 0) {
  381. log(LOG_WARN,"spawn_enough_dnsworkers(): spawn failed!");
  382. return;
  383. }
  384. num_dnsworkers++;
  385. }
  386. while(num_dnsworkers > num_dnsworkers_needed+MAX_IDLE_DNSWORKERS) { /* too many idle? */
  387. /* cull excess workers */
  388. dnsconn = connection_get_by_type_state(CONN_TYPE_DNSWORKER, DNSWORKER_STATE_IDLE);
  389. assert(dnsconn);
  390. dnsconn->marked_for_close = 1;
  391. num_dnsworkers--;
  392. }
  393. }
  394. /*
  395. Local Variables:
  396. mode:c
  397. indent-tabs-mode:nil
  398. c-basic-offset:2
  399. End:
  400. */