1 # Copyright (C) 2003-2007, 2009, 2010 Nominum, Inc.
3 # Permission to use, copy, modify, and distribute this software and its
4 # documentation for any purpose with or without fee is hereby granted,
5 # provided that the above copyright notice and this permission notice
6 # appear in all copies.
8 # THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES
9 # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10 # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR
11 # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12 # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13 # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
14 # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
18 @var default_resolver: The default resolver object
19 @type default_resolver: dns.resolver.Resolver object"""
33 if sys
.platform
== 'win32':
36 class NXDOMAIN(dns
.exception
.DNSException
):
37 """The query name does not exist."""
40 # The definition of the Timeout exception has moved from here to the
41 # dns.exception module. We keep dns.resolver.Timeout defined for
42 # backwards compatibility.
44 Timeout
= dns
.exception
.Timeout
46 class NoAnswer(dns
.exception
.DNSException
):
47 """The response did not contain an answer to the question."""
50 class NoNameservers(dns
.exception
.DNSException
):
51 """No non-broken nameservers are available to answer the query."""
54 class NotAbsolute(dns
.exception
.DNSException
):
55 """Raised if an absolute domain name is required but a relative name
59 class NoRootSOA(dns
.exception
.DNSException
):
60 """Raised if for some reason there is no SOA at the root name.
61 This should never happen!"""
66 """DNS stub resolver answer
68 Instances of this class bundle up the result of a successful DNS
71 For convenience, the answer object implements much of the sequence
72 protocol, forwarding to its rrset. E.g. "for a in answer" is
73 equivalent to "for a in answer.rrset", "answer[i]" is equivalent
74 to "answer.rrset[i]", and "answer[i:j]" is equivalent to
77 Note that CNAMEs or DNAMEs in the response may mean that answer
78 node's name might not be the query name.
80 @ivar qname: The query name
81 @type qname: dns.name.Name object
82 @ivar rdtype: The query type
84 @ivar rdclass: The query class
86 @ivar response: The response message
87 @type response: dns.message.Message object
88 @ivar rrset: The answer
89 @type rrset: dns.rrset.RRset object
90 @ivar expiration: The time when the answer expires
91 @type expiration: float (seconds since the epoch)
93 def __init__(self
, qname
, rdtype
, rdclass
, response
):
96 self
.rdclass
= rdclass
97 self
.response
= response
100 for count
in xrange(0, 15):
102 rrset
= response
.find_rrset(response
.answer
, qname
,
104 if min_ttl
== -1 or rrset
.ttl
< min_ttl
:
108 if rdtype
!= dns
.rdatatype
.CNAME
:
110 crrset
= response
.find_rrset(response
.answer
,
114 if min_ttl
== -1 or crrset
.ttl
< min_ttl
:
126 self
.expiration
= time
.time() + min_ttl
128 def __getattr__(self
, attr
):
130 return self
.rrset
.name
132 return self
.rrset
.ttl
133 elif attr
== 'covers':
134 return self
.rrset
.covers
135 elif attr
== 'rdclass':
136 return self
.rrset
.rdclass
137 elif attr
== 'rdtype':
138 return self
.rrset
.rdtype
140 raise AttributeError(attr
)
143 return len(self
.rrset
)
146 return iter(self
.rrset
)
148 def __getitem__(self
, i
):
151 def __delitem__(self
, i
):
154 def __getslice__(self
, i
, j
):
155 return self
.rrset
[i
:j
]
157 def __delslice__(self
, i
, j
):
161 """Simple DNS answer cache.
163 @ivar data: A dictionary of cached data
165 @ivar cleaning_interval: The number of seconds between cleanings. The
166 default is 300 (5 minutes).
167 @type cleaning_interval: float
168 @ivar next_cleaning: The time the cache should next be cleaned (in seconds
170 @type next_cleaning: float
173 def __init__(self
, cleaning_interval
=300.0):
174 """Initialize a DNS cache.
176 @param cleaning_interval: the number of seconds between periodic
177 cleanings. The default is 300.0
178 @type cleaning_interval: float.
182 self
.cleaning_interval
= cleaning_interval
183 self
.next_cleaning
= time
.time() + self
.cleaning_interval
185 def maybe_clean(self
):
186 """Clean the cache if it's time to do so."""
189 if self
.next_cleaning
<= now
:
191 for (k
, v
) in self
.data
.iteritems():
192 if v
.expiration
<= now
:
193 keys_to_delete
.append(k
)
194 for k
in keys_to_delete
:
197 self
.next_cleaning
= now
+ self
.cleaning_interval
200 """Get the answer associated with I{key}. Returns None if
201 no answer is cached for the key.
203 @type key: (dns.name.Name, int, int) tuple whose values are the
204 query name, rdtype, and rdclass.
205 @rtype: dns.resolver.Answer object or None
209 v
= self
.data
.get(key
)
210 if v
is None or v
.expiration
<= time
.time():
214 def put(self
, key
, value
):
215 """Associate key and value in the cache.
217 @type key: (dns.name.Name, int, int) tuple whose values are the
218 query name, rdtype, and rdclass.
219 @param value: The answer being cached
220 @type value: dns.resolver.Answer object
224 self
.data
[key
] = value
226 def flush(self
, key
=None):
229 If I{key} is specified, only that item is flushed. Otherwise
230 the entire cache is flushed.
232 @param key: the key to flush
233 @type key: (dns.name.Name, int, int) tuple or None
237 if self
.data
.has_key(key
):
241 self
.next_cleaning
= time
.time() + self
.cleaning_interval
243 class Resolver(object):
246 @ivar domain: The domain of this host
247 @type domain: dns.name.Name object
248 @ivar nameservers: A list of nameservers to query. Each nameserver is
249 a string which contains the IP address of a nameserver.
250 @type nameservers: list of strings
251 @ivar search: The search list. If the query name is a relative name,
252 the resolver will construct an absolute query name by appending the search
253 names one by one to the query name.
254 @type search: list of dns.name.Name objects
255 @ivar port: The port to which to send queries. The default is 53.
257 @ivar timeout: The number of seconds to wait for a response from a
258 server, before timing out.
260 @ivar lifetime: The total number of seconds to spend trying to get an
261 answer to the question. If the lifetime expires, a Timeout exception
263 @type lifetime: float
264 @ivar keyring: The TSIG keyring to use. The default is None.
266 @ivar keyname: The TSIG keyname to use. The default is None.
267 @type keyname: dns.name.Name object
268 @ivar keyalgorithm: The TSIG key algorithm to use. The default is
269 dns.tsig.default_algorithm.
270 @type keyalgorithm: string
271 @ivar edns: The EDNS level to use. The default is -1, no Edns.
273 @ivar ednsflags: The EDNS flags
275 @ivar payload: The EDNS payload size. The default is 0.
277 @ivar cache: The cache to use. The default is None.
278 @type cache: dns.resolver.Cache object
280 def __init__(self
, filename
='/etc/resolv.conf', configure
=True):
281 """Initialize a resolver instance.
283 @param filename: The filename of a configuration file in
284 standard /etc/resolv.conf format. This parameter is meaningful
285 only when I{configure} is true and the platform is POSIX.
286 @type filename: string or file object
287 @param configure: If True (the default), the resolver instance
288 is configured in the normal fashion for the operating system
289 the resolver is running on. (I.e. a /etc/resolv.conf file on
290 POSIX systems and from the registry on Windows systems.)
291 @type configure: bool"""
295 if sys
.platform
== 'win32':
298 self
.read_resolv_conf(filename
)
301 """Reset all resolver configuration to the defaults."""
303 dns
.name
.Name(dns
.name
.from_text(socket
.gethostname())[1:])
304 if len(self
.domain
) == 0:
305 self
.domain
= dns
.name
.root
306 self
.nameservers
= []
313 self
.keyalgorithm
= dns
.tsig
.default_algorithm
319 def read_resolv_conf(self
, f
):
320 """Process f as a file in the /etc/resolv.conf format. If f is
321 a string, it is used as the name of the file to open; otherwise it
322 is treated as the file itself."""
323 if isinstance(f
, str) or isinstance(f
, unicode):
327 # /etc/resolv.conf doesn't exist, can't be read, etc.
328 # We'll just use the default resolver configuration.
329 self
.nameservers
= ['127.0.0.1']
336 if len(l
) == 0 or l
[0] == '#' or l
[0] == ';':
341 if tokens
[0] == 'nameserver':
342 self
.nameservers
.append(tokens
[1])
343 elif tokens
[0] == 'domain':
344 self
.domain
= dns
.name
.from_text(tokens
[1])
345 elif tokens
[0] == 'search':
346 for suffix
in tokens
[1:]:
347 self
.search
.append(dns
.name
.from_text(suffix
))
351 if len(self
.nameservers
) == 0:
352 self
.nameservers
.append('127.0.0.1')
354 def _determine_split_char(self
, entry
):
356 # The windows registry irritatingly changes the list element
357 # delimiter in between ' ' and ',' (and vice-versa) in various
358 # versions of windows.
360 if entry
.find(' ') >= 0:
362 elif entry
.find(',') >= 0:
365 # probably a singleton; treat as a space-separated list.
369 def _config_win32_nameservers(self
, nameservers
):
370 """Configure a NameServer registry entry."""
371 # we call str() on nameservers to convert it from unicode to ascii
372 nameservers
= str(nameservers
)
373 split_char
= self
._determine
_split
_char
(nameservers
)
374 ns_list
= nameservers
.split(split_char
)
376 if not ns
in self
.nameservers
:
377 self
.nameservers
.append(ns
)
379 def _config_win32_domain(self
, domain
):
380 """Configure a Domain registry entry."""
381 # we call str() on domain to convert it from unicode to ascii
382 self
.domain
= dns
.name
.from_text(str(domain
))
384 def _config_win32_search(self
, search
):
385 """Configure a Search registry entry."""
386 # we call str() on search to convert it from unicode to ascii
388 split_char
= self
._determine
_split
_char
(search
)
389 search_list
= search
.split(split_char
)
390 for s
in search_list
:
391 if not s
in self
.search
:
392 self
.search
.append(dns
.name
.from_text(s
))
394 def _config_win32_fromkey(self
, key
):
395 """Extract DNS info from a registry key."""
397 servers
, rtype
= _winreg
.QueryValueEx(key
, 'NameServer')
401 self
._config
_win
32_nameservers
(servers
)
403 dom
, rtype
= _winreg
.QueryValueEx(key
, 'Domain')
405 self
._config
_win
32_domain
(dom
)
410 servers
, rtype
= _winreg
.QueryValueEx(key
, 'DhcpNameServer')
414 self
._config
_win
32_nameservers
(servers
)
416 dom
, rtype
= _winreg
.QueryValueEx(key
, 'DhcpDomain')
418 self
._config
_win
32_domain
(dom
)
422 search
, rtype
= _winreg
.QueryValueEx(key
, 'SearchList')
426 self
._config
_win
32_search
(search
)
428 def read_registry(self
):
429 """Extract resolver configuration from the Windows registry."""
430 lm
= _winreg
.ConnectRegistry(None, _winreg
.HKEY_LOCAL_MACHINE
)
435 tcp_params
= _winreg
.OpenKey(lm
,
436 r
'SYSTEM\CurrentControlSet'
437 r
'\Services\Tcpip\Parameters')
439 except EnvironmentError:
441 tcp_params
= _winreg
.OpenKey(lm
,
442 r
'SYSTEM\CurrentControlSet'
443 r
'\Services\VxD\MSTCP')
445 self
._config
_win
32_fromkey
(tcp_params
)
449 interfaces
= _winreg
.OpenKey(lm
,
450 r
'SYSTEM\CurrentControlSet'
451 r
'\Services\Tcpip\Parameters'
457 guid
= _winreg
.EnumKey(interfaces
, i
)
459 key
= _winreg
.OpenKey(interfaces
, guid
)
460 if not self
._win
32_is
_nic
_enabled
(lm
, guid
, key
):
463 self
._config
_win
32_fromkey
(key
)
466 except EnvironmentError:
473 def _win32_is_nic_enabled(self
, lm
, guid
, interface_key
):
474 # Look in the Windows Registry to determine whether the network
475 # interface corresponding to the given guid is enabled.
477 # (Code contributed by Paul Marks, thanks!)
480 # This hard-coded location seems to be consistent, at least
481 # from Windows 2000 through Vista.
482 connection_key
= _winreg
.OpenKey(
484 r
'SYSTEM\CurrentControlSet\Control\Network'
485 r
'\{4D36E972-E325-11CE-BFC1-08002BE10318}'
486 r
'\%s\Connection' % guid
)
489 # The PnpInstanceID points to a key inside Enum
490 (pnp_id
, ttype
) = _winreg
.QueryValueEx(
491 connection_key
, 'PnpInstanceID')
493 if ttype
!= _winreg
.REG_SZ
:
496 device_key
= _winreg
.OpenKey(
497 lm
, r
'SYSTEM\CurrentControlSet\Enum\%s' % pnp_id
)
500 # Get ConfigFlags for this device
501 (flags
, ttype
) = _winreg
.QueryValueEx(
502 device_key
, 'ConfigFlags')
504 if ttype
!= _winreg
.REG_DWORD
:
507 # Based on experimentation, bit 0x1 indicates that the
508 # device is disabled.
509 return not (flags
& 0x1)
514 connection_key
.Close()
515 except (EnvironmentError, ValueError):
516 # Pre-vista, enabled interfaces seem to have a non-empty
517 # NTEContextList; this was how dnspython detected enabled
518 # nics before the code above was contributed. We've retained
519 # the old method since we don't know if the code above works
520 # on Windows 95/98/ME.
522 (nte
, ttype
) = _winreg
.QueryValueEx(interface_key
,
524 return nte
is not None
528 def _compute_timeout(self
, start
):
532 # Time going backwards is bad. Just give up.
535 # Time went backwards, but only a little. This can
536 # happen, e.g. under vmware with older linux kernels.
537 # Pretend it didn't happen.
539 duration
= now
- start
540 if duration
>= self
.lifetime
:
542 return min(self
.lifetime
- duration
, self
.timeout
)
544 def query(self
, qname
, rdtype
=dns
.rdatatype
.A
, rdclass
=dns
.rdataclass
.IN
,
545 tcp
=False, source
=None):
546 """Query nameservers to find the answer to the question.
548 The I{qname}, I{rdtype}, and I{rdclass} parameters may be objects
549 of the appropriate type, or strings that can be converted into objects
550 of the appropriate type. E.g. For I{rdtype} the integer 2 and the
551 the string 'NS' both mean to query for records with DNS rdata type NS.
553 @param qname: the query name
554 @type qname: dns.name.Name object or string
555 @param rdtype: the query type
556 @type rdtype: int or string
557 @param rdclass: the query class
558 @type rdclass: int or string
559 @param tcp: use TCP to make the query (default is False).
561 @param source: bind to this IP address (defaults to machine default IP).
562 @type source: IP address in dotted quad notation
563 @rtype: dns.resolver.Answer instance
564 @raises Timeout: no answers could be found in the specified lifetime
565 @raises NXDOMAIN: the query name does not exist
566 @raises NoAnswer: the response did not contain an answer
567 @raises NoNameservers: no non-broken nameservers are available to
568 answer the question."""
570 if isinstance(qname
, (str, unicode)):
571 qname
= dns
.name
.from_text(qname
, None)
572 if isinstance(rdtype
, str):
573 rdtype
= dns
.rdatatype
.from_text(rdtype
)
574 if isinstance(rdclass
, str):
575 rdclass
= dns
.rdataclass
.from_text(rdclass
)
577 if qname
.is_absolute():
578 qnames_to_try
.append(qname
)
581 qnames_to_try
.append(qname
.concatenate(dns
.name
.root
))
583 for suffix
in self
.search
:
584 qnames_to_try
.append(qname
.concatenate(suffix
))
586 qnames_to_try
.append(qname
.concatenate(self
.domain
))
589 for qname
in qnames_to_try
:
591 answer
= self
.cache
.get((qname
, rdtype
, rdclass
))
594 request
= dns
.message
.make_query(qname
, rdtype
, rdclass
)
595 if not self
.keyname
is None:
596 request
.use_tsig(self
.keyring
, self
.keyname
, self
.keyalgorithm
)
597 request
.use_edns(self
.edns
, self
.ednsflags
, self
.payload
)
600 # make a copy of the servers list so we can alter it later.
602 nameservers
= self
.nameservers
[:]
604 while response
is None:
605 if len(nameservers
) == 0:
607 for nameserver
in nameservers
[:]:
608 timeout
= self
._compute
_timeout
(start
)
611 response
= dns
.query
.tcp(request
, nameserver
,
615 response
= dns
.query
.udp(request
, nameserver
,
618 except (socket
.error
, dns
.exception
.Timeout
):
620 # Communication failure or timeout. Go to the
625 except dns
.query
.UnexpectedSource
:
627 # Who knows? Keep going.
631 except dns
.exception
.FormError
:
633 # We don't understand what this server is
634 # saying. Take it out of the mix and
637 nameservers
.remove(nameserver
)
640 rcode
= response
.rcode()
641 if rcode
== dns
.rcode
.NOERROR
or \
642 rcode
== dns
.rcode
.NXDOMAIN
:
645 # We got a response, but we're not happy with the
646 # rcode in it. Remove the server from the mix if
647 # the rcode isn't SERVFAIL.
649 if rcode
!= dns
.rcode
.SERVFAIL
:
650 nameservers
.remove(nameserver
)
652 if not response
is None:
655 # All nameservers failed!
657 if len(nameservers
) > 0:
659 # But we still have servers to try. Sleep a bit
660 # so we don't pound them!
662 timeout
= self
._compute
_timeout
(start
)
663 sleep_time
= min(timeout
, backoff
)
665 time
.sleep(sleep_time
)
666 if response
.rcode() == dns
.rcode
.NXDOMAIN
:
672 answer
= Answer(qname
, rdtype
, rdclass
, response
)
674 self
.cache
.put((qname
, rdtype
, rdclass
), answer
)
677 def use_tsig(self
, keyring
, keyname
=None,
678 algorithm
=dns
.tsig
.default_algorithm
):
679 """Add a TSIG signature to the query.
681 @param keyring: The TSIG keyring to use; defaults to None.
683 @param keyname: The name of the TSIG key to use; defaults to None.
684 The key must be defined in the keyring. If a keyring is specified
685 but a keyname is not, then the key used will be the first key in the
686 keyring. Note that the order of keys in a dictionary is not defined,
687 so applications should supply a keyname when a keyring is used, unless
688 they know the keyring contains only one key.
689 @param algorithm: The TSIG key algorithm to use. The default
690 is dns.tsig.default_algorithm.
691 @type algorithm: string"""
692 self
.keyring
= keyring
694 self
.keyname
= self
.keyring
.keys()[0]
696 self
.keyname
= keyname
697 self
.keyalgorithm
= algorithm
699 def use_edns(self
, edns
, ednsflags
, payload
):
702 @param edns: The EDNS level to use. The default is -1, no Edns.
704 @param ednsflags: The EDNS flags
706 @param payload: The EDNS payload size. The default is 0.
707 @type payload: int"""
712 self
.ednsflags
= ednsflags
713 self
.payload
= payload
715 default_resolver
= None
717 def get_default_resolver():
718 """Get the default resolver, initializing it if necessary."""
719 global default_resolver
720 if default_resolver
is None:
721 default_resolver
= Resolver()
722 return default_resolver
724 def query(qname
, rdtype
=dns
.rdatatype
.A
, rdclass
=dns
.rdataclass
.IN
,
725 tcp
=False, source
=None):
726 """Query nameservers to find the answer to the question.
728 This is a convenience function that uses the default resolver
729 object to make the query.
730 @see: L{dns.resolver.Resolver.query} for more information on the
732 return get_default_resolver().query(qname
, rdtype
, rdclass
, tcp
, source
)
734 def zone_for_name(name
, rdclass
=dns
.rdataclass
.IN
, tcp
=False, resolver
=None):
735 """Find the name of the zone which contains the specified name.
737 @param name: the query name
738 @type name: absolute dns.name.Name object or string
739 @param rdclass: The query class
741 @param tcp: use TCP to make the query (default is False).
743 @param resolver: the resolver to use
744 @type resolver: dns.resolver.Resolver object or None
745 @rtype: dns.name.Name"""
747 if isinstance(name
, (str, unicode)):
748 name
= dns
.name
.from_text(name
, dns
.name
.root
)
750 resolver
= get_default_resolver()
751 if not name
.is_absolute():
752 raise NotAbsolute(name
)
755 answer
= resolver
.query(name
, dns
.rdatatype
.SOA
, rdclass
, tcp
)
757 except (dns
.resolver
.NXDOMAIN
, dns
.resolver
.NoAnswer
):
760 except dns
.name
.NoParent
: