a
    h;                     @  s  U d dl mZ d dlZd dlZd dlZd dlZd dlmZmZ d dl	m
Z
 d dlmZ d dlmZ d dlmZmZ dd	lmZmZmZmZmZ dd
lmZmZ ddlmZmZmZmZmZm Z  ej!dkrd dlm"Z" nd dl#m"Z" ej!dkrd dlm$Z$m%Z% nd dl#m$Z$m%Z% ej!dkr(d dlm&Z& nd dl#m&Z& edZ'e$dZ(e)e)e*e*f df Z+de,d< e)e+df Z-de,d< G dd deZ.e
ddG dd deZ/e
ddG dd dee/ Z0G d d! d!eZ1dS )"    )annotationsN)CallableMapping)	dataclass)wraps)
SSLContext)AnyTypeVar   )BrokenResourceErrorEndOfStreamaclose_forcefullyget_cancelled_exc_class	to_thread)TypedAttributeSettyped_attribute)AnyByteStreamAnyByteStreamConnectable
ByteStreamByteStreamConnectableListener	TaskGroup)   
   )	TypeAlias)r      )TypeVarTupleUnpack)r      )overrideT_RetvalPosArgsT.r   _PCTRTT_PCTRTTTc                   @  s   e Zd ZU dZe Zded< e Zded< e Zded< e Z	ded	< e Z
d
ed< e Zded< e Zded< e Zded< e Zded< e Zded< dS )TLSAttributez5Contains Transport Layer Security related attributes.
str | Nonealpn_protocolbyteschannel_binding_tls_uniqueztuple[str, str, int]cipherz*None | dict[str, str | _PCTRTTT | _PCTRTT]peer_certificatezbytes | Nonepeer_certificate_binaryboolserver_sidez!list[tuple[str, str, int]] | Noneshared_ciphersssl.SSLObject
ssl_objectstandard_compatiblestrtls_versionN)__name__
__module____qualname____doc__r   r&   __annotations__r(   r)   r*   r+   r-   r.   r0   r1   r3    r9   r9   M/var/www/html/assistant/venv/lib/python3.9/site-packages/anyio/streams/tls.pyr$   3   s   
r$   F)eqc                	   @  s   e Zd ZU dZded< ded< ded< ded	< ded
< eddddddddddd dddZddddddZddddZdddd Z	d/d"d#d$d%d&Z
d#dd'd(d)Zddd*d+Zed,dd-d.ZdS )0	TLSStreama  
    A stream wrapper that encrypts all sent data and decrypts received data.

    This class has no public initializer; use :meth:`wrap` instead.
    All extra attributes from :class:`~TLSAttribute` are supported.

    :var AnyByteStream transport_stream: the wrapped stream

    r   transport_streamr,   r1   r/   _ssl_objectzssl.MemoryBIO	_read_bio
_write_bioNT)r-   hostnamessl_contextr1   zbool | Noner%   ssl.SSLContext | None)r=   r-   rA   rB   r1   returnc                  s   |du r| }|sL|rt jjnt jj}t |}tt drL| jt j M  _t  }t  }t	|t j
u r~|j||||d}	nt|j||||dI dH }	| |||	||d}
|
|	jI dH  |
S )a  
        Wrap an existing stream with Transport Layer Security.

        This performs a TLS handshake with the peer.

        :param transport_stream: a bytes-transporting stream to wrap
        :param server_side: ``True`` if this is the server side of the connection,
            ``False`` if this is the client side (if omitted, will be set to ``False``
            if ``hostname`` has been provided, ``False`` otherwise). Used only to create
            a default context when an explicit context has not been provided.
        :param hostname: host name of the peer (if host name checking is desired)
        :param ssl_context: the SSLContext object to use (if not provided, a secure
            default will be created)
        :param standard_compatible: if ``False``, skip the closing handshake when
            closing the connection, and don't raise an exception if the peer does the
            same
        :raises ~ssl.SSLError: if the TLS handshake fails

        NOP_IGNORE_UNEXPECTED_EOF)r-   server_hostname)r=   r1   r>   r?   r@   )sslPurposeCLIENT_AUTHSERVER_AUTHcreate_default_contexthasattroptionsrE   	MemoryBIOtyper   wrap_bior   Zrun_sync_call_sslobject_methoddo_handshake)clsr=   r-   rA   rB   r1   purposeZbio_inZbio_outr0   wrapperr9   r9   r:   wrapa   s>    


	zTLSStream.wrapz&Callable[[Unpack[PosArgsT]], T_Retval]zUnpack[PosArgsT]r    )funcargsrD   c                   s  z|| }W n t jy   z4| jjr@| j| j I d H  | j I d H }W nX tyn   | j	
  Y nJ ty } z&| j	
  | j
  t|W Y d }~nd }~0 0 | j	| Y q  t jy   | j| j I d H  Y q  t jy& } z&| j	
  | j
  t|W Y d }~q d }~0  t jy } zZ| j	
  | j
  t|t jsn|jrd|jv r| jr~t|ntd  W Y d }~q d }~0 0 | jjr| j| j I d H  |S q d S )NZUNEXPECTED_EOF_WHILE_READING)rG   SSLWantReadErrorr@   pendingr=   sendreadreceiver   r?   	write_eofOSErrorr   writeSSLWantWriteErrorSSLSyscallErrorSSLError
isinstanceSSLEOFErrorstrerrorr1   )selfrW   rX   resultdataexcr9   r9   r:   rQ      sF    






z TLSStream._call_sslobject_methodztuple[AnyByteStream, bytes]rD   c                   s8   |  | jjI dH  | j  | j  | j| j fS )z
        Does the TLS closing handshake.

        :return: a tuple of (wrapped byte stream, bytes left in the read buffer)

        N)rQ   r>   unwrapr?   r^   r@   r=   r\   rg   r9   r9   r:   rl      s    

zTLSStream.unwrapNonec                   sR   | j r>z|  I d H  W n$ ty<   t| jI d H   Y n0 | j I d H  d S N)r1   rl   BaseExceptionr   r=   acloserm   r9   r9   r:   rq      s    zTLSStream.aclose   intr'   )	max_bytesrD   c                   s"   |  | jj|I d H }|st|S ro   )rQ   r>   r\   r   )rg   rt   ri   r9   r9   r:   r]      s    zTLSStream.receive)itemrD   c                   s   |  | jj|I d H  d S ro   )rQ   r>   r`   )rg   ru   r9   r9   r:   r[      s    zTLSStream.sendc                   sd   |  tj}td|}|rXt|dt|dp6d }}||fdk rXtd| tdd S )NzTLSv(\d+)(?:\.(\d+))?   r
   r   )rv   r   z;send_eof() requires at least TLSv1.3; current session uses z7send_eof() has not yet been implemented for TLS streams)extrar$   r3   rematchrs   groupNotImplementedError)rg   r3   ry   majorminorr9   r9   r:   send_eof   s    "zTLSStream.send_eofMapping[Any, Callable[[], Any]]c                   s   i  j jtj jjtj jjtj jjtj	 fddtj
 fddtj fddtj fddtj fddtj fddtj jji
S )Nc                     s    j dS )NFr>   getpeercertr9   rm   r9   r:   <lambda>      z,TLSStream.extra_attributes.<locals>.<lambda>c                     s    j dS )NTr   r9   rm   r9   r:   r     s   c                     s    j jS ro   )r>   r-   r9   rm   r9   r:   r     r   c                     s    j jr j  S d S ro   )r>   r-   r.   r9   rm   r9   r:   r     s    c                     s    j S ro   r1   r9   rm   r9   r:   r     r   c                     s    j S ro   )r>   r9   rm   r9   r:   r     r   )r=   extra_attributesr$   r&   r>   selected_alpn_protocolr(   get_channel_bindingr)   r*   r+   r-   r.   r1   r0   r3   versionrm   r9   rm   r:   r     s    


zTLSStream.extra_attributes)rr   )r4   r5   r6   r7   r8   classmethodrV   rQ   rl   rq   r]   r[   r~   propertyr   r9   r9   r9   r:   r<   O   s(   

F.
r<   c                   @  s   e Zd ZU dZded< ded< dZded< d	Zd
ed< eddddddZdddddddZ	ddddZ
eddddZdS )TLSListenera  
    A convenience listener that wraps another listener and auto-negotiates a TLS session
    on every accepted connection.

    If the TLS handshake times out or raises an exception,
    :meth:`handle_handshake_error` is called to do whatever post-mortem processing is
    deemed necessary.

    Supports only the :attr:`~TLSAttribute.standard_compatible` extra attribute.

    :param Listener listener: the listener to wrap
    :param ssl_context: the SSL context object
    :param standard_compatible: a flag passed through to :meth:`TLSStream.wrap`
    :param handshake_timeout: time limit for the TLS handshake
        (passed to :func:`~anyio.fail_after`)
    zListener[Any]listenerzssl.SSLContextrB   Tr,   r1      floathandshake_timeoutrp   r   rn   )rj   streamrD   c                   sJ   t |I dH  t| t s.ttjd| d t| trDt| t rF dS )a  
        Handle an exception raised during the TLS handshake.

        This method does 3 things:

        #. Forcefully closes the original stream
        #. Logs the exception (unless it was a cancellation exception) using the
           ``anyio.streams.tls`` logger
        #. Reraises the exception if it was a base exception or a cancellation exception

        :param exc: the exception
        :param stream: the original stream

        NzError during TLS handshake)exc_info)r   rd   r   logging	getLoggerr4   	exception	Exception)rj   r   r9   r9   r:   handle_handshake_error4  s    
z"TLSListener.handle_handshake_errorNzCallable[[TLSStream], Any]zTaskGroup | None)handler
task_grouprD   c                   s6   t  ddd fdd}j||I d H  d S )Nr   rn   )r   rD   c              
     s   ddl m} zH|j* tj| jjdI d H }W d    n1 sH0    Y  W n6 ty } z|| I d H  W Y d }~nd }~0 0  |I d H  d S )Nr
   )
fail_after)rB   r1   )	 r   r   r<   rV   rB   r1   rp   r   )r   r   Zwrapped_streamrj   r   rg   r9   r:   handler_wrapperY  s    .(z*TLSListener.serve.<locals>.handler_wrapper)r   r   serve)rg   r   r   r   r9   r   r:   r   T  s    zTLSListener.serverk   c                   s   | j  I d H  d S ro   )r   rq   rm   r9   r9   r:   rq   k  s    zTLSListener.acloser   c                   s   t j fddiS )Nc                     s    j S ro   r   r9   rm   r9   r:   r   q  r   z.TLSListener.extra_attributes.<locals>.<lambda>)r$   r1   rm   r9   rm   r:   r   n  s    zTLSListener.extra_attributes)N)r4   r5   r6   r7   r8   r1   r   staticmethodr   r   rq   r   r   r9   r9   r9   r:   r     s   
" r   c                   @  sB   e Zd ZdZddddddddd	d
ddZeddddZdS )TLSConnectablea  
    Wraps another connectable and does TLS negotiation after a successful connection.

    :param connectable: the connectable to wrap
    :param hostname: host name of the server (if host name checking is desired)
    :param ssl_context: the SSLContext object to use (if not provided, a secure default
        will be created)
    :param standard_compatible: if ``False``, skip the closing handshake when closing
        the connection, and don't raise an exception if the server does the same
    NTrA   rB   r1   r   r%   rC   r,   rn   )connectablerA   rB   r1   rD   c                C  sN   || _ |pttjj| _t| jtjs>tdt	| jj
 || _|| _d S )Nz7ssl_context must be an instance of ssl.SSLContext, not )r   rG   rK   rH   rJ   rB   rd   r   	TypeErrorrO   r4   rA   r1   )rg   r   rA   rB   r1   r9   r9   r:   __init__  s    
zTLSConnectable.__init__r<   rk   c                   sX   | j  I d H }z tj|| j| j| jdI d H W S  tyR   t|I d H   Y n0 d S )Nr   )	r   connectr<   rV   rA   rB   r1   rp   r   )rg   r   r9   r9   r:   r     s    zTLSConnectable.connect)r4   r5   r6   r7   r   r   r   r9   r9   r9   r:   r   u  s   r   )2
__future__r   r   rx   rG   syscollections.abcr   r   Zdataclassesr   	functoolsr   r   typingr   r	   r   r   r   r   r   r   Z_core._typedattrr   r   abcr   r   r   r   r   r   version_infor   Ztyping_extensionsr   r   r   r    r!   tupler2   r"   r8   r#   r$   r<   r   r   r9   r9   r9   r:   <module>   s@    	

 MX