dns.c 15 KB

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