1 /* The original version of this module was written by Adam Langley; for
2 * a history of modifications, check out the subversion logs.
4 * When editing this module, try to keep it re-mergeable by Adam. Don't
5 * reformat the whitespace, add Tor dependencies, or so on.
8 * - Replace all externally visible magic numbers with #defined constants.
9 * - Write documentation for APIs of all external functions.
13 * Adam Langley <agl@imperialviolet.org>
16 * This software is Public Domain. To view a copy of the public domain dedication,
17 * visit http://creativecommons.org/licenses/publicdomain/ or send a letter to
18 * Creative Commons, 559 Nathan Abbott Way, Stanford, California 94305, USA.
20 * I ask and expect, but do not require, that all derivative works contain an
21 * attribution similar to:
22 * Parts developed by Adam Langley <agl@imperialviolet.org>
24 * You may wish to replace the word "Parts" with something else depending on
25 * the amount of original code.
27 * (Derivative works does not include programs which link against, run or include
28 * the source verbatim in their source distributions)
33 #include "eventdns_tor.h"
34 #include <sys/types.h>
37 #ifndef DNS_USE_CPU_CLOCK_FOR_ID
38 #ifndef DNS_USE_GETTIMEOFDAY_FOR_ID
39 #ifndef DNS_USE_OPENSSL_FOR_ID
40 #error Must configure at least one id generation method.
41 #error Please see the documentation.
46 /* #define _POSIX_C_SOURCE 200507 */
49 #ifdef DNS_USE_CPU_CLOCK_FOR_ID
50 #ifdef DNS_USE_OPENSSL_FOR_ID
51 #error Multiple id options selected
53 #ifdef DNS_USE_GETTIMEOFDAY_FOR_ID
54 #error Multiple id options selected
59 #ifdef DNS_USE_OPENSSL_FOR_ID
60 #ifdef DNS_USE_GETTIMEOFDAY_FOR_ID
61 #error Multiple id options selected
63 #include <openssl/rand.h>
70 #ifdef HAVE_SYS_TIME_H
98 #include <sys/socket.h>
99 #include <netinet/in.h>
100 #include <arpa/inet.h>
103 #ifdef HAVE_NETINET_IN6_H
104 #include <netinet/in6.h>
108 typedef int socklen_t
;
111 #define EVDNS_LOG_DEBUG 0
112 #define EVDNS_LOG_WARN 1
114 #ifndef HOST_NAME_MAX
115 #define HOST_NAME_MAX 255
122 /* for debugging possible memory leaks. */
123 #define mm_malloc(x) tor_malloc(x)
124 #define mm_realloc(x,y) tor_realloc((x),(y))
125 #define mm_free(x) tor_free(x)
126 #define mm_strdup(x) tor_strdup(x)
127 #define _mm_free(x) _tor_free(x)
130 #define MIN(a,b) ((a)<(b)?(a):(b))
134 /* libevent doesn't work without this */
135 typedef uint8_t u_char
;
136 typedef unsigned int uint
;
146 #define MAX_ADDRS 4 /* maximum number of addresses from a single packet */
147 /* which we bother recording */
149 #define TYPE_A EVDNS_TYPE_A
151 #define TYPE_PTR EVDNS_TYPE_PTR
152 #define TYPE_AAAA EVDNS_TYPE_AAAA
154 #define CLASS_INET EVDNS_CLASS_INET
156 #define CLEAR(x) do { memset((x), 0xF0, sizeof(*(x))); } while(0)
158 struct evdns_request
{
159 u8
*request
; /* the dns packet data */
160 unsigned int request_len
;
162 int tx_count
; /* the number of times that this packet has been sent */
163 unsigned int request_type
; /* TYPE_PTR or TYPE_A */
164 void *user_pointer
; /* the pointer given to us for this request */
165 evdns_callback_type user_callback
;
166 struct nameserver
*ns
; /* the server which we last sent it */
168 /* elements used by the searching code */
170 struct search_state
*search_state
;
171 char *search_origname
; /* needs to be mm_free()ed */
174 /* these objects are kept in a circular list */
175 struct evdns_request
*next
, *prev
;
177 struct event timeout_event
;
179 u16 trans_id
; /* the transaction id */
180 char request_appended
; /* true if the request pointer is data which follows this struct */
181 char transmit_me
; /* needs to be transmitted */
184 #ifndef HAVE_STRUCT_IN6_ADDR
192 unsigned int have_answer
;
196 u32 addresses
[MAX_ADDRS
];
200 struct in6_addr addresses
[MAX_ADDRS
];
203 char name
[HOST_NAME_MAX
];
209 int socket
; /* a connected UDP socket */
210 struct sockaddr_storage address
;
211 int failed_times
; /* number of times which we have given this server a chance */
212 int timedout
; /* number of times in a row a request has timed out */
214 /* these objects are kept in a circular list */
215 struct nameserver
*next
, *prev
;
216 struct event timeout_event
; /* used to keep the timeout for */
217 /* when we next probe this server. */
218 /* Valid if state == 0 */
219 char state
; /* zero if we think that this server is down */
220 char choked
; /* true if we have an EAGAIN from this server's socket */
221 char write_waiting
; /* true if we are waiting for EV_WRITE events */
224 static struct evdns_request
*req_head
= NULL
, *req_waiting_head
= NULL
;
225 static struct nameserver
*server_head
= NULL
;
227 /* Represents a local port where we're listening for DNS requests. Right now, */
228 /* only UDP is supported. */
229 struct evdns_server_port
{
230 int socket
; /* socket we use to read queries and write replies. */
231 int refcnt
; /* reference count. */
232 char choked
; /* Are we currently blocked from writing? */
233 char closing
; /* Are we trying to close this port, pending writes? */
234 evdns_request_callback_fn_type user_callback
; /* Fn to handle requests */
235 void *user_data
; /* Opaque pointer passed to user_callback */
236 struct event event
; /* Read/write event */
237 /* circular list of replies that we want to write. */
238 struct server_request
*pending_replies
;
241 /* Represents part of a reply being built. (That is, a single RR.) */
242 struct server_reply_item
{
243 struct server_reply_item
*next
; /* next item in sequence. */
244 char *name
; /* name part of the RR */
245 u16 type
: 16; /* The RR type */
246 u16
class : 16; /* The RR class (usually CLASS_INET) */
247 u32 ttl
; /* The RR TTL */
248 char is_name
; /* True iff data is a label */
249 u16 datalen
; /* Length of data; -1 if data is a label */
250 void *data
; /* The contents of the RR */
253 /* Represents a request that we've received as a DNS server, and holds */
254 /* the components of the reply as we're constructing it. */
255 struct server_request
{
256 /* Pointers to the next and previous entries on the list of replies */
257 /* that we're waiting to write. Only set if we have tried to respond */
258 /* and gotten EAGAIN. */
259 struct server_request
*next_pending
;
260 struct server_request
*prev_pending
;
262 u16 trans_id
; /* Transaction id. */
263 struct evdns_server_port
*port
; /* Which port received this request on? */
264 struct sockaddr_storage addr
; /* Where to send the response */
265 socklen_t addrlen
; /* length of addr */
267 int n_answer
; /* how many answer RRs have been set? */
268 int n_authority
; /* how many authority RRs have been set? */
269 int n_additional
; /* how many additional RRs have been set? */
271 struct server_reply_item
*answer
; /* linked list of answer RRs */
272 struct server_reply_item
*authority
; /* linked list of authority RRs */
273 struct server_reply_item
*additional
; /* linked list of additional RRs */
275 /* Constructed response. Only set once we're ready to send a reply. */
276 /* Once this is set, the RR fields are cleared, and no more should be set. */
280 /* Caller-visible fields: flags, questions. */
281 struct evdns_server_request base
;
285 #define OFFSET_OF(st, member) ((off_t) (((char*)&((st*)0)->member)-(char*)0))
287 /* Given a pointer to an evdns_server_request, get the corresponding */
288 /* server_request. */
289 #define TO_SERVER_REQUEST(base_ptr) \
290 ((struct server_request*) \
291 (((char*)(base_ptr) - OFFSET_OF(struct server_request, base))))
293 /* The number of good nameservers that we have */
294 static int global_good_nameservers
= 0;
296 /* inflight requests are contained in the req_head list */
297 /* and are actually going out across the network */
298 static int global_requests_inflight
= 0;
299 /* requests which aren't inflight are in the waiting list */
300 /* and are counted here */
301 static int global_requests_waiting
= 0;
303 static int global_max_requests_inflight
= 64;
305 static struct timeval global_timeout
= {5, 0}; /* 5 seconds */
306 static int global_max_reissues
= 1; /* a reissue occurs when we get some errors from the server */
307 static int global_max_retransmits
= 3; /* number of times we'll retransmit a request which timed out */
308 /* number of timeouts in a row before we consider this server to be down */
309 static int global_max_nameserver_timeout
= 3;
311 /* true iff we should use the 0x20 hack. */
312 static int global_randomize_case
= 1;
314 /* These are the timeout values for nameservers. If we find a nameserver is down */
315 /* we try to probe it at intervals as given below. Values are in seconds. */
316 static const struct timeval global_nameserver_timeouts
[] = {{10, 0}, {60, 0}, {300, 0}, {900, 0}, {3600, 0}};
317 static const int global_nameserver_timeouts_length
= (int)(sizeof(global_nameserver_timeouts
)/sizeof(struct timeval
));
319 static struct nameserver
*nameserver_pick(void);
320 static void evdns_request_insert(struct evdns_request
*req
, struct evdns_request
**head
);
321 static void nameserver_ready_callback(int fd
, short events
, void *arg
);
322 static int evdns_transmit(void);
323 static int evdns_request_transmit(struct evdns_request
*req
);
324 static void nameserver_send_probe(struct nameserver
*const ns
);
325 static void search_request_finished(struct evdns_request
*const);
326 static int search_try_next(struct evdns_request
*const req
);
327 static int search_request_new(int type
, const char *const name
, int flags
, evdns_callback_type user_callback
, void *user_arg
);
328 static void evdns_requests_pump_waiting_queue(void);
329 static u16
transaction_id_pick(void);
330 static struct evdns_request
*request_new(int type
, const char *name
, int flags
, evdns_callback_type callback
, void *ptr
);
331 static void request_submit(struct evdns_request
*req
);
333 static int server_request_free(struct server_request
*req
);
334 static void server_request_free_answers(struct server_request
*req
);
335 static void server_port_free(struct evdns_server_port
*port
);
336 static void server_port_ready_callback(int fd
, short events
, void *arg
);
338 static int strtoint(const char *const str
);
344 int optval
, optvallen
=sizeof(optval
);
345 int err
= WSAGetLastError();
346 if (err
== WSAEWOULDBLOCK
&& sock
>= 0) {
347 if (getsockopt(sock
, SOL_SOCKET
, SO_ERROR
, (void*)&optval
,
357 error_is_eagain(int err
)
359 return err
== EAGAIN
|| err
== WSAEWOULDBLOCK
;
361 #define inet_aton(c, addr) tor_inet_aton((c), (addr))
362 #define CLOSE_SOCKET(x) closesocket(x)
364 #define last_error(sock) (errno)
365 #define error_is_eagain(err) ((err) == EAGAIN)
366 #define CLOSE_SOCKET(x) close(x)
369 #define ISSPACE(c) TOR_ISSPACE(c)
370 #define ISDIGIT(c) TOR_ISDIGIT(c)
371 #define ISALPHA(c) TOR_ISALPHA(c)
372 #define TOLOWER(c) TOR_TOLOWER(c)
373 #define TOUPPER(c) TOR_TOUPPER(c)
377 debug_ntoa(u32 address
)
380 u32 a
= ntohl(address
);
381 snprintf(buf
, sizeof(buf
), "%d.%d.%d.%d",
382 (int)(u8
)((a
>>24)&0xff),
383 (int)(u8
)((a
>>16)&0xff),
384 (int)(u8
)((a
>>8 )&0xff),
385 (int)(u8
)((a
)&0xff));
389 debug_ntop(const struct sockaddr
*sa
)
391 if (sa
->sa_family
== AF_INET
) {
392 struct sockaddr_in
*sin
= (struct sockaddr_in
*) sa
;
393 return debug_ntoa(sin
->sin_addr
.s_addr
);
395 if (sa
->sa_family
== AF_INET6
) {
396 /* Tor-specific. In libevent, add more check code. */
397 static char buf
[128];
398 struct sockaddr_in6
*sin
= (struct sockaddr_in6
*) sa
;
399 tor_inet_ntop(AF_INET6
, &sin
->sin6_addr
, buf
, sizeof(buf
));
406 static evdns_debug_log_fn_type evdns_log_fn
= NULL
;
409 evdns_set_log_fn(evdns_debug_log_fn_type fn
)
415 #define EVDNS_LOG_CHECK __attribute__ ((format(printf, 2, 3)))
417 #define EVDNS_LOG_CHECK
420 static void _evdns_log(int warn
, const char *fmt
, ...) EVDNS_LOG_CHECK
;
422 _evdns_log(int warn
, const char *fmt
, ...)
425 static char buf
[512];
430 _vsnprintf(buf
, sizeof(buf
), fmt
, args
);
432 vsnprintf(buf
, sizeof(buf
), fmt
, args
);
434 buf
[sizeof(buf
)-1] = '\0';
435 evdns_log_fn(warn
, buf
);
439 #define log _evdns_log
442 sockaddr_eq(const struct sockaddr
*sa1
, const struct sockaddr
*sa2
,
445 if (sa1
->sa_family
!= sa2
->sa_family
)
447 if (sa1
->sa_family
== AF_INET
) {
448 const struct sockaddr_in
*sin1
, *sin2
;
449 sin1
= (const struct sockaddr_in
*)sa1
;
450 sin2
= (const struct sockaddr_in
*)sa2
;
451 if (sin1
->sin_addr
.s_addr
!= sin2
->sin_addr
.s_addr
)
453 else if (include_port
&& sin1
->sin_port
!= sin2
->sin_port
)
459 if (sa1
->sa_family
== AF_INET6
) {
460 const struct sockaddr_in6
*sin1
, *sin2
;
461 sin1
= (const struct sockaddr_in6
*)sa1
;
462 sin2
= (const struct sockaddr_in6
*)sa2
;
463 if (memcmp(sin1
->sin6_addr
.s6_addr
, sin2
->sin6_addr
.s6_addr
, 16))
465 else if (include_port
&& sin1
->sin6_port
!= sin2
->sin6_port
)
474 #define add_timeout_event(s, to) \
475 (event_add(&(s)->timeout_event, (to)))
476 #define del_timeout_event(s) \
477 (event_del(&(s)->timeout_event))
479 /* This walks the list of inflight requests to find the */
480 /* one with a matching transaction id. Returns NULL on */
482 static struct evdns_request
*
483 request_find_from_trans_id(u16 trans_id
) {
484 struct evdns_request
*req
= req_head
, *const started_at
= req_head
;
488 if (req
->trans_id
== trans_id
) return req
;
490 } while (req
!= started_at
);
496 /* a libevent callback function which is called when a nameserver */
497 /* has gone down and we want to test if it has came back to life yet */
499 nameserver_prod_callback(int fd
, short events
, void *arg
) {
500 struct nameserver
*const ns
= (struct nameserver
*) arg
;
504 nameserver_send_probe(ns
);
507 /* a libevent callback which is called when a nameserver probe (to see if */
508 /* it has come back to life) times out. We increment the count of failed_times */
509 /* and wait longer to send the next probe packet. */
511 nameserver_probe_failed(struct nameserver
*const ns
) {
512 const struct timeval
* timeout
;
513 del_timeout_event(ns
);
515 if (ns
->state
== 1) {
516 /* This can happen if the nameserver acts in a way which makes us mark */
517 /* it as bad and then starts sending good replies. */
522 &global_nameserver_timeouts
[MIN(ns
->failed_times
,
523 global_nameserver_timeouts_length
- 1)];
526 if (add_timeout_event(ns
, (struct timeval
*) timeout
) < 0) {
528 "Error from libevent when adding timer event for %s",
529 debug_ntop((struct sockaddr
*)&ns
->address
));
534 /* called when a nameserver has been deemed to have failed. For example, too */
535 /* many packets have timed out etc */
537 nameserver_failed(struct nameserver
*const ns
, const char *msg
) {
538 struct evdns_request
*req
, *started_at
;
539 /* if this nameserver has already been marked as failed */
540 /* then don't do anything */
541 if (!ns
->state
) return;
543 log(EVDNS_LOG_WARN
, "Nameserver %s has failed: %s",
544 debug_ntop((struct sockaddr
*)&ns
->address
), msg
);
545 global_good_nameservers
--;
546 assert(global_good_nameservers
>= 0);
547 if (global_good_nameservers
== 0) {
548 log(EVDNS_LOG_WARN
, "All nameservers have failed");
552 ns
->failed_times
= 1;
554 if (add_timeout_event(ns
, (struct timeval
*) &global_nameserver_timeouts
[0]) < 0) {
556 "Error from libevent when adding timer event for %s",
557 debug_ntop((struct sockaddr
*)&ns
->address
));
561 /* walk the list of inflight requests to see if any can be reassigned to */
562 /* a different server. Requests in the waiting queue don't have a */
563 /* nameserver assigned yet */
565 /* if we don't have *any* good nameservers then there's no point */
566 /* trying to reassign requests to one */
567 if (!global_good_nameservers
) return;
570 started_at
= req_head
;
573 if (req
->tx_count
== 0 && req
->ns
== ns
) {
574 /* still waiting to go out, can be moved */
575 /* to another server */
576 req
->ns
= nameserver_pick();
579 } while (req
!= started_at
);
584 nameserver_up(struct nameserver
*const ns
) {
585 if (ns
->state
) return;
586 log(EVDNS_LOG_WARN
, "Nameserver %s is back up",
587 debug_ntop((struct sockaddr
*)&ns
->address
));
588 del_timeout_event(ns
);
590 ns
->failed_times
= 0;
592 global_good_nameservers
++;
596 request_trans_id_set(struct evdns_request
*const req
, const u16 trans_id
) {
597 req
->trans_id
= trans_id
;
598 *((u16
*) req
->request
) = htons(trans_id
);
601 /* Called to remove a request from a list and dealloc it. */
602 /* head is a pointer to the head of the list it should be */
603 /* removed from or NULL if the request isn't in a list. */
605 request_finished(struct evdns_request
*const req
, struct evdns_request
**head
) {
607 if (req
->next
== req
) {
608 /* only item in the list */
611 req
->next
->prev
= req
->prev
;
612 req
->prev
->next
= req
->next
;
613 if (*head
== req
) *head
= req
->next
;
617 log(EVDNS_LOG_DEBUG
, "Removing timeout for request %lx",
618 (unsigned long) req
);
619 del_timeout_event(req
);
621 search_request_finished(req
);
622 global_requests_inflight
--;
624 if (!req
->request_appended
) {
625 /* need to free the request data on it's own */
626 mm_free(req
->request
);
628 /* the request data is appended onto the header */
629 /* so everything gets mm_free()ed when we: */
635 evdns_requests_pump_waiting_queue();
638 /* This is called when a server returns a funny error code. */
639 /* We try the request again with another server. */
643 /* 1 failed/reissue is pointless */
645 request_reissue(struct evdns_request
*req
) {
646 const struct nameserver
*const last_ns
= req
->ns
;
647 /* the last nameserver should have been marked as failing */
648 /* by the caller of this function, therefore pick will try */
649 /* not to return it */
650 req
->ns
= nameserver_pick();
651 if (req
->ns
== last_ns
) {
652 /* ... but pick did return it */
653 /* not a lot of point in trying again with the */
658 req
->reissue_count
++;
660 req
->transmit_me
= 1;
665 /* this function looks for space on the inflight queue and promotes */
666 /* requests from the waiting queue if it can. */
668 evdns_requests_pump_waiting_queue(void) {
669 while (global_requests_inflight
< global_max_requests_inflight
&&
670 global_requests_waiting
) {
671 struct evdns_request
*req
;
672 /* move a request from the waiting queue to the inflight queue */
673 assert(req_waiting_head
);
674 if (req_waiting_head
->next
== req_waiting_head
) {
675 /* only one item in the queue */
676 req
= req_waiting_head
;
677 req_waiting_head
= NULL
;
679 req
= req_waiting_head
;
680 req
->next
->prev
= req
->prev
;
681 req
->prev
->next
= req
->next
;
682 req_waiting_head
= req
->next
;
685 global_requests_waiting
--;
686 global_requests_inflight
++;
688 req
->ns
= nameserver_pick();
689 request_trans_id_set(req
, transaction_id_pick());
691 evdns_request_insert(req
, &req_head
);
692 evdns_request_transmit(req
);
698 reply_callback(struct evdns_request
*const req
, u32 ttl
, u32 err
, struct reply
*reply
) {
699 switch (req
->request_type
) {
702 req
->user_callback(DNS_ERR_NONE
, DNS_IPv4_A
,
703 reply
->data
.a
.addrcount
, ttl
,
704 reply
->data
.a
.addresses
,
707 req
->user_callback(err
, 0, 0, 0, NULL
, req
->user_pointer
);
711 char *name
= reply
->data
.ptr
.name
;
712 req
->user_callback(DNS_ERR_NONE
, DNS_PTR
, 1, ttl
,
713 &name
, req
->user_pointer
);
715 req
->user_callback(err
, 0, 0, 0, NULL
,
721 req
->user_callback(DNS_ERR_NONE
, DNS_IPv6_AAAA
,
722 reply
->data
.aaaa
.addrcount
, ttl
,
723 reply
->data
.aaaa
.addresses
,
726 req
->user_callback(err
, 0, 0, 0, NULL
, req
->user_pointer
);
732 /* this processes a parsed reply packet */
734 reply_handle(struct evdns_request
*const req
, u16 flags
, u32 ttl
, struct reply
*reply
) {
736 static const int error_codes
[] = {DNS_ERR_FORMAT
, DNS_ERR_SERVERFAILED
, DNS_ERR_NOTEXIST
, DNS_ERR_NOTIMPL
, DNS_ERR_REFUSED
};
738 if (flags
& 0x020f || !reply
|| !reply
->have_answer
) {
739 /* there was an error */
740 if (flags
& 0x0200) {
741 error
= DNS_ERR_TRUNCATED
;
743 u16 error_code
= (flags
& 0x000f) - 1;
744 if (error_code
> 4) {
745 error
= DNS_ERR_UNKNOWN
;
747 error
= error_codes
[error_code
];
752 case DNS_ERR_NOTIMPL
:
753 case DNS_ERR_REFUSED
:
754 /* we regard these errors as marking a bad nameserver */
755 if (req
->reissue_count
< global_max_reissues
) {
757 snprintf(msg
, sizeof(msg
), "Bad response %d (%s)",
758 error
, evdns_err_to_string(error
));
759 nameserver_failed(req
->ns
, msg
);
760 if (!request_reissue(req
)) return;
763 case DNS_ERR_SERVERFAILED
:
764 /* rcode 2 (servfailed) sometimes means "we are broken" and
765 * sometimes (with some binds) means "that request was very
766 * confusing." Treat this as a timeout, not a failure.
768 /*XXXX refactor the parts of */
769 log(EVDNS_LOG_DEBUG
, "Got a SERVERFAILED from nameserver %s; "
770 "will allow the request to time out.",
771 debug_ntop((struct sockaddr
*)&req
->ns
->address
));
774 /* we got a good reply from the nameserver */
775 nameserver_up(req
->ns
);
778 if (req
->search_state
&& req
->request_type
!= TYPE_PTR
) {
779 /* if we have a list of domains to search in, try the next one */
780 if (!search_try_next(req
)) {
781 /* a new request was issued so this request is finished and */
782 /* the user callback will be made when that request (or a */
783 /* child of it) finishes. */
784 request_finished(req
, &req_head
);
789 /* all else failed. Pass the failure up */
790 reply_callback(req
, 0, error
, NULL
);
791 request_finished(req
, &req_head
);
793 /* all ok, tell the user */
794 reply_callback(req
, ttl
, 0, reply
);
795 nameserver_up(req
->ns
);
796 request_finished(req
, &req_head
);
801 name_parse(u8
*packet
, int length
, int *idx
, char *name_out
, size_t name_out_len
) {
805 #define GET32(x) do { if (j + 4 > length) goto err; memcpy(&_t32, packet + j, 4); j += 4; x = ntohl(_t32); } while(0)
806 #define GET16(x) do { if (j + 2 > length) goto err; memcpy(&_t, packet + j, 2); j += 2; x = ntohs(_t); } while(0)
807 #define GET8(x) do { if (j >= length) goto err; x = packet[j++]; } while(0)
810 const char *const end
= name_out
+ name_out_len
;
812 /* Normally, names are a series of length prefixed strings terminated */
813 /* with a length of 0 (the lengths are u8's < 63). */
814 /* However, the length can start with a pair of 1 bits and that */
815 /* means that the next 14 bits are a pointer within the current */
820 if (j
>= length
) return -1;
822 if (!label_len
) break;
823 if (label_len
& 0xc0) {
826 if (name_end
< 0) name_end
= j
;
827 j
= (((int)label_len
& 0x3f) << 8) + ptr_low
;
828 /* Make sure that the target offset is in-bounds. */
829 if (j
< 0 || j
>= length
) return -1;
830 /* If we've jumped more times than there are characters in the
831 * message, we must have a loop. */
832 if (++ptr_count
> length
) return -1;
835 if (label_len
> 63) return -1;
836 if (cp
!= name_out
) {
837 if (cp
+ 1 >= end
) return -1;
840 if (cp
+ label_len
>= end
) return -1;
841 memcpy(cp
, packet
+ j
, label_len
);
845 if (cp
>= end
) return -1;
856 /* parses a raw reply from a nameserver. */
858 reply_parse(u8
*packet
, int length
) {
859 int j
= 0; /* index into packet */
861 u16 _t
; /* used by the macros */
862 u32 _t32
; /* used by the macros */
863 char tmp_name
[256], cmp_name
[256]; /* used by the macros */
865 u16 trans_id
, questions
, answers
, authority
, additional
, datalength
;
867 u32 ttl
, ttl_r
= 0xffffffff;
869 struct evdns_request
*req
= NULL
;
871 int name_matches
= 0;
879 (void) authority
; /* suppress "unused variable" warnings. */
880 (void) additional
; /* suppress "unused variable" warnings. */
882 req
= request_find_from_trans_id(trans_id
);
883 /* if no request, can't do anything. */
886 memset(&reply
, 0, sizeof(reply
));
888 /* If it's not an answer, it doesn't go with any of our requests. */
889 if (!(flags
& 0x8000)) return -1; /* must be an answer */
890 if (flags
& 0x020f) {
891 /* there was an error */
894 /* if (!answers) return; */ /* must have an answer of some form */
896 /* This macro skips a name in the DNS reply. */
898 do { tmp_name[0] = '\0'; \
899 if (name_parse(packet, length, &j, tmp_name, sizeof(tmp_name))<0)\
903 do { tmp_name[0] = '\0'; \
904 cmp_name[0] = '\0'; \
906 if (name_parse(packet, length, &j, tmp_name, sizeof(tmp_name))<0)\
908 if (name_parse(req->request, req->request_len, &k, cmp_name, sizeof(cmp_name))<0) \
910 if (global_randomize_case) { \
911 if (strcmp(tmp_name, cmp_name) == 0) \
912 name_matches = 1; /* we ignore mismatching names */ \
914 if (strcasecmp(tmp_name, cmp_name) == 0) \
919 reply
.type
= req
->request_type
;
921 /* skip over each question in the reply */
922 for (i
= 0; i
< questions
; ++i
) {
923 /* the question looks like
924 * <label:name><u16:type><u16:class>
928 if (j
>= length
) goto err
;
934 /* now we have the answer section which looks like
935 * <label:name><u16:type><u16:class><u32:ttl><u16:len><data...>
938 for (i
= 0; i
< answers
; ++i
) {
947 if (type
== TYPE_A
&& class == CLASS_INET
) {
948 int addrcount
, addrtocopy
;
949 if (req
->request_type
!= TYPE_A
) {
950 j
+= datalength
; continue;
952 if ((datalength
& 3) != 0) /* not an even number of As. */
954 addrcount
= datalength
>> 2;
955 addrtocopy
= MIN(MAX_ADDRS
- reply
.data
.a
.addrcount
, (unsigned)addrcount
);
957 ttl_r
= MIN(ttl_r
, ttl
);
958 /* we only bother with the first four addresses. */
959 if (j
+ 4*addrtocopy
> length
) goto err
;
960 memcpy(&reply
.data
.a
.addresses
[reply
.data
.a
.addrcount
],
961 packet
+ j
, 4*addrtocopy
);
962 reply
.data
.a
.addrcount
+= addrtocopy
;
963 reply
.have_answer
= 1;
964 if (reply
.data
.a
.addrcount
== MAX_ADDRS
) break;
966 } else if (type
== TYPE_PTR
&& class == CLASS_INET
) {
967 if (req
->request_type
!= TYPE_PTR
) {
968 j
+= datalength
; continue;
971 strlcpy(reply
.data
.ptr
.name
, tmp_name
,
972 sizeof(reply
.data
.ptr
.name
));
973 ttl_r
= MIN(ttl_r
, ttl
);
974 reply
.have_answer
= 1;
976 } else if (type
== TYPE_AAAA
&& class == CLASS_INET
) {
977 int addrcount
, addrtocopy
;
978 if (req
->request_type
!= TYPE_AAAA
) {
979 j
+= datalength
; continue;
981 if ((datalength
& 15) != 0) /* not an even number of AAAAs. */
983 addrcount
= datalength
>> 4; /* each address is 16 bytes long */
984 addrtocopy
= MIN(MAX_ADDRS
- reply
.data
.aaaa
.addrcount
, (unsigned)addrcount
);
985 ttl_r
= MIN(ttl_r
, ttl
);
987 /* we only bother with the first four addresses. */
988 if (j
+ 16*addrtocopy
> length
) goto err
;
989 memcpy(&reply
.data
.aaaa
.addresses
[reply
.data
.aaaa
.addrcount
],
990 packet
+ j
, 16*addrtocopy
);
991 reply
.data
.aaaa
.addrcount
+= addrtocopy
;
992 reply
.have_answer
= 1;
993 if (reply
.data
.aaaa
.addrcount
== MAX_ADDRS
) break;
996 /* skip over any other type of resource */
1001 reply_handle(req
, flags
, ttl_r
, &reply
);
1005 reply_handle(req
, flags
, 0, NULL
);
1009 /* Parse a raw request (packet,length) sent to a nameserver port (port) from */
1010 /* a DNS client (addr,addrlen), and if it's well-formed, call the corresponding */
1013 request_parse(u8
*packet
, ssize_t length
, struct evdns_server_port
*port
, struct sockaddr
*addr
, socklen_t addrlen
)
1015 int j
= 0; /* index into packet */
1016 u16 _t
; /* used by the macros */
1017 char tmp_name
[256]; /* used by the macros */
1020 u16 trans_id
, flags
, questions
, answers
, authority
, additional
;
1021 struct server_request
*server_req
= NULL
;
1023 /* Get the header fields */
1031 if (flags
& 0x8000) return -1; /* Must not be an answer. */
1032 flags
&= 0x0110; /* Only RD and CD get preserved. */
1034 if (length
> INT_MAX
)
1037 server_req
= mm_malloc(sizeof(struct server_request
));
1038 if (server_req
== NULL
) return -1;
1039 memset(server_req
, 0, sizeof(struct server_request
));
1041 server_req
->trans_id
= trans_id
;
1042 memcpy(&server_req
->addr
, addr
, addrlen
);
1043 server_req
->addrlen
= addrlen
;
1045 server_req
->base
.flags
= flags
;
1046 server_req
->base
.nquestions
= 0;
1047 server_req
->base
.questions
= mm_malloc(sizeof(struct evdns_server_question
*) * questions
);
1048 if (server_req
->base
.questions
== NULL
)
1051 for (i
= 0; i
< questions
; ++i
) {
1053 struct evdns_server_question
*q
;
1055 if (name_parse(packet
, (int)length
, &j
, tmp_name
, sizeof(tmp_name
))<0)
1059 namelen
= strlen(tmp_name
);
1060 q
= mm_malloc(sizeof(struct evdns_server_question
) + namelen
);
1064 q
->dns_question_class
= class;
1065 memcpy(q
->name
, tmp_name
, namelen
+1);
1066 server_req
->base
.questions
[server_req
->base
.nquestions
++] = q
;
1069 /* Ignore answers, authority, and additional. */
1071 server_req
->port
= port
;
1074 /* Only standard queries are supported. */
1075 if (flags
& 0x7800) {
1076 evdns_server_request_respond(&(server_req
->base
), DNS_ERR_NOTIMPL
);
1080 port
->user_callback(&(server_req
->base
), port
->user_data
);
1085 if (server_req
->base
.questions
) {
1086 for (i
= 0; i
< server_req
->base
.nquestions
; ++i
)
1087 mm_free(server_req
->base
.questions
[i
]);
1088 mm_free(server_req
->base
.questions
);
1091 mm_free(server_req
);
1102 default_transaction_id_fn(void)
1105 #ifdef DNS_USE_CPU_CLOCK_FOR_ID
1107 #ifdef CLOCK_MONOTONIC
1108 if (clock_gettime(CLOCK_MONOTONIC
, &ts
) == -1)
1110 if (clock_gettime(CLOCK_REALTIME
, &ts
) == -1)
1112 event_err(1, "clock_gettime");
1113 trans_id
= ts
.tv_nsec
& 0xffff;
1116 #ifdef DNS_USE_GETTIMEOFDAY_FOR_ID
1118 gettimeofday(&tv
, NULL
);
1119 trans_id
= tv
.tv_usec
& 0xffff;
1122 #ifdef DNS_USE_OPENSSL_FOR_ID
1123 if (RAND_pseudo_bytes((u8
*) &trans_id
, 2) == -1) {
1124 /* in the case that the RAND call fails we back */
1125 /* down to using gettimeofday. */
1128 gettimeofday(&tv, NULL);
1129 trans_id = tv.tv_usec & 0xffff;
1134 return (unsigned short) trans_id
;
1137 static uint16_t (*trans_id_function
)(void) = default_transaction_id_fn
;
1140 default_random_bytes_fn(char *buf
, size_t n
)
1143 for (i
= 0; i
< n
; i
+= 2) {
1144 u16 tid
= trans_id_function();
1145 buf
[i
] = (tid
>> 8) & 0xff;
1147 buf
[i
+1] = tid
& 0xff;
1151 static void (*rand_bytes_function
)(char *buf
, size_t n
) =
1152 default_random_bytes_fn
;
1155 trans_id_from_random_bytes_fn(void)
1158 rand_bytes_function((char*) &tid
, sizeof(tid
));
1163 evdns_set_transaction_id_fn(uint16_t (*fn
)(void))
1166 trans_id_function
= fn
;
1168 trans_id_function
= default_transaction_id_fn
;
1169 rand_bytes_function
= default_random_bytes_fn
;
1173 evdns_set_random_bytes_fn(void (*fn
)(char *, size_t))
1175 rand_bytes_function
= fn
;
1176 trans_id_function
= trans_id_from_random_bytes_fn
;
1179 /* Try to choose a strong transaction id which isn't already in flight */
1181 transaction_id_pick(void) {
1183 const struct evdns_request
*req
= req_head
, *started_at
;
1184 u16 trans_id
= trans_id_function();
1186 if (trans_id
== 0xffff) continue;
1187 /* now check to see if that id is already inflight */
1188 req
= started_at
= req_head
;
1191 if (req
->trans_id
== trans_id
) break;
1193 } while (req
!= started_at
);
1195 /* we didn't find it, so this is a good id */
1196 if (req
== started_at
) return trans_id
;
1200 /* choose a namesever to use. This function will try to ignore */
1201 /* nameservers which we think are down and load balance across the rest */
1202 /* by updating the server_head global each time. */
1203 static struct nameserver
*
1204 nameserver_pick(void) {
1205 struct nameserver
*started_at
= server_head
, *picked
;
1206 if (!server_head
) return NULL
;
1208 /* if we don't have any good nameservers then there's no */
1209 /* point in trying to find one. */
1210 if (!global_good_nameservers
) {
1211 server_head
= server_head
->next
;
1215 /* remember that nameservers are in a circular list */
1217 if (server_head
->state
) {
1218 /* we think this server is currently good */
1219 picked
= server_head
;
1220 server_head
= server_head
->next
;
1224 server_head
= server_head
->next
;
1225 if (server_head
== started_at
) {
1226 /* all the nameservers seem to be down */
1227 /* so we just return this one and hope for the */
1229 assert(global_good_nameservers
== 0);
1230 picked
= server_head
;
1231 server_head
= server_head
->next
;
1237 /* this is called when a namesever socket is ready for reading */
1239 nameserver_read(struct nameserver
*ns
) {
1240 struct sockaddr_storage ss
;
1241 struct sockaddr
*sa
= (struct sockaddr
*) &ss
;
1242 socklen_t addrlen
= sizeof(ss
);
1247 (int)recvfrom(ns
->socket
, packet
, (socklen_t
)sizeof(packet
), 0,
1250 int err
= last_error(ns
->socket
);
1251 if (error_is_eagain(err
)) return;
1252 nameserver_failed(ns
, tor_socket_strerror(err
));
1255 /* XXX Match port too? */
1256 if (!sockaddr_eq(sa
, (struct sockaddr
*)&ns
->address
, 0)) {
1258 "Address mismatch on received DNS packet. Address was %s",
1263 reply_parse(packet
, r
);
1267 /* Read a packet from a DNS client on a server port s, parse it, and */
1268 /* act accordingly. */
1270 server_port_read(struct evdns_server_port
*s
) {
1272 struct sockaddr_storage addr
;
1277 addrlen
= (socklen_t
)sizeof(struct sockaddr_storage
);
1278 r
= recvfrom(s
->socket
, packet
, sizeof(packet
), 0,
1279 (struct sockaddr
*) &addr
, &addrlen
);
1281 int err
= last_error(s
->socket
);
1282 if (error_is_eagain(err
)) return;
1283 log(EVDNS_LOG_WARN
, "Error %s (%d) while reading request.",
1284 tor_socket_strerror(err
), err
);
1287 request_parse(packet
, r
, s
, (struct sockaddr
*) &addr
, addrlen
);
1291 /* Try to write all pending replies on a given DNS server port. */
1293 server_port_flush(struct evdns_server_port
*port
)
1295 while (port
->pending_replies
) {
1296 struct server_request
*req
= port
->pending_replies
;
1297 ssize_t r
= sendto(port
->socket
, req
->response
, req
->response_len
, 0,
1298 (struct sockaddr
*) &req
->addr
, (socklen_t
)req
->addrlen
);
1300 int err
= last_error(port
->socket
);
1301 if (error_is_eagain(err
))
1303 log(EVDNS_LOG_WARN
, "Error %s (%d) while writing response to port; dropping", tor_socket_strerror(err
), err
);
1305 if (server_request_free(req
)) {
1306 /* we released the last reference to req->port. */
1311 /* We have no more pending requests; stop listening for 'writeable' events. */
1312 (void) event_del(&port
->event
);
1313 CLEAR(&port
->event
);
1314 event_set(&port
->event
, port
->socket
, EV_READ
| EV_PERSIST
,
1315 server_port_ready_callback
, port
);
1316 if (event_add(&port
->event
, NULL
) < 0) {
1317 log(EVDNS_LOG_WARN
, "Error from libevent when adding event for DNS server.");
1322 /* set if we are waiting for the ability to write to this server. */
1323 /* if waiting is true then we ask libevent for EV_WRITE events, otherwise */
1324 /* we stop these events. */
1326 nameserver_write_waiting(struct nameserver
*ns
, char waiting
) {
1327 if (ns
->write_waiting
== waiting
) return;
1329 ns
->write_waiting
= waiting
;
1330 (void) event_del(&ns
->event
);
1332 event_set(&ns
->event
, ns
->socket
, EV_READ
| (waiting
? EV_WRITE
: 0) | EV_PERSIST
,
1333 nameserver_ready_callback
, ns
);
1334 if (event_add(&ns
->event
, NULL
) < 0) {
1335 log(EVDNS_LOG_WARN
, "Error from libevent when adding event for %s",
1336 debug_ntop((struct sockaddr
*)&ns
->address
));
1341 /* a callback function. Called by libevent when the kernel says that */
1342 /* a nameserver socket is ready for writing or reading */
1344 nameserver_ready_callback(int fd
, short events
, void *arg
) {
1345 struct nameserver
*ns
= (struct nameserver
*) arg
;
1348 if (events
& EV_WRITE
) {
1350 if (!evdns_transmit()) {
1351 nameserver_write_waiting(ns
, 0);
1354 if (events
& EV_READ
) {
1355 nameserver_read(ns
);
1359 /* a callback function. Called by libevent when the kernel says that */
1360 /* a server socket is ready for writing or reading. */
1362 server_port_ready_callback(int fd
, short events
, void *arg
) {
1363 struct evdns_server_port
*port
= (struct evdns_server_port
*) arg
;
1366 if (events
& EV_WRITE
) {
1368 server_port_flush(port
);
1370 if (events
& EV_READ
) {
1371 server_port_read(port
);
1375 /* This is an inefficient representation; only use it via the dnslabel_table_*
1376 * functions, so that is can be safely replaced with something smarter later. */
1377 #define MAX_LABELS 128
1378 /* Structures used to implement name compression */
1379 struct dnslabel_entry
{ char *v
; off_t pos
; };
1380 struct dnslabel_table
{
1381 int n_labels
; /* number of current entries */
1382 /* map from name to position in message */
1383 struct dnslabel_entry labels
[MAX_LABELS
];
1386 /* Initialize dnslabel_table. */
1388 dnslabel_table_init(struct dnslabel_table
*table
)
1390 table
->n_labels
= 0;
1393 /* Free all storage held by table, but not the table itself. */
1395 dnslabel_clear(struct dnslabel_table
*table
)
1398 for (i
= 0; i
< table
->n_labels
; ++i
)
1399 mm_free(table
->labels
[i
].v
);
1400 table
->n_labels
= 0;
1403 /* return the position of the label in the current message, or -1 if the label */
1404 /* hasn't been used yet. */
1406 dnslabel_table_get_pos(const struct dnslabel_table
*table
, const char *label
)
1409 for (i
= 0; i
< table
->n_labels
; ++i
) {
1410 if (!strcmp(label
, table
->labels
[i
].v
)) {
1411 off_t pos
= table
->labels
[i
].pos
;
1420 /* remember that we've used the label at position pos */
1422 dnslabel_table_add(struct dnslabel_table
*table
, const char *label
, off_t pos
)
1426 if (table
->n_labels
== MAX_LABELS
)
1428 v
= mm_strdup(label
);
1431 p
= table
->n_labels
++;
1432 table
->labels
[p
].v
= v
;
1433 table
->labels
[p
].pos
= pos
;
1438 /* Converts a string to a length-prefixed set of DNS labels, starting */
1439 /* at buf[j]. name and buf must not overlap. name_len should be the length */
1440 /* of name. table is optional, and is used for compression. */
1442 /* Input: abc.def */
1443 /* Output: <3>abc<3>def<0> */
1445 /* Returns the first index after the encoded name, or negative on error. */
1446 /* -1 label was > 63 bytes */
1447 /* -2 name too long to fit in buffer. */
1450 dnsname_to_labels(u8
*const buf
, size_t buf_len
, off_t j
,
1451 const char *name
, const size_t name_len
,
1452 struct dnslabel_table
*table
) {
1453 const char *end
= name
+ name_len
;
1457 #define APPEND16(x) do { \
1458 if (j + 2 > (off_t)buf_len) \
1461 memcpy(buf + j, &_t, 2); \
1464 #define APPEND32(x) do { \
1465 if (j + 4 > (off_t)buf_len) \
1468 memcpy(buf + j, &_t32, 4); \
1472 if (name_len
> 255) return -2;
1475 const char *const start
= name
;
1476 if (table
&& (ref
= dnslabel_table_get_pos(table
, name
)) >= 0) {
1477 APPEND16(ref
| 0xc000);
1480 name
= strchr(name
, '.');
1482 const size_t label_len
= end
- start
;
1483 if (label_len
> 63) return -1;
1484 if ((size_t)(j
+label_len
+1) > buf_len
) return -2;
1485 if (table
) dnslabel_table_add(table
, start
, j
);
1486 buf
[j
++] = (uint8_t)label_len
;
1488 memcpy(buf
+ j
, start
, label_len
);
1492 /* append length of the label. */
1493 const size_t label_len
= name
- start
;
1494 if (label_len
> 63) return -1;
1495 if ((size_t)(j
+label_len
+1) > buf_len
) return -2;
1496 if (table
) dnslabel_table_add(table
, start
, j
);
1497 buf
[j
++] = (uint8_t)label_len
;
1499 memcpy(buf
+ j
, start
, name
- start
);
1501 /* hop over the '.' */
1506 /* the labels must be terminated by a 0. */
1507 /* It's possible that the name ended in a . */
1508 /* in which case the zero is already there */
1509 if (!j
|| buf
[j
-1]) buf
[j
++] = 0;
1515 /* Finds the length of a dns request for a DNS name of the given */
1516 /* length. The actual request may be smaller than the value returned */
1519 evdns_request_len(const size_t name_len
) {
1520 return 96 + /* length of the DNS standard header */
1522 4; /* space for the resource type */
1525 /* build a dns request packet into buf. buf should be at least as long */
1526 /* as evdns_request_len told you it should be. */
1528 /* Returns the amount of space used. Negative on error. */
1530 evdns_request_data_build(const char *const name
, const size_t name_len
,
1531 const u16 trans_id
, const u16 type
, const u16
class,
1532 u8
*const buf
, size_t buf_len
) {
1533 off_t j
= 0; /* current offset into buf */
1534 u16 _t
; /* used by the macros */
1537 APPEND16(0x0100); /* standard query, recusion needed */
1538 APPEND16(1); /* one question */
1539 APPEND16(0); /* no answers */
1540 APPEND16(0); /* no authority */
1541 APPEND16(0); /* no additional */
1543 j
= dnsname_to_labels(buf
, buf_len
, j
, name
, name_len
, NULL
);
1556 /* exported function */
1557 struct evdns_server_port
*
1558 evdns_add_server_port(int socket
, int is_tcp
, evdns_request_callback_fn_type cb
, void *user_data
)
1560 struct evdns_server_port
*port
;
1561 if (!(port
= mm_malloc(sizeof(struct evdns_server_port
))))
1563 memset(port
, 0, sizeof(struct evdns_server_port
));
1565 assert(!is_tcp
); /* TCP sockets not yet implemented */
1566 port
->socket
= socket
;
1570 port
->user_callback
= cb
;
1571 port
->user_data
= user_data
;
1572 port
->pending_replies
= NULL
;
1574 event_set(&port
->event
, port
->socket
, EV_READ
| EV_PERSIST
,
1575 server_port_ready_callback
, port
);
1576 if (event_add(&port
->event
, NULL
)<0) {
1583 /* exported function */
1585 evdns_close_server_port(struct evdns_server_port
*port
)
1588 if (--port
->refcnt
== 0)
1589 server_port_free(port
);
1592 /* exported function */
1594 evdns_server_request_add_reply(struct evdns_server_request
*_req
, int section
, const char *name
, int type
, int class, int ttl
, int datalen
, int is_name
, const char *data
)
1596 struct server_request
*req
= TO_SERVER_REQUEST(_req
);
1597 struct server_reply_item
**itemp
, *item
;
1600 if (req
->response
) /* have we already answered? */
1604 case EVDNS_ANSWER_SECTION
:
1605 itemp
= &req
->answer
;
1606 countp
= &req
->n_answer
;
1608 case EVDNS_AUTHORITY_SECTION
:
1609 itemp
= &req
->authority
;
1610 countp
= &req
->n_authority
;
1612 case EVDNS_ADDITIONAL_SECTION
:
1613 itemp
= &req
->additional
;
1614 countp
= &req
->n_additional
;
1620 itemp
= &((*itemp
)->next
);
1622 item
= mm_malloc(sizeof(struct server_reply_item
));
1627 if (!(item
->name
= mm_strdup(name
))) {
1633 item
->class = class;
1635 item
->is_name
= is_name
!= 0;
1639 if (item
->is_name
) {
1640 if (!(item
->data
= mm_strdup(data
))) {
1641 mm_free(item
->name
);
1646 item
->datalen
= (u16
)-1;
1648 if (!(item
->data
= mm_malloc(datalen
))) {
1649 mm_free(item
->name
);
1654 item
->datalen
= datalen
;
1655 memcpy(item
->data
, data
, datalen
);
1664 /* exported function */
1666 evdns_server_request_add_a_reply(struct evdns_server_request
*req
, const char *name
, int n
, void *addrs
, int ttl
)
1668 return evdns_server_request_add_reply(
1669 req
, EVDNS_ANSWER_SECTION
, name
, TYPE_A
, CLASS_INET
,
1670 ttl
, n
*4, 0, addrs
);
1673 /* exported function */
1675 evdns_server_request_add_aaaa_reply(struct evdns_server_request
*req
, const char *name
, int n
, void *addrs
, int ttl
)
1677 return evdns_server_request_add_reply(
1678 req
, EVDNS_ANSWER_SECTION
, name
, TYPE_AAAA
, CLASS_INET
,
1679 ttl
, n
*16, 0, addrs
);
1682 /* exported function */
1684 evdns_server_request_add_ptr_reply(struct evdns_server_request
*req
, struct in_addr
*in
, const char *inaddr_name
, const char *hostname
, int ttl
)
1688 assert(in
|| inaddr_name
);
1689 assert(!(in
&& inaddr_name
));
1691 a
= ntohl(in
->s_addr
);
1692 snprintf(buf
, sizeof(buf
), "%d.%d.%d.%d.in-addr.arpa",
1693 (int)(u8
)((a
)&0xff),
1694 (int)(u8
)((a
>>8 )&0xff),
1695 (int)(u8
)((a
>>16)&0xff),
1696 (int)(u8
)((a
>>24)&0xff));
1699 return evdns_server_request_add_reply(
1700 req
, EVDNS_ANSWER_SECTION
, inaddr_name
, TYPE_PTR
, CLASS_INET
,
1701 ttl
, -1, 1, hostname
);
1704 /* exported function */
1706 evdns_server_request_add_cname_reply(struct evdns_server_request
*req
, const char *name
, const char *cname
, int ttl
)
1708 return evdns_server_request_add_reply(
1709 req
, EVDNS_ANSWER_SECTION
, name
, TYPE_CNAME
, CLASS_INET
,
1715 evdns_server_request_format_response(struct server_request
*req
, int err
)
1717 unsigned char buf
[1500];
1718 size_t buf_len
= sizeof(buf
);
1724 struct dnslabel_table table
;
1726 if (err
< 0 || err
> 15) return -1;
1728 /* Set response bit and error code; copy OPCODE and RD fields from
1729 * question; copy RA and AA if set by caller. */
1730 flags
= req
->base
.flags
;
1731 flags
|= (0x8000 | err
);
1733 dnslabel_table_init(&table
);
1734 APPEND16(req
->trans_id
);
1736 APPEND16(req
->base
.nquestions
);
1737 APPEND16(req
->n_answer
);
1738 APPEND16(req
->n_authority
);
1739 APPEND16(req
->n_additional
);
1741 /* Add questions. */
1742 for (i
=0; i
< req
->base
.nquestions
; ++i
) {
1743 const char *s
= req
->base
.questions
[i
]->name
;
1744 j
= dnsname_to_labels(buf
, buf_len
, j
, s
, strlen(s
), &table
);
1746 dnslabel_clear(&table
);
1749 APPEND16(req
->base
.questions
[i
]->type
);
1750 APPEND16(req
->base
.questions
[i
]->dns_question_class
);
1753 /* Add answer, authority, and additional sections. */
1754 for (i
=0; i
<3; ++i
) {
1755 struct server_reply_item
*item
;
1759 item
= req
->authority
;
1761 item
= req
->additional
;
1763 r
= dnsname_to_labels(buf
, buf_len
, j
, item
->name
, strlen(item
->name
), &table
);
1768 APPEND16(item
->type
);
1769 APPEND16(item
->class);
1770 APPEND32(item
->ttl
);
1771 if (item
->is_name
) {
1772 off_t len_idx
= j
, name_start
;
1775 r
= dnsname_to_labels(buf
, buf_len
, j
, item
->data
, strlen(item
->data
), &table
);
1779 _t
= htons( (j
-name_start
) );
1780 memcpy(buf
+len_idx
, &_t
, 2);
1782 APPEND16(item
->datalen
);
1783 if (j
+item
->datalen
> (off_t
)buf_len
)
1785 memcpy(buf
+j
, item
->data
, item
->datalen
);
1795 buf
[2] |= 0x02; /* set the truncated bit. */
1798 req
->response_len
= (size_t)j
;
1800 if (!(req
->response
= mm_malloc(req
->response_len
))) {
1801 server_request_free_answers(req
);
1802 dnslabel_clear(&table
);
1805 memcpy(req
->response
, buf
, req
->response_len
);
1806 server_request_free_answers(req
);
1807 dnslabel_clear(&table
);
1811 /* exported function */
1813 evdns_server_request_respond(struct evdns_server_request
*_req
, int err
)
1815 struct server_request
*req
= TO_SERVER_REQUEST(_req
);
1816 struct evdns_server_port
*port
= req
->port
;
1818 if (!req
->response
) {
1819 if ((r
= evdns_server_request_format_response(req
, err
))<0)
1823 r
= sendto(port
->socket
, req
->response
, req
->response_len
, 0,
1824 (struct sockaddr
*) &req
->addr
, req
->addrlen
);
1826 int err
= last_error(port
->socket
);
1827 if (! error_is_eagain(err
))
1830 if (port
->pending_replies
) {
1831 req
->prev_pending
= port
->pending_replies
->prev_pending
;
1832 req
->next_pending
= port
->pending_replies
;
1833 req
->prev_pending
->next_pending
=
1834 req
->next_pending
->prev_pending
= req
;
1836 req
->prev_pending
= req
->next_pending
= req
;
1837 port
->pending_replies
= req
;
1840 (void) event_del(&port
->event
);
1841 CLEAR(&port
->event
);
1842 event_set(&port
->event
, port
->socket
, (port
->closing
?0:EV_READ
) | EV_WRITE
| EV_PERSIST
, server_port_ready_callback
, port
);
1844 if (event_add(&port
->event
, NULL
) < 0) {
1845 log(EVDNS_LOG_WARN
, "Error from libevent when adding event for DNS server");
1852 if (server_request_free(req
))
1855 if (port
->pending_replies
)
1856 server_port_flush(port
);
1861 /* Free all storage held by RRs in req. */
1863 server_request_free_answers(struct server_request
*req
)
1865 struct server_reply_item
*victim
, *next
, **list
;
1867 for (i
= 0; i
< 3; ++i
) {
1869 list
= &req
->answer
;
1871 list
= &req
->authority
;
1873 list
= &req
->additional
;
1877 next
= victim
->next
;
1878 mm_free(victim
->name
);
1880 mm_free(victim
->data
);
1888 /* Free all storage held by req, and remove links to it. */
1889 /* return true iff we just wound up freeing the server_port. */
1891 server_request_free(struct server_request
*req
)
1894 if (req
->base
.questions
) {
1895 for (i
= 0; i
< req
->base
.nquestions
; ++i
)
1896 mm_free(req
->base
.questions
[i
]);
1897 mm_free(req
->base
.questions
);
1901 if (req
->port
->pending_replies
== req
) {
1902 if (req
->next_pending
)
1903 req
->port
->pending_replies
= req
->next_pending
;
1905 req
->port
->pending_replies
= NULL
;
1907 rc
= --req
->port
->refcnt
;
1910 if (req
->response
) {
1911 mm_free(req
->response
);
1914 server_request_free_answers(req
);
1916 if (req
->next_pending
&& req
->next_pending
!= req
) {
1917 req
->next_pending
->prev_pending
= req
->prev_pending
;
1918 req
->prev_pending
->next_pending
= req
->next_pending
;
1922 server_port_free(req
->port
);
1932 /* Free all storage held by an evdns_server_port. Only called when the
1933 * reference count is down to 0. */
1935 server_port_free(struct evdns_server_port
*port
)
1938 assert(!port
->refcnt
);
1939 assert(!port
->pending_replies
);
1940 if (port
->socket
> 0) {
1941 CLOSE_SOCKET(port
->socket
);
1944 (void) event_del(&port
->event
);
1945 CLEAR(&port
->event
);
1950 /* exported function */
1952 evdns_server_request_drop(struct evdns_server_request
*_req
)
1954 struct server_request
*req
= TO_SERVER_REQUEST(_req
);
1955 server_request_free(req
);
1959 /* exported function */
1961 evdns_server_request_get_requesting_addr(struct evdns_server_request
*_req
, struct sockaddr
*sa
, int addr_len
)
1963 struct server_request
*req
= TO_SERVER_REQUEST(_req
);
1964 if (addr_len
< (int)req
->addrlen
)
1966 memcpy(sa
, &(req
->addr
), req
->addrlen
);
1967 return req
->addrlen
;
1973 /* this is a libevent callback function which is called when a request */
1974 /* has timed out. */
1976 evdns_request_timeout_callback(int fd
, short events
, void *arg
) {
1977 struct evdns_request
*const req
= (struct evdns_request
*) arg
;
1981 log(EVDNS_LOG_DEBUG
, "Request %lx timed out", (unsigned long) arg
);
1983 req
->ns
->timedout
++;
1984 if (req
->ns
->timedout
> global_max_nameserver_timeout
) {
1985 req
->ns
->timedout
= 0;
1986 nameserver_failed(req
->ns
, "request timed out.");
1989 if (req
->tx_count
>= global_max_retransmits
) {
1990 /* this request has failed */
1991 reply_callback(req
, 0, DNS_ERR_TIMEOUT
, NULL
);
1992 request_finished(req
, &req_head
);
1995 /* Stop waiting for the timeout. No need to do this in
1996 * request_finished; that one already deletes the timeout event.
1997 * XXXX021 port this change to libevent. */
1998 del_timeout_event(req
);
1999 evdns_request_transmit(req
);
2003 /* try to send a request to a given server. */
2007 /* 1 temporary failure */
2008 /* 2 other failure */
2010 evdns_request_transmit_to(struct evdns_request
*req
, struct nameserver
*server
) {
2011 const ssize_t r
= send(server
->socket
, req
->request
, req
->request_len
, 0);
2013 int err
= last_error(server
->socket
);
2014 if (error_is_eagain(err
)) return 1;
2015 nameserver_failed(req
->ns
, tor_socket_strerror(err
));
2017 } else if (r
!= (ssize_t
)req
->request_len
) {
2018 return 1; /* short write */
2024 /* try to send a request, updating the fields of the request */
2031 evdns_request_transmit(struct evdns_request
*req
) {
2034 /* if we fail to send this packet then this flag marks it */
2035 /* for evdns_transmit */
2036 req
->transmit_me
= 1;
2037 if (req
->trans_id
== 0xffff) abort();
2039 if (req
->ns
->choked
) {
2040 /* don't bother trying to write to a socket */
2041 /* which we have had EAGAIN from */
2045 r
= evdns_request_transmit_to(req
, req
->ns
);
2049 req
->ns
->choked
= 1;
2050 nameserver_write_waiting(req
->ns
, 1);
2053 /* failed to transmit the request entirely. */
2055 /* fall through: we'll set a timeout, which will time out,
2056 * and make us retransmit the request anyway. */
2058 /* transmitted; we need to check for timeout. */
2059 log(EVDNS_LOG_DEBUG
,
2060 "Setting timeout for request %lx", (unsigned long) req
);
2062 if (add_timeout_event(req
, &global_timeout
) < 0) {
2064 "Error from libevent when adding timer for request %lx",
2065 (unsigned long) req
);
2069 req
->transmit_me
= 0;
2075 nameserver_probe_callback(int result
, char type
, int count
, int ttl
, void *addresses
, void *arg
) {
2076 struct sockaddr
*addr
= arg
;
2077 struct nameserver
*server
;
2083 for (server
= server_head
; server
; server
= server
->next
) {
2084 if (sockaddr_eq(addr
, (struct sockaddr
*) &server
->address
, 1)) {
2085 if (result
== DNS_ERR_NONE
|| result
== DNS_ERR_NOTEXIST
) {
2086 /* this is a good reply */
2087 nameserver_up(server
);
2089 nameserver_probe_failed(server
);
2092 if (server
->next
== server_head
)
2100 nameserver_send_probe(struct nameserver
*const ns
) {
2101 struct evdns_request
*req
;
2102 struct sockaddr_storage
*addr
;
2103 /* here we need to send a probe to a given nameserver */
2104 /* in the hope that it is up now. */
2106 /* We identify the nameserver by its address, in case it is removed before
2107 * our probe comes back. */
2108 addr
= mm_malloc(sizeof(struct sockaddr_storage
));
2109 memcpy(addr
, &ns
->address
, sizeof(struct sockaddr_storage
));
2111 log(EVDNS_LOG_DEBUG
, "Sending probe to %s", debug_ntop((struct sockaddr
*)&ns
->address
));
2113 req
= request_new(TYPE_A
, "www.google.com", DNS_QUERY_NO_SEARCH
, nameserver_probe_callback
, addr
);
2118 /* we force this into the inflight queue no matter what */
2119 request_trans_id_set(req
, transaction_id_pick());
2121 request_submit(req
);
2125 /* 0 didn't try to transmit anything */
2126 /* 1 tried to transmit something */
2128 evdns_transmit(void) {
2129 char did_try_to_transmit
= 0;
2132 struct evdns_request
*const started_at
= req_head
, *req
= req_head
;
2133 /* first transmit all the requests which are currently waiting */
2135 if (req
->transmit_me
) {
2136 did_try_to_transmit
= 1;
2137 evdns_request_transmit(req
);
2141 } while (req
!= started_at
);
2144 return did_try_to_transmit
;
2147 /* exported function */
2149 evdns_count_nameservers(void)
2151 const struct nameserver
*server
= server_head
;
2157 server
= server
->next
;
2158 } while (server
!= server_head
);
2162 /* exported function */
2164 evdns_clear_nameservers_and_suspend(void)
2166 struct nameserver
*server
= server_head
, *started_at
= server_head
;
2167 struct evdns_request
*req
= req_head
, *req_started_at
= req_head
;
2172 struct nameserver
*next
= server
->next
;
2173 (void) event_del(&server
->event
);
2174 CLEAR(&server
->event
);
2175 del_timeout_event(server
);
2176 if (server
->socket
>= 0)
2177 CLOSE_SOCKET(server
->socket
);
2180 if (next
== started_at
)
2185 global_good_nameservers
= 0;
2188 struct evdns_request
*next
= req
->next
;
2189 req
->tx_count
= req
->reissue_count
= 0;
2191 /* ???? What to do about searches? */
2192 del_timeout_event(req
);
2194 req
->transmit_me
= 0;
2196 global_requests_waiting
++;
2197 evdns_request_insert(req
, &req_waiting_head
);
2198 /* We want to insert these suspended elements at the front of
2199 * the waiting queue, since they were pending before any of
2200 * the waiting entries were added. This is a circular list,
2201 * so we can just shift the start back by one.*/
2202 req_waiting_head
= req_waiting_head
->prev
;
2204 if (next
== req_started_at
)
2209 global_requests_inflight
= 0;
2214 static struct sockaddr_storage global_bind_address
;
2215 static socklen_t global_bind_addrlen
= 0;
2216 static int global_bind_addr_is_set
= 0;
2218 evdns_set_default_outgoing_bind_address(const struct sockaddr
*addr
,
2221 memset(&global_bind_address
, 0, sizeof(global_bind_address
));
2223 assert(addrlen
<= (socklen_t
)sizeof(global_bind_address
));
2224 memcpy(&global_bind_address
, addr
, addrlen
);
2225 global_bind_addrlen
= addrlen
;
2226 global_bind_addr_is_set
= 1;
2228 global_bind_addr_is_set
= 0;
2232 /* exported function */
2236 evdns_requests_pump_waiting_queue();
2241 _evdns_nameserver_add_impl(const struct sockaddr
*address
,
2242 socklen_t addrlen
) {
2243 /* first check to see if we already have this nameserver */
2245 const struct nameserver
*server
= server_head
, *const started_at
= server_head
;
2246 struct nameserver
*ns
;
2251 if (sockaddr_eq(address
, (struct sockaddr
*)&server
->address
, 1)) {
2252 log(EVDNS_LOG_DEBUG
, "Duplicate nameserver.");
2255 server
= server
->next
;
2256 } while (server
!= started_at
);
2258 if (addrlen
> (int)sizeof(ns
->address
)) {
2259 log(EVDNS_LOG_DEBUG
, "Addrlen %d too long.", (int)addrlen
);
2263 ns
= (struct nameserver
*) mm_malloc(sizeof(struct nameserver
));
2266 memset(ns
, 0, sizeof(struct nameserver
));
2268 evtimer_set(&ns
->timeout_event
, nameserver_prod_callback
, ns
);
2270 ns
->socket
= socket(PF_INET
, SOCK_DGRAM
, 0);
2271 if (ns
->socket
< 0) { err
= 1; goto out1
; }
2274 u_long nonblocking
= 1;
2275 ioctlsocket(ns
->socket
, FIONBIO
, &nonblocking
);
2278 fcntl(ns
->socket
, F_SETFL
, O_NONBLOCK
);
2281 if (global_bind_addr_is_set
) {
2282 if (bind(ns
->socket
, (struct sockaddr
*)&global_bind_address
,
2283 global_bind_addrlen
) < 0) {
2284 log(EVDNS_LOG_DEBUG
, "Couldn't bind to outgoing address.");
2290 if (connect(ns
->socket
, address
, addrlen
) != 0) {
2291 log(EVDNS_LOG_DEBUG
, "Couldn't open socket to nameserver.");
2296 memcpy(&ns
->address
, address
, addrlen
);
2298 event_set(&ns
->event
, ns
->socket
, EV_READ
| EV_PERSIST
, nameserver_ready_callback
, ns
);
2299 if (event_add(&ns
->event
, NULL
) < 0) {
2300 log(EVDNS_LOG_DEBUG
, "Couldn't add event for nameserver.");
2305 log(EVDNS_LOG_DEBUG
, "Added nameserver %s", debug_ntop(address
));
2307 /* insert this nameserver into the list of them */
2309 ns
->next
= ns
->prev
= ns
;
2312 ns
->next
= server_head
->next
;
2313 ns
->prev
= server_head
;
2314 server_head
->next
= ns
;
2315 if (server_head
->prev
== server_head
) {
2316 server_head
->prev
= ns
;
2320 global_good_nameservers
++;
2325 CLOSE_SOCKET(ns
->socket
);
2329 log(EVDNS_LOG_WARN
, "Unable to add nameserver %s: error %d", debug_ntop(address
), err
);
2333 /* exported function */
2335 evdns_nameserver_add(uint32_t address
) {
2336 struct sockaddr_in sin
;
2337 memset(&sin
, 0, sizeof(sin
));
2338 sin
.sin_family
= AF_INET
;
2339 #ifdef HAVE_STRUCT_SOCKADDR_IN_SIN_LEN
2340 sin
.sin_len
= sizeof(sin
);
2342 sin
.sin_addr
.s_addr
= htonl(address
);
2344 return _evdns_nameserver_add_impl((struct sockaddr
*) &sin
, sizeof(sin
));
2347 /* exported function */
2349 evdns_nameserver_ip_add(const char *ip_as_string
) {
2352 const char *cp
, *addr_part
, *port_part
;
2354 /* recognized formats are:
2362 log(EVDNS_LOG_DEBUG
, "Trying to add nameserver <%s>", ip_as_string
);
2364 cp
= strchr(ip_as_string
, ':');
2365 if (*ip_as_string
== '[') {
2367 if (!(cp
= strchr(ip_as_string
, ']'))) {
2368 log(EVDNS_LOG_DEBUG
, "Nameserver missing closing ]");
2371 len
= cp
-(ip_as_string
+ 1);
2372 if (len
> sizeof(buf
)-1) {
2373 log(EVDNS_LOG_DEBUG
, "[Nameserver] does not fit in buffer.");
2376 memcpy(buf
, ip_as_string
+1, len
);
2384 } else if (cp
&& strchr(cp
+1, ':')) {
2386 addr_part
= ip_as_string
;
2390 if (cp
- ip_as_string
> (int)sizeof(buf
)-1) {
2391 log(EVDNS_LOG_DEBUG
, "Nameserver does not fit in buffer.");
2394 memcpy(buf
, ip_as_string
, cp
-ip_as_string
);
2395 buf
[cp
-ip_as_string
] = '\0';
2399 addr_part
= ip_as_string
;
2404 if (port_part
== NULL
) {
2407 port
= strtoint(port_part
);
2408 if (port
<= 0 || port
> 65535) {
2409 log(EVDNS_LOG_DEBUG
, "Nameserver port <%s> out of range",
2415 /* Tor-only. needs a more general fix. */
2418 struct sockaddr_in6 sin6
;
2419 memset(&sin6
, 0, sizeof(sin6
));
2420 #ifdef HAVE_STRUCT_SOCKADDR_IN6_SIN6_LEN
2421 sin6
.sin6_len
= sizeof(sin6
);
2423 sin6
.sin6_family
= AF_INET6
;
2424 sin6
.sin6_port
= htons(port
);
2425 if (1 != tor_inet_pton(AF_INET6
, addr_part
, &sin6
.sin6_addr
)) {
2426 log(EVDNS_LOG_DEBUG
, "inet_pton(%s) failed", addr_part
);
2429 return _evdns_nameserver_add_impl((struct sockaddr
*)&sin6
,
2432 struct sockaddr_in sin
;
2433 memset(&sin
, 0, sizeof(sin
));
2434 #ifdef HAVE_STRUCT_SOCKADDR_IN_SIN_LEN
2435 sin
.sin_len
= sizeof(sin
);
2437 sin
.sin_family
= AF_INET
;
2438 sin
.sin_port
= htons(port
);
2439 if (!inet_aton(addr_part
, &sin
.sin_addr
)) {
2440 log(EVDNS_LOG_DEBUG
, "inet_pton(%s) failed", addr_part
);
2443 return _evdns_nameserver_add_impl((struct sockaddr
*)&sin
,
2449 evdns_nameserver_sockaddr_add(const struct sockaddr
*sa
, socklen_t len
)
2451 return _evdns_nameserver_add_impl(sa
, len
);
2454 /* insert into the tail of the queue */
2456 evdns_request_insert(struct evdns_request
*req
, struct evdns_request
**head
) {
2459 req
->next
= req
->prev
= req
;
2463 req
->prev
= (*head
)->prev
;
2464 req
->prev
->next
= req
;
2466 (*head
)->prev
= req
;
2470 string_num_dots(const char *s
) {
2472 while ((s
= strchr(s
, '.'))) {
2479 static struct evdns_request
*
2480 request_new(int type
, const char *name
, int flags
,
2481 evdns_callback_type callback
, void *user_ptr
) {
2482 const char issuing_now
=
2483 (global_requests_inflight
< global_max_requests_inflight
) ? 1 : 0;
2485 const size_t name_len
= strlen(name
);
2486 const size_t request_max_len
= evdns_request_len(name_len
);
2487 const u16 trans_id
= issuing_now
? transaction_id_pick() : 0xffff;
2488 /* the request data is alloced in a single block with the header */
2489 struct evdns_request
*const req
=
2490 (struct evdns_request
*) mm_malloc(sizeof(struct evdns_request
) + request_max_len
);
2495 if (!req
) return NULL
;
2497 if (name_len
>= sizeof(namebuf
)) {
2502 memset(req
, 0, sizeof(struct evdns_request
));
2504 evtimer_set(&req
->timeout_event
, evdns_request_timeout_callback
, req
);
2506 if (global_randomize_case
) {
2509 strlcpy(namebuf
, name
, sizeof(namebuf
));
2510 rand_bytes_function(randbits
, (name_len
+7)/8);
2511 for (i
= 0; i
< name_len
; ++i
) {
2512 if (ISALPHA(namebuf
[i
])) {
2513 if ((randbits
[i
>> 3] & (1<<(i
%7))))
2514 namebuf
[i
] = TOLOWER(namebuf
[i
]);
2516 namebuf
[i
] = TOUPPER(namebuf
[i
]);
2522 /* request data lives just after the header */
2523 req
->request
= ((u8
*) req
) + sizeof(struct evdns_request
);
2524 /* denotes that the request data shouldn't be mm_free()ed */
2525 req
->request_appended
= 1;
2526 rlen
= evdns_request_data_build(name
, name_len
, trans_id
,
2527 type
, CLASS_INET
, req
->request
, request_max_len
);
2530 req
->request_len
= rlen
;
2531 req
->trans_id
= trans_id
;
2533 req
->request_type
= type
;
2534 req
->user_pointer
= user_ptr
;
2535 req
->user_callback
= callback
;
2536 req
->ns
= issuing_now
? nameserver_pick() : NULL
;
2537 req
->next
= req
->prev
= NULL
;
2547 request_submit(struct evdns_request
*const req
) {
2549 /* if it has a nameserver assigned then this is going */
2550 /* straight into the inflight queue */
2551 evdns_request_insert(req
, &req_head
);
2552 global_requests_inflight
++;
2553 evdns_request_transmit(req
);
2555 evdns_request_insert(req
, &req_waiting_head
);
2556 global_requests_waiting
++;
2560 /* exported function */
2561 int evdns_resolve_ipv4(const char *name
, int flags
,
2562 evdns_callback_type callback
, void *ptr
) {
2563 log(EVDNS_LOG_DEBUG
, "Resolve requested for %s", name
);
2564 if (flags
& DNS_QUERY_NO_SEARCH
) {
2565 struct evdns_request
*const req
=
2566 request_new(TYPE_A
, name
, flags
, callback
, ptr
);
2569 request_submit(req
);
2572 return (search_request_new(TYPE_A
, name
, flags
, callback
, ptr
));
2576 /* exported function */
2577 int evdns_resolve_ipv6(const char *name
, int flags
,
2578 evdns_callback_type callback
, void *ptr
) {
2579 log(EVDNS_LOG_DEBUG
, "Resolve requested for %s", name
);
2580 if (flags
& DNS_QUERY_NO_SEARCH
) {
2581 struct evdns_request
*const req
=
2582 request_new(TYPE_AAAA
, name
, flags
, callback
, ptr
);
2585 request_submit(req
);
2588 return (search_request_new(TYPE_AAAA
, name
, flags
, callback
, ptr
));
2592 int evdns_resolve_reverse(const struct in_addr
*in
, int flags
, evdns_callback_type callback
, void *ptr
) {
2594 struct evdns_request
*req
;
2597 a
= ntohl(in
->s_addr
);
2598 snprintf(buf
, sizeof(buf
), "%d.%d.%d.%d.in-addr.arpa",
2599 (int)(u8
)((a
)&0xff),
2600 (int)(u8
)((a
>>8 )&0xff),
2601 (int)(u8
)((a
>>16)&0xff),
2602 (int)(u8
)((a
>>24)&0xff));
2603 log(EVDNS_LOG_DEBUG
, "Resolve requested for %s (reverse)", buf
);
2604 req
= request_new(TYPE_PTR
, buf
, flags
, callback
, ptr
);
2606 request_submit(req
);
2610 int evdns_resolve_reverse_ipv6(const struct in6_addr
*in
, int flags
, evdns_callback_type callback
, void *ptr
) {
2611 /* 32 nybbles, 32 periods, "ip6.arpa", NUL. */
2614 struct evdns_request
*req
;
2618 for (i
=15; i
>= 0; --i
) {
2619 u8 byte
= in
->s6_addr
[i
];
2620 *cp
++ = "0123456789abcdef"[byte
& 0x0f];
2622 *cp
++ = "0123456789abcdef"[byte
>> 4];
2625 assert(cp
+ strlen("ip6.arpa") < buf
+sizeof(buf
));
2626 memcpy(cp
, "ip6.arpa", strlen("ip6.arpa")+1);
2627 log(EVDNS_LOG_DEBUG
, "Resolve requested for %s (reverse)", buf
);
2628 req
= request_new(TYPE_PTR
, buf
, flags
, callback
, ptr
);
2630 request_submit(req
);
2634 /*/////////////////////////////////////////////////////////////////// */
2635 /* Search support */
2637 /* the libc resolver has support for searching a number of domains */
2638 /* to find a name. If nothing else then it takes the single domain */
2639 /* from the gethostname() call. */
2641 /* It can also be configured via the domain and search options in a */
2644 /* The ndots option controls how many dots it takes for the resolver */
2645 /* to decide that a name is non-local and so try a raw lookup first. */
2647 struct search_domain
{
2649 struct search_domain
*next
;
2650 /* the text string is appended to this structure */
2653 struct search_state
{
2657 struct search_domain
*head
;
2660 static struct search_state
*global_search_state
= NULL
;
2663 search_state_decref(struct search_state
*const state
) {
2666 if (!state
->refcount
) {
2667 struct search_domain
*next
, *dom
;
2668 for (dom
= state
->head
; dom
; dom
= next
) {
2678 static struct search_state
*
2679 search_state_new(void) {
2680 struct search_state
*state
= (struct search_state
*) mm_malloc(sizeof(struct search_state
));
2681 if (!state
) return NULL
;
2682 memset(state
, 0, sizeof(struct search_state
));
2683 state
->refcount
= 1;
2690 search_postfix_clear(void) {
2691 search_state_decref(global_search_state
);
2693 global_search_state
= search_state_new();
2696 /* exported function */
2698 evdns_search_clear(void) {
2699 search_postfix_clear();
2703 search_postfix_add(const char *domain
) {
2705 struct search_domain
*sdomain
;
2706 while (domain
[0] == '.') domain
++;
2707 domain_len
= strlen(domain
);
2709 if (!global_search_state
) global_search_state
= search_state_new();
2710 if (!global_search_state
) return;
2711 global_search_state
->num_domains
++;
2713 sdomain
= (struct search_domain
*) mm_malloc(sizeof(struct search_domain
) + domain_len
);
2714 if (!sdomain
) return;
2715 memcpy( ((u8
*) sdomain
) + sizeof(struct search_domain
), domain
, domain_len
);
2716 sdomain
->next
= global_search_state
->head
;
2717 sdomain
->len
= domain_len
;
2719 global_search_state
->head
= sdomain
;
2722 /* reverse the order of members in the postfix list. This is needed because, */
2723 /* when parsing resolv.conf we push elements in the wrong order */
2725 search_reverse(void) {
2726 struct search_domain
*cur
, *prev
= NULL
, *next
;
2727 cur
= global_search_state
->head
;
2735 global_search_state
->head
= prev
;
2738 /* exported function */
2740 evdns_search_add(const char *domain
) {
2741 search_postfix_add(domain
);
2744 /* exported function */
2746 evdns_search_ndots_set(const int ndots
) {
2747 if (!global_search_state
) global_search_state
= search_state_new();
2748 if (!global_search_state
) return;
2749 global_search_state
->ndots
= ndots
;
2753 search_set_from_hostname(void) {
2754 char hostname
[HOST_NAME_MAX
+ 1], *domainname
;
2756 search_postfix_clear();
2757 if (gethostname(hostname
, sizeof(hostname
))) return;
2758 domainname
= strchr(hostname
, '.');
2759 if (!domainname
) return;
2760 search_postfix_add(domainname
);
2763 /* warning: returns malloced string */
2765 search_make_new(const struct search_state
*const state
, int n
, const char *const base_name
) {
2766 const size_t base_len
= strlen(base_name
);
2767 const char need_to_append_dot
= base_name
[base_len
- 1] == '.' ? 0 : 1;
2768 struct search_domain
*dom
;
2770 for (dom
= state
->head
; dom
; dom
= dom
->next
) {
2772 /* this is the postfix we want */
2773 /* the actual postfix string is kept at the end of the structure */
2774 const u8
*const postfix
= ((u8
*) dom
) + sizeof(struct search_domain
);
2775 const size_t postfix_len
= dom
->len
;
2776 char *const newname
= (char *) mm_malloc(base_len
+ need_to_append_dot
+ postfix_len
+ 1);
2777 if (!newname
) return NULL
;
2778 memcpy(newname
, base_name
, base_len
);
2779 if (need_to_append_dot
) newname
[base_len
] = '.';
2780 memcpy(newname
+ base_len
+ need_to_append_dot
, postfix
, postfix_len
);
2781 newname
[base_len
+ need_to_append_dot
+ postfix_len
] = 0;
2786 /* we ran off the end of the list and still didn't find the requested string */
2788 return NULL
; /* unreachable; stops warnings in some compilers. */
2792 search_request_new(int type
, const char *const name
, int flags
, evdns_callback_type user_callback
, void *user_arg
) {
2793 assert(type
== TYPE_A
|| type
== TYPE_AAAA
);
2794 if ( ((flags
& DNS_QUERY_NO_SEARCH
) == 0) &&
2795 global_search_state
&&
2796 global_search_state
->num_domains
) {
2797 /* we have some domains to search */
2798 struct evdns_request
*req
;
2799 if (string_num_dots(name
) >= global_search_state
->ndots
) {
2800 req
= request_new(type
, name
, flags
, user_callback
, user_arg
);
2802 req
->search_index
= -1;
2804 char *const new_name
= search_make_new(global_search_state
, 0, name
);
2805 if (!new_name
) return 1;
2806 req
= request_new(type
, new_name
, flags
, user_callback
, user_arg
);
2809 req
->search_index
= 0;
2811 req
->search_origname
= mm_strdup(name
);
2812 req
->search_state
= global_search_state
;
2813 req
->search_flags
= flags
;
2814 global_search_state
->refcount
++;
2815 request_submit(req
);
2818 struct evdns_request
*const req
= request_new(type
, name
, flags
, user_callback
, user_arg
);
2820 request_submit(req
);
2825 /* this is called when a request has failed to find a name. We need to check */
2826 /* if it is part of a search and, if so, try the next name in the list */
2828 /* 0 another request has been submitted */
2829 /* 1 no more requests needed */
2831 search_try_next(struct evdns_request
*const req
) {
2832 if (req
->search_state
) {
2833 /* it is part of a search */
2835 struct evdns_request
*newreq
;
2836 req
->search_index
++;
2837 if (req
->search_index
>= req
->search_state
->num_domains
) {
2838 /* no more postfixes to try, however we may need to try */
2839 /* this name without a postfix */
2840 if (string_num_dots(req
->search_origname
) < req
->search_state
->ndots
) {
2841 /* yep, we need to try it raw */
2842 struct evdns_request
*const newreq
= request_new(req
->request_type
, req
->search_origname
, req
->search_flags
, req
->user_callback
, req
->user_pointer
);
2843 log(EVDNS_LOG_DEBUG
, "Search: trying raw query %s", req
->search_origname
);
2845 request_submit(newreq
);
2852 new_name
= search_make_new(req
->search_state
, req
->search_index
, req
->search_origname
);
2853 if (!new_name
) return 1;
2854 log(EVDNS_LOG_DEBUG
, "Search: now trying %s (%d)", new_name
, req
->search_index
);
2855 newreq
= request_new(req
->request_type
, new_name
, req
->search_flags
, req
->user_callback
, req
->user_pointer
);
2857 if (!newreq
) return 1;
2858 newreq
->search_origname
= req
->search_origname
;
2859 req
->search_origname
= NULL
;
2860 newreq
->search_state
= req
->search_state
;
2861 newreq
->search_flags
= req
->search_flags
;
2862 newreq
->search_index
= req
->search_index
;
2863 newreq
->search_state
->refcount
++;
2864 request_submit(newreq
);
2871 search_request_finished(struct evdns_request
*const req
) {
2872 if (req
->search_state
) {
2873 search_state_decref(req
->search_state
);
2874 req
->search_state
= NULL
;
2876 if (req
->search_origname
) {
2877 mm_free(req
->search_origname
);
2878 req
->search_origname
= NULL
;
2882 /*/////////////////////////////////////////////////////////////////// */
2883 /* Parsing resolv.conf files */
2886 evdns_resolv_set_defaults(int flags
) {
2887 /* if the file isn't found then we assume a local resolver */
2888 if (flags
& DNS_OPTION_SEARCH
) search_set_from_hostname();
2889 if (flags
& DNS_OPTION_NAMESERVERS
) evdns_nameserver_ip_add("127.0.0.1");
2892 /* helper version of atoi which returns -1 on error */
2894 strtoint(const char *const str
) {
2896 const long r
= strtol(str
, &endptr
, 10);
2897 if (*endptr
|| r
> INT_MAX
) return -1;
2901 /* helper version of atoi that returns -1 on error and clips to bounds. */
2903 strtoint_clipped(const char *const str
, int min
, int max
)
2905 int r
= strtoint(str
);
2916 /* exported function */
2918 evdns_set_option(const char *option
, const char *val
, int flags
)
2920 if (!strncmp(option
, "ndots:", 6)) {
2921 const int ndots
= strtoint(val
);
2922 if (ndots
== -1) return -1;
2923 if (!(flags
& DNS_OPTION_SEARCH
)) return 0;
2924 log(EVDNS_LOG_DEBUG
, "Setting ndots to %d", ndots
);
2925 if (!global_search_state
) global_search_state
= search_state_new();
2926 if (!global_search_state
) return -1;
2927 global_search_state
->ndots
= ndots
;
2928 } else if (!strncmp(option
, "timeout:", 8)) {
2929 const int timeout
= strtoint(val
);
2930 if (timeout
== -1) return -1;
2931 if (!(flags
& DNS_OPTION_MISC
)) return 0;
2932 log(EVDNS_LOG_DEBUG
, "Setting timeout to %d", timeout
);
2933 global_timeout
.tv_sec
= timeout
;
2934 } else if (!strncmp(option
, "max-timeouts:", 12)) {
2935 const int maxtimeout
= strtoint_clipped(val
, 1, 255);
2936 if (maxtimeout
== -1) return -1;
2937 if (!(flags
& DNS_OPTION_MISC
)) return 0;
2938 log(EVDNS_LOG_DEBUG
, "Setting maximum allowed timeouts to %d",
2940 global_max_nameserver_timeout
= maxtimeout
;
2941 } else if (!strncmp(option
, "max-inflight:", 13)) {
2942 const int maxinflight
= strtoint_clipped(val
, 1, 65000);
2943 if (maxinflight
== -1) return -1;
2944 if (!(flags
& DNS_OPTION_MISC
)) return 0;
2945 log(EVDNS_LOG_DEBUG
, "Setting maximum inflight requests to %d",
2947 global_max_requests_inflight
= maxinflight
;
2948 } else if (!strncmp(option
, "attempts:", 9)) {
2949 int retries
= strtoint(val
);
2950 if (retries
== -1) return -1;
2951 if (retries
> 255) retries
= 255;
2952 if (!(flags
& DNS_OPTION_MISC
)) return 0;
2953 log(EVDNS_LOG_DEBUG
, "Setting retries to %d", retries
);
2954 global_max_retransmits
= retries
;
2955 } else if (!strncmp(option
, "randomize-case:", 15)) {
2956 int randcase
= strtoint(val
);
2957 if (!(flags
& DNS_OPTION_MISC
)) return 0;
2958 log(EVDNS_LOG_DEBUG
, "Setting randomize_case to %d", randcase
);
2959 global_randomize_case
= randcase
;
2965 resolv_conf_parse_line(char *const start
, int flags
) {
2967 static const char *const delims
= " \t";
2968 #define NEXT_TOKEN tor_strtok_r(NULL, delims, &strtok_state)
2970 char *const first_token
= tor_strtok_r(start
, delims
, &strtok_state
);
2971 if (!first_token
) return;
2973 if (!strcmp(first_token
, "nameserver") && (flags
& DNS_OPTION_NAMESERVERS
)) {
2974 const char *const nameserver
= NEXT_TOKEN
;
2975 evdns_nameserver_ip_add(nameserver
);
2976 } else if (!strcmp(first_token
, "domain") && (flags
& DNS_OPTION_SEARCH
)) {
2977 const char *const domain
= NEXT_TOKEN
;
2979 search_postfix_clear();
2980 search_postfix_add(domain
);
2982 } else if (!strcmp(first_token
, "search") && (flags
& DNS_OPTION_SEARCH
)) {
2984 search_postfix_clear();
2986 while ((domain
= NEXT_TOKEN
)) {
2987 search_postfix_add(domain
);
2990 } else if (!strcmp(first_token
, "options")) {
2992 while ((option
= NEXT_TOKEN
)) {
2993 const char *val
= strchr(option
, ':');
2994 evdns_set_option(option
, val
? val
+1 : "", flags
);
3000 /* exported function */
3003 /* 1 failed to open file */
3004 /* 2 failed to stat file */
3005 /* 3 file too large */
3006 /* 4 out of memory */
3007 /* 5 short read from file */
3009 evdns_resolv_conf_parse(int flags
, const char *const filename
) {
3016 log(EVDNS_LOG_DEBUG
, "Parsing resolv.conf file %s", filename
);
3018 fd
= open(filename
, O_RDONLY
);
3020 evdns_resolv_set_defaults(flags
);
3024 if (fstat(fd
, &st
)) { err
= 2; goto out1
; }
3026 evdns_resolv_set_defaults(flags
);
3027 err
= (flags
& DNS_OPTION_NAMESERVERS
) ? 6 : 0;
3030 if (st
.st_size
> 65535) { err
= 3; goto out1
; } /* no resolv.conf should be any bigger */
3032 resolv
= (u8
*) mm_malloc((size_t)st
.st_size
+ 1);
3033 if (!resolv
) { err
= 4; goto out1
; }
3036 while ((r
= (int)read(fd
, resolv
+n
, (size_t)st
.st_size
-n
)) > 0) {
3038 if (n
== st
.st_size
)
3040 assert(n
< st
.st_size
);
3042 if (r
< 0) { err
= 5; goto out2
; }
3043 resolv
[n
] = 0; /* we malloced an extra byte; this should be fine. */
3045 start
= (char *) resolv
;
3047 char *const newline
= strchr(start
, '\n');
3049 resolv_conf_parse_line(start
, flags
);
3053 resolv_conf_parse_line(start
, flags
);
3054 start
= newline
+ 1;
3058 if (!server_head
&& (flags
& DNS_OPTION_NAMESERVERS
)) {
3059 /* no nameservers were configured. */
3060 evdns_nameserver_ip_add("127.0.0.1");
3063 if (flags
& DNS_OPTION_SEARCH
&& (!global_search_state
|| global_search_state
->num_domains
== 0)) {
3064 search_set_from_hostname();
3075 /* Add multiple nameservers from a space-or-comma-separated list. */
3077 evdns_nameserver_ip_add_line(const char *ips
) {
3082 while (ISSPACE(*ips
) || *ips
== ',' || *ips
== '\t')
3085 while (ISDIGIT(*ips
) || *ips
== '.' || *ips
== ':' || *ips
== '[' || *ips
== ']')
3087 buf
= mm_malloc(ips
-addr
+1);
3089 memcpy(buf
, addr
, ips
-addr
);
3090 buf
[ips
-addr
] = '\0';
3091 r
= evdns_nameserver_ip_add(buf
);
3098 typedef DWORD(WINAPI
*GetNetworkParams_fn_t
)(FIXED_INFO
*, DWORD
*);
3100 /* Use the windows GetNetworkParams interface in iphlpapi.dll to */
3101 /* figure out what our nameservers are. */
3103 load_nameservers_with_getnetworkparams(void)
3105 /* Based on MSDN examples and inspection of c-ares code. */
3108 ULONG size
= sizeof(FIXED_INFO
);
3110 int status
= 0, r
, added_any
;
3112 GetNetworkParams_fn_t fn
;
3114 /* XXXX Possibly, we should hardcode the location of this DLL. */
3115 if (!(handle
= LoadLibrary("iphlpapi.dll"))) {
3116 log(EVDNS_LOG_WARN
, "Could not open iphlpapi.dll");
3117 /* right now status = 0, doesn't that mean "good" - mikec */
3121 if (!(fn
= (GetNetworkParams_fn_t
) GetProcAddress(handle
, "GetNetworkParams"))) {
3122 log(EVDNS_LOG_WARN
, "Could not get address of function.");
3128 buf
= mm_malloc(size
);
3129 if (!buf
) { status
= 4; goto done
; }
3131 r
= fn(fixed
, &size
);
3132 if (r
!= ERROR_SUCCESS
&& r
!= ERROR_BUFFER_OVERFLOW
) {
3136 if (r
!= ERROR_SUCCESS
) {
3138 buf
= mm_malloc(size
);
3139 if (!buf
) { status
= 4; goto done
; }
3141 r
= fn(fixed
, &size
);
3142 if (r
!= ERROR_SUCCESS
) {
3143 log(EVDNS_LOG_DEBUG
, "fn() failed.");
3151 ns
= &(fixed
->DnsServerList
);
3153 r
= evdns_nameserver_ip_add_line(ns
->IpAddress
.String
);
3155 log(EVDNS_LOG_DEBUG
,"Could not add nameserver %s to list, "
3156 "error: %d; status: %d",
3157 (ns
->IpAddress
.String
),(int)GetLastError(), r
);
3160 log(EVDNS_LOG_DEBUG
,"Successfully added %s as nameserver",ns
->IpAddress
.String
);
3168 log(EVDNS_LOG_DEBUG
, "No nameservers added.");
3179 FreeLibrary(handle
);
3184 config_nameserver_from_reg_key(HKEY key
, const char *subkey
)
3187 DWORD bufsz
= 0, type
= 0;
3190 if (RegQueryValueEx(key
, subkey
, 0, &type
, NULL
, &bufsz
)
3193 if (!(buf
= mm_malloc(bufsz
)))
3196 if (RegQueryValueEx(key
, subkey
, 0, &type
, (LPBYTE
)buf
, &bufsz
)
3197 == ERROR_SUCCESS
&& bufsz
> 1) {
3198 status
= evdns_nameserver_ip_add_line(buf
);
3205 #define SERVICES_KEY "System\\CurrentControlSet\\Services\\"
3206 #define WIN_NS_9X_KEY SERVICES_KEY "VxD\\MSTCP"
3207 #define WIN_NS_NT_KEY SERVICES_KEY "Tcpip\\Parameters"
3210 load_nameservers_from_registry(void)
3214 #define TRY(k, name) \
3215 if (!found && config_nameserver_from_reg_key(k,name) == 0) { \
3216 log(EVDNS_LOG_DEBUG,"Found nameservers in %s/%s",#k,name); \
3218 } else if (!found) { \
3219 log(EVDNS_LOG_DEBUG,"Didn't find nameservers in %s/%s", \
3223 if (((int)GetVersion()) > 0) { /* NT */
3224 HKEY nt_key
= 0, interfaces_key
= 0;
3226 if (RegOpenKeyEx(HKEY_LOCAL_MACHINE
, WIN_NS_NT_KEY
, 0,
3227 KEY_READ
, &nt_key
) != ERROR_SUCCESS
) {
3228 log(EVDNS_LOG_DEBUG
,"Couldn't open nt key, %d",(int)GetLastError());
3231 r
= RegOpenKeyEx(nt_key
, "Interfaces", 0,
3232 KEY_QUERY_VALUE
|KEY_ENUMERATE_SUB_KEYS
,
3234 if (r
!= ERROR_SUCCESS
) {
3235 log(EVDNS_LOG_DEBUG
,"Couldn't open interfaces key, %d",(int)GetLastError());
3238 TRY(nt_key
, "NameServer");
3239 TRY(nt_key
, "DhcpNameServer");
3240 TRY(interfaces_key
, "NameServer");
3241 TRY(interfaces_key
, "DhcpNameServer");
3242 RegCloseKey(interfaces_key
);
3243 RegCloseKey(nt_key
);
3246 if (RegOpenKeyEx(HKEY_LOCAL_MACHINE
, WIN_NS_9X_KEY
, 0,
3247 KEY_READ
, &win_key
) != ERROR_SUCCESS
) {
3248 log(EVDNS_LOG_DEBUG
, "Couldn't open registry key, %d", (int)GetLastError());
3251 TRY(win_key
, "NameServer");
3252 RegCloseKey(win_key
);
3256 log(EVDNS_LOG_WARN
,"Didn't find any nameservers.");
3259 return found
? 0 : -1;
3264 evdns_config_windows_nameservers(void)
3266 if (load_nameservers_with_getnetworkparams() == 0)
3268 return load_nameservers_from_registry();
3277 evdns_config_windows_nameservers();
3279 res
= evdns_resolv_conf_parse(DNS_OPTIONS_ALL
, "/etc/resolv.conf");
3286 evdns_err_to_string(int err
)
3289 case DNS_ERR_NONE
: return "no error";
3290 case DNS_ERR_FORMAT
: return "misformatted query";
3291 case DNS_ERR_SERVERFAILED
: return "server failed";
3292 case DNS_ERR_NOTEXIST
: return "name does not exist";
3293 case DNS_ERR_NOTIMPL
: return "query not implemented";
3294 case DNS_ERR_REFUSED
: return "refused";
3296 case DNS_ERR_TRUNCATED
: return "reply truncated or ill-formed";
3297 case DNS_ERR_UNKNOWN
: return "unknown";
3298 case DNS_ERR_TIMEOUT
: return "request timed out";
3299 case DNS_ERR_SHUTDOWN
: return "dns subsystem shut down";
3300 default: return "[Unknown error code]";
3305 evdns_shutdown(int fail_requests
)
3307 struct nameserver
*server
, *server_next
;
3308 struct search_domain
*dom
, *dom_next
;
3312 reply_callback(req_head
, 0, DNS_ERR_SHUTDOWN
, NULL
);
3313 request_finished(req_head
, &req_head
);
3315 while (req_waiting_head
) {
3317 reply_callback(req_waiting_head
, 0, DNS_ERR_SHUTDOWN
, NULL
);
3318 request_finished(req_waiting_head
, &req_waiting_head
);
3320 global_requests_inflight
= global_requests_waiting
= 0;
3322 for (server
= server_head
; server
; server
= server_next
) {
3323 server_next
= server
->next
;
3324 if (server
->socket
>= 0)
3325 CLOSE_SOCKET(server
->socket
);
3326 (void) event_del(&server
->event
);
3327 del_timeout_event(server
);
3330 if (server_next
== server_head
)
3334 global_good_nameservers
= 0;
3336 if (global_search_state
) {
3337 for (dom
= global_search_state
->head
; dom
; dom
= dom_next
) {
3338 dom_next
= dom
->next
;
3342 CLEAR(global_search_state
);
3343 mm_free(global_search_state
);
3344 global_search_state
= NULL
;
3346 evdns_log_fn
= NULL
;
3351 main_callback(int result
, char type
, int count
, int ttl
,
3352 void *addrs
, void *orig
) {
3353 char *n
= (char*)orig
;
3355 for (i
= 0; i
< count
; ++i
) {
3356 if (type
== DNS_IPv4_A
) {
3357 printf("%s: %s\n", n
, debug_ntoa(((u32
*)addrs
)[i
]));
3358 } else if (type
== DNS_PTR
) {
3359 printf("%s: %s\n", n
, ((char**)addrs
)[i
]);
3363 printf("%s: No answer (%d)\n", n
, result
);
3368 evdns_server_callback(struct evdns_server_request
*req
, void *data
)
3372 /* dummy; give 192.168.11.11 as an answer for all A questions,
3373 * give foo.bar.example.com as an answer for all PTR questions. */
3374 for (i
= 0; i
< req
->nquestions
; ++i
) {
3375 u32 ans
= htonl(0xc0a80b0bUL
);
3376 if (req
->questions
[i
]->type
== EVDNS_TYPE_A
&&
3377 req
->questions
[i
]->dns_question_class
== EVDNS_CLASS_INET
) {
3378 printf(" -- replying for %s (A)\n", req
->questions
[i
]->name
);
3379 r
= evdns_server_request_add_a_reply(req
, req
->questions
[i
]->name
,
3382 printf("eeep, didn't work.\n");
3383 } else if (req
->questions
[i
]->type
== EVDNS_TYPE_PTR
&&
3384 req
->questions
[i
]->dns_question_class
== EVDNS_CLASS_INET
) {
3385 printf(" -- replying for %s (PTR)\n", req
->questions
[i
]->name
);
3386 r
= evdns_server_request_add_ptr_reply(req
, NULL
, req
->questions
[i
]->name
,
3387 "foo.bar.example.com", 10);
3389 printf(" -- skipping %s [%d %d]\n", req
->questions
[i
]->name
,
3390 req
->questions
[i
]->type
, req
->questions
[i
]->dns_question_class
);
3394 r
= evdns_server_request_respond(req
, 0);
3396 printf("eeek, couldn't send reply.\n");
3400 logfn(int is_warn
, const char *msg
) {
3402 fprintf(stderr
, "%s\n", msg
);
3405 main(int c
, char **v
) {
3407 int reverse
= 0, verbose
= 1, servertest
= 0;
3409 fprintf(stderr
, "syntax: %s [-x] [-v] hostname\n", v
[0]);
3410 fprintf(stderr
, "syntax: %s [-servertest]\n", v
[0]);
3414 while (idx
< c
&& v
[idx
][0] == '-') {
3415 if (!strcmp(v
[idx
], "-x"))
3417 else if (!strcmp(v
[idx
], "-v"))
3419 else if (!strcmp(v
[idx
], "-servertest"))
3422 fprintf(stderr
, "Unknown option %s\n", v
[idx
]);
3427 evdns_set_log_fn(logfn
);
3428 evdns_resolv_conf_parse(DNS_OPTION_NAMESERVERS
, "/etc/resolv.conf");
3431 struct sockaddr_in my_addr
;
3432 sock
= socket(PF_INET
, SOCK_DGRAM
, 0);
3433 fcntl(sock
, F_SETFL
, O_NONBLOCK
);
3434 my_addr
.sin_family
= AF_INET
;
3435 my_addr
.sin_port
= htons(10053);
3436 my_addr
.sin_addr
.s_addr
= INADDR_ANY
;
3437 if (bind(sock
, (struct sockaddr
*)&my_addr
, sizeof(my_addr
))<0) {
3441 evdns_add_server_port(sock
, 0, evdns_server_callback
, NULL
);
3443 for (; idx
< c
; ++idx
) {
3445 struct in_addr addr
;
3446 if (!inet_aton(v
[idx
], &addr
)) {
3447 fprintf(stderr
, "Skipping non-IP %s\n", v
[idx
]);
3450 fprintf(stderr
, "resolving %s...\n",v
[idx
]);
3451 evdns_resolve_reverse(&addr
, 0, main_callback
, v
[idx
]);
3453 fprintf(stderr
, "resolving (fwd) %s...\n",v
[idx
]);
3454 evdns_resolve_ipv4(v
[idx
], 0, main_callback
, v
[idx
]);
3463 /* Local Variables: */
3465 /* c-basic-offset: 4 */
3466 /* indent-tabs-mode: t */