dns.c 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526
  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 *address, uint32_t addr);
  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 address[MAX_ADDRESSLEN]; /* the hostname to be resolved */
  29. uint32_t addr; /* 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. static SPLAY_HEAD(cache_tree, cached_resolve) cache_root;
  39. static int compare_cached_resolves(struct cached_resolve *a,
  40. struct cached_resolve *b) {
  41. /* make this smarter one day? */
  42. return strncasecmp(a->address, b->address, MAX_ADDRESSLEN);
  43. }
  44. SPLAY_PROTOTYPE(cache_tree, cached_resolve, node, compare_cached_resolves);
  45. SPLAY_GENERATE(cache_tree, cached_resolve, node, compare_cached_resolves);
  46. static void init_cache_tree(void) {
  47. SPLAY_INIT(&cache_root);
  48. }
  49. void dns_init(void) {
  50. init_cache_tree();
  51. spawn_enough_dnsworkers();
  52. }
  53. static struct cached_resolve *oldest_cached_resolve = NULL; /* linked list, */
  54. static struct cached_resolve *newest_cached_resolve = NULL; /* oldest to newest */
  55. static void purge_expired_resolves(uint32_t now) {
  56. struct cached_resolve *resolve;
  57. /* this is fast because the linked list
  58. * oldest_cached_resolve is ordered by when they came in.
  59. */
  60. while(oldest_cached_resolve && (oldest_cached_resolve->expire < now)) {
  61. resolve = oldest_cached_resolve;
  62. log(LOG_DEBUG,"Forgetting old cached resolve (expires %lu)", (unsigned long)resolve->expire);
  63. oldest_cached_resolve = resolve->next;
  64. if(!oldest_cached_resolve) /* if there are no more, */
  65. newest_cached_resolve = NULL; /* then make sure the list's tail knows that too */
  66. SPLAY_REMOVE(cache_tree, &cache_root, resolve);
  67. free(resolve);
  68. }
  69. }
  70. #if 0
  71. uint32_t dns_lookup(const char *address) {
  72. struct in_addr in;
  73. uint32_t now = time(NULL);
  74. /* first take this opportunity to see if there are any expired
  75. resolves in the tree.*/
  76. purge_expired_resolves(now);
  77. if (inet_aton(address, &in)) {
  78. log_fn(LOG_DEBUG, "Using static address %s (%08X)", address,
  79. ntohl(in.s_addr));
  80. return ntohl(in.s_addr);
  81. }
  82. strncpy(search.address, address, MAX_ADDRESSLEN);
  83. search.address[MAX_ADDRESSLEN-1] = 0;
  84. resolve = SPLAY_FIND(cache_tree, &cache_root, &search);
  85. if(resolve) { /* it's there */
  86. if(resolve->state == CACHE_STATE_VALID) {
  87. in.s_addr = htonl(resolve->addr);
  88. log_fn(LOG_DEBUG, "Found cached entry for address %s: %s", address,
  89. inet_ntoa(in));
  90. return resolve->addr;
  91. }
  92. log_fn(LOG_DEBUG, "Entry found for address %s but it's not valid. Returning 0.",
  93. address);
  94. return 0;
  95. }
  96. /* it's not there */
  97. log_fn(LOG_DEBUG, "No entry found for address %s", address);
  98. return 0;
  99. }
  100. #endif
  101. /* See if we have a cache entry for 'exitconn->address'. if so,
  102. * if resolve valid, put it into exitconn->addr and return 1.
  103. * If resolve failed, return -1.
  104. *
  105. * Else, if seen before and pending, add conn to the pending list,
  106. * and return 0.
  107. *
  108. * Else, if not seen before, add conn to pending list, hand to
  109. * dns farm, and return 0.
  110. */
  111. int dns_resolve(connection_t *exitconn) {
  112. struct cached_resolve *resolve;
  113. struct cached_resolve search;
  114. struct pending_connection_t *pending_connection;
  115. uint32_t now = time(NULL);
  116. /* first take this opportunity to see if there are any expired
  117. resolves in the tree.*/
  118. purge_expired_resolves(now);
  119. /* now check the tree to see if 'address' is already there. */
  120. strncpy(search.address, exitconn->address, MAX_ADDRESSLEN);
  121. search.address[MAX_ADDRESSLEN-1] = 0;
  122. resolve = SPLAY_FIND(cache_tree, &cache_root, &search);
  123. if(resolve) { /* already there */
  124. switch(resolve->state) {
  125. case CACHE_STATE_PENDING:
  126. /* add us to the pending list */
  127. pending_connection = tor_malloc(sizeof(struct pending_connection_t));
  128. pending_connection->conn = exitconn;
  129. pending_connection->next = resolve->pending_connections;
  130. resolve->pending_connections = pending_connection;
  131. log_fn(LOG_DEBUG,"Connection (fd %d) waiting for pending DNS resolve of '%s'",
  132. exitconn->s, exitconn->address);
  133. return 0;
  134. case CACHE_STATE_VALID:
  135. exitconn->addr = resolve->addr;
  136. log_fn(LOG_DEBUG,"Connection (fd %d) found cached answer for '%s'",
  137. exitconn->s, exitconn->address);
  138. return 1;
  139. case CACHE_STATE_FAILED:
  140. return -1;
  141. }
  142. assert(0);
  143. }
  144. /* not there, need to add it */
  145. resolve = tor_malloc_zero(sizeof(struct cached_resolve));
  146. resolve->state = CACHE_STATE_PENDING;
  147. resolve->expire = now + MAX_DNS_ENTRY_AGE;
  148. strncpy(resolve->address, exitconn->address, MAX_ADDRESSLEN);
  149. resolve->address[MAX_ADDRESSLEN-1] = 0;
  150. /* add us to the pending list */
  151. pending_connection = tor_malloc(sizeof(struct pending_connection_t));
  152. pending_connection->conn = exitconn;
  153. pending_connection->next = resolve->pending_connections;
  154. resolve->pending_connections = pending_connection;
  155. /* add us to the linked list of resolves */
  156. if (!oldest_cached_resolve) {
  157. oldest_cached_resolve = resolve;
  158. } else {
  159. newest_cached_resolve->next = resolve;
  160. }
  161. newest_cached_resolve = resolve;
  162. SPLAY_INSERT(cache_tree, &cache_root, resolve);
  163. return assign_to_dnsworker(exitconn);
  164. }
  165. static int assign_to_dnsworker(connection_t *exitconn) {
  166. connection_t *dnsconn;
  167. unsigned char len;
  168. spawn_enough_dnsworkers(); /* respawn here, to be sure there are enough */
  169. dnsconn = connection_get_by_type_state(CONN_TYPE_DNSWORKER, DNSWORKER_STATE_IDLE);
  170. if(!dnsconn) {
  171. log_fn(LOG_WARN,"no idle dns workers. Failing.");
  172. dns_cancel_pending_resolve(exitconn->address, NULL);
  173. return -1;
  174. }
  175. log_fn(LOG_DEBUG, "Connection (fd %d) needs to resolve '%s'; assigning to DNSWorker (fd %d)",
  176. exitconn->s, exitconn->address, dnsconn->s);
  177. free(dnsconn->address);
  178. dnsconn->address = tor_strdup(exitconn->address);
  179. dnsconn->state = DNSWORKER_STATE_BUSY;
  180. num_dnsworkers_busy++;
  181. len = strlen(dnsconn->address);
  182. connection_write_to_buf(&len, 1, dnsconn);
  183. connection_write_to_buf(dnsconn->address, len, dnsconn);
  184. // log_fn(LOG_DEBUG,"submitted '%s'", exitconn->address);
  185. return 0;
  186. }
  187. /* if onlyconn is NULL, cancel the whole thing. if onlyconn is defined,
  188. * then remove onlyconn from the pending list, and if the pending list
  189. * is now empty, cancel the whole thing.
  190. */
  191. void dns_cancel_pending_resolve(char *address, connection_t *onlyconn) {
  192. struct pending_connection_t *pend, *victim;
  193. struct cached_resolve search;
  194. struct cached_resolve *resolve, *tmp;
  195. strncpy(search.address, address, MAX_ADDRESSLEN);
  196. search.address[MAX_ADDRESSLEN-1] = 0;
  197. resolve = SPLAY_FIND(cache_tree, &cache_root, &search);
  198. if(!resolve) {
  199. log_fn(LOG_WARN,"Address '%s' is not pending. Dropping.", address);
  200. return;
  201. }
  202. assert(resolve->state == CACHE_STATE_PENDING);
  203. assert(resolve->pending_connections);
  204. if(onlyconn) {
  205. pend = resolve->pending_connections;
  206. if(pend->conn == onlyconn) {
  207. resolve->pending_connections = pend->next;
  208. free(pend);
  209. if(resolve->pending_connections) {/* more pending, don't cancel it */
  210. log_fn(LOG_DEBUG, "Connection (fd %d) no longer waiting for resolve of '%s'",
  211. onlyconn->s, address);
  212. return;
  213. }
  214. } else {
  215. for( ; pend->next; pend = pend->next) {
  216. if(pend->next->conn == onlyconn) {
  217. victim = pend->next;
  218. pend->next = victim->next;
  219. free(victim);
  220. log_fn(LOG_DEBUG, "Connection (fd %d) no longer waiting for resolve of '%s'",
  221. onlyconn->s, address);
  222. return; /* more are pending */
  223. }
  224. }
  225. assert(0); /* not reachable unless onlyconn not in pending list */
  226. }
  227. } else {
  228. /* mark all pending connections to fail */
  229. log_fn(LOG_DEBUG, "Failing all connections waiting on DNS resolve of '%s'",
  230. address);
  231. while(resolve->pending_connections) {
  232. pend = resolve->pending_connections;
  233. if(connection_edge_end(pend->conn, END_STREAM_REASON_MISC, NULL) < 0)
  234. log_fn(LOG_WARN,"1: I called connection_edge_end redundantly.");
  235. resolve->pending_connections = pend->next;
  236. free(pend);
  237. }
  238. }
  239. /* remove resolve from the linked list */
  240. if(resolve == oldest_cached_resolve) {
  241. oldest_cached_resolve = resolve->next;
  242. if(oldest_cached_resolve == NULL)
  243. newest_cached_resolve = NULL;
  244. } else {
  245. /* FFFF make it a doubly linked list if this becomes too slow */
  246. for(tmp=oldest_cached_resolve; tmp && tmp->next != resolve; tmp=tmp->next) ;
  247. assert(tmp); /* it's got to be in the list, or we screwed up somewhere else */
  248. tmp->next = resolve->next; /* unlink it */
  249. if(newest_cached_resolve == resolve)
  250. newest_cached_resolve = tmp;
  251. }
  252. /* remove resolve from the tree */
  253. SPLAY_REMOVE(cache_tree, &cache_root, resolve);
  254. free(resolve);
  255. }
  256. static void dns_found_answer(char *address, uint32_t addr) {
  257. struct pending_connection_t *pend;
  258. struct cached_resolve search;
  259. struct cached_resolve *resolve;
  260. strncpy(search.address, address, MAX_ADDRESSLEN);
  261. search.address[MAX_ADDRESSLEN-1] = 0;
  262. resolve = SPLAY_FIND(cache_tree, &cache_root, &search);
  263. if(!resolve) {
  264. log_fn(LOG_INFO,"Resolved unasked address '%s'? Dropping.", address);
  265. /* XXX Why drop? Just because we don't care now doesn't mean we shouldn't
  266. * XXX cache the result for later. */
  267. return;
  268. }
  269. if (resolve->state != CACHE_STATE_PENDING) {
  270. log_fn(LOG_WARN, "Resolved '%s' which was already resolved; ignoring",
  271. address);
  272. return;
  273. }
  274. /* Removed this assertion: in fact, we'll sometimes get a double answer
  275. * to the same question. This can happen when we ask one worker to resolve
  276. * X.Y.Z., then we cancel the request, and then we ask another worker to
  277. * resolve X.Y.Z. */
  278. /* assert(resolve->state == CACHE_STATE_PENDING); */
  279. resolve->addr = ntohl(addr);
  280. if(resolve->addr)
  281. resolve->state = CACHE_STATE_VALID;
  282. else
  283. resolve->state = CACHE_STATE_FAILED;
  284. while(resolve->pending_connections) {
  285. pend = resolve->pending_connections;
  286. pend->conn->addr = resolve->addr;
  287. if(resolve->state == CACHE_STATE_FAILED) {
  288. if(connection_edge_end(pend->conn, END_STREAM_REASON_RESOLVEFAILED, NULL) < 0)
  289. log_fn(LOG_WARN,"1: I called connection_edge_end redundantly.");
  290. } else
  291. connection_exit_connect(pend->conn);
  292. resolve->pending_connections = pend->next;
  293. free(pend);
  294. }
  295. }
  296. /******************************************************************/
  297. int connection_dns_finished_flushing(connection_t *conn) {
  298. assert(conn && conn->type == CONN_TYPE_DNSWORKER);
  299. connection_stop_writing(conn);
  300. return 0;
  301. }
  302. int connection_dns_process_inbuf(connection_t *conn) {
  303. uint32_t addr;
  304. assert(conn && conn->type == CONN_TYPE_DNSWORKER);
  305. if(conn->inbuf_reached_eof) {
  306. log_fn(LOG_WARN,"Read eof. Worker dying.");
  307. if(conn->state == DNSWORKER_STATE_BUSY) {
  308. dns_cancel_pending_resolve(conn->address, NULL);
  309. num_dnsworkers_busy--;
  310. }
  311. num_dnsworkers--;
  312. return -1;
  313. }
  314. assert(conn->state == DNSWORKER_STATE_BUSY);
  315. if(buf_datalen(conn->inbuf) < 4) /* entire answer available? */
  316. return 0; /* not yet */
  317. assert(buf_datalen(conn->inbuf) == 4);
  318. connection_fetch_from_buf((char*)&addr,sizeof(addr),conn);
  319. log_fn(LOG_DEBUG, "DNSWorker (fd %d) returned answer for '%s'",
  320. conn->s, conn->address);
  321. dns_found_answer(conn->address, addr);
  322. free(conn->address);
  323. conn->address = tor_strdup("<idle>");
  324. conn->state = DNSWORKER_STATE_IDLE;
  325. num_dnsworkers_busy--;
  326. return 0;
  327. }
  328. int dnsworker_main(void *data) {
  329. char address[MAX_ADDRESSLEN];
  330. unsigned char address_len;
  331. struct hostent *rent;
  332. int *fdarray = data;
  333. int fd;
  334. close(fdarray[0]); /* this is the side of the socketpair the parent uses */
  335. fd = fdarray[1]; /* this side is ours */
  336. for(;;) {
  337. if(read(fd, &address_len, 1) != 1) {
  338. log_fn(LOG_INFO,"read length failed. Child exiting.");
  339. spawn_exit();
  340. }
  341. assert(address_len > 0);
  342. if(read_all(fd, address, address_len) != address_len) {
  343. log_fn(LOG_ERR,"read hostname failed. Child exiting.");
  344. spawn_exit();
  345. }
  346. address[address_len] = 0; /* null terminate it */
  347. rent = gethostbyname(address);
  348. if (!rent) {
  349. log_fn(LOG_INFO,"Could not resolve dest addr %s. Returning nulls.",address);
  350. if(write_all(fd, "\0\0\0\0", 4) != 4) {
  351. log_fn(LOG_ERR,"writing nulls failed. Child exiting.");
  352. spawn_exit();
  353. }
  354. } else {
  355. assert(rent->h_length == 4); /* break to remind us if we move away from ipv4 */
  356. if(write_all(fd, rent->h_addr, 4) != 4) {
  357. log_fn(LOG_INFO,"writing answer failed. Child exiting.");
  358. spawn_exit();
  359. }
  360. log_fn(LOG_INFO,"Resolved address '%s'.",address);
  361. }
  362. }
  363. return 0; /* windows wants this function to return an int */
  364. }
  365. static int spawn_dnsworker(void) {
  366. int fd[2];
  367. connection_t *conn;
  368. if(tor_socketpair(AF_UNIX, SOCK_STREAM, 0, fd) < 0) {
  369. log(LOG_ERR, "Couldn't construct socketpair: %s", strerror(errno));
  370. exit(1);
  371. }
  372. spawn_func(dnsworker_main, (void*)fd);
  373. log_fn(LOG_DEBUG,"just spawned a worker.");
  374. close(fd[1]); /* we don't need the worker's side of the pipe */
  375. conn = connection_new(CONN_TYPE_DNSWORKER);
  376. set_socket_nonblocking(fd[0]);
  377. /* set up conn so it's got all the data we need to remember */
  378. conn->s = fd[0];
  379. conn->address = tor_strdup("<unused>");
  380. if(connection_add(conn) < 0) { /* no space, forget it */
  381. log_fn(LOG_WARN,"connection_add failed. Giving up.");
  382. connection_free(conn); /* this closes fd[0] */
  383. return -1;
  384. }
  385. conn->state = DNSWORKER_STATE_IDLE;
  386. connection_start_reading(conn);
  387. return 0; /* success */
  388. }
  389. static void spawn_enough_dnsworkers(void) {
  390. int num_dnsworkers_needed; /* aim to have 1 more than needed,
  391. * but no less than min and no more than max */
  392. connection_t *dnsconn;
  393. /* XXX This may not be the best strategy. Maybe we should queue pending
  394. * requests until the old ones finish or time out: otherwise, if
  395. * the connection requests come fast enough, we never get any DNS done. -NM
  396. * XXX But if we queue them, then the adversary can pile even more
  397. * queries onto us, blocking legitimate requests for even longer.
  398. * Maybe we should compromise and only kill if it's been at it for
  399. * more than, e.g., 2 seconds. -RD
  400. */
  401. if(num_dnsworkers_busy == MAX_DNSWORKERS) {
  402. /* We always want at least one worker idle.
  403. * So find the oldest busy worker and kill it.
  404. */
  405. dnsconn = connection_get_by_type_state_lastwritten(CONN_TYPE_DNSWORKER,
  406. DNSWORKER_STATE_BUSY);
  407. assert(dnsconn);
  408. log_fn(LOG_WARN, "%d DNS workers are spawned; all are busy. Killing one.",
  409. MAX_DNSWORKERS);
  410. /* tell the exit connection that it's failed */
  411. dns_cancel_pending_resolve(dnsconn->address, NULL);
  412. dnsconn->marked_for_close = 1;
  413. num_dnsworkers_busy--;
  414. num_dnsworkers--;
  415. }
  416. if(num_dnsworkers_busy >= MIN_DNSWORKERS)
  417. num_dnsworkers_needed = num_dnsworkers_busy+1;
  418. else
  419. num_dnsworkers_needed = MIN_DNSWORKERS;
  420. while(num_dnsworkers < num_dnsworkers_needed) {
  421. if(spawn_dnsworker() < 0) {
  422. log(LOG_WARN,"spawn_enough_dnsworkers(): spawn failed!");
  423. return;
  424. }
  425. num_dnsworkers++;
  426. }
  427. while(num_dnsworkers > num_dnsworkers_needed+MAX_IDLE_DNSWORKERS) { /* too many idle? */
  428. /* cull excess workers */
  429. log_fn(LOG_WARN,"%d of %d dnsworkers are idle. Killing one.",
  430. num_dnsworkers-num_dnsworkers_needed, num_dnsworkers);
  431. dnsconn = connection_get_by_type_state(CONN_TYPE_DNSWORKER, DNSWORKER_STATE_IDLE);
  432. assert(dnsconn);
  433. dnsconn->marked_for_close = 1;
  434. num_dnsworkers--;
  435. }
  436. }
  437. /*
  438. Local Variables:
  439. mode:c
  440. indent-tabs-mode:nil
  441. c-basic-offset:2
  442. End:
  443. */