Ϫf_,dZddlZddlZddlZddlmZddlmZmZm Z m Z ddl m Z ddl mZmZmZmZmZmZddlmZmZddlmZdd lmZdd lmZee j<Gd d ej>Z Gd dZ!ddl"m#Z$Gdde$Z#Gdde jJZ&d/dZ'da(dZ)d0dZ*d1dZ+d1dZ,d1dZ-d1dZ.d1dZ/d1dZ0d1dZ1d1dZ2d1dZ3d1d Z4d1d!Z5d1d"Z6d1d#Z7d1d$Z8d1d%Z9d1d&Z:d1d'Z;d1d(Zd1d+Z?d1d,Z@d1d-ZAd1d.ZBy)2a 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)platformceZdZdZdZdZdZdZdZdZ dZ dZ dZ dZ ddZdZdZd Zd Zd Zd Zdd ZdZdZddZdZddZdZddZdZdZddZdZ dZ!y)Resolvera @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<cptjj||ddlm}||_||_|g|_n||_||_t|js |s tdt|||_ d|j_ g|_g|_i|_|j#y)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 rrs 6/usr/lib/python3/dist-packages/twisted/names/client.pyrzResolver.__init__Bs< $$T* ? 0  ?DL"DL 4<< 78 8'g6     cN|jj}g|d<d|d<|S)Nr' _parseCall)__dict__copy)r+ds r, __getstate__zResolver.__getstate__|s, MM   -,r-cZ|jj||jyN)r0updater*)r+states r, __setstate__zResolver.__setstate__s  U# r-c4t|jS)zr Wrapper used for opening files in the class, exists primarily for unit testing purposes. )ropen)r+paths r, _openFilezResolver._openFiles ~""$$r-cf|jy |j|j}|5tj|j j }||j k7r:tj|jd||_|j|ddd|jj|j|j |_y#1swY?xYw#t$r:}|jtjk(r|jdnYd}~d}~wwxYw)Nz changed, reparsingr)r!r<osfstatfilenost_mtime_lastResolvTimermsg parseConfigOSErrorerrnoENOENTr callLater_resolvReadIntervalr*r/)r+ resolvConfmtimees r,r*zResolver.maybeParseConfigs ;;   1 4J 1!2!2!45>>D000GGt{{m+>?@+0D($$Z0  1--11  $ $d&;&;  1 1 ww%,,&  $% s#C-A7C!!C*- D060D++D0cLg}|D]}|j}|jdrWt|jdtj f}|j |tjd|d{|jdr! |jd|_ d|_ |jds|jdd|_ d|_ |s!|j dtj f||_ y#t$r d|_ YxwxYw) Ns nameserverzResolver added z to server listsdomainr-ssearch 127.0.0.1) strip startswithrsplitr PORTappendrrCdomain IndexErrorsearch dynServers)r+rJr Lresolvers r,rDzResolver.parseConfigs #A A||M*(16Ax(/(_EFi(&"#'')A,DK# i(ggim "  # NNK2 3!"&"%DK&sDD#"D#cj|js |jsyt|j}t|j}|xjdz c_|xj||zzc_|j|kr|j|jS|j|j|z S)z Return the address of a nameserver. TODO: Weight servers for response time so faster ones can be preferred. NrN)r rXr"index)r+serverLdynLs r, pickServerzResolver.pickServers||DOOdll#4??# a  gn$ :: << + +??4::#78 8r-cd}tj||j} |jjtj|||S#t j $rS}|dz }t|jdr(|jjtjk(r|dk\rYd}~nd}~wwxYw)zg Return a new L{DNSDatagramProtocol} bound to a randomly selected port number. rr interfacerNrFiN) r DNSDatagramProtocolr listenUDP randomSourcerCannotListenErrorhasattr socketErrorrFEMFILE)r+rbfailuresprotorLs r,_connectedProtocolzResolver._connectedProtocols ''dmmD  ''(8(8(:EY'W" !** A AMM73 ++u||;t# $ s0AB>+A B99B>c|jj||jD]'\}}}|j||j |)|jdd=y)zV Called by associated L{dns.DNSProtocol} instances when they connect. N)r'rTr(queryTCP chainDeferred)r+rr2qts r,connectionMadezResolver.connectionMadesU )|| 1GAq! MM!Q  - -a 0 1 LLOr-cX||jvr|jj|yy)zY Called by associated L{dns.DNSProtocol} instances when they disconnect. N)r'remover+rs r,connectionLostzResolver.connectionLosts+ t'' '    # #H - (r-cLtjd|j|fzy)Nz(Unexpected message (%d) received from %r)rrCid)r+messageraddresss r,messageReceivedzResolver.messageReceiveds :gjj'=RRSr-ct|ddr|jdn|jj|}fd}|j||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::rac<jj|Sr5) transport stopListening)resultrs r, cbQueriedz"Resolver._query..cbQuerieds    , , .Mr-)rrlqueryaddBoth)r+argsr2rrs @r,_queryzResolver._querys^ a $...>H..0H HNND !  )r-cR| |j}|jt|jz}|st j t dS|j|j}|j|||d}|j|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. No domain name servers availabler) rr listrXrfailIOErrorreversepopr addErrback_reissue)r+queriesr addressesusedr2s r,queryUDPzResolver.queryUDPs ?llGLL4#88 ::g&HIJ J }} KKgwqz 2 T]]IvwHr-c|jtj|s|}|jg}|dd}|s(t j t j|S|j}|j||j|||d|jj}|j|j|||||S)NrNr)trapr DNSQueryTimeoutErrorrrFailurer TimeoutErrorrrTrvaluerxrr)r+reason addressesLeft addressesUsedrrrzr2s r,rzResolver._reissue7s C,,- )M  ! ! #MabkG ??5#5#5e#<= = ##%W% KK FLLOO D T]]M=%Qr-ct|js|j}|tjt dS|\}}|j j|||j|jjtj||f|jddS|jdj||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} rr) r"r'r_rrrr connectTCPr%r(rTDeferredr)r+rrrzhostports r,rnzResolver.queryTCPTs4##$oo'Gzz'*L"MNN JD$ MM $ $T4 > LL  !17G D E<<#A& &##A&,,Wg> >r-cj|jr4|j|jj|jS|j t jk7r4tj|j|j |S|j|j|jfS)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. )truncrnr addCallback filterAnswersrCoder OKrrexceptionForCodeanswers authority additional)r+rys r,rzResolver.filterAnswersks ====1==d>P>PQ Q ==CFF "??#G4#8#8#G#PQ Q!2!2G4F4FGGr-cn|||fjj}|kgj<jtj|||g|}fd}|j j |j||Stj}|j||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}. cjjjD]}|j||Sr5)r)rcallback)rr2keyr+s r,cbResultz"Resolver._lookup..cbResults2**3/'AJJv&' r-) r)getrr QueryrrrrrrT) r+nameclstyperwaitingr2rrs ` @r,_lookupzResolver._lookup~s T3--##C( ?!#DMM#  syytS9:GDA  MM$,, - IIh  A NN1 r-c  |j}|tjtdS|\}}tj}t || t |}d|_|jj|||}|jj|xsd|j| ||xsd _ fd} |j|j| |fS)NrF cJjjd_|Sr5) timeoutCallcancel)r controllers r,eliminateTimeoutz-Resolver.lookupZone..eliminateTimeouts"  " " ) ) +%)J "Nr-) callbackArgs)r_rrrrAXFRControllerr$r&rrrH _timeoutZoner addCallbacks _cbLookupZone) r+rrrzrrr2r% connectorrrs @r, lookupZonezResolver.lookupZones//# ?::g&HIJ J d NN #D!, ":w7 MM,,T4A !%!8!8 Mr4,,aY SU"   ~~    0 |  r-c|jd|_d|_|jt j d|fzy)Nz&Zone lookup timed out after %d seconds) disconnectrdeferrederrbackrr)r+r2rrsecondss r,rzResolver._timeoutZones@!% "    G7*T U r-c,|j|ggfSr5)r)r+rrs r,rzResolver._cbLookupZonesBr-)NN)rN -N)r5r)"__name__ __module__ __qualname____doc__r\rr%r rXr(r'r!rBrIrr3r8r<r*rDr_rlrrrvr{rrrrnrrrrrrr-r,rr&s  EGGGJGK FO8 t  % 4"*9&:.T2>:?.H& F 0  r-rc(eZdZdZdZdZdZdZy)rNcN||_||_d|_g|_|fg|_yr5)rrsoarecordsr()r+rrs r,rzAXFRController.__init__s)    ! } r-ctj|jd}tj|jtj tj g|_|j|y)Nr)recDes) r MessagepickIDrrAXFRINr writeMessage)r+rrys r,rrzAXFRController.connectionMadesN++ohoo/:99TYY#&&ABg&r-cyr5rrus r,rvzAXFRController.connectionLosts r-cP|jj|j|jsy|js>|jdjt j k(r|jd|_t|jdkDr|jdjt j k(rg|j!|jjd|_|j-|jj|jd|_ yyyy)NrrNr) rextendrrrr SOAr"rrrr)r+ryrs r,r{zAXFRController.messageReceiveds GOO,|| xx||A##sww.<<? t|| q T\\"%5%:%:cgg%E+  '')#' }}( &&t||4 $ ) &F r-)rrrrrrrrvr{rr-r,rrsK%'  %r-r)ThreadedResolverceZdZddZy)rNcx|ddlm}tj||t j dt dy)Nrrzztwisted.names.client.ThreadedResolver is deprecated since Twisted 9.0, use twisted.internet.base.ThreadedResolver instead.)category stacklevel)rr_ThreadedResolverImplrwarningswarnDeprecationWarning)r+rs r,rzThreadedResolver.__init__s3 ? 0&&tW5  (  r-r5)rrrrrr-r,rrs  r-rc&eZdZddZdZdZdZy)r$c ||_||_yr5)rr)r+rrs r,rzDNSClientFactory.__init__s$ r-cyr5r)r+rrs r,clientConnectionLostz%DNSClientFactory.clientConnectionLosts r-c|jjdd}|jjdd=|D]}|d}|j|y)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( pendingStater2s r,clientConnectionFailedz'DNSClientFactory.clientConnectionFailed sN(//))!, OO # #A &# LQA IIf  r-cRtj|j}||_|Sr5)r DNSProtocolrr%)r+addrps r, buildProtocolzDNSClientFactory.buildProtocol%s OODOO , r-Nr)rrrrrrrrr-r,r$r$s 4r-r$cftjdk(r*|d}|d}t||}tj|}nE|d}ddlm}t |}tj|}tj|t}|tj|g}tj|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} posixs/etc/resolv.confs /etc/hostszc:\windows\hostsrr)resolverFactory) rgetTyper hostsModulerrrr bootstrapr CacheResolverr ResolverChain)r resolvconfr theResolver hostResolverrrrYs r,createResolverr+s,W$  ,J =!Ez73 "++E2 ='E,)'2 "++E2 nnYI u**,k:A   ##r-c~t tatStS#t$rtdgaYtSwxYw)z Get a Resolver instance. Create twisted.names.client.theResolver if it is L{None}, and then return that value. @rtype: C{IResolver} )rO5)r )rrr#rr-r, getResolverrXsL F(*K ; F(2C1DEK  Fs <<c8tj|||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)rrefforts r,r r js( = & &tWf ==r-c6tj||Sr5)rr)rrs r,rrs =  ug ..r-c6tj||Sr5)r lookupAddressrrs r,rr = & &tW 55r-c6tj||Sr5)rlookupIPV6Addressrs r,rr = * *4 99r-c6tj||Sr5)rlookupAddress6rs r,rr = ' 'g 66r-c6tj||Sr5)rlookupMailExchangers r,rr = + +D' ::r-c6tj||Sr5)rlookupNameserversrs r,rrrr-c6tj||Sr5)rlookupCanonicalNamers r,rrs = , ,T7 ;;r-c6tj||Sr5)r lookupMailBoxrs r,rrrr-c6tj||Sr5)rlookupMailGrouprs r,r!r! = ( (w 77r-c6tj||Sr5)rlookupMailRenamers r,r$r$ = ) )$ 88r-c6tj||Sr5)r lookupPointerrs r,r'r'rr-c6tj||Sr5)rlookupAuthorityrs r,r)r)r"r-c6tj||Sr5)r lookupNullrs r,r+r+ = # #D' 22r-c6tj||Sr5)rlookupWellKnownServicesrs r,r.r.s = 0 0w ??r-c6tj||Sr5)r lookupServicers r,r0r0rr-c6tj||Sr5)rlookupHostInfors r,r2r2rr-c6tj||Sr5)rlookupMailboxInfors r,r4r4rr-c6tj||Sr5)r lookupTextrs r,r6r6r,r-c6tj||Sr5)rlookupSenderPolicyrs r,r8r8rr-c6tj||Sr5)rlookupResponsibilityrs r,r:r:s = - -dG <rzope.interfacerrrrrrtwisted.internet.abstractr twisted.namesr r r r rr rtwisted.pythonrrtwisted.python.compatrtwisted.python.filepathrtwisted.python.runtimer IResolverrrrtwisted.internet.baserr ClientFactoryr$rrrr rrrrrrrrr!r$r'r)r+r.r0r2r4r6r8r:r<rr?rArr-r,rLs  )??3QQ'/,+z##$] v""] @ )%)%XL  ,  %x--%P'$T $>./6:7;:<689683@67:3;=:39Er-