Commit 7cb3232a authored by Nick Mathewson's avatar Nick Mathewson 🎨
Browse files

Add async dns code from Adam Langley, tweaked to build on OSX. Long-term, we...

Add  async dns code from Adam Langley, tweaked to build on OSX.  Long-term, we may want to switch to libevnet/c-ares, if they ever handle 10k fd situations properly. This one still needs work too, but at least it is small. This code is disabled by default, and not integrated with dns.c.

parent 86da3e0a
......@@ -44,6 +44,18 @@ if test $enable_threads = "yes"; then
AC_DEFINE(ENABLE_THREADS, 1, [Defined if we will try to use multithreading])
AC_HELP_STRING(--enable-eventdns, enable asynchronous dns module),
[case "${enableval}" in
yes) eventdns=true ;;
no) eventdns=false ;;
*) AC_MSG_ERROR(bad value for --enable-eventdns) ;;
esac], [eventdns=false])
AM_CONDITIONAL(EVENTDNS, test x$eventdns = xtrue)
if test x$eventdns = xtrue; then
AC_DEFINE([USE_EVENTDNS], 1, "Define to 1 if we'll be using eventdns.c")
case $host in
*-*-solaris* )
AC_DEFINE(_REENTRANT, 1, [Define on some platforms to activate x_r() functions in time.h])
......@@ -347,7 +359,7 @@ dnl These headers are not essential
AC_CHECK_HEADERS(stdint.h sys/types.h inttypes.h sys/param.h sys/wait.h sys/limits.h netinet/in.h arpa/inet.h machine/limits.h syslog.h sys/time.h sys/resource.h stddef.h inttypes.h utime.h sys/utime.h sys/mman.h)
AC_CHECK_FUNCS(gettimeofday ftime socketpair uname inet_aton strptime getrlimit setrlimit strlcat strlcpy strtoull getpwnam getpwuid ftello getaddrinfo localtime_r gmtime_r event_get_version event_get_method event_set_log_callback memmem mmap)
AC_CHECK_FUNCS(gettimeofday ftime socketpair uname inet_aton strptime getrlimit setrlimit strlcat strlcpy strtoull getpwnam getpwuid ftello getaddrinfo localtime_r gmtime_r event_get_version event_get_method event_set_log_callback memmem mmap strtok_r)
if test $enable_threads = "yes"; then
......@@ -4,12 +4,19 @@ noinst_PROGRAMS = test
bin_PROGRAMS = tor
EVDNSSRC = eventdns.c
tor_SOURCES = buffers.c circuitbuild.c circuitlist.c \
circuituse.c command.c config.c \
connection.c connection_edge.c connection_or.c control.c \
cpuworker.c directory.c dirserv.c dns.c hibernate.c main.c \
onion.c policies.c relay.c rendcommon.c rendclient.c rendmid.c \
rendservice.c rephist.c router.c routerlist.c routerparse.c \
tor_LDADD = ../common/libor.a ../common/libor-crypto.a -lz -lssl -lcrypto
......@@ -20,6 +27,7 @@ test_SOURCES = buffers.c circuitbuild.c circuitlist.c \
cpuworker.c directory.c dirserv.c dns.c hibernate.c main.c \
onion.c policies.c relay.c rendcommon.c rendclient.c rendmid.c \
rendservice.c rephist.c router.c routerlist.c routerparse.c \
test_LDADD = ../common/libor.a ../common/libor-crypto.a -lz -lssl -lcrypto
/* Async DNS Library
* Adam Langley <>
* Public Domain codenext
* This software is Public Domain. To view a copy of the public domain dedication,
* visit or send a letter to
* Creative Commons, 559 Nathan Abbott Way, Stanford, California 94305, USA.
* I ask and expect, but do not require, that all derivative works contain an
* attribution similar to:
* Parts developed by Adam Langley <>
* You may wish to replace the word "Parts" with something else depending on
* the amount of original code.
* (Derivative works does not include programs which link against, run or include
* the source verbatim in their source distributions)
* Version: 0.1b
* Welcome, gentle reader
* Async DNS lookups are really a whole lot harder than they should be,
* mostly stemming from the fact that the libc resolver has never been
* very good at them. Before you use this library you should see if libc
* can do the job for you with the modern async call getaddrinfo_r
* (Google for it). Otherwise, please continue.
* This code is based on libevent and you must call event_init before
* any of the APIs in this file. You must also seed the OpenSSL random
* source if you are using OpenSSL for ids (see below).
* This library is designed to be included and shipped with your source
* code. You statically link with it. You should also test for the
* existance of strtok_r and define HAVE_STRTOK_R if you have it.
* The DNS protocol requires a good source of id numbers and these
* numbers should be unpredictable for spoofing reasons. There are
* three methods for generating them here and you must define exactly
* one of them. In increasing order of preference:
* Using the bottom 16 bits of the usec result from gettimeofday. This
* is a pretty poor solution but should work anywhere
* Using the bottom 16 bits of the nsec result from the CPU's time
* counter. This is better, but may not work everywhere. Requires
* POSIX realtime support and you'll need to link against -lrt on
* glibc systems at least
* Uses the OpenSSL RAND_bytes call to generate the data. You must
* have seeded the pool before making any calls to this library.
* The library keeps track of the state of nameservers and will avoid
* them when they go down. Otherwise it will round robin between them.
* Quick start guide:
* #include "eventdns.h"
* void callback(int result, char type, int count, int ttl,
* void *addresses, void *arg);
* eventdns_resolv_conf_parse(DNS_OPTIONS_ALL, "/etc/resolv.conf");
* eventdns_resolve("", 0, callback, NULL);
* When the lookup is complete the callback function is called. The
* first argument will be one of the DNS_ERR_* defines in eventdns.h.
* Hopefully it will be DNS_ERR_NONE, in which case type will be
* DNS_IPv4_A, count will be the number of IP addresses, ttl is the time
* which the data can be cached for (in seconds), addresses will point
* to an array of uint32_t's and arg will be whatever you passed to
* eventdns_resolve.
* Searching:
* In order for this library to be a good replacment for glibc's resolver it
* supports searching. This involves setting a list of default domains, in
* which names will be queried for. The number of nots in the query name
* determines the order in which this list is used.
* Searching appears to be a single lookup from the point of view of the API,
* although many DNS queries may be generated from a single call to
* eventdns_resolve. Searching can also drastically slow down the resolution of
* names.
* To disable searching:
* 1. Never set it up. If you never call eventdns_resolv_conf_parse or
* eventdns_search_add then no searching will occur.
* 2. If you do call eventdns_resolv_conf_parse then don't pass
* DNS_OPTION_SEARCH (or DNS_OPTIONS_ALL, which implies it)
* 3. When calling eventdns_resolve, pass the DNS_QUERY_NO_SEARCH flag
* The order of searches depends on the number of dots in the name. If the
* number is greater than the ndots setting then the names is first tried
* globally. Otherwise each search domain is appended in turn.
* The ndots setting can either be set from a resolv.conf, or by calling
* eventdns_search_ndots_set.
* For example, with ndots set to 1 (the default) and a search domain list of
* [""]:
* Query: www
* Order:, www.
* Query:
* Order:,
* API reference:
* int eventdns_nameserver_add(unsigned long int addresss)
* Add a nameserver. The address should be an IP address in
* network byte order. The type of address is chosen so that
* it match in_addr.s_addr.
* Returns non-zero on error.
* int eventdns_nameserer_ip_add(const char *ip_as_string)
* This wraps the above function by parsing a string as an IP
* address and add it as a nameserver.
* Returns non-zero on error
* int eventdns_resolve(const char *name, int flags,
* eventdns_callback_type callback,
* void *ptr)
* Resolve a name. The name parameter should be a DNS name.
* The flags parameter should be 0, or DNS_QUERY_NO_SEARCH
* which disables searching for this query. (see defn of
* searching above).
* The callback argument is a function which is called when
* this query completes and ptr is an argument which is passed
* to that callback function.
* Returns non-zero on error
* void eventdns_search_clear()
* Clears the list of search domains
* void eventdns_search_add(const char *domain)
* Add a domain to the list of search domains
* void eventdns_search_ndots_set(int ndots)
* Set the number of dots which, when found in a name, causes
* the first query to be without any search domain.
* int eventdns_resolv_conf_parse(int flags, const char *filename)
* Parse a resolv.conf like file from the given filename.
* See the manpage for resolv.conf for the format of this file.
* The flags argument determines what information is parsed from
* this file:
* DNS_OPTION_SEARCH - domain, search and ndots options
* DNS_OPTION_NAMESERVERS - nameserver lines
* DNS_OPTION_MISC - timeout and attempts options
* DNS_OPTIONS_ALL - all of the above
* The following directives are not parsed from the file:
* sortlist, rotate, no-check-names, inet6, debug
* Returns non-zero on error:
* 0 no errors
* 1 failed to open file
* 2 failed to stat file
* 3 file too large
* 4 out of memory
* 5 short read from file
* Internals:
* Requests are kept in two queues. The first is the inflight queue. In
* this queue requests have an allocated transaction id and nameserver.
* They will soon be transmitted if they haven't already been.
* The second is the waiting queue. The size of the inflight ring is
* limited and all other requests wait in waiting queue for space. This
* bounds the number of concurrent requests so that we don't flood the
* nameserver. Several algorithms require a full walk of the inflight
* queue and so bounding its size keeps thing going nicly under huge
* (many thousands of requests) loads.
* If a nameserver looses too many requests it is considered down and we
* try not to use it. After a while we send a probe to that nameserver
* (a lookup for and, if it replies, we consider it working
* again. If the nameserver fails a probe we wait longer to try again
* with the next probe.
#include "eventdns.h"
#include "eventdns_tor.h"
//#define NDEBUG
#error Must configure at least one id generation method.
#error Please see the documentation
// #define _POSIX_C_SOURCE 200507
#define _GNU_SOURCE
#error Multiple id options selected
#error Multiple id options selected
#include <time.h>
#error Multiple id options selected
#include <openssl/rand.h>
#include <string.h>
#include <sys/types.h>
#include <fcntl.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <alloca.h>
#include <assert.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <limits.h>
#include <sys/stat.h>
#define HOST_NAME_MAX 255
#ifndef NDEBUG
#include <stdio.h>
#undef MIN
#define MIN(a,b) ((a)<(b)?(a):(b))
#ifdef __USE_ISOC99B
// libevent doesn't work without this
typedef uint8_t u_char;
typedef unsigned int uint;
#include <event.h>
#define u64 uint64_t
#define u32 uint32_t
#define u16 uint16_t
#define u8 uint8_t
#ifndef NDEBUG
#include <stdio.h>
#define log printf
#define log(x,...)
#include "eventdns.h"
#define MAX_ADDRS 4 // maximum number of addresses from a single packet
// which we bother recording
#define TYPE_A 1
#define CLASS_INET 1
struct request {
u8 *request; // the dns packet data
uint request_len;
int reissue_count;
int tx_count; // the number of times that this packet has been sent
void *user_pointer; // the pointer given to us for this request
eventdns_callback_type user_callback;
struct nameserver *ns; // the server which we last sent it
// elements used by the searching code
int search_index;
struct search_state *search_state;
char *search_origname; // needs to be free()ed
int search_flags;
// these objects are kept in a circular list
struct request *next, *prev;
struct event timeout_event;
u16 trans_id; // the transaction id
char request_appended; // true if the request pointer is data which follows this struct
char transmit_me; // needs to be transmitted
struct nameserver {
int socket; // a connected UDP socket
u32 address;
int failed_times; // number of times which we have given this server a chance
int timedout; // number of times in a row a request has timed out
struct event event;
// these objects are kept in a circular list
struct nameserver *next, *prev;
struct event timeout_event; // used to keep the timeout for
// when we next probe this server.
// Valid if state == 0
char state; // zero if we think that this server is down
char choaked; // true if we have an EAGAIN from this server's socket
char write_waiting; // true if we are waiting for EV_WRITE events
static struct request *req_head = NULL, *req_waiting_head = NULL;
static struct nameserver *server_head = NULL;
// The number of good nameservers that we have
static int global_good_nameservers = 0;
// inflight requests are contained in the req_head list
// and are actually going out across the network
static int global_requests_inflight = 0;
// requests which aren't inflight are in the waiting list
// and are counted here
static int global_requests_waiting = 0;
static int global_max_requests_inflight = 64;
static struct timeval global_timeout = {3, 0}; // 3 seconds
static int global_max_reissues = 1; // a reissue occurs when we get some errors from the server
static int global_max_retransmits = 3; // number of times we'll retransmit a request which timed out
// number of timeouts in a row before we consider this server to be down
static int global_max_nameserver_timeout = 3;
// These are the timeout values for nameservers. If we find a nameserver is down
// we try to probe it at intervals as given below. Values are in seconds.
static const struct timeval global_nameserver_timeouts[] = {{10, 0}, {60, 0}, {300, 0}, {900, 0}, {3600, 0}};
static const int global_nameserver_timeouts_length = sizeof(global_nameserver_timeouts)/sizeof(struct timeval);
const char *const eventdns_error_strings[] = {"no error", "The name server was unable to interpret the query", "The name server suffered an internal error", "The requested domain name does not exist", "The name server refused to reply to the request"};
static struct nameserver *nameserver_pick();
static void eventdns_request_insert(struct request *req, struct request **head);
static void nameserver_ready_callback(int fd, short events, void *arg);
static int eventdns_transmit();
static int eventdns_request_transmit(struct request *req);
static void nameserver_send_probe(struct nameserver *const ns);
static void search_request_finished(struct request *const);
static int search_try_next(struct request *const req);
static int search_request_new(const char *const name, int flags, eventdns_callback_type user_callback, void *user_arg);
static void eventdns_requests_pump_waiting_queue();
static u16 transaction_id_pick();
static struct request *request_new(const char *name, int flags, eventdns_callback_type callback, void *ptr);
static void request_submit(struct request *req);
// This walks the list of inflight requests to find the
// one with a matching transaction id. Returns NULL on
// failure
static struct request *
request_find_from_trans_id(u16 trans_id) {
struct request *req = req_head, *const started_at = req_head;
if (req) {
do {
if (req->trans_id == trans_id) return req;
req = req->next;
} while (req != started_at);
return NULL;
// a libevent callback function which is called when a nameserver
// has gone down and we want to test if it has came back to life yet
static void
nameserver_prod_callback(int fd, short events, void *arg) {
struct nameserver *const ns = (struct nameserver *) arg;
// a libevent callback which is called when a nameserver probe (to see if
// it has come back to life) times out. We increment the count of failed_times
// and wait longer to send the next probe packet.
static void
nameserver_probe_failed(struct nameserver *const ns) {
assert(ns->state == 0);
const struct timeval *const timeout =
global_nameserver_timeouts_length - 1)];
evtimer_set(&ns->timeout_event, nameserver_prod_callback, ns);
evtimer_add(&ns->timeout_event, (struct timeval *) timeout);
// called when a nameserver has been deemed to have failed. For example, too
// many packets have timed out etc
static void
nameserver_failed(struct nameserver *const ns) {
// if this nameserver has already been marked as failed
// then don't do anything
if (!ns->state) return;
log("Nameserver %lx has failed\n", (unsigned long)ns->address);
assert(global_good_nameservers >= 0);
if (global_good_nameservers == 0) {
log("All nameservers have failed\n");
ns->state = 0;
ns->failed_times = 1;
evtimer_set(&ns->timeout_event, nameserver_prod_callback, ns);
evtimer_add(&ns->timeout_event, (struct timeval *) &global_nameserver_timeouts[0]);
// walk the list of inflight requests to see if any can be reassigned to
// a different server. Requests in the waiting queue don't have a
// nameserver assigned yet
// if we don't have *any* good nameservers then there's no point
// trying to reassign requests to one
if (!global_good_nameservers) return;
struct request *req = req_head, *const started_at = req_head;
if (req) {
do {
if (req->tx_count == 0 && req->ns == ns) {
// still waiting to go out, can be moved
// to another server
req->ns = nameserver_pick();
req = req->next;
} while (req != started_at);
static void
nameserver_up(struct nameserver *const ns) {
if (ns->state) return;
log("Nameserver %lx is back up\n", (unsigned long)ns->address);
ns->state = 1;
ns->failed_times = 0;
static void
request_trans_id_set(struct request *const req, const u16 trans_id) {
req->trans_id = trans_id;
*((u16 *) req->request) = htons(trans_id);
// Called to remove a request from a list and dealloc it.
// head is a pointer to the head of the list it should be
// removed from or NULL if the request isn't in a list.
static void
request_finished(struct request *const req, struct request **head) {
if (head) {
if (req->next == req) {
// only item in the list
*head = NULL;
} else {
req->next->prev = req->prev;
req->prev->next = req->next;
if (*head == req) *head = req->next;
log("Removing timeout for %x\n", (unsigned) req);
if (!req->request_appended) {
// need to free the request data on it's own
} else {
// the request data is appended onto the header
// so everything gets free()ed when we:
// This is called when a server returns a funny error code.
// We try the request again with another server.
// return:
// 0 ok
// 1 failed/reissue is pointless
static int
request_reissue(struct request *req) {
const struct nameserver *const last_ns = req->ns;
// the last nameserver should have been marked as failing
// by the caller of this function, therefore pick will try
// not to return it
req->ns = nameserver_pick();
if (req->ns == last_ns) {
// ... but pick did return it
// not a lot of point in trying again with the
// same server
return 1;
req->tx_count = 0;
req->transmit_me = 1;
return 0;
// this function looks for space on the inflight queue and promotes
// requests from the waiting queue if it can.
static void
eventdns_requests_pump_waiting_queue() {
while (global_requests_inflight < global_max_requests_inflight &&
global_requests_waiting) {
// move a request from the waiting queue to the inflight queue
struct request *req;
if (req_waiting_head->next == req_waiting_head) {
// only one item in the queue
req = req_waiting_head;
req_waiting_head = NULL;
} else {
req = req_waiting_head;
req->next->prev = req->prev;
req->prev->next = req->next;
req_waiting_head = req->next;
req->ns = nameserver_pick();
request_trans_id_set(req, transaction_id_pick());
eventdns_request_insert(req, &req_head);
// this processes a parsed reply packet
static void
reply_handle(u16 trans_id, u16 flags, u32 ttl, u32 addrcount, u32 *addresses) {
int error;
struct request *const req = request_find_from_trans_id(trans_id);
if (!req) return;
if (flags & 0x020f || !addrcount) {
// there was an error
if (flags & 0x0200) {
} else {
u16 error_code = (flags & 0x000f) - 1;
if (error_code > 4) {
} else {
error = error_codes[error_code];
switch(error) {
// we regard these errors as marking a bad nameserver
if (req->reissue_count < global_max_reissues) {
if (!request_reissue(req)) return;