Allow the resolver source address to be specified in the configuration.
[ircu2.10.12-pk.git] / ircd / ircd_res.c
index 2843fe2dc3ffdd2f1fc05bbebad90144947df6a7..a37654931a9c59499b9c60f890d0eb66b4055a48 100644 (file)
@@ -7,17 +7,19 @@
  * The authors takes no responsibility for any damage or loss
  * of property which results from the use of this software.
  *
- * $Id$
- *
  * July 1999 - Rewrote a bunch of stuff here. Change hostent builder code,
  *     added callbacks and reference counting of returned hostents.
  *     --Bleep (Thomas Helvey <tomh@inxpress.net>)
  *
  * This was all needlessly complicated for irc. Simplified. No more hostent
- * All we really care about is the IP -> hostname mappings. Thats all. 
+ * All we really care about is the IP -> hostname mappings. Thats all.
  *
  * Apr 28, 2003 --cryogen and Dianora
  */
+/** @file
+ * @brief IRC resolver functions.
+ * @version $Id$
+ */
 
 #include "client.h"
 #include "ircd_alloc.h"
 #include "ircd.h"
 #include "numeric.h"
 #include "fileio.h" /* for fbopen / fbclose / fbputs */
+#include "random.h"
 #include "s_bsd.h"
+#include "s_debug.h"
 #include "s_stats.h"
 #include "send.h"
 #include "sys.h"
 #include "res.h"
 #include "ircd_reslib.h"
-#include "ircd_addrinfo.h"
 
-#include <assert.h>
+/* #include <assert.h> -- Now using assert in ircd_log.h */
 #include <string.h>
 #include <sys/time.h>
 #include <sys/socket.h>
 #error this code needs to be able to address individual octets 
 #endif
 
+/** Resolver UDP socket. */
 static struct Socket res_socket;
+/** Next DNS lookup timeout. */
 static struct Timer res_timeout;
+/** Check for whether the resolver has been initialized yet. */
+#define resolver_started() (request_list.next != NULL)
 
-#define MAXPACKET      1024  /* rfc sez 512 but we expand names so ... */
-#define RES_MAXALIASES 35    /* maximum aliases allowed */
-#define RES_MAXADDRS   35    /* maximum addresses allowed */
-#define AR_TTL         600   /* TTL in seconds for dns cache entries */
+/** Maximum DNS packet length.
+ * RFC says 512, but we add extra for expanded names.
+ */
+#define MAXPACKET      1024
+#define AR_TTL         600   /**< TTL in seconds for dns cache entries */
 
 /* RFC 1104/1105 wasn't very helpful about what these fields
  * should be named, so for now, we'll just name them this way.
  * we probably should look at what named calls them or something.
  */
+/** Size of TYPE field of a DNS RR header. */
 #define TYPE_SIZE         (size_t)2
+/** Size of CLASS field of a DNS RR header. */
 #define CLASS_SIZE        (size_t)2
+/** Size of TTL field of a DNS RR header. */
 #define TTL_SIZE          (size_t)4
+/** Size of RDLENGTH field of a DNS RR header. */
 #define RDLENGTH_SIZE     (size_t)2
+/** Size of fixed-format part of a DNS RR header. */
 #define ANSWER_FIXED_SIZE (TYPE_SIZE + CLASS_SIZE + TTL_SIZE + RDLENGTH_SIZE)
 
-typedef enum 
+/** Current request state. */
+typedef enum
 {
-  REQ_IDLE,  /* We're doing not much at all */
-  REQ_PTR,   /* Looking up a PTR */
-  REQ_A,     /* Looking up an A, possibly because AAAA failed */
-#ifdef IPV6
-  REQ_AAAA,  /* Looking up an AAAA */
-#endif
-  REQ_CNAME, /* We got a CNAME in response, we better get a real answer next */
-  REQ_INT    /* ip6.arpa failed, falling back to ip6.int */
+  REQ_IDLE,  /**< We're doing not much at all. */
+  REQ_PTR,   /**< Looking up a PTR. */
+  REQ_A,     /**< Looking up an A, possibly because AAAA failed. */
+  REQ_AAAA,  /**< Looking up an AAAA. */
+  REQ_CNAME, /**< We got a CNAME in response, we better get a real answer next. */
+  REQ_INT    /**< ip6.arpa failed, falling back to ip6.int. */
 } request_state;
 
+/** Doubly linked list node. */
 struct dlink
 {
-    struct dlink *prev;
-    struct dlink *next;
+    struct dlink *prev; /**< Previous element in list. */
+    struct dlink *next; /**< Next element in list. */
 };
 
-struct reslist 
+/** A single resolver request.
+ * (Do not be fooled by the "list" in the name.)
+ */
+struct reslist
 {
-  struct dlink node;
-  int id;
-  int sent;                /* number of requests sent */
-  request_state state;     /* State the resolver machine is in */
-  time_t ttl;
-  char type;
-  char retries;            /* retry counter */
-  char sends;              /* number of sends (>1 means resent) */
-  char resend;             /* send flag. 0 == dont resend */
-  time_t sentat;
-  time_t timeout;
-  struct irc_ssaddr addr;
-  char *name;
-  struct DNSQuery query;   /* query callback for this request */
+  struct dlink node;       /**< Doubly linked list node. */
+  int id;                  /**< Request ID (from request header). */
+  int sent;                /**< Number of requests sent. */
+  request_state state;     /**< State the resolver machine is in. */
+  char type;               /**< Current request type. */
+  char retries;            /**< Retry counter. */
+  char sends;              /**< Number of sends (>1 means resent). */
+  char resend;             /**< Send flag; 0 == dont resend. */
+  time_t sentat;           /**< Timestamp we last sent this request. */
+  time_t timeout;          /**< When this request times out. */
+  struct irc_in_addr addr; /**< Address for this request. */
+  char *name;              /**< Hostname for this request. */
+  struct DNSQuery query;   /**< Query callback for this request. */
 };
 
+/** Base of request list. */
 static struct dlink request_list;
 
 static void rem_request(struct reslist *request);
@@ -108,9 +124,9 @@ static struct reslist *make_request(const struct DNSQuery *query);
 static void do_query_name(const struct DNSQuery *query,
                           const char* name, struct reslist *request, int);
 static void do_query_number(const struct DNSQuery *query,
-                            const struct irc_ssaddr *,
+                            const struct irc_in_addr *,
                             struct reslist *request);
-static void query_name(const char *name, int query_class, int query_type, 
+static void query_name(const char *name, int query_class, int query_type,
                        struct reslist *request);
 static int send_res_msg(const char *buf, int len, int count);
 static void resend_query(struct reslist *request);
@@ -120,122 +136,58 @@ static struct DNSReply *make_dnsreply(struct reslist *request);
 static void res_readreply(struct Event *ev);
 static void timeout_resolver(struct Event *notused);
 
-extern struct irc_ssaddr irc_nsaddr_list[IRCD_MAXNS];
+extern struct irc_sockaddr irc_nsaddr_list[IRCD_MAXNS];
 extern int irc_nscount;
 extern char irc_domain[HOSTLEN];
 
-/*
- * int
- * res_ourserver(inp)
- *      looks up "inp" in irc_nsaddr_list[]
- * returns:
- *      0  : not found
- *      >0 : found
- * author:
- *      paul vixie, 29may94
- *      revised for ircd, cryogen(stu) may03
+struct irc_sockaddr ResolverAddr;
+
+/** Check whether \a inp is a nameserver we use.
+ * @param[in] inp Nameserver address.
+ * @return Non-zero if we trust \a inp; zero if not.
  */
 static int
-res_ourserver(const struct irc_ssaddr *inp) 
+res_ourserver(const struct irc_sockaddr *inp)
 {
-#ifdef IPV6
-  struct sockaddr_in6 *v6;
-  struct sockaddr_in6 *v6in = (struct sockaddr_in6 *)inp;
-#endif
-  struct sockaddr_in *v4;
-  struct sockaddr_in *v4in = (struct sockaddr_in *)inp; 
   int ns;
 
   for (ns = 0;  ns < irc_nscount;  ns++)
-  {
-    const struct irc_ssaddr *srv = &irc_nsaddr_list[ns];
-#ifdef IPV6
-    v6 = (struct sockaddr_in6 *)srv;
-#endif
-    v4 = (struct sockaddr_in *)srv;
-
-    /* could probably just memcmp(srv, inp, srv.ss_len) here
-     * but we'll air on the side of caution - stu
-     *
-     */
-    switch (srv->ss.ss_family)
-    {
-#ifdef IPV6
-      case AF_INET6:
-        if (srv->ss.ss_family == inp->ss.ss_family)
-          if (v6->sin6_port == v6in->sin6_port)
-            if ((memcmp(&v6->sin6_addr.s6_addr, &v6in->sin6_addr.s6_addr, 
-                    sizeof(struct in6_addr)) == 0) || 
-                (memcmp(&v6->sin6_addr.s6_addr, &in6addr_any, 
-                        sizeof(struct in6_addr)) == 0))
-              return(1);
-        break;
-#endif
-      case AF_INET:
-        if (srv->ss.ss_family == inp->ss.ss_family)
-          if (v4->sin_port == v4in->sin_port)
-            if ((v4->sin_addr.s_addr == INADDR_ANY) || 
-                (v4->sin_addr.s_addr == v4in->sin_addr.s_addr))
-              return(1);
-        break;
-      default:
-        break;
-    }
-  }
+    if (!irc_in_addr_cmp(&inp->addr, &irc_nsaddr_list[ns].addr)
+        && inp->port == irc_nsaddr_list[ns].port)
+      return 1;
 
   return(0);
 }
 
-/*
- * start_resolver - do everything we need to read the resolv.conf file
- * and initialize the resolver file descriptor if needed
+/** Start (or re-start) resolver.
+ * This means read resolv.conf, initialize the list of pending
+ * requests, open the resolver socket and initialize its timeout.
  */
-static void
-start_resolver(void)
+void
+restart_resolver(void)
 {
   irc_res_init();
 
   if (!request_list.next)
-      request_list.next = request_list.prev = &request_list;
+    request_list.next = request_list.prev = &request_list;
 
   if (!s_active(&res_socket))
   {
+    struct irc_sockaddr *local;
     int fd;
-    fd = socket(irc_nsaddr_list[0].ss.ss_family, SOCK_DGRAM, 0);
-    if (fd < 0) {} /* TODO: bail on socket() failure */
-    if (!os_set_nonblocking(fd)) {} /* TODO: bail on failure */
+    local = irc_in_addr_valid(&ResolverAddr) ? &ResolverAddr : &VirtualHost;
+    fd = os_socket(local, SOCK_DGRAM, "Resolver UDP socket");
+    if (fd < 0) return;
     if (!socket_add(&res_socket, res_readreply, NULL, SS_DATAGRAM,
-                    SOCK_EVENT_READABLE, fd)) {} /* TODO: bail on socket_add() failure */
+                    SOCK_EVENT_READABLE, fd)) return;
     timer_init(&res_timeout);
-    timer_add(&res_timeout, timeout_resolver, NULL, TT_PERIODIC, 1);
   }
 }
 
