U
    Rh^                     @  s  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Zd dlm	Z	 d dl
mZmZ d dlmZmZ d dlmZmZ d dlmZmZmZmZ dd	lmZ dd
lmZmZmZmZmZmZmZm Z m!Z! 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l,m-Z-m.Z. ej/dk r,d dl0m1Z1 e2eddZ3eej4ej5ej6f Z7eej5ej6f Z8edddddddddddddd d!d"Z9eddddd#dddd$dd%ddd d&d"Z9edddddd'dddd(ddd%ddd)	d*d"Z9edddddd'dddd+ddd%dd,d)	d-d"Z9eddd.ddddd,d/d0d"Z9dd1dd2dd3d4ddddddd%dd5d)	d6d"Z9d7d8d9d:d;Z:dd ejj4d<d1d=ddd>ddd?d@dAdBZ;dd<dCd7dDddEdFdGdHZ<ej4fdd d1dId>ddddJdKdLdMZ=ej4dd d1dNddd>ddddOdPdQdRZ>dddSdTdDdUdVdWdXZ?dddSd7dTdDdYdZd[d\Z@d d d d d]d^d_d`dadddbdcdddeZAdzdfddgdhdidjZBdkdldmdndoZCdkdldmdpdqZDdrdsdtdudvZEdTdDddkdwdxdyZFdS ){    )annotationsN)	Awaitable)IPv6Address
ip_address)PathLikechmod)AddressFamily
SocketKind)AnyLiteralcastoverload   )	to_thread)	ConnectedUDPSocketConnectedUNIXDatagramSocketIPAddressTypeIPSockAddrTypeSocketListenerSocketStream	UDPSocketUNIXDatagramSocketUNIXSocketStream)MultiListener)	TLSStream   )get_async_backend)aclose_forcefully)Event)create_task_groupmove_on_after)      )ExceptionGroupIPPROTO_IPV6)   .)
local_hostssl_contexttls_standard_compatiblehappy_eyeballs_delayr   intzIPAddressType | Nonezssl.SSLContext | Noneboolstrfloatr   )remote_hostremote_portr&   r'   r(   tls_hostnamer)   returnc                  s   d S N r.   r/   r&   r'   r(   r0   r)   r3   r3   :./venv/lib/python3.8/site-packages/anyio/_core/_sockets.pyconnect_tcp.   s    
r6   )r&   r(   r0   r)   zssl.SSLContextz
str | Nonec                  s   d S r2   r3   r4   r3   r3   r5   r6   <   s    
)r&   r'   r(   r0   r)   zLiteral[True])	r.   r/   r&   tlsr'   r(   r0   r)   r1   c                  s   d S r2   r3   r.   r/   r&   r7   r'   r(   r0   r)   r3   r3   r5   r6   J   s    zLiteral[False]r   c                  s   d S r2   r3   r8   r3   r3   r5   r6   Y   s    )r&   r)   )r.   r/   r&   r)   r1   c                  s   d S r2   r3   )r.   r/   r&   r)   r3   r3   r5   r6   h   s    FTg      ?)r&   r7   r'   r(   r0   r)   zSocketStream | TLSStreamc                  s^  ddddd fdd}t   dtj}	|r\tt|dI dH }
|
d ^}	}t| }zt| }W n tk
r(   t||	tjd	I dH }
d
 }}g }|
D ]x^}}}|tjkr|sd}|	d||d f q|tj
kr|s|rd}|	d||d f q|||d f qY n,X t|trFtj|jfg}ntj
|jfg}g t 4 I dH Tt|D ]D\}\}}t }||| t| | I dH  W 5 Q R X qpW 5 Q I dH R X dkrtdkrd ntd}td||s|s|rZz&tjd
|p"t| ||dI dH W S  tk
rX   tI dH   Y nX S )a~  
    Connect to a host using the TCP protocol.

    This function implements the stateless version of the Happy Eyeballs algorithm (RFC
    6555). If ``remote_host`` is a host name that resolves to multiple IP addresses,
    each one is tried until one connection attempt succeeds. If the first attempt does
    not connected within 250 milliseconds, a second attempt is started using the next
    address in the list, and so on. On IPv6 enabled systems, an IPv6 address (if
    available) is tried first.

    When the connection has been established, a TLS handshake will be done if either
    ``ssl_context`` or ``tls_hostname`` is not ``None``, or if ``tls`` is ``True``.

    :param remote_host: the IP address or host name to connect to
    :param remote_port: port on the target host to connect to
    :param local_host: the interface address or name to bind the socket to before
        connecting
    :param tls: ``True`` to do a TLS handshake with the connected stream and return a
        :class:`~anyio.streams.tls.TLSStream` instead
    :param ssl_context: the SSL context object to use (if omitted, a default context is
        created)
    :param tls_standard_compatible: If ``True``, performs the TLS shutdown handshake
        before closing the stream and requires that the server does this as well.
        Otherwise, :exc:`~ssl.SSLEOFError` may be raised during reads from the stream.
        Some protocols, such as HTTP, require this option to be ``False``.
        See :meth:`~ssl.SSLContext.wrap_socket` for details.
    :param tls_hostname: host name to check the server certificate against (defaults to
        the value of ``remote_host``)
    :param happy_eyeballs_delay: delay (in seconds) before starting the next connection
        attempt
    :return: a socket stream object if no TLS handshake was done, otherwise a TLS stream
    :raises OSError: if the connection attempt fails

    Nr,   r   None)r.   eventr1   c              
     s   zzz | I d H }W n6 tk
rP } z| W Y W <d S d }~X Y n(X d krj|j  n| I d H  W 5 |   X d S r2   )setr6   OSErrorappendZcancel_scopecancelaclose)r.   r:   streamexcasynclibZconnected_streamlocal_addressZoserrorsr/   tgr3   r5   try_connect   s    
z connect_tcp.<locals>.try_connectr   familytypeFTr   z#multiple connection attempts failedzAll connection attempts failed)Zserver_sideZhostnamer'   Zstandard_compatible)r   socket	AF_UNSPECgetaddrinfor,   r   
ValueErrorSOCK_STREAMAF_INET6insertAF_INETr=   
isinstancer   
compressedr   	enumerater   Z
start_soonr    waitlenr#   r<   r   wrapBaseExceptionr   )r.   r/   r&   r7   r'   r(   r0   r)   rF   rH   gai_res_Ztarget_hostZaddr_objZv6_foundZv4_foundZtarget_addrsafrestZsaiaddrr:   causer3   rB   r5   r6   r   sr    .    
,


zstr | bytes | PathLike[Any]r   )pathr1   c                   s   t | } t | I dH S )z
    Connect to the given UNIX socket.

    Not available on Windows.

    :param path: path to the socket
    :return: a socket stream object

    N)osfspathr   connect_unix)r`   r3   r3   r5   rc      s    

rc      )r&   
local_portrH   backlog
reuse_portAnyIPAddressFamilyzMultiListener[SocketStream])r&   re   rH   rf   rg   r1   c                   s  t  }t|d}| dk	r t| nd} t| ||tjdkr>tjjndtj	tj
B dI dH }g }z
tt|D ]^}}	}
}tjdkr|	tjk	rqjt|}|d tjdkr|tjtjd n|tjtjd |r|tjtjd |tjkr:|ttjd d|d kr:|d dd\}}||d dt|f}|| || ||}|| qjW n2 tk
r   |D ]}| I dH  q| Y nX t|S )	a  
    Create a TCP socket listener.

    :param local_port: port number to listen on
    :param local_host: IP address of the interface to listen on. If omitted, listen on
        all IPv4 and IPv6 interfaces. To listen on all interfaces on a specific address
        family, use ``0.0.0.0`` for IPv4 or ``::`` for IPv6.
    :param family: address family (used if ``local_host`` was omitted)
    :param backlog: maximum number of queued incoming connections (up to a maximum of
        2**16, or 65536)
    :param reuse_port: ``True`` to allow multiple sockets to bind to the same
        address/port (not supported on Windows)
    :return: a list of listener objects

    rd   Nwin32r   rH   rI   flagsFr   %)r   minr,   rL   sysplatformrJ   r	   rN   
AI_PASSIVEAI_ADDRCONFIGsortedr;   setblockingZ
setsockoptZ
SOL_SOCKETZSO_EXCLUSIVEADDRUSEZSO_REUSEADDRZSO_REUSEPORTrO   r$   ZIPV6_V6ONLYsplitr*   bindlistencreate_tcp_listenerr=   rX   r?   r   )r&   re   rH   rf   rg   rC   rY   Z	listenersZfamkindrZ   sockaddr
raw_socketr^   scope_idZlistenerr3   r3   r5   rw     sH    







rw   )moderf   z
int | Noner   )r`   r|   rf   r1   c                  sZ   t |d}t| |tjI dH }z|| t |W S  tk
rT   |   Y nX dS )a  
    Create a UNIX socket listener.

    Not available on Windows.

    :param path: path of the socket
    :param mode: permissions to set on the socket
    :param backlog: maximum number of queued incoming connections (up to a maximum of
        2**16, or 65536)
    :return: a listener object

    .. versionchanged:: 3.0
        If a socket already exists on the file system in the given path, it will be
        removed first.

    rd   N)	rm   setup_unix_local_socketrJ   rN   rv   r   create_unix_listenerrX   close)r`   r|   rf   rz   r3   r3   r5   r~   S  s    

r~   )r&   re   rg   r   )rH   r&   re   rg   r1   c                  s   | t jkr|std|r`tt||| tjtjtjB dI dH }t	t
|d d } |d d }n| t jkrpd}nd}t | |d|I dH }t	t|S )uY  
    Create a UDP socket.

    If ``port`` has been given, the socket will be bound to this port on the local
    machine, making this socket suitable for providing UDP based services.

    :param family: address family (``AF_INET`` or ``AF_INET6``) – automatically
        determined from ``local_host`` if omitted
    :param local_host: IP address or host name of the local interface to bind to
    :param local_port: local port to bind to
    :param reuse_port: ``True`` to allow multiple sockets to bind to the same
        address/port (not supported on Windows)
    :return: a UDP socket

    z-Either "family" or "local_host" must be givenrj   Nr   )z::r   )z0.0.0.0r   )r   rK   rM   rL   r,   rJ   
