
    h                       S 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  SSKJrJrJrJrJr  SSKJr  SSKJr  SSKJrJrJr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&  SSK'J(r(J)r)  SSK*J+r+  \
" \5       " S S5      5       r,SS jr-\
" \!\\"5       " S S\(5      5       r.\
" \\5       " S S5      5       r/ " S S5      r0SS jr1 " S S\.5      r2 " S S\)5      r3g)a  
Implementation of a TLS transport (L{ISSLTransport}) as an
L{IProtocol<twisted.internet.interfaces.IProtocol>} layered on top of any
L{ITransport<twisted.internet.interfaces.ITransport>} implementation, based on
U{OpenSSL<http://www.openssl.org>}'s memory BIO features.

L{TLSMemoryBIOFactory} is a L{WrappingFactory} which wraps protocols created by
the factory it wraps with L{TLSMemoryBIOProtocol}.  L{TLSMemoryBIOProtocol}
intercedes between the underlying transport and the wrapped protocol to
implement SSL and TLS.  Typical usage of this module looks like this::

    from twisted.protocols.tls import TLSMemoryBIOFactory
    from twisted.internet.protocol import ServerFactory
    from twisted.internet.ssl import PrivateCertificate
    from twisted.internet import reactor

    from someapplication import ApplicationProtocol

    serverFactory = ServerFactory()
    serverFactory.protocol = ApplicationProtocol
    certificate = PrivateCertificate.loadPEM(certPEMData)
    contextFactory = certificate.options()
    tlsFactory = TLSMemoryBIOFactory(contextFactory, False, serverFactory)
    reactor.listenTCP(12345, tlsFactory)
    reactor.run()

This API offers somewhat more flexibility than
L{twisted.internet.interfaces.IReactorSSL}; for example, a
L{TLSMemoryBIOProtocol} instance can use another instance of
L{TLSMemoryBIOProtocol} as its transport, yielding TLS over TLS - useful to
implement onion routing.  It can also be used to run TLS over unusual
transports, such as UNIX sockets and stdio.
    )annotations)CallableIterableOptionalcast)directlyProvidesimplementer
providedBy)
ConnectionErrorSysCallErrorWantReadErrorZeroReturnError)_PullToPush)_setAcceptableProtocols)IDelayedCallIHandshakeListenerILoggingContextINegotiatedIOpenSSLClientConnectionCreatorIOpenSSLServerConnectionCreator	IProtocolIProtocolNegotiationFactoryIPushProducerIReactorTimeISystemHandle
ITransport)CONNECTION_LOST)Protocol)ProtocolWrapperWrappingFactory)Failurec                  4    \ rS rSrSrSrS rS rS rS r	Sr
g	)
_ProducerMembraneE   a  
Stand-in for producer registered with a L{TLSMemoryBIOProtocol} transport.

Ensures that producer pause/resume events from the undelying transport are
coordinated with pause/resume events from the TLS layer.

@ivar _producer: The application-layer producer.
Fc                    Xl         g N)	_producer)selfproducers     \/root/1688_scrapy/alibaba-scraper/venv/lib/python3.13/site-packages/twisted/protocols/tls.py__init___ProducerMembrane.__init__R   s    !    c                j    U R                   (       a  gSU l         U R                  R                  5         g)z@
C{pauseProducing} the underlying producer, if it's not paused.
NT)_producerPausedr(   pauseProducingr)   s    r+   r1    _ProducerMembrane.pauseProducingU   s(     #%%'r.   c                j    U R                   (       d  gSU l         U R                  R                  5         g)z=
C{resumeProducing} the underlying producer, if it's paused.
NF)r0   r(   resumeProducingr2   s    r+   r5   !_ProducerMembrane.resumeProducing^   s(     ##$&&(r.   c                8    U R                   R                  5         g)zt
C{stopProducing} the underlying producer.

There is only a single source for this event, so it's simply passed
on.
N)r(   stopProducingr2   s    r+   r8   _ProducerMembrane.stopProducingg   s     	$$&r.   )r(   r0   N)__name__
__module____qualname____firstlineno____doc__r0   r,   r1   r5   r8   __static_attributes__ r.   r+   r$   r$   E   s"     O"()'r.   r$   c                    [        U [        5      (       a  U R                  u  pOU R                  S   nUS   u    pUR                  5       R	                  S5      $ )z<
Does the given OpenSSL.SSL.Error represent an end-of-file?
r   zunexpected eof)
isinstancer   argscasefold
startswith)exceptionObject_reasonString
errorQueues       r+   _representsEOFrK   q   sY    
 /<00)..<$))!,
'^1  "--.>??r.   c                      \ rS rSrSrSrSrSrSrSr	SS j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S rS rS rS rS r\S 5       rS rS r Sr!g)TLSMemoryBIOProtocol~   a
  
L{TLSMemoryBIOProtocol} is a protocol wrapper which uses OpenSSL via a
memory BIO to encrypt bytes written to it before sending them on to the
underlying transport and decrypts bytes received from the underlying
transport before delivering them to the wrapped protocol.

In addition to producer events from the underlying transport, the need to
wait for reads before a write can proceed means the L{TLSMemoryBIOProtocol}
may also want to pause a producer.  Pause/resume events are therefore
merged using the L{_ProducerMembrane} wrapper.  Non-streaming (pull)
producers are supported by wrapping them with L{_PullToPush}.

Because TLS may need to wait for reads before writing, some writes may be
buffered until a read occurs.

@ivar _tlsConnection: The L{OpenSSL.SSL.Connection} instance which is
    encrypted and decrypting this connection.

@ivar _lostTLSConnection: A flag indicating whether connection loss has
    already been dealt with (C{True}) or not (C{False}).  TLS disconnection
    is distinct from the underlying connection being lost.

@ivar _appSendBuffer: application-level (cleartext) data that is waiting to
    be transferred to the TLS buffer, but can't be because the TLS
    connection is handshaking.
@type _appSendBuffer: L{list} of L{bytes}

@ivar _connectWrapped: A flag indicating whether or not to call
    C{makeConnection} on the wrapped protocol.  This is for the reactor's
    L{twisted.internet.interfaces.ITLSTransport.startTLS} implementation,
    since it has a protocol which it has already called C{makeConnection}
    on, and which has no interest in a new transport.  See #3821.

@ivar _handshakeDone: A flag indicating whether or not the handshake is
    known to have completed successfully (C{True}) or not (C{False}).  This
    is used to control error reporting behavior.  If the handshake has not
    completed, the underlying L{OpenSSL.SSL.Error} will be passed to the
    application's C{connectionLost} method.  If it has completed, any
    unexpected L{OpenSSL.SSL.Error} will be turned into a
    L{ConnectionLost}.  This is weird; however, it is simply an attempt at
    a faithful re-implementation of the behavior provided by
    L{twisted.internet.ssl}.

@ivar _reason: If an unexpected L{OpenSSL.SSL.Error} occurs which causes
    the connection to be lost, it is saved here.  If appropriate, this may
    be used as the reason passed to the application protocol's
    C{connectionLost} method.

@ivar _producer: The current producer registered via C{registerProducer},
    or L{None} if no producer has been registered or a previous one was
    unregistered.

@ivar _aborted: C{abortConnection} has been called.  No further data will
    be received to the wrapped protocol's C{dataReceived}.
@type _aborted: L{bool}
NFc                >    [         R                  " XU5        X0l        g r'   )r    r,   _connectWrapped)r)   factorywrappedProtocolrP   s       r+   r,   TLSMemoryBIOProtocol.__init__   s      @.r.   c                    U R                   $ )a1  
Return the L{OpenSSL.SSL.Connection} object being used to encrypt and
decrypt this connection.

This is done for the benefit of L{twisted.internet.ssl.Certificate}'s
C{peerFromTransport} and C{hostFromTransport} methods only.  A
different system handle may be returned by future versions of this
method.
)_tlsConnectionr2   s    r+   	getHandleTLSMemoryBIOProtocol.getHandle   s     """r.   c                \   U R                   R                  U 5      U l        / U l        [	        U5       H  n[        X5        M     [        R                  " X5        U R                   R                  U 5        U R                  (       a  [        R                  " X5        U R                  5         g)zw
Connect this wrapper to the given transport and initialize the
necessary L{OpenSSL.SSL.Connection} with a memory BIO.
N)rQ   _createConnectionrU   _appSendBufferr
   r   r   makeConnectionregisterProtocolrP   r    _checkHandshakeStatus)r)   	transport	interfaces      r+   r[   #TLSMemoryBIOProtocol.makeConnection   s    
 #ll<<TB  $I.IT- /
 	0%%d+ **4;
 	""$r.   c                t   U R                   (       a  g U R                  R                  5         SU l        [        R
                  " U R                  5      (       a  U R                  R                  5         gg! [         a    U R                  5          g[         a    U R                  [        5       5         gf = f)a   
Ask OpenSSL to proceed with a handshake in progress.

Initially, this just sends the ClientHello; after some bytes have been
stuffed in to the C{Connection} object by C{dataReceived}, it will then
respond to any C{Certificate} or C{KeyExchange} messages.
NT)_abortedrU   do_handshake_handshakeDoner   r
   rR   handshakeCompletedr   _flushSendBIOr   _tlsShutdownFinishedr"   r2   s    r+   r]   *TLSMemoryBIOProtocol._checkHandshakeStatus   s     ==		:,,. #'D!,,T-A-ABB$$779 C  	!  	1%%gi0	1s   A6 6B7"B76B7c                     U R                   R                  S5      nU R                  R                  U5        g! [         a     gf = f)zP
Read any bytes out of the send BIO and write them to the underlying
transport.
   N)rU   bio_readr^   writer   r)   bytess     r+   rf   "TLSMemoryBIOProtocol._flushSendBIO  sE    
	(''007E
 NN  '	  		s   9 
AAc                   U R                   (       dV   U R                  R                  S5      nU R                  (       d  [        R
                  " X5        U R                   (       d  MV  U R                  5         g! [         a     M  [         a$    U R                  5         U R                  S5         N][         a    [        5       nU R                  U5         Nf = f)a5  
Try to receive any application-level bytes which are now available
because of a previous write into the receive BIO.  This will take
care of delivering any application-level bytes which are received to
the protocol, as well as handling of the various exceptions which
can come from trying to get such bytes.
rj   N)_lostTLSConnectionrU   recvrb   r    dataReceivedr   r   _shutdownTLSrg   r   r"   rf   )r)   rn   failures      r+   _flushReceiveBIO%TLSMemoryBIOProtocol._flushReceiveBIO  s     ))>++007( }}#00=/ )))8 	3 !  " 0 !!# ))$/ 3
 ")))'23s   A9 9
C*C2$CCc                   U R                   R                  U5        U R                  (       d"  U R                  5         U R                  (       d  gU R                  (       a  U R                  5         U R                  5         g)z
Deliver any received bytes to the receive BIO and then read and deliver
to the application any application-level data which becomes available
as a result of this.
N)rU   	bio_writerd   r]   rZ   _unbufferPendingWritesrv   rm   s     r+   rs   !TLSMemoryBIOProtocol.dataReceived8  sb     	%%e, ""&&( && '')
 	r.   c                     U R                   R                  5       nU R                  5         U(       a  U R                  R                  5         gg! [         a    Sn NAf = f)zA
Initiate, or reply to, the shutdown handshake of the TLS layer.
FN)rU   shutdownr   rf   r^   loseConnection)r)   shutdownSuccesss     r+   rt   !TLSMemoryBIOProtocol._shutdownTLSU  s[    	$"11::<O 	
 NN))+   	$
 $O	$s   A AAc                    Ub)  [        UR                  5      (       a  [        [        5      nU R                  c  Xl        SU l        U R                  5         U R                  R                  5         g)a  
Called when TLS connection has gone away; tell underlying transport to
disconnect.

@param reason: a L{Failure} whose value is an L{Exception} if we want to
    report that failure through to the wrapped protocol's
    C{connectionLost}, or L{None} if the C{reason} that
    C{connectionLost} should receive should be coming from the
    underlying transport.
@type reason: L{Failure} or L{None}
NT)	rK   valuer"   r   _reasonrq   rf   r^   r~   r)   reasons     r+   rg   )TLSMemoryBIOProtocol._tlsShutdownFinishedi  s\      fll++ 1<<!L"& 	 	%%'r.   c                   U R                   (       d1  U R                  R                  5         U R                  5         SU l         U R                  =(       d    UnSU l        SU l        [        R                  " X5        SU l        g)z
Handle the possible repetition of calls to this method (due to either
the underlying transport going away or due to an error at the TLS
layer) and make sure the base implementation only gets invoked once.
TNF)rq   rU   bio_shutdownrv   r   	connectedr    connectionLostr   s     r+   r   #TLSMemoryBIOProtocol.connectionLost  si     && ,,.!!#&*D#'&&t4 #r.   c                   U R                   (       d  U R                  (       d  gU R                  (       d!  U R                  (       d  U R	                  5         SU l         U R                  (       d  U R
                  c  U R                  5         ggg)z=
Send a TLS close alert and close the underlying connection.
NT)disconnectingr   rd   rZ   abortConnectionr(   rt   r2   s    r+   r~   #TLSMemoryBIOProtocol.loseConnection  sc     T^^ ""4+>+>  "!""t~~'= (>"r.   c                t    SU l         SU l        U R                  5         U R                  R	                  5         g)z
Tear down TLS state so that if the connection is aborted mid-handshake
we don't deliver any further data from the application.
TN)rb   r   rt   r^   r   r2   s    r+   r   $TLSMemoryBIOProtocol.abortConnection  s/    
 !&&(r.   c                0    Xl         U R                  5         g)z
Abort the connection during connection setup, giving a reason that
certificate verification failed.

@param reason: The reason that the verification failed; reported to the
    application protocol's C{connectionLost} method.
@type reason: L{Failure}
N)r   r   r   s     r+   failVerification%TLSMemoryBIOProtocol.failVerification  s     r.   c                d    U R                   (       a  U R                  c  gU R                  U5        g)z
Process the given application bytes and send any resulting TLS traffic
which arrives in the send BIO.

If C{loseConnection} was called, subsequent calls to C{write} will
drop the bytes on the floor.
N)r   r(   _writerm   s     r+   rl   TLSMemoryBIOProtocol.write  s%     $.."8Er.   c                    U R                   R                  U5        U R                  b  U R                  R                  5         gg)z
Put the given octets into L{TLSMemoryBIOProtocol._appSendBuffer}, and
tell any listening producer that it should pause because we are now
buffering.
N)rZ   appendr(   r1   )r)   octetss     r+   _bufferedWrite#TLSMemoryBIOProtocol._bufferedWrite  s7     	""6*>>%NN))+ &r.   c                   U R                   / sol         U H  nU R                  U5        M     U R                   (       a  gU R                  b  U R                  R                  5         gU R                  (       a  U R                  5         gg)zI
Un-buffer all waiting writes in L{TLSMemoryBIOProtocol._appSendBuffer}.
N)rZ   r   r(   r5   r   rt   )r)   pendingWrites	eachWrites      r+   rz   +TLSMemoryBIOProtocol._unbufferPendingWrites  sx     .2-@-@"**&IKK	" '  >>% NN**, 	 r.   c                l   U R                   (       a  gSnSnU[        U5      :  aH  XX2-    n U R                  R                  U5      nX5-  nU R	                  5         U[        U5      :  a  MG  gg! [
         a    U R                  XS 5         g[         a    U R                  [        5       5         gf = f)a.  
Process the given application bytes and send any resulting TLS traffic
which arrives in the send BIO.

This may be called by C{dataReceived} with bytes that were buffered
before C{loseConnection} was called, which is why this function
doesn't check for disconnection but accepts the bytes regardless.
Ni @  r   )
rq   lenrU   sendrf   r   r   r   rg   r"   )r)   rn   
bufferSizealreadySenttoSendsents         r+   r   TLSMemoryBIOProtocol._write  s     "" 
 CJ&)ABF%**//7 # ""$+ CJ& ! ##E,$78  ))')4s   A/ /B3"B32B3c                D    U R                  SR                  U5      5        g)ze
Write a sequence of application bytes by joining them into one string
and passing them to L{write}.
r.   N)rl   join)r)   iovecs     r+   writeSequence"TLSMemoryBIOProtocol.writeSequence"  s    
 	

388E?#r.   c                6    U R                   R                  5       $ r'   )rU   get_peer_certificater2   s    r+   getPeerCertificate'TLSMemoryBIOProtocol.getPeerCertificate)  s    ""7799r.   c                    Sn U R                   R                  5       nUS;  a  U$  U R                   R	                  5       nUS:w  a  U$ g! [        [        4 a     N>f = f! [        [        4 a     N1f = f)z)
@see: L{INegotiated.negotiatedProtocol}
N)r.   Nr.   )rU   get_alpn_proto_negotiatedNotImplementedErrorAttributeErrorget_next_proto_negotiated)r)   protocolNames     r+   negotiatedProtocol'TLSMemoryBIOProtocol.negotiatedProtocol,  s    
 	..HHJL {*	..HHJL 3 $^4 		 $^4 		s"   A
 A  
AA A32A3c                    U R                   (       a  UR                  5         g U(       d  [        X5      =p[        U5      nU R                  R                  US5        Xl        U(       d  WR                  5         g g )NT)rq   r8   r   r$   r^   registerProducerr(   startStreaming)r)   r*   	streamingstreamingProducers       r+   r   %TLSMemoryBIOProtocol.registerProducerG  se    """"$ +6x+FFH$X.''$7! ,,. r.   c                r   U R                   c  g [        U R                   R                   [        5      (       a$  U R                   R                   R                  5         S U l         SU l        U R
                  R                  5         U R                  (       a#  U R                  (       d  U R                  5         g g g )NF)
r(   rC   r   stopStreamingr0   r^   unregisterProducerr   rZ   rt   r2   s    r+   r   'TLSMemoryBIOProtocol.unregisterProducerZ  s    >>! dnn..<<NN$$224$))+d&9&9 ':r.   )rb   rZ   rP   rd   rq   r(   r0   r   rU   r   r   T)"r:   r;   r<   r=   r>   r   rd   rq   r(   rb   r,   rV   r[   r]   rf   rv   rs   rt   rg   r   r~   r   r   rl   r   rz   r   r   r   propertyr   r   r   r?   r@   r.   r+   rM   rM   ~   s    7r GNIH/
#%4:0((T :,((B#( $)
, 4'%R$:  4/& r.   rM   c                  0    \ rS rSrSrS rS rS rS rSr	g)	"_ContextFactoryToConnectionFactoryij  z
Adapter wrapping a L{twisted.internet.interfaces.IOpenSSLContextFactory}
into a L{IOpenSSLClientConnectionCreator} or
L{IOpenSSLServerConnectionCreator}.

See U{https://twistedmatrix.com/trac/ticket/7215} for work that should make
this unnecessary.
c                0    UR                  5         Xl        g)a  
Construct a L{_ContextFactoryToConnectionFactory} with a
L{twisted.internet.interfaces.IOpenSSLContextFactory}.

Immediately call C{getContext} on C{oldStyleContextFactory} in order to
force advance parameter checking, since old-style context factories
don't actually check that their arguments to L{OpenSSL} are correct.

@param oldStyleContextFactory: A factory that can produce contexts.
@type oldStyleContextFactory:
    L{twisted.internet.interfaces.IOpenSSLContextFactory}
N)
getContext_oldStyleContextFactory)r)   oldStyleContextFactorys     r+   r,   +_ContextFactoryToConnectionFactory.__init__u  s     	))+'=$r.   c                N    U R                   R                  5       n[        US5      $ )z
Create an L{OpenSSL.SSL.Connection} object.

@param protocol: The protocol initiating a TLS connection.
@type protocol: L{TLSMemoryBIOProtocol}

@return: a connection
@rtype: L{OpenSSL.SSL.Connection}
N)r   r   r   )r)   protocolcontexts      r+   _connectionForTLS4_ContextFactoryToConnectionFactory._connectionForTLS  s%     ..99;'4((r.   c                $    U R                  U5      $ )a  
Construct an OpenSSL server connection from the wrapped old-style
context factory.

@note: Since old-style context factories don't distinguish between
    clients and servers, this is exactly the same as
    L{_ContextFactoryToConnectionFactory.clientConnectionForTLS}.

@param protocol: The protocol initiating a TLS connection.
@type protocol: L{TLSMemoryBIOProtocol}

@return: a connection
@rtype: L{OpenSSL.SSL.Connection}
r   r)   r   s     r+   serverConnectionForTLS9_ContextFactoryToConnectionFactory.serverConnectionForTLS       %%h//r.   c                $    U R                  U5      $ )a  
Construct an OpenSSL server connection from the wrapped old-style
context factory.

@note: Since old-style context factories don't distinguish between
    clients and servers, this is exactly the same as
    L{_ContextFactoryToConnectionFactory.serverConnectionForTLS}.

@param protocol: The protocol initiating a TLS connection.
@type protocol: L{TLSMemoryBIOProtocol}

@return: a connection
@rtype: L{OpenSSL.SSL.Connection}
r   r   s     r+   clientConnectionForTLS9_ContextFactoryToConnectionFactory.clientConnectionForTLS  r   r.   )r   N)
r:   r;   r<   r=   r>   r,   r   r   r   r?   r@   r.   r+   r   r   j  s    > )0"0r.   r   c                  D    \ rS rSrSrSrS
S jrSS jrSS jrSS jr	Sr
g	)_AggregateSmallWritesi  aQ  
Aggregate small writes so they get written in large batches.

If this is used as part of a transport, the transport needs to call
``flush()`` immediately when ``loseConnection()`` is called, otherwise any
buffered writes will never get written.

@cvar MAX_BUFFER_SIZE: The maximum amount of bytes to buffer before writing
    them out.
i   c                Z    Xl         X l        / U l        U R                  U l        S U l        g r'   )r   _clock_bufferMAX_BUFFER_SIZE_bufferLeft
_scheduled)r)   rl   clocks      r+   r,   _AggregateSmallWrites.__init__  s(    $&//26r.   c                2   U R                   R                  U5        U =R                  [        U5      -  sl        U R                  S:  a  U R	                  5         gU R
                  (       a  gU R                  R                  SU R                  5      U l        g)z
Buffer the data, or write it immediately if we've accumulated enough to
make it worth it.

Accumulating too much data can result in higher memory usage.
r   N)	r   r   r   r   flushr   r   	callLater_scheduledFlush)r)   datas     r+   rl   _AggregateSmallWrites.write  ss     	D!CI%a JJL??  ++//43G3GHr.   c                2    SU l         U R                  5         g)z!Called in next reactor iteration.N)r   r   r2   s    r+   r   %_AggregateSmallWrites._scheduledFlush  s    

r.   c                    U R                   (       aK  U R                  U l        U R                  SR	                  U R                   5      5        U R                   SS2	 gg)zFlush any buffered writes.r.   N)r   r   r   r   r   r2   s    r+   r   _AggregateSmallWrites.flush  s@    <<#33DKK./Q r.   )r   r   r   r   r   N)rl   zCallable[[bytes], object]r   r   )r   rn   returnNoner   r   )r:   r;   r<   r=   r>   r   r,   rl   r   r   r?   r@   r.   r+   r   r     s#    	 O7I2
 r.   r   c                 .    SSK Jn   [        [        U 5      $ )z
Return the default reactor.

This is a function so it can be monkey-patched in tests, specifically
L{twisted.web.test.test_agent}.
r   reactor)twisted.internetr   r   r   r   s    r+   _get_default_clockr     s     )g&&r.   c                  Z   ^  \ rS rSrSr S     SU 4S jjjrS	S jrS
U 4S jjrSrU =r	$ )BufferingTLSTransporti  av  
A TLS transport implemented by wrapping buffering around a
L{TLSMemoryBIOProtocol}.

Doing many small writes directly to a L{OpenSSL.SSL.Connection}, as
implemented in L{TLSMemoryBIOProtocol}, can add significant CPU and
bandwidth overhead.  Thus, even when writing is possible, small writes will
get aggregated and written as a single write at the next reactor iteration.
c                   > [         TU ]  XU5        [         TU ]  n[        XAR                  5      U l        U R
                  R                  U l        g r'   )superr,   rl   r   r   _aggregator)r)   rQ   rR   rP   actual_write	__class__s        r+   r,   BufferingTLSTransport.__init__  sC     	?Cw}0~~N %%++
r.   c                X    U R                   R                  SR                  U5      5        g )Nr.   )r   rl   r   )r)   sequences     r+   r   #BufferingTLSTransport.writeSequence  s    sxx12r.   c                V   > U R                   R                  5         [        TU ]  5         g r'   )r   r   r   r~   )r)   r   s    r+   r~   $BufferingTLSTransport.loseConnection  s       r.   )r   rl   r   )rQ   TLSMemoryBIOFactoryrR   r   rP   bool)r   zIterable[bytes]r   r   r   )
r:   r;   r<   r=   r>   r,   r   r~   r?   __classcell__)r   s   @r+   r   r     sB    * !%	,$, #, 	, ,3! !r.   r   c                  >    \ rS rSrSr\rSr S
S jrS r	S r
S rS	rg)r  i$  a  
L{TLSMemoryBIOFactory} adds TLS to connections.

@ivar _creatorInterface: the interface which L{_connectionCreator} is
    expected to implement.
@type _creatorInterface: L{zope.interface.interfaces.IInterface}

@ivar _connectionCreator: a callable which creates an OpenSSL Connection
    object.
@type _connectionCreator: 1-argument callable taking
    L{TLSMemoryBIOProtocol} and returning L{OpenSSL.SSL.Connection}.
FNc                    [         R                  " X5        U(       a  [        nO[        nXPl        UR                  U5      (       d  [        U5      nXl        Uc
  [        5       nX@l	        g)a"  
Create a L{TLSMemoryBIOFactory}.

@param contextFactory: Configuration parameters used to create an
    OpenSSL connection.  In order of preference, what you should pass
    here should be:

        1. L{twisted.internet.ssl.CertificateOptions} (if you're
           writing a server) or the result of
           L{twisted.internet.ssl.optionsForClientTLS} (if you're
           writing a client).  If you want security you should really
           use one of these.

        2. If you really want to implement something yourself, supply a
           provider of L{IOpenSSLClientConnectionCreator} or
           L{IOpenSSLServerConnectionCreator}.

        3. If you really have to, supply a
           L{twisted.internet.ssl.ContextFactory}.  This will likely be
           deprecated at some point so please upgrade to the new
           interfaces.

@type contextFactory: L{IOpenSSLClientConnectionCreator} or
    L{IOpenSSLServerConnectionCreator}, or, for compatibility with
    older code, anything implementing
    L{twisted.internet.interfaces.IOpenSSLContextFactory}.  See
    U{https://twistedmatrix.com/trac/ticket/7215} for information on
    the upcoming deprecation of passing a
    L{twisted.internet.ssl.ContextFactory} here.

@param isClient: Is this a factory for TLS client connections; in other
    words, those that will send a C{ClientHello} greeting?  L{True} if
    so, L{False} otherwise.  This flag determines what interface is
    expected of C{contextFactory}.  If L{True}, C{contextFactory}
    should provide L{IOpenSSLClientConnectionCreator}; otherwise it
    should provide L{IOpenSSLServerConnectionCreator}.
@type isClient: L{bool}

@param wrappedFactory: A factory which will create the
    application-level protocol.
@type wrappedFactory: L{twisted.internet.interfaces.IProtocolFactory}
N)
r!   r,   r   r   _creatorInterfacer
   r   _connectionCreatorr   r   )r)   contextFactoryisClientwrappedFactoryr   creatorInterfaces         r+   r,   TLSMemoryBIOFactory.__init__6  s[    b 	  6>>!1**>::?ON"0=&(Er.   c                    [         R                  " U R                  5      (       a  U R                  R                  5       nO U R                  R                  R
                  nU S3$ )zd
Annotate the wrapped factory's log prefix with some text indicating TLS
is in use.

@rtype: C{str}
z (TLS))r   r
   r  	logPrefixr   r:   )r)   r  s     r+   r  TLSMemoryBIOFactory.logPrefixu  sS     %%d&9&9::++557I++55>>IF##r.   c                    [         R                  " U R                  5      (       a5  U R                  R                  5       nUR	                  5       n[        X25        g)z
