U
    nËjÍ1  ã                   @  sP  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mZmZ ddl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 ejdkrÄd dlmZm Z  nd dl!mZm Z  edƒZ"edƒZ#eee$e$f df Z%ee%df Z&G dd„ deƒZ'e
dd�G dd„ deƒƒZ(e
dd�G dd„ dee( ƒƒZ)dS )é    )ÚannotationsN)ÚCallableÚMapping)Ú	dataclass)Úwraps)ÚAnyÚTupleÚTypeVaré   )ÚBrokenResourceErrorÚEndOfStreamÚaclose_forcefullyÚget_cancelled_exc_class)ÚTypedAttributeSetÚtyped_attribute)ÚAnyByteStreamÚ
ByteStreamÚListenerÚ	TaskGroup)é   é   )ÚTypeVarTupleÚUnpackÚT_RetvalÚPosArgsT.c                   @  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%   r'   r(   r*   © r0   r0   ú5/tmp/pip-unpacked-wheel-k8mofgf9/anyio/streams/tls.pyr       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#   r(   r&   Ú_ssl_objectzssl.MemoryBIOÚ	_read_bioÚ
_write_bioNT)r$   ÚhostnameÚssl_contextr(   zbool | Noner   zssl.SSLContext | None)r4   r$   r8   r9   r(   Úreturnc                Ã  s–   |dkr| }|sL|rt jjnt jj}t  |¡}tt dƒrL| jt j M  _t  ¡ }t  ¡ }|j	||||d�}	| |||	||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)r4   r(   r5   r6   r7   )ÚsslÚPurposeÚCLIENT_AUTHÚSERVER_AUTHÚcreate_default_contextÚhasattrÚoptionsr;   Ú	MemoryBIOÚwrap_bioÚ_call_sslobject_methodÚdo_handshake)Úclsr4   r$   r8   r9   r(   ÚpurposeZbio_inZbio_outr'   Úwrapperr0   r0   r1   ÚwrapN   s2    ÿ

   ÿûzTLSStream.wrapz&Callable[[Unpack[PosArgsT]], T_Retval]zUnpack[PosArgsT]r   )ÚfuncÚargsr:   c                 Ç  sÈ  z||Ž }W �nŒ t jk
r¾   z4| jjrB| j | j ¡ ¡I d H  | j ¡ I d H }W nX tk
rr   | j	 
¡  Y nH tk
r¬ } z| j	 
¡  | j 
¡  t|‚W 5 d }~X Y nX | j	 |¡ Y q  t jk
rê   | j | j ¡ ¡I d H  Y q  t jk
�r( } z| j	 
¡  | j 
¡  t|‚W 5 d }~X Y q  t jk
�rš } zR| j	 
¡  | j 
¡  t|t jƒ�sr|j�rˆd|jk�rˆ| j�r‚t|‚ntd ‚‚ W 5 d }~X Y q X | jj�r¾| j | j ¡ ¡I d H  |S q d S )NZUNEXPECTED_EOF_WHILE_READING)r=   ÚSSLWantReadErrorr7   Úpendingr4   ÚsendÚreadÚreceiver   r6   Ú	write_eofÚOSErrorr   ÚwriteÚSSLWantWriteErrorÚSSLSyscallErrorÚSSLErrorÚ
isinstanceÚSSLEOFErrorÚstrerrorr(   )ÚselfrL   rM   ÚresultÚdataÚexcr0   r0   r1   rF   ‡   sF    





ÿÿ
z TLSStream._call_sslobject_methodztuple[AnyByteStream, bytes]©r:   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)rF   r5   Úunwrapr6   rS   r7   r4   rQ   ©r\   r0   r0   r1   ra   µ   s    

zTLSStream.unwrapÚNonec                 Ã  sT   | j r@z|  ¡ I d H  W n& tk
r>   t| jƒI d H  ‚ Y nX | j ¡ I d H  d S ©N)r(   ra   ÚBaseExceptionr   r4   Úacloserb   r0   r0   r1   rf   Á   s    zTLSStream.acloseé   Úintr   )Ú	max_bytesr:   c                 Ã  s"   |   | jj|¡I d H }|st‚|S rd   )rF   r5   rQ   r   )r\   ri   r^   r0   r0   r1   rR   Ë   s    zTLSStream.receive)Úitemr:   c                 Ã  s   |   | jj|¡I d H  d S rd   )rF   r5   rU   )r\   rj   r0   r0   r1   rP   Ò   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   )rk   r   z;send_eof() requires at least TLSv1.3; current session uses z7send_eof() has not yet been implemented for TLS streams)Úextrar   r*   ÚreÚmatchrh   ÚgroupÚNotImplementedError)r\   r*   rn   ÚmajorÚminorr0   r0   r1   Úsend_eofÕ   s    "ÿÿzTLSStream.send_eofúMapping[Any, Callable[[], Any]]c                   sˆ   ˆ 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©r5   Úgetpeercertr0   rb   r0   r1   Ú<lambda>í   ó    z,TLSStream.extra_attributes.<locals>.<lambda>c                     s   ˆ j  d¡S )NTru   r0   rb   r0   r1   rw   î   s   ÿc                     s   ˆ j jS rd   )r5   r$   r0   rb   r0   r1   rw   ñ   rx   c                     s   ˆ j jrˆ j  ¡ S d S rd   )r5   r$   r%   r0   rb   r0   r1   rw   ò   s    ÿc                     s   ˆ j S rd   ©r(   r0   rb   r0   r1   rw   õ   rx   c                     s   ˆ j S rd   )r5   r0   rb   r0   r1   rw   ö   rx   )r4   Úextra_attributesr   r   r5   Úselected_alpn_protocolr   Úget_channel_bindingr    r!   r"   r$   r%   r(   r'   r*   Úversionrb   r0   rb   r1   rz   ä   s,       
 
 
 
 
 
 ïzTLSStream.extra_attributes)rg   )r+   r,   r-   r.   r/   ÚclassmethodrK   rF   ra   rf   rR   rP   rs   Úpropertyrz   r0   r0   r0   r1   r3   <   s(   

ù8.
r3   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.SSLContextr9   Tr#   r(   é   ÚfloatÚhandshake_timeoutre   r   rc   )r_   Ústreamr:   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   rY   r   ÚloggingÚ	getLoggerr+   Ú	exceptionÚ	Exception)r_   r…   r0   r0   r1   Úhandle_handshake_error  s    
 ÿz"TLSListener.handle_handshake_errorNzCallable[[TLSStream], Any]zTaskGroup | None)ÚhandlerÚ
task_groupr:   c                 ƒ  s6   t ˆ ƒdddœ‡ ‡fdd„ƒ}ˆj ||¡I d H  d S )Nr   rc   )r…   r:   c              
   “  sˆ   ddl m} z4|ˆjƒ�  tj| ˆjˆjd�I d H }W 5 Q R X W n4 tk
rt } zˆ || ¡I d H  W 5 d }~X Y nX ˆ |ƒI d H  d S )Nr
   )Ú
fail_after)r9   r(   )	Ú rŽ   r„   r3   rK   r9   r(   re   r‹   )r…   rŽ   Zwrapped_streamr_   ©rŒ   r\   r0   r1   Úhandler_wrapper8  s    ý$z*TLSListener.serve.<locals>.handler_wrapper)r   r�   Úserve)r\   rŒ   r�   r‘   r0   r�   r1   r’   3  s    zTLSListener.server`   c                 Ã  s   | j  ¡ I d H  d S rd   )r�   rf   rb   r0   r0   r1   rf   J  s    zTLSListener.aclosert   c                   s   t j‡ fdd„iS )Nc                     s   ˆ j S rd   ry   r0   rb   r0   r1   rw   P  rx   z.TLSListener.extra_attributes.<locals>.<lambda>)r   r(   rb   r0   rb   r1   rz   M  s     
ÿzTLSListener.extra_attributes)N)r+   r,   r-   r.   r/   r(   r„   Ústaticmethodr‹   r’   rf   r   rz   r0   r0   r0   r1   r€   û   s   
" ýr€   )*Ú
__future__r   r‡   rm   r=   ÚsysÚcollections.abcr   r   Zdataclassesr   Ú	functoolsr   Útypingr   r   r	   r�   r   r   r   r   Z_core._typedattrr   r   Úabcr   r   r   r   Úversion_infor   r   Ztyping_extensionsr   r   r)   Z_PCTRTTZ_PCTRTTTr   r3   r€   r0   r0   r0   r1   Ú<module>   s0   
 ?