
    h?                      S r SSKJr  SSKrSSKrSSKrSSKrSSKJrJ	r	J
r
JrJrJrJrJrJr  SSKJr  SSKJrJr  SSKJrJr  SSKJr  SS	KJrJrJrJrJ r   SS
K!J"r"  SSK#J$r$J%r%J&r&J'r'  SSK(J)r)J*r*J+r+J,r,J-r-J.r.J/r/J0r0J1r1J2r2J3r3J4r4  SSK5J6r6J7r7J8r8J9r9   SSK:J;r;J<r<  SSK>J?r?  SSK@JArA  SSKBJCrC  SSKDJErE  SSKFJGrGJHrH  SSKIJJrJJKrK  SSKLJMrMJNrNJOrO  SSKPJQrQ  SSKRJSrS  SSKTJUrU  SSKVJWrW  SSKXJYrYJZrZ   SSK[J\r]  SSK^J_r_J`r`JaraJbrbJcrcJdrd  SSKeJfrg  \grf/ SQrh " S  S!\95      ri " S" S#\65      rj\" \R                  5       " S$ S%5      5       rl " S& S'\R                  \R                  \R                  5      rp " S( S)\Q" \pS*5      5      rq " S+ S,\85      rr " S- S.\5      rs\" \Rd                  5       " S/ S05      5       rt\" \R                  5       " S1 S25      5       ru " S3 S4\u5      rv " S5 S6\u5      rw\" \Rd                  5       " S7 S85      5       rx\" \Rd                  5       " S9 S:5      5       ry\\\R                  \R                  \|\}\\\}\|4   \\}\|\|\|4   4   4      r~ \" \*5       " S; S<5      5       r\" \Rd                  5       " S= S>5      5       r\" \R                  5       " S? S@5      5       r\" \Rd                  5       " SA SB5      5       r\" \R                  5       " SC SD5      5       r\" \Rd                  5       " SE SF5      5       r\" \R                  5       " SG SH5      5       rSlSI jrSmSJ jr       SnSK jr\" \G\45       " SL SM5      5       r\" \G\45       " SN SO5      5       r\" \G\45       " SP SQ5      5       r\\\SR.r\" SS5      u  rrST rSU r\v\\SV.r\x\\SV.rSW rSX rSY rSZ rS[ rS\ rS] rS^ rS_ rS` rSa r\\\SV.rSb rSc r\" \Rd                  5       " Sd Se5      5       r\" \R                  5       " Sf Sg5      5       r      SoSh jr      Sp                     SqSi jjr\" \G\35       " Sj Sk5      5       rg! \= a    Sr<Sr; GNf = f! \= a    Srf GNff = f)ra7  
Implementations of L{IStreamServerEndpoint} and L{IStreamClientEndpoint} that
wrap the L{IReactorTCP}, L{IReactorSSL}, and L{IReactorUNIX} interfaces.

This also implements an extensible mini-language for describing endpoints,
parsed by the L{clientFromString} and L{serverFromString} functions.

@since: 10.1
    )annotationsN)	AnyCallableIterableListOptionalSequenceTupleTypeUnion)	normalize)directlyProvidesimplementer)NamedConstantNames)Version)defererrorfdesc
interfacesthreads)isIPv6Address)HostnameAddressIPv4AddressIPv6Address_ProcessAddress)IAddressIHostnameResolverIHostResolutionIOpenSSLClientConnectionCreator	IProtocolIProtocolFactoryIReactorPluggableNameResolverIReactorSocketIResolutionReceiverIStreamClientEndpoint,IStreamClientEndpointStringParserWithReactor!IStreamServerEndpointStringParser)ClientFactoryFactoryProcessProtocolProtocol)PipeAddress
StandardIO)HostResolution)Deferred)LoopingCall)Logger)IPlugin
getPlugins)	deprecatelog)_matchingString	iterbytesnativeString)proxyForInterface)Failure)FilePath)	ListenFDs   )
_idnaBytes	_idnaText)Error)CertificateCertificateOptionsKeyPairPrivateCertificateoptionsForClientTLStrustRootFromCertificatesTLSMemoryBIOFactory)clientFromStringserverFromStringTCP4ServerEndpointTCP6ServerEndpointTCP4ClientEndpointTCP6ClientEndpointUNIXServerEndpointUNIXClientEndpointSSL4ServerEndpointSSL4ClientEndpointAdoptedStreamServerEndpointStandardIOEndpointProcessEndpointHostnameEndpointStandardErrorBehaviorconnectProtocolwrapClientTLSc                  N    \ rS rSrSrS rS rS rS rS r	S r
S	 rS
 rS rSrg)_WrappingProtocolo   zS
Wrap another protocol in order to notify my user when a connection has
been made.
c                    Xl         X l        [        R                  [        R                  [        R
                  4 H0  nUR                  U R                  5      (       d  M%  [        X5        M2     g)z
@param connectedDeferred: The L{Deferred} that will callback
    with the C{wrappedProtocol} when it is connected.

@param wrappedProtocol: An L{IProtocol} provider that will be
    connected.
N)_connectedDeferred_wrappedProtocolr   IHalfCloseableProtocolIFileDescriptorReceiverIHandshakeListener
providedByr   )selfconnectedDeferredwrappedProtocolifaces       a/root/1688_scrapy/alibaba-scraper/venv/lib/python3.13/site-packages/twisted/internet/endpoints.py__init___WrappingProtocol.__init__u   sZ     #4 / --..))
E
  5 566 -
    c                    [         R                  R                  U R                  5      (       a  U R                  R	                  5       $ U R                  R
                  R                  $ )z?
Transparently pass through the wrapped protocol's log prefix.
)r   ILoggingContextrd   r`   	logPrefix	__class____name__re   s    ri   ro   _WrappingProtocol.logPrefix   sN     %%001F1FGG((2244$$..777rl   c                    U R                   R                  U R                  5        U R                  R	                  U R                   5        g)z
Connect the C{self._wrappedProtocol} to our C{self.transport} and
callback C{self._connectedDeferred} with the C{self._wrappedProtocol}
N)r`   makeConnection	transportr_   callbackrr   s    ri   connectionMade _WrappingProtocol.connectionMade   s6    
 	,,T^^<(()>)>?rl   c                8    U R                   R                  U5      $ )z=
Proxy C{dataReceived} calls to our C{self._wrappedProtocol}
)r`   dataReceived)re   datas     ri   r{   _WrappingProtocol.dataReceived   s     $$11$77rl   c                8    U R                   R                  U5      $ )zG
Proxy C{fileDescriptorReceived} calls to our C{self._wrappedProtocol}
)r`   fileDescriptorReceived)re   
descriptors     ri   r   (_WrappingProtocol.fileDescriptorReceived   s     $$;;JGGrl   c                8    U R                   R                  U5      $ )z?
Proxy C{connectionLost} calls to our C{self._wrappedProtocol}
)r`   connectionLostre   reasons     ri   r    _WrappingProtocol.connectionLost   s     $$33F;;rl   c                8    U R                   R                  5         g)zT
Proxy L{IHalfCloseableProtocol.readConnectionLost} to our
C{self._wrappedProtocol}
N)r`   readConnectionLostrr   s    ri   r   $_WrappingProtocol.readConnectionLost       
 	002rl   c                8    U R                   R                  5         g)zU
