root/opal/mca/event/libevent2022/libevent/evdns.c

/* [<][>][^][v][top][bottom][index][help] */

DEFINITIONS

This source file includes following definitions.
  1. evdns_get_global_base
  2. default_evdns_log_fn
  3. evdns_set_log_fn
  4. _evdns_log
  5. request_find_from_trans_id
  6. nameserver_prod_callback
  7. nameserver_probe_failed
  8. nameserver_failed
  9. nameserver_up
  10. request_trans_id_set
  11. request_finished
  12. request_reissue
  13. evdns_requests_pump_waiting_queue
  14. reply_run_callback
  15. reply_schedule_callback
  16. reply_handle
  17. name_parse
  18. reply_parse
  19. request_parse
  20. evdns_set_transaction_id_fn
  21. evdns_set_random_bytes_fn
  22. transaction_id_pick
  23. nameserver_pick
  24. nameserver_read
  25. server_port_read
  26. server_port_flush
  27. nameserver_write_waiting
  28. nameserver_ready_callback
  29. server_port_ready_callback
  30. dnslabel_table_init
  31. dnslabel_clear
  32. dnslabel_table_get_pos
  33. dnslabel_table_add
  34. dnsname_to_labels
  35. evdns_request_len
  36. evdns_request_data_build
  37. evdns_add_server_port_with_base
  38. evdns_add_server_port
  39. evdns_close_server_port
  40. evdns_server_request_add_reply
  41. evdns_server_request_add_a_reply
  42. evdns_server_request_add_aaaa_reply
  43. evdns_server_request_add_ptr_reply
  44. evdns_server_request_add_cname_reply
  45. evdns_server_request_set_flags
  46. evdns_server_request_format_response
  47. evdns_server_request_respond
  48. server_request_free_answers
  49. server_request_free
  50. server_port_free
  51. evdns_server_request_drop
  52. evdns_server_request_get_requesting_addr
  53. evdns_request_timeout_callback
  54. evdns_request_transmit_to
  55. evdns_request_transmit
  56. nameserver_probe_callback
  57. nameserver_send_probe
  58. evdns_transmit
  59. evdns_base_count_nameservers
  60. evdns_count_nameservers
  61. evdns_base_clear_nameservers_and_suspend
  62. evdns_clear_nameservers_and_suspend
  63. evdns_base_resume
  64. evdns_resume
  65. _evdns_nameserver_add_impl
  66. evdns_base_nameserver_add
  67. evdns_nameserver_add
  68. sockaddr_setport
  69. sockaddr_getport
  70. evdns_base_nameserver_ip_add
  71. evdns_nameserver_ip_add
  72. evdns_base_nameserver_sockaddr_add
  73. evdns_request_remove
  74. evdns_request_insert
  75. string_num_dots
  76. request_new
  77. request_submit
  78. evdns_cancel_request
  79. evdns_base_resolve_ipv4
  80. evdns_resolve_ipv4
  81. evdns_base_resolve_ipv6
  82. evdns_resolve_ipv6
  83. evdns_base_resolve_reverse
  84. evdns_resolve_reverse
  85. evdns_base_resolve_reverse_ipv6
  86. evdns_resolve_reverse_ipv6
  87. search_state_decref
  88. search_state_new
  89. search_postfix_clear
  90. evdns_base_search_clear
  91. evdns_search_clear
  92. search_postfix_add
  93. search_reverse
  94. evdns_base_search_add
  95. evdns_search_add
  96. evdns_base_search_ndots_set
  97. evdns_search_ndots_set
  98. search_set_from_hostname
  99. search_make_new
  100. search_request_new
  101. search_try_next
  102. search_request_finished
  103. evdns_resolv_set_defaults
  104. strtok_r
  105. strtoint
  106. strtotimeval
  107. strtoint_clipped
  108. evdns_base_set_max_requests_inflight
  109. evdns_base_set_option
  110. str_matches_option
  111. evdns_base_set_option_impl
  112. evdns_set_option
  113. resolv_conf_parse_line
  114. evdns_base_resolv_conf_parse
  115. evdns_get_default_hosts_filename
  116. evdns_base_resolv_conf_parse_impl
  117. evdns_resolv_conf_parse
  118. evdns_nameserver_ip_add_line
  119. load_nameservers_with_getnetworkparams
  120. config_nameserver_from_reg_key
  121. load_nameservers_from_registry
  122. evdns_base_config_windows_nameservers
  123. evdns_config_windows_nameservers
  124. evdns_base_new
  125. evdns_init
  126. evdns_err_to_string
  127. evdns_nameserver_free
  128. evdns_base_free_and_unlock
  129. evdns_base_free
  130. evdns_shutdown
  131. evdns_base_parse_hosts_line
  132. evdns_base_load_hosts_impl
  133. evdns_base_load_hosts
  134. evdns_err_to_getaddrinfo_err
  135. getaddrinfo_merge_err
  136. free_getaddrinfo_request
  137. add_cname_to_reply
  138. evdns_getaddrinfo_timeout_cb
  139. evdns_getaddrinfo_set_timeout
  140. evdns_result_is_answer
  141. evdns_getaddrinfo_gotresolve
  142. find_hosts_entry
  143. evdns_getaddrinfo_fromhosts
  144. evdns_getaddrinfo
  145. evdns_getaddrinfo_cancel

   1 /* Copyright 2006-2007 Niels Provos
   2  * Copyright 2007-2012 Nick Mathewson and Niels Provos
   3  *
   4  * Redistribution and use in source and binary forms, with or without
   5  * modification, are permitted provided that the following conditions
   6  * are met:
   7  * 1. Redistributions of source code must retain the above copyright
   8  *    notice, this list of conditions and the following disclaimer.
   9  * 2. Redistributions in binary form must reproduce the above copyright
  10  *    notice, this list of conditions and the following disclaimer in the
  11  *    documentation and/or other materials provided with the distribution.
  12  * 3. The name of the author may not be used to endorse or promote products
  13  *    derived from this software without specific prior written permission.
  14  *
  15  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
  16  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  17  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
  18  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
  19  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  20  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  21  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  22  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  23  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  24  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  25  */
  26 
  27 /* Based on software by Adam Langly. Adam's original message:
  28  *
  29  * Async DNS Library
  30  * Adam Langley <agl@imperialviolet.org>
  31  * http://www.imperialviolet.org/eventdns.html
  32  * Public Domain code
  33  *
  34  * This software is Public Domain. To view a copy of the public domain dedication,
  35  * visit http://creativecommons.org/licenses/publicdomain/ or send a letter to
  36  * Creative Commons, 559 Nathan Abbott Way, Stanford, California 94305, USA.
  37  *
  38  * I ask and expect, but do not require, that all derivative works contain an
  39  * attribution similar to:
  40  *      Parts developed by Adam Langley <agl@imperialviolet.org>
  41  *
  42  * You may wish to replace the word "Parts" with something else depending on
  43  * the amount of original code.
  44  *
  45  * (Derivative works does not include programs which link against, run or include
  46  * the source verbatim in their source distributions)
  47  *
  48  * Version: 0.1b
  49  */
  50 
  51 #include "opal_config.h"
  52 
  53 #include <sys/types.h>
  54 #include "event2/event-config.h"
  55 
  56 #ifndef _FORTIFY_SOURCE
  57 #define _FORTIFY_SOURCE 3
  58 #endif
  59 
  60 #include <string.h>
  61 #include <fcntl.h>
  62 #ifdef _EVENT_HAVE_SYS_TIME_H
  63 #include <sys/time.h>
  64 #endif
  65 #ifdef _EVENT_HAVE_STDINT_H
  66 #include <stdint.h>
  67 #endif
  68 #include <stdlib.h>
  69 #include <string.h>
  70 #include <errno.h>
  71 #ifdef _EVENT_HAVE_UNISTD_H
  72 #include <unistd.h>
  73 #endif
  74 #include <limits.h>
  75 #include <sys/stat.h>
  76 #include <stdio.h>
  77 #include <stdarg.h>
  78 #ifdef WIN32
  79 #include <winsock2.h>
  80 #include <ws2tcpip.h>
  81 #ifndef _WIN32_IE
  82 #define _WIN32_IE 0x400
  83 #endif
  84 #include <shlobj.h>
  85 #endif
  86 
  87 #include "event2/dns.h"
  88 #include "event2/dns_struct.h"
  89 #include "event2/dns_compat.h"
  90 #include "event2/util.h"
  91 #include "event2/event.h"
  92 #include "event2/event_struct.h"
  93 #include "event2/thread.h"
  94 
  95 #include "event2/bufferevent.h"
  96 #include "event2/bufferevent_struct.h"
  97 #include "bufferevent-internal.h"
  98 
  99 #include "defer-internal.h"
 100 #include "log-internal.h"
 101 #include "mm-internal.h"
 102 #include "strlcpy-internal.h"
 103 #include "ipv6-internal.h"
 104 #include "util-internal.h"
 105 #include "evthread-internal.h"
 106 #ifdef WIN32
 107 #include <ctype.h>
 108 #include <winsock2.h>
 109 #include <windows.h>
 110 #include <iphlpapi.h>
 111 #include <io.h>
 112 #else
 113 #include <sys/socket.h>
 114 #include <netinet/in.h>
 115 #include <arpa/inet.h>
 116 #endif
 117 
 118 #ifdef _EVENT_HAVE_NETINET_IN6_H
 119 #include <netinet/in6.h>
 120 #endif
 121 
 122 #define EVDNS_LOG_DEBUG 0
 123 #define EVDNS_LOG_WARN 1
 124 #define EVDNS_LOG_MSG 2
 125 
 126 #include <stdio.h>
 127 
 128 #undef MIN
 129 #define MIN(a,b) ((a)<(b)?(a):(b))
 130 
 131 #define ASSERT_VALID_REQUEST(req) \
 132         EVUTIL_ASSERT((req)->handle && (req)->handle->current_req == (req))
 133 
 134 #define u64 ev_uint64_t
 135 #define u32 ev_uint32_t
 136 #define u16 ev_uint16_t
 137 #define u8  ev_uint8_t
 138 
 139 /* maximum number of addresses from a single packet */
 140 /* that we bother recording */
 141 #define MAX_V4_ADDRS 32
 142 #define MAX_V6_ADDRS 32
 143 
 144 
 145 #define TYPE_A         EVDNS_TYPE_A
 146 #define TYPE_CNAME     5
 147 #define TYPE_PTR       EVDNS_TYPE_PTR
 148 #define TYPE_SOA       EVDNS_TYPE_SOA
 149 #define TYPE_AAAA      EVDNS_TYPE_AAAA
 150 
 151 #define CLASS_INET     EVDNS_CLASS_INET
 152 
 153 /* Persistent handle.  We keep this separate from 'struct request' since we
 154  * need some object to last for as long as an evdns_request is outstanding so
 155  * that it can be canceled, whereas a search request can lead to multiple
 156  * 'struct request' instances being created over its lifetime. */
 157 struct evdns_request {
 158         struct request *current_req;
 159         struct evdns_base *base;
 160 
 161         int pending_cb; /* Waiting for its callback to be invoked; not
 162                          * owned by event base any more. */
 163 
 164         /* elements used by the searching code */
 165         int search_index;
 166         struct search_state *search_state;
 167         char *search_origname;  /* needs to be free()ed */
 168         int search_flags;
 169 };
 170 
 171 struct request {
 172         u8 *request;  /* the dns packet data */
 173         u8 request_type; /* TYPE_PTR or TYPE_A or TYPE_AAAA */
 174         unsigned int request_len;
 175         int reissue_count;
 176         int tx_count;  /* the number of times that this packet has been sent */
 177         void *user_pointer;  /* the pointer given to us for this request */
 178         evdns_callback_type user_callback;
 179         struct nameserver *ns;  /* the server which we last sent it */
 180 
 181         /* these objects are kept in a circular list */
 182         /* XXX We could turn this into a CIRCLEQ. */
 183         struct request *next, *prev;
 184 
 185         struct event timeout_event;
 186 
 187         u16 trans_id;  /* the transaction id */
 188         unsigned request_appended :1;   /* true if the request pointer is data which follows this struct */
 189         unsigned transmit_me :1;  /* needs to be transmitted */
 190 
 191         /* XXXX This is a horrible hack. */
 192         char **put_cname_in_ptr; /* store the cname here if we get one. */
 193 
 194         struct evdns_base *base;
 195 
 196         struct evdns_request *handle;
 197 };
 198 
 199 struct reply {
 200         unsigned int type;
 201         unsigned int have_answer : 1;
 202         union {
 203                 struct {
 204                         u32 addrcount;
 205                         u32 addresses[MAX_V4_ADDRS];
 206                 } a;
 207                 struct {
 208                         u32 addrcount;
 209                         struct in6_addr addresses[MAX_V6_ADDRS];
 210                 } aaaa;
 211                 struct {
 212                         char name[HOST_NAME_MAX];
 213                 } ptr;
 214         } data;
 215 };
 216 
 217 struct nameserver {
 218         evutil_socket_t socket;  /* a connected UDP socket */
 219         struct sockaddr_storage address;
 220         ev_socklen_t addrlen;
 221         int failed_times;  /* number of times which we have given this server a chance */
 222         int timedout;  /* number of times in a row a request has timed out */
 223         struct event event;
 224         /* these objects are kept in a circular list */
 225         struct nameserver *next, *prev;
 226         struct event timeout_event;  /* used to keep the timeout for */
 227                                      /* when we next probe this server. */
 228                                      /* Valid if state == 0 */
 229         /* Outstanding probe request for this nameserver, if any */
 230         struct evdns_request *probe_request;
 231         char state;  /* zero if we think that this server is down */
 232         char choked;  /* true if we have an EAGAIN from this server's socket */
 233         char write_waiting;  /* true if we are waiting for EV_WRITE events */
 234         struct evdns_base *base;
 235 };
 236 
 237 
 238 /* Represents a local port where we're listening for DNS requests. Right now, */
 239 /* only UDP is supported. */
 240 struct evdns_server_port {
 241         evutil_socket_t socket; /* socket we use to read queries and write replies. */
 242         int refcnt; /* reference count. */
 243         char choked; /* Are we currently blocked from writing? */
 244         char closing; /* Are we trying to close this port, pending writes? */
 245         evdns_request_callback_fn_type user_callback; /* Fn to handle requests */
 246         void *user_data; /* Opaque pointer passed to user_callback */
 247         struct event event; /* Read/write event */
 248         /* circular list of replies that we want to write. */
 249         struct server_request *pending_replies;
 250         struct event_base *event_base;
 251 
 252 #ifndef _EVENT_DISABLE_THREAD_SUPPORT
 253         void *lock;
 254 #endif
 255 };
 256 
 257 /* Represents part of a reply being built.      (That is, a single RR.) */
 258 struct server_reply_item {
 259         struct server_reply_item *next; /* next item in sequence. */
 260         char *name; /* name part of the RR */
 261         u16 type; /* The RR type */
 262         u16 class; /* The RR class (usually CLASS_INET) */
 263         u32 ttl; /* The RR TTL */
 264         char is_name; /* True iff data is a label */
 265         u16 datalen; /* Length of data; -1 if data is a label */
 266         void *data; /* The contents of the RR */
 267 };
 268 
 269 /* Represents a request that we've received as a DNS server, and holds */
 270 /* the components of the reply as we're constructing it. */
 271 struct server_request {
 272         /* Pointers to the next and previous entries on the list of replies */
 273         /* that we're waiting to write.  Only set if we have tried to respond */
 274         /* and gotten EAGAIN. */
 275         struct server_request *next_pending;
 276         struct server_request *prev_pending;
 277 
 278         u16 trans_id; /* Transaction id. */
 279         struct evdns_server_port *port; /* Which port received this request on? */
 280         struct sockaddr_storage addr; /* Where to send the response */
 281         ev_socklen_t addrlen; /* length of addr */
 282 
 283         int n_answer; /* how many answer RRs have been set? */
 284         int n_authority; /* how many authority RRs have been set? */
 285         int n_additional; /* how many additional RRs have been set? */
 286 
 287         struct server_reply_item *answer; /* linked list of answer RRs */
 288         struct server_reply_item *authority; /* linked list of authority RRs */
 289         struct server_reply_item *additional; /* linked list of additional RRs */
 290 
 291         /* Constructed response.  Only set once we're ready to send a reply. */
 292         /* Once this is set, the RR fields are cleared, and no more should be set. */
 293         char *response;
 294         size_t response_len;
 295 
 296         /* Caller-visible fields: flags, questions. */
 297         struct evdns_server_request base;
 298 };
 299 
 300 struct evdns_base {
 301         /* An array of n_req_heads circular lists for inflight requests.
 302          * Each inflight request req is in req_heads[req->trans_id % n_req_heads].
 303          */
 304         struct request **req_heads;
 305         /* A circular list of requests that we're waiting to send, but haven't
 306          * sent yet because there are too many requests inflight */
 307         struct request *req_waiting_head;
 308         /* A circular list of nameservers. */
 309         struct nameserver *server_head;
 310         int n_req_heads;
 311 
 312         struct event_base *event_base;
 313 
 314         /* The number of good nameservers that we have */
 315         int global_good_nameservers;
 316 
 317         /* inflight requests are contained in the req_head list */
 318         /* and are actually going out across the network */
 319         int global_requests_inflight;
 320         /* requests which aren't inflight are in the waiting list */
 321         /* and are counted here */
 322         int global_requests_waiting;
 323 
 324         int global_max_requests_inflight;
 325 
 326         struct timeval global_timeout;  /* 5 seconds by default */
 327         int global_max_reissues;  /* a reissue occurs when we get some errors from the server */
 328         int global_max_retransmits;  /* number of times we'll retransmit a request which timed out */
 329         /* number of timeouts in a row before we consider this server to be down */
 330         int global_max_nameserver_timeout;
 331         /* true iff we will use the 0x20 hack to prevent poisoning attacks. */
 332         int global_randomize_case;
 333 
 334         /* The first time that a nameserver fails, how long do we wait before
 335          * probing to see if it has returned?  */
 336         struct timeval global_nameserver_probe_initial_timeout;
 337 
 338         /** Port to bind to for outgoing DNS packets. */
 339         struct sockaddr_storage global_outgoing_address;
 340         /** ev_socklen_t for global_outgoing_address. 0 if it isn't set. */
 341         ev_socklen_t global_outgoing_addrlen;
 342 
 343         struct timeval global_getaddrinfo_allow_skew;
 344 
 345         int getaddrinfo_ipv4_timeouts;
 346         int getaddrinfo_ipv6_timeouts;
 347         int getaddrinfo_ipv4_answered;
 348         int getaddrinfo_ipv6_answered;
 349 
 350         struct search_state *global_search_state;
 351 
 352         TAILQ_HEAD(hosts_list, hosts_entry) hostsdb;
 353 
 354 #ifndef _EVENT_DISABLE_THREAD_SUPPORT
 355         void *lock;
 356 #endif
 357 };
 358 
 359 struct hosts_entry {
 360         TAILQ_ENTRY(hosts_entry) next;
 361         union {
 362                 struct sockaddr sa;
 363                 struct sockaddr_in sin;
 364                 struct sockaddr_in6 sin6;
 365         } addr;
 366         int addrlen;
 367         char hostname[1];
 368 };
 369 
 370 static struct evdns_base *current_base = NULL;
 371 
 372 struct evdns_base *
 373 evdns_get_global_base(void)
 374 {
 375         return current_base;
 376 }
 377 
 378 /* Given a pointer to an evdns_server_request, get the corresponding */
 379 /* server_request. */
 380 #define TO_SERVER_REQUEST(base_ptr)                                     \
 381         ((struct server_request*)                                       \
 382           (((char*)(base_ptr) - evutil_offsetof(struct server_request, base))))
 383 
 384 #define REQ_HEAD(base, id) ((base)->req_heads[id % (base)->n_req_heads])
 385 
 386 static struct nameserver *nameserver_pick(struct evdns_base *base);
 387 static void evdns_request_insert(struct request *req, struct request **head);
 388 static void evdns_request_remove(struct request *req, struct request **head);
 389 static void nameserver_ready_callback(evutil_socket_t fd, short events, void *arg);
 390 static int evdns_transmit(struct evdns_base *base);
 391 static int evdns_request_transmit(struct request *req);
 392 static void nameserver_send_probe(struct nameserver *const ns);
 393 static void search_request_finished(struct evdns_request *const);
 394 static int search_try_next(struct evdns_request *const req);
 395 static struct request *search_request_new(struct evdns_base *base, struct evdns_request *handle, int type, const char *const name, int flags, evdns_callback_type user_callback, void *user_arg);
 396 static void evdns_requests_pump_waiting_queue(struct evdns_base *base);
 397 static u16 transaction_id_pick(struct evdns_base *base);
 398 static struct request *request_new(struct evdns_base *base, struct evdns_request *handle, int type, const char *name, int flags, evdns_callback_type callback, void *ptr);
 399 static void request_submit(struct request *const req);
 400 
 401 static int server_request_free(struct server_request *req);
 402 static void server_request_free_answers(struct server_request *req);
 403 static void server_port_free(struct evdns_server_port *port);
 404 static void server_port_ready_callback(evutil_socket_t fd, short events, void *arg);
 405 static int evdns_base_resolv_conf_parse_impl(struct evdns_base *base, int flags, const char *const filename);
 406 static int evdns_base_set_option_impl(struct evdns_base *base,
 407     const char *option, const char *val, int flags);
 408 static void evdns_base_free_and_unlock(struct evdns_base *base, int fail_requests);
 409 
 410 static int strtoint(const char *const str);
 411 
 412 #ifdef _EVENT_DISABLE_THREAD_SUPPORT
 413 #define EVDNS_LOCK(base)  _EVUTIL_NIL_STMT
 414 #define EVDNS_UNLOCK(base) _EVUTIL_NIL_STMT
 415 #define ASSERT_LOCKED(base) _EVUTIL_NIL_STMT
 416 #else
 417 #define EVDNS_LOCK(base)                        \
 418         EVLOCK_LOCK((base)->lock, 0)
 419 #define EVDNS_UNLOCK(base)                      \
 420         EVLOCK_UNLOCK((base)->lock, 0)
 421 #define ASSERT_LOCKED(base)                     \
 422         EVLOCK_ASSERT_LOCKED((base)->lock)
 423 #endif
 424 
 425 static void
 426 default_evdns_log_fn(int warning, const char *buf)
 427 {
 428         if (warning == EVDNS_LOG_WARN)
 429                 event_warnx("[evdns] %s", buf);
 430         else if (warning == EVDNS_LOG_MSG)
 431                 event_msgx("[evdns] %s", buf);
 432         else
 433                 event_debug(("[evdns] %s", buf));
 434 }
 435 
 436 static evdns_debug_log_fn_type evdns_log_fn = NULL;
 437 
 438 void
 439 evdns_set_log_fn(evdns_debug_log_fn_type fn)
 440 {
 441         evdns_log_fn = fn;
 442 }
 443 
 444 #ifdef __GNUC__
 445 #define EVDNS_LOG_CHECK  __attribute__ ((format(printf, 2, 3)))
 446 #else
 447 #define EVDNS_LOG_CHECK
 448 #endif
 449 
 450 static void _evdns_log(int warn, const char *fmt, ...) EVDNS_LOG_CHECK;
 451 static void
 452 _evdns_log(int warn, const char *fmt, ...)
 453 {
 454         va_list args;
 455         char buf[512];
 456         if (!evdns_log_fn)
 457                 return;
 458         va_start(args,fmt);
 459         evutil_vsnprintf(buf, sizeof(buf), fmt, args);
 460         va_end(args);
 461         if (evdns_log_fn) {
 462                 if (warn == EVDNS_LOG_MSG)
 463                         warn = EVDNS_LOG_WARN;
 464                 evdns_log_fn(warn, buf);
 465         } else {
 466                 default_evdns_log_fn(warn, buf);
 467         }
 468 
 469 }
 470 
 471 #define log _evdns_log
 472 
 473 /* This walks the list of inflight requests to find the */
 474 /* one with a matching transaction id. Returns NULL on */
 475 /* failure */
 476 static struct request *
 477 request_find_from_trans_id(struct evdns_base *base, u16 trans_id) {
 478         struct request *req = REQ_HEAD(base, trans_id);
 479         struct request *const started_at = req;
 480 
 481         ASSERT_LOCKED(base);
 482 
 483         if (req) {
 484                 do {
 485                         if (req->trans_id == trans_id) return req;
 486                         req = req->next;
 487                 } while (req != started_at);
 488         }
 489 
 490         return NULL;
 491 }
 492 
 493 /* a libevent callback function which is called when a nameserver */
 494 /* has gone down and we want to test if it has came back to life yet */
 495 static void
 496 nameserver_prod_callback(evutil_socket_t fd, short events, void *arg) {
 497         struct nameserver *const ns = (struct nameserver *) arg;
 498         (void)fd;
 499         (void)events;
 500 
 501         EVDNS_LOCK(ns->base);
 502         nameserver_send_probe(ns);
 503         EVDNS_UNLOCK(ns->base);
 504 }
 505 
 506 /* a libevent callback which is called when a nameserver probe (to see if */
 507 /* it has come back to life) times out. We increment the count of failed_times */
 508 /* and wait longer to send the next probe packet. */
 509 static void
 510 nameserver_probe_failed(struct nameserver *const ns) {
 511         struct timeval timeout;
 512         int i;
 513 
 514         ASSERT_LOCKED(ns->base);
 515         (void) evtimer_del(&ns->timeout_event);
 516         if (ns->state == 1) {
 517                 /* This can happen if the nameserver acts in a way which makes us mark */
 518                 /* it as bad and then starts sending good replies. */
 519                 return;
 520         }
 521 
 522 #define MAX_PROBE_TIMEOUT 3600
 523 #define TIMEOUT_BACKOFF_FACTOR 3
 524 
 525         memcpy(&timeout, &ns->base->global_nameserver_probe_initial_timeout,
 526             sizeof(struct timeval));
 527         for (i=ns->failed_times; i > 0 && timeout.tv_sec < MAX_PROBE_TIMEOUT; --i) {
 528                 timeout.tv_sec *= TIMEOUT_BACKOFF_FACTOR;
 529                 timeout.tv_usec *= TIMEOUT_BACKOFF_FACTOR;
 530                 if (timeout.tv_usec > 1000000) {
 531                         timeout.tv_sec += timeout.tv_usec / 1000000;
 532                         timeout.tv_usec %= 1000000;
 533                 }
 534         }
 535         if (timeout.tv_sec > MAX_PROBE_TIMEOUT) {
 536                 timeout.tv_sec = MAX_PROBE_TIMEOUT;
 537                 timeout.tv_usec = 0;
 538         }
 539 
 540         ns->failed_times++;
 541 
 542         if (evtimer_add(&ns->timeout_event, &timeout) < 0) {
 543                 char addrbuf[128];
 544                 log(EVDNS_LOG_WARN,
 545                     "Error from libevent when adding timer event for %s",
 546                     evutil_format_sockaddr_port(
 547                             (struct sockaddr *)&ns->address,
 548                             addrbuf, sizeof(addrbuf)));
 549         }
 550 }
 551 
 552 /* called when a nameserver has been deemed to have failed. For example, too */
 553 /* many packets have timed out etc */
 554 static void
 555 nameserver_failed(struct nameserver *const ns, const char *msg) {
 556         struct request *req, *started_at;
 557         struct evdns_base *base = ns->base;
 558         int i;
 559         char addrbuf[128];
 560 
 561         ASSERT_LOCKED(base);
 562         /* if this nameserver has already been marked as failed */
 563         /* then don't do anything */
 564         if (!ns->state) return;
 565 
 566         log(EVDNS_LOG_MSG, "Nameserver %s has failed: %s",
 567             evutil_format_sockaddr_port(
 568                     (struct sockaddr *)&ns->address,
 569                     addrbuf, sizeof(addrbuf)),
 570             msg);
 571 
 572         base->global_good_nameservers--;
 573         EVUTIL_ASSERT(base->global_good_nameservers >= 0);
 574         if (base->global_good_nameservers == 0) {
 575                 log(EVDNS_LOG_MSG, "All nameservers have failed");
 576         }
 577 
 578         ns->state = 0;
 579         ns->failed_times = 1;
 580 
 581         if (evtimer_add(&ns->timeout_event,
 582                 &base->global_nameserver_probe_initial_timeout) < 0) {
 583                 log(EVDNS_LOG_WARN,
 584                     "Error from libevent when adding timer event for %s",
 585                     evutil_format_sockaddr_port(
 586                             (struct sockaddr *)&ns->address,
 587                             addrbuf, sizeof(addrbuf)));
 588                 /* ???? Do more? */
 589         }
 590 
 591         /* walk the list of inflight requests to see if any can be reassigned to */
 592         /* a different server. Requests in the waiting queue don't have a */
 593         /* nameserver assigned yet */
 594 
 595         /* if we don't have *any* good nameservers then there's no point */
 596         /* trying to reassign requests to one */
 597         if (!base->global_good_nameservers) return;
 598 
 599         for (i = 0; i < base->n_req_heads; ++i) {
 600                 req = started_at = base->req_heads[i];
 601                 if (req) {
 602                         do {
 603                                 if (req->tx_count == 0 && req->ns == ns) {
 604                                         /* still waiting to go out, can be moved */
 605                                         /* to another server */
 606                                         req->ns = nameserver_pick(base);
 607                                 }
 608                                 req = req->next;
 609                         } while (req != started_at);
 610                 }
 611         }
 612 }
 613 
 614 static void
 615 nameserver_up(struct nameserver *const ns)
 616 {
 617         char addrbuf[128];
 618         ASSERT_LOCKED(ns->base);
 619         if (ns->state) return;
 620         log(EVDNS_LOG_MSG, "Nameserver %s is back up",
 621             evutil_format_sockaddr_port(
 622                     (struct sockaddr *)&ns->address,
 623                     addrbuf, sizeof(addrbuf)));
 624         evtimer_del(&ns->timeout_event);
 625         if (ns->probe_request) {
 626                 evdns_cancel_request(ns->base, ns->probe_request);
 627                 ns->probe_request = NULL;
 628         }
 629         ns->state = 1;
 630         ns->failed_times = 0;
 631         ns->timedout = 0;
 632         ns->base->global_good_nameservers++;
 633 }
 634 
 635 static void
 636 request_trans_id_set(struct request *const req, const u16 trans_id) {
 637         req->trans_id = trans_id;
 638         *((u16 *) req->request) = htons(trans_id);
 639 }
 640 
 641 /* Called to remove a request from a list and dealloc it. */
 642 /* head is a pointer to the head of the list it should be */
 643 /* removed from or NULL if the request isn't in a list. */
 644 /* when free_handle is one, free the handle as well. */
 645 static void
 646 request_finished(struct request *const req, struct request **head, int free_handle) {
 647         struct evdns_base *base = req->base;
 648         int was_inflight = (head != &base->req_waiting_head);
 649         EVDNS_LOCK(base);
 650         ASSERT_VALID_REQUEST(req);
 651 
 652         if (head)
 653                 evdns_request_remove(req, head);
 654 
 655         log(EVDNS_LOG_DEBUG, "Removing timeout for request %p", req);
 656         if (was_inflight) {
 657                 evtimer_del(&req->timeout_event);
 658                 base->global_requests_inflight--;
 659         } else {
 660                 base->global_requests_waiting--;
 661         }
 662         /* it was initialized during request_new / evtimer_assign */
 663         event_debug_unassign(&req->timeout_event);
 664 
 665         if (!req->request_appended) {
 666                 /* need to free the request data on it's own */
 667                 mm_free(req->request);
 668         } else {
 669                 /* the request data is appended onto the header */
 670                 /* so everything gets free()ed when we: */
 671         }
 672 
 673         if (req->handle) {
 674                 EVUTIL_ASSERT(req->handle->current_req == req);
 675 
 676                 if (free_handle) {
 677                         search_request_finished(req->handle);
 678                         req->handle->current_req = NULL;
 679                         if (! req->handle->pending_cb) {
 680                                 /* If we're planning to run the callback,
 681                                  * don't free the handle until later. */
 682                                 mm_free(req->handle);
 683                         }
 684                         req->handle = NULL; /* If we have a bug, let's crash
 685                                              * early */
 686                 } else {
 687                         req->handle->current_req = NULL;
 688                 }
 689         }
 690 
 691         mm_free(req);
 692 
 693         evdns_requests_pump_waiting_queue(base);
 694         EVDNS_UNLOCK(base);
 695 }
 696 
 697 /* This is called when a server returns a funny error code. */
 698 /* We try the request again with another server. */
 699 /* */
 700 /* return: */
 701 /*   0 ok */
 702 /*   1 failed/reissue is pointless */
 703 static int
 704 request_reissue(struct request *req) {
 705         const struct nameserver *const last_ns = req->ns;
 706         ASSERT_LOCKED(req->base);
 707         ASSERT_VALID_REQUEST(req);
 708         /* the last nameserver should have been marked as failing */
 709         /* by the caller of this function, therefore pick will try */
 710         /* not to return it */
 711         req->ns = nameserver_pick(req->base);
 712         if (req->ns == last_ns) {
 713                 /* ... but pick did return it */
 714                 /* not a lot of point in trying again with the */
 715                 /* same server */
 716                 return 1;
 717         }
 718 
 719         req->reissue_count++;
 720         req->tx_count = 0;
 721         req->transmit_me = 1;
 722 
 723         return 0;
 724 }
 725 
 726 /* this function looks for space on the inflight queue and promotes */
 727 /* requests from the waiting queue if it can. */
 728 /* */
 729 /* TODO: */
 730 /* add return code, see at nameserver_pick() and other functions. */
 731 static void
 732 evdns_requests_pump_waiting_queue(struct evdns_base *base) {
 733         ASSERT_LOCKED(base);
 734         while (base->global_requests_inflight < base->global_max_requests_inflight &&
 735                    base->global_requests_waiting) {
 736                 struct request *req;
 737 
 738                 EVUTIL_ASSERT(base->req_waiting_head);
 739                 req = base->req_waiting_head;
 740 
 741                 req->ns = nameserver_pick(base);
 742                 if (!req->ns)
 743                         return;
 744 
 745                 /* move a request from the waiting queue to the inflight queue */
 746                 evdns_request_remove(req, &base->req_waiting_head);
 747 
 748                 base->global_requests_waiting--;
 749                 base->global_requests_inflight++;
 750 
 751                 request_trans_id_set(req, transaction_id_pick(base));
 752 
 753                 evdns_request_insert(req, &REQ_HEAD(base, req->trans_id));
 754                 evdns_request_transmit(req);
 755                 evdns_transmit(base);
 756         }
 757 }
 758 
 759 /* TODO(nickm) document */
 760 struct deferred_reply_callback {
 761         struct deferred_cb deferred;
 762         struct evdns_request *handle;
 763         u8 request_type;
 764         u8 have_reply;
 765         u32 ttl;
 766         u32 err;
 767         evdns_callback_type user_callback;
 768         struct reply reply;
 769 };
 770 
 771 static void
 772 reply_run_callback(struct deferred_cb *d, void *user_pointer)
 773 {
 774         struct deferred_reply_callback *cb =
 775             EVUTIL_UPCAST(d, struct deferred_reply_callback, deferred);
 776 
 777         switch (cb->request_type) {
 778         case TYPE_A:
 779                 if (cb->have_reply)
 780                         cb->user_callback(DNS_ERR_NONE, DNS_IPv4_A,
 781                             cb->reply.data.a.addrcount, cb->ttl,
 782                             cb->reply.data.a.addresses,
 783                             user_pointer);
 784                 else
 785                         cb->user_callback(cb->err, 0, 0, cb->ttl, NULL, user_pointer);
 786                 break;
 787         case TYPE_PTR:
 788                 if (cb->have_reply) {
 789                         char *name = cb->reply.data.ptr.name;
 790                         cb->user_callback(DNS_ERR_NONE, DNS_PTR, 1, cb->ttl,
 791                             &name, user_pointer);
 792                 } else {
 793                         cb->user_callback(cb->err, 0, 0, cb->ttl, NULL, user_pointer);
 794                 }
 795                 break;
 796         case TYPE_AAAA:
 797                 if (cb->have_reply)
 798                         cb->user_callback(DNS_ERR_NONE, DNS_IPv6_AAAA,
 799                             cb->reply.data.aaaa.addrcount, cb->ttl,
 800                             cb->reply.data.aaaa.addresses,
 801                             user_pointer);
 802                 else
 803                         cb->user_callback(cb->err, 0, 0, cb->ttl, NULL, user_pointer);
 804                 break;
 805         default:
 806                 EVUTIL_ASSERT(0);
 807         }
 808 
 809         if (cb->handle && cb->handle->pending_cb) {
 810                 mm_free(cb->handle);
 811         }
 812 
 813         mm_free(cb);
 814 }
 815 
 816 static void
 817 reply_schedule_callback(struct request *const req, u32 ttl, u32 err, struct reply *reply)
 818 {
 819         struct deferred_reply_callback *d = mm_calloc(1, sizeof(*d));
 820 
 821         if (!d) {
 822                 event_warn("%s: Couldn't allocate space for deferred callback.",
 823                     __func__);
 824                 return;
 825         }
 826 
 827         ASSERT_LOCKED(req->base);
 828 
 829         d->request_type = req->request_type;
 830         d->user_callback = req->user_callback;
 831         d->ttl = ttl;
 832         d->err = err;
 833         if (reply) {
 834                 d->have_reply = 1;
 835                 memcpy(&d->reply, reply, sizeof(struct reply));
 836         }
 837 
 838         if (req->handle) {
 839                 req->handle->pending_cb = 1;
 840                 d->handle = req->handle;
 841         }
 842 
 843         event_deferred_cb_init(&d->deferred, reply_run_callback,
 844             req->user_pointer);
 845         event_deferred_cb_schedule(
 846                 event_base_get_deferred_cb_queue(req->base->event_base),
 847                 &d->deferred);
 848 }
 849 
 850 /* this processes a parsed reply packet */
 851 static void
 852 reply_handle(struct request *const req, u16 flags, u32 ttl, struct reply *reply) {
 853         int error;
 854         char addrbuf[128];
 855         static const int error_codes[] = {
 856                 DNS_ERR_FORMAT, DNS_ERR_SERVERFAILED, DNS_ERR_NOTEXIST,
 857                 DNS_ERR_NOTIMPL, DNS_ERR_REFUSED
 858         };
 859 
 860         ASSERT_LOCKED(req->base);
 861         ASSERT_VALID_REQUEST(req);
 862 
 863         if (flags & 0x020f || !reply || !reply->have_answer) {
 864                 /* there was an error */
 865                 if (flags & 0x0200) {
 866                         error = DNS_ERR_TRUNCATED;
 867                 } else if (flags & 0x000f) {
 868                         u16 error_code = (flags & 0x000f) - 1;
 869                         if (error_code > 4) {
 870                                 error = DNS_ERR_UNKNOWN;
 871                         } else {
 872                                 error = error_codes[error_code];
 873                         }
 874                 } else if (reply && !reply->have_answer) {
 875                         error = DNS_ERR_NODATA;
 876                 } else {
 877                         error = DNS_ERR_UNKNOWN;
 878                 }
 879 
 880                 switch (error) {
 881                 case DNS_ERR_NOTIMPL:
 882                 case DNS_ERR_REFUSED:
 883                         /* we regard these errors as marking a bad nameserver */
 884                         if (req->reissue_count < req->base->global_max_reissues) {
 885                                 char msg[64];
 886                                 evutil_snprintf(msg, sizeof(msg), "Bad response %d (%s)",
 887                                          error, evdns_err_to_string(error));
 888                                 nameserver_failed(req->ns, msg);
 889                                 if (!request_reissue(req)) return;
 890                         }
 891                         break;
 892                 case DNS_ERR_SERVERFAILED:
 893                         /* rcode 2 (servfailed) sometimes means "we
 894                          * are broken" and sometimes (with some binds)
 895                          * means "that request was very confusing."
 896                          * Treat this as a timeout, not a failure.
 897                          */
 898                         log(EVDNS_LOG_DEBUG, "Got a SERVERFAILED from nameserver"
 899                                 "at %s; will allow the request to time out.",
 900                             evutil_format_sockaddr_port(
 901                                     (struct sockaddr *)&req->ns->address,
 902                                     addrbuf, sizeof(addrbuf)));
 903                         break;
 904                 default:
 905                         /* we got a good reply from the nameserver: it is up. */
 906                         if (req->handle == req->ns->probe_request) {
 907                                 /* Avoid double-free */
 908                                 req->ns->probe_request = NULL;
 909                         }
 910 
 911                         nameserver_up(req->ns);
 912                 }
 913 
 914                 if (req->handle->search_state &&
 915                     req->request_type != TYPE_PTR) {
 916                         /* if we have a list of domains to search in,
 917                          * try the next one */
 918                         if (!search_try_next(req->handle)) {
 919                                 /* a new request was issued so this
 920                                  * request is finished and */
 921                                 /* the user callback will be made when
 922                                  * that request (or a */
 923                                 /* child of it) finishes. */
 924                                 return;
 925                         }
 926                 }
 927 
 928                 /* all else failed. Pass the failure up */
 929                 reply_schedule_callback(req, ttl, error, NULL);
 930                 request_finished(req, &REQ_HEAD(req->base, req->trans_id), 1);
 931         } else {
 932                 /* all ok, tell the user */
 933                 reply_schedule_callback(req, ttl, 0, reply);
 934                 if (req->handle == req->ns->probe_request)
 935                         req->ns->probe_request = NULL; /* Avoid double-free */
 936                 nameserver_up(req->ns);
 937                 request_finished(req, &REQ_HEAD(req->base, req->trans_id), 1);
 938         }
 939 }
 940 
 941 static int
 942 name_parse(u8 *packet, int length, int *idx, char *name_out, int name_out_len) {
 943         int name_end = -1;
 944         int j = *idx;
 945         int ptr_count = 0;
 946 #define GET32(x) do { if (j + 4 > length) goto err; memcpy(&_t32, packet + j, 4); j += 4; x = ntohl(_t32); } while (0)
 947 #define GET16(x) do { if (j + 2 > length) goto err; memcpy(&_t, packet + j, 2); j += 2; x = ntohs(_t); } while (0)
 948 #define GET8(x) do { if (j >= length) goto err; x = packet[j++]; } while (0)
 949 
 950         char *cp = name_out;
 951         const char *const end = name_out + name_out_len;
 952 
 953         /* Normally, names are a series of length prefixed strings terminated */
 954         /* with a length of 0 (the lengths are u8's < 63). */
 955         /* However, the length can start with a pair of 1 bits and that */
 956         /* means that the next 14 bits are a pointer within the current */
 957         /* packet. */
 958 
 959         for (;;) {
 960                 u8 label_len;
 961                 if (j >= length) return -1;
 962                 GET8(label_len);
 963                 if (!label_len) break;
 964                 if (label_len & 0xc0) {
 965                         u8 ptr_low;
 966                         GET8(ptr_low);
 967                         if (name_end < 0) name_end = j;
 968                         j = (((int)label_len & 0x3f) << 8) + ptr_low;
 969                         /* Make sure that the target offset is in-bounds. */
 970                         if (j < 0 || j >= length) return -1;
 971                         /* If we've jumped more times than there are characters in the
 972                          * message, we must have a loop. */
 973                         if (++ptr_count > length) return -1;
 974                         continue;
 975                 }
 976                 if (label_len > 63) return -1;
 977                 if (cp != name_out) {
 978                         if (cp + 1 >= end) return -1;
 979                         *cp++ = '.';
 980                 }
 981                 if (cp + label_len >= end) return -1;
 982                 memcpy(cp, packet + j, label_len);
 983                 cp += label_len;
 984                 j += label_len;
 985         }
 986         if (cp >= end) return -1;
 987         *cp = '\0';
 988         if (name_end < 0)
 989                 *idx = j;
 990         else
 991                 *idx = name_end;
 992         return 0;
 993  err:
 994         return -1;
 995 }
 996 
 997 /* parses a raw request from a nameserver */
 998 static int
 999 reply_parse(struct evdns_base *base, u8 *packet, int length) {
1000         int j = 0, k = 0;  /* index into packet */
1001         u16 _t;  /* used by the macros */
1002         u32 _t32;  /* used by the macros */
1003         char tmp_name[256], cmp_name[256]; /* used by the macros */
1004         int name_matches = 0;
1005 
1006         u16 trans_id, questions, answers, authority, additional, datalength;
1007         u16 flags = 0;
1008         u32 ttl, ttl_r = 0xffffffff;
1009         struct reply reply;
1010         struct request *req = NULL;
1011         unsigned int i;
1012 
1013         ASSERT_LOCKED(base);
1014 
1015         GET16(trans_id);
1016         GET16(flags);
1017         GET16(questions);
1018         GET16(answers);
1019         GET16(authority);
1020         GET16(additional);
1021         (void) authority; /* suppress "unused variable" warnings. */
1022         (void) additional; /* suppress "unused variable" warnings. */
1023 
1024         req = request_find_from_trans_id(base, trans_id);
1025         if (!req) return -1;
1026         EVUTIL_ASSERT(req->base == base);
1027 
1028         memset(&reply, 0, sizeof(reply));
1029 
1030         /* If it's not an answer, it doesn't correspond to any request. */
1031         if (!(flags & 0x8000)) return -1;  /* must be an answer */
1032         if ((flags & 0x020f) && (flags & 0x020f) != DNS_ERR_NOTEXIST) {
1033                 /* there was an error and it's not NXDOMAIN */
1034                 goto err;
1035         }
1036         /* if (!answers) return; */  /* must have an answer of some form */
1037 
1038         /* This macro skips a name in the DNS reply. */
1039 #define SKIP_NAME                                               \
1040         do { tmp_name[0] = '\0';                                \
1041                 if (name_parse(packet, length, &j, tmp_name,    \
1042                         sizeof(tmp_name))<0)                    \
1043                         goto err;                               \
1044         } while (0)
1045 #define TEST_NAME                                                       \
1046         do { tmp_name[0] = '\0';                                        \
1047                 cmp_name[0] = '\0';                                     \
1048                 k = j;                                                  \
1049                 if (name_parse(packet, length, &j, tmp_name,            \
1050                         sizeof(tmp_name))<0)                            \
1051                         goto err;                                       \
1052                 if (name_parse(req->request, req->request_len, &k,      \
1053                         cmp_name, sizeof(cmp_name))<0)                  \
1054                         goto err;                                       \
1055                 if (base->global_randomize_case) {                      \
1056                         if (strcmp(tmp_name, cmp_name) == 0)            \
1057                                 name_matches = 1;                       \
1058                 } else {                                                \
1059                         if (evutil_ascii_strcasecmp(tmp_name, cmp_name) == 0) \
1060                                 name_matches = 1;                       \
1061                 }                                                       \
1062         } while (0)
1063 
1064         reply.type = req->request_type;
1065 
1066         /* skip over each question in the reply */
1067         for (i = 0; i < questions; ++i) {
1068                 /* the question looks like
1069                  *   <label:name><u16:type><u16:class>
1070                  */
1071                 TEST_NAME;
1072                 j += 4;
1073                 if (j > length) goto err;
1074         }
1075 
1076         if (!name_matches)
1077                 goto err;
1078 
1079         /* now we have the answer section which looks like
1080          * <label:name><u16:type><u16:class><u32:ttl><u16:len><data...>
1081          */
1082 
1083         for (i = 0; i < answers; ++i) {
1084                 u16 type, class;
1085 
1086                 SKIP_NAME;
1087                 GET16(type);
1088                 GET16(class);
1089                 GET32(ttl);
1090                 GET16(datalength);
1091 
1092                 if (type == TYPE_A && class == CLASS_INET) {
1093                         int addrcount, addrtocopy;
1094                         if (req->request_type != TYPE_A) {
1095                                 j += datalength; continue;
1096                         }
1097                         if ((datalength & 3) != 0) /* not an even number of As. */
1098                             goto err;
1099                         addrcount = datalength >> 2;
1100                         addrtocopy = MIN(MAX_V4_ADDRS - reply.data.a.addrcount, (unsigned)addrcount);
1101 
1102                         ttl_r = MIN(ttl_r, ttl);
1103                         /* we only bother with the first four addresses. */
1104                         if (j + 4*addrtocopy > length) goto err;
1105                         memcpy(&reply.data.a.addresses[reply.data.a.addrcount],
1106                                    packet + j, 4*addrtocopy);
1107                         j += 4*addrtocopy;
1108                         reply.data.a.addrcount += addrtocopy;
1109                         reply.have_answer = 1;
1110                         if (reply.data.a.addrcount == MAX_V4_ADDRS) break;
1111                 } else if (type == TYPE_PTR && class == CLASS_INET) {
1112                         if (req->request_type != TYPE_PTR) {
1113                                 j += datalength; continue;
1114                         }
1115                         if (name_parse(packet, length, &j, reply.data.ptr.name,
1116                                                    sizeof(reply.data.ptr.name))<0)
1117                                 goto err;
1118                         ttl_r = MIN(ttl_r, ttl);
1119                         reply.have_answer = 1;
1120                         break;
1121                 } else if (type == TYPE_CNAME) {
1122                         char cname[HOST_NAME_MAX];
1123                         if (!req->put_cname_in_ptr || *req->put_cname_in_ptr) {
1124                                 j += datalength; continue;
1125                         }
1126                         if (name_parse(packet, length, &j, cname,
1127                                 sizeof(cname))<0)
1128                                 goto err;
1129                         *req->put_cname_in_ptr = mm_strdup(cname);
1130                 } else if (type == TYPE_AAAA && class == CLASS_INET) {
1131                         int addrcount, addrtocopy;
1132                         if (req->request_type != TYPE_AAAA) {
1133                                 j += datalength; continue;
1134                         }
1135                         if ((datalength & 15) != 0) /* not an even number of AAAAs. */
1136                                 goto err;
1137                         addrcount = datalength >> 4;  /* each address is 16 bytes long */
1138                         addrtocopy = MIN(MAX_V6_ADDRS - reply.data.aaaa.addrcount, (unsigned)addrcount);
1139                         ttl_r = MIN(ttl_r, ttl);
1140 
1141                         /* we only bother with the first four addresses. */
1142                         if (j + 16*addrtocopy > length) goto err;
1143                         memcpy(&reply.data.aaaa.addresses[reply.data.aaaa.addrcount],
1144                                    packet + j, 16*addrtocopy);
1145                         reply.data.aaaa.addrcount += addrtocopy;
1146                         j += 16*addrtocopy;
1147                         reply.have_answer = 1;
1148                         if (reply.data.aaaa.addrcount == MAX_V6_ADDRS) break;
1149                 } else {
1150                         /* skip over any other type of resource */
1151                         j += datalength;
1152                 }
1153         }
1154 
1155         if (!reply.have_answer) {
1156                 for (i = 0; i < authority; ++i) {
1157                         u16 type, class;
1158                         SKIP_NAME;
1159                         GET16(type);
1160                         GET16(class);
1161                         GET32(ttl);
1162                         GET16(datalength);
1163                         if (type == TYPE_SOA && class == CLASS_INET) {
1164                                 u32 serial, refresh, retry, expire, minimum;
1165                                 SKIP_NAME;
1166                                 SKIP_NAME;
1167                                 GET32(serial);
1168                                 GET32(refresh);
1169                                 GET32(retry);
1170                                 GET32(expire);
1171                                 GET32(minimum);
1172                                 (void)expire;
1173                                 (void)retry;
1174                                 (void)refresh;
1175                                 (void)serial;
1176                                 ttl_r = MIN(ttl_r, ttl);
1177                                 ttl_r = MIN(ttl_r, minimum);
1178                         } else {
1179                                 /* skip over any other type of resource */
1180                                 j += datalength;
1181                         }
1182                 }
1183         }
1184 
1185         if (ttl_r == 0xffffffff)
1186                 ttl_r = 0;
1187 
1188         reply_handle(req, flags, ttl_r, &reply);
1189         return 0;
1190  err:
1191         if (req)
1192                 reply_handle(req, flags, 0, NULL);
1193         return -1;
1194 }
1195 
1196 /* Parse a raw request (packet,length) sent to a nameserver port (port) from */
1197 /* a DNS client (addr,addrlen), and if it's well-formed, call the corresponding */
1198 /* callback. */
1199 static int
1200 request_parse(u8 *packet, int length, struct evdns_server_port *port, struct sockaddr *addr, ev_socklen_t addrlen)
1201 {
1202         int j = 0;      /* index into packet */
1203         u16 _t;  /* used by the macros */
1204         char tmp_name[256]; /* used by the macros */
1205 
1206         int i;
1207         u16 trans_id, flags, questions, answers, authority, additional;
1208         struct server_request *server_req = NULL;
1209 
1210         ASSERT_LOCKED(port);
1211 
1212         /* Get the header fields */
1213         GET16(trans_id);
1214         GET16(flags);
1215         GET16(questions);
1216         GET16(answers);
1217         GET16(authority);
1218         GET16(additional);
1219         (void)answers;
1220         (void)additional;
1221         (void)authority;
1222 
1223         if (flags & 0x8000) return -1; /* Must not be an answer. */
1224         flags &= 0x0110; /* Only RD and CD get preserved. */
1225 
1226         server_req = mm_malloc(sizeof(struct server_request));
1227         if (server_req == NULL) return -1;
1228         memset(server_req, 0, sizeof(struct server_request));
1229 
1230         server_req->trans_id = trans_id;
1231         memcpy(&server_req->addr, addr, addrlen);
1232         server_req->addrlen = addrlen;
1233 
1234         server_req->base.flags = flags;
1235         server_req->base.nquestions = 0;
1236         server_req->base.questions = mm_calloc(sizeof(struct evdns_server_question *), questions);
1237         if (server_req->base.questions == NULL)
1238                 goto err;
1239 
1240         for (i = 0; i < questions; ++i) {
1241                 u16 type, class;
1242                 struct evdns_server_question *q;
1243                 int namelen;
1244                 if (name_parse(packet, length, &j, tmp_name, sizeof(tmp_name))<0)
1245                         goto err;
1246                 GET16(type);
1247                 GET16(class);
1248                 namelen = (int)strlen(tmp_name);
1249                 q = mm_malloc(sizeof(struct evdns_server_question) + namelen);
1250                 if (!q)
1251                         goto err;
1252                 q->type = type;
1253                 q->dns_question_class = class;
1254                 memcpy(q->name, tmp_name, namelen+1);
1255                 server_req->base.questions[server_req->base.nquestions++] = q;
1256         }
1257 
1258         /* Ignore answers, authority, and additional. */
1259 
1260         server_req->port = port;
1261         port->refcnt++;
1262 
1263         /* Only standard queries are supported. */
1264         if (flags & 0x7800) {
1265                 evdns_server_request_respond(&(server_req->base), DNS_ERR_NOTIMPL);
1266                 return -1;
1267         }
1268 
1269         port->user_callback(&(server_req->base), port->user_data);
1270 
1271         return 0;
1272 err:
1273         if (server_req) {
1274                 if (server_req->base.questions) {
1275                         for (i = 0; i < server_req->base.nquestions; ++i)
1276                                 mm_free(server_req->base.questions[i]);
1277                         mm_free(server_req->base.questions);
1278                 }
1279                 mm_free(server_req);
1280         }
1281         return -1;
1282 
1283 #undef SKIP_NAME
1284 #undef GET32
1285 #undef GET16
1286 #undef GET8
1287 }
1288 
1289 
1290 void
1291 evdns_set_transaction_id_fn(ev_uint16_t (*fn)(void))
1292 {
1293 }
1294 
1295 void
1296 evdns_set_random_bytes_fn(void (*fn)(char *, size_t))
1297 {
1298 }
1299 
1300 /* Try to choose a strong transaction id which isn't already in flight */
1301 static u16
1302 transaction_id_pick(struct evdns_base *base) {
1303         ASSERT_LOCKED(base);
1304         for (;;) {
1305                 u16 trans_id;
1306                 evutil_secure_rng_get_bytes(&trans_id, sizeof(trans_id));
1307 
1308                 if (trans_id == 0xffff) continue;
1309                 /* now check to see if that id is already inflight */
1310                 if (request_find_from_trans_id(base, trans_id) == NULL)
1311                         return trans_id;
1312         }
1313 }
1314 
1315 /* choose a namesever to use. This function will try to ignore */
1316 /* nameservers which we think are down and load balance across the rest */
1317 /* by updating the server_head global each time. */
1318 static struct nameserver *
1319 nameserver_pick(struct evdns_base *base) {
1320         struct nameserver *started_at = base->server_head, *picked;
1321         ASSERT_LOCKED(base);
1322         if (!base->server_head) return NULL;
1323 
1324         /* if we don't have any good nameservers then there's no */
1325         /* point in trying to find one. */
1326         if (!base->global_good_nameservers) {
1327                 base->server_head = base->server_head->next;
1328                 return base->server_head;
1329         }
1330 
1331         /* remember that nameservers are in a circular list */
1332         for (;;) {
1333                 if (base->server_head->state) {
1334                         /* we think this server is currently good */
1335                         picked = base->server_head;
1336                         base->server_head = base->server_head->next;
1337                         return picked;
1338                 }
1339 
1340                 base->server_head = base->server_head->next;
1341                 if (base->server_head == started_at) {
1342                         /* all the nameservers seem to be down */
1343                         /* so we just return this one and hope for the */
1344                         /* best */
1345                         EVUTIL_ASSERT(base->global_good_nameservers == 0);
1346                         picked = base->server_head;
1347                         base->server_head = base->server_head->next;
1348                         return picked;
1349                 }
1350         }
1351 }
1352 
1353 /* this is called when a namesever socket is ready for reading */
1354 static void
1355 nameserver_read(struct nameserver *ns) {
1356         struct sockaddr_storage ss;
1357         ev_socklen_t addrlen = sizeof(ss);
1358         u8 packet[1500];
1359         char addrbuf[128];
1360         ASSERT_LOCKED(ns->base);
1361 
1362         for (;;) {
1363                 const int r = recvfrom(ns->socket, (void*)packet,
1364                     sizeof(packet), 0,
1365                     (struct sockaddr*)&ss, &addrlen);
1366                 if (r < 0) {
1367                         int err = evutil_socket_geterror(ns->socket);
1368                         if (EVUTIL_ERR_RW_RETRIABLE(err))
1369                                 return;
1370                         nameserver_failed(ns,
1371                             evutil_socket_error_to_string(err));
1372                         return;
1373                 }
1374                 if (evutil_sockaddr_cmp((struct sockaddr*)&ss,
1375                         (struct sockaddr*)&ns->address, 0)) {
1376                         log(EVDNS_LOG_WARN, "Address mismatch on received "
1377                             "DNS packet.  Apparent source was %s",
1378                             evutil_format_sockaddr_port(
1379                                     (struct sockaddr *)&ss,
1380                                     addrbuf, sizeof(addrbuf)));
1381                         return;
1382                 }
1383 
1384                 ns->timedout = 0;
1385                 reply_parse(ns->base, packet, r);
1386         }
1387 }
1388 
1389 /* Read a packet from a DNS client on a server port s, parse it, and */
1390 /* act accordingly. */
1391 static void
1392 server_port_read(struct evdns_server_port *s) {
1393         u8 packet[1500];
1394         struct sockaddr_storage addr;
1395         ev_socklen_t addrlen;
1396         int r;
1397         ASSERT_LOCKED(s);
1398 
1399         for (;;) {
1400                 addrlen = sizeof(struct sockaddr_storage);
1401                 r = recvfrom(s->socket, (void*)packet, sizeof(packet), 0,
1402                                          (struct sockaddr*) &addr, &addrlen);
1403                 if (r < 0) {
1404                         int err = evutil_socket_geterror(s->socket);
1405                         if (EVUTIL_ERR_RW_RETRIABLE(err))
1406                                 return;
1407                         log(EVDNS_LOG_WARN,
1408                             "Error %s (%d) while reading request.",
1409                             evutil_socket_error_to_string(err), err);
1410                         return;
1411                 }
1412                 request_parse(packet, r, s, (struct sockaddr*) &addr, addrlen);
1413         }
1414 }
1415 
1416 /* Try to write all pending replies on a given DNS server port. */
1417 static void
1418 server_port_flush(struct evdns_server_port *port)
1419 {
1420         struct server_request *req = port->pending_replies;
1421         ASSERT_LOCKED(port);
1422         while (req) {
1423                 int r = sendto(port->socket, req->response, (int)req->response_len, 0,
1424                            (struct sockaddr*) &req->addr, (ev_socklen_t)req->addrlen);
1425                 if (r < 0) {
1426                         int err = evutil_socket_geterror(port->socket);
1427                         if (EVUTIL_ERR_RW_RETRIABLE(err))
1428                                 return;
1429                         log(EVDNS_LOG_WARN, "Error %s (%d) while writing response to port; dropping", evutil_socket_error_to_string(err), err);
1430                 }
1431                 if (server_request_free(req)) {
1432                         /* we released the last reference to req->port. */
1433                         return;
1434                 } else {
1435                         EVUTIL_ASSERT(req != port->pending_replies);
1436                         req = port->pending_replies;
1437                 }
1438         }
1439 
1440         /* We have no more pending requests; stop listening for 'writeable' events. */
1441         (void) event_del(&port->event);
1442         event_assign(&port->event, port->event_base,
1443                                  port->socket, EV_READ | EV_PERSIST,
1444                                  server_port_ready_callback, port);
1445 
1446         if (event_add(&port->event, NULL) < 0) {
1447                 log(EVDNS_LOG_WARN, "Error from libevent when adding event for DNS server.");
1448                 /* ???? Do more? */
1449         }
1450 }
1451 
1452 /* set if we are waiting for the ability to write to this server. */
1453 /* if waiting is true then we ask libevent for EV_WRITE events, otherwise */
1454 /* we stop these events. */
1455 static void
1456 nameserver_write_waiting(struct nameserver *ns, char waiting) {
1457         ASSERT_LOCKED(ns->base);
1458         if (ns->write_waiting == waiting) return;
1459 
1460         ns->write_waiting = waiting;
1461         (void) event_del(&ns->event);
1462         event_assign(&ns->event, ns->base->event_base,
1463             ns->socket, EV_READ | (waiting ? EV_WRITE : 0) | EV_PERSIST,
1464             nameserver_ready_callback, ns);
1465         if (event_add(&ns->event, NULL) < 0) {
1466                 char addrbuf[128];
1467                 log(EVDNS_LOG_WARN, "Error from libevent when adding event for %s",
1468                     evutil_format_sockaddr_port(
1469                             (struct sockaddr *)&ns->address,
1470                             addrbuf, sizeof(addrbuf)));
1471                 /* ???? Do more? */
1472         }
1473 }
1474 
1475 /* a callback function. Called by libevent when the kernel says that */
1476 /* a nameserver socket is ready for writing or reading */
1477 static void
1478 nameserver_ready_callback(evutil_socket_t fd, short events, void *arg) {
1479         struct nameserver *ns = (struct nameserver *) arg;
1480         (void)fd;
1481 
1482         EVDNS_LOCK(ns->base);
1483         if (events & EV_WRITE) {
1484                 ns->choked = 0;
1485                 if (!evdns_transmit(ns->base)) {
1486                         nameserver_write_waiting(ns, 0);
1487                 }
1488         }
1489         if (events & EV_READ) {
1490                 nameserver_read(ns);
1491         }
1492         EVDNS_UNLOCK(ns->base);
1493 }
1494 
1495 /* a callback function. Called by libevent when the kernel says that */
1496 /* a server socket is ready for writing or reading. */
1497 static void
1498 server_port_ready_callback(evutil_socket_t fd, short events, void *arg) {
1499         struct evdns_server_port *port = (struct evdns_server_port *) arg;
1500         (void) fd;
1501 
1502         EVDNS_LOCK(port);
1503         if (events & EV_WRITE) {
1504                 port->choked = 0;
1505                 server_port_flush(port);
1506         }
1507         if (events & EV_READ) {
1508                 server_port_read(port);
1509         }
1510         EVDNS_UNLOCK(port);
1511 }
1512 
1513 /* This is an inefficient representation; only use it via the dnslabel_table_*
1514  * functions, so that is can be safely replaced with something smarter later. */
1515 #define MAX_LABELS 128
1516 /* Structures used to implement name compression */
1517 struct dnslabel_entry { char *v; off_t pos; };
1518 struct dnslabel_table {
1519         int n_labels; /* number of current entries */
1520         /* map from name to position in message */
1521         struct dnslabel_entry labels[MAX_LABELS];
1522 };
1523 
1524 /* Initialize dnslabel_table. */
1525 static void
1526 dnslabel_table_init(struct dnslabel_table *table)
1527 {
1528         table->n_labels = 0;
1529 }
1530 
1531 /* Free all storage held by table, but not the table itself. */
1532 static void
1533 dnslabel_clear(struct dnslabel_table *table)
1534 {
1535         int i;
1536         for (i = 0; i < table->n_labels; ++i)
1537                 mm_free(table->labels[i].v);
1538         table->n_labels = 0;
1539 }
1540 
1541 /* return the position of the label in the current message, or -1 if the label */
1542 /* hasn't been used yet. */
1543 static int
1544 dnslabel_table_get_pos(const struct dnslabel_table *table, const char *label)
1545 {
1546         int i;
1547         for (i = 0; i < table->n_labels; ++i) {
1548                 if (!strcmp(label, table->labels[i].v))
1549                         return table->labels[i].pos;
1550         }
1551         return -1;
1552 }
1553 
1554 /* remember that we've used the label at position pos */
1555 static int
1556 dnslabel_table_add(struct dnslabel_table *table, const char *label, off_t pos)
1557 {
1558         char *v;
1559         int p;
1560         if (table->n_labels == MAX_LABELS)
1561                 return (-1);
1562         v = mm_strdup(label);
1563         if (v == NULL)
1564                 return (-1);
1565         p = table->n_labels++;
1566         table->labels[p].v = v;
1567         table->labels[p].pos = pos;
1568 
1569         return (0);
1570 }
1571 
1572 /* Converts a string to a length-prefixed set of DNS labels, starting */
1573 /* at buf[j]. name and buf must not overlap. name_len should be the length */
1574 /* of name.      table is optional, and is used for compression. */
1575 /* */
1576 /* Input: abc.def */
1577 /* Output: <3>abc<3>def<0> */
1578 /* */
1579 /* Returns the first index after the encoded name, or negative on error. */
1580 /*       -1      label was > 63 bytes */
1581 /*       -2      name too long to fit in buffer. */
1582 /* */
1583 static off_t
1584 dnsname_to_labels(u8 *const buf, size_t buf_len, off_t j,
1585                                   const char *name, const size_t name_len,
1586                                   struct dnslabel_table *table) {
1587         const char *end = name + name_len;
1588         int ref = 0;
1589         u16 _t;
1590 
1591 #define APPEND16(x) do {                                                \
1592                 if (j + 2 > (off_t)buf_len)                             \
1593                         goto overflow;                                  \
1594                 _t = htons(x);                                          \
1595                 memcpy(buf + j, &_t, 2);                                \
1596                 j += 2;                                                 \
1597         } while (0)
1598 #define APPEND32(x) do {                                                \
1599                 if (j + 4 > (off_t)buf_len)                             \
1600                         goto overflow;                                  \
1601                 _t32 = htonl(x);                                        \
1602                 memcpy(buf + j, &_t32, 4);                              \
1603                 j += 4;                                                 \
1604         } while (0)
1605 
1606         if (name_len > 255) return -2;
1607 
1608         for (;;) {
1609                 const char *const start = name;
1610                 if (table && (ref = dnslabel_table_get_pos(table, name)) >= 0) {
1611                         APPEND16(ref | 0xc000);
1612                         return j;
1613                 }
1614                 name = strchr(name, '.');
1615                 if (!name) {
1616                         const size_t label_len = end - start;
1617                         if (label_len > 63) return -1;
1618                         if ((size_t)(j+label_len+1) > buf_len) return -2;
1619                         if (table) dnslabel_table_add(table, start, j);
1620                         buf[j++] = (ev_uint8_t)label_len;
1621 
1622                         memcpy(buf + j, start, label_len);
1623                         j += (int) label_len;
1624                         break;
1625                 } else {
1626                         /* append length of the label. */
1627                         const size_t label_len = name - start;
1628                         if (label_len > 63) return -1;
1629                         if ((size_t)(j+label_len+1) > buf_len) return -2;
1630                         if (table) dnslabel_table_add(table, start, j);
1631                         buf[j++] = (ev_uint8_t)label_len;
1632 
1633                         memcpy(buf + j, start, label_len);
1634                         j += (int) label_len;
1635                         /* hop over the '.' */
1636                         name++;
1637                 }
1638         }
1639 
1640         /* the labels must be terminated by a 0. */
1641         /* It's possible that the name ended in a . */
1642         /* in which case the zero is already there */
1643         if (!j || buf[j-1]) buf[j++] = 0;
1644         return j;
1645  overflow:
1646         return (-2);
1647 }
1648 
1649 /* Finds the length of a dns request for a DNS name of the given */
1650 /* length. The actual request may be smaller than the value returned */
1651 /* here */
1652 static size_t
1653 evdns_request_len(const size_t name_len) {
1654         return 96 + /* length of the DNS standard header */
1655                 name_len + 2 +
1656                 4;  /* space for the resource type */
1657 }
1658 
1659 /* build a dns request packet into buf. buf should be at least as long */
1660 /* as evdns_request_len told you it should be. */
1661 /* */
1662 /* Returns the amount of space used. Negative on error. */
1663 static int
1664 evdns_request_data_build(const char *const name, const size_t name_len,
1665     const u16 trans_id, const u16 type, const u16 class,
1666     u8 *const buf, size_t buf_len) {
1667         off_t j = 0;  /* current offset into buf */
1668         u16 _t;  /* used by the macros */
1669 
1670         APPEND16(trans_id);
1671         APPEND16(0x0100);  /* standard query, recusion needed */
1672         APPEND16(1);  /* one question */
1673         APPEND16(0);  /* no answers */
1674         APPEND16(0);  /* no authority */
1675         APPEND16(0);  /* no additional */
1676 
1677         j = dnsname_to_labels(buf, buf_len, j, name, name_len, NULL);
1678         if (j < 0) {
1679                 return (int)j;
1680         }
1681 
1682         APPEND16(type);
1683         APPEND16(class);
1684 
1685         return (int)j;
1686  overflow:
1687         return (-1);
1688 }
1689 
1690 /* exported function */
1691 struct evdns_server_port *
1692 evdns_add_server_port_with_base(struct event_base *base, evutil_socket_t socket, int flags, evdns_request_callback_fn_type cb, void *user_data)
1693 {
1694         struct evdns_server_port *port;
1695         if (flags)
1696                 return NULL; /* flags not yet implemented */
1697         if (!(port = mm_malloc(sizeof(struct evdns_server_port))))
1698                 return NULL;
1699         memset(port, 0, sizeof(struct evdns_server_port));
1700 
1701 
1702         port->socket = socket;
1703         port->refcnt = 1;
1704         port->choked = 0;
1705         port->closing = 0;
1706         port->user_callback = cb;
1707         port->user_data = user_data;
1708         port->pending_replies = NULL;
1709         port->event_base = base;
1710 
1711         event_assign(&port->event, port->event_base,
1712                                  port->socket, EV_READ | EV_PERSIST,
1713                                  server_port_ready_callback, port);
1714         if (event_add(&port->event, NULL) < 0) {
1715                 mm_free(port);
1716                 return NULL;
1717         }
1718         EVTHREAD_ALLOC_LOCK(port->lock, EVTHREAD_LOCKTYPE_RECURSIVE);
1719         return port;
1720 }
1721 
1722 struct evdns_server_port *
1723 evdns_add_server_port(evutil_socket_t socket, int flags, evdns_request_callback_fn_type cb, void *user_data)
1724 {
1725         return evdns_add_server_port_with_base(NULL, socket, flags, cb, user_data);
1726 }
1727 
1728 /* exported function */
1729 void
1730 evdns_close_server_port(struct evdns_server_port *port)
1731 {
1732         EVDNS_LOCK(port);
1733         if (--port->refcnt == 0) {
1734                 EVDNS_UNLOCK(port);
1735                 server_port_free(port);
1736         } else {
1737                 port->closing = 1;
1738         }
1739 }
1740 
1741 /* exported function */
1742 int
1743 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)
1744 {
1745         struct server_request *req = TO_SERVER_REQUEST(_req);
1746         struct server_reply_item **itemp, *item;
1747         int *countp;
1748         int result = -1;
1749 
1750         EVDNS_LOCK(req->port);
1751         if (req->response) /* have we already answered? */
1752                 goto done;
1753 
1754         switch (section) {
1755         case EVDNS_ANSWER_SECTION:
1756                 itemp = &req->answer;
1757                 countp = &req->n_answer;
1758                 break;
1759         case EVDNS_AUTHORITY_SECTION:
1760                 itemp = &req->authority;
1761                 countp = &req->n_authority;
1762                 break;
1763         case EVDNS_ADDITIONAL_SECTION:
1764                 itemp = &req->additional;
1765                 countp = &req->n_additional;
1766                 break;
1767         default:
1768                 goto done;
1769         }
1770         while (*itemp) {
1771                 itemp = &((*itemp)->next);
1772         }
1773         item = mm_malloc(sizeof(struct server_reply_item));
1774         if (!item)
1775                 goto done;
1776         item->next = NULL;
1777         if (!(item->name = mm_strdup(name))) {
1778                 mm_free(item);
1779                 goto done;
1780         }
1781         item->type = type;
1782         item->dns_question_class = class;
1783         item->ttl = ttl;
1784         item->is_name = is_name != 0;
1785         item->datalen = 0;
1786         item->data = NULL;
1787         if (data) {
1788                 if (item->is_name) {
1789                         if (!(item->data = mm_strdup(data))) {
1790                                 mm_free(item->name);
1791                                 mm_free(item);
1792                                 goto done;
1793                         }
1794                         item->datalen = (u16)-1;
1795                 } else {
1796                         if (!(item->data = mm_malloc(datalen))) {
1797                                 mm_free(item->name);
1798                                 mm_free(item);
1799                                 goto done;
1800                         }
1801                         item->datalen = datalen;
1802                         memcpy(item->data, data, datalen);
1803                 }
1804         }
1805 
1806         *itemp = item;
1807         ++(*countp);
1808         result = 0;
1809 done:
1810         EVDNS_UNLOCK(req->port);
1811         return result;
1812 }
1813 
1814 /* exported function */
1815 int
1816 evdns_server_request_add_a_reply(struct evdns_server_request *req, const char *name, int n, const void *addrs, int ttl)
1817 {
1818         return evdns_server_request_add_reply(
1819                   req, EVDNS_ANSWER_SECTION, name, TYPE_A, CLASS_INET,
1820                   ttl, n*4, 0, addrs);
1821 }
1822 
1823 /* exported function */
1824 int
1825 evdns_server_request_add_aaaa_reply(struct evdns_server_request *req, const char *name, int n, const void *addrs, int ttl)
1826 {
1827         return evdns_server_request_add_reply(
1828                   req, EVDNS_ANSWER_SECTION, name, TYPE_AAAA, CLASS_INET,
1829                   ttl, n*16, 0, addrs);
1830 }
1831 
1832 /* exported function */
1833 int
1834 evdns_server_request_add_ptr_reply(struct evdns_server_request *req, struct in_addr *in, const char *inaddr_name, const char *hostname, int ttl)
1835 {
1836         u32 a;
1837         char buf[32];
1838         if (in && inaddr_name)
1839                 return -1;
1840         else if (!in && !inaddr_name)
1841                 return -1;
1842         if (in) {
1843                 a = ntohl(in->s_addr);
1844                 evutil_snprintf(buf, sizeof(buf), "%d.%d.%d.%d.in-addr.arpa",
1845                                 (int)(u8)((a    )&0xff),
1846                                 (int)(u8)((a>>8 )&0xff),
1847                                 (int)(u8)((a>>16)&0xff),
1848                                 (int)(u8)((a>>24)&0xff));
1849                 inaddr_name = buf;
1850         }
1851         return evdns_server_request_add_reply(
1852                   req, EVDNS_ANSWER_SECTION, inaddr_name, TYPE_PTR, CLASS_INET,
1853                   ttl, -1, 1, hostname);
1854 }
1855 
1856 /* exported function */
1857 int
1858 evdns_server_request_add_cname_reply(struct evdns_server_request *req, const char *name, const char *cname, int ttl)
1859 {
1860         return evdns_server_request_add_reply(
1861                   req, EVDNS_ANSWER_SECTION, name, TYPE_CNAME, CLASS_INET,
1862                   ttl, -1, 1, cname);
1863 }
1864 
1865 /* exported function */
1866 void
1867 evdns_server_request_set_flags(struct evdns_server_request *exreq, int flags)
1868 {
1869         struct server_request *req = TO_SERVER_REQUEST(exreq);
1870         req->base.flags &= ~(EVDNS_FLAGS_AA|EVDNS_FLAGS_RD);
1871         req->base.flags |= flags;
1872 }
1873 
1874 static int
1875 evdns_server_request_format_response(struct server_request *req, int err)
1876 {
1877         unsigned char buf[1500];
1878         size_t buf_len = sizeof(buf);
1879         off_t j = 0, r;
1880         u16 _t;
1881         u32 _t32;
1882         int i;
1883         u16 flags;
1884         struct dnslabel_table table;
1885 
1886         if (err < 0 || err > 15) return -1;
1887 
1888         /* Set response bit and error code; copy OPCODE and RD fields from
1889          * question; copy RA and AA if set by caller. */
1890         flags = req->base.flags;
1891         flags |= (0x8000 | err);
1892 
1893         dnslabel_table_init(&table);
1894         APPEND16(req->trans_id);
1895         APPEND16(flags);
1896         APPEND16(req->base.nquestions);
1897         APPEND16(req->n_answer);
1898         APPEND16(req->n_authority);
1899         APPEND16(req->n_additional);
1900 
1901         /* Add questions. */
1902         for (i=0; i < req->base.nquestions; ++i) {
1903                 const char *s = req->base.questions[i]->name;
1904                 j = dnsname_to_labels(buf, buf_len, j, s, strlen(s), &table);
1905                 if (j < 0) {
1906                         dnslabel_clear(&table);
1907                         return (int) j;
1908                 }
1909                 APPEND16(req->base.questions[i]->type);
1910                 APPEND16(req->base.questions[i]->dns_question_class);
1911         }
1912 
1913         /* Add answer, authority, and additional sections. */
1914         for (i=0; i<3; ++i) {
1915                 struct server_reply_item *item;
1916                 if (i==0)
1917                         item = req->answer;
1918                 else if (i==1)
1919                         item = req->authority;
1920                 else
1921                         item = req->additional;
1922                 while (item) {
1923                         r = dnsname_to_labels(buf, buf_len, j, item->name, strlen(item->name), &table);
1924                         if (r < 0)
1925                                 goto overflow;
1926                         j = r;
1927 
1928                         APPEND16(item->type);
1929                         APPEND16(item->dns_question_class);
1930                         APPEND32(item->ttl);
1931                         if (item->is_name) {
1932                                 off_t len_idx = j, name_start;
1933                                 j += 2;
1934                                 name_start = j;
1935                                 r = dnsname_to_labels(buf, buf_len, j, item->data, strlen(item->data), &table);
1936                                 if (r < 0)
1937                                         goto overflow;
1938                                 j = r;
1939                                 _t = htons( (short) (j-name_start) );
1940                                 memcpy(buf+len_idx, &_t, 2);
1941                         } else {
1942                                 APPEND16(item->datalen);
1943                                 if (j+item->datalen > (off_t)buf_len)
1944                                         goto overflow;
1945                                 memcpy(buf+j, item->data, item->datalen);
1946                                 j += item->datalen;
1947                         }
1948                         item = item->next;
1949                 }
1950         }
1951 
1952         if (j > 512) {
1953 overflow:
1954                 j = 512;
1955                 buf[2] |= 0x02; /* set the truncated bit. */
1956         }
1957 
1958         req->response_len = j;
1959 
1960         if (!(req->response = mm_malloc(req->response_len))) {
1961                 server_request_free_answers(req);
1962                 dnslabel_clear(&table);
1963                 return (-1);
1964         }
1965         memcpy(req->response, buf, req->response_len);
1966         server_request_free_answers(req);
1967         dnslabel_clear(&table);
1968         return (0);
1969 }
1970 
1971 /* exported function */
1972 int
1973 evdns_server_request_respond(struct evdns_server_request *_req, int err)
1974 {
1975         struct server_request *req = TO_SERVER_REQUEST(_req);
1976         struct evdns_server_port *port = req->port;
1977         int r = -1;
1978 
1979         EVDNS_LOCK(port);
1980         if (!req->response) {
1981                 if ((r = evdns_server_request_format_response(req, err))<0)
1982                         goto done;
1983         }
1984 
1985         r = sendto(port->socket, req->response, (int)req->response_len, 0,
1986                            (struct sockaddr*) &req->addr, (ev_socklen_t)req->addrlen);
1987         if (r<0) {
1988                 int sock_err = evutil_socket_geterror(port->socket);
1989                 if (EVUTIL_ERR_RW_RETRIABLE(sock_err))
1990                         goto done;
1991 
1992                 if (port->pending_replies) {
1993                         req->prev_pending = port->pending_replies->prev_pending;
1994                         req->next_pending = port->pending_replies;
1995                         req->prev_pending->next_pending =
1996                                 req->next_pending->prev_pending = req;
1997                 } else {
1998                         req->prev_pending = req->next_pending = req;
1999                         port->pending_replies = req;
2000                         port->choked = 1;
2001 
2002                         (void) event_del(&port->event);
2003                         event_assign(&port->event, port->event_base, port->socket, (port->closing?0:EV_READ) | EV_WRITE | EV_PERSIST, server_port_ready_callback, port);
2004 
2005                         if (event_add(&port->event, NULL) < 0) {
2006                                 log(EVDNS_LOG_WARN, "Error from libevent when adding event for DNS server");
2007                         }
2008 
2009                 }
2010 
2011                 r = 1;
2012                 goto done;
2013         }
2014         if (server_request_free(req)) {
2015                 r = 0;
2016                 goto done;
2017         }
2018 
2019         if (port->pending_replies)
2020                 server_port_flush(port);
2021 
2022         r = 0;
2023 done:
2024         EVDNS_UNLOCK(port);
2025         return r;
2026 }
2027 
2028 /* Free all storage held by RRs in req. */
2029 static void
2030 server_request_free_answers(struct server_request *req)
2031 {
2032         struct server_reply_item *victim, *next, **list;
2033         int i;
2034         for (i = 0; i < 3; ++i) {
2035                 if (i==0)
2036                         list = &req->answer;
2037                 else if (i==1)
2038                         list = &req->authority;
2039                 else
2040                         list = &req->additional;
2041 
2042                 victim = *list;
2043                 while (victim) {
2044                         next = victim->next;
2045                         mm_free(victim->name);
2046                         if (victim->data)
2047                                 mm_free(victim->data);
2048                         mm_free(victim);
2049                         victim = next;
2050                 }
2051                 *list = NULL;
2052         }
2053 }
2054 
2055 /* Free all storage held by req, and remove links to it. */
2056 /* return true iff we just wound up freeing the server_port. */
2057 static int
2058 server_request_free(struct server_request *req)
2059 {
2060         int i, rc=1, lock=0;
2061         if (req->base.questions) {
2062                 for (i = 0; i < req->base.nquestions; ++i)
2063                         mm_free(req->base.questions[i]);
2064                 mm_free(req->base.questions);
2065         }
2066 
2067         if (req->port) {
2068                 EVDNS_LOCK(req->port);
2069                 lock=1;
2070                 if (req->port->pending_replies == req) {
2071                         if (req->next_pending && req->next_pending != req)
2072                                 req->port->pending_replies = req->next_pending;
2073                         else
2074                                 req->port->pending_replies = NULL;
2075                 }
2076                 rc = --req->port->refcnt;
2077         }
2078 
2079         if (req->response) {
2080                 mm_free(req->response);
2081         }
2082 
2083         server_request_free_answers(req);
2084 
2085         if (req->next_pending && req->next_pending != req) {
2086                 req->next_pending->prev_pending = req->prev_pending;
2087                 req->prev_pending->next_pending = req->next_pending;
2088         }
2089 
2090         if (rc == 0) {
2091                 EVDNS_UNLOCK(req->port); /* ????? nickm */
2092                 server_port_free(req->port);
2093                 mm_free(req);
2094                 return (1);
2095         }
2096         if (lock)
2097                 EVDNS_UNLOCK(req->port);
2098         mm_free(req);
2099         return (0);
2100 }
2101 
2102 /* Free all storage held by an evdns_server_port.  Only called when  */
2103 static void
2104 server_port_free(struct evdns_server_port *port)
2105 {
2106         EVUTIL_ASSERT(port);
2107         EVUTIL_ASSERT(!port->refcnt);
2108         EVUTIL_ASSERT(!port->pending_replies);
2109         if (port->socket > 0) {
2110                 evutil_closesocket(port->socket);
2111                 port->socket = -1;
2112         }
2113         (void) event_del(&port->event);
2114         event_debug_unassign(&port->event);
2115         EVTHREAD_FREE_LOCK(port->lock, EVTHREAD_LOCKTYPE_RECURSIVE);
2116         mm_free(port);
2117 }
2118 
2119 /* exported function */
2120 int
2121 evdns_server_request_drop(struct evdns_server_request *_req)
2122 {
2123         struct server_request *req = TO_SERVER_REQUEST(_req);
2124         server_request_free(req);
2125         return 0;
2126 }
2127 
2128 /* exported function */
2129 int
2130 evdns_server_request_get_requesting_addr(struct evdns_server_request *_req, struct sockaddr *sa, int addr_len)
2131 {
2132         struct server_request *req = TO_SERVER_REQUEST(_req);
2133         if (addr_len < (int)req->addrlen)
2134                 return -1;
2135         memcpy(sa, &(req->addr), req->addrlen);
2136         return req->addrlen;
2137 }
2138 
2139 #undef APPEND16
2140 #undef APPEND32
2141 
2142 /* this is a libevent callback function which is called when a request */
2143 /* has timed out. */
2144 static void
2145 evdns_request_timeout_callback(evutil_socket_t fd, short events, void *arg) {
2146         struct request *const req = (struct request *) arg;
2147         struct evdns_base *base = req->base;
2148 
2149         (void) fd;
2150         (void) events;
2151 
2152         log(EVDNS_LOG_DEBUG, "Request %p timed out", arg);
2153         EVDNS_LOCK(base);
2154 
2155         req->ns->timedout++;
2156         if (req->ns->timedout > req->base->global_max_nameserver_timeout) {
2157                 req->ns->timedout = 0;
2158                 nameserver_failed(req->ns, "request timed out.");
2159         }
2160 
2161         if (req->tx_count >= req->base->global_max_retransmits) {
2162                 /* this request has failed */
2163                 log(EVDNS_LOG_DEBUG, "Giving up on request %p; tx_count==%d",
2164                     arg, req->tx_count);
2165                 reply_schedule_callback(req, 0, DNS_ERR_TIMEOUT, NULL);
2166                 request_finished(req, &REQ_HEAD(req->base, req->trans_id), 1);
2167         } else {
2168                 /* retransmit it */
2169                 struct nameserver *new_ns;
2170                 log(EVDNS_LOG_DEBUG, "Retransmitting request %p; tx_count==%d",
2171                     arg, req->tx_count);
2172                 (void) evtimer_del(&req->timeout_event);
2173                 new_ns = nameserver_pick(base);
2174                 if (new_ns)
2175                         req->ns = new_ns;
2176                 evdns_request_transmit(req);
2177         }
2178         EVDNS_UNLOCK(base);
2179 }
2180 
2181 /* try to send a request to a given server. */
2182 /* */
2183 /* return: */
2184 /*   0 ok */
2185 /*   1 temporary failure */
2186 /*   2 other failure */
2187 static int
2188 evdns_request_transmit_to(struct request *req, struct nameserver *server) {
2189         int r;
2190         ASSERT_LOCKED(req->base);
2191         ASSERT_VALID_REQUEST(req);
2192         r = sendto(server->socket, (void*)req->request, req->request_len, 0,
2193             (struct sockaddr *)&server->address, server->addrlen);
2194         if (r < 0) {
2195                 int err = evutil_socket_geterror(server->socket);
2196                 if (EVUTIL_ERR_RW_RETRIABLE(err))
2197                         return 1;
2198                 nameserver_failed(req->ns, evutil_socket_error_to_string(err));
2199                 return 2;
2200         } else if (r != (int)req->request_len) {
2201                 return 1;  /* short write */
2202         } else {
2203                 return 0;
2204         }
2205 }
2206 
2207 /* try to send a request, updating the fields of the request */
2208 /* as needed */
2209 /* */
2210 /* return: */
2211 /*   0 ok */
2212 /*   1 failed */
2213 static int
2214 evdns_request_transmit(struct request *req) {
2215         int retcode = 0, r;
2216 
2217         ASSERT_LOCKED(req->base);
2218         ASSERT_VALID_REQUEST(req);
2219         /* if we fail to send this packet then this flag marks it */
2220         /* for evdns_transmit */
2221         req->transmit_me = 1;
2222         EVUTIL_ASSERT(req->trans_id != 0xffff);
2223 
2224         if (!req->ns)
2225         {
2226                 /* unable to transmit request if no nameservers */
2227                 return 1;
2228         }
2229 
2230         if (req->ns->choked) {
2231                 /* don't bother trying to write to a socket */
2232                 /* which we have had EAGAIN from */
2233                 return 1;
2234         }
2235 
2236         r = evdns_request_transmit_to(req, req->ns);
2237         switch (r) {
2238         case 1:
2239                 /* temp failure */
2240                 req->ns->choked = 1;
2241                 nameserver_write_waiting(req->ns, 1);
2242                 return 1;
2243         case 2:
2244                 /* failed to transmit the request entirely. */
2245                 retcode = 1;
2246                 /* fall through: we'll set a timeout, which will time out,
2247                  * and make us retransmit the request anyway. */
2248         default:
2249                 /* all ok */
2250                 log(EVDNS_LOG_DEBUG,
2251                     "Setting timeout for request %p, sent to nameserver %p", req, req->ns);
2252                 if (evtimer_add(&req->timeout_event, &req->base->global_timeout) < 0) {
2253                         log(EVDNS_LOG_WARN,
2254                       "Error from libevent when adding timer for request %p",
2255                             req);
2256                         /* ???? Do more? */
2257                 }
2258                 req->tx_count++;
2259                 req->transmit_me = 0;
2260                 return retcode;
2261         }
2262 }
2263 
2264 static void
2265 nameserver_probe_callback(int result, char type, int count, int ttl, void *addresses, void *arg) {
2266         struct nameserver *const ns = (struct nameserver *) arg;
2267         (void) type;
2268         (void) count;
2269         (void) ttl;
2270         (void) addresses;
2271 
2272         if (result == DNS_ERR_CANCEL) {
2273                 /* We canceled this request because the nameserver came up
2274                  * for some other reason.  Do not change our opinion about
2275                  * the nameserver. */
2276                 return;
2277         }
2278 
2279         EVDNS_LOCK(ns->base);
2280         ns->probe_request = NULL;
2281         if (result == DNS_ERR_NONE || result == DNS_ERR_NOTEXIST) {
2282                 /* this is a good reply */
2283                 nameserver_up(ns);
2284         } else {
2285                 nameserver_probe_failed(ns);
2286         }
2287         EVDNS_UNLOCK(ns->base);
2288 }
2289 
2290 static void
2291 nameserver_send_probe(struct nameserver *const ns) {
2292         struct evdns_request *handle;
2293         struct request *req;
2294         char addrbuf[128];
2295         /* here we need to send a probe to a given nameserver */
2296         /* in the hope that it is up now. */
2297 
2298         ASSERT_LOCKED(ns->base);
2299         log(EVDNS_LOG_DEBUG, "Sending probe to %s",
2300             evutil_format_sockaddr_port(
2301                     (struct sockaddr *)&ns->address,
2302                     addrbuf, sizeof(addrbuf)));
2303         handle = mm_calloc(1, sizeof(*handle));
2304         if (!handle) return;
2305         req = request_new(ns->base, handle, TYPE_A, "google.com", DNS_QUERY_NO_SEARCH, nameserver_probe_callback, ns);
2306         if (!req) {
2307                 mm_free(handle);
2308                 return;
2309         }
2310         ns->probe_request = handle;
2311         /* we force this into the inflight queue no matter what */
2312         request_trans_id_set(req, transaction_id_pick(ns->base));
2313         req->ns = ns;
2314         request_submit(req);
2315 }
2316 
2317 /* returns: */
2318 /*   0 didn't try to transmit anything */
2319 /*   1 tried to transmit something */
2320 static int
2321 evdns_transmit(struct evdns_base *base) {
2322         char did_try_to_transmit = 0;
2323         int i;
2324 
2325         ASSERT_LOCKED(base);
2326         for (i = 0; i < base->n_req_heads; ++i) {
2327                 if (base->req_heads[i]) {
2328                         struct request *const started_at = base->req_heads[i], *req = started_at;
2329                         /* first transmit all the requests which are currently waiting */
2330                         do {
2331                                 if (req->transmit_me) {
2332                                         did_try_to_transmit = 1;
2333                                         evdns_request_transmit(req);
2334                                 }
2335 
2336                                 req = req->next;
2337                         } while (req != started_at);
2338                 }
2339         }
2340 
2341         return did_try_to_transmit;
2342 }
2343 
2344 /* exported function */
2345 int
2346 evdns_base_count_nameservers(struct evdns_base *base)
2347 {
2348         const struct nameserver *server;
2349         int n = 0;
2350 
2351         EVDNS_LOCK(base);
2352         server = base->server_head;
2353         if (!server)
2354                 goto done;
2355         do {
2356                 ++n;
2357                 server = server->next;
2358         } while (server != base->server_head);
2359 done:
2360         EVDNS_UNLOCK(base);
2361         return n;
2362 }
2363 
2364 int
2365 evdns_count_nameservers(void)
2366 {
2367         return evdns_base_count_nameservers(current_base);
2368 }
2369 
2370 /* exported function */
2371 int
2372 evdns_base_clear_nameservers_and_suspend(struct evdns_base *base)
2373 {
2374         struct nameserver *server, *started_at;
2375         int i;
2376 
2377         EVDNS_LOCK(base);
2378         server = base->server_head;
2379         started_at = base->server_head;
2380         if (!server) {
2381                 EVDNS_UNLOCK(base);
2382                 return 0;
2383         }
2384         while (1) {
2385                 struct nameserver *next = server->next;
2386                 (void) event_del(&server->event);
2387                 if (evtimer_initialized(&server->timeout_event))
2388                         (void) evtimer_del(&server->timeout_event);
2389                 if (server->probe_request) {
2390                         evdns_cancel_request(server->base, server->probe_request);
2391                         server->probe_request = NULL;
2392                 }
2393                 if (server->socket >= 0)
2394                         evutil_closesocket(server->socket);
2395                 mm_free(server);
2396                 if (next == started_at)
2397                         break;
2398                 server = next;
2399         }
2400         base->server_head = NULL;
2401         base->global_good_nameservers = 0;
2402 
2403         for (i = 0; i < base->n_req_heads; ++i) {
2404                 struct request *req, *req_started_at;
2405                 req = req_started_at = base->req_heads[i];
2406                 while (req) {
2407                         struct request *next = req->next;
2408                         req->tx_count = req->reissue_count = 0;
2409                         req->ns = NULL;
2410                         /* ???? What to do about searches? */
2411                         (void) evtimer_del(&req->timeout_event);
2412                         req->trans_id = 0;
2413                         req->transmit_me = 0;
2414 
2415                         base->global_requests_waiting++;
2416                         evdns_request_insert(req, &base->req_waiting_head);
2417                         /* We want to insert these suspended elements at the front of
2418                          * the waiting queue, since they were pending before any of
2419                          * the waiting entries were added.  This is a circular list,
2420                          * so we can just shift the start back by one.*/
2421                         base->req_waiting_head = base->req_waiting_head->prev;
2422 
2423                         if (next == req_started_at)
2424                                 break;
2425                         req = next;
2426                 }
2427                 base->req_heads[i] = NULL;
2428         }
2429 
2430         base->global_requests_inflight = 0;
2431 
2432         EVDNS_UNLOCK(base);
2433         return 0;
2434 }
2435 
2436 int
2437 evdns_clear_nameservers_and_suspend(void)
2438 {
2439         return evdns_base_clear_nameservers_and_suspend(current_base);
2440 }
2441 
2442 
2443 /* exported function */
2444 int
2445 evdns_base_resume(struct evdns_base *base)
2446 {
2447         EVDNS_LOCK(base);
2448         evdns_requests_pump_waiting_queue(base);
2449         EVDNS_UNLOCK(base);
2450 
2451         return 0;
2452 }
2453 
2454 int
2455 evdns_resume(void)
2456 {
2457         return evdns_base_resume(current_base);
2458 }
2459 
2460 static int
2461 _evdns_nameserver_add_impl(struct evdns_base *base, const struct sockaddr *address, int addrlen) {
2462         /* first check to see if we already have this nameserver */
2463 
2464         const struct nameserver *server = base->server_head, *const started_at = base->server_head;
2465         struct nameserver *ns;
2466         int err = 0;
2467         char addrbuf[128];
2468 
2469         ASSERT_LOCKED(base);
2470         if (server) {
2471                 do {
2472                         if (!evutil_sockaddr_cmp((struct sockaddr*)&server->address, address, 1)) return 3;
2473                         server = server->next;
2474                 } while (server != started_at);
2475         }
2476         if (addrlen > (int)sizeof(ns->address)) {
2477                 log(EVDNS_LOG_DEBUG, "Addrlen %d too long.", (int)addrlen);
2478                 return 2;
2479         }
2480 
2481         ns = (struct nameserver *) mm_malloc(sizeof(struct nameserver));
2482         if (!ns) return -1;
2483 
2484         memset(ns, 0, sizeof(struct nameserver));
2485         ns->base = base;
2486 
2487         evtimer_assign(&ns->timeout_event, ns->base->event_base, nameserver_prod_callback, ns);
2488 
2489         ns->socket = socket(address->sa_family, SOCK_DGRAM, 0);
2490         if (ns->socket < 0) { err = 1; goto out1; }
2491         evutil_make_socket_closeonexec(ns->socket);
2492         evutil_make_socket_nonblocking(ns->socket);
2493 
2494         if (base->global_outgoing_addrlen &&
2495             !evutil_sockaddr_is_loopback(address)) {
2496                 if (bind(ns->socket,
2497                         (struct sockaddr*)&base->global_outgoing_address,
2498                         base->global_outgoing_addrlen) < 0) {
2499                         log(EVDNS_LOG_WARN,"Couldn't bind to outgoing address");
2500                         err = 2;
2501                         goto out2;
2502                 }
2503         }
2504 
2505         memcpy(&ns->address, address, addrlen);
2506         ns->addrlen = addrlen;
2507         ns->state = 1;
2508         event_assign(&ns->event, ns->base->event_base, ns->socket, EV_READ | EV_PERSIST, nameserver_ready_callback, ns);
2509         if (event_add(&ns->event, NULL) < 0) {
2510                 err = 2;
2511                 goto out2;
2512         }
2513 
2514         log(EVDNS_LOG_DEBUG, "Added nameserver %s as %p",
2515             evutil_format_sockaddr_port(address, addrbuf, sizeof(addrbuf)), ns);
2516 
2517         /* insert this nameserver into the list of them */
2518         if (!base->server_head) {
2519                 ns->next = ns->prev = ns;
2520                 base->server_head = ns;
2521         } else {
2522                 ns->next = base->server_head->next;
2523                 ns->prev = base->server_head;
2524                 base->server_head->next = ns;
2525                 ns->next->prev = ns;
2526         }
2527 
2528         base->global_good_nameservers++;
2529 
2530         return 0;
2531 
2532 out2:
2533         evutil_closesocket(ns->socket);
2534 out1:
2535         event_debug_unassign(&ns->event);
2536         mm_free(ns);
2537         log(EVDNS_LOG_WARN, "Unable to add nameserver %s: error %d",
2538             evutil_format_sockaddr_port(address, addrbuf, sizeof(addrbuf)), err);
2539         return err;
2540 }
2541 
2542 /* exported function */
2543 int
2544 evdns_base_nameserver_add(struct evdns_base *base, unsigned long int address)
2545 {
2546         struct sockaddr_in sin;
2547         int res;
2548         memset(&sin, 0, sizeof(sin));
2549         sin.sin_addr.s_addr = address;
2550         sin.sin_port = htons(53);
2551         sin.sin_family = AF_INET;
2552         EVDNS_LOCK(base);
2553         res = _evdns_nameserver_add_impl(base, (struct sockaddr*)&sin, sizeof(sin));
2554         EVDNS_UNLOCK(base);
2555         return res;
2556 }
2557 
2558 int
2559 evdns_nameserver_add(unsigned long int address) {
2560         if (!current_base)
2561                 current_base = evdns_base_new(NULL, 0);
2562         return evdns_base_nameserver_add(current_base, address);
2563 }
2564 
2565 static void
2566 sockaddr_setport(struct sockaddr *sa, ev_uint16_t port)
2567 {
2568         if (sa->sa_family == AF_INET) {
2569                 ((struct sockaddr_in *)sa)->sin_port = htons(port);
2570         } else if (sa->sa_family == AF_INET6) {
2571                 ((struct sockaddr_in6 *)sa)->sin6_port = htons(port);
2572         }
2573 }
2574 
2575 static ev_uint16_t
2576 sockaddr_getport(struct sockaddr *sa)
2577 {
2578         if (sa->sa_family == AF_INET) {
2579                 return ntohs(((struct sockaddr_in *)sa)->sin_port);
2580         } else if (sa->sa_family == AF_INET6) {
2581                 return ntohs(((struct sockaddr_in6 *)sa)->sin6_port);
2582         } else {
2583                 return 0;
2584         }
2585 }
2586 
2587 /* exported function */
2588 int
2589 evdns_base_nameserver_ip_add(struct evdns_base *base, const char *ip_as_string) {
2590         struct sockaddr_storage ss;
2591         struct sockaddr *sa;
2592         int len = sizeof(ss);
2593         int res;
2594         if (evutil_parse_sockaddr_port(ip_as_string, (struct sockaddr *)&ss,
2595                 &len)) {
2596                 log(EVDNS_LOG_WARN, "Unable to parse nameserver address %s",
2597                         ip_as_string);
2598                 return 4;
2599         }
2600         sa = (struct sockaddr *) &ss;
2601         if (sockaddr_getport(sa) == 0)
2602                 sockaddr_setport(sa, 53);
2603 
2604         EVDNS_LOCK(base);
2605         res = _evdns_nameserver_add_impl(base, sa, len);
2606         EVDNS_UNLOCK(base);
2607         return res;
2608 }
2609 
2610 int
2611 evdns_nameserver_ip_add(const char *ip_as_string) {
2612         if (!current_base)
2613                 current_base = evdns_base_new(NULL, 0);
2614         return evdns_base_nameserver_ip_add(current_base, ip_as_string);
2615 }
2616 
2617 int
2618 evdns_base_nameserver_sockaddr_add(struct evdns_base *base,
2619     const struct sockaddr *sa, ev_socklen_t len, unsigned flags)
2620 {
2621         int res;
2622         EVUTIL_ASSERT(base);
2623         EVDNS_LOCK(base);
2624         res = _evdns_nameserver_add_impl(base, sa, len);
2625         EVDNS_UNLOCK(base);
2626         return res;
2627 }
2628 
2629 /* remove from the queue */
2630 static void
2631 evdns_request_remove(struct request *req, struct request **head)
2632 {
2633         ASSERT_LOCKED(req->base);
2634         ASSERT_VALID_REQUEST(req);
2635 
2636 #if 0
2637         {
2638                 struct request *ptr;
2639                 int found = 0;
2640                 EVUTIL_ASSERT(*head != NULL);
2641 
2642                 ptr = *head;
2643                 do {
2644                         if (ptr == req) {
2645                                 found = 1;
2646                                 break;
2647                         }
2648                         ptr = ptr->next;
2649                 } while (ptr != *head);
2650                 EVUTIL_ASSERT(found);
2651 
2652                 EVUTIL_ASSERT(req->next);
2653         }
2654 #endif
2655 
2656         if (req->next == req) {
2657                 /* only item in the list */
2658                 *head = NULL;
2659         } else {
2660                 req->next->prev = req->prev;
2661                 req->prev->next = req->next;
2662                 if (*head == req) *head = req->next;
2663         }
2664         req->next = req->prev = NULL;
2665 }
2666 
2667 /* insert into the tail of the queue */
2668 static void
2669 evdns_request_insert(struct request *req, struct request **head) {
2670         ASSERT_LOCKED(req->base);
2671         ASSERT_VALID_REQUEST(req);
2672         if (!*head) {
2673                 *head = req;
2674                 req->next = req->prev = req;
2675                 return;
2676         }
2677 
2678         req->prev = (*head)->prev;
2679         req->prev->next = req;
2680         req->next = *head;
2681         (*head)->prev = req;
2682 }
2683 
2684 static int
2685 string_num_dots(const char *s) {
2686         int count = 0;
2687         while ((s = strchr(s, '.'))) {
2688                 s++;
2689                 count++;
2690         }
2691         return count;
2692 }
2693 
2694 static struct request *
2695 request_new(struct evdns_base *base, struct evdns_request *handle, int type,
2696             const char *name, int flags, evdns_callback_type callback,
2697             void *user_ptr) {
2698 
2699         const char issuing_now =
2700             (base->global_requests_inflight < base->global_max_requests_inflight) ? 1 : 0;
2701 
2702         const size_t name_len = strlen(name);
2703         const size_t request_max_len = evdns_request_len(name_len);
2704         const u16 trans_id = issuing_now ? transaction_id_pick(base) : 0xffff;
2705         /* the request data is alloced in a single block with the header */
2706         struct request *const req =
2707             mm_malloc(sizeof(struct request) + request_max_len);
2708         int rlen;
2709         char namebuf[256];
2710         (void) flags;
2711 
2712         ASSERT_LOCKED(base);
2713 
2714         if (!req) return NULL;
2715 
2716         if (name_len >= sizeof(namebuf)) {
2717                 mm_free(req);
2718                 return NULL;
2719         }
2720 
2721         memset(req, 0, sizeof(struct request));
2722         req->base = base;
2723 
2724         evtimer_assign(&req->timeout_event, req->base->event_base, evdns_request_timeout_callback, req);
2725 
2726         if (base->global_randomize_case) {
2727                 unsigned i;
2728                 char randbits[(sizeof(namebuf)+7)/8];
2729                 strlcpy(namebuf, name, sizeof(namebuf));
2730                 evutil_secure_rng_get_bytes(randbits, (name_len+7)/8);
2731                 for (i = 0; i < name_len; ++i) {
2732                         if (EVUTIL_ISALPHA(namebuf[i])) {
2733                                 if ((randbits[i >> 3] & (1<<(i & 7))))
2734                                         namebuf[i] |= 0x20;
2735                                 else
2736                                         namebuf[i] &= ~0x20;
2737                         }
2738                 }
2739                 name = namebuf;
2740         }
2741 
2742         /* request data lives just after the header */
2743         req->request = ((u8 *) req) + sizeof(struct request);
2744         /* denotes that the request data shouldn't be free()ed */
2745         req->request_appended = 1;
2746         rlen = evdns_request_data_build(name, name_len, trans_id,
2747             type, CLASS_INET, req->request, request_max_len);
2748         if (rlen < 0)
2749                 goto err1;
2750 
2751         req->request_len = rlen;
2752         req->trans_id = trans_id;
2753         req->tx_count = 0;
2754         req->request_type = type;
2755         req->user_pointer = user_ptr;
2756         req->user_callback = callback;
2757         req->ns = issuing_now ? nameserver_pick(base) : NULL;
2758         req->next = req->prev = NULL;
2759         req->handle = handle;
2760         if (handle) {
2761                 handle->current_req = req;
2762                 handle->base = base;
2763         }
2764 
2765         return req;
2766 err1:
2767         mm_free(req);
2768         return NULL;
2769 }
2770 
2771 static void
2772 request_submit(struct request *const req) {
2773         struct evdns_base *base = req->base;
2774         ASSERT_LOCKED(base);
2775         ASSERT_VALID_REQUEST(req);
2776         if (req->ns) {
2777                 /* if it has a nameserver assigned then this is going */
2778                 /* straight into the inflight queue */
2779                 evdns_request_insert(req, &REQ_HEAD(base, req->trans_id));
2780                 base->global_requests_inflight++;
2781                 evdns_request_transmit(req);
2782         } else {
2783                 evdns_request_insert(req, &base->req_waiting_head);
2784                 base->global_requests_waiting++;
2785         }
2786 }
2787 
2788 /* exported function */
2789 void
2790 evdns_cancel_request(struct evdns_base *base, struct evdns_request *handle)
2791 {
2792         struct request *req;
2793 
2794         if (!handle->current_req)
2795                 return;
2796 
2797         if (!base) {
2798                 /* This redundancy is silly; can we fix it? (Not for 2.0) XXXX */
2799                 base = handle->base;
2800                 if (!base)
2801                         base = handle->current_req->base;
2802         }
2803 
2804         EVDNS_LOCK(base);
2805         if (handle->pending_cb) {
2806                 EVDNS_UNLOCK(base);
2807                 return;
2808         }
2809 
2810         req = handle->current_req;
2811         ASSERT_VALID_REQUEST(req);
2812 
2813         reply_schedule_callback(req, 0, DNS_ERR_CANCEL, NULL);
2814         if (req->ns) {
2815                 /* remove from inflight queue */
2816                 request_finished(req, &REQ_HEAD(base, req->trans_id), 1);
2817         } else {
2818                 /* remove from global_waiting head */
2819                 request_finished(req, &base->req_waiting_head, 1);
2820         }
2821         EVDNS_UNLOCK(base);
2822 }
2823 
2824 /* exported function */
2825 struct evdns_request *
2826 evdns_base_resolve_ipv4(struct evdns_base *base, const char *name, int flags,
2827     evdns_callback_type callback, void *ptr) {
2828         struct evdns_request *handle;
2829         struct request *req;
2830         log(EVDNS_LOG_DEBUG, "Resolve requested for %s", name);
2831         handle = mm_calloc(1, sizeof(*handle));
2832         if (handle == NULL)
2833                 return NULL;
2834         EVDNS_LOCK(base);
2835         if (flags & DNS_QUERY_NO_SEARCH) {
2836                 req =
2837                         request_new(base, handle, TYPE_A, name, flags,
2838                                     callback, ptr);
2839                 if (req)
2840                         request_submit(req);
2841         } else {
2842                 search_request_new(base, handle, TYPE_A, name, flags,
2843                     callback, ptr);
2844         }
2845         if (handle->current_req == NULL) {
2846                 mm_free(handle);
2847                 handle = NULL;
2848         }
2849         EVDNS_UNLOCK(base);
2850         return handle;
2851 }
2852 
2853 int evdns_resolve_ipv4(const char *name, int flags,
2854                                            evdns_callback_type callback, void *ptr)
2855 {
2856         return evdns_base_resolve_ipv4(current_base, name, flags, callback, ptr)
2857                 ? 0 : -1;
2858 }
2859 
2860 
2861 /* exported function */
2862 struct evdns_request *
2863 evdns_base_resolve_ipv6(struct evdns_base *base,
2864     const char *name, int flags,
2865     evdns_callback_type callback, void *ptr)
2866 {
2867         struct evdns_request *handle;
2868         struct request *req;
2869         log(EVDNS_LOG_DEBUG, "Resolve requested for %s", name);
2870         handle = mm_calloc(1, sizeof(*handle));
2871         if (handle == NULL)
2872                 return NULL;
2873         EVDNS_LOCK(base);
2874         if (flags & DNS_QUERY_NO_SEARCH) {
2875                 req = request_new(base, handle, TYPE_AAAA, name, flags,
2876                                   callback, ptr);
2877                 if (req)
2878                         request_submit(req);
2879         } else {
2880                 search_request_new(base, handle, TYPE_AAAA, name, flags,
2881                     callback, ptr);
2882         }
2883         if (handle->current_req == NULL) {
2884                 mm_free(handle);
2885                 handle = NULL;
2886         }
2887         EVDNS_UNLOCK(base);
2888         return handle;
2889 }
2890 
2891 int evdns_resolve_ipv6(const char *name, int flags,
2892     evdns_callback_type callback, void *ptr) {
2893         return evdns_base_resolve_ipv6(current_base, name, flags, callback, ptr)
2894                 ? 0 : -1;
2895 }
2896 
2897 struct evdns_request *
2898 evdns_base_resolve_reverse(struct evdns_base *base, const struct in_addr *in, int flags, evdns_callback_type callback, void *ptr) {
2899         char buf[32];
2900         struct evdns_request *handle;
2901         struct request *req;
2902         u32 a;
2903         EVUTIL_ASSERT(in);
2904         a = ntohl(in->s_addr);
2905         evutil_snprintf(buf, sizeof(buf), "%d.%d.%d.%d.in-addr.arpa",
2906                         (int)(u8)((a    )&0xff),
2907                         (int)(u8)((a>>8 )&0xff),
2908                         (int)(u8)((a>>16)&0xff),
2909                         (int)(u8)((a>>24)&0xff));
2910         handle = mm_calloc(1, sizeof(*handle));
2911         if (handle == NULL)
2912                 return NULL;
2913         log(EVDNS_LOG_DEBUG, "Resolve requested for %s (reverse)", buf);
2914         EVDNS_LOCK(base);
2915         req = request_new(base, handle, TYPE_PTR, buf, flags, callback, ptr);
2916         if (req)
2917                 request_submit(req);
2918         if (handle->current_req == NULL) {
2919                 mm_free(handle);
2920                 handle = NULL;
2921         }
2922         EVDNS_UNLOCK(base);
2923         return (handle);
2924 }
2925 
2926 int evdns_resolve_reverse(const struct in_addr *in, int flags, evdns_callback_type callback, void *ptr) {
2927         return evdns_base_resolve_reverse(current_base, in, flags, callback, ptr)
2928                 ? 0 : -1;
2929 }
2930 
2931 struct evdns_request *
2932 evdns_base_resolve_reverse_ipv6(struct evdns_base *base, const struct in6_addr *in, int flags, evdns_callback_type callback, void *ptr) {
2933         /* 32 nybbles, 32 periods, "ip6.arpa", NUL. */
2934         char buf[73];
2935         char *cp;
2936         struct evdns_request *handle;
2937         struct request *req;
2938         int i;
2939         EVUTIL_ASSERT(in);
2940         cp = buf;
2941         for (i=15; i >= 0; --i) {
2942                 u8 byte = in->s6_addr[i];
2943                 *cp++ = "0123456789abcdef"[byte & 0x0f];
2944                 *cp++ = '.';
2945                 *cp++ = "0123456789abcdef"[byte >> 4];
2946                 *cp++ = '.';
2947         }
2948         EVUTIL_ASSERT(cp + strlen("ip6.arpa") < buf+sizeof(buf));
2949         memcpy(cp, "ip6.arpa", strlen("ip6.arpa")+1);
2950         handle = mm_calloc(1, sizeof(*handle));
2951         if (handle == NULL)
2952                 return NULL;
2953         log(EVDNS_LOG_DEBUG, "Resolve requested for %s (reverse)", buf);
2954         EVDNS_LOCK(base);
2955         req = request_new(base, handle, TYPE_PTR, buf, flags, callback, ptr);
2956         if (req)
2957                 request_submit(req);
2958         if (handle->current_req == NULL) {
2959                 mm_free(handle);
2960                 handle = NULL;
2961         }
2962         EVDNS_UNLOCK(base);
2963         return (handle);
2964 }
2965 
2966 int evdns_resolve_reverse_ipv6(const struct in6_addr *in, int flags, evdns_callback_type callback, void *ptr) {
2967         return evdns_base_resolve_reverse_ipv6(current_base, in, flags, callback, ptr)
2968                 ? 0 : -1;
2969 }
2970 
2971 /* ================================================================= */
2972 /* Search support */
2973 /* */
2974 /* the libc resolver has support for searching a number of domains */
2975 /* to find a name. If nothing else then it takes the single domain */
2976 /* from the gethostname() call. */
2977 /* */
2978 /* It can also be configured via the domain and search options in a */
2979 /* resolv.conf. */
2980 /* */
2981 /* The ndots option controls how many dots it takes for the resolver */
2982 /* to decide that a name is non-local and so try a raw lookup first. */
2983 
2984 struct search_domain {
2985         int len;
2986         struct search_domain *next;
2987         /* the text string is appended to this structure */
2988 };
2989 
2990 struct search_state {
2991         int refcount;
2992         int ndots;
2993         int num_domains;
2994         struct search_domain *head;
2995 };
2996 
2997 static void
2998 search_state_decref(struct search_state *const state) {
2999         if (!state) return;
3000         state->refcount--;
3001         if (!state->refcount) {
3002                 struct search_domain *next, *dom;
3003                 for (dom = state->head; dom; dom = next) {
3004                         next = dom->next;
3005                         mm_free(dom);
3006                 }
3007                 mm_free(state);
3008         }
3009 }
3010 
3011 static struct search_state *
3012 search_state_new(void) {
3013         struct search_state *state = (struct search_state *) mm_malloc(sizeof(struct search_state));
3014         if (!state) return NULL;
3015         memset(state, 0, sizeof(struct search_state));
3016         state->refcount = 1;
3017         state->ndots = 1;
3018 
3019         return state;
3020 }
3021 
3022 static void
3023 search_postfix_clear(struct evdns_base *base) {
3024         search_state_decref(base->global_search_state);
3025 
3026         base->global_search_state = search_state_new();
3027 }
3028 
3029 /* exported function */
3030 void
3031 evdns_base_search_clear(struct evdns_base *base)
3032 {
3033         EVDNS_LOCK(base);
3034         search_postfix_clear(base);
3035         EVDNS_UNLOCK(base);
3036 }
3037 
3038 void
3039 evdns_search_clear(void) {
3040         evdns_base_search_clear(current_base);
3041 }
3042 
3043 static void
3044 search_postfix_add(struct evdns_base *base, const char *domain) {
3045         size_t domain_len;
3046         struct search_domain *sdomain;
3047         while (domain[0] == '.') domain++;
3048         domain_len = strlen(domain);
3049 
3050         ASSERT_LOCKED(base);
3051         if (!base->global_search_state) base->global_search_state = search_state_new();
3052         if (!base->global_search_state) return;
3053         base->global_search_state->num_domains++;
3054 
3055         sdomain = (struct search_domain *) mm_malloc(sizeof(struct search_domain) + domain_len);
3056         if (!sdomain) return;
3057         memcpy( ((u8 *) sdomain) + sizeof(struct search_domain), domain, domain_len);
3058         sdomain->next = base->global_search_state->head;
3059         sdomain->len = (int) domain_len;
3060 
3061         base->global_search_state->head = sdomain;
3062 }
3063 
3064 /* reverse the order of members in the postfix list. This is needed because, */
3065 /* when parsing resolv.conf we push elements in the wrong order */
3066 static void
3067 search_reverse(struct evdns_base *base) {
3068         struct search_domain *cur, *prev = NULL, *next;
3069         ASSERT_LOCKED(base);
3070         cur = base->global_search_state->head;
3071         while (cur) {
3072                 next = cur->next;
3073                 cur->next = prev;
3074                 prev = cur;
3075                 cur = next;
3076         }
3077 
3078         base->global_search_state->head = prev;
3079 }
3080 
3081 /* exported function */
3082 void
3083 evdns_base_search_add(struct evdns_base *base, const char *domain) {
3084         EVDNS_LOCK(base);
3085         search_postfix_add(base, domain);
3086         EVDNS_UNLOCK(base);
3087 }
3088 void
3089 evdns_search_add(const char *domain) {
3090         evdns_base_search_add(current_base, domain);
3091 }
3092 
3093 /* exported function */
3094 void
3095 evdns_base_search_ndots_set(struct evdns_base *base, const int ndots) {
3096         EVDNS_LOCK(base);
3097         if (!base->global_search_state) base->global_search_state = search_state_new();
3098         if (base->global_search_state)
3099                 base->global_search_state->ndots = ndots;
3100         EVDNS_UNLOCK(base);
3101 }
3102 void
3103 evdns_search_ndots_set(const int ndots) {
3104         evdns_base_search_ndots_set(current_base, ndots);
3105 }
3106 
3107 static void
3108 search_set_from_hostname(struct evdns_base *base) {
3109         char hostname[OPAL_MAXHOSTNAMELEN], *domainname;
3110 
3111         ASSERT_LOCKED(base);
3112         search_postfix_clear(base);
3113         if (gethostname(hostname, sizeof(hostname))) return;
3114         domainname = strchr(hostname, '.');
3115         if (!domainname) return;
3116         search_postfix_add(base, domainname);
3117 }
3118 
3119 /* warning: returns malloced string */
3120 static char *
3121 search_make_new(const struct search_state *const state, int n, const char *const base_name) {
3122         const size_t base_len = strlen(base_name);
3123         const char need_to_append_dot = base_name[base_len - 1] == '.' ? 0 : 1;
3124         struct search_domain *dom;
3125 
3126         for (dom = state->head; dom; dom = dom->next) {
3127                 if (!n--) {
3128                         /* this is the postfix we want */
3129                         /* the actual postfix string is kept at the end of the structure */
3130                         const u8 *const postfix = ((u8 *) dom) + sizeof(struct search_domain);
3131                         const int postfix_len = dom->len;
3132                         char *const newname = (char *) mm_malloc(base_len + need_to_append_dot + postfix_len + 1);
3133                         if (!newname) return NULL;
3134                         memcpy(newname, base_name, base_len);
3135                         if (need_to_append_dot) newname[base_len] = '.';
3136                         memcpy(newname + base_len + need_to_append_dot, postfix, postfix_len);
3137                         newname[base_len + need_to_append_dot + postfix_len] = 0;
3138                         return newname;
3139                 }
3140         }
3141 
3142         /* we ran off the end of the list and still didn't find the requested string */
3143         EVUTIL_ASSERT(0);
3144         return NULL; /* unreachable; stops warnings in some compilers. */
3145 }
3146 
3147 static struct request *
3148 search_request_new(struct evdns_base *base, struct evdns_request *handle,
3149                    int type, const char *const name, int flags,
3150                    evdns_callback_type user_callback, void *user_arg) {
3151         ASSERT_LOCKED(base);
3152         EVUTIL_ASSERT(type == TYPE_A || type == TYPE_AAAA);
3153         EVUTIL_ASSERT(handle->current_req == NULL);
3154         if ( ((flags & DNS_QUERY_NO_SEARCH) == 0) &&
3155              base->global_search_state &&
3156                  base->global_search_state->num_domains) {
3157                 /* we have some domains to search */
3158                 struct request *req;
3159                 if (string_num_dots(name) >= base->global_search_state->ndots) {
3160                         req = request_new(base, handle, type, name, flags, user_callback, user_arg);
3161                         if (!req) return NULL;
3162                         handle->search_index = -1;
3163                 } else {
3164                         char *const new_name = search_make_new(base->global_search_state, 0, name);
3165                         if (!new_name) return NULL;
3166                         req = request_new(base, handle, type, new_name, flags, user_callback, user_arg);
3167                         mm_free(new_name);
3168                         if (!req) return NULL;
3169                         handle->search_index = 0;
3170                 }
3171                 EVUTIL_ASSERT(handle->search_origname == NULL);
3172                 handle->search_origname = mm_strdup(name);
3173                 if (handle->search_origname == NULL) {
3174                         /* XXX Should we dealloc req? If yes, how? */
3175                         if (req)
3176                                 mm_free(req);
3177                         return NULL;
3178                 }
3179                 handle->search_state = base->global_search_state;
3180                 handle->search_flags = flags;
3181                 base->global_search_state->refcount++;
3182                 request_submit(req);
3183                 return req;
3184         } else {
3185                 struct request *const req = request_new(base, handle, type, name, flags, user_callback, user_arg);
3186                 if (!req) return NULL;
3187                 request_submit(req);
3188                 return req;
3189         }
3190 }
3191 
3192 /* this is called when a request has failed to find a name. We need to check */
3193 /* if it is part of a search and, if so, try the next name in the list */
3194 /* returns: */
3195 /*   0 another request has been submitted */
3196 /*   1 no more requests needed */
3197 static int
3198 search_try_next(struct evdns_request *const handle) {
3199         struct request *req = handle->current_req;
3200         struct evdns_base *base = req->base;
3201         struct request *newreq;
3202         ASSERT_LOCKED(base);
3203         if (handle->search_state) {
3204                 /* it is part of a search */
3205                 char *new_name;
3206                 handle->search_index++;
3207                 if (handle->search_index >= handle->search_state->num_domains) {
3208                         /* no more postfixes to try, however we may need to try */
3209                         /* this name without a postfix */
3210                         if (string_num_dots(handle->search_origname) < handle->search_state->ndots) {
3211                                 /* yep, we need to try it raw */
3212                                 newreq = request_new(base, NULL, req->request_type, handle->search_origname, handle->search_flags, req->user_callback, req->user_pointer);
3213                                 log(EVDNS_LOG_DEBUG, "Search: trying raw query %s", handle->search_origname);
3214                                 if (newreq) {
3215                                         search_request_finished(handle);
3216                                         goto submit_next;
3217                                 }
3218                         }
3219                         return 1;
3220                 }
3221 
3222                 new_name = search_make_new(handle->search_state, handle->search_index, handle->search_origname);
3223                 if (!new_name) return 1;
3224                 log(EVDNS_LOG_DEBUG, "Search: now trying %s (%d)", new_name, handle->search_index);
3225                 newreq = request_new(base, NULL, req->request_type, new_name, handle->search_flags, req->user_callback, req->user_pointer);
3226                 mm_free(new_name);
3227                 if (!newreq) return 1;
3228                 goto submit_next;
3229         }
3230         return 1;
3231 
3232 submit_next:
3233         request_finished(req, &REQ_HEAD(req->base, req->trans_id), 0);
3234         handle->current_req = newreq;
3235         newreq->handle = handle;
3236         request_submit(newreq);
3237         return 0;
3238 }
3239 
3240 static void
3241 search_request_finished(struct evdns_request *const handle) {
3242         ASSERT_LOCKED(handle->current_req->base);
3243         if (handle->search_state) {
3244                 search_state_decref(handle->search_state);
3245                 handle->search_state = NULL;
3246         }
3247         if (handle->search_origname) {
3248                 mm_free(handle->search_origname);
3249                 handle->search_origname = NULL;
3250         }
3251 }
3252 
3253 /* ================================================================= */
3254 /* Parsing resolv.conf files */
3255 
3256 static void
3257 evdns_resolv_set_defaults(struct evdns_base *base, int flags) {
3258         /* if the file isn't found then we assume a local resolver */
3259         ASSERT_LOCKED(base);
3260         if (flags & DNS_OPTION_SEARCH) search_set_from_hostname(base);
3261         if (flags & DNS_OPTION_NAMESERVERS) evdns_base_nameserver_ip_add(base,"127.0.0.1");
3262 }
3263 
3264 #ifndef _EVENT_HAVE_STRTOK_R
3265 static char *
3266 strtok_r(char *s, const char *delim, char **state) {
3267         char *cp, *start;
3268         start = cp = s ? s : *state;
3269         if (!cp)
3270                 return NULL;
3271         while (*cp && !strchr(delim, *cp))
3272                 ++cp;
3273         if (!*cp) {
3274                 if (cp == start)
3275                         return NULL;
3276                 *state = NULL;
3277                 return start;
3278         } else {
3279                 *cp++ = '\0';
3280                 *state = cp;
3281                 return start;
3282         }
3283 }
3284 #endif
3285 
3286 /* helper version of atoi which returns -1 on error */
3287 static int
3288 strtoint(const char *const str)
3289 {
3290         char *endptr;
3291         const int r = strtol(str, &endptr, 10);
3292         if (*endptr) return -1;
3293         return r;
3294 }
3295 
3296 /* Parse a number of seconds into a timeval; return -1 on error. */
3297 static int
3298 strtotimeval(const char *const str, struct timeval *out)
3299 {
3300         double d;
3301         char *endptr;
3302         d = strtod(str, &endptr);
3303         if (*endptr) return -1;
3304         if (d < 0) return -1;
3305         out->tv_sec = (int) d;
3306         out->tv_usec = (int) ((d - (int) d)*1000000);
3307         if (out->tv_sec == 0 && out->tv_usec < 1000) /* less than 1 msec */
3308                 return -1;
3309         return 0;
3310 }
3311 
3312 /* helper version of atoi that returns -1 on error and clips to bounds. */
3313 static int
3314 strtoint_clipped(const char *const str, int min, int max)
3315 {
3316         int r = strtoint(str);
3317         if (r == -1)
3318                 return r;
3319         else if (r<min)
3320                 return min;
3321         else if (r>max)
3322                 return max;
3323         else
3324                 return r;
3325 }
3326 
3327 static int
3328 evdns_base_set_max_requests_inflight(struct evdns_base *base, int maxinflight)
3329 {
3330         int old_n_heads = base->n_req_heads, n_heads;
3331         struct request **old_heads = base->req_heads, **new_heads, *req;
3332         int i;
3333 
3334         ASSERT_LOCKED(base);
3335         if (maxinflight < 1)
3336                 maxinflight = 1;
3337         n_heads = (maxinflight+4) / 5;
3338         EVUTIL_ASSERT(n_heads > 0);
3339         new_heads = mm_calloc(n_heads, sizeof(struct request*));
3340         if (!new_heads)
3341                 return (-1);
3342         if (old_heads) {
3343                 for (i = 0; i < old_n_heads; ++i) {
3344                         while (old_heads[i]) {
3345                                 req = old_heads[i];
3346                                 evdns_request_remove(req, &old_heads[i]);
3347                                 evdns_request_insert(req, &new_heads[req->trans_id % n_heads]);
3348                         }
3349                 }
3350                 mm_free(old_heads);
3351         }
3352         base->req_heads = new_heads;
3353         base->n_req_heads = n_heads;
3354         base->global_max_requests_inflight = maxinflight;
3355         return (0);
3356 }
3357 
3358 /* exported function */
3359 int
3360 evdns_base_set_option(struct evdns_base *base,
3361     const char *option, const char *val)
3362 {
3363         int res;
3364         EVDNS_LOCK(base);
3365         res = evdns_base_set_option_impl(base, option, val, DNS_OPTIONS_ALL);
3366         EVDNS_UNLOCK(base);
3367         return res;
3368 }
3369 
3370 static inline int
3371 str_matches_option(const char *s1, const char *optionname)
3372 {
3373         /* Option names are given as "option:" We accept either 'option' in
3374          * s1, or 'option:randomjunk'.  The latter form is to implement the
3375          * resolv.conf parser. */
3376         size_t optlen = strlen(optionname);
3377         size_t slen = strlen(s1);
3378         if (slen == optlen || slen == optlen - 1)
3379                 return !strncmp(s1, optionname, slen);
3380         else if (slen > optlen)
3381                 return !strncmp(s1, optionname, optlen);
3382         else
3383                 return 0;
3384 }
3385 
3386 static int
3387 evdns_base_set_option_impl(struct evdns_base *base,
3388     const char *option, const char *val, int flags)
3389 {
3390         ASSERT_LOCKED(base);
3391         if (str_matches_option(option, "ndots:")) {
3392                 const int ndots = strtoint(val);
3393                 if (ndots == -1) return -1;
3394                 if (!(flags & DNS_OPTION_SEARCH)) return 0;
3395                 log(EVDNS_LOG_DEBUG, "Setting ndots to %d", ndots);
3396                 if (!base->global_search_state) base->global_search_state = search_state_new();
3397                 if (!base->global_search_state) return -1;
3398                 base->global_search_state->ndots = ndots;
3399         } else if (str_matches_option(option, "timeout:")) {
3400                 struct timeval tv;
3401                 if (strtotimeval(val, &tv) == -1) return -1;
3402                 if (!(flags & DNS_OPTION_MISC)) return 0;
3403                 log(EVDNS_LOG_DEBUG, "Setting timeout to %s", val);
3404                 memcpy(&base->global_timeout, &tv, sizeof(struct timeval));
3405         } else if (str_matches_option(option, "getaddrinfo-allow-skew:")) {
3406                 struct timeval tv;
3407                 if (strtotimeval(val, &tv) == -1) return -1;
3408                 if (!(flags & DNS_OPTION_MISC)) return 0;
3409                 log(EVDNS_LOG_DEBUG, "Setting getaddrinfo-allow-skew to %s",
3410                     val);
3411                 memcpy(&base->global_getaddrinfo_allow_skew, &tv,
3412                     sizeof(struct timeval));
3413         } else if (str_matches_option(option, "max-timeouts:")) {
3414                 const int maxtimeout = strtoint_clipped(val, 1, 255);
3415                 if (maxtimeout == -1) return -1;
3416                 if (!(flags & DNS_OPTION_MISC)) return 0;
3417                 log(EVDNS_LOG_DEBUG, "Setting maximum allowed timeouts to %d",
3418                         maxtimeout);
3419                 base->global_max_nameserver_timeout = maxtimeout;
3420         } else if (str_matches_option(option, "max-inflight:")) {
3421                 const int maxinflight = strtoint_clipped(val, 1, 65000);
3422                 if (maxinflight == -1) return -1;
3423                 if (!(flags & DNS_OPTION_MISC)) return 0;
3424                 log(EVDNS_LOG_DEBUG, "Setting maximum inflight requests to %d",
3425                         maxinflight);
3426                 evdns_base_set_max_requests_inflight(base, maxinflight);
3427         } else if (str_matches_option(option, "attempts:")) {
3428                 int retries = strtoint(val);
3429                 if (retries == -1) return -1;
3430                 if (retries > 255) retries = 255;
3431                 if (!(flags & DNS_OPTION_MISC)) return 0;
3432                 log(EVDNS_LOG_DEBUG, "Setting retries to %d", retries);
3433                 base->global_max_retransmits = retries;
3434         } else if (str_matches_option(option, "randomize-case:")) {
3435                 int randcase = strtoint(val);
3436                 if (!(flags & DNS_OPTION_MISC)) return 0;
3437                 base->global_randomize_case = randcase;
3438         } else if (str_matches_option(option, "bind-to:")) {
3439                 /* XXX This only applies to successive nameservers, not
3440                  * to already-configured ones.  We might want to fix that. */
3441                 int len = sizeof(base->global_outgoing_address);
3442                 if (!(flags & DNS_OPTION_NAMESERVERS)) return 0;
3443                 if (evutil_parse_sockaddr_port(val,
3444                         (struct sockaddr*)&base->global_outgoing_address, &len))
3445                         return -1;
3446                 base->global_outgoing_addrlen = len;
3447         } else if (str_matches_option(option, "initial-probe-timeout:")) {
3448                 struct timeval tv;
3449                 if (strtotimeval(val, &tv) == -1) return -1;
3450                 if (tv.tv_sec > 3600)
3451                         tv.tv_sec = 3600;
3452                 if (!(flags & DNS_OPTION_MISC)) return 0;
3453                 log(EVDNS_LOG_DEBUG, "Setting initial probe timeout to %s",
3454                     val);
3455                 memcpy(&base->global_nameserver_probe_initial_timeout, &tv,
3456                     sizeof(tv));
3457         }
3458         return 0;
3459 }
3460 
3461 int
3462 evdns_set_option(const char *option, const char *val, int flags)
3463 {
3464         if (!current_base)
3465                 current_base = evdns_base_new(NULL, 0);
3466         return evdns_base_set_option(current_base, option, val);
3467 }
3468 
3469 static void
3470 resolv_conf_parse_line(struct evdns_base *base, char *const start, int flags) {
3471         char *strtok_state;
3472         static const char *const delims = " \t";
3473 #define NEXT_TOKEN strtok_r(NULL, delims, &strtok_state)
3474 
3475 
3476         char *const first_token = strtok_r(start, delims, &strtok_state);
3477         ASSERT_LOCKED(base);
3478         if (!first_token) return;
3479 
3480         if (!strcmp(first_token, "nameserver") && (flags & DNS_OPTION_NAMESERVERS)) {
3481                 const char *const nameserver = NEXT_TOKEN;
3482 
3483                 if (nameserver)
3484                         evdns_base_nameserver_ip_add(base, nameserver);
3485         } else if (!strcmp(first_token, "domain") && (flags & DNS_OPTION_SEARCH)) {
3486                 const char *const domain = NEXT_TOKEN;
3487                 if (domain) {
3488                         search_postfix_clear(base);
3489                         search_postfix_add(base, domain);
3490                 }
3491         } else if (!strcmp(first_token, "search") && (flags & DNS_OPTION_SEARCH)) {
3492                 const char *domain;
3493                 search_postfix_clear(base);
3494 
3495                 while ((domain = NEXT_TOKEN)) {
3496                         search_postfix_add(base, domain);
3497                 }
3498                 search_reverse(base);
3499         } else if (!strcmp(first_token, "options")) {
3500                 const char *option;
3501                 while ((option = NEXT_TOKEN)) {
3502                         const char *val = strchr(option, ':');
3503                         evdns_base_set_option_impl(base, option, val ? val+1 : "", flags);
3504                 }
3505         }
3506 #undef NEXT_TOKEN
3507 }
3508 
3509 /* exported function */
3510 /* returns: */
3511 /*   0 no errors */
3512 /*   1 failed to open file */
3513 /*   2 failed to stat file */
3514 /*   3 file too large */
3515 /*   4 out of memory */
3516 /*   5 short read from file */
3517 int
3518 evdns_base_resolv_conf_parse(struct evdns_base *base, int flags, const char *const filename) {
3519         int res;
3520         EVDNS_LOCK(base);
3521         res = evdns_base_resolv_conf_parse_impl(base, flags, filename);
3522         EVDNS_UNLOCK(base);
3523         return res;
3524 }
3525 
3526 static char *
3527 evdns_get_default_hosts_filename(void)
3528 {
3529 #ifdef WIN32
3530         /* Windows is a little coy about where it puts its configuration
3531          * files.  Sure, they're _usually_ in C:\windows\system32, but
3532          * there's no reason in principle they couldn't be in
3533          * W:\hoboken chicken emergency\
3534          */
3535         char path[MAX_PATH+1];
3536         static const char hostfile[] = "\\drivers\\etc\\hosts";
3537         char *path_out;
3538         size_t len_out;
3539 
3540         if (! SHGetSpecialFolderPathA(NULL, path, CSIDL_SYSTEM, 0))
3541                 return NULL;
3542         len_out = strlen(path)+strlen(hostfile);
3543         path_out = mm_malloc(len_out+1);
3544         evutil_snprintf(path_out, len_out, "%s%s", path, hostfile);
3545         return path_out;
3546 #else
3547         return mm_strdup("/etc/hosts");
3548 #endif
3549 }
3550 
3551 static int
3552 evdns_base_resolv_conf_parse_impl(struct evdns_base *base, int flags, const char *const filename) {
3553         size_t n;
3554         char *resolv;
3555         char *start;
3556         int err = 0;
3557 
3558         log(EVDNS_LOG_DEBUG, "Parsing resolv.conf file %s", filename);
3559 
3560         if (flags & DNS_OPTION_HOSTSFILE) {
3561                 char *fname = evdns_get_default_hosts_filename();
3562                 evdns_base_load_hosts(base, fname);
3563                 if (fname)
3564                         mm_free(fname);
3565         }
3566 
3567         if ((err = evutil_read_file(filename, &resolv, &n, 0)) < 0) {
3568                 if (err == -1) {
3569                         /* No file. */
3570                         evdns_resolv_set_defaults(base, flags);
3571                         return 1;
3572                 } else {
3573                         return 2;
3574                 }
3575         }
3576 
3577         start = resolv;
3578         for (;;) {
3579                 char *const newline = strchr(start, '\n');
3580                 if (!newline) {
3581                         resolv_conf_parse_line(base, start, flags);
3582                         break;
3583                 } else {
3584                         *newline = 0;
3585                         resolv_conf_parse_line(base, start, flags);
3586                         start = newline + 1;
3587                 }
3588         }
3589 
3590         if (!base->server_head && (flags & DNS_OPTION_NAMESERVERS)) {
3591                 /* no nameservers were configured. */
3592                 evdns_base_nameserver_ip_add(base, "127.0.0.1");
3593                 err = 6;
3594         }
3595         if (flags & DNS_OPTION_SEARCH && (!base->global_search_state || base->global_search_state->num_domains == 0)) {
3596                 search_set_from_hostname(base);
3597         }
3598 
3599         mm_free(resolv);
3600         return err;
3601 }
3602 
3603 int
3604 evdns_resolv_conf_parse(int flags, const char *const filename) {
3605         if (!current_base)
3606                 current_base = evdns_base_new(NULL, 0);
3607         return evdns_base_resolv_conf_parse(current_base, flags, filename);
3608 }
3609 
3610 
3611 #ifdef WIN32
3612 /* Add multiple nameservers from a space-or-comma-separated list. */
3613 static int
3614 evdns_nameserver_ip_add_line(struct evdns_base *base, const char *ips) {
3615         const char *addr;
3616         char *buf;
3617         int r;
3618         ASSERT_LOCKED(base);
3619         while (*ips) {
3620                 while (isspace(*ips) || *ips == ',' || *ips == '\t')
3621                         ++ips;
3622                 addr = ips;
3623                 while (isdigit(*ips) || *ips == '.' || *ips == ':' ||
3624                     *ips=='[' || *ips==']')
3625                         ++ips;
3626                 buf = mm_malloc(ips-addr+1);
3627                 if (!buf) return 4;
3628                 memcpy(buf, addr, ips-addr);
3629                 buf[ips-addr] = '\0';
3630                 r = evdns_base_nameserver_ip_add(base, buf);
3631                 mm_free(buf);
3632                 if (r) return r;
3633         }
3634         return 0;
3635 }
3636 
3637 typedef DWORD(WINAPI *GetNetworkParams_fn_t)(FIXED_INFO *, DWORD*);
3638 
3639 /* Use the windows GetNetworkParams interface in iphlpapi.dll to */
3640 /* figure out what our nameservers are. */
3641 static int
3642 load_nameservers_with_getnetworkparams(struct evdns_base *base)
3643 {
3644         /* Based on MSDN examples and inspection of  c-ares code. */
3645         FIXED_INFO *fixed;
3646         HMODULE handle = 0;
3647         ULONG size = sizeof(FIXED_INFO);
3648         void *buf = NULL;
3649         int status = 0, r, added_any;
3650         IP_ADDR_STRING *ns;
3651         GetNetworkParams_fn_t fn;
3652 
3653         ASSERT_LOCKED(base);
3654         if (!(handle = evutil_load_windows_system_library(
3655                         TEXT("iphlpapi.dll")))) {
3656                 log(EVDNS_LOG_WARN, "Could not open iphlpapi.dll");
3657                 status = -1;
3658                 goto done;
3659         }
3660         if (!(fn = (GetNetworkParams_fn_t) GetProcAddress(handle, "GetNetworkParams"))) {
3661                 log(EVDNS_LOG_WARN, "Could not get address of function.");
3662                 status = -1;
3663                 goto done;
3664         }
3665 
3666         buf = mm_malloc(size);
3667         if (!buf) { status = 4; goto done; }
3668         fixed = buf;
3669         r = fn(fixed, &size);
3670         if (r != ERROR_SUCCESS && r != ERROR_BUFFER_OVERFLOW) {
3671                 status = -1;
3672                 goto done;
3673         }
3674         if (r != ERROR_SUCCESS) {
3675                 mm_free(buf);
3676                 buf = mm_malloc(size);
3677                 if (!buf) { status = 4; goto done; }
3678                 fixed = buf;
3679                 r = fn(fixed, &size);
3680                 if (r != ERROR_SUCCESS) {
3681                         log(EVDNS_LOG_DEBUG, "fn() failed.");
3682                         status = -1;
3683                         goto done;
3684                 }
3685         }
3686 
3687         EVUTIL_ASSERT(fixed);
3688         added_any = 0;
3689         ns = &(fixed->DnsServerList);
3690         while (ns) {
3691                 r = evdns_nameserver_ip_add_line(base, ns->IpAddress.String);
3692                 if (r) {
3693                         log(EVDNS_LOG_DEBUG,"Could not add nameserver %s to list,error: %d",
3694                                 (ns->IpAddress.String),(int)GetLastError());
3695                         status = r;
3696                 } else {
3697                         ++added_any;
3698                         log(EVDNS_LOG_DEBUG,"Successfully added %s as nameserver",ns->IpAddress.String);
3699                 }
3700 
3701                 ns = ns->Next;
3702         }
3703 
3704         if (!added_any) {
3705                 log(EVDNS_LOG_DEBUG, "No nameservers added.");
3706                 if (status == 0)
3707                         status = -1;
3708         } else {
3709                 status = 0;
3710         }
3711 
3712  done:
3713         if (buf)
3714                 mm_free(buf);
3715         if (handle)
3716                 FreeLibrary(handle);
3717         return status;
3718 }
3719 
3720 static int
3721 config_nameserver_from_reg_key(struct evdns_base *base, HKEY key, const TCHAR *subkey)
3722 {
3723         char *buf;
3724         DWORD bufsz = 0, type = 0;
3725         int status = 0;
3726 
3727         ASSERT_LOCKED(base);
3728         if (RegQueryValueEx(key, subkey, 0, &type, NULL, &bufsz)
3729             != ERROR_MORE_DATA)
3730                 return -1;
3731         if (!(buf = mm_malloc(bufsz)))
3732                 return -1;
3733 
3734         if (RegQueryValueEx(key, subkey, 0, &type, (LPBYTE)buf, &bufsz)
3735             == ERROR_SUCCESS && bufsz > 1) {
3736                 status = evdns_nameserver_ip_add_line(base,buf);
3737         }
3738 
3739         mm_free(buf);
3740         return status;
3741 }
3742 
3743 #define SERVICES_KEY TEXT("System\\CurrentControlSet\\Services\\")
3744 #define WIN_NS_9X_KEY  SERVICES_KEY TEXT("VxD\\MSTCP")
3745 #define WIN_NS_NT_KEY  SERVICES_KEY TEXT("Tcpip\\Parameters")
3746 
3747 static int
3748 load_nameservers_from_registry(struct evdns_base *base)
3749 {
3750         int found = 0;
3751         int r;
3752 #define TRY(k, name) \
3753         if (!found && config_nameserver_from_reg_key(base,k,TEXT(name)) == 0) { \
3754                 log(EVDNS_LOG_DEBUG,"Found nameservers in %s/%s",#k,name); \
3755                 found = 1;                                              \
3756         } else if (!found) {                                            \
3757                 log(EVDNS_LOG_DEBUG,"Didn't find nameservers in %s/%s", \
3758                     #k,#name);                                          \
3759         }
3760 
3761         ASSERT_LOCKED(base);
3762 
3763         if (((int)GetVersion()) > 0) { /* NT */
3764                 HKEY nt_key = 0, interfaces_key = 0;
3765 
3766                 if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, WIN_NS_NT_KEY, 0,
3767                                  KEY_READ, &nt_key) != ERROR_SUCCESS) {
3768                         log(EVDNS_LOG_DEBUG,"Couldn't open nt key, %d",(int)GetLastError());
3769                         return -1;
3770                 }
3771                 r = RegOpenKeyEx(nt_key, TEXT("Interfaces"), 0,
3772                              KEY_QUERY_VALUE|KEY_ENUMERATE_SUB_KEYS,
3773                              &interfaces_key);
3774                 if (r != ERROR_SUCCESS) {
3775                         log(EVDNS_LOG_DEBUG,"Couldn't open interfaces key, %d",(int)GetLastError());
3776                         return -1;
3777                 }
3778                 TRY(nt_key, "NameServer");
3779                 TRY(nt_key, "DhcpNameServer");
3780                 TRY(interfaces_key, "NameServer");
3781                 TRY(interfaces_key, "DhcpNameServer");
3782                 RegCloseKey(interfaces_key);
3783                 RegCloseKey(nt_key);
3784         } else {
3785                 HKEY win_key = 0;
3786                 if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, WIN_NS_9X_KEY, 0,
3787                                  KEY_READ, &win_key) != ERROR_SUCCESS) {
3788                         log(EVDNS_LOG_DEBUG, "Couldn't open registry key, %d", (int)GetLastError());
3789                         return -1;
3790                 }
3791                 TRY(win_key, "NameServer");
3792                 RegCloseKey(win_key);
3793         }
3794 
3795         if (found == 0) {
3796                 log(EVDNS_LOG_WARN,"Didn't find any nameservers.");
3797         }
3798 
3799         return found ? 0 : -1;
3800 #undef TRY
3801 }
3802 
3803 int
3804 evdns_base_config_windows_nameservers(struct evdns_base *base)
3805 {
3806         int r;
3807         char *fname;
3808         if (base == NULL)
3809                 base = current_base;
3810         if (base == NULL)
3811                 return -1;
3812         EVDNS_LOCK(base);
3813         if (load_nameservers_with_getnetworkparams(base) == 0) {
3814                 EVDNS_UNLOCK(base);
3815                 return 0;
3816         }
3817         r = load_nameservers_from_registry(base);
3818 
3819         fname = evdns_get_default_hosts_filename();
3820         evdns_base_load_hosts(base, fname);
3821         if (fname)
3822                 mm_free(fname);
3823 
3824         EVDNS_UNLOCK(base);
3825         return r;
3826 }
3827 
3828 int
3829 evdns_config_windows_nameservers(void)
3830 {
3831         if (!current_base) {
3832                 current_base = evdns_base_new(NULL, 1);
3833                 return current_base == NULL ? -1 : 0;
3834         } else {
3835                 return evdns_base_config_windows_nameservers(current_base);
3836         }
3837 }
3838 #endif
3839 
3840 struct evdns_base *
3841 evdns_base_new(struct event_base *event_base, int initialize_nameservers)
3842 {
3843         struct evdns_base *base;
3844 
3845         if (evutil_secure_rng_init() < 0) {
3846                 log(EVDNS_LOG_WARN, "Unable to seed random number generator; "
3847                     "DNS can't run.");
3848                 return NULL;
3849         }
3850 
3851         /* Give the evutil library a hook into its evdns-enabled
3852          * functionality.  We can't just call evdns_getaddrinfo directly or
3853          * else libevent-core will depend on libevent-extras. */
3854         evutil_set_evdns_getaddrinfo_fn(evdns_getaddrinfo);
3855 
3856         base = mm_malloc(sizeof(struct evdns_base));
3857         if (base == NULL)
3858                 return (NULL);
3859         memset(base, 0, sizeof(struct evdns_base));
3860         base->req_waiting_head = NULL;
3861 
3862         EVTHREAD_ALLOC_LOCK(base->lock, EVTHREAD_LOCKTYPE_RECURSIVE);
3863         EVDNS_LOCK(base);
3864 
3865         /* Set max requests inflight and allocate req_heads. */
3866         base->req_heads = NULL;
3867 
3868         evdns_base_set_max_requests_inflight(base, 64);
3869 
3870         base->server_head = NULL;
3871         base->event_base = event_base;
3872         base->global_good_nameservers = base->global_requests_inflight =
3873                 base->global_requests_waiting = 0;
3874 
3875         base->global_timeout.tv_sec = 5;
3876         base->global_timeout.tv_usec = 0;
3877         base->global_max_reissues = 1;
3878         base->global_max_retransmits = 3;
3879         base->global_max_nameserver_timeout = 3;
3880         base->global_search_state = NULL;
3881         base->global_randomize_case = 1;
3882         base->global_getaddrinfo_allow_skew.tv_sec = 3;
3883         base->global_getaddrinfo_allow_skew.tv_usec = 0;
3884         base->global_nameserver_probe_initial_timeout.tv_sec = 10;
3885         base->global_nameserver_probe_initial_timeout.tv_usec = 0;
3886 
3887         TAILQ_INIT(&base->hostsdb);
3888 
3889         if (initialize_nameservers) {
3890                 int r;
3891 #ifdef WIN32
3892                 r = evdns_base_config_windows_nameservers(base);
3893 #else
3894                 r = evdns_base_resolv_conf_parse(base, DNS_OPTIONS_ALL, "/etc/resolv.conf");
3895 #endif
3896                 if (r == -1) {
3897                         evdns_base_free_and_unlock(base, 0);
3898                         return NULL;
3899                 }
3900         }
3901         EVDNS_UNLOCK(base);
3902         return base;
3903 }
3904 
3905 int
3906 evdns_init(void)
3907 {
3908         struct evdns_base *base = evdns_base_new(NULL, 1);
3909         if (base) {
3910                 current_base = base;
3911                 return 0;
3912         } else {
3913                 return -1;
3914         }
3915 }
3916 
3917 const char *
3918 evdns_err_to_string(int err)
3919 {
3920     switch (err) {
3921         case DNS_ERR_NONE: return "no error";
3922         case DNS_ERR_FORMAT: return "misformatted query";
3923         case DNS_ERR_SERVERFAILED: return "server failed";
3924         case DNS_ERR_NOTEXIST: return "name does not exist";
3925         case DNS_ERR_NOTIMPL: return "query not implemented";
3926         case DNS_ERR_REFUSED: return "refused";
3927 
3928         case DNS_ERR_TRUNCATED: return "reply truncated or ill-formed";
3929         case DNS_ERR_UNKNOWN: return "unknown";
3930         case DNS_ERR_TIMEOUT: return "request timed out";
3931         case DNS_ERR_SHUTDOWN: return "dns subsystem shut down";
3932         case DNS_ERR_CANCEL: return "dns request canceled";
3933         case DNS_ERR_NODATA: return "no records in the reply";
3934         default: return "[Unknown error code]";
3935     }
3936 }
3937 
3938 static void
3939 evdns_nameserver_free(struct nameserver *server)
3940 {
3941         if (server->socket >= 0)
3942         evutil_closesocket(server->socket);
3943         (void) event_del(&server->event);
3944         event_debug_unassign(&server->event);
3945         if (server->state == 0)
3946                 (void) event_del(&server->timeout_event);
3947         if (server->probe_request) {
3948                 evdns_cancel_request(server->base, server->probe_request);
3949                 server->probe_request = NULL;
3950         }
3951         event_debug_unassign(&server->timeout_event);
3952         mm_free(server);
3953 }
3954 
3955 static void
3956 evdns_base_free_and_unlock(struct evdns_base *base, int fail_requests)
3957 {
3958         struct nameserver *server, *server_next;
3959         struct search_domain *dom, *dom_next;
3960         int i;
3961 
3962         /* Requires that we hold the lock. */
3963 
3964         /* TODO(nickm) we might need to refcount here. */
3965 
3966         for (server = base->server_head; server; server = server_next) {
3967                 server_next = server->next;
3968                 evdns_nameserver_free(server);
3969                 if (server_next == base->server_head)
3970                         break;
3971         }
3972         base->server_head = NULL;
3973         base->global_good_nameservers = 0;
3974 
3975         for (i = 0; i < base->n_req_heads; ++i) {
3976                 while (base->req_heads[i]) {
3977                         if (fail_requests)
3978                                 reply_schedule_callback(base->req_heads[i], 0, DNS_ERR_SHUTDOWN, NULL);
3979                         request_finished(base->req_heads[i], &REQ_HEAD(base, base->req_heads[i]->trans_id), 1);
3980                 }
3981         }
3982         while (base->req_waiting_head) {
3983                 if (fail_requests)
3984                         reply_schedule_callback(base->req_waiting_head, 0, DNS_ERR_SHUTDOWN, NULL);
3985                 request_finished(base->req_waiting_head, &base->req_waiting_head, 1);
3986         }
3987         base->global_requests_inflight = base->global_requests_waiting = 0;
3988 
3989 
3990         if (base->global_search_state) {
3991                 for (dom = base->global_search_state->head; dom; dom = dom_next) {
3992                         dom_next = dom->next;
3993                         mm_free(dom);
3994                 }
3995                 mm_free(base->global_search_state);
3996                 base->global_search_state = NULL;
3997         }
3998 
3999         {
4000                 struct hosts_entry *victim;
4001                 while ((victim = TAILQ_FIRST(&base->hostsdb))) {
4002                         TAILQ_REMOVE(&base->hostsdb, victim, next);
4003                         mm_free(victim);
4004                 }
4005         }
4006 
4007         mm_free(base->req_heads);
4008 
4009         EVDNS_UNLOCK(base);
4010         EVTHREAD_FREE_LOCK(base->lock, EVTHREAD_LOCKTYPE_RECURSIVE);
4011 
4012         mm_free(base);
4013 }
4014 
4015 void
4016 evdns_base_free(struct evdns_base *base, int fail_requests)
4017 {
4018         EVDNS_LOCK(base);
4019         evdns_base_free_and_unlock(base, fail_requests);
4020 }
4021 
4022 void
4023 evdns_shutdown(int fail_requests)
4024 {
4025         if (current_base) {
4026                 struct evdns_base *b = current_base;
4027                 current_base = NULL;
4028                 evdns_base_free(b, fail_requests);
4029         }
4030         evdns_log_fn = NULL;
4031 }
4032 
4033 static int
4034 evdns_base_parse_hosts_line(struct evdns_base *base, char *line)
4035 {
4036         char *strtok_state;
4037         static const char *const delims = " \t";
4038         char *const addr = strtok_r(line, delims, &strtok_state);
4039         char *hostname, *hash;
4040         struct sockaddr_storage ss;
4041         int socklen = sizeof(ss);
4042         ASSERT_LOCKED(base);
4043 
4044 #define NEXT_TOKEN strtok_r(NULL, delims, &strtok_state)
4045 
4046         if (!addr || *addr == '#')
4047                 return 0;
4048 
4049         memset(&ss, 0, sizeof(ss));
4050         if (evutil_parse_sockaddr_port(addr, (struct sockaddr*)&ss, &socklen)<0)
4051                 return -1;
4052         if (socklen > (int)sizeof(struct sockaddr_in6))
4053                 return -1;
4054 
4055         if (sockaddr_getport((struct sockaddr*)&ss))
4056                 return -1;
4057 
4058         while ((hostname = NEXT_TOKEN)) {
4059                 struct hosts_entry *he;
4060                 size_t namelen;
4061                 if ((hash = strchr(hostname, '#'))) {
4062                         if (hash == hostname)
4063                                 return 0;
4064                         *hash = '\0';
4065                 }
4066 
4067                 namelen = strlen(hostname);
4068 
4069                 he = mm_calloc(1, sizeof(struct hosts_entry)+namelen);
4070                 if (!he)
4071                         return -1;
4072                 EVUTIL_ASSERT(socklen <= (int)sizeof(he->addr));
4073                 memcpy(&he->addr, &ss, socklen);
4074                 memcpy(he->hostname, hostname, namelen+1);
4075                 he->addrlen = socklen;
4076 
4077                 TAILQ_INSERT_TAIL(&base->hostsdb, he, next);
4078 
4079                 if (hash)
4080                         return 0;
4081         }
4082 
4083         return 0;
4084 #undef NEXT_TOKEN
4085 }
4086 
4087 static int
4088 evdns_base_load_hosts_impl(struct evdns_base *base, const char *hosts_fname)
4089 {
4090         char *str=NULL, *cp, *eol;
4091         size_t len;
4092         int err=0;
4093 
4094         ASSERT_LOCKED(base);
4095 
4096         if (hosts_fname == NULL ||
4097             (err = evutil_read_file(hosts_fname, &str, &len, 0)) < 0) {
4098                 char tmp[64];
4099                 strlcpy(tmp, "127.0.0.1   localhost", sizeof(tmp));
4100                 evdns_base_parse_hosts_line(base, tmp);
4101                 strlcpy(tmp, "::1   localhost", sizeof(tmp));
4102                 evdns_base_parse_hosts_line(base, tmp);
4103                 return err ? -1 : 0;
4104         }
4105 
4106         /* This will break early if there is a NUL in the hosts file.
4107          * Probably not a problem.*/
4108         cp = str;
4109         for (;;) {
4110                 eol = strchr(cp, '\n');
4111 
4112                 if (eol) {
4113                         *eol = '\0';
4114                         evdns_base_parse_hosts_line(base, cp);
4115                         cp = eol+1;
4116                 } else {
4117                         evdns_base_parse_hosts_line(base, cp);
4118                         break;
4119                 }
4120         }
4121 
4122         mm_free(str);
4123         return 0;
4124 }
4125 
4126 int
4127 evdns_base_load_hosts(struct evdns_base *base, const char *hosts_fname)
4128 {
4129         int res;
4130         if (!base)
4131                 base = current_base;
4132         EVDNS_LOCK(base);
4133         res = evdns_base_load_hosts_impl(base, hosts_fname);
4134         EVDNS_UNLOCK(base);
4135         return res;
4136 }
4137 
4138 /* A single request for a getaddrinfo, either v4 or v6. */
4139 struct getaddrinfo_subrequest {
4140         struct evdns_request *r;
4141         ev_uint32_t type;
4142 };
4143 
4144 /* State data used to implement an in-progress getaddrinfo. */
4145 struct evdns_getaddrinfo_request {
4146         struct evdns_base *evdns_base;
4147         /* Copy of the modified 'hints' data that we'll use to build
4148          * answers. */
4149         struct evutil_addrinfo hints;
4150         /* The callback to invoke when we're done */
4151         evdns_getaddrinfo_cb user_cb;
4152         /* User-supplied data to give to the callback. */
4153         void *user_data;
4154         /* The port to use when building sockaddrs. */
4155         ev_uint16_t port;
4156         /* The sub_request for an A record (if any) */
4157         struct getaddrinfo_subrequest ipv4_request;
4158         /* The sub_request for an AAAA record (if any) */
4159         struct getaddrinfo_subrequest ipv6_request;
4160 
4161         /* The cname result that we were told (if any) */
4162         char *cname_result;
4163 
4164         /* If we have one request answered and one request still inflight,
4165          * then this field holds the answer from the first request... */
4166         struct evutil_addrinfo *pending_result;
4167         /* And this event is a timeout that will tell us to cancel the second
4168          * request if it's taking a long time. */
4169         struct event timeout;
4170 
4171         /* And this field holds the error code from the first request... */
4172         int pending_error;
4173         /* If this is set, the user canceled this request. */
4174         unsigned user_canceled : 1;
4175         /* If this is set, the user can no longer cancel this request; we're
4176          * just waiting for the free. */
4177         unsigned request_done : 1;
4178 };
4179 
4180 /* Convert an evdns errors to the equivalent getaddrinfo error. */
4181 static int
4182 evdns_err_to_getaddrinfo_err(int e1)
4183 {
4184         /* XXX Do this better! */
4185         if (e1 == DNS_ERR_NONE)
4186                 return 0;
4187         else if (e1 == DNS_ERR_NOTEXIST)
4188                 return EVUTIL_EAI_NONAME;
4189         else
4190                 return EVUTIL_EAI_FAIL;
4191 }
4192 
4193 /* Return the more informative of two getaddrinfo errors. */
4194 static int
4195 getaddrinfo_merge_err(int e1, int e2)
4196 {
4197         /* XXXX be cleverer here. */
4198         if (e1 == 0)
4199                 return e2;
4200         else
4201                 return e1;
4202 }
4203 
4204 static void
4205 free_getaddrinfo_request(struct evdns_getaddrinfo_request *data)
4206 {
4207         /* DO NOT CALL this if either of the requests is pending.  Only once
4208          * both callbacks have been invoked is it safe to free the request */
4209         if (data->pending_result)
4210                 evutil_freeaddrinfo(data->pending_result);
4211         if (data->cname_result)
4212                 mm_free(data->cname_result);
4213         event_del(&data->timeout);
4214         mm_free(data);
4215         return;
4216 }
4217 
4218 static void
4219 add_cname_to_reply(struct evdns_getaddrinfo_request *data,
4220     struct evutil_addrinfo *ai)
4221 {
4222         if (data->cname_result && ai) {
4223                 ai->ai_canonname = data->cname_result;
4224                 data->cname_result = NULL;
4225         }
4226 }
4227 
4228 /* Callback: invoked when one request in a mixed-format A/AAAA getaddrinfo
4229  * request has finished, but the other one took too long to answer. Pass
4230  * along the answer we got, and cancel the other request.
4231  */
4232 static void
4233 evdns_getaddrinfo_timeout_cb(evutil_socket_t fd, short what, void *ptr)
4234 {
4235         int v4_timedout = 0, v6_timedout = 0;
4236         struct evdns_getaddrinfo_request *data = ptr;
4237 
4238         /* Cancel any pending requests, and note which one */
4239         if (data->ipv4_request.r) {
4240                 /* XXXX This does nothing if the request's callback is already
4241                  * running (pending_cb is set). */
4242                 evdns_cancel_request(NULL, data->ipv4_request.r);
4243                 v4_timedout = 1;
4244                 EVDNS_LOCK(data->evdns_base);
4245                 ++data->evdns_base->getaddrinfo_ipv4_timeouts;
4246                 EVDNS_UNLOCK(data->evdns_base);
4247         }
4248         if (data->ipv6_request.r) {
4249                 /* XXXX This does nothing if the request's callback is already
4250                  * running (pending_cb is set). */
4251                 evdns_cancel_request(NULL, data->ipv6_request.r);
4252                 v6_timedout = 1;
4253                 EVDNS_LOCK(data->evdns_base);
4254                 ++data->evdns_base->getaddrinfo_ipv6_timeouts;
4255                 EVDNS_UNLOCK(data->evdns_base);
4256         }
4257 
4258         /* We only use this timeout callback when we have an answer for
4259          * one address. */
4260         EVUTIL_ASSERT(!v4_timedout || !v6_timedout);
4261 
4262         /* Report the outcome of the other request that didn't time out. */
4263         if (data->pending_result) {
4264                 add_cname_to_reply(data, data->pending_result);
4265                 data->user_cb(0, data->pending_result, data->user_data);
4266                 data->pending_result = NULL;
4267         } else {
4268                 int e = data->pending_error;
4269                 if (!e)
4270                         e = EVUTIL_EAI_AGAIN;
4271                 data->user_cb(e, NULL, data->user_data);
4272         }
4273 
4274         data->user_cb = NULL; /* prevent double-call if evdns callbacks are
4275                                * in-progress. XXXX It would be better if this
4276                                * weren't necessary. */
4277 
4278         if (!v4_timedout && !v6_timedout) {
4279                 /* should be impossible? XXXX */
4280                 free_getaddrinfo_request(data);
4281         }
4282 }
4283 
4284 static int
4285 evdns_getaddrinfo_set_timeout(struct evdns_base *evdns_base,
4286     struct evdns_getaddrinfo_request *data)
4287 {
4288         return event_add(&data->timeout, &evdns_base->global_getaddrinfo_allow_skew);
4289 }
4290 
4291 static inline int
4292 evdns_result_is_answer(int result)
4293 {
4294         return (result != DNS_ERR_NOTIMPL && result != DNS_ERR_REFUSED &&
4295             result != DNS_ERR_SERVERFAILED && result != DNS_ERR_CANCEL);
4296 }
4297 
4298 static void
4299 evdns_getaddrinfo_gotresolve(int result, char type, int count,
4300     int ttl, void *addresses, void *arg)
4301 {
4302         int i;
4303         struct getaddrinfo_subrequest *req = arg;
4304         struct getaddrinfo_subrequest *other_req;
4305         struct evdns_getaddrinfo_request *data;
4306 
4307         struct evutil_addrinfo *res;
4308 
4309         struct sockaddr_in sin;
4310         struct sockaddr_in6 sin6;
4311         struct sockaddr *sa;
4312         int socklen, addrlen;
4313         void *addrp;
4314         int err;
4315         int user_canceled;
4316 
4317         EVUTIL_ASSERT(req->type == DNS_IPv4_A || req->type == DNS_IPv6_AAAA);
4318         if (req->type == DNS_IPv4_A) {
4319                 data = EVUTIL_UPCAST(req, struct evdns_getaddrinfo_request, ipv4_request);
4320                 other_req = &data->ipv6_request;
4321         } else {
4322                 data = EVUTIL_UPCAST(req, struct evdns_getaddrinfo_request, ipv6_request);
4323                 other_req = &data->ipv4_request;
4324         }
4325 
4326         EVDNS_LOCK(data->evdns_base);
4327         if (evdns_result_is_answer(result)) {
4328                 if (req->type == DNS_IPv4_A)
4329                         ++data->evdns_base->getaddrinfo_ipv4_answered;
4330                 else
4331                         ++data->evdns_base->getaddrinfo_ipv6_answered;
4332         }
4333         user_canceled = data->user_canceled;
4334         if (other_req->r == NULL)
4335                 data->request_done = 1;
4336         EVDNS_UNLOCK(data->evdns_base);
4337 
4338         req->r = NULL;
4339 
4340         if (result == DNS_ERR_CANCEL && ! user_canceled) {
4341                 /* Internal cancel request from timeout or internal error.
4342                  * we already answered the user. */
4343                 if (other_req->r == NULL)
4344                         free_getaddrinfo_request(data);
4345                 return;
4346         }
4347 
4348         if (data->user_cb == NULL) {
4349                 /* We already answered.  XXXX This shouldn't be needed; see
4350                  * comments in evdns_getaddrinfo_timeout_cb */
4351                 free_getaddrinfo_request(data);
4352                 return;
4353         }
4354 
4355         if (result == DNS_ERR_NONE) {
4356                 if (count == 0)
4357                         err = EVUTIL_EAI_NODATA;
4358                 else
4359                         err = 0;
4360         } else {
4361                 err = evdns_err_to_getaddrinfo_err(result);
4362         }
4363 
4364         if (err) {
4365                 /* Looks like we got an error. */
4366                 if (other_req->r) {
4367                         /* The other request is still working; maybe it will
4368                          * succeed. */
4369                         /* XXXX handle failure from set_timeout */
4370                         evdns_getaddrinfo_set_timeout(data->evdns_base, data);
4371                         data->pending_error = err;
4372                         return;
4373                 }
4374 
4375                 if (user_canceled) {
4376                         data->user_cb(EVUTIL_EAI_CANCEL, NULL, data->user_data);
4377                 } else if (data->pending_result) {
4378                         /* If we have an answer waiting, and we weren't
4379                          * canceled, ignore this error. */
4380                         add_cname_to_reply(data, data->pending_result);
4381                         data->user_cb(0, data->pending_result, data->user_data);
4382                         data->pending_result = NULL;
4383                 } else {
4384                         if (data->pending_error)
4385                                 err = getaddrinfo_merge_err(err,
4386                                     data->pending_error);
4387                         data->user_cb(err, NULL, data->user_data);
4388                 }
4389                 free_getaddrinfo_request(data);
4390                 return;
4391         } else if (user_canceled) {
4392                 if (other_req->r) {
4393                         /* The other request is still working; let it hit this
4394                          * callback with EVUTIL_EAI_CANCEL callback and report
4395                          * the failure. */
4396                         return;
4397                 }
4398                 data->user_cb(EVUTIL_EAI_CANCEL, NULL, data->user_data);
4399                 free_getaddrinfo_request(data);
4400                 return;
4401         }
4402 
4403         /* Looks like we got some answers. We should turn them into addrinfos
4404          * and then either queue those or return them all. */
4405         EVUTIL_ASSERT(type == DNS_IPv4_A || type == DNS_IPv6_AAAA);
4406 
4407         if (type == DNS_IPv4_A) {
4408                 memset(&sin, 0, sizeof(sin));
4409                 sin.sin_family = AF_INET;
4410                 sin.sin_port = htons(data->port);
4411 
4412                 sa = (struct sockaddr *)&sin;
4413                 socklen = sizeof(sin);
4414                 addrlen = 4;
4415                 addrp = &sin.sin_addr.s_addr;
4416         } else {
4417                 memset(&sin6, 0, sizeof(sin6));
4418                 sin6.sin6_family = AF_INET6;
4419                 sin6.sin6_port = htons(data->port);
4420 
4421                 sa = (struct sockaddr *)&sin6;
4422                 socklen = sizeof(sin6);
4423                 addrlen = 16;
4424                 addrp = &sin6.sin6_addr.s6_addr;
4425         }
4426 
4427         res = NULL;
4428         for (i=0; i < count; ++i) {
4429                 struct evutil_addrinfo *ai;
4430                 memcpy(addrp, ((char*)addresses)+i*addrlen, addrlen);
4431                 ai = evutil_new_addrinfo(sa, socklen, &data->hints);
4432                 if (!ai) {
4433                         if (other_req->r) {
4434                                 evdns_cancel_request(NULL, other_req->r);
4435                         }
4436                         data->user_cb(EVUTIL_EAI_MEMORY, NULL, data->user_data);
4437                         if (res)
4438                                 evutil_freeaddrinfo(res);
4439 
4440                         if (other_req->r == NULL)
4441                                 free_getaddrinfo_request(data);
4442                         return;
4443                 }
4444                 res = evutil_addrinfo_append(res, ai);
4445         }
4446 
4447         if (other_req->r) {
4448                 /* The other request is still in progress; wait for it */
4449                 /* XXXX handle failure from set_timeout */
4450                 evdns_getaddrinfo_set_timeout(data->evdns_base, data);
4451                 data->pending_result = res;
4452                 return;
4453         } else {
4454                 /* The other request is done or never started; append its
4455                  * results (if any) and return them. */
4456                 if (data->pending_result) {
4457                         if (req->type == DNS_IPv4_A)
4458                                 res = evutil_addrinfo_append(res,
4459                                     data->pending_result);
4460                         else
4461                                 res = evutil_addrinfo_append(
4462                                     data->pending_result, res);
4463                         data->pending_result = NULL;
4464                 }
4465 
4466                 /* Call the user callback. */
4467                 add_cname_to_reply(data, res);
4468                 data->user_cb(0, res, data->user_data);
4469 
4470                 /* Free data. */
4471                 free_getaddrinfo_request(data);
4472         }
4473 }
4474 
4475 static struct hosts_entry *
4476 find_hosts_entry(struct evdns_base *base, const char *hostname,
4477     struct hosts_entry *find_after)
4478 {
4479         struct hosts_entry *e;
4480 
4481         if (find_after)
4482                 e = TAILQ_NEXT(find_after, next);
4483         else
4484                 e = TAILQ_FIRST(&base->hostsdb);
4485 
4486         for (; e; e = TAILQ_NEXT(e, next)) {
4487                 if (!evutil_ascii_strcasecmp(e->hostname, hostname))
4488                         return e;
4489         }
4490         return NULL;
4491 }
4492 
4493 static int
4494 evdns_getaddrinfo_fromhosts(struct evdns_base *base,
4495     const char *nodename, struct evutil_addrinfo *hints, ev_uint16_t port,
4496     struct evutil_addrinfo **res)
4497 {
4498         int n_found = 0;
4499         struct hosts_entry *e;
4500         struct evutil_addrinfo *ai=NULL;
4501         int f = hints->ai_family;
4502 
4503         EVDNS_LOCK(base);
4504         for (e = find_hosts_entry(base, nodename, NULL); e;
4505             e = find_hosts_entry(base, nodename, e)) {
4506                 struct evutil_addrinfo *ai_new;
4507                 ++n_found;
4508                 if ((e->addr.sa.sa_family == AF_INET && f == PF_INET6) ||
4509                     (e->addr.sa.sa_family == AF_INET6 && f == PF_INET))
4510                         continue;
4511                 ai_new = evutil_new_addrinfo(&e->addr.sa, e->addrlen, hints);
4512                 if (!ai_new) {
4513                         n_found = 0;
4514                         goto out;
4515                 }
4516                 sockaddr_setport(ai_new->ai_addr, port);
4517                 ai = evutil_addrinfo_append(ai, ai_new);
4518         }
4519         EVDNS_UNLOCK(base);
4520 out:
4521         if (n_found) {
4522                 /* Note that we return an empty answer if we found entries for
4523                  * this hostname but none were of the right address type. */
4524                 *res = ai;
4525                 return 0;
4526         } else {
4527                 if (ai)
4528                         evutil_freeaddrinfo(ai);
4529                 return -1;
4530         }
4531 }
4532 
4533 struct evdns_getaddrinfo_request *
4534 evdns_getaddrinfo(struct evdns_base *dns_base,
4535     const char *nodename, const char *servname,
4536     const struct evutil_addrinfo *hints_in,
4537     evdns_getaddrinfo_cb cb, void *arg)
4538 {
4539         struct evdns_getaddrinfo_request *data;
4540         struct evutil_addrinfo hints;
4541         struct evutil_addrinfo *res = NULL;
4542         int err;
4543         int port = 0;
4544         int want_cname = 0;
4545 
4546         if (!dns_base) {
4547                 dns_base = current_base;
4548                 if (!dns_base) {
4549                         log(EVDNS_LOG_WARN,
4550                             "Call to getaddrinfo_async with no "
4551                             "evdns_base configured.");
4552                         cb(EVUTIL_EAI_FAIL, NULL, arg); /* ??? better error? */
4553                         return NULL;
4554                 }
4555         }
4556 
4557         /* If we _must_ answer this immediately, do so. */
4558         if ((hints_in && (hints_in->ai_flags & EVUTIL_AI_NUMERICHOST))) {
4559                 res = NULL;
4560                 err = evutil_getaddrinfo(nodename, servname, hints_in, &res);
4561                 cb(err, res, arg);
4562                 return NULL;
4563         }
4564 
4565         if (hints_in) {
4566                 memcpy(&hints, hints_in, sizeof(hints));
4567         } else {
4568                 memset(&hints, 0, sizeof(hints));
4569                 hints.ai_family = PF_UNSPEC;
4570         }
4571 
4572         evutil_adjust_hints_for_addrconfig(&hints);
4573 
4574         /* Now try to see if we _can_ answer immediately. */
4575         /* (It would be nice to do this by calling getaddrinfo directly, with
4576          * AI_NUMERICHOST, on plaforms that have it, but we can't: there isn't
4577          * a reliable way to distinguish the "that wasn't a numeric host!" case
4578          * from any other EAI_NONAME cases.) */
4579         err = evutil_getaddrinfo_common(nodename, servname, &hints, &res, &port);
4580         if (err != EVUTIL_EAI_NEED_RESOLVE) {
4581                 cb(err, res, arg);
4582                 return NULL;
4583         }
4584 
4585         /* If there is an entry in the hosts file, we should give it now. */
4586         if (!evdns_getaddrinfo_fromhosts(dns_base, nodename, &hints, port, &res)) {
4587                 cb(0, res, arg);
4588                 return NULL;
4589         }
4590 
4591         /* Okay, things are serious now. We're going to need to actually
4592          * launch a request.
4593          */
4594         data = mm_calloc(1,sizeof(struct evdns_getaddrinfo_request));
4595         if (!data) {
4596                 cb(EVUTIL_EAI_MEMORY, NULL, arg);
4597                 return NULL;
4598         }
4599 
4600         memcpy(&data->hints, &hints, sizeof(data->hints));
4601         data->port = (ev_uint16_t)port;
4602         data->ipv4_request.type = DNS_IPv4_A;
4603         data->ipv6_request.type = DNS_IPv6_AAAA;
4604         data->user_cb = cb;
4605         data->user_data = arg;
4606         data->evdns_base = dns_base;
4607 
4608         want_cname = (hints.ai_flags & EVUTIL_AI_CANONNAME);
4609 
4610         /* If we are asked for a PF_UNSPEC address, we launch two requests in
4611          * parallel: one for an A address and one for an AAAA address.  We
4612          * can't send just one request, since many servers only answer one
4613          * question per DNS request.
4614          *
4615          * Once we have the answer to one request, we allow for a short
4616          * timeout before we report it, to see if the other one arrives.  If
4617          * they both show up in time, then we report both the answers.
4618          *
4619          * If too many addresses of one type time out or fail, we should stop
4620          * launching those requests. (XXX we don't do that yet.)
4621          */
4622 
4623         if (hints.ai_family != PF_INET6) {
4624                 log(EVDNS_LOG_DEBUG, "Sending request for %s on ipv4 as %p",
4625                     nodename, &data->ipv4_request);
4626 
4627                 data->ipv4_request.r = evdns_base_resolve_ipv4(dns_base,
4628                     nodename, 0, evdns_getaddrinfo_gotresolve,
4629                     &data->ipv4_request);
4630                 if (want_cname)
4631                         data->ipv4_request.r->current_req->put_cname_in_ptr =
4632                             &data->cname_result;
4633         }
4634         if (hints.ai_family != PF_INET) {
4635                 log(EVDNS_LOG_DEBUG, "Sending request for %s on ipv6 as %p",
4636                     nodename, &data->ipv6_request);
4637 
4638                 data->ipv6_request.r = evdns_base_resolve_ipv6(dns_base,
4639                     nodename, 0, evdns_getaddrinfo_gotresolve,
4640                     &data->ipv6_request);
4641                 if (want_cname)
4642                         data->ipv6_request.r->current_req->put_cname_in_ptr =
4643                             &data->cname_result;
4644         }
4645 
4646         evtimer_assign(&data->timeout, dns_base->event_base,
4647             evdns_getaddrinfo_timeout_cb, data);
4648 
4649         if (data->ipv4_request.r || data->ipv6_request.r) {
4650                 return data;
4651         } else {
4652                 mm_free(data);
4653                 cb(EVUTIL_EAI_FAIL, NULL, arg);
4654                 return NULL;
4655         }
4656 }
4657 
4658 void
4659 evdns_getaddrinfo_cancel(struct evdns_getaddrinfo_request *data)
4660 {
4661         EVDNS_LOCK(data->evdns_base);
4662         if (data->request_done) {
4663                 EVDNS_UNLOCK(data->evdns_base);
4664                 return;
4665         }
4666         event_del(&data->timeout);
4667         data->user_canceled = 1;
4668         if (data->ipv4_request.r)
4669                 evdns_cancel_request(data->evdns_base, data->ipv4_request.r);
4670         if (data->ipv6_request.r)
4671                 evdns_cancel_request(data->evdns_base, data->ipv6_request.r);
4672         EVDNS_UNLOCK(data->evdns_base);
4673 }

/* [<][>][^][v][top][bottom][index][help] */