Applies ALPN/NPN protocol neogitation to the connection, if the factory
supports it.

@param connection: The OpenSSL connection object to have ALPN/NPN added
    to it.
@type connection: L{OpenSSL.SSL.Connection}

@return: Nothing
@rtype: L{None}
N)r   r
   r  acceptableProtocolsget_contextr   )r)   
connection	protocolsr   s       r+   _applyProtocolNegotiation-TLSMemoryBIOFactory._applyProtocolNegotiation  sH     '11$2E2EFF++??AI ,,.G#G7r.   c                   U R                   nU R                  [        L a4  UR                  U5      nU R	                  U5        UR                  5         U$ UR                  U5      nU R	                  U5        UR                  5         U$ )a  
Create an OpenSSL connection and set it up good.

@param tlsProtocol: The protocol which is establishing the connection.
@type tlsProtocol: L{TLSMemoryBIOProtocol}

@return: an OpenSSL connection object for C{tlsProtocol} to use
@rtype: L{OpenSSL.SSL.Connection}
)r
  r	  r   r   r  set_connect_stater   set_accept_state)r)   tlsProtocolconnectionCreatorr  s       r+   rY   %TLSMemoryBIOFactory._createConnection  s     !33!!%DD*AA+NJ**:6((*
  +AA+NJ**:6'')r.   )r   r
  r	  r'   )r:   r;   r<   r=   r>   r   r   noisyr,   r  r  rY   r?   r@   r.   r+   r  r  $  s-     %HE =~$&r.   r  N)rG   r   r   r  )r   r   )4r>   
__future__r   typingr   r   r   r   zope.interfacer   r	   r
   OpenSSL.SSLr   r   r   r   r   "twisted.internet._producer_helpersr   twisted.internet._sslverifyr   twisted.internet.interfacesr   r   r   r   r   r   r   r   r   r   r   r   twisted.internet.mainr   twisted.internet.protocolr   twisted.protocols.policiesr    r!   twisted.python.failurer"   r$   rK   rM   r   r   r   r   r  r@   r.   r+   <module>r,     s   
 D # 5 5 D D W W : ?    2 . G * ](' (' ('V
@ ]K4h ? h  5h V ,.MNG0 G0 OG0T8  8 v	'%!0 %!PD/ Dr.   