/* The original version of this module was written by Adam Langley; for
* a history of modifications, check out the subversion logs.
*
- * When editiing this module, try to keep it re-mergeable by Adam. Don't
+ * When editing this module, try to keep it re-mergeable by Adam. Don't
* reformat the whitespace, add Tor dependencies, or so on.
*
* TODO:
/* Async DNS Library
* Adam Langley <agl@imperialviolet.org>
* http://www.imperialviolet.org/eventdns.html
- * Public Domain codenext
+ * Public Domain code
*
* This software is Public Domain. To view a copy of the public domain dedication,
* visit http://creativecommons.org/licenses/publicdomain/ or send a letter to
* 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.
- *
- * [I googled for getaddrinfo_r and got only two hits, one of which was this
- * code. Did you mean something different? -NM]
+ * can do the job for you with the modern async call getaddrinfo_a
+ * (see http://www.imperialviolet.org/page25.html#e498). 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
* evdns_search_add then no searching will occur.
*
* 2. If you do call evdns_resolv_conf_parse then don't pass
- * DNS_OPTION_SEARCH (or DNS_OPTIONS_ALL, which implies it)
+ * DNS_OPTION_SEARCH (or DNS_OPTIONS_ALL, which implies it).
*
- * 3. When calling evdns_resolve, pass the DNS_QUERY_NO_SEARCH flag
+ * 3. When calling evdns_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
* queue and so bounding its size keeps thing going nicely under huge
* (many thousands of requests) loads.
*
- * If a nameserver looses too many requests it is considered down and we
+ * If a nameserver loses 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 google.com) and, if it replies, we consider it working
* again. If the nameserver fails a probe we wait longer to try again
#ifndef DNS_USE_GETTIMEOFDAY_FOR_ID
#ifndef DNS_USE_OPENSSL_FOR_ID
#error Must configure at least one id generation method.
-#error Please see the documentation
+#error Please see the documentation.
#endif
#endif
#endif
#include <string.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 <assert.h>
-#include <netinet/in.h>
-#include <arpa/inet.h>
#include <unistd.h>
#include <limits.h>
#include <sys/stat.h>
#include "evdns.h"
#include "log.h"
+#ifdef WIN32
+#include <windows.h>
+#include <winsock2.h>
+#include <iphlpapi.h>
+#else
+#include <sys/socket.h>
+#include <netinet/in.h>
+#include <arpa/inet.h>
+#endif
+
+#define EVDNS_LOG_DEBUG 0
+#define EVDNS_LOG_WARN 1
#ifndef HOST_NAME_MAX
#define HOST_NAME_MAX 255
struct request {
u8 *request; // the dns packet data
- uint request_len;
+ unsigned int request_len;
int reissue_count;
int tx_count; // the number of times that this packet has been sent
+ unsigned int request_type; // TYPE_PTR or TYPE_A
void *user_pointer; // the pointer given to us for this request
evdns_callback_type user_callback;
struct nameserver *ns; // the server which we last sent it
char transmit_me; // needs to be transmitted
};
+struct reply {
+ unsigned int type;
+ unsigned int have_answer;
+ union {
+ struct {
+ u32 addrcount;
+ u32 addresses[MAX_ADDRS];
+ } a;
+ struct {
+ char name[HOST_NAME_MAX];
+ } ptr;
+ } data;
+};
+
struct nameserver {
int socket; // a connected UDP socket
u32 address;
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, evdns_callback_type user_callback, void *user_arg);
+static int search_request_new(int type, const char *const name, int flags, evdns_callback_type user_callback, void *user_arg);
static void evdns_requests_pump_waiting_queue(void);
static u16 transaction_id_pick(void);
-static struct request *request_new(const char *name, int flags, evdns_callback_type callback, void *ptr);
+static struct request *request_new(int type, const char *name, int flags, evdns_callback_type callback, void *ptr);
static void request_submit(struct request *req);
#ifdef MS_WINDOWS
{
return err == EAGAIN || err == WSAEWOULDBLOCK;
}
+static int
+inet_aton(const char *c, struct in_addr *addr)
+{
+ uint32_t r;
+ if (strcmp(c, "255.255.255.255") == 0) {
+ addr->s_addr = 0xffffffffu;
+ } else {
+ r = inet_addr(c);
+ if (r == INADDR_NONE)
+ return 0;
+ addr->s_addr = r;
+ }
+ return 1;
+}
#define CLOSE_SOCKET(x) closesocket(x)
#else
#define last_error(sock) (errno)
}
#ifdef __GNUC__
-#define EVENTDNS_LOG_CHECK __attribute__ ((format(printf, 1, 2)))
+#define EVDNS_LOG_CHECK __attribute__ ((format(printf, 2, 3)))
#else
-#define EVENTDNS_LOG_CHECK
+#define EVDNS_LOG_CHECK
#endif
-static void _evdns_log(const char *fmt, ...) EVENTDNS_LOG_CHECK;
+static void _evdns_log(int warn, const char *fmt, ...) EVDNS_LOG_CHECK;
static void
-_evdns_log(const char *fmt, ...)
+_evdns_log(int warn, const char *fmt, ...)
{
va_list args;
static char buf[512];
vsnprintf(buf, sizeof(buf), fmt, args);
#endif
buf[sizeof(buf)-1] = '\0';
- evdns_log_fn(buf);
+ evdns_log_fn(warn, buf);
va_end(args);
}
static void
nameserver_probe_failed(struct nameserver *const ns) {
const struct timeval * timeout;
- assert(ns->state == 0);
(void) evtimer_del(&ns->timeout_event);
+ if (ns->state == 1) {
+ // This can happen if the nameserver acts in a way which makes us mark
+ // it as bad and then starts sending good replies.
+ return;
+ }
+
timeout =
&global_nameserver_timeouts[MIN(ns->failed_times,
global_nameserver_timeouts_length - 1)];
evtimer_set(&ns->timeout_event, nameserver_prod_callback, ns);
if (evtimer_add(&ns->timeout_event, (struct timeval *) timeout) < 0) {
- log("Error from libevent when adding timer event for %s",
+ log(EVDNS_LOG_WARN,
+ "Error from libevent when adding timer event for %s",
debug_ntoa(ns->address));
// ???? Do more?
}
// then don't do anything
if (!ns->state) return;
- log("Nameserver %s has failed: %s", debug_ntoa(ns->address), msg);
+ log(EVDNS_LOG_WARN, "Nameserver %s has failed: %s",
+ debug_ntoa(ns->address), msg);
global_good_nameservers--;
assert(global_good_nameservers >= 0);
if (global_good_nameservers == 0) {
- log("All nameservers have failed");
+ log(EVDNS_LOG_WARN, "All nameservers have failed");
}
ns->state = 0;
evtimer_set(&ns->timeout_event, nameserver_prod_callback, ns);
if (evtimer_add(&ns->timeout_event, (struct timeval *) &global_nameserver_timeouts[0]) < 0) {
- log("Error from libevent when adding timer event for %s",
- debug_ntoa(ns->address));
- // ???? Do more?
+ log(EVDNS_LOG_WARN,
+ "Error from libevent when adding timer event for %s",
+ debug_ntoa(ns->address));
+ // ???? Do more?
}
// walk the list of inflight requests to see if any can be reassigned to
static void
nameserver_up(struct nameserver *const ns) {
if (ns->state) return;
- log("Nameserver %s is back up", debug_ntoa(ns->address));
+ log(EVDNS_LOG_WARN, "Nameserver %s is back up",
+ debug_ntoa(ns->address));
evtimer_del(&ns->timeout_event);
ns->state = 1;
ns->failed_times = 0;
}
}
- log("Removing timeout for request %lx", (unsigned long) req);
+ log(EVDNS_LOG_DEBUG, "Removing timeout for request %lx",
+ (unsigned long) req);
evtimer_del(&req->timeout_event);
search_request_finished(req);
}
}
+static void
+reply_callback(struct request *const req, u32 ttl, u32 err, struct reply *reply) {
+ switch (req->request_type) {
+ case TYPE_A:
+ if (reply)
+ req->user_callback(DNS_ERR_NONE, DNS_IPv4_A,
+ reply->data.a.addrcount, ttl,
+ reply->data.a.addresses,
+ req->user_pointer);
+ else
+ req->user_callback(err, 0, 0, 0, NULL, req->user_pointer);
+ return;
+ case TYPE_PTR:
+ if (reply) {
+ char *name = reply->data.ptr.name;
+ req->user_callback(DNS_ERR_NONE, DNS_PTR, 1, ttl,
+ &name, req->user_pointer);
+ } else {
+ req->user_callback(err, 0, 0, 0, NULL,
+ req->user_pointer);
+ }
+ return;
+ }
+ assert(0);
+}
+
// this processes a parsed reply packet
static void
-reply_handle(u16 trans_id, u16 flags, u32 ttl, u32 addrcount, u32 *addresses) {
+reply_handle(struct request *const req, u16 flags, u32 ttl, struct reply *reply) {
int error;
static const int error_codes[] = {DNS_ERR_FORMAT, DNS_ERR_SERVERFAILED, DNS_ERR_NOTEXIST, DNS_ERR_NOTIMPL, DNS_ERR_REFUSED};
- struct request *const req = request_find_from_trans_id(trans_id);
- if (!req) return;
-
- if (flags & 0x020f || !addrcount) {
+ if (flags & 0x020f || !reply || !reply->have_answer) {
// there was an error
if (flags & 0x0200) {
error = DNS_ERR_TRUNCATED;
// we regard these errors as marking a bad nameserver
if (req->reissue_count < global_max_reissues) {
char msg[64];
- snprintf(msg, sizeof(msg), "Bad response %d",
- error);
+ snprintf(msg, sizeof(msg), "Bad response %d (%s)",
+ error, evdns_err_to_string(error));
nameserver_failed(req->ns, msg);
if (!request_reissue(req)) return;
}
nameserver_up(req->ns);
}
- if (req->search_state) {
+ if (req->search_state && req->request_type != TYPE_PTR) {
// if we have a list of domains to search in, try the next one
if (!search_try_next(req)) {
// a new request was issued so this request is finished and
}
// all else failed. Pass the failure up
- req->user_callback(error, 0, 0, 0, NULL, req->user_pointer);
+ reply_callback(req, 0, error, NULL);
request_finished(req, &req_head);
} else {
// all ok, tell the user
- req->user_callback(DNS_ERR_NONE, DNS_IPv4_A, addrcount, ttl, addresses, req->user_pointer);
+ reply_callback(req, ttl, 0, reply);
nameserver_up(req->ns);
request_finished(req, &req_head);
}
}
+static inline int
+name_parse(u8 *packet, int length, int *idx, char *name_out, int name_out_len) {
+ int name_end = -1;
+ int j = *idx;
+#define GET32(x) do { if (j + 4 > length) return -1; memcpy(&_t32, packet + j, 4); j += 4; x = ntohl(_t32); } while(0);
+#define GET16(x) do { if (j + 2 > length) return -1; memcpy(&_t, packet + j, 2); j += 2; x = ntohs(_t); } while(0);
+#define GET8(x) do { if (j >= length) return -1; x = packet[j++]; } while(0);
+
+ char *cp = name_out;
+ const char *const end = name_out + name_out_len;
+
+ // Normally, names are a series of length prefixed strings terminated
+ // with a length of 0 (the lengths are u8's < 63).
+ // However, the length can start with a pair of 1 bits and that
+ // means that the next 14 bits are a pointer within the current
+ // packet.
+
+ for(;;) {
+ u8 label_len;
+ if (j >= length) return -1;
+ GET8(label_len);
+ if (!label_len) break;
+ if (label_len & 0xc0) {
+ u8 ptr_low;
+ GET8(ptr_low);
+ if (name_end < 0) name_end = j;
+ j = (((int)label_len & 0x3f) << 8) + ptr_low;
+ if (j < 0 || j >= length) return -1;
+ continue;
+ }
+ if (label_len > 63) return -1;
+ if (cp != name_out) {
+ if (cp + 1 >= end) return -1;
+ *cp++ = '.';
+ }
+ if (cp + label_len >= end) return -1;
+ memcpy(cp, packet + j, label_len);
+ cp += label_len;
+ j += label_len;
+ }
+ if (cp >= end) return -1;
+ *cp = '\0';
+ if (name_end < 0)
+ *idx = j;
+ else
+ *idx = name_end;
+ return 0;
+}
+
// parses a raw packet from the wire
-static void
+static int
reply_parse(u8 *packet, int length) {
int j = 0; // index into packet
u16 _t; // used by the macros
u32 _t32; // used by the macros
+ char tmp_name[256]; // used by the macros
-#define GET32(x) do { if (j + 4 > length) return; memcpy(&_t32, packet + j, 4); j += 4; x = ntohl(_t32); } while(0);
-#define GET16(x) do { if (j + 2 > length) return; memcpy(&_t, packet + j, 2); j += 2; x = ntohs(_t); } while(0);
-#define GET8(x) do { if (j >= length) return; x = packet[j++]; } while(0);
u16 trans_id, flags, questions, answers, authority, additional, datalength;
u32 ttl, ttl_r = 0xffffffff;
- u32 addresses[MAX_ADDRS];
- int addresses_done = 0;
- uint i;
+ struct reply reply;
+ struct request *req;
+ unsigned int i;
GET16(trans_id);
GET16(flags);
GET16(authority);
GET16(additional);
- if (!(flags & 0x8000)) return; // must be an answer
+ req = request_find_from_trans_id(trans_id);
+ if (!req) return -1;
+ // XXXX should the other return points also call reply_handle? -NM
+
+ memset(&reply, 0, sizeof(reply));
+
+ if (!(flags & 0x8000)) return -1; // must be an answer
if (flags & 0x020f) {
// there was an error
- reply_handle(trans_id, flags, 0, 0, NULL);
- return;
+ reply_handle(req, flags, 0, NULL);
+ return -1;
}
// if (!answers) return; // must have an answer of some form
- // This macro skips a name in the DNS reply. Normally the
- // names are a series of length prefixed strings terminated with
- // a length of 0 (the lengths are u8's < 63).
- // However, the length can start with a pair of 1 bits and that
- // means that the next 14 bits are a pointer within the current
- // packet. The name stops after a pointer like that.
+ // This macro skips a name in the DNS reply.
#define SKIP_NAME \
- for(;;) { \
- u8 label_len; \
- GET8(label_len); \
- if (!label_len) break; \
- if (label_len & 0xc0) { \
- GET8(label_len); \
- break; \
- } \
- if (label_len > 63) return; \
- j += label_len; \
- }
+ do { tmp_name[0] = '\0'; \
+ if (name_parse(packet, length, &j, tmp_name, sizeof(tmp_name))<0) \
+ return -1; \
+ } while(0);
+
+ reply.type = req->request_type;
// skip over each question in the reply
for (i = 0; i < questions; ++i) {
// <label:name><u16:type><u16:class>
SKIP_NAME;
j += 4;
+ if (j >= length) return -1;
}
// now we have the answer section which looks like
GET16(datalength);
if (type == TYPE_A && class == CLASS_INET) {
- const int addrcount = datalength >> 2; // each IP address is 4 bytes
+ int addrcount, addrtocopy;
+ if (req->request_type != TYPE_A) {
+ j += datalength; continue;
+ }
// XXXX do something sane with malformed A answers.
- const int addrtocopy = MIN(MAX_ADDRS - addresses_done, addrcount);
+ addrcount = datalength >> 2;
+ addrtocopy = MIN(MAX_ADDRS - reply.data.a.addrcount, (unsigned)addrcount);
ttl_r = MIN(ttl_r, ttl);
// we only bother with the first four addresses.
- if (j + 4*addrtocopy > length) return;
- memcpy(&addresses[addresses_done], packet + j, 4*addrtocopy);
+ if (j + 4*addrtocopy > length) return -1;
+ memcpy(&reply.data.a.addresses[reply.data.a.addrcount],
+ packet + j, 4*addrtocopy);
j += 4*addrtocopy;
- addresses_done += addrtocopy;
- if (addresses_done == MAX_ADDRS) break;
+ reply.data.a.addrcount += addrtocopy;
+ reply.have_answer = 1;
+ if (reply.data.a.addrcount == MAX_ADDRS) break;
+ } else if (type == TYPE_PTR && class == CLASS_INET) {
+ if (req->request_type != TYPE_PTR) {
+ j += datalength; continue;
+ }
+ if (name_parse(packet, length, &j, reply.data.ptr.name,
+ sizeof(reply.data.ptr.name))<0)
+ return -1;
+ reply.have_answer = 1;
+ break;
} else {
// skip over any other type of resource
j += datalength;
}
}
- reply_handle(trans_id, flags, ttl_r, addresses_done, addresses);
+ reply_handle(req, flags, ttl_r, &reply);
+ return 0;
#undef SKIP_NAME
#undef GET32
#undef GET16
for (;;) {
const int r = recv(ns->socket, packet, sizeof(packet), 0);
if (r < 0) {
- int err = last_error(ns_socket);
+ int err = last_error(ns->socket);
if (error_is_eagain(err)) return;
nameserver_failed(ns, strerror(err));
return;
event_set(&ns->event, ns->socket, EV_READ | (waiting ? EV_WRITE : 0) | EV_PERSIST,
nameserver_ready_callback, ns);
if (event_add(&ns->event, NULL) < 0) {
- log("Error from libevent when adding event for %s",
+ log(EVDNS_LOG_WARN, "Error from libevent when adding event for %s",
debug_ntoa(ns->address));
// ???? Do more?
}
// -1 label was > 63 bytes
// -2 name was > 255 bytes
static int
-dnsname_to_labels(u8 *const buf, const char *name, const int name_len) { \
- const char *end = name + name_len; \
+dnsname_to_labels(u8 *const buf, const char *name, const int name_len) {
+ const char *end = name + name_len;
int j = 0; // current offset into buf
if (name_len > 255) return -2;
const char *const start = name;
name = strchr(name, '.');
if (!name) {
- const uint label_len = end - start;
+ const unsigned int label_len = end - start;
if (label_len > 63) return -1;
buf[j++] = label_len;
break;
} else {
// append length of the label.
- const uint label_len = name - start;
+ const unsigned int label_len = name - start;
if (label_len > 63) return -1;
buf[j++] = label_len;
// Returns the amount of space used. Negative on error.
static int
evdns_request_data_build(const char *const name, const int name_len,
- const u16 trans_id, const u16 type, const u16 class,
+ const u16 trans_id, const u16 type, const u16 class,
u8 *const buf, size_t buf_len) {
int j = 0; // current offset into buf
u16 _t; // used by the macros
free(labels);
return (labels_len);
}
- if (j + labels_len > buf_len) {
+ if ((size_t)(j + labels_len) > buf_len) {
free(labels);
return (-1);
}
(void) fd;
(void) events;
- log("Request %lx timed out", (unsigned long) arg);
+ log(EVDNS_LOG_DEBUG, "Request %lx timed out", (unsigned long) arg);
req->ns->timedout++;
if (req->ns->timedout > global_max_nameserver_timeout) {
(void) evtimer_del(&req->timeout_event);
if (req->tx_count >= global_max_retransmits) {
// this request has failed
- req->user_callback(DNS_ERR_TIMEOUT, 0, 0, 0, NULL, req->user_pointer);
+ reply_callback(req, 0, DNS_ERR_TIMEOUT, NULL);
request_finished(req, &req_head);
} else {
// retransmit it
// fall through
default:
// all ok
- log("Setting timeout for request %lx", (unsigned long) req);
+ log(EVDNS_LOG_DEBUG,
+ "Setting timeout for request %lx", (unsigned long) req);
evtimer_set(&req->timeout_event, evdns_request_timeout_callback, req);
if (evtimer_add(&req->timeout_event, &global_timeout) < 0) {
- log("Error from libevent when adding timer for request %lx",
+ log(EVDNS_LOG_WARN,
+ "Error from libevent when adding timer for request %lx",
(unsigned long) req);
// ???? Do more?
}
// here we need to send a probe to a given nameserver
// in the hope that it is up now.
- log("Sending probe to %s", debug_ntoa(ns->address));
+ log(EVDNS_LOG_DEBUG, "Sending probe to %s", debug_ntoa(ns->address));
- req = request_new("www.google.com", DNS_QUERY_NO_SEARCH, nameserver_probe_callback, ns);
+ req = request_new(TYPE_A, "www.google.com", DNS_QUERY_NO_SEARCH, nameserver_probe_callback, ns);
if (!req) return;
// we force this into the inflight queue no matter what
request_trans_id_set(req, transaction_id_pick());
goto out2;
}
- log("Added nameserver %s", debug_ntoa(address));
+ log(EVDNS_LOG_DEBUG, "Added nameserver %s", debug_ntoa(address));
// insert this nameserver into the list of them
if (!server_head) {
CLOSE_SOCKET(ns->socket);
out1:
free(ns);
- log("Unable to add nameserver %s: error %d", debug_ntoa(address), err);
+ log(EVDNS_LOG_WARN, "Unable to add nameserver %s: error %d", debug_ntoa(address), err);
return err;
}
}
static struct request *
-request_new(const char *name, int flags,
- evdns_callback_type callback, void *ptr) {
+request_new(int type, const char *name, int flags,
+ evdns_callback_type callback, void *user_ptr) {
const char issuing_now =
(global_requests_inflight < global_max_requests_inflight) ? 1 : 0;
// denotes that the request data shouldn't be free()ed
req->request_appended = 1;
rlen = evdns_request_data_build(name, name_len, trans_id,
- TYPE_A, CLASS_INET, req->request, request_max_len);
+ type, CLASS_INET, req->request, request_max_len);
if (rlen < 0)
goto err1;
req->request_len = rlen;
req->trans_id = trans_id;
req->tx_count = 0;
- req->user_pointer = ptr;
+ req->request_type = type;
+ req->user_pointer = user_ptr;
req->user_callback = callback;
req->ns = issuing_now ? nameserver_pick() : NULL;
req->next = req->prev = NULL;
return req;
err1:
- free(req->request);
+ free(req);
return NULL;
}
}
// exported function
-int evdns_resolve(const char *name, int flags,
+int evdns_resolve_ipv4(const char *name, int flags,
evdns_callback_type callback, void *ptr) {
- log("Resolve requested for %s", name);
+ log(EVDNS_LOG_DEBUG, "Resolve requested for %s", name);
if (flags & DNS_QUERY_NO_SEARCH) {
struct request *const req =
- request_new(name, flags, callback, ptr);
+ request_new(TYPE_A, name, flags, callback, ptr);
if (req == NULL)
return (1);
request_submit(req);
return (0);
} else {
- return (search_request_new(name, flags, callback, ptr));
+ return (search_request_new(TYPE_A, name, flags, callback, ptr));
}
}
+int evdns_resolve_reverse(struct in_addr *in, int flags, evdns_callback_type callback, void *ptr) {
+ char buf[32];
+ struct request *req;
+ u32 a;
+ assert(in);
+ a = ntohl(in->s_addr);
+ sprintf(buf, "%d.%d.%d.%d.in-addr.arpa",
+ (int)(u8)((a )&0xff),
+ (int)(u8)((a>>8 )&0xff),
+ (int)(u8)((a>>16)&0xff),
+ (int)(u8)((a>>24)&0xff));
+ log(EVDNS_LOG_DEBUG, "Resolve requested for %s (reverse)", buf);
+ req = request_new(TYPE_PTR, buf, flags, callback, ptr);
+ if (!req) return 1;
+ request_submit(req);
+ return 0;
+}
+
/////////////////////////////////////////////////////////////////////
// Search support
//
}
free(state);
}
-};
+}
static struct search_state *
search_state_new(void) {
}
static int
-search_request_new(const char *const name, int flags, evdns_callback_type user_callback, void *user_arg) {
+search_request_new(int type, const char *const name, int flags, evdns_callback_type user_callback, void *user_arg) {
+ assert(type == TYPE_A);
if ( ((flags & DNS_QUERY_NO_SEARCH) == 0) &&
global_search_state &&
global_search_state->num_domains) {
// we have some domains to search
struct request *req;
if (string_num_dots(name) >= global_search_state->ndots) {
- req = request_new(name, flags, user_callback, user_arg);
+ req = request_new(type, name, flags, user_callback, user_arg);
if (!req) return 1;
req->search_index = -1;
} else {
char *const new_name = search_make_new(global_search_state, 0, name);
if (!new_name) return 1;
- req = request_new(new_name, flags, user_callback, user_arg);
+ req = request_new(type, new_name, flags, user_callback, user_arg);
free(new_name);
if (!req) return 1;
req->search_index = 0;
request_submit(req);
return 0;
} else {
- struct request *const req = request_new(name, flags, user_callback, user_arg);
+ struct request *const req = request_new(type, name, flags, user_callback, user_arg);
if (!req) return 1;
request_submit(req);
return 0;
// this name without a postfix
if (string_num_dots(req->search_origname) < req->search_state->ndots) {
// yep, we need to try it raw
- struct request *const newreq = request_new(req->search_origname, req->search_flags, req->user_callback, req->user_pointer);
- log("Search: trying raw query %s", req->search_origname);
+ struct request *const newreq = request_new(req->request_type, req->search_origname, req->search_flags, req->user_callback, req->user_pointer);
+ log(EVDNS_LOG_DEBUG, "Search: trying raw query %s", req->search_origname);
if (newreq) {
request_submit(newreq);
return 0;
new_name = search_make_new(req->search_state, req->search_index, req->search_origname);
if (!new_name) return 1;
- log("Search: now trying %s (%d)", new_name, req->search_index);
- newreq = request_new(new_name, req->search_flags, req->user_callback, req->user_pointer);
+ log(EVDNS_LOG_DEBUG, "Search: now trying %s (%d)", new_name, req->search_index);
+ newreq = request_new(req->request_type, new_name, req->search_flags, req->user_callback, req->user_pointer);
free(new_name);
if (!newreq) return 1;
newreq->search_origname = req->search_origname;
const int ndots = strtoint(&option[6]);
if (ndots == -1) continue;
if (!(flags & DNS_OPTION_SEARCH)) continue;
- log("Setting ndots to %d", ndots);
+ log(EVDNS_LOG_DEBUG, "Setting ndots to %d", ndots);
if (!global_search_state) global_search_state = search_state_new();
if (!global_search_state) return;
global_search_state->ndots = ndots;
const int timeout = strtoint(&option[8]);
if (timeout == -1) continue;
if (!(flags & DNS_OPTION_MISC)) continue;
- log("Setting timeout to %d", timeout);
+ log(EVDNS_LOG_DEBUG, "Setting timeout to %d", timeout);
global_timeout.tv_sec = timeout;
} else if (!strncmp(option, "attempts:", 9)) {
- const int retries = strtoint(&option[9]);
+ int retries = strtoint(&option[9]);
if (retries == -1) continue;
+ if (retries > 255) retries = 255;
if (!(flags & DNS_OPTION_MISC)) continue;
- log("Setting retries to %d", retries);
+ log(EVDNS_LOG_DEBUG, "Setting retries to %d", retries);
global_max_retransmits = retries;
}
}
char *start;
int err = 0;
- log("Parsing resolve.conf file %s", filename);
+ log(EVDNS_LOG_DEBUG, "Parsing resolv.conf file %s", filename);
fd = open(filename, O_RDONLY);
if (fd < 0) {
return 0;
}
+typedef DWORD(WINAPI *GetNetworkParams_fn_t)(FIXED_INFO *, DWORD*);
+
// Use the windows GetNetworkParams interface in iphlpapi.dll to
// figure out what our nameservers are.
static int
void *buf = NULL;
int status = 0, r, added_any;
IP_ADDR_STRING *ns;
- DWORD (WINAPI *fn)(FIXED_INFO*, DWORD*);
+ GetNetworkParams_fn_t fn;
- if (!(handle = LoadLibrary("iphlpapi.dll")))
+ if (!(handle = LoadLibrary("iphlpapi.dll"))) {
+ log(EVDNS_LOG_WARN, "Could not open iphlpapi.dll");
+ status = -1;
goto done;
- if (!(fn = GetProcAddress(handle, "GetNetworkParams")))
+ }
+ if (!(fn = (GetNetworkParams_fn_t) GetProcAddress(handle, "GetNetworkParams"))) {
+ log(EVDNS_LOG_WARN, "Could not get address of function.");
+ status = -1;
goto done;
+ }
buf = malloc(size);
if (!buf) { status = 4; goto done; }
if (!buf) { status = 4; goto done; }
fixed = buf;
r = fn(fixed, &size);
- if (r != ERROR_SUCCESS) { status = -1; goto done; }
+ if (r != ERROR_SUCCESS) {
+ log(EVDNS_LOG_DEBUG, "fn() failed.");
+ status = -1;
+ goto done;
+ }
}
assert(fixed);
added_any = 0;
- ns = fixed->DnsServerList;
+ ns = &(fixed->DnsServerList);
while (ns) {
r = evdns_nameserver_ip_add_line(ns->IpAddress.String);
- if (r) { status = r; goto done; }
- added_any = 0;
- ns = ns->next;
+ if (r) {
+ log(EVDNS_LOG_DEBUG,"Could not add nameserver %s to list,error: %d",
+ (ns->IpAddress.String),(int)GetLastError());
+ status = r;
+ goto done;
+ } else {
+ log(EVDNS_LOG_DEBUG,"Succesfully added %s as nameserver",ns->IpAddress.String);
+ }
+
+ added_any++;
+ ns = ns->Next;
}
- if (!added_any)
+ if (!added_any) {
+ log(EVDNS_LOG_DEBUG, "No nameservers added.");
status = -1;
+ }
done:
if (buf)
return status;
}
+#define SERVICES_KEY "System\\CurrentControlSet\\Services\\"
+#define WIN_NS_9X_KEY SERVICES_KEY "VxD\\MSTCP"
+#define WIN_NS_NT_KEY SERVICES_KEY "Tcpip\\Parameters"
+
static int
load_nameservers_from_registry(void)
{
int found = 0;
+ int r;
#define TRY(k, name) \
if (!found && config_nameserver_from_reg_key(k,name) == 0) { \
- log("Found nameservers in %s/%s",#k,name); \
+ log(EVDNS_LOG_DEBUG,"Found nameservers in %s/%s",#k,name); \
found = 1; \
+ } else if (!found) { \
+ log(EVDNS_LOG_DEBUG,"Didn't find nameservers in %s/%s", \
+ #k,#name); \
}
- if (IS_NT()) {
+ if (((int)GetVersion()) > 0) { /* NT */
HKEY nt_key = 0, interfaces_key = 0;
if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, WIN_NS_NT_KEY, 0,
- KEY_READ, &nt_key) != ERROR_SUCCESS)
+ KEY_READ, &nt_key) != ERROR_SUCCESS) {
+ log(EVDNS_LOG_DEBUG,"Couldn't open nt key, %d",(int)GetLastError());
return -1;
- RegOpenKeyEx(nt_key, "Interfaces", 0,
- KEY_QUERY_VALUE|KEY_ENUMERATE_SUBKEYS,
+ }
+ r = RegOpenKeyEx(nt_key, "Interfaces", 0,
+ KEY_QUERY_VALUE|KEY_ENUMERATE_SUB_KEYS,
&interfaces_key);
- TRY(nt_key, NAMESERVER);
- TRY(nt_key, DHCPNAMESERVER);
- TRY(interfaces_key, NAMESERVER);
- TRY(interfaces_key, DHCPNAMESERVER);
+ if (r != ERROR_SUCCESS) {
+ log(EVDNS_LOG_DEBUG,"Couldn't open interfaces key, %d",(int)GetLastError());
+ return -1;
+ }
+ TRY(nt_key, "NameServer");
+ TRY(nt_key, "DhcpNameServer");
+ TRY(interfaces_key, "NameServer");
+ TRY(interfaces_key, "DhcpNameServer");
RegCloseKey(interfaces_key);
RegCloseKey(nt_key);
} else {
HKEY win_key = 0;
- if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, WIN_NS_9X, 0,
- KEY_READ, &win_key) != ERROR_SUCCESS)
+ if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, WIN_NS_9X_KEY, 0,
+ KEY_READ, &win_key) != ERROR_SUCCESS) {
+ log(EVDNS_LOG_DEBUG, "Couldn't open registry key, %d", (int)GetLastError());
return -1;
- TRY(win_key, NAMESERVER);
+ }
+ TRY(win_key, "NameServer");
RegCloseKey(win_key);
}
+
+ if (found == 0) {
+ log(EVDNS_LOG_WARN,"Didn't find any nameservers.");
+ }
+
return found ? 0 : -1;
#undef TRY
}
return (res);
}
+
+const char *
+evdns_err_to_string(int err)
+{
+ switch (err) {
+ case DNS_ERR_NONE: return "no error";
+ case DNS_ERR_FORMAT: return "misformatted query";
+ case DNS_ERR_SERVERFAILED: return "server failed";
+ case DNS_ERR_NOTEXIST: return "name does not exist";
+ case DNS_ERR_NOTIMPL: return "query not implemented";
+ case DNS_ERR_REFUSED: return "refused";
+
+ case DNS_ERR_TRUNCATED: return "reply truncated or ill-formed";
+ case DNS_ERR_UNKNOWN: return "unknown";
+ case DNS_ERR_TIMEOUT: return "request timed out";
+ case DNS_ERR_SHUTDOWN: return "dns subsystem shut down";
+ default: return "[Unknown error code]";
+ }
+}
+
+void
+evdns_shutdown(int fail_requests)
+{
+ struct nameserver *server, *server_next;
+ struct search_domain *dom, *dom_next;
+
+ while (req_head) {
+ if (fail_requests)
+ reply_callback(req_head, 0, DNS_ERR_SHUTDOWN, NULL);
+ request_finished(req_head, &req_head);
+ }
+ while (req_waiting_head) {
+ if (fail_requests)
+ reply_callback(req_waiting_head, 0, DNS_ERR_SHUTDOWN, NULL);
+ request_finished(req_waiting_head, &req_waiting_head);
+ }
+ global_requests_inflight = global_requests_waiting = 0;
+
+ for (server = server_head; server; server = server_next) {
+ server_next = server->next;
+ if (server->socket >= 0)
+ CLOSE_SOCKET(server->socket);
+ (void) event_del(&server->event);
+ free(server);
+ if (server_next == server_head)
+ break;
+ }
+ server_head = NULL;
+ global_good_nameservers = 0;
+
+ if (global_search_state) {
+ for (dom = global_search_state->head; dom; dom = dom_next) {
+ dom_next = dom->next;
+ free(dom);
+ }
+ free(global_search_state);
+ global_search_state = NULL;
+ }
+ evdns_log_fn = NULL;
+}
+
+#ifdef EVDNS_MAIN
+void
+main_callback(int result, char type, int count, int ttl,
+ void *addrs, void *orig) {
+ char *n = (char*)orig;
+ int i;
+ for (i = 0; i < count; ++i) {
+ if (type == DNS_IPv4_A) {
+ printf("%s: %s\n", n, debug_ntoa(((u32*)addrs)[i]));
+ } else if (type == DNS_PTR) {
+ printf("%s: %s\n", n, ((char**)addrs)[i]);
+ }
+ }
+ if (!count) {
+ printf("%s: No answer (%d)\n", n, result);
+ }
+ fflush(stdout);
+}
+
+void
+logfn(const char *msg) {
+ fprintf(stderr, "%s\n", msg);
+}
+int
+main(int c, char **v) {
+ int idx;
+ int reverse = 0, verbose = 1;
+ if (c<2) {
+ fprintf(stderr, "syntax: %s [-x] [-v] hostname\n", v[0]);
+ return 1;
+ }
+ idx = 1;
+ while (idx < c && v[idx][0] == '-') {
+ if (!strcmp(v[idx], "-x"))
+ reverse = 1;
+ else if (!strcmp(v[idx], "-v"))
+ verbose = 1;
+ else
+ fprintf(stderr, "Unknown option %s\n", v[idx]);
+ ++idx;
+ }
+ event_init();
+ if (verbose)
+ evdns_set_log_fn(logfn);
+ evdns_resolv_conf_parse(DNS_OPTION_NAMESERVERS, "/etc/resolv.conf");
+ for (; idx < c; ++idx) {
+ if (reverse) {
+ struct in_addr addr;
+ if (!inet_aton(v[idx], &addr)) {
+ fprintf(stderr, "Skipping non-IP %s\n", v[idx]);
+ continue;
+ }
+ fprintf(stderr, "resolving %s...\n",v[idx]);
+ evdns_resolve_reverse(&addr, 0, main_callback, v[idx]);
+ } else {
+ fprintf(stderr, "resolving (fwd) %s...\n",v[idx]);
+ evdns_resolve_ipv4(v[idx], 0, main_callback, v[idx]);
+ }
+ }
+ fflush(stdout);
+ event_dispatch();
+ return 0;
+}
+#endif