o
    US`c                     @   sF  d dl Z d dlZd dlZd dlZd dlmZ d dl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Zdd Zdd Zd	d
 ZG dd dejZG dd dejZG dd dZdZG dd deZdd Zdd Ze dZdedefddZe	j G dd dZ!dd  Z"d!d" Z#e d#Z$e	j G d$d% d%Z%d&d' Z&d(d) Z'd*d+ Z(e	j G d,d- d-Z)e	j G d.d/ d/Z*e	j G d0d1 d1Z+d2d3 Z,G d4d5 d5Z-d6Z.d7Z/d8Z0d9Z1d7Z2d:d; Z3d<d= Z4d>d? Z5d@dA Z6dBdC Z7G dDdE dEZ8dFdG Z9dHdI Z:dJdK Z;e	j G dLdM dMZ<G dNdO dOe
j=j>e edPZ?G dQdR dRedPZ@dS )S    N)count)NoPublicConstructorFinali  c                 C   s   | j tjjkr	dS dS )N   0   )familytriosocketAF_INETsock r   5/usr/local/lib/python3.10/dist-packages/trio/_dtls.pypacket_header_overhead   s   r   c                 C   s&   | j tjjkrdt|  S dt|  S )Ni@  i   )r   r   r	   r
   r   r   r   r   r   worst_case_mtu!   s   r   c                 C   s   dt |  S )Ni  )r   r   r   r   r   best_guess_mtu(      r   c                   @   s    e Zd ZdZdZdZdZdZdS )ContentType               N)__name__
__module____qualname__change_cipher_specalert	handshakeZapplication_data	heartbeatr   r   r   r   r   /   s    r   c                   @   s`   e Zd ZdZdZdZdZdZdZdZ	dZ
dZd	Zd
ZdZdZdZdZdZdZdZdZdZdZdS )HandshakeTyper                                    r   r   r   r   r            N)r   r   r   Zhello_requestclient_helloZserver_hellohello_verify_requestZnew_session_ticketZend_of_early_dataZencrypted_extensionsZcertificateZserver_key_exchangeZcertificate_requestZserver_hello_doneZcertificate_verifyZclient_key_exchangefinishedZcertificate_urlZcertificate_statusZsupplemental_dataZ
key_updateZcompressed_certificateZekt_keyZmessage_hashr   r   r   r   r    7   s,    r    c                   @   s$   e Zd ZeddgZeddgZdS )ProtocolVersionr.         N)r   r   r   bytesDTLS10ZDTLS12r   r   r   r   r2   O   s    r2   l          c                   @   s   e Zd ZdS )	BadPacketN)r   r   r   r   r   r   r   r7   \   s    r7   c                 C   s   | dd dkS )Nr#      s     r   packetr   r   r   part_of_handshake_untrustedf   s   r;   c                 C   s4   z| d t jko| d tjkW S  ty   Y dS w )Nr   r(   F)r   r   r    r/   
IndexErrorr9   r   r   r   is_client_hello_untrustedm   s   r=   z!B2sQHdatareturnc                 C   s   |   S N)hex)r>   r   r   r   to_hex   s   rB   c                   @   sF   e Zd ZU eed< ejedZe	ed< eed< ejedZ
e	ed< dS )Recordcontent_typereprversionepoch_seqnopayloadN)r   r   r   int__annotations__attribrB   rG   r5   rI   r   r   r   r   rC      s
   
 rC   c              
   c   s    d}|t | k rSzt| |\}}}}W n tjy' } ztd|d }~ww |tj7 }| |||  }t ||kr?td||7 }t||||V  |t | k s	d S d S )Nr   zinvalid record headerzshort record)lenRECORD_HEADERunpack_fromstructerrorr7   sizerC   )r:   ictrG   rH   Zpayload_lenexcrI   r   r   r   records_untrusted   s    

