
    hV                     b    S r SSKrSSKJr  SSKJrJr  SSKJr   " S S\R                  5      r
g)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)dnsresolve)logc                       \ rS rSrSr\R                  rSr\R                  r
SS jrS rS rS rS rS	 r\R"                  SSS4S
 jrS rS rS rS rS rS rS rSS jrS rSrg)DNSServerFactory   a  
Server factory and tracker for L{DNSProtocol} connections.  This class also
provides records for responses to DNS queries.

@ivar cache: A L{Cache<twisted.names.cache.CacheResolver>} 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<twisted.names.cache.CacheResolver>} 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}
Nc                    / nUb  UR                  U5        Ub  UR                  U5        Ub  UR                  U5        U(       U l        [        R                  " U5      U l        X@l        U(       a
  US   U l        / U l        g)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<twisted.names.cache.CacheResolver>} 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   ResolverChainresolververbosecacheconnections)selfauthoritiescachesclientsr   	resolverss         [/root/1688_scrapy/alibaba-scraper/venv/lib/python3.13/site-packages/twisted/names/server.py__init__DNSServerFactory.__init__E   s{    ( 	"[)V$W%")k--i8DJ    c                 R    U R                   S:  a  [        R                  " U0 UD6  gg)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}
r   N)r   r   msg)r   argskwargss      r   _verboseLogDNSServerFactory._verboseLogh   s&     <<!GGT$V$ r   c                 4    U R                  U 5      nXl        U$ N)r   factory)r   addrps      r   buildProtocolDNSServerFactory.buildProtocolr   s    MM$	r   c                 :    U R                   R                  U5        g)z
Track a newly connected L{DNSProtocol}.

