You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1383 lines
49 KiB

4 years ago
  1. # Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license
  2. # Copyright (C) 2003-2017 Nominum, Inc.
  3. #
  4. # Permission to use, copy, modify, and distribute this software and its
  5. # documentation for any purpose with or without fee is hereby granted,
  6. # provided that the above copyright notice and this permission notice
  7. # appear in all copies.
  8. #
  9. # THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES
  10. # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  11. # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR
  12. # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  13. # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  14. # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
  15. # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  16. """DNS stub resolver."""
  17. import socket
  18. import sys
  19. import time
  20. import random
  21. try:
  22. import threading as _threading
  23. except ImportError:
  24. import dummy_threading as _threading
  25. import dns.exception
  26. import dns.flags
  27. import dns.ipv4
  28. import dns.ipv6
  29. import dns.message
  30. import dns.name
  31. import dns.query
  32. import dns.rcode
  33. import dns.rdataclass
  34. import dns.rdatatype
  35. import dns.reversename
  36. import dns.tsig
  37. from ._compat import xrange, string_types
  38. if sys.platform == 'win32':
  39. try:
  40. import winreg as _winreg
  41. except ImportError:
  42. import _winreg # pylint: disable=import-error
  43. class NXDOMAIN(dns.exception.DNSException):
  44. """The DNS query name does not exist."""
  45. supp_kwargs = {'qnames', 'responses'}
  46. fmt = None # we have our own __str__ implementation
  47. def _check_kwargs(self, qnames, responses=None):
  48. if not isinstance(qnames, (list, tuple, set)):
  49. raise AttributeError("qnames must be a list, tuple or set")
  50. if len(qnames) == 0:
  51. raise AttributeError("qnames must contain at least one element")
  52. if responses is None:
  53. responses = {}
  54. elif not isinstance(responses, dict):
  55. raise AttributeError("responses must be a dict(qname=response)")
  56. kwargs = dict(qnames=qnames, responses=responses)
  57. return kwargs
  58. def __str__(self):
  59. if 'qnames' not in self.kwargs:
  60. return super(NXDOMAIN, self).__str__()
  61. qnames = self.kwargs['qnames']
  62. if len(qnames) > 1:
  63. msg = 'None of DNS query names exist'
  64. else:
  65. msg = 'The DNS query name does not exist'
  66. qnames = ', '.join(map(str, qnames))
  67. return "{}: {}".format(msg, qnames)
  68. def canonical_name(self):
  69. if not 'qnames' in self.kwargs:
  70. raise TypeError("parametrized exception required")
  71. IN = dns.rdataclass.IN
  72. CNAME = dns.rdatatype.CNAME
  73. cname = None
  74. for qname in self.kwargs['qnames']:
  75. response = self.kwargs['responses'][qname]
  76. for answer in response.answer:
  77. if answer.rdtype != CNAME or answer.rdclass != IN:
  78. continue
  79. cname = answer.items[0].target.to_text()
  80. if cname is not None:
  81. return dns.name.from_text(cname)
  82. return self.kwargs['qnames'][0]
  83. canonical_name = property(canonical_name, doc=(
  84. "Return the unresolved canonical name."))
  85. def __add__(self, e_nx):
  86. """Augment by results from another NXDOMAIN exception."""
  87. qnames0 = list(self.kwargs.get('qnames', []))
  88. responses0 = dict(self.kwargs.get('responses', {}))
  89. responses1 = e_nx.kwargs.get('responses', {})
  90. for qname1 in e_nx.kwargs.get('qnames', []):
  91. if qname1 not in qnames0:
  92. qnames0.append(qname1)
  93. if qname1 in responses1:
  94. responses0[qname1] = responses1[qname1]
  95. return NXDOMAIN(qnames=qnames0, responses=responses0)
  96. def qnames(self):
  97. """All of the names that were tried.
  98. Returns a list of ``dns.name.Name``.
  99. """
  100. return self.kwargs['qnames']
  101. def responses(self):
  102. """A map from queried names to their NXDOMAIN responses.
  103. Returns a dict mapping a ``dns.name.Name`` to a
  104. ``dns.message.Message``.
  105. """
  106. return self.kwargs['responses']
  107. def response(self, qname):
  108. """The response for query *qname*.
  109. Returns a ``dns.message.Message``.
  110. """
  111. return self.kwargs['responses'][qname]
  112. class YXDOMAIN(dns.exception.DNSException):
  113. """The DNS query name is too long after DNAME substitution."""
  114. # The definition of the Timeout exception has moved from here to the
  115. # dns.exception module. We keep dns.resolver.Timeout defined for
  116. # backwards compatibility.
  117. Timeout = dns.exception.Timeout
  118. class NoAnswer(dns.exception.DNSException):
  119. """The DNS response does not contain an answer to the question."""
  120. fmt = 'The DNS response does not contain an answer ' + \
  121. 'to the question: {query}'
  122. supp_kwargs = {'response'}
  123. def _fmt_kwargs(self, **kwargs):
  124. return super(NoAnswer, self)._fmt_kwargs(
  125. query=kwargs['response'].question)
  126. class NoNameservers(dns.exception.DNSException):
  127. """All nameservers failed to answer the query.
  128. errors: list of servers and respective errors
  129. The type of errors is
  130. [(server IP address, any object convertible to string)].
  131. Non-empty errors list will add explanatory message ()
  132. """
  133. msg = "All nameservers failed to answer the query."
  134. fmt = "%s {query}: {errors}" % msg[:-1]
  135. supp_kwargs = {'request', 'errors'}
  136. def _fmt_kwargs(self, **kwargs):
  137. srv_msgs = []
  138. for err in kwargs['errors']:
  139. srv_msgs.append('Server {} {} port {} answered {}'.format(err[0],
  140. 'TCP' if err[1] else 'UDP', err[2], err[3]))
  141. return super(NoNameservers, self)._fmt_kwargs(
  142. query=kwargs['request'].question, errors='; '.join(srv_msgs))
  143. class NotAbsolute(dns.exception.DNSException):
  144. """An absolute domain name is required but a relative name was provided."""
  145. class NoRootSOA(dns.exception.DNSException):
  146. """There is no SOA RR at the DNS root name. This should never happen!"""
  147. class NoMetaqueries(dns.exception.DNSException):
  148. """DNS metaqueries are not allowed."""
  149. class Answer(object):
  150. """DNS stub resolver answer.
  151. Instances of this class bundle up the result of a successful DNS
  152. resolution.
  153. For convenience, the answer object implements much of the sequence
  154. protocol, forwarding to its ``rrset`` attribute. E.g.
  155. ``for a in answer`` is equivalent to ``for a in answer.rrset``.
  156. ``answer[i]`` is equivalent to ``answer.rrset[i]``, and
  157. ``answer[i:j]`` is equivalent to ``answer.rrset[i:j]``.
  158. Note that CNAMEs or DNAMEs in the response may mean that answer
  159. RRset's name might not be the query name.
  160. """
  161. def __init__(self, qname, rdtype, rdclass, response,
  162. raise_on_no_answer=True):
  163. self.qname = qname
  164. self.rdtype = rdtype
  165. self.rdclass = rdclass
  166. self.response = response
  167. min_ttl = -1
  168. rrset = None
  169. for count in xrange(0, 15):
  170. try:
  171. rrset = response.find_rrset(response.answer, qname,
  172. rdclass, rdtype)
  173. if min_ttl == -1 or rrset.ttl < min_ttl:
  174. min_ttl = rrset.ttl
  175. break
  176. except KeyError:
  177. if rdtype != dns.rdatatype.CNAME:
  178. try:
  179. crrset = response.find_rrset(response.answer,
  180. qname,
  181. rdclass,
  182. dns.rdatatype.CNAME)
  183. if min_ttl == -1 or crrset.ttl < min_ttl:
  184. min_ttl = crrset.ttl
  185. for rd in crrset:
  186. qname = rd.target
  187. break
  188. continue
  189. except KeyError:
  190. if raise_on_no_answer:
  191. raise NoAnswer(response=response)
  192. if raise_on_no_answer:
  193. raise NoAnswer(response=response)
  194. if rrset is None and raise_on_no_answer:
  195. raise NoAnswer(response=response)
  196. self.canonical_name = qname
  197. self.rrset = rrset
  198. if rrset is None:
  199. while 1:
  200. # Look for a SOA RR whose owner name is a superdomain
  201. # of qname.
  202. try:
  203. srrset = response.find_rrset(response.authority, qname,
  204. rdclass, dns.rdatatype.SOA)
  205. if min_ttl == -1 or srrset.ttl < min_ttl:
  206. min_ttl = srrset.ttl
  207. if srrset[0].minimum < min_ttl:
  208. min_ttl = srrset[0].minimum
  209. break
  210. except KeyError:
  211. try:
  212. qname = qname.parent()
  213. except dns.name.NoParent:
  214. break
  215. self.expiration = time.time() + min_ttl
  216. def __getattr__(self, attr):
  217. if attr == 'name':
  218. return self.rrset.name
  219. elif attr == 'ttl':
  220. return self.rrset.ttl
  221. elif attr == 'covers':
  222. return self.rrset.covers
  223. elif attr == 'rdclass':
  224. return self.rrset.rdclass
  225. elif attr == 'rdtype':
  226. return self.rrset.rdtype
  227. else:
  228. raise AttributeError(attr)
  229. def __len__(self):
  230. return self.rrset and len(self.rrset) or 0
  231. def __iter__(self):
  232. return self.rrset and iter(self.rrset) or iter(tuple())
  233. def __getitem__(self, i):
  234. if self.rrset is None:
  235. raise IndexError
  236. return self.rrset[i]
  237. def __delitem__(self, i):
  238. if self.rrset is None:
  239. raise IndexError
  240. del self.rrset[i]
  241. class Cache(object):
  242. """Simple thread-safe DNS answer cache."""
  243. def __init__(self, cleaning_interval=300.0):
  244. """*cleaning_interval*, a ``float`` is the number of seconds between
  245. periodic cleanings.
  246. """
  247. self.data = {}
  248. self.cleaning_interval = cleaning_interval
  249. self.next_cleaning = time.time() + self.cleaning_interval
  250. self.lock = _threading.Lock()
  251. def _maybe_clean(self):
  252. """Clean the cache if it's time to do so."""
  253. now = time.time()
  254. if self.next_cleaning <= now:
  255. keys_to_delete = []
  256. for (k, v) in self.data.items():
  257. if v.expiration <= now:
  258. keys_to_delete.append(k)
  259. for k in keys_to_delete:
  260. del self.data[k]
  261. now = time.time()
  262. self.next_cleaning = now + self.cleaning_interval
  263. def get(self, key):
  264. """Get the answer associated with *key*.
  265. Returns None if no answer is cached for the key.
  266. *key*, a ``(dns.name.Name, int, int)`` tuple whose values are the
  267. query name, rdtype, and rdclass respectively.
  268. Returns a ``dns.resolver.Answer`` or ``None``.
  269. """
  270. try:
  271. self.lock.acquire()
  272. self._maybe_clean()
  273. v = self.data.get(key)
  274. if v is None or v.expiration <= time.time():
  275. return None
  276. return v
  277. finally:
  278. self.lock.release()
  279. def put(self, key, value):
  280. """Associate key and value in the cache.
  281. *key*, a ``(dns.name.Name, int, int)`` tuple whose values are the
  282. query name, rdtype, and rdclass respectively.
  283. *value*, a ``dns.resolver.Answer``, the answer.
  284. """
  285. try:
  286. self.lock.acquire()
  287. self._maybe_clean()
  288. self.data[key] = value
  289. finally:
  290. self.lock.release()
  291. def flush(self, key=None):
  292. """Flush the cache.
  293. If *key* is not ``None``, only that item is flushed. Otherwise
  294. the entire cache is flushed.
  295. *key*, a ``(dns.name.Name, int, int)`` tuple whose values are the
  296. query name, rdtype, and rdclass respectively.
  297. """
  298. try:
  299. self.lock.acquire()
  300. if key is not None:
  301. if key in self.data:
  302. del self.data[key]
  303. else:
  304. self.data = {}
  305. self.next_cleaning = time.time() + self.cleaning_interval
  306. finally:
  307. self.lock.release()
  308. class LRUCacheNode(object):
  309. """LRUCache node."""
  310. def __init__(self, key, value):
  311. self.key = key
  312. self.value = value
  313. self.prev = self
  314. self.next = self
  315. def link_before(self, node):
  316. self.prev = node.prev
  317. self.next = node
  318. node.prev.next = self
  319. node.prev = self
  320. def link_after(self, node):
  321. self.prev = node
  322. self.next = node.next
  323. node.next.prev = self
  324. node.next = self
  325. def unlink(self):
  326. self.next.prev = self.prev
  327. self.prev.next = self.next
  328. class LRUCache(object):
  329. """Thread-safe, bounded, least-recently-used DNS answer cache.
  330. This cache is better than the simple cache (above) if you're
  331. running a web crawler or other process that does a lot of
  332. resolutions. The LRUCache has a maximum number of nodes, and when
  333. it is full, the least-recently used node is removed to make space
  334. for a new one.
  335. """
  336. def __init__(self, max_size=100000):
  337. """*max_size*, an ``int``, is the maximum number of nodes to cache;
  338. it must be greater than 0.
  339. """
  340. self.data = {}
  341. self.set_max_size(max_size)
  342. self.sentinel = LRUCacheNode(None, None)
  343. self.lock = _threading.Lock()
  344. def set_max_size(self, max_size):
  345. if max_size < 1:
  346. max_size = 1
  347. self.max_size = max_size
  348. def get(self, key):
  349. """Get the answer associated with *key*.
  350. Returns None if no answer is cached for the key.
  351. *key*, a ``(dns.name.Name, int, int)`` tuple whose values are the
  352. query name, rdtype, and rdclass respectively.
  353. Returns a ``dns.resolver.Answer`` or ``None``.
  354. """
  355. try:
  356. self.lock.acquire()
  357. node = self.data.get(key)
  358. if node is None:
  359. return None
  360. # Unlink because we're either going to move the node to the front
  361. # of the LRU list or we're going to free it.
  362. node.unlink()
  363. if node.value.expiration <= time.time():
  364. del self.data[node.key]
  365. return None
  366. node.link_after(self.sentinel)
  367. return node.value
  368. finally:
  369. self.lock.release()
  370. def put(self, key, value):
  371. """Associate key and value in the cache.
  372. *key*, a ``(dns.name.Name, int, int)`` tuple whose values are the
  373. query name, rdtype, and rdclass respectively.
  374. *value*, a ``dns.resolver.Answer``, the answer.
  375. """
  376. try:
  377. self.lock.acquire()
  378. node = self.data.get(key)
  379. if node is not None:
  380. node.unlink()
  381. del self.data[node.key]
  382. while len(self.data) >= self.max_size:
  383. node = self.sentinel.prev
  384. node.unlink()
  385. del self.data[node.key]
  386. node = LRUCacheNode(key, value)
  387. node.link_after(self.sentinel)
  388. self.data[key] = node
  389. finally:
  390. self.lock.release()
  391. def flush(self, key=None):
  392. """Flush the cache.
  393. If *key* is not ``None``, only that item is flushed. Otherwise
  394. the entire cache is flushed.
  395. *key*, a ``(dns.name.Name, int, int)`` tuple whose values are the
  396. query name, rdtype, and rdclass respectively.
  397. """
  398. try:
  399. self.lock.acquire()
  400. if key is not None:
  401. node = self.data.get(key)
  402. if node is not None:
  403. node.unlink()
  404. del self.data[node.key]
  405. else:
  406. node = self.sentinel.next
  407. while node != self.sentinel:
  408. next = node.next
  409. node.prev = None
  410. node.next = None
  411. node = next
  412. self.data = {}
  413. finally:
  414. self.lock.release()
  415. class Resolver(object):
  416. """DNS stub resolver."""
  417. def __init__(self, filename='/etc/resolv.conf', configure=True):
  418. """*filename*, a ``text`` or file object, specifying a file
  419. in standard /etc/resolv.conf format. This parameter is meaningful
  420. only when *configure* is true and the platform is POSIX.
  421. *configure*, a ``bool``. If True (the default), the resolver
  422. instance is configured in the normal fashion for the operating
  423. system the resolver is running on. (I.e. by reading a
  424. /etc/resolv.conf file on POSIX systems and from the registry
  425. on Windows systems.)
  426. """
  427. self.domain = None
  428. self.nameservers = None
  429. self.nameserver_ports = None
  430. self.port = None
  431. self.search = None
  432. self.timeout = None
  433. self.lifetime = None
  434. self.keyring = None
  435. self.keyname = None
  436. self.keyalgorithm = None
  437. self.edns = None
  438. self.ednsflags = None
  439. self.payload = None
  440. self.cache = None
  441. self.flags = None
  442. self.retry_servfail = False
  443. self.rotate = False
  444. self.reset()
  445. if configure:
  446. if sys.platform == 'win32':
  447. self.read_registry()
  448. elif filename:
  449. self.read_resolv_conf(filename)
  450. def reset(self):
  451. """Reset all resolver configuration to the defaults."""
  452. self.domain = \
  453. dns.name.Name(dns.name.from_text(socket.gethostname())[1:])
  454. if len(self.domain) == 0:
  455. self.domain = dns.name.root
  456. self.nameservers = []
  457. self.nameserver_ports = {}
  458. self.port = 53
  459. self.search = []
  460. self.timeout = 2.0
  461. self.lifetime = 30.0
  462. self.keyring = None
  463. self.keyname = None
  464. self.keyalgorithm = dns.tsig.default_algorithm
  465. self.edns = -1
  466. self.ednsflags = 0
  467. self.payload = 0
  468. self.cache = None
  469. self.flags = None
  470. self.retry_servfail = False
  471. self.rotate = False
  472. def read_resolv_conf(self, f):
  473. """Process *f* as a file in the /etc/resolv.conf format. If f is
  474. a ``text``, it is used as the name of the file to open; otherwise it
  475. is treated as the file itself."""
  476. if isinstance(f, string_types):
  477. try:
  478. f = open(f, 'r')
  479. except IOError:
  480. # /etc/resolv.conf doesn't exist, can't be read, etc.
  481. # We'll just use the default resolver configuration.
  482. self.nameservers = ['127.0.0.1']
  483. return
  484. want_close = True
  485. else:
  486. want_close = False
  487. try:
  488. for l in f:
  489. if len(l) == 0 or l[0] == '#' or l[0] == ';':
  490. continue
  491. tokens = l.split()
  492. # Any line containing less than 2 tokens is malformed
  493. if len(tokens) < 2:
  494. continue
  495. if tokens[0] == 'nameserver':
  496. self.nameservers.append(tokens[1])
  497. elif tokens[0] == 'domain':
  498. self.domain = dns.name.from_text(tokens[1])
  499. elif tokens[0] == 'search':
  500. for suffix in tokens[1:]:
  501. self.search.append(dns.name.from_text(suffix))
  502. elif tokens[0] == 'options':
  503. if 'rotate' in tokens[1:]:
  504. self.rotate = True
  505. finally:
  506. if want_close:
  507. f.close()
  508. if len(self.nameservers) == 0:
  509. self.nameservers.append('127.0.0.1')
  510. def _determine_split_char(self, entry):
  511. #
  512. # The windows registry irritatingly changes the list element
  513. # delimiter in between ' ' and ',' (and vice-versa) in various
  514. # versions of windows.
  515. #
  516. if entry.find(' ') >= 0:
  517. split_char = ' '
  518. elif entry.find(',') >= 0:
  519. split_char = ','
  520. else:
  521. # probably a singleton; treat as a space-separated list.
  522. split_char = ' '
  523. return split_char
  524. def _config_win32_nameservers(self, nameservers):
  525. # we call str() on nameservers to convert it from unicode to ascii
  526. nameservers = str(nameservers)
  527. split_char = self._determine_split_char(nameservers)
  528. ns_list = nameservers.split(split_char)
  529. for ns in ns_list:
  530. if ns not in self.nameservers:
  531. self.nameservers.append(ns)
  532. def _config_win32_domain(self, domain):
  533. # we call str() on domain to convert it from unicode to ascii
  534. self.domain = dns.name.from_text(str(domain))
  535. def _config_win32_search(self, search):
  536. # we call str() on search to convert it from unicode to ascii
  537. search = str(search)
  538. split_char = self._determine_split_char(search)
  539. search_list = search.split(split_char)
  540. for s in search_list:
  541. if s not in self.search:
  542. self.search.append(dns.name.from_text(s))
  543. def _config_win32_fromkey(self, key, always_try_domain):
  544. try:
  545. servers, rtype = _winreg.QueryValueEx(key, 'NameServer')
  546. except WindowsError: # pylint: disable=undefined-variable
  547. servers = None
  548. if servers:
  549. self._config_win32_nameservers(servers)
  550. if servers or always_try_domain:
  551. try:
  552. dom, rtype = _winreg.QueryValueEx(key, 'Domain')
  553. if dom:
  554. self._config_win32_domain(dom)
  555. except WindowsError: # pylint: disable=undefined-variable
  556. pass
  557. else:
  558. try:
  559. servers, rtype = _winreg.QueryValueEx(key, 'DhcpNameServer')
  560. except WindowsError: # pylint: disable=undefined-variable
  561. servers = None
  562. if servers:
  563. self._config_win32_nameservers(servers)
  564. try:
  565. dom, rtype = _winreg.QueryValueEx(key, 'DhcpDomain')
  566. if dom:
  567. self._config_win32_domain(dom)
  568. except WindowsError: # pylint: disable=undefined-variable
  569. pass
  570. try:
  571. search, rtype = _winreg.QueryValueEx(key, 'SearchList')
  572. except WindowsError: # pylint: disable=undefined-variable
  573. search = None
  574. if search:
  575. self._config_win32_search(search)
  576. def read_registry(self):
  577. """Extract resolver configuration from the Windows registry."""
  578. lm = _winreg.ConnectRegistry(None, _winreg.HKEY_LOCAL_MACHINE)
  579. want_scan = False
  580. try:
  581. try:
  582. # XP, 2000
  583. tcp_params = _winreg.OpenKey(lm,
  584. r'SYSTEM\CurrentControlSet'
  585. r'\Services\Tcpip\Parameters')
  586. want_scan = True
  587. except EnvironmentError:
  588. # ME
  589. tcp_params = _winreg.OpenKey(lm,
  590. r'SYSTEM\CurrentControlSet'
  591. r'\Services\VxD\MSTCP')
  592. try:
  593. self._config_win32_fromkey(tcp_params, True)
  594. finally:
  595. tcp_params.Close()
  596. if want_scan:
  597. interfaces = _winreg.OpenKey(lm,
  598. r'SYSTEM\CurrentControlSet'
  599. r'\Services\Tcpip\Parameters'
  600. r'\Interfaces')
  601. try:
  602. i = 0
  603. while True:
  604. try:
  605. guid = _winreg.EnumKey(interfaces, i)
  606. i += 1
  607. key = _winreg.OpenKey(interfaces, guid)
  608. if not self._win32_is_nic_enabled(lm, guid, key):
  609. continue
  610. try:
  611. self._config_win32_fromkey(key, False)
  612. finally:
  613. key.Close()
  614. except EnvironmentError:
  615. break
  616. finally:
  617. interfaces.Close()
  618. finally:
  619. lm.Close()
  620. def _win32_is_nic_enabled(self, lm, guid, interface_key):
  621. # Look in the Windows Registry to determine whether the network
  622. # interface corresponding to the given guid is enabled.
  623. #
  624. # (Code contributed by Paul Marks, thanks!)
  625. #
  626. try:
  627. # This hard-coded location seems to be consistent, at least
  628. # from Windows 2000 through Vista.
  629. connection_key = _winreg.OpenKey(
  630. lm,
  631. r'SYSTEM\CurrentControlSet\Control\Network'
  632. r'\{4D36E972-E325-11CE-BFC1-08002BE10318}'
  633. r'\%s\Connection' % guid)
  634. try:
  635. # The PnpInstanceID points to a key inside Enum
  636. (pnp_id, ttype) = _winreg.QueryValueEx(
  637. connection_key, 'PnpInstanceID')
  638. if ttype != _winreg.REG_SZ:
  639. raise ValueError
  640. device_key = _winreg.OpenKey(
  641. lm, r'SYSTEM\CurrentControlSet\Enum\%s' % pnp_id)
  642. try:
  643. # Get ConfigFlags for this device
  644. (flags, ttype) = _winreg.QueryValueEx(
  645. device_key, 'ConfigFlags')
  646. if ttype != _winreg.REG_DWORD:
  647. raise ValueError
  648. # Based on experimentation, bit 0x1 indicates that the
  649. # device is disabled.
  650. return not flags & 0x1
  651. finally:
  652. device_key.Close()
  653. finally:
  654. connection_key.Close()
  655. except (EnvironmentError, ValueError):
  656. # Pre-vista, enabled interfaces seem to have a non-empty
  657. # NTEContextList; this was how dnspython detected enabled
  658. # nics before the code above was contributed. We've retained
  659. # the old method since we don't know if the code above works
  660. # on Windows 95/98/ME.
  661. try:
  662. (nte, ttype) = _winreg.QueryValueEx(interface_key,
  663. 'NTEContextList')
  664. return nte is not None
  665. except WindowsError: # pylint: disable=undefined-variable
  666. return False
  667. def _compute_timeout(self, start, lifetime=None):
  668. lifetime = self.lifetime if lifetime is None else lifetime
  669. now = time.time()
  670. duration = now - start
  671. if duration < 0:
  672. if duration < -1:
  673. # Time going backwards is bad. Just give up.
  674. raise Timeout(timeout=duration)
  675. else:
  676. # Time went backwards, but only a little. This can
  677. # happen, e.g. under vmware with older linux kernels.
  678. # Pretend it didn't happen.
  679. now = start
  680. if duration >= lifetime:
  681. raise Timeout(timeout=duration)
  682. return min(lifetime - duration, self.timeout)
  683. def query(self, qname, rdtype=dns.rdatatype.A, rdclass=dns.rdataclass.IN,
  684. tcp=False, source=None, raise_on_no_answer=True, source_port=0,
  685. lifetime=None):
  686. """Query nameservers to find the answer to the question.
  687. The *qname*, *rdtype*, and *rdclass* parameters may be objects
  688. of the appropriate type, or strings that can be converted into objects
  689. of the appropriate type.
  690. *qname*, a ``dns.name.Name`` or ``text``, the query name.
  691. *rdtype*, an ``int`` or ``text``, the query type.
  692. *rdclass*, an ``int`` or ``text``, the query class.
  693. *tcp*, a ``bool``. If ``True``, use TCP to make the query.
  694. *source*, a ``text`` or ``None``. If not ``None``, bind to this IP
  695. address when making queries.
  696. *raise_on_no_answer*, a ``bool``. If ``True``, raise
  697. ``dns.resolver.NoAnswer`` if there's no answer to the question.
  698. *source_port*, an ``int``, the port from which to send the message.
  699. *lifetime*, a ``float``, how long query should run before timing out.
  700. Raises ``dns.exception.Timeout`` if no answers could be found
  701. in the specified lifetime.
  702. Raises ``dns.resolver.NXDOMAIN`` if the query name does not exist.
  703. Raises ``dns.resolver.YXDOMAIN`` if the query name is too long after
  704. DNAME substitution.
  705. Raises ``dns.resolver.NoAnswer`` if *raise_on_no_answer* is
  706. ``True`` and the query name exists but has no RRset of the
  707. desired type and class.
  708. Raises ``dns.resolver.NoNameservers`` if no non-broken
  709. nameservers are available to answer the question.
  710. Returns a ``dns.resolver.Answer`` instance.
  711. """
  712. if isinstance(qname, string_types):
  713. qname = dns.name.from_text(qname, None)
  714. if isinstance(rdtype, string_types):
  715. rdtype = dns.rdatatype.from_text(rdtype)
  716. if dns.rdatatype.is_metatype(rdtype):
  717. raise NoMetaqueries
  718. if isinstance(rdclass, string_types):
  719. rdclass = dns.rdataclass.from_text(rdclass)
  720. if dns.rdataclass.is_metaclass(rdclass):
  721. raise NoMetaqueries
  722. qnames_to_try = []
  723. if qname.is_absolute():
  724. qnames_to_try.append(qname)
  725. else:
  726. if len(qname) > 1:
  727. qnames_to_try.append(qname.concatenate(dns.name.root))
  728. if self.search:
  729. for suffix in self.search:
  730. qnames_to_try.append(qname.concatenate(suffix))
  731. else:
  732. qnames_to_try.append(qname.concatenate(self.domain))
  733. all_nxdomain = True
  734. nxdomain_responses = {}
  735. start = time.time()
  736. _qname = None # make pylint happy
  737. for _qname in qnames_to_try:
  738. if self.cache:
  739. answer = self.cache.get((_qname, rdtype, rdclass))
  740. if answer is not None:
  741. if answer.rrset is None and raise_on_no_answer:
  742. raise NoAnswer(response=answer.response)
  743. else:
  744. return answer
  745. request = dns.message.make_query(_qname, rdtype, rdclass)
  746. if self.keyname is not None:
  747. request.use_tsig(self.keyring, self.keyname,
  748. algorithm=self.keyalgorithm)
  749. request.use_edns(self.edns, self.ednsflags, self.payload)
  750. if self.flags is not None:
  751. request.flags = self.flags
  752. response = None
  753. #
  754. # make a copy of the servers list so we can alter it later.
  755. #
  756. nameservers = self.nameservers[:]
  757. errors = []
  758. if self.rotate:
  759. random.shuffle(nameservers)
  760. backoff = 0.10
  761. while response is None:
  762. if len(nameservers) == 0:
  763. raise NoNameservers(request=request, errors=errors)
  764. for nameserver in nameservers[:]:
  765. timeout = self._compute_timeout(start, lifetime)
  766. port = self.nameserver_ports.get(nameserver, self.port)
  767. try:
  768. tcp_attempt = tcp
  769. if tcp:
  770. response = dns.query.tcp(request, nameserver,
  771. timeout, port,
  772. source=source,
  773. source_port=source_port)
  774. else:
  775. response = dns.query.udp(request, nameserver,
  776. timeout, port,
  777. source=source,
  778. source_port=source_port)
  779. if response.flags & dns.flags.TC:
  780. # Response truncated; retry with TCP.
  781. tcp_attempt = True
  782. timeout = self._compute_timeout(start, lifetime)
  783. response = \
  784. dns.query.tcp(request, nameserver,
  785. timeout, port,
  786. source=source,
  787. source_port=source_port)
  788. except (socket.error, dns.exception.Timeout) as ex:
  789. #
  790. # Communication failure or timeout. Go to the
  791. # next server
  792. #
  793. errors.append((nameserver, tcp_attempt, port, ex,
  794. response))
  795. response = None
  796. continue
  797. except dns.query.UnexpectedSource as ex:
  798. #
  799. # Who knows? Keep going.
  800. #
  801. errors.append((nameserver, tcp_attempt, port, ex,
  802. response))
  803. response = None
  804. continue
  805. except dns.exception.FormError as ex:
  806. #
  807. # We don't understand what this server is
  808. # saying. Take it out of the mix and
  809. # continue.
  810. #
  811. nameservers.remove(nameserver)
  812. errors.append((nameserver, tcp_attempt, port, ex,
  813. response))
  814. response = None
  815. continue
  816. except EOFError as ex:
  817. #
  818. # We're using TCP and they hung up on us.
  819. # Probably they don't support TCP (though
  820. # they're supposed to!). Take it out of the
  821. # mix and continue.
  822. #
  823. nameservers.remove(nameserver)
  824. errors.append((nameserver, tcp_attempt, port, ex,
  825. response))
  826. response = None
  827. continue
  828. rcode = response.rcode()
  829. if rcode == dns.rcode.YXDOMAIN:
  830. ex = YXDOMAIN()
  831. errors.append((nameserver, tcp_attempt, port, ex,
  832. response))
  833. raise ex
  834. if rcode == dns.rcode.NOERROR or \
  835. rcode == dns.rcode.NXDOMAIN:
  836. break
  837. #
  838. # We got a response, but we're not happy with the
  839. # rcode in it. Remove the server from the mix if
  840. # the rcode isn't SERVFAIL.
  841. #
  842. if rcode != dns.rcode.SERVFAIL or not self.retry_servfail:
  843. nameservers.remove(nameserver)
  844. errors.append((nameserver, tcp_attempt, port,
  845. dns.rcode.to_text(rcode), response))
  846. response = None
  847. if response is not None:
  848. break
  849. #
  850. # All nameservers failed!
  851. #
  852. if len(nameservers) > 0:
  853. #
  854. # But we still have servers to try. Sleep a bit
  855. # so we don't pound them!
  856. #
  857. timeout = self._compute_timeout(start, lifetime)
  858. sleep_time = min(timeout, backoff)
  859. backoff *= 2
  860. time.sleep(sleep_time)
  861. if response.rcode() == dns.rcode.NXDOMAIN:
  862. nxdomain_responses[_qname] = response
  863. continue
  864. all_nxdomain = False
  865. break
  866. if all_nxdomain:
  867. raise NXDOMAIN(qnames=qnames_to_try, responses=nxdomain_responses)
  868. answer = Answer(_qname, rdtype, rdclass, response,
  869. raise_on_no_answer)
  870. if self.cache:
  871. self.cache.put((_qname, rdtype, rdclass), answer)
  872. return answer
  873. def use_tsig(self, keyring, keyname=None,
  874. algorithm=dns.tsig.default_algorithm):
  875. """Add a TSIG signature to the query.
  876. See the documentation of the Message class for a complete
  877. description of the keyring dictionary.
  878. *keyring*, a ``dict``, the TSIG keyring to use. If a
  879. *keyring* is specified but a *keyname* is not, then the key
  880. used will be the first key in the *keyring*. Note that the
  881. order of keys in a dictionary is not defined, so applications
  882. should supply a keyname when a keyring is used, unless they
  883. know the keyring contains only one key.
  884. *keyname*, a ``dns.name.Name`` or ``None``, the name of the TSIG key
  885. to use; defaults to ``None``. The key must be defined in the keyring.
  886. *algorithm*, a ``dns.name.Name``, the TSIG algorithm to use.
  887. """
  888. self.keyring = keyring
  889. if keyname is None:
  890. self.keyname = list(self.keyring.keys())[0]
  891. else:
  892. self.keyname = keyname
  893. self.keyalgorithm = algorithm
  894. def use_edns(self, edns, ednsflags, payload):
  895. """Configure EDNS behavior.
  896. *edns*, an ``int``, is the EDNS level to use. Specifying
  897. ``None``, ``False``, or ``-1`` means "do not use EDNS", and in this case
  898. the other parameters are ignored. Specifying ``True`` is
  899. equivalent to specifying 0, i.e. "use EDNS0".
  900. *ednsflags*, an ``int``, the EDNS flag values.
  901. *payload*, an ``int``, is the EDNS sender's payload field, which is the
  902. maximum size of UDP datagram the sender can handle. I.e. how big
  903. a response to this message can be.
  904. """
  905. if edns is None:
  906. edns = -1
  907. self.edns = edns
  908. self.ednsflags = ednsflags
  909. self.payload = payload
  910. def set_flags(self, flags):
  911. """Overrides the default flags with your own.
  912. *flags*, an ``int``, the message flags to use.
  913. """
  914. self.flags = flags
  915. #: The default resolver.
  916. default_resolver = None
  917. def get_default_resolver():
  918. """Get the default resolver, initializing it if necessary."""
  919. if default_resolver is None:
  920. reset_default_resolver()
  921. return default_resolver
  922. def reset_default_resolver():
  923. """Re-initialize default resolver.
  924. Note that the resolver configuration (i.e. /etc/resolv.conf on UNIX
  925. systems) will be re-read immediately.
  926. """
  927. global default_resolver
  928. default_resolver = Resolver()
  929. def query(qname, rdtype=dns.rdatatype.A, rdclass=dns.rdataclass.IN,
  930. tcp=False, source=None, raise_on_no_answer=True,
  931. source_port=0, lifetime=None):
  932. """Query nameservers to find the answer to the question.
  933. This is a convenience function that uses the default resolver
  934. object to make the query.
  935. See ``dns.resolver.Resolver.query`` for more information on the
  936. parameters.
  937. """
  938. return get_default_resolver().query(qname, rdtype, rdclass, tcp, source,
  939. raise_on_no_answer, source_port,
  940. lifetime)
  941. def zone_for_name(name, rdclass=dns.rdataclass.IN, tcp=False, resolver=None):
  942. """Find the name of the zone which contains the specified name.
  943. *name*, an absolute ``dns.name.Name`` or ``text``, the query name.
  944. *rdclass*, an ``int``, the query class.
  945. *tcp*, a ``bool``. If ``True``, use TCP to make the query.
  946. *resolver*, a ``dns.resolver.Resolver`` or ``None``, the resolver to use.
  947. If ``None``, the default resolver is used.
  948. Raises ``dns.resolver.NoRootSOA`` if there is no SOA RR at the DNS
  949. root. (This is only likely to happen if you're using non-default
  950. root servers in your network and they are misconfigured.)
  951. Returns a ``dns.name.Name``.
  952. """
  953. if isinstance(name, string_types):
  954. name = dns.name.from_text(name, dns.name.root)
  955. if resolver is None:
  956. resolver = get_default_resolver()
  957. if not name.is_absolute():
  958. raise NotAbsolute(name)
  959. while 1:
  960. try:
  961. answer = resolver.query(name, dns.rdatatype.SOA, rdclass, tcp)
  962. if answer.rrset.name == name:
  963. return name
  964. # otherwise we were CNAMEd or DNAMEd and need to look higher
  965. except (dns.resolver.NXDOMAIN, dns.resolver.NoAnswer):
  966. pass
  967. try:
  968. name = name.parent()
  969. except dns.name.NoParent:
  970. raise NoRootSOA
  971. #
  972. # Support for overriding the system resolver for all python code in the
  973. # running process.
  974. #
  975. _protocols_for_socktype = {
  976. socket.SOCK_DGRAM: [socket.SOL_UDP],
  977. socket.SOCK_STREAM: [socket.SOL_TCP],
  978. }
  979. _resolver = None
  980. _original_getaddrinfo = socket.getaddrinfo
  981. _original_getnameinfo = socket.getnameinfo
  982. _original_getfqdn = socket.getfqdn
  983. _original_gethostbyname = socket.gethostbyname
  984. _original_gethostbyname_ex = socket.gethostbyname_ex
  985. _original_gethostbyaddr = socket.gethostbyaddr
  986. def _getaddrinfo(host=None, service=None, family=socket.AF_UNSPEC, socktype=0,
  987. proto=0, flags=0):
  988. if flags & (socket.AI_ADDRCONFIG | socket.AI_V4MAPPED) != 0:
  989. raise NotImplementedError
  990. if host is None and service is None:
  991. raise socket.gaierror(socket.EAI_NONAME)
  992. v6addrs = []
  993. v4addrs = []
  994. canonical_name = None
  995. try:
  996. # Is host None or a V6 address literal?
  997. if host is None:
  998. canonical_name = 'localhost'
  999. if flags & socket.AI_PASSIVE != 0:
  1000. v6addrs.append('::')
  1001. v4addrs.append('0.0.0.0')
  1002. else:
  1003. v6addrs.append('::1')
  1004. v4addrs.append('127.0.0.1')
  1005. else:
  1006. parts = host.split('%')
  1007. if len(parts) == 2:
  1008. ahost = parts[0]
  1009. else:
  1010. ahost = host
  1011. addr = dns.ipv6.inet_aton(ahost)
  1012. v6addrs.append(host)
  1013. canonical_name = host
  1014. except Exception:
  1015. try:
  1016. # Is it a V4 address literal?
  1017. addr = dns.ipv4.inet_aton(host)
  1018. v4addrs.append(host)
  1019. canonical_name = host
  1020. except Exception:
  1021. if flags & socket.AI_NUMERICHOST == 0:
  1022. try:
  1023. if family == socket.AF_INET6 or family == socket.AF_UNSPEC:
  1024. v6 = _resolver.query(host, dns.rdatatype.AAAA,
  1025. raise_on_no_answer=False)
  1026. # Note that setting host ensures we query the same name
  1027. # for A as we did for AAAA.
  1028. host = v6.qname
  1029. canonical_name = v6.canonical_name.to_text(True)
  1030. if v6.rrset is not None:
  1031. for rdata in v6.rrset:
  1032. v6addrs.append(rdata.address)
  1033. if family == socket.AF_INET or family == socket.AF_UNSPEC:
  1034. v4 = _resolver.query(host, dns.rdatatype.A,
  1035. raise_on_no_answer=False)
  1036. host = v4.qname
  1037. canonical_name = v4.canonical_name.to_text(True)
  1038. if v4.rrset is not None:
  1039. for rdata in v4.rrset:
  1040. v4addrs.append(rdata.address)
  1041. except dns.resolver.NXDOMAIN:
  1042. raise socket.gaierror(socket.EAI_NONAME)
  1043. except Exception:
  1044. raise socket.gaierror(socket.EAI_SYSTEM)
  1045. port = None
  1046. try:
  1047. # Is it a port literal?
  1048. if service is None:
  1049. port = 0
  1050. else:
  1051. port = int(service)
  1052. except Exception:
  1053. if flags & socket.AI_NUMERICSERV == 0:
  1054. try:
  1055. port = socket.getservbyname(service)
  1056. except Exception:
  1057. pass
  1058. if port is None:
  1059. raise socket.gaierror(socket.EAI_NONAME)
  1060. tuples = []
  1061. if socktype == 0:
  1062. socktypes = [socket.SOCK_DGRAM, socket.SOCK_STREAM]
  1063. else:
  1064. socktypes = [socktype]
  1065. if flags & socket.AI_CANONNAME != 0:
  1066. cname = canonical_name
  1067. else:
  1068. cname = ''
  1069. if family == socket.AF_INET6 or family == socket.AF_UNSPEC:
  1070. for addr in v6addrs:
  1071. for socktype in socktypes:
  1072. for proto in _protocols_for_socktype[socktype]:
  1073. tuples.append((socket.AF_INET6, socktype, proto,
  1074. cname, (addr, port, 0, 0)))
  1075. if family == socket.AF_INET or family == socket.AF_UNSPEC:
  1076. for addr in v4addrs:
  1077. for socktype in socktypes:
  1078. for proto in _protocols_for_socktype[socktype]:
  1079. tuples.append((socket.AF_INET, socktype, proto,
  1080. cname, (addr, port)))
  1081. if len(tuples) == 0:
  1082. raise socket.gaierror(socket.EAI_NONAME)
  1083. return tuples
  1084. def _getnameinfo(sockaddr, flags=0):
  1085. host = sockaddr[0]
  1086. port = sockaddr[1]
  1087. if len(sockaddr) == 4:
  1088. scope = sockaddr[3]
  1089. family = socket.AF_INET6
  1090. else:
  1091. scope = None
  1092. family = socket.AF_INET
  1093. tuples = _getaddrinfo(host, port, family, socket.SOCK_STREAM,
  1094. socket.SOL_TCP, 0)
  1095. if len(tuples) > 1:
  1096. raise socket.error('sockaddr resolved to multiple addresses')
  1097. addr = tuples[0][4][0]
  1098. if flags & socket.NI_DGRAM:
  1099. pname = 'udp'
  1100. else:
  1101. pname = 'tcp'
  1102. qname = dns.reversename.from_address(addr)
  1103. if flags & socket.NI_NUMERICHOST == 0:
  1104. try:
  1105. answer = _resolver.query(qname, 'PTR')
  1106. hostname = answer.rrset[0].target.to_text(True)
  1107. except (dns.resolver.NXDOMAIN, dns.resolver.NoAnswer):
  1108. if flags & socket.NI_NAMEREQD:
  1109. raise socket.gaierror(socket.EAI_NONAME)
  1110. hostname = addr
  1111. if scope is not None:
  1112. hostname += '%' + str(scope)
  1113. else:
  1114. hostname = addr
  1115. if scope is not None:
  1116. hostname += '%' + str(scope)
  1117. if flags & socket.NI_NUMERICSERV:
  1118. service = str(port)
  1119. else:
  1120. service = socket.getservbyport(port, pname)
  1121. return (hostname, service)
  1122. def _getfqdn(name=None):
  1123. if name is None:
  1124. name = socket.gethostname()
  1125. try:
  1126. return _getnameinfo(_getaddrinfo(name, 80)[0][4])[0]
  1127. except Exception:
  1128. return name
  1129. def _gethostbyname(name):
  1130. return _gethostbyname_ex(name)[2][0]
  1131. def _gethostbyname_ex(name):
  1132. aliases = []
  1133. addresses = []
  1134. tuples = _getaddrinfo(name, 0, socket.AF_INET, socket.SOCK_STREAM,
  1135. socket.SOL_TCP, socket.AI_CANONNAME)
  1136. canonical = tuples[0][3]
  1137. for item in tuples:
  1138. addresses.append(item[4][0])
  1139. # XXX we just ignore aliases
  1140. return (canonical, aliases, addresses)
  1141. def _gethostbyaddr(ip):
  1142. try:
  1143. dns.ipv6.inet_aton(ip)
  1144. sockaddr = (ip, 80, 0, 0)
  1145. family = socket.AF_INET6
  1146. except Exception:
  1147. sockaddr = (ip, 80)
  1148. family = socket.AF_INET
  1149. (name, port) = _getnameinfo(sockaddr, socket.NI_NAMEREQD)
  1150. aliases = []
  1151. addresses = []
  1152. tuples = _getaddrinfo(name, 0, family, socket.SOCK_STREAM, socket.SOL_TCP,
  1153. socket.AI_CANONNAME)
  1154. canonical = tuples[0][3]
  1155. for item in tuples:
  1156. addresses.append(item[4][0])
  1157. # XXX we just ignore aliases
  1158. return (canonical, aliases, addresses)
  1159. def override_system_resolver(resolver=None):
  1160. """Override the system resolver routines in the socket module with
  1161. versions which use dnspython's resolver.
  1162. This can be useful in testing situations where you want to control
  1163. the resolution behavior of python code without having to change
  1164. the system's resolver settings (e.g. /etc/resolv.conf).
  1165. The resolver to use may be specified; if it's not, the default
  1166. resolver will be used.
  1167. resolver, a ``dns.resolver.Resolver`` or ``None``, the resolver to use.
  1168. """
  1169. if resolver is None:
  1170. resolver = get_default_resolver()
  1171. global _resolver
  1172. _resolver = resolver
  1173. socket.getaddrinfo = _getaddrinfo
  1174. socket.getnameinfo = _getnameinfo
  1175. socket.getfqdn = _getfqdn
  1176. socket.gethostbyname = _gethostbyname
  1177. socket.gethostbyname_ex = _gethostbyname_ex
  1178. socket.gethostbyaddr = _gethostbyaddr
  1179. def restore_system_resolver():
  1180. """Undo the effects of prior override_system_resolver()."""
  1181. global _resolver
  1182. _resolver = None
  1183. socket.getaddrinfo = _original_getaddrinfo
  1184. socket.getnameinfo = _original_getnameinfo
  1185. socket.getfqdn = _original_getfqdn
  1186. socket.gethostbyname = _original_gethostbyname
  1187. socket.gethostbyname_ex = _original_gethostbyname_ex
  1188. socket.gethostbyaddr = _original_gethostbyaddr