rW   c                 C   s&   t | j| j| jt| j}|| j S r@   )rO   packrD   rG   rH   rN   rI   )recordheaderr   r   r   encode_record   s   
r[   z	!B3sH3s3sc                   @   sJ   e Zd ZU eed< eed< eed< eed< eed< ejedZe	ed< dS )	HandshakeFragmentmsg_typemsg_lenmsg_seqfrag_offsetfrag_lenrE   fragN)
r   r   r   rJ   rK   rL   rM   rB   rb   r5   r   r   r   r   r\      s   
 r\   c              
   C   s   zt | \}}}}}W n tjy } ztd|d }~ww t|d}t|d}t|d}	| t jd  }
t|
|	krBtdt	|||||	|
S )Nzbad handshake message headerbigz5handshake fragment length doesn't match record length)
HANDSHAKE_MESSAGE_HEADERrP   rQ   rR   r7   rJ   
from_bytesrS   rN   r\   )rI   r]   msg_len_bytesr_   frag_offset_bytesfrag_len_bytesrV   r^   r`   ra   rb   r   r   r   #decode_handshake_fragment_untrusted   s4   
ri   c              
   C   s>   t | j| jdd| j| jdd| jdd}|| j S )Nr#   rc   )	rd   rX   r]   r^   to_bytesr_   r`   ra   rb   )ZhsfZ	hs_headerr   r   r   encode_handshake_fragment   s   
rk   c              
   C   s  znt t| }|jtjkrtdt|j}|jt	j
kr td|jdkr)td|j|jkr3td|j}|d }d| }|| }|d }|| }|d | }	||| }
||d  }t|
|krftd|j|
|	| fW S  tjtfy } ztd	|d }~ww )
Nznot a handshake recordznot a ClientHellor   zfragmented ClientHello"   #   r!   zshort cookiezbad ClientHello)nextrW   rD   r   r   r7   ri   rI   r]   r    r/   r`   ra   r^   rb   rN   rH   rQ   rR   r<   )r:   rY   fragmentbodyZsession_id_lenZcookie_len_offsetZ
cookie_lenZcookie_startZ
cookie_endZbefore_cookiecookieZafter_cookierV   r   r   r   decode_client_hello_untrusted   s6   


rr   c                   @   sF   e Zd ZU ejedZeed< e	ed< e
ed< ejedZeed< dS )HandshakeMessagerE   record_versionr]   r_   rp   N)r   r   r   rL   rM   rB   rt   r5   rK   r    rJ   rp   	bytearrayr   r   r   r   rs   -  s
   
 rs   c                   @   s>   e Zd ZU ejedZeed< e	ed< ejedZ
eed< dS )PseudoHandshakeMessagerE   rt   rD   rI   N)r   r   r   rL   rM   rB   rt   r5   rK   rJ   rI   r   r   r   r   rv   7  s   
 rv   c                   @      e Zd ZU eed< dS )OpaqueHandshakeMessagerY   N)r   r   r   rC   rK   r   r   r   r   rx   C     
 rx   c                 C   s  g }i }t | D ]}|jt@ r|t| q|jtjtjfv r-|t	|j
|j|j q|jtjks5J t|j}t|j}|j|vr[t|j
||jt|j}|| |||j< n||j }|j|jkshJ |j|jkspJ t|j|jkszJ |j|j|j|j|j < q|S r@   )rW   rH   
EPOCH_MASKappendrx   rD   r   r   r   rv   rG   rI   r   ri   r    r]   r_   rs   ru   r^   rN   rp   rb   r`   ra   )ZvolleymessagesZmessages_by_seqrY   ro   r]   msgr   r   r   decode_volley_trustedL  s@   





r~   c                   @   s$   e Zd Zdd Zdd Zdd ZdS )RecordEncoderc                 C   s   t  | _d S r@   r   _record_seqselfr   r   r   __init__y  r   zRecordEncoder.__init__c                 C   s   t || _d S r@   r   )r   nr   r   r   set_first_record_number|  s   z%RecordEncoder.set_first_record_numberc              
   C   s  g }t  }|D ]}t|tr4t|j}|t| t| dkr'|| t  }||7 }t||ks3J qt|trs|t| tj	 t|j
 }|dkrS|| t  }|t|j|jt| jt|j
7 }||j
7 }t||ksrJ qt|jdd}d}	d}
|	t|jk s|
s|t| tj	 tj	 }|dkr|| t  }q|j|	|	|  }|	dd}t|dd}|	t|7 }	|ttj|jt| jtj	t| 7 }|t|j||j||7 }||7 }|
d7 }
t||ksJ |	t|jk s|
rq|r|| |S )Nr   r#   rc   r!   )ru   
isinstancerx   r[   rY   rN   r{   rv   rO   rS   rI   rX   rD   rt   rn   r   rp   rj   rd   r   r   r]   r_   )r   r|   Zmtupacketsr:   messageencodedspacerf   r`   Zfrags_encodedrb   rg   rh   r   r   r   encode_volley  s   






