dns.c 18 KB

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