Proxy L{IHalfCloseableProtocol.writeConnectionLost} to our
C{self._wrappedProtocol}
N)r`   writeConnectionLostrr   s    ri   r   %_WrappingProtocol.writeConnectionLost   s    
 	113rl   c                8    U R                   R                  5         g)zI
Proxy L{interfaces.IHandshakeListener} to our
C{self._wrappedProtocol}.
N)r`   handshakeCompletedrr   s    ri   r   $_WrappingProtocol.handshakeCompleted   r   rl   )r_   r`   N)rq   
__module____qualname____firstlineno____doc__rj   ro   rx   r{   r   r   r   r   r   __static_attributes__ rl   ri   r\   r\   o   s6    
.&8@8H<343rl   r\   c                  J    \ rS rSrSr\rSS jrS rS r	S r
S rS rS	 rS
rg)_WrappingFactory   a  
Wrap a factory in order to wrap the protocols it builds.

@ivar _wrappedFactory: A provider of I{IProtocolFactory} whose buildProtocol
    method will be called and whose resulting protocol will be wrapped.

@ivar _onConnection: A L{Deferred} that fires when the protocol is
    connected

@ivar _connector: A L{connector <twisted.internet.interfaces.IConnector>}
    that is managing the current or previous connection attempt.
c                V    Xl         [        R                  " U R                  S9U l        g)z
@param wrappedFactory: A provider of I{IProtocolFactory} whose
    buildProtocol method will be called and whose resulting protocol
    will be wrapped.
	cancellerN)_wrappedFactoryr   r0   
_canceller_onConnection)re   wrappedFactorys     ri   rj   _WrappingFactory.__init__   s"      .8=oo9
rl   c                    Xl         g)zf
A connection attempt was started.  Remember the connector which started
said attempt, for use later.
N)
_connector)re   	connectors     ri   startedConnecting"_WrappingFactory.startedConnecting   s	    
 $rl   c                    UR                  [        R                  " U R                  R	                  5       5      5        U R                  R                  5         g)a  
The outgoing connection attempt was cancelled.  Fail that L{Deferred}
with an L{error.ConnectingCancelledError}.

@param deferred: The L{Deferred <defer.Deferred>} that was cancelled;
    should be the same as C{self._onConnection}.
@type deferred: L{Deferred <defer.Deferred>}

@note: This relies on startedConnecting having been called, so it may
    seem as though there's a race condition where C{_connector} may not
    have been set.  However, using public APIs, this condition is
    impossible to catch, because a connection API
    (C{connectTCP}/C{SSL}/C{UNIX}) is always invoked before a
    L{_WrappingFactory}'s L{Deferred <defer.Deferred>} is returned to
    C{connect()}'s caller.

@return: L{None}
N)errbackr   ConnectingCancelledErrorr   getDestinationstopConnecting)re   deferreds     ri   r   _WrappingFactory._canceller   s?    & 	**4??+I+I+KL	
 	&&(rl   c                8    U R                   R                  5         g)zI
Start notifications are passed straight through to the wrapped factory.
N)r   doStartrr   s    ri   r   _WrappingFactory.doStart   s     	$$&rl   c                8    U R                   R                  5         g)zH
Stop notifications are passed straight through to the wrapped factory.
N)r   doStoprr   s    ri   r   _WrappingFactory.doStop  s     	##%rl   c                     U R                   R                  U5      nUc  [        R                  " 5       e U R	                  U R
                  U5      $ ! [         a    U R
                  R                  5          gf = f)z
Proxy C{buildProtocol} to our C{self._wrappedFactory} or errback the
C{self._onConnection} L{Deferred} if the wrapped factory raises an
exception or returns L{None}.

@return: An instance of L{_WrappingProtocol} or L{None}
N)r   buildProtocolr   
NoProtocolprotocolr   BaseExceptionr   )re   addrprotos      ri   r   _WrappingFactory.buildProtocol  sr    	<((66t<E}&&(( 
 ==!3!3U;;  	)&&(	)s   3A $A98A9c                r    U R                   R                  (       d  U R                   R                  U5        gg)zQ
Errback the C{self._onConnection} L{Deferred} when the
client connection fails.
N)r   calledr   )re   r   r   s      ri   clientConnectionFailed'_WrappingFactory.clientConnectionFailed  s,    
 !!((&&v. )rl   )r   r   r   N)r   r"   returnNone)rq   r   r   r   r   r\   r   rj   r   r   r   r   r   r   r   r   rl   ri   r   r      s1     !H	
$)0'&<"/rl   r   c                  (    \ rS rSrSr\rS rS rSr	g)rU   i!  z
A Standard Input/Output endpoint

@ivar _stdio: a callable, like L{stdio.StandardIO}, which takes an
    L{IProtocol} provider and a C{reactor} keyword argument (interface
    dependent upon your platform).
c                    Xl         g)z/
@param reactor: The reactor for the endpoint.
N_reactorre   reactors     ri   rj   StandardIOEndpoint.__init__-  s	      rl   c                    [         R                  " U R                  UR                  [	        5       5      U R
                  S9$ )zE
Implement L{IStreamServerEndpoint.listen} to listen on stdin/stdout
)r   )r   execute_stdior   r-   r   )re   stdioProtocolFactorys     ri   listenStandardIOEndpoint.listen3  s3     }}KK ..{}=MM
 	
rl   r   N)
rq   r   r   r   r   r.   r   rj   r   r   r   rl   ri   rU   rU   !  s     F 
rl   rU   c                      \ rS rSrSrSrg))_IProcessTransportWithConsumerAndProduceri>  a  
An L{_IProcessTransportWithConsumerAndProducer} combines various interfaces
to work around the issue that L{interfaces.IProcessTransport} is
incompletely defined and doesn't specify flow-control interfaces, and that
L{proxyForInterface} doesn't allow for multiple interfaces.
r   Nrq   r   r   r   r   r   r   rl   ri   r   r   >  s    rl   r   c                      \ rS rSrSrSrg)_ProcessEndpointTransportiI  aR  
An L{ITransport}, L{IProcessTransport}, L{IConsumer}, and L{IPushProducer}
provider for the L{IProtocol} instance passed to the process endpoint.

@ivar _process: An active process transport which will be used by write
    methods on this object to write data to a child process.
@type _process: L{interfaces.IProcessTransport} provider
r   Nr   r   rl   ri   r   r   I  s    rl   r   _processc                  0    \ rS rSrSrS rS rS rS rSr	g)	_WrapIProtocoliY  z
An L{IProcessProtocol} provider that wraps an L{IProtocol}.

@ivar transport: A L{_ProcessEndpointTransport} provider that is hooked to
    the wrapped L{IProtocol} provider.

@see: L{protocol.ProcessProtocol}
c                (    Xl         X0l        X l        g)z
@param proto: An L{IProtocol} provider.
@param errFlag: A constant belonging to L{StandardErrorBehavior}
    that determines if stderr is logged or dropped.
@param executable: The file name (full path) to spawn.
N)r   errFlag
executable)re   r   r   r   s       ri   rj   _WrapIProtocol.__init__c  s     $rl   c                l    [        U5      U l        U R                  R                  U R                  5      $ )z
Call L{IProtocol} provider's makeConnection method with an
L{ITransport} provider.

@param process: An L{IProcessTransport} provider.
)r   rv   r   ru   )re   processs     ri   ru   _WrapIProtocol.makeConnectionn  s)     37;}}++DNN;;rl   c                    US:X  a  U R                   R                  U5      $ US:X  aK  U R                  [        R                  :X  a,  [
        R                  " SU R                  U R                   US9  ggg)z
This is called with data from the process's stdout or stderr pipes. It
checks the status of the errFlag to setermine if stderr should be
logged (default) or dropped.
r>      zGProcess %(executable)r wrote stderr unhandled by %(protocol)s: %(data)s)formatr   r   r|   N)r   r{   r   rX   LOGr6   msgr   )re   childFDr|   s      ri   childDataReceived _WrapIProtocol.childDataReceivedx  sc     a<==--d33\dll.C.G.GGGG)?? H\rl   c                <   UR                  [        R                  5      [        R                  :X  aQ  UR                  R                  S:X  a7  U R
                  R                  [        [        R                  " 5       5      5      $ U R
                  R                  U5      $ )z
If the process ends with L{error.ProcessDone}, this method calls the
L{IProtocol} provider's L{connectionLost} with a
L{error.ConnectionDone}

@see: L{ProcessProtocol.processEnded}
r   )	checkr   ProcessDonevaluestatusr   r   r;   ConnectionDoner   s     ri   processEnded_WrapIProtocol.processEnded  sk     LL**+u/@/@@LL1$==//8L8L8N0OPP==//77rl   )r   r   r   rv   N)
rq   r   r   r   r   rj   ru   r   r   r   r   rl   ri   r   r   Y  s    	%<"8rl   r   c                  4    \ rS rSrSr\" 5       r\" 5       rSrg)rX   i  z
Constants used in ProcessEndpoint to decide what to do with stderr.

@cvar LOG: Indicates that stderr is to be logged.
@cvar DROP: Indicates that stderr is to be dropped (and not logged).

@since: 13.1
r   N)	rq   r   r   r   r   r   r   DROPr   r   rl   ri   rX   rX     s     /C?Drl   rX   c                  L    \ rS rSrSrS0 SSSSS\R                  4S jrS rSr	g)	rV   i  z|
An endpoint for child processes

@ivar _spawnProcess: A hook used for testing the spawning of child process.

@since: 13.1
r   Nr   c                    Xl         X l        X0l        X@l        XPl        X`l        Xpl        Xl        Xl        Xl	        U R                   R                  U l        g)z
See L{IReactorProcess.spawnProcess}.

@param errFlag: Determines if stderr should be logged.
@type errFlag: L{endpoints.StandardErrorBehavior}
N)r   _executable_args_env_path_uid_gid_usePTY	_childFDs_errFlagspawnProcess_spawnProcess)re   r   r   argsenvpathuidgidusePTYchildFDsr   s              ri   rj   ProcessEndpoint.__init__  sI    &  %
	
		!!]]77rl   c                   UR                  [        5       5      n U R                  [        X R                  U R
                  5      U R                  U R                  U R                  U R                  U R                  U R                  U R                  U R                  5	        [        R                  " U5      $ ! [         a    [        R                   " 5       s $ f = f)a  
Implement L{IStreamClientEndpoint.connect} to launch a child process
and connect it to a protocol created by C{protocolFactory}.

@param protocolFactory: A factory for an L{IProtocol} provider which
    will be notified of all events related to the created process.
)r   r   r   r   r   r   r   r   r   r   r   r   r   r   succeedr   fail)re   protocolFactoryr   s      ri   connectProcessEndpoint.connect  s      --o.?@	(u&6&6F  

		

				
 ==''  	 ::<	 s   BB8 8CC)r   r   r   r   r   r   r   r   r   r   r   )
rq   r   r   r   r   rX   r   rj   r	  r   r   rl   ri   rV   rV     s1     %))8>(rl   rV   c                  $    \ rS rSrSrS rS rSrg)_TCPServerEndpointi  z!
A TCP server endpoint interface
c                4    Xl         X l        X0l        X@l        g)z
@param reactor: An L{IReactorTCP} provider.

@param port: The port number used for listening
@type port: int

@param backlog: Size of the listen queue
@type backlog: int

@param interface: The hostname to bind to
@type interface: str
N)r   _port_backlog
_interfacere   r   portbacklog	interfaces        ri   rj   _TCPServerEndpoint.__init__  s      
#rl   c                    [         R                  " U R                  R                  U R                  UU R
                  U R                  S9$ )zE
Implement L{IStreamServerEndpoint.listen} to listen on a TCP
socket
)r  r  )r   r   r   	listenTCPr  r  r  re   r  s     ri   r   _TCPServerEndpoint.listen  s:    
 }}MM##JJMMoo
 	
