o
    :ήclM                     @   s  d dl Z d dlZd dlZd dlmZmZ d dlmZ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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 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rd dlm-Z- nd dl.m-Z- e/e ddZ0eeeee1e2ee2e1f f  Z3e-ej4ej5ej6f Z7e-ej5ej6f Z8eddddddede1dee deej9 de:de2de;de"fdd Z<eddddd!dede1dee dej9de:dee2 de;de"fd"d Z<edddddd#dede1dee d$e-d% deej9 de:dee2 de;de"fd&d Z<edddddd#dede1dee d$e-d' deej9 de:dee2 de;defd(d Z<eddd)dede1dee de;def
d*d Z<dd'dd%dd+d,dede1dee d$e:deej9 de:dee2 de;deee"f fd-d Z<d.ee2d/f defd0d1Z=dd e jj4d2d'd3dee d4e1d5e7d6e1d7e:de e fd8d9Z>dd2d:d.ee2d/f d;ee1 d6e1defd<d=Z?ej4fdd d'd>d5e7dee d4e1d7e:def
d?d@Z@ej4dd d'dAdede1d5e7dee d4e1d7e:defdBdCZAd d d d dDdEeeBeCe2f dFee2e1df d5ee1ef dGee1ef dHe1dIe1de3fdJdKZDdVdLedIe1deee2e2f  fdMdNZEdOe j ded fdPdQZFdOe j ded fdRdSZGdLeee2e1e1e1f ee2e1f f dee2e1f fdTdUZHdS )W    N)IPv6Address
ip_address)PathLikechmod)Path)AddressFamily
SocketKind)	AwaitableListOptionalTupleUnioncastoverload   )	to_thread)ConnectedUDPSocketIPAddressTypeIPSockAddrTypeSocketListenerSocketStream	UDPSocketUNIXSocketStream)MultiListener)	TLSStream   )get_asynclib)aclose_forcefully)Event)create_task_groupmove_on_after)      )LiteralIPPROTO_IPV6)   .)
local_hostssl_contexttls_standard_compatiblehappy_eyeballs_delayremote_hostremote_portr&   r'   r(   tls_hostnamer)   returnc                      d S N r*   r+   r&   r'   r(   r,   r)   r0   r0   ;/tmp/pip-target-vg8gfxp4/lib/python/anyio/_core/_sockets.pyconnect_tcp,      r3   )r&   r(   r,   r)   c                   r.   r/   r0   r1   r0   r0   r2   r3   ;   r4   )r&   r'   r(   r,   r)   tlsTc                   r.   r/   r0   r*   r+   r&   r5   r'   r(   r,   r)   r0   r0   r2   r3   J      Fc                   r.   r/   r0   r6   r0   r0   r2   r3   Z   r7   )r&   r)   c                   r.   r/   r0   )r*   r+   r&   r)   r0   r0   r2   r3   j   s   g      ?)r&   r5   r'   r(   r,   r)   c             
      s~  ddt dtddf fdd}t  dtj}	|r1tt |dI dH }
|
d ^}	}t | }zt| }W nW ty   t||	tjdI dH }
d	 }}g }|
D ]9^}}}|tj	krp|spd
}|
d||d f qV|tjkr|s|rd
}|
d||d f qV|||d f qVY nw t|trtj	|jfg}ntj|jfg}g t 4 I dH ;t|D ]+\}\}}t }||| t| | I dH  W d   n1 sw   Y  qW d  I dH  n1 I dH sw   Y  du rtdkrd n }td||s|s|r=ztjd	|p$t | ||dI dH W S  ty<   tI dH   w S )a^  
    Connect to a host using the TCP protocol.

    This function implements the stateless version of the Happy Eyeballs algorithm (RFC 6555).
    If ``address`` 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*   eventr-   c              
      s   zKz  | I d H }W n ty+ } z| W Y d }~W |  d S d }~ww d u r8|j  n| I d H  W |  d S W |  d S |  w r/   )r3   OSErrorappendsetcancel_scopecancelaclose)r*   r8   streamexcasynclibconnected_streamlocal_addressoserrorsr+   tgr0   r2   try_connect   s    
z connect_tcp.<locals>.try_connectr   familytypeFTr   zAll connection attempts failed)server_sidehostnamer'   standard_compatible)strr   r   socket	AF_UNSPECgetaddrinfor   
ValueErrorSOCK_STREAMAF_INET6insertAF_INETr:   
isinstancer   
compressedr   	enumerate
start_soonr    waitlenExceptionGroupr9   r   wrapBaseExceptionr   )r*   r+   r&   r5   r'   r(   r,   r)   rG   rI   gai_res_target_hostaddr_objv6_foundv4_foundtarget_addrsafrestsaiaddrr8   causer0   rA   r2   r3   u   sv   *$


