client.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754
  1. # -*- test-case-name: twisted.names.test.test_names -*-
  2. # Copyright (c) Twisted Matrix Laboratories.
  3. # See LICENSE for details.
  4. """
  5. Asynchronous client DNS
  6. The functions exposed in this module can be used for asynchronous name
  7. resolution and dns queries.
  8. If you need to create a resolver with specific requirements, such as needing to
  9. do queries against a particular host, the L{createResolver} function will
  10. return an C{IResolver}.
  11. Future plans: Proper nameserver acquisition on Windows/MacOS,
  12. better caching, respect timeouts
  13. """
  14. import os
  15. import errno
  16. import warnings
  17. from zope.interface import moduleProvides
  18. # Twisted imports
  19. from twisted.python.compat import nativeString
  20. from twisted.python.runtime import platform
  21. from twisted.python.filepath import FilePath
  22. from twisted.internet import error, defer, interfaces, protocol
  23. from twisted.python import log, failure
  24. from twisted.names import (
  25. dns, common, resolve, cache, root, hosts as hostsModule)
  26. from twisted.internet.abstract import isIPv6Address
  27. moduleProvides(interfaces.IResolver)
  28. class Resolver(common.ResolverBase):
  29. """
  30. @ivar _waiting: A C{dict} mapping tuple keys of query name/type/class to
  31. Deferreds which will be called back with the result of those queries.
  32. This is used to avoid issuing the same query more than once in
  33. parallel. This is more efficient on the network and helps avoid a
  34. "birthday paradox" attack by keeping the number of outstanding requests
  35. for a particular query fixed at one instead of allowing the attacker to
  36. raise it to an arbitrary number.
  37. @ivar _reactor: A provider of L{IReactorTCP}, L{IReactorUDP}, and
  38. L{IReactorTime} which will be used to set up network resources and
  39. track timeouts.
  40. """
  41. index = 0
  42. timeout = None
  43. factory = None
  44. servers = None
  45. dynServers = ()
  46. pending = None
  47. connections = None
  48. resolv = None
  49. _lastResolvTime = None
  50. _resolvReadInterval = 60
  51. def __init__(self, resolv=None, servers=None, timeout=(1, 3, 11, 45), reactor=None):
  52. """
  53. Construct a resolver which will query domain name servers listed in
  54. the C{resolv.conf(5)}-format file given by C{resolv} as well as
  55. those in the given C{servers} list. Servers are queried in a
  56. round-robin fashion. If given, C{resolv} is periodically checked
  57. for modification and re-parsed if it is noticed to have changed.
  58. @type servers: C{list} of C{(str, int)} or L{None}
  59. @param servers: If not None, interpreted as a list of (host, port)
  60. pairs specifying addresses of domain name servers to attempt to use
  61. for this lookup. Host addresses should be in IPv4 dotted-quad
  62. form. If specified, overrides C{resolv}.
  63. @type resolv: C{str}
  64. @param resolv: Filename to read and parse as a resolver(5)
  65. configuration file.
  66. @type timeout: Sequence of C{int}
  67. @param timeout: Default number of seconds after which to reissue the
  68. query. When the last timeout expires, the query is considered
  69. failed.
  70. @param reactor: A provider of L{IReactorTime}, L{IReactorUDP}, and
  71. L{IReactorTCP} which will be used to establish connections, listen
  72. for DNS datagrams, and enforce timeouts. If not provided, the
  73. global reactor will be used.
  74. @raise ValueError: Raised if no nameserver addresses can be found.
  75. """
  76. common.ResolverBase.__init__(self)
  77. if reactor is None:
  78. from twisted.internet import reactor
  79. self._reactor = reactor
  80. self.timeout = timeout
  81. if servers is None:
  82. self.servers = []
  83. else:
  84. self.servers = servers
  85. self.resolv = resolv
  86. if not len(self.servers) and not resolv:
  87. raise ValueError("No nameservers specified")
  88. self.factory = DNSClientFactory(self, timeout)
  89. self.factory.noisy = 0 # Be quiet by default
  90. self.connections = []
  91. self.pending = []
  92. self._waiting = {}
  93. self.maybeParseConfig()
  94. def __getstate__(self):
  95. d = self.__dict__.copy()
  96. d['connections'] = []
  97. d['_parseCall'] = None
  98. return d
  99. def __setstate__(self, state):
  100. self.__dict__.update(state)
  101. self.maybeParseConfig()
  102. def _openFile(self, path):
  103. """
  104. Wrapper used for opening files in the class, exists primarily for unit
  105. testing purposes.
  106. """
  107. return FilePath(path).open()
  108. def maybeParseConfig(self):
  109. if self.resolv is None:
  110. # Don't try to parse it, don't set up a call loop
  111. return
  112. try:
  113. resolvConf = self._openFile(self.resolv)
  114. except IOError as e:
  115. if e.errno == errno.ENOENT:
  116. # Missing resolv.conf is treated the same as an empty resolv.conf
  117. self.parseConfig(())
  118. else:
  119. raise
  120. else:
  121. with resolvConf:
  122. mtime = os.fstat(resolvConf.fileno()).st_mtime
  123. if mtime != self._lastResolvTime:
  124. log.msg('%s changed, reparsing' % (self.resolv,))
  125. self._lastResolvTime = mtime
  126. self.parseConfig(resolvConf)
  127. # Check again in a little while
  128. self._parseCall = self._reactor.callLater(
  129. self._resolvReadInterval, self.maybeParseConfig)
  130. def parseConfig(self, resolvConf):
  131. servers = []
  132. for L in resolvConf:
  133. L = L.strip()
  134. if L.startswith(b'nameserver'):
  135. resolver = (nativeString(L.split()[1]), dns.PORT)
  136. servers.append(resolver)
  137. log.msg("Resolver added %r to server list" % (resolver,))
  138. elif L.startswith(b'domain'):
  139. try:
  140. self.domain = L.split()[1]
  141. except IndexError:
  142. self.domain = b''
  143. self.search = None
  144. elif L.startswith(b'search'):
  145. self.search = L.split()[1:]
  146. self.domain = None
  147. if not servers:
  148. servers.append(('127.0.0.1', dns.PORT))
  149. self.dynServers = servers
  150. def pickServer(self):
  151. """
  152. Return the address of a nameserver.
  153. TODO: Weight servers for response time so faster ones can be
  154. preferred.
  155. """
  156. if not self.servers and not self.dynServers:
  157. return None
  158. serverL = len(self.servers)
  159. dynL = len(self.dynServers)
  160. self.index += 1
  161. self.index %= (serverL + dynL)
  162. if self.index < serverL:
  163. return self.servers[self.index]
  164. else:
  165. return self.dynServers[self.index - serverL]
  166. def _connectedProtocol(self, interface=''):
  167. """
  168. Return a new L{DNSDatagramProtocol} bound to a randomly selected port
  169. number.
  170. """
  171. proto = dns.DNSDatagramProtocol(self, reactor=self._reactor)
  172. while True:
  173. try:
  174. self._reactor.listenUDP(dns.randomSource(), proto,
  175. interface=interface)
  176. except error.CannotListenError:
  177. pass
  178. else:
  179. return proto
  180. def connectionMade(self, protocol):
  181. """
  182. Called by associated L{dns.DNSProtocol} instances when they connect.
  183. """
  184. self.connections.append(protocol)
  185. for (d, q, t) in self.pending:
  186. self.queryTCP(q, t).chainDeferred(d)
  187. del self.pending[:]
  188. def connectionLost(self, protocol):
  189. """
  190. Called by associated L{dns.DNSProtocol} instances when they disconnect.
  191. """
  192. if protocol in self.connections:
  193. self.connections.remove(protocol)
  194. def messageReceived(self, message, protocol, address = None):
  195. log.msg("Unexpected message (%d) received from %r" % (message.id, address))
  196. def _query(self, *args):
  197. """
  198. Get a new L{DNSDatagramProtocol} instance from L{_connectedProtocol},
  199. issue a query to it using C{*args}, and arrange for it to be
  200. disconnected from its transport after the query completes.
  201. @param *args: Positional arguments to be passed to
  202. L{DNSDatagramProtocol.query}.
  203. @return: A L{Deferred} which will be called back with the result of the
  204. query.
  205. """
  206. if isIPv6Address(args[0][0]):
  207. protocol = self._connectedProtocol(interface='::')
  208. else:
  209. protocol = self._connectedProtocol()
  210. d = protocol.query(*args)
  211. def cbQueried(result):
  212. protocol.transport.stopListening()
  213. return result
  214. d.addBoth(cbQueried)
  215. return d
  216. def queryUDP(self, queries, timeout = None):
  217. """
  218. Make a number of DNS queries via UDP.
  219. @type queries: A C{list} of C{dns.Query} instances
  220. @param queries: The queries to make.
  221. @type timeout: Sequence of C{int}
  222. @param timeout: Number of seconds after which to reissue the query.
  223. When the last timeout expires, the query is considered failed.
  224. @rtype: C{Deferred}
  225. @raise C{twisted.internet.defer.TimeoutError}: When the query times
  226. out.
  227. """
  228. if timeout is None:
  229. timeout = self.timeout
  230. addresses = self.servers + list(self.dynServers)
  231. if not addresses:
  232. return defer.fail(IOError("No domain name servers available"))
  233. # Make sure we go through servers in the list in the order they were
  234. # specified.
  235. addresses.reverse()
  236. used = addresses.pop()
  237. d = self._query(used, queries, timeout[0])
  238. d.addErrback(self._reissue, addresses, [used], queries, timeout)
  239. return d
  240. def _reissue(self, reason, addressesLeft, addressesUsed, query, timeout):
  241. reason.trap(dns.DNSQueryTimeoutError)
  242. # If there are no servers left to be tried, adjust the timeout
  243. # to the next longest timeout period and move all the
  244. # "used" addresses back to the list of addresses to try.
  245. if not addressesLeft:
  246. addressesLeft = addressesUsed
  247. addressesLeft.reverse()
  248. addressesUsed = []
  249. timeout = timeout[1:]
  250. # If all timeout values have been used this query has failed. Tell the
  251. # protocol we're giving up on it and return a terminal timeout failure
  252. # to our caller.
  253. if not timeout:
  254. return failure.Failure(defer.TimeoutError(query))
  255. # Get an address to try. Take it out of the list of addresses
  256. # to try and put it ino the list of already tried addresses.
  257. address = addressesLeft.pop()
  258. addressesUsed.append(address)
  259. # Issue a query to a server. Use the current timeout. Add this
  260. # function as a timeout errback in case another retry is required.
  261. d = self._query(address, query, timeout[0], reason.value.id)
  262. d.addErrback(self._reissue, addressesLeft, addressesUsed, query, timeout)
  263. return d
  264. def queryTCP(self, queries, timeout = 10):
  265. """
  266. Make a number of DNS queries via TCP.
  267. @type queries: Any non-zero number of C{dns.Query} instances
  268. @param queries: The queries to make.
  269. @type timeout: C{int}
  270. @param timeout: The number of seconds after which to fail.
  271. @rtype: C{Deferred}
  272. """
  273. if not len(self.connections):
  274. address = self.pickServer()
  275. if address is None:
  276. return defer.fail(IOError("No domain name servers available"))
  277. host, port = address
  278. self._reactor.connectTCP(host, port, self.factory)
  279. self.pending.append((defer.Deferred(), queries, timeout))
  280. return self.pending[-1][0]
  281. else:
  282. return self.connections[0].query(queries, timeout)
  283. def filterAnswers(self, message):
  284. """
  285. Extract results from the given message.
  286. If the message was truncated, re-attempt the query over TCP and return
  287. a Deferred which will fire with the results of that query.
  288. If the message's result code is not C{twisted.names.dns.OK}, return a
  289. Failure indicating the type of error which occurred.
  290. Otherwise, return a three-tuple of lists containing the results from
  291. the answers section, the authority section, and the additional section.
  292. """
  293. if message.trunc:
  294. return self.queryTCP(message.queries).addCallback(self.filterAnswers)
  295. if message.rCode != dns.OK:
  296. return failure.Failure(self.exceptionForCode(message.rCode)(message))
  297. return (message.answers, message.authority, message.additional)
  298. def _lookup(self, name, cls, type, timeout):
  299. """
  300. Build a L{dns.Query} for the given parameters and dispatch it via UDP.
  301. If this query is already outstanding, it will not be re-issued.
  302. Instead, when the outstanding query receives a response, that response
  303. will be re-used for this query as well.
  304. @type name: C{str}
  305. @type type: C{int}
  306. @type cls: C{int}
  307. @return: A L{Deferred} which fires with a three-tuple giving the
  308. answer, authority, and additional sections of the response or with
  309. a L{Failure} if the response code is anything other than C{dns.OK}.
  310. """
  311. key = (name, type, cls)
  312. waiting = self._waiting.get(key)
  313. if waiting is None:
  314. self._waiting[key] = []
  315. d = self.queryUDP([dns.Query(name, type, cls)], timeout)
  316. def cbResult(result):
  317. for d in self._waiting.pop(key):
  318. d.callback(result)
  319. return result
  320. d.addCallback(self.filterAnswers)
  321. d.addBoth(cbResult)
  322. else:
  323. d = defer.Deferred()
  324. waiting.append(d)
  325. return d
  326. # This one doesn't ever belong on UDP
  327. def lookupZone(self, name, timeout=10):
  328. address = self.pickServer()
  329. if address is None:
  330. return defer.fail(IOError('No domain name servers available'))
  331. host, port = address
  332. d = defer.Deferred()
  333. controller = AXFRController(name, d)
  334. factory = DNSClientFactory(controller, timeout)
  335. factory.noisy = False #stfu
  336. connector = self._reactor.connectTCP(host, port, factory)
  337. controller.timeoutCall = self._reactor.callLater(
  338. timeout or 10, self._timeoutZone, d, controller,
  339. connector, timeout or 10)
  340. return d.addCallback(self._cbLookupZone, connector)
  341. def _timeoutZone(self, d, controller, connector, seconds):
  342. connector.disconnect()
  343. controller.timeoutCall = None
  344. controller.deferred = None
  345. d.errback(error.TimeoutError("Zone lookup timed out after %d seconds" % (seconds,)))
  346. def _cbLookupZone(self, result, connector):
  347. connector.disconnect()
  348. return (result, [], [])
  349. class AXFRController:
  350. timeoutCall = None
  351. def __init__(self, name, deferred):
  352. self.name = name
  353. self.deferred = deferred
  354. self.soa = None
  355. self.records = []
  356. def connectionMade(self, protocol):
  357. # dig saids recursion-desired to 0, so I will too
  358. message = dns.Message(protocol.pickID(), recDes=0)
  359. message.queries = [dns.Query(self.name, dns.AXFR, dns.IN)]
  360. protocol.writeMessage(message)
  361. def connectionLost(self, protocol):
  362. # XXX Do something here - see #3428
  363. pass
  364. def messageReceived(self, message, protocol):
  365. # Caveat: We have to handle two cases: All records are in 1
  366. # message, or all records are in N messages.
  367. # According to http://cr.yp.to/djbdns/axfr-notes.html,
  368. # 'authority' and 'additional' are always empty, and only
  369. # 'answers' is present.
  370. self.records.extend(message.answers)
  371. if not self.records:
  372. return
  373. if not self.soa:
  374. if self.records[0].type == dns.SOA:
  375. #print "first SOA!"
  376. self.soa = self.records[0]
  377. if len(self.records) > 1 and self.records[-1].type == dns.SOA:
  378. #print "It's the second SOA! We're done."
  379. if self.timeoutCall is not None:
  380. self.timeoutCall.cancel()
  381. self.timeoutCall = None
  382. if self.deferred is not None:
  383. self.deferred.callback(self.records)
  384. self.deferred = None
  385. from twisted.internet.base import ThreadedResolver as _ThreadedResolverImpl
  386. class ThreadedResolver(_ThreadedResolverImpl):
  387. def __init__(self, reactor=None):
  388. if reactor is None:
  389. from twisted.internet import reactor
  390. _ThreadedResolverImpl.__init__(self, reactor)
  391. warnings.warn(
  392. "twisted.names.client.ThreadedResolver is deprecated since "
  393. "Twisted 9.0, use twisted.internet.base.ThreadedResolver "
  394. "instead.",
  395. category=DeprecationWarning, stacklevel=2)
  396. class DNSClientFactory(protocol.ClientFactory):
  397. def __init__(self, controller, timeout = 10):
  398. self.controller = controller
  399. self.timeout = timeout
  400. def clientConnectionLost(self, connector, reason):
  401. pass
  402. def clientConnectionFailed(self, connector, reason):
  403. """
  404. Fail all pending TCP DNS queries if the TCP connection attempt
  405. fails.
  406. @see: L{twisted.internet.protocol.ClientFactory}
  407. @param connector: Not used.
  408. @type connector: L{twisted.internet.interfaces.IConnector}
  409. @param reason: A C{Failure} containing information about the
  410. cause of the connection failure. This will be passed as the
  411. argument to C{errback} on every pending TCP query
  412. C{deferred}.
  413. @type reason: L{twisted.python.failure.Failure}
  414. """
  415. # Copy the current pending deferreds then reset the master
  416. # pending list. This prevents triggering new deferreds which
  417. # may be added by callback or errback functions on the current
  418. # deferreds.
  419. pending = self.controller.pending[:]
  420. del self.controller.pending[:]
  421. for d, query, timeout in pending:
  422. d.errback(reason)
  423. def buildProtocol(self, addr):
  424. p = dns.DNSProtocol(self.controller)
  425. p.factory = self
  426. return p
  427. def createResolver(servers=None, resolvconf=None, hosts=None):
  428. """
  429. Create and return a Resolver.
  430. @type servers: C{list} of C{(str, int)} or L{None}
  431. @param servers: If not L{None}, interpreted as a list of domain name servers
  432. to attempt to use. Each server is a tuple of address in C{str} dotted-quad
  433. form and C{int} port number.
  434. @type resolvconf: C{str} or L{None}
  435. @param resolvconf: If not L{None}, on posix systems will be interpreted as
  436. an alternate resolv.conf to use. Will do nothing on windows systems. If
  437. L{None}, /etc/resolv.conf will be used.
  438. @type hosts: C{str} or L{None}
  439. @param hosts: If not L{None}, an alternate hosts file to use. If L{None}
  440. on posix systems, /etc/hosts will be used. On windows, C:\windows\hosts
  441. will be used.
  442. @rtype: C{IResolver}
  443. """
  444. if platform.getType() == 'posix':
  445. if resolvconf is None:
  446. resolvconf = b'/etc/resolv.conf'
  447. if hosts is None:
  448. hosts = b'/etc/hosts'
  449. theResolver = Resolver(resolvconf, servers)
  450. hostResolver = hostsModule.Resolver(hosts)
  451. else:
  452. if hosts is None:
  453. hosts = r'c:\windows\hosts'
  454. from twisted.internet import reactor
  455. bootstrap = _ThreadedResolverImpl(reactor)
  456. hostResolver = hostsModule.Resolver(hosts)
  457. theResolver = root.bootstrap(bootstrap, resolverFactory=Resolver)
  458. L = [hostResolver, cache.CacheResolver(), theResolver]
  459. return resolve.ResolverChain(L)
  460. theResolver = None
  461. def getResolver():
  462. """
  463. Get a Resolver instance.
  464. Create twisted.names.client.theResolver if it is L{None}, and then return
  465. that value.
  466. @rtype: C{IResolver}
  467. """
  468. global theResolver
  469. if theResolver is None:
  470. try:
  471. theResolver = createResolver()
  472. except ValueError:
  473. theResolver = createResolver(servers=[('127.0.0.1', 53)])
  474. return theResolver
  475. def getHostByName(name, timeout=None, effort=10):
  476. """
  477. Resolve a name to a valid ipv4 or ipv6 address.
  478. Will errback with C{DNSQueryTimeoutError} on a timeout, C{DomainError} or
  479. C{AuthoritativeDomainError} (or subclasses) on other errors.
  480. @type name: C{str}
  481. @param name: DNS name to resolve.
  482. @type timeout: Sequence of C{int}
  483. @param timeout: Number of seconds after which to reissue the query.
  484. When the last timeout expires, the query is considered failed.
  485. @type effort: C{int}
  486. @param effort: How many times CNAME and NS records to follow while
  487. resolving this name.
  488. @rtype: C{Deferred}
  489. """
  490. return getResolver().getHostByName(name, timeout, effort)
  491. def query(query, timeout=None):
  492. return getResolver().query(query, timeout)
  493. def lookupAddress(name, timeout=None):
  494. return getResolver().lookupAddress(name, timeout)
  495. def lookupIPV6Address(name, timeout=None):
  496. return getResolver().lookupIPV6Address(name, timeout)
  497. def lookupAddress6(name, timeout=None):
  498. return getResolver().lookupAddress6(name, timeout)
  499. def lookupMailExchange(name, timeout=None):
  500. return getResolver().lookupMailExchange(name, timeout)
  501. def lookupNameservers(name, timeout=None):
  502. return getResolver().lookupNameservers(name, timeout)
  503. def lookupCanonicalName(name, timeout=None):
  504. return getResolver().lookupCanonicalName(name, timeout)
  505. def lookupMailBox(name, timeout=None):
  506. return getResolver().lookupMailBox(name, timeout)
  507. def lookupMailGroup(name, timeout=None):
  508. return getResolver().lookupMailGroup(name, timeout)
  509. def lookupMailRename(name, timeout=None):
  510. return getResolver().lookupMailRename(name, timeout)
  511. def lookupPointer(name, timeout=None):
  512. return getResolver().lookupPointer(name, timeout)
  513. def lookupAuthority(name, timeout=None):
  514. return getResolver().lookupAuthority(name, timeout)
  515. def lookupNull(name, timeout=None):
  516. return getResolver().lookupNull(name, timeout)
  517. def lookupWellKnownServices(name, timeout=None):
  518. return getResolver().lookupWellKnownServices(name, timeout)
  519. def lookupService(name, timeout=None):
  520. return getResolver().lookupService(name, timeout)
  521. def lookupHostInfo(name, timeout=None):
  522. return getResolver().lookupHostInfo(name, timeout)
  523. def lookupMailboxInfo(name, timeout=None):
  524. return getResolver().lookupMailboxInfo(name, timeout)
  525. def lookupText(name, timeout=None):
  526. return getResolver().lookupText(name, timeout)
  527. def lookupSenderPolicy(name, timeout=None):
  528. return getResolver().lookupSenderPolicy(name, timeout)
  529. def lookupResponsibility(name, timeout=None):
  530. return getResolver().lookupResponsibility(name, timeout)
  531. def lookupAFSDatabase(name, timeout=None):
  532. return getResolver().lookupAFSDatabase(name, timeout)
  533. def lookupZone(name, timeout=None):
  534. return getResolver().lookupZone(name, timeout)
  535. def lookupAllRecords(name, timeout=None):
  536. return getResolver().lookupAllRecords(name, timeout)
  537. def lookupNamingAuthorityPointer(name, timeout=None):
  538. return getResolver().lookupNamingAuthorityPointer(name, timeout)