LCOV - code coverage report
Current view: directory - ipc/chromium/src/third_party/libevent - evdns.c (source / functions) Found Hit Coverage
Test: app.info Lines: 1277 0 0.0 %
Date: 2012-06-02 Functions: 90 0 0.0 %

       1                 : /* $Id: evdns.c 6979 2006-08-04 18:31:13Z nickm $ */
       2                 : 
       3                 : /* The original version of this module was written by Adam Langley; for
       4                 :  * a history of modifications, check out the subversion logs.
       5                 :  *
       6                 :  * When editing this module, try to keep it re-mergeable by Adam.  Don't
       7                 :  * reformat the whitespace, add Tor dependencies, or so on.
       8                 :  *
       9                 :  * TODO:
      10                 :  *   - Support IPv6 and PTR records.
      11                 :  *   - Replace all externally visible magic numbers with #defined constants.
      12                 :  *   - Write doccumentation for APIs of all external functions.
      13                 :  */
      14                 : 
      15                 : /* Async DNS Library
      16                 :  * Adam Langley <agl@imperialviolet.org>
      17                 :  * http://www.imperialviolet.org/eventdns.html
      18                 :  * Public Domain code
      19                 :  *
      20                 :  * This software is Public Domain. To view a copy of the public domain dedication,
      21                 :  * visit http://creativecommons.org/licenses/publicdomain/ or send a letter to
      22                 :  * Creative Commons, 559 Nathan Abbott Way, Stanford, California 94305, USA.
      23                 :  *
      24                 :  * I ask and expect, but do not require, that all derivative works contain an
      25                 :  * attribution similar to:
      26                 :  *      Parts developed by Adam Langley <agl@imperialviolet.org>
      27                 :  *
      28                 :  * You may wish to replace the word "Parts" with something else depending on
      29                 :  * the amount of original code.
      30                 :  *
      31                 :  * (Derivative works does not include programs which link against, run or include
      32                 :  * the source verbatim in their source distributions)
      33                 :  *
      34                 :  * Version: 0.1b
      35                 :  */
      36                 : 
      37                 : #include <sys/types.h>
      38                 : #ifdef HAVE_CONFIG_H
      39                 : #include "config.h"
      40                 : #endif
      41                 : 
      42                 : #ifdef DNS_USE_FTIME_FOR_ID
      43                 : #include <sys/timeb.h>
      44                 : #endif
      45                 : 
      46                 : #ifndef DNS_USE_CPU_CLOCK_FOR_ID
      47                 : #ifndef DNS_USE_GETTIMEOFDAY_FOR_ID
      48                 : #ifndef DNS_USE_OPENSSL_FOR_ID
      49                 : #ifndef DNS_USE_FTIME_FOR_ID
      50                 : #error Must configure at least one id generation method.
      51                 : #error Please see the documentation.
      52                 : #endif
      53                 : #endif
      54                 : #endif
      55                 : #endif
      56                 : 
      57                 : /* #define _POSIX_C_SOURCE 200507 */
      58                 : #define _GNU_SOURCE
      59                 : 
      60                 : #ifdef DNS_USE_CPU_CLOCK_FOR_ID
      61                 : #ifdef DNS_USE_OPENSSL_FOR_ID
      62                 : #error Multiple id options selected
      63                 : #endif
      64                 : #ifdef DNS_USE_GETTIMEOFDAY_FOR_ID
      65                 : #error Multiple id options selected
      66                 : #endif
      67                 : #include <time.h>
      68                 : #endif
      69                 : 
      70                 : #ifdef DNS_USE_OPENSSL_FOR_ID
      71                 : #ifdef DNS_USE_GETTIMEOFDAY_FOR_ID
      72                 : #error Multiple id options selected
      73                 : #endif
      74                 : #include <openssl/rand.h>
      75                 : #endif
      76                 : 
      77                 : #define _FORTIFY_SOURCE 3
      78                 : 
      79                 : #include <string.h>
      80                 : #include <fcntl.h>
      81                 : #ifdef HAVE_SYS_TIME_H
      82                 : #include <sys/time.h>
      83                 : #endif
      84                 : #ifdef HAVE_STDINT_H
      85                 : #include <stdint.h>
      86                 : #endif
      87                 : #include <stdlib.h>
      88                 : #include <string.h>
      89                 : #include <errno.h>
      90                 : #include <assert.h>
      91                 : #ifdef HAVE_UNISTD_H
      92                 : #include <unistd.h>
      93                 : #endif
      94                 : #include <limits.h>
      95                 : #include <sys/stat.h>
      96                 : #include <ctype.h>
      97                 : #include <stdio.h>
      98                 : #include <stdarg.h>
      99                 : 
     100                 : #include "evdns.h"
     101                 : #include "evutil.h"
     102                 : #include "log.h"
     103                 : #ifdef WIN32
     104                 : #include <winsock2.h>
     105                 : #include <windows.h>
     106                 : #include <iphlpapi.h>
     107                 : #include <io.h>
     108                 : #else
     109                 : #include <sys/socket.h>
     110                 : #include <netinet/in.h>
     111                 : #include <arpa/inet.h>
     112                 : #endif
     113                 : 
     114                 : #ifdef HAVE_NETINET_IN6_H
     115                 : #include <netinet/in6.h>
     116                 : #endif
     117                 : 
     118                 : #define EVDNS_LOG_DEBUG 0
     119                 : #define EVDNS_LOG_WARN 1
     120                 : 
     121                 : #ifndef HOST_NAME_MAX
     122                 : #define HOST_NAME_MAX 255
     123                 : #endif
     124                 : 
     125                 : #include <stdio.h>
     126                 : 
     127                 : #undef MIN
     128                 : #define MIN(a,b) ((a)<(b)?(a):(b))
     129                 : 
     130                 : #ifdef __USE_ISOC99B
     131                 : /* libevent doesn't work without this */
     132                 : typedef ev_uint8_t u_char;
     133                 : typedef unsigned int uint;
     134                 : #endif
     135                 : #include <event.h>
     136                 : 
     137                 : #define u64 ev_uint64_t
     138                 : #define u32 ev_uint32_t
     139                 : #define u16 ev_uint16_t
     140                 : #define u8  ev_uint8_t
     141                 : 
     142                 : #ifdef WIN32
     143                 : #define open _open
     144                 : #define read _read
     145                 : #define close _close
     146                 : #define strdup _strdup
     147                 : #endif
     148                 : 
     149                 : #define MAX_ADDRS 32  /* maximum number of addresses from a single packet */
     150                 : /* which we bother recording */
     151                 : 
     152                 : #define TYPE_A         EVDNS_TYPE_A
     153                 : #define TYPE_CNAME     5
     154                 : #define TYPE_PTR       EVDNS_TYPE_PTR
     155                 : #define TYPE_AAAA      EVDNS_TYPE_AAAA
     156                 : 
     157                 : #define CLASS_INET     EVDNS_CLASS_INET
     158                 : 
     159                 : struct request {
     160                 :         u8 *request;  /* the dns packet data */
     161                 :         unsigned int request_len;
     162                 :         int reissue_count;
     163                 :         int tx_count;  /* the number of times that this packet has been sent */
     164                 :         unsigned int request_type; /* TYPE_PTR or TYPE_A */
     165                 :         void *user_pointer;  /* the pointer given to us for this request */
     166                 :         evdns_callback_type user_callback;
     167                 :         struct nameserver *ns;  /* the server which we last sent it */
     168                 : 
     169                 :         /* elements used by the searching code */
     170                 :         int search_index;
     171                 :         struct search_state *search_state;
     172                 :         char *search_origname;  /* needs to be free()ed */
     173                 :         int search_flags;
     174                 : 
     175                 :         /* these objects are kept in a circular list */
     176                 :         struct request *next, *prev;
     177                 : 
     178                 :         struct event timeout_event;
     179                 : 
     180                 :         u16 trans_id;  /* the transaction id */
     181                 :         char request_appended;  /* true if the request pointer is data which follows this struct */
     182                 :         char transmit_me;  /* needs to be transmitted */
     183                 : };
     184                 : 
     185                 : #ifndef HAVE_STRUCT_IN6_ADDR
     186                 : struct in6_addr {
     187                 :         u8 s6_addr[16];
     188                 : };
     189                 : #endif
     190                 : 
     191                 : struct reply {
     192                 :         unsigned int type;
     193                 :         unsigned int have_answer;
     194                 :         union {
     195                 :                 struct {
     196                 :                         u32 addrcount;
     197                 :                         u32 addresses[MAX_ADDRS];
     198                 :                 } a;
     199                 :                 struct {
     200                 :                         u32 addrcount;
     201                 :                         struct in6_addr addresses[MAX_ADDRS];
     202                 :                 } aaaa;
     203                 :                 struct {
     204                 :                         char name[HOST_NAME_MAX];
     205                 :                 } ptr;
     206                 :         } data;
     207                 : };
     208                 : 
     209                 : struct nameserver {
     210                 :         int socket;  /* a connected UDP socket */
     211                 :         u32 address;
     212                 :         int failed_times;  /* number of times which we have given this server a chance */
     213                 :         int timedout;  /* number of times in a row a request has timed out */
     214                 :         struct event event;
     215                 :         /* these objects are kept in a circular list */
     216                 :         struct nameserver *next, *prev;
     217                 :         struct event timeout_event;  /* used to keep the timeout for */
     218                 :                                      /* when we next probe this server. */
     219                 :                                      /* Valid if state == 0 */
     220                 :         char state;  /* zero if we think that this server is down */
     221                 :         char choked;  /* true if we have an EAGAIN from this server's socket */
     222                 :         char write_waiting;  /* true if we are waiting for EV_WRITE events */
     223                 : };
     224                 : 
     225                 : static struct request *req_head = NULL, *req_waiting_head = NULL;
     226                 : static struct nameserver *server_head = NULL;
     227                 : 
     228                 : /* Represents a local port where we're listening for DNS requests. Right now, */
     229                 : /* only UDP is supported. */
     230                 : struct evdns_server_port {
     231                 :         int socket; /* socket we use to read queries and write replies. */
     232                 :         int refcnt; /* reference count. */
     233                 :         char choked; /* Are we currently blocked from writing? */
     234                 :         char closing; /* Are we trying to close this port, pending writes? */
     235                 :         evdns_request_callback_fn_type user_callback; /* Fn to handle requests */
     236                 :         void *user_data; /* Opaque pointer passed to user_callback */
     237                 :         struct event event; /* Read/write event */
     238                 :         /* circular list of replies that we want to write. */
     239                 :         struct server_request *pending_replies;
     240                 : };
     241                 : 
     242                 : /* Represents part of a reply being built.      (That is, a single RR.) */
     243                 : struct server_reply_item {
     244                 :         struct server_reply_item *next; /* next item in sequence. */
     245                 :         char *name; /* name part of the RR */
     246                 :         u16 type : 16; /* The RR type */
     247                 :         u16 class : 16; /* The RR class (usually CLASS_INET) */
     248                 :         u32 ttl; /* The RR TTL */
     249                 :         char is_name; /* True iff data is a label */
     250                 :         u16 datalen; /* Length of data; -1 if data is a label */
     251                 :         void *data; /* The contents of the RR */
     252                 : };
     253                 : 
     254                 : /* Represents a request that we've received as a DNS server, and holds */
     255                 : /* the components of the reply as we're constructing it. */
     256                 : struct server_request {
     257                 :         /* Pointers to the next and previous entries on the list of replies */
     258                 :         /* that we're waiting to write.  Only set if we have tried to respond */
     259                 :         /* and gotten EAGAIN. */
     260                 :         struct server_request *next_pending;
     261                 :         struct server_request *prev_pending;
     262                 : 
     263                 :         u16 trans_id; /* Transaction id. */
     264                 :         struct evdns_server_port *port; /* Which port received this request on? */
     265                 :         struct sockaddr_storage addr; /* Where to send the response */
     266                 :         socklen_t addrlen; /* length of addr */
     267                 : 
     268                 :         int n_answer; /* how many answer RRs have been set? */
     269                 :         int n_authority; /* how many authority RRs have been set? */
     270                 :         int n_additional; /* how many additional RRs have been set? */
     271                 : 
     272                 :         struct server_reply_item *answer; /* linked list of answer RRs */
     273                 :         struct server_reply_item *authority; /* linked list of authority RRs */
     274                 :         struct server_reply_item *additional; /* linked list of additional RRs */
     275                 : 
     276                 :         /* Constructed response.  Only set once we're ready to send a reply. */
     277                 :         /* Once this is set, the RR fields are cleared, and no more should be set. */
     278                 :         char *response;
     279                 :         size_t response_len;
     280                 : 
     281                 :         /* Caller-visible fields: flags, questions. */
     282                 :         struct evdns_server_request base;
     283                 : };
     284                 : 
     285                 : /* helper macro */
     286                 : #define OFFSET_OF(st, member) ((off_t) (((char*)&((st*)0)->member)-(char*)0))
     287                 : 
     288                 : /* Given a pointer to an evdns_server_request, get the corresponding */
     289                 : /* server_request. */
     290                 : #define TO_SERVER_REQUEST(base_ptr)                                                                             \
     291                 :         ((struct server_request*)                                                                                       \
     292                 :          (((char*)(base_ptr) - OFFSET_OF(struct server_request, base))))
     293                 : 
     294                 : /* The number of good nameservers that we have */
     295                 : static int global_good_nameservers = 0;
     296                 : 
     297                 : /* inflight requests are contained in the req_head list */
     298                 : /* and are actually going out across the network */
     299                 : static int global_requests_inflight = 0;
     300                 : /* requests which aren't inflight are in the waiting list */
     301                 : /* and are counted here */
     302                 : static int global_requests_waiting = 0;
     303                 : 
     304                 : static int global_max_requests_inflight = 64;
     305                 : 
     306                 : static struct timeval global_timeout = {5, 0};  /* 5 seconds */
     307                 : static int global_max_reissues = 1;  /* a reissue occurs when we get some errors from the server */
     308                 : static int global_max_retransmits = 3;  /* number of times we'll retransmit a request which timed out */
     309                 : /* number of timeouts in a row before we consider this server to be down */
     310                 : static int global_max_nameserver_timeout = 3;
     311                 : 
     312                 : /* These are the timeout values for nameservers. If we find a nameserver is down */
     313                 : /* we try to probe it at intervals as given below. Values are in seconds. */
     314                 : static const struct timeval global_nameserver_timeouts[] = {{10, 0}, {60, 0}, {300, 0}, {900, 0}, {3600, 0}};
     315                 : static const int global_nameserver_timeouts_length = sizeof(global_nameserver_timeouts)/sizeof(struct timeval);
     316                 : 
     317                 : static struct nameserver *nameserver_pick(void);
     318                 : static void evdns_request_insert(struct request *req, struct request **head);
     319                 : static void nameserver_ready_callback(int fd, short events, void *arg);
     320                 : static int evdns_transmit(void);
     321                 : static int evdns_request_transmit(struct request *req);
     322                 : static void nameserver_send_probe(struct nameserver *const ns);
     323                 : static void search_request_finished(struct request *const);
     324                 : static int search_try_next(struct request *const req);
     325                 : static int search_request_new(int type, const char *const name, int flags, evdns_callback_type user_callback, void *user_arg);
     326                 : static void evdns_requests_pump_waiting_queue(void);
     327                 : static u16 transaction_id_pick(void);
     328                 : static struct request *request_new(int type, const char *name, int flags, evdns_callback_type callback, void *ptr);
     329                 : static void request_submit(struct request *const req);
     330                 : 
     331                 : static int server_request_free(struct server_request *req);
     332                 : static void server_request_free_answers(struct server_request *req);
     333                 : static void server_port_free(struct evdns_server_port *port);
     334                 : static void server_port_ready_callback(int fd, short events, void *arg);
     335                 : 
     336                 : static int strtoint(const char *const str);
     337                 : 
     338                 : #ifdef WIN32
     339                 : static int
     340                 : last_error(int sock)
     341                 : {
     342                 :         int optval, optvallen=sizeof(optval);
     343                 :         int err = WSAGetLastError();
     344                 :         if (err == WSAEWOULDBLOCK && sock >= 0) {
     345                 :                 if (getsockopt(sock, SOL_SOCKET, SO_ERROR, (void*)&optval,
     346                 :                                &optvallen))
     347                 :                         return err;
     348                 :                 if (optval)
     349                 :                         return optval;
     350                 :         }
     351                 :         return err;
     352                 : 
     353                 : }
     354                 : static int
     355                 : error_is_eagain(int err)
     356                 : {
     357                 :         return err == EAGAIN || err == WSAEWOULDBLOCK;
     358                 : }
     359                 : static int
     360                 : inet_aton(const char *c, struct in_addr *addr)
     361                 : {
     362                 :         ev_uint32_t r;
     363                 :         if (strcmp(c, "255.255.255.255") == 0) {
     364                 :                 addr->s_addr = 0xffffffffu;
     365                 :         } else {
     366                 :                 r = inet_addr(c);
     367                 :                 if (r == INADDR_NONE)
     368                 :                         return 0;
     369                 :                 addr->s_addr = r;
     370                 :         }
     371                 :         return 1;
     372                 : }
     373                 : #else
     374                 : #define last_error(sock) (errno)
     375                 : #define error_is_eagain(err) ((err) == EAGAIN)
     376                 : #endif
     377                 : #define CLOSE_SOCKET(s) EVUTIL_CLOSESOCKET(s)
     378                 : 
     379                 : #define ISSPACE(c) isspace((int)(unsigned char)(c))
     380                 : #define ISDIGIT(c) isdigit((int)(unsigned char)(c))
     381                 : 
     382                 : static const char *
     383               0 : debug_ntoa(u32 address)
     384                 : {
     385                 :         static char buf[32];
     386               0 :         u32 a = ntohl(address);
     387               0 :         evutil_snprintf(buf, sizeof(buf), "%d.%d.%d.%d",
     388               0 :                       (int)(u8)((a>>24)&0xff),
     389               0 :                       (int)(u8)((a>>16)&0xff),
     390               0 :                       (int)(u8)((a>>8 )&0xff),
     391               0 :                       (int)(u8)((a    )&0xff));
     392               0 :         return buf;
     393                 : }
     394                 : 
     395                 : static evdns_debug_log_fn_type evdns_log_fn = NULL;
     396                 : 
     397                 : void
     398               0 : evdns_set_log_fn(evdns_debug_log_fn_type fn)
     399                 : {
     400               0 :   evdns_log_fn = fn;
     401               0 : }
     402                 : 
     403                 : #ifdef __GNUC__
     404                 : #define EVDNS_LOG_CHECK  __attribute__ ((format(printf, 2, 3)))
     405                 : #else
     406                 : #define EVDNS_LOG_CHECK
     407                 : #endif
     408                 : 
     409                 : static void _evdns_log(int warn, const char *fmt, ...) EVDNS_LOG_CHECK;
     410                 : static void
     411               0 : _evdns_log(int warn, const char *fmt, ...)
     412                 : {
     413                 :   va_list args;
     414                 :   static char buf[512];
     415               0 :   if (!evdns_log_fn)
     416               0 :     return;
     417               0 :   va_start(args,fmt);
     418               0 :   evutil_vsnprintf(buf, sizeof(buf), fmt, args);
     419               0 :   buf[sizeof(buf)-1] = '\0';
     420               0 :   evdns_log_fn(warn, buf);
     421               0 :   va_end(args);
     422                 : }
     423                 : 
     424                 : #define log _evdns_log
     425                 : 
     426                 : /* This walks the list of inflight requests to find the */
     427                 : /* one with a matching transaction id. Returns NULL on */
     428                 : /* failure */
     429                 : static struct request *
     430               0 : request_find_from_trans_id(u16 trans_id) {
     431               0 :         struct request *req = req_head, *const started_at = req_head;
     432                 : 
     433               0 :         if (req) {
     434                 :                 do {
     435               0 :                         if (req->trans_id == trans_id) return req;
     436               0 :                         req = req->next;
     437               0 :                 } while (req != started_at);
     438                 :         }
     439                 : 
     440               0 :         return NULL;
     441                 : }
     442                 : 
     443                 : /* a libevent callback function which is called when a nameserver */
     444                 : /* has gone down and we want to test if it has came back to life yet */
     445                 : static void
     446               0 : nameserver_prod_callback(int fd, short events, void *arg) {
     447               0 :         struct nameserver *const ns = (struct nameserver *) arg;
     448                 :         (void)fd;
     449                 :         (void)events;
     450                 : 
     451               0 :         nameserver_send_probe(ns);
     452               0 : }
     453                 : 
     454                 : /* a libevent callback which is called when a nameserver probe (to see if */
     455                 : /* it has come back to life) times out. We increment the count of failed_times */
     456                 : /* and wait longer to send the next probe packet. */
     457                 : static void
     458               0 : nameserver_probe_failed(struct nameserver *const ns) {
     459                 :         const struct timeval * timeout;
     460               0 :         (void) evtimer_del(&ns->timeout_event);
     461               0 :         if (ns->state == 1) {
     462                 :                 /* This can happen if the nameserver acts in a way which makes us mark */
     463                 :                 /* it as bad and then starts sending good replies. */
     464               0 :                 return;
     465                 :         }
     466                 : 
     467               0 :         timeout =
     468               0 :           &global_nameserver_timeouts[MIN(ns->failed_times,
     469                 :                                           global_nameserver_timeouts_length - 1)];
     470               0 :         ns->failed_times++;
     471                 : 
     472               0 :         evtimer_set(&ns->timeout_event, nameserver_prod_callback, ns);
     473               0 :         if (evtimer_add(&ns->timeout_event, (struct timeval *) timeout) < 0) {
     474               0 :           log(EVDNS_LOG_WARN,
     475                 :               "Error from libevent when adding timer event for %s",
     476                 :               debug_ntoa(ns->address));
     477                 :           /* ???? Do more? */
     478                 :         }
     479                 : }
     480                 : 
     481                 : /* called when a nameserver has been deemed to have failed. For example, too */
     482                 : /* many packets have timed out etc */
     483                 : static void
     484               0 : nameserver_failed(struct nameserver *const ns, const char *msg) {
     485                 :         struct request *req, *started_at;
     486                 :         /* if this nameserver has already been marked as failed */
     487                 :         /* then don't do anything */
     488               0 :         if (!ns->state) return;
     489                 : 
     490               0 :         log(EVDNS_LOG_WARN, "Nameserver %s has failed: %s",
     491                 :             debug_ntoa(ns->address), msg);
     492               0 :         global_good_nameservers--;
     493               0 :         assert(global_good_nameservers >= 0);
     494               0 :         if (global_good_nameservers == 0) {
     495               0 :                 log(EVDNS_LOG_WARN, "All nameservers have failed");
     496                 :         }
     497                 : 
     498               0 :         ns->state = 0;
     499               0 :         ns->failed_times = 1;
     500                 : 
     501               0 :         evtimer_set(&ns->timeout_event, nameserver_prod_callback, ns);
     502               0 :         if (evtimer_add(&ns->timeout_event, (struct timeval *) &global_nameserver_timeouts[0]) < 0) {
     503               0 :                 log(EVDNS_LOG_WARN,
     504                 :                     "Error from libevent when adding timer event for %s",
     505                 :                     debug_ntoa(ns->address));
     506                 :                 /* ???? Do more? */
     507                 :         }
     508                 : 
     509                 :         /* walk the list of inflight requests to see if any can be reassigned to */
     510                 :         /* a different server. Requests in the waiting queue don't have a */
     511                 :         /* nameserver assigned yet */
     512                 : 
     513                 :         /* if we don't have *any* good nameservers then there's no point */
     514                 :         /* trying to reassign requests to one */
     515               0 :         if (!global_good_nameservers) return;
     516                 : 
     517               0 :         req = req_head;
     518               0 :         started_at = req_head;
     519               0 :         if (req) {
     520                 :                 do {
     521               0 :                         if (req->tx_count == 0 && req->ns == ns) {
     522                 :                                 /* still waiting to go out, can be moved */
     523                 :                                 /* to another server */
     524               0 :                                 req->ns = nameserver_pick();
     525                 :                         }
     526               0 :                         req = req->next;
     527               0 :                 } while (req != started_at);
     528                 :         }
     529                 : }
     530                 : 
     531                 : static void
     532               0 : nameserver_up(struct nameserver *const ns) {
     533               0 :         if (ns->state) return;
     534               0 :         log(EVDNS_LOG_WARN, "Nameserver %s is back up",
     535                 :             debug_ntoa(ns->address));
     536               0 :         evtimer_del(&ns->timeout_event);
     537               0 :         ns->state = 1;
     538               0 :         ns->failed_times = 0;
     539               0 :         ns->timedout = 0;
     540               0 :         global_good_nameservers++;
     541                 : }
     542                 : 
     543                 : static void
     544               0 : request_trans_id_set(struct request *const req, const u16 trans_id) {
     545               0 :         req->trans_id = trans_id;
     546               0 :         *((u16 *) req->request) = htons(trans_id);
     547               0 : }
     548                 : 
     549                 : /* Called to remove a request from a list and dealloc it. */
     550                 : /* head is a pointer to the head of the list it should be */
     551                 : /* removed from or NULL if the request isn't in a list. */
     552                 : static void
     553               0 : request_finished(struct request *const req, struct request **head) {
     554               0 :         if (head) {
     555               0 :                 if (req->next == req) {
     556                 :                         /* only item in the list */
     557               0 :                         *head = NULL;
     558                 :                 } else {
     559               0 :                         req->next->prev = req->prev;
     560               0 :                         req->prev->next = req->next;
     561               0 :                         if (*head == req) *head = req->next;
     562                 :                 }
     563                 :         }
     564                 : 
     565               0 :         log(EVDNS_LOG_DEBUG, "Removing timeout for request %lx",
     566                 :             (unsigned long) req);
     567               0 :         evtimer_del(&req->timeout_event);
     568                 : 
     569               0 :         search_request_finished(req);
     570               0 :         global_requests_inflight--;
     571                 : 
     572               0 :         if (!req->request_appended) {
     573                 :                 /* need to free the request data on it's own */
     574               0 :                 free(req->request);
     575                 :         } else {
     576                 :                 /* the request data is appended onto the header */
     577                 :                 /* so everything gets free()ed when we: */
     578                 :         }
     579                 : 
     580               0 :         free(req);
     581                 : 
     582               0 :         evdns_requests_pump_waiting_queue();
     583               0 : }
     584                 : 
     585                 : /* This is called when a server returns a funny error code. */
     586                 : /* We try the request again with another server. */
     587                 : /* */
     588                 : /* return: */
     589                 : /*   0 ok */
     590                 : /*   1 failed/reissue is pointless */
     591                 : static int
     592               0 : request_reissue(struct request *req) {
     593               0 :         const struct nameserver *const last_ns = req->ns;
     594                 :         /* the last nameserver should have been marked as failing */
     595                 :         /* by the caller of this function, therefore pick will try */
     596                 :         /* not to return it */
     597               0 :         req->ns = nameserver_pick();
     598               0 :         if (req->ns == last_ns) {
     599                 :                 /* ... but pick did return it */
     600                 :                 /* not a lot of point in trying again with the */
     601                 :                 /* same server */
     602               0 :                 return 1;
     603                 :         }
     604                 : 
     605               0 :         req->reissue_count++;
     606               0 :         req->tx_count = 0;
     607               0 :         req->transmit_me = 1;
     608                 : 
     609               0 :         return 0;
     610                 : }
     611                 : 
     612                 : /* this function looks for space on the inflight queue and promotes */
     613                 : /* requests from the waiting queue if it can. */
     614                 : static void
     615               0 : evdns_requests_pump_waiting_queue(void) {
     616               0 :         while (global_requests_inflight < global_max_requests_inflight &&
     617                 :             global_requests_waiting) {
     618                 :                 struct request *req;
     619                 :                 /* move a request from the waiting queue to the inflight queue */
     620               0 :                 assert(req_waiting_head);
     621               0 :                 if (req_waiting_head->next == req_waiting_head) {
     622                 :                         /* only one item in the queue */
     623               0 :                         req = req_waiting_head;
     624               0 :                         req_waiting_head = NULL;
     625                 :                 } else {
     626               0 :                         req = req_waiting_head;
     627               0 :                         req->next->prev = req->prev;
     628               0 :                         req->prev->next = req->next;
     629               0 :                         req_waiting_head = req->next;
     630                 :                 }
     631                 : 
     632               0 :                 global_requests_waiting--;
     633               0 :                 global_requests_inflight++;
     634                 : 
     635               0 :                 req->ns = nameserver_pick();
     636               0 :                 request_trans_id_set(req, transaction_id_pick());
     637                 : 
     638               0 :                 evdns_request_insert(req, &req_head);
     639               0 :                 evdns_request_transmit(req);
     640               0 :                 evdns_transmit();
     641                 :         }
     642               0 : }
     643                 : 
     644                 : static void
     645               0 : reply_callback(struct request *const req, u32 ttl, u32 err, struct reply *reply) {
     646               0 :         switch (req->request_type) {
     647                 :         case TYPE_A:
     648               0 :                 if (reply)
     649               0 :                         req->user_callback(DNS_ERR_NONE, DNS_IPv4_A,
     650               0 :                                                            reply->data.a.addrcount, ttl,
     651               0 :                                                  reply->data.a.addresses,
     652                 :                                                            req->user_pointer);
     653                 :                 else
     654               0 :                         req->user_callback(err, 0, 0, 0, NULL, req->user_pointer);
     655               0 :                 return;
     656                 :         case TYPE_PTR:
     657               0 :                 if (reply) {
     658               0 :                         char *name = reply->data.ptr.name;
     659               0 :                         req->user_callback(DNS_ERR_NONE, DNS_PTR, 1, ttl,
     660                 :                                                            &name, req->user_pointer);
     661                 :                 } else {
     662               0 :                         req->user_callback(err, 0, 0, 0, NULL,
     663                 :                                                            req->user_pointer);
     664                 :                 }
     665               0 :                 return;
     666                 :         case TYPE_AAAA:
     667               0 :                 if (reply)
     668               0 :                         req->user_callback(DNS_ERR_NONE, DNS_IPv6_AAAA,
     669               0 :                                                            reply->data.aaaa.addrcount, ttl,
     670               0 :                                                            reply->data.aaaa.addresses,
     671                 :                                                            req->user_pointer);
     672                 :                 else
     673               0 :                         req->user_callback(err, 0, 0, 0, NULL, req->user_pointer);
     674               0 :                 return;
     675                 :         }
     676               0 :         assert(0);
     677                 : }
     678                 : 
     679                 : /* this processes a parsed reply packet */
     680                 : static void
     681               0 : reply_handle(struct request *const req, u16 flags, u32 ttl, struct reply *reply) {
     682                 :         int error;
     683                 :         static const int error_codes[] = {DNS_ERR_FORMAT, DNS_ERR_SERVERFAILED, DNS_ERR_NOTEXIST, DNS_ERR_NOTIMPL, DNS_ERR_REFUSED};
     684                 : 
     685               0 :         if (flags & 0x020f || !reply || !reply->have_answer) {
     686                 :                 /* there was an error */
     687               0 :                 if (flags & 0x0200) {
     688               0 :                         error = DNS_ERR_TRUNCATED;
     689                 :                 } else {
     690               0 :                         u16 error_code = (flags & 0x000f) - 1;
     691               0 :                         if (error_code > 4) {
     692               0 :                                 error = DNS_ERR_UNKNOWN;
     693                 :                         } else {
     694               0 :                                 error = error_codes[error_code];
     695                 :                         }
     696                 :                 }
     697                 : 
     698               0 :                 switch(error) {
     699                 :                 case DNS_ERR_NOTIMPL:
     700                 :                 case DNS_ERR_REFUSED:
     701                 :                         /* we regard these errors as marking a bad nameserver */
     702               0 :                         if (req->reissue_count < global_max_reissues) {
     703                 :                                 char msg[64];
     704               0 :                                 evutil_snprintf(msg, sizeof(msg),
     705                 :                                     "Bad response %d (%s)",
     706                 :                                          error, evdns_err_to_string(error));
     707               0 :                                 nameserver_failed(req->ns, msg);
     708               0 :                                 if (!request_reissue(req)) return;
     709                 :                         }
     710               0 :                         break;
     711                 :                 case DNS_ERR_SERVERFAILED:
     712                 :                         /* rcode 2 (servfailed) sometimes means "we are broken" and
     713                 :                          * sometimes (with some binds) means "that request was very
     714                 :                          * confusing."  Treat this as a timeout, not a failure. 
     715                 :                          */
     716               0 :                         log(EVDNS_LOG_DEBUG, "Got a SERVERFAILED from nameserver %s; "
     717                 :                                 "will allow the request to time out.",
     718               0 :                                 debug_ntoa(req->ns->address));
     719               0 :                         break;
     720                 :                 default:
     721                 :                         /* we got a good reply from the nameserver */
     722               0 :                         nameserver_up(req->ns);
     723                 :                 }
     724                 : 
     725               0 :                 if (req->search_state && req->request_type != TYPE_PTR) {
     726                 :                         /* if we have a list of domains to search in, try the next one */
     727               0 :                         if (!search_try_next(req)) {
     728                 :                                 /* a new request was issued so this request is finished and */
     729                 :                                 /* the user callback will be made when that request (or a */
     730                 :                                 /* child of it) finishes. */
     731               0 :                                 request_finished(req, &req_head);
     732               0 :                                 return;
     733                 :                         }
     734                 :                 }
     735                 : 
     736                 :                 /* all else failed. Pass the failure up */
     737               0 :                 reply_callback(req, 0, error, NULL);
     738               0 :                 request_finished(req, &req_head);
     739                 :         } else {
     740                 :                 /* all ok, tell the user */
     741               0 :                 reply_callback(req, ttl, 0, reply);
     742               0 :                 nameserver_up(req->ns);
     743               0 :                 request_finished(req, &req_head);
     744                 :         }
     745                 : }
     746                 : 
     747                 : static int
     748               0 : name_parse(u8 *packet, int length, int *idx, char *name_out, int name_out_len) {
     749               0 :         int name_end = -1;
     750               0 :         int j = *idx;
     751               0 :         int ptr_count = 0;
     752                 : #define GET32(x) do { if (j + 4 > length) goto err; memcpy(&_t32, packet + j, 4); j += 4; x = ntohl(_t32); } while(0)
     753                 : #define GET16(x) do { if (j + 2 > length) goto err; memcpy(&_t, packet + j, 2); j += 2; x = ntohs(_t); } while(0)
     754                 : #define GET8(x) do { if (j >= length) goto err; x = packet[j++]; } while(0)
     755                 : 
     756               0 :         char *cp = name_out;
     757               0 :         const char *const end = name_out + name_out_len;
     758                 : 
     759                 :         /* Normally, names are a series of length prefixed strings terminated */
     760                 :         /* with a length of 0 (the lengths are u8's < 63). */
     761                 :         /* However, the length can start with a pair of 1 bits and that */
     762                 :         /* means that the next 14 bits are a pointer within the current */
     763                 :         /* packet. */
     764                 : 
     765                 :         for(;;) {
     766                 :                 u8 label_len;
     767               0 :                 if (j >= length) return -1;
     768               0 :                 GET8(label_len);
     769               0 :                 if (!label_len) break;
     770               0 :                 if (label_len & 0xc0) {
     771                 :                         u8 ptr_low;
     772               0 :                         GET8(ptr_low);
     773               0 :                         if (name_end < 0) name_end = j;
     774               0 :                         j = (((int)label_len & 0x3f) << 8) + ptr_low;
     775                 :                         /* Make sure that the target offset is in-bounds. */
     776               0 :                         if (j < 0 || j >= length) return -1;
     777                 :                         /* If we've jumped more times than there are characters in the
     778                 :                          * message, we must have a loop. */
     779               0 :                         if (++ptr_count > length) return -1;
     780               0 :                         continue;
     781                 :                 }
     782               0 :                 if (label_len > 63) return -1;
     783               0 :                 if (cp != name_out) {
     784               0 :                         if (cp + 1 >= end) return -1;
     785               0 :                         *cp++ = '.';
     786                 :                 }
     787               0 :                 if (cp + label_len >= end) return -1;
     788               0 :                 memcpy(cp, packet + j, label_len);
     789               0 :                 cp += label_len;
     790               0 :                 j += label_len;
     791               0 :         }
     792               0 :         if (cp >= end) return -1;
     793               0 :         *cp = '\0';
     794               0 :         if (name_end < 0)
     795               0 :                 *idx = j;
     796                 :         else
     797               0 :                 *idx = name_end;
     798               0 :         return 0;
     799                 :  err:
     800               0 :         return -1;
     801                 : }
     802                 : 
     803                 : /* parses a raw request from a nameserver */
     804                 : static int
     805               0 : reply_parse(u8 *packet, int length) {
     806               0 :         int j = 0;  /* index into packet */
     807                 :         u16 _t;  /* used by the macros */
     808                 :         u32 _t32;  /* used by the macros */
     809                 :         char tmp_name[256]; /* used by the macros */
     810                 : 
     811                 :         u16 trans_id, questions, answers, authority, additional, datalength;
     812               0 :         u16 flags = 0;
     813               0 :         u32 ttl, ttl_r = 0xffffffff;
     814                 :         struct reply reply;
     815               0 :         struct request *req = NULL;
     816                 :         unsigned int i;
     817                 : 
     818               0 :         GET16(trans_id);
     819               0 :         GET16(flags);
     820               0 :         GET16(questions);
     821               0 :         GET16(answers);
     822               0 :         GET16(authority);
     823               0 :         GET16(additional);
     824                 :         (void) authority; /* suppress "unused variable" warnings. */
     825                 :         (void) additional; /* suppress "unused variable" warnings. */
     826                 : 
     827               0 :         req = request_find_from_trans_id(trans_id);
     828               0 :         if (!req) return -1;
     829                 : 
     830               0 :         memset(&reply, 0, sizeof(reply));
     831                 : 
     832                 :         /* If it's not an answer, it doesn't correspond to any request. */
     833               0 :         if (!(flags & 0x8000)) return -1;  /* must be an answer */
     834               0 :         if (flags & 0x020f) {
     835                 :                 /* there was an error */
     836               0 :                 goto err;
     837                 :         }
     838                 :         /* if (!answers) return; */  /* must have an answer of some form */
     839                 : 
     840                 :         /* This macro skips a name in the DNS reply. */
     841                 : #define SKIP_NAME \
     842                 :         do { tmp_name[0] = '\0';                                        \
     843                 :                 if (name_parse(packet, length, &j, tmp_name, sizeof(tmp_name))<0) \
     844                 :                         goto err;                                                                                                       \
     845                 :         } while(0);
     846                 : 
     847               0 :         reply.type = req->request_type;
     848                 : 
     849                 :         /* skip over each question in the reply */
     850               0 :         for (i = 0; i < questions; ++i) {
     851                 :                 /* the question looks like
     852                 :                  *   <label:name><u16:type><u16:class>
     853                 :                  */
     854               0 :                 SKIP_NAME;
     855               0 :                 j += 4;
     856               0 :                 if (j > length) goto err;
     857                 :         }
     858                 : 
     859                 :         /* now we have the answer section which looks like
     860                 :          * <label:name><u16:type><u16:class><u32:ttl><u16:len><data...>
     861                 :          */
     862                 : 
     863               0 :         for (i = 0; i < answers; ++i) {
     864                 :                 u16 type, class;
     865                 : 
     866               0 :                 SKIP_NAME;
     867               0 :                 GET16(type);
     868               0 :                 GET16(class);
     869               0 :                 GET32(ttl);
     870               0 :                 GET16(datalength);
     871                 : 
     872               0 :                 if (type == TYPE_A && class == CLASS_INET) {
     873                 :                         int addrcount, addrtocopy;
     874               0 :                         if (req->request_type != TYPE_A) {
     875               0 :                                 j += datalength; continue;
     876                 :                         }
     877               0 :                         if ((datalength & 3) != 0) /* not an even number of As. */
     878               0 :                             goto err;
     879               0 :                         addrcount = datalength >> 2;
     880               0 :                         addrtocopy = MIN(MAX_ADDRS - reply.data.a.addrcount, (unsigned)addrcount);
     881                 : 
     882               0 :                         ttl_r = MIN(ttl_r, ttl);
     883                 :                         /* we only bother with the first four addresses. */
     884               0 :                         if (j + 4*addrtocopy > length) goto err;
     885               0 :                         memcpy(&reply.data.a.addresses[reply.data.a.addrcount],
     886               0 :                                    packet + j, 4*addrtocopy);
     887               0 :                         j += 4*addrtocopy;
     888               0 :                         reply.data.a.addrcount += addrtocopy;
     889               0 :                         reply.have_answer = 1;
     890               0 :                         if (reply.data.a.addrcount == MAX_ADDRS) break;
     891               0 :                 } else if (type == TYPE_PTR && class == CLASS_INET) {
     892               0 :                         if (req->request_type != TYPE_PTR) {
     893               0 :                                 j += datalength; continue;
     894                 :                         }
     895               0 :                         if (name_parse(packet, length, &j, reply.data.ptr.name,
     896                 :                                                    sizeof(reply.data.ptr.name))<0)
     897               0 :                                 goto err;
     898               0 :                         ttl_r = MIN(ttl_r, ttl);
     899               0 :                         reply.have_answer = 1;
     900               0 :                         break;
     901               0 :                 } else if (type == TYPE_AAAA && class == CLASS_INET) {
     902                 :                         int addrcount, addrtocopy;
     903               0 :                         if (req->request_type != TYPE_AAAA) {
     904               0 :                                 j += datalength; continue;
     905                 :                         }
     906               0 :                         if ((datalength & 15) != 0) /* not an even number of AAAAs. */
     907               0 :                                 goto err;
     908               0 :                         addrcount = datalength >> 4;  /* each address is 16 bytes long */
     909               0 :                         addrtocopy = MIN(MAX_ADDRS - reply.data.aaaa.addrcount, (unsigned)addrcount);
     910               0 :                         ttl_r = MIN(ttl_r, ttl);
     911                 : 
     912                 :                         /* we only bother with the first four addresses. */
     913               0 :                         if (j + 16*addrtocopy > length) goto err;
     914               0 :                         memcpy(&reply.data.aaaa.addresses[reply.data.aaaa.addrcount],
     915               0 :                                    packet + j, 16*addrtocopy);
     916               0 :                         reply.data.aaaa.addrcount += addrtocopy;
     917               0 :                         j += 16*addrtocopy;
     918               0 :                         reply.have_answer = 1;
     919               0 :                         if (reply.data.aaaa.addrcount == MAX_ADDRS) break;
     920                 :                 } else {
     921                 :                         /* skip over any other type of resource */
     922               0 :                         j += datalength;
     923                 :                 }
     924                 :         }
     925                 : 
     926               0 :         reply_handle(req, flags, ttl_r, &reply);
     927               0 :         return 0;
     928                 :  err:
     929               0 :         if (req)
     930               0 :                 reply_handle(req, flags, 0, NULL);
     931               0 :         return -1;
     932                 : }
     933                 : 
     934                 : /* Parse a raw request (packet,length) sent to a nameserver port (port) from */
     935                 : /* a DNS client (addr,addrlen), and if it's well-formed, call the corresponding */
     936                 : /* callback. */
     937                 : static int
     938               0 : request_parse(u8 *packet, int length, struct evdns_server_port *port, struct sockaddr *addr, socklen_t addrlen)
     939                 : {
     940               0 :         int j = 0;      /* index into packet */
     941                 :         u16 _t;  /* used by the macros */
     942                 :         char tmp_name[256]; /* used by the macros */
     943                 : 
     944                 :         int i;
     945                 :         u16 trans_id, flags, questions, answers, authority, additional;
     946               0 :         struct server_request *server_req = NULL;
     947                 : 
     948                 :         /* Get the header fields */
     949               0 :         GET16(trans_id);
     950               0 :         GET16(flags);
     951               0 :         GET16(questions);
     952               0 :         GET16(answers);
     953               0 :         GET16(authority);
     954               0 :         GET16(additional);
     955                 : 
     956               0 :         if (flags & 0x8000) return -1; /* Must not be an answer. */
     957               0 :         flags &= 0x0110; /* Only RD and CD get preserved. */
     958                 : 
     959               0 :         server_req = malloc(sizeof(struct server_request));
     960               0 :         if (server_req == NULL) return -1;
     961               0 :         memset(server_req, 0, sizeof(struct server_request));
     962                 : 
     963               0 :         server_req->trans_id = trans_id;
     964               0 :         memcpy(&server_req->addr, addr, addrlen);
     965               0 :         server_req->addrlen = addrlen;
     966                 : 
     967               0 :         server_req->base.flags = flags;
     968               0 :         server_req->base.nquestions = 0;
     969               0 :         server_req->base.questions = malloc(sizeof(struct evdns_server_question *) * questions);
     970               0 :         if (server_req->base.questions == NULL)
     971               0 :                 goto err;
     972                 : 
     973               0 :         for (i = 0; i < questions; ++i) {
     974                 :                 u16 type, class;
     975                 :                 struct evdns_server_question *q;
     976                 :                 int namelen;
     977               0 :                 if (name_parse(packet, length, &j, tmp_name, sizeof(tmp_name))<0)
     978               0 :                         goto err;
     979               0 :                 GET16(type);
     980               0 :                 GET16(class);
     981               0 :                 namelen = strlen(tmp_name);
     982               0 :                 q = malloc(sizeof(struct evdns_server_question) + namelen);
     983               0 :                 if (!q)
     984               0 :                         goto err;
     985               0 :                 q->type = type;
     986               0 :                 q->dns_question_class = class;
     987               0 :                 memcpy(q->name, tmp_name, namelen+1);
     988               0 :                 server_req->base.questions[server_req->base.nquestions++] = q;
     989                 :         }
     990                 : 
     991                 :         /* Ignore answers, authority, and additional. */
     992                 : 
     993               0 :         server_req->port = port;
     994               0 :         port->refcnt++;
     995                 : 
     996                 :         /* Only standard queries are supported. */
     997               0 :         if (flags & 0x7800) {
     998               0 :                 evdns_server_request_respond(&(server_req->base), DNS_ERR_NOTIMPL);
     999               0 :                 return -1;
    1000                 :         }
    1001                 : 
    1002               0 :         port->user_callback(&(server_req->base), port->user_data);
    1003                 : 
    1004               0 :         return 0;
    1005                 : err:
    1006               0 :         if (server_req) {
    1007               0 :                 if (server_req->base.questions) {
    1008               0 :                         for (i = 0; i < server_req->base.nquestions; ++i)
    1009               0 :                                 free(server_req->base.questions[i]);
    1010               0 :                         free(server_req->base.questions);
    1011                 :                 }
    1012               0 :                 free(server_req);
    1013                 :         }
    1014               0 :         return -1;
    1015                 : 
    1016                 : #undef SKIP_NAME
    1017                 : #undef GET32
    1018                 : #undef GET16
    1019                 : #undef GET8
    1020                 : }
    1021                 : 
    1022                 : static u16
    1023               0 : default_transaction_id_fn(void)
    1024                 : {
    1025                 :         u16 trans_id;
    1026                 : #ifdef DNS_USE_CPU_CLOCK_FOR_ID
    1027                 :         struct timespec ts;
    1028                 :         static int clkid = -1;
    1029               0 :         if (clkid == -1) {
    1030               0 :                 clkid = CLOCK_REALTIME;
    1031                 : #ifdef CLOCK_MONOTONIC
    1032               0 :                 if (clock_gettime(CLOCK_MONOTONIC, &ts) != -1)
    1033               0 :                         clkid = CLOCK_MONOTONIC;
    1034                 : #endif
    1035                 :         }
    1036               0 :         if (clock_gettime(clkid, &ts) == -1)
    1037               0 :                 event_err(1, "clock_gettime");
    1038               0 :         trans_id = ts.tv_nsec & 0xffff;
    1039                 : #endif
    1040                 : 
    1041                 : #ifdef DNS_USE_FTIME_FOR_ID
    1042                 :         struct _timeb tb;
    1043                 :         _ftime(&tb);
    1044                 :         trans_id = tb.millitm & 0xffff;
    1045                 : #endif
    1046                 : 
    1047                 : #ifdef DNS_USE_GETTIMEOFDAY_FOR_ID
    1048                 :         struct timeval tv;
    1049                 :         evutil_gettimeofday(&tv, NULL);
    1050                 :         trans_id = tv.tv_usec & 0xffff;
    1051                 : #endif
    1052                 : 
    1053                 : #ifdef DNS_USE_OPENSSL_FOR_ID
    1054                 :         if (RAND_pseudo_bytes((u8 *) &trans_id, 2) == -1) {
    1055                 :                 /* in the case that the RAND call fails we back */
    1056                 :                 /* down to using gettimeofday. */
    1057                 :                 /*
    1058                 :                   struct timeval tv;
    1059                 :                   evutil_gettimeofday(&tv, NULL);
    1060                 :                   trans_id = tv.tv_usec & 0xffff;
    1061                 :                 */
    1062                 :                 abort();
    1063                 :         }
    1064                 : #endif
    1065               0 :         return trans_id;
    1066                 : }
    1067                 : 
    1068                 : static ev_uint16_t (*trans_id_function)(void) = default_transaction_id_fn;
    1069                 : 
    1070                 : void
    1071               0 : evdns_set_transaction_id_fn(ev_uint16_t (*fn)(void))
    1072                 : {
    1073               0 :         if (fn)
    1074               0 :                 trans_id_function = fn;
    1075                 :         else
    1076               0 :                 trans_id_function = default_transaction_id_fn;
    1077               0 : }
    1078                 : 
    1079                 : /* Try to choose a strong transaction id which isn't already in flight */
    1080                 : static u16
    1081               0 : transaction_id_pick(void) {
    1082                 :         for (;;) {
    1083               0 :                 const struct request *req = req_head, *started_at;
    1084               0 :                 u16 trans_id = trans_id_function();
    1085                 : 
    1086               0 :                 if (trans_id == 0xffff) continue;
    1087                 :                 /* now check to see if that id is already inflight */
    1088               0 :                 req = started_at = req_head;
    1089               0 :                 if (req) {
    1090                 :                         do {
    1091               0 :                                 if (req->trans_id == trans_id) break;
    1092               0 :                                 req = req->next;
    1093               0 :                         } while (req != started_at);
    1094                 :                 }
    1095                 :                 /* we didn't find it, so this is a good id */
    1096               0 :                 if (req == started_at) return trans_id;
    1097               0 :         }
    1098                 : }
    1099                 : 
    1100                 : /* choose a namesever to use. This function will try to ignore */
    1101                 : /* nameservers which we think are down and load balance across the rest */
    1102                 : /* by updating the server_head global each time. */
    1103                 : static struct nameserver *
    1104               0 : nameserver_pick(void) {
    1105               0 :         struct nameserver *started_at = server_head, *picked;
    1106               0 :         if (!server_head) return NULL;
    1107                 : 
    1108                 :         /* if we don't have any good nameservers then there's no */
    1109                 :         /* point in trying to find one. */
    1110               0 :         if (!global_good_nameservers) {
    1111               0 :                 server_head = server_head->next;
    1112               0 :                 return server_head;
    1113                 :         }
    1114                 : 
    1115                 :         /* remember that nameservers are in a circular list */
    1116                 :         for (;;) {
    1117               0 :                 if (server_head->state) {
    1118                 :                         /* we think this server is currently good */
    1119               0 :                         picked = server_head;
    1120               0 :                         server_head = server_head->next;
    1121               0 :                         return picked;
    1122                 :                 }
    1123                 : 
    1124               0 :                 server_head = server_head->next;
    1125               0 :                 if (server_head == started_at) {
    1126                 :                         /* all the nameservers seem to be down */
    1127                 :                         /* so we just return this one and hope for the */
    1128                 :                         /* best */
    1129               0 :                         assert(global_good_nameservers == 0);
    1130               0 :                         picked = server_head;
    1131               0 :                         server_head = server_head->next;
    1132               0 :                         return picked;
    1133                 :                 }
    1134               0 :         }
    1135                 : }
    1136                 : 
    1137                 : /* this is called when a namesever socket is ready for reading */
    1138                 : static void
    1139               0 : nameserver_read(struct nameserver *ns) {
    1140                 :         u8 packet[1500];
    1141                 : 
    1142                 :         for (;;) {
    1143               0 :                 const int r = recv(ns->socket, packet, sizeof(packet), 0);
    1144               0 :                 if (r < 0) {
    1145               0 :                         int err = last_error(ns->socket);
    1146               0 :                         if (error_is_eagain(err)) return;
    1147               0 :                         nameserver_failed(ns, strerror(err));
    1148               0 :                         return;
    1149                 :                 }
    1150               0 :                 ns->timedout = 0;
    1151               0 :                 reply_parse(packet, r);
    1152               0 :         }
    1153                 : }
    1154                 : 
    1155                 : /* Read a packet from a DNS client on a server port s, parse it, and */
    1156                 : /* act accordingly. */
    1157                 : static void
    1158               0 : server_port_read(struct evdns_server_port *s) {
    1159                 :         u8 packet[1500];
    1160                 :         struct sockaddr_storage addr;
    1161                 :         socklen_t addrlen;
    1162                 :         int r;
    1163                 : 
    1164                 :         for (;;) {
    1165               0 :                 addrlen = sizeof(struct sockaddr_storage);
    1166               0 :                 r = recvfrom(s->socket, packet, sizeof(packet), 0,
    1167                 :                                          (struct sockaddr*) &addr, &addrlen);
    1168               0 :                 if (r < 0) {
    1169               0 :                         int err = last_error(s->socket);
    1170               0 :                         if (error_is_eagain(err)) return;
    1171               0 :                         log(EVDNS_LOG_WARN, "Error %s (%d) while reading request.",
    1172                 :                                 strerror(err), err);
    1173               0 :                         return;
    1174                 :                 }
    1175               0 :                 request_parse(packet, r, s, (struct sockaddr*) &addr, addrlen);
    1176               0 :         }
    1177                 : }
    1178                 : 
    1179                 : /* Try to write all pending replies on a given DNS server port. */
    1180                 : static void
    1181               0 : server_port_flush(struct evdns_server_port *port)
    1182                 : {
    1183               0 :         while (port->pending_replies) {
    1184               0 :                 struct server_request *req = port->pending_replies;
    1185               0 :                 int r = sendto(port->socket, req->response, req->response_len, 0,
    1186               0 :                            (struct sockaddr*) &req->addr, req->addrlen);
    1187               0 :                 if (r < 0) {
    1188               0 :                         int err = last_error(port->socket);
    1189               0 :                         if (error_is_eagain(err))
    1190               0 :                                 return;
    1191               0 :                         log(EVDNS_LOG_WARN, "Error %s (%d) while writing response to port; dropping", strerror(err), err);
    1192                 :                 }
    1193               0 :                 if (server_request_free(req)) {
    1194                 :                         /* we released the last reference to req->port. */
    1195               0 :                         return;
    1196                 :                 }
    1197                 :         }
    1198                 : 
    1199                 :         /* We have no more pending requests; stop listening for 'writeable' events. */
    1200               0 :         (void) event_del(&port->event);
    1201               0 :         event_set(&port->event, port->socket, EV_READ | EV_PERSIST,
    1202                 :                           server_port_ready_callback, port);
    1203               0 :         if (event_add(&port->event, NULL) < 0) {
    1204               0 :                 log(EVDNS_LOG_WARN, "Error from libevent when adding event for DNS server.");
    1205                 :                 /* ???? Do more? */
    1206                 :         }
    1207                 : }
    1208                 : 
    1209                 : /* set if we are waiting for the ability to write to this server. */
    1210                 : /* if waiting is true then we ask libevent for EV_WRITE events, otherwise */
    1211                 : /* we stop these events. */
    1212                 : static void
    1213               0 : nameserver_write_waiting(struct nameserver *ns, char waiting) {
    1214               0 :         if (ns->write_waiting == waiting) return;
    1215                 : 
    1216               0 :         ns->write_waiting = waiting;
    1217               0 :         (void) event_del(&ns->event);
    1218               0 :         event_set(&ns->event, ns->socket, EV_READ | (waiting ? EV_WRITE : 0) | EV_PERSIST,
    1219                 :                         nameserver_ready_callback, ns);
    1220               0 :         if (event_add(&ns->event, NULL) < 0) {
    1221               0 :           log(EVDNS_LOG_WARN, "Error from libevent when adding event for %s",
    1222                 :               debug_ntoa(ns->address));
    1223                 :           /* ???? Do more? */
    1224                 :         }
    1225                 : }
    1226                 : 
    1227                 : /* a callback function. Called by libevent when the kernel says that */
    1228                 : /* a nameserver socket is ready for writing or reading */
    1229                 : static void
    1230               0 : nameserver_ready_callback(int fd, short events, void *arg) {
    1231               0 :         struct nameserver *ns = (struct nameserver *) arg;
    1232                 :         (void)fd;
    1233                 : 
    1234               0 :         if (events & EV_WRITE) {
    1235               0 :                 ns->choked = 0;
    1236               0 :                 if (!evdns_transmit()) {
    1237               0 :                         nameserver_write_waiting(ns, 0);
    1238                 :                 }
    1239                 :         }
    1240               0 :         if (events & EV_READ) {
    1241               0 :                 nameserver_read(ns);
    1242                 :         }
    1243               0 : }
    1244                 : 
    1245                 : /* a callback function. Called by libevent when the kernel says that */
    1246                 : /* a server socket is ready for writing or reading. */
    1247                 : static void
    1248               0 : server_port_ready_callback(int fd, short events, void *arg) {
    1249               0 :         struct evdns_server_port *port = (struct evdns_server_port *) arg;
    1250                 :         (void) fd;
    1251                 : 
    1252               0 :         if (events & EV_WRITE) {
    1253               0 :                 port->choked = 0;
    1254               0 :                 server_port_flush(port);
    1255                 :         }
    1256               0 :         if (events & EV_READ) {
    1257               0 :                 server_port_read(port);
    1258                 :         }
    1259               0 : }
    1260                 : 
    1261                 : /* This is an inefficient representation; only use it via the dnslabel_table_*
    1262                 :  * functions, so that is can be safely replaced with something smarter later. */
    1263                 : #define MAX_LABELS 128
    1264                 : /* Structures used to implement name compression */
    1265                 : struct dnslabel_entry { char *v; off_t pos; };
    1266                 : struct dnslabel_table {
    1267                 :         int n_labels; /* number of current entries */
    1268                 :         /* map from name to position in message */
    1269                 :         struct dnslabel_entry labels[MAX_LABELS];
    1270                 : };
    1271                 : 
    1272                 : /* Initialize dnslabel_table. */
    1273                 : static void
    1274               0 : dnslabel_table_init(struct dnslabel_table *table)
    1275                 : {
    1276               0 :         table->n_labels = 0;
    1277               0 : }
    1278                 : 
    1279                 : /* Free all storage held by table, but not the table itself. */
    1280                 : static void
    1281               0 : dnslabel_clear(struct dnslabel_table *table)
    1282                 : {
    1283                 :         int i;
    1284               0 :         for (i = 0; i < table->n_labels; ++i)
    1285               0 :                 free(table->labels[i].v);
    1286               0 :         table->n_labels = 0;
    1287               0 : }
    1288                 : 
    1289                 : /* return the position of the label in the current message, or -1 if the label */
    1290                 : /* hasn't been used yet. */
    1291                 : static int
    1292               0 : dnslabel_table_get_pos(const struct dnslabel_table *table, const char *label)
    1293                 : {
    1294                 :         int i;
    1295               0 :         for (i = 0; i < table->n_labels; ++i) {
    1296               0 :                 if (!strcmp(label, table->labels[i].v))
    1297               0 :                         return table->labels[i].pos;
    1298                 :         }
    1299               0 :         return -1;
    1300                 : }
    1301                 : 
    1302                 : /* remember that we've used the label at position pos */
    1303                 : static int
    1304               0 : dnslabel_table_add(struct dnslabel_table *table, const char *label, off_t pos)
    1305                 : {
    1306                 :         char *v;
    1307                 :         int p;
    1308               0 :         if (table->n_labels == MAX_LABELS)
    1309               0 :                 return (-1);
    1310               0 :         v = strdup(label);
    1311               0 :         if (v == NULL)
    1312               0 :                 return (-1);
    1313               0 :         p = table->n_labels++;
    1314               0 :         table->labels[p].v = v;
    1315               0 :         table->labels[p].pos = pos;
    1316                 : 
    1317               0 :         return (0);
    1318                 : }
    1319                 : 
    1320                 : /* Converts a string to a length-prefixed set of DNS labels, starting */
    1321                 : /* at buf[j]. name and buf must not overlap. name_len should be the length */
    1322                 : /* of name.      table is optional, and is used for compression. */
    1323                 : /* */
    1324                 : /* Input: abc.def */
    1325                 : /* Output: <3>abc<3>def<0> */
    1326                 : /* */
    1327                 : /* Returns the first index after the encoded name, or negative on error. */
    1328                 : /*       -1      label was > 63 bytes */
    1329                 : /*       -2      name too long to fit in buffer. */
    1330                 : /* */
    1331                 : static off_t
    1332               0 : dnsname_to_labels(u8 *const buf, size_t buf_len, off_t j,
    1333                 :                                   const char *name, const int name_len,
    1334                 :                                   struct dnslabel_table *table) {
    1335               0 :         const char *end = name + name_len;
    1336               0 :         int ref = 0;
    1337                 :         u16 _t;
    1338                 : 
    1339                 : #define APPEND16(x) do {                                                   \
    1340                 :                 if (j + 2 > (off_t)buf_len)                             \
    1341                 :                         goto overflow;                                             \
    1342                 :                 _t = htons(x);                                                     \
    1343                 :                 memcpy(buf + j, &_t, 2);                               \
    1344                 :                 j += 2;                                                                    \
    1345                 :         } while (0)
    1346                 : #define APPEND32(x) do {                                                   \
    1347                 :                 if (j + 4 > (off_t)buf_len)                             \
    1348                 :                         goto overflow;                                             \
    1349                 :                 _t32 = htonl(x);                                                   \
    1350                 :                 memcpy(buf + j, &_t32, 4);                             \
    1351                 :                 j += 4;                                                                    \
    1352                 :         } while (0)
    1353                 : 
    1354               0 :         if (name_len > 255) return -2;
    1355                 : 
    1356                 :         for (;;) {
    1357               0 :                 const char *const start = name;
    1358               0 :                 if (table && (ref = dnslabel_table_get_pos(table, name)) >= 0) {
    1359               0 :                         APPEND16(ref | 0xc000);
    1360               0 :                         return j;
    1361                 :                 }
    1362               0 :                 name = strchr(name, '.');
    1363               0 :                 if (!name) {
    1364               0 :                         const unsigned int label_len = end - start;
    1365               0 :                         if (label_len > 63) return -1;
    1366               0 :                         if ((size_t)(j+label_len+1) > buf_len) return -2;
    1367               0 :                         if (table) dnslabel_table_add(table, start, j);
    1368               0 :                         buf[j++] = label_len;
    1369                 : 
    1370               0 :                         memcpy(buf + j, start, end - start);
    1371               0 :                         j += end - start;
    1372                 :                         break;
    1373                 :                 } else {
    1374                 :                         /* append length of the label. */
    1375               0 :                         const unsigned int label_len = name - start;
    1376               0 :                         if (label_len > 63) return -1;
    1377               0 :                         if ((size_t)(j+label_len+1) > buf_len) return -2;
    1378               0 :                         if (table) dnslabel_table_add(table, start, j);
    1379               0 :                         buf[j++] = label_len;
    1380                 : 
    1381               0 :                         memcpy(buf + j, start, name - start);
    1382               0 :                         j += name - start;
    1383                 :                         /* hop over the '.' */
    1384               0 :                         name++;
    1385                 :                 }
    1386               0 :         }
    1387                 : 
    1388                 :         /* the labels must be terminated by a 0. */
    1389                 :         /* It's possible that the name ended in a . */
    1390                 :         /* in which case the zero is already there */
    1391               0 :         if (!j || buf[j-1]) buf[j++] = 0;
    1392               0 :         return j;
    1393                 :  overflow:
    1394               0 :         return (-2);
    1395                 : }
    1396                 : 
    1397                 : /* Finds the length of a dns request for a DNS name of the given */
    1398                 : /* length. The actual request may be smaller than the value returned */
    1399                 : /* here */
    1400                 : static int
    1401               0 : evdns_request_len(const int name_len) {
    1402               0 :         return 96 + /* length of the DNS standard header */
    1403                 :                 name_len + 2 +
    1404                 :                 4;  /* space for the resource type */
    1405                 : }
    1406                 : 
    1407                 : /* build a dns request packet into buf. buf should be at least as long */
    1408                 : /* as evdns_request_len told you it should be. */
    1409                 : /* */
    1410                 : /* Returns the amount of space used. Negative on error. */
    1411                 : static int
    1412               0 : evdns_request_data_build(const char *const name, const int name_len,
    1413                 :     const u16 trans_id, const u16 type, const u16 class,
    1414                 :     u8 *const buf, size_t buf_len) {
    1415               0 :         off_t j = 0;  /* current offset into buf */
    1416                 :         u16 _t;  /* used by the macros */
    1417                 : 
    1418               0 :         APPEND16(trans_id);
    1419               0 :         APPEND16(0x0100);  /* standard query, recusion needed */
    1420               0 :         APPEND16(1);  /* one question */
    1421               0 :         APPEND16(0);  /* no answers */
    1422               0 :         APPEND16(0);  /* no authority */
    1423               0 :         APPEND16(0);  /* no additional */
    1424                 : 
    1425               0 :         j = dnsname_to_labels(buf, buf_len, j, name, name_len, NULL);
    1426               0 :         if (j < 0) {
    1427               0 :                 return (int)j;
    1428                 :         }
    1429                 :         
    1430               0 :         APPEND16(type);
    1431               0 :         APPEND16(class);
    1432                 : 
    1433               0 :         return (int)j;
    1434                 :  overflow:
    1435               0 :         return (-1);
    1436                 : }
    1437                 : 
    1438                 : /* exported function */
    1439                 : struct evdns_server_port *
    1440               0 : evdns_add_server_port(int socket, int is_tcp, evdns_request_callback_fn_type cb, void *user_data)
    1441                 : {
    1442                 :         struct evdns_server_port *port;
    1443               0 :         if (!(port = malloc(sizeof(struct evdns_server_port))))
    1444               0 :                 return NULL;
    1445               0 :         memset(port, 0, sizeof(struct evdns_server_port));
    1446                 : 
    1447               0 :         assert(!is_tcp); /* TCP sockets not yet implemented */
    1448               0 :         port->socket = socket;
    1449               0 :         port->refcnt = 1;
    1450               0 :         port->choked = 0;
    1451               0 :         port->closing = 0;
    1452               0 :         port->user_callback = cb;
    1453               0 :         port->user_data = user_data;
    1454               0 :         port->pending_replies = NULL;
    1455                 : 
    1456               0 :         event_set(&port->event, port->socket, EV_READ | EV_PERSIST,
    1457                 :                           server_port_ready_callback, port);
    1458               0 :         event_add(&port->event, NULL); /* check return. */
    1459               0 :         return port;
    1460                 : }
    1461                 : 
    1462                 : /* exported function */
    1463                 : void
    1464               0 : evdns_close_server_port(struct evdns_server_port *port)
    1465                 : {
    1466               0 :         if (--port->refcnt == 0)
    1467               0 :                 server_port_free(port);
    1468               0 :         port->closing = 1;
    1469               0 : }
    1470                 : 
    1471                 : /* exported function */
    1472                 : int
    1473               0 : evdns_server_request_add_reply(struct evdns_server_request *_req, int section, const char *name, int type, int class, int ttl, int datalen, int is_name, const char *data)
    1474                 : {
    1475               0 :         struct server_request *req = TO_SERVER_REQUEST(_req);
    1476                 :         struct server_reply_item **itemp, *item;
    1477                 :         int *countp;
    1478                 : 
    1479               0 :         if (req->response) /* have we already answered? */
    1480               0 :                 return (-1);
    1481                 : 
    1482               0 :         switch (section) {
    1483                 :         case EVDNS_ANSWER_SECTION:
    1484               0 :                 itemp = &req->answer;
    1485               0 :                 countp = &req->n_answer;
    1486               0 :                 break;
    1487                 :         case EVDNS_AUTHORITY_SECTION:
    1488               0 :                 itemp = &req->authority;
    1489               0 :                 countp = &req->n_authority;
    1490               0 :                 break;
    1491                 :         case EVDNS_ADDITIONAL_SECTION:
    1492               0 :                 itemp = &req->additional;
    1493               0 :                 countp = &req->n_additional;
    1494               0 :                 break;
    1495                 :         default:
    1496               0 :                 return (-1);
    1497                 :         }
    1498               0 :         while (*itemp) {
    1499               0 :                 itemp = &((*itemp)->next);
    1500                 :         }
    1501               0 :         item = malloc(sizeof(struct server_reply_item));
    1502               0 :         if (!item)
    1503               0 :                 return -1;
    1504               0 :         item->next = NULL;
    1505               0 :         if (!(item->name = strdup(name))) {
    1506               0 :                 free(item);
    1507               0 :                 return -1;
    1508                 :         }
    1509               0 :         item->type = type;
    1510               0 :         item->dns_question_class = class;
    1511               0 :         item->ttl = ttl;
    1512               0 :         item->is_name = is_name != 0;
    1513               0 :         item->datalen = 0;
    1514               0 :         item->data = NULL;
    1515               0 :         if (data) {
    1516               0 :                 if (item->is_name) {
    1517               0 :                         if (!(item->data = strdup(data))) {
    1518               0 :                                 free(item->name);
    1519               0 :                                 free(item);
    1520               0 :                                 return -1;
    1521                 :                         }
    1522               0 :                         item->datalen = (u16)-1;
    1523                 :                 } else {
    1524               0 :                         if (!(item->data = malloc(datalen))) {
    1525               0 :                                 free(item->name);
    1526               0 :                                 free(item);
    1527               0 :                                 return -1;
    1528                 :                         }
    1529               0 :                         item->datalen = datalen;
    1530               0 :                         memcpy(item->data, data, datalen);
    1531                 :                 }
    1532                 :         }
    1533                 : 
    1534               0 :         *itemp = item;
    1535               0 :         ++(*countp);
    1536               0 :         return 0;
    1537                 : }
    1538                 : 
    1539                 : /* exported function */
    1540                 : int
    1541               0 : evdns_server_request_add_a_reply(struct evdns_server_request *req, const char *name, int n, void *addrs, int ttl)
    1542                 : {
    1543               0 :         return evdns_server_request_add_reply(
    1544                 :                   req, EVDNS_ANSWER_SECTION, name, TYPE_A, CLASS_INET,
    1545                 :                   ttl, n*4, 0, addrs);
    1546                 : }
    1547                 : 
    1548                 : /* exported function */
    1549                 : int
    1550               0 : evdns_server_request_add_aaaa_reply(struct evdns_server_request *req, const char *name, int n, void *addrs, int ttl)
    1551                 : {
    1552               0 :         return evdns_server_request_add_reply(
    1553                 :                   req, EVDNS_ANSWER_SECTION, name, TYPE_AAAA, CLASS_INET,
    1554                 :                   ttl, n*16, 0, addrs);
    1555                 : }
    1556                 : 
    1557                 : /* exported function */
    1558                 : int
    1559               0 : evdns_server_request_add_ptr_reply(struct evdns_server_request *req, struct in_addr *in, const char *inaddr_name, const char *hostname, int ttl)
    1560                 : {
    1561                 :         u32 a;
    1562                 :         char buf[32];
    1563               0 :         assert(in || inaddr_name);
    1564               0 :         assert(!(in && inaddr_name));
    1565               0 :         if (in) {
    1566               0 :                 a = ntohl(in->s_addr);
    1567               0 :                 evutil_snprintf(buf, sizeof(buf), "%d.%d.%d.%d.in-addr.arpa",
    1568               0 :                                 (int)(u8)((a    )&0xff),
    1569               0 :                                 (int)(u8)((a>>8 )&0xff),
    1570               0 :                                 (int)(u8)((a>>16)&0xff),
    1571               0 :                                 (int)(u8)((a>>24)&0xff));
    1572               0 :                 inaddr_name = buf;
    1573                 :         }
    1574               0 :         return evdns_server_request_add_reply(
    1575                 :                   req, EVDNS_ANSWER_SECTION, inaddr_name, TYPE_PTR, CLASS_INET,
    1576                 :                   ttl, -1, 1, hostname);
    1577                 : }
    1578                 : 
    1579                 : /* exported function */
    1580                 : int
    1581               0 : evdns_server_request_add_cname_reply(struct evdns_server_request *req, const char *name, const char *cname, int ttl)
    1582                 : {
    1583               0 :         return evdns_server_request_add_reply(
    1584                 :                   req, EVDNS_ANSWER_SECTION, name, TYPE_CNAME, CLASS_INET,
    1585                 :                   ttl, -1, 1, cname);
    1586                 : }
    1587                 : 
    1588                 : 
    1589                 : static int
    1590               0 : evdns_server_request_format_response(struct server_request *req, int err)
    1591                 : {
    1592                 :         unsigned char buf[1500];
    1593               0 :         size_t buf_len = sizeof(buf);
    1594               0 :         off_t j = 0, r;
    1595                 :         u16 _t;
    1596                 :         u32 _t32;
    1597                 :         int i;
    1598                 :         u16 flags;
    1599                 :         struct dnslabel_table table;
    1600                 : 
    1601               0 :         if (err < 0 || err > 15) return -1;
    1602                 : 
    1603                 :         /* Set response bit and error code; copy OPCODE and RD fields from
    1604                 :          * question; copy RA and AA if set by caller. */
    1605               0 :         flags = req->base.flags;
    1606               0 :         flags |= (0x8000 | err);
    1607                 : 
    1608               0 :         dnslabel_table_init(&table);
    1609               0 :         APPEND16(req->trans_id);
    1610               0 :         APPEND16(flags);
    1611               0 :         APPEND16(req->base.nquestions);
    1612               0 :         APPEND16(req->n_answer);
    1613               0 :         APPEND16(req->n_authority);
    1614               0 :         APPEND16(req->n_additional);
    1615                 : 
    1616                 :         /* Add questions. */
    1617               0 :         for (i=0; i < req->base.nquestions; ++i) {
    1618               0 :                 const char *s = req->base.questions[i]->name;
    1619               0 :                 j = dnsname_to_labels(buf, buf_len, j, s, strlen(s), &table);
    1620               0 :                 if (j < 0) {
    1621               0 :                         dnslabel_clear(&table);
    1622               0 :                         return (int) j;
    1623                 :                 }
    1624               0 :                 APPEND16(req->base.questions[i]->type);
    1625               0 :                 APPEND16(req->base.questions[i]->dns_question_class);
    1626                 :         }
    1627                 : 
    1628                 :         /* Add answer, authority, and additional sections. */
    1629               0 :         for (i=0; i<3; ++i) {
    1630                 :                 struct server_reply_item *item;
    1631               0 :                 if (i==0)
    1632               0 :                         item = req->answer;
    1633               0 :                 else if (i==1)
    1634               0 :                         item = req->authority;
    1635                 :                 else
    1636               0 :                         item = req->additional;
    1637               0 :                 while (item) {
    1638               0 :                         r = dnsname_to_labels(buf, buf_len, j, item->name, strlen(item->name), &table);
    1639               0 :                         if (r < 0)
    1640               0 :                                 goto overflow;
    1641               0 :                         j = r;
    1642                 : 
    1643               0 :                         APPEND16(item->type);
    1644               0 :                         APPEND16(item->dns_question_class);
    1645               0 :                         APPEND32(item->ttl);
    1646               0 :                         if (item->is_name) {
    1647               0 :                                 off_t len_idx = j, name_start;
    1648               0 :                                 j += 2;
    1649               0 :                                 name_start = j;
    1650               0 :                                 r = dnsname_to_labels(buf, buf_len, j, item->data, strlen(item->data), &table);
    1651               0 :                                 if (r < 0)
    1652               0 :                                         goto overflow;
    1653               0 :                                 j = r;
    1654               0 :                                 _t = htons( (short) (j-name_start) );
    1655               0 :                                 memcpy(buf+len_idx, &_t, 2);
    1656                 :                         } else {
    1657               0 :                                 APPEND16(item->datalen);
    1658               0 :                                 if (j+item->datalen > (off_t)buf_len)
    1659               0 :                                         goto overflow;
    1660               0 :                                 memcpy(buf+j, item->data, item->datalen);
    1661               0 :                                 j += item->datalen;
    1662                 :                         }
    1663               0 :                         item = item->next;
    1664                 :                 }
    1665                 :         }
    1666                 : 
    1667               0 :         if (j > 512) {
    1668                 : overflow:
    1669               0 :                 j = 512;
    1670               0 :                 buf[3] |= 0x02; /* set the truncated bit. */
    1671                 :         }
    1672                 : 
    1673               0 :         req->response_len = j;
    1674                 : 
    1675               0 :         if (!(req->response = malloc(req->response_len))) {
    1676               0 :                 server_request_free_answers(req);
    1677               0 :                 dnslabel_clear(&table);
    1678               0 :                 return (-1);
    1679                 :         }
    1680               0 :         memcpy(req->response, buf, req->response_len);
    1681               0 :         server_request_free_answers(req);
    1682               0 :         dnslabel_clear(&table);
    1683               0 :         return (0);
    1684                 : }
    1685                 : 
    1686                 : /* exported function */
    1687                 : int
    1688               0 : evdns_server_request_respond(struct evdns_server_request *_req, int err)
    1689                 : {
    1690               0 :         struct server_request *req = TO_SERVER_REQUEST(_req);
    1691               0 :         struct evdns_server_port *port = req->port;
    1692                 :         int r;
    1693               0 :         if (!req->response) {
    1694               0 :                 if ((r = evdns_server_request_format_response(req, err))<0)
    1695               0 :                         return r;
    1696                 :         }
    1697                 : 
    1698               0 :         r = sendto(port->socket, req->response, req->response_len, 0,
    1699               0 :                            (struct sockaddr*) &req->addr, req->addrlen);
    1700               0 :         if (r<0) {
    1701               0 :                 int sock_err = last_error(port->socket);
    1702               0 :                 if (! error_is_eagain(sock_err))
    1703               0 :                         return -1;
    1704                 : 
    1705               0 :                 if (port->pending_replies) {
    1706               0 :                         req->prev_pending = port->pending_replies->prev_pending;
    1707               0 :                         req->next_pending = port->pending_replies;
    1708               0 :                         req->prev_pending->next_pending =
    1709               0 :                                 req->next_pending->prev_pending = req;
    1710                 :                 } else {
    1711               0 :                         req->prev_pending = req->next_pending = req;
    1712               0 :                         port->pending_replies = req;
    1713               0 :                         port->choked = 1;
    1714                 : 
    1715               0 :                         (void) event_del(&port->event);
    1716               0 :                         event_set(&port->event, port->socket, (port->closing?0:EV_READ) | EV_WRITE | EV_PERSIST, server_port_ready_callback, port);
    1717                 : 
    1718               0 :                         if (event_add(&port->event, NULL) < 0) {
    1719               0 :                                 log(EVDNS_LOG_WARN, "Error from libevent when adding event for DNS server");
    1720                 :                         }
    1721                 : 
    1722                 :                 }
    1723                 : 
    1724               0 :                 return 1;
    1725                 :         }
    1726               0 :         if (server_request_free(req))
    1727               0 :                 return 0;
    1728                 : 
    1729               0 :         if (port->pending_replies)
    1730               0 :                 server_port_flush(port);
    1731                 : 
    1732               0 :         return 0;
    1733                 : }
    1734                 : 
    1735                 : /* Free all storage held by RRs in req. */
    1736                 : static void
    1737               0 : server_request_free_answers(struct server_request *req)
    1738                 : {
    1739                 :         struct server_reply_item *victim, *next, **list;
    1740                 :         int i;
    1741               0 :         for (i = 0; i < 3; ++i) {
    1742               0 :                 if (i==0)
    1743               0 :                         list = &req->answer;
    1744               0 :                 else if (i==1)
    1745               0 :                         list = &req->authority;
    1746                 :                 else
    1747               0 :                         list = &req->additional;
    1748                 : 
    1749               0 :                 victim = *list;
    1750               0 :                 while (victim) {
    1751               0 :                         next = victim->next;
    1752               0 :                         free(victim->name);
    1753               0 :                         if (victim->data)
    1754               0 :                                 free(victim->data);
    1755               0 :                         free(victim);
    1756               0 :                         victim = next;
    1757                 :                 }
    1758               0 :                 *list = NULL;
    1759                 :         }
    1760               0 : }
    1761                 : 
    1762                 : /* Free all storage held by req, and remove links to it. */
    1763                 : /* return true iff we just wound up freeing the server_port. */
    1764                 : static int
    1765               0 : server_request_free(struct server_request *req)
    1766                 : {
    1767               0 :         int i, rc=1;
    1768               0 :         if (req->base.questions) {
    1769               0 :                 for (i = 0; i < req->base.nquestions; ++i)
    1770               0 :                         free(req->base.questions[i]);
    1771               0 :                 free(req->base.questions);
    1772                 :         }
    1773                 : 
    1774               0 :         if (req->port) {
    1775               0 :                 if (req->port->pending_replies == req) {
    1776               0 :                         if (req->next_pending)
    1777               0 :                                 req->port->pending_replies = req->next_pending;
    1778                 :                         else
    1779               0 :                                 req->port->pending_replies = NULL;
    1780                 :                 }
    1781               0 :                 rc = --req->port->refcnt;
    1782                 :         }
    1783                 : 
    1784               0 :         if (req->response) {
    1785               0 :                 free(req->response);
    1786                 :         }
    1787                 : 
    1788               0 :         server_request_free_answers(req);
    1789                 : 
    1790               0 :         if (req->next_pending && req->next_pending != req) {
    1791               0 :                 req->next_pending->prev_pending = req->prev_pending;
    1792               0 :                 req->prev_pending->next_pending = req->next_pending;
    1793                 :         }
    1794                 : 
    1795               0 :         if (rc == 0) {
    1796               0 :                 server_port_free(req->port);
    1797               0 :                 free(req);
    1798               0 :                 return (1);
    1799                 :         }
    1800               0 :         free(req);
    1801               0 :         return (0);
    1802                 : }
    1803                 : 
    1804                 : /* Free all storage held by an evdns_server_port.  Only called when  */
    1805                 : static void
    1806               0 : server_port_free(struct evdns_server_port *port)
    1807                 : {
    1808               0 :         assert(port);
    1809               0 :         assert(!port->refcnt);
    1810               0 :         assert(!port->pending_replies);
    1811               0 :         if (port->socket > 0) {
    1812               0 :                 CLOSE_SOCKET(port->socket);
    1813               0 :                 port->socket = -1;
    1814                 :         }
    1815               0 :         (void) event_del(&port->event);
    1816                 :         /* XXXX actually free the port? -NM */
    1817               0 : }
    1818                 : 
    1819                 : /* exported function */
    1820                 : int
    1821               0 : evdns_server_request_drop(struct evdns_server_request *_req)
    1822                 : {
    1823               0 :         struct server_request *req = TO_SERVER_REQUEST(_req);
    1824               0 :         server_request_free(req);
    1825               0 :         return 0;
    1826                 : }
    1827                 : 
    1828                 : /* exported function */
    1829                 : int
    1830               0 : evdns_server_request_get_requesting_addr(struct evdns_server_request *_req, struct sockaddr *sa, int addr_len)
    1831                 : {
    1832               0 :         struct server_request *req = TO_SERVER_REQUEST(_req);
    1833               0 :         if (addr_len < (int)req->addrlen)
    1834               0 :                 return -1;
    1835               0 :         memcpy(sa, &(req->addr), req->addrlen);
    1836               0 :         return req->addrlen;
    1837                 : }
    1838                 : 
    1839                 : #undef APPEND16
    1840                 : #undef APPEND32
    1841                 : 
    1842                 : /* this is a libevent callback function which is called when a request */
    1843                 : /* has timed out. */
    1844                 : static void
    1845               0 : evdns_request_timeout_callback(int fd, short events, void *arg) {
    1846               0 :         struct request *const req = (struct request *) arg;
    1847                 :         (void) fd;
    1848                 :         (void) events;
    1849                 : 
    1850               0 :         log(EVDNS_LOG_DEBUG, "Request %lx timed out", (unsigned long) arg);
    1851                 : 
    1852               0 :         req->ns->timedout++;
    1853               0 :         if (req->ns->timedout > global_max_nameserver_timeout) {
    1854               0 :                 req->ns->timedout = 0;
    1855               0 :                 nameserver_failed(req->ns, "request timed out.");
    1856                 :         }
    1857                 : 
    1858               0 :         (void) evtimer_del(&req->timeout_event);
    1859               0 :         if (req->tx_count >= global_max_retransmits) {
    1860                 :                 /* this request has failed */
    1861               0 :                 reply_callback(req, 0, DNS_ERR_TIMEOUT, NULL);
    1862               0 :                 request_finished(req, &req_head);
    1863                 :         } else {
    1864                 :                 /* retransmit it */
    1865               0 :                 evdns_request_transmit(req);
    1866                 :         }
    1867               0 : }
    1868                 : 
    1869                 : /* try to send a request to a given server. */
    1870                 : /* */
    1871                 : /* return: */
    1872                 : /*   0 ok */
    1873                 : /*   1 temporary failure */
    1874                 : /*   2 other failure */
    1875                 : static int
    1876               0 : evdns_request_transmit_to(struct request *req, struct nameserver *server) {
    1877               0 :         const int r = send(server->socket, req->request, req->request_len, 0);
    1878               0 :         if (r < 0) {
    1879               0 :                 int err = last_error(server->socket);
    1880               0 :                 if (error_is_eagain(err)) return 1;
    1881               0 :                 nameserver_failed(req->ns, strerror(err));
    1882               0 :                 return 2;
    1883               0 :         } else if (r != (int)req->request_len) {
    1884               0 :                 return 1;  /* short write */
    1885                 :         } else {
    1886               0 :                 return 0;
    1887                 :         }
    1888                 : }
    1889                 : 
    1890                 : /* try to send a request, updating the fields of the request */
    1891                 : /* as needed */
    1892                 : /* */
    1893                 : /* return: */
    1894                 : /*   0 ok */
    1895                 : /*   1 failed */
    1896                 : static int
    1897               0 : evdns_request_transmit(struct request *req) {
    1898               0 :         int retcode = 0, r;
    1899                 : 
    1900                 :         /* if we fail to send this packet then this flag marks it */
    1901                 :         /* for evdns_transmit */
    1902               0 :         req->transmit_me = 1;
    1903               0 :         if (req->trans_id == 0xffff) abort();
    1904                 : 
    1905               0 :         if (req->ns->choked) {
    1906                 :                 /* don't bother trying to write to a socket */
    1907                 :                 /* which we have had EAGAIN from */
    1908               0 :                 return 1;
    1909                 :         }
    1910                 : 
    1911               0 :         r = evdns_request_transmit_to(req, req->ns);
    1912               0 :         switch (r) {
    1913                 :         case 1:
    1914                 :                 /* temp failure */
    1915               0 :                 req->ns->choked = 1;
    1916               0 :                 nameserver_write_waiting(req->ns, 1);
    1917               0 :                 return 1;
    1918                 :         case 2:
    1919                 :                 /* failed in some other way */
    1920               0 :                 retcode = 1;
    1921                 :                 /* fall through */
    1922                 :         default:
    1923                 :                 /* all ok */
    1924               0 :                 log(EVDNS_LOG_DEBUG,
    1925                 :                     "Setting timeout for request %lx", (unsigned long) req);
    1926               0 :                 evtimer_set(&req->timeout_event, evdns_request_timeout_callback, req);
    1927               0 :                 if (evtimer_add(&req->timeout_event, &global_timeout) < 0) {
    1928               0 :                   log(EVDNS_LOG_WARN,
    1929                 :                       "Error from libevent when adding timer for request %lx",
    1930                 :                       (unsigned long) req);
    1931                 :                   /* ???? Do more? */
    1932                 :                 }
    1933               0 :                 req->tx_count++;
    1934               0 :                 req->transmit_me = 0;
    1935               0 :                 return retcode;
    1936                 :         }
    1937                 : }
    1938                 : 
    1939                 : static void
    1940               0 : nameserver_probe_callback(int result, char type, int count, int ttl, void *addresses, void *arg) {
    1941               0 :         struct nameserver *const ns = (struct nameserver *) arg;
    1942                 :         (void) type;
    1943                 :         (void) count;
    1944                 :         (void) ttl;
    1945                 :         (void) addresses;
    1946                 : 
    1947               0 :         if (result == DNS_ERR_NONE || result == DNS_ERR_NOTEXIST) {
    1948                 :                 /* this is a good reply */
    1949               0 :                 nameserver_up(ns);
    1950               0 :         } else nameserver_probe_failed(ns);
    1951               0 : }
    1952                 : 
    1953                 : static void
    1954               0 : nameserver_send_probe(struct nameserver *const ns) {
    1955                 :         struct request *req;
    1956                 :         /* here we need to send a probe to a given nameserver */
    1957                 :         /* in the hope that it is up now. */
    1958                 : 
    1959               0 :         log(EVDNS_LOG_DEBUG, "Sending probe to %s", debug_ntoa(ns->address));
    1960                 : 
    1961               0 :         req = request_new(TYPE_A, "www.google.com", DNS_QUERY_NO_SEARCH, nameserver_probe_callback, ns);
    1962               0 :         if (!req) return;
    1963                 :         /* we force this into the inflight queue no matter what */
    1964               0 :         request_trans_id_set(req, transaction_id_pick());
    1965               0 :         req->ns = ns;
    1966               0 :         request_submit(req);
    1967                 : }
    1968                 : 
    1969                 : /* returns: */
    1970                 : /*   0 didn't try to transmit anything */
    1971                 : /*   1 tried to transmit something */
    1972                 : static int
    1973               0 : evdns_transmit(void) {
    1974               0 :         char did_try_to_transmit = 0;
    1975                 : 
    1976               0 :         if (req_head) {
    1977               0 :                 struct request *const started_at = req_head, *req = req_head;
    1978                 :                 /* first transmit all the requests which are currently waiting */
    1979                 :                 do {
    1980               0 :                         if (req->transmit_me) {
    1981               0 :                                 did_try_to_transmit = 1;
    1982               0 :                                 evdns_request_transmit(req);
    1983                 :                         }
    1984                 : 
    1985               0 :                         req = req->next;
    1986               0 :                 } while (req != started_at);
    1987                 :         }
    1988                 : 
    1989               0 :         return did_try_to_transmit;
    1990                 : }
    1991                 : 
    1992                 : /* exported function */
    1993                 : int
    1994               0 : evdns_count_nameservers(void)
    1995                 : {
    1996               0 :         const struct nameserver *server = server_head;
    1997               0 :         int n = 0;
    1998               0 :         if (!server)
    1999               0 :                 return 0;
    2000                 :         do {
    2001               0 :                 ++n;
    2002               0 :                 server = server->next;
    2003               0 :         } while (server != server_head);
    2004               0 :         return n;
    2005                 : }
    2006                 : 
    2007                 : /* exported function */
    2008                 : int
    2009               0 : evdns_clear_nameservers_and_suspend(void)
    2010                 : {
    2011               0 :         struct nameserver *server = server_head, *started_at = server_head;
    2012               0 :         struct request *req = req_head, *req_started_at = req_head;
    2013                 : 
    2014               0 :         if (!server)
    2015               0 :                 return 0;
    2016                 :         while (1) {
    2017               0 :                 struct nameserver *next = server->next;
    2018               0 :                 (void) event_del(&server->event);
    2019               0 :                 if (evtimer_initialized(&server->timeout_event))
    2020               0 :                         (void) evtimer_del(&server->timeout_event);
    2021               0 :                 if (server->socket >= 0)
    2022               0 :                         CLOSE_SOCKET(server->socket);
    2023               0 :                 free(server);
    2024               0 :                 if (next == started_at)
    2025                 :                         break;
    2026               0 :                 server = next;
    2027               0 :         }
    2028               0 :         server_head = NULL;
    2029               0 :         global_good_nameservers = 0;
    2030                 : 
    2031               0 :         while (req) {
    2032               0 :                 struct request *next = req->next;
    2033               0 :                 req->tx_count = req->reissue_count = 0;
    2034               0 :                 req->ns = NULL;
    2035                 :                 /* ???? What to do about searches? */
    2036               0 :                 (void) evtimer_del(&req->timeout_event);
    2037               0 :                 req->trans_id = 0;
    2038               0 :                 req->transmit_me = 0;
    2039                 : 
    2040               0 :                 global_requests_waiting++;
    2041               0 :                 evdns_request_insert(req, &req_waiting_head);
    2042                 :                 /* We want to insert these suspended elements at the front of
    2043                 :                  * the waiting queue, since they were pending before any of
    2044                 :                  * the waiting entries were added.  This is a circular list,
    2045                 :                  * so we can just shift the start back by one.*/
    2046               0 :                 req_waiting_head = req_waiting_head->prev;
    2047                 : 
    2048               0 :                 if (next == req_started_at)
    2049               0 :                         break;
    2050               0 :                 req = next;
    2051                 :         }
    2052               0 :         req_head = NULL;
    2053               0 :         global_requests_inflight = 0;
    2054                 : 
    2055               0 :         return 0;
    2056                 : }
    2057                 : 
    2058                 : 
    2059                 : /* exported function */
    2060                 : int
    2061               0 : evdns_resume(void)
    2062                 : {
    2063               0 :         evdns_requests_pump_waiting_queue();
    2064               0 :         return 0;
    2065                 : }
    2066                 : 
    2067                 : static int
    2068               0 : _evdns_nameserver_add_impl(unsigned long int address, int port) {
    2069                 :         /* first check to see if we already have this nameserver */
    2070                 : 
    2071               0 :         const struct nameserver *server = server_head, *const started_at = server_head;
    2072                 :         struct nameserver *ns;
    2073                 :         struct sockaddr_in sin;
    2074               0 :         int err = 0;
    2075               0 :         if (server) {
    2076                 :                 do {
    2077               0 :                         if (server->address == address) return 3;
    2078               0 :                         server = server->next;
    2079               0 :                 } while (server != started_at);
    2080                 :         }
    2081                 : 
    2082               0 :         ns = (struct nameserver *) malloc(sizeof(struct nameserver));
    2083               0 :         if (!ns) return -1;
    2084                 : 
    2085               0 :         memset(ns, 0, sizeof(struct nameserver));
    2086                 : 
    2087               0 :         ns->socket = socket(PF_INET, SOCK_DGRAM, 0);
    2088               0 :         if (ns->socket < 0) { err = 1; goto out1; }
    2089               0 :         evutil_make_socket_nonblocking(ns->socket);
    2090               0 :         sin.sin_addr.s_addr = address;
    2091               0 :         sin.sin_port = htons(port);
    2092               0 :         sin.sin_family = AF_INET;
    2093               0 :         if (connect(ns->socket, (struct sockaddr *) &sin, sizeof(sin)) != 0) {
    2094               0 :                 err = 2;
    2095               0 :                 goto out2;
    2096                 :         }
    2097                 : 
    2098               0 :         ns->address = address;
    2099               0 :         ns->state = 1;
    2100               0 :         event_set(&ns->event, ns->socket, EV_READ | EV_PERSIST, nameserver_ready_callback, ns);
    2101               0 :         if (event_add(&ns->event, NULL) < 0) {
    2102               0 :           err = 2;
    2103               0 :           goto out2;
    2104                 :         }
    2105                 : 
    2106               0 :         log(EVDNS_LOG_DEBUG, "Added nameserver %s", debug_ntoa(address));
    2107                 : 
    2108                 :         /* insert this nameserver into the list of them */
    2109               0 :         if (!server_head) {
    2110               0 :                 ns->next = ns->prev = ns;
    2111               0 :                 server_head = ns;
    2112                 :         } else {
    2113               0 :                 ns->next = server_head->next;
    2114               0 :                 ns->prev = server_head;
    2115               0 :                 server_head->next = ns;
    2116               0 :                 if (server_head->prev == server_head) {
    2117               0 :                         server_head->prev = ns;
    2118                 :                 }
    2119                 :         }
    2120                 : 
    2121               0 :         global_good_nameservers++;
    2122                 : 
    2123               0 :         return 0;
    2124                 : 
    2125                 : out2:
    2126               0 :         CLOSE_SOCKET(ns->socket);
    2127                 : out1:
    2128               0 :         free(ns);
    2129               0 :         log(EVDNS_LOG_WARN, "Unable to add nameserver %s: error %d", debug_ntoa(address), err);
    2130               0 :         return err;
    2131                 : }
    2132                 : 
    2133                 : /* exported function */
    2134                 : int
    2135               0 : evdns_nameserver_add(unsigned long int address) {
    2136               0 :         return _evdns_nameserver_add_impl(address, 53);
    2137                 : }
    2138                 : 
    2139                 : /* exported function */
    2140                 : int
    2141               0 : evdns_nameserver_ip_add(const char *ip_as_string) {
    2142                 :         struct in_addr ina;
    2143                 :         int port;
    2144                 :         char buf[20];
    2145                 :         const char *cp;
    2146               0 :         cp = strchr(ip_as_string, ':');
    2147               0 :         if (! cp) {
    2148               0 :                 cp = ip_as_string;
    2149               0 :                 port = 53;
    2150                 :         } else {
    2151               0 :                 port = strtoint(cp+1);
    2152               0 :                 if (port < 0 || port > 65535) {
    2153               0 :                         return 4;
    2154                 :                 }
    2155               0 :                 if ((cp-ip_as_string) >= (int)sizeof(buf)) {
    2156               0 :                         return 4;
    2157                 :                 }
    2158               0 :                 memcpy(buf, ip_as_string, cp-ip_as_string);
    2159               0 :                 buf[cp-ip_as_string] = '\0';
    2160               0 :                 cp = buf;
    2161                 :         }
    2162               0 :         if (!inet_aton(cp, &ina)) {
    2163               0 :                 return 4;
    2164                 :         }
    2165               0 :         return _evdns_nameserver_add_impl(ina.s_addr, port);
    2166                 : }
    2167                 : 
    2168                 : /* insert into the tail of the queue */
    2169                 : static void
    2170               0 : evdns_request_insert(struct request *req, struct request **head) {
    2171               0 :         if (!*head) {
    2172               0 :                 *head = req;
    2173               0 :                 req->next = req->prev = req;
    2174               0 :                 return;
    2175                 :         }
    2176                 : 
    2177               0 :         req->prev = (*head)->prev;
    2178               0 :         req->prev->next = req;
    2179               0 :         req->next = *head;
    2180               0 :         (*head)->prev = req;
    2181                 : }
    2182                 : 
    2183                 : static int
    2184               0 : string_num_dots(const char *s) {
    2185               0 :         int count = 0;
    2186               0 :         while ((s = strchr(s, '.'))) {
    2187               0 :                 s++;
    2188               0 :                 count++;
    2189                 :         }
    2190               0 :         return count;
    2191                 : }
    2192                 : 
    2193                 : static struct request *
    2194               0 : request_new(int type, const char *name, int flags,
    2195                 :     evdns_callback_type callback, void *user_ptr) {
    2196               0 :         const char issuing_now =
    2197               0 :             (global_requests_inflight < global_max_requests_inflight) ? 1 : 0;
    2198                 : 
    2199               0 :         const int name_len = strlen(name);
    2200               0 :         const int request_max_len = evdns_request_len(name_len);
    2201               0 :         const u16 trans_id = issuing_now ? transaction_id_pick() : 0xffff;
    2202                 :         /* the request data is alloced in a single block with the header */
    2203               0 :         struct request *const req =
    2204               0 :             (struct request *) malloc(sizeof(struct request) + request_max_len);
    2205                 :         int rlen;
    2206                 :         (void) flags;
    2207                 : 
    2208               0 :         if (!req) return NULL;
    2209               0 :         memset(req, 0, sizeof(struct request));
    2210                 : 
    2211                 :         /* request data lives just after the header */
    2212               0 :         req->request = ((u8 *) req) + sizeof(struct request);
    2213                 :         /* denotes that the request data shouldn't be free()ed */
    2214               0 :         req->request_appended = 1;
    2215               0 :         rlen = evdns_request_data_build(name, name_len, trans_id,
    2216                 :             type, CLASS_INET, req->request, request_max_len);
    2217               0 :         if (rlen < 0)
    2218               0 :                 goto err1;
    2219               0 :         req->request_len = rlen;
    2220               0 :         req->trans_id = trans_id;
    2221               0 :         req->tx_count = 0;
    2222               0 :         req->request_type = type;
    2223               0 :         req->user_pointer = user_ptr;
    2224               0 :         req->user_callback = callback;
    2225               0 :         req->ns = issuing_now ? nameserver_pick() : NULL;
    2226               0 :         req->next = req->prev = NULL;
    2227                 : 
    2228               0 :         return req;
    2229                 : err1:
    2230               0 :         free(req);
    2231               0 :         return NULL;
    2232                 : }
    2233                 : 
    2234                 : static void
    2235               0 : request_submit(struct request *const req) {
    2236               0 :         if (req->ns) {
    2237                 :                 /* if it has a nameserver assigned then this is going */
    2238                 :                 /* straight into the inflight queue */
    2239               0 :                 evdns_request_insert(req, &req_head);
    2240               0 :                 global_requests_inflight++;
    2241               0 :                 evdns_request_transmit(req);
    2242                 :         } else {
    2243               0 :                 evdns_request_insert(req, &req_waiting_head);
    2244               0 :                 global_requests_waiting++;
    2245                 :         }
    2246               0 : }
    2247                 : 
    2248                 : /* exported function */
    2249               0 : int evdns_resolve_ipv4(const char *name, int flags,
    2250                 :     evdns_callback_type callback, void *ptr) {
    2251               0 :         log(EVDNS_LOG_DEBUG, "Resolve requested for %s", name);
    2252               0 :         if (flags & DNS_QUERY_NO_SEARCH) {
    2253               0 :                 struct request *const req =
    2254                 :                         request_new(TYPE_A, name, flags, callback, ptr);
    2255               0 :                 if (req == NULL)
    2256               0 :                         return (1);
    2257               0 :                 request_submit(req);
    2258               0 :                 return (0);
    2259                 :         } else {
    2260               0 :                 return (search_request_new(TYPE_A, name, flags, callback, ptr));
    2261                 :         }
    2262                 : }
    2263                 : 
    2264                 : /* exported function */
    2265               0 : int evdns_resolve_ipv6(const char *name, int flags,
    2266                 :                                            evdns_callback_type callback, void *ptr) {
    2267               0 :         log(EVDNS_LOG_DEBUG, "Resolve requested for %s", name);
    2268               0 :         if (flags & DNS_QUERY_NO_SEARCH) {
    2269               0 :                 struct request *const req =
    2270                 :                         request_new(TYPE_AAAA, name, flags, callback, ptr);
    2271               0 :                 if (req == NULL)
    2272               0 :                         return (1);
    2273               0 :                 request_submit(req);
    2274               0 :                 return (0);
    2275                 :         } else {
    2276               0 :                 return (search_request_new(TYPE_AAAA, name, flags, callback, ptr));
    2277                 :         }
    2278                 : }
    2279                 : 
    2280               0 : int evdns_resolve_reverse(struct in_addr *in, int flags, evdns_callback_type callback, void *ptr) {
    2281                 :         char buf[32];
    2282                 :         struct request *req;
    2283                 :         u32 a;
    2284               0 :         assert(in);
    2285               0 :         a = ntohl(in->s_addr);
    2286               0 :         evutil_snprintf(buf, sizeof(buf), "%d.%d.%d.%d.in-addr.arpa",
    2287               0 :                         (int)(u8)((a    )&0xff),
    2288               0 :                         (int)(u8)((a>>8 )&0xff),
    2289               0 :                         (int)(u8)((a>>16)&0xff),
    2290               0 :                         (int)(u8)((a>>24)&0xff));
    2291               0 :         log(EVDNS_LOG_DEBUG, "Resolve requested for %s (reverse)", buf);
    2292               0 :         req = request_new(TYPE_PTR, buf, flags, callback, ptr);
    2293               0 :         if (!req) return 1;
    2294               0 :         request_submit(req);
    2295               0 :         return 0;
    2296                 : }
    2297                 : 
    2298               0 : int evdns_resolve_reverse_ipv6(struct in6_addr *in, int flags, evdns_callback_type callback, void *ptr) {
    2299                 :         /* 32 nybbles, 32 periods, "ip6.arpa", NUL. */
    2300                 :         char buf[73];
    2301                 :         char *cp;
    2302                 :         struct request *req;
    2303                 :         int i;
    2304               0 :         assert(in);
    2305               0 :         cp = buf;
    2306               0 :         for (i=15; i >= 0; --i) {
    2307               0 :                 u8 byte = in->s6_addr[i];
    2308               0 :                 *cp++ = "0123456789abcdef"[byte & 0x0f];
    2309               0 :                 *cp++ = '.';
    2310               0 :                 *cp++ = "0123456789abcdef"[byte >> 4];
    2311               0 :                 *cp++ = '.';
    2312                 :         }
    2313               0 :         assert(cp + strlen("ip6.arpa") < buf+sizeof(buf));
    2314               0 :         memcpy(cp, "ip6.arpa", strlen("ip6.arpa")+1);
    2315               0 :         log(EVDNS_LOG_DEBUG, "Resolve requested for %s (reverse)", buf);
    2316               0 :         req = request_new(TYPE_PTR, buf, flags, callback, ptr);
    2317               0 :         if (!req) return 1;
    2318               0 :         request_submit(req);
    2319               0 :         return 0;
    2320                 : }
    2321                 : 
    2322                 : /*/////////////////////////////////////////////////////////////////// */
    2323                 : /* Search support */
    2324                 : /* */
    2325                 : /* the libc resolver has support for searching a number of domains */
    2326                 : /* to find a name. If nothing else then it takes the single domain */
    2327                 : /* from the gethostname() call. */
    2328                 : /* */
    2329                 : /* It can also be configured via the domain and search options in a */
    2330                 : /* resolv.conf. */
    2331                 : /* */
    2332                 : /* The ndots option controls how many dots it takes for the resolver */
    2333                 : /* to decide that a name is non-local and so try a raw lookup first. */
    2334                 : 
    2335                 : struct search_domain {
    2336                 :         int len;
    2337                 :         struct search_domain *next;
    2338                 :         /* the text string is appended to this structure */
    2339                 : };
    2340                 : 
    2341                 : struct search_state {
    2342                 :         int refcount;
    2343                 :         int ndots;
    2344                 :         int num_domains;
    2345                 :         struct search_domain *head;
    2346                 : };
    2347                 : 
    2348                 : static struct search_state *global_search_state = NULL;
    2349                 : 
    2350                 : static void
    2351               0 : search_state_decref(struct search_state *const state) {
    2352               0 :         if (!state) return;
    2353               0 :         state->refcount--;
    2354               0 :         if (!state->refcount) {
    2355                 :                 struct search_domain *next, *dom;
    2356               0 :                 for (dom = state->head; dom; dom = next) {
    2357               0 :                         next = dom->next;
    2358               0 :                         free(dom);
    2359                 :                 }
    2360               0 :                 free(state);
    2361                 :         }
    2362                 : }
    2363                 : 
    2364                 : static struct search_state *
    2365               0 : search_state_new(void) {
    2366               0 :         struct search_state *state = (struct search_state *) malloc(sizeof(struct search_state));
    2367               0 :         if (!state) return NULL;
    2368               0 :         memset(state, 0, sizeof(struct search_state));
    2369               0 :         state->refcount = 1;
    2370               0 :         state->ndots = 1;
    2371                 : 
    2372               0 :         return state;
    2373                 : }
    2374                 : 
    2375                 : static void
    2376               0 : search_postfix_clear(void) {
    2377               0 :         search_state_decref(global_search_state);
    2378                 : 
    2379               0 :         global_search_state = search_state_new();
    2380               0 : }
    2381                 : 
    2382                 : /* exported function */
    2383                 : void
    2384               0 : evdns_search_clear(void) {
    2385               0 :         search_postfix_clear();
    2386               0 : }
    2387                 : 
    2388                 : static void
    2389               0 : search_postfix_add(const char *domain) {
    2390                 :         int domain_len;
    2391                 :         struct search_domain *sdomain;
    2392               0 :         while (domain[0] == '.') domain++;
    2393               0 :         domain_len = strlen(domain);
    2394                 : 
    2395               0 :         if (!global_search_state) global_search_state = search_state_new();
    2396               0 :         if (!global_search_state) return;
    2397               0 :         global_search_state->num_domains++;
    2398                 : 
    2399               0 :         sdomain = (struct search_domain *) malloc(sizeof(struct search_domain) + domain_len);
    2400               0 :         if (!sdomain) return;
    2401               0 :         memcpy( ((u8 *) sdomain) + sizeof(struct search_domain), domain, domain_len);
    2402               0 :         sdomain->next = global_search_state->head;
    2403               0 :         sdomain->len = domain_len;
    2404                 : 
    2405               0 :         global_search_state->head = sdomain;
    2406                 : }
    2407                 : 
    2408                 : /* reverse the order of members in the postfix list. This is needed because, */
    2409                 : /* when parsing resolv.conf we push elements in the wrong order */
    2410                 : static void
    2411               0 : search_reverse(void) {
    2412               0 :         struct search_domain *cur, *prev = NULL, *next;
    2413               0 :         cur = global_search_state->head;
    2414               0 :         while (cur) {
    2415               0 :                 next = cur->next;
    2416               0 :                 cur->next = prev;
    2417               0 :                 prev = cur;
    2418               0 :                 cur = next;
    2419                 :         }
    2420                 : 
    2421               0 :         global_search_state->head = prev;
    2422               0 : }
    2423                 : 
    2424                 : /* exported function */
    2425                 : void
    2426               0 : evdns_search_add(const char *domain) {
    2427               0 :         search_postfix_add(domain);
    2428               0 : }
    2429                 : 
    2430                 : /* exported function */
    2431                 : void
    2432               0 : evdns_search_ndots_set(const int ndots) {
    2433               0 :         if (!global_search_state) global_search_state = search_state_new();
    2434               0 :         if (!global_search_state) return;
    2435               0 :         global_search_state->ndots = ndots;
    2436                 : }
    2437                 : 
    2438                 : static void
    2439               0 : search_set_from_hostname(void) {
    2440                 :         char hostname[HOST_NAME_MAX + 1], *domainname;
    2441                 : 
    2442               0 :         search_postfix_clear();
    2443               0 :         if (gethostname(hostname, sizeof(hostname))) return;
    2444               0 :         domainname = strchr(hostname, '.');
    2445               0 :         if (!domainname) return;
    2446               0 :         search_postfix_add(domainname);
    2447                 : }
    2448                 : 
    2449                 : /* warning: returns malloced string */
    2450                 : static char *
    2451               0 : search_make_new(const struct search_state *const state, int n, const char *const base_name) {
    2452               0 :         const int base_len = strlen(base_name);
    2453               0 :         const char need_to_append_dot = base_name[base_len - 1] == '.' ? 0 : 1;
    2454                 :         struct search_domain *dom;
    2455                 : 
    2456               0 :         for (dom = state->head; dom; dom = dom->next) {
    2457               0 :                 if (!n--) {
    2458                 :                         /* this is the postfix we want */
    2459                 :                         /* the actual postfix string is kept at the end of the structure */
    2460               0 :                         const u8 *const postfix = ((u8 *) dom) + sizeof(struct search_domain);
    2461               0 :                         const int postfix_len = dom->len;
    2462               0 :                         char *const newname = (char *) malloc(base_len + need_to_append_dot + postfix_len + 1);
    2463               0 :                         if (!newname) return NULL;
    2464               0 :                         memcpy(newname, base_name, base_len);
    2465               0 :                         if (need_to_append_dot) newname[base_len] = '.';
    2466               0 :                         memcpy(newname + base_len + need_to_append_dot, postfix, postfix_len);
    2467               0 :                         newname[base_len + need_to_append_dot + postfix_len] = 0;
    2468               0 :                         return newname;
    2469                 :                 }
    2470                 :         }
    2471                 : 
    2472                 :         /* we ran off the end of the list and still didn't find the requested string */
    2473               0 :         abort();
    2474                 :         return NULL; /* unreachable; stops warnings in some compilers. */
    2475                 : }
    2476                 : 
    2477                 : static int
    2478               0 : search_request_new(int type, const char *const name, int flags, evdns_callback_type user_callback, void *user_arg) {
    2479               0 :         assert(type == TYPE_A || type == TYPE_AAAA);
    2480               0 :         if ( ((flags & DNS_QUERY_NO_SEARCH) == 0) &&
    2481               0 :              global_search_state &&
    2482               0 :                  global_search_state->num_domains) {
    2483                 :                 /* we have some domains to search */
    2484                 :                 struct request *req;
    2485               0 :                 if (string_num_dots(name) >= global_search_state->ndots) {
    2486               0 :                         req = request_new(type, name, flags, user_callback, user_arg);
    2487               0 :                         if (!req) return 1;
    2488               0 :                         req->search_index = -1;
    2489                 :                 } else {
    2490               0 :                         char *const new_name = search_make_new(global_search_state, 0, name);
    2491               0 :                         if (!new_name) return 1;
    2492               0 :                         req = request_new(type, new_name, flags, user_callback, user_arg);
    2493               0 :                         free(new_name);
    2494               0 :                         if (!req) return 1;
    2495               0 :                         req->search_index = 0;
    2496                 :                 }
    2497               0 :                 req->search_origname = strdup(name);
    2498               0 :                 req->search_state = global_search_state;
    2499               0 :                 req->search_flags = flags;
    2500               0 :                 global_search_state->refcount++;
    2501               0 :                 request_submit(req);
    2502               0 :                 return 0;
    2503                 :         } else {
    2504               0 :                 struct request *const req = request_new(type, name, flags, user_callback, user_arg);
    2505               0 :                 if (!req) return 1;
    2506               0 :                 request_submit(req);
    2507               0 :                 return 0;
    2508                 :         }
    2509                 : }
    2510                 : 
    2511                 : /* this is called when a request has failed to find a name. We need to check */
    2512                 : /* if it is part of a search and, if so, try the next name in the list */
    2513                 : /* returns: */
    2514                 : /*   0 another request has been submitted */
    2515                 : /*   1 no more requests needed */
    2516                 : static int
    2517               0 : search_try_next(struct request *const req) {
    2518               0 :         if (req->search_state) {
    2519                 :                 /* it is part of a search */
    2520                 :                 char *new_name;
    2521                 :                 struct request *newreq;
    2522               0 :                 req->search_index++;
    2523               0 :                 if (req->search_index >= req->search_state->num_domains) {
    2524                 :                         /* no more postfixes to try, however we may need to try */
    2525                 :                         /* this name without a postfix */
    2526               0 :                         if (string_num_dots(req->search_origname) < req->search_state->ndots) {
    2527                 :                                 /* yep, we need to try it raw */
    2528               0 :                                 newreq = request_new(req->request_type, req->search_origname, req->search_flags, req->user_callback, req->user_pointer);
    2529               0 :                                 log(EVDNS_LOG_DEBUG, "Search: trying raw query %s", req->search_origname);
    2530               0 :                                 if (newreq) {
    2531               0 :                                         request_submit(newreq);
    2532               0 :                                         return 0;
    2533                 :                                 }
    2534                 :                         }
    2535               0 :                         return 1;
    2536                 :                 }
    2537                 : 
    2538               0 :                 new_name = search_make_new(req->search_state, req->search_index, req->search_origname);
    2539               0 :                 if (!new_name) return 1;
    2540               0 :                 log(EVDNS_LOG_DEBUG, "Search: now trying %s (%d)", new_name, req->search_index);
    2541               0 :                 newreq = request_new(req->request_type, new_name, req->search_flags, req->user_callback, req->user_pointer);
    2542               0 :                 free(new_name);
    2543               0 :                 if (!newreq) return 1;
    2544               0 :                 newreq->search_origname = req->search_origname;
    2545               0 :                 req->search_origname = NULL;
    2546               0 :                 newreq->search_state = req->search_state;
    2547               0 :                 newreq->search_flags = req->search_flags;
    2548               0 :                 newreq->search_index = req->search_index;
    2549               0 :                 newreq->search_state->refcount++;
    2550               0 :                 request_submit(newreq);
    2551               0 :                 return 0;
    2552                 :         }
    2553               0 :         return 1;
    2554                 : }
    2555                 : 
    2556                 : static void
    2557               0 : search_request_finished(struct request *const req) {
    2558               0 :         if (req->search_state) {
    2559               0 :                 search_state_decref(req->search_state);
    2560               0 :                 req->search_state = NULL;
    2561                 :         }
    2562               0 :         if (req->search_origname) {
    2563               0 :                 free(req->search_origname);
    2564               0 :                 req->search_origname = NULL;
    2565                 :         }
    2566               0 : }
    2567                 : 
    2568                 : /*/////////////////////////////////////////////////////////////////// */
    2569                 : /* Parsing resolv.conf files */
    2570                 : 
    2571                 : static void
    2572               0 : evdns_resolv_set_defaults(int flags) {
    2573                 :         /* if the file isn't found then we assume a local resolver */
    2574               0 :         if (flags & DNS_OPTION_SEARCH) search_set_from_hostname();
    2575               0 :         if (flags & DNS_OPTION_NAMESERVERS) evdns_nameserver_ip_add("127.0.0.1");
    2576               0 : }
    2577                 : 
    2578                 : #ifndef HAVE_STRTOK_R
    2579                 : static char *
    2580                 : strtok_r(char *s, const char *delim, char **state) {
    2581                 :         return strtok(s, delim);
    2582                 : }
    2583                 : #endif
    2584                 : 
    2585                 : /* helper version of atoi which returns -1 on error */
    2586                 : static int
    2587               0 : strtoint(const char *const str) {
    2588                 :         char *endptr;
    2589               0 :         const int r = strtol(str, &endptr, 10);
    2590               0 :         if (*endptr) return -1;
    2591               0 :         return r;
    2592                 : }
    2593                 : 
    2594                 : /* helper version of atoi that returns -1 on error and clips to bounds. */
    2595                 : static int
    2596               0 : strtoint_clipped(const char *const str, int min, int max)
    2597                 : {
    2598               0 :         int r = strtoint(str);
    2599               0 :         if (r == -1)
    2600               0 :                 return r;
    2601               0 :         else if (r<min)
    2602               0 :                 return min;
    2603               0 :         else if (r>max)
    2604               0 :                 return max;
    2605                 :         else
    2606               0 :                 return r;
    2607                 : }
    2608                 : 
    2609                 : /* exported function */
    2610                 : int
    2611               0 : evdns_set_option(const char *option, const char *val, int flags)
    2612                 : {
    2613               0 :         if (!strncmp(option, "ndots:", 6)) {
    2614               0 :                 const int ndots = strtoint(val);
    2615               0 :                 if (ndots == -1) return -1;
    2616               0 :                 if (!(flags & DNS_OPTION_SEARCH)) return 0;
    2617               0 :                 log(EVDNS_LOG_DEBUG, "Setting ndots to %d", ndots);
    2618               0 :                 if (!global_search_state) global_search_state = search_state_new();
    2619               0 :                 if (!global_search_state) return -1;
    2620               0 :                 global_search_state->ndots = ndots;
    2621               0 :         } else if (!strncmp(option, "timeout:", 8)) {
    2622               0 :                 const int timeout = strtoint(val);
    2623               0 :                 if (timeout == -1) return -1;
    2624               0 :                 if (!(flags & DNS_OPTION_MISC)) return 0;
    2625               0 :                 log(EVDNS_LOG_DEBUG, "Setting timeout to %d", timeout);
    2626               0 :                 global_timeout.tv_sec = timeout;
    2627               0 :         } else if (!strncmp(option, "max-timeouts:", 12)) {
    2628               0 :                 const int maxtimeout = strtoint_clipped(val, 1, 255);
    2629               0 :                 if (maxtimeout == -1) return -1;
    2630               0 :                 if (!(flags & DNS_OPTION_MISC)) return 0;
    2631               0 :                 log(EVDNS_LOG_DEBUG, "Setting maximum allowed timeouts to %d",
    2632                 :                         maxtimeout);
    2633               0 :                 global_max_nameserver_timeout = maxtimeout;
    2634               0 :         } else if (!strncmp(option, "max-inflight:", 13)) {
    2635               0 :                 const int maxinflight = strtoint_clipped(val, 1, 65000);
    2636               0 :                 if (maxinflight == -1) return -1;
    2637               0 :                 if (!(flags & DNS_OPTION_MISC)) return 0;
    2638               0 :                 log(EVDNS_LOG_DEBUG, "Setting maximum inflight requests to %d",
    2639                 :                         maxinflight);
    2640               0 :                 global_max_requests_inflight = maxinflight;
    2641               0 :         } else if (!strncmp(option, "attempts:", 9)) {
    2642               0 :                 int retries = strtoint(val);
    2643               0 :                 if (retries == -1) return -1;
    2644               0 :                 if (retries > 255) retries = 255;
    2645               0 :                 if (!(flags & DNS_OPTION_MISC)) return 0;
    2646               0 :                 log(EVDNS_LOG_DEBUG, "Setting retries to %d", retries);
    2647               0 :                 global_max_retransmits = retries;
    2648                 :         }
    2649               0 :         return 0;
    2650                 : }
    2651                 : 
    2652                 : static void
    2653               0 : resolv_conf_parse_line(char *const start, int flags) {
    2654                 :         char *strtok_state;
    2655                 :         static const char *const delims = " \t";
    2656                 : #define NEXT_TOKEN strtok_r(NULL, delims, &strtok_state)
    2657                 : 
    2658               0 :         char *const first_token = strtok_r(start, delims, &strtok_state);
    2659               0 :         if (!first_token) return;
    2660                 : 
    2661               0 :         if (!strcmp(first_token, "nameserver") && (flags & DNS_OPTION_NAMESERVERS)) {
    2662               0 :                 const char *const nameserver = NEXT_TOKEN;
    2663                 :                 struct in_addr ina;
    2664                 : 
    2665               0 :                 if (inet_aton(nameserver, &ina)) {
    2666                 :                         /* address is valid */
    2667               0 :                         evdns_nameserver_add(ina.s_addr);
    2668                 :                 }
    2669               0 :         } else if (!strcmp(first_token, "domain") && (flags & DNS_OPTION_SEARCH)) {
    2670               0 :                 const char *const domain = NEXT_TOKEN;
    2671               0 :                 if (domain) {
    2672               0 :                         search_postfix_clear();
    2673               0 :                         search_postfix_add(domain);
    2674                 :                 }
    2675               0 :         } else if (!strcmp(first_token, "search") && (flags & DNS_OPTION_SEARCH)) {
    2676                 :                 const char *domain;
    2677               0 :                 search_postfix_clear();
    2678                 : 
    2679               0 :                 while ((domain = NEXT_TOKEN)) {
    2680               0 :                         search_postfix_add(domain);
    2681                 :                 }
    2682               0 :                 search_reverse();
    2683               0 :         } else if (!strcmp(first_token, "options")) {
    2684                 :                 const char *option;
    2685               0 :                 while ((option = NEXT_TOKEN)) {
    2686               0 :                         const char *val = strchr(option, ':');
    2687               0 :                         evdns_set_option(option, val ? val+1 : "", flags);
    2688                 :                 }
    2689                 :         }
    2690                 : #undef NEXT_TOKEN
    2691                 : }
    2692                 : 
    2693                 : /* exported function */
    2694                 : /* returns: */
    2695                 : /*   0 no errors */
    2696                 : /*   1 failed to open file */
    2697                 : /*   2 failed to stat file */
    2698                 : /*   3 file too large */
    2699                 : /*   4 out of memory */
    2700                 : /*   5 short read from file */
    2701                 : int
    2702               0 : evdns_resolv_conf_parse(int flags, const char *const filename) {
    2703                 :         struct stat st;
    2704                 :         int fd, n, r;
    2705                 :         u8 *resolv;
    2706                 :         char *start;
    2707               0 :         int err = 0;
    2708                 : 
    2709               0 :         log(EVDNS_LOG_DEBUG, "Parsing resolv.conf file %s", filename);
    2710                 : 
    2711               0 :         fd = open(filename, O_RDONLY);
    2712               0 :         if (fd < 0) {
    2713               0 :                 evdns_resolv_set_defaults(flags);
    2714               0 :                 return 1;
    2715                 :         }
    2716                 : 
    2717               0 :         if (fstat(fd, &st)) { err = 2; goto out1; }
    2718               0 :         if (!st.st_size) {
    2719               0 :                 evdns_resolv_set_defaults(flags);
    2720               0 :                 err = (flags & DNS_OPTION_NAMESERVERS) ? 6 : 0;
    2721               0 :                 goto out1;
    2722                 :         }
    2723               0 :         if (st.st_size > 65535) { err = 3; goto out1; }  /* no resolv.conf should be any bigger */
    2724                 : 
    2725               0 :         resolv = (u8 *) malloc((size_t)st.st_size + 1);
    2726               0 :         if (!resolv) { err = 4; goto out1; }
    2727                 : 
    2728               0 :         n = 0;
    2729               0 :         while ((r = read(fd, resolv+n, (size_t)st.st_size-n)) > 0) {
    2730               0 :                 n += r;
    2731               0 :                 if (n == st.st_size)
    2732               0 :                         break;
    2733               0 :                 assert(n < st.st_size);
    2734                 :         }
    2735               0 :         if (r < 0) { err = 5; goto out2; }
    2736               0 :         resolv[n] = 0;   /* we malloced an extra byte; this should be fine. */
    2737                 : 
    2738               0 :         start = (char *) resolv;
    2739                 :         for (;;) {
    2740               0 :                 char *const newline = strchr(start, '\n');
    2741               0 :                 if (!newline) {
    2742               0 :                         resolv_conf_parse_line(start, flags);
    2743                 :                         break;
    2744                 :                 } else {
    2745               0 :                         *newline = 0;
    2746               0 :                         resolv_conf_parse_line(start, flags);
    2747               0 :                         start = newline + 1;
    2748                 :                 }
    2749               0 :         }
    2750                 : 
    2751               0 :         if (!server_head && (flags & DNS_OPTION_NAMESERVERS)) {
    2752                 :                 /* no nameservers were configured. */
    2753               0 :                 evdns_nameserver_ip_add("127.0.0.1");
    2754               0 :                 err = 6;
    2755                 :         }
    2756               0 :         if (flags & DNS_OPTION_SEARCH && (!global_search_state || global_search_state->num_domains == 0)) {
    2757               0 :                 search_set_from_hostname();
    2758                 :         }
    2759                 : 
    2760                 : out2:
    2761               0 :         free(resolv);
    2762                 : out1:
    2763               0 :         close(fd);
    2764               0 :         return err;
    2765                 : }
    2766                 : 
    2767                 : #ifdef WIN32
    2768                 : /* Add multiple nameservers from a space-or-comma-separated list. */
    2769                 : static int
    2770                 : evdns_nameserver_ip_add_line(const char *ips) {
    2771                 :         const char *addr;
    2772                 :         char *buf;
    2773                 :         int r;
    2774                 :         while (*ips) {
    2775                 :                 while (ISSPACE(*ips) || *ips == ',' || *ips == '\t')
    2776                 :                         ++ips;
    2777                 :                 addr = ips;
    2778                 :                 while (ISDIGIT(*ips) || *ips == '.' || *ips == ':')
    2779                 :                         ++ips;
    2780                 :                 buf = malloc(ips-addr+1);
    2781                 :                 if (!buf) return 4;
    2782                 :                 memcpy(buf, addr, ips-addr);
    2783                 :                 buf[ips-addr] = '\0';
    2784                 :                 r = evdns_nameserver_ip_add(buf);
    2785                 :                 free(buf);
    2786                 :                 if (r) return r;
    2787                 :         }
    2788                 :         return 0;
    2789                 : }
    2790                 : 
    2791                 : typedef DWORD(WINAPI *GetNetworkParams_fn_t)(FIXED_INFO *, DWORD*);
    2792                 : 
    2793                 : /* Use the windows GetNetworkParams interface in iphlpapi.dll to */
    2794                 : /* figure out what our nameservers are. */
    2795                 : static int
    2796                 : load_nameservers_with_getnetworkparams(void)
    2797                 : {
    2798                 :         /* Based on MSDN examples and inspection of  c-ares code. */
    2799                 :         FIXED_INFO *fixed;
    2800                 :         HMODULE handle = 0;
    2801                 :         ULONG size = sizeof(FIXED_INFO);
    2802                 :         void *buf = NULL;
    2803                 :         int status = 0, r, added_any;
    2804                 :         IP_ADDR_STRING *ns;
    2805                 :         GetNetworkParams_fn_t fn;
    2806                 : 
    2807                 :         if (!(handle = LoadLibrary("iphlpapi.dll"))) {
    2808                 :                 log(EVDNS_LOG_WARN, "Could not open iphlpapi.dll");
    2809                 :                 status = -1;
    2810                 :                 goto done;
    2811                 :         }
    2812                 :         if (!(fn = (GetNetworkParams_fn_t) GetProcAddress(handle, "GetNetworkParams"))) {
    2813                 :                 log(EVDNS_LOG_WARN, "Could not get address of function.");
    2814                 :                 status = -1;
    2815                 :                 goto done;
    2816                 :         }
    2817                 : 
    2818                 :         buf = malloc(size);
    2819                 :         if (!buf) { status = 4; goto done; }
    2820                 :         fixed = buf;
    2821                 :         r = fn(fixed, &size);
    2822                 :         if (r != ERROR_SUCCESS && r != ERROR_BUFFER_OVERFLOW) {
    2823                 :                 status = -1;
    2824                 :                 goto done;
    2825                 :         }
    2826                 :         if (r != ERROR_SUCCESS) {
    2827                 :                 free(buf);
    2828                 :                 buf = malloc(size);
    2829                 :                 if (!buf) { status = 4; goto done; }
    2830                 :                 fixed = buf;
    2831                 :                 r = fn(fixed, &size);
    2832                 :                 if (r != ERROR_SUCCESS) {
    2833                 :                         log(EVDNS_LOG_DEBUG, "fn() failed.");
    2834                 :                         status = -1;
    2835                 :                         goto done;
    2836                 :                 }
    2837                 :         }
    2838                 : 
    2839                 :         assert(fixed);
    2840                 :         added_any = 0;
    2841                 :         ns = &(fixed->DnsServerList);
    2842                 :         while (ns) {
    2843                 :                 r = evdns_nameserver_ip_add_line(ns->IpAddress.String);
    2844                 :                 if (r) {
    2845                 :                         log(EVDNS_LOG_DEBUG,"Could not add nameserver %s to list,error: %d",
    2846                 :                                 (ns->IpAddress.String),(int)GetLastError());
    2847                 :                         status = r;
    2848                 :                         goto done;
    2849                 :                 } else {
    2850                 :                         log(EVDNS_LOG_DEBUG,"Succesfully added %s as nameserver",ns->IpAddress.String);
    2851                 :                 }
    2852                 : 
    2853                 :                 added_any++;
    2854                 :                 ns = ns->Next;
    2855                 :         }
    2856                 : 
    2857                 :         if (!added_any) {
    2858                 :                 log(EVDNS_LOG_DEBUG, "No nameservers added.");
    2859                 :                 status = -1;
    2860                 :         }
    2861                 : 
    2862                 :  done:
    2863                 :         if (buf)
    2864                 :                 free(buf);
    2865                 :         if (handle)
    2866                 :                 FreeLibrary(handle);
    2867                 :         return status;
    2868                 : }
    2869                 : 
    2870                 : static int
    2871                 : config_nameserver_from_reg_key(HKEY key, const char *subkey)
    2872                 : {
    2873                 :         char *buf;
    2874                 :         DWORD bufsz = 0, type = 0;
    2875                 :         int status = 0;
    2876                 : 
    2877                 :         if (RegQueryValueEx(key, subkey, 0, &type, NULL, &bufsz)
    2878                 :             != ERROR_MORE_DATA)
    2879                 :                 return -1;
    2880                 :         if (!(buf = malloc(bufsz)))
    2881                 :                 return -1;
    2882                 : 
    2883                 :         if (RegQueryValueEx(key, subkey, 0, &type, (LPBYTE)buf, &bufsz)
    2884                 :             == ERROR_SUCCESS && bufsz > 1) {
    2885                 :                 status = evdns_nameserver_ip_add_line(buf);
    2886                 :         }
    2887                 : 
    2888                 :         free(buf);
    2889                 :         return status;
    2890                 : }
    2891                 : 
    2892                 : #define SERVICES_KEY "System\\CurrentControlSet\\Services\\"
    2893                 : #define WIN_NS_9X_KEY  SERVICES_KEY "VxD\\MSTCP"
    2894                 : #define WIN_NS_NT_KEY  SERVICES_KEY "Tcpip\\Parameters"
    2895                 : 
    2896                 : static int
    2897                 : load_nameservers_from_registry(void)
    2898                 : {
    2899                 :         int found = 0;
    2900                 :         int r;
    2901                 : #define TRY(k, name) \
    2902                 :         if (!found && config_nameserver_from_reg_key(k,name) == 0) {    \
    2903                 :                 log(EVDNS_LOG_DEBUG,"Found nameservers in %s/%s",#k,name); \
    2904                 :                 found = 1;                                              \
    2905                 :         } else if (!found) {                                            \
    2906                 :                 log(EVDNS_LOG_DEBUG,"Didn't find nameservers in %s/%s", \
    2907                 :                     #k,#name);                                          \
    2908                 :         }
    2909                 : 
    2910                 :         if (((int)GetVersion()) > 0) { /* NT */
    2911                 :                 HKEY nt_key = 0, interfaces_key = 0;
    2912                 : 
    2913                 :                 if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, WIN_NS_NT_KEY, 0,
    2914                 :                                  KEY_READ, &nt_key) != ERROR_SUCCESS) {
    2915                 :                         log(EVDNS_LOG_DEBUG,"Couldn't open nt key, %d",(int)GetLastError());
    2916                 :                         return -1;
    2917                 :                 }
    2918                 :                 r = RegOpenKeyEx(nt_key, "Interfaces", 0,
    2919                 :                              KEY_QUERY_VALUE|KEY_ENUMERATE_SUB_KEYS,
    2920                 :                              &interfaces_key);
    2921                 :                 if (r != ERROR_SUCCESS) {
    2922                 :                         log(EVDNS_LOG_DEBUG,"Couldn't open interfaces key, %d",(int)GetLastError());
    2923                 :                         return -1;
    2924                 :                 }
    2925                 :                 TRY(nt_key, "NameServer");
    2926                 :                 TRY(nt_key, "DhcpNameServer");
    2927                 :                 TRY(interfaces_key, "NameServer");
    2928                 :                 TRY(interfaces_key, "DhcpNameServer");
    2929                 :                 RegCloseKey(interfaces_key);
    2930                 :                 RegCloseKey(nt_key);
    2931                 :         } else {
    2932                 :                 HKEY win_key = 0;
    2933                 :                 if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, WIN_NS_9X_KEY, 0,
    2934                 :                                  KEY_READ, &win_key) != ERROR_SUCCESS) {
    2935                 :                         log(EVDNS_LOG_DEBUG, "Couldn't open registry key, %d", (int)GetLastError());
    2936                 :                         return -1;
    2937                 :                 }
    2938                 :                 TRY(win_key, "NameServer");
    2939                 :                 RegCloseKey(win_key);
    2940                 :         }
    2941                 : 
    2942                 :         if (found == 0) {
    2943                 :                 log(EVDNS_LOG_WARN,"Didn't find any nameservers.");
    2944                 :         }
    2945                 : 
    2946                 :         return found ? 0 : -1;
    2947                 : #undef TRY
    2948                 : }
    2949                 : 
    2950                 : static int
    2951                 : evdns_config_windows_nameservers(void)
    2952                 : {
    2953                 :         if (load_nameservers_with_getnetworkparams() == 0)
    2954                 :                 return 0;
    2955                 :         return load_nameservers_from_registry();
    2956                 : }
    2957                 : #endif
    2958                 : 
    2959                 : int
    2960               0 : evdns_init(void)
    2961                 : {
    2962               0 :         int res = 0;
    2963                 : #ifdef WIN32
    2964                 :         res = evdns_config_windows_nameservers();
    2965                 : #else
    2966               0 :         res = evdns_resolv_conf_parse(DNS_OPTIONS_ALL, "/etc/resolv.conf");
    2967                 : #endif
    2968                 : 
    2969               0 :         return (res);
    2970                 : }
    2971                 : 
    2972                 : const char *
    2973               0 : evdns_err_to_string(int err)
    2974                 : {
    2975               0 :     switch (err) {
    2976               0 :         case DNS_ERR_NONE: return "no error";
    2977               0 :         case DNS_ERR_FORMAT: return "misformatted query";
    2978               0 :         case DNS_ERR_SERVERFAILED: return "server failed";
    2979               0 :         case DNS_ERR_NOTEXIST: return "name does not exist";
    2980               0 :         case DNS_ERR_NOTIMPL: return "query not implemented";
    2981               0 :         case DNS_ERR_REFUSED: return "refused";
    2982                 : 
    2983               0 :         case DNS_ERR_TRUNCATED: return "reply truncated or ill-formed";
    2984               0 :         case DNS_ERR_UNKNOWN: return "unknown";
    2985               0 :         case DNS_ERR_TIMEOUT: return "request timed out";
    2986               0 :         case DNS_ERR_SHUTDOWN: return "dns subsystem shut down";
    2987               0 :         default: return "[Unknown error code]";
    2988                 :     }
    2989                 : }
    2990                 : 
    2991                 : void
    2992               0 : evdns_shutdown(int fail_requests)
    2993                 : {
    2994                 :         struct nameserver *server, *server_next;
    2995                 :         struct search_domain *dom, *dom_next;
    2996                 : 
    2997               0 :         while (req_head) {
    2998               0 :                 if (fail_requests)
    2999               0 :                         reply_callback(req_head, 0, DNS_ERR_SHUTDOWN, NULL);
    3000               0 :                 request_finished(req_head, &req_head);
    3001                 :         }
    3002               0 :         while (req_waiting_head) {
    3003               0 :                 if (fail_requests)
    3004               0 :                         reply_callback(req_waiting_head, 0, DNS_ERR_SHUTDOWN, NULL);
    3005               0 :                 request_finished(req_waiting_head, &req_waiting_head);
    3006                 :         }
    3007               0 :         global_requests_inflight = global_requests_waiting = 0;
    3008                 : 
    3009               0 :         for (server = server_head; server; server = server_next) {
    3010               0 :                 server_next = server->next;
    3011               0 :                 if (server->socket >= 0)
    3012               0 :                         CLOSE_SOCKET(server->socket);
    3013               0 :                 (void) event_del(&server->event);
    3014               0 :                 if (server->state == 0)
    3015               0 :                         (void) event_del(&server->timeout_event);
    3016               0 :                 free(server);
    3017               0 :                 if (server_next == server_head)
    3018               0 :                         break;
    3019                 :         }
    3020               0 :         server_head = NULL;
    3021               0 :         global_good_nameservers = 0;
    3022                 : 
    3023               0 :         if (global_search_state) {
    3024               0 :                 for (dom = global_search_state->head; dom; dom = dom_next) {
    3025               0 :                         dom_next = dom->next;
    3026               0 :                         free(dom);
    3027                 :                 }
    3028               0 :                 free(global_search_state);
    3029               0 :                 global_search_state = NULL;
    3030                 :         }
    3031               0 :         evdns_log_fn = NULL;
    3032               0 : }
    3033                 : 
    3034                 : #ifdef EVDNS_MAIN
    3035                 : void
    3036                 : main_callback(int result, char type, int count, int ttl,
    3037                 :                           void *addrs, void *orig) {
    3038                 :         char *n = (char*)orig;
    3039                 :         int i;
    3040                 :         for (i = 0; i < count; ++i) {
    3041                 :                 if (type == DNS_IPv4_A) {
    3042                 :                         printf("%s: %s\n", n, debug_ntoa(((u32*)addrs)[i]));
    3043                 :                 } else if (type == DNS_PTR) {
    3044                 :                         printf("%s: %s\n", n, ((char**)addrs)[i]);
    3045                 :                 }
    3046                 :         }
    3047                 :         if (!count) {
    3048                 :                 printf("%s: No answer (%d)\n", n, result);
    3049                 :         }
    3050                 :         fflush(stdout);
    3051                 : }
    3052                 : void
    3053                 : evdns_server_callback(struct evdns_server_request *req, void *data)
    3054                 : {
    3055                 :         int i, r;
    3056                 :         (void)data;
    3057                 :         /* dummy; give 192.168.11.11 as an answer for all A questions,
    3058                 :          *      give foo.bar.example.com as an answer for all PTR questions. */
    3059                 :         for (i = 0; i < req->nquestions; ++i) {
    3060                 :                 u32 ans = htonl(0xc0a80b0bUL);
    3061                 :                 if (req->questions[i]->type == EVDNS_TYPE_A &&
    3062                 :                         req->questions[i]->dns_question_class == EVDNS_CLASS_INET) {
    3063                 :                         printf(" -- replying for %s (A)\n", req->questions[i]->name);
    3064                 :                         r = evdns_server_request_add_a_reply(req, req->questions[i]->name,
    3065                 :                                                                                   1, &ans, 10);
    3066                 :                         if (r<0)
    3067                 :                                 printf("eeep, didn't work.\n");
    3068                 :                 } else if (req->questions[i]->type == EVDNS_TYPE_PTR &&
    3069                 :                                    req->questions[i]->dns_question_class == EVDNS_CLASS_INET) {
    3070                 :                         printf(" -- replying for %s (PTR)\n", req->questions[i]->name);
    3071                 :                         r = evdns_server_request_add_ptr_reply(req, NULL, req->questions[i]->name,
    3072                 :                                                                                         "foo.bar.example.com", 10);
    3073                 :                 } else {
    3074                 :                         printf(" -- skipping %s [%d %d]\n", req->questions[i]->name,
    3075                 :                                    req->questions[i]->type, req->questions[i]->dns_question_class);
    3076                 :                 }
    3077                 :         }
    3078                 : 
    3079                 :         r = evdns_request_respond(req, 0);
    3080                 :         if (r<0)
    3081                 :                 printf("eeek, couldn't send reply.\n");
    3082                 : }
    3083                 : 
    3084                 : void
    3085                 : logfn(int is_warn, const char *msg) {
    3086                 :   (void) is_warn;
    3087                 :   fprintf(stderr, "%s\n", msg);
    3088                 : }
    3089                 : int
    3090                 : main(int c, char **v) {
    3091                 :         int idx;
    3092                 :         int reverse = 0, verbose = 1, servertest = 0;
    3093                 :         if (c<2) {
    3094                 :                 fprintf(stderr, "syntax: %s [-x] [-v] hostname\n", v[0]);
    3095                 :                 fprintf(stderr, "syntax: %s [-servertest]\n", v[0]);
    3096                 :                 return 1;
    3097                 :         }
    3098                 :         idx = 1;
    3099                 :         while (idx < c && v[idx][0] == '-') {
    3100                 :                 if (!strcmp(v[idx], "-x"))
    3101                 :                         reverse = 1;
    3102                 :                 else if (!strcmp(v[idx], "-v"))
    3103                 :                         verbose = 1;
    3104                 :                 else if (!strcmp(v[idx], "-servertest"))
    3105                 :                         servertest = 1;
    3106                 :                 else
    3107                 :                         fprintf(stderr, "Unknown option %s\n", v[idx]);
    3108                 :                 ++idx;
    3109                 :         }
    3110                 :         event_init();
    3111                 :         if (verbose)
    3112                 :                 evdns_set_log_fn(logfn);
    3113                 :         evdns_resolv_conf_parse(DNS_OPTION_NAMESERVERS, "/etc/resolv.conf");
    3114                 :         if (servertest) {
    3115                 :                 int sock;
    3116                 :                 struct sockaddr_in my_addr;
    3117                 :                 sock = socket(PF_INET, SOCK_DGRAM, 0);
    3118                 :                 evutil_make_socket_nonblocking(sock);
    3119                 :                 my_addr.sin_family = AF_INET;
    3120                 :                 my_addr.sin_port = htons(10053);
    3121                 :                 my_addr.sin_addr.s_addr = INADDR_ANY;
    3122                 :                 if (bind(sock, (struct sockaddr*)&my_addr, sizeof(my_addr))<0) {
    3123                 :                         perror("bind");
    3124                 :                         exit(1);
    3125                 :                 }
    3126                 :                 evdns_add_server_port(sock, 0, evdns_server_callback, NULL);
    3127                 :         }
    3128                 :         for (; idx < c; ++idx) {
    3129                 :                 if (reverse) {
    3130                 :                         struct in_addr addr;
    3131                 :                         if (!inet_aton(v[idx], &addr)) {
    3132                 :                                 fprintf(stderr, "Skipping non-IP %s\n", v[idx]);
    3133                 :                                 continue;
    3134                 :                         }
    3135                 :                         fprintf(stderr, "resolving %s...\n",v[idx]);
    3136                 :                         evdns_resolve_reverse(&addr, 0, main_callback, v[idx]);
    3137                 :                 } else {
    3138                 :                         fprintf(stderr, "resolving (fwd) %s...\n",v[idx]);
    3139                 :                         evdns_resolve_ipv4(v[idx], 0, main_callback, v[idx]);
    3140                 :                 }
    3141                 :         }
    3142                 :         fflush(stdout);
    3143                 :         event_dispatch();
    3144                 :         return 0;
    3145                 : }
    3146                 : #endif

Generated by: LCOV version 1.7