rl   )r  r  r  r   Nrq   r   r   r   r   rj   r   r   r   rl   ri   r  r    s    $$
rl   r  c                  "    \ rS rSrSrSS jrSrg)rL   i  z;
Implements TCP server endpoint with an IPv4 configuration
c                2    [         R                  XX#U5        g)a  
@param reactor: An L{IReactorTCP} provider.

@param port: The port number used for listening
@type port: int

@param backlog: Size of the listen queue
@type backlog: int

@param interface: The hostname to bind to, defaults to '' (all)
@type interface: str
Nr  rj   r  s        ri   rj   TCP4ServerEndpoint.__init__       	##D4)Lrl   r   N2    rq   r   r   r   r   rj   r   r   rl   ri   rL   rL         Mrl   rL   c                  "    \ rS rSrSrSS jrSrg)rM   i&  z;
Implements TCP server endpoint with an IPv6 configuration
c                2    [         R                  XX#U5        g)a  
@param reactor: An L{IReactorTCP} provider.

@param port: The port number used for listening
@type port: int

@param backlog: Size of the listen queue
@type backlog: int

@param interface: The hostname to bind to, defaults to C{::} (all)
@type interface: str
Nr  r  s        ri   rj   TCP6ServerEndpoint.__init__+  r  rl   r   Nr!  z::r#  r   rl   ri   rM   rM   &  r$  rl   rM   c                  J    \ rS rSrSr  S           SS jjrS	S jrSrg)
rN   i;  z1
TCP client endpoint with an IPv4 configuration.
Nc                @    Xl         X l        X0l        X@l        XPl        g)a  
@param reactor: An L{IReactorTCP} provider

@param host: A hostname, used when connecting
@type host: str

@param port: The port number, used when connecting
@type port: int

@param timeout: The number of seconds to wait before assuming the
    connection has failed.
@type timeout: L{float} or L{int}

@param bindAddress: A (host, port) tuple of local address to bind to,
    or None.
@type bindAddress: tuple
Nr   _hostr  _timeout_bindAddressre   r   hostr  timeoutbindAddresss         ri   rj   TCP4ClientEndpoint.__init__A  s    2  

'rl   c                    [        U5      nU R                  R                  U R                  U R                  UU R
                  U R                  S9  UR                  $ ! [         a    [        R                  " 5       s $ f = f)z@
Implement L{IStreamClientEndpoint.connect} to connect via TCP.
r1  r2  )r   r   
connectTCPr,  r  r-  r.  r   r   r   r  re   r  wfs      ri   r	  TCP4ClientEndpoint.connect`  sr    	 !/2BMM$$



 -- %  ### 	 ::<	 s   AA B ?B r.  r,  r  r   r-     N)r   r   r0  strr  intr1  floatr2  z$str | tuple[bytes | str, int] | Noner   r   r  r"   r   Deferred[IProtocol]rq   r   r   r   r   rj   r	  r   r   rl   ri   rN   rN   ;  sS     <@(( ( 	(
 ( :( 
(> rl   rN   c                      \ rS rSrSr\" \R                  5      r\" \	R                  5      rSrSrSS jrS rS r      SS	 jrS
rg)rO   ir  ag  
TCP client endpoint with an IPv6 configuration.

@ivar _getaddrinfo: A hook used for testing name resolution.

@ivar _deferToThread: A hook used for testing deferToThread.

@ivar _GAI_ADDRESS: Index of the address portion in result of
    getaddrinfo to be used.

@ivar _GAI_ADDRESS_HOST: Index of the actual host-address in the
    5-tuple L{_GAI_ADDRESS}.
   r   Nc                @    Xl         X l        X0l        X@l        XPl        g)z
@param host: An IPv6 address literal or a hostname with an
    IPv6 address

@see: L{twisted.internet.interfaces.IReactorTCP.connectTCP}
Nr+  r/  s         ri   rj   TCP6ClientEndpoint.__init__  s      

'rl   c                  ^  [        T R                  5      (       a  T R                  T R                  U5      nU$ T R                  T R                  5      nUR	                  U 4S j5        UR	                  T R                  U5        U$ )zf
Implement L{IStreamClientEndpoint.connect} to connect via TCP,
once the hostname resolution is done.
c                B   > U S   TR                      TR                     $ )Nr   )_GAI_ADDRESS_GAI_ADDRESS_HOST)resultre   s    ri   <lambda>,TCP6ClientEndpoint.connect.<locals>.<lambda>  s    vay):):;D<R<RSrl   )r   r,  _resolvedHostConnect_nameResolutionaddCallback)re   r  ds   `  ri   r	  TCP6ClientEndpoint.connect  sq    
 $$))$**oFA  $$TZZ0AMMS MM$33_Erl   c                Z    U R                  U R                  US[        R                  5      $ )zL
Resolve the hostname string into a tuple containing the host
IPv6 address.
r   )_deferToThread_getaddrinfosocketAF_INET6re   r0  s     ri   rO  "TCP6ClientEndpoint._nameResolution  s%    
 ""4#4#4dAvOOrl   c                     [        U5      nU R                  R                  UU R                  UU R                  U R
                  S9  UR                  $ ! [         a    [        R                  " 5       s $ f = f)z4
Connect to the server using the resolved hostname.
r5  )
r   r   r6  r  r-  r.  r   r   r   r  )re   resolvedHostr  r8  s       ri   rN  'TCP6ClientEndpoint._resolvedHostConnect  sn    	 !/2BMM$$

 -- %  ### 	 ::<	 s   AA A65A6r:  r;  )r[  r=  r  r"   r   rA  )rq   r   r   r   r   staticmethodrV  getaddrinforU  r   deferToThreadrT  rI  rJ  rj   r	  rO  rN  r   r   rl   ri   rO   rO   r  sa       2 23L!'"7"78NL(P  2B 	 rl   rO   c                  b    \ rS rSrSr\" 5       r    SS jr   S           S	S jjrSr	g)
_SimpleHostnameResolveri  a>  
An L{IHostnameResolver} provider that invokes a provided callable
to resolve hostnames.

@ivar _nameResolution: the callable L{resolveHostName} invokes to
    resolve hostnames.
@type _nameResolution: A L{callable} that accepts two arguments:
    the host to resolve and the port number to include in the
    result.
c                    Xl         g)z/
Create a L{_SimpleHostnameResolver} instance.
NrO  )re   nameResolutions     ri   rj    _SimpleHostnameResolver.__init__  s
      .rl   Nc                   ^ ^^ [        T5      nTR                  U5        T R                  TU5      nU4S jnUU 4S jn	UR                  U5        UR	                  U	5        UR                  U4S j5        U$ )a  
Initiate a hostname resolution.

@param resolutionReceiver: an object that will receive each resolved
    address as it arrives.
@type resolutionReceiver: L{IResolutionReceiver}

@param hostName: see interface

@param portNumber: see interface

@param addressTypes: Ignored in this implementation.

@param transportSemantics: Ignored in this implementation.

@return: The resolution in progress.
@rtype: L{IResolutionReceiver}
c                   > U  Hi  u  pp4nU[         R                  :X  a  TR                  [        S/UQ76 5        M8  U[         R                  :X  d  MN  TR                  [        S/UQ76 5        Mk     g )NTCP)rV  rW  addressResolvedr   AF_INETr   )	gairesultfamilysocktyper   	canonnamesockaddrresolutionReceivers         ri   	cbDeliver:_SimpleHostnameResolver.resolveHostName.<locals>.cbDeliver  s^    @I<%HV__,&66{57T87TUv~~-&66{57T87TU	 AJrl   c                R   > TR                   R                  SU TTR                  S9  g )Nz'while looking up {name} with {callable})namecallable)_logfailurerO  )r   hostNamere   s    ri   ebLog6_SimpleHostnameResolver.resolveHostName.<locals>.ebLog  s,    II9--	  rl   c                $   > TR                  5       $ N)resolutionComplete)ignoredrp  s    ri   rL  9_SimpleHostnameResolver.resolveHostName.<locals>.<lambda>  s    "4"G"G"Irl   )r/   resolutionBeganrO  rP  
addErrbackaddBoth)
re   rp  rx  
portNumberaddressTypestransportSemantics
resolutionrQ  rq  ry  s
   ```       ri   resolveHostName'_SimpleHostnameResolver.resolveHostName  sg    4 $H-
**:6  :6	V	 	
i 	U			IJrl   rc  )rd  z*Callable[[str, int], Deferred[_gairesult]]r   r   )r   Nrh  )rp  r%   rx  r=  r  r>  r  z"Optional[Sequence[Type[IAddress]]]r  r=  r   r   )
rq   r   r   r   r   r2   rv  rj   r  r   r   rl   ri   ra  ra    st    	 8D.H.	. ;?"'0/0 0 	0
 90  0 
0 0rl   ra  c                      \ rS rSrSr\" \R                  5      r\" \	R                  5      rSr   S             SS jjrSS jrSS jr\SS j5       rSS	 jrS
 rSrg)rW   i  aS  
A name-based endpoint that connects to the fastest amongst the resolved
host addresses.

@cvar _DEFAULT_ATTEMPT_DELAY: The default time to use between attempts, in
    seconds, when no C{attemptDelay} is given to
    L{HostnameEndpoint.__init__}.

@ivar _hostText: the textual representation of the hostname passed to the
    constructor.  Used to pass to the reactor's hostname resolver.
@type _hostText: L{unicode}

@ivar _hostBytes: the encoded bytes-representation of the hostname passed
    to the constructor.  Used to construct the L{HostnameAddress}
    associated with this endpoint.
@type _hostBytes: L{bytes}

@ivar _badHostname: a flag - hopefully false!  - indicating that an invalid
    hostname was passed to the constructor.  This might be a textual
    hostname that isn't valid IDNA, or non-ASCII bytes.
@type _badHostname: L{bool}
g333333?Nc                l   Xl         U R                  U5        U R                  U5      u  U l        U l        U l        X0l        X@l        UbO  [        U[        [        45      (       a  US4n[        US   [        5      (       a  US   R                  5       US   4nXPl        Uc  U R                  nX`l        g)a  
Create a L{HostnameEndpoint}.

@param reactor: The reactor to use for connections and delayed calls.
@type reactor: provider of L{IReactorTCP}, L{IReactorTime} and either
    L{IReactorPluggableNameResolver} or L{IReactorPluggableResolver}.

@param host: A hostname to connect to.
@type host: L{bytes} or L{str}

@param port: The port number to connect to.
@type port: L{int}

@param timeout: For each individual connection attempt, the number of
    seconds to wait before assuming the connection has failed.
@type timeout: L{float} or L{int}

@param bindAddress: The client socket normally uses whatever
    local interface (eth0, en0, lo, etc) is best suited for the
    target address, and a randomly-assigned port. This argument
    allows that local address/port to be overridden. Providing
    just an address (as a str) will bind the client socket to
    whichever interface is assigned that address. Providing a
    tuple of (str, int) will bind it to both an interface and a
    specific local port. To bind the port, but leave the
    interface unbound, use a tuple of ("", port), or ("0.0.0.0",
    port) for IPv4, or ("::0", port) for IPv6. To leave both
    interface and port unbound, just use None.
@type bindAddress: L{str}, L{tuple}, or None

@param attemptDelay: The number of seconds to delay between connection
    attempts.
@type attemptDelay: L{float}

@see: L{twisted.internet.interfaces.IReactorTCP.connectTCP}
Nr   r>   )r   _getNameResolverAndMaybeWarn_hostAsBytesAndText_badHostname
_hostBytes	_hostTextr  r-  
isinstancebytesr=  decoder.  _DEFAULT_ATTEMPT_DELAY_attemptDelay)re   r   r0  r  r1  r2  attemptDelays          ri   rj   HostnameEndpoint.__init__6  s    \   	))'2?C?W?W@
<	DOT^ 
"+s|44*A.+a.%00*1~446AG'66L)rl   c                    U R                   (       a  U R                  OD[        U R                  5      (       a  SU R                   S3OU R                  R	                  S5      nSU SU R
                   S3$ )zP
