o b_@s dZddlZddlZddlZddlmZddlmZmZm Z m Z ddl m Z ddl mZmZmZmZmZmZddlmZmZddlmZdd lmZdd lmZee jGd d d ejZ Gd ddZ!ddl"m#Z$Gddde$Z#Gddde j%Z&dKddZ'da(ddZ)dLddZ*dMddZ+dMddZ,dMdd Z-dMd!d"Z.dMd#d$Z/dMd%d&Z0dMd'd(Z1dMd)d*Z2dMd+d,Z3dMd-d.Z4dMd/d0Z5dMd1d2Z6dMd3d4Z7dMd5d6Z8dMd7d8Z9dMd9d:Z:dMd;d<Z;dMd=d>ZdMdCdDZ?dMdEdFZ@dMdGdHZAdMdIdJZBdS)Na Asynchronous client DNS The functions exposed in this module can be used for asynchronous name resolution and dns queries. If you need to create a resolver with specific requirements, such as needing to do queries against a particular host, the L{createResolver} function will return an C{IResolver}. Future plans: Proper nameserver acquisition on Windows/MacOS, better caching, respect timeouts N)moduleProvides)defererror interfacesprotocol) isIPv6Address)cachecommondnshostsresolveroot)failurelog) nativeString)FilePath)platformc@seZdZdZdZdZdZdZdZdZ dZ dZ dZ dZ d1ddZd d Zd d Zd dZddZddZddZd2ddZddZddZd3ddZddZd3d d!Zd"d#Zd4d%d&Zd'd(Zd)d*Zd4d+d,Zd-d.Z d/d0Z!dS)5Resolvera @ivar _waiting: A C{dict} mapping tuple keys of query name/type/class to Deferreds which will be called back with the result of those queries. This is used to avoid issuing the same query more than once in parallel. This is more efficient on the network and helps avoid a "birthday paradox" attack by keeping the number of outstanding requests for a particular query fixed at one instead of allowing the attacker to raise it to an arbitrary number. @ivar _reactor: A provider of L{IReactorTCP}, L{IReactorUDP}, and L{IReactorTime} which will be used to set up network resources and track timeouts. rN< -cCstj||durddlm}||_||_|durg|_n||_||_t |js/|s/t dt |||_ d|j _ g|_g|_i|_|dS)a Construct a resolver which will query domain name servers listed in the C{resolv.conf(5)}-format file given by C{resolv} as well as those in the given C{servers} list. Servers are queried in a round-robin fashion. If given, C{resolv} is periodically checked for modification and re-parsed if it is noticed to have changed. @type servers: C{list} of C{(str, int)} or L{None} @param servers: If not None, interpreted as a list of (host, port) pairs specifying addresses of domain name servers to attempt to use for this lookup. Host addresses should be in IPv4 dotted-quad form. If specified, overrides C{resolv}. @type resolv: C{str} @param resolv: Filename to read and parse as a resolver(5) configuration file. @type timeout: Sequence of C{int} @param timeout: Default number of seconds after which to reissue the query. When the last timeout expires, the query is considered failed. @param reactor: A provider of L{IReactorTime}, L{IReactorUDP}, and L{IReactorTCP} which will be used to establish connections, listen for DNS datagrams, and enforce timeouts. If not provided, the global reactor will be used. @raise ValueError: Raised if no nameserver addresses can be found. NrreactorzNo nameservers specified)r ResolverBase__init__twisted.internetr_reactortimeoutserversresolvlen ValueErrorDNSClientFactoryfactorynoisy connectionspending_waitingmaybeParseConfig)selfr#r"r!rrr6/usr/lib/python3/dist-packages/twisted/names/client.pyrBs"    zResolver.__init__cCs|j}g|d<d|d<|S)Nr) _parseCall)__dict__copy)r-drrr. __getstate__|s zResolver.__getstate__cCs|j||dSN)r0updater,)r-staterrr. __setstate__s  zResolver.__setstate__cCs t|S)zr Wrapper used for opening files in the class, exists primarily for unit testing purposes. )ropen)r-pathrrr. _openFiles zResolver._openFilec Cs|jdurdSz||j}Wnty.}z|jtjkr#|dnWYd}~n5d}~ww|&t|j }||j krPt |jd||_ ||Wdn1sZwY|j |j|j|_dS)Nrz changed, reparsing)r#r:OSErrorerrnoENOENT parseConfigosfstatfilenost_mtime_lastResolvTimermsgr callLater_resolvReadIntervalr,r/)r- resolvConfemtimerrr.r,s,       zResolver.maybeParseConfigc Csg}|D]U}|}|dr)t|dtjf}||td|dq|drHz |d|_ Wn t yCd|_ Ynwd|_ q|drY|dd|_ d|_ q|sd|dtjf||_ dS) Ns nameserverrzResolver added z to server listsdomainssearch 127.0.0.1) strip startswithrsplitr PORTappendrrDdomain IndexErrorsearch dynServers)r-rGr"Lresolverrrr.r>s*       zResolver.parseConfigcCsj|js|jsdSt|j}t|j}|jd7_|j||;_|j|kr-|j|jS|j|j|S)z Return the address of a nameserver. TODO: Weight servers for response time so faster ones can be preferred. Nr)r"rTr$index)r-serverLdynLrrr. pickServers     zResolver.pickServerc Csd}tj||jd} z|jjt||dW|StjyC}z|d7}t|jdr4|jj t j kr4|dkr9WYd}~nd}~wwq ) zg Return a new L{DNSDatagramProtocol} bound to a randomly selected port number. rrT interfacerr<iN) r DNSDatagramProtocolr listenUDP randomSourcerCannotListenErrorhasattr socketErrorr<EMFILE)r-r]failuresprotorHrrr._connectedProtocols$  zResolver._connectedProtocolcCs@|j||jD]\}}}||||q |jdd=dS)zV Called by associated L{dns.DNSProtocol} instances when they connect. N)r)rPr*queryTCP chainDeferred)r-rr2qtrrr.connectionMades zResolver.connectionMadecCs||jvr |j|dSdS)zY Called by associated L{dns.DNSProtocol} instances when they disconnect. N)r)remover-rrrr.connectionLosts zResolver.connectionLostcCstd|j|fdS)Nz(Unexpected message (%d) received from %r)rrDid)r-messageraddressrrr.messageReceivedszResolver.messageReceivedcsJt|ddr|jddn|j|}fdd}|||S)a Get a new L{DNSDatagramProtocol} instance from L{_connectedProtocol}, issue a query to it using C{*args}, and arrange for it to be disconnected from its transport after the query completes. @param args: Positional arguments to be passed to L{DNSDatagramProtocol.query}. @return: A L{Deferred} which will be called back with the result of the query. rz::r\csj|Sr4) transport stopListening)resultrrr. cbQuerieds z"Resolver._query..cbQueried)rrgqueryaddBoth)r-argsr2rxrrwr._querys    zResolver._querycCsl|dur|j}|jt|j}|sttdS||}| |||d}| |j ||g|||S)a Make a number of DNS queries via UDP. @type queries: A C{list} of C{dns.Query} instances @param queries: The queries to make. @type timeout: Sequence of C{int} @param timeout: Number of seconds after which to reissue the query. When the last timeout expires, the query is considered failed. @rtype: C{Deferred} @raise C{twisted.internet.defer.TimeoutError}: When the query times out. N No domain name servers availabler) r!r"listrTrfailIOErrorreversepopr| addErrback_reissue)r-queriesr! addressesusedr2rrr.queryUDPszResolver.queryUDPcCs|tj|s|}|g}|dd}|s tt|S|}| || |||d|j j }| |j|||||S)Nrr)trapr DNSQueryTimeoutErrorrrFailurer TimeoutErrorrrPr|valuerprr)r-reason addressesLeft addressesUsedryr!rrr2rrr.r7s   zResolver._reissue cCsxt|js3|}|durttdS|\}}|j|||j|j t ||f|j ddS|jd ||S)a) Make a number of DNS queries via TCP. @type queries: Any non-zero number of C{dns.Query} instances @param queries: The queries to make. @type timeout: C{int} @param timeout: The number of seconds after which to fail. @rtype: C{Deferred} Nr}r) r$r)rZrrrr connectTCPr'r*rPDeferredry)r-rr!rrhostportrrr.rhTs zResolver.queryTCPcCsL|jr ||j|jS|jtjkrt | |j|S|j |j |j fS)a Extract results from the given message. If the message was truncated, re-attempt the query over TCP and return a Deferred which will fire with the results of that query. If the message's result code is not C{twisted.names.dns.OK}, return a Failure indicating the type of error which occurred. Otherwise, return a three-tuple of lists containing the results from the answers section, the authority section, and the additional section. )truncrhr addCallback filterAnswersrCoder OKrrexceptionForCodeanswers authority additional)r-rqrrr.rks   zResolver.filterAnswerscs~|||fj}|dur4gj<t|||g|}fdd}|j|||St }| ||S)aZ Build a L{dns.Query} for the given parameters and dispatch it via UDP. If this query is already outstanding, it will not be re-issued. Instead, when the outstanding query receives a response, that response will be re-used for this query as well. @type name: C{str} @type type: C{int} @type cls: C{int} @return: A L{Deferred} which fires with a three-tuple giving the answer, authority, and additional sections of the response or with a L{Failure} if the response code is anything other than C{dns.OK}. Ncs jD]}||q|Sr4)r+rcallback)rvr2keyr-rr.cbResults z"Resolver._lookup..cbResult) r+getrr QueryrrrzrrrP)r-nameclstyper!waitingr2rrrr._lookup~s      zResolver._lookupc s|}|durttdS|\}}t}t||t|}d|_|j |||}|j |p2d|j |||p:d_ fdd} |j |j| |fdS)Nr}Frcsjd_|Sr4) timeoutCallcancel)r controllerrr.eliminateTimeouts z-Resolver.lookupZone..eliminateTimeout) callbackArgs)rZrrrrAXFRControllerr&r(r rrE _timeoutZoner addCallbacks _cbLookupZone) r-rr!rrrrr2r' connectorrrrr. lookupZones     zResolver.lookupZonecCs.|d|_d|_|td|fdS)Nz&Zone lookup timed out after %d seconds) disconnectrdeferrederrbackrr)r-r2rrsecondsrrr.rs zResolver._timeoutZonecCs||ggfSr4)r)r-rvrrrr.rs zResolver._cbLookupZone)NNrN)r[r4r)"__name__ __module__ __qualname____doc__rWr!r'r"rTr*r)r#rCrFrr3r7r:r,r>rZrgrlrorsr|rrrhrrrrrrrrr.r&s@ :     # rc@s0eZdZdZddZddZddZdd ZdS) rNcCs&||_||_d|_g|_|fg|_dSr4)rrsoarecordsr*)r-rrrrr.rs zAXFRController.__init__cCs8tj|dd}t|jtjtjg|_||dS)Nr)recDes) r MessagepickIDrrAXFRINr writeMessage)r-rrqrrr.rlszAXFRController.connectionMadecCdSr4rrnrrr.roszAXFRController.connectionLostcCs|j|j|js dS|js|jdjtjkr|jd|_t|jdkrL|jdjtjkrN|jdur;|j d|_|j durP|j |jd|_ dSdSdSdS)Nrrr) rextendrrrr SOAr$rrrr)r-rqrrrr.rss      zAXFRController.messageReceived)rrrrrrlrorsrrrr.rs  r)ThreadedResolverc@seZdZdddZdS)rNcCs4|dur ddlm}t||tjdtdddS)Nrrzztwisted.names.client.ThreadedResolver is deprecated since Twisted 9.0, use twisted.internet.base.ThreadedResolver instead.)category stacklevel)rr_ThreadedResolverImplrwarningswarnDeprecationWarning)r-rrrr.rs   zThreadedResolver.__init__r4)rrrrrrrr.rsrc@s.eZdZd ddZddZddZdd Zd S) r&rcCs||_||_dSr4)rr!)r-rr!rrr.rs zDNSClientFactory.__init__cCrr4r)r-rrrrr.clientConnectionLostsz%DNSClientFactory.clientConnectionLostcCs>|jjdd}|jjdd=|D] }|d}||qdS)a Fail all pending TCP DNS queries if the TCP connection attempt fails. @see: L{twisted.internet.protocol.ClientFactory} @param connector: Not used. @type connector: L{twisted.internet.interfaces.IConnector} @param reason: A C{Failure} containing information about the cause of the connection failure. This will be passed as the argument to C{errback} on every pending TCP query C{deferred}. @type reason: L{twisted.python.failure.Failure} Nr)rr*r)r-rrr* pendingStater2rrr.clientConnectionFailed s  z'DNSClientFactory.clientConnectionFailedcCst|j}||_|Sr4)r DNSProtocolrr')r-addrprrr. buildProtocol%s zDNSClientFactory.buildProtocolNr)rrrrrrrrrrr.r&s   r&cCstdkr|dur d}|durd}t||}t|}n|dur#d}ddlm}t|}t|}tj|td}|t |g}t |S) a Create and return a Resolver. @type servers: C{list} of C{(str, int)} or L{None} @param servers: If not L{None}, interpreted as a list of domain name servers to attempt to use. Each server is a tuple of address in C{str} dotted-quad form and C{int} port number. @type resolvconf: C{str} or L{None} @param resolvconf: If not L{None}, on posix systems will be interpreted as an alternate resolv.conf to use. Will do nothing on windows systems. If L{None}, /etc/resolv.conf will be used. @type hosts: C{str} or L{None} @param hosts: If not L{None}, an alternate hosts file to use. If L{None} on posix systems, /etc/hosts will be used. On windows, C:\windows\hosts will be used. @rtype: C{IResolver} posixNs/etc/resolv.confs /etc/hostszc:\windows\hostsrr)resolverFactory) rgetTyper hostsModulerrrr bootstrapr CacheResolverr ResolverChain)r" resolvconfr theResolver hostResolverrrrUrrr.createResolver+s      rcCs:tdurztaWtStytdgdaYtSwtS)z Get a Resolver instance. Create twisted.names.client.theResolver if it is L{None}, and then return that value. @rtype: C{IResolver} N)rK5)r")rrr%rrrr. getResolverXs  rrcCst|||S)aL Resolve a name to a valid ipv4 or ipv6 address. Will errback with C{DNSQueryTimeoutError} on a timeout, C{DomainError} or C{AuthoritativeDomainError} (or subclasses) on other errors. @type name: C{str} @param name: DNS name to resolve. @type timeout: Sequence of C{int} @param timeout: Number of seconds after which to reissue the query. When the last timeout expires, the query is considered failed. @type effort: C{int} @param effort: How many times CNAME and NS records to follow while resolving this name. @rtype: C{Deferred} )r getHostByName)rr!effortrrr.rjsrcCt||Sr4)rry)ryr!rrr.ryrycCrr4)r lookupAddressrr!rrr.rrrcCrr4)rlookupIPV6Addressrrrr.rrrcCrr4)rlookupAddress6rrrr.rrrcCrr4)rlookupMailExchangerrrr.rrrcCrr4)rlookupNameserversrrrr.rrrcCrr4)rlookupCanonicalNamerrrr.rrrcCrr4)r lookupMailBoxrrrr.rrrcCrr4)rlookupMailGrouprrrr.rrrcCrr4)rlookupMailRenamerrrr.rrrcCrr4)r lookupPointerrrrr.rrrcCrr4)rlookupAuthorityrrrr.rrrcCrr4)r lookupNullrrrr.rrrcCrr4)rlookupWellKnownServicesrrrr.rrrcCrr4)r lookupServicerrrr.rrrcCrr4)rlookupHostInforrrr.rrrcCrr4)rlookupMailboxInforrrr.rrrcCrr4)r lookupTextrrrr.rrrcCrr4)rlookupSenderPolicyrrrr.rrrcCrr4)rlookupResponsibilityrrrr.rrrcCrr4)rlookupAFSDatabaserrrr.rrrcCrr4)rrrrrr.rrrcCrr4)rlookupAllRecordsrrrr.rrrcCrr4)rlookupNamingAuthorityPointerrrrr.rrr)NNN)Nrr4)Crr<r?rzope.interfacerrrrrrtwisted.internet.abstractr twisted.namesrr r r rr r twisted.pythonrrtwisted.python.compatrtwisted.python.filepathrtwisted.python.runtimer IResolverrrrtwisted.internet.baserr ClientFactoryr&rrrrryrrrrrrrrrrrrrrrrrrrrrrrrrrr.sb       # , (*