Back to index

tor  0.2.3.19-rc
eventdns.c
Go to the documentation of this file.
00001 /* READ THIS COMMENT BEFORE HACKING THIS FILE.
00002  *
00003  * This eventdns.c copy has diverged a bit from Libevent's version, and it's
00004  * no longer easy to resynchronize them.  Once Tor requires Libevent 2.0, we
00005  * will just dump this file and use Libevent's evdns code.
00006  *
00007  * Therefore, you probably shouldn't make any change here without making it to
00008  * Libevent as well: it's not good for the implementation to diverge even
00009  * more.  Also, we can't shouldn't wantonly the API here (since Libevent APIs
00010  * can't change in ways that break user behavior).  Also, we shouldn't bother
00011  * with cosmetic changes: the whole module is slated for demolition, so
00012  * there's no point dusting the linebreaks or re-painting the parser.
00013  *
00014  * (We can't just drop the Libevent 2.0 evdns implementation in here instead,
00015  * since it depends pretty heavily on parts of Libevent 2.0.)
00016  */
00017 
00018 /* Async DNS Library
00019  * Adam Langley <agl@imperialviolet.org>
00020  * Public Domain code
00021  *
00022  * This software is Public Domain. To view a copy of the public domain dedication,
00023  * visit http://creativecommons.org/licenses/publicdomain/ or send a letter to
00024  * Creative Commons, 559 Nathan Abbott Way, Stanford, California 94305, USA.
00025  *
00026  * I ask and expect, but do not require, that all derivative works contain an
00027  * attribution similar to:
00028  *     Parts developed by Adam Langley <agl@imperialviolet.org>
00029  *
00030  * You may wish to replace the word "Parts" with something else depending on
00031  * the amount of original code.
00032  *
00033  * (Derivative works does not include programs which link against, run or include
00034  * the source verbatim in their source distributions)
00035  *
00036  * Version: 0.1b
00037  */
00038 
00039 #include "eventdns_tor.h"
00040 #include "../common/util.h"
00041 #include <sys/types.h>
00042 /* #define NDEBUG */
00043 
00044 #ifndef DNS_USE_CPU_CLOCK_FOR_ID
00045 #ifndef DNS_USE_GETTIMEOFDAY_FOR_ID
00046 #ifndef DNS_USE_OPENSSL_FOR_ID
00047 #error Must configure at least one id generation method.
00048 #error Please see the documentation.
00049 #endif
00050 #endif
00051 #endif
00052 
00053 /* #define _POSIX_C_SOURCE 200507 */
00054 #define _GNU_SOURCE
00055 
00056 #ifdef DNS_USE_CPU_CLOCK_FOR_ID
00057 #ifdef DNS_USE_OPENSSL_FOR_ID
00058 #error Multiple id options selected
00059 #endif
00060 #ifdef DNS_USE_GETTIMEOFDAY_FOR_ID
00061 #error Multiple id options selected
00062 #endif
00063 #include <time.h>
00064 #endif
00065 
00066 #ifdef DNS_USE_OPENSSL_FOR_ID
00067 #ifdef DNS_USE_GETTIMEOFDAY_FOR_ID
00068 #error Multiple id options selected
00069 #endif
00070 #include <openssl/rand.h>
00071 #endif
00072 
00073 #include <string.h>
00074 #ifdef HAVE_FCNTL_H
00075 #include <fcntl.h>
00076 #endif
00077 #ifdef HAVE_SYS_TIME_H
00078 #include <sys/time.h>
00079 #endif
00080 #ifdef HAVE_STDINT_H
00081 #include <stdint.h>
00082 #endif
00083 #include <stdlib.h>
00084 #include <errno.h>
00085 #include <assert.h>
00086 #ifdef HAVE_UNISTD_H
00087 #include <unistd.h>
00088 #endif
00089 #ifdef HAVE_LIMITS_H
00090 #include <limits.h>
00091 #endif
00092 #include <sys/stat.h>
00093 #include <ctype.h>
00094 #include <stdio.h>
00095 #include <stdarg.h>
00096 
00097 #include "eventdns.h"
00098 
00099 #ifdef _WIN32
00100 #include <windows.h>
00101 #include <winsock2.h>
00102 #include <iphlpapi.h>
00103 #else
00104 #include <sys/socket.h>
00105 #include <netinet/in.h>
00106 #include <arpa/inet.h>
00107 #endif
00108 
00109 #ifdef HAVE_NETINET_IN6_H
00110 #include <netinet/in6.h>
00111 #endif
00112 
00113 #ifdef _WIN32
00114 typedef int socklen_t;
00115 #endif
00116 
00117 #define EVDNS_LOG_DEBUG 0
00118 #define EVDNS_LOG_WARN 1
00119 
00120 #ifndef HOST_NAME_MAX
00121 #define HOST_NAME_MAX 255
00122 #endif
00123 
00124 #ifndef NDEBUG
00125 #include <stdio.h>
00126 #endif
00127 
00128 /* for debugging possible memory leaks. */
00129 #define mm_malloc(x) tor_malloc(x)
00130 #define mm_realloc(x,y) tor_realloc((x),(y))
00131 #define mm_free(x) tor_free(x)
00132 #define mm_strdup(x) tor_strdup(x)
00133 #define _mm_free(x) _tor_free(x)
00134 
00135 #undef MIN
00136 #define MIN(a,b) ((a)<(b)?(a):(b))
00137 
00138 #if 0
00139 #ifdef __USE_ISOC99B
00140 /* libevent doesn't work without this */
00141 typedef uint8_t u_char;
00142 typedef unsigned int uint;
00143 #endif
00144 #endif
00145 #include <event.h>
00146 
00147 #define u64 uint64_t
00148 #define u32 uint32_t
00149 #define u16 uint16_t
00150 #define u8    uint8_t
00151 
00152 #define MAX_ADDRS 4   /* maximum number of addresses from a single packet */
00153 /* which we bother recording */
00154 
00155 #define TYPE_A              EVDNS_TYPE_A
00156 #define TYPE_CNAME   5
00157 #define TYPE_PTR     EVDNS_TYPE_PTR
00158 #define TYPE_AAAA    EVDNS_TYPE_AAAA
00159 
00160 #define CLASS_INET   EVDNS_CLASS_INET
00161 
00162 #define CLEAR(x) do { memset((x), 0xF0, sizeof(*(x))); } while(0)
00163 
00164 struct evdns_request {
00165        u8 *request; /* the dns packet data */
00166        unsigned int request_len;
00167        int reissue_count;
00168        int tx_count;  /* the number of times that this packet has been sent */
00169        unsigned int request_type; /* TYPE_PTR or TYPE_A */
00170        void *user_pointer;   /* the pointer given to us for this request */
00171        evdns_callback_type user_callback;
00172        struct nameserver *ns;      /* the server which we last sent it */
00173 
00174        /* elements used by the searching code */
00175        int search_index;
00176        struct search_state *search_state;
00177        char *search_origname;      /* needs to be mm_free()ed */
00178        int search_flags;
00179 
00180        /* these objects are kept in a circular list */
00181        struct evdns_request *next, *prev;
00182 
00183        struct event timeout_event;
00184 
00185        u16 trans_id;  /* the transaction id */
00186        char request_appended;      /* true if the request pointer is data which follows this struct */
00187        char transmit_me;  /* needs to be transmitted */
00188 };
00189 
00190 #ifndef HAVE_STRUCT_IN6_ADDR
00191 struct in6_addr {
00192        u8 s6_addr[16];
00193 };
00194 #endif
00195 
00196 struct reply {
00197        unsigned int type;
00198        unsigned int have_answer;
00199        union {
00200               struct {
00201                      u32 addrcount;
00202                      u32 addresses[MAX_ADDRS];
00203               } a;
00204               struct {
00205                      u32 addrcount;
00206                      struct in6_addr addresses[MAX_ADDRS];
00207               } aaaa;
00208               struct {
00209                      char name[HOST_NAME_MAX];
00210               } ptr;
00211        } data;
00212 };
00213 
00214 struct nameserver {
00215        int socket;    /* a connected UDP socket */
00216        struct sockaddr_storage address;
00217        int failed_times;  /* number of times which we have given this server a chance */
00218        int timedout;  /* number of times in a row a request has timed out */
00219        struct event event;
00220        /* these objects are kept in a circular list */
00221        struct nameserver *next, *prev;
00222        struct event timeout_event; /* used to keep the timeout for */
00223                                                         /* when we next probe this server. */
00224                                                         /* Valid if state == 0 */
00225        char state;    /* zero if we think that this server is down */
00226        char choked;  /* true if we have an EAGAIN from this server's socket */
00227        char write_waiting;   /* true if we are waiting for EV_WRITE events */
00228 };
00229 
00230 static struct evdns_request *req_head = NULL, *req_waiting_head = NULL;
00231 static struct nameserver *server_head = NULL;
00232 
00233 /* Represents a local port where we're listening for DNS requests. Right now, */
00234 /* only UDP is supported. */
00235 struct evdns_server_port {
00236        int socket; /* socket we use to read queries and write replies. */
00237        int refcnt; /* reference count. */
00238        char choked; /* Are we currently blocked from writing? */
00239        char closing; /* Are we trying to close this port, pending writes? */
00240        evdns_request_callback_fn_type user_callback; /* Fn to handle requests */
00241        void *user_data; /* Opaque pointer passed to user_callback */
00242        struct event event; /* Read/write event */
00243        /* circular list of replies that we want to write. */
00244        struct server_request *pending_replies;
00245 };
00246 
00247 /* Represents part of a reply being built.       (That is, a single RR.) */
00248 struct server_reply_item {
00249        struct server_reply_item *next; /* next item in sequence. */
00250        char *name; /* name part of the RR */
00251        u16 type : 16; /* The RR type */
00252        u16 class : 16; /* The RR class (usually CLASS_INET) */
00253        u32 ttl; /* The RR TTL */
00254        char is_name; /* True iff data is a label */
00255        u16 datalen; /* Length of data; -1 if data is a label */
00256        void *data; /* The contents of the RR */
00257 };
00258 
00259 /* Represents a request that we've received as a DNS server, and holds */
00260 /* the components of the reply as we're constructing it. */
00261 struct server_request {
00262        /* Pointers to the next and previous entries on the list of replies */
00263        /* that we're waiting to write.     Only set if we have tried to respond */
00264        /* and gotten EAGAIN. */
00265        struct server_request *next_pending;
00266        struct server_request *prev_pending;
00267 
00268        u16 trans_id; /* Transaction id. */
00269        struct evdns_server_port *port; /* Which port received this request on? */
00270        struct sockaddr_storage addr; /* Where to send the response */
00271        socklen_t addrlen; /* length of addr */
00272 
00273        int n_answer; /* how many answer RRs have been set? */
00274        int n_authority; /* how many authority RRs have been set? */
00275        int n_additional; /* how many additional RRs have been set? */
00276 
00277        struct server_reply_item *answer; /* linked list of answer RRs */
00278        struct server_reply_item *authority; /* linked list of authority RRs */
00279        struct server_reply_item *additional; /* linked list of additional RRs */
00280 
00281        /* Constructed response.  Only set once we're ready to send a reply. */
00282        /* Once this is set, the RR fields are cleared, and no more should be set. */
00283        char *response;
00284        size_t response_len;
00285 
00286        /* Caller-visible fields: flags, questions. */
00287        struct evdns_server_request base;
00288 };
00289 
00290 /* helper macro */
00291 #define OFFSET_OF(st, member) ((off_t) (((char*)&((st*)0)->member)-(char*)0))
00292 
00293 /* Given a pointer to an evdns_server_request, get the corresponding */
00294 /* server_request. */
00295 #define TO_SERVER_REQUEST(base_ptr)                                                                      \
00296        ((struct server_request*)                                                                         \
00297         (((char*)(base_ptr) - OFFSET_OF(struct server_request, base))))
00298 
00299 /* The number of good nameservers that we have */
00300 static int global_good_nameservers = 0;
00301 
00302 /* inflight requests are contained in the req_head list */
00303 /* and are actually going out across the network */
00304 static int global_requests_inflight = 0;
00305 /* requests which aren't inflight are in the waiting list */
00306 /* and are counted here */
00307 static int global_requests_waiting = 0;
00308 
00309 static int global_max_requests_inflight = 64;
00310 
00311 static struct timeval global_timeout = {5, 0};   /* 5 seconds */
00312 static int global_max_reissues = 1;       /* a reissue occurs when we get some errors from the server */
00313 static int global_max_retransmits = 3;    /* number of times we'll retransmit a request which timed out */
00314 /* number of timeouts in a row before we consider this server to be down */
00315 static int global_max_nameserver_timeout = 3;
00316 
00317 /* true iff we should use the 0x20 hack. */
00318 static int global_randomize_case = 1;
00319 
00320 /* These are the timeout values for nameservers. If we find a nameserver is down */
00321 /* we try to probe it at intervals as given below. Values are in seconds. */
00322 static const struct timeval global_nameserver_timeouts[] = {{10, 0}, {60, 0}, {300, 0}, {900, 0}, {3600, 0}};
00323 static const int global_nameserver_timeouts_length = (int)(sizeof(global_nameserver_timeouts)/sizeof(struct timeval));
00324 
00325 static struct nameserver *nameserver_pick(void);
00326 static void evdns_request_insert(struct evdns_request *req, struct evdns_request **head);
00327 static void nameserver_ready_callback(int fd, short events, void *arg);
00328 static int evdns_transmit(void);
00329 static int evdns_request_transmit(struct evdns_request *req);
00330 static void nameserver_send_probe(struct nameserver *const ns);
00331 static void search_request_finished(struct evdns_request *const);
00332 static int search_try_next(struct evdns_request *const req);
00333 static int search_request_new(int type, const char *const name, int flags, evdns_callback_type user_callback, void *user_arg);
00334 static void evdns_requests_pump_waiting_queue(void);
00335 static u16 transaction_id_pick(void);
00336 static struct evdns_request *request_new(int type, const char *name, int flags, evdns_callback_type callback, void *ptr);
00337 static void request_submit(struct evdns_request *req);
00338 
00339 static int server_request_free(struct server_request *req);
00340 static void server_request_free_answers(struct server_request *req);
00341 static void server_port_free(struct evdns_server_port *port);
00342 static void server_port_ready_callback(int fd, short events, void *arg);
00343 
00344 static int strtoint(const char *const str);
00345 
00346 #ifdef _WIN32
00347 static int
00348 last_error(int sock)
00349 {
00350        int optval, optvallen=sizeof(optval);
00351        int err = WSAGetLastError();
00352        if (err == WSAEWOULDBLOCK && sock >= 0) {
00353               if (getsockopt(sock, SOL_SOCKET, SO_ERROR, (void*)&optval,
00354                                       &optvallen))
00355                      return err;
00356               if (optval)
00357                      return optval;
00358        }
00359        return err;
00360 
00361 }
00362 static int
00363 error_is_eagain(int err)
00364 {
00365        return err == EAGAIN || err == WSAEWOULDBLOCK;
00366 }
00367 #define inet_aton(c, addr) tor_inet_aton((c), (addr))
00368 #define CLOSE_SOCKET(x) closesocket(x)
00369 #else
00370 #define last_error(sock) (errno)
00371 #define error_is_eagain(err) ((err) == EAGAIN)
00372 #define CLOSE_SOCKET(x) close(x)
00373 #endif
00374 
00375 #define ISSPACE(c) TOR_ISSPACE(c)
00376 #define ISDIGIT(c) TOR_ISDIGIT(c)
00377 #define ISALPHA(c) TOR_ISALPHA(c)
00378 #define TOLOWER(c) TOR_TOLOWER(c)
00379 #define TOUPPER(c) TOR_TOUPPER(c)
00380 
00381 #ifndef NDEBUG
00382 static const char *
00383 debug_ntoa(u32 address)
00384 {
00385        static char buf[32];
00386        u32 a = ntohl(address);
00387        snprintf(buf, sizeof(buf), "%d.%d.%d.%d",
00388                      (int)(u8)((a>>24)&0xff),
00389                      (int)(u8)((a>>16)&0xff),
00390                      (int)(u8)((a>>8 )&0xff),
00391                      (int)(u8)((a  )&0xff));
00392        return buf;
00393 }
00394 static const char *
00395 debug_ntop(const struct sockaddr *sa)
00396 {
00397        if (sa->sa_family == AF_INET) {
00398               struct sockaddr_in *sin = (struct sockaddr_in *) sa;
00399               return debug_ntoa(sin->sin_addr.s_addr);
00400        }
00401        if (sa->sa_family == AF_INET6) {
00402               /* Tor-specific.  In libevent, add more check code. */
00403               static char buf[128];
00404               struct sockaddr_in6 *sin = (struct sockaddr_in6 *) sa;
00405               tor_inet_ntop(AF_INET6, &sin->sin6_addr, buf, sizeof(buf));
00406               return buf;
00407        }
00408        return "<unknown>";
00409 }
00410 #endif
00411 
00412 static evdns_debug_log_fn_type evdns_log_fn = NULL;
00413 
00414 void
00415 evdns_set_log_fn(evdns_debug_log_fn_type fn)
00416 {
00417        evdns_log_fn = fn;
00418 }
00419 
00420 #ifdef __GNUC__
00421 #define EVDNS_LOG_CHECK     __attribute__ ((format(printf, 2, 3)))
00422 #else
00423 #define EVDNS_LOG_CHECK
00424 #endif
00425 
00426 static void _evdns_log(int warn, const char *fmt, ...) EVDNS_LOG_CHECK;
00427 static void
00428 _evdns_log(int warn, const char *fmt, ...)
00429 {
00430        va_list args;
00431        static char buf[512];
00432        if (!evdns_log_fn)
00433               return;
00434        va_start(args,fmt);
00435 #ifdef _WIN32
00436        _vsnprintf(buf, sizeof(buf), fmt, args);
00437 #else
00438        vsnprintf(buf, sizeof(buf), fmt, args);
00439 #endif
00440        buf[sizeof(buf)-1] = '\0';
00441        evdns_log_fn(warn, buf);
00442        va_end(args);
00443 }
00444 
00445 #define log _evdns_log
00446 
00447 static int
00448 sockaddr_eq(const struct sockaddr *sa1, const struct sockaddr *sa2,
00449                      int include_port)
00450 {
00451        if (sa1->sa_family != sa2->sa_family)
00452               return 0;
00453        if (sa1->sa_family == AF_INET) {
00454               const struct sockaddr_in *sin1, *sin2;
00455               sin1 = (const struct sockaddr_in *)sa1;
00456               sin2 = (const struct sockaddr_in *)sa2;
00457               if (sin1->sin_addr.s_addr != sin2->sin_addr.s_addr)
00458                      return 0;
00459               else if (include_port && sin1->sin_port != sin2->sin_port)
00460                      return 0;
00461               else
00462                      return 1;
00463        }
00464 #ifdef AF_INET6
00465        if (sa1->sa_family == AF_INET6) {
00466               const struct sockaddr_in6 *sin1, *sin2;
00467               sin1 = (const struct sockaddr_in6 *)sa1;
00468               sin2 = (const struct sockaddr_in6 *)sa2;
00469               if (tor_memneq(sin1->sin6_addr.s6_addr, sin2->sin6_addr.s6_addr, 16))
00470                      return 0;
00471               else if (include_port && sin1->sin6_port != sin2->sin6_port)
00472                      return 0;
00473               else
00474                      return 1;
00475        }
00476 #endif
00477        return 1;
00478 }
00479 
00480 #define add_timeout_event(s, to)                        \
00481        (event_add(&(s)->timeout_event, (to)))
00482 #define del_timeout_event(s)                                   \
00483        (event_del(&(s)->timeout_event))
00484 
00485 /* This walks the list of inflight requests to find the */
00486 /* one with a matching transaction id. Returns NULL on */
00487 /* failure */
00488 static struct evdns_request *
00489 request_find_from_trans_id(u16 trans_id) {
00490        struct evdns_request *req = req_head, *const started_at = req_head;
00491 
00492        if (req) {
00493               do {
00494                      if (req->trans_id == trans_id) return req;
00495                      req = req->next;
00496               } while (req != started_at);
00497        }
00498 
00499        return NULL;
00500 }
00501 
00502 /* a libevent callback function which is called when a nameserver */
00503 /* has gone down and we want to test if it has came back to life yet */
00504 static void
00505 nameserver_prod_callback(int fd, short events, void *arg) {
00506        struct nameserver *const ns = (struct nameserver *) arg;
00507        (void)fd;
00508        (void)events;
00509 
00510        nameserver_send_probe(ns);
00511 }
00512 
00513 /* a libevent callback which is called when a nameserver probe (to see if */
00514 /* it has come back to life) times out. We increment the count of failed_times */
00515 /* and wait longer to send the next probe packet. */
00516 static void
00517 nameserver_probe_failed(struct nameserver *const ns) {
00518        const struct timeval * timeout;
00519        del_timeout_event(ns);
00520 
00521        if (ns->state == 1) {
00522               /* This can happen if the nameserver acts in a way which makes us mark */
00523               /* it as bad and then starts sending good replies. */
00524               return;
00525        }
00526 
00527        timeout =
00528               &global_nameserver_timeouts[MIN(ns->failed_times,
00529                                                                       global_nameserver_timeouts_length - 1)];
00530        ns->failed_times++;
00531 
00532        if (add_timeout_event(ns, (struct timeval *) timeout) < 0) {
00533               log(EVDNS_LOG_WARN,
00534                      "Error from libevent when adding timer event for %s",
00535                      debug_ntop((struct sockaddr *)&ns->address));
00536               /* ???? Do more? */
00537        }
00538 }
00539 
00540 /* called when a nameserver has been deemed to have failed. For example, too */
00541 /* many packets have timed out etc */
00542 static void
00543 nameserver_failed(struct nameserver *const ns, const char *msg) {
00544        struct evdns_request *req, *started_at;
00545        /* if this nameserver has already been marked as failed */
00546        /* then don't do anything */
00547        if (!ns->state) return;
00548 
00549        log(EVDNS_LOG_WARN, "Nameserver %s has failed: %s",
00550               debug_ntop((struct sockaddr *)&ns->address), msg);
00551        global_good_nameservers--;
00552        assert(global_good_nameservers >= 0);
00553        if (global_good_nameservers == 0) {
00554               log(EVDNS_LOG_WARN, "All nameservers have failed");
00555        }
00556 
00557        ns->state = 0;
00558        ns->failed_times = 1;
00559 
00560        if (add_timeout_event(ns, (struct timeval *) &global_nameserver_timeouts[0]) < 0) {
00561               log(EVDNS_LOG_WARN,
00562                      "Error from libevent when adding timer event for %s",
00563                      debug_ntop((struct sockaddr *)&ns->address));
00564               /* ???? Do more? */
00565        }
00566 
00567        /* walk the list of inflight requests to see if any can be reassigned to */
00568        /* a different server. Requests in the waiting queue don't have a */
00569        /* nameserver assigned yet */
00570 
00571        /* if we don't have *any* good nameservers then there's no point */
00572        /* trying to reassign requests to one */
00573        if (!global_good_nameservers) return;
00574 
00575        req = req_head;
00576        started_at = req_head;
00577        if (req) {
00578               do {
00579                      if (req->tx_count == 0 && req->ns == ns) {
00580                             /* still waiting to go out, can be moved */
00581                             /* to another server */
00582                             req->ns = nameserver_pick();
00583                      }
00584                      req = req->next;
00585               } while (req != started_at);
00586        }
00587 }
00588 
00589 static void
00590 nameserver_up(struct nameserver *const ns) {
00591        if (ns->state) return;
00592        log(EVDNS_LOG_WARN, "Nameserver %s is back up",
00593               debug_ntop((struct sockaddr *)&ns->address));
00594        del_timeout_event(ns);
00595        ns->state = 1;
00596        ns->failed_times = 0;
00597        ns->timedout = 0;
00598        global_good_nameservers++;
00599 }
00600 
00601 static void
00602 request_trans_id_set(struct evdns_request *const req, const u16 trans_id) {
00603        req->trans_id = trans_id;
00604        *((u16 *) req->request) = htons(trans_id);
00605 }
00606 
00607 /* Called to remove a request from a list and dealloc it. */
00608 /* head is a pointer to the head of the list it should be */
00609 /* removed from or NULL if the request isn't in a list. */
00610 static void
00611 request_finished(struct evdns_request *const req, struct evdns_request **head) {
00612        if (head) {
00613               if (req->next == req) {
00614                      /* only item in the list */
00615                      *head = NULL;
00616               } else {
00617                      req->next->prev = req->prev;
00618                      req->prev->next = req->next;
00619                      if (*head == req) *head = req->next;
00620               }
00621        }
00622 
00623        log(EVDNS_LOG_DEBUG, "Removing timeout for request %lx",
00624               (unsigned long) req);
00625        del_timeout_event(req);
00626 
00627        search_request_finished(req);
00628        global_requests_inflight--;
00629 
00630        if (!req->request_appended) {
00631               /* need to free the request data on it's own */
00632               mm_free(req->request);
00633        } else {
00634               /* the request data is appended onto the header */
00635               /* so everything gets mm_free()ed when we: */
00636        }
00637 
00638        CLEAR(req);
00639        _mm_free(req);
00640 
00641        evdns_requests_pump_waiting_queue();
00642 }
00643 
00644 /* This is called when a server returns a funny error code. */
00645 /* We try the request again with another server. */
00646 /* */
00647 /* return: */
00648 /* 0 ok */
00649 /* 1 failed/reissue is pointless */
00650 static int
00651 request_reissue(struct evdns_request *req) {
00652        const struct nameserver *const last_ns = req->ns;
00653        /* the last nameserver should have been marked as failing */
00654        /* by the caller of this function, therefore pick will try */
00655        /* not to return it */
00656        req->ns = nameserver_pick();
00657        if (req->ns == last_ns) {
00658               /* ... but pick did return it */
00659               /* not a lot of point in trying again with the */
00660               /* same server */
00661               return 1;
00662        }
00663 
00664        req->reissue_count++;
00665        req->tx_count = 0;
00666        req->transmit_me = 1;
00667 
00668        return 0;
00669 }
00670 
00671 /* this function looks for space on the inflight queue and promotes */
00672 /* requests from the waiting queue if it can. */
00673 static void
00674 evdns_requests_pump_waiting_queue(void) {
00675        while (global_requests_inflight < global_max_requests_inflight &&
00676               global_requests_waiting) {
00677               struct evdns_request *req;
00678               /* move a request from the waiting queue to the inflight queue */
00679               assert(req_waiting_head);
00680               if (req_waiting_head->next == req_waiting_head) {
00681                      /* only one item in the queue */
00682                      req = req_waiting_head;
00683                      req_waiting_head = NULL;
00684               } else {
00685                      req = req_waiting_head;
00686                      req->next->prev = req->prev;
00687                      req->prev->next = req->next;
00688                      req_waiting_head = req->next;
00689               }
00690 
00691               global_requests_waiting--;
00692               global_requests_inflight++;
00693 
00694               req->ns = nameserver_pick();
00695               request_trans_id_set(req, transaction_id_pick());
00696 
00697               evdns_request_insert(req, &req_head);
00698               evdns_request_transmit(req);
00699               evdns_transmit();
00700        }
00701 }
00702 
00703 static void
00704 reply_callback(struct evdns_request *const req, u32 ttl, u32 err, struct reply *reply) {
00705        switch (req->request_type) {
00706        case TYPE_A:
00707               if (reply)
00708                      req->user_callback(DNS_ERR_NONE, DNS_IPv4_A,
00709                                                     reply->data.a.addrcount, ttl,
00710                                                     reply->data.a.addresses,
00711                                                     req->user_pointer);
00712               else
00713                      req->user_callback(err, 0, 0, 0, NULL, req->user_pointer);
00714               return;
00715        case TYPE_PTR:
00716               if (reply) {
00717                      char *name = reply->data.ptr.name;
00718                      req->user_callback(DNS_ERR_NONE, DNS_PTR, 1, ttl,
00719                                                     &name, req->user_pointer);
00720               } else {
00721                      req->user_callback(err, 0, 0, 0, NULL,
00722                                                     req->user_pointer);
00723               }
00724               return;
00725        case TYPE_AAAA:
00726               if (reply)
00727                      req->user_callback(DNS_ERR_NONE, DNS_IPv6_AAAA,
00728                                                     reply->data.aaaa.addrcount, ttl,
00729                                                     reply->data.aaaa.addresses,
00730                                                     req->user_pointer);
00731               else
00732                      req->user_callback(err, 0, 0, 0, NULL, req->user_pointer);
00733               return;
00734        }
00735        assert(0);
00736 }
00737 
00738 /* this processes a parsed reply packet */
00739 static void
00740 reply_handle(struct evdns_request *const req, u16 flags, u32 ttl, struct reply *reply) {
00741        int error;
00742        static const int error_codes[] = {DNS_ERR_FORMAT, DNS_ERR_SERVERFAILED, DNS_ERR_NOTEXIST, DNS_ERR_NOTIMPL, DNS_ERR_REFUSED};
00743 
00744        if (flags & 0x020f || !reply || !reply->have_answer) {
00745               /* there was an error */
00746               if (flags & 0x0200) {
00747                      error = DNS_ERR_TRUNCATED;
00748               } else {
00749                      u16 error_code = (flags & 0x000f) - 1;
00750                      if (error_code > 4) {
00751                             error = DNS_ERR_UNKNOWN;
00752                      } else {
00753                             error = error_codes[error_code];
00754                      }
00755               }
00756 
00757               switch(error) {
00758               case DNS_ERR_NOTIMPL:
00759               case DNS_ERR_REFUSED:
00760                      /* we regard these errors as marking a bad nameserver */
00761                      if (req->reissue_count < global_max_reissues) {
00762                             char msg[64];
00763                             snprintf(msg, sizeof(msg), "Bad response %d (%s)",
00764                                            error, evdns_err_to_string(error));
00765                             nameserver_failed(req->ns, msg);
00766                             if (!request_reissue(req)) return;
00767                      }
00768                      break;
00769               case DNS_ERR_SERVERFAILED:
00770                      /* rcode 2 (servfailed) sometimes means "we are broken" and
00771                       * sometimes (with some binds) means "that request was very
00772                       * confusing."  Treat this as a timeout, not a failure.
00773                       */
00774                      /*XXXX refactor the parts of */
00775                      log(EVDNS_LOG_DEBUG, "Got a SERVERFAILED from nameserver %s; "
00776                             "will allow the request to time out.",
00777                             debug_ntop((struct sockaddr *)&req->ns->address));
00778                      break;
00779               default:
00780                      /* we got a good reply from the nameserver */
00781                      nameserver_up(req->ns);
00782               }
00783 
00784               if (req->search_state && req->request_type != TYPE_PTR) {
00785                      /* if we have a list of domains to search in, try the next one */
00786                      if (!search_try_next(req)) {
00787                             /* a new request was issued so this request is finished and */
00788                             /* the user callback will be made when that request (or a */
00789                             /* child of it) finishes. */
00790                             request_finished(req, &req_head);
00791                             return;
00792                      }
00793               }
00794 
00795               /* all else failed. Pass the failure up */
00796               reply_callback(req, 0, error, NULL);
00797               request_finished(req, &req_head);
00798        } else {
00799               /* all ok, tell the user */
00800               reply_callback(req, ttl, 0, reply);
00801               nameserver_up(req->ns);
00802               request_finished(req, &req_head);
00803        }
00804 }
00805 
00806 static INLINE int
00807 name_parse(u8 *packet, int length, int *idx, char *name_out, size_t name_out_len) {
00808        int name_end = -1;
00809        int j = *idx;
00810        int ptr_count = 0;
00811 #define GET32(x) do { if (j + 4 > length) goto err; memcpy(&_t32, packet + j, 4); j += 4; x = ntohl(_t32); } while(0)
00812 #define GET16(x) do { if (j + 2 > length) goto err; memcpy(&_t, packet + j, 2); j += 2; x = ntohs(_t); } while(0)
00813 #define GET8(x) do { if (j >= length) goto err; x = packet[j++]; } while(0)
00814 
00815        char *cp = name_out;
00816        const char *const end = name_out + name_out_len;
00817 
00818        /* Normally, names are a series of length prefixed strings terminated */
00819        /* with a length of 0 (the lengths are u8's < 63). */
00820        /* However, the length can start with a pair of 1 bits and that */
00821        /* means that the next 14 bits are a pointer within the current */
00822        /* packet. */
00823 
00824        for(;;) {
00825               u8 label_len;
00826               if (j >= length) return -1;
00827               GET8(label_len);
00828               if (!label_len) break;
00829               if (label_len & 0xc0) {
00830                      u8 ptr_low;
00831                      GET8(ptr_low);
00832                      if (name_end < 0) name_end = j;
00833                      j = (((int)label_len & 0x3f) << 8) + ptr_low;
00834                      /* Make sure that the target offset is in-bounds. */
00835                      if (j < 0 || j >= length) return -1;
00836                      /* If we've jumped more times than there are characters in the
00837                       * message, we must have a loop. */
00838                      if (++ptr_count > length) return -1;
00839                      continue;
00840               }
00841               if (label_len > 63) return -1;
00842               if (cp != name_out) {
00843                      if (cp + 1 >= end) return -1;
00844                      *cp++ = '.';
00845               }
00846               if (cp + label_len >= end) return -1;
00847               memcpy(cp, packet + j, label_len);
00848               cp += label_len;
00849               j += label_len;
00850        }
00851        if (cp >= end) return -1;
00852        *cp = '\0';
00853        if (name_end < 0)
00854               *idx = j;
00855        else
00856               *idx = name_end;
00857        return 0;
00858  err:
00859        return -1;
00860 }
00861 
00862 /* parses a raw reply from a nameserver. */
00863 static int
00864 reply_parse(u8 *packet, int length) {
00865        int j = 0;    /* index into packet */
00866        int k;
00867        u16 _t;        /* used by the macros */
00868        u32 _t32;  /* used by the macros */
00869        char tmp_name[256], cmp_name[256]; /* used by the macros */
00870 
00871        u16 trans_id, questions, answers, authority, additional, datalength;
00872        u16 flags = 0;
00873        u32 ttl, ttl_r = 0xffffffff;
00874        struct reply reply;
00875        struct evdns_request *req = NULL;
00876        unsigned int i;
00877        int name_matches = 0;
00878 
00879        GET16(trans_id);
00880        GET16(flags);
00881        GET16(questions);
00882        GET16(answers);
00883        GET16(authority);
00884        GET16(additional);
00885        (void) authority; /* suppress "unused variable" warnings. */
00886        (void) additional; /* suppress "unused variable" warnings. */
00887 
00888        req = request_find_from_trans_id(trans_id);
00889        /* if no request, can't do anything. */
00890        if (!req) return -1;
00891 
00892        memset(&reply, 0, sizeof(reply));
00893 
00894        /* If it's not an answer, it doesn't go with any of our requests. */
00895        if (!(flags & 0x8000)) return -1;  /* must be an answer */
00896        if (flags & 0x020f) {
00897               /* there was an error */
00898               goto err;
00899        }
00900        /* if (!answers) return; */  /* must have an answer of some form */
00901 
00902        /* This macro skips a name in the DNS reply. */
00903 #define GET_NAME \
00904        do { tmp_name[0] = '\0';                         \
00905               if (name_parse(packet, length, &j, tmp_name, sizeof(tmp_name))<0)\
00906                      goto err;                          \
00907        } while(0)
00908 #define TEST_NAME \
00909        do { tmp_name[0] = '\0';                         \
00910               cmp_name[0] = '\0';                       \
00911               k = j;                                    \
00912               if (name_parse(packet, length, &j, tmp_name, sizeof(tmp_name))<0)\
00913                      goto err;                                 \
00914               if (name_parse(req->request, req->request_len, &k, cmp_name, sizeof(cmp_name))<0)   \
00915                      goto err;                          \
00916               if (global_randomize_case) {                                                 \
00917                      if (strcmp(tmp_name, cmp_name) == 0)                           \
00918                             name_matches = 1; /* we ignore mismatching names */     \
00919               } else {                                                                                          \
00920                      if (strcasecmp(tmp_name, cmp_name) == 0)                       \
00921                             name_matches = 1;                                                            \
00922               }                                                                                                        \
00923        } while(0)
00924 
00925        reply.type = req->request_type;
00926 
00927        /* skip over each question in the reply */
00928        for (i = 0; i < questions; ++i) {
00929               /* the question looks like
00930                * <label:name><u16:type><u16:class>
00931                */
00932               TEST_NAME;
00933               j += 4;
00934               if (j >= length) goto err;
00935        }
00936 
00937        if (!name_matches)
00938               goto err;
00939 
00940        /* now we have the answer section which looks like
00941         * <label:name><u16:type><u16:class><u32:ttl><u16:len><data...>
00942         */
00943 
00944        for (i = 0; i < answers; ++i) {
00945               u16 type, class;
00946 
00947               GET_NAME;
00948               GET16(type);
00949               GET16(class);
00950               GET32(ttl);
00951               GET16(datalength);
00952 
00953               if (type == TYPE_A && class == CLASS_INET) {
00954                      int addrcount, addrtocopy;
00955                      if (req->request_type != TYPE_A) {
00956                             j += datalength; continue;
00957                      }
00958                      if ((datalength & 3) != 0) /* not an even number of As. */
00959                             goto err;
00960                      addrcount = datalength >> 2;
00961                      addrtocopy = MIN(MAX_ADDRS - reply.data.a.addrcount, (unsigned)addrcount);
00962 
00963                      ttl_r = MIN(ttl_r, ttl);
00964                      /* we only bother with the first four addresses. */
00965                      if (j + 4*addrtocopy > length) goto err;
00966                      memcpy(&reply.data.a.addresses[reply.data.a.addrcount],
00967                                packet + j, 4*addrtocopy);
00968                      reply.data.a.addrcount += addrtocopy;
00969                      reply.have_answer = 1;
00970                      if (reply.data.a.addrcount == MAX_ADDRS) break;
00971                      j += 4*addrtocopy;
00972               } else if (type == TYPE_PTR && class == CLASS_INET) {
00973                      if (req->request_type != TYPE_PTR) {
00974                             j += datalength; continue;
00975                      }
00976                      GET_NAME;
00977                      strlcpy(reply.data.ptr.name, tmp_name,
00978                                    sizeof(reply.data.ptr.name));
00979                      ttl_r = MIN(ttl_r, ttl);
00980                      reply.have_answer = 1;
00981                      break;
00982               } else if (type == TYPE_AAAA && class == CLASS_INET) {
00983                      int addrcount, addrtocopy;
00984                      if (req->request_type != TYPE_AAAA) {
00985                             j += datalength; continue;
00986                      }
00987                      if ((datalength & 15) != 0) /* not an even number of AAAAs. */
00988                             goto err;
00989                      addrcount = datalength >> 4;  /* each address is 16 bytes long */
00990                      addrtocopy = MIN(MAX_ADDRS - reply.data.aaaa.addrcount, (unsigned)addrcount);
00991                      ttl_r = MIN(ttl_r, ttl);
00992 
00993                      /* we only bother with the first four addresses. */
00994                      if (j + 16*addrtocopy > length) goto err;
00995                      memcpy(&reply.data.aaaa.addresses[reply.data.aaaa.addrcount],
00996                                packet + j, 16*addrtocopy);
00997                      reply.data.aaaa.addrcount += addrtocopy;
00998                      reply.have_answer = 1;
00999                      if (reply.data.aaaa.addrcount == MAX_ADDRS) break;
01000                      j += 16*addrtocopy;
01001               } else {
01002                      /* skip over any other type of resource */
01003                      j += datalength;
01004               }
01005        }
01006 
01007        reply_handle(req, flags, ttl_r, &reply);
01008        return 0;
01009  err:
01010        if (req)
01011               reply_handle(req, flags, 0, NULL);
01012        return -1;
01013 }
01014 
01015 /* Parse a raw request (packet,length) sent to a nameserver port (port) from */
01016 /* a DNS client (addr,addrlen), and if it's well-formed, call the corresponding */
01017 /* callback. */
01018 static int
01019 request_parse(u8 *packet, ssize_t length, struct evdns_server_port *port, struct sockaddr *addr, socklen_t addrlen)
01020 {
01021        int j = 0;    /* index into packet */
01022        u16 _t;        /* used by the macros */
01023        char tmp_name[256]; /* used by the macros */
01024 
01025        int i;
01026        u16 trans_id, flags, questions, answers, authority, additional;
01027        struct server_request *server_req = NULL;
01028 
01029        /* Get the header fields */
01030        GET16(trans_id);
01031        GET16(flags);
01032        GET16(questions);
01033        GET16(answers);
01034        GET16(authority);
01035        GET16(additional);
01036        (void)additional;
01037        (void)authority;
01038        (void)answers;
01039 
01040        if (flags & 0x8000) return -1; /* Must not be an answer. */
01041        flags &= 0x0110; /* Only RD and CD get preserved. */
01042 
01043     if (length > INT_MAX)
01044         return -1;
01045 
01046        server_req = mm_malloc(sizeof(struct server_request));
01047        if (server_req == NULL) return -1;
01048        memset(server_req, 0, sizeof(struct server_request));
01049 
01050        server_req->trans_id = trans_id;
01051        memcpy(&server_req->addr, addr, addrlen);
01052        server_req->addrlen = addrlen;
01053 
01054        server_req->base.flags = flags;
01055        server_req->base.nquestions = 0;
01056        server_req->base.questions = mm_malloc(sizeof(struct evdns_server_question *) * questions);
01057        if (server_req->base.questions == NULL)
01058               goto err;
01059 
01060        for (i = 0; i < questions; ++i) {
01061               u16 type, class;
01062               struct evdns_server_question *q;
01063               size_t namelen;
01064               if (name_parse(packet, (int)length, &j, tmp_name, sizeof(tmp_name))<0)
01065                      goto err;
01066               GET16(type);
01067               GET16(class);
01068               namelen = strlen(tmp_name);
01069               q = mm_malloc(sizeof(struct evdns_server_question) + namelen);
01070               if (!q)
01071                      goto err;
01072               q->type = type;
01073               q->dns_question_class = class;
01074               memcpy(q->name, tmp_name, namelen+1);
01075               server_req->base.questions[server_req->base.nquestions++] = q;
01076        }
01077 
01078        /* Ignore answers, authority, and additional. */
01079 
01080        server_req->port = port;
01081        port->refcnt++;
01082 
01083        /* Only standard queries are supported. */
01084        if (flags & 0x7800) {
01085               evdns_server_request_respond(&(server_req->base), DNS_ERR_NOTIMPL);
01086               return -1;
01087        }
01088 
01089        port->user_callback(&(server_req->base), port->user_data);
01090 
01091        return 0;
01092 err:
01093        if (server_req) {
01094               if (server_req->base.questions) {
01095                      for (i = 0; i < server_req->base.nquestions; ++i)
01096                             mm_free(server_req->base.questions[i]);
01097                      mm_free(server_req->base.questions);
01098               }
01099               CLEAR(server_req);
01100               mm_free(server_req);
01101        }
01102        return -1;
01103 
01104 #undef SKIP_NAME
01105 #undef GET32
01106 #undef GET16
01107 #undef GET8
01108 }
01109 
01110 static uint16_t
01111 default_transaction_id_fn(void)
01112 {
01113        u16 trans_id;
01114 #ifdef DNS_USE_CPU_CLOCK_FOR_ID
01115        struct timespec ts;
01116 #ifdef CLOCK_MONOTONIC
01117        if (clock_gettime(CLOCK_MONOTONIC, &ts) == -1)
01118 #else
01119        if (clock_gettime(CLOCK_REALTIME, &ts) == -1)
01120 #endif
01121        event_err(1, "clock_gettime");
01122        trans_id = ts.tv_nsec & 0xffff;
01123 #endif
01124 
01125 #ifdef DNS_USE_GETTIMEOFDAY_FOR_ID
01126        struct timeval tv;
01127        gettimeofday(&tv, NULL);
01128        trans_id = tv.tv_usec & 0xffff;
01129 #endif
01130 
01131 #ifdef DNS_USE_OPENSSL_FOR_ID
01132        if (RAND_pseudo_bytes((u8 *) &trans_id, 2) == -1) {
01133               /* in the case that the RAND call fails we back */
01134               /* down to using gettimeofday. */
01135               /*
01136                 struct timeval tv;
01137                 gettimeofday(&tv, NULL);
01138                 trans_id = tv.tv_usec & 0xffff;
01139               */
01140               abort();
01141        }
01142 #endif
01143        return (unsigned short) trans_id;
01144 }
01145 
01146 static uint16_t (*trans_id_function)(void) = default_transaction_id_fn;
01147 
01148 static void
01149 default_random_bytes_fn(char *buf, size_t n)
01150 {
01151        unsigned i;
01152        for (i = 0; i < n; i += 2) {
01153               u16 tid = trans_id_function();
01154               buf[i] = (tid >> 8) & 0xff;
01155               if (i+1<n)
01156                      buf[i+1] = tid & 0xff;
01157        }
01158 }
01159 
01160 static void (*rand_bytes_function)(char *buf, size_t n) =
01161        default_random_bytes_fn;
01162 
01163 static u16
01164 trans_id_from_random_bytes_fn(void)
01165 {
01166        u16 tid;
01167        rand_bytes_function((char*) &tid, sizeof(tid));
01168        return tid;
01169 }
01170 
01171 void
01172 evdns_set_transaction_id_fn(uint16_t (*fn)(void))
01173 {
01174        if (fn)
01175               trans_id_function = fn;
01176        else
01177               trans_id_function = default_transaction_id_fn;
01178        rand_bytes_function = default_random_bytes_fn;
01179 }
01180 
01181 void
01182 evdns_set_random_bytes_fn(void (*fn)(char *, size_t))
01183 {
01184        rand_bytes_function = fn;
01185        trans_id_function = trans_id_from_random_bytes_fn;
01186 }
01187 
01188 /* Try to choose a strong transaction id which isn't already in flight */
01189 static u16
01190 transaction_id_pick(void) {
01191        for (;;) {
01192               const struct evdns_request *req = req_head, *started_at;
01193               u16 trans_id = trans_id_function();
01194 
01195               if (trans_id == 0xffff) continue;
01196               /* now check to see if that id is already inflight */
01197               req = started_at = req_head;
01198               if (req) {
01199                      do {
01200                             if (req->trans_id == trans_id) break;
01201                             req = req->next;
01202                      } while (req != started_at);
01203               }
01204               /* we didn't find it, so this is a good id */
01205               if (req == started_at) return trans_id;
01206        }
01207 }
01208 
01209 /* choose a namesever to use. This function will try to ignore */
01210 /* nameservers which we think are down and load balance across the rest */
01211 /* by updating the server_head global each time. */
01212 static struct nameserver *
01213 nameserver_pick(void) {
01214        struct nameserver *started_at = server_head, *picked;
01215        if (!server_head) return NULL;
01216 
01217        /* if we don't have any good nameservers then there's no */
01218        /* point in trying to find one. */
01219        if (!global_good_nameservers) {
01220               server_head = server_head->next;
01221               return server_head;
01222        }
01223 
01224        /* remember that nameservers are in a circular list */
01225        for (;;) {
01226               if (server_head->state) {
01227                      /* we think this server is currently good */
01228                      picked = server_head;
01229                      server_head = server_head->next;
01230                      return picked;
01231               }
01232 
01233               server_head = server_head->next;
01234               if (server_head == started_at) {
01235                      /* all the nameservers seem to be down */
01236                      /* so we just return this one and hope for the */
01237                      /* best */
01238                      assert(global_good_nameservers == 0);
01239                      picked = server_head;
01240                      server_head = server_head->next;
01241                      return picked;
01242               }
01243        }
01244 }
01245 
01246 /* this is called when a namesever socket is ready for reading */
01247 static void
01248 nameserver_read(struct nameserver *ns) {
01249        struct sockaddr_storage ss;
01250        struct sockaddr *sa = (struct sockaddr *) &ss;
01251        socklen_t addrlen = sizeof(ss);
01252        u8 packet[1500];
01253 
01254        for (;;) {
01255               const int r =
01256             (int)recvfrom(ns->socket, (void*)packet,
01257                                             (socklen_t)sizeof(packet), 0,
01258                                             sa, &addrlen);
01259               if (r < 0) {
01260                      int err = last_error(ns->socket);
01261                      if (error_is_eagain(err)) return;
01262                      nameserver_failed(ns, tor_socket_strerror(err));
01263                      return;
01264               }
01265               /* XXX Match port too? */
01266               if (!sockaddr_eq(sa, (struct sockaddr*)&ns->address, 0)) {
01267                      log(EVDNS_LOG_WARN,
01268                             "Address mismatch on received DNS packet.  Address was %s",
01269                             debug_ntop(sa));
01270                      return;
01271               }
01272               ns->timedout = 0;
01273               reply_parse(packet, r);
01274        }
01275 }
01276 
01277 /* Read a packet from a DNS client on a server port s, parse it, and */
01278 /* act accordingly. */
01279 static void
01280 server_port_read(struct evdns_server_port *s) {
01281        u8 packet[1500];
01282        struct sockaddr_storage addr;
01283        socklen_t addrlen;
01284        ssize_t r;
01285 
01286        for (;;) {
01287               addrlen = (socklen_t)sizeof(struct sockaddr_storage);
01288               r = recvfrom(s->socket, (void*)packet, sizeof(packet), 0,
01289                                     (struct sockaddr*) &addr, &addrlen);
01290               if (r < 0) {
01291                      int err = last_error(s->socket);
01292                      if (error_is_eagain(err)) return;
01293                      log(EVDNS_LOG_WARN, "Error %s (%d) while reading request.",
01294                             tor_socket_strerror(err), err);
01295                      return;
01296               }
01297               request_parse(packet, r, s, (struct sockaddr*) &addr, addrlen);
01298        }
01299 }
01300 
01301 /* Try to write all pending replies on a given DNS server port. */
01302 static void
01303 server_port_flush(struct evdns_server_port *port)
01304 {
01305        struct server_request *req = port->pending_replies;
01306        while (req) {
01307               ssize_t r = sendto(port->socket, req->response, req->response_len, 0,
01308                        (struct sockaddr*) &req->addr, (socklen_t)req->addrlen);
01309               if (r < 0) {
01310                      int err = last_error(port->socket);
01311                      if (error_is_eagain(err))
01312                             return;
01313                      log(EVDNS_LOG_WARN, "Error %s (%d) while writing response to port; dropping", tor_socket_strerror(err), err);
01314               }
01315               if (server_request_free(req)) {
01316                      /* we released the last reference to req->port. */
01317                      return;
01318               } else {
01319                      assert(port->pending_replies != req);
01320                      req = port->pending_replies;
01321               }
01322        }
01323 
01324        /* We have no more pending requests; stop listening for 'writeable' events. */
01325        (void) event_del(&port->event);
01326        CLEAR(&port->event);
01327        event_set(&port->event, port->socket, EV_READ | EV_PERSIST,
01328                        server_port_ready_callback, port);
01329        if (event_add(&port->event, NULL) < 0) {
01330               log(EVDNS_LOG_WARN, "Error from libevent when adding event for DNS server.");
01331               /* ???? Do more? */
01332        }
01333 }
01334 
01335 /* set if we are waiting for the ability to write to this server. */
01336 /* if waiting is true then we ask libevent for EV_WRITE events, otherwise */
01337 /* we stop these events. */
01338 static void
01339 nameserver_write_waiting(struct nameserver *ns, char waiting) {
01340        if (ns->write_waiting == waiting) return;
01341 
01342        ns->write_waiting = waiting;
01343        (void) event_del(&ns->event);
01344        CLEAR(&ns->event);
01345        event_set(&ns->event, ns->socket, EV_READ | (waiting ? EV_WRITE : 0) | EV_PERSIST,
01346                        nameserver_ready_callback, ns);
01347        if (event_add(&ns->event, NULL) < 0) {
01348               log(EVDNS_LOG_WARN, "Error from libevent when adding event for %s",
01349                      debug_ntop((struct sockaddr *)&ns->address));
01350               /* ???? Do more? */
01351        }
01352 }
01353 
01354 /* a callback function. Called by libevent when the kernel says that */
01355 /* a nameserver socket is ready for writing or reading */
01356 static void
01357 nameserver_ready_callback(int fd, short events, void *arg) {
01358        struct nameserver *ns = (struct nameserver *) arg;
01359        (void)fd;
01360 
01361        if (events & EV_WRITE) {
01362               ns->choked = 0;
01363               if (!evdns_transmit()) {
01364                      nameserver_write_waiting(ns, 0);
01365               }
01366        }
01367        if (events & EV_READ) {
01368               nameserver_read(ns);
01369        }
01370 }
01371 
01372 /* a callback function. Called by libevent when the kernel says that */
01373 /* a server socket is ready for writing or reading. */
01374 static void
01375 server_port_ready_callback(int fd, short events, void *arg) {
01376        struct evdns_server_port *port = (struct evdns_server_port *) arg;
01377        (void) fd;
01378 
01379        if (events & EV_WRITE) {
01380               port->choked = 0;
01381               server_port_flush(port);
01382        }
01383        if (events & EV_READ) {
01384               server_port_read(port);
01385        }
01386 }
01387 
01388 /* This is an inefficient representation; only use it via the dnslabel_table_*
01389  * functions, so that is can be safely replaced with something smarter later. */
01390 #define MAX_LABELS 128
01391 /* Structures used to implement name compression */
01392 struct dnslabel_entry { char *v; off_t pos; };
01393 struct dnslabel_table {
01394        int n_labels; /* number of current entries */
01395        /* map from name to position in message */
01396        struct dnslabel_entry labels[MAX_LABELS];
01397 };
01398 
01399 /* Initialize dnslabel_table. */
01400 static void
01401 dnslabel_table_init(struct dnslabel_table *table)
01402 {
01403        table->n_labels = 0;
01404 }
01405 
01406 /* Free all storage held by table, but not the table itself. */
01407 static void
01408 dnslabel_clear(struct dnslabel_table *table)
01409 {
01410        int i;
01411        for (i = 0; i < table->n_labels; ++i)
01412               mm_free(table->labels[i].v);
01413        table->n_labels = 0;
01414 }
01415 
01416 /* return the position of the label in the current message, or -1 if the label */
01417 /* hasn't been used yet. */
01418 static int
01419 dnslabel_table_get_pos(const struct dnslabel_table *table, const char *label)
01420 {
01421        int i;
01422        for (i = 0; i < table->n_labels; ++i) {
01423               if (!strcmp(label, table->labels[i].v)) {
01424                      off_t pos = table->labels[i].pos;
01425             if (pos > 65535)
01426                 return -1;
01427             return (int)pos;
01428         }
01429        }
01430        return -1;
01431 }
01432 
01433 /* remember that we've used the label at position pos */
01434 static int
01435 dnslabel_table_add(struct dnslabel_table *table, const char *label, off_t pos)
01436 {
01437        char *v;
01438        int p;
01439        if (table->n_labels == MAX_LABELS)
01440               return (-1);
01441        v = mm_strdup(label);
01442        if (v == NULL)
01443               return (-1);
01444        p = table->n_labels++;
01445        table->labels[p].v = v;
01446        table->labels[p].pos = pos;
01447 
01448        return (0);
01449 }
01450 
01451 /* Converts a string to a length-prefixed set of DNS labels, starting */
01452 /* at buf[j]. name and buf must not overlap. name_len should be the length */
01453 /* of name.    table is optional, and is used for compression. */
01454 /* */
01455 /* Input: abc.def */
01456 /* Output: <3>abc<3>def<0> */
01457 /* */
01458 /* Returns the first index after the encoded name, or negative on error. */
01459 /* -1   label was > 63 bytes */
01460 /* -2   name too long to fit in buffer. */
01461 /* */
01462 static off_t
01463 dnsname_to_labels(u8 *const buf, size_t buf_len, off_t j,
01464                               const char *name, const size_t name_len,
01465                               struct dnslabel_table *table) {
01466        const char *end = name + name_len;
01467        int ref = 0;
01468        u16 _t;
01469 
01470 #define APPEND16(x) do {                                          \
01471               if (j + 2 > (off_t)buf_len)                         \
01472                      goto overflow;                                             \
01473               _t = htons(x);                                                    \
01474               memcpy(buf + j, &_t, 2);                            \
01475               j += 2;                                                                  \
01476        } while (0)
01477 #define APPEND32(x) do {                                          \
01478               if (j + 4 > (off_t)buf_len)                         \
01479                      goto overflow;                                             \
01480               _t32 = htonl(x);                                           \
01481               memcpy(buf + j, &_t32, 4);                          \
01482               j += 4;                                                                  \
01483        } while (0)
01484 
01485        if (name_len > 255) return -2;
01486 
01487        for (;;) {
01488               const char *const start = name;
01489               if (table && (ref = dnslabel_table_get_pos(table, name)) >= 0) {
01490                      APPEND16(ref | 0xc000);
01491                      return j;
01492               }
01493               name = strchr(name, '.');
01494               if (!name) {
01495                      const size_t label_len = end - start;
01496                      if (label_len > 63) return -1;
01497                      if ((size_t)(j+label_len+1) > buf_len) return -2;
01498                      if (table) dnslabel_table_add(table, start, j);
01499                      buf[j++] = (uint8_t)label_len;
01500 
01501                      memcpy(buf + j, start, label_len);
01502                      j += end - start;
01503                      break;
01504               } else {
01505                      /* append length of the label. */
01506                      const size_t label_len = name - start;
01507                      if (label_len > 63) return -1;
01508                      if ((size_t)(j+label_len+1) > buf_len) return -2;
01509                      if (table) dnslabel_table_add(table, start, j);
01510                      buf[j++] = (uint8_t)label_len;
01511 
01512                      memcpy(buf + j, start, name - start);
01513                      j += name - start;
01514                      /* hop over the '.' */
01515                      name++;
01516               }
01517        }
01518 
01519        /* the labels must be terminated by a 0. */
01520        /* It's possible that the name ended in a . */
01521        /* in which case the zero is already there */
01522        if (!j || buf[j-1]) buf[j++] = 0;
01523        return j;
01524  overflow:
01525        return (-2);
01526 }
01527 
01528 /* Finds the length of a dns request for a DNS name of the given */
01529 /* length. The actual request may be smaller than the value returned */
01530 /* here */
01531 static size_t
01532 evdns_request_len(const size_t name_len) {
01533        return 96 + /* length of the DNS standard header */
01534               name_len + 2 +
01535               4;     /* space for the resource type */
01536 }
01537 
01538 /* build a dns request packet into buf. buf should be at least as long */
01539 /* as evdns_request_len told you it should be. */
01540 /* */
01541 /* Returns the amount of space used. Negative on error. */
01542 static int
01543 evdns_request_data_build(const char *const name, const size_t name_len,
01544                                            const u16 trans_id, const u16 type, const u16 class,
01545                                            u8 *const buf, size_t buf_len) {
01546        off_t j = 0;  /* current offset into buf */
01547        u16 _t;        /* used by the macros */
01548 
01549        APPEND16(trans_id);
01550        APPEND16(0x0100);  /* standard query, recusion needed */
01551        APPEND16(1);  /* one question */
01552        APPEND16(0);  /* no answers */
01553        APPEND16(0);  /* no authority */
01554        APPEND16(0);  /* no additional */
01555 
01556        j = dnsname_to_labels(buf, buf_len, j, name, name_len, NULL);
01557        if (j < 0) {
01558               return (int)j;
01559        }
01560 
01561        APPEND16(type);
01562        APPEND16(class);
01563 
01564        return (int)j;
01565  overflow:
01566        return (-1);
01567 }
01568 
01569 /* exported function */
01570 struct evdns_server_port *
01571 evdns_add_server_port(tor_socket_t socket, int is_tcp, evdns_request_callback_fn_type cb, void *user_data)
01572 {
01573        struct evdns_server_port *port;
01574        if (!(port = mm_malloc(sizeof(struct evdns_server_port))))
01575               return NULL;
01576        memset(port, 0, sizeof(struct evdns_server_port));
01577 
01578        assert(!is_tcp); /* TCP sockets not yet implemented */
01579        port->socket = socket;
01580        port->refcnt = 1;
01581        port->choked = 0;
01582        port->closing = 0;
01583        port->user_callback = cb;
01584        port->user_data = user_data;
01585        port->pending_replies = NULL;
01586 
01587        event_set(&port->event, port->socket, EV_READ | EV_PERSIST,
01588                        server_port_ready_callback, port);
01589        if (event_add(&port->event, NULL)<0) {
01590               mm_free(port);
01591               return NULL;
01592        }
01593        return port;
01594 }
01595 
01596 /* exported function */
01597 void
01598 evdns_close_server_port(struct evdns_server_port *port)
01599 {
01600        port->closing = 1;
01601        if (--port->refcnt == 0)
01602               server_port_free(port);
01603 }
01604 
01605 /* exported function */
01606 int
01607 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)
01608 {
01609        struct server_request *req = TO_SERVER_REQUEST(_req);
01610        struct server_reply_item **itemp, *item;
01611        int *countp;
01612 
01613        if (req->response) /* have we already answered? */
01614               return (-1);
01615 
01616        switch (section) {
01617        case EVDNS_ANSWER_SECTION:
01618               itemp = &req->answer;
01619               countp = &req->n_answer;
01620               break;
01621        case EVDNS_AUTHORITY_SECTION:
01622               itemp = &req->authority;
01623               countp = &req->n_authority;
01624               break;
01625        case EVDNS_ADDITIONAL_SECTION:
01626               itemp = &req->additional;
01627               countp = &req->n_additional;
01628               break;
01629        default:
01630               return (-1);
01631        }
01632        while (*itemp) {
01633               itemp = &((*itemp)->next);
01634        }
01635        item = mm_malloc(sizeof(struct server_reply_item));
01636        if (!item)
01637               return -1;
01638        CLEAR(item);
01639        item->next = NULL;
01640        if (!(item->name = mm_strdup(name))) {
01641               CLEAR(item);
01642               mm_free(item);
01643               return -1;
01644        }
01645        item->type = type;
01646        item->class = class;
01647        item->ttl = ttl;
01648        item->is_name = is_name != 0;
01649        item->datalen = 0;
01650        item->data = NULL;
01651        if (data) {
01652               if (item->is_name) {
01653                      if (!(item->data = mm_strdup(data))) {
01654                             mm_free(item->name);
01655                             CLEAR(item);
01656                             mm_free(item);
01657                             return -1;
01658                      }
01659                      item->datalen = (u16)-1;
01660               } else {
01661                      if (!(item->data = mm_malloc(datalen))) {
01662                             mm_free(item->name);
01663                             CLEAR(item);
01664                             mm_free(item);
01665                             return -1;
01666                      }
01667                      item->datalen = datalen;
01668                      memcpy(item->data, data, datalen);
01669               }
01670        }
01671 
01672        *itemp = item;
01673        ++(*countp);
01674        return 0;
01675 }
01676 
01677 /* exported function */
01678 int
01679 evdns_server_request_add_a_reply(struct evdns_server_request *req, const char *name, int n, const void *addrs, int ttl)
01680 {
01681        return evdns_server_request_add_reply(
01682                 req, EVDNS_ANSWER_SECTION, name, TYPE_A, CLASS_INET,
01683                 ttl, n*4, 0, addrs);
01684 }
01685 
01686 /* exported function */
01687 int
01688 evdns_server_request_add_aaaa_reply(struct evdns_server_request *req, const char *name, int n, const void *addrs, int ttl)
01689 {
01690        return evdns_server_request_add_reply(
01691                 req, EVDNS_ANSWER_SECTION, name, TYPE_AAAA, CLASS_INET,
01692                 ttl, n*16, 0, addrs);
01693 }
01694 
01695 /* exported function */
01696 int
01697 evdns_server_request_add_ptr_reply(struct evdns_server_request *req, struct in_addr *in, const char *inaddr_name, const char *hostname, int ttl)
01698 {
01699        u32 a;
01700        char buf[32];
01701        assert(in || inaddr_name);
01702        assert(!(in && inaddr_name));
01703        if (in) {
01704               a = ntohl(in->s_addr);
01705               snprintf(buf, sizeof(buf), "%d.%d.%d.%d.in-addr.arpa",
01706                             (int)(u8)((a  )&0xff),
01707                             (int)(u8)((a>>8 )&0xff),
01708                             (int)(u8)((a>>16)&0xff),
01709                             (int)(u8)((a>>24)&0xff));
01710               inaddr_name = buf;
01711        }
01712        return evdns_server_request_add_reply(
01713                 req, EVDNS_ANSWER_SECTION, inaddr_name, TYPE_PTR, CLASS_INET,
01714                 ttl, -1, 1, hostname);
01715 }
01716 
01717 /* exported function */
01718 int
01719 evdns_server_request_add_cname_reply(struct evdns_server_request *req, const char *name, const char *cname, int ttl)
01720 {
01721        return evdns_server_request_add_reply(
01722                 req, EVDNS_ANSWER_SECTION, name, TYPE_CNAME, CLASS_INET,
01723                 ttl, -1, 1, cname);
01724 }
01725 
01726 
01727 static int
01728 evdns_server_request_format_response(struct server_request *req, int err)
01729 {
01730        unsigned char buf[1500];
01731        size_t buf_len = sizeof(buf);
01732        off_t j = 0, r;
01733        u16 _t;
01734        u32 _t32;
01735        int i;
01736        u16 flags;
01737        struct dnslabel_table table;
01738 
01739        if (err < 0 || err > 15) return -1;
01740 
01741        /* Set response bit and error code; copy OPCODE and RD fields from
01742         * question; copy RA and AA if set by caller. */
01743        flags = req->base.flags;
01744        flags |= (0x8000 | err);
01745 
01746        dnslabel_table_init(&table);
01747        APPEND16(req->trans_id);
01748        APPEND16(flags);
01749        APPEND16(req->base.nquestions);
01750        APPEND16(req->n_answer);
01751        APPEND16(req->n_authority);
01752        APPEND16(req->n_additional);
01753 
01754        /* Add questions. */
01755        for (i=0; i < req->base.nquestions; ++i) {
01756               const char *s = req->base.questions[i]->name;
01757               j = dnsname_to_labels(buf, buf_len, j, s, strlen(s), &table);
01758               if (j < 0) {
01759                      dnslabel_clear(&table);
01760                      return (int) j;
01761               }
01762               APPEND16(req->base.questions[i]->type);
01763               APPEND16(req->base.questions[i]->dns_question_class);
01764        }
01765 
01766        /* Add answer, authority, and additional sections. */
01767        for (i=0; i<3; ++i) {
01768               struct server_reply_item *item;
01769               if (i==0)
01770                      item = req->answer;
01771               else if (i==1)
01772                      item = req->authority;
01773               else
01774                      item = req->additional;
01775               while (item) {
01776                      r = dnsname_to_labels(buf, buf_len, j, item->name, strlen(item->name), &table);
01777                      if (r < 0)
01778                             goto overflow;
01779                      j = r;
01780 
01781                      APPEND16(item->type);
01782                      APPEND16(item->class);
01783                      APPEND32(item->ttl);
01784                      if (item->is_name) {
01785                             off_t len_idx = j, name_start;
01786                             j += 2;
01787                             name_start = j;
01788                             r = dnsname_to_labels(buf, buf_len, j, item->data, strlen(item->data), &table);
01789                             if (r < 0)
01790                                    goto overflow;
01791                             j = r;
01792                             _t = htons( (j-name_start) );
01793                             memcpy(buf+len_idx, &_t, 2);
01794                      } else {
01795                             APPEND16(item->datalen);
01796                             if (j+item->datalen > (off_t)buf_len)
01797                                    goto overflow;
01798                             memcpy(buf+j, item->data, item->datalen);
01799                             j += item->datalen;
01800                      }
01801                      item = item->next;
01802               }
01803        }
01804 
01805        if (j > 512) {
01806 overflow:
01807               j = 512;
01808               buf[2] |= 0x02; /* set the truncated bit. */
01809        }
01810 
01811        req->response_len = (size_t)j;
01812 
01813        if (!(req->response = mm_malloc(req->response_len))) {
01814               server_request_free_answers(req);
01815               dnslabel_clear(&table);
01816               return (-1);
01817        }
01818        memcpy(req->response, buf, req->response_len);
01819        server_request_free_answers(req);
01820        dnslabel_clear(&table);
01821        return (0);
01822 }
01823 
01824 /* exported function */
01825 int
01826 evdns_server_request_respond(struct evdns_server_request *_req, int err)
01827 {
01828        struct server_request *req = TO_SERVER_REQUEST(_req);
01829        struct evdns_server_port *port = req->port;
01830        ssize_t r;
01831        if (!req->response) {
01832               if ((r = evdns_server_request_format_response(req, err))<0)
01833                      return (int)r;
01834        }
01835 
01836        r = sendto(port->socket, req->response, req->response_len, 0,
01837                         (struct sockaddr*) &req->addr, req->addrlen);
01838        if (r<0) {
01839               int error = last_error(port->socket);
01840               if (! error_is_eagain(error))
01841                      return -1;
01842 
01843               if (port->pending_replies) {
01844                      req->prev_pending = port->pending_replies->prev_pending;
01845                      req->next_pending = port->pending_replies;
01846                      req->prev_pending->next_pending =
01847                             req->next_pending->prev_pending = req;
01848               } else {
01849                      req->prev_pending = req->next_pending = req;
01850                      port->pending_replies = req;
01851                      port->choked = 1;
01852 
01853                      (void) event_del(&port->event);
01854                      CLEAR(&port->event);
01855                      event_set(&port->event, port->socket, (port->closing?0:EV_READ) | EV_WRITE | EV_PERSIST, server_port_ready_callback, port);
01856 
01857                      if (event_add(&port->event, NULL) < 0) {
01858                             log(EVDNS_LOG_WARN, "Error from libevent when adding event for DNS server");
01859                      }
01860 
01861               }
01862 
01863               return 1;
01864        }
01865        if (server_request_free(req))
01866               return 0;
01867 
01868        if (port->pending_replies)
01869               server_port_flush(port);
01870 
01871        return 0;
01872 }
01873 
01874 /* Free all storage held by RRs in req. */
01875 static void
01876 server_request_free_answers(struct server_request *req)
01877 {
01878        struct server_reply_item *victim, *next, **list;
01879        int i;
01880        for (i = 0; i < 3; ++i) {
01881               if (i==0)
01882                      list = &req->answer;
01883               else if (i==1)
01884                      list = &req->authority;
01885               else
01886                      list = &req->additional;
01887 
01888               victim = *list;
01889               while (victim) {
01890                      next = victim->next;
01891                      mm_free(victim->name);
01892                      if (victim->data)
01893                             mm_free(victim->data);
01894                      mm_free(victim);
01895                      victim = next;
01896               }
01897               *list = NULL;
01898        }
01899 }
01900 
01901 /* Free all storage held by req, and remove links to it. */
01902 /* return true iff we just wound up freeing the server_port. */
01903 static int
01904 server_request_free(struct server_request *req)
01905 {
01906        int i, rc=1;
01907        if (req->base.questions) {
01908               for (i = 0; i < req->base.nquestions; ++i)
01909                      mm_free(req->base.questions[i]);
01910               mm_free(req->base.questions);
01911        }
01912 
01913        if (req->port) {
01914               if (req->port->pending_replies == req) {
01915                      if (req->next_pending && req->next_pending != req)
01916                             req->port->pending_replies = req->next_pending;
01917                      else
01918                             req->port->pending_replies = NULL;
01919               }
01920               rc = --req->port->refcnt;
01921        }
01922 
01923        if (req->response) {
01924               mm_free(req->response);
01925        }
01926 
01927        server_request_free_answers(req);
01928 
01929        if (req->next_pending && req->next_pending != req) {
01930               req->next_pending->prev_pending = req->prev_pending;
01931               req->prev_pending->next_pending = req->next_pending;
01932        }
01933 
01934        if (rc == 0) {
01935               server_port_free(req->port);
01936               CLEAR(req);
01937               mm_free(req);
01938               return (1);
01939        }
01940        CLEAR(req);
01941        mm_free(req);
01942        return (0);
01943 }
01944 
01945 /* Free all storage held by an evdns_server_port.  Only called when the
01946  * reference count is down to 0. */
01947 static void
01948 server_port_free(struct evdns_server_port *port)
01949 {
01950        assert(port);
01951        assert(!port->refcnt);
01952        assert(!port->pending_replies);
01953        if (port->socket > 0) {
01954               CLOSE_SOCKET(port->socket);
01955               port->socket = -1;
01956        }
01957        (void) event_del(&port->event);
01958        CLEAR(&port->event);
01959        CLEAR(port);
01960        mm_free(port);
01961 }
01962 
01963 /* exported function */
01964 int
01965 evdns_server_request_drop(struct evdns_server_request *_req)
01966 {
01967        struct server_request *req = TO_SERVER_REQUEST(_req);
01968        server_request_free(req);
01969        return 0;
01970 }
01971 
01972 /* exported function */
01973 int
01974 evdns_server_request_get_requesting_addr(struct evdns_server_request *_req, struct sockaddr *sa, int addr_len)
01975 {
01976        struct server_request *req = TO_SERVER_REQUEST(_req);
01977        if (addr_len < (int)req->addrlen)
01978               return -1;
01979        memcpy(sa, &(req->addr), req->addrlen);
01980        return req->addrlen;
01981 }
01982 
01983 #undef APPEND16
01984 #undef APPEND32
01985 
01986 /* this is a libevent callback function which is called when a request */
01987 /* has timed out. */
01988 static void
01989 evdns_request_timeout_callback(int fd, short events, void *arg) {
01990        struct evdns_request *const req = (struct evdns_request *) arg;
01991        (void) fd;
01992        (void) events;
01993 
01994        log(EVDNS_LOG_DEBUG, "Request %lx timed out", (unsigned long) arg);
01995 
01996        req->ns->timedout++;
01997        if (req->ns->timedout > global_max_nameserver_timeout) {
01998               req->ns->timedout = 0;
01999               nameserver_failed(req->ns, "request timed out.");
02000        }
02001 
02002        if (req->tx_count >= global_max_retransmits) {
02003               /* this request has failed */
02004               reply_callback(req, 0, DNS_ERR_TIMEOUT, NULL);
02005               request_finished(req, &req_head);
02006        } else {
02007               /* retransmit it */
02008               /* Stop waiting for the timeout.  No need to do this in
02009                * request_finished; that one already deletes the timeout event.
02010                * XXXX023 port this change to libevent. */
02011               del_timeout_event(req);
02012               evdns_request_transmit(req);
02013        }
02014 }
02015 
02016 /* try to send a request to a given server. */
02017 /* */
02018 /* return: */
02019 /* 0 ok */
02020 /* 1 temporary failure */
02021 /* 2 other failure */
02022 static int
02023 evdns_request_transmit_to(struct evdns_request *req, struct nameserver *server) {
02024        const ssize_t r = send(server->socket, (void*)req->request,
02025                          req->request_len, 0);
02026        if (r < 0) {
02027               int err = last_error(server->socket);
02028               if (error_is_eagain(err)) return 1;
02029               nameserver_failed(req->ns, tor_socket_strerror(err));
02030               return 2;
02031        } else if (r != (ssize_t)req->request_len) {
02032               return 1;  /* short write */
02033        } else {
02034               return 0;
02035        }
02036 }
02037 
02038 /* try to send a request, updating the fields of the request */
02039 /* as needed */
02040 /* */
02041 /* return: */
02042 /* 0 ok */
02043 /* 1 failed */
02044 static int
02045 evdns_request_transmit(struct evdns_request *req) {
02046        int retcode = 0, r;
02047 
02048        /* if we fail to send this packet then this flag marks it */
02049        /* for evdns_transmit */
02050        req->transmit_me = 1;
02051        if (req->trans_id == 0xffff) abort();
02052 
02053        if (req->ns->choked) {
02054               /* don't bother trying to write to a socket */
02055               /* which we have had EAGAIN from */
02056               return 1;
02057        }
02058 
02059        r = evdns_request_transmit_to(req, req->ns);
02060        switch (r) {
02061        case 1:
02062               /* temp failure */
02063               req->ns->choked = 1;
02064               nameserver_write_waiting(req->ns, 1);
02065               return 1;
02066        case 2:
02067               /* failed to transmit the request entirely. */
02068               retcode = 1;
02069               /* fall through: we'll set a timeout, which will time out,
02070                * and make us retransmit the request anyway. */
02071        default:
02072               /* transmitted; we need to check for timeout. */
02073               log(EVDNS_LOG_DEBUG,
02074                      "Setting timeout for request %lx", (unsigned long) req);
02075 
02076               if (add_timeout_event(req, &global_timeout) < 0) {
02077                      log(EVDNS_LOG_WARN,
02078                             "Error from libevent when adding timer for request %lx",
02079                             (unsigned long) req);
02080                      /* ???? Do more? */
02081               }
02082               req->tx_count++;
02083               req->transmit_me = 0;
02084               return retcode;
02085        }
02086 }
02087 
02088 static void
02089 nameserver_probe_callback(int result, char type, int count, int ttl, void *addresses, void *arg) {
02090        struct sockaddr *addr = arg;
02091        struct nameserver *server;
02092        (void) type;
02093        (void) count;
02094        (void) ttl;
02095        (void) addresses;
02096 
02097        for (server = server_head; server; server = server->next) {
02098               if (sockaddr_eq(addr, (struct sockaddr*) &server->address, 1)) {
02099                      if (result == DNS_ERR_NONE || result == DNS_ERR_NOTEXIST) {
02100                             /* this is a good reply */
02101                             nameserver_up(server);
02102                      } else {
02103                             nameserver_probe_failed(server);
02104                      }
02105               }
02106               if (server->next == server_head)
02107                      break;
02108        }
02109 
02110        mm_free(addr);
02111 }
02112 
02113 static void
02114 nameserver_send_probe(struct nameserver *const ns) {
02115        struct evdns_request *req;
02116        struct sockaddr_storage *addr;
02117        /* here we need to send a probe to a given nameserver */
02118        /* in the hope that it is up now. */
02119 
02120        /* We identify the nameserver by its address, in case it is removed before
02121         * our probe comes back. */
02122        addr = mm_malloc(sizeof(struct sockaddr_storage));
02123        memcpy(addr, &ns->address, sizeof(struct sockaddr_storage));
02124 
02125        log(EVDNS_LOG_DEBUG, "Sending probe to %s", debug_ntop((struct sockaddr *)&ns->address));
02126 
02127        req = request_new(TYPE_A, "www.google.com", DNS_QUERY_NO_SEARCH, nameserver_probe_callback, addr);
02128        if (!req) {
02129               mm_free(addr);
02130               return;
02131        }
02132        /* we force this into the inflight queue no matter what */
02133        request_trans_id_set(req, transaction_id_pick());
02134        req->ns = ns;
02135        request_submit(req);
02136 }
02137 
02138 /* returns: */
02139 /* 0 didn't try to transmit anything */
02140 /* 1 tried to transmit something */
02141 static int
02142 evdns_transmit(void) {
02143        char did_try_to_transmit = 0;
02144 
02145        if (req_head) {
02146               struct evdns_request *const started_at = req_head, *req = req_head;
02147               /* first transmit all the requests which are currently waiting */
02148               do {
02149                      if (req->transmit_me) {
02150                             did_try_to_transmit = 1;
02151                             evdns_request_transmit(req);
02152                      }
02153 
02154                      req = req->next;
02155               } while (req != started_at);
02156        }
02157 
02158        return did_try_to_transmit;
02159 }
02160 
02161 /* exported function */
02162 int
02163 evdns_count_nameservers(void)
02164 {
02165        const struct nameserver *server = server_head;
02166        int n = 0;
02167        if (!server)
02168               return 0;
02169        do {
02170               ++n;
02171               server = server->next;
02172        } while (server != server_head);
02173        return n;
02174 }
02175 
02176 /* exported function */
02177 int
02178 evdns_clear_nameservers_and_suspend(void)
02179 {
02180        struct nameserver *server = server_head, *started_at = server_head;
02181        struct evdns_request *req = req_head, *req_started_at = req_head;
02182 
02183        if (!server)
02184               return 0;
02185        while (1) {
02186               struct nameserver *next = server->next;
02187               (void) event_del(&server->event);
02188               CLEAR(&server->event);
02189               del_timeout_event(server);
02190               if (server->socket >= 0)
02191                      CLOSE_SOCKET(server->socket);
02192               CLEAR(server);
02193               mm_free(server);
02194               if (next == started_at)
02195                      break;
02196               server = next;
02197        }
02198        server_head = NULL;
02199        global_good_nameservers = 0;
02200 
02201        while (req) {
02202               struct evdns_request *next = req->next;
02203               req->tx_count = req->reissue_count = 0;
02204               req->ns = NULL;
02205               /* ???? What to do about searches? */
02206               del_timeout_event(req);
02207               req->trans_id = 0;
02208               req->transmit_me = 0;
02209 
02210               global_requests_waiting++;
02211               evdns_request_insert(req, &req_waiting_head);
02212               /* We want to insert these suspended elements at the front of
02213                * the waiting queue, since they were pending before any of
02214                * the waiting entries were added. This is a circular list,
02215                * so we can just shift the start back by one.*/
02216               req_waiting_head = req_waiting_head->prev;
02217 
02218               if (next == req_started_at)
02219                      break;
02220               req = next;
02221        }
02222        req_head = NULL;
02223        global_requests_inflight = 0;
02224 
02225        return 0;
02226 }
02227 
02228 static struct sockaddr_storage global_bind_address;
02229 static socklen_t global_bind_addrlen = 0;
02230 static int global_bind_addr_is_set = 0;
02231 void
02232 evdns_set_default_outgoing_bind_address(const struct sockaddr *addr,
02233                                                                       socklen_t addrlen)
02234 {
02235        memset(&global_bind_address, 0, sizeof(global_bind_address));
02236        if (addr) {
02237               assert(addrlen <= (socklen_t)sizeof(global_bind_address));
02238               memcpy(&global_bind_address, addr, addrlen);
02239               global_bind_addrlen = addrlen;
02240               global_bind_addr_is_set = 1;
02241        } else {
02242               global_bind_addr_is_set = 0;
02243        }
02244 }
02245 
02246 /* exported function */
02247 int
02248 evdns_resume(void)
02249 {
02250        evdns_requests_pump_waiting_queue();
02251        return 0;
02252 }
02253 
02254 static int
02255 sockaddr_is_loopback(const struct sockaddr *addr)
02256 {
02257        static const char LOOPBACK_S6[16] =
02258            "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\1";
02259        if (addr->sa_family == AF_INET) {
02260               struct sockaddr_in *sin = (struct sockaddr_in *)addr;
02261               return (ntohl(sin->sin_addr.s_addr) & 0xff000000) == 0x7f000000;
02262        } else if (addr->sa_family == AF_INET6) {
02263               struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)addr;
02264               return fast_memeq(sin6->sin6_addr.s6_addr, LOOPBACK_S6, 16);
02265        }
02266        return 0;
02267 }
02268 
02269 static int
02270 _evdns_nameserver_add_impl(const struct sockaddr *address,
02271                                              socklen_t addrlen) {
02272        /* first check to see if we already have this nameserver */
02273 
02274        const struct nameserver *server = server_head, *const started_at = server_head;
02275        struct nameserver *ns;
02276 
02277        int err = 0;
02278        if (server) {
02279               do {
02280                      if (sockaddr_eq(address, (struct sockaddr *)&server->address, 1)) {
02281                             log(EVDNS_LOG_DEBUG, "Duplicate nameserver.");
02282                             return 3;
02283                      }
02284                      server = server->next;
02285               } while (server != started_at);
02286        }
02287        if (addrlen > (int)sizeof(ns->address)) {
02288               log(EVDNS_LOG_DEBUG, "Addrlen %d too long.", (int)addrlen);
02289               return 2;
02290        }
02291 
02292        ns = (struct nameserver *) mm_malloc(sizeof(struct nameserver));
02293        if (!ns) return -1;
02294 
02295        memset(ns, 0, sizeof(struct nameserver));
02296 
02297        evtimer_set(&ns->timeout_event, nameserver_prod_callback, ns);
02298 
02299        ns->socket = tor_open_socket(address->sa_family, SOCK_DGRAM, 0);
02300        if (ns->socket < 0) { err = 1; goto out1; }
02301 #ifdef _WIN32
02302        {
02303               u_long nonblocking = 1;
02304               ioctlsocket(ns->socket, FIONBIO, &nonblocking);
02305        }
02306 #else
02307        fcntl(ns->socket, F_SETFL, O_NONBLOCK);
02308 #endif
02309 
02310        if (global_bind_addr_is_set &&
02311            !sockaddr_is_loopback((struct sockaddr*)&global_bind_address)) {
02312               if (bind(ns->socket, (struct sockaddr *)&global_bind_address,
02313                              global_bind_addrlen) < 0) {
02314                      log(EVDNS_LOG_DEBUG, "Couldn't bind to outgoing address.");
02315                      err = 2;
02316                      goto out2;
02317               }
02318        }
02319 
02320        if (connect(ns->socket, address, addrlen) != 0) {
02321               log(EVDNS_LOG_DEBUG, "Couldn't open socket to nameserver.");
02322               err = 2;
02323               goto out2;
02324        }
02325 
02326        memcpy(&ns->address, address, addrlen);
02327        ns->state = 1;
02328        event_set(&ns->event, ns->socket, EV_READ | EV_PERSIST, nameserver_ready_callback, ns);
02329        if (event_add(&ns->event, NULL) < 0) {
02330               log(EVDNS_LOG_DEBUG, "Couldn't add event for nameserver.");
02331               err = 2;
02332               goto out2;
02333        }
02334 
02335        log(EVDNS_LOG_DEBUG, "Added nameserver %s", debug_ntop(address));
02336 
02337        /* insert this nameserver into the list of them */
02338        if (!server_head) {
02339               ns->next = ns->prev = ns;
02340               server_head = ns;
02341        } else {
02342               ns->next = server_head->next;
02343               ns->prev = server_head;
02344               server_head->next = ns;
02345               if (server_head->prev == server_head) {
02346                      server_head->prev = ns;
02347               }
02348        }
02349 
02350        global_good_nameservers++;
02351 
02352        return 0;
02353 
02354 out2:
02355        CLOSE_SOCKET(ns->socket);
02356 out1:
02357        CLEAR(ns);
02358        mm_free(ns);
02359        log(EVDNS_LOG_WARN, "Unable to add nameserver %s: error %d", debug_ntop(address), err);
02360        return err;
02361 }
02362 
02363 /* exported function */
02364 int
02365 evdns_nameserver_add(uint32_t address) {
02366        struct sockaddr_in sin;
02367        memset(&sin, 0, sizeof(sin));
02368        sin.sin_family = AF_INET;
02369 #ifdef HAVE_STRUCT_SOCKADDR_IN_SIN_LEN
02370        sin.sin_len = sizeof(sin);
02371 #endif
02372        sin.sin_addr.s_addr = htonl(address);
02373        sin.sin_port = 53;
02374        return _evdns_nameserver_add_impl((struct sockaddr*) &sin, sizeof(sin));
02375 }
02376 
02377 /* exported function */
02378 int
02379 evdns_nameserver_ip_add(const char *ip_as_string) {
02380        int port;
02381        char buf[128];
02382        const char *cp, *addr_part, *port_part;
02383        int is_ipv6;
02384        /* recognized formats are:
02385         * [ipv6]:port
02386         * ipv6
02387         * [ipv6]
02388         * ipv4:port
02389         * ipv4
02390         */
02391 
02392        log(EVDNS_LOG_DEBUG, "Trying to add nameserver <%s>", ip_as_string);
02393 
02394        cp = strchr(ip_as_string, ':');
02395        if (*ip_as_string == '[') {
02396               size_t len;
02397               if (!(cp = strchr(ip_as_string, ']'))) {
02398                      log(EVDNS_LOG_DEBUG, "Nameserver missing closing ]");
02399                      return 4;
02400               }
02401               len = cp-(ip_as_string + 1);
02402               if (len > sizeof(buf)-1) {
02403                      log(EVDNS_LOG_DEBUG, "[Nameserver] does not fit in buffer.");
02404                      return 4;
02405               }
02406               memcpy(buf, ip_as_string+1, len);
02407               buf[len] = '\0';
02408               addr_part = buf;
02409               if (cp[1] == ':')
02410                      port_part = cp+2;
02411               else
02412                      port_part = NULL;
02413               is_ipv6 = 1;
02414        } else if (cp && strchr(cp+1, ':')) {
02415               is_ipv6 = 1;
02416               addr_part = ip_as_string;
02417               port_part = NULL;
02418        } else if (cp) {
02419               is_ipv6 = 0;
02420               if (cp - ip_as_string > (int)sizeof(buf)-1) {
02421                      log(EVDNS_LOG_DEBUG, "Nameserver does not fit in buffer.");
02422                      return 4;
02423               }
02424               memcpy(buf, ip_as_string, cp-ip_as_string);
02425               buf[cp-ip_as_string] = '\0';
02426               addr_part = buf;
02427               port_part = cp+1;
02428        } else {
02429               addr_part = ip_as_string;
02430               port_part = NULL;
02431               is_ipv6 = 0;
02432        }
02433 
02434        if (port_part == NULL) {
02435               port = 53;
02436        } else {
02437               port = strtoint(port_part);
02438               if (port <= 0 || port > 65535) {
02439                      log(EVDNS_LOG_DEBUG, "Nameserver port <%s> out of range",
02440                             port_part);
02441                      return 4;
02442               }
02443        }
02444 
02445        /* Tor-only.  needs a more general fix. */
02446        assert(addr_part);
02447        if (is_ipv6) {
02448               struct sockaddr_in6 sin6;
02449               memset(&sin6, 0, sizeof(sin6));
02450 #ifdef HAVE_STRUCT_SOCKADDR_IN6_SIN6_LEN
02451               sin6.sin6_len = sizeof(sin6);
02452 #endif
02453               sin6.sin6_family = AF_INET6;
02454               sin6.sin6_port = htons(port);
02455               if (1 != tor_inet_pton(AF_INET6, addr_part, &sin6.sin6_addr)) {
02456                      log(EVDNS_LOG_DEBUG, "inet_pton(%s) failed", addr_part);
02457                      return 4;
02458               }
02459               return _evdns_nameserver_add_impl((struct sockaddr*)&sin6,
02460                                                                         sizeof(sin6));
02461        } else {
02462               struct sockaddr_in sin;
02463               memset(&sin, 0, sizeof(sin));
02464 #ifdef HAVE_STRUCT_SOCKADDR_IN_SIN_LEN
02465               sin.sin_len = sizeof(sin);
02466 #endif
02467               sin.sin_family = AF_INET;
02468               sin.sin_port = htons(port);
02469               if (!inet_aton(addr_part, &sin.sin_addr)) {
02470                      log(EVDNS_LOG_DEBUG, "inet_pton(%s) failed", addr_part);
02471                      return 4;
02472               }
02473               return _evdns_nameserver_add_impl((struct sockaddr*)&sin,
02474                                                                         sizeof(sin));
02475        }
02476 }
02477 
02478 int
02479 evdns_nameserver_sockaddr_add(const struct sockaddr *sa, socklen_t len)
02480 {
02481        return _evdns_nameserver_add_impl(sa, len);
02482 }
02483 
02484 /* insert into the tail of the queue */
02485 static void
02486 evdns_request_insert(struct evdns_request *req, struct evdns_request **head) {
02487        if (!*head) {
02488               *head = req;
02489               req->next = req->prev = req;
02490               return;
02491        }
02492 
02493        req->prev = (*head)->prev;
02494        req->prev->next = req;
02495        req->next = *head;
02496        (*head)->prev = req;
02497 }
02498 
02499 static int
02500 string_num_dots(const char *s) {
02501        int count = 0;
02502        while ((s = strchr(s, '.'))) {
02503               s++;
02504               count++;
02505        }
02506        return count;
02507 }
02508 
02509 static struct evdns_request *
02510 request_new(int type, const char *name, int flags,
02511        evdns_callback_type callback, void *user_ptr) {
02512        const char issuing_now =
02513               (global_requests_inflight < global_max_requests_inflight) ? 1 : 0;
02514 
02515        const size_t name_len = strlen(name);
02516        const size_t request_max_len = evdns_request_len(name_len);
02517        const u16 trans_id = issuing_now ? transaction_id_pick() : 0xffff;
02518        /* the request data is alloced in a single block with the header */
02519        struct evdns_request *const req =
02520               (struct evdns_request *) mm_malloc(sizeof(struct evdns_request) + request_max_len);
02521        char namebuf[256];
02522        int rlen;
02523        (void) flags;
02524 
02525        if (!req) return NULL;
02526 
02527        if (name_len >= sizeof(namebuf)) {
02528               _mm_free(req);
02529               return NULL;
02530        }
02531 
02532        memset(req, 0, sizeof(struct evdns_request));
02533 
02534        evtimer_set(&req->timeout_event, evdns_request_timeout_callback, req);
02535 
02536        if (global_randomize_case) {
02537               unsigned i;
02538               char randbits[32];
02539               strlcpy(namebuf, name, sizeof(namebuf));
02540               rand_bytes_function(randbits, (name_len+7)/8);
02541               for (i = 0; i < name_len; ++i) {
02542                      if (ISALPHA(namebuf[i])) {
02543                             if ((randbits[i >> 3] & (1<<(i%7))))
02544                                    namebuf[i] = TOLOWER(namebuf[i]);
02545                             else
02546                                    namebuf[i] = TOUPPER(namebuf[i]);
02547                      }
02548               }
02549               name = namebuf;
02550        }
02551 
02552        /* request data lives just after the header */
02553        req->request = ((u8 *) req) + sizeof(struct evdns_request);
02554        /* denotes that the request data shouldn't be mm_free()ed */
02555        req->request_appended = 1;
02556        rlen = evdns_request_data_build(name, name_len, trans_id,
02557                                                  type, CLASS_INET, req->request, request_max_len);
02558        if (rlen < 0)
02559               goto err1;
02560        req->request_len = rlen;
02561        req->trans_id = trans_id;
02562        req->tx_count = 0;
02563        req->request_type = type;
02564        req->user_pointer = user_ptr;
02565        req->user_callback = callback;
02566        req->ns = issuing_now ? nameserver_pick() : NULL;
02567        req->next = req->prev = NULL;
02568 
02569        return req;
02570 err1:
02571        CLEAR(req);
02572        _mm_free(req);
02573        return NULL;
02574 }
02575 
02576 static void
02577 request_submit(struct evdns_request *const req) {
02578        if (req->ns) {
02579               /* if it has a nameserver assigned then this is going */
02580               /* straight into the inflight queue */
02581               evdns_request_insert(req, &req_head);
02582               global_requests_inflight++;
02583               evdns_request_transmit(req);
02584        } else {
02585               evdns_request_insert(req, &req_waiting_head);
02586               global_requests_waiting++;
02587        }
02588 }
02589 
02590 /* exported function */
02591 int evdns_resolve_ipv4(const char *name, int flags,
02592                                       evdns_callback_type callback, void *ptr) {
02593        log(EVDNS_LOG_DEBUG, "Resolve requested for %s", name);
02594        if (flags & DNS_QUERY_NO_SEARCH) {
02595               struct evdns_request *const req =
02596                      request_new(TYPE_A, name, flags, callback, ptr);
02597               if (req == NULL)
02598                      return (1);
02599               request_submit(req);
02600               return (0);
02601        } else {
02602               return (search_request_new(TYPE_A, name, flags, callback, ptr));
02603        }
02604 }
02605 
02606 /* exported function */
02607 int evdns_resolve_ipv6(const char *name, int flags,
02608                                       evdns_callback_type callback, void *ptr) {
02609        log(EVDNS_LOG_DEBUG, "Resolve requested for %s", name);
02610        if (flags & DNS_QUERY_NO_SEARCH) {
02611               struct evdns_request *const req =
02612                      request_new(TYPE_AAAA, name, flags, callback, ptr);
02613               if (req == NULL)
02614                      return (1);
02615               request_submit(req);
02616               return (0);
02617        } else {
02618               return (search_request_new(TYPE_AAAA, name, flags, callback, ptr));
02619        }
02620 }
02621 
02622 int evdns_resolve_reverse(const struct in_addr *in, int flags, evdns_callback_type callback, void *ptr) {
02623        char buf[32];
02624        struct evdns_request *req;
02625        u32 a;
02626        assert(in);
02627        a = ntohl(in->s_addr);
02628        snprintf(buf, sizeof(buf), "%d.%d.%d.%d.in-addr.arpa",
02629                      (int)(u8)((a  )&0xff),
02630                      (int)(u8)((a>>8 )&0xff),
02631                      (int)(u8)((a>>16)&0xff),
02632                      (int)(u8)((a>>24)&0xff));
02633        log(EVDNS_LOG_DEBUG, "Resolve requested for %s (reverse)", buf);
02634        req = request_new(TYPE_PTR, buf, flags, callback, ptr);
02635        if (!req) return 1;
02636        request_submit(req);
02637        return 0;
02638 }
02639 
02640 int evdns_resolve_reverse_ipv6(const struct in6_addr *in, int flags, evdns_callback_type callback, void *ptr) {
02641        /* 32 nybbles, 32 periods, "ip6.arpa", NUL. */
02642        char buf[73];
02643        char *cp;
02644        struct evdns_request *req;
02645        int i;
02646        assert(in);
02647        cp = buf;
02648        for (i=15; i >= 0; --i) {
02649               u8 byte = in->s6_addr[i];
02650               *cp++ = "0123456789abcdef"[byte & 0x0f];
02651               *cp++ = '.';
02652               *cp++ = "0123456789abcdef"[byte >> 4];
02653               *cp++ = '.';
02654        }
02655        assert(cp + strlen("ip6.arpa") < buf+sizeof(buf));
02656        memcpy(cp, "ip6.arpa", strlen("ip6.arpa")+1);
02657        log(EVDNS_LOG_DEBUG, "Resolve requested for %s (reverse)", buf);
02658        req = request_new(TYPE_PTR, buf, flags, callback, ptr);
02659        if (!req) return 1;
02660        request_submit(req);
02661        return 0;
02662 }
02663 
02664 /*/////////////////////////////////////////////////////////////////// */
02665 /* Search support */
02666 /* */
02667 /* the libc resolver has support for searching a number of domains */
02668 /* to find a name. If nothing else then it takes the single domain */
02669 /* from the gethostname() call. */
02670 /* */
02671 /* It can also be configured via the domain and search options in a */
02672 /* resolv.conf. */
02673 /* */
02674 /* The ndots option controls how many dots it takes for the resolver */
02675 /* to decide that a name is non-local and so try a raw lookup first. */
02676 
02677 struct search_domain {
02678        size_t len;
02679        struct search_domain *next;
02680        /* the text string is appended to this structure */
02681 };
02682 
02683 struct search_state {
02684        int refcount;
02685        int ndots;
02686        int num_domains;
02687        struct search_domain *head;
02688 };
02689 
02690 static struct search_state *global_search_state = NULL;
02691 
02692 static void
02693 search_state_decref(struct search_state *const state) {
02694        if (!state) return;
02695        state->refcount--;
02696        if (!state->refcount) {
02697               struct search_domain *next, *dom;
02698               for (dom = state->head; dom; dom = next) {
02699                      next = dom->next;
02700                      CLEAR(dom);
02701                      _mm_free(dom);
02702               }
02703               CLEAR(state);
02704               _mm_free(state);
02705        }
02706 }
02707 
02708 static struct search_state *
02709 search_state_new(void) {
02710        struct search_state *state = (struct search_state *) mm_malloc(sizeof(struct search_state));
02711        if (!state) return NULL;
02712        memset(state, 0, sizeof(struct search_state));
02713        state->refcount = 1;
02714        state->ndots = 1;
02715 
02716        return state;
02717 }
02718 
02719 static void
02720 search_postfix_clear(void) {
02721        search_state_decref(global_search_state);
02722 
02723        global_search_state = search_state_new();
02724 }
02725 
02726 /* exported function */
02727 void
02728 evdns_search_clear(void) {
02729        search_postfix_clear();
02730 }
02731 
02732 static void
02733 search_postfix_add(const char *domain) {
02734        size_t domain_len;
02735        struct search_domain *sdomain;
02736        while (domain[0] == '.') domain++;
02737        domain_len = strlen(domain);
02738 
02739        if (!global_search_state) global_search_state = search_state_new();
02740               if (!global_search_state) return;
02741        global_search_state->num_domains++;
02742 
02743        sdomain = (struct search_domain *) mm_malloc(sizeof(struct search_domain) + domain_len);
02744               if (!sdomain) return;
02745        memcpy( ((u8 *) sdomain) + sizeof(struct search_domain), domain, domain_len);
02746        sdomain->next = global_search_state->head;
02747        sdomain->len = domain_len;
02748 
02749        global_search_state->head = sdomain;
02750 }
02751 
02752 /* reverse the order of members in the postfix list. This is needed because, */
02753 /* when parsing resolv.conf we push elements in the wrong order */
02754 static void
02755 search_reverse(void) {
02756        struct search_domain *cur, *prev = NULL, *next;
02757        cur = global_search_state->head;
02758        while (cur) {
02759               next = cur->next;
02760               cur->next = prev;
02761               prev = cur;
02762               cur = next;
02763        }
02764 
02765        global_search_state->head = prev;
02766 }
02767 
02768 /* exported function */
02769 void
02770 evdns_search_add(const char *domain) {
02771        search_postfix_add(domain);
02772 }
02773 
02774 /* exported function */
02775 void
02776 evdns_search_ndots_set(const int ndots) {
02777        if (!global_search_state) global_search_state = search_state_new();
02778               if (!global_search_state) return;
02779        global_search_state->ndots = ndots;
02780 }
02781 
02782 static void
02783 search_set_from_hostname(void) {
02784        char hostname[HOST_NAME_MAX + 1], *domainname;
02785 
02786        search_postfix_clear();
02787        if (gethostname(hostname, sizeof(hostname))) return;
02788        domainname = strchr(hostname, '.');
02789        if (!domainname) return;
02790        search_postfix_add(domainname);
02791 }
02792 
02793 /* warning: returns malloced string */
02794 static char *
02795 search_make_new(const struct search_state *const state, int n, const char *const base_name) {
02796        const size_t base_len = strlen(base_name);
02797        const char need_to_append_dot = base_name[base_len - 1] == '.' ? 0 : 1;
02798        struct search_domain *dom;
02799 
02800        for (dom = state->head; dom; dom = dom->next) {
02801               if (!n--) {
02802                      /* this is the postfix we want */
02803                      /* the actual postfix string is kept at the end of the structure */
02804                      const u8 *const postfix = ((u8 *) dom) + sizeof(struct search_domain);
02805                      const size_t postfix_len = dom->len;
02806                      char *const newname = (char *) mm_malloc(base_len + need_to_append_dot + postfix_len + 1);
02807                      if (!newname) return NULL;
02808                      memcpy(newname, base_name, base_len);
02809                      if (need_to_append_dot) newname[base_len] = '.';
02810                      memcpy(newname + base_len + need_to_append_dot, postfix, postfix_len);
02811                      newname[base_len + need_to_append_dot + postfix_len] = 0;
02812                      return newname;
02813               }
02814        }
02815 
02816        /* we ran off the end of the list and still didn't find the requested string */
02817        abort();
02818        return NULL; /* unreachable; stops warnings in some compilers. */
02819 }
02820 
02821 static int
02822 search_request_new(int type, const char *const name, int flags, evdns_callback_type user_callback, void *user_arg) {
02823        assert(type == TYPE_A || type == TYPE_AAAA);
02824        if ( ((flags & DNS_QUERY_NO_SEARCH) == 0) &&
02825                global_search_state &&
02826                global_search_state->num_domains) {
02827               /* we have some domains to search */
02828               struct evdns_request *req;
02829               if (string_num_dots(name) >= global_search_state->ndots) {
02830                      req = request_new(type, name, flags, user_callback, user_arg);
02831                      if (!req) return 1;
02832                      req->search_index = -1;
02833               } else {
02834                      char *const new_name = search_make_new(global_search_state, 0, name);
02835                                           if (!new_name) return 1;
02836                      req = request_new(type, new_name, flags, user_callback, user_arg);
02837                      _mm_free(new_name);
02838                      if (!req) return 1;
02839                      req->search_index = 0;
02840               }
02841               req->search_origname = mm_strdup(name);
02842               req->search_state = global_search_state;
02843               req->search_flags = flags;
02844               global_search_state->refcount++;
02845               request_submit(req);
02846               return 0;
02847        } else {
02848               struct evdns_request *const req = request_new(type, name, flags, user_callback, user_arg);
02849               if (!req) return 1;
02850               request_submit(req);
02851               return 0;
02852        }
02853 }
02854 
02855 /* this is called when a request has failed to find a name. We need to check */
02856 /* if it is part of a search and, if so, try the next name in the list */
02857 /* returns: */
02858 /* 0 another request has been submitted */
02859 /* 1 no more requests needed */
02860 static int
02861 search_try_next(struct evdns_request *const req) {
02862        if (req->search_state) {
02863               /* it is part of a search */
02864               char *new_name;
02865               struct evdns_request *newreq;
02866               req->search_index++;
02867               if (req->search_index >= req->search_state->num_domains) {
02868                      /* no more postfixes to try, however we may need to try */
02869                      /* this name without a postfix */
02870                      if (string_num_dots(req->search_origname) < req->search_state->ndots) {
02871                             /* yep, we need to try it raw */
02872                             struct evdns_request *const newreq = request_new(req->request_type, req->search_origname, req->search_flags, req->user_callback, req->user_pointer);
02873                             log(EVDNS_LOG_DEBUG, "Search: trying raw query %s", req->search_origname);
02874                             if (newreq) {
02875                                    request_submit(newreq);
02876                                    return 0;
02877                             }
02878                      }
02879                      return 1;
02880               }
02881 
02882               new_name = search_make_new(req->search_state, req->search_index, req->search_origname);
02883                             if (!new_name) return 1;
02884               log(EVDNS_LOG_DEBUG, "Search: now trying %s (%d)", new_name, req->search_index);
02885               newreq = request_new(req->request_type, new_name, req->search_flags, req->user_callback, req->user_pointer);
02886               mm_free(new_name);
02887               if (!newreq) return 1;
02888               newreq->search_origname = req->search_origname;
02889               req->search_origname = NULL;
02890               newreq->search_state = req->search_state;
02891               newreq->search_flags = req->search_flags;
02892               newreq->search_index = req->search_index;
02893               newreq->search_state->refcount++;
02894               request_submit(newreq);
02895               return 0;
02896        }
02897        return 1;
02898 }
02899 
02900 static void
02901 search_request_finished(struct evdns_request *const req) {
02902        if (req->search_state) {
02903               search_state_decref(req->search_state);
02904               req->search_state = NULL;
02905        }
02906        if (req->search_origname) {
02907               mm_free(req->search_origname);
02908               req->search_origname = NULL;
02909        }
02910 }
02911 
02912 /*/////////////////////////////////////////////////////////////////// */
02913 /* Parsing resolv.conf files */
02914 
02915 static void
02916 evdns_resolv_set_defaults(int flags) {
02917        /* if the file isn't found then we assume a local resolver */
02918        if (flags & DNS_OPTION_SEARCH) search_set_from_hostname();
02919        if (flags & DNS_OPTION_NAMESERVERS) evdns_nameserver_ip_add("127.0.0.1");
02920 }
02921 
02922 /* helper version of atoi which returns -1 on error */
02923 static int
02924 strtoint(const char *const str) {
02925        char *endptr;
02926        const long r = strtol(str, &endptr, 10);
02927        if (*endptr || r > INT_MAX) return -1;
02928        return (int)r;
02929 }
02930 
02931 /* helper version of atoi that returns -1 on error and clips to bounds. */
02932 static int
02933 strtoint_clipped(const char *const str, int min, int max)
02934 {
02935        int r = strtoint(str);
02936        if (r == -1)
02937               return r;
02938        else if (r<min)
02939               return min;
02940        else if (r>max)
02941               return max;
02942        else
02943               return r;
02944 }
02945 
02946 /* exported function */
02947 int
02948 evdns_set_option(const char *option, const char *val, int flags)
02949 {
02950        if (!strncmp(option, "ndots:", 6)) {
02951               const int ndots = strtoint(val);
02952               if (ndots == -1) return -1;
02953               if (!(flags & DNS_OPTION_SEARCH)) return 0;
02954               log(EVDNS_LOG_DEBUG, "Setting ndots to %d", ndots);
02955               if (!global_search_state) global_search_state = search_state_new();
02956               if (!global_search_state) return -1;
02957               global_search_state->ndots = ndots;
02958        } else if (!strncmp(option, "timeout:", 8)) {
02959               const int timeout = strtoint(val);
02960               if (timeout == -1) return -1;
02961               if (!(flags & DNS_OPTION_MISC)) return 0;
02962               log(EVDNS_LOG_DEBUG, "Setting timeout to %d", timeout);
02963               global_timeout.tv_sec = timeout;
02964        } else if (!strncmp(option, "max-timeouts:", 12)) {
02965               const int maxtimeout = strtoint_clipped(val, 1, 255);
02966               if (maxtimeout == -1) return -1;
02967               if (!(flags & DNS_OPTION_MISC)) return 0;
02968               log(EVDNS_LOG_DEBUG, "Setting maximum allowed timeouts to %d",
02969                      maxtimeout);
02970               global_max_nameserver_timeout = maxtimeout;
02971        } else if (!strncmp(option, "max-inflight:", 13)) {
02972               const int maxinflight = strtoint_clipped(val, 1, 65000);
02973               if (maxinflight == -1) return -1;
02974               if (!(flags & DNS_OPTION_MISC)) return 0;
02975               log(EVDNS_LOG_DEBUG, "Setting maximum inflight requests to %d",
02976                      maxinflight);
02977               global_max_requests_inflight = maxinflight;
02978        } else if (!strncmp(option, "attempts:", 9)) {
02979               int retries = strtoint(val);
02980               if (retries == -1) return -1;
02981               if (retries > 255) retries = 255;
02982               if (!(flags & DNS_OPTION_MISC)) return 0;
02983               log(EVDNS_LOG_DEBUG, "Setting retries to %d", retries);
02984               global_max_retransmits = retries;
02985        } else if (!strncmp(option, "randomize-case:", 15)) {
02986               int randcase = strtoint(val);
02987               if (!(flags & DNS_OPTION_MISC)) return 0;
02988               log(EVDNS_LOG_DEBUG, "Setting randomize_case to %d", randcase);
02989               global_randomize_case = randcase;
02990        }
02991        return 0;
02992 }
02993 
02994 static void
02995 resolv_conf_parse_line(char *const start, int flags) {
02996        char *strtok_state;
02997        static const char *const delims = " \t";
02998 #define NEXT_TOKEN tor_strtok_r(NULL, delims, &strtok_state)
02999 
03000        char *const first_token = tor_strtok_r(start, delims, &strtok_state);
03001        if (!first_token) return;
03002 
03003        if (!strcmp(first_token, "nameserver") && (flags & DNS_OPTION_NAMESERVERS)) {
03004               const char *const nameserver = NEXT_TOKEN;
03005               evdns_nameserver_ip_add(nameserver);
03006        } else if (!strcmp(first_token, "domain") && (flags & DNS_OPTION_SEARCH)) {
03007               const char *const domain = NEXT_TOKEN;
03008               if (domain) {
03009                      search_postfix_clear();
03010                      search_postfix_add(domain);
03011               }
03012        } else if (!strcmp(first_token, "search") && (flags & DNS_OPTION_SEARCH)) {
03013               const char *domain;
03014               search_postfix_clear();
03015 
03016               while ((domain = NEXT_TOKEN)) {
03017                      search_postfix_add(domain);
03018               }
03019               search_reverse();
03020        } else if (!strcmp(first_token, "options")) {
03021               const char *option;
03022               while ((option = NEXT_TOKEN)) {
03023                      const char *val = strchr(option, ':');
03024                      evdns_set_option(option, val ? val+1 : "", flags);
03025               }
03026        }
03027 #undef NEXT_TOKEN
03028 }
03029 
03030 /* exported function */
03031 /* returns: */
03032 /* 0 no errors */
03033 /* 1 failed to open file */
03034 /* 2 failed to stat file */
03035 /* 3 file too large */
03036 /* 4 out of memory */
03037 /* 5 short read from file */
03038 int
03039 evdns_resolv_conf_parse(int flags, const char *const filename) {
03040        struct stat st;
03041        int fd, n, r;
03042        u8 *resolv;
03043        char *start;
03044        int err = 0;
03045 
03046        log(EVDNS_LOG_DEBUG, "Parsing resolv.conf file %s", filename);
03047 
03048        fd = tor_open_cloexec(filename, O_RDONLY, 0);
03049        if (fd < 0) {
03050               evdns_resolv_set_defaults(flags);
03051               return 1;
03052        }
03053 
03054        if (fstat(fd, &st)) { err = 2; goto out1; }
03055        if (!st.st_size) {
03056               evdns_resolv_set_defaults(flags);
03057               err = (flags & DNS_OPTION_NAMESERVERS) ? 6 : 0;
03058               goto out1;
03059        }
03060        if (st.st_size > 65535) { err = 3; goto out1; }   /* no resolv.conf should be any bigger */
03061 
03062        resolv = (u8 *) mm_malloc((size_t)st.st_size + 1);
03063        if (!resolv) { err = 4; goto out1; }
03064 
03065     n = 0;
03066        while ((r = (int)read(fd, resolv+n, (size_t)st.st_size-n)) > 0) {
03067               n += r;
03068               if (n == st.st_size)
03069                      break;
03070               assert(n < st.st_size);
03071        }
03072        if (r < 0) { err = 5; goto out2; }
03073        resolv[n] = 0;        /* we malloced an extra byte; this should be fine. */
03074 
03075        start = (char *) resolv;
03076        for (;;) {
03077               char *const newline = strchr(start, '\n');
03078               if (!newline) {
03079                      resolv_conf_parse_line(start, flags);
03080                      break;
03081               } else {
03082                      *newline = 0;
03083                      resolv_conf_parse_line(start, flags);
03084                      start = newline + 1;
03085               }
03086        }
03087 
03088        if (!server_head && (flags & DNS_OPTION_NAMESERVERS)) {
03089               /* no nameservers were configured. */
03090               evdns_nameserver_ip_add("127.0.0.1");
03091               err = 6;
03092        }
03093        if (flags & DNS_OPTION_SEARCH && (!global_search_state || global_search_state->num_domains == 0)) {
03094               search_set_from_hostname();
03095        }
03096 
03097 out2:
03098        mm_free(resolv);
03099 out1:
03100        close(fd);
03101        return err;
03102 }
03103 
03104 #ifdef _WIN32
03105 /* Add multiple nameservers from a space-or-comma-separated list. */
03106 static int
03107 evdns_nameserver_ip_add_line(const char *ips) {
03108        const char *addr;
03109        char *buf;
03110        int r;
03111        while (*ips) {
03112               while (ISSPACE(*ips) || *ips == ',' || *ips == '\t')
03113                      ++ips;
03114               addr = ips;
03115               while (ISDIGIT(*ips) || *ips == '.' || *ips == ':' || *ips == '[' || *ips == ']')
03116                      ++ips;
03117               buf = mm_malloc(ips-addr+1);
03118               if (!buf) return 4;
03119               memcpy(buf, addr, ips-addr);
03120               buf[ips-addr] = '\0';
03121               r = evdns_nameserver_ip_add(buf);
03122               mm_free(buf);
03123               if (r) return r;
03124        }
03125        return 0;
03126 }
03127 
03128 typedef DWORD(WINAPI *GetNetworkParams_fn_t)(FIXED_INFO *, DWORD*);
03129 
03130 /* Use the windows GetNetworkParams interface in iphlpapi.dll to */
03131 /* figure out what our nameservers are. */
03132 static int
03133 load_nameservers_with_getnetworkparams(void)
03134 {
03135        /* Based on MSDN examples and inspection of       c-ares code. */
03136        FIXED_INFO *fixed;
03137        HMODULE handle = 0;
03138        ULONG size = sizeof(FIXED_INFO);
03139        void *buf = NULL;
03140        int status = 0, r, added_any;
03141        IP_ADDR_STRING *ns;
03142        GetNetworkParams_fn_t fn;
03143 
03144        if (!(handle = load_windows_system_library(TEXT("iphlpapi.dll")))) {
03145               log(EVDNS_LOG_WARN, "Could not open iphlpapi.dll");
03146               /* right now status = 0, doesn't that mean "good" - mikec */
03147               status = -1;
03148               goto done;
03149        }
03150        if (!(fn = (GetNetworkParams_fn_t) GetProcAddress(handle, TEXT("GetNetworkParams")))) {
03151               log(EVDNS_LOG_WARN, "Could not get address of function.");
03152               /* same as above */
03153               status = -1;
03154               goto done;
03155        }
03156 
03157        buf = mm_malloc(size);
03158        if (!buf) { status = 4; goto done; }
03159        fixed = buf;
03160        r = fn(fixed, &size);
03161        if (r != ERROR_SUCCESS && r != ERROR_BUFFER_OVERFLOW) {
03162               status = -1;
03163               goto done;
03164        }
03165        if (r != ERROR_SUCCESS) {
03166               mm_free(buf);
03167               buf = mm_malloc(size);
03168               if (!buf) { status = 4; goto done; }
03169               fixed = buf;
03170               r = fn(fixed, &size);
03171               if (r != ERROR_SUCCESS) {
03172                      log(EVDNS_LOG_DEBUG, "fn() failed.");
03173                      status = -1;
03174                      goto done;
03175               }
03176        }
03177 
03178        assert(fixed);
03179        added_any = 0;
03180        ns = &(fixed->DnsServerList);
03181        while (ns) {
03182               r = evdns_nameserver_ip_add_line(ns->IpAddress.String);
03183               if (r) {
03184                      log(EVDNS_LOG_DEBUG,"Could not add nameserver %s to list, "
03185                             "error: %d; status: %d",
03186                             (ns->IpAddress.String),(int)GetLastError(), r);
03187                      status = r;
03188               } else {
03189                      log(EVDNS_LOG_DEBUG,"Successfully added %s as nameserver",ns->IpAddress.String);
03190                      added_any++;
03191               }
03192 
03193               ns = ns->Next;
03194        }
03195 
03196        if (!added_any) {
03197               log(EVDNS_LOG_DEBUG, "No nameservers added.");
03198               if (status == 0)
03199                      status = -1;
03200        } else {
03201               status = 0;
03202        }
03203 
03204  done:
03205        if (buf)
03206               mm_free(buf);
03207        if (handle)
03208               FreeLibrary(handle);
03209        return status;
03210 }
03211 
03212 static int
03213 config_nameserver_from_reg_key(HKEY key, const TCHAR *subkey)
03214 {
03215        char *buf;
03216        char ansibuf[MAX_PATH] = {0};
03217        DWORD bufsz = 0, type = 0;
03218        int status = 0;
03219 
03220        if (RegQueryValueEx(key, subkey, 0, &type, NULL, &bufsz)
03221               != ERROR_MORE_DATA)
03222               return -1;
03223        if (!(buf = mm_malloc(bufsz)))
03224               return -1;
03225 
03226        if (RegQueryValueEx(key, subkey, 0, &type, (LPBYTE)buf, &bufsz)
03227               == ERROR_SUCCESS && bufsz > 1) {
03228               wcstombs(ansibuf,(wchar_t*)buf,MAX_PATH);/*XXXX UNICODE */
03229               abuf[MAX_PATH-1] = '\0';
03230               status = evdns_nameserver_ip_add_line(ansibuf);
03231        }
03232 
03233        mm_free(buf);
03234        return status;
03235 }
03236 
03237 #define SERVICES_KEY TEXT("System\\CurrentControlSet\\Services\\")
03238 #define WIN_NS_9X_KEY  SERVICES_KEY TEXT("VxD\\MSTCP")
03239 #define WIN_NS_NT_KEY  SERVICES_KEY TEXT("Tcpip\\Parameters")
03240 
03241 static int
03242 load_nameservers_from_registry(void)
03243 {
03244        int found = 0;
03245        int r;
03246        OSVERSIONINFO info;
03247        memset(&info, 0, sizeof(info));
03248        info.dwOSVersionInfoSize = sizeof (info);
03249        GetVersionEx(&info);
03250 
03251 #define TRY(k, name)                                                                                     \
03252        if (!found && config_nameserver_from_reg_key(k,TEXT(name)) == 0) {    \
03253               log(EVDNS_LOG_DEBUG,"Found nameservers in %s/%s",#k,name);            \
03254               found = 1;                                                                                               \
03255        } else if (!found) {                                                                              \
03256               log(EVDNS_LOG_DEBUG,"Didn't find nameservers in %s/%s",               \
03257                      #k,#name);                                                                                        \
03258        }
03259 
03260        if (info.dwMajorVersion >= 5) { /* NT */
03261               HKEY nt_key = 0, interfaces_key = 0;
03262 
03263               if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, WIN_NS_NT_KEY, 0,
03264                                            KEY_READ, &nt_key) != ERROR_SUCCESS) {
03265                      log(EVDNS_LOG_DEBUG,"Couldn't open nt key, %d",(int)GetLastError());
03266                      return -1;
03267               }
03268               r = RegOpenKeyEx(nt_key, TEXT("Interfaces"), 0,
03269                                            KEY_QUERY_VALUE|KEY_ENUMERATE_SUB_KEYS,
03270                                            &interfaces_key);
03271               if (r != ERROR_SUCCESS) {
03272                      log(EVDNS_LOG_DEBUG,"Couldn't open interfaces key, %d",(int)GetLastError());
03273                      return -1;
03274               }
03275               TRY(nt_key, "NameServer");
03276               TRY(nt_key, "DhcpNameServer");
03277               TRY(interfaces_key, "NameServer");
03278               TRY(interfaces_key, "DhcpNameServer");
03279               RegCloseKey(interfaces_key);
03280               RegCloseKey(nt_key);
03281        } else {
03282               HKEY win_key = 0;
03283               if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, WIN_NS_9X_KEY, 0,
03284                                            KEY_READ, &win_key) != ERROR_SUCCESS) {
03285                      log(EVDNS_LOG_DEBUG, "Couldn't open registry key, %d", (int)GetLastError());
03286                      return -1;
03287               }
03288               TRY(win_key, "NameServer");
03289               RegCloseKey(win_key);
03290        }
03291 
03292        if (found == 0) {
03293               log(EVDNS_LOG_WARN,"Didn't find any nameservers.");
03294        }
03295 
03296        return found ? 0 : -1;
03297 #undef TRY
03298 }
03299 
03300 int
03301 evdns_config_windows_nameservers(void)
03302 {
03303        if (load_nameservers_with_getnetworkparams() == 0)
03304               return 0;
03305        return load_nameservers_from_registry();
03306 }
03307 #endif
03308 
03309 int
03310 evdns_init(void)
03311 {
03312               int res = 0;
03313 #ifdef _WIN32
03314               evdns_config_windows_nameservers();
03315 #else
03316               res = evdns_resolv_conf_parse(DNS_OPTIONS_ALL, "/etc/resolv.conf");
03317 #endif
03318 
03319               return (res);
03320 }
03321 
03322 const char *
03323 evdns_err_to_string(int err)
03324 {
03325        switch (err) {
03326        case DNS_ERR_NONE: return "no error";
03327        case DNS_ERR_FORMAT: return "misformatted query";
03328        case DNS_ERR_SERVERFAILED: return "server failed";
03329        case DNS_ERR_NOTEXIST: return "name does not exist";
03330        case DNS_ERR_NOTIMPL: return "query not implemented";
03331        case DNS_ERR_REFUSED: return "refused";
03332 
03333        case DNS_ERR_TRUNCATED: return "reply truncated or ill-formed";
03334        case DNS_ERR_UNKNOWN: return "unknown";
03335        case DNS_ERR_TIMEOUT: return "request timed out";
03336        case DNS_ERR_SHUTDOWN: return "dns subsystem shut down";
03337        default: return "[Unknown error code]";
03338        }
03339 }
03340 
03341 void
03342 evdns_shutdown(int fail_requests)
03343 {
03344        struct nameserver *server, *server_next;
03345        struct search_domain *dom, *dom_next;
03346 
03347        while (req_head) {
03348               if (fail_requests)
03349                      reply_callback(req_head, 0, DNS_ERR_SHUTDOWN, NULL);
03350               request_finished(req_head, &req_head);
03351        }
03352        while (req_waiting_head) {
03353               if (fail_requests)
03354                      reply_callback(req_waiting_head, 0, DNS_ERR_SHUTDOWN, NULL);
03355               request_finished(req_waiting_head, &req_waiting_head);
03356        }
03357        global_requests_inflight = global_requests_waiting = 0;
03358 
03359        for (server = server_head; server; server = server_next) {
03360               server_next = server->next;
03361               if (server->socket >= 0)
03362                      CLOSE_SOCKET(server->socket);
03363               (void) event_del(&server->event);
03364               del_timeout_event(server);
03365               CLEAR(server);
03366               mm_free(server);
03367               if (server_next == server_head)
03368                      break;
03369        }
03370        server_head = NULL;
03371        global_good_nameservers = 0;
03372 
03373        if (global_search_state) {
03374               for (dom = global_search_state->head; dom; dom = dom_next) {
03375                      dom_next = dom->next;
03376                      CLEAR(dom);
03377                      mm_free(dom);
03378               }
03379               CLEAR(global_search_state);
03380               mm_free(global_search_state);
03381               global_search_state = NULL;
03382        }
03383        evdns_log_fn = NULL;
03384 }
03385 
03386 #ifdef EVDNS_MAIN
03387 void
03388 main_callback(int result, char type, int count, int ttl,
03389                        void *addrs, void *orig) {
03390        char *n = (char*)orig;
03391        int i;
03392        for (i = 0; i < count; ++i) {
03393               if (type == DNS_IPv4_A) {
03394                      printf("%s: %s\n", n, debug_ntoa(((u32*)addrs)[i]));
03395               } else if (type == DNS_PTR) {
03396                      printf("%s: %s\n", n, ((char**)addrs)[i]);
03397               }
03398        }
03399        if (!count) {
03400               printf("%s: No answer (%d)\n", n, result);
03401        }
03402        fflush(stdout);
03403 }
03404 void
03405 evdns_server_callback(struct evdns_server_request *req, void *data)
03406 {
03407        int i, r;
03408        (void)data;
03409        /* dummy; give 192.168.11.11 as an answer for all A questions,
03410         *     give foo.bar.example.com as an answer for all PTR questions. */
03411        for (i = 0; i < req->nquestions; ++i) {
03412               u32 ans = htonl(0xc0a80b0bUL);
03413               if (req->questions[i]->type == EVDNS_TYPE_A &&
03414                      req->questions[i]->dns_question_class == EVDNS_CLASS_INET) {
03415                      printf(" -- replying for %s (A)\n", req->questions[i]->name);
03416                      r = evdns_server_request_add_a_reply(req, req->questions[i]->name,
03417                                                                         1, &ans, 10);
03418                      if (r<0)
03419                             printf("eeep, didn't work.\n");
03420               } else if (req->questions[i]->type == EVDNS_TYPE_PTR &&
03421                                req->questions[i]->dns_question_class == EVDNS_CLASS_INET) {
03422                      printf(" -- replying for %s (PTR)\n", req->questions[i]->name);
03423                      r = evdns_server_request_add_ptr_reply(req, NULL, req->questions[i]->name,
03424                                                                              "foo.bar.example.com", 10);
03425               } else {
03426                      printf(" -- skipping %s [%d %d]\n", req->questions[i]->name,
03427                                req->questions[i]->type, req->questions[i]->dns_question_class);
03428               }
03429        }
03430 
03431        r = evdns_server_request_respond(req, 0);
03432        if (r<0)
03433               printf("eeek, couldn't send reply.\n");
03434 }
03435 
03436 void
03437 logfn(int is_warn, const char *msg) {
03438        (void) is_warn;
03439        fprintf(stderr, "%s\n", msg);
03440 }
03441 int
03442 main(int c, char **v) {
03443        int idx;
03444        int reverse = 0, verbose = 1, servertest = 0;
03445        if (c<2) {
03446               fprintf(stderr, "syntax: %s [-x] [-v] hostname\n", v[0]);
03447               fprintf(stderr, "syntax: %s [-servertest]\n", v[0]);
03448               return 1;
03449        }
03450        idx = 1;
03451        while (idx < c && v[idx][0] == '-') {
03452               if (!strcmp(v[idx], "-x"))
03453                      reverse = 1;
03454               else if (!strcmp(v[idx], "-v"))
03455                      verbose = 1;
03456               else if (!strcmp(v[idx], "-servertest"))
03457                      servertest = 1;
03458               else
03459                      fprintf(stderr, "Unknown option %s\n", v[idx]);
03460               ++idx;
03461        }
03462        event_init();
03463        if (verbose)
03464               evdns_set_log_fn(logfn);
03465        evdns_resolv_conf_parse(DNS_OPTION_NAMESERVERS, "/etc/resolv.conf");
03466        if (servertest) {
03467               int sock;
03468               struct sockaddr_in my_addr;
03469               sock = tor_open_socket(PF_INET, SOCK_DGRAM, 0);
03470               fcntl(sock, F_SETFL, O_NONBLOCK);
03471               my_addr.sin_family = AF_INET;
03472               my_addr.sin_port = htons(10053);
03473               my_addr.sin_addr.s_addr = INADDR_ANY;
03474               if (bind(sock, (struct sockaddr*)&my_addr, sizeof(my_addr))<0) {
03475                      perror("bind");
03476                      exit(1);
03477               }
03478               evdns_add_server_port(sock, 0, evdns_server_callback, NULL);
03479        }
03480        for (; idx < c; ++idx) {
03481               if (reverse) {
03482                      struct in_addr addr;
03483                      if (!inet_aton(v[idx], &addr)) {
03484                             fprintf(stderr, "Skipping non-IP %s\n", v[idx]);
03485                             continue;
03486                      }
03487                      fprintf(stderr, "resolving %s...\n",v[idx]);
03488                      evdns_resolve_reverse(&addr, 0, main_callback, v[idx]);
03489               } else {
03490                      fprintf(stderr, "resolving (fwd) %s...\n",v[idx]);
03491                      evdns_resolve_ipv4(v[idx], 0, main_callback, v[idx]);
03492               }
03493        }
03494        fflush(stdout);
03495        event_dispatch();
03496        return 0;
03497 }
03498 #endif
03499 
03500 /* Local Variables: */
03501 /* tab-width: 4 */
03502 /* c-basic-offset: 4 */
03503 /* indent-tabs-mode: t */
03504 /* End: */
03505