dns.c 17 KB

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