-/*
- * init_resolver - initialize resolver and resolver library
- */
-int
-init_resolver(void)
-{
-#ifdef LRAND48
-  srand48(CurrentTime);
-#endif
-  start_resolver();
-  return(s_fd(&res_socket));
-}
-
-/*
- * restart_resolver - reread resolv.conf, reopen socket
- */
-void
-restart_resolver(void)
-{
-  start_resolver();
-}
-
-/*
- * add_local_domain - Add the domain to hostname, if it is missing
- * (as suggested by eps@TOASTER.SFSU.EDU)
+/** Append local domain to hostname if needed.
+ * If \a hname does not contain any '.'s, append #irc_domain to it.
+ * @param[in,out] hname Hostname to check.
+ * @param[in] size Length of \a hname buffer.
  */
 void
 add_local_domain(char* hname, size_t size)
@@ -257,18 +209,9 @@ add_local_domain(char* hname, size_t size)
   }
 }
 
-/*
- * remove_dlink - remove a link from a doubly linked list
- */
-static void
-remove_dlink(struct dlink *node)
-{
-    node->prev->next = node->next;
-    node->next->prev = node->prev;
-}
-
-/*
- * add_dlink - add a link to a doubly linked list
+/** Add a node to a doubly linked list.
+ * @param[in,out] node Node to add to list.
+ * @param[in,out] next Add \a node before this one.
  */
 static void
 add_dlink(struct dlink *node, struct dlink *next)
@@ -279,49 +222,66 @@ add_dlink(struct dlink *node, struct dlink *next)
     node->next->prev = node;
 }
 
-/*
- * rem_request - remove a request from the list. 
- * This must also free any memory that has been allocated for 
- * temporary storage of DNS results.
+/** Remove a request from the list and free it.
+ * @param[in] request Node to free.
  */
 static void
 rem_request(struct reslist *request)
 {
-  remove_dlink(&request->node);
+  /* remove from dlist */
+  request->node.prev->next = request->node.next;
+  request->node.next->prev = request->node.prev;
+  /* free memory */
   MyFree(request->name);
   MyFree(request);
 }
 
-/*
- * make_request - Create a DNS request record for the server.
+/** Create a DNS request record for the server.
+ * @param[in] query Callback information for caller.
+ * @return Newly allocated and linked-in reslist.
  */
 static struct reslist *
 make_request(const struct DNSQuery* query)
 {
   struct reslist *request;
 
+  if (!resolver_started())
+    restart_resolver();
+
   request = (struct reslist *)MyMalloc(sizeof(struct reslist));
   memset(request, 0, sizeof(struct reslist));
 
+  request->state   = REQ_IDLE;
   request->sentat  = CurrentTime;
-  request->retries = 3;
+  request->retries = feature_int(FEAT_IRCD_RES_RETRIES);
   request->resend  = 1;
-  request->timeout = 4;    /* start at 4 and exponential inc. */
+  request->timeout = feature_int(FEAT_IRCD_RES_TIMEOUT);
   memset(&request->addr, 0, sizeof(request->addr));
-  request->query.vptr     = query->vptr;
-  request->query.callback = query->callback;
-  request->state          = REQ_IDLE;
+  memcpy(&request->query, query, sizeof(request->query));
 
   add_dlink(&request->node, &request_list);
   return(request);
 }
 
-/*
- * timeout_query_list - Remove queries from the list which have been 
- * there too long without being resolved.
+/** Make sure that a timeout event will happen by the given time.
+ * @param[in] when Latest time for timeout to run.
+ */
+static void
+check_resolver_timeout(time_t when)
+{
+  if (when > CurrentTime + AR_TTL)
+    when = CurrentTime + AR_TTL;
+  if (!t_active(&res_timeout))
+    timer_add(&res_timeout, timeout_resolver, NULL, TT_ABSOLUTE, when);
+  else if (when < t_expire(&res_timeout))
+    timer_chg(&res_timeout, TT_ABSOLUTE, when);
+}
+
+/** Drop pending DNS lookups which have timed out.
+ * @param[in] notused Timer event data (ignored).
  */
-static time_t
-timeout_query_list(time_t now)
+static void
+timeout_resolver(struct Event *notused)
 {
   struct dlink *ptr, *next_ptr;
   struct reslist *request;
@@ -334,17 +294,18 @@ timeout_query_list(time_t now)
     request = (struct reslist*)ptr;
     timeout = request->sentat + request->timeout;
 
-    if (now >= timeout)
+    if (CurrentTime >= timeout)
     {
       if (--request->retries <= 0)
       {
+        Debug((DEBUG_DNS, "Request %p out of retries; destroying", request));
         (*request->query.callback)(request->query.vptr, 0);
         rem_request(request);
         continue;
       }
       else
       {
-        request->sentat = now;
+        request->sentat = CurrentTime;
         request->timeout += request->timeout;
         resend_query(request);
       }
@@ -356,21 +317,15 @@ timeout_query_list(time_t now)
     }
   }
 
-  return((next_time > now) ? next_time : (now + AR_TTL));
-}
-
-/*
- * timeout_resolver - check request list
- */
-static void
-timeout_resolver(struct Event *notused)
-{
-  timeout_query_list(CurrentTime);
+  if (next_time <= CurrentTime)
+    next_time = CurrentTime + AR_TTL;
+  check_resolver_timeout(next_time);
 }
 
-/*
- * delete_resolver_queries - cleanup outstanding queries 
- * for which there no longer exist clients or conf lines.
+/** Drop queries that are associated with a particular pointer.
+ * This is used to clean up lookups for clients or conf blocks
+ * that went away.
+ * @param[in] vptr User callback pointer to search for.
  */
 void
 delete_resolver_queries(const void *vptr)
@@ -378,21 +333,24 @@ delete_resolver_queries(const void *vptr)
   struct dlink *ptr, *next_ptr;
   struct reslist *request;
 
-  for (ptr = request_list.next; ptr != &request_list; ptr = next_ptr)
-  {
-    next_ptr = ptr->next;
-    request = (struct reslist*)ptr;
-    if (vptr == request->query.vptr)
-      rem_request(request);
+  if (request_list.next) {
+    for (ptr = request_list.next; ptr != &request_list; ptr = next_ptr)
+    {
+      next_ptr = ptr->next;
+      request = (struct reslist*)ptr;
+      if (vptr == request->query.vptr) {
+        Debug((DEBUG_DNS, "Removing request %p with vptr %p", request, vptr));
+        rem_request(request);
+      }
+    }
   }
 }
 
-/*
- * send_res_msg - sends msg to all nameservers found in the "_res" structure.
- * This should reflect /etc/resolv.conf. We will get responses
- * which arent needed but is easier than checking to see if nameserver
- * isnt present. Returns number of messages successfully sent to 
- * nameservers or -1 if no successful sends.
+/** Send a message to all of our nameservers.
+ * @param[in] msg Message to send.
+ * @param[in] len Length of message.
+ * @param[in] rcount Maximum number of servers to ask.
+ * @return Number of servers that were successfully asked.
  */
 static int
 send_res_msg(const char *msg, int len, int rcount)
@@ -408,18 +366,15 @@ send_res_msg(const char *msg, int len, int rcount)
     max_queries = 1;
 
   for (i = 0; i < max_queries; i++)
-  {
-    if (sendto(s_fd(&res_socket), msg, len, 0, 
-        (struct sockaddr*)&(irc_nsaddr_list[i]), 
-        irc_nsaddr_list[i].ss_len) == len) 
+    if (os_sendto_nonb(s_fd(&res_socket), msg, len, NULL, 0, &irc_nsaddr_list[i]) == IO_SUCCESS)
       ++sent;
-  }
 
   return(sent);
 }
 
-/*
- * find_id - find a dns request id (id is determined by dn_mkquery)
+/** Find a DNS request by ID.
+ * @param[in] id Identifier to find.
+ * @return Matching DNS request, or NULL if none are found.
  */
 static struct reslist *
 find_id(int id)
@@ -431,60 +386,41 @@ find_id(int id)
   {
     request = (struct reslist*)ptr;
 
-    if (request->id == id)
+    if (request->id == id) {
+      Debug((DEBUG_DNS, "find_id(%d) -> %p", id, request));
       return(request);
+    }
   }
 
+  Debug((DEBUG_DNS, "find_id(%d) -> NULL", id));
   return(NULL);
 }
 
-/* 
- * gethost_byname_type - get host address from name
- *
- */
-void
-gethost_byname_type(const char *name, const struct DNSQuery *query, int type)
-{
-  assert(name != 0);
-  do_query_name(query, name, NULL, type);
-}
-
-/*
- * gethost_byname - wrapper for _type - send T_AAAA first
+/** Try to look up address for a hostname, trying IPv6 (T_AAAA) first.
+ * @param[in] name Hostname to look up.
+ * @param[in] query Callback information.
  */
 void
 gethost_byname(const char *name, const struct DNSQuery *query)
 {
-  gethost_byname_type(name, query, T_AAAA);
+  do_query_name(query, name, NULL, T_AAAA);
 }
 