Produce a string representation of the L{HostnameEndpoint}.

@return: A L{str}
[]asciiz<HostnameEndpoint :>)r  r  r   r  r  r  rX  s     ri   __repr__HostnameEndpoint.__repr__  sn        NN
 !00 DNN#1% __++G4 	  $D64::,a88rl   c           	        [         R                  " U5      (       d\  [        R                  " UR                  [        SSSS5      SSS9n[        R                  " U[        SS	9  [        U R                  5      $ UR                  $ )
z
Retrieve a C{nameResolver} callable and warn the caller's
caller that using a reactor which doesn't provide
L{IReactorPluggableNameResolver} is deprecated.

@param reactor: The reactor to check.

@return: A L{IHostnameResolver} provider.
Twisted      r   zPassing HostnameEndpoint a reactor that does not provide IReactorPluggableNameResolver (%(fqpn)s) was deprecated in %(version)sz5a reactor that provides IReactorPluggableNameResolver)r   replacement   )
stacklevel)r#   rd   r5   getDeprecationWarningStringrp   r   warningswarnDeprecationWarningra  _fallbackNameResolutionnameResolver)re   r   warningStrings      ri   r  -HostnameEndpoint._getNameResolverAndMaybeWarn  sw     -77@@%AA!!	2q!,5
 OM MM-);J*4+G+GHH###rl   c                   Sn[        U [        5      (       a  U n [        U5      nO:[        SU 5      n[        U5      (       a  UR                  S5      nO [        U5      nU(       a#  UR                  SS5      nUR	                  S5      nUWU4$ ! [         a&    UR	                  S5      n[        U5      (       d  Sn N^f = f! [         a    Sn Npf = f)a8  
For various reasons (documented in the C{@ivar}'s in the class
docstring) we need both a textual and a binary representation of the
hostname given to the constructor.  For compatibility and convenience,
we accept both textual and binary representations of the hostname, save
the form that was passed, and convert into the other form.  This is
mostly just because L{HostnameAddress} chose somewhat poorly to define
its attribute as bytes; hopefully we can find a compatible way to clean
this up in the future and just operate in terms of text internally.

@param host: A hostname to convert.

@return: a 3-tuple of C{(invalid, bytes, text)} where C{invalid} is a
    boolean indicating the validity of the hostname, C{bytes} is a
    binary representation of C{host}, and C{text} is a textual
    representation of C{host}.
FcharmapTNFCr  backslashreplace)	r  r  r@   UnicodeErrorr  r   r   encoder?   )r0  invalid	hostByteshostTexts       ri   r  $HostnameEndpoint._hostAsBytesAndText  s    & dE""I#$Y/ !-HX&&$OOG4	# *8 4I  1CDI ''0H	8++!   #$++I6$X.."G# $ #"G#s#   B C -C ?C CCc                D  ^ ^^^	^
 T R                   (       a,  [        R                  " [        ST R                   35      5      $ [        5       m
/ m	[        [        5       " U	U
4S jS5      5       nT R                  T R                  5      nUR                  U" 5       T R                  T R                  S9  T
R                  U 4S j5            S	U 4S jjnT
R                  U5      nUR                  [        5      nS
U 4S jjm    SUUU 4S jjnUR                  U5      $ )a  
Attempts a connection to each resolved address, and returns a
connection which is established first.

@param protocolFactory: The protocol factory whose protocol
    will be connected.
@type protocolFactory:
    L{IProtocolFactory<twisted.internet.interfaces.IProtocolFactory>}

@return: A L{Deferred} that fires with the connected protocol
    or fails a connection-related error.
zinvalid hostname: c                  `   > \ rS rSr\SS j5       r\SU 4S jj5       r\S	U U4S jj5       rSrg)
2HostnameEndpoint.connect.<locals>.EndpointReceiveri  c                    g r|  r   )resolutionInProgresss    ri   r  BHostnameEndpoint.connect.<locals>.EndpointReceiver.resolutionBegan  s    rl   c                (   > TR                  U 5        g r|  append)address	addressess    ri   ri  BHostnameEndpoint.connect.<locals>.EndpointReceiver.addressResolved  s      )rl   c                 (   > TR                  T 5        g r|  rw   r  resolveds   ri   r}  EHostnameEndpoint.connect.<locals>.EndpointReceiver.resolutionComplete  s    !!),rl   r   N)r  r   r   r   )r  r   r   r   r   r   )	rq   r   r   r   r]  r  ri  r}  r   r  s   ri   EndpointReceiverr    s=      * * - -rl   r  )r  c                t   > [         R                  " [        R                  " STR                   S35      5      $ )NzCouldn't find the hostname '')r   r  r   DNSLookupErrorr  )r~  re   s    ri   rL  *HostnameEndpoint.connect.<locals>.<lambda>  s,    EJJ$$'CDNNCSST%UVrl   c              3    >#    U  H  n[        U[        5      (       aC  [        TR                  UR                  UR
                  TR                  TR                  5      v   [        U[        5      (       d  Mr  [        TR                  UR                  UR
                  TR                  TR                  5      v   M     g 7fr|  )
r  r   rO   r   r0  r  r-  r.  r   rN   )r  eachAddressre   s     ri   resolvedAddressesToEndpoints>HostnameEndpoint.connect.<locals>.resolvedAddressesToEndpoints	  s       )k;77,#((#(())  k;77,#((#(())   )s   A1C 8AC c                   > U R                  [        R                  " [        TR                  TR
                  5      5      5        g r|  )r   r   r   r   r  r  )	cancelledre   s    ri   r   ,HostnameEndpoint.connect.<locals>._canceller"  s3     ..#DOOTZZ@rl   c           	       >^^^^^^^^	 U (       d#  [         R                  " STR                   35      e[        U 5      m/ m/ m[        R
                  " T
S9m	SmSmSUUUUU	4S jjm[        SUUUUUUU	4S jj5       mTR                  Tl        TR                  TR                  5            S	UUU4S jjnT	R                  U5      $ )
a  
Given a sequence of endpoints obtained via name resolution, start
connecting to a new one every C{self._attemptDelay} seconds until
one of the connections succeeds, all of them fail, or the attempt
is cancelled.

@param endpoints: a list of all the endpoints we might try to
    connect to, as determined by name resolution.
@type endpoints: L{list} of L{IStreamServerEndpoint}

@return: a Deferred that fires with the result of the
    C{endpoint.connect} method that completes the fastest, or fails
    with the first connection error it encountered if none of them
    succeed.
@rtype: L{Deferred} failing with L{error.ConnectingCancelledError}
    or firing with L{IProtocol}
z no results for hostname lookup: r   FTc                 p   > T(       d  T (       d  T(       a  g TR                  TR                  5       5        g r|  )r   pop)checkDoneCompletedcheckDoneEndpointsLeftfailurespendingwinners   ri   	checkDoneLHostnameEndpoint.connect.<locals>.startConnectionAttempts.<locals>.checkDoneN  s!    04Jx||~.rl   c                   >^ [        T	S 5      n U c
  SmT" 5         g U R                  T5      mT
R                  T5        SUU
4S jjnTR                  U5      nSU4S jjnUR	                  U5        UU4S jnUR                  U5        g )NFc                *   > TR                  T5        U $ r|  )remove)rK  eachAttemptr  s    ri   noLongerPendingkHostnameEndpoint.connect.<locals>.startConnectionAttempts.<locals>.iterateEndpoint.<locals>.noLongerPending`  s    NN;/!Mrl   c                (   > TR                  U 5        g r|  r  )rK  r  s    ri   	succeededeHostnameEndpoint.connect.<locals>.startConnectionAttempts.<locals>.iterateEndpoint.<locals>.succeededf  s    OOF+rl   c                6   > TR                  U 5        T" 5         g r|  r  )r   r  r  s    ri   failedbHostnameEndpoint.connect.<locals>.startConnectionAttempts.<locals>.iterateEndpoint.<locals>.failedk  s    OOF+Krl   rK  IProtocol | Failurer   r  )rK  r!   r   r   )nextr	  r  r  rP  r  )endpointr  successStater  r  r  r  r  r  iterEndpointsr  r  r  s        @ri   iterateEndpointRHostnameEndpoint.connect.<locals>.startConnectionAttempts.<locals>.iterateEndpointS  s      t4#-2*K&..?{+" "  +22?C, ((3  ''/rl   c                   > SmTS S   H  nUR                  5         M     TR                  (       a  TR                  5         U $ NT)cancelrunningstop)rK  	remainingr  r  r  s     ri   cancelRemainingPendingYHostnameEndpoint.connect.<locals>.startConnectionAttempts.<locals>.cancelRemainingPendingt  s?     &*"!(I$$& ","**#((*rl   r  r  )r   r  r  iterr   r0   r1   r   clockstartr  r  )	endpointsr  r  r  r  r  r  r  r  r  r   r  re   s     @@@@@@@@ri   startConnectionAttempts9HostnameEndpoint.connect.<locals>.startConnectionAttempts.  s    ( **6t~~6FG  !OM79G&(H050TF!&%)"/ /
 0 0 0: %)MMO!!!$"4"45	+	$	 	 >>"899rl   )r  zIterable[IAddress]r   z1Iterable[TCP6ClientEndpoint | TCP4ClientEndpoint])r  rA  r   r   )r  z-list[TCP6ClientEndpoint | TCP4ClientEndpoint]r   rA  )r  r   r  
ValueErrorr  r0   r   r%   r  r   r  r  r  rP  list)re   r  r  r  r  iterdlistdr   r   r  r  s   ``      @@@ri   r	  HostnameEndpoint.connect  s    ::j+=dnn=M)NOPP-5Z$&		(	)	- 	- 
*	- 88G$$4:: 	% 	
 		
	)	>	, $$%AB!!$'
	Q	:DQ	: Q	: Q	:f   !899rl   c                Z    U R                  U R                  XS[        R                  5      $ )aV  
Resolve the hostname string into a tuple containing the host
address.  This is method is only used when the reactor does
not provide L{IReactorPluggableNameResolver}.

@param host: A unicode hostname to resolve.

@param port: The port to include in the resolution.

@return: A L{Deferred} that fires with L{_getaddrinfo}'s
    return value.
r   )rT  rU  rV  SOCK_STREAM)re   r0  r  s      ri   r  (HostnameEndpoint._fallbackNameResolution  s'     ""4#4#4d!VEWEWXXrl   )r  r  r.  r  r  r  r   r-  )r<  NN)r   r   r0  zstr | bytesr  r>  r1  r?  r2  z,bytes | str | tuple[bytes | str, int] | Noner  zfloat | Noner   r   )r   r=  )r   objectr   r   )r0  bytes | strr   ztuple[bool, bytes, str]r@  )rq   r   r   r   r   r]  rV  r^  rU  r   r_  rT  r  rj   r  r  r  r	  r  r   r   rl   ri   rW   rW     s    .   2 23L!'"7"78N  DH%)H*H* H* 	H*
 H* BH* #H* 
H*T90$6 ', ',Rd:LYrl   rW   c                  (    \ rS rSrSrSS jrS rSrg)rR   i  z=
SSL secured TCP server endpoint with an IPv4 configuration.
c                @    Xl         X l        X0l        X@l        XPl        g)aU  
@param reactor: An L{IReactorSSL} provider.

@param port: The port number used for listening
@type port: int

@param sslContextFactory: An instance of
    L{interfaces.IOpenSSLContextFactory}.

@param backlog: Size of the listen queue
@type backlog: int

@param interface: The hostname to bind to, defaults to '' (all)
@type interface: str
N)r   r  _sslContextFactoryr  r  )re   r   r  sslContextFactoryr  r  s         ri   rj   SSL4ServerEndpoint.__init__  s       
"3#rl   c           	         [         R                  " U R                  R                  U R                  UU R
                  U R                  U R                  S9$ )zN
Implement L{IStreamServerEndpoint.listen} to listen for SSL on a
TCP socket.
)contextFactoryr  r  )r   r   r   	listenSSLr  r  r  r  r  s     ri   r   SSL4ServerEndpoint.listen  sC    
 }}MM##JJ22MMoo
 	
rl   )r  r  r  r   r  Nr   r  r   rl   ri   rR   rR     s    $,
rl   rR   c                  *    \ rS rSrSr SS jrS rSrg)rS   i  z<
SSL secured TCP client endpoint with an IPv4 configuration
Nc                L    Xl         X l        X0l        X@l        XPl        X`l        g)a  
@param reactor: An L{IReactorSSL} provider.

@param host: A hostname, used when connecting
@type host: str

@param port: The port number, used when connecting
@type port: int

@param sslContextFactory: SSL Configuration information as an instance
    of L{interfaces.IOpenSSLContextFactory}.

@param timeout: Number of seconds to wait before assuming the
    connection has failed.
@type timeout: int

@param bindAddress: A (host, port) tuple of local address to bind to,
    or None.
@type bindAddress: tuple
N)r   r,  r  r  r-  r.  )re   r   r0  r  r  r1  r2  s          ri   rj   SSL4ClientEndpoint.__init__  s$    .  

"3'rl   c           	         [        U5      nU R                  R                  U R                  U R                  UU R
                  U R                  U R                  S9  UR                  $ ! [         a    [        R                  " 5       s $ f = f)zJ
Implement L{IStreamClientEndpoint.connect} to connect with SSL over
TCP.
r5  )r   r   
connectSSLr,  r  r  r-  r.  r   r   r   r  r7  s      ri   r	  SSL4ClientEndpoint.connect  s{    
	 !/2BMM$$



'' -- %  ### 	 ::<	 s   A&A) )B
B)r.  r,  r  r   r  r-  r;  rB  r   rl   ri   rS   rS     s    
 OS(< rl   rS   c                  (    \ rS rSrSrSS jrS rSrg)rP   i  z
UnixSocket server endpoint.
c                @    Xl         X l        X0l        X@l        XPl        g)a  
@param reactor: An L{IReactorUNIX} provider.
@param address: The path to the Unix socket file, used when listening
@param backlog: number of connections to allow in backlog.
@param mode: mode to set on the unix socket.  This parameter is
    deprecated.  Permissions should be set on the directory which
    contains the UNIX socket.
@param wantPID: If True, create a pidfile for the socket.
N)r   _addressr  _mode_wantPID)re   r   r  r  modewantPIDs         ri   rj   UNIXServerEndpoint.__init__  s      
rl   c           	         [         R                  " U R                  R                  U R                  UU R
                  U R                  U R                  S9$ )zG
Implement L{IStreamServerEndpoint.listen} to listen on a UNIX socket.
)r  r   r!  )r   r   r   
listenUNIXr  r  r  r  r  s     ri   r   UNIXServerEndpoint.listen  sA     }}MM$$MMMMMM
 	
rl   )r  r  r  r   r  N)r!  i  r   r  r   rl   ri   rP   rP     s      
rl   rP   c                  (    \ rS rSrSrSS jrS rSrg)rQ   i  z
UnixSocket client endpoint.
c                4    Xl         X l        X0l        X@l        g)a_  
@param reactor: An L{IReactorUNIX} provider.

@param path: The path to the Unix socket file, used when connecting
@type path: str

@param timeout: Number of seconds to wait before assuming the
    connection has failed.
@type timeout: int

@param checkPID: If True, check for a pid file to verify that a server
    is listening.
@type checkPID: bool
N)r   r   r-  	_checkPID)re   r   r   r1  checkPIDs        ri   rj   UNIXClientEndpoint.__init__   s      
!rl   c                     [        U5      nU R                  R                  U R                  X R                  U R
                  S9  UR                  $ ! [         a    [        R                  " 5       s $ f = f)zI
Implement L{IStreamClientEndpoint.connect} to connect via a
UNIX Socket
)r1  r)  )
r   r   connectUNIXr   r-  r(  r   r   r   r  r7  s      ri   r	  UNIXClientEndpoint.connect4  sd    
	 !/2BMM%%

B &  ### 	 ::<	 s   AA A43A4)r(  r   r   r-  N)r<  r   rB  r   rl   ri   rQ   rQ     s    "( rl   rQ   c                  `    \ rS rSrSr\R                  r\" \	R                  5      rS rS rSrg)rT   iC  z
An endpoint for listening on a file descriptor initialized outside of
Twisted.

@ivar _used: A C{bool} indicating whether this endpoint has been used to
    listen with a factory yet.  C{True} if so.
c                6    Xl         X l        X0l        SU l        g)z
@param reactor: An L{IReactorSocket} provider.

@param fileno: An integer file descriptor corresponding to a listening
    I{SOCK_STREAM} socket.

@param addressFamily: The address family of the socket given by
    C{fileno}.
FN)r   filenoaddressFamily_used)re   r   r0  r1  s       ri   rj   $AdoptedStreamServerEndpoint.__init__P  s     *
rl   c                   U R                   (       a)  [        R                  " [        R                  " 5       5      $ SU l          U R                  U R                  5        U R                  R                  U R                  U R                  U5      nU R                  U R                  5        [        R                  " U5      $ ! [         a    [        R                  " 5       s $ f = f)zc
Implement L{IStreamServerEndpoint.listen} to start listening on, and
then close, C{self._fileno}.
T)r2  r   r  r   AlreadyListened_setNonBlockingr0  r   adoptStreamPortr1  _closer   r  )re   factoryr  s      ri   r   "AdoptedStreamServerEndpoint.listen_  s    
 ::::e33566
	   -<<//T//D KK$ }}T""  	 ::<	 s   A'C   C"!C")r2  r1  r0  r   N)rq   r   r   r   r   oscloser8  r]  r   setNonBlockingr6  rj   r   r   r   rl   ri   rT   rT   C  s,     XXF"5#7#78O#rl   rT   c                8    [        U5      U 4U[        U5      S.4$ )a  
Internal parser function for L{_parseServer} to convert the string
arguments for a TCP(IPv4) stream endpoint into the structured arguments.

@param factory: the protocol factory being parsed, or L{None}.  (This was a
    leftover argument from when this code was in C{strports}, and is now
    mostly None and unused.)

@type factory: L{IProtocolFactory} or L{None}

@param port: the integer port number to bind
@type port: C{str}

@param interface: the interface IP to listen on
@param backlog: the length of the listen queue
@type backlog: C{str}

@return: a 2-tuple of (args, kwargs), describing  the parameters to
    L{IReactorTCP.listenTCP} (or, modulo argument 2, the factory, arguments
    to L{TCP4ServerEndpoint}.
r  r  )r>  )r9  r  r  r  s       ri   	_parseTCPr@  s  s!    , IwyS\!RRRrl   c                ^    X4[        US5      [        U5      [        [        U5      5      S.4$ )a[  
Internal parser function for L{_parseServer} to convert the string
arguments for a UNIX (AF_UNIX/SOCK_STREAM) stream endpoint into the
structured arguments.

@param factory: the protocol factory being parsed, or L{None}.  (This was a
    leftover argument from when this code was in C{strports}, and is now
    mostly None and unused.)

@type factory: L{IProtocolFactory} or L{None}

@param address: the pathname of the unix socket
@type address: C{str}

@param backlog: the length of the listen queue
@type backlog: C{str}

@param lockfile: A string '0' or '1', mapping to True and False
    respectively.  See the C{wantPID} argument to C{listenUNIX}

@return: a 2-tuple of (args, kwargs), describing  the parameters to
    L{twisted.internet.interfaces.IReactorUNIX.listenUNIX} (or,
    modulo argument 2, the factory, arguments to L{UNIXServerEndpoint}.
   )r   r  r!  )r>  bool)r9  r  r   r  lockfiles        ri   
_parseUNIXrE    s1    4 
T1#g,4HCVW rl   c	                   SSK Jn	  Uc  Un0 n
Ub  [        U	R                  U5      U
S'   [	        U5      R                  5       n[	        U5      R                  5       nU	R                  R                  US-   U-   5      nUb  [        R                  " S[        [	        U5      R                  5       5      [        R                  S9nU Vs/ s H'  oR                  R                  U5      R                  PM)     nnU(       d  [        SU< S	35      eOSnUb$  U	R                  R!                  [	        U5      5      nU	R"                  " SUR$                  R                  UR                  UUS
.U
D6n['        U5      U U4U['        U5      S.4$ s  snf )a  
Internal parser function for L{_parseServer} to convert the string
arguments for an SSL (over TCP/IPv4) stream endpoint into the structured
arguments.

@param factory: the protocol factory being parsed, or L{None}.  (This was a
    leftover argument from when this code was in C{strports}, and is now
    mostly None and unused.)
@type factory: L{IProtocolFactory} or L{None}

@param port: the integer port number to bind
@type port: C{str}

@param interface: the interface IP to listen on
@param backlog: the length of the listen queue
@type backlog: C{str}

@param privateKey: The file name of a PEM format private key file.
@type privateKey: C{str}

@param certKey: The file name of a PEM format certificate file.
@type certKey: C{str}

@param sslmethod: The string name of an SSL method, based on the name of a
    constant in C{OpenSSL.SSL}.
@type sslmethod: C{str}

@param extraCertChain: The path of a file containing one or more
    certificates in PEM format that establish the chain from a root CA to
    the CA that signed your C{certKey}.
@type extraCertChain: L{str}

@param dhParameters: The file name of a file containing parameters that are
    required for Diffie-Hellman key exchange.  If this is not specified,
    the forward secret C{DHE} ciphers aren't available for servers.
@type dhParameters: L{str}

@return: a 2-tuple of (args, kwargs), describing  the parameters to
    L{IReactorSSL.listenSSL} (or, modulo argument 2, the factory, arguments
    to L{SSL4ServerEndpoint}.
r   )sslNmethod   
z=(-----BEGIN CERTIFICATE-----\n.+?\n-----END CERTIFICATE-----))flagszSpecified chain file 'z7' doesn't contain any valid certificates in PEM format.)
privateKeycertificateextraCertChaindhParametersr?  r   )twisted.internetrG  getattrSSLr<   
getContentrE   loadPEMrefindallr9   DOTALLrB   originalr  DiffieHellmanParametersfromFilerC   rK  r>  )r9  r  rK  certKey	sslmethodr  r  rM  rN  rG  kwcertPEMkeyPEMprivateCertificatematcheschainCertPEMchainCertificatescfs                     ri   	_parseSSLrd    s   h %	Bsww	28w**,Gj!,,.F//77%&8PQ!**L.1<<>?))
 PW
OV|OO##L1::w 	 
 !1?B  ! !22;;\"
 
		 
%0099&//(!	

 
B Y$I#g,&WXX-
s   .F
c                  (    \ rS rSrSrSrS rS rSrg)_StandardIOParseri  z
Stream server endpoint string parser for the Standard I/O type.

@ivar prefix: See L{IStreamServerEndpointStringParser.prefix}.
stdioc                    [        U5      $ )z
Internal parser function for L{_parseServer} to convert the string
arguments into structured arguments for the L{StandardIOEndpoint}

@param reactor: Reactor for the endpoint
)rU   r   s     ri   _parseServer_StandardIOParser._parseServer  s     "'**rl   c                $    U R                  U5      $ r|  ri  re   r   r   kwargss       ri   parseStreamServer#_StandardIOParser.parseStreamServer  s       ))rl   r   N	rq   r   r   r   r   prefixri  ro  r   r   rl   ri   rf  rf    s     F+*rl   rf  c                  h    \ rS rSrSr\R                  " 5       rSr  S         S	S jjr	S r
Srg)
_SystemdParseri!  z
Stream server endpoint string parser for the I{systemd} endpoint type.

@ivar prefix: See L{IStreamServerEndpointStringParser.prefix}.

@ivar _sddaemon: A L{ListenFDs} instance used to translate an index into an
    actual file descriptor.
systemdNc                   USL USL :X  a  [        S5      eUb'  U R                  R                  5       [        U5         nO"Uc   eU R                  R	                  5       U   n[        [        SU-   5      n[        XU5      $ )a  
Internal parser function for L{_parseServer} to convert the string
arguments for a systemd server endpoint into structured arguments for
L{AdoptedStreamServerEndpoint}.

@param reactor: An L{IReactorSocket} provider.

@param domain: The domain (or address family) of the socket inherited
    from systemd.  This is a string like C{"INET"} or C{"UNIX"}, ie
    the name of an address family from the L{socket} module, without
    the C{"AF_"} prefix.

@param index: If given, the decimal representation of an integer
    giving the offset into the list of file descriptors inherited from
    systemd.  Since the order of descriptors received from systemd is
    hard to predict, this option should only be used if only one
    descriptor is being inherited.  Even in that case, C{name} is
    probably a better idea.  Either C{index} or C{name} must be given.

@param name: If given, the name (as defined by C{FileDescriptorName}
    in the C{[Socket]} section of a systemd service definition) of an
    inherited file descriptor.  Either C{index} or C{name} must be
    given.

@return: An L{AdoptedStreamServerEndpoint} which will adopt the
    inherited listening port when it is used to listen.
Nz/Specify exactly one of descriptor index or nameAF_)r  	_sddaemoninheritedDescriptorsr>  inheritedNamedDescriptorsrP  rV  rT   )re   r   domainindexrt  r0  r1  s          ri   ri  _SystemdParser._parseServer0  s    D TMtt|,NOO^^88:3u:FF###^^==?EF7*7MJJrl   c                .    U R                   " U/UQ70 UD6$ r|  rl  rm  s       ri   ro   _SystemdParser.parseStreamServer^  s       :4:6::rl   r   )NN)
r   r$   r{  r=  r|  Optional[str]rt  r  r   rT   )rq   r   r   r   r   r=   fromEnvironmentrx  rr  ri  ro  r   r   rl   ri   rt  rt  !  se     ))+IF  $",K,K ,K 	,K
 ,K 
%,K\;rl   rt  c                  ,    \ rS rSrSrSrSS jrS rSrg)	_TCP6ServerParserie  z
Stream server endpoint string parser for the TCP6ServerEndpoint type.

@ivar prefix: See L{IStreamServerEndpointStringParser.prefix}.
tcp6c                F    [        U5      n[        U5      n[        XX45      $ )aq  
Internal parser function for L{_parseServer} to convert the string
arguments into structured arguments for the L{TCP6ServerEndpoint}

@param reactor: An L{IReactorTCP} provider.

@param port: The port number used for listening
@type port: int

@param backlog: Size of the listen queue
@type backlog: int

@param interface: The hostname to bind to
@type interface: str
)r>  rM   r  s        ri   ri  _TCP6ServerParser._parseServerq  s#      4yg,!'DDrl   c                .    U R                   " U/UQ70 UD6$ r|  rl  rm  s       ri   ro  #_TCP6ServerParser.parseStreamServer  s       :4:6::rl   r   Nr(  rq  r   rl   ri   r  r  e  s     	 E(;rl   r  )tcpunixrG  r   c              #  \  #    [        SU 5      n[        SU 5      n[        SU 5      n[        SU 5      nUnX#-   nX"U-   X20n[        [        U 5      5      nU HG  n	U	[        U5      ;   a  [        U4v   [        U	4v   UnXy   nM.  X:X  a  U[        U5      -  nMC  XY-  nMI     [        U4v   g7f)aj  
Tokenize a strports string and yield each token.

@param description: a string as described by L{serverFromString} or
    L{clientFromString}.
@type description: L{str} or L{bytes}

@return: an iterable of 2-tuples of (C{_OP} or C{_STRING}, string).  Tuples
    starting with C{_OP} will contain a second element of either ':' (i.e.
    'next parameter') or '=' (i.e. 'assign parameter value').  For example,
    the string 'hello:greeting=world' would result in a generator yielding
    these values::

        _STRING, 'hello'
        _OP, ':'
        _STRING, 'greet=ing'
        _OP, '='
        _STRING, 'world'
r"  r  =\N)r7   r  r8   _STRING_OPr  )
descriptionemptycolonequals	backslashcurrentopsnextOpsiterdescns
             ri   	_tokenizer    s     ( B,EC-ES+.F4IG
.Cfnf4GIk*+H	#7""q&LG*C^tH~%GLG  7
s   B*B,c                   ^^ / 0 smm[        SU 5      nUU4S jnSn[        U 5       H&  u  pEU[        L a  X54-  nM  XQ:X  d  M  U" U5        SnM(     U" U5        TT4$ )a  
Convert a description string into a list of positional and keyword
parameters, using logic vaguely like what Python does.

@param description: a string as described by L{serverFromString} or
    L{clientFromString}.

@return: a 2-tuple of C{(args, kwargs)}, where 'args' is a list of all
    ':'-separated C{str}s not containing an '=' and 'kwargs' is a map of
    all C{str}s which do contain an '='.  For example, the result of
    C{_parse('a:b:d=1:c')} would be C{(['a', 'b', 'c'], {'d': '1'})}.
r  c                v   > [        U 5      S:X  a  TR                  U S   5        g U S   T[        U S   5      '   g )Nr>   r   )lenr  r9   )sofarr   r\  s    ri   add_parse.<locals>.add  s5    u:?KKa!).qB|E!H%&rl   r   )r7   r  r  )r  r  r  r  typer   r   r\  s         @@ri   _parser    sm     2HD"C-E2 E -7?XE^JE . J8Orl   )rh  rQ  UNIXc                    [        U 5      u  p#US   n[        R                  U5      nUc   [        [	        [
        5      U5      nXbSS U4$ UR                  5       4U" U/USS Q70 UD6-   $ )a  
Parse a strports description into a 2-tuple of arguments and keyword
values.

@param description: A description in the format explained by
    L{serverFromString}.
@type description: C{str}

@param factory: A 'factory' argument; this is left-over from
    twisted.application.strports, it's not really used.
@type factory: L{IProtocolFactory} or L{None}

@return: a 3-tuple of (plugin or name, arguments, keyword arguments)
r   Nr>   )r  _serverParsersget_matchPluginToPrefixr4   r(   upper)r  r9  r   r\  endpointTypeparserplugins          ri   ri  ri    s     k"HD7L-F~ &89<
 QR"%% "VG%Ed12h%E"%EEErl   c                    UR                  5       nU  H/  n[        UR                  R                  5       U5      U:X  d  M-  Us  $    [        SU S35      e)z
Match plugin to prefix.
zUnknown endpoint type: 'r  )lowerr7   rr  r  )pluginsr  r  s      ri   r  r  	  sT      %%'L6==..0,?<OM  /~Q?
@@rl   c                    [        US5      u  p#n[        U5      [        La  UnUR                  " U /UQ70 UD6$ UnUSS USS -   n[        U   " U /UQ70 UD6$ )a  
Construct a stream server endpoint from an endpoint description string.

The format for server endpoint descriptions is a simple byte string.  It is
a prefix naming the type of endpoint, then a colon, then the arguments for
that endpoint.

For example, you can call it like this to create an endpoint that will
listen on TCP port 80::

    serverFromString(reactor, "tcp:80")

Additional arguments may be specified as keywords, separated with colons.
For example, you can specify the interface for a TCP server endpoint to
bind to like this::

    serverFromString(reactor, "tcp:80:interface=127.0.0.1")

SSL server endpoints may be specified with the 'ssl' prefix, and the
private key and certificate files may be specified by the C{privateKey} and
C{certKey} arguments::

    serverFromString(
        reactor, "ssl:443:privateKey=key.pem:certKey=crt.pem")

If a private key file name (C{privateKey}) isn't provided, a "server.pem"
file is assumed to exist which contains the private key. If the certificate
file name (C{certKey}) isn't provided, the private key file is assumed to
contain the certificate as well.

You may escape colons in arguments with a backslash, which you will need to
use if you want to specify a full pathname argument on Windows::

    serverFromString(reactor,
        "ssl:443:privateKey=C\:/key.pem:certKey=C\:/cert.pem")

finally, the 'unix' prefix may be used to specify a filesystem UNIX socket,
optionally with a 'mode' argument to specify the mode of the socket file
created by C{listen}::

    serverFromString(reactor, "unix:/var/run/finger")
    serverFromString(reactor, "unix:/var/run/finger:mode=660")

This function is also extensible; new endpoint types may be registered as
L{IStreamServerEndpointStringParser} plugins.  See that interface for more
information.

@param reactor: The server endpoint will be constructed with this reactor.

@param description: The strports description to parse.
@type description: L{str}

@return: A new endpoint which can be used to listen with the parameters
    given by C{description}.

@rtype: L{IStreamServerEndpoint<twisted.internet.interfaces.IStreamServerEndpoint>}

@raise ValueError: when the 'description' string cannot be parsed.

@since: 10.2
Nr>   r   )ri  r  r=  ro  _endpointServerFactories)r   r  nameOrPluginr   r\  r  rt  s          ri   rK   rK     sx    | *+t<LL$''=$="==8d12hD#D)'?D?B??rl   c                J    Su  pX4 H  nU R                  X1U-   5      n M     U $ )a@  
Quote an argument to L{serverFromString} and L{clientFromString}.  Since
arguments are separated with colons and colons are escaped with
backslashes, some care is necessary if, for example, you have a pathname,
you may be tempted to interpolate into a string like this::

    serverFromString(reactor, "ssl:443:privateKey=%s" % (myPathName,))

This may appear to work, but will have portability issues (Windows
pathnames, for example).  Usually you should just construct the appropriate
endpoint type rather than interpolating strings, which in this case would
be L{SSL4ServerEndpoint}.  There are some use-cases where you may need to
generate such a string, though; for example, a tool to manipulate a
configuration file which has strports descriptions in it.  To be correct in
those cases, do this instead::

    serverFromString(reactor, "ssl:443:privateKey=%s" %
                     (quoteStringArgument(myPathName),))

@param argument: The part of the endpoint description string you want to
    pass through.

@type argument: C{str}

@return: The quoted argument.

@rtype: C{str}
z\:)replace)argumentr  r  cs       ri   quoteStringArgumentr  ]  s2    : I##A1}5 Orl   c                 v   [        U 5      S:X  a  [        U S   5      US'   U S   US'   O/[        U 5      S:X  a   SU;   a  [        U S   5      US'   OU S   US'    [        US   5      US'    [        US   5      US'    US   S4US'   U$ ! [         a     N+f = f! [         a     N)f = f! [         a     U$ f = f)a  
Perform any argument value coercion necessary for TCP client parameters.

Valid positional arguments to this function are host and port.

Valid keyword arguments to this function are all L{IReactorTCP.connectTCP}
arguments.

@return: The coerced values as a C{dict}.
r   r>   r  r   r0  r1  r2  )r  r>  KeyErrorr   rn  s     ri   _parseClientTCPr    s     4yA~T!Wvav	TaV a\F6N!!WF6NVF^,vy 12y!'!6 :} M  
  
  Ms6   B
 ,B >
