common.py 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  1. # -*- test-case-name: twisted.names.test -*-
  2. # Copyright (c) Twisted Matrix Laboratories.
  3. # See LICENSE for details.
  4. """
  5. Base functionality useful to various parts of Twisted Names.
  6. """
  7. from __future__ import division, absolute_import
  8. import socket
  9. from zope.interface import implementer
  10. from twisted.names import dns
  11. from twisted.names.error import DNSFormatError, DNSServerError, DNSNameError
  12. from twisted.names.error import DNSNotImplementedError, DNSQueryRefusedError
  13. from twisted.names.error import DNSUnknownError
  14. from twisted.internet import defer, error, interfaces
  15. from twisted.logger import Logger
  16. # Helpers for indexing the three-tuples that get thrown around by this code a
  17. # lot.
  18. _ANS, _AUTH, _ADD = range(3)
  19. EMPTY_RESULT = (), (), ()
  20. @implementer(interfaces.IResolver)
  21. class ResolverBase:
  22. """
  23. L{ResolverBase} is a base class for implementations of
  24. L{interfaces.IResolver} which deals with a lot
  25. of the boilerplate of implementing all of the lookup methods.
  26. @cvar _errormap: A C{dict} mapping DNS protocol failure response codes
  27. to exception classes which will be used to represent those failures.
  28. """
  29. _log = Logger()
  30. _errormap = {
  31. dns.EFORMAT: DNSFormatError,
  32. dns.ESERVER: DNSServerError,
  33. dns.ENAME: DNSNameError,
  34. dns.ENOTIMP: DNSNotImplementedError,
  35. dns.EREFUSED: DNSQueryRefusedError}
  36. typeToMethod = None
  37. def __init__(self):
  38. self.typeToMethod = {}
  39. for (k, v) in typeToMethod.items():
  40. self.typeToMethod[k] = getattr(self, v)
  41. def exceptionForCode(self, responseCode):
  42. """
  43. Convert a response code (one of the possible values of
  44. L{dns.Message.rCode} to an exception instance representing it.
  45. @since: 10.0
  46. """
  47. return self._errormap.get(responseCode, DNSUnknownError)
  48. def query(self, query, timeout=None):
  49. try:
  50. method = self.typeToMethod[query.type]
  51. except KeyError:
  52. self._log.debug(
  53. 'Query of unknown type {query.type} for {query.name.name!r}',
  54. query=query)
  55. return defer.maybeDeferred(
  56. self._lookup, query.name.name, dns.IN, query.type, timeout)
  57. else:
  58. return defer.maybeDeferred(method, query.name.name, timeout)
  59. def _lookup(self, name, cls, type, timeout):
  60. return defer.fail(NotImplementedError("ResolverBase._lookup"))
  61. def lookupAddress(self, name, timeout=None):
  62. return self._lookup(dns.domainString(name), dns.IN, dns.A, timeout)
  63. def lookupIPV6Address(self, name, timeout=None):
  64. return self._lookup(dns.domainString(name), dns.IN, dns.AAAA, timeout)
  65. def lookupAddress6(self, name, timeout=None):
  66. return self._lookup(dns.domainString(name), dns.IN, dns.A6, timeout)
  67. def lookupMailExchange(self, name, timeout=None):
  68. return self._lookup(dns.domainString(name), dns.IN, dns.MX, timeout)
  69. def lookupNameservers(self, name, timeout=None):
  70. return self._lookup(dns.domainString(name), dns.IN, dns.NS, timeout)
  71. def lookupCanonicalName(self, name, timeout=None):
  72. return self._lookup(dns.domainString(name), dns.IN, dns.CNAME, timeout)
  73. def lookupMailBox(self, name, timeout=None):
  74. return self._lookup(dns.domainString(name), dns.IN, dns.MB, timeout)
  75. def lookupMailGroup(self, name, timeout=None):
  76. return self._lookup(dns.domainString(name), dns.IN, dns.MG, timeout)
  77. def lookupMailRename(self, name, timeout=None):
  78. return self._lookup(dns.domainString(name), dns.IN, dns.MR, timeout)
  79. def lookupPointer(self, name, timeout=None):
  80. return self._lookup(dns.domainString(name), dns.IN, dns.PTR, timeout)
  81. def lookupAuthority(self, name, timeout=None):
  82. return self._lookup(dns.domainString(name), dns.IN, dns.SOA, timeout)
  83. def lookupNull(self, name, timeout=None):
  84. return self._lookup(dns.domainString(name), dns.IN, dns.NULL, timeout)
  85. def lookupWellKnownServices(self, name, timeout=None):
  86. return self._lookup(dns.domainString(name), dns.IN, dns.WKS, timeout)
  87. def lookupService(self, name, timeout=None):
  88. return self._lookup(dns.domainString(name), dns.IN, dns.SRV, timeout)
  89. def lookupHostInfo(self, name, timeout=None):
  90. return self._lookup(dns.domainString(name), dns.IN, dns.HINFO, timeout)
  91. def lookupMailboxInfo(self, name, timeout=None):
  92. return self._lookup(dns.domainString(name), dns.IN, dns.MINFO, timeout)
  93. def lookupText(self, name, timeout=None):
  94. return self._lookup(dns.domainString(name), dns.IN, dns.TXT, timeout)
  95. def lookupSenderPolicy(self, name, timeout=None):
  96. return self._lookup(dns.domainString(name), dns.IN, dns.SPF, timeout)
  97. def lookupResponsibility(self, name, timeout=None):
  98. return self._lookup(dns.domainString(name), dns.IN, dns.RP, timeout)
  99. def lookupAFSDatabase(self, name, timeout=None):
  100. return self._lookup(dns.domainString(name), dns.IN, dns.AFSDB, timeout)
  101. def lookupZone(self, name, timeout=None):
  102. return self._lookup(dns.domainString(name), dns.IN, dns.AXFR, timeout)
  103. def lookupNamingAuthorityPointer(self, name, timeout=None):
  104. return self._lookup(dns.domainString(name), dns.IN, dns.NAPTR, timeout)
  105. def lookupAllRecords(self, name, timeout=None):
  106. return self._lookup(dns.domainString(name), dns.IN, dns.ALL_RECORDS,
  107. timeout)
  108. # IResolverSimple
  109. def getHostByName(self, name, timeout=None, effort=10):
  110. name = dns.domainString(name)
  111. # XXX - respect timeout
  112. # XXX - this should do A and AAAA lookups, not ANY (see RFC 8482).
  113. # https://twistedmatrix.com/trac/ticket/9691
  114. d = self.lookupAllRecords(name, timeout)
  115. d.addCallback(self._cbRecords, name, effort)
  116. return d
  117. def _cbRecords(self, records, name, effort):
  118. (ans, auth, add) = records
  119. result = extractRecord(self, dns.Name(name), ans + auth + add, effort)
  120. if not result:
  121. raise error.DNSLookupError(name)
  122. return result
  123. def extractRecord(resolver, name, answers, level=10):
  124. """
  125. Resolve a name to an IP address, following I{CNAME} records and I{NS}
  126. referrals recursively.
  127. This is an implementation detail of L{ResolverBase.getHostByName}.
  128. @param resolver: The resolver to use for the next query (unless handling
  129. an I{NS} referral).
  130. @type resolver: L{IResolver}
  131. @param name: The name being looked up.
  132. @type name: L{dns.Name}
  133. @param answers: All of the records returned by the previous query (answers,
  134. authority, and additional concatenated).
  135. @type answers: L{list} of L{dns.RRHeader}
  136. @param level: Remaining recursion budget. This is decremented at each
  137. recursion. The query returns L{None} when it reaches 0.
  138. @type level: L{int}
  139. @returns: The first IPv4 or IPv6 address (as a dotted quad or colon
  140. quibbles), or L{None} when no result is found.
  141. @rtype: native L{str} or L{None}
  142. """
  143. if not level:
  144. return None
  145. # FIXME: twisted.python.compat monkeypatches this if missing, so this
  146. # condition is always true. https://twistedmatrix.com/trac/ticket/9753
  147. if hasattr(socket, 'inet_ntop'):
  148. for r in answers:
  149. if r.name == name and r.type == dns.A6:
  150. return socket.inet_ntop(socket.AF_INET6, r.payload.address)
  151. for r in answers:
  152. if r.name == name and r.type == dns.AAAA:
  153. return socket.inet_ntop(socket.AF_INET6, r.payload.address)
  154. for r in answers:
  155. if r.name == name and r.type == dns.A:
  156. return socket.inet_ntop(socket.AF_INET, r.payload.address)
  157. for r in answers:
  158. if r.name == name and r.type == dns.CNAME:
  159. result = extractRecord(
  160. resolver, r.payload.name, answers, level - 1)
  161. if not result:
  162. return resolver.getHostByName(
  163. r.payload.name.name, effort=level - 1)
  164. return result
  165. # No answers, but maybe there's a hint at who we should be asking about
  166. # this
  167. for r in answers:
  168. if r.type != dns.NS:
  169. continue
  170. from twisted.names import client
  171. nsResolver = client.Resolver(servers=[
  172. (r.payload.name.name.decode('ascii'), dns.PORT),
  173. ])
  174. def queryAgain(records):
  175. (ans, auth, add) = records
  176. return extractRecord(nsResolver, name, ans + auth + add, level - 1)
  177. return nsResolver.lookupAddress(name.name).addCallback(queryAgain)
  178. typeToMethod = {
  179. dns.A: 'lookupAddress',
  180. dns.AAAA: 'lookupIPV6Address',
  181. dns.A6: 'lookupAddress6',
  182. dns.NS: 'lookupNameservers',
  183. dns.CNAME: 'lookupCanonicalName',
  184. dns.SOA: 'lookupAuthority',
  185. dns.MB: 'lookupMailBox',
  186. dns.MG: 'lookupMailGroup',
  187. dns.MR: 'lookupMailRename',
  188. dns.NULL: 'lookupNull',
  189. dns.WKS: 'lookupWellKnownServices',
  190. dns.PTR: 'lookupPointer',
  191. dns.HINFO: 'lookupHostInfo',
  192. dns.MINFO: 'lookupMailboxInfo',
  193. dns.MX: 'lookupMailExchange',
  194. dns.TXT: 'lookupText',
  195. dns.SPF: 'lookupSenderPolicy',
  196. dns.RP: 'lookupResponsibility',
  197. dns.AFSDB: 'lookupAFSDatabase',
  198. dns.SRV: 'lookupService',
  199. dns.NAPTR: 'lookupNamingAuthorityPointer',
  200. dns.AXFR: 'lookupZone',
  201. dns.ALL_RECORDS: 'lookupAllRecords',
  202. }