Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(95)

Side by Side Diff: third_party/libevent/evdns.c

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

Powered by Google App Engine
This is Rietveld 408576698