$
zRecordEncoder.encode_volleyN)r   r   r   r   r   r   r   r   r   r   r   x  s    r          sha256r%   c                   C   s   t t t S r@   )rJ   r   current_timeCOOKIE_REFRESH_INTERVALr   r   r   r   _current_cookie_tick  s   r   c                  G   s8   g }| D ]}| tdt| | | qd|S )N!Q    )r{   rQ   rX   rN   join)fieldsoutfieldr   r   r   	_signable	  s
   
r   c                 C   s^   t |tksJ t | tksJ t|td|tdd |D  |}|t| |t d t	 S )Nr   c                 s   s    | ]	}t | V  qd S r@   )strencode).0partr   r   r   	<genexpr>  s    z_make_cookie.<locals>.<genexpr>)
rN   
SALT_BYTES	KEY_BYTESr   rQ   rX   hmacdigestCOOKIE_HASHCOOKIE_LENGTH)keysalttickaddressclient_hello_bitsZsignable_datar   r   r   _make_cookie  s   
	r   c                 C   sd   t |tkr0|d t }t }t| ||||}t| |t|d d||}t||t||B S dS )Nr!   r   F)rN   r   r   r   maxr   compare_digest)r   rq   r   r   r   r   Z
cur_cookieZ
old_cookier   r   r   valid_cookie!  s   r   c                 C   sx   t t}t }t| ||||}tjtt|g | }t	t
jt|ddt||d}t|}	tttjtj||	}
|
S )Nr   )r]   r^   r_   r`   ra   rb   )osurandomr   r   r   r2   r6   r5   rN   r\   r    r0   rk   r[   rC   r   r   )r   r   rH   r   r   r   rq   rp   hsrI   r:   r   r   r   challenge_for5  s"   
r   c                   @   s   e Zd Zdd ZdS )_Queuec                 C   s   t |\| _| _d S r@   )r   Zopen_memory_channelsr)r   incoming_packets_bufferr   r   r   r   ^  s   z_Queue.__init__N)r   r   r   r   r   r   r   r   r   ]  s    r   c                 C   s>   g }	 z| d}W n
 t jy   Y nw || qd|S )NTi @  r   )SSLWantReadErrorr{   r   )Zread_fnchunkschunkr   r   r   
_read_loopb  s   

r   c           	   	      s  | j d u rd S z	t|\}}}W n
 ty   Y d S w | jd u r'tt| _t| j|||sqt| j|||}z,| j	4 I d H  | j
||I d H  W d   I d H  W d S 1 I d H s\w   Y  W d S  ttjfyp   Y d S w t| || j }|j| z|j| |j  W n tjy   Y d S w |j| | j|}|d ur|j||fkrd S |  ||f|_|| j|< | jj| d S r@   )_listening_contextrr   r7   _listening_keyr   r   r   r   r   
_send_lockr	   sendtoOSErrorr   ClosedResourceErrorDTLSChannel_create_record_encoderr   _ssl	bio_writeZDTLSv1_listenr   Error_streamsget_client_hello_set_replaced_incoming_connections_qr   send_nowait)	endpointr   r:   rH   rq   bitsZchallenge_packetstreamZ
old_streamr   r   r   handle_client_hello_untrustedm  sL   


2	

r   c              
      sL  z}	 z| tI d H \}}W n ty( } z|jtjkr#W Y d }~q d }~ww |  }zO|d u r6W ~W d S t|rDt|||I d H  n5||jv rx|j| }|jr]t	|r]|
 I d H  nz	|jj| W n tjyw   | jd7  _Y nw 	 W ~n~w q tjy   Y d S  ty } z|jtjtjfv rW Y d }~d S  d }~ww )NTr!   )recvfromMAX_UDP_PACKET_SIZEr   errno
ECONNRESETr=   r   r   _did_handshaker;   _resend_final_volley_qr   r   r   Z
WouldBlock_packets_dropped_in_trior   EBADFENOTSOCK)Zendpoint_refr   r:   r   rV   r   r   r   r   r   dtls_receive_loop  sN   

)r   c                   @   rw   )DTLSChannelStatisticsZ incoming_packets_dropped_in_trioN)r   r   r   rJ   rK   r   r   r   r   r     ry   r   c                   @   s   e Zd ZdZdd Zdd Zdd Zdd	 Zd
d Zdd Z	dd Z
dd Zdd ZddddZdd Zdd Zdd Zdd Zd d! Zd"S )#r   u`  A DTLS connection.

    This class has no public constructor – you get instances by calling
    `DTLSEndpoint.serve` or `~DTLSEndpoint.connect`.

    .. attribute:: endpoint

       The `DTLSEndpoint` that this connection is using.

    .. attribute:: peer_address

       The IP/port of the remote peer that this connection is associated with.

    c                 C   s   || _ || _d| _d | _d| _|tjtjB  t	|| _
