blib/lib/AnyEvent/DNS.pm untested

filter: Statementstmt 0.0% 0 / 464 Branchbran 0.0% 0 / 126 Conditioncond 0.0% 0 / 108 MC/DCmcdc 0.0% 0 / 63 Subroutinesub 0.0% 0 / 51 Podpod 0.0% 0 / 39 totaltotal 0.0% 0 / 851 CC 63 SCAR 36.7
CC
63
Cov
0%
parse_resolv_conf
132.0
os_config
110.0
resolve
72.0
CRAP 39.2
1 =head1 NAME
2  
3 AnyEvent::DNS - fully asynchronous DNS resolution
4  
5 =head1 SYNOPSIS
6  
7 use AnyEvent::DNS;
8
9 my $cv = AnyEvent->condvar;
10 AnyEvent::DNS::a "www.google.de", $cv;
11 # ... later
12 my @addrs = $cv->recv;
13  
14 =head1 DESCRIPTION
15  
16 This module offers both a number of DNS convenience functions as well
17 as a fully asynchronous and high-performance pure-perl stub resolver.
18  
19 The stub resolver supports DNS over IPv4 and IPv6, UDP and TCP, optional
20 EDNS0 support for up to 4kiB datagrams and automatically falls back to
21 virtual circuit mode for large responses.
22  
23 =head2 CONVENIENCE FUNCTIONS
24  
25 =over 4
26  
27 =cut
28  
29 package AnyEvent::DNS;
30  
31 use Carp ();
32 use Socket qw(AF_INET SOCK_DGRAM SOCK_STREAM);
33  
34 use AnyEvent (); BEGIN { AnyEvent::common_sense }
35 use AnyEvent::Util qw(AF_INET6);
36  
37 our $VERSION = $AnyEvent::VERSION;
38  
39 # some public dns servers
40 our @DNS_FALLBACK = (
41 (v8.8.8.8, v8.8.4.4)[rand 2], # google public dns
42 (v209.244.0.3, v209.244.0.4)[rand 2], # level3
43 (v4.2.2.1, v4.2.2.3, v4.2.2.4, v4.2.2.5, v4.2.2.6)[rand 4], # vnsc-pri.sys.gtei.net
44 );
45 push @DNS_FALLBACK, splice @DNS_FALLBACK, rand $_, 1 for reverse 1..@DNS_FALLBACK;
46  
47 =item AnyEvent::DNS::a $domain, $cb->(@addrs)
48  
49 Tries to resolve the given domain to IPv4 address(es).
50  
51 =item AnyEvent::DNS::aaaa $domain, $cb->(@addrs)
52  
53 Tries to resolve the given domain to IPv6 address(es).
54  
55 =item AnyEvent::DNS::mx $domain, $cb->(@hostnames)
56  
57 Tries to resolve the given domain into a sorted (lower preference value
58 first) list of domain names.
59  
60 =item AnyEvent::DNS::ns $domain, $cb->(@hostnames)
61  
62 Tries to resolve the given domain name into a list of name servers.
63  
64 =item AnyEvent::DNS::txt $domain, $cb->(@hostnames)
65  
66 Tries to resolve the given domain name into a list of text records.
67  
68 =item AnyEvent::DNS::srv $service, $proto, $domain, $cb->(@srv_rr)
69  
70 Tries to resolve the given service, protocol and domain name into a list
71 of service records.
72  
73 Each C<$srv_rr> is an array reference with the following contents:
74 C<[$priority, $weight, $transport, $target]>.
75  
76 They will be sorted with lowest priority first, then randomly
77 distributed by weight as per RFC 2782.
78  
79 Example:
80  
81 AnyEvent::DNS::srv "sip", "udp", "schmorp.de", sub { ...
82 # @_ = ( [10, 10, 5060, "sip1.schmorp.de" ] )
83  
84 =item AnyEvent::DNS::ptr $domain, $cb->(@hostnames)
85  
86 Tries to make a PTR lookup on the given domain. See C<reverse_lookup>
87 and C<reverse_verify> if you want to resolve an IP address to a hostname
88 instead.
89  
90 =item AnyEvent::DNS::any $domain, $cb->(@rrs)
91  
92 Tries to resolve the given domain and passes all resource records found to
93 the callback.
94  
95 =item AnyEvent::DNS::reverse_lookup $ipv4_or_6, $cb->(@hostnames)
96  
97 Tries to reverse-resolve the given IPv4 or IPv6 address (in textual form)
98 into it's hostname(s). Handles V4MAPPED and V4COMPAT IPv6 addresses
99 transparently.
100  
101 =item AnyEvent::DNS::reverse_verify $ipv4_or_6, $cb->(@hostnames)
102  
103 The same as C<reverse_lookup>, but does forward-lookups to verify that
104 the resolved hostnames indeed point to the address, which makes spoofing
105 harder.
106  
107 If you want to resolve an address into a hostname, this is the preferred
108 method: The DNS records could still change, but at least this function
109 verified that the hostname, at one point in the past, pointed at the IP
110 address you originally resolved.
111  
112 Example:
113  
114 AnyEvent::DNS::ptr "2001:500:2f::f", sub { print shift };
115 # => f.root-servers.net
116  
117 =cut
118  
119 sub MAX_PKT() { 4096 } # max packet size we advertise and accept
120  
121 sub DOMAIN_PORT() { 53 } # if this changes drop me a note
122  
123 sub resolver ();
124  
125 sub a($$) {
126 my ($domain, $cb) = @_;
127  
128 resolver->resolve ($domain => "a", sub {
129 $cb->(map $_->[3], @_);
130 });
131 }
132  
133 sub aaaa($$) {
134 my ($domain, $cb) = @_;
135  
136 resolver->resolve ($domain => "aaaa", sub {
137 $cb->(map $_->[3], @_);
138 });
139 }
140  
141 sub mx($$) {
142 my ($domain, $cb) = @_;
143  
144 resolver->resolve ($domain => "mx", sub {
145 $cb->(map $_->[4], sort { $a->[3] <=> $b->[3] } @_);
146 });
147 }
148  
149 sub ns($$) {
150 my ($domain, $cb) = @_;
151  
152 resolver->resolve ($domain => "ns", sub {
153 $cb->(map $_->[3], @_);
154 });
155 }
156  
157 sub txt($$) {
158 my ($domain, $cb) = @_;
159  
160 resolver->resolve ($domain => "txt", sub {
161 $cb->(map $_->[3], @_);
162 });
163 }
164  
165 sub srv($$$$) {
166 my ($service, $proto, $domain, $cb) = @_;
167  
168 # todo, ask for any and check glue records
169 resolver->resolve ("_$service._$proto.$domain" => "srv", sub {
170 my @res;
171  
172 # classify by priority
173 my %pri;
174 push @{ $pri{$_->[3]} }, [ @$_[3,4,5,6] ]
175 for @_;
176  
177 # order by priority
178 for my $pri (sort { $a <=> $b } keys %pri) {
179 # order by weight
180 my @rr = sort { $a->[1] <=> $b->[1] } @{ delete $pri{$pri} };
181  
182 my $sum; $sum += $_->[1] for @rr;
183  
184 while (@rr) {
185 my $w = int rand $sum + 1;
186 for (0 .. $#rr) {
187 if (($w -= $rr[$_][1]) <= 0) {
188 $sum -= $rr[$_][1];
189 push @res, splice @rr, $_, 1, ();
190 last;
191 }
192 }
193 }
194 }
195  
196 $cb->(@res);
197 });
198 }
199  
200 sub ptr($$) {
201 my ($domain, $cb) = @_;
202  
203 resolver->resolve ($domain => "ptr", sub {
204 $cb->(map $_->[3], @_);
205 });
206 }
207  
208 sub any($$) {
209 my ($domain, $cb) = @_;
210  
211 resolver->resolve ($domain => "*", $cb);
212 }
213  
214 # convert textual ip address into reverse lookup form
215 sub _munge_ptr($) {
216 my $ipn = $_[0]
217 or return;
218  
219 my $ptr;
220  
221 my $af = AnyEvent::Socket::address_family ($ipn);
222  
223 if ($af == AF_INET6) {
224 $ipn = substr $ipn, 0, 16; # anticipate future expansion
225  
226 # handle v4mapped and v4compat
227 if ($ipn =~ s/^\x00{10}(?:\xff\xff|\x00\x00)//) {
228 $af = AF_INET;
229 } else {
230 $ptr = join ".", (reverse split //, unpack "H32", $ipn), "ip6.arpa.";
231 }
232 }
233  
234 if ($af == AF_INET) {
235 $ptr = join ".", (reverse unpack "C4", $ipn), "in-addr.arpa.";
236 }
237  
238 $ptr
239 }
240  
241 sub reverse_lookup($$) {
242 my ($ip, $cb) = @_;
243  
244 $ip = _munge_ptr AnyEvent::Socket::parse_address ($ip)
245 or return $cb->();
246  
247 resolver->resolve ($ip => "ptr", sub {
248 $cb->(map $_->[3], @_);
249 });
250 }
251  
252 sub reverse_verify($$) {
253 my ($ip, $cb) = @_;
254
255 my $ipn = AnyEvent::Socket::parse_address ($ip)
256 or return $cb->();
257  
258 my $af = AnyEvent::Socket::address_family ($ipn);
259  
260 my @res;
261 my $cnt;
262  
263 my $ptr = _munge_ptr $ipn
264 or return $cb->();
265  
266 $ip = AnyEvent::Socket::format_address ($ipn); # normalise into the same form
267  
268 ptr $ptr, sub {
269 for my $name (@_) {
270 ++$cnt;
271
272 # () around AF_INET to work around bug in 5.8
273 resolver->resolve ("$name." => ($af == (AF_INET) ? "a" : "aaaa"), sub {
274 for (@_) {
275 push @res, $name
276 if $_->[3] eq $ip;
277 }
278 $cb->(@res) unless --$cnt;
279 });
280 }
281  
282 $cb->() unless $cnt;
283 };
284 }
285  
286 #################################################################################
287  
288 =back
289  
290 =head2 LOW-LEVEL DNS EN-/DECODING FUNCTIONS
291  
292 =over 4
293  
294 =item $AnyEvent::DNS::EDNS0
295  
296 This variable decides whether dns_pack automatically enables EDNS0
297 support. By default, this is disabled (C<0>), unless overridden by
298 C<$ENV{PERL_ANYEVENT_EDNS0}>, but when set to C<1>, AnyEvent::DNS will use
299 EDNS0 in all requests.
300  
301 =cut
302  
303 our $EDNS0 = $ENV{PERL_ANYEVENT_EDNS0}*1; # set to 1 to enable (partial) edns0
304  
305 our %opcode_id = (
306 query => 0,
307 iquery => 1,
308 status => 2,
309 notify => 4,
310 update => 5,
311 map +($_ => $_), 3, 6..15
312 );
313  
314 our %opcode_str = reverse %opcode_id;
315  
316 our %rcode_id = (
317 noerror => 0,
318 formerr => 1,
319 servfail => 2,
320 nxdomain => 3,
321 notimp => 4,
322 refused => 5,
323 yxdomain => 6, # Name Exists when it should not [RFC 2136]
324 yxrrset => 7, # RR Set Exists when it should not [RFC 2136]
325 nxrrset => 8, # RR Set that should exist does not [RFC 2136]
326 notauth => 9, # Server Not Authoritative for zone [RFC 2136]
327 notzone => 10, # Name not contained in zone [RFC 2136]
328 # EDNS0 16 BADVERS Bad OPT Version [RFC 2671]
329 # EDNS0 16 BADSIG TSIG Signature Failure [RFC 2845]
330 # EDNS0 17 BADKEY Key not recognized [RFC 2845]
331 # EDNS0 18 BADTIME Signature out of time window [RFC 2845]
332 # EDNS0 19 BADMODE Bad TKEY Mode [RFC 2930]
333 # EDNS0 20 BADNAME Duplicate key name [RFC 2930]
334 # EDNS0 21 BADALG Algorithm not supported [RFC 2930]
335 map +($_ => $_), 11..15
336 );
337  
338 our %rcode_str = reverse %rcode_id;
339  
340 our %type_id = (
341 a => 1,
342 ns => 2,
343 md => 3,
344 mf => 4,
345 cname => 5,
346 soa => 6,
347 mb => 7,
348 mg => 8,
349 mr => 9,
350 null => 10,
351 wks => 11,
352 ptr => 12,
353 hinfo => 13,
354 minfo => 14,
355 mx => 15,
356 txt => 16,
357 aaaa => 28,
358 srv => 33,
359 naptr => 35, # rfc2915
360 dname => 39, # rfc2672
361 opt => 41,
362 spf => 99,
363 tkey => 249,
364 tsig => 250,
365 ixfr => 251,
366 axfr => 252,
367 mailb => 253,
368 "*" => 255,
369 );
370  
371 our %type_str = reverse %type_id;
372  
373 our %class_id = (
374 in => 1,
375 ch => 3,
376 hs => 4,
377 none => 254,
378 "*" => 255,
379 );
380  
381 our %class_str = reverse %class_id;
382  
383 sub _enc_name($) {
384 pack "(C/a*)*", (split /\./, shift), ""
385 }
386  
387 if ($] < 5.008) {
388 # special slower 5.6 version
389 *_enc_name = sub ($) {
390 join "", map +(pack "C/a*", $_), (split /\./, shift), ""
391 };
392 }
393  
394 sub _enc_qd() {
395 (_enc_name $_->[0]) . pack "nn",
396 ($_->[1] > 0 ? $_->[1] : $type_id {$_->[1]}),
397 ($_->[2] > 0 ? $_->[2] : $class_id{$_->[2] || "in"})
398 }
399  
400 sub _enc_rr() {
401 die "encoding of resource records is not supported";
402 }
403  
404 =item $pkt = AnyEvent::DNS::dns_pack $dns
405  
406 Packs a perl data structure into a DNS packet. Reading RFC 1035 is strongly
407 recommended, then everything will be totally clear. Or maybe not.
408  
409 Resource records are not yet encodable.
410  
411 Examples:
412  
413 # very simple request, using lots of default values:
414 { rd => 1, qd => [ [ "host.domain", "a"] ] }
415
416 # more complex example, showing how flags etc. are named:
417
418 {
419 id => 10000,
420 op => "query",
421 rc => "nxdomain",
422
423 # flags
424 qr => 1,
425 aa => 0,
426 tc => 0,
427 rd => 0,
428 ra => 0,
429 ad => 0,
430 cd => 0,
431
432 qd => [@rr], # query section
433 an => [@rr], # answer section
434 ns => [@rr], # authority section
435 ar => [@rr], # additional records section
436 }
437  
438 =cut
439  
440 sub dns_pack($) {
441 my ($req) = @_;
442  
443 pack "nn nnnn a* a* a* a* a*",
444 $req->{id},
445  
446 ! !$req->{qr} * 0x8000
447 + $opcode_id{$req->{op}} * 0x0800
448 + ! !$req->{aa} * 0x0400
449 + ! !$req->{tc} * 0x0200
450 + ! !$req->{rd} * 0x0100
451 + ! !$req->{ra} * 0x0080
452 + ! !$req->{ad} * 0x0020
453 + ! !$req->{cd} * 0x0010
454 + $rcode_id{$req->{rc}} * 0x0001,
455  
456 scalar @{ $req->{qd} || [] },
457 scalar @{ $req->{an} || [] },
458 scalar @{ $req->{ns} || [] },
459 $EDNS0 + scalar @{ $req->{ar} || [] }, # EDNS0 option included here
460  
461 (join "", map _enc_qd, @{ $req->{qd} || [] }),
462 (join "", map _enc_rr, @{ $req->{an} || [] }),
463 (join "", map _enc_rr, @{ $req->{ns} || [] }),
464 (join "", map _enc_rr, @{ $req->{ar} || [] }),
465  
466 ($EDNS0 ? pack "C nnNn", 0, 41, MAX_PKT, 0, 0 : "") # EDNS0 option
467 }
468  
469 our $ofs;
470 our $pkt;
471  
472 # bitches
473 sub _dec_name {
474 my @res;
475 my $redir;
476 my $ptr = $ofs;
477 my $cnt;
478  
479 while () {
480 return undef if ++$cnt >= 256; # to avoid DoS attacks
481  
482 my $len = ord substr $pkt, $ptr++, 1;
483  
484 if ($len >= 0xc0) {
485 $ptr++;
486 $ofs = $ptr if $ptr > $ofs;
487 $ptr = (unpack "n", substr $pkt, $ptr - 2, 2) & 0x3fff;
488 } elsif ($len) {
489 push @res, substr $pkt, $ptr, $len;
490 $ptr += $len;
491 } else {
492 $ofs = $ptr if $ptr > $ofs;
493 return join ".", @res;
494 }
495 }
496 }
497  
498 sub _dec_qd {
499 my $qname = _dec_name;
500 my ($qt, $qc) = unpack "nn", substr $pkt, $ofs; $ofs += 4;
501 [$qname, $type_str{$qt} || $qt, $class_str{$qc} || $qc]
502 }
503  
504 our %dec_rr = (
505 1 => sub { join ".", unpack "C4", $_ }, # a
506 2 => sub { local $ofs = $ofs - length; _dec_name }, # ns
507 5 => sub { local $ofs = $ofs - length; _dec_name }, # cname
508 6 => sub {
509 local $ofs = $ofs - length;
510 my $mname = _dec_name;
511 my $rname = _dec_name;
512 ($mname, $rname, unpack "NNNNN", substr $pkt, $ofs)
513 }, # soa
514 11 => sub { ((join ".", unpack "C4", $_), unpack "C a*", substr $_, 4) }, # wks
515 12 => sub { local $ofs = $ofs - length; _dec_name }, # ptr
516 13 => sub { unpack "C/a* C/a*", $_ }, # hinfo
517 15 => sub { local $ofs = $ofs + 2 - length; ((unpack "n", $_), _dec_name) }, # mx
518 16 => sub { unpack "(C/a*)*", $_ }, # txt
519 28 => sub { AnyEvent::Socket::format_ipv6 ($_) }, # aaaa
520 33 => sub { local $ofs = $ofs + 6 - length; ((unpack "nnn", $_), _dec_name) }, # srv
521 35 => sub { # naptr
522 # requires perl 5.10, sorry
523 my ($order, $preference, $flags, $service, $regexp, $offset) = unpack "nn C/a* C/a* C/a* .", $_;
524 local $ofs = $ofs + $offset - length;
525 ($order, $preference, $flags, $service, $regexp, _dec_name)
526 },
527 39 => sub { local $ofs = $ofs - length; _dec_name }, # dname
528 99 => sub { unpack "(C/a*)*", $_ }, # spf
529 );
530  
531 sub _dec_rr {
532 my $name = _dec_name;
533  
534 my ($rt, $rc, $ttl, $rdlen) = unpack "nn N n", substr $pkt, $ofs; $ofs += 10;
535 local $_ = substr $pkt, $ofs, $rdlen; $ofs += $rdlen;
536  
537 [
538 $name,
539 $type_str{$rt} || $rt,
540 $class_str{$rc} || $rc,
541 ($dec_rr{$rt} || sub { $_ })->(),
542 ]
543 }
544  
545 =item $dns = AnyEvent::DNS::dns_unpack $pkt
546  
547 Unpacks a DNS packet into a perl data structure.
548  
549 Examples:
550  
551 # an unsuccessful reply
552 {
553 'qd' => [
554 [ 'ruth.plan9.de.mach.uni-karlsruhe.de', '*', 'in' ]
555 ],
556 'rc' => 'nxdomain',
557 'ar' => [],
558 'ns' => [
559 [
560 'uni-karlsruhe.de',
561 'soa',
562 'in',
563 'netserv.rz.uni-karlsruhe.de',
564 'hostmaster.rz.uni-karlsruhe.de',
565 2008052201, 10800, 1800, 2592000, 86400
566 ]
567 ],
568 'tc' => '',
569 'ra' => 1,
570 'qr' => 1,
571 'id' => 45915,
572 'aa' => '',
573 'an' => [],
574 'rd' => 1,
575 'op' => 'query'
576 }
577
578 # a successful reply
579
580 {
581 'qd' => [ [ 'www.google.de', 'a', 'in' ] ],
582 'rc' => 0,
583 'ar' => [
584 [ 'a.l.google.com', 'a', 'in', '209.85.139.9' ],
585 [ 'b.l.google.com', 'a', 'in', '64.233.179.9' ],
586 [ 'c.l.google.com', 'a', 'in', '64.233.161.9' ],
587 ],
588 'ns' => [
589 [ 'l.google.com', 'ns', 'in', 'a.l.google.com' ],
590 [ 'l.google.com', 'ns', 'in', 'b.l.google.com' ],
591 ],
592 'tc' => '',
593 'ra' => 1,
594 'qr' => 1,
595 'id' => 64265,
596 'aa' => '',
597 'an' => [
598 [ 'www.google.de', 'cname', 'in', 'www.google.com' ],
599 [ 'www.google.com', 'cname', 'in', 'www.l.google.com' ],
600 [ 'www.l.google.com', 'a', 'in', '66.249.93.104' ],
601 [ 'www.l.google.com', 'a', 'in', '66.249.93.147' ],
602 ],
603 'rd' => 1,
604 'op' => 0
605 }
606  
607 =cut
608  
609 sub dns_unpack($) {
610 local $pkt = shift;
611 my ($id, $flags, $qd, $an, $ns, $ar)
612 = unpack "nn nnnn A*", $pkt;
613  
614 local $ofs = 6 * 2;
615  
616 {
617 id => $id,
618 qr => ! ! ($flags & 0x8000),
619 aa => ! ! ($flags & 0x0400),
620 tc => ! ! ($flags & 0x0200),
621 rd => ! ! ($flags & 0x0100),
622 ra => ! ! ($flags & 0x0080),
623 ad => ! ! ($flags & 0x0020),
624 cd => ! ! ($flags & 0x0010),
625 op => $opcode_str{($flags & 0x001e) >> 11},
626 rc => $rcode_str{($flags & 0x000f)},
627  
628 qd => [map _dec_qd, 1 .. $qd],
629 an => [map _dec_rr, 1 .. $an],
630 ns => [map _dec_rr, 1 .. $ns],
631 ar => [map _dec_rr, 1 .. $ar],
632 }
633 }
634  
635 #############################################################################
636  
637 =back
638  
639 =head2 THE AnyEvent::DNS RESOLVER CLASS
640  
641 This is the class which does the actual protocol work.
642  
643 =over 4
644  
645 =cut
646  
647 use Carp ();
648 use Scalar::Util ();
649 use Socket ();
650  
651 our $NOW;
652  
653 =item AnyEvent::DNS::resolver
654  
655 This function creates and returns a resolver that is ready to use and
656 should mimic the default resolver for your system as good as possible.
657  
658 It only ever creates one resolver and returns this one on subsequent
659 calls.
660  
661 Unless you have special needs, prefer this function over creating your own
662 resolver object.
663  
664 The resolver is created with the following parameters:
665  
666 untaint enabled
667 max_outstanding $ENV{PERL_ANYEVENT_MAX_OUTSTANDING_DNS}
668  
669 C<os_config> will be used for OS-specific configuration, unless
670 C<$ENV{PERL_ANYEVENT_RESOLV_CONF}> is specified, in which case that file
671 gets parsed.
672  
673 =cut
674  
675 our $RESOLVER;
676  
677 sub resolver() {
678 $RESOLVER || do {
679 $RESOLVER = new AnyEvent::DNS
680 untaint => 1,
681 exists $ENV{PERL_ANYEVENT_MAX_OUTSTANDING_DNS}
682 ? (max_outstanding => $ENV{PERL_ANYEVENT_MAX_OUTSTANDING_DNS}*1 || 1) : (),
683 ;
684  
685 exists $ENV{PERL_ANYEVENT_RESOLV_CONF}
686 ? length $ENV{PERL_ANYEVENT_RESOLV_CONF} && $RESOLVER->_parse_resolv_conf_file ($ENV{PERL_ANYEVENT_RESOLV_CONF})
687 : $RESOLVER->os_config;
688  
689 $RESOLVER
690 }
691 }
692  
693 =item $resolver = new AnyEvent::DNS key => value...
694  
695 Creates and returns a new resolver.
696  
697 The following options are supported:
698  
699 =over 4
700  
701 =item server => [...]
702  
703 A list of server addresses (default: C<v127.0.0.1>) in network format
704 (i.e. as returned by C<AnyEvent::Socket::parse_address> - both IPv4 and
705 IPv6 are supported).
706  
707 =item timeout => [...]
708  
709 A list of timeouts to use (also determines the number of retries). To make
710 three retries with individual time-outs of 2, 5 and 5 seconds, use C<[2,
711 5, 5]>, which is also the default.
712  
713 =item search => [...]
714  
715 The default search list of suffixes to append to a domain name (default: none).
716  
717 =item ndots => $integer
718  
719 The number of dots (default: C<1>) that a name must have so that the resolver
720 tries to resolve the name without any suffixes first.
721  
722 =item max_outstanding => $integer
723  
724 Most name servers do not handle many parallel requests very well. This
725 option limits the number of outstanding requests to C<$integer>
726 (default: C<10>), that means if you request more than this many requests,
727 then the additional requests will be queued until some other requests have
728 been resolved.
729  
730 =item reuse => $seconds
731  
732 The number of seconds (default: C<300>) that a query id cannot be re-used
733 after a timeout. If there was no time-out then query ids can be reused
734 immediately.
735  
736 =item untaint => $boolean
737  
738 When true, then the resolver will automatically untaint results, and might
739 also ignore certain environment variables.
740  
741 =back
742  
743 =cut
744  
745 sub new {
746 my ($class, %arg) = @_;
747  
748 my $self = bless {
749 server => [],
750 timeout => [2, 5, 5],
751 search => [],
752 ndots => 1,
753 max_outstanding => 10,
754 reuse => 300,
755 %arg,
756 reuse_q => [],
757 }, $class;
758  
759 # search should default to gethostname's domain
760 # but perl lacks a good posix module
761  
762 # try to create an ipv4 and an ipv6 socket
763 # only fail when we cannot create either
764 my $got_socket;
765  
766 Scalar::Util::weaken (my $wself = $self);
767  
768 if (socket my $fh4, AF_INET , Socket::SOCK_DGRAM(), 0) {
769 ++$got_socket;
770  
771 AnyEvent::Util::fh_nonblocking $fh4, 1;
772 $self->{fh4} = $fh4;
773 $self->{rw4} = AE::io $fh4, 0, sub {
774 if (my $peer = recv $fh4, my $pkt, MAX_PKT, 0) {
775 $wself->_recv ($pkt, $peer);
776 }
777 };
778 }
779  
780 if (AF_INET6 && socket my $fh6, AF_INET6, Socket::SOCK_DGRAM(), 0) {
781 ++$got_socket;
782  
783 $self->{fh6} = $fh6;
784 AnyEvent::Util::fh_nonblocking $fh6, 1;
785 $self->{rw6} = AE::io $fh6, 0, sub {
786 if (my $peer = recv $fh6, my $pkt, MAX_PKT, 0) {
787 $wself->_recv ($pkt, $peer);
788 }
789 };
790 }
791  
792 $got_socket
793 or Carp::croak "unable to create either an IPv4 or an IPv6 socket";
794  
795 $self->_compile;
796  
797 $self
798 }
799  
800 =item $resolver->parse_resolv_conf ($string)
801  
802 Parses the given string as if it were a F<resolv.conf> file. The following
803 directives are supported (but not necessarily implemented).
804  
805 C<#>-style comments, C<nameserver>, C<domain>, C<search>, C<sortlist>,
806 C<options> (C<timeout>, C<attempts>, C<ndots>).
807  
808 Everything else is silently ignored.
809  
810 =cut
811  
812 sub parse_resolv_conf {
813 my ($self, $resolvconf) = @_;
814  
815 $self->{server} = [];
816 $self->{search} = [];
817  
818 my $attempts;
819  
820 for (split /\n/, $resolvconf) {
821 s/#.*$//; # not quite legal, but many people insist
822  
823 if (/^\s*nameserver\s+(\S+)\s*$/i) {
824 my $ip = $1;
825 if (my $ipn = AnyEvent::Socket::parse_address ($ip)) {
826 push @{ $self->{server} }, $ipn;
827 } else {
828 warn "nameserver $ip invalid and ignored\n";
829 }
830 } elsif (/^\s*domain\s+(\S*)\s+$/i) {
831 $self->{search} = [$1];
832 } elsif (/^\s*search\s+(.*?)\s*$/i) {
833 $self->{search} = [split /\s+/, $1];
834 } elsif (/^\s*sortlist\s+(.*?)\s*$/i) {
835 # ignored, NYI
836 } elsif (/^\s*options\s+(.*?)\s*$/i) {
837 for (split /\s+/, $1) {
838 if (/^timeout:(\d+)$/) {
839 $self->{timeout} = [$1];
840 } elsif (/^attempts:(\d+)$/) {
841 $attempts = $1;
842 } elsif (/^ndots:(\d+)$/) {
843 $self->{ndots} = $1;
844 } else {
845 # debug, rotate, no-check-names, inet6
846 }
847 }
848 }
849 }
850  
851 $self->{timeout} = [($self->{timeout}[0]) x $attempts]
852 if $attempts;
853  
854 $self->_compile;
855 }
856  
857 sub _parse_resolv_conf_file {
858 my ($self, $resolv_conf) = @_;
859  
860 open my $fh, "<", $resolv_conf
861 or Carp::croak "$resolv_conf: $!";
862  
863 local $/;
864 $self->parse_resolv_conf (<$fh>);
865 }
866  
867 =item $resolver->os_config
868  
869 Tries so load and parse F</etc/resolv.conf> on portable operating
870 systems. Tries various egregious hacks on windows to force the DNS servers
871 and searchlist out of the system.
872  
873 =cut
874  
875 sub os_config {
876 my ($self) = @_;
877  
878 $self->{server} = [];
879 $self->{search} = [];
880  
881 if ((AnyEvent::WIN32 || $^O =~ /cygwin/i)) {
882 no strict 'refs';
883  
884 # there are many options to find the current nameservers etc. on windows
885 # all of them don't work consistently:
886 # - the registry thing needs separate code on win32 native vs. cygwin
887 # - the registry layout differs between windows versions
888 # - calling windows api functions doesn't work on cygwin
889 # - ipconfig uses locale-specific messages
890  
891 # we use Net::DNS::Resolver first, and if it fails, will fall back to
892 # ipconfig parsing.
893 unless (eval {
894 # Net::DNS::Resolver uses a LOT of ram (~10mb), but what can we do :/
895 # (this seems mostly to be due to Win32::API).
896 require Net::DNS::Resolver;
897 my $r = Net::DNS::Resolver->new;
898  
899 $r->nameservers
900 or die;
901  
902 for my $s ($r->nameservers) {
903 if (my $ipn = AnyEvent::Socket::parse_address ($s)) {
904 push @{ $self->{server} }, $ipn;
905 }
906 }
907 $self->{search} = [$r->searchlist];
908  
909 1
910 }) {
911 # we use ipconfig parsing because, despite all its brokenness,
912 # it seems most stable in practise.
913 # unfortunately it wants a console window.
914 # for good measure, we append a fallback nameserver to our list.
915  
916 if (open my $fh, "ipconfig /all |") {
917 # parsing strategy: we go through the output and look for
918 # :-lines with DNS in them. everything in those is regarded as
919 # either a nameserver (if it parses as an ip address), or a suffix
920 # (all else).
921  
922 my $dns;
923 local $_;
924 while (<$fh>) {
925 if (s/^\s.*\bdns\b.*://i) {
926 $dns = 1;
927 } elsif (/^\S/ || /^\s[^:]{16,}: /) {
928 $dns = 0;
929 }
930 if ($dns && /^\s*(\S+)\s*$/) {
931 my $s = $1;
932 $s =~ s/%\d+(?!\S)//; # get rid of ipv6 scope id
933 if (my $ipn = AnyEvent::Socket::parse_address ($s)) {
934 push @{ $self->{server} }, $ipn;
935 } else {
936 push @{ $self->{search} }, $s;
937 }
938 }
939 }
940 }
941 }
942  
943 # always add the fallback servers
944 push @{ $self->{server} }, @DNS_FALLBACK;
945  
946 $self->_compile;
947 } else {
948 # try resolv.conf everywhere else
949  
950 $self->_parse_resolv_conf_file ("/etc/resolv.conf")
951 if -e "/etc/resolv.conf";
952 }
953 }
954  
955 =item $resolver->timeout ($timeout, ...)
956  
957 Sets the timeout values. See the C<timeout> constructor argument (and note
958 that this method uses the values itself, not an array-reference).
959  
960 =cut
961  
962 sub timeout {
963 my ($self, @timeout) = @_;
964  
965 $self->{timeout} = \@timeout;
966 $self->_compile;
967 }
968  
969 =item $resolver->max_outstanding ($nrequests)
970  
971 Sets the maximum number of outstanding requests to C<$nrequests>. See the
972 C<max_outstanding> constructor argument.
973  
974 =cut
975  
976 sub max_outstanding {
977 my ($self, $max) = @_;
978  
979 $self->{max_outstanding} = $max;
980 $self->_scheduler;
981 }
982  
983 sub _compile {
984 my $self = shift;
985  
986 my %search; $self->{search} = [grep 0 < length, grep !$search{$_}++, @{ $self->{search} }];
987 my %server; $self->{server} = [grep 0 < length, grep !$server{$_}++, @{ $self->{server} }];
988  
989 unless (@{ $self->{server} }) {
990 # use 127.0.0.1 by default, and one opendns nameserver as fallback
991 $self->{server} = [v127.0.0.1, $DNS_FALLBACK[rand @DNS_FALLBACK]];
992 }
993  
994 my @retry;
995  
996 for my $timeout (@{ $self->{timeout} }) {
997 for my $server (@{ $self->{server} }) {
998 push @retry, [$server, $timeout];
999 }
1000 }
1001  
1002 $self->{retry} = \@retry;
1003 }
1004  
1005 sub _feed {
1006 my ($self, $res) = @_;
1007  
1008 ($res) = $res =~ /^(.*)$/s
1009 if AnyEvent::TAINT && $self->{untaint};
1010  
1011 $res = dns_unpack $res
1012 or return;
1013  
1014 my $id = $self->{id}{$res->{id}};
1015  
1016 return unless ref $id;
1017  
1018 $NOW = time;
1019 $id->[1]->($res);
1020 }
1021  
1022 sub _recv {
1023 my ($self, $pkt, $peer) = @_;
1024  
1025 # we ignore errors (often one gets port unreachable, but there is
1026 # no good way to take advantage of that.
1027  
1028 my ($port, $host) = AnyEvent::Socket::unpack_sockaddr ($peer);
1029  
1030 return unless $port == 53 && grep $_ eq $host, @{ $self->{server} };
1031  
1032 $self->_feed ($pkt);
1033 }
1034  
1035 sub _free_id {
1036 my ($self, $id, $timeout) = @_;
1037  
1038 if ($timeout) {
1039 # we need to block the id for a while
1040 $self->{id}{$id} = 1;
1041 push @{ $self->{reuse_q} }, [$NOW + $self->{reuse}, $id];
1042 } else {
1043 # we can quickly recycle the id
1044 delete $self->{id}{$id};
1045 }
1046  
1047 --$self->{outstanding};
1048 $self->_scheduler;
1049 }
1050  
1051 # execute a single request, involves sending it with timeouts to multiple servers
1052 sub _exec {
1053 my ($self, $req) = @_;
1054  
1055 my $retry; # of retries
1056 my $do_retry;
1057  
1058 $do_retry = sub {
1059 my $retry_cfg = $self->{retry}[$retry++]
1060 or do {
1061 # failure
1062 $self->_free_id ($req->[2], $retry > 1);
1063 undef $do_retry; return $req->[1]->();
1064 };
1065  
1066 my ($server, $timeout) = @$retry_cfg;
1067
1068 $self->{id}{$req->[2]} = [(AE::timer $timeout, 0, sub {
1069 $NOW = time;
1070  
1071 # timeout, try next
1072 &$do_retry if $do_retry;
1073 }), sub {
1074 my ($res) = @_;
1075  
1076 if ($res->{tc}) {
1077 # success, but truncated, so use tcp
1078 AnyEvent::Socket::tcp_connect (AnyEvent::Socket::format_address ($server), DOMAIN_PORT, sub {
1079 return unless $do_retry; # some other request could have invalidated us already
1080  
1081 my ($fh) = @_
1082 or return &$do_retry;
1083  
1084 require AnyEvent::Handle;
1085  
1086 my $handle; $handle = new AnyEvent::Handle
1087 fh => $fh,
1088 timeout => $timeout,
1089 on_error => sub {
1090 undef $handle;
1091 return unless $do_retry; # some other request could have invalidated us already
1092 # failure, try next
1093 &$do_retry;
1094 };
1095  
1096 $handle->push_write (pack "n/a*", $req->[0]);
1097 $handle->push_read (chunk => 2, sub {
1098 $handle->unshift_read (chunk => (unpack "n", $_[1]), sub {
1099 undef $handle;
1100 $self->_feed ($_[1]);
1101 });
1102 });
1103  
1104 }, sub { $timeout });
1105  
1106 } else {
1107 # success
1108 $self->_free_id ($req->[2], $retry > 1);
1109 undef $do_retry; return $req->[1]->($res);
1110 }
1111 }];
1112
1113 my $sa = AnyEvent::Socket::pack_sockaddr (DOMAIN_PORT, $server);
1114  
1115 my $fh = AF_INET == AnyEvent::Socket::sockaddr_family ($sa)
1116 ? $self->{fh4} : $self->{fh6}
1117 or return &$do_retry;
1118  
1119 send $fh, $req->[0], 0, $sa;
1120 };
1121  
1122 &$do_retry;
1123 }
1124  
1125 sub _scheduler {
1126 my ($self) = @_;
1127  
1128 no strict 'refs';
1129  
1130 $NOW = time;
1131  
1132 # first clear id reuse queue
1133 delete $self->{id}{ (shift @{ $self->{reuse_q} })->[1] }
1134 while @{ $self->{reuse_q} } && $self->{reuse_q}[0][0] <= $NOW;
1135  
1136 while ($self->{outstanding} < $self->{max_outstanding}) {
1137  
1138 if (@{ $self->{reuse_q} } >= 30000) {
1139 # we ran out of ID's, wait a bit
1140 $self->{reuse_to} ||= AE::timer $self->{reuse_q}[0][0] - $NOW, 0, sub {
1141 delete $self->{reuse_to};
1142 $self->_scheduler;
1143 };
1144 last;
1145 }
1146  
1147 if (my $req = shift @{ $self->{queue} }) {
1148 # found a request in the queue, execute it
1149 while () {
1150 $req->[2] = int rand 65536;
1151 last unless exists $self->{id}{$req->[2]};
1152 }
1153  
1154 ++$self->{outstanding};
1155 $self->{id}{$req->[2]} = 1;
1156 substr $req->[0], 0, 2, pack "n", $req->[2];
1157  
1158 $self->_exec ($req);
1159  
1160 } elsif (my $cb = shift @{ $self->{wait} }) {
1161 # found a wait_for_slot callback, call that one first
1162 $cb->($self);
1163  
1164 } else {
1165 # nothing to do, just exit
1166 last;
1167 }
1168 }
1169 }
1170  
1171 =item $resolver->request ($req, $cb->($res))
1172  
1173 This is the main low-level workhorse for sending DNS requests.
1174  
1175 This function sends a single request (a hash-ref formated as specified
1176 for C<dns_pack>) to the configured nameservers in turn until it gets a
1177 response. It handles timeouts, retries and automatically falls back to
1178 virtual circuit mode (TCP) when it receives a truncated reply.
1179  
1180 Calls the callback with the decoded response packet if a reply was
1181 received, or no arguments in case none of the servers answered.
1182  
1183 =cut
1184  
1185 sub request($$) {
1186 my ($self, $req, $cb) = @_;
1187  
1188 push @{ $self->{queue} }, [dns_pack $req, $cb];
1189 $self->_scheduler;
1190 }
1191  
1192 =item $resolver->resolve ($qname, $qtype, %options, $cb->(@rr))
1193  
1194 Queries the DNS for the given domain name C<$qname> of type C<$qtype>.
1195  
1196 A C<$qtype> is either a numerical query type (e.g. C<1> for A records) or
1197 a lowercase name (you have to look at the source to see which aliases are
1198 supported, but all types from RFC 1035, C<aaaa>, C<srv>, C<spf> and a few
1199 more are known to this module). A C<$qtype> of "*" is supported and means
1200 "any" record type.
1201  
1202 The callback will be invoked with a list of matching result records or
1203 none on any error or if the name could not be found.
1204  
1205 CNAME chains (although illegal) are followed up to a length of 10.
1206  
1207 The callback will be invoked with arraryefs of the form C<[$name, $type,
1208 $class, @data>], where C<$name> is the domain name, C<$type> a type string
1209 or number, C<$class> a class name and @data is resource-record-dependent
1210 data. For C<a> records, this will be the textual IPv4 addresses, for C<ns>
1211 or C<cname> records this will be a domain name, for C<txt> records these
1212 are all the strings and so on.
1213  
1214 All types mentioned in RFC 1035, C<aaaa>, C<srv>, C<naptr> and C<spf> are
1215 decoded. All resource records not known to this module will have
1216 the raw C<rdata> field as fourth entry.
1217  
1218 Note that this resolver is just a stub resolver: it requires a name server
1219 supporting recursive queries, will not do any recursive queries itself and
1220 is not secure when used against an untrusted name server.
1221  
1222 The following options are supported:
1223  
1224 =over 4
1225  
1226 =item search => [$suffix...]
1227  
1228 Use the given search list (which might be empty), by appending each one
1229 in turn to the C<$qname>. If this option is missing then the configured
1230 C<ndots> and C<search> values define its value (depending on C<ndots>, the
1231 empty suffix will be prepended or appended to that C<search> value). If
1232 the C<$qname> ends in a dot, then the searchlist will be ignored.
1233  
1234 =item accept => [$type...]
1235  
1236 Lists the acceptable result types: only result types in this set will be
1237 accepted and returned. The default includes the C<$qtype> and nothing
1238 else. If this list includes C<cname>, then CNAME-chains will not be
1239 followed (because you asked for the CNAME record).
1240  
1241 =item class => "class"
1242  
1243 Specify the query class ("in" for internet, "ch" for chaosnet and "hs" for
1244 hesiod are the only ones making sense). The default is "in", of course.
1245  
1246 =back
1247  
1248 Examples:
1249  
1250 # full example, you can paste this into perl:
1251 use Data::Dumper;
1252 use AnyEvent::DNS;
1253 AnyEvent::DNS::resolver->resolve (
1254 "google.com", "*", my $cv = AnyEvent->condvar);
1255 warn Dumper [$cv->recv];
1256  
1257 # shortened result:
1258 # [
1259 # [ 'google.com', 'soa', 'in', 'ns1.google.com', 'dns-admin.google.com',
1260 # 2008052701, 7200, 1800, 1209600, 300 ],
1261 # [
1262 # 'google.com', 'txt', 'in',
1263 # 'v=spf1 include:_netblocks.google.com ~all'
1264 # ],
1265 # [ 'google.com', 'a', 'in', '64.233.187.99' ],
1266 # [ 'google.com', 'mx', 'in', 10, 'smtp2.google.com' ],
1267 # [ 'google.com', 'ns', 'in', 'ns2.google.com' ],
1268 # ]
1269  
1270 # resolve a records:
1271 $res->resolve ("ruth.plan9.de", "a", sub { warn Dumper [@_] });
1272  
1273 # result:
1274 # [
1275 # [ 'ruth.schmorp.de', 'a', 'in', '129.13.162.95' ]
1276 # ]
1277  
1278 # resolve any records, but return only a and aaaa records:
1279 $res->resolve ("test1.laendle", "*",
1280 accept => ["a", "aaaa"],
1281 sub {
1282 warn Dumper [@_];
1283 }
1284 );
1285  
1286 # result:
1287 # [
1288 # [ 'test1.laendle', 'a', 'in', '10.0.0.255' ],
1289 # [ 'test1.laendle', 'aaaa', 'in', '3ffe:1900:4545:0002:0240:0000:0000:f7e1' ]
1290 # ]
1291  
1292 =cut
1293  
1294 sub resolve($%) {
1295 my $cb = pop;
1296 my ($self, $qname, $qtype, %opt) = @_;
1297  
1298 my @search = $qname =~ s/\.$//
1299 ? ""
1300 : $opt{search}
1301 ? @{ $opt{search} }
1302 : ($qname =~ y/.//) >= $self->{ndots}
1303 ? ("", @{ $self->{search} })
1304 : (@{ $self->{search} }, "");
1305  
1306 my $class = $opt{class} || "in";
1307  
1308 my %atype = $opt{accept}
1309 ? map +($_ => 1), @{ $opt{accept} }
1310 : ($qtype => 1);
1311  
1312 # advance in searchlist
1313 my ($do_search, $do_req);
1314
1315 $do_search = sub {
1316 @search
1317 or (undef $do_search), (undef $do_req), return $cb->();
1318  
1319 (my $name = lc "$qname." . shift @search) =~ s/\.$//;
1320 my $depth = 10;
1321  
1322 # advance in cname-chain
1323 $do_req = sub {
1324 $self->request ({
1325 rd => 1,
1326 qd => [[$name, $qtype, $class]],
1327 }, sub {
1328 my ($res) = @_
1329 or return $do_search->();
1330  
1331 my $cname;
1332  
1333 while () {
1334 # results found?
1335 my @rr = grep $name eq lc $_->[0] && ($atype{"*"} || $atype{$_->[1]}), @{ $res->{an} };
1336  
1337 (undef $do_search), (undef $do_req), return $cb->(@rr)
1338 if @rr;
1339  
1340 # see if there is a cname we can follow
1341 my @rr = grep $name eq lc $_->[0] && $_->[1] eq "cname", @{ $res->{an} };
1342  
1343 if (@rr) {
1344 $depth--
1345 or return $do_search->(); # cname chain too long
1346  
1347 $cname = 1;
1348 $name = lc $rr[0][3];
1349  
1350 } elsif ($cname) {
1351 # follow the cname
1352 return $do_req->();
1353  
1354 } else {
1355 # no, not found anything
1356 return $do_search->();
1357 }
1358 }
1359 });
1360 };
1361  
1362 $do_req->();
1363 };
1364  
1365 $do_search->();
1366 }
1367  
1368 =item $resolver->wait_for_slot ($cb->($resolver))
1369  
1370 Wait until a free request slot is available and call the callback with the
1371 resolver object.
1372  
1373 A request slot is used each time a request is actually sent to the
1374 nameservers: There are never more than C<max_outstanding> of them.
1375  
1376 Although you can submit more requests (they will simply be queued until
1377 a request slot becomes available), sometimes, usually for rate-limiting
1378 purposes, it is useful to instead wait for a slot before generating the
1379 request (or simply to know when the request load is low enough so one can
1380 submit requests again).
1381  
1382 This is what this method does: The callback will be called when submitting
1383 a DNS request will not result in that request being queued. The callback
1384 may or may not generate any requests in response.
1385  
1386 Note that the callback will only be invoked when the request queue is
1387 empty, so this does not play well if somebody else keeps the request queue
1388 full at all times.
1389  
1390 =cut
1391  
1392 sub wait_for_slot {
1393 my ($self, $cb) = @_;
1394  
1395 push @{ $self->{wait} }, $cb;
1396 $self->_scheduler;
1397 }
1398  
1399 use AnyEvent::Socket (); # circular dependency, so do not import anything and do it at the end
1400  
1401 1;
1402  
1403 =back
1404  
1405 =head1 AUTHOR
1406  
1407 Marc Lehmann <schmorp@schmorp.de>
1408 http://home.schmorp.de/
1409  
1410 =cut
1411