@param protocol: The protocol instance to be tracked.
@type protocol: L{dns.DNSProtocol}
N)r   appendr   r   s     r   connectionMadeDNSServerFactory.connectionMadew   s     	)r   c                 :    U R                   R                  U5        g)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)r   remover+   s     r   connectionLostDNSServerFactory.connectionLost   s     	)r   c                 H   U R                   S:  Ga&  SR                  UR                   Vs/ s H  n[        UR                  5      PM     sn5      nSR                  UR
                   Vs/ s H  n[        UR                  5      PM     sn5      nSR                  UR                   Vs/ s H  n[        UR                  5      PM     sn5      nU(       d  [        R                  " S5        OK[        R                  " SU-   5        [        R                  " SU-   5        [        R                  " SU-   5        Uc  UR                  " U5        OUR                  " X#5        U R                  S[        R                  " 5       UR                  -
  -  5        gs  snf s  snf s  snf )	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}
    zReplying with no answerszAnswers are zAuthority is zAdditional is Nz Processed query in %0.3f seconds)r   joinanswersstrpayload	authority
additionalr   r   writeMessager    timetimeReceived)r   r   messageaddressasauthadds           r   	sendReplyDNSServerFactory.sendReply   s+   " <<!'//B/Q#aii./BCA88W5F5FG5FS^5FGHD((G4F4FG4FqC		N4FGHC23*+$./(3./?!!'*!!'3.$))+@T@T2TU	
 CGGs   F*F)Fc                 .   Uc  / nUc  / nUc  / nSnU H  nUR                  5       (       d  M  Sn  O   [        R                  " U R                  UU R                  UUS9n[        USS5      Ul        UR                  Ul        X8l        XHl	        XXl
        U$ )aC  
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)responseConstructorr>   recAvrCoderB   r=   )isAuthoritativer   _responseFromMessage_messageFactoryr   getattrr=   maxSizer6   r9   r:   )	r   r>   rI   r6   r9   r:   authoritativeAnswerxresponses	            r   rK   %DNSServerFactory._responseFromMessage   s    \ ?GIJ#A  ""&*# 
 ++ $ 4 4//$
 !( F
 #??"&(r   c                    Uu  pVnU R                  U[        R                  XVUS9nU R                  X!U5        [	        U5      [	        U5      -   [	        U5      -   nU R                  SXS:g  =(       a    S=(       d    S4-  5        U R                  (       a4  U(       a,  U R                  R                  UR                  S   XVU45        ggg)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}
)r>   rI   r6   r9   r:   zLookup found %d record%sr3   rA    r   N)	rK   r   OKrD   lenr    r   cacheResultqueries)	r   rQ   r   r>   r?   ansrB   rC   ls	            r   gotResolverResponse$DNSServerFactory.gotResolverResponse  s    : "3,,3663SV - 
 	x73Hs4y 3s8+3qq&.S:NB6OOP::!JJ""7??1#537GH :r   c                 <   UR                  [        R                  [        R                  5      (       a  [        R                  nO&[        R
                  n[        R                  " U5        U R                  X5S9nU R                  X&U5        U R                  S5        g)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<twisted.python.failure.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}
)r>   rI   zLookup failedN)checkr   DomainErrorAuthoritativeDomainErrorENAMEESERVERr   errrK   rD   r    )r   failurer   r>   r?   rI   rQ   s          r   gotResolverError!DNSServerFactory.gotResolverError*  sl    4 ==#*F*FGGIIEKKEGGG,,W,Jx73)r   c                     UR                   S   nU R                  R                  U5      R                  U R                  X!U5      R                  U R                  X!U5      $ )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<twisted.internet.defer.Deferred>}
r   )rX   r   queryaddCallbackr[   
addErrbackre   )r   r>   r   r?   rh   s        r   handleQueryDNSServerFactory.handleQueryO  sT    B " MM&[118gNZ--x'J	
r   c                 |    [         R                  Ul        U R                  X!U5        U R	                  SU< 35        g)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}
zInverse query from Nr   ENOTIMPrI   rD   r    r   r>   r   r?   s       r   handleInverseQuery#DNSServerFactory.handleInverseQueryx  s3    . x'2.wk:;r   c                 |    [         R                  Ul        U R                  X!U5        U R	                  SU< 35        g)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}
zStatus request from Nrn   rp   s       r   handleStatusDNSServerFactory.handleStatus  3    . x'2/{;<r   c                 |    [         R                  Ul        U R                  X!U5        U R	                  SU< 35        g)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}
zNotify message from Nrn   rp   s       r   handleNotifyDNSServerFactory.handleNotify  rv   r   c                     [         R                  Ul        U R                  X!U5        U R	                  SUR
                  U4-  5        g)a  
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}
zUnknown op code (%d) from %rN)r   ro   rI   rD   r    opCoderp   s       r   handleOtherDNSServerFactory.handleOther  s:    . x'277>>7:SSTr   c           	         [         R                   " 5       Ul        U R                  (       Ga#  U R                  S:  a6  SR                  UR                   Vs/ s H  n[        U5      PM     sn5      nOTSR                  UR                   Vs/ s H-  n[        R                  R                  UR                  S5      PM/     sn5      n[        U5      (       d<  [        R                  " SU=(       d    UR                  R                  5       < 35        O=[        R                  " U SU=(       d    UR                  R                  5       < 35        U R                  XU5      (       d(  [        R                   Ul        U R%                  X!U5        gUR&                  [        R(                  :X  a  U R+                  XU5        gUR&                  [        R,                  :X  a  U R/                  XU5        gUR&                  [        R0                  :X  a  U R3                  XU5        gUR&                  [        R4                  :X  a  U R7                  XU5        gU R9                  XU5        gs  snf s  snf )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}
r3   r4   UNKNOWNzEmpty query from z query from N)r<   r=   r   r5   rX   r7   r   QUERY_TYPESgettyperV   r   r   	transportgetPeer
allowQueryEREFUSEDrI   rD   r{   OP_QUERYrk   
OP_INVERSErq   	OP_STATUSrt   	OP_NOTIFYrx   r|   )r   r>   protor?   qrA   s         r   messageReceived DNSServerFactory.messageReceived  s   @  $yy{<<<||aHHgoo>oc!fo>?HHEL__U_S__((;_U q66+G,Pu7N7N7P+STU1#\'*NU__5L5L5N)QRSww77LLGMNN573^^s||+WW5^^s~~-##GG<^^s}},gg6^^s}},gg6WW5- ? Vs   I&4I+c                 ,    [        UR                  5      $ )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}
)rV   rX   rp   s       r   r   DNSServerFactory.allowQuery   s    2 7??##r   )r   r   r   r   r   )NNNr   r#   )__name__
__module____qualname____firstlineno____doc__r   DNSProtocolr   r   MessagerL   r   r    r'   r,   r0   rD   rU   rK   r[   re   rk   rq   rt   rx   r|   r   r   __static_attributes__ r   r   r   r      s    "J HEkkO!F%
**#
L !VVTTdPd'IR#*J'
R<6=6=6U6:6x$r   r   )r   r<   twisted.internetr   twisted.namesr   r   twisted.pythonr   ServerFactoryr   r   r   r   <module>r      s,   
  % & ^$x-- ^$r   