d | _| t| j j d| _d| _t|j| _t | _t | _d S )Nr   F)r   peer_addressr   r   r   Zset_optionsr   ZOP_NO_QUERY_MTUOP_NO_RENEGOTIATION
Connectionr   _handshake_mtuset_ciphertext_mtur   r	   	_replaced_closedr   r   r   r   Lock_handshake_lockr   r   )r   r   r   ctxr   r   r   r     s   
zDTLSChannel.__init__c                 C   s   d| _ | jj  d S NT)r   r   r   closer   r   r   r   r     s   zDTLSChannel._set_replacedc                 C   s   | j rtdd S )Nz1peer tore down this connection to start a new one)r   r   ZBrokenResourceErrorr   r   r   r   _check_replaced  s
   zDTLSChannel._check_replacedc                 C   s@   | j rdS d| _ | jj| j| u r| jj| j= | jj  dS )u  Close this connection.

        `DTLSChannel`\s don't actually own any OS-level resources – the
        socket is owned by the `DTLSEndpoint`, not the individual connections. So
        you don't really *have* to call this. But it will interrupt any other tasks
        calling `receive` with a `ClosedResourceError`, and cause future attempts to use
        this connection to fail.

        You can also use this object as a synchronous or asynchronous context manager.

        NT)r   r   r   r   r   r   r   r   r   r   r   r   r   ,  s   zDTLSChannel.closec                 C      | S r@   r   r   r   r   r   	__enter__A     zDTLSChannel.__enter__c                 G      |    d S r@   r   r   argsr   r   r   __exit__D  r   zDTLSChannel.__exit__c                    s   |    tj I dH  dS )zClose this connection, but asynchronously.

        This is included to satisfy the `trio.abc.Channel` contract. It's
        identical to `close`, but async.

        N)r   r   lowlevel
checkpointr   r   r   r   acloseG  s   zDTLSChannel.aclosec              
      st   | j || j}|D ],}| jj4 I d H  | jj|| jI d H  W d   I d H  n1 I d H s2w   Y  qd S r@   )r   r   r   r   r   r	   r   r   )r   volley_messagesr   r:   r   r   r   _send_volleyQ  s   (zDTLSChannel._send_volleyc                    s   |  | jI d H  d S r@   )r   _final_volleyr   r   r   r   r   Y  s   z DTLSChannel._resend_final_volleyg      ?)initial_retransmit_timeoutc                   s*   j 4 I dH   jr	 W d  I dH  dS |}g d} fdd}z j  W n
 tjy6   Y nw | sAtd	 sFJ     I dH   j	
  t|} jj2 zl3 dH W } j| z j  W n tjtjfy   Y n#w d _|  _  jI dH   W d   W d  I dH  dS | }|rt|d tr|d jtjkr |I dH  n||dkr|}d} nqa6  jsJ    W d   n1 sw   Y  |jrtd| d}|d	7 }|dkrt jt j	j _qB1 I dH sw   Y  dS )
u  Perform the handshake.

        Calling this is optional – if you don't, then it will be automatically called
        the first time you call `send` or `receive`. But calling it explicitly can be
        useful in case you want to control the retransmit timeout, use a cancel scope to
        place an overall timeout on the handshake, or catch errors from the handshake
        specifically.

        It's safe to call this multiple times, or call it simultaneously from multiple
        tasks – the first call will perform the handshake, and the rest will be no-ops.

        Args:

          initial_retransmit_timeout (float): Since UDP is an unreliable protocol, it's
            possible that some of the packets we send during the handshake will get
            lost. To handle this, DTLS uses a timer to automatically retransmit
            handshake packets that don't receive a response. This lets you set the
            timeout we use to detect packet loss. Ideally, it should be set to ~1.5
            times the round-trip time to your peer, but 1 second is a reasonable
            default. There's `some useful guidance here
            <https://tlswg.org/dtls13-spec/draft-ietf-tls-dtls13.html#name-timer-values>`__.

            This is the *initial* timeout, because if packets keep being lost then Trio
            will automatically back off to longer values, to avoid overloading the
            network.

        Nr   c                     sF   t  jj} t| }|r!r!t|d tr!|d jd jkr!g S |S )Nr   )r   r   bio_readr~   r   rs   r_   )Zvolley_bytesZnew_volley_messagesr   r   r   r   read_volley  s   z-DTLSChannel.do_handshake.<locals>.read_volleyz'something wrong with peer's ClientHelloTr"   g      N@r!   )r   r   r   do_handshaker   r   r   r   r   r   _ensure_receive_loopr   Zmove_on_afterr   r   r   r   r   rv   rD   r   r   r   Zcancelled_caughtminr   r   r	   )r   r   timeoutZvolley_failed_sendsr   Zcscoper:   Zmaybe_volleyr   r   r   r   \  s|   

>
),
zDTLSChannel.do_handshakec              	      s   | j rtj|std| js|  I dH  |   | j| | j	j
4 I dH  | j	jt| jj| jI dH  W d  I dH  dS 1 I dH sKw   Y  dS )z Send a packet of data, securely.z2openssl doesn't support sending empty DTLS packetsN)r   r   r   
ValueErrorr   r   r   r   writer   r   r	   r   r   r   r   )r   r>   r   r   r   send  s   .zDTLSChannel.sendc                    sx   | j s|  I dH  	 z| jj I dH }W n tjy*   | js$J |   Y nw | j	
| t| j	j}|r;|S q)a  Fetch the next packet of data from this connection's peer, waiting if
        necessary.

        This is safe to call from multiple tasks simultaneously, in case you have some
        reason to do that. And more importantly, it's cancellation-safe, meaning that
        cancelling a call to `receive` will never cause a packet to be lost or corrupt
        the underlying connection.

        N)r   r   r   r   receiver   ZEndOfChannelr   r   r   r   r   read)r   r:   Z	cleartextr   r   r   r    s   

zDTLSChannel.receivec                 C   s   || _ | j| dS )uj  Tells Trio the `largest amount of data that can be sent in a single packet to
        this peer <https://en.wikipedia.org/wiki/Maximum_transmission_unit>`__.

        Trio doesn't actually enforce this limit – if you pass a huge packet to `send`,
        then we'll dutifully encrypt it and attempt to send it. But calling this method
        does have two useful effects:

        - If called before the handshake is performed, then Trio will automatically
          fragment handshake messages to fit within the given MTU. It also might
          fragment them even smaller, if it detects signs of packet loss, so setting
          this should never be necessary to make a successful connection. But, the
          packet loss detection only happens after multiple timeouts have expired, so if
          you have reason to believe that a smaller MTU is required, then you can set
          this to skip those timeouts and establish the connection more quickly.

        - It changes the value returned from `get_cleartext_mtu`. So if you have some
          kind of estimate of the network-level MTU, then you can use this to figure out
          how much overhead DTLS will need for hashes/padding/etc., and how much space
          you have left for your application data.

        The MTU here is measuring the largest UDP *payload* you think can be sent, the
        amount of encrypted data that can be handed to the operating system in a single
        call to `send`. It should *not* include IP/UDP headers. Note that OS estimates
        of the MTU often are link-layer MTUs, so you have to subtract off 28 bytes on
        IPv4 and 48 bytes on IPv6 to get the ciphertext MTU.

        By default, Trio assumes an MTU of 1472 bytes on IPv4, and 1452 bytes on IPv6,
        which correspond to the common Ethernet MTU of 1500 bytes after accounting for
        IP/UDP overhead.

        N)r   r   r   )r   Znew_mtur   r   r   r     s    zDTLSChannel.set_ciphertext_mtuc                 C   s   | j stj| j S )zReturns the largest number of bytes that you can pass in a single call to
        `send` while still fitting within the network-level MTU.

        See `set_ciphertext_mtu` for more details.

        )r   r   ZNeedHandshakeErrorr   get_cleartext_mtur   r   r   r   r  +  s   
zDTLSChannel.get_cleartext_mtuc                 C   s
   t | jS )a  Returns an object with statistics about this connection.

        Currently this has only one attribute:

        - ``incoming_packets_dropped_in_trio`` (``int``): Gives a count of the number of
          incoming packets from this peer that Trio successfully received from the
          network, but then got dropped because the internal channel buffer was full. If
          this is non-zero, then you might want to call ``receive`` more often, or use a
          larger ``incoming_packets_buffer``, or just not worry about it because your
          UDP-based protocol should be able to handle the occasional lost packet, right?

        )r   r   r   r   r   r   
statistics6  s   
zDTLSChannel.statisticsN)r   r   r   __doc__r   r   r   r   r   r   r   r   r   r   r  r  r   r  r  r   r   r   r   r     s$    
 #r   )	metaclassc                   @   sf   e Zd ZdZddddZdd Zdd	 Zd
d Zdd Zdd Z	dd Z
ejdddZdd ZdS )DTLSEndpointa  A DTLS endpoint.

    A single UDP socket can handle arbitrarily many DTLS connections simultaneously,
    acting as a client or server as needed. A `DTLSEndpoint` object holds a UDP socket
    and manages these connections, which are represented as `DTLSChannel` objects.

    Args:
      socket: (trio.socket.SocketType): A ``SOCK_DGRAM`` socket. If you want to accept
        incoming connections in server mode, then you should probably bind the socket to
        some known port.
      incoming_packets_buffer (int): Each `DTLSChannel` using this socket has its own
        buffer that holds incoming packets until you call `~DTLSChannel.receive` to read
        them. This lets you adjust the size of this buffer. `~DTLSChannel.statistics`
        lets you check if the buffer has overflowed.

    .. attribute:: socket
                   incoming_packets_buffer

       Both constructor arguments are also exposed as attributes, in case you need to
       access them later.

    
   )r   c                C   s~   ddl ma d | _|jtjjkrtd|| _|| _tj	 | _
t | _d | _d | _ttd| _t | _d| _d| _d S )Nr   )r   z!DTLS requires a SOCK_DGRAM socketinfF)ZOpenSSLr   r	   typer   
SOCK_DGRAMr   r   r   Zcurrent_trio_token_tokenweakrefWeakValueDictionaryr   r   r   r   floatr   r   r   r   _receive_loop_spawned)r   r	   r   r   r   r   r   ^  s   


zDTLSEndpoint.__init__c                 C   s,   | j stjtt| | j d| _ d S d S r   )r  r   r   Zspawn_system_taskr   r  refr	   r   r   r   r   r   x  s   
z!DTLSEndpoint._ensure_receive_loopc                 C   sX   | j d u rd S | js*z	| j| j W n	 ty   Y nw tjd| t| d d S d S )Nzunclosed DTLS endpoint )source)	r	   r   r  Zrun_sync_soonr   RuntimeErrorwarningswarnResourceWarningr   r   r   r   __del__  s   

