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