Hi, all.  Hi, Niels!  Here's another patch to evdns.c.  This patch has
the following effects:

  - add functions for forward and reverse IPv6 lookups.
  - implement the server side of the DNS protocol: receive a set of
    questions, and send an answer back to the client.
    - As a subcomponent, implement the compression side of the DNS
      name compression scheme.
  - macro fix: WIN32 is sufficient; MS_WINDOWS is unnecessary.
  - suppress warnings on some compilers related to running off the end
    of a function or unused variables or typechecking.
  - spelling fix: choaked->choked

The example main() function has been expanded to include demonstration
use of the server functions.  The new functions still need
documentation and references in the man page.  I've tried to test this
all as well as I could, but there may be bugs left, especially in
retrying writes after they've failed.  This patch should not introduce
bugs in code that doesn't use any of the new functions.

yrs,
-- 
Nick Mathewson
=== configure.in
==================================================================
--- configure.in        (revision 11547)
+++ configure.in        (local)
@@ -341,6 +341,7 @@
 AC_CHECK_TYPE(u_int32_t, unsigned int)
 AC_CHECK_TYPE(u_int16_t, unsigned short)
 AC_CHECK_TYPE(u_int8_t, unsigned char)
+AC_CHECK_TYPES(struct in6_addr, , , [#include <netinet/in.h>])
 
 AC_MSG_CHECKING([for socklen_t])
 AC_TRY_COMPILE([
=== evdns.c
==================================================================
--- evdns.c     (revision 11547)
+++ evdns.c     (local)
@@ -134,12 +134,11 @@
 #define MAX_ADDRS 4  // maximum number of addresses from a single packet
 // which we bother recording
 
-#define TYPE_A         1
-#define TYPE_CNAME     5
-#define TYPE_PTR      12
-#define TYPE_AAAA     28
+#define TYPE_A         EVDNS_TYPE_A
+#define TYPE_PTR       EVDNS_TYPE_PTR
+#define TYPE_AAAA      EVDNS_TYPE_AAAA
 
-#define CLASS_INET 1
+#define CLASS_INET     EVDNS_CLASS_INET
 
 struct request {
        u8 *request;  // the dns packet data
@@ -167,6 +166,12 @@
        char transmit_me;  // needs to be transmitted
 };
 
+#ifndef HAVE_STRUCT_IN6_ADDR
+struct in6_addr {
+       u8 s6_addr[16];
+};
+#endif
+
 struct reply {
        unsigned int type;
        unsigned int have_answer;
@@ -176,6 +181,10 @@
                        u32 addresses[MAX_ADDRS];
                } a;
                struct {
+                       u32 addrcount;
+                       struct in6_addr addresses[MAX_ADDRS];
+               } aaaa;
+               struct {
                        char name[HOST_NAME_MAX];
                } ptr;
        } data;
@@ -193,13 +202,79 @@
                                     // when we next probe this server.
                                     // Valid if state == 0
        char state;  // zero if we think that this server is down
-       char choaked;  // true if we have an EAGAIN from this server's socket
+       char choked;  // true if we have an EAGAIN from this server's socket
        char write_waiting;  // true if we are waiting for EV_WRITE events
 };
 
 static struct request *req_head = NULL, *req_waiting_head = NULL;
 static struct nameserver *server_head = NULL;
 
+// Represents a local port where we're listening for DNS requests. Right now,
+// only UDP is supported.
+struct evdns_server_port {
+       int socket; // socket we use to read queries and write replies.
+       int refcnt; // reference count.
+       char choked; // Are we currently blocked from writing?
+       char closing; // Are we trying to close this port, pending writes?
+       evdns_request_callback_fn_type user_callback; // Fn to handle requests
+       void *user_data; // Opaque pointer passed to user_callback
+       struct event event; // Read/write event
+       // circular list of replies that we want to write.
+       struct server_request *pending_replies;
+};
+
+// Represents part of a reply being built.     (That is, a single RR.)
+struct server_reply_item {
+       struct server_reply_item *next; // next item in sequence.
+       char *name; // name part of the RR
+       u16 type : 16; // The RR type
+       u16 class : 16; // The RR class (usually CLASS_INET)
+       u32 ttl; // The RR TTL
+       char is_name; // True iff data is a label
+       u16 datalen; // Length of data; -1 if data is a label
+       void *data; // The contents of the RR
+};
+
+// Represents a request that we've received as a DNS server, and holds
+// the components of the reply as we're constructing it.
+struct server_request {
+       // Pointers to the next and previous entries on the list of replies
+       // that we're waiting to write.  Only set if we have tried to respond
+       // and gotten EAGAIN.
+       struct server_request *next_pending;
+       struct server_request *prev_pending;
+
+       u16 trans_id; // Transaction id.
+       struct evdns_server_port *port; // Which port received this request on?
+       struct sockaddr_storage addr; // Where to send the response
+       socklen_t addrlen; // length of addr
+
+       int n_answer; // how many answer RRs have been set?
+       int n_authority; // how many authority RRs have been set?
+       int n_additional; // how many additional RRs have been set?
+
+       struct server_reply_item *answer; // linked list of answer RRs
+       struct server_reply_item *authority; // linked list of authority RRs
+       struct server_reply_item *additional; // linked list of additional RRs
+
+       // Constructed response.  Only set once we're ready to send a reply.
+       // Once this is set, the RR fields are cleared, and no more should be 
set.
+       char *response;
+       size_t response_len;
+
+       // Caller-visible fields: flags, questions.
+       struct evdns_server_request base;
+};
+
+// helper macro
+#define OFFSET_OF(st, member) ((off_t) (((char*)&((st*)0)->member)-(char*)0))
+
+// Given a pointer to an evdns_server_request, get the corresponding
+// server_request.
+#define TO_SERVER_REQUEST(base_ptr)                                            
                                \
+       ((struct server_request*)                                               
                                        \
+        (((char*)(base_ptr) - OFFSET_OF(struct server_request, base))))
+
 // The number of good nameservers that we have
 static int global_good_nameservers = 0;
 
@@ -239,7 +314,12 @@
 static struct request *request_new(int type, const char *name, int flags, 
evdns_callback_type callback, void *ptr);
 static void request_submit(struct request *req);
 
-#if defined(MS_WINDOWS) || defined(WIN32)
+static int server_request_free(struct server_request *req);
+static void server_request_free_answers(struct server_request *req);
+static void server_port_free(struct evdns_server_port *port);
+static void server_port_ready_callback(int fd, short events, void *arg);
+
+#ifdef WIN32
 static int
 last_error(int sock)
 {
@@ -322,7 +402,7 @@
   if (!evdns_log_fn)
     return;
   va_start(args,fmt);
-#ifdef MS_WINDOWS
+#ifdef WIN32
   _vsnprintf(buf, sizeof(buf), fmt, args);
 #else
   vsnprintf(buf, sizeof(buf), fmt, args);
@@ -574,6 +654,14 @@
                                                           req->user_pointer);
                }
                return;
+       case TYPE_AAAA:
+               if (reply)
+                       req->user_callback(DNS_ERR_NONE, DNS_IPv6_AAAA,
+                                                          
reply->data.aaaa.addrcount, ttl,
+                                                          
reply->data.aaaa.addresses,
+                                                          req->user_pointer);
+               else
+                       req->user_callback(err, 0, 0, 0, NULL, 
req->user_pointer);
        }
        assert(0);
 }
