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