SOCK_DGRAMrp   rq   r   rh   rO   r   create_udp_socketr   )rH   r&   re   rg   rY   rD   sockr3   r3   r5   r   s  s,    

   
r   )rH   r&   re   rg   r   )r.   r/   rH   r&   re   rg   r1   c          
        s   d}|rLt t|||tjtjtjB dI dH }tt|d d }|d d }t t| ||tjdI dH }tt|d d }|d d }t 	||||I dH }	tt
|	S )u  
    Create a connected UDP socket.

    Connected UDP sockets can only communicate with the specified remote host/port, an
    any packets sent from other sources are dropped.

    :param remote_host: remote host to set as the default target
    :param remote_port: port on the remote host to set as the default target
    :param family: address family (``AF_INET`` or ``AF_INET6``) – automatically
        determined from ``local_host`` or ``remote_host`` if omitted
    :param local_host: IP address or host name of the local interface to bind to
    :param local_port: local port to bind to
    :param reuse_port: ``True`` to allow multiple sockets to bind to the same
        address/port (not supported on Windows)
    :return: a connected UDP socket

    Nrj   r   r   rG   )rL   r,   rJ   r   rp   rq   r   rh   r   r   r   )
r.   r/   rH   r&   re   rg   rD   rY   Zremote_addressr   r3   r3   r5   create_connected_udp_socket  s4    
      
r   )
local_path
local_modez"None | str | bytes | PathLike[Any]r   )r   r   r1   c                   s(   t | |tjI dH }t |dI dH S )a8  
    Create a UNIX datagram socket.

    Not available on Windows.

    If ``local_path`` has been given, the socket will be bound to this path, making this
    socket suitable for receiving datagrams from other processes. Other processes can
    send datagrams to this socket only if ``local_path`` is set.

    If a socket already exists on the file system in the ``local_path``, it will be
    removed first.

    :param local_path: the path on which to bind to
    :param local_mode: permissions to set on the local socket
    :return: a UNIX datagram socket

    N)r}   rJ   r   r   create_unix_datagram_socket)r   r   rz   r3   r3   r5   r     s      
r   r   )remote_pathr   r   r1   c                  s2   t | } t||tjI dH }t || I dH S )a  
    Create a connected UNIX datagram socket.

    Connected datagram sockets can only communicate with the specified remote path.

    If ``local_path`` has been given, the socket will be bound to this path, making
    this socket suitable for receiving datagrams from other processes. Other processes
    can send datagrams to this socket only if ``local_path`` is set.

    If a socket already exists on the file system in the ``local_path``, it will be
    removed first.

    :param remote_path: the path to set as the default target
    :param local_path: the path on which to bind to
    :param local_mode: permissions to set on the local socket
    :return: a connected UNIX datagram socket

    N)ra   rb   r}   rJ   r   r   r   )r   r   r   rz   r3   r3   r5   %create_connected_unix_datagram_socket  s    
  
 r   rH   rI   protork   zbytes | str | Nonezstr | int | Nonezint | AddressFamilyzint | SocketKindzAlist[tuple[AddressFamily, SocketKind, int, str, tuple[str, int]]])hostportrH   rI   r   rk   r1   c          	        sv   t | trFz| d}W qJ tk
