1AnyEvent::DNS(3)      User Contributed Perl Documentation     AnyEvent::DNS(3)
2
3
4

NAME

6       AnyEvent::DNS - fully asynchronous DNS resolution
7

SYNOPSIS

9          use AnyEvent::DNS;
10
11          my $cv = AnyEvent->condvar;
12          AnyEvent::DNS::a "www.google.de", $cv;
13          # ... later
14          my @addrs = $cv->recv;
15

DESCRIPTION

17       This module offers both a number of DNS convenience functions as well
18       as a fully asynchronous and high-performance pure-perl stub resolver.
19
20       The stub resolver supports DNS over IPv4 and IPv6, UDP and TCP,
21       optional EDNS0 support for up to 4kiB datagrams and automatically falls
22       back to virtual circuit mode for large responses.
23
24   CONVENIENCE FUNCTIONS
25       AnyEvent::DNS::a $domain, $cb->(@addrs)
26           Tries to resolve the given domain to IPv4 address(es).
27
28       AnyEvent::DNS::aaaa $domain, $cb->(@addrs)
29           Tries to resolve the given domain to IPv6 address(es).
30
31       AnyEvent::DNS::mx $domain, $cb->(@hostnames)
32           Tries to resolve the given domain into a sorted (lower preference
33           value first) list of domain names.
34
35       AnyEvent::DNS::ns $domain, $cb->(@hostnames)
36           Tries to resolve the given domain name into a list of name servers.
37
38       AnyEvent::DNS::txt $domain, $cb->(@hostnames)
39           Tries to resolve the given domain name into a list of text records.
40           Only the first text string per record will be returned. If you want
41           all strings, you need to call the resolver manually:
42
43              resolver->resolve ($domain => "txt", sub {
44                 for my $record (@_) {
45                    my (undef, undef, undef, @txt) = @$record;
46                    # strings now in @txt
47                 }
48              });
49
50       AnyEvent::DNS::srv $service, $proto, $domain, $cb->(@srv_rr)
51           Tries to resolve the given service, protocol and domain name into a
52           list of service records.
53
54           Each $srv_rr is an array reference with the following contents:
55           "[$priority, $weight, $transport, $target]".
56
57           They will be sorted with lowest priority first, then randomly
58           distributed by weight as per RFC 2782.
59
60           Example:
61
62              AnyEvent::DNS::srv "sip", "udp", "schmorp.de", sub { ...
63              # @_ = ( [10, 10, 5060, "sip1.schmorp.de" ] )
64
65       AnyEvent::DNS::any $domain, $cb->(@rrs)
66           Tries to resolve the given domain and passes all resource records
67           found to the callback.
68
69       AnyEvent::DNS::ptr $domain, $cb->(@hostnames)
70           Tries to make a PTR lookup on the given domain. See
71           "reverse_lookup" and "reverse_verify" if you want to resolve an IP
72           address to a hostname instead.
73
74       AnyEvent::DNS::reverse_lookup $ipv4_or_6, $cb->(@hostnames)
75           Tries to reverse-resolve the given IPv4 or IPv6 address (in textual
76           form) into its hostname(s). Handles V4MAPPED and V4COMPAT IPv6
77           addresses transparently.
78
79       AnyEvent::DNS::reverse_verify $ipv4_or_6, $cb->(@hostnames)
80           The same as "reverse_lookup", but does forward-lookups to verify
81           that the resolved hostnames indeed point to the address, which
82           makes spoofing harder.
83
84           If you want to resolve an address into a hostname, this is the
85           preferred method: The DNS records could still change, but at least
86           this function verified that the hostname, at one point in the past,
87           pointed at the IP address you originally resolved.
88
89           Example:
90
91              AnyEvent::DNS::reverse_verify "2001:500:2f::f", sub { print shift };
92              # => f.root-servers.net
93
94   LOW-LEVEL DNS EN-/DECODING FUNCTIONS
95       $AnyEvent::DNS::EDNS0
96           This variable decides whether dns_pack automatically enables EDNS0
97           support. By default, this is disabled (0), unless overridden by
98           $ENV{PERL_ANYEVENT_EDNS0}, but when set to 1, AnyEvent::DNS will
99           use EDNS0 in all requests.
100
101       $pkt = AnyEvent::DNS::dns_pack $dns
102           Packs a perl data structure into a DNS packet. Reading RFC 1035 is
103           strongly recommended, then everything will be totally clear. Or
104           maybe not.
105
106           Resource records are not yet encodable.
107
108           Examples:
109
110              # very simple request, using lots of default values:
111              { rd => 1, qd => [ [ "host.domain", "a"] ] }
112
113              # more complex example, showing how flags etc. are named:
114
115              {
116                 id => 10000,
117                 op => "query",
118                 rc => "nxdomain",
119
120                 # flags
121                 qr => 1,
122                 aa => 0,
123                 tc => 0,
124                 rd => 0,
125                 ra => 0,
126                 ad => 0,
127                 cd => 0,
128
129                 qd => [@rr], # query section
130                 an => [@rr], # answer section
131                 ns => [@rr], # authority section
132                 ar => [@rr], # additional records section
133              }
134
135       $dns = AnyEvent::DNS::dns_unpack $pkt
136           Unpacks a DNS packet into a perl data structure.
137
138           Examples:
139
140              # an unsuccessful reply
141              {
142                'qd' => [
143                          [ 'ruth.plan9.de.mach.uni-karlsruhe.de', '*', 'in' ]
144                        ],
145                'rc' => 'nxdomain',
146                'ar' => [],
147                'ns' => [
148                          [
149                            'uni-karlsruhe.de',
150                            'soa',
151                            'in',
152                            600,
153                            'netserv.rz.uni-karlsruhe.de',
154                            'hostmaster.rz.uni-karlsruhe.de',
155                            2008052201, 10800, 1800, 2592000, 86400
156                          ]
157                        ],
158                'tc' => '',
159                'ra' => 1,
160                'qr' => 1,
161                'id' => 45915,
162                'aa' => '',
163                'an' => [],
164                'rd' => 1,
165                'op' => 'query',
166                '__' => '<original dns packet>',
167              }
168
169              # a successful reply
170
171              {
172                'qd' => [ [ 'www.google.de', 'a', 'in' ] ],
173                'rc' => 0,
174                'ar' => [
175                          [ 'a.l.google.com', 'a', 'in', 3600, '209.85.139.9' ],
176                          [ 'b.l.google.com', 'a', 'in', 3600, '64.233.179.9' ],
177                          [ 'c.l.google.com', 'a', 'in', 3600, '64.233.161.9' ],
178                        ],
179                'ns' => [
180                          [ 'l.google.com', 'ns', 'in', 3600, 'a.l.google.com' ],
181                          [ 'l.google.com', 'ns', 'in', 3600, 'b.l.google.com' ],
182                        ],
183                'tc' => '',
184                'ra' => 1,
185                'qr' => 1,
186                'id' => 64265,
187                'aa' => '',
188                'an' => [
189                          [ 'www.google.de', 'cname', 'in', 3600, 'www.google.com' ],
190                          [ 'www.google.com', 'cname', 'in', 3600, 'www.l.google.com' ],
191                          [ 'www.l.google.com', 'a', 'in', 3600, '66.249.93.104' ],
192                          [ 'www.l.google.com', 'a', 'in', 3600, '66.249.93.147' ],
193                        ],
194                'rd' => 1,
195                'op' => 0,
196                '__' => '<original dns packet>',
197              }
198
199       Extending DNS Encoder and Decoder
200
201       This section describes an experimental method to extend the DNS encoder
202       and decoder with new opcode, rcode, class and type strings, as well as
203       resource record decoders.
204
205       Since this is experimental, it can change, as anything can change, but
206       this interface is expe ctedc to be relatively stable and was stable
207       during the whole existance of "AnyEvent::DNS" so far.
208
209       Note that, since changing the decoder or encoder might break existing
210       code, you should either be sure to control for this, or only
211       temporarily change these values, e.g. like so:
212
213          my $decoded = do {
214             local $AnyEvent::DNS::opcode_str{7} = "yxrrset";
215             AnyEvent::DNS::dns_unpack $mypkt
216          };
217
218       %AnyEvent::DNS::opcode_id, %AnyEvent::DNS::opcode_str
219           Two hashes that map lowercase opcode strings to numerical id's (For
220           the encoder), or vice versa (for the decoder). Example: add a new
221           opcode string "notzone".
222
223              $AnyEvent::DNS::opcode_id{notzone} = 10;
224              $AnyEvent::DNS::opcode_str{10} = 'notzone';
225
226       %AnyEvent::DNS::rcode_id, %AnyEvent::DNS::rcode_str
227           Same as above, for for rcode values.
228
229       %AnyEvent::DNS::class_id, %AnyEvent::DNS::class_str
230           Same as above, but for resource record class names/values.
231
232       %AnyEvent::DNS::type_id, %AnyEvent::DNS::type_str
233           Same as above, but for resource record type names/values.
234
235       %AnyEvent::DNS::dec_rr
236           This hash maps resource record type values to code references. When
237           decoding, they are called with $_ set to the undecoded data portion
238           and $ofs being the current byte offset. of the record. You should
239           have a look at the existing implementations to understand how it
240           works in detail, but here are two examples:
241
242           Decode an A record. A records are simply four bytes with one byte
243           per address component, so the decoder simply unpacks them and joins
244           them with dots in between:
245
246              $AnyEvent::DNS::dec_rr{1} = sub { join ".", unpack "C4", $_ };
247
248           Decode a CNAME record, which contains a potentially compressed
249           domain name.
250
251              package AnyEvent::DNS; # for %dec_rr, $ofsd and &_dec_name
252              $dec_rr{5} = sub { local $ofs = $ofs - length; _dec_name };
253
254   THE AnyEvent::DNS RESOLVER CLASS
255       This is the class which does the actual protocol work.
256
257       AnyEvent::DNS::resolver
258           This function creates and returns a resolver that is ready to use
259           and should mimic the default resolver for your system as good as
260           possible. It is used by AnyEvent itself as well.
261
262           It only ever creates one resolver and returns this one on
263           subsequent calls - see $AnyEvent::DNS::RESOLVER, below, for
264           details.
265
266           Unless you have special needs, prefer this function over creating
267           your own resolver object.
268
269           The resolver is created with the following parameters:
270
271              untaint          enabled
272              max_outstanding  $ENV{PERL_ANYEVENT_MAX_OUTSTANDING_DNS} (default 10)
273
274           "os_config" will be used for OS-specific configuration, unless
275           $ENV{PERL_ANYEVENT_RESOLV_CONF} is specified, in which case that
276           file gets parsed.
277
278       $AnyEvent::DNS::RESOLVER
279           This variable stores the default resolver returned by
280           "AnyEvent::DNS::resolver", or "undef" when the default resolver
281           hasn't been instantiated yet.
282
283           One can provide a custom resolver (e.g. one with caching
284           functionality) by storing it in this variable, causing all
285           subsequent resolves done via "AnyEvent::DNS::resolver" to be done
286           via the custom one.
287
288       $resolver = new AnyEvent::DNS key => value...
289           Creates and returns a new resolver.
290
291           The following options are supported:
292
293           server => [...]
294               A list of server addresses (default: "v127.0.0.1" or "::1") in
295               network format (i.e. as returned by
296               "AnyEvent::Socket::parse_address" - both IPv4 and IPv6 are
297               supported).
298
299           timeout => [...]
300               A list of timeouts to use (also determines the number of
301               retries). To make three retries with individual time-outs of 2,
302               5 and 5 seconds, use "[2, 5, 5]", which is also the default.
303
304           search => [...]
305               The default search list of suffixes to append to a domain name
306               (default: none).
307
308           ndots => $integer
309               The number of dots (default: 1) that a name must have so that
310               the resolver tries to resolve the name without any suffixes
311               first.
312
313           max_outstanding => $integer
314               Most name servers do not handle many parallel requests very
315               well. This option limits the number of outstanding requests to
316               $integer (default: 10), that means if you request more than
317               this many requests, then the additional requests will be queued
318               until some other requests have been resolved.
319
320           reuse => $seconds
321               The number of seconds (default: 300) that a query id cannot be
322               re-used after a timeout. If there was no time-out then query
323               ids can be reused immediately.
324
325           untaint => $boolean
326               When true, then the resolver will automatically untaint
327               results, and might also ignore certain environment variables.
328
329       $resolver->parse_resolv_conf ($string)
330           Parses the given string as if it were a resolv.conf file. The
331           following directives are supported (but not necessarily
332           implemented).
333
334           "#"- and ";"-style comments, "nameserver", "domain", "search",
335           "sortlist", "options" ("timeout", "attempts", "ndots").
336
337           Everything else is silently ignored.
338
339       $resolver->os_config
340           Tries so load and parse /etc/resolv.conf on portable operating
341           systems. Tries various egregious hacks on windows to force the DNS
342           servers and searchlist out of the system.
343
344           This method must be called at most once before trying to resolve
345           anything.
346
347       $resolver->timeout ($timeout, ...)
348           Sets the timeout values. See the "timeout" constructor argument
349           (and note that this method expects the timeout values themselves,
350           not an array-reference).
351
352       $resolver->max_outstanding ($nrequests)
353           Sets the maximum number of outstanding requests to $nrequests. See
354           the "max_outstanding" constructor argument.
355
356       $resolver->request ($req, $cb->($res))
357           This is the main low-level workhorse for sending DNS requests.
358
359           This function sends a single request (a hash-ref formated as
360           specified for "dns_pack") to the configured nameservers in turn
361           until it gets a response. It handles timeouts, retries and
362           automatically falls back to virtual circuit mode (TCP) when it
363           receives a truncated reply. It does not handle anything else, such
364           as the domain searchlist or relative names - use "->resolve" for
365           that.
366
367           Calls the callback with the decoded response packet if a reply was
368           received, or no arguments in case none of the servers answered.
369
370       $resolver->resolve ($qname, $qtype, %options, $cb->(@rr))
371           Queries the DNS for the given domain name $qname of type $qtype.
372
373           A $qtype is either a numerical query type (e.g. 1 for A records) or
374           a lowercase name (you have to look at the source to see which
375           aliases are supported, but all types from RFC 1035, "aaaa", "srv",
376           "spf" and a few more are known to this module). A $qtype of "*" is
377           supported and means "any" record type.
378
379           The callback will be invoked with a list of matching result records
380           or none on any error or if the name could not be found.
381
382           CNAME chains (although illegal) are followed up to a length of 10.
383
384           The callback will be invoked with arraryefs of the form "[$name,
385           $type, $class, $ttl, @data"], where $name is the domain name, $type
386           a type string or number, $class a class name, $ttl is the remaining
387           time-to-live and @data is resource-record-dependent data, in
388           seconds. For "a" records, this will be the textual IPv4 addresses,
389           for "ns" or "cname" records this will be a domain name, for "txt"
390           records these are all the strings and so on.
391
392           All types mentioned in RFC 1035, "aaaa", "srv", "naptr" and "spf"
393           are decoded. All resource records not known to this module will
394           have the raw "rdata" field as fifth array element.
395
396           Note that this resolver is just a stub resolver: it requires a name
397           server supporting recursive queries, will not do any recursive
398           queries itself and is not secure when used against an untrusted
399           name server.
400
401           The following options are supported:
402
403           search => [$suffix...]
404               Use the given search list (which might be empty), by appending
405               each one in turn to the $qname. If this option is missing then
406               the configured "ndots" and "search" values define its value
407               (depending on "ndots", the empty suffix will be prepended or
408               appended to that "search" value). If the $qname ends in a dot,
409               then the searchlist will be ignored.
410
411           accept => [$type...]
412               Lists the acceptable result types: only result types in this
413               set will be accepted and returned. The default includes the
414               $qtype and nothing else. If this list includes "cname", then
415               CNAME-chains will not be followed (because you asked for the
416               CNAME record).
417
418           class => "class"
419               Specify the query class ("in" for internet, "ch" for chaosnet
420               and "hs" for hesiod are the only ones making sense). The
421               default is "in", of course.
422
423           Examples:
424
425              # full example, you can paste this into perl:
426              use Data::Dumper;
427              use AnyEvent::DNS;
428              AnyEvent::DNS::resolver->resolve (
429                 "google.com", "*", my $cv = AnyEvent->condvar);
430              warn Dumper [$cv->recv];
431
432              # shortened result:
433              # [
434              #   [ 'google.com', 'soa', 'in', 3600, 'ns1.google.com', 'dns-admin.google.com',
435              #     2008052701, 7200, 1800, 1209600, 300 ],
436              #   [
437              #     'google.com', 'txt', 'in', 3600,
438              #     'v=spf1 include:_netblocks.google.com ~all'
439              #   ],
440              #   [ 'google.com', 'a', 'in', 3600, '64.233.187.99' ],
441              #   [ 'google.com', 'mx', 'in', 3600, 10, 'smtp2.google.com' ],
442              #   [ 'google.com', 'ns', 'in', 3600, 'ns2.google.com' ],
443              # ]
444
445              # resolve a records:
446              $res->resolve ("ruth.plan9.de", "a", sub { warn Dumper [@_] });
447
448              # result:
449              # [
450              #   [ 'ruth.schmorp.de', 'a', 'in', 86400, '129.13.162.95' ]
451              # ]
452
453              # resolve any records, but return only a and aaaa records:
454              $res->resolve ("test1.laendle", "*",
455                 accept => ["a", "aaaa"],
456                 sub {
457                    warn Dumper [@_];
458                 }
459              );
460
461              # result:
462              # [
463              #   [ 'test1.laendle', 'a', 'in', 86400, '10.0.0.255' ],
464              #   [ 'test1.laendle', 'aaaa', 'in', 60, '3ffe:1900:4545:0002:0240:0000:0000:f7e1' ]
465              # ]
466
467       $resolver->wait_for_slot ($cb->($resolver))
468           Wait until a free request slot is available and call the callback
469           with the resolver object.
470
471           A request slot is used each time a request is actually sent to the
472           nameservers: There are never more than "max_outstanding" of them.
473
474           Although you can submit more requests (they will simply be queued
475           until a request slot becomes available), sometimes, usually for
476           rate-limiting purposes, it is useful to instead wait for a slot
477           before generating the request (or simply to know when the request
478           load is low enough so one can submit requests again).
479
480           This is what this method does: The callback will be called when
481           submitting a DNS request will not result in that request being
482           queued. The callback may or may not generate any requests in
483           response.
484
485           Note that the callback will only be invoked when the request queue
486           is empty, so this does not play well if somebody else keeps the
487           request queue full at all times.
488

AUTHOR

490          Marc Lehmann <schmorp@schmorp.de>
491          http://anyevent.schmorp.de
492
493
494
495perl v5.28.1                      2019-02-26                  AnyEvent::DNS(3)
Impressum