B* 

BB
B'&B'*
B87B8c                   0 nU R                  5        H  nUR                  5       R                  5       R                  S5      S   R	                  5       S:X  d  MG   UR                  5       n [        R                  " U5      nXAUR                  5       '   M     [        UR                  5       5      $ ! [         a     M  f = f! [         a     M  f = f)z
Load certificate-authority certificate objects in a given directory.

@param directoryPath: a L{unicode} or L{bytes} pointing at a directory to
    load .pem files from, or L{None}.

@return: an L{IOpenSSLTrustRoot} provider.
.pem)children
asTextModebasenamesplitr  rR  OSErrorrB   rS  digestSSLErrorrG   values)directoryPathcaCertschildr|   theCerts        ri   _loadCAsFromDirr    s     G'')!**,2237;AACuL	##%D	0!))$/G
 )0GNN$% * %W^^%566  		
  		s$   B1,C1
B?>B?
CCc                2    U c  g[        [        U 5      5      $ )z
Parse a string referring to a directory full of certificate authorities
into a trust root.

@param pathName: path name
@type pathName: L{unicode} or L{bytes} or L{None}

@return: L{None} or L{IOpenSSLTrustRoot}
N)r  r<   )pathNames    ri   _parseTrustRootPathr    s     8H-..rl   c                   U c  g[        U 5      R                  5       nUc  [        R                  " U5      $ [        R                  " [
        R                  " U5      [        R                  " [        U5      R                  5       S5      5      $ )aX  
Parse a certificate path and key path, either or both of which might be
L{None}, into a certificate object.

@param certificatePath: the certificate path
@type certificatePath: L{bytes} or L{unicode} or L{None}

@param keyPath: the private key path
@type keyPath: L{bytes} or L{unicode} or L{None}

@return: a L{PrivateCertificate} or L{None}
Nr>   )r<   rR  rE   rS  fromCertificateAndKeyPairrB   rD   load)certificatePathkeyPath	certBytess      ri   _privateCertFromPathsr    ss     )446I!)))44!;;	*LL'*557;
 	
rl   c                Z   U R                  SS5      n[        U R                  SS5      U R                  SS5      5      n[        U R                  SS5      5      nUb  [        [	        U5      UUS9nO5Ub#  UR
                  R                  nUR                  nOSnSn[        UUUS9nX@S'   U $ )	al  
Parse common arguments for SSL endpoints, creating an L{CertificateOptions}
instance.

@param kwargs: A dict of keyword arguments to be parsed, potentially
    containing keys C{certKey}, C{privateKey}, C{caCertsDir}, and
    C{hostname}.  See L{_parseClientSSL}.
@type kwargs: L{dict}

@return: The remaining arguments, including a new key C{sslContextFactory}.
hostnameNrZ  rK  
caCertsDir	trustRootclientCertificate)r  rK  rL  r  )r  r  r  rF   r@   rK  rW  rC   )rn  r  r  r  configurationprivateKeyOpenSSLcertificateOpenSSLs          ri   _parseClientSSLOptionsr    s     zz*d+H-

9d#VZZd%C $FJJ|T$BCI+h/
 ( 1 < < E E!2!;!; $!%*(*

 #0Mrl   c                 .    [        U 0 UD6n[        U5      $ )a  
Perform any argument value coercion necessary for SSL client parameters.

Valid keyword arguments to this function are all L{IReactorSSL.connectSSL}
arguments except for C{contextFactory}.  Instead, C{certKey} (the path name
of the certificate file) C{privateKey} (the path name of the private key
associated with the certificate) are accepted and used to construct a
context factory.

Valid positional arguments to this function are host and port.

@keyword caCertsDir: The one parameter which is not part of
    L{IReactorSSL.connectSSL}'s signature, this is a path name used to
    construct a list of certificate authority certificates.  The directory
    will be scanned for files ending in C{.pem}, all of which will be
    considered valid certificate authorities for this connection.
@type caCertsDir: L{str}

@keyword hostname: The hostname to use for validating the server's
    certificate.
@type hostname: L{unicode}

@return: The coerced values as a L{dict}.
)r  r  r  s     ri   _parseClientSSLr    s    2 d-f-F!&))rl   c                     [        U 5      S:X  a  U S   US'    [        [        UR                  S5      5      5      US'    [        US   5      US'   U$ ! [         a     N f = f! [         a     U$ f = f)a  
Perform any argument value coercion necessary for UNIX client parameters.

Valid keyword arguments to this function are all L{IReactorUNIX.connectUNIX}
keyword arguments except for C{checkPID}.  Instead, C{lockfile} is accepted
and has the same meaning.  Also C{path} is used instead of C{address}.

Valid positional arguments to this function are C{path}.

@return: The coerced values as a C{dict}.
r>   r   r   rD  r)  r1  )r  rC  r>  r  r  r  s     ri   _parseClientUNIXr  0  s     4yA~av!#fjj&<"=>zy 12y M    Ms#   &A  A# 
A A #
A10A1c                   [        U5      u  p#UR                  S5      nUR                  5       nU[        ;  a/  [	        [        [        5      U5      nUR                  " U /UQ70 UD6$ [        U   " U0 UD6n[        U   " U 40 UD6$ )a3
  
Construct a client endpoint from a description string.

Client description strings are much like server description strings,
although they take all of their arguments as keywords, aside from host and
port.

You can create a TCP client endpoint with the 'host' and 'port' arguments,
like so::

    clientFromString(reactor, "tcp:host=www.example.com:port=80")

or, without specifying host and port keywords::

    clientFromString(reactor, "tcp:www.example.com:80")

Or you can specify only one or the other, as in the following 2 examples::

    clientFromString(reactor, "tcp:host=www.example.com:80")
    clientFromString(reactor, "tcp:www.example.com:port=80")

or an SSL client endpoint with those arguments, plus the arguments used by
the server SSL, for a client certificate::

    clientFromString(reactor, "ssl:web.example.com:443:"
                              "privateKey=foo.pem:certKey=foo.pem")

to specify your certificate trust roots, you can identify a directory with
PEM files in it with the C{caCertsDir} argument::

    clientFromString(reactor, "ssl:host=web.example.com:port=443:"
                              "caCertsDir=/etc/ssl/certs")

Both TCP and SSL client endpoint description strings can include a
'bindAddress' keyword argument, whose value should be a local IPv4
address. This fixes the client socket to that IP address::

    clientFromString(reactor, "tcp:www.example.com:80:"
                              "bindAddress=192.0.2.100")

NB: Fixed client ports are not currently supported in TCP or SSL
client endpoints. The client socket will always use an ephemeral
port assigned by the operating system

You can create a UNIX client endpoint with the 'path' argument and optional
'lockfile' and 'timeout' arguments::

    clientFromString(
        reactor, b"unix:path=/var/foo/bar:lockfile=1:timeout=9")

or, with the path as a positional argument with or without optional
arguments as in the following 2 examples::

    clientFromString(reactor, "unix:/var/foo/bar")
    clientFromString(reactor, "unix:/var/foo/bar:lockfile=1:timeout=9")

This function is also extensible; new endpoint types may be registered as
L{IStreamClientEndpointStringParserWithReactor} plugins.  See that
interface for more information.

@param reactor: The client endpoint will be constructed with this reactor.

@param description: The strports description to parse.
@type description: L{str}

@return: A new endpoint which can be used to connect with the parameters
    given by C{description}.
@rtype: L{IStreamClientEndpoint<twisted.internet.interfaces.IStreamClientEndpoint>}

@since: 10.2
r   )	r  r  r  _clientParsersr  r4   r'   parseStreamClient_endpointClientFactories)r   r  r   rn  anamert  r  s          ri   rJ   rJ   Q  s    P +&LDHHQKE;;=D>!%CDd
 ''A$A&AAD!4262F#D)'<V<<rl   c                T   ^  " U4S jS[         5      nU R                  U" 5       5      $ )a  
Connect a protocol instance to an endpoint.

This allows using a client endpoint without having to create a factory.

@param endpoint: A client endpoint to connect to.

@param protocol: A protocol instance.

@return: The result of calling C{connect} on the endpoint, i.e. a
    L{Deferred} that will fire with the protocol when connected, or an
    appropriate error.

@since: 13.1
c                  "   > \ rS rSrU 4S jrSrg)'connectProtocol.<locals>.OneShotFactoryi  c                   > T$ r|  r   )re   r   r   s     ri   r   5connectProtocol.<locals>.OneShotFactory.buildProtocol  s    Orl   r   N)rq   r   r   r   r   r   r   s   ri   OneShotFactoryr    s    	 	rl   r  )r*   r	  )r  r   r  s    ` ri   rY   rY     s%    "  N,--rl   c                  $    \ rS rSrSrS rS rSrg)_WrapperEndpointi  z*
An endpoint that wraps another endpoint.
c                    Xl         X l        g)z"
Construct a L{_WrapperEndpoint}.
N_wrappedEndpoint_wrapperFactoryre   wrappedEndpointwrapperFactorys      ri   rj   _WrapperEndpoint.__init__       !0-rl   c                v    U R                   R                  U R                  U5      5      R                  S 5      $ );
Connect the given protocol factory and unwrap its result.
c                    U R                   $ r|  )rg   r  s    ri   rL  *_WrapperEndpoint.connect.<locals>.<lambda>  s
    x'?'?rl   )r  r	  r  rP  r  s     ri   r	  _WrapperEndpoint.connect  s7     $$,,  1