@@ -641,9 +729,9 @@
 name_parse(u8 *packet, int length, int *idx, char *name_out, int name_out_len) 
{
        int name_end = -1;
        int j = *idx;
-#define GET32(x) do { if (j + 4 > length) return -1; memcpy(&_t32, packet + j, 
4); j += 4; x = ntohl(_t32); } while(0);
-#define GET16(x) do { if (j + 2 > length) return -1; memcpy(&_t, packet + j, 
2); j += 2; x = ntohs(_t); } while(0);
-#define GET8(x) do { if (j >= length) return -1; x = packet[j++]; } while(0);
+#define GET32(x) do { if (j + 4 > length) goto err; memcpy(&_t32, packet + j, 
4); j += 4; x = ntohl(_t32); } while(0);
+#define GET16(x) do { if (j + 2 > length) goto err; memcpy(&_t, packet + j, 
2); j += 2; x = ntohs(_t); } while(0);
+#define GET8(x) do { if (j >= length) goto err; x = packet[j++]; } while(0);
 
        char *cp = name_out;
        const char *const end = name_out + name_out_len;
@@ -684,9 +772,11 @@
        else
                *idx = name_end;
        return 0;
+ err:
+       return -1;
 }
 
-// parses a raw packet from the wire
+// parses a raw request from a nameserver.
 static int
 reply_parse(u8 *packet, int length) {
        int j = 0;  // index into packet
@@ -706,6 +796,8 @@
        GET16(answers);
        GET16(authority);
        GET16(additional);
+       (void) authority; /* suppress "unused variable" warnings. */
+       (void) additional; /* suppress "unused variable" warnings. */
 
        req = request_find_from_trans_id(trans_id);
        if (!req) return -1;
@@ -725,7 +817,7 @@
 #define SKIP_NAME \
        do { tmp_name[0] = '\0';                                        \
                if (name_parse(packet, length, &j, tmp_name, 
sizeof(tmp_name))<0) \
-                       return -1;                                      \
+                       goto err;                                               
                                                        \
        } while(0);
 
        reply.type = req->request_type;
@@ -778,6 +870,24 @@
                                return -1;
                        reply.have_answer = 1;
                        break;
+               } else if (type == TYPE_AAAA && class == CLASS_INET) {
+                       int addrcount, addrtocopy;
+                       if (req->request_type != TYPE_AAAA) {
+                               j += datalength; continue;
+                       }
+                       // XXXX do something sane with malformed AAAA answers.
+                       addrcount = datalength >> 4;  // each address is 16 
bytes long
+                       addrtocopy = MIN(MAX_ADDRS - reply.data.aaaa.addrcount, 
(unsigned)addrcount);
+                       ttl_r = MIN(ttl_r, ttl);
+
+                       // we only bother with the first four addresses.
+                       if (j + 16*addrtocopy > length) return -1;
+                       
memcpy(&reply.data.aaaa.addresses[reply.data.aaaa.addrcount],
+                                  packet + j, 16*addrtocopy);
+                       reply.data.aaaa.addrcount += addrtocopy;
+                       j += 16*addrtocopy;
+                       reply.have_answer = 1;
+                       if (reply.data.a.addrcount == MAX_ADDRS) break;
                } else {
                        // skip over any other type of resource
                        j += datalength;
@@ -786,6 +896,86 @@
 
        reply_handle(req, flags, ttl_r, &reply);
        return 0;
+ err:
+       return -1;
+}
+
+// Parse a raw request (packet,length) sent to a nameserver port (port) from
+// a DNS client (addr,addrlen), and if it's well-formed, call the corresponding
+// callback.
+static int
+request_parse(u8 *packet, int length, struct evdns_server_port *port, struct 
sockaddr *addr, socklen_t addrlen)
+{
+       int j = 0;      // index into packet
+       u16 _t;  // used by the macros
+       char tmp_name[256]; // used by the macros
+
+       int i;
+       u16 trans_id, flags, questions, answers, authority, additional;
+       struct server_request *server_req = NULL;
+
+       // Get the header fields
+       GET16(trans_id);
+       GET16(flags);
+       GET16(questions);
+       GET16(answers);
+       GET16(authority);
+       GET16(additional);
+
+       if (flags & 0x8000) return -1; // Must not be an answer.
+       if (flags & 0x7800) return -1; // only standard queries are supported
+       flags &= 0x0300; // Only TC and RD get preserved.
+
+       server_req = malloc(sizeof(struct server_request));
+       if (server_req == NULL) return -1;
+       memset(server_req, 0, sizeof(struct server_request));
+
+       server_req->trans_id = trans_id;
+       memcpy(&server_req->addr, addr, addrlen);
+       server_req->addrlen = addrlen;
+
+       server_req->base.flags = flags;
+       server_req->base.nquestions = 0;
+       server_req->base.questions = malloc(sizeof(struct evdns_server_question 
*) * questions);
+       if (server_req->base.questions == NULL)
+               goto err;
+
+       for (i = 0; i < questions; ++i) {
+               u16 type, class;
+               struct evdns_server_question *q;
+               int namelen;
+               if (name_parse(packet, length, &j, tmp_name, 
sizeof(tmp_name))<0)
+                       goto err;
+               GET16(type);
+               GET16(class);
+               namelen = strlen(tmp_name);
+               q = malloc(sizeof(struct evdns_server_question) + namelen);
+               if (!q)
+                       goto err;
+               q->type = type;
+               q->class = class;
+               memcpy(q->name, tmp_name, namelen+1);
+               server_req->base.questions[server_req->base.nquestions++] = q;
+       }
+
+       // Ignore answers, authority, and additional.
+
+       server_req->port = port;
+       port->refcnt++;
+       port->user_callback(&(server_req->base), port->user_data);
+
+       return 0;
+err:
+       if (server_req) {
+               if (server_req->base.questions) {
+                       for (i = 0; i < server_req->base.nquestions; ++i)
+                               free(server_req->base.questions[i]);
+                       free(server_req->base.questions);
+               }
+               free(server_req);
+       }
+       return -1;
+
 #undef SKIP_NAME
 #undef GET32
 #undef GET16
@@ -897,6 +1087,60 @@
        }
 }
 
