o bV@sJdZddlZddlmZddlmZmZddlmZGdddej Z dS)a` Async DNS server Future plans: - Better config file format maybe - Make sure to differentiate between different classes - notice truncation bit Important: No additional processing is done on some of the record types. This violates the most basic RFC and is just plain annoying for resolvers to deal with. Fix it. @author: Jp Calderone N)protocol)dnsresolve)logc@seZdZdZejZdZejZ d$ddZ ddZ dd Z d d Z d d ZddZejdddfddZddZddZddZddZddZddZddZd%d d!Zd"d#ZdS)&DNSServerFactorya Server factory and tracker for L{DNSProtocol} connections. This class also provides records for responses to DNS queries. @ivar cache: A L{Cache} instance whose C{cacheResult} method is called when a response is received from one of C{clients}. Defaults to L{None} if no caches are specified. See C{caches} of L{__init__} for more details. @type cache: L{Cache} or L{None} @ivar canRecurse: A flag indicating whether this server is capable of performing recursive DNS resolution. @type canRecurse: L{bool} @ivar resolver: A L{resolve.ResolverChain} containing an ordered list of C{authorities}, C{caches} and C{clients} to which queries will be dispatched. @type resolver: L{resolve.ResolverChain} @ivar verbose: See L{__init__} @ivar connections: A list of all the connected L{DNSProtocol} instances using this object as their controller. @type connections: C{list} of L{DNSProtocol} instances @ivar protocol: A callable used for building a DNS stream protocol. Called by L{DNSServerFactory.buildProtocol} and passed the L{DNSServerFactory} instance as the one and only positional argument. Defaults to L{dns.DNSProtocol}. @type protocol: L{IProtocolFactory} constructor @ivar _messageFactory: A response message constructor with an initializer signature matching L{dns.Message.__init__}. @type _messageFactory: C{callable} NrcCsng}|dur |||dur|||dur||| |_t||_||_|r2|d|_g|_dS)a @param authorities: Resolvers which provide authoritative answers. @type authorities: L{list} of L{IResolver} providers @param caches: Resolvers which provide cached non-authoritative answers. The first cache instance is assigned to C{DNSServerFactory.cache} and its C{cacheResult} method will be called when a response is received from one of C{clients}. @type caches: L{list} of L{Cache} instances @param clients: Resolvers which are capable of performing recursive DNS lookups. @type clients: L{list} of L{IResolver} providers @param verbose: An integer controlling the verbosity of logging of queries and responses. Default is C{0} which means no logging. Set to C{2} to enable logging of full query and response messages. @type verbose: L{int} N)extend canRecurser ResolverChainresolververbosecache connections)self authoritiescachesclientsr resolversr6/usr/lib/python3/dist-packages/twisted/names/server.py__init__Es       zDNSServerFactory.__init__cOs"|jdkrtj|i|dSdS)z Log a message only if verbose logging is enabled. @param args: Positional arguments which will be passed to C{log.msg} @param kwargs: Keyword arguments which will be passed to C{log.msg} rN)r rmsg)rargskwargsrrr _verboseLoghs zDNSServerFactory._verboseLogcCs||}||_|SN)rfactory)raddrprrr buildProtocolrs zDNSServerFactory.buildProtocolcC|j|dS)z Track a newly connected L{DNSProtocol}. @param protocol: The protocol instance to be tracked. @type protocol: L{dns.DNSProtocol} N)rappendrrrrrconnectionMadewszDNSServerFactory.connectionMadecCr )z Stop tracking a no-longer connected L{DNSProtocol}. @param protocol: The tracked protocol instance to be which has been lost. @type protocol: L{dns.DNSProtocol} N)rremover"rrrconnectionLostszDNSServerFactory.connectionLostcCs|jdkrCddd|jD}ddd|jD}ddd|jD}|s.tdntd|td |td ||d urM||n||||d t |j d S) a] Send a response C{message} to a given C{address} via the supplied C{protocol}. Message payload will be logged if C{DNSServerFactory.verbose} is C{>1}. @param protocol: The DNS protocol instance to which to send the message. @type protocol: L{dns.DNSDatagramProtocol} or L{dns.DNSProtocol} @param message: The DNS message to be sent. @type message: L{dns.Message} @param address: The address to which the message will be sent or L{None} if C{protocol} is a stream protocol. @type address: L{tuple} or L{None}  cSg|]}t|jqSrstrpayload.0arrr z.DNSServerFactory.sendReply..cSr(rr)r,rrrr/r0cSr(rr)r,rrrr/r0zReplying with no answersz Answers are z Authority is zAdditional is Nz Processed query in %0.3f seconds) r joinanswers authority additionalrr writeMessagertime timeReceived)rrmessageaddresssauthaddrrr sendReplys    zDNSServerFactory.sendReplyc Cs|durg}|dur g}|durg}d}|D] }|r d}nqtj|j||j||d}t|dd|_|j|_||_||_ ||_ |S)a+ Generate a L{Message} instance suitable for use as the response to C{message}. C{queries} will be copied from the request to the response. C{rCode}, C{answers}, C{authority} and C{additional} will be assigned to the response, if supplied. The C{recAv} flag will be set on the response if the C{canRecurse} flag on this L{DNSServerFactory} is set to L{True}. The C{auth} flag will be set on the response if *any* of the supplied C{answers} have their C{auth} flag set to L{True}. The response will have the same C{maxSize} as the request. Additionally, the response will have a C{timeReceived} attribute whose value is that of the original request and the @see: L{dns._responseFromMessage} @param message: The request message @type message: L{Message} @param rCode: The response code which will be assigned to the response. @type message: L{int} @param answers: An optional list of answer records which will be assigned to the response. @type answers: L{list} of L{dns.RRHeader} @param authority: An optional list of authority records which will be assigned to the response. @type authority: L{list} of L{dns.RRHeader} @param additional: An optional list of additional records which will be assigned to the response. @type additional: L{list} of L{dns.RRHeader} @return: A response L{Message} instance. @rtype: L{Message} NFT)responseConstructorr8recAvrCoder;r7) isAuthoritativer_responseFromMessage_messageFactoryr getattrr7maxSizer2r3r4) rr8r@r2r3r4authoritativeAnswerxresponserrrrBs2. z%DNSServerFactory._responseFromMessagec Cs|\}}}|j|tj|||d}||||t|t|t|}|d||dkr-dp.df|jrF|rH|j|jd|||fdSdSdS)a A callback used by L{DNSServerFactory.handleQuery} for handling the deferred response from C{self.resolver.query}. Constructs a response message by combining the original query message with the resolved answer, authority and additional records. Marks the response message as authoritative if any of the resolved answers are found to be authoritative. The resolved answers count will be logged if C{DNSServerFactory.verbose} is C{>1}. @param response: Answer records, authority records and additional records @type response: L{tuple} of L{list} of L{dns.RRHeader} instances @param protocol: The DNS protocol instance to which to send a response message. @type protocol: L{dns.DNSDatagramProtocol} or L{dns.DNSProtocol} @param message: The original DNS query message for which a response message will be constructed. @type message: L{dns.Message} @param address: The address to which the response message will be sent or L{None} if C{protocol} is a stream protocol. @type address: L{tuple} or L{None} )r8r@r2r3r4zLookup found %d record%sr&r:rN) rBrOKr=lenrr cacheResultqueries) rrHrr8r9ansr;r<lrrrgotResolverResponses   z$DNSServerFactory.gotResolverResponsecCsR|tjtjr tj}ntj}t||j||d}| |||| ddS)a  A callback used by L{DNSServerFactory.handleQuery} for handling deferred errors from C{self.resolver.query}. Constructs a response message from the original query message by assigning a suitable error code to C{rCode}. An error message will be logged if C{DNSServerFactory.verbose} is C{>1}. @param failure: The reason for the failed resolution (as reported by C{self.resolver.query}). @type failure: L{Failure} @param protocol: The DNS protocol instance to which to send a response message. @type protocol: L{dns.DNSDatagramProtocol} or L{dns.DNSProtocol} @param message: The original DNS query message for which a response message will be constructed. @type message: L{dns.Message} @param address: The address to which the response message will be sent or L{None} if C{protocol} is a stream protocol. @type address: L{tuple} or L{None} )r8r@z Lookup failedN) checkr DomainErrorAuthoritativeDomainErrorENAMEESERVERrerrrBr=r)rfailurerr8r9r@rHrrrgotResolverError*s z!DNSServerFactory.gotResolverErrorcCs2|jd}|j||j||||j|||S)a` Called by L{DNSServerFactory.messageReceived} when a query message is received. Takes the first query from the received message and dispatches it to C{self.resolver.query}. Adds callbacks L{DNSServerFactory.gotResolverResponse} and L{DNSServerFactory.gotResolverError} to the resulting deferred. Note: Multiple queries in a single message are not supported because there is no standard way to respond with multiple rCodes, auth, etc. This is consistent with other DNS server implementations. See U{http://tools.ietf.org/html/draft-ietf-dnsext-edns1-03} for a proposed solution. @param protocol: The DNS protocol instance to which to send a response message. @type protocol: L{dns.DNSDatagramProtocol} or L{dns.DNSProtocol} @param message: The original DNS query message for which a response message will be constructed. @type message: L{dns.Message} @param address: The address to which the response message will be sent or L{None} if C{protocol} is a stream protocol. @type address: L{tuple} or L{None} @return: A C{deferred} which fires with the resolved result or error of the first query in C{message}. @rtype: L{Deferred} r)rMr query addCallbackrP addErrbackrX)rr8rr9rYrrr handleQueryOs ! zDNSServerFactory.handleQuerycC*tj|_|||||d|dS)a# Called by L{DNSServerFactory.messageReceived} when an inverse query message is received. Replies with a I{Not Implemented} error by default. An error message will be logged if C{DNSServerFactory.verbose} is C{>1}. Override in a subclass. @param protocol: The DNS protocol instance to which to send a response message. @type protocol: L{dns.DNSDatagramProtocol} or L{dns.DNSProtocol} @param message: The original DNS query message for which a response message will be constructed. @type message: L{dns.Message} @param address: The address to which the response message will be sent or L{None} if C{protocol} is a stream protocol. @type address: L{tuple} or L{None} zInverse query from NrENOTIMPr@r=rrr8rr9rrrhandleInverseQueryxz#DNSServerFactory.handleInverseQuerycCr])a Called by L{DNSServerFactory.messageReceived} when a status message is received. Replies with a I{Not Implemented} error by default. An error message will be logged if C{DNSServerFactory.verbose} is C{>1}. Override in a subclass. @param protocol: The DNS protocol instance to which to send a response message. @type protocol: L{dns.DNSDatagramProtocol} or L{dns.DNSProtocol} @param message: The original DNS query message for which a response message will be constructed. @type message: L{dns.Message} @param address: The address to which the response message will be sent or L{None} if C{protocol} is a stream protocol. @type address: L{tuple} or L{None} zStatus request from Nr^r`rrr handleStatusrbzDNSServerFactory.handleStatuscCr])a Called by L{DNSServerFactory.messageReceived} when a notify message is received. Replies with a I{Not Implemented} error by default. An error message will be logged if C{DNSServerFactory.verbose} is C{>1}. Override in a subclass. @param protocol: The DNS protocol instance to which to send a response message. @type protocol: L{dns.DNSDatagramProtocol} or L{dns.DNSProtocol} @param message: The original DNS query message for which a response message will be constructed. @type message: L{dns.Message} @param address: The address to which the response message will be sent or L{None} if C{protocol} is a stream protocol. @type address: L{tuple} or L{None} zNotify message from Nr^r`rrr handleNotifyrbzDNSServerFactory.handleNotifycCs.tj|_|||||d|j|fdS)a0 Called by L{DNSServerFactory.messageReceived} when a message with unrecognised I{OPCODE} is received. Replies with a I{Not Implemented} error by default. An error message will be logged if C{DNSServerFactory.verbose} is C{>1}. Override in a subclass. @param protocol: The DNS protocol instance to which to send a response message. @type protocol: L{dns.DNSDatagramProtocol} or L{dns.DNSProtocol} @param message: The original DNS query message for which a response message will be constructed. @type message: L{dns.Message} @param address: The address to which the response message will be sent or L{None} if C{protocol} is a stream protocol. @type address: L{tuple} or L{None} zUnknown op code (%d) from %rN)rr_r@r=ropCoder`rrr handleOtherszDNSServerFactory.handleOthercCs<t|_|jrE|jdkrddd|jD}n ddd|jD}t|s6td|p1|j nt|d|pA|j | |||sYt j |_ ||||dS|jt jkrh||||dS|jt jkrw||||dS|jt jkr||||dS|jt jkr||||dS||||dS) a L{DNSServerFactory.messageReceived} is called by protocols which are under the control of this L{DNSServerFactory} whenever they receive a DNS query message or an unexpected / duplicate / late DNS response message. L{DNSServerFactory.allowQuery} is called with the received message, protocol and origin address. If it returns L{False}, a C{dns.EREFUSED} response is sent back to the client. Otherwise the received message is dispatched to one of L{DNSServerFactory.handleQuery}, L{DNSServerFactory.handleInverseQuery}, L{DNSServerFactory.handleStatus}, L{DNSServerFactory.handleNotify}, or L{DNSServerFactory.handleOther} depending on the I{OPCODE} of the received message. If C{DNSServerFactory.verbose} is C{>0} all received messages will be logged in more or less detail depending on the value of C{verbose}. @param message: The DNS message that was received. @type message: L{dns.Message} @param proto: The DNS protocol instance which received the message @type proto: L{dns.DNSDatagramProtocol} or L{dns.DNSProtocol} @param address: The address from which the message was received. Only provided for messages received by datagram protocols. The origin of Messages received from stream protocols can be gleaned from the protocol C{transport} attribute. @type address: L{tuple} or L{None} r&r'cSsg|]}t|qSr)r*r-qrrrr/sz4DNSServerFactory.messageReceived..cSsg|] }tj|jdqS)UNKNOWN)r QUERY_TYPESgettypergrrrr/ szEmpty query from z query from N)r6r7r r1rMrKrr transportgetPeer allowQueryrEREFUSEDr@r=reOP_QUERYr\ OP_INVERSEra OP_STATUSrc OP_NOTIFYrdrf)rr8protor9r:rrrmessageReceiveds,      z DNSServerFactory.messageReceivedcCs t|jS)a Called by L{DNSServerFactory.messageReceived} to decide whether to process a received message or to reply with C{dns.EREFUSED}. This default implementation permits anything but empty queries. Override in a subclass to implement alternative policies. @param message: The DNS message that was received. @type message: L{dns.Message} @param protocol: The DNS protocol instance which received the message @type protocol: L{dns.DNSDatagramProtocol} or L{dns.DNSProtocol} @param address: The address from which the message was received. Only provided for messages received by datagram protocols. The origin of Messages received from stream protocols can be gleaned from the protocol C{transport} attribute. @type address: L{tuple} or L{None} @return: L{True} if the received message contained one or more queries, else L{False}. @rtype: L{bool} )rKrMr`rrrro s zDNSServerFactory.allowQuery)NNNrr)__name__ __module__ __qualname____doc__r DNSProtocolrr MessagerCrrrr#r%r=rJrBrPrXr\rarcrdrfrvrorrrrrs,% #   & R)%)  s