zDTLSEndpoint.__del__c                 C   s<   d| _ | j  t| j D ]}|  q| jj  dS )z}Close this socket, and all associated DTLS connections.

        This object can also be used as a context manager.

        TN)r   r	   r   listr   valuesr   r   )r   r   r   r   r   r     s
   

zDTLSEndpoint.closec                 C   r   r@   r   r   r   r   r   r     r   zDTLSEndpoint.__enter__c                 G   r   r@   r   r   r   r   r   r     r   zDTLSEndpoint.__exit__c                 C   s   | j rtjd S r@   )r   r   r   r   r   r   r   _check_closed  s   zDTLSEndpoint._check_closed)task_statusc             	      s   |    | jdurtdz| j  W n ty!   tdw |   |	dd  zJ|| _|
   fdd}t 4 I dH }| jj2 z3 dH W }||| qI6 W d  I dH  n1 I dH sgw   Y  W d| _dS W d| _dS d| _w )a  Listen for incoming connections, and spawn a handler for each using an
        internal nursery.

        Similar to `~trio.serve_tcp`, this function never returns until cancelled, or
        the `DTLSEndpoint` is closed and all handlers have exited.

        Usage commonly looks like::

            async def handler(dtls_channel):
                ...

            async with trio.open_nursery() as nursery:
                await nursery.start(dtls_endpoint.serve, ssl_context, handler)
                # ... do other things here ...

        The ``dtls_channel`` passed into the handler function has already performed the
        "cookie exchange" part of the DTLS handshake, so the peer address is
        trustworthy. But the actual cryptographic handshake doesn't happen until you
        start using it, giving you a chance for any last minute configuration, and the
        option to catch and handle handshake errors.

        Args:
          ssl_context (OpenSSL.SSL.Context): The PyOpenSSL context object to use for
            incoming connections.
          async_fn: The handler function that will be invoked for each incoming
            connection.

        Nz!another task is already listeningz-DTLS socket must be bound before it can servec                  W   s   dS r   r   )_r   r   r   <lambda>  s    z$DTLSEndpoint.serve.<locals>.<lambda>c                    sB   |  | g R  I d H  W d    d S 1 sw   Y  d S r@   r   )r   r   async_fnr   r   handler_wrapper  s   "z+DTLSEndpoint.serve.<locals>.handler_wrapper)r  r   r   ZBusyResourceErrorr	   getsocknamer   r  r   Zset_cookie_verify_callbackstartedZopen_nurseryr   r   Z
start_soon)r   ssl_contextr!  r  r   r"  Znurseryr   r   r   r   serve  s.   

*
zDTLSEndpoint.servec                 C   sJ   |    t| ||}|j  | j|}|dur|  || j|< |S )u  Initiate an outgoing DTLS connection.

        Notice that this is a synchronous method. That's because it doesn't actually
        initiate any I/O – it just sets up a `DTLSChannel` object. The actual handshake
        doesn't occur until you start using the `DTLSChannel`. This gives you a chance
        to do further configuration first, like setting MTU etc.

        Args:
          address: The address to connect to. Usually a (host, port) tuple, like
            ``("127.0.0.1", 12345)``.
          ssl_context (OpenSSL.SSL.Context): The PyOpenSSL context object to use for
            this connection.

        Returns:
          DTLSChannel

        N)r  r   r   r   Zset_connect_stater   r   r   )r   r   r%  ZchannelZold_channelr   r   r   connect  s   

zDTLSEndpoint.connectN)r   r   r   r  r   r   r  r   r   r   r  r   ZTASK_STATUS_IGNOREDr&  r'  r   r   r   r   r	  F  s    
8r	  )ArQ   r   r   enum	itertoolsr   r  r   r  rL   r   Z
trio._utilr   r   r   r   r   r   IntEnumr   r    r2   rz   	Exceptionr7   r;   r=   StructrO   r5   r   rB   frozenrC   rW   r[   rd   r\   ri   rk   rr   rs   rv   rx   r~   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   abcZChannelr   r	  r   r   r   r   <module>   s|   


	E	,|	(I7  V