3 >DW@sdZddlZddlZddlZddlZy ddlZWnek rLddlZYnXddl Z ddl Z ddl Z ddl Z ddlZ ddlZ ddlZ ddlZ ddlZ ddlZ ddlZ ddlZ ddlmZmZejdkry ddlZWnek rddlZYnXGddde jjZGdd d e jjZe jj Z Gd d d e jjZ!Gd d d e jjZ"Gddde jjZ#Gddde jjZ$Gddde jjZ%Gddde&Z'Gddde&Z(Gddde&Z)Gddde&Z*Gddde&Z+da,ddZ-d d!Z.e j/j0e j1j2d"dd#dfd$d%Z3e j1j2d"dfd&d'Z4ej5ej6gej7ej8giZ9da:ej;Zej?Z@ejAZBejCZDejEZFddejGdddfd(d)ZHd8d*d+ZId9d,d-ZJd.d/ZKd0d1ZLd2d3ZMd:d4d5ZNd6d7ZOdS);z{DNS stub resolver. @var default_resolver: The default resolver object @type default_resolver: dns.resolver.Resolver objectN)xrange string_typeswin32csVeZdZdZeddgZdZdddZfddZd d Z e e d d Z d dZ Z S)NXDOMAINz"The DNS query name does not exist.qnames responsesNcCs\t|tttfstdt|dkr,td|dkr:i}nt|tsLtdt||d}|S)Nz#qnames must be a list, tuple or setrz(qnames must contain at least one elementz(responses must be a dict(qname=response))rr) isinstancelisttuplesetAttributeErrorlendict)selfrrkwargsr/usr/lib/python3.6/resolver.py _check_kwargs9s   zNXDOMAIN._check_kwargscs^d|jkrtt|jS|jd}t|dkr4d}n|jdd}djtt|}d||fS)NrrzNone of DNS query names existz, z%s: %s) rsuperr__str__r__doc__joinmapstr)rrmsg) __class__rrrEs   zNXDOMAIN.__str__cCsd|jkrtdtjj}tjj}d}xj|jdD]\}|jd|}x4|jD]*}|j|ksL|j |krfqL|j dj j }qLW|dk r2tj j|Sq2W|jddS)Nrzparametrized exception requiredrr)r TypeErrordns rdataclassIN rdatatypeCNAMEanswerrdtyperdclassitemstargetto_textname from_text)rr!r#cnameqnameresponser$rrrcanonical_namePs  zNXDOMAIN.canonical_namez%Return the unresolved canonical name.)doccCs|t|jjdg}t|jjdi}|jjdi}x<|jjdgD]*}||krX|j|||krB||||<qBWt||dS)z3Augment by results from another NXDOMAIN exception.rr)rr)r rgetrappendr)rZe_nxZqnames0Z responses0Z responses1Zqname1rrr__add__bs zNXDOMAIN.__add__)N) __name__ __module__ __qualname__rr supp_kwargsfmtrrr/propertyr3 __classcell__rr)rrr3s  rc@seZdZdZdS)YXDOMAINz8The DNS query name is too long after DNAME substitution.N)r4r5r6rrrrrr;osr;cs.eZdZdZdZedgZfddZZS)NoAnswerzs zNoAnswer._fmt_kwargszDThe DNS response does not contain an answer to the question: {query}) r4r5r6rr8r r7r>r:rr)rrr<zs  r<cs@eZdZdZdZdedd ZeddgZfdd ZZ S) NoNameserverszAll nameservers failed to answer the query. errors: list of servers and respective errors The type of errors is [(server ip address, any object convertible to string)]. Non-empty errors list will add explanatory message () z+All nameservers failed to answer the query.z%s {query}: {errors}Nrrequesterrorsc sdg}x>|dD]2}|jd|d|dr*dnd|d|dfqWtt|j|d jd j|d S) NrBz Server %s %s port %s answered %srrZTCPZUDPrAz; )r=rB)r2rr@r>r?r)rrZsrv_msgserr)rrrr>s  & zNoNameservers._fmt_kwargsr) r4r5r6rrr8r r7r>r:rr)rrr@s  r@c@seZdZdZdS) NotAbsolutezEAn absolute domain name is required but a relative name was provided.N)r4r5r6rrrrrrFsrFc@seZdZdZdS) NoRootSOAzBThere is no SOA RR at the DNS root name. This should never happen!N)r4r5r6rrrrrrGsrGc@seZdZdZdS) NoMetaqueriesz DNS metaqueries are not allowed.N)r4r5r6rrrrrrHsrHc@sBeZdZdZdddZddZddZd d Zd d Zd dZ dS)Answera9DNS stub resolver answer Instances of this class bundle up the result of a successful DNS resolution. For convenience, the answer object implements much of the sequence protocol, forwarding to its rrset. E.g. "for a in answer" is equivalent to "for a in answer.rrset", "answer[i]" is equivalent to "answer.rrset[i]", and "answer[i:j]" is equivalent to "answer.rrset[i:j]". Note that CNAMEs or DNAMEs in the response may mean that answer node's name might not be the query name. @ivar qname: The query name @type qname: dns.name.Name object @ivar rdtype: The query type @type rdtype: int @ivar rdclass: The query class @type rdclass: int @ivar response: The response message @type response: dns.message.Message object @ivar rrset: The answer @type rrset: dns.rrset.RRset object @ivar expiration: The time when the answer expires @type expiration: float (seconds since the epoch) @ivar canonical_name: The canonical name of the query name @type canonical_name: dns.name.Name object Tc Cs||_||_||_||_d}d}xtddD]}y0|j|j|||}|dksV|j|kr\|j}PWq,tk r|t j j kryJ|j|j||t j j } |dks| j|kr| j}x| D] } | j }PqWw,Wn"tk r|rt |dYnX|rt |dYq,Xq,W|dkr |r t |d||_||_|dkrxyR|j|j||t j j} |dksf| j|krl| j}| dj|kr| dj}PWn@tk ry |j}Wnt jjk rPYnXYnXq8Wtj||_dS) Nrr)r.rrrr)r-r%r&r.rZ find_rrsetr$ttlKeyErrorrr"r#r(r<r/rrsetZ authoritySOAZminimumparentr*NoParenttime expiration) rr-r%r&r.raise_on_no_answerZmin_ttlrMcountZcrrsetZrdZsrrsetrrr__init__sf          zAnswer.__init__cCs\|dkr|jjS|dkr |jjS|dkr0|jjS|dkr@|jjS|dkrP|jjSt|dS)Nr*rKcoversr&r%)rMr*rKrVr&r%r )rattrrrr __getattr__szAnswer.__getattr__cCs|jrt|jpdS)Nr)rMr)rrrr__len__szAnswer.__len__cCs|jrt|jpttS)N)rMiterr )rrrr__iter__szAnswer.__iter__cCs |j|S)N)rM)rirrr __getitem__szAnswer.__getitem__cCs |j|=dS)N)rM)rr\rrr __delitem__szAnswer.__delitem__N)T) r4r5r6rrUrXrYr[r]r^rrrrrIs 7rIc@s<eZdZdZdddZddZddZd d Zdd d Zd S)CacheaqSimple DNS answer cache. @ivar data: A dictionary of cached data @type data: dict @ivar cleaning_interval: The number of seconds between cleanings. The default is 300 (5 minutes). @type cleaning_interval: float @ivar next_cleaning: The time the cache should next be cleaned (in seconds since the epoch.) @type next_cleaning: float r@cCs*i|_||_tj|j|_tj|_dS)zInitialize a DNS cache. @param cleaning_interval: the number of seconds between periodic cleanings. The default is 300.0 @type cleaning_interval: float. N)datacleaning_intervalrQ next_cleaning _threadingLocklock)rrbrrrrU-szCache.__init__cCsptj}|j|krlg}x*|jjD]\}}|j|kr"|j|q"Wx|D] }|j|=qHWtj}||j|_dS)z&Clean the cache if it's time to do so.N)rQrcrar'rRr2rb)rnowZkeys_to_deletekvrrr _maybe_clean:s    zCache._maybe_cleanc CsNz<|jj|j|jj|}|dks6|jtjkr:dS|S|jjXdS)a)Get the answer associated with I{key}. Returns None if no answer is cached for the key. @param key: the key @type key: (dns.name.Name, int, int) tuple whose values are the query name, rdtype, and rdclass. @rtype: dns.resolver.Answer object or None N)rfacquirerjrar1rRrQrelease)rkeyrirrrr1Hs   z Cache.getc Cs2z |jj|j||j|<Wd|jjXdS)aAssociate key and value in the cache. @param key: the key @type key: (dns.name.Name, int, int) tuple whose values are the query name, rdtype, and rdclass. @param value: The answer being cached @type value: dns.resolver.Answer object N)rfrkrjrarl)rrmvaluerrrput[s  z Cache.putNc CsRz@|jj|dk r(||jkr>|j|=ni|_tj|j|_Wd|jjXdS)zFlush the cache. If I{key} is specified, only that item is flushed. Otherwise the entire cache is flushed. @param key: the key to flush @type key: (dns.name.Name, int, int) tuple or None N)rfrkrarQrbrcrl)rrmrrrflushks    z Cache.flush)r`)N) r4r5r6rrUrjr1rorprrrrr_s   r_c@s0eZdZdZddZddZddZdd Zd S) LRUCacheNodezLRUCache node. cCs||_||_||_||_dS)N)rmrnprevnext)rrmrnrrrrUszLRUCacheNode.__init__cCs |j|_||_||j_||_dS)N)rrrs)rnoderrr link_beforeszLRUCacheNode.link_beforecCs ||_|j|_||j_||_dS)N)rrrs)rrtrrr link_afterszLRUCacheNode.link_aftercCs|j|j_|j|j_dS)N)rrrs)rrrrunlinks zLRUCacheNode.unlinkN)r4r5r6rrUrurvrwrrrrrqs rqc@s<eZdZdZdddZddZddZd d Zdd d Zd S)LRUCacheaOBounded least-recently-used DNS answer cache. This cache is better than the simple cache (above) if you're running a web crawler or other process that does a lot of resolutions. The LRUCache has a maximum number of nodes, and when it is full, the least-recently used node is removed to make space for a new one. @ivar data: A dictionary of cached data @type data: dict @ivar sentinel: sentinel node for circular doubly linked list of nodes @type sentinel: LRUCacheNode object @ivar max_size: The maximum number of nodes @type max_size: int 順cCs*i|_|j|tdd|_tj|_dS)zInitialize a DNS cache. @param max_size: The maximum number of nodes to cache; the default is 100,000. Must be greater than 1. @type max_size: int N)ra set_max_sizerqsentinelrdrerf)rmax_sizerrrrUs  zLRUCache.__init__cCs|dkr d}||_dS)Nr)r|)rr|rrrrzszLRUCache.set_max_sizec CslzZ|jj|jj|}|dkr$dS|j|jjtjkrJ|j|j=dS|j |j |jS|jj XdS)a)Get the answer associated with I{key}. Returns None if no answer is cached for the key. @param key: the key @type key: (dns.name.Name, int, int) tuple whose values are the query name, rdtype, and rdclass. @rtype: dns.resolver.Answer object or None N) rfrkrar1rwrnrRrQrmrvr{rl)rrmrtrrrr1s    z LRUCache.getc Csz|jj|jj|}|dk r2|j|j|j=x.t|j|jkr`|jj }|j|j|j=q4Wt ||}|j |j||j|<Wd|jj XdS)aAssociate key and value in the cache. @param key: the key @type key: (dns.name.Name, int, int) tuple whose values are the query name, rdtype, and rdclass. @param value: The answer being cached @type value: dns.resolver.Answer object N) rfrkrar1rwrmrr|r{rrrqrvrl)rrmrnrtrrrros     z LRUCache.putNc Cszr|jj|dk r<|jj|}|dk rp|j|j|j=n4|jj}x$||jkrh|j}d|_d|_|}qFWi|_Wd|jj XdS)zFlush the cache. If I{key} is specified, only that item is flushed. Otherwise the entire cache is flushed. @param key: the key to flush @type key: (dns.name.Name, int, int) tuple or None N) rfrkrar1rwrmr{rsrrrl)rrmrtrsrrrrps      zLRUCache.flush)ry)N) r4r5r6rrUrzr1rorprrrrrxs  rxc@seZdZdZd%ddZddZdd Zd d Zd d ZddZ ddZ ddZ ddZ ddZ ddZejjejjddddfddZdejjfdd Zd!d"Zd#d$ZdS)&Resolvera-DNS stub resolver @ivar domain: The domain of this host @type domain: dns.name.Name object @ivar nameservers: A list of nameservers to query. Each nameserver is a string which contains the IP address of a nameserver. @type nameservers: list of strings @ivar search: The search list. If the query name is a relative name, the resolver will construct an absolute query name by appending the search names one by one to the query name. @type search: list of dns.name.Name objects @ivar port: The port to which to send queries. The default is 53. @type port: int @ivar timeout: The number of seconds to wait for a response from a server, before timing out. @type timeout: float @ivar lifetime: The total number of seconds to spend trying to get an answer to the question. If the lifetime expires, a Timeout exception will occur. @type lifetime: float @ivar keyring: The TSIG keyring to use. The default is None. @type keyring: dict @ivar keyname: The TSIG keyname to use. The default is None. @type keyname: dns.name.Name object @ivar keyalgorithm: The TSIG key algorithm to use. The default is dns.tsig.default_algorithm. @type keyalgorithm: string @ivar edns: The EDNS level to use. The default is -1, no Edns. @type edns: int @ivar ednsflags: The EDNS flags @type ednsflags: int @ivar payload: The EDNS payload size. The default is 0. @type payload: int @ivar flags: The message flags to use. The default is None (i.e. not overwritten) @type flags: int @ivar cache: The cache to use. The default is None. @type cache: dns.resolver.Cache object @ivar retry_servfail: should we retry a nameserver if it says SERVFAIL? The default is 'false'. @type retry_servfail: bool /etc/resolv.confTcCsd|_d|_d|_d|_d|_d|_d|_d|_d|_d|_ d|_ d|_ d|_ d|_ d|_d|_d|_|j|rtjdkr|jn|r|j|dS)aJInitialize a resolver instance. @param filename: The filename of a configuration file in standard /etc/resolv.conf format. This parameter is meaningful only when I{configure} is true and the platform is POSIX. @type filename: string or file object @param configure: If True (the default), the resolver instance is configured in the normal fashion for the operating system the resolver is running on. (I.e. a /etc/resolv.conf file on POSIX systems and from the registry on Windows systems.) @type configure: boolNFr)domain nameserversnameserver_portsportsearchtimeoutlifetimekeyringkeyname keyalgorithmedns ednsflagspayloadcacheflagsretry_servfailrotateresetsysplatform read_registryread_resolv_conf)rfilenameZ configurerrrrU9s.   zResolver.__init__cCstjjtjjtjdd|_t|jdkr:tjj|_g|_ i|_ d|_ g|_ d|_ d|_d|_d|_tjj|_d|_d|_d|_d|_d|_d|_d|_dS) z1Reset all resolver configuration to the defaults.rNr5g@g>@Fr)rr*Namer+socket gethostnamerrrootrrrrrrrrtsigdefault_algorithmrrrrrrrr)rrrrr_s&"  zResolver.resetcCsZt|trtt|trTtjj|}tjj |rdtg}|j r||j |nZt |dkr|j |j tjj|jrx2|jD]} |j |j | qWn|j |j |jd} i} tj} d} x|D]} |jr@|jj| ||f}|dk r@|jdkr<|r|qW|j6tj6j9kr|| | <qd } PqW| rt9|| d t?| ||||}|jr|jj@| ||f||S) aQuery nameservers to find the answer to the question. The I{qname}, I{rdtype}, and I{rdclass} parameters may be objects of the appropriate type, or strings that can be converted into objects of the appropriate type. E.g. For I{rdtype} the integer 2 and the the string 'NS' both mean to query for records with DNS rdata type NS. @param qname: the query name @type qname: dns.name.Name object or string @param rdtype: the query type @type rdtype: int or string @param rdclass: the query class @type rdclass: int or string @param tcp: use TCP to make the query (default is False). @type tcp: bool @param source: bind to this IP address (defaults to machine default IP). @type source: IP address in dotted quad notation @param raise_on_no_answer: raise NoAnswer if there's no answer (defaults is True). @type raise_on_no_answer: bool @param source_port: The port from which to send the message. The default is 0. @type source_port: int @rtype: dns.resolver.Answer instance @raises Timeout: no answers could be found in the specified lifetime @raises NXDOMAIN: the query name does not exist @raises YXDOMAIN: the query name is too long after DNAME substitution @raises NoAnswer: the response did not contain an answer and raise_on_no_answer is True. @raises NoNameservers: no non-broken nameservers are available to answer the question.NrT)r.) algorithmg?r)rArB)source source_portrCF)rr)Ar rrr*r+r"Z is_metatyperHr Z is_metaclass is_absoluter2rZ concatenaterrrrQrr1rMr<r.messageZ make_queryruse_tsigrruse_ednsrrrrrrrandomZshuffler@rrrr=tcpudpZTCrerror exceptionrZUnexpectedSourceZ FormErrorremoveEOFErrorrcoder;ZNOERRORrZSERVFAILrr)rZsleeprIro)rr-r%r&rrrSrZ qnames_to_tryrZ all_nxdomainZnxdomain_responsesrZ_qnamer$rAr.rrBZbackoffrrrZ tcp_attemptZexrZ sleep_timerrrr=]s#                                      zResolver.querycCs4||_|dkr$t|jjd|_n||_||_dS)aAdd a TSIG signature to the query. @param keyring: The TSIG keyring to use; defaults to None. @type keyring: dict @param keyname: The name of the TSIG key to use; defaults to None. The key must be defined in the keyring. If a keyring is specified but a keyname is not, then the key used will be the first key in the keyring. Note that the order of keys in a dictionary is not defined, so applications should supply a keyname when a keyring is used, unless they know the keyring contains only one key. @param algorithm: The TSIG key algorithm to use. The default is dns.tsig.default_algorithm. @type algorithm: stringNr)rr keysrr)rrrrrrrr"s zResolver.use_tsigcCs"|dkr d}||_||_||_dS)aConfigure Edns. @param edns: The EDNS level to use. The default is -1, no Edns. @type edns: int @param ednsflags: The EDNS flags @type ednsflags: int @param payload: The EDNS payload size. The default is 0. @type payload: intNrr)rrr)rrrrrrrr8s zResolver.use_ednscCs ||_dS)zOverrides the default flags with your own @param flags: The flags to overwrite the default with @type flags: intN)r)rrrrr set_flagsHszResolver.set_flags)r~T)r4r5r6rrUrrrrrrrrrrrr"Ar r!r=rrrrrrrrrr} s&+ &)  "-7 Er}cCstdkrttS)z7Get the default resolver, initializing it if necessary.N)default_resolverreset_default_resolverrrrrget_default_resolverRsrcCs tadS)zSRe-initialize default resolver. resolv.conf will be re-read immediatelly. N)r}rrrrrrYsrFTcCstj|||||||S)zQuery nameservers to find the answer to the question. This is a convenience function that uses the default resolver object to make the query. @see: L{dns.resolver.Resolver.query} for more information on the parameters.)rr=)r-r%r&rrrSrrrrr=bs r=cCst|trtjj|tjj}|dkr*t}|js:t|xxy(|j |tj j ||}|j j|krb|SWn tj jtj jfk rYnXy |j}Wq<tjjk rtYq|jd} t | dkr| d} n|} t j j | } |j||}Wnpt k r:y t jj |} |j||}Wn8t k r4|tj@dkr0y|tjks8|tjkrtj|t jjd d } | j}| jjd }| jdk rx| jD]} |j| jqrW|tjks|tjkrtj|t jjd d }|j}|jjd }|jdk rx|jD]} |j| jqWWn<t jjk rtjtjYntjtjYnXYnXYnXd}y|dkrRd}nt |}WnLt k r|tj!@dkrytj"|}Wnt k rYnXYnX|dkrtjtjg}|dkrtj#tj$g}n|g}|tj%@dkr|}nd }|tjks|tjkrfxP|D]H} x@|D]8}x0t&|D]$}|jtj|||| |ddffq2Wq$WqW|tjks~|tjkrxL|D]D} x<|D]4}x,t&|D] }|jtj|||| |ffqWqWqWt |dkrtjtj|S) NrZ localhostz::z0.0.0.0z::1z 127.0.0.1%rCF)rST)'rZ AI_ADDRCONFIGZ AI_V4MAPPEDNotImplementedErrorgaierror EAI_NONAMEZ AI_PASSIVEr2rrripv6 inet_aton ExceptionZipv4ZAI_NUMERICHOSTAF_INET6 AF_UNSPEC _resolverr=r"ZAAAAr-r/r)rMZaddressAF_INETrrrZ EAI_SYSTEMintZAI_NUMERICSERVZ getservbyname SOCK_DGRAM SOCK_STREAM AI_CANONNAME_protocols_for_socktype)hostservicefamilyZsocktypeprotorZv6addrsZv4addrsr/partsZahostaddrZv6ZrdataZv4rtuplesZ socktypesr,rrr _getaddrinfos                               $     rc Csf|d}|d}t|dkr,|d}tj}n d}tj}t|||tjtjd}t|dkrbtjd|ddd}|tj@rd}nd}t j j |} |tj @dkry"t j| d} | jdjjd } WnVt jjt jjfk r|tj@rtjtj|} |dk r| d t|7} YnXn|} |dk r<| d t|7} |tj@rRt|} n tj||} | | fS) NrrrDz'sockaddr resolved to multiple addressesrrZPTRTr)rrrrrrSOL_TCPrZNI_DGRAMrZ reversenameZ from_addressZNI_NUMERICHOSTrr=rMr(r)rrr< NI_NAMEREQDrrrZNI_NUMERICSERVZ getservbyport) sockaddrrrrZscoperrrZpnamer-r$Zhostnamerrrr _getnameinfosB               rc CsD|dkrtj}ytt|ddddStk r>|SXdS)NPrr)rrrrr)r*rrr_getfqdn.s rcCst|ddS)NrCr)_gethostbyname_ex)r*rrr_gethostbyname7srcCsXg}g}t|dtjtjtjtj}|dd}x|D]}|j|ddq4W|||fS)NrrDr)rrrrrrr2)r*aliases addressesr canonicalitemrrrr;s   rc Csy"tjj||dddf}tj}Wn"tk rD|df}tj}YnXt|tj\}}g}g}t |d|tj tj tj }|dd}x|D]} |j | ddqW|||fS)NrrrDr)rrrrrrrrrrrrrr2) Ziprrr*rrrrrrrrr_gethostbyaddrGs       rcCs:|dkrt}|att_tt_tt_t t_ t t_ t t_dS)aOverride the system resolver routines in the socket module with versions which use dnspython's resolver. This can be useful in testing situations where you want to control the resolution behavior of python code without having to change the system's resolver settings (e.g. /etc/resolv.conf). The resolver to use may be specified; if it's not, the default resolver will be used. @param resolver: the resolver to use @type resolver: dns.resolver.Resolver object or None N)rrrr getaddrinfor getnameinforgetfqdnr gethostbynamergethostbyname_exr gethostbyaddr)rrrroverride_system_resolver[srcCs,datt_tt_tt_tt_ t t_ t t_ dS)z4Undo the effects of override_system_resolver(). N)r_original_getaddrinforr_original_getnameinfor_original_getfqdnr_original_gethostbynamer_original_gethostbyname_exr_original_gethostbyaddrrrrrrrestore_system_resolverusr)r)N)N)PrrrrQrZ threadingrd ImportErrorZdummy_threadingZ dns.exceptionrZ dns.flagsZdns.ipv4Zdns.ipv6Z dns.messageZdns.nameZ dns.queryZ dns.rcodeZdns.rdataclassZ dns.rdatatypeZdns.reversenameZdns.tsigZ_compatrrrwinregrrZ DNSExceptionrr;rr<r@rFrGrHobjectrIr_rqrxr}rrrr"rr r!r=rrZSOL_UDPrrrrrr rr rr rr rr rrrrrrrrrrrrrrrs   < sboG  &  c (