U
    adJj                     @   s   d dl Z d dlZzd dlZW n ek
r4   dZY nX ddlmZ ddlmZ ddlmZ ddlmZ ddl	m
Z
 dd	 Zd
ZdZdZdZG dd deZG dd dejejZG dd dejZdS )    N   )base_events)	constants)	protocols)
transports)loggerc                 C   s"   | rt dt }|sd|_|S )Nz(Server side SSL needs a valid SSLContextF)
ValueErrorsslZcreate_default_contextZcheck_hostname)server_sideserver_hostname
sslcontext r   &/usr/lib/python3.8/asyncio/sslproto.py_create_transport_context   s    r   Z	UNWRAPPEDZDO_HANDSHAKEZWRAPPEDZSHUTDOWNc                   @   s~   e Zd ZdZdZdddZedd Zedd	 Zed
d Z	edd Z
dddZdddZdd ZdddZdddZdS )_SSLPipea  An SSL "Pipe".

    An SSL pipe allows you to communicate with an SSL/TLS protocol instance
    through memory buffers. It can be used to implement a security layer for an
    existing connection where you don't have access to the connection's file
    descriptor, or for some reason you don't want to use it.

    An SSL pipe can be in "wrapped" and "unwrapped" mode. In unwrapped mode,
    data is passed through untransformed. In wrapped mode, application level
    data is encrypted to SSL record level data and vice versa. The SSL record
    level is the lowest level in the SSL protocol suite and is what travels
    as-is over the wire.

    An SslPipe initially is in "unwrapped" mode. To start SSL, call
    do_handshake(). To shutdown SSL again, call unwrap().
    i   Nc                 C   sH   || _ || _|| _t| _t | _t | _d| _	d| _
d| _d| _dS )a  
        The *context* argument specifies the ssl.SSLContext to use.

        The *server_side* argument indicates whether this is a server side or
        client side transport.

        The optional *server_hostname* argument can be used to specify the
        hostname you are connecting to. You may only specify this parameter if
        the _ssl module supports Server Name Indication (SNI).
        NF)_context_server_side_server_hostname
_UNWRAPPED_stater	   Z	MemoryBIO	_incoming	_outgoing_sslobj_need_ssldata_handshake_cb_shutdown_cb)selfcontextr
   r   r   r   r   __init__8   s    

z_SSLPipe.__init__c                 C   s   | j S )z*The SSL context passed to the constructor.)r   r   r   r   r   r   N   s    z_SSLPipe.contextc                 C   s   | j S )z^The internal ssl.SSLObject instance.

        Return None if the pipe is not wrapped.
        )r   r   r   r   r   
ssl_objectS   s    z_SSLPipe.ssl_objectc                 C   s   | j S )zgWhether more record level data is needed to complete a handshake
        that is currently in progress.)r   r   r   r   r   need_ssldata[   s    z_SSLPipe.need_ssldatac                 C   s
   | j tkS )zj
        Whether a security layer is currently in effect.

        Return False during handshake.
        )r   _WRAPPEDr   r   r   r   wrappeda   s    z_SSLPipe.wrappedc                 C   sb   | j tkrtd| jj| j| j| j| jd| _	t
| _ || _| jddd\}}t|dks^t|S )aL  Start the SSL handshake.

        Return a list of ssldata. A ssldata element is a list of buffers

        The optional *callback* argument can be used to install a callback that
        will be called when the handshake is complete. The callback will be
        called with None if successful, else an exception instance.
        z"handshake in progress or completed)r
   r       T)only_handshaker   )r   r   RuntimeErrorr   Zwrap_bior   r   r   r   r   _DO_HANDSHAKEr   feed_ssldatalenAssertionErrorr   callbackssldataappdatar   r   r   do_handshakej   s    	
 z_SSLPipe.do_handshakec                 C   sj   | j tkrtd| j tkr$td| j ttfks6tt| _ || _| d\}}|g ksf|dgksft|S )a1  Start the SSL shutdown sequence.

        Return a list of ssldata. A ssldata element is a list of buffers

        The optional *callback* argument can be used to install a callback that
        will be called when the shutdown is complete. The callback will be
        called without arguments.
        zno security layer presentzshutdown in progressr$   )	r   r   r&   	_SHUTDOWNr"   r'   r*   r   r(   r+   r   r   r   shutdown   s    	

z_SSLPipe.shutdownc                 C   s2   | j   | d\}}|g ks.|dgks.tdS )zSend a potentially "ragged" EOF.

        This method will raise an SSL_ERROR_EOF exception if the EOF is
        unexpected.
        r$   N)r   Z	write_eofr(   r*   )r   r-   r.   r   r   r   feed_eof   s    
z_SSLPipe.feed_eofFc              
   C   s  | j tkr"|r|g}ng }g |fS d| _|r8| j| g }g }z| j tkrz| j  t| _ | j	rl| 	d |rz||fW S | j tkr| j
| j}|| |sqqnJ| j tkr| j  d| _t| _ | jr|   n| j tkr|| j
  W nz tjtjfk
rl } zRt|dd}|tjtjtjfkrP| j tkrN| j	rN| 	|  |tjk| _W 5 d}~X Y nX | jjr|| j
  ||fS )a  Feed SSL record level data into the pipe.

        The data must be a bytes instance. It is OK to send an empty bytes
        instance. This can be used to get ssldata for a handshake initiated by
        this endpoint.

        Return a (ssldata, appdata) tuple. The ssldata element is a list of
        buffers containing SSL data that needs to be sent to the remote SSL.

        The appdata element is a list of buffers containing plaintext data that
        needs to be forwarded to the application. The appdata list may contain
        an empty buffer indicating an SSL "close_notify" alert. This alert must
        be acknowledged by calling shutdown().
        FNerrno)r   r   r   r   writer'   r   r/   r"   r   readmax_sizeappendr0   Zunwrapr   r	   SSLErrorCertificateErrorgetattrSSL_ERROR_WANT_READSSL_ERROR_WANT_WRITESSL_ERROR_SYSCALLr   pending)r   datar%   r.   r-   chunkexc	exc_errnor   r   r   r(      sZ    










 

z_SSLPipe.feed_ssldatar   c              
   C   s4  d|  krt |ksn t| jtkrT|t |k rD||d g}ng }|t |fS g }t|}d| _z(|t |k r|| j||d 7 }W nh tj	k
r } zHt
|dd}|jdkrtj }|_|tjtjtjfkrڂ |tjk| _W 5 d}~X Y nX | jjr|| j  |t |ks,| jr`q,q`||fS )a  Feed plaintext data into the pipe.

        Return an (ssldata, offset) tuple. The ssldata element is a list of
        buffers containing record level data that needs to be sent to the
        remote SSL instance. The offset is the number of plaintext bytes that
        were processed, which may be less than the length of data.

        NOTE: In case of short writes, this call MUST be retried with the SAME
        buffer passed into the *data* argument (i.e. the id() must be the
        same). This is an OpenSSL requirement. A further particularity is that
        a short write will always have offset == 0, because the _ssl module
        does not enable partial writes. And even though the offset is zero,
        there will still be encrypted data in ssldata.
        r   NFr3   ZPROTOCOL_IS_SHUTDOWN)r)   r*   r   r   
memoryviewr   r   r4   r	   r8   r:   reasonr;   r3   r<   r=   r   r>   r7   r5   )r   r?   offsetr-   ZviewrA   rB   r   r   r   feed_appdata   s6    


z_SSLPipe.feed_appdata)N)N)N)F)r   )__name__
__module____qualname____doc__r6   r   propertyr   r    r!   r#   r/   r1   r2   r(   rF   r   r   r   r   r   $   s    








Kr   c                   @   s   e Zd ZejjZdd Zd"ddZdd Z	dd	 Z
d
d Zdd ZejfddZdd Zdd Zdd Zd#ddZdd Zedd Zdd Zdd Zd d! ZdS )$_SSLProtocolTransportc                 C   s   || _ || _d| _d S )NF)_loop_ssl_protocol_closed)r   loopZssl_protocolr   r   r   r   !  s    z_SSLProtocolTransport.__init__Nc                 C   s   | j ||S )z#Get optional transport information.)rN   _get_extra_infor   namedefaultr   r   r   get_extra_info'  s    z$_SSLProtocolTransport.get_extra_infoc                 C   s   | j | d S N)rN   _set_app_protocol)r   protocolr   r   r   set_protocol+  s    z"_SSLProtocolTransport.set_protocolc                 C   s   | j jS rV   )rN   _app_protocolr   r   r   r   get_protocol.  s    z"_SSLProtocolTransport.get_protocolc                 C   s   | j S rV   )rO   r   r   r   r   
is_closing1  s    z _SSLProtocolTransport.is_closingc                 C   s   d| _ | j  dS )a  Close the transport.

        Buffered data will be flushed asynchronously.  No more data
        will be received.  After all buffered data is flushed, the
        protocol's connection_lost() method will (eventually) called
        with None as its argument.
        TN)rO   rN   _start_shutdownr   r   r   r   close4  s    z_SSLProtocolTransport.closec                 C   s&   | j s"|d| t| d |   d S )Nzunclosed transport )source)rO   ResourceWarningr^   )r   Z_warnr   r   r   __del__?  s    z_SSLProtocolTransport.__del__c                 C   s    | j j}|d krtd| S )Nz*SSL transport has not been initialized yet)rN   
_transportr&   
is_reading)r   Ztrr   r   r   rc   D  s    z _SSLProtocolTransport.is_readingc                 C   s   | j j  dS )zPause the receiving end.

        No data will be passed to the protocol's data_received()
        method until resume_reading() is called.
        N)rN   rb   pause_readingr   r   r   r   rd   J  s    z#_SSLProtocolTransport.pause_readingc                 C   s   | j j  dS )zResume the receiving end.

        Data received will once again be passed to the protocol's
        data_received() method.
        N)rN   rb   resume_readingr   r   r   r   re   R  s    z$_SSLProtocolTransport.resume_readingc                 C   s   | j j|| dS )a  Set the high- and low-water limits for write flow control.

        These two values control when to call the protocol's
        pause_writing() and resume_writing() methods.  If specified,
        the low-water limit must be less than or equal to the
        high-water limit.  Neither value can be negative.

        The defaults are implementation-specific.  If only the
        high-water limit is given, the low-water limit defaults to an
        implementation-specific value less than or equal to the
        high-water limit.  Setting high to zero forces low to zero as
        well, and causes pause_writing() to be called whenever the
        buffer becomes non-empty.  Setting low to zero causes
        resume_writing() to be called only once the buffer is empty.
        Use of zero for either limit is generally sub-optimal as it
        reduces opportunities for doing I/O and computation
        concurrently.
        N)rN   rb   set_write_buffer_limits)r   ZhighZlowr   r   r   rf   Z  s    z-_SSLProtocolTransport.set_write_buffer_limitsc                 C   s   | j j S )z,Return the current size of the write buffer.)rN   rb   get_write_buffer_sizer   r   r   r   rg   o  s    z+_SSLProtocolTransport.get_write_buffer_sizec                 C   s
   | j jjS rV   )rN   rb   _protocol_pausedr   r   r   r   rh   s  s    z&_SSLProtocolTransport._protocol_pausedc                 C   s<   t |tttfs$tdt|j |s,dS | j| dS )zWrite some data bytes to the transport.

        This does not block; it buffers the data and arranges for it
        to be sent out asynchronously.
        z+data: expecting a bytes-like instance, got N)	
isinstancebytes	bytearrayrC   	TypeErrortyperG   rN   _write_appdatar   r?   r   r   r   r4   x  s
    z_SSLProtocolTransport.writec                 C   s   dS )zAReturn True if this transport supports write_eof(), False if not.Fr   r   r   r   r   can_write_eof  s    z#_SSLProtocolTransport.can_write_eofc                 C   s   | j   d| _dS )zClose the transport immediately.

        Buffered data will be lost.  No more data will be received.
        The protocol's connection_lost() method will (eventually) be
        called with None as its argument.
        TN)rN   _abortrO   r   r   r   r   abort  s    
z_SSLProtocolTransport.abort)N)NN)rG   rH   rI   r   Z_SendfileModeZFALLBACKZ_sendfile_compatibler   rU   rY   r[   r\   r^   warningswarnra   rc   rd   re   rf   rg   rK   rh   r4   rp   rr   r   r   r   r   rL     s$   


rL   c                   @   s   e Zd ZdZd,ddZdd Zd-d	d
Zdd Zdd Zdd Z	dd Z
dd Zdd Zd.ddZdd Zdd Zdd Zdd  Zd!d" Zd#d$ Zd/d&d'Zd(d) Zd*d+ ZdS )0SSLProtocolzSSL protocol.

    Implementation of SSL on top of a socket using incoming and outgoing
    buffers which are ssl.MemoryBIO objects.
    FNTc	           	      C   s   t d krtd|d kr tj}n|dkr6td| |sDt||}|| _|rZ|sZ|| _nd | _|| _t	|d| _
t | _d| _|| _|| _| | t| j| | _d | _d| _d| _d| _d | _|| _|| _d S )Nzstdlib ssl module not availabler   z7ssl_handshake_timeout should be a positive number, got )r   F)r	   r&   r   ZSSL_HANDSHAKE_TIMEOUTr   r   r   r   _sslcontextdict_extracollectionsdeque_write_backlog_write_buffer_size_waiterrM   rW   rL   _app_transport_sslpipe_session_established_in_handshake_in_shutdownrb   _call_connection_made_ssl_handshake_timeout)	r   rP   app_protocolr   Zwaiterr
   r   Zcall_connection_madeZssl_handshake_timeoutr   r   r   r     s@     

zSSLProtocol.__init__c                 C   s   || _ t|tj| _d S rV   )rZ   ri   r   ZBufferedProtocol_app_protocol_is_buffer)r   r   r   r   r   rW     s    
zSSLProtocol._set_app_protocolc                 C   sD   | j d krd S | j  s:|d k	r.| j | n| j d  d | _ d S rV   )r}   Z	cancelledZset_exceptionZ
set_resultr   rA   r   r   r   _wakeup_waiter  s    

zSSLProtocol._wakeup_waiterc                 C   s&   || _ t| j| j| j| _|   dS )zXCalled when the low-level connection is made.

        Start the SSL handshake.
        N)rb   r   rv   r   r   r   _start_handshake)r   	transportr   r   r   connection_made  s    zSSLProtocol.connection_madec                 C   sn   | j r d| _ | j| jj| n| jdk	r2d| j_d| _d| _t| ddrT| j	
  | | d| _d| _dS )zCalled when the low-level connection is lost or closed.

        The argument is an exception object or None (the latter
        meaning a regular EOF is received or the connection was
        aborted or closed).
        FNT_handshake_timeout_handle)r   rM   	call_soonrZ   connection_lostr~   rO   rb   r:   r   cancelr   r   r   r   r   r   r     s    


zSSLProtocol.connection_lostc                 C   s   | j   dS )z\Called when the low-level transport's buffer goes over
        the high-water mark.
        N)rZ   pause_writingr   r   r   r   r     s    zSSLProtocol.pause_writingc                 C   s   | j   dS )z^Called when the low-level transport's buffer drains below
        the low-water mark.
        N)rZ   resume_writingr   r   r   r   r     s    zSSLProtocol.resume_writingc                 C   s"  | j dkrdS z| j |\}}W nL ttfk
r<    Y n4 tk
rn } z| |d W Y dS d}~X Y nX |D ]}| j| qt|D ]}|rz&| jrt	
| j| n| j| W nP ttfk
r    Y n8 tk
r
 } z| |d W Y  dS d}~X Y nX q|    qqdS )zXCalled when some SSL data is received.

        The argument is a bytes object.
        NzSSL error in data receivedz/application protocol failed to receive SSL data)r   r(   
SystemExitKeyboardInterruptBaseException_fatal_errorrb   r4   r   r   Z_feed_data_to_buffered_protorZ   data_receivedr]   )r   r?   r-   r.   er@   Zexr   r   r   r     s<    
  zSSLProtocol.data_receivedc                 C   sT   zB| j rtd|  | t | js@| j	
 }|r@td W 5 | j   X dS )a  Called when the other end of the low-level stream
        is half-closed.

        If this returns a false value (including None), the transport
        will close itself.  If it returns a true value, closing the
        transport is up to the protocol.
        z%r received EOFz?returning true from eof_received() has no effect when using sslN)rb   r^   rM   	get_debugr   debugr   ConnectionResetErrorr   rZ   eof_receivedZwarning)r   Z	keep_openr   r   r   r   -  s    


zSSLProtocol.eof_receivedc                 C   s4   || j kr| j | S | jd k	r,| j||S |S d S rV   )rx   rb   rU   rR   r   r   r   rQ   C  s
    


zSSLProtocol._get_extra_infoc                 C   s.   | j r
d S | jr|   nd| _ | d d S )NTr$   )r   r   rq   rn   r   r   r   r   r]   K  s    
zSSLProtocol._start_shutdownc                 C   s.   | j |df |  jt|7  _|   d S )Nr   )r{   r7   r|   r)   _process_write_backlogro   r   r   r   rn   T  s    zSSLProtocol._write_appdatac                 C   s\   | j  r$td|  | j  | _nd | _d| _| jd | j 	| j
| j| _|   d S )Nz%r starts SSL handshakeT)r$   r   )rM   r   r   r   time_handshake_start_timer   r{   r7   Z
call_laterr   _check_handshake_timeoutr   r   r   r   r   r   r   Y  s    

zSSLProtocol._start_handshakec                 C   s*   | j dkr&d| j d}| t| d S )NTz$SSL handshake is taking longer than z! seconds: aborting the connection)r   r   r   ConnectionAbortedError)r   msgr   r   r   r   h  s    
z$SSLProtocol._check_handshake_timeoutc              
   C   s  d| _ | j  | jj}z|d k	r&|| }W nb ttfk
rJ    Y nJ tk
r } z,t	|t
jrld}nd}| || W Y d S d }~X Y nX | j r| j | j }td| |d  | jj|| | |d | jr| j| j |   d| _| j| j d S )NFz1SSL handshake failed on verifying the certificatezSSL handshake failedz%r: SSL handshake took %.1f msg     @@)peercertciphercompressionr    T)r   r   r   r   r    Zgetpeercertr   r   r   ri   r	   r9   r   rM   r   r   r   r   r   rx   updater   r   r   rZ   r   r~   r   r   r   r   )r   Zhandshake_excZsslobjr   rA   r   Zdtr   r   r   _on_handshake_completeq  s8    

z"SSLProtocol._on_handshake_completec              
   C   sP  | j d ks| jd krd S ztt| jD ]}| jd \}}|rR| j||\}}n*|rj| j| j}d}n| j| j	}d}|D ]}| j 
| q|t|k r||f| jd< | jjst| j jr| j    q| jd= |  jt|8  _q(W n^ ttfk
r    Y nD tk
rJ } z$| jr.| | n| |d W 5 d }~X Y nX d S )Nr   r   zFatal error on SSL transport)rb   r   ranger)   r{   rF   r/   r   r1   	_finalizer4   r!   r*   Z_pausedre   r|   r   r   r   r   r   )r   ir?   rE   r-   r@   rA   r   r   r   r     s<    
z"SSLProtocol._process_write_backlogFatal error on transportc                 C   sV   t |tr(| j r@tjd| |dd n| j||| j| d | jrR| j| d S )Nz%r: %sT)exc_info)messageZ	exceptionr   rX   )	ri   OSErrorrM   r   r   r   Zcall_exception_handlerrb   Z_force_close)r   rA   r   r   r   r   r     s    

zSSLProtocol._fatal_errorc                 C   s   d | _ | jd k	r| j  d S rV   )r   rb   r^   r   r   r   r   r     s    
zSSLProtocol._finalizec                 C   s(   z| jd k	r| j  W 5 |    X d S rV   )r   rb   rr   r   r   r   r   rq     s    
zSSLProtocol._abort)FNTN)N)N)r   )rG   rH   rI   rJ   r   rW   r   r   r   r   r   r   r   rQ   r]   rn   r   r   r   r   r   r   rq   r   r   r   r   ru     s0        
.

&
		)+
ru   )ry   rs   r	   ImportError r   r   r   r   logr   r   r   r'   r"   r0   objectr   Z_FlowControlMixinZ	TransportrL   ZProtocolru   r   r   r   r   <module>   s*   
 yx