rB   ddl}|j| dd}Y qJX n| }t j||||||dI dH }dd |D S )	a  
    Look up a numeric IP address given a host name.

    Internationalized domain names are translated according to the (non-transitional)
    IDNA 2008 standard.

    .. note:: 4-tuple IPv6 socket addresses are automatically converted to 2-tuples of
        (host, port), unlike what :func:`socket.getaddrinfo` does.

    :param host: host name
    :param port: port number
    :param family: socket family (`'AF_INET``, ...)
    :param type: socket type (``SOCK_STREAM``, ...)
    :param proto: protocol number
    :param flags: flags to pass to upstream ``getaddrinfo()``
    :return: list of tuples containing (family, type, proto, canonname, sockaddr)

    .. seealso:: :func:`socket.getaddrinfo`

    asciir   NT)Zuts46r   c                 S  s(   g | ] \}}}}}||||t |fqS r3   )convert_ipv6_sockaddr).0rH   rI   r   Z	canonnamery   r3   r3   r5   
<listcomp>;  s   zgetaddrinfo.<locals>.<listcomp>)rR   r,   encodeUnicodeEncodeErroridnar   rL   )	r   r   rH   rI   r   rk   Zencoded_hostr   rY   r3   r3   r5   rL     s$    
     rL   r   zAwaitable[tuple[str, str]])ry   rk   r1   c                 C  s   t  | |S )a  
    Look up the host name of an IP address.

    :param sockaddr: socket address (e.g. (ipaddress, port) for IPv4)
    :param flags: flags to pass to upstream ``getnameinfo()``
    :return: a tuple of (host name, service name)

    .. seealso:: :func:`socket.getnameinfo`

    )r   getnameinfo)ry   rk   r3   r3   r5   r   A  s    r   zsocket.socketzAwaitable[None])r   r1   c                 C  s   t  | S )aI  
    Wait until the given socket has data to be read.

    This does **NOT** work on Windows when using the asyncio backend with a proactor
    event loop (default on py3.8+).

    .. warning:: Only use this on raw sockets that have not been wrapped by any higher
        level constructs like socket streams!

    :param sock: a socket object
    :raises ~anyio.ClosedResourceError: if the socket was closed while waiting for the
        socket to become readable
    :raises ~anyio.BusyResourceError: if another task is already waiting for the socket
        to become readable

    )r   wait_socket_readabler   r3   r3   r5   r   O  s    r   c                 C  s   t  | S )aG  
    Wait until the given socket can be written to.

    This does **NOT** work on Windows when using the asyncio backend with a proactor
    event loop (default on py3.8+).

    .. warning:: Only use this on raw sockets that have not been wrapped by any higher
        level constructs like socket streams!

    :param sock: a socket object
    :raises ~anyio.ClosedResourceError: if the socket was closed while waiting for the
        socket to become writable
    :raises ~anyio.BusyResourceError: if another task is already waiting for the socket
        to become writable

    )r   wait_socket_writabler   r3   r3   r5   r   c  s    r   z+tuple[str, int, int, int] | tuple[str, int]ztuple[str, int])ry   r1   c                 C  sX   t | trPt| dkrP| \}}}}|rF|dd }| d| |fS ||fS n| S dS )a  
    Convert a 4-tuple IPv6 socket address to a 2-tuple (address, port) format.

    If the scope ID is nonzero, it is added to the address, separated with ``%``.
    Otherwise the flow id and scope id are simply cut off from the tuple.
    Any other kinds of socket addresses are returned as-is.

    :param sockaddr: the result of :meth:`~socket.socket.getsockname`
    :return: the converted socket address

       rl   r   N)rR   tuplerV   rt   )ry   r   r   Zflowinfor{   r3   r3   r5   r   |  s    
r   )r`   r|   socktyper1   c              
     s
  | dk	rt | }|dszt | }W n> tk
rh } z |jtjtjtjtj	fkrX W 5 d}~X Y qX t
|jrt |  nd}ttj|}|d |dk	rz<tj|j|ddI dH  |dk	rtjt||ddI dH  W n  tk
r   |   Y nX |S )a  
    Create a UNIX local socket object, deleting the socket at the given path if it
    exists.

    Not available on Windows.

    :param path: path of the socket
    :param mode: permissions to set on the socket
    :param socktype: socket.SOCK_STREAM or socket.SOCK_DGRAM

    N FT)Zabandon_on_cancel)ra   fsdecode
startswithstatr<   errnoENOENTZENOTDIRZEBADFZELOOPS_ISSOCKst_modeunlinkrJ   ZAF_UNIXrs   r   Zrun_syncru   r   rX   r   )r`   r|   r   Zpath_strstat_resulterz   r3   r3   r5   r}     s6    



r}   )r   )GZ
__future__r   r   ra   rJ   Zsslr   rn   Zcollections.abcr   Z	ipaddressr   r   r   r   r   r	   typingr
   r   r   r    r   abcr   r   r   r   r   r   r   r   r   Zstreams.stapledr   Zstreams.tlsr   Z
_eventloopr   Z
_resourcesr   Z_synchronizationr   Z_tasksr   r    version_infoZexceptiongroupr#   getattrr$   rK   rQ   rO   rh   ZIPAddressFamilyr6   rc   rw   r~   r   r   r   r   rL   r   r   r   r   r}   r3   r3   r3   r5   <module>   s   ,""$$" S!24%1