+// Read a packet from a DNS client on a server port s, parse it, and
+// act accordingly.
+static void
+server_port_read(struct evdns_server_port *s) {
+       u8 packet[1500];
+       struct sockaddr_storage addr;
+       socklen_t addrlen;
+       int r;
+
+       for (;;) {
+               addrlen = sizeof(struct sockaddr_storage);
+               r = recvfrom(s->socket, packet, sizeof(packet), 0,
+                                        (struct sockaddr*) &addr, &addrlen);
+               if (r < 0) {
+                       int err = last_error(s->socket);
+                       if (error_is_eagain(err)) return;
+                       log(EVDNS_LOG_WARN, "Error %s (%d) while reading 
request.",
+                               strerror(err), err);
+                       return;
+               }
+               request_parse(packet, r, s, (struct sockaddr*) &addr, addrlen);
+       }
+}
+
+// Try to write all pending replies on a given DNS server port.
+static void
+server_port_flush(struct evdns_server_port *port)
+{
+       while (port->pending_replies) {
+               struct server_request *req = port->pending_replies;
+               int r = sendto(port->socket, req->response, req->response_len, 
0,
+                          (struct sockaddr*) &req->addr, req->addrlen);
+               if (r < 0) {
+                       int err = last_error(port->socket);
+                       if (error_is_eagain(err))
+                               return;
+                       log(EVDNS_LOG_WARN, "Error %s (%d) while writing 
response to port; dropping", strerror(err), err);
+               }
+               if (server_request_free(req)) {
+                       // we released the last reference to req->port.
+                       return;
+               }
+       }
+
+       // We have no more pending requests; stop listening for 'writeable' 
events.
+       (void) event_del(&port->event);
+       event_set(&port->event, port->socket, EV_READ | EV_PERSIST,
+                         server_port_ready_callback, port);
+       if (event_add(&port->event, NULL) < 0) {
+               log(EVDNS_LOG_WARN, "Error from libevent when adding event for 
DNS server.");
+               // ???? Do more?
+       }
+}
+
 // set if we are waiting for the ability to write to this server.
 // if waiting is true then we ask libevent for EV_WRITE events, otherwise
 // we stop these events.
@@ -923,7 +1167,7 @@
         (void)fd;
 
        if (events & EV_WRITE) {
-               ns->choaked = 0;
+               ns->choked = 0;
                if (!evdns_transmit()) {
                        nameserver_write_waiting(ns, 0);
                }
@@ -933,29 +1177,129 @@
        }
 }
 
-// Converts a string to a length-prefixed set of DNS labels.
-// @buf must be strlen(name)+2 or longer. name and buf must
-// not overlap. name_len should be the length of name
+// a callback function. Called by libevent when the kernel says that
+// a server socket is ready for writing or reading.
+static void
+server_port_ready_callback(int fd, short events, void *arg) {
+       struct evdns_server_port *port = (struct evdns_server_port *) arg;
+       (void) fd;
+
+       if (events & EV_WRITE) {
+               port->choked = 0;
+               server_port_flush(port);
+       }
+       if (events & EV_READ) {
+               server_port_read(port);
+       }
+}
+
+/* This is an inefficient representation; only use it via the dnslabel_table_*
+ * functions, so that is can be safely replaced with something smarter later. 
*/
+#define MAX_LABELS 128
+// Structures used to implement name compression
+struct dnslabel_entry { char *v; int pos; };
+struct dnslabel_table {
+       int n_labels; // number of current entries
+       // map from name to position in message
+       struct dnslabel_entry labels[MAX_LABELS];
+};
+
+// Initialize dnslabel_table.
+static void
+dnslabel_table_init(struct dnslabel_table *table)
+{
+       table->n_labels = 0;
+}
+
+// Free all storage held by table, but not the table itself.
+static void
+dnslabel_clear(struct dnslabel_table *table)
+{
+       int i;
+       for (i = 0; i < table->n_labels; ++i)
+               free(table->labels[i].v);
+       table->n_labels = 0;
+}
+
+// return the position of the label in the current message, or -1 if the label
+// hasn't been used yet.
+static int
+dnslabel_table_get_pos(const struct dnslabel_table *table, const char *label)
+{
+       int i;
+       for (i = 0; i < table->n_labels; ++i) {
+               if (!strcmp(label, table->labels[i].v))
+                       return table->labels[i].pos;
+       }
+       return -1;
+}
+
+// remember that we've used the label at position pos
+static int
+dnslabel_table_add(struct dnslabel_table *table, const char *label, int pos)
+{
+       char *v;
+       int p;
+       if (table->n_labels == MAX_LABELS)
+               return (-1);
+       v = strdup(label);
+       if (v == NULL)
+               return (-1);
+       p = table->n_labels++;
+       table->labels[p].v = v;
+       table->labels[p].pos = pos;
+
+       return (0);
+}
+
+// Converts a string to a length-prefixed set of DNS labels, starting
+// at buf[j]. name and buf must not overlap. name_len should be the length
+// of name.     table is optional, and is used for compression.
 //
 // Input: abc.def
 // Output: <3>abc<3>def<0>
 //
-// Returns the length of the data. negative on error
+// Returns the first index after the encoded name, or negative on error.
 //   -1  label was > 63 bytes
-//   -2  name was > 255 bytes
-static int
-dnsname_to_labels(u8 *const buf, const char *name, const int name_len) {
+//      -2      name too long to fit in buffer.
+//
+static off_t
+dnsname_to_labels(u8 *const buf, size_t buf_len, off_t j,
+                                 const char *name, const int name_len,
+                                 struct dnslabel_table *table) {
        const char *end = name + name_len;
-       int j = 0;  // current offset into buf
+       int ref = 0;
+       u16 _t;
 
+#define APPEND16(x) do {                                                  \
+               if (j + 2 > (off_t)buf_len)                                \
+                       goto overflow;                                          
   \
+               _t = htons(x);                                                  
   \
+               memcpy(buf + j, &_t, 2);                                   \
+               j += 2;                                                         
           \
+       } while (0)
+#define APPEND32(x) do {                                                  \
+               if (j + 4 > (off_t)buf_len)                                \
+                       goto overflow;                                          
   \
+               _t32 = htonl(x);                                                
   \
+               memcpy(buf + j, &_t32, 4);                                 \
+               j += 4;                                                         
           \
+       } while (0)
+
        if (name_len > 255) return -2;
 
        for (;;) {
                const char *const start = name;
+               if (table && (ref = dnslabel_table_get_pos(table, name)) >= 0) {
+                       APPEND16(ref | 0xc000);
+                       return j;
+               }
                name = strchr(name, '.');
                if (!name) {
                        const unsigned int label_len = end - start;
                        if (label_len > 63) return -1;
+                       if ((size_t)(j+label_len+1) > buf_len) return -2;
+                       if (table) dnslabel_table_add(table, start, j);
                        buf[j++] = label_len;
 
                        memcpy(buf + j, start, end - start);
@@ -965,6 +1309,8 @@
                        // append length of the label.
                        const unsigned int label_len = name - start;
                        if (label_len > 63) return -1;
+                       if ((size_t)(j+label_len+1) > buf_len) return -2;
+                       if (table) dnslabel_table_add(table, start, j);
                        buf[j++] = label_len;
 
                        memcpy(buf + j, start, name - start);
@@ -979,6 +1325,8 @@
        // in which case the zero is already there
        if (!j || buf[j-1]) buf[j++] = 0;
        return j;
+ overflow:
+       return (-2);
 }
 
 // Finds the length of a dns request for a DNS name of the given
@@ -999,17 +1347,8 @@
 evdns_request_data_build(const char *const name, const int name_len,
     const u16 trans_id, const u16 type, const u16 class,
     u8 *const buf, size_t buf_len) {
-       int j = 0;  // current offset into buf
+       off_t j = 0;    // current offset into buf
        u16 _t;  // used by the macros
-       u8 *labels;
-       int labels_len;
-
-#define APPEND16(x) do { \
-  if (j + 2 > buf_len) \
-    return (-1); \
-  _t = htons(x); \
-  memcpy(buf + j, &_t, 2); j += 2; \
-} while(0)
        
        APPEND16(trans_id);
        APPEND16(0x0100);  // standard query, recusion needed
@@ -1018,29 +1357,407 @@
        APPEND16(0);  // no authority
        APPEND16(0);  // no additional
 
-       labels = (u8 *) malloc(name_len + 2);
-        if (labels == NULL)
+       j = dnsname_to_labels(buf, buf_len, j, name, name_len, NULL);
+       if (j < 0) {
+               return (int)j;
+       }
+
+       APPEND16(type);
+       APPEND16(class);
+
+       return (int)j;
+ overflow:
+       return (-1);
+}
+
+// exported function
+struct evdns_server_port *
+evdns_add_server_port(int socket, int is_tcp, evdns_request_callback_fn_type 
cb, void *user_data)
+{
+       struct evdns_server_port *port;
+       if (!(port = malloc(sizeof(struct evdns_server_port))))
+               return NULL;
+
+       assert(!is_tcp); // TCP sockets not yet implemented
+       port->socket = socket;
+       port->refcnt = 1;
+       port->choked = 0;
+       port->closing = 0;
+       port->user_callback = cb;
+       port->user_data = user_data;
+       port->pending_replies = NULL;
+
+       event_set(&port->event, port->socket, EV_READ | EV_PERSIST,
+                         server_port_ready_callback, port);
+       event_add(&port->event, NULL); // check return.
+       return port;
+}
+
+// exported function
+void
+evdns_close_server_port(struct evdns_server_port *port)
+{
+       if (--port->refcnt == 0)
+               server_port_free(port);
+       port->closing = 1;
+}
+
+// exported function
+int
+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)
+{
+       struct server_request *req = TO_SERVER_REQUEST(_req);
+       struct server_reply_item **itemp, *item;
+       int *countp;
+
+       if (req->response) /* have we already answered? */
                return (-1);
-       labels_len = dnsname_to_labels(labels, name, name_len);
-       if (labels_len < 0) {
-               free(labels);
-               return (labels_len);
+
+       switch (section) {
+       case EVDNS_ANSWER_SECTION:
+               itemp = &req->answer;
+               countp = &req->n_answer;
+               break;
+       case EVDNS_AUTHORITY_SECTION:
+               itemp = &req->authority;
+               countp = &req->n_authority;
+               break;
+       case EVDNS_ADDITIONAL_SECTION:
+               itemp = &req->additional;
+               countp = &req->n_additional;
+               break;
+       default:
+               return (-1);
        }
-       if ((size_t)(j + labels_len) > buf_len) {
-               free(labels);
+       while (*itemp) {
+               itemp = &((*itemp)->next);
+       }
+       item = malloc(sizeof(struct server_reply_item));
+       if (!item)
+               return -1;
+       item->next = NULL;
+       if (!(item->name = strdup(name))) {
+               free(item);
+               return -1;
+       }
+       item->type = type;
+       item->class = class;
+       item->ttl = ttl;
+       item->is_name = is_name != 0;
+       item->datalen = 0;
+       item->data = NULL;
+       if (data) {
+               if (item->is_name) {
+                       if (!(item->data = strdup(data))) {
+                               free(item->name);
+                               free(item);
+                               return -1;
+                       }
+                       item->datalen = -1;
+               } else {
+                       if (!(item->data = malloc(datalen))) {
+                               free(item->name);
+                               free(item);
+                               return -1;
+                       }
+                       item->datalen = datalen;
+                       memcpy(item->data, data, datalen);
+               }
+       }
+
+       *itemp = item;
+       ++(*countp);
+       return 0;
+}
+
+// exported function
+int
+evdns_server_request_add_a_reply(struct evdns_server_request *req, const char 
*name, int n, void *addrs, int ttl)
+{
+       return evdns_server_request_add_reply(
+                 req, EVDNS_ANSWER_SECTION, name, TYPE_A, CLASS_INET,
+                 ttl, n*4, 0, addrs);
+}
+
+// exported function
+int
+evdns_server_request_add_aaaa_reply(struct evdns_server_request *req, const 
char *name, int n, void *addrs, int ttl)
+{
+       return evdns_server_request_add_reply(
+                 req, EVDNS_ANSWER_SECTION, name, TYPE_AAAA, CLASS_INET,
+                 ttl, n*16, 0, addrs);
+}
+
+// exported function
+int
+evdns_server_request_add_ptr_reply(struct evdns_server_request *req, struct 
in_addr *in, const char *inaddr_name, const char *hostname, int ttl)
+{
+       u32 a;
+       char buf[32];
+       assert(in || inaddr_name);
+       assert(!(in && inaddr_name));
+       if (in) {
+               a = ntohl(in->s_addr);
+               sprintf(buf, "%d.%d.%d.%d.in-addr.arpa",
+                               (int)(u8)((a    )&0xff),
+                               (int)(u8)((a>>8 )&0xff),
+                               (int)(u8)((a>>16)&0xff),
+                               (int)(u8)((a>>24)&0xff));
+               inaddr_name = buf;
+       }
+       return evdns_server_request_add_reply(
+                 req, EVDNS_ANSWER_SECTION, inaddr_name, TYPE_PTR, CLASS_INET,
+                 ttl, -1, 1, hostname);
+}
+
+// exported function
+int
+evdns_server_request_add_cname_reply(struct evdns_server_request *req, const 
char *name, const char *cname, int ttl)
+{
+       return evdns_server_request_add_reply(
+                 req, EVDNS_ANSWER_SECTION, name, TYPE_A, CLASS_INET,
+                 ttl, -1, 1, cname);
+}
+
+
+static int
+evdns_server_request_format_response(struct server_request *req, int err)
+{
+       unsigned char buf[1500];
+       size_t buf_len = sizeof(buf);
+       off_t j = 0, r;
+       u16 _t;
+       u32 _t32;
+       int i;
+       u16 flags;
+       struct dnslabel_table table;
+
+       if (err < 0 || err > 15) return -1;
+
+       /* Set response bit and error code; copy OPCODE and RD fields from
+        * question; copy RA and AA if set by caller. */
+       flags = req->base.flags;
+       flags |= (0x8000 | err);
+
+       dnslabel_table_init(&table);
+       APPEND16(req->trans_id);
+       APPEND16(flags);
+       APPEND16(req->base.nquestions);
+       APPEND16(req->n_answer);
+       APPEND16(req->n_authority);
+       APPEND16(req->n_additional);
+
+       /* Add questions. */
+       for (i=0; i < req->base.nquestions; ++i) {
+               const char *s = req->base.questions[i]->name;
+               j = dnsname_to_labels(buf, buf_len, j, s, strlen(s), &table);
+               if (j < 0) {
+                       dnslabel_clear(&table);
+                       return (int) j;
+               }
+               APPEND16(req->base.questions[i]->type);
+               APPEND16(req->base.questions[i]->class);
+       }
+
+       /* Add answer, authority, and additional sections. */
+       for (i=0; i<3; ++i) {
+               struct server_reply_item *item;
+               if (i==0)
+                       item = req->answer;
+               else if (i==1)
+                       item = req->authority;
+               else
+                       item = req->additional;
+               while (item) {
+                       r = dnsname_to_labels(buf, buf_len, j, item->name, 
strlen(item->name), &table);
+                       if (r < 0)
+                               goto overflow;
+                       j = r;
+
+                       APPEND16(item->type);
+                       APPEND16(item->class);
+                       APPEND32(item->ttl);
+                       if (item->is_name) {
+                               off_t len_idx = j, name_start;
+                               j += 2;
+                               name_start = j;
+                               r = dnsname_to_labels(buf, buf_len, j, 
item->data, strlen(item->data), &table);
+                               if (r < 0)
+                                       goto overflow;
+                               j = r;
+                               _t = htons( (j-name_start) );
+                               memcpy(buf+len_idx, &_t, 2);
+                       } else {
+                               APPEND16(item->datalen);
+                               if (j+item->datalen > (off_t)buf_len)
+                                       goto overflow;
+                               memcpy(buf+j, item->data, item->datalen);
+                               j += item->datalen;
+                       }
+                       item = item->next;
+               }
+       }
+
+       if (j > 512) {
+overflow:
+               j = 512;
+               buf[3] |= 0x02; /* set the truncated bit. */
+       }
+
+       req->response_len = j;
+
+       if (!(req->response = malloc(req->response_len))) {
+               server_request_free_answers(req);
+               dnslabel_clear(&table);
                return (-1);
        }
-       memcpy(buf + j, labels, labels_len);
-       j += labels_len;
-       free(labels);
+       memcpy(req->response, buf, req->response_len);
+       server_request_free_answers(req);
+       dnslabel_clear(&table);
+       return (0);
+}
        
-       APPEND16(type);
-       APPEND16(class);
-#undef APPEND16
+// exported function
+int
+evdns_server_request_respond(struct evdns_server_request *_req, int err)
+{
+       struct server_request *req = TO_SERVER_REQUEST(_req);
+       struct evdns_server_port *port = req->port;
+       int r;
+       if (!req->response) {
+               if ((r = evdns_server_request_format_response(req, err))<0)
+                       return r;
+       }
 
-       return (j);
+       r = sendto(port->socket, req->response, req->response_len, 0,
+                          (struct sockaddr*) &req->addr, req->addrlen);
+       if (r<0) {
+               int err = last_error(port->socket);
+               if (! error_is_eagain(err))
+                       return -1;
+
+               if (port->pending_replies) {
+                       req->prev_pending = port->pending_replies->prev_pending;
+                       req->next_pending = port->pending_replies;
+                       req->prev_pending->next_pending =
+                               req->next_pending->prev_pending = req;
+               } else {
+                       req->prev_pending = req->next_pending = req;
+                       port->pending_replies = req;
+                       port->choked = 1;
+
+                       (void) event_del(&port->event);
+                       event_set(&port->event, port->socket, 
(port->closing?0:EV_READ) | EV_WRITE | EV_PERSIST, server_port_ready_callback, 
port);
+
+                       if (event_add(&port->event, NULL) < 0) {
+                               log(EVDNS_LOG_WARN, "Error from libevent when 
adding event for DNS server");
+                       }
+
+               }
+
+               return 1;
+       }
+       if (server_request_free(req))
+               return 0;
+
+       if (req->port->pending_replies)
+               server_port_flush(port);
+
+       return 0;
 }
 
+// Free all storage held by RRs in req.
+static void
+server_request_free_answers(struct server_request *req)
+{
+       struct server_reply_item *victim, *next, **list;
+       int i;
+       for (i = 0; i < 3; ++i) {
+               if (i==0)
+                       list = &req->answer;
+               else if (i==1)
+                       list = &req->authority;
+               else
+                       list = &req->additional;
+
+               victim = *list;
+               while (victim) {
+                       next = victim->next;
+                       free(victim->name);
+                       if (victim->data)
+                               free(victim->data);
+                       victim = next;
+               }
+               *list = NULL;
+       }
+}
+
+// Free all storage held by req, and remove links to it.
+// return true iff we just wound up freeing the server_port.
+static int
+server_request_free(struct server_request *req)
+{
+       int i, rc=1;
+       if (req->base.questions) {
+               for (i = 0; i < req->base.nquestions; ++i)
+                       free(req->base.questions[i]);
+       }
+
+       if (req->port) {
+               if (req->port->pending_replies == req) {
+                       if (req->next_pending)
+                               req->port->pending_replies = req->next_pending;
+                       else
+                               req->port->pending_replies = NULL;
+               }
+               rc = --req->port->refcnt;
+       }
+
+       if (req->response)
+               free(req->response);
+
+       server_request_free_answers(req);
+
+       if (req->next_pending && req->next_pending != req) {
+               req->next_pending->prev_pending = req->prev_pending;
+               req->prev_pending->next_pending = req->next_pending;
+       }
+
+       if (rc == 0) {
+               server_port_free(req->port);
+               free(req);
+               return (1);
+       }
+       free(req);
+       return (0);
+}
+
+// Free all storage held by an evdns_server_port.  Only called when 
+static void
+server_port_free(struct evdns_server_port *port)
+{
+       assert(port);
+       assert(!port->refcnt);
+       assert(!port->pending_replies);
+       if (port->socket > 0) {
+               CLOSE_SOCKET(port->socket);
+               port->socket = -1;
+       }
+       (void) event_del(&port->event);
+}
+
+// exported function
+int
+evdns_server_request_drop(struct evdns_server_request *_req)
+{
+       struct server_request *req = TO_SERVER_REQUEST(_req);
+       server_request_free(req);
+       return 0;
+}
+
+#undef APPEND16
+#undef APPEND32
+
 // this is a libevent callback function which is called when a request
 // has timed out.
 static void
@@ -1104,7 +1821,7 @@
        req->transmit_me = 1;
        if (req->trans_id == 0xffff) abort();
 
-       if (req->ns->choaked) {
+       if (req->ns->choked) {
                // don't bother trying to write to a socket
                // which we have had EAGAIN from
                return 1;
@@ -1114,7 +1831,7 @@
        switch (r) {
        case 1:
                // temp failure
-               req->ns->choaked = 1;
+               req->ns->choked = 1;
                nameserver_write_waiting(req->ns, 1);
                return 1;
        case 2:
@@ -1288,7 +2005,7 @@
 
        ns->socket = socket(PF_INET, SOCK_DGRAM, 0);
        if (ns->socket < 0) { err = 1; goto out1; }
-#if defined(MS_WINDOWS) || defined(WIN32)
+#ifdef WIN32
         {
                u_long nonblocking = 1;
                ioctlsocket(ns->socket, FIONBIO, &nonblocking);
@@ -1444,6 +2161,22 @@
        }
 }
 
+// exported function
+int evdns_resolve_ipv6(const char *name, int flags,
+                                          evdns_callback_type callback, void 
*ptr) {
+       log(EVDNS_LOG_DEBUG, "Resolve requested for %s", name);
+       if (flags & DNS_QUERY_NO_SEARCH) {
+               struct request *const req =
+                       request_new(TYPE_AAAA, name, flags, callback, ptr);
+               if (req == NULL)
+                       return (1);
+               request_submit(req);
+               return (0);
+       } else {
+               return (search_request_new(TYPE_AAAA, name, flags, callback, 
ptr));
+       }
+}
+
 int evdns_resolve_reverse(struct in_addr *in, int flags, evdns_callback_type 
callback, void *ptr) {
        char buf[32];
        struct request *req;
@@ -1462,6 +2195,30 @@
        return 0;
 }
 
+int evdns_resolve_reverse_ipv6(struct in6_addr *in, int flags, 
evdns_callback_type callback, void *ptr) {
+       char buf[64];
+       char *cp;
+       struct request *req;
+       int i;
+       assert(in);
+       cp = buf;
+       for (i=0; i < 16; ++i) {
+               u8 byte = in->s6_addr[i];
+               *cp++ = "0123456789abcdef"[byte >> 4];
+               *cp++ = '.';
+               *cp++ = "0123456789abcdef"[byte & 0x0f];
+               *cp++ = '.';
+       }
+       assert(cp + strlen(".ip6.arpa") < buf+sizeof(buf));
+       strcpy(cp, ".ip6.arpa");
+       log(EVDNS_LOG_DEBUG, "Resolve requested for %s (reverse)", buf);
+       req = request_new(TYPE_PTR, buf, flags, callback, ptr);
+       if (!req) return 1;
+       request_submit(req);
+       return 0;
+}
+
+
 /////////////////////////////////////////////////////////////////////
 // Search support
 //
@@ -1614,6 +2371,7 @@
 
        // we ran off the end of the list and still didn't find the requested 
string
        abort();
+       return NULL; /* unreachable; stops warnings in some compilers. */
 }
 
 static int
@@ -1827,10 +2585,12 @@
        }
        if (st.st_size > 65535) { err = 3; goto out1; }  // no resolv.conf 
should be any bigger
 
-       resolv = (u8 *) malloc(st.st_size + 1);
+       resolv = (u8 *) malloc((size_t)st.st_size + 1);
        if (!resolv) { err = 4; goto out1; }
 
-       if (read(fd, resolv, st.st_size) != st.st_size) { err = 5; goto out2; }
+       if (read(fd, resolv, (size_t)st.st_size) != st.st_size) {
+               err = 5; goto out2;
+       }
        resolv[st.st_size] = 0;  // we malloced an extra byte
 
        start = (char *) resolv;
@@ -1861,7 +2621,7 @@
        return err;
 }
 
-#if defined(MS_WINDOWS) || defined(WIN32)
+#ifdef WIN32
 // Add multiple nameservers from a space-or-comma-separated list.
 static int
 evdns_nameserver_ip_add_line(const char *ips) {
@@ -2054,10 +2816,10 @@
 #endif
 
 int
-evdns_init()
+evdns_init(void)
 {
        int res = 0;
-#if defined(MS_WINDOWS) || defined(WIN32)
+#ifdef WIN32
        evdns_config_windows_nameservers();
 #else
        res = evdns_resolv_conf_parse(DNS_OPTIONS_ALL, "/etc/resolv.conf");
@@ -2144,17 +2906,50 @@
        }
        fflush(stdout);
 }
+void
+evdns_server_callback(struct evdns_server_request *req, void *data)
+{
+       int i, r;
+       (void)data;
+       /* dummy; give 192.168.11.11 as an answer for all A questions,
+        *      give foo.bar.example.com as an answer for all PTR questions. */
+       for (i = 0; i < req->nquestions; ++i) {
+               u32 ans = htonl(0xc0a80b0bUL);
+               if (req->questions[i]->type == EVDNS_TYPE_A &&
+                       req->questions[i]->class == EVDNS_CLASS_INET) {
+                       printf(" -- replying for %s (A)\n", 
req->questions[i]->name);
+                       r = evdns_server_request_add_a_reply(req, 
req->questions[i]->name,
+                                                                               
  1, &ans, 10);
+                       if (r<0)
+                               printf("eeep, didn't work.\n");
+               } else if (req->questions[i]->type == EVDNS_TYPE_PTR &&
+                                  req->questions[i]->class == 
EVDNS_CLASS_INET) {
+                       printf(" -- replying for %s (PTR)\n", 
req->questions[i]->name);
+                       r = evdns_server_request_add_ptr_reply(req, NULL, 
req->questions[i]->name,
+                                                                               
        "foo.bar.example.com", 10);
+               } else {
+                       printf(" -- skipping %s [%d %d]\n", 
req->questions[i]->name,
+                                  req->questions[i]->type, 
req->questions[i]->class);
+               }
+       }
 
+       r = evdns_request_respond(req, 0);
+       if (r<0)
+               printf("eeek, couldn't send reply.\n");
+}
+
 void
-logfn(const char *msg) {
+logfn(int is_warn, const char *msg) {
+       (void) is_warn;
   fprintf(stderr, "%s\n", msg);
 }
 int
 main(int c, char **v) {
        int idx;
-       int reverse = 0, verbose = 1;
+       int reverse = 0, verbose = 1, servertest = 0;
        if (c<2) {
                fprintf(stderr, "syntax: %s [-x] [-v] hostname\n", v[0]);
+               fprintf(stderr, "syntax: %s [-servertest]\n", v[0]);
                return 1;
        }
        idx = 1;
@@ -2163,6 +2958,8 @@
                        reverse = 1;
                else if (!strcmp(v[idx], "-v"))
                        verbose = 1;
+               else if (!strcmp(v[idx], "-servertest"))
+                       servertest = 1;
                else
                        fprintf(stderr, "Unknown option %s\n", v[idx]);
                ++idx;
@@ -2171,6 +2968,20 @@
        if (verbose)
                evdns_set_log_fn(logfn);
        evdns_resolv_conf_parse(DNS_OPTION_NAMESERVERS, "/etc/resolv.conf");
+       if (servertest) {
+               int sock;
+               struct sockaddr_in my_addr;
+               sock = socket(PF_INET, SOCK_DGRAM, 0);
+               fcntl(sock, F_SETFL, O_NONBLOCK);
+               my_addr.sin_family = AF_INET;
+               my_addr.sin_port = htons(10053);
+               my_addr.sin_addr.s_addr = INADDR_ANY;
+               if (bind(sock, (struct sockaddr*)&my_addr, sizeof(my_addr))<0) {
+                       perror("bind");
+                       exit(1);
+               }
+               evdns_add_server_port(sock, 0, evdns_server_callback, NULL);
+       }
        for (; idx < c; ++idx) {
                if (reverse) {
                        struct in_addr addr;
=== evdns.h
==================================================================
--- evdns.h     (revision 11547)
+++ evdns.h     (local)
@@ -262,6 +262,7 @@
 
 #define DNS_IPv4_A 1
 #define DNS_PTR 2
+#define DNS_IPv6_AAAA 3
 
 #define DNS_QUERY_NO_SEARCH 1
 
@@ -272,7 +273,7 @@
 
 /* 
  * The callback that contains the results from a lookup.
- * - type is either DNS_IPv4_A or DNS_PTR
+ * - type is either DNS_IPv4_A or DNS_IPv6_AAAA or DNS_PTR
  * - count contains the number of addresses of form type
  * - ttl is the number of seconds the resolution may be cached for.
  * - addresses needs to be cast according to type
@@ -288,8 +289,11 @@
 int evdns_resume(void);
 int evdns_nameserver_ip_add(const char *ip_as_string);
 int evdns_resolve_ipv4(const char *name, int flags, evdns_callback_type 
callback, void *ptr);
+int evdns_resolve_ipv6(const char *name, int flags, evdns_callback_type 
callback, void *ptr);
 struct in_addr;
+struct in6_addr;
 int evdns_resolve_reverse(struct in_addr *in, int flags, evdns_callback_type 
callback, void *ptr);
+int evdns_resolve_reverse_ipv6(struct in6_addr *in, int flags, 
evdns_callback_type callback, void *ptr);
 int evdns_resolv_conf_parse(int flags, const char *);
 #ifdef MS_WINDOWS
 int evdns_config_windows_nameservers(void);
@@ -303,4 +307,47 @@
 
 #define DNS_NO_SEARCH 1
 
+/* Structures and functions used to implement a DNS server. */
+
+struct evdns_server_request {
+       int flags;
+       int nquestions;
+       struct evdns_server_question **questions;
+};
+struct evdns_server_question {
+       int type;
+       int class;
+       char name[1];
+};
+typedef void (*evdns_request_callback_fn_type)(struct evdns_server_request *, 
void *);
+#define EVDNS_ANSWER_SECTION 0
+#define EVDNS_AUTHORITY_SECTION 1
+#define EVDNS_ADDITIONAL_SECTION 2
+
+#define EVDNS_TYPE_A      1
+#define EVDNS_TYPE_NS     2
+#define EVDNS_TYPE_CNAME   5
+#define EVDNS_TYPE_SOA    6
+#define EVDNS_TYPE_PTR   12
+#define EVDNS_TYPE_MX    15
+#define EVDNS_TYPE_TXT   16
+#define EVDNS_TYPE_AAAA          28
+
+#define EVDNS_QTYPE_AXFR 252
+#define EVDNS_QTYPE_ALL         255
+
+#define EVDNS_CLASS_INET   1
+
+struct evdns_server_port *evdns_add_server_port(int socket, int is_tcp, 
evdns_request_callback_fn_type callback, void *user_data);
+void evdns_close_server_port(struct evdns_server_port *port);
+
+int 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);
+int evdns_server_request_add_a_reply(struct evdns_server_request *req, const 
char *name, int n, void *addrs, int ttl);
+int evdns_server_request_add_aaaa_reply(struct evdns_server_request *req, 
const char *name, int n, void *addrs, int ttl);
+int evdns_server_request_add_ptr_reply(struct evdns_server_request *req, 
struct in_addr *in, const char *inaddr_name, const char *hostname, int ttl);
+int evdns_server_request_add_cname_reply(struct evdns_server_request *req, 
const char *name, const char *cname, int ttl);
+
+int evdns_server_request_respond(struct evdns_server_request *req, int err);
+int evdns_server_request_drop(struct evdns_server_request *req);
+
 #endif  // !EVENTDNS_H

Attachment: pgplyagUMuzhH.pgp
Description: PGP signature

_______________________________________________
Libevent-users mailing list
Libevent-users@monkey.org
http://monkey.org/mailman/listinfo/libevent-users

Reply via email to