+?
@	Arl   r  NrB  r   rl   ri   r  r    s    .Arl   r  c                  $    \ rS rSrSrS rS rSrg)_WrapperServerEndpointi  z7
A server endpoint that wraps another server endpoint.
c                    Xl         X l        g)z(
Construct a L{_WrapperServerEndpoint}.
Nr  r  s      ri   rj   _WrapperServerEndpoint.__init__  r  rl   c                V    U R                   R                  U R                  U5      5      $ )r  )r  r   r  r  s     ri   r   _WrapperServerEndpoint.listen  s&     $$++D,@,@,QRRrl   r  Nr  r   rl   ri   r  r    s    .Srl   r  c                H   ^  [         c  [        S5      e[        UU 4S j5      $ )a_  
Wrap an endpoint which upgrades to TLS as soon as the connection is
established.

@since: 16.0

@param connectionCreator: The TLS options to use when connecting; see
    L{twisted.internet.ssl.optionsForClientTLS} for how to construct this.
@type connectionCreator:
    L{twisted.internet.interfaces.IOpenSSLClientConnectionCreator}

@param wrappedEndpoint: The endpoint to wrap.
@type wrappedEndpoint: An L{IStreamClientEndpoint} provider.

@return: an endpoint that provides transport level encryption layered on
    top of C{wrappedEndpoint}
@rtype: L{twisted.internet.interfaces.IStreamClientEndpoint}
z6OpenSSL not available. Try `pip install twisted[tls]`.c                   > [        TSU 5      $ r  rH   )r  connectionCreators    ri   rL  wrapClientTLS.<locals>.<lambda>	  s     3t_!
rl   )rI   NotImplementedErrorr  )r  r  s   ` ri   rZ   rZ     s2    , "!D
 	
 	
 rl   c	                   U	(       a#  [        S[        U	R                  5       5      5      e[        U[        5      (       a  UOUR                  S5      n[        U[        5      (       d  Uc  UOUR                  S5      n[        U5      n
[        U5      n[        [        U[        U5      [        XV5      S9Ub  [        X5      5      $ [        U [        U5      U
UUc  SOUS45      5      $ )aN  
Internal method to construct an endpoint from string parameters.

@param reactor: The reactor passed to L{clientFromString}.

@param host: The hostname to connect to.
@type host: L{bytes} or L{unicode}

@param port: The port to connect to.
@type port: L{bytes} or L{unicode}

@param timeout: For each individual connection attempt, the number of
    seconds to wait before assuming the connection has failed.
@type timeout: L{bytes} or L{unicode}

@param bindAddress: The address to which to bind outgoing connections.
@type bindAddress: L{bytes} or L{unicode}

@param certificate: a string representing a filesystem path to a
    PEM-encoded certificate.
@type certificate: L{bytes} or L{unicode}

@param privateKey: a string representing a filesystem path to a PEM-encoded
    certificate.
@type privateKey: L{bytes} or L{unicode}

@param endpoint: an optional string endpoint description of an endpoint to
    wrap; if this is passed then C{host} is used only for certificate
    verification.
@type endpoint: L{bytes} or L{unicode}

@return: a client TLS endpoint
@rtype: L{IStreamClientEndpoint}
z&unrecognized keyword arguments presentzutf-8Nr  r   )	TypeErrorr  keysr  r=  r  r>  rZ   rF   r  r  rJ   rW   r?   )r   r0  r  r1  r2  rL  rK  
trustRootsr  rn  portint
timeoutints               ri   _parseClientTLSr  		  s    \ @$v{{}BUVVdC((4dkk'.BD k3'';+> 	( 
 $iGWJ)*53KL	
 # W/  "4 #++q1A rl   c                  ,    \ rS rSrSrSr\S 5       rSrg)_TLSClientEndpointParseriU	  z
Stream client endpoint string parser for L{wrapClientTLS} with
L{HostnameEndpoint}.

@ivar prefix: See
    L{IStreamClientEndpointStringParserWithReactor.prefix}.
tlsc                     [        U /UQ70 UD6$ )aB  
Redirects to another function L{_parseClientTLS}; tricks zope.interface
into believing the interface is correctly implemented, since the
signature is (C{reactor}, C{*args}, C{**kwargs}).  See
L{_parseClientTLS} for the specific signature description for this
endpoint parser.

@param reactor: The reactor passed to L{clientFromString}.

@param args: The positional arguments in the endpoint description.
@type args: L{tuple}

@param kwargs: The named arguments in the endpoint description.
@type kwargs: L{dict}

@return: a client TLS endpoint
@rtype: L{IStreamClientEndpoint}
)r  )r   r   rn  s      ri   r  *_TLSClientEndpointParser.parseStreamClienta	  s    ( w8888rl   r   N)	rq   r   r   r   r   rr  r]  r  r   r   rl   ri   r  r  U	  s      F9 9rl   r  )r"  r!  )666r!  T)z
server.pemNNr"  r!  NN)r  r    r  r&   r   r  )s   30NNNNN)r   r   r0  r  r  r  r1  r  r2  bytes | str | NonerL  r  rK  r  r  r  r  r  rn  r
  r   r&   )r   
__future__r   r;  rT  rV  r  typingr   r   r   r   r   r	   r
   r   r   unicodedatar   zope.interfacer   r   
constantlyr   r   incrementalr   rO  r   r   r   r   r   twisted.internet.abstractr   twisted.internet.addressr   r   r   r   twisted.internet.interfacesr   r   r   r    r!   r"   r#   r$   r%   r&   r'   r(   twisted.internet.protocolr)   r*   r+   r,   twisted.internet.stdior-   r.   ImportErrortwisted.internet._resolverr/   twisted.internet.deferr0   twisted.internet.taskr1   twisted.loggerr2   twisted.pluginr3   r4   twisted.pythonr5   r6   twisted.python.compatr7   r8   r9   twisted.python.componentsr:   twisted.python.failurer;   twisted.python.filepathr<   twisted.python.systemdr=   _idnar?   r@   OpenSSL.SSLrA   r  twisted.internet.sslrB   rC   rD   rE   rF   rG   twisted.protocols.tlsrI   _TLSMemoryBIOFactory__all__r\   r   IStreamServerEndpointrU   IProcessTransport	IConsumerIPushProducerr   r   r   rX   rV   r  rL   rM   rN   rO   AddressFamily
SocketKindr>  r=  
_gairesultra  rW   rR   rS   rP   rQ   rT   r@  rE  rd  rf  rt  r  r  ranger  r  r  r  r  r  ri  r  rK   r  r  r  r  r  r  r  r  r  rJ   rY   r  r  rZ   r  r  r   rl   ri   <module>r>     s  
 # 	 	   X X X ! 8 +  E E 3     X W> 6 + - ! . ) J J 7 * , , (/-  R /*N3 N3b^/} ^/B Z--.
 
 /
8  *"6"6
8P8P1 =8_ =8@E  Z--.@( @( /@(F Z--."
 "
 /"
JM+ M*M+ M* Z--.3  3  /3 l Z--.H  H  /H V 	#s(O#sC$%'	
			

 F F  FR Z--.vY vY /vYr Z--.'
 '
 /'
T Z--.4  4  /4 n Z--. 
  
 / 
F Z--.%  %  /% P Z--.,# ,# /,#^S2D ZYz W78* * 9*0 W78@; @; 9@;F W78"; "; 9";L  QxW'TF    F8AF@R F$N78/
2%P*:6 Q=h.0 Z--.A A /A* Z--.S S /S&6* L !&*&*%)%)#'II
I I 	I
 $I $I #I #I !I I IX WBC9 9 D9H  JK<  s$   Q /Q( 
Q%$Q%(Q43Q4