Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

842 lignes
30KB

  1. '''greendns - non-blocking DNS support for Eventlet
  2. '''
  3. # Portions of this code taken from the gogreen project:
  4. # http://github.com/slideinc/gogreen
  5. #
  6. # Copyright (c) 2005-2010 Slide, Inc.
  7. # All rights reserved.
  8. #
  9. # Redistribution and use in source and binary forms, with or without
  10. # modification, are permitted provided that the following conditions are
  11. # met:
  12. #
  13. # * Redistributions of source code must retain the above copyright
  14. # notice, this list of conditions and the following disclaimer.
  15. # * Redistributions in binary form must reproduce the above
  16. # copyright notice, this list of conditions and the following
  17. # disclaimer in the documentation and/or other materials provided
  18. # with the distribution.
  19. # * Neither the name of the author nor the names of other
  20. # contributors may be used to endorse or promote products derived
  21. # from this software without specific prior written permission.
  22. #
  23. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  24. # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  25. # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  26. # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  27. # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  28. # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  29. # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  30. # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  31. # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  32. # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  33. # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  34. import re
  35. import struct
  36. import sys
  37. import eventlet
  38. from eventlet import patcher
  39. from eventlet.green import _socket_nodns
  40. from eventlet.green import os
  41. from eventlet.green import time
  42. from eventlet.green import select
  43. import six
  44. def import_patched(module_name):
  45. # Import cycle note: it's crucial to use _socket_nodns here because
  46. # regular evenlet.green.socket imports *this* module and if we imported
  47. # it back we'd end with an import cycle (socket -> greendns -> socket).
  48. # We break this import cycle by providing a restricted socket module.
  49. modules = {
  50. 'select': select,
  51. 'time': time,
  52. 'os': os,
  53. 'socket': _socket_nodns,
  54. }
  55. return patcher.import_patched(module_name, **modules)
  56. dns = import_patched('dns')
  57. for pkg in dns.__all__:
  58. setattr(dns, pkg, import_patched('dns.' + pkg))
  59. dns.rdtypes.__all__.extend(['dnskeybase', 'dsbase', 'txtbase'])
  60. for pkg in dns.rdtypes.__all__:
  61. setattr(dns.rdtypes, pkg, import_patched('dns.rdtypes.' + pkg))
  62. for pkg in dns.rdtypes.IN.__all__:
  63. setattr(dns.rdtypes.IN, pkg, import_patched('dns.rdtypes.IN.' + pkg))
  64. for pkg in dns.rdtypes.ANY.__all__:
  65. setattr(dns.rdtypes.ANY, pkg, import_patched('dns.rdtypes.ANY.' + pkg))
  66. del import_patched
  67. socket = _socket_nodns
  68. DNS_QUERY_TIMEOUT = 10.0
  69. HOSTS_TTL = 10.0
  70. EAI_EAGAIN_ERROR = socket.gaierror(socket.EAI_AGAIN, 'Lookup timed out')
  71. EAI_NONAME_ERROR = socket.gaierror(socket.EAI_NONAME, 'Name or service not known')
  72. # EAI_NODATA was removed from RFC3493, it's now replaced with EAI_NONAME
  73. # socket.EAI_NODATA is not defined on FreeBSD, probably on some other platforms too.
  74. # https://lists.freebsd.org/pipermail/freebsd-ports/2003-October/005757.html
  75. EAI_NODATA_ERROR = EAI_NONAME_ERROR
  76. if (os.environ.get('EVENTLET_DEPRECATED_EAI_NODATA', '').lower() in ('1', 'y', 'yes')
  77. and hasattr(socket, 'EAI_NODATA')):
  78. EAI_NODATA_ERROR = socket.gaierror(socket.EAI_NODATA, 'No address associated with hostname')
  79. def is_ipv4_addr(host):
  80. """Return True if host is a valid IPv4 address"""
  81. if not isinstance(host, six.string_types):
  82. return False
  83. try:
  84. dns.ipv4.inet_aton(host)
  85. except dns.exception.SyntaxError:
  86. return False
  87. else:
  88. return True
  89. def is_ipv6_addr(host):
  90. """Return True if host is a valid IPv6 address"""
  91. if not isinstance(host, six.string_types):
  92. return False
  93. host = host.split('%', 1)[0]
  94. try:
  95. dns.ipv6.inet_aton(host)
  96. except dns.exception.SyntaxError:
  97. return False
  98. else:
  99. return True
  100. def is_ip_addr(host):
  101. """Return True if host is a valid IPv4 or IPv6 address"""
  102. return is_ipv4_addr(host) or is_ipv6_addr(host)
  103. class HostsAnswer(dns.resolver.Answer):
  104. """Answer class for HostsResolver object"""
  105. def __init__(self, qname, rdtype, rdclass, rrset, raise_on_no_answer=True):
  106. """Create a new answer
  107. :qname: A dns.name.Name instance of the query name
  108. :rdtype: The rdatatype of the query
  109. :rdclass: The rdataclass of the query
  110. :rrset: The dns.rrset.RRset with the response, must have ttl attribute
  111. :raise_on_no_answer: Whether to raise dns.resolver.NoAnswer if no
  112. answer.
  113. """
  114. self.response = None
  115. self.qname = qname
  116. self.rdtype = rdtype
  117. self.rdclass = rdclass
  118. self.canonical_name = qname
  119. if not rrset and raise_on_no_answer:
  120. raise dns.resolver.NoAnswer()
  121. self.rrset = rrset
  122. self.expiration = (time.time() +
  123. rrset.ttl if hasattr(rrset, 'ttl') else 0)
  124. class HostsResolver(object):
  125. """Class to parse the hosts file
  126. Attributes
  127. ----------
  128. :fname: The filename of the hosts file in use.
  129. :interval: The time between checking for hosts file modification
  130. """
  131. LINES_RE = re.compile(r"""
  132. \s* # Leading space
  133. ([^\r\n#]*?) # The actual match, non-greedy so as not to include trailing space
  134. \s* # Trailing space
  135. (?:[#][^\r\n]+)? # Comments
  136. (?:$|[\r\n]+) # EOF or newline
  137. """, re.VERBOSE)
  138. def __init__(self, fname=None, interval=HOSTS_TTL):
  139. self._v4 = {} # name -> ipv4
  140. self._v6 = {} # name -> ipv6
  141. self._aliases = {} # name -> canonical_name
  142. self.interval = interval
  143. self.fname = fname
  144. if fname is None:
  145. if os.name == 'posix':
  146. self.fname = '/etc/hosts'
  147. elif os.name == 'nt':
  148. self.fname = os.path.expandvars(
  149. r'%SystemRoot%\system32\drivers\etc\hosts')
  150. self._last_load = 0
  151. if self.fname:
  152. self._load()
  153. def _readlines(self):
  154. """Read the contents of the hosts file
  155. Return list of lines, comment lines and empty lines are
  156. excluded.
  157. Note that this performs disk I/O so can be blocking.
  158. """
  159. try:
  160. with open(self.fname, 'rb') as fp:
  161. fdata = fp.read()
  162. except (IOError, OSError):
  163. return []
  164. udata = fdata.decode(errors='ignore')
  165. return six.moves.filter(None, self.LINES_RE.findall(udata))
  166. def _load(self):
  167. """Load hosts file
  168. This will unconditionally (re)load the data from the hosts
  169. file.
  170. """
  171. lines = self._readlines()
  172. self._v4.clear()
  173. self._v6.clear()
  174. self._aliases.clear()
  175. for line in lines:
  176. parts = line.split()
  177. if len(parts) < 2:
  178. continue
  179. ip = parts.pop(0)
  180. if is_ipv4_addr(ip):
  181. ipmap = self._v4
  182. elif is_ipv6_addr(ip):
  183. if ip.startswith('fe80'):
  184. # Do not use link-local addresses, OSX stores these here
  185. continue
  186. ipmap = self._v6
  187. else:
  188. continue
  189. cname = parts.pop(0).lower()
  190. ipmap[cname] = ip
  191. for alias in parts:
  192. alias = alias.lower()
  193. ipmap[alias] = ip
  194. self._aliases[alias] = cname
  195. self._last_load = time.time()
  196. def query(self, qname, rdtype=dns.rdatatype.A, rdclass=dns.rdataclass.IN,
  197. tcp=False, source=None, raise_on_no_answer=True):
  198. """Query the hosts file
  199. The known rdtypes are dns.rdatatype.A, dns.rdatatype.AAAA and
  200. dns.rdatatype.CNAME.
  201. The ``rdclass`` parameter must be dns.rdataclass.IN while the
  202. ``tcp`` and ``source`` parameters are ignored.
  203. Return a HostAnswer instance or raise a dns.resolver.NoAnswer
  204. exception.
  205. """
  206. now = time.time()
  207. if self._last_load + self.interval < now:
  208. self._load()
  209. rdclass = dns.rdataclass.IN
  210. if isinstance(qname, six.string_types):
  211. name = qname
  212. qname = dns.name.from_text(qname)
  213. else:
  214. name = str(qname)
  215. name = name.lower()
  216. rrset = dns.rrset.RRset(qname, rdclass, rdtype)
  217. rrset.ttl = self._last_load + self.interval - now
  218. if rdclass == dns.rdataclass.IN and rdtype == dns.rdatatype.A:
  219. addr = self._v4.get(name)
  220. if not addr and qname.is_absolute():
  221. addr = self._v4.get(name[:-1])
  222. if addr:
  223. rrset.add(dns.rdtypes.IN.A.A(rdclass, rdtype, addr))
  224. elif rdclass == dns.rdataclass.IN and rdtype == dns.rdatatype.AAAA:
  225. addr = self._v6.get(name)
  226. if not addr and qname.is_absolute():
  227. addr = self._v6.get(name[:-1])
  228. if addr:
  229. rrset.add(dns.rdtypes.IN.AAAA.AAAA(rdclass, rdtype, addr))
  230. elif rdclass == dns.rdataclass.IN and rdtype == dns.rdatatype.CNAME:
  231. cname = self._aliases.get(name)
  232. if not cname and qname.is_absolute():
  233. cname = self._aliases.get(name[:-1])
  234. if cname:
  235. rrset.add(dns.rdtypes.ANY.CNAME.CNAME(
  236. rdclass, rdtype, dns.name.from_text(cname)))
  237. return HostsAnswer(qname, rdtype, rdclass, rrset, raise_on_no_answer)
  238. def getaliases(self, hostname):
  239. """Return a list of all the aliases of a given cname"""
  240. # Due to the way store aliases this is a bit inefficient, this
  241. # clearly was an afterthought. But this is only used by
  242. # gethostbyname_ex so it's probably fine.
  243. aliases = []
  244. if hostname in self._aliases:
  245. cannon = self._aliases[hostname]
  246. else:
  247. cannon = hostname
  248. aliases.append(cannon)
  249. for alias, cname in six.iteritems(self._aliases):
  250. if cannon == cname:
  251. aliases.append(alias)
  252. aliases.remove(hostname)
  253. return aliases
  254. class ResolverProxy(object):
  255. """Resolver class which can also use /etc/hosts
  256. Initialise with a HostsResolver instance in order for it to also
  257. use the hosts file.
  258. """
  259. def __init__(self, hosts_resolver=None, filename='/etc/resolv.conf'):
  260. """Initialise the resolver proxy
  261. :param hosts_resolver: An instance of HostsResolver to use.
  262. :param filename: The filename containing the resolver
  263. configuration. The default value is correct for both UNIX
  264. and Windows, on Windows it will result in the configuration
  265. being read from the Windows registry.
  266. """
  267. self._hosts = hosts_resolver
  268. self._filename = filename
  269. self.clear()
  270. def clear(self):
  271. self._resolver = dns.resolver.Resolver(filename=self._filename)
  272. self._resolver.cache = dns.resolver.LRUCache()
  273. def query(self, qname, rdtype=dns.rdatatype.A, rdclass=dns.rdataclass.IN,
  274. tcp=False, source=None, raise_on_no_answer=True,
  275. _hosts_rdtypes=(dns.rdatatype.A, dns.rdatatype.AAAA),
  276. use_network=True):
  277. """Query the resolver, using /etc/hosts if enabled.
  278. Behavior:
  279. 1. if hosts is enabled and contains answer, return it now
  280. 2. query nameservers for qname if use_network is True
  281. 3. if qname did not contain dots, pretend it was top-level domain,
  282. query "foobar." and append to previous result
  283. """
  284. result = [None, None, 0]
  285. if qname is None:
  286. qname = '0.0.0.0'
  287. if isinstance(qname, six.string_types):
  288. qname = dns.name.from_text(qname, None)
  289. def step(fun, *args, **kwargs):
  290. try:
  291. a = fun(*args, **kwargs)
  292. except Exception as e:
  293. result[1] = e
  294. return False
  295. if a.rrset is not None and len(a.rrset):
  296. if result[0] is None:
  297. result[0] = a
  298. else:
  299. result[0].rrset.union_update(a.rrset)
  300. result[2] += len(a.rrset)
  301. return True
  302. def end():
  303. if result[0] is not None:
  304. if raise_on_no_answer and result[2] == 0:
  305. raise dns.resolver.NoAnswer
  306. return result[0]
  307. if result[1] is not None:
  308. if raise_on_no_answer or not isinstance(result[1], dns.resolver.NoAnswer):
  309. raise result[1]
  310. raise dns.resolver.NXDOMAIN(qnames=(qname,))
  311. if (self._hosts and (rdclass == dns.rdataclass.IN) and (rdtype in _hosts_rdtypes)):
  312. if step(self._hosts.query, qname, rdtype, raise_on_no_answer=False):
  313. if (result[0] is not None) or (result[1] is not None) or (not use_network):
  314. return end()
  315. # Main query
  316. step(self._resolver.query, qname, rdtype, rdclass, tcp, source, raise_on_no_answer=False)
  317. # `resolv.conf` docs say unqualified names must resolve from search (or local) domain.
  318. # However, common OS `getaddrinfo()` implementations append trailing dot (e.g. `db -> db.`)
  319. # and ask nameservers, as if top-level domain was queried.
  320. # This step follows established practice.
  321. # https://github.com/nameko/nameko/issues/392
  322. # https://github.com/eventlet/eventlet/issues/363
  323. if len(qname) == 1:
  324. step(self._resolver.query, qname.concatenate(dns.name.root),
  325. rdtype, rdclass, tcp, source, raise_on_no_answer=False)
  326. return end()
  327. def getaliases(self, hostname):
  328. """Return a list of all the aliases of a given hostname"""
  329. if self._hosts:
  330. aliases = self._hosts.getaliases(hostname)
  331. else:
  332. aliases = []
  333. while True:
  334. try:
  335. ans = self._resolver.query(hostname, dns.rdatatype.CNAME)
  336. except (dns.resolver.NoAnswer, dns.resolver.NXDOMAIN):
  337. break
  338. else:
  339. aliases.extend(str(rr.target) for rr in ans.rrset)
  340. hostname = ans[0].target
  341. return aliases
  342. resolver = ResolverProxy(hosts_resolver=HostsResolver())
  343. def resolve(name, family=socket.AF_INET, raises=True, _proxy=None,
  344. use_network=True):
  345. """Resolve a name for a given family using the global resolver proxy.
  346. This method is called by the global getaddrinfo() function. If use_network
  347. is False, only resolution via hosts file will be performed.
  348. Return a dns.resolver.Answer instance. If there is no answer it's
  349. rrset will be emtpy.
  350. """
  351. if family == socket.AF_INET:
  352. rdtype = dns.rdatatype.A
  353. elif family == socket.AF_INET6:
  354. rdtype = dns.rdatatype.AAAA
  355. else:
  356. raise socket.gaierror(socket.EAI_FAMILY,
  357. 'Address family not supported')
  358. if _proxy is None:
  359. _proxy = resolver
  360. try:
  361. try:
  362. return _proxy.query(name, rdtype, raise_on_no_answer=raises,
  363. use_network=use_network)
  364. except dns.resolver.NXDOMAIN:
  365. if not raises:
  366. return HostsAnswer(dns.name.Name(name),
  367. rdtype, dns.rdataclass.IN, None, False)
  368. raise
  369. except dns.exception.Timeout:
  370. raise EAI_EAGAIN_ERROR
  371. except dns.exception.DNSException:
  372. raise EAI_NODATA_ERROR
  373. def resolve_cname(host):
  374. """Return the canonical name of a hostname"""
  375. try:
  376. ans = resolver.query(host, dns.rdatatype.CNAME)
  377. except dns.resolver.NoAnswer:
  378. return host
  379. except dns.exception.Timeout:
  380. raise EAI_EAGAIN_ERROR
  381. except dns.exception.DNSException:
  382. raise EAI_NODATA_ERROR
  383. else:
  384. return str(ans[0].target)
  385. def getaliases(host):
  386. """Return a list of for aliases for the given hostname
  387. This method does translate the dnspython exceptions into
  388. socket.gaierror exceptions. If no aliases are available an empty
  389. list will be returned.
  390. """
  391. try:
  392. return resolver.getaliases(host)
  393. except dns.exception.Timeout:
  394. raise EAI_EAGAIN_ERROR
  395. except dns.exception.DNSException:
  396. raise EAI_NODATA_ERROR
  397. def _getaddrinfo_lookup(host, family, flags):
  398. """Resolve a hostname to a list of addresses
  399. Helper function for getaddrinfo.
  400. """
  401. if flags & socket.AI_NUMERICHOST:
  402. raise EAI_NONAME_ERROR
  403. addrs = []
  404. if family == socket.AF_UNSPEC:
  405. err = None
  406. for use_network in [False, True]:
  407. for qfamily in [socket.AF_INET6, socket.AF_INET]:
  408. try:
  409. answer = resolve(host, qfamily, False, use_network=use_network)
  410. except socket.gaierror as e:
  411. if e.errno not in (socket.EAI_AGAIN, EAI_NONAME_ERROR.errno, EAI_NODATA_ERROR.errno):
  412. raise
  413. err = e
  414. else:
  415. if answer.rrset:
  416. addrs.extend(rr.address for rr in answer.rrset)
  417. if addrs:
  418. break
  419. if err is not None and not addrs:
  420. raise err
  421. elif family == socket.AF_INET6 and flags & socket.AI_V4MAPPED:
  422. answer = resolve(host, socket.AF_INET6, False)
  423. if answer.rrset:
  424. addrs = [rr.address for rr in answer.rrset]
  425. if not addrs or flags & socket.AI_ALL:
  426. answer = resolve(host, socket.AF_INET, False)
  427. if answer.rrset:
  428. addrs = ['::ffff:' + rr.address for rr in answer.rrset]
  429. else:
  430. answer = resolve(host, family, False)
  431. if answer.rrset:
  432. addrs = [rr.address for rr in answer.rrset]
  433. return str(answer.qname), addrs
  434. def getaddrinfo(host, port, family=0, socktype=0, proto=0, flags=0):
  435. """Replacement for Python's socket.getaddrinfo
  436. This does the A and AAAA lookups asynchronously after which it
  437. calls the OS' getaddrinfo(3) using the AI_NUMERICHOST flag. This
  438. flag ensures getaddrinfo(3) does not use the network itself and
  439. allows us to respect all the other arguments like the native OS.
  440. """
  441. if isinstance(host, six.string_types):
  442. host = host.encode('idna').decode('ascii')
  443. if host is not None and not is_ip_addr(host):
  444. qname, addrs = _getaddrinfo_lookup(host, family, flags)
  445. else:
  446. qname = host
  447. addrs = [host]
  448. aiflags = (flags | socket.AI_NUMERICHOST) & (0xffff ^ socket.AI_CANONNAME)
  449. res = []
  450. err = None
  451. for addr in addrs:
  452. try:
  453. ai = socket.getaddrinfo(addr, port, family,
  454. socktype, proto, aiflags)
  455. except socket.error as e:
  456. if flags & socket.AI_ADDRCONFIG:
  457. err = e
  458. continue
  459. raise
  460. res.extend(ai)
  461. if not res:
  462. if err:
  463. raise err
  464. raise socket.gaierror(socket.EAI_NONAME, 'No address found')
  465. if flags & socket.AI_CANONNAME:
  466. if not is_ip_addr(qname):
  467. qname = resolve_cname(qname).encode('ascii').decode('idna')
  468. ai = res[0]
  469. res[0] = (ai[0], ai[1], ai[2], qname, ai[4])
  470. return res
  471. def gethostbyname(hostname):
  472. """Replacement for Python's socket.gethostbyname"""
  473. if is_ipv4_addr(hostname):
  474. return hostname
  475. rrset = resolve(hostname)
  476. return rrset[0].address
  477. def gethostbyname_ex(hostname):
  478. """Replacement for Python's socket.gethostbyname_ex"""
  479. if is_ipv4_addr(hostname):
  480. return (hostname, [], [hostname])
  481. ans = resolve(hostname)
  482. aliases = getaliases(hostname)
  483. addrs = [rr.address for rr in ans.rrset]
  484. qname = str(ans.qname)
  485. if qname[-1] == '.':
  486. qname = qname[:-1]
  487. return (qname, aliases, addrs)
  488. def getnameinfo(sockaddr, flags):
  489. """Replacement for Python's socket.getnameinfo.
  490. Currently only supports IPv4.
  491. """
  492. try:
  493. host, port = sockaddr
  494. except (ValueError, TypeError):
  495. if not isinstance(sockaddr, tuple):
  496. del sockaddr # to pass a stdlib test that is
  497. # hyper-careful about reference counts
  498. raise TypeError('getnameinfo() argument 1 must be a tuple')
  499. else:
  500. # must be ipv6 sockaddr, pretending we don't know how to resolve it
  501. raise EAI_NONAME_ERROR
  502. if (flags & socket.NI_NAMEREQD) and (flags & socket.NI_NUMERICHOST):
  503. # Conflicting flags. Punt.
  504. raise EAI_NONAME_ERROR
  505. if is_ipv4_addr(host):
  506. try:
  507. rrset = resolver.query(
  508. dns.reversename.from_address(host), dns.rdatatype.PTR)
  509. if len(rrset) > 1:
  510. raise socket.error('sockaddr resolved to multiple addresses')
  511. host = rrset[0].target.to_text(omit_final_dot=True)
  512. except dns.exception.Timeout:
  513. if flags & socket.NI_NAMEREQD:
  514. raise EAI_EAGAIN_ERROR
  515. except dns.exception.DNSException:
  516. if flags & socket.NI_NAMEREQD:
  517. raise EAI_NONAME_ERROR
  518. else:
  519. try:
  520. rrset = resolver.query(host)
  521. if len(rrset) > 1:
  522. raise socket.error('sockaddr resolved to multiple addresses')
  523. if flags & socket.NI_NUMERICHOST:
  524. host = rrset[0].address
  525. except dns.exception.Timeout:
  526. raise EAI_EAGAIN_ERROR
  527. except dns.exception.DNSException:
  528. raise socket.gaierror(
  529. (socket.EAI_NODATA, 'No address associated with hostname'))
  530. if not (flags & socket.NI_NUMERICSERV):
  531. proto = (flags & socket.NI_DGRAM) and 'udp' or 'tcp'
  532. port = socket.getservbyport(port, proto)
  533. return (host, port)
  534. def _net_read(sock, count, expiration):
  535. """coro friendly replacement for dns.query._net_read
  536. Read the specified number of bytes from sock. Keep trying until we
  537. either get the desired amount, or we hit EOF.
  538. A Timeout exception will be raised if the operation is not completed
  539. by the expiration time.
  540. """
  541. s = bytearray()
  542. while count > 0:
  543. try:
  544. n = sock.recv(count)
  545. except socket.timeout:
  546. # Q: Do we also need to catch coro.CoroutineSocketWake and pass?
  547. if expiration - time.time() <= 0.0:
  548. raise dns.exception.Timeout
  549. eventlet.sleep(0.01)
  550. continue
  551. if n == b'':
  552. raise EOFError
  553. count = count - len(n)
  554. s += n
  555. return s
  556. def _net_write(sock, data, expiration):
  557. """coro friendly replacement for dns.query._net_write
  558. Write the specified data to the socket.
  559. A Timeout exception will be raised if the operation is not completed
  560. by the expiration time.
  561. """
  562. current = 0
  563. l = len(data)
  564. while current < l:
  565. try:
  566. current += sock.send(data[current:])
  567. except socket.timeout:
  568. # Q: Do we also need to catch coro.CoroutineSocketWake and pass?
  569. if expiration - time.time() <= 0.0:
  570. raise dns.exception.Timeout
  571. def udp(q, where, timeout=DNS_QUERY_TIMEOUT, port=53,
  572. af=None, source=None, source_port=0, ignore_unexpected=False):
  573. """coro friendly replacement for dns.query.udp
  574. Return the response obtained after sending a query via UDP.
  575. @param q: the query
  576. @type q: dns.message.Message
  577. @param where: where to send the message
  578. @type where: string containing an IPv4 or IPv6 address
  579. @param timeout: The number of seconds to wait before the query times out.
  580. If None, the default, wait forever.
  581. @type timeout: float
  582. @param port: The port to which to send the message. The default is 53.
  583. @type port: int
  584. @param af: the address family to use. The default is None, which
  585. causes the address family to use to be inferred from the form of of where.
  586. If the inference attempt fails, AF_INET is used.
  587. @type af: int
  588. @rtype: dns.message.Message object
  589. @param source: source address. The default is the IPv4 wildcard address.
  590. @type source: string
  591. @param source_port: The port from which to send the message.
  592. The default is 0.
  593. @type source_port: int
  594. @param ignore_unexpected: If True, ignore responses from unexpected
  595. sources. The default is False.
  596. @type ignore_unexpected: bool"""
  597. wire = q.to_wire()
  598. if af is None:
  599. try:
  600. af = dns.inet.af_for_address(where)
  601. except:
  602. af = dns.inet.AF_INET
  603. if af == dns.inet.AF_INET:
  604. destination = (where, port)
  605. if source is not None:
  606. source = (source, source_port)
  607. elif af == dns.inet.AF_INET6:
  608. # Purge any stray zeroes in source address. When doing the tuple comparison
  609. # below, we need to always ensure both our target and where we receive replies
  610. # from are compared with all zeroes removed so that we don't erroneously fail.
  611. # e.g. ('00::1', 53, 0, 0) != ('::1', 53, 0, 0)
  612. where_trunc = dns.ipv6.inet_ntoa(dns.ipv6.inet_aton(where))
  613. destination = (where_trunc, port, 0, 0)
  614. if source is not None:
  615. source = (source, source_port, 0, 0)
  616. s = socket.socket(af, socket.SOCK_DGRAM)
  617. s.settimeout(timeout)
  618. try:
  619. expiration = dns.query._compute_expiration(timeout)
  620. if source is not None:
  621. s.bind(source)
  622. while True:
  623. try:
  624. s.sendto(wire, destination)
  625. break
  626. except socket.timeout:
  627. # Q: Do we also need to catch coro.CoroutineSocketWake and pass?
  628. if expiration - time.time() <= 0.0:
  629. raise dns.exception.Timeout
  630. eventlet.sleep(0.01)
  631. continue
  632. tried = False
  633. while True:
  634. # If we've tried to receive at least once, check to see if our
  635. # timer expired
  636. if tried and (expiration - time.time() <= 0.0):
  637. raise dns.exception.Timeout
  638. # Sleep if we are retrying the operation due to a bad source
  639. # address or a socket timeout.
  640. if tried:
  641. eventlet.sleep(0.01)
  642. tried = True
  643. try:
  644. (wire, from_address) = s.recvfrom(65535)
  645. except socket.timeout:
  646. # Q: Do we also need to catch coro.CoroutineSocketWake and pass?
  647. continue
  648. if dns.inet.af_for_address(from_address[0]) == dns.inet.AF_INET6:
  649. # Purge all possible zeroes for ipv6 to match above logic
  650. addr = from_address[0]
  651. addr = dns.ipv6.inet_ntoa(dns.ipv6.inet_aton(addr))
  652. from_address = (addr, from_address[1], from_address[2], from_address[3])
  653. if from_address == destination:
  654. break
  655. if not ignore_unexpected:
  656. raise dns.query.UnexpectedSource(
  657. 'got a response from %s instead of %s'
  658. % (from_address, destination))
  659. finally:
  660. s.close()
  661. r = dns.message.from_wire(wire, keyring=q.keyring, request_mac=q.mac)
  662. if not q.is_response(r):
  663. raise dns.query.BadResponse()
  664. return r
  665. def tcp(q, where, timeout=DNS_QUERY_TIMEOUT, port=53,
  666. af=None, source=None, source_port=0):
  667. """coro friendly replacement for dns.query.tcp
  668. Return the response obtained after sending a query via TCP.
  669. @param q: the query
  670. @type q: dns.message.Message object
  671. @param where: where to send the message
  672. @type where: string containing an IPv4 or IPv6 address
  673. @param timeout: The number of seconds to wait before the query times out.
  674. If None, the default, wait forever.
  675. @type timeout: float
  676. @param port: The port to which to send the message. The default is 53.
  677. @type port: int
  678. @param af: the address family to use. The default is None, which
  679. causes the address family to use to be inferred from the form of of where.
  680. If the inference attempt fails, AF_INET is used.
  681. @type af: int
  682. @rtype: dns.message.Message object
  683. @param source: source address. The default is the IPv4 wildcard address.
  684. @type source: string
  685. @param source_port: The port from which to send the message.
  686. The default is 0.
  687. @type source_port: int"""
  688. wire = q.to_wire()
  689. if af is None:
  690. try:
  691. af = dns.inet.af_for_address(where)
  692. except:
  693. af = dns.inet.AF_INET
  694. if af == dns.inet.AF_INET:
  695. destination = (where, port)
  696. if source is not None:
  697. source = (source, source_port)
  698. elif af == dns.inet.AF_INET6:
  699. destination = (where, port, 0, 0)
  700. if source is not None:
  701. source = (source, source_port, 0, 0)
  702. s = socket.socket(af, socket.SOCK_STREAM)
  703. s.settimeout(timeout)
  704. try:
  705. expiration = dns.query._compute_expiration(timeout)
  706. if source is not None:
  707. s.bind(source)
  708. while True:
  709. try:
  710. s.connect(destination)
  711. break
  712. except socket.timeout:
  713. # Q: Do we also need to catch coro.CoroutineSocketWake and pass?
  714. if expiration - time.time() <= 0.0:
  715. raise dns.exception.Timeout
  716. eventlet.sleep(0.01)
  717. continue
  718. l = len(wire)
  719. # copying the wire into tcpmsg is inefficient, but lets us
  720. # avoid writev() or doing a short write that would get pushed
  721. # onto the net
  722. tcpmsg = struct.pack("!H", l) + wire
  723. _net_write(s, tcpmsg, expiration)
  724. ldata = _net_read(s, 2, expiration)
  725. (l,) = struct.unpack("!H", ldata)
  726. wire = bytes(_net_read(s, l, expiration))
  727. finally:
  728. s.close()
  729. r = dns.message.from_wire(wire, keyring=q.keyring, request_mac=q.mac)
  730. if not q.is_response(r):
  731. raise dns.query.BadResponse()
  732. return r
  733. def reset():
  734. resolver.clear()
  735. # Install our coro-friendly replacements for the tcp and udp query methods.
  736. dns.query.tcp = tcp
  737. dns.query.udp = udp