-/*
- * gethost_byaddr - get host name from address
+/** Try to look up hostname for an address.
+ * @param[in] addr Address to look up.
+ * @param[in] query Callback information.
  */
 void
-gethost_byaddr(const struct irc_ssaddr *addr, const struct DNSQuery *query)
+gethost_byaddr(const struct irc_in_addr *addr, const struct DNSQuery *query)
 {
   do_query_number(query, addr, NULL);
 }
 
-/*
- * gethost_byinaddr - kludgy hack for IPv4-only compatibility
- */
-void
-gethost_byinaddr(const struct in_addr *addr, const struct DNSQuery *query)
-{
-  struct irc_ssaddr new_addr;
-  struct sockaddr_in *sin;
-  memset(&new_addr, 0, sizeof(new_addr));
-  sin = (struct sockaddr_in*)&new_addr.ss;
-  sin->sin_family = AF_INET;
-  memcpy(&sin->sin_addr, addr, sizeof(sin->sin_addr));
-  new_addr.ss_len = sizeof(*sin);
-  gethost_byaddr(&new_addr, query);
-}
-
-/*
- * do_query_name - nameserver lookup name
+/** Send a query to look up the address for a name.
+ * @param[in] query Callback information.
+ * @param[in] name Hostname to look up.
+ * @param[in] request DNS lookup structure (may be NULL).
+ * @param[in] type Preferred request type.
  */
 static void
 do_query_name(const struct DNSQuery *query, const char *name,
@@ -498,9 +434,7 @@ do_query_name(const struct DNSQuery *query, const char *name,
   if (request == NULL)
   {
     request       = make_request(query);
-    request->name = (char *)MyMalloc(strlen(host_name) + 1);
-    request->type = type;
-    strcpy(request->name, host_name);
+    DupString(request->name, host_name);
 #ifdef IPV6
     if (type != T_A)
       request->state = REQ_AAAA;
@@ -510,42 +444,39 @@ do_query_name(const struct DNSQuery *query, const char *name,
   }
 
   request->type = type;
+  Debug((DEBUG_DNS, "Requesting DNS %s %s as %p", (request->state == REQ_AAAA ? "AAAA" : "A"), host_name, request));
   query_name(host_name, C_IN, type, request);
 }
 
-/*
- * do_query_number - Use this to do reverse IP# lookups.
+/** Send a query to look up the name for an address.
+ * @param[in] query Callback information.
+ * @param[in] addr Address to look up.
+ * @param[in] request DNS lookup structure (may be NULL).
  */
 static void
-do_query_number(const struct DNSQuery *query, const struct irc_ssaddr *addr,
+do_query_number(const struct DNSQuery *query, const struct irc_in_addr *addr,
                 struct reslist *request)
 {
   char ipbuf[128];
   const unsigned char *cp;
-#ifdef IPV6
-  const char *intarpa;
-#endif
-  if (addr->ss.ss_family == AF_INET)
-  {
-    struct sockaddr_in *v4 = (struct sockaddr_in *)addr;
-    cp = (const unsigned char*)&v4->sin_addr.s_addr;
 
-    ircd_snprintf(NULL, ipbuf, sizeof(ipbuf),
-                  "%u.%u.%u.%u.in-addr.arpa.",
+  if (irc_in_addr_is_ipv4(addr))
+  {
+    cp = (const unsigned char*)&addr->in6_16[6];
+    ircd_snprintf(NULL, ipbuf, sizeof(ipbuf), "%u.%u.%u.%u.in-addr.arpa.",
                   (unsigned int)(cp[3]), (unsigned int)(cp[2]),
                   (unsigned int)(cp[1]), (unsigned int)(cp[0]));
   }
-#ifdef IPV6
-  else if (addr->ss.ss_family == AF_INET6)
+  else
   {
-    struct sockaddr_in6 *v6 = (struct sockaddr_in6 *)addr;
-    cp = (const unsigned char *)&v6->sin6_addr.s6_addr;
+    const char *intarpa;
 
     if (request != NULL && request->state == REQ_INT)
       intarpa = "int";
     else
       intarpa = "arpa";
 
+    cp = (const unsigned char *)&addr->in6_16[0];
     ircd_snprintf(NULL, ipbuf, sizeof(ipbuf),
                   "%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x."
                   "%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.ip6.%s.",
@@ -566,20 +497,22 @@ do_query_number(const struct DNSQuery *query, const struct irc_ssaddr *addr,
                   (unsigned int)(cp[1]&0xf), (unsigned int)(cp[1]>>4),
                   (unsigned int)(cp[0]&0xf), (unsigned int)(cp[0]>>4), intarpa);
   }
-#endif
   if (request == NULL)
   {
     request       = make_request(query);
     request->type = T_PTR;
-    memcpy(&request->addr, addr, sizeof(struct irc_ssaddr));
+    memcpy(&request->addr, addr, sizeof(request->addr));
     request->name = (char *)MyMalloc(HOSTLEN + 1);
   }
-
+  Debug((DEBUG_DNS, "Requesting DNS PTR %s as %p", ipbuf, request));
   query_name(ipbuf, C_IN, T_PTR, request);
 }
 
-/*
- * query_name - generate a query based on class, type and name.
+/** Generate a query based on class, type and name.
+ * @param[in] name Domain name to look up.
+ * @param[in] query_class Query class (see RFC 1035).
+ * @param[in] type Query type (see RFC 1035).
+ * @param[in] request DNS request structure.
  */
 static void
 query_name(const char *name, int query_class, int type,
@@ -590,41 +523,32 @@ query_name(const char *name, int query_class, int type,
 
   memset(buf, 0, sizeof(buf));
 
-  if ((request_len = irc_res_mkquery(name, query_class, type, 
+  if ((request_len = irc_res_mkquery(name, query_class, type,
       (unsigned char *)buf, sizeof(buf))) > 0)
   {
     HEADER *header = (HEADER *)buf;
-#ifndef LRAND48
-    int k = 0;
-    struct timeval tv;
-#endif
+
     /*
      * generate an unique id
      * NOTE: we don't have to worry about converting this to and from
      * network byte order, the nameserver does not interpret this value
      * and returns it unchanged
      */
-#ifdef LRAND48
     do
     {
-      header->id = (header->id + lrand48()) & 0xffff;
+      header->id = (header->id + ircrandom()) & 0xffff;
     } while (find_id(header->id));
-#else
-    gettimeofday(&tv, NULL);
-
-    do
-    {
-      header->id = (header->id + k + tv.tv_usec) & 0xffff;
-      k++;
-    } while (find_id(header->id));
-#endif /* LRAND48 */
     request->id = header->id;
     ++request->sends;
 
     request->sent += send_res_msg(buf, request_len, request->sends);
+    check_resolver_timeout(request->sentat + request->timeout);
   }
 }
 
+/** Send a failed DNS lookup request again.
+ * @param[in] request Request to resend.
+ */
 static void
 resend_query(struct reslist *request)
 {
@@ -639,19 +563,21 @@ resend_query(struct reslist *request)
     case T_A:
       do_query_name(NULL, request->name, request, request->type);
       break;
-#ifdef IPV6
     case T_AAAA:
       /* didnt work, try A */
       if (request->state == REQ_AAAA)
         do_query_name(NULL, request->name, request, T_A);
-#endif
     default:
       break;
   }
 }
 
-/*
- * proc_answer - process name server reply
+/** Process the answer for a lookup request.
+ * @param[in] request DNS request that got an answer.
+ * @param[in] header Header of DNS response.
+ * @param[in] buf DNS response body.
+ * @param[in] eob Pointer to end of DNS response.
+ * @return Number of answers read from \a buf.
  */
 static int
 proc_answer(struct reslist *request, HEADER* header, char* buf, char* eob)
@@ -662,10 +588,7 @@ proc_answer(struct reslist *request, HEADER* header, char* buf, char* eob)
   int type;                    /* answer type */
   int n;                       /* temp count */
   int rd_length;
-  struct sockaddr_in *v4;      /* conversion */
-#ifdef IPV6
-  struct sockaddr_in6 *v6;
-#endif
+
   current = (unsigned char *)buf + sizeof(HEADER);
 
   for (; header->qdcount > 0; --header->qdcount)
@@ -718,14 +641,13 @@ proc_answer(struct reslist *request, HEADER* header, char* buf, char* eob)
     query_class = irc_ns_get16(current);
     current += CLASS_SIZE;
 
-    request->ttl = irc_ns_get32(current);
     current += TTL_SIZE;
 
     rd_length = irc_ns_get16(current);
     current += RDLENGTH_SIZE;
 
-    /* 
-     * Wait to set request->type until we verify this structure 
+    /*
+     * Wait to set request->type until we verify this structure
      */
     switch (type)
     {
@@ -738,25 +660,18 @@ proc_answer(struct reslist *request, HEADER* header, char* buf, char* eob)
          */
         if (rd_length != sizeof(struct in_addr))
           return(0);
-        v4 = (struct sockaddr_in *)&request->addr;
-        request->addr.ss_len = sizeof(struct sockaddr_in);
-        v4->sin_family = AF_INET;
-        memcpy(&v4->sin_addr, current, sizeof(struct in_addr));
+        memset(&request->addr, 0, sizeof(request->addr));
+        memcpy(&request->addr.in6_16[6], current, sizeof(struct in_addr));
         return(1);
         break;
-#ifdef IPV6
       case T_AAAA:
         if (request->type != T_AAAA)
           return(0);
-        if (rd_length != sizeof(struct in6_addr))
+        if (rd_length != sizeof(struct irc_in_addr))
           return(0);
-        request->addr.ss_len = sizeof(struct sockaddr_in6);
-        v6 = (struct sockaddr_in6 *)&request->addr;
-        v6->sin6_family = AF_INET6;
-        memcpy(&v6->sin6_addr, current, sizeof(struct in6_addr));
+        memcpy(&request->addr, current, sizeof(struct irc_in_addr));
         return(1);
         break;
-#endif
       case T_PTR:
         if (request->type != T_PTR)
           return(0);
@@ -771,9 +686,9 @@ proc_answer(struct reslist *request, HEADER* header, char* buf, char* eob)
 
         return(1);
         break;
-      case T_CNAME: /* first check we already havent started looking 
+      case T_CNAME: /* first check we already havent started looking
                        into a cname */
-        if (request->type != T_PTR) 
+        if (request->type != T_PTR)
           return(0);
 
         if (request->state == REQ_CNAME)
@@ -789,7 +704,7 @@ proc_answer(struct reslist *request, HEADER* header, char* buf, char* eob)
         request->state = REQ_CNAME;
         current += rd_length;
         break;
-        
+
       default:
         /* XXX I'd rather just throw away the entire bogus thing
          * but its possible its just a broken nameserver with still
@@ -803,28 +718,26 @@ proc_answer(struct reslist *request, HEADER* header, char* buf, char* eob)
   return(1);
 }
 
-/*
- * res_readreply - read a dns reply from the nameserver and process it.
+/** Read a DNS reply from the nameserver and process it.
+ * @param[in] ev I/O activity event for resolver socket.
  */
 static void
 res_readreply(struct Event *ev)
 {
+  struct irc_sockaddr lsin;
   struct Socket *sock;
   char buf[sizeof(HEADER) + MAXPACKET];
   HEADER *header;
   struct reslist *request = NULL;
   struct DNSReply *reply  = NULL;
-  int rc;
+  unsigned int rc;
   int answer_count;
-  socklen_t len = sizeof(struct irc_ssaddr);
-  struct irc_ssaddr lsin;
 
   assert(ev_socket(ev) == &res_socket);
   sock = ev_socket(ev);
 
-  rc = recvfrom(s_fd(sock), buf, sizeof(buf), 0, (struct sockaddr *)&lsin, &len);
-  /* Better to cast the sizeof instead of rc */
-  if (rc <= (int)(sizeof(HEADER)))
+  if (IO_SUCCESS != os_recvfrom_nonb(s_fd(sock), buf, sizeof(buf), &rc, &lsin)
+      || (rc <= sizeof(HEADER)))
     return;
 
   /*
@@ -855,40 +768,39 @@ res_readreply(struct Event *ev)
       resend_query(request);
     else
     {
-      /* 
+      /*
        * If we havent already tried this, and we're looking up AAAA, try A
        * now
        */
 
-#ifdef IPV6
       if (request->state == REQ_AAAA && request->type == T_AAAA)
       {
-        request->timeout += 4;
+        request->timeout += feature_int(FEAT_IRCD_RES_TIMEOUT);
         resend_query(request);
       }
       else if (request->type == T_PTR && request->state != REQ_INT &&
-               request->addr.ss.ss_family == AF_INET6)
+               !irc_in_addr_is_ipv4(&request->addr))
       {
         request->state = REQ_INT;
-        request->timeout += 4;
+        request->timeout += feature_int(FEAT_IRCD_RES_TIMEOUT);
         resend_query(request);
       }
       else
-#endif
       {
         /*
          * If a bad error was returned, we stop here and dont send
          * send any more (no retries granted).
          */
+          Debug((DEBUG_DNS, "Request %p has bad response (state %d type %d)", request, request->state, request->type));
         (*request->query.callback)(request->query.vptr, 0);
        rem_request(request);
-      } 
+      }
     }
 
     return;
   }
   /*
-   * If this fails there was an error decoding the received packet, 
+   * If this fails there was an error decoding the received packet,
    * try it again and hope it works the next time.
    */
   answer_count = proc_answer(request, header, buf, buf + rc);
@@ -903,6 +815,7 @@ res_readreply(struct Event *ev)
          * got a PTR response with no name, something bogus is happening
          * don't bother trying again, the client address doesn't resolve
          */
+        Debug((DEBUG_DNS, "Request %p PTR had empty name", request));
         (*request->query.callback)(request->query.vptr, reply);
         rem_request(request);
         return;
@@ -910,15 +823,15 @@ res_readreply(struct Event *ev)
 
       /*
        * Lookup the 'authoritative' name that we were given for the
-       * ip#. 
-       *
+       * ip#.
        */
 #ifdef IPV6
-      if (request->addr.ss.ss_family == AF_INET6)
-        gethost_byname_type(request->name, &request->query, T_AAAA);
+      if (!irc_in_addr_is_ipv4(&request->addr))
+        do_query_name(&request->query, request->name, NULL, T_AAAA);
       else
 #endif
-      gethost_byname_type(request->name, &request->query, T_A);
+      do_query_name(&request->query, request->name, NULL, T_A);
+      Debug((DEBUG_DNS, "Request %p switching to forward resolution", request));
       rem_request(request);
     }
     else
@@ -928,6 +841,7 @@ res_readreply(struct Event *ev)
        */
       reply = make_dnsreply(request);
       (*request->query.callback)(request->query.vptr, (reply) ? reply : 0);
+      Debug((DEBUG_DNS, "Request %p got forward resolution", request));
       rem_request(request);
     }
   }
@@ -939,10 +853,15 @@ res_readreply(struct Event *ev)
     assert(0);
 
     /* XXX don't leak it */
+    Debug((DEBUG_DNS, "Request %p was unexpected(!)", request));
     rem_request(request);
   }
 }
 
+/** Build a DNSReply for a completed request.
+ * @param[in] request Completed DNS request.
+ * @return Newly allocated DNSReply containing host name and address.
+ */
 static struct DNSReply *
 make_dnsreply(struct reslist *request)
 {
@@ -956,21 +875,28 @@ make_dnsreply(struct reslist *request)
   return(cp);
 }
 
+/** Statistics callback to list DNS servers.
+ * @param[in] source_p Client requesting statistics.
+ * @param[in] sd Stats descriptor for request (ignored).
+ * @param[in] param Extra parameter from user (ignored).
+ */
 void
-report_dns_servers(struct Client *source_p, struct StatDesc *sd, int stat, char *param)
+report_dns_servers(struct Client *source_p, const struct StatDesc *sd, char *param)
 {
   int i;
   char ipaddr[128];
 
   for (i = 0; i < irc_nscount; i++)
   {
-    irc_getnameinfo((struct sockaddr *)&(irc_nsaddr_list[i]),
-                    irc_nsaddr_list[i].ss_len, ipaddr, sizeof(ipaddr), NULL, 0,
-                    NI_NUMERICHOST);
-    send_reply(source_p, RPL_STATSALINE, ipaddr); 
+    ircd_ntoa_r(ipaddr, &irc_nsaddr_list[i].addr);
+    send_reply(source_p, RPL_STATSALINE, ipaddr);
   }
 }
 
+/** Report memory usage to a client.
+ * @param[in] sptr Client requesting information.
+ * @return Total memory used by pending requests.
+ */
 size_t
 cres_mem(struct Client* sptr)
 {
@@ -979,15 +905,69 @@ cres_mem(struct Client* sptr)
   size_t request_mem   = 0;
   int    request_count = 0;
 
-  for (dlink = request_list.next; dlink != &request_list; dlink = dlink->next) {
-    request = (struct reslist*)dlink;
-    request_mem += sizeof(*request);
-    if (request->name)
-      request_mem += strlen(request->name) + 1; 
-    ++request_count;
+  if (request_list.next) {
+    for (dlink = request_list.next; dlink != &request_list; dlink = dlink->next) {
+      request = (struct reslist*)dlink;
+      request_mem += sizeof(*request);
+      if (request->name)
+        request_mem += strlen(request->name) + 1;
+      ++request_count;
+    }
   }
 
   send_reply(sptr, SND_EXPLICIT | RPL_STATSDEBUG,
             ":Resolver: requests %d(%d)", request_count, request_mem);
   return request_mem;
 }
+
+/** Check whether an address looks valid.
+ * This means not all 0s and not all 1s.
+ * @param[in] addr Address to check for validity.
+ * @return Non-zero if the address looks valid.
+ */
+int irc_in_addr_valid(const struct irc_in_addr *addr)
+{
+  unsigned int ii;
+  unsigned short val;
+
+  val = addr->in6_16[0];
+  if (val != 0 && val != 0xffff)
+    return 1;
+  for (ii = 1; ii < 8; ii++)
+    if (addr->in6_16[ii] != val)
+      return 1;
+  return 0;
+}
+
+/** Compare two IP addresses.
+ * @param[in] a First address to compare.
+ * @param[in] b Second address to compare.
+ * @return Non-zero if the two addresses differ, zero if they are identical.
+ */
+int irc_in_addr_cmp(const struct irc_in_addr *a, const struct irc_in_addr *b)
+{
+  if (irc_in_addr_is_ipv4(a))
+    return a->in6_16[6] != b->in6_16[6]
+        || a->in6_16[7] != b->in6_16[7]
+        || !irc_in_addr_is_ipv4(b);
+  else
+    return memcmp(a, b, sizeof(*a));
+}
+
+/** Indicate whether an IP address is a loopback address.
+ * @param[in] addr Address to check.
+ * @return Non-zero if the address is loopback; zero if not.
+ */
+int irc_in_addr_is_loopback(const struct irc_in_addr *addr)
+{
+  if (addr->in6_16[0] != 0
+    || addr->in6_16[1] != 0
+    || addr->in6_16[2] != 0
+    || addr->in6_16[3] != 0
+    || addr->in6_16[4] != 0)
+    return 0;
+  if ((addr->in6_16[5] == 0xffff) || (addr->in6_16[5] == 0 && addr->in6_16[6] != 0))
+    return (ntohs(addr->in6_16[6]) & 0xff00) == 0x7f00;
+  else
+    return addr->in6_16[5] == 0 && addr->in6_16[6] == 0 && htons(addr->in6_16[7]) == 1;
+}