michael@0: /* Copyright 2006-2007 Niels Provos michael@0: * Copyright 2007-2012 Nick Mathewson and Niels Provos michael@0: * michael@0: * Redistribution and use in source and binary forms, with or without michael@0: * modification, are permitted provided that the following conditions michael@0: * are met: michael@0: * 1. Redistributions of source code must retain the above copyright michael@0: * notice, this list of conditions and the following disclaimer. michael@0: * 2. Redistributions in binary form must reproduce the above copyright michael@0: * notice, this list of conditions and the following disclaimer in the michael@0: * documentation and/or other materials provided with the distribution. michael@0: * 3. The name of the author may not be used to endorse or promote products michael@0: * derived from this software without specific prior written permission. michael@0: * michael@0: * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR michael@0: * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES michael@0: * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. michael@0: * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, michael@0: * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT michael@0: * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, michael@0: * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY michael@0: * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT michael@0: * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF michael@0: * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. michael@0: */ michael@0: michael@0: /* Based on software by Adam Langly. Adam's original message: michael@0: * michael@0: * Async DNS Library michael@0: * Adam Langley michael@0: * http://www.imperialviolet.org/eventdns.html michael@0: * Public Domain code michael@0: * michael@0: * This software is Public Domain. To view a copy of the public domain dedication, michael@0: * visit http://creativecommons.org/licenses/publicdomain/ or send a letter to michael@0: * Creative Commons, 559 Nathan Abbott Way, Stanford, California 94305, USA. michael@0: * michael@0: * I ask and expect, but do not require, that all derivative works contain an michael@0: * attribution similar to: michael@0: * Parts developed by Adam Langley michael@0: * michael@0: * You may wish to replace the word "Parts" with something else depending on michael@0: * the amount of original code. michael@0: * michael@0: * (Derivative works does not include programs which link against, run or include michael@0: * the source verbatim in their source distributions) michael@0: * michael@0: * Version: 0.1b michael@0: */ michael@0: michael@0: #include michael@0: #include "event2/event-config.h" michael@0: michael@0: #ifndef _FORTIFY_SOURCE michael@0: #define _FORTIFY_SOURCE 3 michael@0: #endif michael@0: michael@0: #include michael@0: #include michael@0: #ifdef _EVENT_HAVE_SYS_TIME_H michael@0: #include michael@0: #endif michael@0: #ifdef _EVENT_HAVE_STDINT_H michael@0: #include michael@0: #endif michael@0: #include michael@0: #include michael@0: #include michael@0: #ifdef _EVENT_HAVE_UNISTD_H michael@0: #include michael@0: #endif michael@0: #include michael@0: #include michael@0: #include michael@0: #include michael@0: #ifdef WIN32 michael@0: #include michael@0: #include michael@0: #ifndef _WIN32_IE michael@0: #define _WIN32_IE 0x400 michael@0: #endif michael@0: #include michael@0: #endif michael@0: michael@0: #include "event2/dns.h" michael@0: #include "event2/dns_struct.h" michael@0: #include "event2/dns_compat.h" michael@0: #include "event2/util.h" michael@0: #include "event2/event.h" michael@0: #include "event2/event_struct.h" michael@0: #include "event2/thread.h" michael@0: michael@0: #include "event2/bufferevent.h" michael@0: #include "event2/bufferevent_struct.h" michael@0: #include "bufferevent-internal.h" michael@0: michael@0: #include "defer-internal.h" michael@0: #include "log-internal.h" michael@0: #include "mm-internal.h" michael@0: #include "strlcpy-internal.h" michael@0: #include "ipv6-internal.h" michael@0: #include "util-internal.h" michael@0: #include "evthread-internal.h" michael@0: #ifdef WIN32 michael@0: #include michael@0: #include michael@0: #include michael@0: #include michael@0: #include michael@0: #else michael@0: #include michael@0: #include michael@0: #include michael@0: #endif michael@0: michael@0: #ifdef _EVENT_HAVE_NETINET_IN6_H michael@0: #include michael@0: #endif michael@0: michael@0: #define EVDNS_LOG_DEBUG 0 michael@0: #define EVDNS_LOG_WARN 1 michael@0: #define EVDNS_LOG_MSG 2 michael@0: michael@0: #ifndef HOST_NAME_MAX michael@0: #define HOST_NAME_MAX 255 michael@0: #endif michael@0: michael@0: #include michael@0: michael@0: #undef MIN michael@0: #define MIN(a,b) ((a)<(b)?(a):(b)) michael@0: michael@0: #define ASSERT_VALID_REQUEST(req) \ michael@0: EVUTIL_ASSERT((req)->handle && (req)->handle->current_req == (req)) michael@0: michael@0: #define u64 ev_uint64_t michael@0: #define u32 ev_uint32_t michael@0: #define u16 ev_uint16_t michael@0: #define u8 ev_uint8_t michael@0: michael@0: /* maximum number of addresses from a single packet */ michael@0: /* that we bother recording */ michael@0: #define MAX_V4_ADDRS 32 michael@0: #define MAX_V6_ADDRS 32 michael@0: michael@0: michael@0: #define TYPE_A EVDNS_TYPE_A michael@0: #define TYPE_CNAME 5 michael@0: #define TYPE_PTR EVDNS_TYPE_PTR michael@0: #define TYPE_SOA EVDNS_TYPE_SOA michael@0: #define TYPE_AAAA EVDNS_TYPE_AAAA michael@0: michael@0: #define CLASS_INET EVDNS_CLASS_INET michael@0: michael@0: /* Persistent handle. We keep this separate from 'struct request' since we michael@0: * need some object to last for as long as an evdns_request is outstanding so michael@0: * that it can be canceled, whereas a search request can lead to multiple michael@0: * 'struct request' instances being created over its lifetime. */ michael@0: struct evdns_request { michael@0: struct request *current_req; michael@0: struct evdns_base *base; michael@0: michael@0: int pending_cb; /* Waiting for its callback to be invoked; not michael@0: * owned by event base any more. */ michael@0: michael@0: /* elements used by the searching code */ michael@0: int search_index; michael@0: struct search_state *search_state; michael@0: char *search_origname; /* needs to be free()ed */ michael@0: int search_flags; michael@0: }; michael@0: michael@0: struct request { michael@0: u8 *request; /* the dns packet data */ michael@0: u8 request_type; /* TYPE_PTR or TYPE_A or TYPE_AAAA */ michael@0: unsigned int request_len; michael@0: int reissue_count; michael@0: int tx_count; /* the number of times that this packet has been sent */ michael@0: void *user_pointer; /* the pointer given to us for this request */ michael@0: evdns_callback_type user_callback; michael@0: struct nameserver *ns; /* the server which we last sent it */ michael@0: michael@0: /* these objects are kept in a circular list */ michael@0: /* XXX We could turn this into a CIRCLEQ. */ michael@0: struct request *next, *prev; michael@0: michael@0: struct event timeout_event; michael@0: michael@0: u16 trans_id; /* the transaction id */ michael@0: unsigned request_appended :1; /* true if the request pointer is data which follows this struct */ michael@0: unsigned transmit_me :1; /* needs to be transmitted */ michael@0: michael@0: /* XXXX This is a horrible hack. */ michael@0: char **put_cname_in_ptr; /* store the cname here if we get one. */ michael@0: michael@0: struct evdns_base *base; michael@0: michael@0: struct evdns_request *handle; michael@0: }; michael@0: michael@0: struct reply { michael@0: unsigned int type; michael@0: unsigned int have_answer : 1; michael@0: union { michael@0: struct { michael@0: u32 addrcount; michael@0: u32 addresses[MAX_V4_ADDRS]; michael@0: } a; michael@0: struct { michael@0: u32 addrcount; michael@0: struct in6_addr addresses[MAX_V6_ADDRS]; michael@0: } aaaa; michael@0: struct { michael@0: char name[HOST_NAME_MAX]; michael@0: } ptr; michael@0: } data; michael@0: }; michael@0: michael@0: struct nameserver { michael@0: evutil_socket_t socket; /* a connected UDP socket */ michael@0: struct sockaddr_storage address; michael@0: ev_socklen_t addrlen; michael@0: int failed_times; /* number of times which we have given this server a chance */ michael@0: int timedout; /* number of times in a row a request has timed out */ michael@0: struct event event; michael@0: /* these objects are kept in a circular list */ michael@0: struct nameserver *next, *prev; michael@0: struct event timeout_event; /* used to keep the timeout for */ michael@0: /* when we next probe this server. */ michael@0: /* Valid if state == 0 */ michael@0: /* Outstanding probe request for this nameserver, if any */ michael@0: struct evdns_request *probe_request; michael@0: char state; /* zero if we think that this server is down */ michael@0: char choked; /* true if we have an EAGAIN from this server's socket */ michael@0: char write_waiting; /* true if we are waiting for EV_WRITE events */ michael@0: struct evdns_base *base; michael@0: }; michael@0: michael@0: michael@0: /* Represents a local port where we're listening for DNS requests. Right now, */ michael@0: /* only UDP is supported. */ michael@0: struct evdns_server_port { michael@0: evutil_socket_t socket; /* socket we use to read queries and write replies. */ michael@0: int refcnt; /* reference count. */ michael@0: char choked; /* Are we currently blocked from writing? */ michael@0: char closing; /* Are we trying to close this port, pending writes? */ michael@0: evdns_request_callback_fn_type user_callback; /* Fn to handle requests */ michael@0: void *user_data; /* Opaque pointer passed to user_callback */ michael@0: struct event event; /* Read/write event */ michael@0: /* circular list of replies that we want to write. */ michael@0: struct server_request *pending_replies; michael@0: struct event_base *event_base; michael@0: michael@0: #ifndef _EVENT_DISABLE_THREAD_SUPPORT michael@0: void *lock; michael@0: #endif michael@0: }; michael@0: michael@0: /* Represents part of a reply being built. (That is, a single RR.) */ michael@0: struct server_reply_item { michael@0: struct server_reply_item *next; /* next item in sequence. */ michael@0: char *name; /* name part of the RR */ michael@0: u16 type; /* The RR type */ michael@0: u16 class; /* The RR class (usually CLASS_INET) */ michael@0: u32 ttl; /* The RR TTL */ michael@0: char is_name; /* True iff data is a label */ michael@0: u16 datalen; /* Length of data; -1 if data is a label */ michael@0: void *data; /* The contents of the RR */ michael@0: }; michael@0: michael@0: /* Represents a request that we've received as a DNS server, and holds */ michael@0: /* the components of the reply as we're constructing it. */ michael@0: struct server_request { michael@0: /* Pointers to the next and previous entries on the list of replies */ michael@0: /* that we're waiting to write. Only set if we have tried to respond */ michael@0: /* and gotten EAGAIN. */ michael@0: struct server_request *next_pending; michael@0: struct server_request *prev_pending; michael@0: michael@0: u16 trans_id; /* Transaction id. */ michael@0: struct evdns_server_port *port; /* Which port received this request on? */ michael@0: struct sockaddr_storage addr; /* Where to send the response */ michael@0: ev_socklen_t addrlen; /* length of addr */ michael@0: michael@0: int n_answer; /* how many answer RRs have been set? */ michael@0: int n_authority; /* how many authority RRs have been set? */ michael@0: int n_additional; /* how many additional RRs have been set? */ michael@0: michael@0: struct server_reply_item *answer; /* linked list of answer RRs */ michael@0: struct server_reply_item *authority; /* linked list of authority RRs */ michael@0: struct server_reply_item *additional; /* linked list of additional RRs */ michael@0: michael@0: /* Constructed response. Only set once we're ready to send a reply. */ michael@0: /* Once this is set, the RR fields are cleared, and no more should be set. */ michael@0: char *response; michael@0: size_t response_len; michael@0: michael@0: /* Caller-visible fields: flags, questions. */ michael@0: struct evdns_server_request base; michael@0: }; michael@0: michael@0: struct evdns_base { michael@0: /* An array of n_req_heads circular lists for inflight requests. michael@0: * Each inflight request req is in req_heads[req->trans_id % n_req_heads]. michael@0: */ michael@0: struct request **req_heads; michael@0: /* A circular list of requests that we're waiting to send, but haven't michael@0: * sent yet because there are too many requests inflight */ michael@0: struct request *req_waiting_head; michael@0: /* A circular list of nameservers. */ michael@0: struct nameserver *server_head; michael@0: int n_req_heads; michael@0: michael@0: struct event_base *event_base; michael@0: michael@0: /* The number of good nameservers that we have */ michael@0: int global_good_nameservers; michael@0: michael@0: /* inflight requests are contained in the req_head list */ michael@0: /* and are actually going out across the network */ michael@0: int global_requests_inflight; michael@0: /* requests which aren't inflight are in the waiting list */ michael@0: /* and are counted here */ michael@0: int global_requests_waiting; michael@0: michael@0: int global_max_requests_inflight; michael@0: michael@0: struct timeval global_timeout; /* 5 seconds by default */ michael@0: int global_max_reissues; /* a reissue occurs when we get some errors from the server */ michael@0: int global_max_retransmits; /* number of times we'll retransmit a request which timed out */ michael@0: /* number of timeouts in a row before we consider this server to be down */ michael@0: int global_max_nameserver_timeout; michael@0: /* true iff we will use the 0x20 hack to prevent poisoning attacks. */ michael@0: int global_randomize_case; michael@0: michael@0: /* The first time that a nameserver fails, how long do we wait before michael@0: * probing to see if it has returned? */ michael@0: struct timeval global_nameserver_probe_initial_timeout; michael@0: michael@0: /** Port to bind to for outgoing DNS packets. */ michael@0: struct sockaddr_storage global_outgoing_address; michael@0: /** ev_socklen_t for global_outgoing_address. 0 if it isn't set. */ michael@0: ev_socklen_t global_outgoing_addrlen; michael@0: michael@0: struct timeval global_getaddrinfo_allow_skew; michael@0: michael@0: int getaddrinfo_ipv4_timeouts; michael@0: int getaddrinfo_ipv6_timeouts; michael@0: int getaddrinfo_ipv4_answered; michael@0: int getaddrinfo_ipv6_answered; michael@0: michael@0: struct search_state *global_search_state; michael@0: michael@0: TAILQ_HEAD(hosts_list, hosts_entry) hostsdb; michael@0: michael@0: #ifndef _EVENT_DISABLE_THREAD_SUPPORT michael@0: void *lock; michael@0: #endif michael@0: }; michael@0: michael@0: struct hosts_entry { michael@0: TAILQ_ENTRY(hosts_entry) next; michael@0: union { michael@0: struct sockaddr sa; michael@0: struct sockaddr_in sin; michael@0: struct sockaddr_in6 sin6; michael@0: } addr; michael@0: int addrlen; michael@0: char hostname[1]; michael@0: }; michael@0: michael@0: static struct evdns_base *current_base = NULL; michael@0: michael@0: struct evdns_base * michael@0: evdns_get_global_base(void) michael@0: { michael@0: return current_base; michael@0: } michael@0: michael@0: /* Given a pointer to an evdns_server_request, get the corresponding */ michael@0: /* server_request. */ michael@0: #define TO_SERVER_REQUEST(base_ptr) \ michael@0: ((struct server_request*) \ michael@0: (((char*)(base_ptr) - evutil_offsetof(struct server_request, base)))) michael@0: michael@0: #define REQ_HEAD(base, id) ((base)->req_heads[id % (base)->n_req_heads]) michael@0: michael@0: static struct nameserver *nameserver_pick(struct evdns_base *base); michael@0: static void evdns_request_insert(struct request *req, struct request **head); michael@0: static void evdns_request_remove(struct request *req, struct request **head); michael@0: static void nameserver_ready_callback(evutil_socket_t fd, short events, void *arg); michael@0: static int evdns_transmit(struct evdns_base *base); michael@0: static int evdns_request_transmit(struct request *req); michael@0: static void nameserver_send_probe(struct nameserver *const ns); michael@0: static void search_request_finished(struct evdns_request *const); michael@0: static int search_try_next(struct evdns_request *const req); michael@0: static struct request *search_request_new(struct evdns_base *base, struct evdns_request *handle, int type, const char *const name, int flags, evdns_callback_type user_callback, void *user_arg); michael@0: static void evdns_requests_pump_waiting_queue(struct evdns_base *base); michael@0: static u16 transaction_id_pick(struct evdns_base *base); michael@0: static struct request *request_new(struct evdns_base *base, struct evdns_request *handle, int type, const char *name, int flags, evdns_callback_type callback, void *ptr); michael@0: static void request_submit(struct request *const req); michael@0: michael@0: static int server_request_free(struct server_request *req); michael@0: static void server_request_free_answers(struct server_request *req); michael@0: static void server_port_free(struct evdns_server_port *port); michael@0: static void server_port_ready_callback(evutil_socket_t fd, short events, void *arg); michael@0: static int evdns_base_resolv_conf_parse_impl(struct evdns_base *base, int flags, const char *const filename); michael@0: static int evdns_base_set_option_impl(struct evdns_base *base, michael@0: const char *option, const char *val, int flags); michael@0: static void evdns_base_free_and_unlock(struct evdns_base *base, int fail_requests); michael@0: michael@0: static int strtoint(const char *const str); michael@0: michael@0: #ifdef _EVENT_DISABLE_THREAD_SUPPORT michael@0: #define EVDNS_LOCK(base) _EVUTIL_NIL_STMT michael@0: #define EVDNS_UNLOCK(base) _EVUTIL_NIL_STMT michael@0: #define ASSERT_LOCKED(base) _EVUTIL_NIL_STMT michael@0: #else michael@0: #define EVDNS_LOCK(base) \ michael@0: EVLOCK_LOCK((base)->lock, 0) michael@0: #define EVDNS_UNLOCK(base) \ michael@0: EVLOCK_UNLOCK((base)->lock, 0) michael@0: #define ASSERT_LOCKED(base) \ michael@0: EVLOCK_ASSERT_LOCKED((base)->lock) michael@0: #endif michael@0: michael@0: static void michael@0: default_evdns_log_fn(int warning, const char *buf) michael@0: { michael@0: if (warning == EVDNS_LOG_WARN) michael@0: event_warnx("[evdns] %s", buf); michael@0: else if (warning == EVDNS_LOG_MSG) michael@0: event_msgx("[evdns] %s", buf); michael@0: else michael@0: event_debug(("[evdns] %s", buf)); michael@0: } michael@0: michael@0: static evdns_debug_log_fn_type evdns_log_fn = NULL; michael@0: michael@0: void michael@0: evdns_set_log_fn(evdns_debug_log_fn_type fn) michael@0: { michael@0: evdns_log_fn = fn; michael@0: } michael@0: michael@0: #ifdef __GNUC__ michael@0: #define EVDNS_LOG_CHECK __attribute__ ((format(printf, 2, 3))) michael@0: #else michael@0: #define EVDNS_LOG_CHECK michael@0: #endif michael@0: michael@0: static void _evdns_log(int warn, const char *fmt, ...) EVDNS_LOG_CHECK; michael@0: static void michael@0: _evdns_log(int warn, const char *fmt, ...) michael@0: { michael@0: va_list args; michael@0: char buf[512]; michael@0: if (!evdns_log_fn) michael@0: return; michael@0: va_start(args,fmt); michael@0: evutil_vsnprintf(buf, sizeof(buf), fmt, args); michael@0: va_end(args); michael@0: if (evdns_log_fn) { michael@0: if (warn == EVDNS_LOG_MSG) michael@0: warn = EVDNS_LOG_WARN; michael@0: evdns_log_fn(warn, buf); michael@0: } else { michael@0: default_evdns_log_fn(warn, buf); michael@0: } michael@0: michael@0: } michael@0: michael@0: #define log _evdns_log michael@0: michael@0: /* This walks the list of inflight requests to find the */ michael@0: /* one with a matching transaction id. Returns NULL on */ michael@0: /* failure */ michael@0: static struct request * michael@0: request_find_from_trans_id(struct evdns_base *base, u16 trans_id) { michael@0: struct request *req = REQ_HEAD(base, trans_id); michael@0: struct request *const started_at = req; michael@0: michael@0: ASSERT_LOCKED(base); michael@0: michael@0: if (req) { michael@0: do { michael@0: if (req->trans_id == trans_id) return req; michael@0: req = req->next; michael@0: } while (req != started_at); michael@0: } michael@0: michael@0: return NULL; michael@0: } michael@0: michael@0: /* a libevent callback function which is called when a nameserver */ michael@0: /* has gone down and we want to test if it has came back to life yet */ michael@0: static void michael@0: nameserver_prod_callback(evutil_socket_t fd, short events, void *arg) { michael@0: struct nameserver *const ns = (struct nameserver *) arg; michael@0: (void)fd; michael@0: (void)events; michael@0: michael@0: EVDNS_LOCK(ns->base); michael@0: nameserver_send_probe(ns); michael@0: EVDNS_UNLOCK(ns->base); michael@0: } michael@0: michael@0: /* a libevent callback which is called when a nameserver probe (to see if */ michael@0: /* it has come back to life) times out. We increment the count of failed_times */ michael@0: /* and wait longer to send the next probe packet. */ michael@0: static void michael@0: nameserver_probe_failed(struct nameserver *const ns) { michael@0: struct timeval timeout; michael@0: int i; michael@0: michael@0: ASSERT_LOCKED(ns->base); michael@0: (void) evtimer_del(&ns->timeout_event); michael@0: if (ns->state == 1) { michael@0: /* This can happen if the nameserver acts in a way which makes us mark */ michael@0: /* it as bad and then starts sending good replies. */ michael@0: return; michael@0: } michael@0: michael@0: #define MAX_PROBE_TIMEOUT 3600 michael@0: #define TIMEOUT_BACKOFF_FACTOR 3 michael@0: michael@0: memcpy(&timeout, &ns->base->global_nameserver_probe_initial_timeout, michael@0: sizeof(struct timeval)); michael@0: for (i=ns->failed_times; i > 0 && timeout.tv_sec < MAX_PROBE_TIMEOUT; --i) { michael@0: timeout.tv_sec *= TIMEOUT_BACKOFF_FACTOR; michael@0: timeout.tv_usec *= TIMEOUT_BACKOFF_FACTOR; michael@0: if (timeout.tv_usec > 1000000) { michael@0: timeout.tv_sec += timeout.tv_usec / 1000000; michael@0: timeout.tv_usec %= 1000000; michael@0: } michael@0: } michael@0: if (timeout.tv_sec > MAX_PROBE_TIMEOUT) { michael@0: timeout.tv_sec = MAX_PROBE_TIMEOUT; michael@0: timeout.tv_usec = 0; michael@0: } michael@0: michael@0: ns->failed_times++; michael@0: michael@0: if (evtimer_add(&ns->timeout_event, &timeout) < 0) { michael@0: char addrbuf[128]; michael@0: log(EVDNS_LOG_WARN, michael@0: "Error from libevent when adding timer event for %s", michael@0: evutil_format_sockaddr_port( michael@0: (struct sockaddr *)&ns->address, michael@0: addrbuf, sizeof(addrbuf))); michael@0: } michael@0: } michael@0: michael@0: /* called when a nameserver has been deemed to have failed. For example, too */ michael@0: /* many packets have timed out etc */ michael@0: static void michael@0: nameserver_failed(struct nameserver *const ns, const char *msg) { michael@0: struct request *req, *started_at; michael@0: struct evdns_base *base = ns->base; michael@0: int i; michael@0: char addrbuf[128]; michael@0: michael@0: ASSERT_LOCKED(base); michael@0: /* if this nameserver has already been marked as failed */ michael@0: /* then don't do anything */ michael@0: if (!ns->state) return; michael@0: michael@0: log(EVDNS_LOG_MSG, "Nameserver %s has failed: %s", michael@0: evutil_format_sockaddr_port( michael@0: (struct sockaddr *)&ns->address, michael@0: addrbuf, sizeof(addrbuf)), michael@0: msg); michael@0: michael@0: base->global_good_nameservers--; michael@0: EVUTIL_ASSERT(base->global_good_nameservers >= 0); michael@0: if (base->global_good_nameservers == 0) { michael@0: log(EVDNS_LOG_MSG, "All nameservers have failed"); michael@0: } michael@0: michael@0: ns->state = 0; michael@0: ns->failed_times = 1; michael@0: michael@0: if (evtimer_add(&ns->timeout_event, michael@0: &base->global_nameserver_probe_initial_timeout) < 0) { michael@0: log(EVDNS_LOG_WARN, michael@0: "Error from libevent when adding timer event for %s", michael@0: evutil_format_sockaddr_port( michael@0: (struct sockaddr *)&ns->address, michael@0: addrbuf, sizeof(addrbuf))); michael@0: /* ???? Do more? */ michael@0: } michael@0: michael@0: /* walk the list of inflight requests to see if any can be reassigned to */ michael@0: /* a different server. Requests in the waiting queue don't have a */ michael@0: /* nameserver assigned yet */ michael@0: michael@0: /* if we don't have *any* good nameservers then there's no point */ michael@0: /* trying to reassign requests to one */ michael@0: if (!base->global_good_nameservers) return; michael@0: michael@0: for (i = 0; i < base->n_req_heads; ++i) { michael@0: req = started_at = base->req_heads[i]; michael@0: if (req) { michael@0: do { michael@0: if (req->tx_count == 0 && req->ns == ns) { michael@0: /* still waiting to go out, can be moved */ michael@0: /* to another server */ michael@0: req->ns = nameserver_pick(base); michael@0: } michael@0: req = req->next; michael@0: } while (req != started_at); michael@0: } michael@0: } michael@0: } michael@0: michael@0: static void michael@0: nameserver_up(struct nameserver *const ns) michael@0: { michael@0: char addrbuf[128]; michael@0: ASSERT_LOCKED(ns->base); michael@0: if (ns->state) return; michael@0: log(EVDNS_LOG_MSG, "Nameserver %s is back up", michael@0: evutil_format_sockaddr_port( michael@0: (struct sockaddr *)&ns->address, michael@0: addrbuf, sizeof(addrbuf))); michael@0: evtimer_del(&ns->timeout_event); michael@0: if (ns->probe_request) { michael@0: evdns_cancel_request(ns->base, ns->probe_request); michael@0: ns->probe_request = NULL; michael@0: } michael@0: ns->state = 1; michael@0: ns->failed_times = 0; michael@0: ns->timedout = 0; michael@0: ns->base->global_good_nameservers++; michael@0: } michael@0: michael@0: static void michael@0: request_trans_id_set(struct request *const req, const u16 trans_id) { michael@0: req->trans_id = trans_id; michael@0: *((u16 *) req->request) = htons(trans_id); michael@0: } michael@0: michael@0: /* Called to remove a request from a list and dealloc it. */ michael@0: /* head is a pointer to the head of the list it should be */ michael@0: /* removed from or NULL if the request isn't in a list. */ michael@0: /* when free_handle is one, free the handle as well. */ michael@0: static void michael@0: request_finished(struct request *const req, struct request **head, int free_handle) { michael@0: struct evdns_base *base = req->base; michael@0: int was_inflight = (head != &base->req_waiting_head); michael@0: EVDNS_LOCK(base); michael@0: ASSERT_VALID_REQUEST(req); michael@0: michael@0: if (head) michael@0: evdns_request_remove(req, head); michael@0: michael@0: log(EVDNS_LOG_DEBUG, "Removing timeout for request %p", req); michael@0: if (was_inflight) { michael@0: evtimer_del(&req->timeout_event); michael@0: base->global_requests_inflight--; michael@0: } else { michael@0: base->global_requests_waiting--; michael@0: } michael@0: /* it was initialized during request_new / evtimer_assign */ michael@0: event_debug_unassign(&req->timeout_event); michael@0: michael@0: if (!req->request_appended) { michael@0: /* need to free the request data on it's own */ michael@0: mm_free(req->request); michael@0: } else { michael@0: /* the request data is appended onto the header */ michael@0: /* so everything gets free()ed when we: */ michael@0: } michael@0: michael@0: if (req->handle) { michael@0: EVUTIL_ASSERT(req->handle->current_req == req); michael@0: michael@0: if (free_handle) { michael@0: search_request_finished(req->handle); michael@0: req->handle->current_req = NULL; michael@0: if (! req->handle->pending_cb) { michael@0: /* If we're planning to run the callback, michael@0: * don't free the handle until later. */ michael@0: mm_free(req->handle); michael@0: } michael@0: req->handle = NULL; /* If we have a bug, let's crash michael@0: * early */ michael@0: } else { michael@0: req->handle->current_req = NULL; michael@0: } michael@0: } michael@0: michael@0: mm_free(req); michael@0: michael@0: evdns_requests_pump_waiting_queue(base); michael@0: EVDNS_UNLOCK(base); michael@0: } michael@0: michael@0: /* This is called when a server returns a funny error code. */ michael@0: /* We try the request again with another server. */ michael@0: /* */ michael@0: /* return: */ michael@0: /* 0 ok */ michael@0: /* 1 failed/reissue is pointless */ michael@0: static int michael@0: request_reissue(struct request *req) { michael@0: const struct nameserver *const last_ns = req->ns; michael@0: ASSERT_LOCKED(req->base); michael@0: ASSERT_VALID_REQUEST(req); michael@0: /* the last nameserver should have been marked as failing */ michael@0: /* by the caller of this function, therefore pick will try */ michael@0: /* not to return it */ michael@0: req->ns = nameserver_pick(req->base); michael@0: if (req->ns == last_ns) { michael@0: /* ... but pick did return it */ michael@0: /* not a lot of point in trying again with the */ michael@0: /* same server */ michael@0: return 1; michael@0: } michael@0: michael@0: req->reissue_count++; michael@0: req->tx_count = 0; michael@0: req->transmit_me = 1; michael@0: michael@0: return 0; michael@0: } michael@0: michael@0: /* this function looks for space on the inflight queue and promotes */ michael@0: /* requests from the waiting queue if it can. */ michael@0: static void michael@0: evdns_requests_pump_waiting_queue(struct evdns_base *base) { michael@0: ASSERT_LOCKED(base); michael@0: while (base->global_requests_inflight < base->global_max_requests_inflight && michael@0: base->global_requests_waiting) { michael@0: struct request *req; michael@0: /* move a request from the waiting queue to the inflight queue */ michael@0: EVUTIL_ASSERT(base->req_waiting_head); michael@0: req = base->req_waiting_head; michael@0: evdns_request_remove(req, &base->req_waiting_head); michael@0: michael@0: base->global_requests_waiting--; michael@0: base->global_requests_inflight++; michael@0: michael@0: req->ns = nameserver_pick(base); michael@0: request_trans_id_set(req, transaction_id_pick(base)); michael@0: michael@0: evdns_request_insert(req, &REQ_HEAD(base, req->trans_id)); michael@0: evdns_request_transmit(req); michael@0: evdns_transmit(base); michael@0: } michael@0: } michael@0: michael@0: /* TODO(nickm) document */ michael@0: struct deferred_reply_callback { michael@0: struct deferred_cb deferred; michael@0: struct evdns_request *handle; michael@0: u8 request_type; michael@0: u8 have_reply; michael@0: u32 ttl; michael@0: u32 err; michael@0: evdns_callback_type user_callback; michael@0: struct reply reply; michael@0: }; michael@0: michael@0: static void michael@0: reply_run_callback(struct deferred_cb *d, void *user_pointer) michael@0: { michael@0: struct deferred_reply_callback *cb = michael@0: EVUTIL_UPCAST(d, struct deferred_reply_callback, deferred); michael@0: michael@0: switch (cb->request_type) { michael@0: case TYPE_A: michael@0: if (cb->have_reply) michael@0: cb->user_callback(DNS_ERR_NONE, DNS_IPv4_A, michael@0: cb->reply.data.a.addrcount, cb->ttl, michael@0: cb->reply.data.a.addresses, michael@0: user_pointer); michael@0: else michael@0: cb->user_callback(cb->err, 0, 0, cb->ttl, NULL, user_pointer); michael@0: break; michael@0: case TYPE_PTR: michael@0: if (cb->have_reply) { michael@0: char *name = cb->reply.data.ptr.name; michael@0: cb->user_callback(DNS_ERR_NONE, DNS_PTR, 1, cb->ttl, michael@0: &name, user_pointer); michael@0: } else { michael@0: cb->user_callback(cb->err, 0, 0, cb->ttl, NULL, user_pointer); michael@0: } michael@0: break; michael@0: case TYPE_AAAA: michael@0: if (cb->have_reply) michael@0: cb->user_callback(DNS_ERR_NONE, DNS_IPv6_AAAA, michael@0: cb->reply.data.aaaa.addrcount, cb->ttl, michael@0: cb->reply.data.aaaa.addresses, michael@0: user_pointer); michael@0: else michael@0: cb->user_callback(cb->err, 0, 0, cb->ttl, NULL, user_pointer); michael@0: break; michael@0: default: michael@0: EVUTIL_ASSERT(0); michael@0: } michael@0: michael@0: if (cb->handle && cb->handle->pending_cb) { michael@0: mm_free(cb->handle); michael@0: } michael@0: michael@0: mm_free(cb); michael@0: } michael@0: michael@0: static void michael@0: reply_schedule_callback(struct request *const req, u32 ttl, u32 err, struct reply *reply) michael@0: { michael@0: struct deferred_reply_callback *d = mm_calloc(1, sizeof(*d)); michael@0: michael@0: if (!d) { michael@0: event_warn("%s: Couldn't allocate space for deferred callback.", michael@0: __func__); michael@0: return; michael@0: } michael@0: michael@0: ASSERT_LOCKED(req->base); michael@0: michael@0: d->request_type = req->request_type; michael@0: d->user_callback = req->user_callback; michael@0: d->ttl = ttl; michael@0: d->err = err; michael@0: if (reply) { michael@0: d->have_reply = 1; michael@0: memcpy(&d->reply, reply, sizeof(struct reply)); michael@0: } michael@0: michael@0: if (req->handle) { michael@0: req->handle->pending_cb = 1; michael@0: d->handle = req->handle; michael@0: } michael@0: michael@0: event_deferred_cb_init(&d->deferred, reply_run_callback, michael@0: req->user_pointer); michael@0: event_deferred_cb_schedule( michael@0: event_base_get_deferred_cb_queue(req->base->event_base), michael@0: &d->deferred); michael@0: } michael@0: michael@0: /* this processes a parsed reply packet */ michael@0: static void michael@0: reply_handle(struct request *const req, u16 flags, u32 ttl, struct reply *reply) { michael@0: int error; michael@0: char addrbuf[128]; michael@0: static const int error_codes[] = { michael@0: DNS_ERR_FORMAT, DNS_ERR_SERVERFAILED, DNS_ERR_NOTEXIST, michael@0: DNS_ERR_NOTIMPL, DNS_ERR_REFUSED michael@0: }; michael@0: michael@0: ASSERT_LOCKED(req->base); michael@0: ASSERT_VALID_REQUEST(req); michael@0: michael@0: if (flags & 0x020f || !reply || !reply->have_answer) { michael@0: /* there was an error */ michael@0: if (flags & 0x0200) { michael@0: error = DNS_ERR_TRUNCATED; michael@0: } else if (flags & 0x000f) { michael@0: u16 error_code = (flags & 0x000f) - 1; michael@0: if (error_code > 4) { michael@0: error = DNS_ERR_UNKNOWN; michael@0: } else { michael@0: error = error_codes[error_code]; michael@0: } michael@0: } else if (reply && !reply->have_answer) { michael@0: error = DNS_ERR_NODATA; michael@0: } else { michael@0: error = DNS_ERR_UNKNOWN; michael@0: } michael@0: michael@0: switch (error) { michael@0: case DNS_ERR_NOTIMPL: michael@0: case DNS_ERR_REFUSED: michael@0: /* we regard these errors as marking a bad nameserver */ michael@0: if (req->reissue_count < req->base->global_max_reissues) { michael@0: char msg[64]; michael@0: evutil_snprintf(msg, sizeof(msg), "Bad response %d (%s)", michael@0: error, evdns_err_to_string(error)); michael@0: nameserver_failed(req->ns, msg); michael@0: if (!request_reissue(req)) return; michael@0: } michael@0: break; michael@0: case DNS_ERR_SERVERFAILED: michael@0: /* rcode 2 (servfailed) sometimes means "we michael@0: * are broken" and sometimes (with some binds) michael@0: * means "that request was very confusing." michael@0: * Treat this as a timeout, not a failure. michael@0: */ michael@0: log(EVDNS_LOG_DEBUG, "Got a SERVERFAILED from nameserver" michael@0: "at %s; will allow the request to time out.", michael@0: evutil_format_sockaddr_port( michael@0: (struct sockaddr *)&req->ns->address, michael@0: addrbuf, sizeof(addrbuf))); michael@0: break; michael@0: default: michael@0: /* we got a good reply from the nameserver: it is up. */ michael@0: if (req->handle == req->ns->probe_request) { michael@0: /* Avoid double-free */ michael@0: req->ns->probe_request = NULL; michael@0: } michael@0: michael@0: nameserver_up(req->ns); michael@0: } michael@0: michael@0: if (req->handle->search_state && michael@0: req->request_type != TYPE_PTR) { michael@0: /* if we have a list of domains to search in, michael@0: * try the next one */ michael@0: if (!search_try_next(req->handle)) { michael@0: /* a new request was issued so this michael@0: * request is finished and */ michael@0: /* the user callback will be made when michael@0: * that request (or a */ michael@0: /* child of it) finishes. */ michael@0: return; michael@0: } michael@0: } michael@0: michael@0: /* all else failed. Pass the failure up */ michael@0: reply_schedule_callback(req, ttl, error, NULL); michael@0: request_finished(req, &REQ_HEAD(req->base, req->trans_id), 1); michael@0: } else { michael@0: /* all ok, tell the user */ michael@0: reply_schedule_callback(req, ttl, 0, reply); michael@0: if (req->handle == req->ns->probe_request) michael@0: req->ns->probe_request = NULL; /* Avoid double-free */ michael@0: nameserver_up(req->ns); michael@0: request_finished(req, &REQ_HEAD(req->base, req->trans_id), 1); michael@0: } michael@0: } michael@0: michael@0: static int michael@0: name_parse(u8 *packet, int length, int *idx, char *name_out, int name_out_len) { michael@0: int name_end = -1; michael@0: int j = *idx; michael@0: int ptr_count = 0; michael@0: #define GET32(x) do { if (j + 4 > length) goto err; memcpy(&_t32, packet + j, 4); j += 4; x = ntohl(_t32); } while (0) michael@0: #define GET16(x) do { if (j + 2 > length) goto err; memcpy(&_t, packet + j, 2); j += 2; x = ntohs(_t); } while (0) michael@0: #define GET8(x) do { if (j >= length) goto err; x = packet[j++]; } while (0) michael@0: michael@0: char *cp = name_out; michael@0: const char *const end = name_out + name_out_len; michael@0: michael@0: /* Normally, names are a series of length prefixed strings terminated */ michael@0: /* with a length of 0 (the lengths are u8's < 63). */ michael@0: /* However, the length can start with a pair of 1 bits and that */ michael@0: /* means that the next 14 bits are a pointer within the current */ michael@0: /* packet. */ michael@0: michael@0: for (;;) { michael@0: u8 label_len; michael@0: if (j >= length) return -1; michael@0: GET8(label_len); michael@0: if (!label_len) break; michael@0: if (label_len & 0xc0) { michael@0: u8 ptr_low; michael@0: GET8(ptr_low); michael@0: if (name_end < 0) name_end = j; michael@0: j = (((int)label_len & 0x3f) << 8) + ptr_low; michael@0: /* Make sure that the target offset is in-bounds. */ michael@0: if (j < 0 || j >= length) return -1; michael@0: /* If we've jumped more times than there are characters in the michael@0: * message, we must have a loop. */ michael@0: if (++ptr_count > length) return -1; michael@0: continue; michael@0: } michael@0: if (label_len > 63) return -1; michael@0: if (cp != name_out) { michael@0: if (cp + 1 >= end) return -1; michael@0: *cp++ = '.'; michael@0: } michael@0: if (cp + label_len >= end) return -1; michael@0: memcpy(cp, packet + j, label_len); michael@0: cp += label_len; michael@0: j += label_len; michael@0: } michael@0: if (cp >= end) return -1; michael@0: *cp = '\0'; michael@0: if (name_end < 0) michael@0: *idx = j; michael@0: else michael@0: *idx = name_end; michael@0: return 0; michael@0: err: michael@0: return -1; michael@0: } michael@0: michael@0: /* parses a raw request from a nameserver */ michael@0: static int michael@0: reply_parse(struct evdns_base *base, u8 *packet, int length) { michael@0: int j = 0, k = 0; /* index into packet */ michael@0: u16 _t; /* used by the macros */ michael@0: u32 _t32; /* used by the macros */ michael@0: char tmp_name[256], cmp_name[256]; /* used by the macros */ michael@0: int name_matches = 0; michael@0: michael@0: u16 trans_id, questions, answers, authority, additional, datalength; michael@0: u16 flags = 0; michael@0: u32 ttl, ttl_r = 0xffffffff; michael@0: struct reply reply; michael@0: struct request *req = NULL; michael@0: unsigned int i; michael@0: michael@0: ASSERT_LOCKED(base); michael@0: michael@0: GET16(trans_id); michael@0: GET16(flags); michael@0: GET16(questions); michael@0: GET16(answers); michael@0: GET16(authority); michael@0: GET16(additional); michael@0: (void) authority; /* suppress "unused variable" warnings. */ michael@0: (void) additional; /* suppress "unused variable" warnings. */ michael@0: michael@0: req = request_find_from_trans_id(base, trans_id); michael@0: if (!req) return -1; michael@0: EVUTIL_ASSERT(req->base == base); michael@0: michael@0: memset(&reply, 0, sizeof(reply)); michael@0: michael@0: /* If it's not an answer, it doesn't correspond to any request. */ michael@0: if (!(flags & 0x8000)) return -1; /* must be an answer */ michael@0: if ((flags & 0x020f) && (flags & 0x020f) != DNS_ERR_NOTEXIST) { michael@0: /* there was an error and it's not NXDOMAIN */ michael@0: goto err; michael@0: } michael@0: /* if (!answers) return; */ /* must have an answer of some form */ michael@0: michael@0: /* This macro skips a name in the DNS reply. */ michael@0: #define SKIP_NAME \ michael@0: do { tmp_name[0] = '\0'; \ michael@0: if (name_parse(packet, length, &j, tmp_name, \ michael@0: sizeof(tmp_name))<0) \ michael@0: goto err; \ michael@0: } while (0) michael@0: #define TEST_NAME \ michael@0: do { tmp_name[0] = '\0'; \ michael@0: cmp_name[0] = '\0'; \ michael@0: k = j; \ michael@0: if (name_parse(packet, length, &j, tmp_name, \ michael@0: sizeof(tmp_name))<0) \ michael@0: goto err; \ michael@0: if (name_parse(req->request, req->request_len, &k, \ michael@0: cmp_name, sizeof(cmp_name))<0) \ michael@0: goto err; \ michael@0: if (base->global_randomize_case) { \ michael@0: if (strcmp(tmp_name, cmp_name) == 0) \ michael@0: name_matches = 1; \ michael@0: } else { \ michael@0: if (evutil_ascii_strcasecmp(tmp_name, cmp_name) == 0) \ michael@0: name_matches = 1; \ michael@0: } \ michael@0: } while (0) michael@0: michael@0: reply.type = req->request_type; michael@0: michael@0: /* skip over each question in the reply */ michael@0: for (i = 0; i < questions; ++i) { michael@0: /* the question looks like michael@0: * michael@0: */ michael@0: TEST_NAME; michael@0: j += 4; michael@0: if (j > length) goto err; michael@0: } michael@0: michael@0: if (!name_matches) michael@0: goto err; michael@0: michael@0: /* now we have the answer section which looks like michael@0: * michael@0: */ michael@0: michael@0: for (i = 0; i < answers; ++i) { michael@0: u16 type, class; michael@0: michael@0: SKIP_NAME; michael@0: GET16(type); michael@0: GET16(class); michael@0: GET32(ttl); michael@0: GET16(datalength); michael@0: michael@0: if (type == TYPE_A && class == CLASS_INET) { michael@0: int addrcount, addrtocopy; michael@0: if (req->request_type != TYPE_A) { michael@0: j += datalength; continue; michael@0: } michael@0: if ((datalength & 3) != 0) /* not an even number of As. */ michael@0: goto err; michael@0: addrcount = datalength >> 2; michael@0: addrtocopy = MIN(MAX_V4_ADDRS - reply.data.a.addrcount, (unsigned)addrcount); michael@0: michael@0: ttl_r = MIN(ttl_r, ttl); michael@0: /* we only bother with the first four addresses. */ michael@0: if (j + 4*addrtocopy > length) goto err; michael@0: memcpy(&reply.data.a.addresses[reply.data.a.addrcount], michael@0: packet + j, 4*addrtocopy); michael@0: j += 4*addrtocopy; michael@0: reply.data.a.addrcount += addrtocopy; michael@0: reply.have_answer = 1; michael@0: if (reply.data.a.addrcount == MAX_V4_ADDRS) break; michael@0: } else if (type == TYPE_PTR && class == CLASS_INET) { michael@0: if (req->request_type != TYPE_PTR) { michael@0: j += datalength; continue; michael@0: } michael@0: if (name_parse(packet, length, &j, reply.data.ptr.name, michael@0: sizeof(reply.data.ptr.name))<0) michael@0: goto err; michael@0: ttl_r = MIN(ttl_r, ttl); michael@0: reply.have_answer = 1; michael@0: break; michael@0: } else if (type == TYPE_CNAME) { michael@0: char cname[HOST_NAME_MAX]; michael@0: if (!req->put_cname_in_ptr || *req->put_cname_in_ptr) { michael@0: j += datalength; continue; michael@0: } michael@0: if (name_parse(packet, length, &j, cname, michael@0: sizeof(cname))<0) michael@0: goto err; michael@0: *req->put_cname_in_ptr = mm_strdup(cname); michael@0: } else if (type == TYPE_AAAA && class == CLASS_INET) { michael@0: int addrcount, addrtocopy; michael@0: if (req->request_type != TYPE_AAAA) { michael@0: j += datalength; continue; michael@0: } michael@0: if ((datalength & 15) != 0) /* not an even number of AAAAs. */ michael@0: goto err; michael@0: addrcount = datalength >> 4; /* each address is 16 bytes long */ michael@0: addrtocopy = MIN(MAX_V6_ADDRS - reply.data.aaaa.addrcount, (unsigned)addrcount); michael@0: ttl_r = MIN(ttl_r, ttl); michael@0: michael@0: /* we only bother with the first four addresses. */ michael@0: if (j + 16*addrtocopy > length) goto err; michael@0: memcpy(&reply.data.aaaa.addresses[reply.data.aaaa.addrcount], michael@0: packet + j, 16*addrtocopy); michael@0: reply.data.aaaa.addrcount += addrtocopy; michael@0: j += 16*addrtocopy; michael@0: reply.have_answer = 1; michael@0: if (reply.data.aaaa.addrcount == MAX_V6_ADDRS) break; michael@0: } else { michael@0: /* skip over any other type of resource */ michael@0: j += datalength; michael@0: } michael@0: } michael@0: michael@0: if (!reply.have_answer) { michael@0: for (i = 0; i < authority; ++i) { michael@0: u16 type, class; michael@0: SKIP_NAME; michael@0: GET16(type); michael@0: GET16(class); michael@0: GET32(ttl); michael@0: GET16(datalength); michael@0: if (type == TYPE_SOA && class == CLASS_INET) { michael@0: u32 serial, refresh, retry, expire, minimum; michael@0: SKIP_NAME; michael@0: SKIP_NAME; michael@0: GET32(serial); michael@0: GET32(refresh); michael@0: GET32(retry); michael@0: GET32(expire); michael@0: GET32(minimum); michael@0: (void)expire; michael@0: (void)retry; michael@0: (void)refresh; michael@0: (void)serial; michael@0: ttl_r = MIN(ttl_r, ttl); michael@0: ttl_r = MIN(ttl_r, minimum); michael@0: } else { michael@0: /* skip over any other type of resource */ michael@0: j += datalength; michael@0: } michael@0: } michael@0: } michael@0: michael@0: if (ttl_r == 0xffffffff) michael@0: ttl_r = 0; michael@0: michael@0: reply_handle(req, flags, ttl_r, &reply); michael@0: return 0; michael@0: err: michael@0: if (req) michael@0: reply_handle(req, flags, 0, NULL); michael@0: return -1; michael@0: } michael@0: michael@0: /* Parse a raw request (packet,length) sent to a nameserver port (port) from */ michael@0: /* a DNS client (addr,addrlen), and if it's well-formed, call the corresponding */ michael@0: /* callback. */ michael@0: static int michael@0: request_parse(u8 *packet, int length, struct evdns_server_port *port, struct sockaddr *addr, ev_socklen_t addrlen) michael@0: { michael@0: int j = 0; /* index into packet */ michael@0: u16 _t; /* used by the macros */ michael@0: char tmp_name[256]; /* used by the macros */ michael@0: michael@0: int i; michael@0: u16 trans_id, flags, questions, answers, authority, additional; michael@0: struct server_request *server_req = NULL; michael@0: michael@0: ASSERT_LOCKED(port); michael@0: michael@0: /* Get the header fields */ michael@0: GET16(trans_id); michael@0: GET16(flags); michael@0: GET16(questions); michael@0: GET16(answers); michael@0: GET16(authority); michael@0: GET16(additional); michael@0: (void)answers; michael@0: (void)additional; michael@0: (void)authority; michael@0: michael@0: if (flags & 0x8000) return -1; /* Must not be an answer. */ michael@0: flags &= 0x0110; /* Only RD and CD get preserved. */ michael@0: michael@0: server_req = mm_malloc(sizeof(struct server_request)); michael@0: if (server_req == NULL) return -1; michael@0: memset(server_req, 0, sizeof(struct server_request)); michael@0: michael@0: server_req->trans_id = trans_id; michael@0: memcpy(&server_req->addr, addr, addrlen); michael@0: server_req->addrlen = addrlen; michael@0: michael@0: server_req->base.flags = flags; michael@0: server_req->base.nquestions = 0; michael@0: server_req->base.questions = mm_calloc(sizeof(struct evdns_server_question *), questions); michael@0: if (server_req->base.questions == NULL) michael@0: goto err; michael@0: michael@0: for (i = 0; i < questions; ++i) { michael@0: u16 type, class; michael@0: struct evdns_server_question *q; michael@0: int namelen; michael@0: if (name_parse(packet, length, &j, tmp_name, sizeof(tmp_name))<0) michael@0: goto err; michael@0: GET16(type); michael@0: GET16(class); michael@0: namelen = (int)strlen(tmp_name); michael@0: q = mm_malloc(sizeof(struct evdns_server_question) + namelen); michael@0: if (!q) michael@0: goto err; michael@0: q->type = type; michael@0: q->dns_question_class = class; michael@0: memcpy(q->name, tmp_name, namelen+1); michael@0: server_req->base.questions[server_req->base.nquestions++] = q; michael@0: } michael@0: michael@0: /* Ignore answers, authority, and additional. */ michael@0: michael@0: server_req->port = port; michael@0: port->refcnt++; michael@0: michael@0: /* Only standard queries are supported. */ michael@0: if (flags & 0x7800) { michael@0: evdns_server_request_respond(&(server_req->base), DNS_ERR_NOTIMPL); michael@0: return -1; michael@0: } michael@0: michael@0: port->user_callback(&(server_req->base), port->user_data); michael@0: michael@0: return 0; michael@0: err: michael@0: if (server_req) { michael@0: if (server_req->base.questions) { michael@0: for (i = 0; i < server_req->base.nquestions; ++i) michael@0: mm_free(server_req->base.questions[i]); michael@0: mm_free(server_req->base.questions); michael@0: } michael@0: mm_free(server_req); michael@0: } michael@0: return -1; michael@0: michael@0: #undef SKIP_NAME michael@0: #undef GET32 michael@0: #undef GET16 michael@0: #undef GET8 michael@0: } michael@0: michael@0: michael@0: void michael@0: evdns_set_transaction_id_fn(ev_uint16_t (*fn)(void)) michael@0: { michael@0: } michael@0: michael@0: void michael@0: evdns_set_random_bytes_fn(void (*fn)(char *, size_t)) michael@0: { michael@0: } michael@0: michael@0: /* Try to choose a strong transaction id which isn't already in flight */ michael@0: static u16 michael@0: transaction_id_pick(struct evdns_base *base) { michael@0: ASSERT_LOCKED(base); michael@0: for (;;) { michael@0: u16 trans_id; michael@0: evutil_secure_rng_get_bytes(&trans_id, sizeof(trans_id)); michael@0: michael@0: if (trans_id == 0xffff) continue; michael@0: /* now check to see if that id is already inflight */ michael@0: if (request_find_from_trans_id(base, trans_id) == NULL) michael@0: return trans_id; michael@0: } michael@0: } michael@0: michael@0: /* choose a namesever to use. This function will try to ignore */ michael@0: /* nameservers which we think are down and load balance across the rest */ michael@0: /* by updating the server_head global each time. */ michael@0: static struct nameserver * michael@0: nameserver_pick(struct evdns_base *base) { michael@0: struct nameserver *started_at = base->server_head, *picked; michael@0: ASSERT_LOCKED(base); michael@0: if (!base->server_head) return NULL; michael@0: michael@0: /* if we don't have any good nameservers then there's no */ michael@0: /* point in trying to find one. */ michael@0: if (!base->global_good_nameservers) { michael@0: base->server_head = base->server_head->next; michael@0: return base->server_head; michael@0: } michael@0: michael@0: /* remember that nameservers are in a circular list */ michael@0: for (;;) { michael@0: if (base->server_head->state) { michael@0: /* we think this server is currently good */ michael@0: picked = base->server_head; michael@0: base->server_head = base->server_head->next; michael@0: return picked; michael@0: } michael@0: michael@0: base->server_head = base->server_head->next; michael@0: if (base->server_head == started_at) { michael@0: /* all the nameservers seem to be down */ michael@0: /* so we just return this one and hope for the */ michael@0: /* best */ michael@0: EVUTIL_ASSERT(base->global_good_nameservers == 0); michael@0: picked = base->server_head; michael@0: base->server_head = base->server_head->next; michael@0: return picked; michael@0: } michael@0: } michael@0: } michael@0: michael@0: /* this is called when a namesever socket is ready for reading */ michael@0: static void michael@0: nameserver_read(struct nameserver *ns) { michael@0: struct sockaddr_storage ss; michael@0: ev_socklen_t addrlen = sizeof(ss); michael@0: u8 packet[1500]; michael@0: char addrbuf[128]; michael@0: ASSERT_LOCKED(ns->base); michael@0: michael@0: for (;;) { michael@0: const int r = recvfrom(ns->socket, (void*)packet, michael@0: sizeof(packet), 0, michael@0: (struct sockaddr*)&ss, &addrlen); michael@0: if (r < 0) { michael@0: int err = evutil_socket_geterror(ns->socket); michael@0: if (EVUTIL_ERR_RW_RETRIABLE(err)) michael@0: return; michael@0: nameserver_failed(ns, michael@0: evutil_socket_error_to_string(err)); michael@0: return; michael@0: } michael@0: if (evutil_sockaddr_cmp((struct sockaddr*)&ss, michael@0: (struct sockaddr*)&ns->address, 0)) { michael@0: log(EVDNS_LOG_WARN, "Address mismatch on received " michael@0: "DNS packet. Apparent source was %s", michael@0: evutil_format_sockaddr_port( michael@0: (struct sockaddr *)&ss, michael@0: addrbuf, sizeof(addrbuf))); michael@0: return; michael@0: } michael@0: michael@0: ns->timedout = 0; michael@0: reply_parse(ns->base, packet, r); michael@0: } michael@0: } michael@0: michael@0: /* Read a packet from a DNS client on a server port s, parse it, and */ michael@0: /* act accordingly. */ michael@0: static void michael@0: server_port_read(struct evdns_server_port *s) { michael@0: u8 packet[1500]; michael@0: struct sockaddr_storage addr; michael@0: ev_socklen_t addrlen; michael@0: int r; michael@0: ASSERT_LOCKED(s); michael@0: michael@0: for (;;) { michael@0: addrlen = sizeof(struct sockaddr_storage); michael@0: r = recvfrom(s->socket, (void*)packet, sizeof(packet), 0, michael@0: (struct sockaddr*) &addr, &addrlen); michael@0: if (r < 0) { michael@0: int err = evutil_socket_geterror(s->socket); michael@0: if (EVUTIL_ERR_RW_RETRIABLE(err)) michael@0: return; michael@0: log(EVDNS_LOG_WARN, michael@0: "Error %s (%d) while reading request.", michael@0: evutil_socket_error_to_string(err), err); michael@0: return; michael@0: } michael@0: request_parse(packet, r, s, (struct sockaddr*) &addr, addrlen); michael@0: } michael@0: } michael@0: michael@0: /* Try to write all pending replies on a given DNS server port. */ michael@0: static void michael@0: server_port_flush(struct evdns_server_port *port) michael@0: { michael@0: struct server_request *req = port->pending_replies; michael@0: ASSERT_LOCKED(port); michael@0: while (req) { michael@0: int r = sendto(port->socket, req->response, (int)req->response_len, 0, michael@0: (struct sockaddr*) &req->addr, (ev_socklen_t)req->addrlen); michael@0: if (r < 0) { michael@0: int err = evutil_socket_geterror(port->socket); michael@0: if (EVUTIL_ERR_RW_RETRIABLE(err)) michael@0: return; michael@0: log(EVDNS_LOG_WARN, "Error %s (%d) while writing response to port; dropping", evutil_socket_error_to_string(err), err); michael@0: } michael@0: if (server_request_free(req)) { michael@0: /* we released the last reference to req->port. */ michael@0: return; michael@0: } else { michael@0: EVUTIL_ASSERT(req != port->pending_replies); michael@0: req = port->pending_replies; michael@0: } michael@0: } michael@0: michael@0: /* We have no more pending requests; stop listening for 'writeable' events. */ michael@0: (void) event_del(&port->event); michael@0: event_assign(&port->event, port->event_base, michael@0: port->socket, EV_READ | EV_PERSIST, michael@0: server_port_ready_callback, port); michael@0: michael@0: if (event_add(&port->event, NULL) < 0) { michael@0: log(EVDNS_LOG_WARN, "Error from libevent when adding event for DNS server."); michael@0: /* ???? Do more? */ michael@0: } michael@0: } michael@0: michael@0: /* set if we are waiting for the ability to write to this server. */ michael@0: /* if waiting is true then we ask libevent for EV_WRITE events, otherwise */ michael@0: /* we stop these events. */ michael@0: static void michael@0: nameserver_write_waiting(struct nameserver *ns, char waiting) { michael@0: ASSERT_LOCKED(ns->base); michael@0: if (ns->write_waiting == waiting) return; michael@0: michael@0: ns->write_waiting = waiting; michael@0: (void) event_del(&ns->event); michael@0: event_assign(&ns->event, ns->base->event_base, michael@0: ns->socket, EV_READ | (waiting ? EV_WRITE : 0) | EV_PERSIST, michael@0: nameserver_ready_callback, ns); michael@0: if (event_add(&ns->event, NULL) < 0) { michael@0: char addrbuf[128]; michael@0: log(EVDNS_LOG_WARN, "Error from libevent when adding event for %s", michael@0: evutil_format_sockaddr_port( michael@0: (struct sockaddr *)&ns->address, michael@0: addrbuf, sizeof(addrbuf))); michael@0: /* ???? Do more? */ michael@0: } michael@0: } michael@0: michael@0: /* a callback function. Called by libevent when the kernel says that */ michael@0: /* a nameserver socket is ready for writing or reading */ michael@0: static void michael@0: nameserver_ready_callback(evutil_socket_t fd, short events, void *arg) { michael@0: struct nameserver *ns = (struct nameserver *) arg; michael@0: (void)fd; michael@0: michael@0: EVDNS_LOCK(ns->base); michael@0: if (events & EV_WRITE) { michael@0: ns->choked = 0; michael@0: if (!evdns_transmit(ns->base)) { michael@0: nameserver_write_waiting(ns, 0); michael@0: } michael@0: } michael@0: if (events & EV_READ) { michael@0: nameserver_read(ns); michael@0: } michael@0: EVDNS_UNLOCK(ns->base); michael@0: } michael@0: michael@0: /* a callback function. Called by libevent when the kernel says that */ michael@0: /* a server socket is ready for writing or reading. */ michael@0: static void michael@0: server_port_ready_callback(evutil_socket_t fd, short events, void *arg) { michael@0: struct evdns_server_port *port = (struct evdns_server_port *) arg; michael@0: (void) fd; michael@0: michael@0: EVDNS_LOCK(port); michael@0: if (events & EV_WRITE) { michael@0: port->choked = 0; michael@0: server_port_flush(port); michael@0: } michael@0: if (events & EV_READ) { michael@0: server_port_read(port); michael@0: } michael@0: EVDNS_UNLOCK(port); michael@0: } michael@0: michael@0: /* This is an inefficient representation; only use it via the dnslabel_table_* michael@0: * functions, so that is can be safely replaced with something smarter later. */ michael@0: #define MAX_LABELS 128 michael@0: /* Structures used to implement name compression */ michael@0: struct dnslabel_entry { char *v; off_t pos; }; michael@0: struct dnslabel_table { michael@0: int n_labels; /* number of current entries */ michael@0: /* map from name to position in message */ michael@0: struct dnslabel_entry labels[MAX_LABELS]; michael@0: }; michael@0: michael@0: /* Initialize dnslabel_table. */ michael@0: static void michael@0: dnslabel_table_init(struct dnslabel_table *table) michael@0: { michael@0: table->n_labels = 0; michael@0: } michael@0: michael@0: /* Free all storage held by table, but not the table itself. */ michael@0: static void michael@0: dnslabel_clear(struct dnslabel_table *table) michael@0: { michael@0: int i; michael@0: for (i = 0; i < table->n_labels; ++i) michael@0: mm_free(table->labels[i].v); michael@0: table->n_labels = 0; michael@0: } michael@0: michael@0: /* return the position of the label in the current message, or -1 if the label */ michael@0: /* hasn't been used yet. */ michael@0: static int michael@0: dnslabel_table_get_pos(const struct dnslabel_table *table, const char *label) michael@0: { michael@0: int i; michael@0: for (i = 0; i < table->n_labels; ++i) { michael@0: if (!strcmp(label, table->labels[i].v)) michael@0: return table->labels[i].pos; michael@0: } michael@0: return -1; michael@0: } michael@0: michael@0: /* remember that we've used the label at position pos */ michael@0: static int michael@0: dnslabel_table_add(struct dnslabel_table *table, const char *label, off_t pos) michael@0: { michael@0: char *v; michael@0: int p; michael@0: if (table->n_labels == MAX_LABELS) michael@0: return (-1); michael@0: v = mm_strdup(label); michael@0: if (v == NULL) michael@0: return (-1); michael@0: p = table->n_labels++; michael@0: table->labels[p].v = v; michael@0: table->labels[p].pos = pos; michael@0: michael@0: return (0); michael@0: } michael@0: michael@0: /* Converts a string to a length-prefixed set of DNS labels, starting */ michael@0: /* at buf[j]. name and buf must not overlap. name_len should be the length */ michael@0: /* of name. table is optional, and is used for compression. */ michael@0: /* */ michael@0: /* Input: abc.def */ michael@0: /* Output: <3>abc<3>def<0> */ michael@0: /* */ michael@0: /* Returns the first index after the encoded name, or negative on error. */ michael@0: /* -1 label was > 63 bytes */ michael@0: /* -2 name too long to fit in buffer. */ michael@0: /* */ michael@0: static off_t michael@0: dnsname_to_labels(u8 *const buf, size_t buf_len, off_t j, michael@0: const char *name, const size_t name_len, michael@0: struct dnslabel_table *table) { michael@0: const char *end = name + name_len; michael@0: int ref = 0; michael@0: u16 _t; michael@0: michael@0: #define APPEND16(x) do { \ michael@0: if (j + 2 > (off_t)buf_len) \ michael@0: goto overflow; \ michael@0: _t = htons(x); \ michael@0: memcpy(buf + j, &_t, 2); \ michael@0: j += 2; \ michael@0: } while (0) michael@0: #define APPEND32(x) do { \ michael@0: if (j + 4 > (off_t)buf_len) \ michael@0: goto overflow; \ michael@0: _t32 = htonl(x); \ michael@0: memcpy(buf + j, &_t32, 4); \ michael@0: j += 4; \ michael@0: } while (0) michael@0: michael@0: if (name_len > 255) return -2; michael@0: michael@0: for (;;) { michael@0: const char *const start = name; michael@0: if (table && (ref = dnslabel_table_get_pos(table, name)) >= 0) { michael@0: APPEND16(ref | 0xc000); michael@0: return j; michael@0: } michael@0: name = strchr(name, '.'); michael@0: if (!name) { michael@0: const size_t label_len = end - start; michael@0: if (label_len > 63) return -1; michael@0: if ((size_t)(j+label_len+1) > buf_len) return -2; michael@0: if (table) dnslabel_table_add(table, start, j); michael@0: buf[j++] = (ev_uint8_t)label_len; michael@0: michael@0: memcpy(buf + j, start, label_len); michael@0: j += (int) label_len; michael@0: break; michael@0: } else { michael@0: /* append length of the label. */ michael@0: const size_t label_len = name - start; michael@0: if (label_len > 63) return -1; michael@0: if ((size_t)(j+label_len+1) > buf_len) return -2; michael@0: if (table) dnslabel_table_add(table, start, j); michael@0: buf[j++] = (ev_uint8_t)label_len; michael@0: michael@0: memcpy(buf + j, start, label_len); michael@0: j += (int) label_len; michael@0: /* hop over the '.' */ michael@0: name++; michael@0: } michael@0: } michael@0: michael@0: /* the labels must be terminated by a 0. */ michael@0: /* It's possible that the name ended in a . */ michael@0: /* in which case the zero is already there */ michael@0: if (!j || buf[j-1]) buf[j++] = 0; michael@0: return j; michael@0: overflow: michael@0: return (-2); michael@0: } michael@0: michael@0: /* Finds the length of a dns request for a DNS name of the given */ michael@0: /* length. The actual request may be smaller than the value returned */ michael@0: /* here */ michael@0: static size_t michael@0: evdns_request_len(const size_t name_len) { michael@0: return 96 + /* length of the DNS standard header */ michael@0: name_len + 2 + michael@0: 4; /* space for the resource type */ michael@0: } michael@0: michael@0: /* build a dns request packet into buf. buf should be at least as long */ michael@0: /* as evdns_request_len told you it should be. */ michael@0: /* */ michael@0: /* Returns the amount of space used. Negative on error. */ michael@0: static int michael@0: evdns_request_data_build(const char *const name, const size_t name_len, michael@0: const u16 trans_id, const u16 type, const u16 class, michael@0: u8 *const buf, size_t buf_len) { michael@0: off_t j = 0; /* current offset into buf */ michael@0: u16 _t; /* used by the macros */ michael@0: michael@0: APPEND16(trans_id); michael@0: APPEND16(0x0100); /* standard query, recusion needed */ michael@0: APPEND16(1); /* one question */ michael@0: APPEND16(0); /* no answers */ michael@0: APPEND16(0); /* no authority */ michael@0: APPEND16(0); /* no additional */ michael@0: michael@0: j = dnsname_to_labels(buf, buf_len, j, name, name_len, NULL); michael@0: if (j < 0) { michael@0: return (int)j; michael@0: } michael@0: michael@0: APPEND16(type); michael@0: APPEND16(class); michael@0: michael@0: return (int)j; michael@0: overflow: michael@0: return (-1); michael@0: } michael@0: michael@0: /* exported function */ michael@0: struct evdns_server_port * michael@0: evdns_add_server_port_with_base(struct event_base *base, evutil_socket_t socket, int flags, evdns_request_callback_fn_type cb, void *user_data) michael@0: { michael@0: struct evdns_server_port *port; michael@0: if (flags) michael@0: return NULL; /* flags not yet implemented */ michael@0: if (!(port = mm_malloc(sizeof(struct evdns_server_port)))) michael@0: return NULL; michael@0: memset(port, 0, sizeof(struct evdns_server_port)); michael@0: michael@0: michael@0: port->socket = socket; michael@0: port->refcnt = 1; michael@0: port->choked = 0; michael@0: port->closing = 0; michael@0: port->user_callback = cb; michael@0: port->user_data = user_data; michael@0: port->pending_replies = NULL; michael@0: port->event_base = base; michael@0: michael@0: event_assign(&port->event, port->event_base, michael@0: port->socket, EV_READ | EV_PERSIST, michael@0: server_port_ready_callback, port); michael@0: if (event_add(&port->event, NULL) < 0) { michael@0: mm_free(port); michael@0: return NULL; michael@0: } michael@0: EVTHREAD_ALLOC_LOCK(port->lock, EVTHREAD_LOCKTYPE_RECURSIVE); michael@0: return port; michael@0: } michael@0: michael@0: struct evdns_server_port * michael@0: evdns_add_server_port(evutil_socket_t socket, int flags, evdns_request_callback_fn_type cb, void *user_data) michael@0: { michael@0: return evdns_add_server_port_with_base(NULL, socket, flags, cb, user_data); michael@0: } michael@0: michael@0: /* exported function */ michael@0: void michael@0: evdns_close_server_port(struct evdns_server_port *port) michael@0: { michael@0: EVDNS_LOCK(port); michael@0: if (--port->refcnt == 0) { michael@0: EVDNS_UNLOCK(port); michael@0: server_port_free(port); michael@0: } else { michael@0: port->closing = 1; michael@0: } michael@0: } michael@0: michael@0: /* exported function */ michael@0: int michael@0: evdns_server_request_add_reply(struct evdns_server_request *_req, int section, const char *name, int type, int class, int ttl, int datalen, int is_name, const char *data) michael@0: { michael@0: struct server_request *req = TO_SERVER_REQUEST(_req); michael@0: struct server_reply_item **itemp, *item; michael@0: int *countp; michael@0: int result = -1; michael@0: michael@0: EVDNS_LOCK(req->port); michael@0: if (req->response) /* have we already answered? */ michael@0: goto done; michael@0: michael@0: switch (section) { michael@0: case EVDNS_ANSWER_SECTION: michael@0: itemp = &req->answer; michael@0: countp = &req->n_answer; michael@0: break; michael@0: case EVDNS_AUTHORITY_SECTION: michael@0: itemp = &req->authority; michael@0: countp = &req->n_authority; michael@0: break; michael@0: case EVDNS_ADDITIONAL_SECTION: michael@0: itemp = &req->additional; michael@0: countp = &req->n_additional; michael@0: break; michael@0: default: michael@0: goto done; michael@0: } michael@0: while (*itemp) { michael@0: itemp = &((*itemp)->next); michael@0: } michael@0: item = mm_malloc(sizeof(struct server_reply_item)); michael@0: if (!item) michael@0: goto done; michael@0: item->next = NULL; michael@0: if (!(item->name = mm_strdup(name))) { michael@0: mm_free(item); michael@0: goto done; michael@0: } michael@0: item->type = type; michael@0: item->dns_question_class = class; michael@0: item->ttl = ttl; michael@0: item->is_name = is_name != 0; michael@0: item->datalen = 0; michael@0: item->data = NULL; michael@0: if (data) { michael@0: if (item->is_name) { michael@0: if (!(item->data = mm_strdup(data))) { michael@0: mm_free(item->name); michael@0: mm_free(item); michael@0: goto done; michael@0: } michael@0: item->datalen = (u16)-1; michael@0: } else { michael@0: if (!(item->data = mm_malloc(datalen))) { michael@0: mm_free(item->name); michael@0: mm_free(item); michael@0: goto done; michael@0: } michael@0: item->datalen = datalen; michael@0: memcpy(item->data, data, datalen); michael@0: } michael@0: } michael@0: michael@0: *itemp = item; michael@0: ++(*countp); michael@0: result = 0; michael@0: done: michael@0: EVDNS_UNLOCK(req->port); michael@0: return result; michael@0: } michael@0: michael@0: /* exported function */ michael@0: int michael@0: evdns_server_request_add_a_reply(struct evdns_server_request *req, const char *name, int n, const void *addrs, int ttl) michael@0: { michael@0: return evdns_server_request_add_reply( michael@0: req, EVDNS_ANSWER_SECTION, name, TYPE_A, CLASS_INET, michael@0: ttl, n*4, 0, addrs); michael@0: } michael@0: michael@0: /* exported function */ michael@0: int michael@0: evdns_server_request_add_aaaa_reply(struct evdns_server_request *req, const char *name, int n, const void *addrs, int ttl) michael@0: { michael@0: return evdns_server_request_add_reply( michael@0: req, EVDNS_ANSWER_SECTION, name, TYPE_AAAA, CLASS_INET, michael@0: ttl, n*16, 0, addrs); michael@0: } michael@0: michael@0: /* exported function */ michael@0: int michael@0: evdns_server_request_add_ptr_reply(struct evdns_server_request *req, struct in_addr *in, const char *inaddr_name, const char *hostname, int ttl) michael@0: { michael@0: u32 a; michael@0: char buf[32]; michael@0: if (in && inaddr_name) michael@0: return -1; michael@0: else if (!in && !inaddr_name) michael@0: return -1; michael@0: if (in) { michael@0: a = ntohl(in->s_addr); michael@0: evutil_snprintf(buf, sizeof(buf), "%d.%d.%d.%d.in-addr.arpa", michael@0: (int)(u8)((a )&0xff), michael@0: (int)(u8)((a>>8 )&0xff), michael@0: (int)(u8)((a>>16)&0xff), michael@0: (int)(u8)((a>>24)&0xff)); michael@0: inaddr_name = buf; michael@0: } michael@0: return evdns_server_request_add_reply( michael@0: req, EVDNS_ANSWER_SECTION, inaddr_name, TYPE_PTR, CLASS_INET, michael@0: ttl, -1, 1, hostname); michael@0: } michael@0: michael@0: /* exported function */ michael@0: int michael@0: evdns_server_request_add_cname_reply(struct evdns_server_request *req, const char *name, const char *cname, int ttl) michael@0: { michael@0: return evdns_server_request_add_reply( michael@0: req, EVDNS_ANSWER_SECTION, name, TYPE_CNAME, CLASS_INET, michael@0: ttl, -1, 1, cname); michael@0: } michael@0: michael@0: /* exported function */ michael@0: void michael@0: evdns_server_request_set_flags(struct evdns_server_request *exreq, int flags) michael@0: { michael@0: struct server_request *req = TO_SERVER_REQUEST(exreq); michael@0: req->base.flags &= ~(EVDNS_FLAGS_AA|EVDNS_FLAGS_RD); michael@0: req->base.flags |= flags; michael@0: } michael@0: michael@0: static int michael@0: evdns_server_request_format_response(struct server_request *req, int err) michael@0: { michael@0: unsigned char buf[1500]; michael@0: size_t buf_len = sizeof(buf); michael@0: off_t j = 0, r; michael@0: u16 _t; michael@0: u32 _t32; michael@0: int i; michael@0: u16 flags; michael@0: struct dnslabel_table table; michael@0: michael@0: if (err < 0 || err > 15) return -1; michael@0: michael@0: /* Set response bit and error code; copy OPCODE and RD fields from michael@0: * question; copy RA and AA if set by caller. */ michael@0: flags = req->base.flags; michael@0: flags |= (0x8000 | err); michael@0: michael@0: dnslabel_table_init(&table); michael@0: APPEND16(req->trans_id); michael@0: APPEND16(flags); michael@0: APPEND16(req->base.nquestions); michael@0: APPEND16(req->n_answer); michael@0: APPEND16(req->n_authority); michael@0: APPEND16(req->n_additional); michael@0: michael@0: /* Add questions. */ michael@0: for (i=0; i < req->base.nquestions; ++i) { michael@0: const char *s = req->base.questions[i]->name; michael@0: j = dnsname_to_labels(buf, buf_len, j, s, strlen(s), &table); michael@0: if (j < 0) { michael@0: dnslabel_clear(&table); michael@0: return (int) j; michael@0: } michael@0: APPEND16(req->base.questions[i]->type); michael@0: APPEND16(req->base.questions[i]->dns_question_class); michael@0: } michael@0: michael@0: /* Add answer, authority, and additional sections. */ michael@0: for (i=0; i<3; ++i) { michael@0: struct server_reply_item *item; michael@0: if (i==0) michael@0: item = req->answer; michael@0: else if (i==1) michael@0: item = req->authority; michael@0: else michael@0: item = req->additional; michael@0: while (item) { michael@0: r = dnsname_to_labels(buf, buf_len, j, item->name, strlen(item->name), &table); michael@0: if (r < 0) michael@0: goto overflow; michael@0: j = r; michael@0: michael@0: APPEND16(item->type); michael@0: APPEND16(item->dns_question_class); michael@0: APPEND32(item->ttl); michael@0: if (item->is_name) { michael@0: off_t len_idx = j, name_start; michael@0: j += 2; michael@0: name_start = j; michael@0: r = dnsname_to_labels(buf, buf_len, j, item->data, strlen(item->data), &table); michael@0: if (r < 0) michael@0: goto overflow; michael@0: j = r; michael@0: _t = htons( (short) (j-name_start) ); michael@0: memcpy(buf+len_idx, &_t, 2); michael@0: } else { michael@0: APPEND16(item->datalen); michael@0: if (j+item->datalen > (off_t)buf_len) michael@0: goto overflow; michael@0: memcpy(buf+j, item->data, item->datalen); michael@0: j += item->datalen; michael@0: } michael@0: item = item->next; michael@0: } michael@0: } michael@0: michael@0: if (j > 512) { michael@0: overflow: michael@0: j = 512; michael@0: buf[2] |= 0x02; /* set the truncated bit. */ michael@0: } michael@0: michael@0: req->response_len = j; michael@0: michael@0: if (!(req->response = mm_malloc(req->response_len))) { michael@0: server_request_free_answers(req); michael@0: dnslabel_clear(&table); michael@0: return (-1); michael@0: } michael@0: memcpy(req->response, buf, req->response_len); michael@0: server_request_free_answers(req); michael@0: dnslabel_clear(&table); michael@0: return (0); michael@0: } michael@0: michael@0: /* exported function */ michael@0: int michael@0: evdns_server_request_respond(struct evdns_server_request *_req, int err) michael@0: { michael@0: struct server_request *req = TO_SERVER_REQUEST(_req); michael@0: struct evdns_server_port *port = req->port; michael@0: int r = -1; michael@0: michael@0: EVDNS_LOCK(port); michael@0: if (!req->response) { michael@0: if ((r = evdns_server_request_format_response(req, err))<0) michael@0: goto done; michael@0: } michael@0: michael@0: r = sendto(port->socket, req->response, (int)req->response_len, 0, michael@0: (struct sockaddr*) &req->addr, (ev_socklen_t)req->addrlen); michael@0: if (r<0) { michael@0: int sock_err = evutil_socket_geterror(port->socket); michael@0: if (EVUTIL_ERR_RW_RETRIABLE(sock_err)) michael@0: goto done; michael@0: michael@0: if (port->pending_replies) { michael@0: req->prev_pending = port->pending_replies->prev_pending; michael@0: req->next_pending = port->pending_replies; michael@0: req->prev_pending->next_pending = michael@0: req->next_pending->prev_pending = req; michael@0: } else { michael@0: req->prev_pending = req->next_pending = req; michael@0: port->pending_replies = req; michael@0: port->choked = 1; michael@0: michael@0: (void) event_del(&port->event); michael@0: event_assign(&port->event, port->event_base, port->socket, (port->closing?0:EV_READ) | EV_WRITE | EV_PERSIST, server_port_ready_callback, port); michael@0: michael@0: if (event_add(&port->event, NULL) < 0) { michael@0: log(EVDNS_LOG_WARN, "Error from libevent when adding event for DNS server"); michael@0: } michael@0: michael@0: } michael@0: michael@0: r = 1; michael@0: goto done; michael@0: } michael@0: if (server_request_free(req)) { michael@0: r = 0; michael@0: goto done; michael@0: } michael@0: michael@0: if (port->pending_replies) michael@0: server_port_flush(port); michael@0: michael@0: r = 0; michael@0: done: michael@0: EVDNS_UNLOCK(port); michael@0: return r; michael@0: } michael@0: michael@0: /* Free all storage held by RRs in req. */ michael@0: static void michael@0: server_request_free_answers(struct server_request *req) michael@0: { michael@0: struct server_reply_item *victim, *next, **list; michael@0: int i; michael@0: for (i = 0; i < 3; ++i) { michael@0: if (i==0) michael@0: list = &req->answer; michael@0: else if (i==1) michael@0: list = &req->authority; michael@0: else michael@0: list = &req->additional; michael@0: michael@0: victim = *list; michael@0: while (victim) { michael@0: next = victim->next; michael@0: mm_free(victim->name); michael@0: if (victim->data) michael@0: mm_free(victim->data); michael@0: mm_free(victim); michael@0: victim = next; michael@0: } michael@0: *list = NULL; michael@0: } michael@0: } michael@0: michael@0: /* Free all storage held by req, and remove links to it. */ michael@0: /* return true iff we just wound up freeing the server_port. */ michael@0: static int michael@0: server_request_free(struct server_request *req) michael@0: { michael@0: int i, rc=1, lock=0; michael@0: if (req->base.questions) { michael@0: for (i = 0; i < req->base.nquestions; ++i) michael@0: mm_free(req->base.questions[i]); michael@0: mm_free(req->base.questions); michael@0: } michael@0: michael@0: if (req->port) { michael@0: EVDNS_LOCK(req->port); michael@0: lock=1; michael@0: if (req->port->pending_replies == req) { michael@0: if (req->next_pending && req->next_pending != req) michael@0: req->port->pending_replies = req->next_pending; michael@0: else michael@0: req->port->pending_replies = NULL; michael@0: } michael@0: rc = --req->port->refcnt; michael@0: } michael@0: michael@0: if (req->response) { michael@0: mm_free(req->response); michael@0: } michael@0: michael@0: server_request_free_answers(req); michael@0: michael@0: if (req->next_pending && req->next_pending != req) { michael@0: req->next_pending->prev_pending = req->prev_pending; michael@0: req->prev_pending->next_pending = req->next_pending; michael@0: } michael@0: michael@0: if (rc == 0) { michael@0: EVDNS_UNLOCK(req->port); /* ????? nickm */ michael@0: server_port_free(req->port); michael@0: mm_free(req); michael@0: return (1); michael@0: } michael@0: if (lock) michael@0: EVDNS_UNLOCK(req->port); michael@0: mm_free(req); michael@0: return (0); michael@0: } michael@0: michael@0: /* Free all storage held by an evdns_server_port. Only called when */ michael@0: static void michael@0: server_port_free(struct evdns_server_port *port) michael@0: { michael@0: EVUTIL_ASSERT(port); michael@0: EVUTIL_ASSERT(!port->refcnt); michael@0: EVUTIL_ASSERT(!port->pending_replies); michael@0: if (port->socket > 0) { michael@0: evutil_closesocket(port->socket); michael@0: port->socket = -1; michael@0: } michael@0: (void) event_del(&port->event); michael@0: event_debug_unassign(&port->event); michael@0: EVTHREAD_FREE_LOCK(port->lock, EVTHREAD_LOCKTYPE_RECURSIVE); michael@0: mm_free(port); michael@0: } michael@0: michael@0: /* exported function */ michael@0: int michael@0: evdns_server_request_drop(struct evdns_server_request *_req) michael@0: { michael@0: struct server_request *req = TO_SERVER_REQUEST(_req); michael@0: server_request_free(req); michael@0: return 0; michael@0: } michael@0: michael@0: /* exported function */ michael@0: int michael@0: evdns_server_request_get_requesting_addr(struct evdns_server_request *_req, struct sockaddr *sa, int addr_len) michael@0: { michael@0: struct server_request *req = TO_SERVER_REQUEST(_req); michael@0: if (addr_len < (int)req->addrlen) michael@0: return -1; michael@0: memcpy(sa, &(req->addr), req->addrlen); michael@0: return req->addrlen; michael@0: } michael@0: michael@0: #undef APPEND16 michael@0: #undef APPEND32 michael@0: michael@0: /* this is a libevent callback function which is called when a request */ michael@0: /* has timed out. */ michael@0: static void michael@0: evdns_request_timeout_callback(evutil_socket_t fd, short events, void *arg) { michael@0: struct request *const req = (struct request *) arg; michael@0: struct evdns_base *base = req->base; michael@0: michael@0: (void) fd; michael@0: (void) events; michael@0: michael@0: log(EVDNS_LOG_DEBUG, "Request %p timed out", arg); michael@0: EVDNS_LOCK(base); michael@0: michael@0: req->ns->timedout++; michael@0: if (req->ns->timedout > req->base->global_max_nameserver_timeout) { michael@0: req->ns->timedout = 0; michael@0: nameserver_failed(req->ns, "request timed out."); michael@0: } michael@0: michael@0: if (req->tx_count >= req->base->global_max_retransmits) { michael@0: /* this request has failed */ michael@0: log(EVDNS_LOG_DEBUG, "Giving up on request %p; tx_count==%d", michael@0: arg, req->tx_count); michael@0: reply_schedule_callback(req, 0, DNS_ERR_TIMEOUT, NULL); michael@0: request_finished(req, &REQ_HEAD(req->base, req->trans_id), 1); michael@0: } else { michael@0: /* retransmit it */ michael@0: struct nameserver *new_ns; michael@0: log(EVDNS_LOG_DEBUG, "Retransmitting request %p; tx_count==%d", michael@0: arg, req->tx_count); michael@0: (void) evtimer_del(&req->timeout_event); michael@0: new_ns = nameserver_pick(base); michael@0: if (new_ns) michael@0: req->ns = new_ns; michael@0: evdns_request_transmit(req); michael@0: } michael@0: EVDNS_UNLOCK(base); michael@0: } michael@0: michael@0: /* try to send a request to a given server. */ michael@0: /* */ michael@0: /* return: */ michael@0: /* 0 ok */ michael@0: /* 1 temporary failure */ michael@0: /* 2 other failure */ michael@0: static int michael@0: evdns_request_transmit_to(struct request *req, struct nameserver *server) { michael@0: int r; michael@0: ASSERT_LOCKED(req->base); michael@0: ASSERT_VALID_REQUEST(req); michael@0: r = sendto(server->socket, (void*)req->request, req->request_len, 0, michael@0: (struct sockaddr *)&server->address, server->addrlen); michael@0: if (r < 0) { michael@0: int err = evutil_socket_geterror(server->socket); michael@0: if (EVUTIL_ERR_RW_RETRIABLE(err)) michael@0: return 1; michael@0: nameserver_failed(req->ns, evutil_socket_error_to_string(err)); michael@0: return 2; michael@0: } else if (r != (int)req->request_len) { michael@0: return 1; /* short write */ michael@0: } else { michael@0: return 0; michael@0: } michael@0: } michael@0: michael@0: /* try to send a request, updating the fields of the request */ michael@0: /* as needed */ michael@0: /* */ michael@0: /* return: */ michael@0: /* 0 ok */ michael@0: /* 1 failed */ michael@0: static int michael@0: evdns_request_transmit(struct request *req) { michael@0: int retcode = 0, r; michael@0: michael@0: ASSERT_LOCKED(req->base); michael@0: ASSERT_VALID_REQUEST(req); michael@0: /* if we fail to send this packet then this flag marks it */ michael@0: /* for evdns_transmit */ michael@0: req->transmit_me = 1; michael@0: EVUTIL_ASSERT(req->trans_id != 0xffff); michael@0: michael@0: if (req->ns->choked) { michael@0: /* don't bother trying to write to a socket */ michael@0: /* which we have had EAGAIN from */ michael@0: return 1; michael@0: } michael@0: michael@0: r = evdns_request_transmit_to(req, req->ns); michael@0: switch (r) { michael@0: case 1: michael@0: /* temp failure */ michael@0: req->ns->choked = 1; michael@0: nameserver_write_waiting(req->ns, 1); michael@0: return 1; michael@0: case 2: michael@0: /* failed to transmit the request entirely. */ michael@0: retcode = 1; michael@0: /* fall through: we'll set a timeout, which will time out, michael@0: * and make us retransmit the request anyway. */ michael@0: default: michael@0: /* all ok */ michael@0: log(EVDNS_LOG_DEBUG, michael@0: "Setting timeout for request %p, sent to nameserver %p", req, req->ns); michael@0: if (evtimer_add(&req->timeout_event, &req->base->global_timeout) < 0) { michael@0: log(EVDNS_LOG_WARN, michael@0: "Error from libevent when adding timer for request %p", michael@0: req); michael@0: /* ???? Do more? */ michael@0: } michael@0: req->tx_count++; michael@0: req->transmit_me = 0; michael@0: return retcode; michael@0: } michael@0: } michael@0: michael@0: static void michael@0: nameserver_probe_callback(int result, char type, int count, int ttl, void *addresses, void *arg) { michael@0: struct nameserver *const ns = (struct nameserver *) arg; michael@0: (void) type; michael@0: (void) count; michael@0: (void) ttl; michael@0: (void) addresses; michael@0: michael@0: if (result == DNS_ERR_CANCEL) { michael@0: /* We canceled this request because the nameserver came up michael@0: * for some other reason. Do not change our opinion about michael@0: * the nameserver. */ michael@0: return; michael@0: } michael@0: michael@0: EVDNS_LOCK(ns->base); michael@0: ns->probe_request = NULL; michael@0: if (result == DNS_ERR_NONE || result == DNS_ERR_NOTEXIST) { michael@0: /* this is a good reply */ michael@0: nameserver_up(ns); michael@0: } else { michael@0: nameserver_probe_failed(ns); michael@0: } michael@0: EVDNS_UNLOCK(ns->base); michael@0: } michael@0: michael@0: static void michael@0: nameserver_send_probe(struct nameserver *const ns) { michael@0: struct evdns_request *handle; michael@0: struct request *req; michael@0: char addrbuf[128]; michael@0: /* here we need to send a probe to a given nameserver */ michael@0: /* in the hope that it is up now. */ michael@0: michael@0: ASSERT_LOCKED(ns->base); michael@0: log(EVDNS_LOG_DEBUG, "Sending probe to %s", michael@0: evutil_format_sockaddr_port( michael@0: (struct sockaddr *)&ns->address, michael@0: addrbuf, sizeof(addrbuf))); michael@0: handle = mm_calloc(1, sizeof(*handle)); michael@0: if (!handle) return; michael@0: req = request_new(ns->base, handle, TYPE_A, "google.com", DNS_QUERY_NO_SEARCH, nameserver_probe_callback, ns); michael@0: if (!req) { michael@0: mm_free(handle); michael@0: return; michael@0: } michael@0: ns->probe_request = handle; michael@0: /* we force this into the inflight queue no matter what */ michael@0: request_trans_id_set(req, transaction_id_pick(ns->base)); michael@0: req->ns = ns; michael@0: request_submit(req); michael@0: } michael@0: michael@0: /* returns: */ michael@0: /* 0 didn't try to transmit anything */ michael@0: /* 1 tried to transmit something */ michael@0: static int michael@0: evdns_transmit(struct evdns_base *base) { michael@0: char did_try_to_transmit = 0; michael@0: int i; michael@0: michael@0: ASSERT_LOCKED(base); michael@0: for (i = 0; i < base->n_req_heads; ++i) { michael@0: if (base->req_heads[i]) { michael@0: struct request *const started_at = base->req_heads[i], *req = started_at; michael@0: /* first transmit all the requests which are currently waiting */ michael@0: do { michael@0: if (req->transmit_me) { michael@0: did_try_to_transmit = 1; michael@0: evdns_request_transmit(req); michael@0: } michael@0: michael@0: req = req->next; michael@0: } while (req != started_at); michael@0: } michael@0: } michael@0: michael@0: return did_try_to_transmit; michael@0: } michael@0: michael@0: /* exported function */ michael@0: int michael@0: evdns_base_count_nameservers(struct evdns_base *base) michael@0: { michael@0: const struct nameserver *server; michael@0: int n = 0; michael@0: michael@0: EVDNS_LOCK(base); michael@0: server = base->server_head; michael@0: if (!server) michael@0: goto done; michael@0: do { michael@0: ++n; michael@0: server = server->next; michael@0: } while (server != base->server_head); michael@0: done: michael@0: EVDNS_UNLOCK(base); michael@0: return n; michael@0: } michael@0: michael@0: int michael@0: evdns_count_nameservers(void) michael@0: { michael@0: return evdns_base_count_nameservers(current_base); michael@0: } michael@0: michael@0: /* exported function */ michael@0: int michael@0: evdns_base_clear_nameservers_and_suspend(struct evdns_base *base) michael@0: { michael@0: struct nameserver *server, *started_at; michael@0: int i; michael@0: michael@0: EVDNS_LOCK(base); michael@0: server = base->server_head; michael@0: started_at = base->server_head; michael@0: if (!server) { michael@0: EVDNS_UNLOCK(base); michael@0: return 0; michael@0: } michael@0: while (1) { michael@0: struct nameserver *next = server->next; michael@0: (void) event_del(&server->event); michael@0: if (evtimer_initialized(&server->timeout_event)) michael@0: (void) evtimer_del(&server->timeout_event); michael@0: if (server->probe_request) { michael@0: evdns_cancel_request(server->base, server->probe_request); michael@0: server->probe_request = NULL; michael@0: } michael@0: if (server->socket >= 0) michael@0: evutil_closesocket(server->socket); michael@0: mm_free(server); michael@0: if (next == started_at) michael@0: break; michael@0: server = next; michael@0: } michael@0: base->server_head = NULL; michael@0: base->global_good_nameservers = 0; michael@0: michael@0: for (i = 0; i < base->n_req_heads; ++i) { michael@0: struct request *req, *req_started_at; michael@0: req = req_started_at = base->req_heads[i]; michael@0: while (req) { michael@0: struct request *next = req->next; michael@0: req->tx_count = req->reissue_count = 0; michael@0: req->ns = NULL; michael@0: /* ???? What to do about searches? */ michael@0: (void) evtimer_del(&req->timeout_event); michael@0: req->trans_id = 0; michael@0: req->transmit_me = 0; michael@0: michael@0: base->global_requests_waiting++; michael@0: evdns_request_insert(req, &base->req_waiting_head); michael@0: /* We want to insert these suspended elements at the front of michael@0: * the waiting queue, since they were pending before any of michael@0: * the waiting entries were added. This is a circular list, michael@0: * so we can just shift the start back by one.*/ michael@0: base->req_waiting_head = base->req_waiting_head->prev; michael@0: michael@0: if (next == req_started_at) michael@0: break; michael@0: req = next; michael@0: } michael@0: base->req_heads[i] = NULL; michael@0: } michael@0: michael@0: base->global_requests_inflight = 0; michael@0: michael@0: EVDNS_UNLOCK(base); michael@0: return 0; michael@0: } michael@0: michael@0: int michael@0: evdns_clear_nameservers_and_suspend(void) michael@0: { michael@0: return evdns_base_clear_nameservers_and_suspend(current_base); michael@0: } michael@0: michael@0: michael@0: /* exported function */ michael@0: int michael@0: evdns_base_resume(struct evdns_base *base) michael@0: { michael@0: EVDNS_LOCK(base); michael@0: evdns_requests_pump_waiting_queue(base); michael@0: EVDNS_UNLOCK(base); michael@0: return 0; michael@0: } michael@0: michael@0: int michael@0: evdns_resume(void) michael@0: { michael@0: return evdns_base_resume(current_base); michael@0: } michael@0: michael@0: static int michael@0: _evdns_nameserver_add_impl(struct evdns_base *base, const struct sockaddr *address, int addrlen) { michael@0: /* first check to see if we already have this nameserver */ michael@0: michael@0: const struct nameserver *server = base->server_head, *const started_at = base->server_head; michael@0: struct nameserver *ns; michael@0: int err = 0; michael@0: char addrbuf[128]; michael@0: michael@0: ASSERT_LOCKED(base); michael@0: if (server) { michael@0: do { michael@0: if (!evutil_sockaddr_cmp((struct sockaddr*)&server->address, address, 1)) return 3; michael@0: server = server->next; michael@0: } while (server != started_at); michael@0: } michael@0: if (addrlen > (int)sizeof(ns->address)) { michael@0: log(EVDNS_LOG_DEBUG, "Addrlen %d too long.", (int)addrlen); michael@0: return 2; michael@0: } michael@0: michael@0: ns = (struct nameserver *) mm_malloc(sizeof(struct nameserver)); michael@0: if (!ns) return -1; michael@0: michael@0: memset(ns, 0, sizeof(struct nameserver)); michael@0: ns->base = base; michael@0: michael@0: evtimer_assign(&ns->timeout_event, ns->base->event_base, nameserver_prod_callback, ns); michael@0: michael@0: ns->socket = socket(address->sa_family, SOCK_DGRAM, 0); michael@0: if (ns->socket < 0) { err = 1; goto out1; } michael@0: evutil_make_socket_closeonexec(ns->socket); michael@0: evutil_make_socket_nonblocking(ns->socket); michael@0: michael@0: if (base->global_outgoing_addrlen && michael@0: !evutil_sockaddr_is_loopback(address)) { michael@0: if (bind(ns->socket, michael@0: (struct sockaddr*)&base->global_outgoing_address, michael@0: base->global_outgoing_addrlen) < 0) { michael@0: log(EVDNS_LOG_WARN,"Couldn't bind to outgoing address"); michael@0: err = 2; michael@0: goto out2; michael@0: } michael@0: } michael@0: michael@0: memcpy(&ns->address, address, addrlen); michael@0: ns->addrlen = addrlen; michael@0: ns->state = 1; michael@0: event_assign(&ns->event, ns->base->event_base, ns->socket, EV_READ | EV_PERSIST, nameserver_ready_callback, ns); michael@0: if (event_add(&ns->event, NULL) < 0) { michael@0: err = 2; michael@0: goto out2; michael@0: } michael@0: michael@0: log(EVDNS_LOG_DEBUG, "Added nameserver %s as %p", michael@0: evutil_format_sockaddr_port(address, addrbuf, sizeof(addrbuf)), ns); michael@0: michael@0: /* insert this nameserver into the list of them */ michael@0: if (!base->server_head) { michael@0: ns->next = ns->prev = ns; michael@0: base->server_head = ns; michael@0: } else { michael@0: ns->next = base->server_head->next; michael@0: ns->prev = base->server_head; michael@0: base->server_head->next = ns; michael@0: ns->next->prev = ns; michael@0: } michael@0: michael@0: base->global_good_nameservers++; michael@0: michael@0: return 0; michael@0: michael@0: out2: michael@0: evutil_closesocket(ns->socket); michael@0: out1: michael@0: event_debug_unassign(&ns->event); michael@0: mm_free(ns); michael@0: log(EVDNS_LOG_WARN, "Unable to add nameserver %s: error %d", michael@0: evutil_format_sockaddr_port(address, addrbuf, sizeof(addrbuf)), err); michael@0: return err; michael@0: } michael@0: michael@0: /* exported function */ michael@0: int michael@0: evdns_base_nameserver_add(struct evdns_base *base, unsigned long int address) michael@0: { michael@0: struct sockaddr_in sin; michael@0: int res; michael@0: memset(&sin, 0, sizeof(sin)); michael@0: sin.sin_addr.s_addr = address; michael@0: sin.sin_port = htons(53); michael@0: sin.sin_family = AF_INET; michael@0: EVDNS_LOCK(base); michael@0: res = _evdns_nameserver_add_impl(base, (struct sockaddr*)&sin, sizeof(sin)); michael@0: EVDNS_UNLOCK(base); michael@0: return res; michael@0: } michael@0: michael@0: int michael@0: evdns_nameserver_add(unsigned long int address) { michael@0: if (!current_base) michael@0: current_base = evdns_base_new(NULL, 0); michael@0: return evdns_base_nameserver_add(current_base, address); michael@0: } michael@0: michael@0: static void michael@0: sockaddr_setport(struct sockaddr *sa, ev_uint16_t port) michael@0: { michael@0: if (sa->sa_family == AF_INET) { michael@0: ((struct sockaddr_in *)sa)->sin_port = htons(port); michael@0: } else if (sa->sa_family == AF_INET6) { michael@0: ((struct sockaddr_in6 *)sa)->sin6_port = htons(port); michael@0: } michael@0: } michael@0: michael@0: static ev_uint16_t michael@0: sockaddr_getport(struct sockaddr *sa) michael@0: { michael@0: if (sa->sa_family == AF_INET) { michael@0: return ntohs(((struct sockaddr_in *)sa)->sin_port); michael@0: } else if (sa->sa_family == AF_INET6) { michael@0: return ntohs(((struct sockaddr_in6 *)sa)->sin6_port); michael@0: } else { michael@0: return 0; michael@0: } michael@0: } michael@0: michael@0: /* exported function */ michael@0: int michael@0: evdns_base_nameserver_ip_add(struct evdns_base *base, const char *ip_as_string) { michael@0: struct sockaddr_storage ss; michael@0: struct sockaddr *sa; michael@0: int len = sizeof(ss); michael@0: int res; michael@0: if (evutil_parse_sockaddr_port(ip_as_string, (struct sockaddr *)&ss, michael@0: &len)) { michael@0: log(EVDNS_LOG_WARN, "Unable to parse nameserver address %s", michael@0: ip_as_string); michael@0: return 4; michael@0: } michael@0: sa = (struct sockaddr *) &ss; michael@0: if (sockaddr_getport(sa) == 0) michael@0: sockaddr_setport(sa, 53); michael@0: michael@0: EVDNS_LOCK(base); michael@0: res = _evdns_nameserver_add_impl(base, sa, len); michael@0: EVDNS_UNLOCK(base); michael@0: return res; michael@0: } michael@0: michael@0: int michael@0: evdns_nameserver_ip_add(const char *ip_as_string) { michael@0: if (!current_base) michael@0: current_base = evdns_base_new(NULL, 0); michael@0: return evdns_base_nameserver_ip_add(current_base, ip_as_string); michael@0: } michael@0: michael@0: int michael@0: evdns_base_nameserver_sockaddr_add(struct evdns_base *base, michael@0: const struct sockaddr *sa, ev_socklen_t len, unsigned flags) michael@0: { michael@0: int res; michael@0: EVUTIL_ASSERT(base); michael@0: EVDNS_LOCK(base); michael@0: res = _evdns_nameserver_add_impl(base, sa, len); michael@0: EVDNS_UNLOCK(base); michael@0: return res; michael@0: } michael@0: michael@0: /* remove from the queue */ michael@0: static void michael@0: evdns_request_remove(struct request *req, struct request **head) michael@0: { michael@0: ASSERT_LOCKED(req->base); michael@0: ASSERT_VALID_REQUEST(req); michael@0: michael@0: #if 0 michael@0: { michael@0: struct request *ptr; michael@0: int found = 0; michael@0: EVUTIL_ASSERT(*head != NULL); michael@0: michael@0: ptr = *head; michael@0: do { michael@0: if (ptr == req) { michael@0: found = 1; michael@0: break; michael@0: } michael@0: ptr = ptr->next; michael@0: } while (ptr != *head); michael@0: EVUTIL_ASSERT(found); michael@0: michael@0: EVUTIL_ASSERT(req->next); michael@0: } michael@0: #endif michael@0: michael@0: if (req->next == req) { michael@0: /* only item in the list */ michael@0: *head = NULL; michael@0: } else { michael@0: req->next->prev = req->prev; michael@0: req->prev->next = req->next; michael@0: if (*head == req) *head = req->next; michael@0: } michael@0: req->next = req->prev = NULL; michael@0: } michael@0: michael@0: /* insert into the tail of the queue */ michael@0: static void michael@0: evdns_request_insert(struct request *req, struct request **head) { michael@0: ASSERT_LOCKED(req->base); michael@0: ASSERT_VALID_REQUEST(req); michael@0: if (!*head) { michael@0: *head = req; michael@0: req->next = req->prev = req; michael@0: return; michael@0: } michael@0: michael@0: req->prev = (*head)->prev; michael@0: req->prev->next = req; michael@0: req->next = *head; michael@0: (*head)->prev = req; michael@0: } michael@0: michael@0: static int michael@0: string_num_dots(const char *s) { michael@0: int count = 0; michael@0: while ((s = strchr(s, '.'))) { michael@0: s++; michael@0: count++; michael@0: } michael@0: return count; michael@0: } michael@0: michael@0: static struct request * michael@0: request_new(struct evdns_base *base, struct evdns_request *handle, int type, michael@0: const char *name, int flags, evdns_callback_type callback, michael@0: void *user_ptr) { michael@0: michael@0: const char issuing_now = michael@0: (base->global_requests_inflight < base->global_max_requests_inflight) ? 1 : 0; michael@0: michael@0: const size_t name_len = strlen(name); michael@0: const size_t request_max_len = evdns_request_len(name_len); michael@0: const u16 trans_id = issuing_now ? transaction_id_pick(base) : 0xffff; michael@0: /* the request data is alloced in a single block with the header */ michael@0: struct request *const req = michael@0: mm_malloc(sizeof(struct request) + request_max_len); michael@0: int rlen; michael@0: char namebuf[256]; michael@0: (void) flags; michael@0: michael@0: ASSERT_LOCKED(base); michael@0: michael@0: if (!req) return NULL; michael@0: michael@0: if (name_len >= sizeof(namebuf)) { michael@0: mm_free(req); michael@0: return NULL; michael@0: } michael@0: michael@0: memset(req, 0, sizeof(struct request)); michael@0: req->base = base; michael@0: michael@0: evtimer_assign(&req->timeout_event, req->base->event_base, evdns_request_timeout_callback, req); michael@0: michael@0: if (base->global_randomize_case) { michael@0: unsigned i; michael@0: char randbits[(sizeof(namebuf)+7)/8]; michael@0: strlcpy(namebuf, name, sizeof(namebuf)); michael@0: evutil_secure_rng_get_bytes(randbits, (name_len+7)/8); michael@0: for (i = 0; i < name_len; ++i) { michael@0: if (EVUTIL_ISALPHA(namebuf[i])) { michael@0: if ((randbits[i >> 3] & (1<<(i & 7)))) michael@0: namebuf[i] |= 0x20; michael@0: else michael@0: namebuf[i] &= ~0x20; michael@0: } michael@0: } michael@0: name = namebuf; michael@0: } michael@0: michael@0: /* request data lives just after the header */ michael@0: req->request = ((u8 *) req) + sizeof(struct request); michael@0: /* denotes that the request data shouldn't be free()ed */ michael@0: req->request_appended = 1; michael@0: rlen = evdns_request_data_build(name, name_len, trans_id, michael@0: type, CLASS_INET, req->request, request_max_len); michael@0: if (rlen < 0) michael@0: goto err1; michael@0: michael@0: req->request_len = rlen; michael@0: req->trans_id = trans_id; michael@0: req->tx_count = 0; michael@0: req->request_type = type; michael@0: req->user_pointer = user_ptr; michael@0: req->user_callback = callback; michael@0: req->ns = issuing_now ? nameserver_pick(base) : NULL; michael@0: req->next = req->prev = NULL; michael@0: req->handle = handle; michael@0: if (handle) { michael@0: handle->current_req = req; michael@0: handle->base = base; michael@0: } michael@0: michael@0: return req; michael@0: err1: michael@0: mm_free(req); michael@0: return NULL; michael@0: } michael@0: michael@0: static void michael@0: request_submit(struct request *const req) { michael@0: struct evdns_base *base = req->base; michael@0: ASSERT_LOCKED(base); michael@0: ASSERT_VALID_REQUEST(req); michael@0: if (req->ns) { michael@0: /* if it has a nameserver assigned then this is going */ michael@0: /* straight into the inflight queue */ michael@0: evdns_request_insert(req, &REQ_HEAD(base, req->trans_id)); michael@0: base->global_requests_inflight++; michael@0: evdns_request_transmit(req); michael@0: } else { michael@0: evdns_request_insert(req, &base->req_waiting_head); michael@0: base->global_requests_waiting++; michael@0: } michael@0: } michael@0: michael@0: /* exported function */ michael@0: void michael@0: evdns_cancel_request(struct evdns_base *base, struct evdns_request *handle) michael@0: { michael@0: struct request *req; michael@0: michael@0: if (!handle->current_req) michael@0: return; michael@0: michael@0: if (!base) { michael@0: /* This redundancy is silly; can we fix it? (Not for 2.0) XXXX */ michael@0: base = handle->base; michael@0: if (!base) michael@0: base = handle->current_req->base; michael@0: } michael@0: michael@0: EVDNS_LOCK(base); michael@0: if (handle->pending_cb) { michael@0: EVDNS_UNLOCK(base); michael@0: return; michael@0: } michael@0: michael@0: req = handle->current_req; michael@0: ASSERT_VALID_REQUEST(req); michael@0: michael@0: reply_schedule_callback(req, 0, DNS_ERR_CANCEL, NULL); michael@0: if (req->ns) { michael@0: /* remove from inflight queue */ michael@0: request_finished(req, &REQ_HEAD(base, req->trans_id), 1); michael@0: } else { michael@0: /* remove from global_waiting head */ michael@0: request_finished(req, &base->req_waiting_head, 1); michael@0: } michael@0: EVDNS_UNLOCK(base); michael@0: } michael@0: michael@0: /* exported function */ michael@0: struct evdns_request * michael@0: evdns_base_resolve_ipv4(struct evdns_base *base, const char *name, int flags, michael@0: evdns_callback_type callback, void *ptr) { michael@0: struct evdns_request *handle; michael@0: struct request *req; michael@0: log(EVDNS_LOG_DEBUG, "Resolve requested for %s", name); michael@0: handle = mm_calloc(1, sizeof(*handle)); michael@0: if (handle == NULL) michael@0: return NULL; michael@0: EVDNS_LOCK(base); michael@0: if (flags & DNS_QUERY_NO_SEARCH) { michael@0: req = michael@0: request_new(base, handle, TYPE_A, name, flags, michael@0: callback, ptr); michael@0: if (req) michael@0: request_submit(req); michael@0: } else { michael@0: search_request_new(base, handle, TYPE_A, name, flags, michael@0: callback, ptr); michael@0: } michael@0: if (handle->current_req == NULL) { michael@0: mm_free(handle); michael@0: handle = NULL; michael@0: } michael@0: EVDNS_UNLOCK(base); michael@0: return handle; michael@0: } michael@0: michael@0: int evdns_resolve_ipv4(const char *name, int flags, michael@0: evdns_callback_type callback, void *ptr) michael@0: { michael@0: return evdns_base_resolve_ipv4(current_base, name, flags, callback, ptr) michael@0: ? 0 : -1; michael@0: } michael@0: michael@0: michael@0: /* exported function */ michael@0: struct evdns_request * michael@0: evdns_base_resolve_ipv6(struct evdns_base *base, michael@0: const char *name, int flags, michael@0: evdns_callback_type callback, void *ptr) michael@0: { michael@0: struct evdns_request *handle; michael@0: struct request *req; michael@0: log(EVDNS_LOG_DEBUG, "Resolve requested for %s", name); michael@0: handle = mm_calloc(1, sizeof(*handle)); michael@0: if (handle == NULL) michael@0: return NULL; michael@0: EVDNS_LOCK(base); michael@0: if (flags & DNS_QUERY_NO_SEARCH) { michael@0: req = request_new(base, handle, TYPE_AAAA, name, flags, michael@0: callback, ptr); michael@0: if (req) michael@0: request_submit(req); michael@0: } else { michael@0: search_request_new(base, handle, TYPE_AAAA, name, flags, michael@0: callback, ptr); michael@0: } michael@0: if (handle->current_req == NULL) { michael@0: mm_free(handle); michael@0: handle = NULL; michael@0: } michael@0: EVDNS_UNLOCK(base); michael@0: return handle; michael@0: } michael@0: michael@0: int evdns_resolve_ipv6(const char *name, int flags, michael@0: evdns_callback_type callback, void *ptr) { michael@0: return evdns_base_resolve_ipv6(current_base, name, flags, callback, ptr) michael@0: ? 0 : -1; michael@0: } michael@0: michael@0: struct evdns_request * michael@0: evdns_base_resolve_reverse(struct evdns_base *base, const struct in_addr *in, int flags, evdns_callback_type callback, void *ptr) { michael@0: char buf[32]; michael@0: struct evdns_request *handle; michael@0: struct request *req; michael@0: u32 a; michael@0: EVUTIL_ASSERT(in); michael@0: a = ntohl(in->s_addr); michael@0: evutil_snprintf(buf, sizeof(buf), "%d.%d.%d.%d.in-addr.arpa", michael@0: (int)(u8)((a )&0xff), michael@0: (int)(u8)((a>>8 )&0xff), michael@0: (int)(u8)((a>>16)&0xff), michael@0: (int)(u8)((a>>24)&0xff)); michael@0: handle = mm_calloc(1, sizeof(*handle)); michael@0: if (handle == NULL) michael@0: return NULL; michael@0: log(EVDNS_LOG_DEBUG, "Resolve requested for %s (reverse)", buf); michael@0: EVDNS_LOCK(base); michael@0: req = request_new(base, handle, TYPE_PTR, buf, flags, callback, ptr); michael@0: if (req) michael@0: request_submit(req); michael@0: if (handle->current_req == NULL) { michael@0: mm_free(handle); michael@0: handle = NULL; michael@0: } michael@0: EVDNS_UNLOCK(base); michael@0: return (handle); michael@0: } michael@0: michael@0: int evdns_resolve_reverse(const struct in_addr *in, int flags, evdns_callback_type callback, void *ptr) { michael@0: return evdns_base_resolve_reverse(current_base, in, flags, callback, ptr) michael@0: ? 0 : -1; michael@0: } michael@0: michael@0: struct evdns_request * michael@0: evdns_base_resolve_reverse_ipv6(struct evdns_base *base, const struct in6_addr *in, int flags, evdns_callback_type callback, void *ptr) { michael@0: /* 32 nybbles, 32 periods, "ip6.arpa", NUL. */ michael@0: char buf[73]; michael@0: char *cp; michael@0: struct evdns_request *handle; michael@0: struct request *req; michael@0: int i; michael@0: EVUTIL_ASSERT(in); michael@0: cp = buf; michael@0: for (i=15; i >= 0; --i) { michael@0: u8 byte = in->s6_addr[i]; michael@0: *cp++ = "0123456789abcdef"[byte & 0x0f]; michael@0: *cp++ = '.'; michael@0: *cp++ = "0123456789abcdef"[byte >> 4]; michael@0: *cp++ = '.'; michael@0: } michael@0: EVUTIL_ASSERT(cp + strlen("ip6.arpa") < buf+sizeof(buf)); michael@0: memcpy(cp, "ip6.arpa", strlen("ip6.arpa")+1); michael@0: handle = mm_calloc(1, sizeof(*handle)); michael@0: if (handle == NULL) michael@0: return NULL; michael@0: log(EVDNS_LOG_DEBUG, "Resolve requested for %s (reverse)", buf); michael@0: EVDNS_LOCK(base); michael@0: req = request_new(base, handle, TYPE_PTR, buf, flags, callback, ptr); michael@0: if (req) michael@0: request_submit(req); michael@0: if (handle->current_req == NULL) { michael@0: mm_free(handle); michael@0: handle = NULL; michael@0: } michael@0: EVDNS_UNLOCK(base); michael@0: return (handle); michael@0: } michael@0: michael@0: int evdns_resolve_reverse_ipv6(const struct in6_addr *in, int flags, evdns_callback_type callback, void *ptr) { michael@0: return evdns_base_resolve_reverse_ipv6(current_base, in, flags, callback, ptr) michael@0: ? 0 : -1; michael@0: } michael@0: michael@0: /* ================================================================= */ michael@0: /* Search support */ michael@0: /* */ michael@0: /* the libc resolver has support for searching a number of domains */ michael@0: /* to find a name. If nothing else then it takes the single domain */ michael@0: /* from the gethostname() call. */ michael@0: /* */ michael@0: /* It can also be configured via the domain and search options in a */ michael@0: /* resolv.conf. */ michael@0: /* */ michael@0: /* The ndots option controls how many dots it takes for the resolver */ michael@0: /* to decide that a name is non-local and so try a raw lookup first. */ michael@0: michael@0: struct search_domain { michael@0: int len; michael@0: struct search_domain *next; michael@0: /* the text string is appended to this structure */ michael@0: }; michael@0: michael@0: struct search_state { michael@0: int refcount; michael@0: int ndots; michael@0: int num_domains; michael@0: struct search_domain *head; michael@0: }; michael@0: michael@0: static void michael@0: search_state_decref(struct search_state *const state) { michael@0: if (!state) return; michael@0: state->refcount--; michael@0: if (!state->refcount) { michael@0: struct search_domain *next, *dom; michael@0: for (dom = state->head; dom; dom = next) { michael@0: next = dom->next; michael@0: mm_free(dom); michael@0: } michael@0: mm_free(state); michael@0: } michael@0: } michael@0: michael@0: static struct search_state * michael@0: search_state_new(void) { michael@0: struct search_state *state = (struct search_state *) mm_malloc(sizeof(struct search_state)); michael@0: if (!state) return NULL; michael@0: memset(state, 0, sizeof(struct search_state)); michael@0: state->refcount = 1; michael@0: state->ndots = 1; michael@0: michael@0: return state; michael@0: } michael@0: michael@0: static void michael@0: search_postfix_clear(struct evdns_base *base) { michael@0: search_state_decref(base->global_search_state); michael@0: michael@0: base->global_search_state = search_state_new(); michael@0: } michael@0: michael@0: /* exported function */ michael@0: void michael@0: evdns_base_search_clear(struct evdns_base *base) michael@0: { michael@0: EVDNS_LOCK(base); michael@0: search_postfix_clear(base); michael@0: EVDNS_UNLOCK(base); michael@0: } michael@0: michael@0: void michael@0: evdns_search_clear(void) { michael@0: evdns_base_search_clear(current_base); michael@0: } michael@0: michael@0: static void michael@0: search_postfix_add(struct evdns_base *base, const char *domain) { michael@0: size_t domain_len; michael@0: struct search_domain *sdomain; michael@0: while (domain[0] == '.') domain++; michael@0: domain_len = strlen(domain); michael@0: michael@0: ASSERT_LOCKED(base); michael@0: if (!base->global_search_state) base->global_search_state = search_state_new(); michael@0: if (!base->global_search_state) return; michael@0: base->global_search_state->num_domains++; michael@0: michael@0: sdomain = (struct search_domain *) mm_malloc(sizeof(struct search_domain) + domain_len); michael@0: if (!sdomain) return; michael@0: memcpy( ((u8 *) sdomain) + sizeof(struct search_domain), domain, domain_len); michael@0: sdomain->next = base->global_search_state->head; michael@0: sdomain->len = (int) domain_len; michael@0: michael@0: base->global_search_state->head = sdomain; michael@0: } michael@0: michael@0: /* reverse the order of members in the postfix list. This is needed because, */ michael@0: /* when parsing resolv.conf we push elements in the wrong order */ michael@0: static void michael@0: search_reverse(struct evdns_base *base) { michael@0: struct search_domain *cur, *prev = NULL, *next; michael@0: ASSERT_LOCKED(base); michael@0: cur = base->global_search_state->head; michael@0: while (cur) { michael@0: next = cur->next; michael@0: cur->next = prev; michael@0: prev = cur; michael@0: cur = next; michael@0: } michael@0: michael@0: base->global_search_state->head = prev; michael@0: } michael@0: michael@0: /* exported function */ michael@0: void michael@0: evdns_base_search_add(struct evdns_base *base, const char *domain) { michael@0: EVDNS_LOCK(base); michael@0: search_postfix_add(base, domain); michael@0: EVDNS_UNLOCK(base); michael@0: } michael@0: void michael@0: evdns_search_add(const char *domain) { michael@0: evdns_base_search_add(current_base, domain); michael@0: } michael@0: michael@0: /* exported function */ michael@0: void michael@0: evdns_base_search_ndots_set(struct evdns_base *base, const int ndots) { michael@0: EVDNS_LOCK(base); michael@0: if (!base->global_search_state) base->global_search_state = search_state_new(); michael@0: if (base->global_search_state) michael@0: base->global_search_state->ndots = ndots; michael@0: EVDNS_UNLOCK(base); michael@0: } michael@0: void michael@0: evdns_search_ndots_set(const int ndots) { michael@0: evdns_base_search_ndots_set(current_base, ndots); michael@0: } michael@0: michael@0: static void michael@0: search_set_from_hostname(struct evdns_base *base) { michael@0: char hostname[HOST_NAME_MAX + 1], *domainname; michael@0: michael@0: ASSERT_LOCKED(base); michael@0: search_postfix_clear(base); michael@0: if (gethostname(hostname, sizeof(hostname))) return; michael@0: domainname = strchr(hostname, '.'); michael@0: if (!domainname) return; michael@0: search_postfix_add(base, domainname); michael@0: } michael@0: michael@0: /* warning: returns malloced string */ michael@0: static char * michael@0: search_make_new(const struct search_state *const state, int n, const char *const base_name) { michael@0: const size_t base_len = strlen(base_name); michael@0: const char need_to_append_dot = base_name[base_len - 1] == '.' ? 0 : 1; michael@0: struct search_domain *dom; michael@0: michael@0: for (dom = state->head; dom; dom = dom->next) { michael@0: if (!n--) { michael@0: /* this is the postfix we want */ michael@0: /* the actual postfix string is kept at the end of the structure */ michael@0: const u8 *const postfix = ((u8 *) dom) + sizeof(struct search_domain); michael@0: const int postfix_len = dom->len; michael@0: char *const newname = (char *) mm_malloc(base_len + need_to_append_dot + postfix_len + 1); michael@0: if (!newname) return NULL; michael@0: memcpy(newname, base_name, base_len); michael@0: if (need_to_append_dot) newname[base_len] = '.'; michael@0: memcpy(newname + base_len + need_to_append_dot, postfix, postfix_len); michael@0: newname[base_len + need_to_append_dot + postfix_len] = 0; michael@0: return newname; michael@0: } michael@0: } michael@0: michael@0: /* we ran off the end of the list and still didn't find the requested string */ michael@0: EVUTIL_ASSERT(0); michael@0: return NULL; /* unreachable; stops warnings in some compilers. */ michael@0: } michael@0: michael@0: static struct request * michael@0: search_request_new(struct evdns_base *base, struct evdns_request *handle, michael@0: int type, const char *const name, int flags, michael@0: evdns_callback_type user_callback, void *user_arg) { michael@0: ASSERT_LOCKED(base); michael@0: EVUTIL_ASSERT(type == TYPE_A || type == TYPE_AAAA); michael@0: EVUTIL_ASSERT(handle->current_req == NULL); michael@0: if ( ((flags & DNS_QUERY_NO_SEARCH) == 0) && michael@0: base->global_search_state && michael@0: base->global_search_state->num_domains) { michael@0: /* we have some domains to search */ michael@0: struct request *req; michael@0: if (string_num_dots(name) >= base->global_search_state->ndots) { michael@0: req = request_new(base, handle, type, name, flags, user_callback, user_arg); michael@0: if (!req) return NULL; michael@0: handle->search_index = -1; michael@0: } else { michael@0: char *const new_name = search_make_new(base->global_search_state, 0, name); michael@0: if (!new_name) return NULL; michael@0: req = request_new(base, handle, type, new_name, flags, user_callback, user_arg); michael@0: mm_free(new_name); michael@0: if (!req) return NULL; michael@0: handle->search_index = 0; michael@0: } michael@0: EVUTIL_ASSERT(handle->search_origname == NULL); michael@0: handle->search_origname = mm_strdup(name); michael@0: if (handle->search_origname == NULL) { michael@0: /* XXX Should we dealloc req? If yes, how? */ michael@0: if (req) michael@0: mm_free(req); michael@0: return NULL; michael@0: } michael@0: handle->search_state = base->global_search_state; michael@0: handle->search_flags = flags; michael@0: base->global_search_state->refcount++; michael@0: request_submit(req); michael@0: return req; michael@0: } else { michael@0: struct request *const req = request_new(base, handle, type, name, flags, user_callback, user_arg); michael@0: if (!req) return NULL; michael@0: request_submit(req); michael@0: return req; michael@0: } michael@0: } michael@0: michael@0: /* this is called when a request has failed to find a name. We need to check */ michael@0: /* if it is part of a search and, if so, try the next name in the list */ michael@0: /* returns: */ michael@0: /* 0 another request has been submitted */ michael@0: /* 1 no more requests needed */ michael@0: static int michael@0: search_try_next(struct evdns_request *const handle) { michael@0: struct request *req = handle->current_req; michael@0: struct evdns_base *base = req->base; michael@0: struct request *newreq; michael@0: ASSERT_LOCKED(base); michael@0: if (handle->search_state) { michael@0: /* it is part of a search */ michael@0: char *new_name; michael@0: handle->search_index++; michael@0: if (handle->search_index >= handle->search_state->num_domains) { michael@0: /* no more postfixes to try, however we may need to try */ michael@0: /* this name without a postfix */ michael@0: if (string_num_dots(handle->search_origname) < handle->search_state->ndots) { michael@0: /* yep, we need to try it raw */ michael@0: newreq = request_new(base, NULL, req->request_type, handle->search_origname, handle->search_flags, req->user_callback, req->user_pointer); michael@0: log(EVDNS_LOG_DEBUG, "Search: trying raw query %s", handle->search_origname); michael@0: if (newreq) { michael@0: search_request_finished(handle); michael@0: goto submit_next; michael@0: } michael@0: } michael@0: return 1; michael@0: } michael@0: michael@0: new_name = search_make_new(handle->search_state, handle->search_index, handle->search_origname); michael@0: if (!new_name) return 1; michael@0: log(EVDNS_LOG_DEBUG, "Search: now trying %s (%d)", new_name, handle->search_index); michael@0: newreq = request_new(base, NULL, req->request_type, new_name, handle->search_flags, req->user_callback, req->user_pointer); michael@0: mm_free(new_name); michael@0: if (!newreq) return 1; michael@0: goto submit_next; michael@0: } michael@0: return 1; michael@0: michael@0: submit_next: michael@0: request_finished(req, &REQ_HEAD(req->base, req->trans_id), 0); michael@0: handle->current_req = newreq; michael@0: newreq->handle = handle; michael@0: request_submit(newreq); michael@0: return 0; michael@0: } michael@0: michael@0: static void michael@0: search_request_finished(struct evdns_request *const handle) { michael@0: ASSERT_LOCKED(handle->current_req->base); michael@0: if (handle->search_state) { michael@0: search_state_decref(handle->search_state); michael@0: handle->search_state = NULL; michael@0: } michael@0: if (handle->search_origname) { michael@0: mm_free(handle->search_origname); michael@0: handle->search_origname = NULL; michael@0: } michael@0: } michael@0: michael@0: /* ================================================================= */ michael@0: /* Parsing resolv.conf files */ michael@0: michael@0: static void michael@0: evdns_resolv_set_defaults(struct evdns_base *base, int flags) { michael@0: /* if the file isn't found then we assume a local resolver */ michael@0: ASSERT_LOCKED(base); michael@0: if (flags & DNS_OPTION_SEARCH) search_set_from_hostname(base); michael@0: if (flags & DNS_OPTION_NAMESERVERS) evdns_base_nameserver_ip_add(base,"127.0.0.1"); michael@0: } michael@0: michael@0: #ifndef _EVENT_HAVE_STRTOK_R michael@0: static char * michael@0: strtok_r(char *s, const char *delim, char **state) { michael@0: char *cp, *start; michael@0: start = cp = s ? s : *state; michael@0: if (!cp) michael@0: return NULL; michael@0: while (*cp && !strchr(delim, *cp)) michael@0: ++cp; michael@0: if (!*cp) { michael@0: if (cp == start) michael@0: return NULL; michael@0: *state = NULL; michael@0: return start; michael@0: } else { michael@0: *cp++ = '\0'; michael@0: *state = cp; michael@0: return start; michael@0: } michael@0: } michael@0: #endif michael@0: michael@0: /* helper version of atoi which returns -1 on error */ michael@0: static int michael@0: strtoint(const char *const str) michael@0: { michael@0: char *endptr; michael@0: const int r = strtol(str, &endptr, 10); michael@0: if (*endptr) return -1; michael@0: return r; michael@0: } michael@0: michael@0: /* Parse a number of seconds into a timeval; return -1 on error. */ michael@0: static int michael@0: strtotimeval(const char *const str, struct timeval *out) michael@0: { michael@0: double d; michael@0: char *endptr; michael@0: d = strtod(str, &endptr); michael@0: if (*endptr) return -1; michael@0: if (d < 0) return -1; michael@0: out->tv_sec = (int) d; michael@0: out->tv_usec = (int) ((d - (int) d)*1000000); michael@0: if (out->tv_sec == 0 && out->tv_usec < 1000) /* less than 1 msec */ michael@0: return -1; michael@0: return 0; michael@0: } michael@0: michael@0: /* helper version of atoi that returns -1 on error and clips to bounds. */ michael@0: static int michael@0: strtoint_clipped(const char *const str, int min, int max) michael@0: { michael@0: int r = strtoint(str); michael@0: if (r == -1) michael@0: return r; michael@0: else if (rmax) michael@0: return max; michael@0: else michael@0: return r; michael@0: } michael@0: michael@0: static int michael@0: evdns_base_set_max_requests_inflight(struct evdns_base *base, int maxinflight) michael@0: { michael@0: int old_n_heads = base->n_req_heads, n_heads; michael@0: struct request **old_heads = base->req_heads, **new_heads, *req; michael@0: int i; michael@0: michael@0: ASSERT_LOCKED(base); michael@0: if (maxinflight < 1) michael@0: maxinflight = 1; michael@0: n_heads = (maxinflight+4) / 5; michael@0: EVUTIL_ASSERT(n_heads > 0); michael@0: new_heads = mm_calloc(n_heads, sizeof(struct request*)); michael@0: if (!new_heads) michael@0: return (-1); michael@0: if (old_heads) { michael@0: for (i = 0; i < old_n_heads; ++i) { michael@0: while (old_heads[i]) { michael@0: req = old_heads[i]; michael@0: evdns_request_remove(req, &old_heads[i]); michael@0: evdns_request_insert(req, &new_heads[req->trans_id % n_heads]); michael@0: } michael@0: } michael@0: mm_free(old_heads); michael@0: } michael@0: base->req_heads = new_heads; michael@0: base->n_req_heads = n_heads; michael@0: base->global_max_requests_inflight = maxinflight; michael@0: return (0); michael@0: } michael@0: michael@0: /* exported function */ michael@0: int michael@0: evdns_base_set_option(struct evdns_base *base, michael@0: const char *option, const char *val) michael@0: { michael@0: int res; michael@0: EVDNS_LOCK(base); michael@0: res = evdns_base_set_option_impl(base, option, val, DNS_OPTIONS_ALL); michael@0: EVDNS_UNLOCK(base); michael@0: return res; michael@0: } michael@0: michael@0: static inline int michael@0: str_matches_option(const char *s1, const char *optionname) michael@0: { michael@0: /* Option names are given as "option:" We accept either 'option' in michael@0: * s1, or 'option:randomjunk'. The latter form is to implement the michael@0: * resolv.conf parser. */ michael@0: size_t optlen = strlen(optionname); michael@0: size_t slen = strlen(s1); michael@0: if (slen == optlen || slen == optlen - 1) michael@0: return !strncmp(s1, optionname, slen); michael@0: else if (slen > optlen) michael@0: return !strncmp(s1, optionname, optlen); michael@0: else michael@0: return 0; michael@0: } michael@0: michael@0: static int michael@0: evdns_base_set_option_impl(struct evdns_base *base, michael@0: const char *option, const char *val, int flags) michael@0: { michael@0: ASSERT_LOCKED(base); michael@0: if (str_matches_option(option, "ndots:")) { michael@0: const int ndots = strtoint(val); michael@0: if (ndots == -1) return -1; michael@0: if (!(flags & DNS_OPTION_SEARCH)) return 0; michael@0: log(EVDNS_LOG_DEBUG, "Setting ndots to %d", ndots); michael@0: if (!base->global_search_state) base->global_search_state = search_state_new(); michael@0: if (!base->global_search_state) return -1; michael@0: base->global_search_state->ndots = ndots; michael@0: } else if (str_matches_option(option, "timeout:")) { michael@0: struct timeval tv; michael@0: if (strtotimeval(val, &tv) == -1) return -1; michael@0: if (!(flags & DNS_OPTION_MISC)) return 0; michael@0: log(EVDNS_LOG_DEBUG, "Setting timeout to %s", val); michael@0: memcpy(&base->global_timeout, &tv, sizeof(struct timeval)); michael@0: } else if (str_matches_option(option, "getaddrinfo-allow-skew:")) { michael@0: struct timeval tv; michael@0: if (strtotimeval(val, &tv) == -1) return -1; michael@0: if (!(flags & DNS_OPTION_MISC)) return 0; michael@0: log(EVDNS_LOG_DEBUG, "Setting getaddrinfo-allow-skew to %s", michael@0: val); michael@0: memcpy(&base->global_getaddrinfo_allow_skew, &tv, michael@0: sizeof(struct timeval)); michael@0: } else if (str_matches_option(option, "max-timeouts:")) { michael@0: const int maxtimeout = strtoint_clipped(val, 1, 255); michael@0: if (maxtimeout == -1) return -1; michael@0: if (!(flags & DNS_OPTION_MISC)) return 0; michael@0: log(EVDNS_LOG_DEBUG, "Setting maximum allowed timeouts to %d", michael@0: maxtimeout); michael@0: base->global_max_nameserver_timeout = maxtimeout; michael@0: } else if (str_matches_option(option, "max-inflight:")) { michael@0: const int maxinflight = strtoint_clipped(val, 1, 65000); michael@0: if (maxinflight == -1) return -1; michael@0: if (!(flags & DNS_OPTION_MISC)) return 0; michael@0: log(EVDNS_LOG_DEBUG, "Setting maximum inflight requests to %d", michael@0: maxinflight); michael@0: evdns_base_set_max_requests_inflight(base, maxinflight); michael@0: } else if (str_matches_option(option, "attempts:")) { michael@0: int retries = strtoint(val); michael@0: if (retries == -1) return -1; michael@0: if (retries > 255) retries = 255; michael@0: if (!(flags & DNS_OPTION_MISC)) return 0; michael@0: log(EVDNS_LOG_DEBUG, "Setting retries to %d", retries); michael@0: base->global_max_retransmits = retries; michael@0: } else if (str_matches_option(option, "randomize-case:")) { michael@0: int randcase = strtoint(val); michael@0: if (!(flags & DNS_OPTION_MISC)) return 0; michael@0: base->global_randomize_case = randcase; michael@0: } else if (str_matches_option(option, "bind-to:")) { michael@0: /* XXX This only applies to successive nameservers, not michael@0: * to already-configured ones. We might want to fix that. */ michael@0: int len = sizeof(base->global_outgoing_address); michael@0: if (!(flags & DNS_OPTION_NAMESERVERS)) return 0; michael@0: if (evutil_parse_sockaddr_port(val, michael@0: (struct sockaddr*)&base->global_outgoing_address, &len)) michael@0: return -1; michael@0: base->global_outgoing_addrlen = len; michael@0: } else if (str_matches_option(option, "initial-probe-timeout:")) { michael@0: struct timeval tv; michael@0: if (strtotimeval(val, &tv) == -1) return -1; michael@0: if (tv.tv_sec > 3600) michael@0: tv.tv_sec = 3600; michael@0: if (!(flags & DNS_OPTION_MISC)) return 0; michael@0: log(EVDNS_LOG_DEBUG, "Setting initial probe timeout to %s", michael@0: val); michael@0: memcpy(&base->global_nameserver_probe_initial_timeout, &tv, michael@0: sizeof(tv)); michael@0: } michael@0: return 0; michael@0: } michael@0: michael@0: int michael@0: evdns_set_option(const char *option, const char *val, int flags) michael@0: { michael@0: if (!current_base) michael@0: current_base = evdns_base_new(NULL, 0); michael@0: return evdns_base_set_option(current_base, option, val); michael@0: } michael@0: michael@0: static void michael@0: resolv_conf_parse_line(struct evdns_base *base, char *const start, int flags) { michael@0: char *strtok_state; michael@0: static const char *const delims = " \t"; michael@0: #define NEXT_TOKEN strtok_r(NULL, delims, &strtok_state) michael@0: michael@0: michael@0: char *const first_token = strtok_r(start, delims, &strtok_state); michael@0: ASSERT_LOCKED(base); michael@0: if (!first_token) return; michael@0: michael@0: if (!strcmp(first_token, "nameserver") && (flags & DNS_OPTION_NAMESERVERS)) { michael@0: const char *const nameserver = NEXT_TOKEN; michael@0: michael@0: if (nameserver) michael@0: evdns_base_nameserver_ip_add(base, nameserver); michael@0: } else if (!strcmp(first_token, "domain") && (flags & DNS_OPTION_SEARCH)) { michael@0: const char *const domain = NEXT_TOKEN; michael@0: if (domain) { michael@0: search_postfix_clear(base); michael@0: search_postfix_add(base, domain); michael@0: } michael@0: } else if (!strcmp(first_token, "search") && (flags & DNS_OPTION_SEARCH)) { michael@0: const char *domain; michael@0: search_postfix_clear(base); michael@0: michael@0: while ((domain = NEXT_TOKEN)) { michael@0: search_postfix_add(base, domain); michael@0: } michael@0: search_reverse(base); michael@0: } else if (!strcmp(first_token, "options")) { michael@0: const char *option; michael@0: while ((option = NEXT_TOKEN)) { michael@0: const char *val = strchr(option, ':'); michael@0: evdns_base_set_option_impl(base, option, val ? val+1 : "", flags); michael@0: } michael@0: } michael@0: #undef NEXT_TOKEN michael@0: } michael@0: michael@0: /* exported function */ michael@0: /* returns: */ michael@0: /* 0 no errors */ michael@0: /* 1 failed to open file */ michael@0: /* 2 failed to stat file */ michael@0: /* 3 file too large */ michael@0: /* 4 out of memory */ michael@0: /* 5 short read from file */ michael@0: int michael@0: evdns_base_resolv_conf_parse(struct evdns_base *base, int flags, const char *const filename) { michael@0: int res; michael@0: EVDNS_LOCK(base); michael@0: res = evdns_base_resolv_conf_parse_impl(base, flags, filename); michael@0: EVDNS_UNLOCK(base); michael@0: return res; michael@0: } michael@0: michael@0: static char * michael@0: evdns_get_default_hosts_filename(void) michael@0: { michael@0: #ifdef WIN32 michael@0: /* Windows is a little coy about where it puts its configuration michael@0: * files. Sure, they're _usually_ in C:\windows\system32, but michael@0: * there's no reason in principle they couldn't be in michael@0: * W:\hoboken chicken emergency\ michael@0: */ michael@0: char path[MAX_PATH+1]; michael@0: static const char hostfile[] = "\\drivers\\etc\\hosts"; michael@0: char *path_out; michael@0: size_t len_out; michael@0: michael@0: if (! SHGetSpecialFolderPathA(NULL, path, CSIDL_SYSTEM, 0)) michael@0: return NULL; michael@0: len_out = strlen(path)+strlen(hostfile); michael@0: path_out = mm_malloc(len_out+1); michael@0: evutil_snprintf(path_out, len_out, "%s%s", path, hostfile); michael@0: return path_out; michael@0: #else michael@0: return mm_strdup("/etc/hosts"); michael@0: #endif michael@0: } michael@0: michael@0: static int michael@0: evdns_base_resolv_conf_parse_impl(struct evdns_base *base, int flags, const char *const filename) { michael@0: size_t n; michael@0: char *resolv; michael@0: char *start; michael@0: int err = 0; michael@0: michael@0: log(EVDNS_LOG_DEBUG, "Parsing resolv.conf file %s", filename); michael@0: michael@0: if (flags & DNS_OPTION_HOSTSFILE) { michael@0: char *fname = evdns_get_default_hosts_filename(); michael@0: evdns_base_load_hosts(base, fname); michael@0: if (fname) michael@0: mm_free(fname); michael@0: } michael@0: michael@0: if ((err = evutil_read_file(filename, &resolv, &n, 0)) < 0) { michael@0: if (err == -1) { michael@0: /* No file. */ michael@0: evdns_resolv_set_defaults(base, flags); michael@0: return 1; michael@0: } else { michael@0: return 2; michael@0: } michael@0: } michael@0: michael@0: start = resolv; michael@0: for (;;) { michael@0: char *const newline = strchr(start, '\n'); michael@0: if (!newline) { michael@0: resolv_conf_parse_line(base, start, flags); michael@0: break; michael@0: } else { michael@0: *newline = 0; michael@0: resolv_conf_parse_line(base, start, flags); michael@0: start = newline + 1; michael@0: } michael@0: } michael@0: michael@0: if (!base->server_head && (flags & DNS_OPTION_NAMESERVERS)) { michael@0: /* no nameservers were configured. */ michael@0: evdns_base_nameserver_ip_add(base, "127.0.0.1"); michael@0: err = 6; michael@0: } michael@0: if (flags & DNS_OPTION_SEARCH && (!base->global_search_state || base->global_search_state->num_domains == 0)) { michael@0: search_set_from_hostname(base); michael@0: } michael@0: michael@0: mm_free(resolv); michael@0: return err; michael@0: } michael@0: michael@0: int michael@0: evdns_resolv_conf_parse(int flags, const char *const filename) { michael@0: if (!current_base) michael@0: current_base = evdns_base_new(NULL, 0); michael@0: return evdns_base_resolv_conf_parse(current_base, flags, filename); michael@0: } michael@0: michael@0: michael@0: #ifdef WIN32 michael@0: /* Add multiple nameservers from a space-or-comma-separated list. */ michael@0: static int michael@0: evdns_nameserver_ip_add_line(struct evdns_base *base, const char *ips) { michael@0: const char *addr; michael@0: char *buf; michael@0: int r; michael@0: ASSERT_LOCKED(base); michael@0: while (*ips) { michael@0: while (isspace(*ips) || *ips == ',' || *ips == '\t') michael@0: ++ips; michael@0: addr = ips; michael@0: while (isdigit(*ips) || *ips == '.' || *ips == ':' || michael@0: *ips=='[' || *ips==']') michael@0: ++ips; michael@0: buf = mm_malloc(ips-addr+1); michael@0: if (!buf) return 4; michael@0: memcpy(buf, addr, ips-addr); michael@0: buf[ips-addr] = '\0'; michael@0: r = evdns_base_nameserver_ip_add(base, buf); michael@0: mm_free(buf); michael@0: if (r) return r; michael@0: } michael@0: return 0; michael@0: } michael@0: michael@0: typedef DWORD(WINAPI *GetNetworkParams_fn_t)(FIXED_INFO *, DWORD*); michael@0: michael@0: /* Use the windows GetNetworkParams interface in iphlpapi.dll to */ michael@0: /* figure out what our nameservers are. */ michael@0: static int michael@0: load_nameservers_with_getnetworkparams(struct evdns_base *base) michael@0: { michael@0: /* Based on MSDN examples and inspection of c-ares code. */ michael@0: FIXED_INFO *fixed; michael@0: HMODULE handle = 0; michael@0: ULONG size = sizeof(FIXED_INFO); michael@0: void *buf = NULL; michael@0: int status = 0, r, added_any; michael@0: IP_ADDR_STRING *ns; michael@0: GetNetworkParams_fn_t fn; michael@0: michael@0: ASSERT_LOCKED(base); michael@0: if (!(handle = evutil_load_windows_system_library( michael@0: TEXT("iphlpapi.dll")))) { michael@0: log(EVDNS_LOG_WARN, "Could not open iphlpapi.dll"); michael@0: status = -1; michael@0: goto done; michael@0: } michael@0: if (!(fn = (GetNetworkParams_fn_t) GetProcAddress(handle, "GetNetworkParams"))) { michael@0: log(EVDNS_LOG_WARN, "Could not get address of function."); michael@0: status = -1; michael@0: goto done; michael@0: } michael@0: michael@0: buf = mm_malloc(size); michael@0: if (!buf) { status = 4; goto done; } michael@0: fixed = buf; michael@0: r = fn(fixed, &size); michael@0: if (r != ERROR_SUCCESS && r != ERROR_BUFFER_OVERFLOW) { michael@0: status = -1; michael@0: goto done; michael@0: } michael@0: if (r != ERROR_SUCCESS) { michael@0: mm_free(buf); michael@0: buf = mm_malloc(size); michael@0: if (!buf) { status = 4; goto done; } michael@0: fixed = buf; michael@0: r = fn(fixed, &size); michael@0: if (r != ERROR_SUCCESS) { michael@0: log(EVDNS_LOG_DEBUG, "fn() failed."); michael@0: status = -1; michael@0: goto done; michael@0: } michael@0: } michael@0: michael@0: EVUTIL_ASSERT(fixed); michael@0: added_any = 0; michael@0: ns = &(fixed->DnsServerList); michael@0: while (ns) { michael@0: r = evdns_nameserver_ip_add_line(base, ns->IpAddress.String); michael@0: if (r) { michael@0: log(EVDNS_LOG_DEBUG,"Could not add nameserver %s to list,error: %d", michael@0: (ns->IpAddress.String),(int)GetLastError()); michael@0: status = r; michael@0: } else { michael@0: ++added_any; michael@0: log(EVDNS_LOG_DEBUG,"Successfully added %s as nameserver",ns->IpAddress.String); michael@0: } michael@0: michael@0: ns = ns->Next; michael@0: } michael@0: michael@0: if (!added_any) { michael@0: log(EVDNS_LOG_DEBUG, "No nameservers added."); michael@0: if (status == 0) michael@0: status = -1; michael@0: } else { michael@0: status = 0; michael@0: } michael@0: michael@0: done: michael@0: if (buf) michael@0: mm_free(buf); michael@0: if (handle) michael@0: FreeLibrary(handle); michael@0: return status; michael@0: } michael@0: michael@0: static int michael@0: config_nameserver_from_reg_key(struct evdns_base *base, HKEY key, const TCHAR *subkey) michael@0: { michael@0: char *buf; michael@0: DWORD bufsz = 0, type = 0; michael@0: int status = 0; michael@0: michael@0: ASSERT_LOCKED(base); michael@0: if (RegQueryValueEx(key, subkey, 0, &type, NULL, &bufsz) michael@0: != ERROR_MORE_DATA) michael@0: return -1; michael@0: if (!(buf = mm_malloc(bufsz))) michael@0: return -1; michael@0: michael@0: if (RegQueryValueEx(key, subkey, 0, &type, (LPBYTE)buf, &bufsz) michael@0: == ERROR_SUCCESS && bufsz > 1) { michael@0: status = evdns_nameserver_ip_add_line(base,buf); michael@0: } michael@0: michael@0: mm_free(buf); michael@0: return status; michael@0: } michael@0: michael@0: #define SERVICES_KEY TEXT("System\\CurrentControlSet\\Services\\") michael@0: #define WIN_NS_9X_KEY SERVICES_KEY TEXT("VxD\\MSTCP") michael@0: #define WIN_NS_NT_KEY SERVICES_KEY TEXT("Tcpip\\Parameters") michael@0: michael@0: static int michael@0: load_nameservers_from_registry(struct evdns_base *base) michael@0: { michael@0: int found = 0; michael@0: int r; michael@0: #define TRY(k, name) \ michael@0: if (!found && config_nameserver_from_reg_key(base,k,TEXT(name)) == 0) { \ michael@0: log(EVDNS_LOG_DEBUG,"Found nameservers in %s/%s",#k,name); \ michael@0: found = 1; \ michael@0: } else if (!found) { \ michael@0: log(EVDNS_LOG_DEBUG,"Didn't find nameservers in %s/%s", \ michael@0: #k,#name); \ michael@0: } michael@0: michael@0: ASSERT_LOCKED(base); michael@0: michael@0: if (((int)GetVersion()) > 0) { /* NT */ michael@0: HKEY nt_key = 0, interfaces_key = 0; michael@0: michael@0: if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, WIN_NS_NT_KEY, 0, michael@0: KEY_READ, &nt_key) != ERROR_SUCCESS) { michael@0: log(EVDNS_LOG_DEBUG,"Couldn't open nt key, %d",(int)GetLastError()); michael@0: return -1; michael@0: } michael@0: r = RegOpenKeyEx(nt_key, TEXT("Interfaces"), 0, michael@0: KEY_QUERY_VALUE|KEY_ENUMERATE_SUB_KEYS, michael@0: &interfaces_key); michael@0: if (r != ERROR_SUCCESS) { michael@0: log(EVDNS_LOG_DEBUG,"Couldn't open interfaces key, %d",(int)GetLastError()); michael@0: return -1; michael@0: } michael@0: TRY(nt_key, "NameServer"); michael@0: TRY(nt_key, "DhcpNameServer"); michael@0: TRY(interfaces_key, "NameServer"); michael@0: TRY(interfaces_key, "DhcpNameServer"); michael@0: RegCloseKey(interfaces_key); michael@0: RegCloseKey(nt_key); michael@0: } else { michael@0: HKEY win_key = 0; michael@0: if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, WIN_NS_9X_KEY, 0, michael@0: KEY_READ, &win_key) != ERROR_SUCCESS) { michael@0: log(EVDNS_LOG_DEBUG, "Couldn't open registry key, %d", (int)GetLastError()); michael@0: return -1; michael@0: } michael@0: TRY(win_key, "NameServer"); michael@0: RegCloseKey(win_key); michael@0: } michael@0: michael@0: if (found == 0) { michael@0: log(EVDNS_LOG_WARN,"Didn't find any nameservers."); michael@0: } michael@0: michael@0: return found ? 0 : -1; michael@0: #undef TRY michael@0: } michael@0: michael@0: int michael@0: evdns_base_config_windows_nameservers(struct evdns_base *base) michael@0: { michael@0: int r; michael@0: char *fname; michael@0: if (base == NULL) michael@0: base = current_base; michael@0: if (base == NULL) michael@0: return -1; michael@0: EVDNS_LOCK(base); michael@0: if (load_nameservers_with_getnetworkparams(base) == 0) { michael@0: EVDNS_UNLOCK(base); michael@0: return 0; michael@0: } michael@0: r = load_nameservers_from_registry(base); michael@0: michael@0: fname = evdns_get_default_hosts_filename(); michael@0: evdns_base_load_hosts(base, fname); michael@0: if (fname) michael@0: mm_free(fname); michael@0: michael@0: EVDNS_UNLOCK(base); michael@0: return r; michael@0: } michael@0: michael@0: int michael@0: evdns_config_windows_nameservers(void) michael@0: { michael@0: if (!current_base) { michael@0: current_base = evdns_base_new(NULL, 1); michael@0: return current_base == NULL ? -1 : 0; michael@0: } else { michael@0: return evdns_base_config_windows_nameservers(current_base); michael@0: } michael@0: } michael@0: #endif michael@0: michael@0: struct evdns_base * michael@0: evdns_base_new(struct event_base *event_base, int initialize_nameservers) michael@0: { michael@0: struct evdns_base *base; michael@0: michael@0: if (evutil_secure_rng_init() < 0) { michael@0: log(EVDNS_LOG_WARN, "Unable to seed random number generator; " michael@0: "DNS can't run."); michael@0: return NULL; michael@0: } michael@0: michael@0: /* Give the evutil library a hook into its evdns-enabled michael@0: * functionality. We can't just call evdns_getaddrinfo directly or michael@0: * else libevent-core will depend on libevent-extras. */ michael@0: evutil_set_evdns_getaddrinfo_fn(evdns_getaddrinfo); michael@0: michael@0: base = mm_malloc(sizeof(struct evdns_base)); michael@0: if (base == NULL) michael@0: return (NULL); michael@0: memset(base, 0, sizeof(struct evdns_base)); michael@0: base->req_waiting_head = NULL; michael@0: michael@0: EVTHREAD_ALLOC_LOCK(base->lock, EVTHREAD_LOCKTYPE_RECURSIVE); michael@0: EVDNS_LOCK(base); michael@0: michael@0: /* Set max requests inflight and allocate req_heads. */ michael@0: base->req_heads = NULL; michael@0: michael@0: evdns_base_set_max_requests_inflight(base, 64); michael@0: michael@0: base->server_head = NULL; michael@0: base->event_base = event_base; michael@0: base->global_good_nameservers = base->global_requests_inflight = michael@0: base->global_requests_waiting = 0; michael@0: michael@0: base->global_timeout.tv_sec = 5; michael@0: base->global_timeout.tv_usec = 0; michael@0: base->global_max_reissues = 1; michael@0: base->global_max_retransmits = 3; michael@0: base->global_max_nameserver_timeout = 3; michael@0: base->global_search_state = NULL; michael@0: base->global_randomize_case = 1; michael@0: base->global_getaddrinfo_allow_skew.tv_sec = 3; michael@0: base->global_getaddrinfo_allow_skew.tv_usec = 0; michael@0: base->global_nameserver_probe_initial_timeout.tv_sec = 10; michael@0: base->global_nameserver_probe_initial_timeout.tv_usec = 0; michael@0: michael@0: TAILQ_INIT(&base->hostsdb); michael@0: michael@0: if (initialize_nameservers) { michael@0: int r; michael@0: #ifdef WIN32 michael@0: r = evdns_base_config_windows_nameservers(base); michael@0: #else michael@0: r = evdns_base_resolv_conf_parse(base, DNS_OPTIONS_ALL, "/etc/resolv.conf"); michael@0: #endif michael@0: if (r == -1) { michael@0: evdns_base_free_and_unlock(base, 0); michael@0: return NULL; michael@0: } michael@0: } michael@0: EVDNS_UNLOCK(base); michael@0: return base; michael@0: } michael@0: michael@0: int michael@0: evdns_init(void) michael@0: { michael@0: struct evdns_base *base = evdns_base_new(NULL, 1); michael@0: if (base) { michael@0: current_base = base; michael@0: return 0; michael@0: } else { michael@0: return -1; michael@0: } michael@0: } michael@0: michael@0: const char * michael@0: evdns_err_to_string(int err) michael@0: { michael@0: switch (err) { michael@0: case DNS_ERR_NONE: return "no error"; michael@0: case DNS_ERR_FORMAT: return "misformatted query"; michael@0: case DNS_ERR_SERVERFAILED: return "server failed"; michael@0: case DNS_ERR_NOTEXIST: return "name does not exist"; michael@0: case DNS_ERR_NOTIMPL: return "query not implemented"; michael@0: case DNS_ERR_REFUSED: return "refused"; michael@0: michael@0: case DNS_ERR_TRUNCATED: return "reply truncated or ill-formed"; michael@0: case DNS_ERR_UNKNOWN: return "unknown"; michael@0: case DNS_ERR_TIMEOUT: return "request timed out"; michael@0: case DNS_ERR_SHUTDOWN: return "dns subsystem shut down"; michael@0: case DNS_ERR_CANCEL: return "dns request canceled"; michael@0: case DNS_ERR_NODATA: return "no records in the reply"; michael@0: default: return "[Unknown error code]"; michael@0: } michael@0: } michael@0: michael@0: static void michael@0: evdns_nameserver_free(struct nameserver *server) michael@0: { michael@0: if (server->socket >= 0) michael@0: evutil_closesocket(server->socket); michael@0: (void) event_del(&server->event); michael@0: event_debug_unassign(&server->event); michael@0: if (server->state == 0) michael@0: (void) event_del(&server->timeout_event); michael@0: event_debug_unassign(&server->timeout_event); michael@0: mm_free(server); michael@0: } michael@0: michael@0: static void michael@0: evdns_base_free_and_unlock(struct evdns_base *base, int fail_requests) michael@0: { michael@0: struct nameserver *server, *server_next; michael@0: struct search_domain *dom, *dom_next; michael@0: int i; michael@0: michael@0: /* Requires that we hold the lock. */ michael@0: michael@0: /* TODO(nickm) we might need to refcount here. */ michael@0: michael@0: for (i = 0; i < base->n_req_heads; ++i) { michael@0: while (base->req_heads[i]) { michael@0: if (fail_requests) michael@0: reply_schedule_callback(base->req_heads[i], 0, DNS_ERR_SHUTDOWN, NULL); michael@0: request_finished(base->req_heads[i], &REQ_HEAD(base, base->req_heads[i]->trans_id), 1); michael@0: } michael@0: } michael@0: while (base->req_waiting_head) { michael@0: if (fail_requests) michael@0: reply_schedule_callback(base->req_waiting_head, 0, DNS_ERR_SHUTDOWN, NULL); michael@0: request_finished(base->req_waiting_head, &base->req_waiting_head, 1); michael@0: } michael@0: base->global_requests_inflight = base->global_requests_waiting = 0; michael@0: michael@0: for (server = base->server_head; server; server = server_next) { michael@0: server_next = server->next; michael@0: evdns_nameserver_free(server); michael@0: if (server_next == base->server_head) michael@0: break; michael@0: } michael@0: base->server_head = NULL; michael@0: base->global_good_nameservers = 0; michael@0: michael@0: if (base->global_search_state) { michael@0: for (dom = base->global_search_state->head; dom; dom = dom_next) { michael@0: dom_next = dom->next; michael@0: mm_free(dom); michael@0: } michael@0: mm_free(base->global_search_state); michael@0: base->global_search_state = NULL; michael@0: } michael@0: michael@0: { michael@0: struct hosts_entry *victim; michael@0: while ((victim = TAILQ_FIRST(&base->hostsdb))) { michael@0: TAILQ_REMOVE(&base->hostsdb, victim, next); michael@0: mm_free(victim); michael@0: } michael@0: } michael@0: michael@0: mm_free(base->req_heads); michael@0: michael@0: EVDNS_UNLOCK(base); michael@0: EVTHREAD_FREE_LOCK(base->lock, EVTHREAD_LOCKTYPE_RECURSIVE); michael@0: michael@0: mm_free(base); michael@0: } michael@0: michael@0: void michael@0: evdns_base_free(struct evdns_base *base, int fail_requests) michael@0: { michael@0: EVDNS_LOCK(base); michael@0: evdns_base_free_and_unlock(base, fail_requests); michael@0: } michael@0: michael@0: void michael@0: evdns_shutdown(int fail_requests) michael@0: { michael@0: if (current_base) { michael@0: struct evdns_base *b = current_base; michael@0: current_base = NULL; michael@0: evdns_base_free(b, fail_requests); michael@0: } michael@0: evdns_log_fn = NULL; michael@0: } michael@0: michael@0: static int michael@0: evdns_base_parse_hosts_line(struct evdns_base *base, char *line) michael@0: { michael@0: char *strtok_state; michael@0: static const char *const delims = " \t"; michael@0: char *const addr = strtok_r(line, delims, &strtok_state); michael@0: char *hostname, *hash; michael@0: struct sockaddr_storage ss; michael@0: int socklen = sizeof(ss); michael@0: ASSERT_LOCKED(base); michael@0: michael@0: #define NEXT_TOKEN strtok_r(NULL, delims, &strtok_state) michael@0: michael@0: if (!addr || *addr == '#') michael@0: return 0; michael@0: michael@0: memset(&ss, 0, sizeof(ss)); michael@0: if (evutil_parse_sockaddr_port(addr, (struct sockaddr*)&ss, &socklen)<0) michael@0: return -1; michael@0: if (socklen > (int)sizeof(struct sockaddr_in6)) michael@0: return -1; michael@0: michael@0: if (sockaddr_getport((struct sockaddr*)&ss)) michael@0: return -1; michael@0: michael@0: while ((hostname = NEXT_TOKEN)) { michael@0: struct hosts_entry *he; michael@0: size_t namelen; michael@0: if ((hash = strchr(hostname, '#'))) { michael@0: if (hash == hostname) michael@0: return 0; michael@0: *hash = '\0'; michael@0: } michael@0: michael@0: namelen = strlen(hostname); michael@0: michael@0: he = mm_calloc(1, sizeof(struct hosts_entry)+namelen); michael@0: if (!he) michael@0: return -1; michael@0: EVUTIL_ASSERT(socklen <= (int)sizeof(he->addr)); michael@0: memcpy(&he->addr, &ss, socklen); michael@0: memcpy(he->hostname, hostname, namelen+1); michael@0: he->addrlen = socklen; michael@0: michael@0: TAILQ_INSERT_TAIL(&base->hostsdb, he, next); michael@0: michael@0: if (hash) michael@0: return 0; michael@0: } michael@0: michael@0: return 0; michael@0: #undef NEXT_TOKEN michael@0: } michael@0: michael@0: static int michael@0: evdns_base_load_hosts_impl(struct evdns_base *base, const char *hosts_fname) michael@0: { michael@0: char *str=NULL, *cp, *eol; michael@0: size_t len; michael@0: int err=0; michael@0: michael@0: ASSERT_LOCKED(base); michael@0: michael@0: if (hosts_fname == NULL || michael@0: (err = evutil_read_file(hosts_fname, &str, &len, 0)) < 0) { michael@0: char tmp[64]; michael@0: strlcpy(tmp, "127.0.0.1 localhost", sizeof(tmp)); michael@0: evdns_base_parse_hosts_line(base, tmp); michael@0: strlcpy(tmp, "::1 localhost", sizeof(tmp)); michael@0: evdns_base_parse_hosts_line(base, tmp); michael@0: return err ? -1 : 0; michael@0: } michael@0: michael@0: /* This will break early if there is a NUL in the hosts file. michael@0: * Probably not a problem.*/ michael@0: cp = str; michael@0: for (;;) { michael@0: eol = strchr(cp, '\n'); michael@0: michael@0: if (eol) { michael@0: *eol = '\0'; michael@0: evdns_base_parse_hosts_line(base, cp); michael@0: cp = eol+1; michael@0: } else { michael@0: evdns_base_parse_hosts_line(base, cp); michael@0: break; michael@0: } michael@0: } michael@0: michael@0: mm_free(str); michael@0: return 0; michael@0: } michael@0: michael@0: int michael@0: evdns_base_load_hosts(struct evdns_base *base, const char *hosts_fname) michael@0: { michael@0: int res; michael@0: if (!base) michael@0: base = current_base; michael@0: EVDNS_LOCK(base); michael@0: res = evdns_base_load_hosts_impl(base, hosts_fname); michael@0: EVDNS_UNLOCK(base); michael@0: return res; michael@0: } michael@0: michael@0: /* A single request for a getaddrinfo, either v4 or v6. */ michael@0: struct getaddrinfo_subrequest { michael@0: struct evdns_request *r; michael@0: ev_uint32_t type; michael@0: }; michael@0: michael@0: /* State data used to implement an in-progress getaddrinfo. */ michael@0: struct evdns_getaddrinfo_request { michael@0: struct evdns_base *evdns_base; michael@0: /* Copy of the modified 'hints' data that we'll use to build michael@0: * answers. */ michael@0: struct evutil_addrinfo hints; michael@0: /* The callback to invoke when we're done */ michael@0: evdns_getaddrinfo_cb user_cb; michael@0: /* User-supplied data to give to the callback. */ michael@0: void *user_data; michael@0: /* The port to use when building sockaddrs. */ michael@0: ev_uint16_t port; michael@0: /* The sub_request for an A record (if any) */ michael@0: struct getaddrinfo_subrequest ipv4_request; michael@0: /* The sub_request for an AAAA record (if any) */ michael@0: struct getaddrinfo_subrequest ipv6_request; michael@0: michael@0: /* The cname result that we were told (if any) */ michael@0: char *cname_result; michael@0: michael@0: /* If we have one request answered and one request still inflight, michael@0: * then this field holds the answer from the first request... */ michael@0: struct evutil_addrinfo *pending_result; michael@0: /* And this event is a timeout that will tell us to cancel the second michael@0: * request if it's taking a long time. */ michael@0: struct event timeout; michael@0: michael@0: /* And this field holds the error code from the first request... */ michael@0: int pending_error; michael@0: /* If this is set, the user canceled this request. */ michael@0: unsigned user_canceled : 1; michael@0: /* If this is set, the user can no longer cancel this request; we're michael@0: * just waiting for the free. */ michael@0: unsigned request_done : 1; michael@0: }; michael@0: michael@0: /* Convert an evdns errors to the equivalent getaddrinfo error. */ michael@0: static int michael@0: evdns_err_to_getaddrinfo_err(int e1) michael@0: { michael@0: /* XXX Do this better! */ michael@0: if (e1 == DNS_ERR_NONE) michael@0: return 0; michael@0: else if (e1 == DNS_ERR_NOTEXIST) michael@0: return EVUTIL_EAI_NONAME; michael@0: else michael@0: return EVUTIL_EAI_FAIL; michael@0: } michael@0: michael@0: /* Return the more informative of two getaddrinfo errors. */ michael@0: static int michael@0: getaddrinfo_merge_err(int e1, int e2) michael@0: { michael@0: /* XXXX be cleverer here. */ michael@0: if (e1 == 0) michael@0: return e2; michael@0: else michael@0: return e1; michael@0: } michael@0: michael@0: static void michael@0: free_getaddrinfo_request(struct evdns_getaddrinfo_request *data) michael@0: { michael@0: /* DO NOT CALL this if either of the requests is pending. Only once michael@0: * both callbacks have been invoked is it safe to free the request */ michael@0: if (data->pending_result) michael@0: evutil_freeaddrinfo(data->pending_result); michael@0: if (data->cname_result) michael@0: mm_free(data->cname_result); michael@0: event_del(&data->timeout); michael@0: mm_free(data); michael@0: return; michael@0: } michael@0: michael@0: static void michael@0: add_cname_to_reply(struct evdns_getaddrinfo_request *data, michael@0: struct evutil_addrinfo *ai) michael@0: { michael@0: if (data->cname_result && ai) { michael@0: ai->ai_canonname = data->cname_result; michael@0: data->cname_result = NULL; michael@0: } michael@0: } michael@0: michael@0: /* Callback: invoked when one request in a mixed-format A/AAAA getaddrinfo michael@0: * request has finished, but the other one took too long to answer. Pass michael@0: * along the answer we got, and cancel the other request. michael@0: */ michael@0: static void michael@0: evdns_getaddrinfo_timeout_cb(evutil_socket_t fd, short what, void *ptr) michael@0: { michael@0: int v4_timedout = 0, v6_timedout = 0; michael@0: struct evdns_getaddrinfo_request *data = ptr; michael@0: michael@0: /* Cancel any pending requests, and note which one */ michael@0: if (data->ipv4_request.r) { michael@0: /* XXXX This does nothing if the request's callback is already michael@0: * running (pending_cb is set). */ michael@0: evdns_cancel_request(NULL, data->ipv4_request.r); michael@0: v4_timedout = 1; michael@0: EVDNS_LOCK(data->evdns_base); michael@0: ++data->evdns_base->getaddrinfo_ipv4_timeouts; michael@0: EVDNS_UNLOCK(data->evdns_base); michael@0: } michael@0: if (data->ipv6_request.r) { michael@0: /* XXXX This does nothing if the request's callback is already michael@0: * running (pending_cb is set). */ michael@0: evdns_cancel_request(NULL, data->ipv6_request.r); michael@0: v6_timedout = 1; michael@0: EVDNS_LOCK(data->evdns_base); michael@0: ++data->evdns_base->getaddrinfo_ipv6_timeouts; michael@0: EVDNS_UNLOCK(data->evdns_base); michael@0: } michael@0: michael@0: /* We only use this timeout callback when we have an answer for michael@0: * one address. */ michael@0: EVUTIL_ASSERT(!v4_timedout || !v6_timedout); michael@0: michael@0: /* Report the outcome of the other request that didn't time out. */ michael@0: if (data->pending_result) { michael@0: add_cname_to_reply(data, data->pending_result); michael@0: data->user_cb(0, data->pending_result, data->user_data); michael@0: data->pending_result = NULL; michael@0: } else { michael@0: int e = data->pending_error; michael@0: if (!e) michael@0: e = EVUTIL_EAI_AGAIN; michael@0: data->user_cb(e, NULL, data->user_data); michael@0: } michael@0: michael@0: data->user_cb = NULL; /* prevent double-call if evdns callbacks are michael@0: * in-progress. XXXX It would be better if this michael@0: * weren't necessary. */ michael@0: michael@0: if (!v4_timedout && !v6_timedout) { michael@0: /* should be impossible? XXXX */ michael@0: free_getaddrinfo_request(data); michael@0: } michael@0: } michael@0: michael@0: static int michael@0: evdns_getaddrinfo_set_timeout(struct evdns_base *evdns_base, michael@0: struct evdns_getaddrinfo_request *data) michael@0: { michael@0: return event_add(&data->timeout, &evdns_base->global_getaddrinfo_allow_skew); michael@0: } michael@0: michael@0: static inline int michael@0: evdns_result_is_answer(int result) michael@0: { michael@0: return (result != DNS_ERR_NOTIMPL && result != DNS_ERR_REFUSED && michael@0: result != DNS_ERR_SERVERFAILED && result != DNS_ERR_CANCEL); michael@0: } michael@0: michael@0: static void michael@0: evdns_getaddrinfo_gotresolve(int result, char type, int count, michael@0: int ttl, void *addresses, void *arg) michael@0: { michael@0: int i; michael@0: struct getaddrinfo_subrequest *req = arg; michael@0: struct getaddrinfo_subrequest *other_req; michael@0: struct evdns_getaddrinfo_request *data; michael@0: michael@0: struct evutil_addrinfo *res; michael@0: michael@0: struct sockaddr_in sin; michael@0: struct sockaddr_in6 sin6; michael@0: struct sockaddr *sa; michael@0: int socklen, addrlen; michael@0: void *addrp; michael@0: int err; michael@0: int user_canceled; michael@0: michael@0: EVUTIL_ASSERT(req->type == DNS_IPv4_A || req->type == DNS_IPv6_AAAA); michael@0: if (req->type == DNS_IPv4_A) { michael@0: data = EVUTIL_UPCAST(req, struct evdns_getaddrinfo_request, ipv4_request); michael@0: other_req = &data->ipv6_request; michael@0: } else { michael@0: data = EVUTIL_UPCAST(req, struct evdns_getaddrinfo_request, ipv6_request); michael@0: other_req = &data->ipv4_request; michael@0: } michael@0: michael@0: EVDNS_LOCK(data->evdns_base); michael@0: if (evdns_result_is_answer(result)) { michael@0: if (req->type == DNS_IPv4_A) michael@0: ++data->evdns_base->getaddrinfo_ipv4_answered; michael@0: else michael@0: ++data->evdns_base->getaddrinfo_ipv6_answered; michael@0: } michael@0: user_canceled = data->user_canceled; michael@0: if (other_req->r == NULL) michael@0: data->request_done = 1; michael@0: EVDNS_UNLOCK(data->evdns_base); michael@0: michael@0: req->r = NULL; michael@0: michael@0: if (result == DNS_ERR_CANCEL && ! user_canceled) { michael@0: /* Internal cancel request from timeout or internal error. michael@0: * we already answered the user. */ michael@0: if (other_req->r == NULL) michael@0: free_getaddrinfo_request(data); michael@0: return; michael@0: } michael@0: michael@0: if (data->user_cb == NULL) { michael@0: /* We already answered. XXXX This shouldn't be needed; see michael@0: * comments in evdns_getaddrinfo_timeout_cb */ michael@0: free_getaddrinfo_request(data); michael@0: return; michael@0: } michael@0: michael@0: if (result == DNS_ERR_NONE) { michael@0: if (count == 0) michael@0: err = EVUTIL_EAI_NODATA; michael@0: else michael@0: err = 0; michael@0: } else { michael@0: err = evdns_err_to_getaddrinfo_err(result); michael@0: } michael@0: michael@0: if (err) { michael@0: /* Looks like we got an error. */ michael@0: if (other_req->r) { michael@0: /* The other request is still working; maybe it will michael@0: * succeed. */ michael@0: /* XXXX handle failure from set_timeout */ michael@0: evdns_getaddrinfo_set_timeout(data->evdns_base, data); michael@0: data->pending_error = err; michael@0: return; michael@0: } michael@0: michael@0: if (user_canceled) { michael@0: data->user_cb(EVUTIL_EAI_CANCEL, NULL, data->user_data); michael@0: } else if (data->pending_result) { michael@0: /* If we have an answer waiting, and we weren't michael@0: * canceled, ignore this error. */ michael@0: add_cname_to_reply(data, data->pending_result); michael@0: data->user_cb(0, data->pending_result, data->user_data); michael@0: data->pending_result = NULL; michael@0: } else { michael@0: if (data->pending_error) michael@0: err = getaddrinfo_merge_err(err, michael@0: data->pending_error); michael@0: data->user_cb(err, NULL, data->user_data); michael@0: } michael@0: free_getaddrinfo_request(data); michael@0: return; michael@0: } else if (user_canceled) { michael@0: if (other_req->r) { michael@0: /* The other request is still working; let it hit this michael@0: * callback with EVUTIL_EAI_CANCEL callback and report michael@0: * the failure. */ michael@0: return; michael@0: } michael@0: data->user_cb(EVUTIL_EAI_CANCEL, NULL, data->user_data); michael@0: free_getaddrinfo_request(data); michael@0: return; michael@0: } michael@0: michael@0: /* Looks like we got some answers. We should turn them into addrinfos michael@0: * and then either queue those or return them all. */ michael@0: EVUTIL_ASSERT(type == DNS_IPv4_A || type == DNS_IPv6_AAAA); michael@0: michael@0: if (type == DNS_IPv4_A) { michael@0: memset(&sin, 0, sizeof(sin)); michael@0: sin.sin_family = AF_INET; michael@0: sin.sin_port = htons(data->port); michael@0: michael@0: sa = (struct sockaddr *)&sin; michael@0: socklen = sizeof(sin); michael@0: addrlen = 4; michael@0: addrp = &sin.sin_addr.s_addr; michael@0: } else { michael@0: memset(&sin6, 0, sizeof(sin6)); michael@0: sin6.sin6_family = AF_INET6; michael@0: sin6.sin6_port = htons(data->port); michael@0: michael@0: sa = (struct sockaddr *)&sin6; michael@0: socklen = sizeof(sin6); michael@0: addrlen = 16; michael@0: addrp = &sin6.sin6_addr.s6_addr; michael@0: } michael@0: michael@0: res = NULL; michael@0: for (i=0; i < count; ++i) { michael@0: struct evutil_addrinfo *ai; michael@0: memcpy(addrp, ((char*)addresses)+i*addrlen, addrlen); michael@0: ai = evutil_new_addrinfo(sa, socklen, &data->hints); michael@0: if (!ai) { michael@0: if (other_req->r) { michael@0: evdns_cancel_request(NULL, other_req->r); michael@0: } michael@0: data->user_cb(EVUTIL_EAI_MEMORY, NULL, data->user_data); michael@0: if (res) michael@0: evutil_freeaddrinfo(res); michael@0: michael@0: if (other_req->r == NULL) michael@0: free_getaddrinfo_request(data); michael@0: return; michael@0: } michael@0: res = evutil_addrinfo_append(res, ai); michael@0: } michael@0: michael@0: if (other_req->r) { michael@0: /* The other request is still in progress; wait for it */ michael@0: /* XXXX handle failure from set_timeout */ michael@0: evdns_getaddrinfo_set_timeout(data->evdns_base, data); michael@0: data->pending_result = res; michael@0: return; michael@0: } else { michael@0: /* The other request is done or never started; append its michael@0: * results (if any) and return them. */ michael@0: if (data->pending_result) { michael@0: if (req->type == DNS_IPv4_A) michael@0: res = evutil_addrinfo_append(res, michael@0: data->pending_result); michael@0: else michael@0: res = evutil_addrinfo_append( michael@0: data->pending_result, res); michael@0: data->pending_result = NULL; michael@0: } michael@0: michael@0: /* Call the user callback. */ michael@0: add_cname_to_reply(data, res); michael@0: data->user_cb(0, res, data->user_data); michael@0: michael@0: /* Free data. */ michael@0: free_getaddrinfo_request(data); michael@0: } michael@0: } michael@0: michael@0: static struct hosts_entry * michael@0: find_hosts_entry(struct evdns_base *base, const char *hostname, michael@0: struct hosts_entry *find_after) michael@0: { michael@0: struct hosts_entry *e; michael@0: michael@0: if (find_after) michael@0: e = TAILQ_NEXT(find_after, next); michael@0: else michael@0: e = TAILQ_FIRST(&base->hostsdb); michael@0: michael@0: for (; e; e = TAILQ_NEXT(e, next)) { michael@0: if (!evutil_ascii_strcasecmp(e->hostname, hostname)) michael@0: return e; michael@0: } michael@0: return NULL; michael@0: } michael@0: michael@0: static int michael@0: evdns_getaddrinfo_fromhosts(struct evdns_base *base, michael@0: const char *nodename, struct evutil_addrinfo *hints, ev_uint16_t port, michael@0: struct evutil_addrinfo **res) michael@0: { michael@0: int n_found = 0; michael@0: struct hosts_entry *e; michael@0: struct evutil_addrinfo *ai=NULL; michael@0: int f = hints->ai_family; michael@0: michael@0: EVDNS_LOCK(base); michael@0: for (e = find_hosts_entry(base, nodename, NULL); e; michael@0: e = find_hosts_entry(base, nodename, e)) { michael@0: struct evutil_addrinfo *ai_new; michael@0: ++n_found; michael@0: if ((e->addr.sa.sa_family == AF_INET && f == PF_INET6) || michael@0: (e->addr.sa.sa_family == AF_INET6 && f == PF_INET)) michael@0: continue; michael@0: ai_new = evutil_new_addrinfo(&e->addr.sa, e->addrlen, hints); michael@0: if (!ai_new) { michael@0: n_found = 0; michael@0: goto out; michael@0: } michael@0: sockaddr_setport(ai_new->ai_addr, port); michael@0: ai = evutil_addrinfo_append(ai, ai_new); michael@0: } michael@0: EVDNS_UNLOCK(base); michael@0: out: michael@0: if (n_found) { michael@0: /* Note that we return an empty answer if we found entries for michael@0: * this hostname but none were of the right address type. */ michael@0: *res = ai; michael@0: return 0; michael@0: } else { michael@0: if (ai) michael@0: evutil_freeaddrinfo(ai); michael@0: return -1; michael@0: } michael@0: } michael@0: michael@0: struct evdns_getaddrinfo_request * michael@0: evdns_getaddrinfo(struct evdns_base *dns_base, michael@0: const char *nodename, const char *servname, michael@0: const struct evutil_addrinfo *hints_in, michael@0: evdns_getaddrinfo_cb cb, void *arg) michael@0: { michael@0: struct evdns_getaddrinfo_request *data; michael@0: struct evutil_addrinfo hints; michael@0: struct evutil_addrinfo *res = NULL; michael@0: int err; michael@0: int port = 0; michael@0: int want_cname = 0; michael@0: michael@0: if (!dns_base) { michael@0: dns_base = current_base; michael@0: if (!dns_base) { michael@0: log(EVDNS_LOG_WARN, michael@0: "Call to getaddrinfo_async with no " michael@0: "evdns_base configured."); michael@0: cb(EVUTIL_EAI_FAIL, NULL, arg); /* ??? better error? */ michael@0: return NULL; michael@0: } michael@0: } michael@0: michael@0: /* If we _must_ answer this immediately, do so. */ michael@0: if ((hints_in && (hints_in->ai_flags & EVUTIL_AI_NUMERICHOST))) { michael@0: res = NULL; michael@0: err = evutil_getaddrinfo(nodename, servname, hints_in, &res); michael@0: cb(err, res, arg); michael@0: return NULL; michael@0: } michael@0: michael@0: if (hints_in) { michael@0: memcpy(&hints, hints_in, sizeof(hints)); michael@0: } else { michael@0: memset(&hints, 0, sizeof(hints)); michael@0: hints.ai_family = PF_UNSPEC; michael@0: } michael@0: michael@0: evutil_adjust_hints_for_addrconfig(&hints); michael@0: michael@0: /* Now try to see if we _can_ answer immediately. */ michael@0: /* (It would be nice to do this by calling getaddrinfo directly, with michael@0: * AI_NUMERICHOST, on plaforms that have it, but we can't: there isn't michael@0: * a reliable way to distinguish the "that wasn't a numeric host!" case michael@0: * from any other EAI_NONAME cases.) */ michael@0: err = evutil_getaddrinfo_common(nodename, servname, &hints, &res, &port); michael@0: if (err != EVUTIL_EAI_NEED_RESOLVE) { michael@0: cb(err, res, arg); michael@0: return NULL; michael@0: } michael@0: michael@0: /* If there is an entry in the hosts file, we should give it now. */ michael@0: if (!evdns_getaddrinfo_fromhosts(dns_base, nodename, &hints, port, &res)) { michael@0: cb(0, res, arg); michael@0: return NULL; michael@0: } michael@0: michael@0: /* Okay, things are serious now. We're going to need to actually michael@0: * launch a request. michael@0: */ michael@0: data = mm_calloc(1,sizeof(struct evdns_getaddrinfo_request)); michael@0: if (!data) { michael@0: cb(EVUTIL_EAI_MEMORY, NULL, arg); michael@0: return NULL; michael@0: } michael@0: michael@0: memcpy(&data->hints, &hints, sizeof(data->hints)); michael@0: data->port = (ev_uint16_t)port; michael@0: data->ipv4_request.type = DNS_IPv4_A; michael@0: data->ipv6_request.type = DNS_IPv6_AAAA; michael@0: data->user_cb = cb; michael@0: data->user_data = arg; michael@0: data->evdns_base = dns_base; michael@0: michael@0: want_cname = (hints.ai_flags & EVUTIL_AI_CANONNAME); michael@0: michael@0: /* If we are asked for a PF_UNSPEC address, we launch two requests in michael@0: * parallel: one for an A address and one for an AAAA address. We michael@0: * can't send just one request, since many servers only answer one michael@0: * question per DNS request. michael@0: * michael@0: * Once we have the answer to one request, we allow for a short michael@0: * timeout before we report it, to see if the other one arrives. If michael@0: * they both show up in time, then we report both the answers. michael@0: * michael@0: * If too many addresses of one type time out or fail, we should stop michael@0: * launching those requests. (XXX we don't do that yet.) michael@0: */ michael@0: michael@0: if (hints.ai_family != PF_INET6) { michael@0: log(EVDNS_LOG_DEBUG, "Sending request for %s on ipv4 as %p", michael@0: nodename, &data->ipv4_request); michael@0: michael@0: data->ipv4_request.r = evdns_base_resolve_ipv4(dns_base, michael@0: nodename, 0, evdns_getaddrinfo_gotresolve, michael@0: &data->ipv4_request); michael@0: if (want_cname) michael@0: data->ipv4_request.r->current_req->put_cname_in_ptr = michael@0: &data->cname_result; michael@0: } michael@0: if (hints.ai_family != PF_INET) { michael@0: log(EVDNS_LOG_DEBUG, "Sending request for %s on ipv6 as %p", michael@0: nodename, &data->ipv6_request); michael@0: michael@0: data->ipv6_request.r = evdns_base_resolve_ipv6(dns_base, michael@0: nodename, 0, evdns_getaddrinfo_gotresolve, michael@0: &data->ipv6_request); michael@0: if (want_cname) michael@0: data->ipv6_request.r->current_req->put_cname_in_ptr = michael@0: &data->cname_result; michael@0: } michael@0: michael@0: evtimer_assign(&data->timeout, dns_base->event_base, michael@0: evdns_getaddrinfo_timeout_cb, data); michael@0: michael@0: if (data->ipv4_request.r || data->ipv6_request.r) { michael@0: return data; michael@0: } else { michael@0: mm_free(data); michael@0: cb(EVUTIL_EAI_FAIL, NULL, arg); michael@0: return NULL; michael@0: } michael@0: } michael@0: michael@0: void michael@0: evdns_getaddrinfo_cancel(struct evdns_getaddrinfo_request *data) michael@0: { michael@0: EVDNS_LOCK(data->evdns_base); michael@0: if (data->request_done) { michael@0: EVDNS_UNLOCK(data->evdns_base); michael@0: return; michael@0: } michael@0: event_del(&data->timeout); michael@0: data->user_canceled = 1; michael@0: if (data->ipv4_request.r) michael@0: evdns_cancel_request(data->evdns_base, data->ipv4_request.r); michael@0: if (data->ipv6_request.r) michael@0: evdns_cancel_request(data->evdns_base, data->ipv6_request.r); michael@0: EVDNS_UNLOCK(data->evdns_base); michael@0: }