(
 
pathzPathLike[str]c                    s    t 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)rN   r   r   connect_unix)rm   r0   r0   r2   rn      s   
rn      )r&   
local_portrI   backlog
reuse_portrp   rI   rq   rr   c                    s6  t  }t|d}| durt| nd} t| ||tjtjtjB dI dH }g }z`tt	|D ]T^}}	}
t|}|
d tjdkrL|tjtjd n	|tjtjd |r`|tjtjd |tjkrm|ttjd ||
 || ||}|| q-W t|S  ty   |D ]	}| I dH  q w )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 ``interface`` 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

    ro   NrI   rJ   flagsFwin32r   )r   minrN   rQ   rO   rS   
AI_PASSIVEAI_ADDRCONFIGsortedr;   setblockingsysplatform
setsockopt
SOL_SOCKETSO_EXCLUSIVEADDRUSESO_REUSEADDRSO_REUSEPORTrT   r$   IPV6_V6ONLYbindlistenTCPSocketListenerr:   r_   r>   r   )r&   rp   rI   rq   rr   rB   r`   	listenersfamra   sockaddr
raw_socketlistenerr0   r0   r2   create_tcp_listener   sD   








r   )moderq   r   c                   s   t | }t| } |  r|   t|d}ttj}|d z(tj	|j
|ddI dH  |dur>tj	t||ddI dH  || t |W S  tyU   |   w )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.

    ro   FT)cancellableN)rN   r   	is_socketunlinkrv   rO   AF_UNIXrz   r   run_syncr   r   r   r   UNIXSocketListenerr_   close)rm   r   rq   path_strr   r0   r0   r2   create_unix_listenerA  s$   


r   )r&   rp   rr   c                   s   | t ju r|std|r1tt||| tjtjtjB dI dH }t	t
|d d } |d d }n
| t ju r9d}nd}t | |d|I dH 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 givenrs   Nr   )z::r   )z0.0.0.0r   )r   rP   rR   rQ   rN   rO   
SOCK_DGRAMrw   rx   r   AnyIPAddressFamilyrT   r   create_udp_socket)rI   r&   rp   rr   r`   rD   r0   r0   r2   r   j  s&   


r   )rI   r&   rp   rr   c          	         s   d}|r't 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 S )u  
    Create a connected UDP socket.

    Connected UDP sockets can only communicate with the specified remote host/port, and 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

    Nrs   r   r   rH   )
rQ   rN   rO   r   rw   rx   r   r   r   r   )	r*   r+   rI   r&   rp   rr   rD   r`   remote_addressr0   r0   r2   create_connected_udp_socket  s(   

r   rI   rJ   protort   hostportrJ   r   rt   c          	         st   t | tr"z| d}W n ty!   ddl}|j| dd}Y nw | }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)uts46r   c                 S   s(   g | ]\}}}}}||||t |fqS r0   )convert_ipv6_sockaddr).0rI   rJ   r   	canonnamer   r0   r0   r2   
<listcomp>  s    zgetaddrinfo.<locals>.<listcomp>)rW   rN   encodeUnicodeEncodeErroridnar   rQ   )	r   r   rI   rJ   r   rt   encoded_hostr   r`   r0   r0   r2   rQ     s   
rQ   r   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)r   rt   r0   r0   r2   r     s   r   sockc                 C      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   r0   r0   r2   r        r   c                 C   r   )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   r0   r0   r2   r     r   r   c                 C   sd   t | tr)t| dkr)ttttttf | \}}}}|r%| d| |fS ||fS ttttf | 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

       %)rW   tupler\   r   r   rN   int)r   r   r   flowinfoscope_idr0   r0   r2   r   4  s   r   )r   )IrO   sslr{   	ipaddressr   r   osr   r   pathlibr   r   r   typingr	   r
   r   r   r   r   r    r   abcr   r   r   r   r   r   r   streams.stapledr   streams.tlsr   
_eventloopr   
_resourcesr   _synchronizationr   _tasksr   r    version_infor#   typing_extensionsgetattrr$   r   rN   GetAddrInfoReturnTyperP   rV   rT   r   IPAddressFamily
SSLContextboolfloatr3   rn   r   r   r   r   	bytearraybytesrQ   r   r   r   r   r0   r0   r0   r2   <module>   s   $$	
			
	
	


{
F

*
1
5


$1
