o
    _i\V                     @  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mZ d dl	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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" 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- ddl.m/Z/m0Z0 ddl1m2Z2 ddl3m4Z4 g dZ5G dd de2Z6ddddddddedddddddddddddbdDdEZ7		dcdddGdHZ8zd dIl9m:Z: d dJl;m$Z< W n e=y   dedQdRZ>Y nw e:j?e:j?e:j@e:j@dSZAddTddTdSZBdedUdRZ>dfdWdXZCddddYdgdZd[ZDed\ZEed]ed^eEf d_ZFG d`da daZGdS )h    )annotationsN)Sequence)AnyCallableLiteralTypeVarcast   )ClientProtocol)HeadersLike)InvalidProxyMessageInvalidProxyStatus
ProxyError)ClientExtensionFactory) enable_client_permessage_deflate)validate_subprotocols)
USER_AGENTResponse)
CONNECTINGEvent)Proxy	get_proxyparse_proxyprepare_connect_request)StreamReader)	BytesLike
LoggerLikeOriginSubprotocol)WebSocketURI	parse_uri   )
Connection)Deadline)connectunix_connectClientConnectionc                      s\   e Zd ZdZdddddd" fddZdedfd#ddZd$ fddZd% fd d!Z  Z	S )&r&   a+  
    :mod:`threading` implementation of a WebSocket client connection.

    :class:`ClientConnection` provides :meth:`recv` and :meth:`send` methods for
    receiving and sending messages.

    It supports iteration to receive messages::

        for message in websocket:
            process(message)

    The iterator exits normally when the connection is closed with code
    1000 (OK) or 1001 (going away) or without a close code. It raises a
    :exc:`~websockets.exceptions.ConnectionClosedError` when the connection is
    closed with any other code.

    The ``ping_interval``, ``ping_timeout``, ``close_timeout``, and
    ``max_queue`` arguments have the same meaning as in :func:`connect`.

    Args:
        socket: Socket connected to a WebSocket server.
        protocol: Sans-I/O connection.

       
      ping_intervalping_timeoutclose_timeout	max_queuesocketsocket.socketprotocolr
   r+   float | Noner,   r-   r.   *int | None | tuple[int | None, int | None]returnNonec                  s*   |  t  | _t j||||||d d S )Nr*   )	threadingr   response_rcvdsuper__init__)selfr/   r1   r+   r,   r-   r.   	__class__ X/sda-disk/www/egybert/egybert_env/lib/python3.10/site-packages/websockets/sync/client.pyr9   7   s   


zClientConnection.__init__Nadditional_headersHeadersLike | Noneuser_agent_header
str | Nonetimeoutc                 C  s   | j td, | j | _|dur| jj| |dur$| jjd| | j| j W d   n1 s5w   Y  | j	
|sDtd| jjdurN| jjdS )z1
        Perform the opening handshake.

        )expected_stateNz
User-Agentz.timed out while waiting for handshake response)send_contextr   r1   r$   requestheadersupdate
setdefaultsend_requestr7   waitTimeoutErrorhandshake_exc)r:   r?   rA   rC   r=   r=   r>   	handshakeL   s   
zClientConnection.handshakeeventr   c                   s<   | j du rt|tsJ || _ | j  dS t | dS )z.
        Process one incoming event.

        N)response
isinstancer   r7   setr8   process_event)r:   rO   r;   r=   r>   rS   h   s
   
zClientConnection.process_eventc                   s(   zt    W | j  dS | j  w )zI
        Read incoming data from the socket and process events.

        N)r8   recv_eventsr7   rR   )r:   r;   r=   r>   rT   v   s   zClientConnection.recv_events)r/   r0   r1   r
   r+   r2   r,   r2   r-   r2   r.   r3   r4   r5   )r?   r@   rA   rB   rC   r2   r4   r5   )rO   r   r4   r5   )r4   r5   )
__name__
__module____qualname____doc__r9   r   rN   rS   rT   __classcell__r=   r=   r;   r>   r&      s    r&   deflateTr(   r'   i   r)   )socksslserver_hostnameorigin
extensionssubprotocolscompressionr?   rA   proxy	proxy_sslproxy_server_hostnameopen_timeoutr+   r,   r-   max_sizer.   loggercreate_connectionuristrr[   socket.socket | Noner\   ssl_module.SSLContext | Noner]   rB   r^   Origin | Noner_   'Sequence[ClientExtensionFactory] | Noner`   Sequence[Subprotocol] | Nonera   r?   r@   rA   rb   str | Literal[True] | Nonerc   rd   re   r2   r+   r,   r-   rf   r3   r.   rg   LoggerLike | Nonerh   type[ClientConnection] | Nonekwargsr   r4   c                K  s.  |du rd|v r| d}tdt t| }|js"|dur"td| dd}| dd}|rH|du r<|du r<td|durH|durHtd	|durPt| |d
krYt|}n|durdtd| |rhd}
|durnd}
|
du rvt	|}
t
|}|du rt}z|du r|rttjtj}||  |dusJ || n\|
durt|
}|jdd dkrt|||| ddd}n>|jdd dkr|jdkr|durtdt|||f|	||d|}ntd|d|  tj|j|jffi |}|d |s|tjtjd |jrK|du rt }|du r%|j}||  |du r9|j ||d}nt!|||d}t"tj|}|d t#||||||d}|||||||d}W n t$yr   |durq|%   w z|&||	|  W n t$y   |'  |j()   w |*  |S )a  
    Connect to the WebSocket server at ``uri``.

    This function returns a :class:`ClientConnection` instance, which you can
    use to send and receive messages.

    :func:`connect` may be used as a context manager::

        from websockets.sync.client import connect

        with connect(...) as websocket:
            ...

    The connection is closed automatically when exiting the context.

    Args:
        uri: URI of the WebSocket server.
        sock: Preexisting TCP socket. ``sock`` overrides the host and port
            from ``uri``. You may call :func:`socket.create_connection` to
            create a suitable TCP socket.
        ssl: Configuration for enabling TLS on the connection.
        server_hostname: Host name for the TLS handshake. ``server_hostname``
            overrides the host name from ``uri``.
        origin: Value of the ``Origin`` header, for servers that require it.
        extensions: List of supported extensions, in order in which they
            should be negotiated and run.
        subprotocols: List of supported subprotocols, in order of decreasing
            preference.
        compression: The "permessage-deflate" extension is enabled by default.
            Set ``compression`` to :obj:`None` to disable it. See the
            :doc:`compression guide <../../topics/compression>` for details.
        additional_headers (HeadersLike | None): Arbitrary HTTP headers to add
            to the handshake request.
        user_agent_header: Value of  the ``User-Agent`` request header.
            It defaults to ``"Python/x.y.z websockets/X.Y"``.
            Setting it to :obj:`None` removes the header.
        proxy: If a proxy is configured, it is used by default. Set ``proxy``
            to :obj:`None` to disable the proxy or to the address of a proxy
            to override the system configuration. See the :doc:`proxy docs
            <../../topics/proxies>` for details.
        proxy_ssl: Configuration for enabling TLS on the proxy connection.
        proxy_server_hostname: Host name for the TLS handshake with the proxy.
            ``proxy_server_hostname`` overrides the host name from ``proxy``.
        open_timeout: Timeout for opening the connection in seconds.
            :obj:`None` disables the timeout.
        ping_interval: Interval between keepalive pings in seconds.
            :obj:`None` disables keepalive.
        ping_timeout: Timeout for keepalive pings in seconds.
            :obj:`None` disables timeouts.
        close_timeout: Timeout for closing the connection in seconds.
            :obj:`None` disables the timeout.
        max_size: Maximum size of incoming messages in bytes.
            :obj:`None` disables the limit. You may pass a ``(max_message_size,
            max_fragment_size)`` tuple to set different limits for messages and
            fragments when you expect long messages sent in short fragments.
        max_queue: High-water mark of the buffer where frames are received.
            It defaults to 16 frames. The low-water mark defaults to ``max_queue
            // 4``. You may pass a ``(high, low)`` tuple to set the high-water
            and low-water marks. If you want to disable flow control entirely,
            you may set it to ``None``, although that's a bad idea.
        logger: Logger for this client.
            It defaults to ``logging.getLogger("websockets.client")``.
            See the :doc:`logging guide <../../topics/logging>` for details.
        create_connection: Factory for the :class:`ClientConnection` managing
            the connection. Set it to a wrapper or a subclass to customize
            connection handling.

    Any other keyword arguments are passed to :func:`~socket.create_connection`.

    Raises:
        InvalidURI: If ``uri`` isn't a valid WebSocket URI.
        OSError: If the TCP connection fails.
        InvalidHandshake: If the opening handshake fails.
        TimeoutError: If the opening handshake times out.

    Nssl_contextzssl_context was renamed to sslz-ssl argument is incompatible with a ws:// URIunixFpathzmissing path argumentz(path and sock arguments are incompatiblerZ   zunsupported compression: T   sockssource_address)
local_addr   httphttpsz8proxy_ssl argument is incompatible with an http:// proxyrA   r\   r]   zunsupported proxyrC   r]   )r^   r_   r`   rf   rg   r*   )+popwarningswarnDeprecationWarningr    secure
ValueErrorr   r   r   r#   r&   r/   AF_UNIXSOCK_STREAM
settimeoutrC   r$   r   schemeconnect_socks_proxyconnect_http_proxyAssertionErrorrI   rh   hostport
setsockoptIPPROTO_TCPTCP_NODELAY
ssl_modulecreate_default_contextwrap_socketSSLSSLSocketr   r
   	ExceptioncloserN   close_socketrecv_events_threadjoinstart_keepalive)ri   r[   r\   r]   r^   r_   r`   ra   r?   rA   rb   rc   rd   re   r+   r,   r-   rf   r.   rg   rh   rs   ws_uriru   rv   deadlineproxy_parsedsock_2r1   
connectionr=   r=   r>   r$      s   p













r$   rv   c                 K  sD   |du r| ddu r| ddu rd}nd}td|d| d|S )	a  
    Connect to a WebSocket server listening on a Unix socket.

    This function accepts the same keyword arguments as :func:`connect`.

    It's only available on Unix.

    It's mainly useful for debugging servers listening on Unix sockets.

    Args:
        path: File system path to the Unix socket.
        uri: URI of the WebSocket server. ``uri`` defaults to
            ``ws://localhost/`` or, when a ``ssl`` is provided, to
            ``wss://localhost/``.

    Nr\   rt   zws://localhost/zwss://localhost/T)ri   ru   rv   r=   )getr$   )rv   ri   rs   r=   r=   r>   r%     s
   r%   )	ProxyType)r   r   r   r   r   r#   r0   c                 K  s   t d)Nz6connecting through a SOCKS proxy requires python-socks)ImportError)rb   r   r   rs   r=   r=   r>   r     s   r   )socks5hsocks5socks4asocks4Fc              
   K  s   t t| j | j| j| j| jt| j }|d|	  z|j
|j|jfi |W S  tttj	fy4     tyD } ztd|d}~ww )z0Connect via a SOCKS proxy and return the socket.rC   z failed to connect to SOCKS proxyN)
SocksProxySOCKS_PROXY_TYPESr   r   r   usernamepasswordSOCKS_PROXY_RDNSrI   rC   r$   OSErrorrL   r/   r   r   )rb   r   r   rs   socks_proxyexcr=   r=   r>   r     s"   
r   c              
   C  s  t  }tj|j|j|jdd}zsz	 | |  | d}|r&|	| n|
  t| q tyg } z-t|jts>J |j}d|j  krLdk r_n t||W  Y d }~W | d  S t|d }~w tjyr   td ty } ztd|d }~ww | d  w )NT)rb   i      i,  z(timed out while connecting to HTTP proxyz0did not receive a valid HTTP response from proxy)r   r   parse	read_line
read_exactread_to_eofr   rC   recv	feed_datafeed_eofnextStopIterationrQ   valuestatus_coder   r/   rL   r   r   )r[   r   readerparserdatar   rP   r=   r=   r>   read_connect_response  sH   

r   r~   c                K  s   | d|  tj| j| jffi |}| jdkr<|d u r"t }|d u r)| j}|	|  |j
||d}|	d  |t| || zt|| W |S  tyY   |   w )NrC   r}   r   )rI   rC   r/   rh   r   r   r   r   r   r   r   sendallr   r   r   r   )rb   r   r   rA   r\   r]   rs   r[   r=   r=   r>   r     s$   

r   TF.)boundc                   @  sT   e Zd ZdZdZ	d$d%ddZd&ddZd'ddZd(ddZd)ddZ	d*d"d#Z
dS )+r   zr
    Socket-like object providing TLS-in-TLS.

    Only methods that are used by websockets are implemented.

    i   Nr[   r0   rt   ssl_module.SSLContextr]   rB   r4   r5   c                 C  sB   t  | _t  | _|| _|j| j| j|d| _| | jj d S )Nr   )	r   	MemoryBIOincomingoutgoing
ssl_socketwrap_bio
ssl_objectrun_iodo_handshake)r:   r[   rt   r]   r=   r=   r>   r9   6  s   

zSSLSSLSocket.__init__funcCallable[..., T]argsr   r   c                 G  s   	 d}d}z|| }W n t jy   d}Y n t jy"   d}Y nw | j }|r0| j| |rH| j| j}|rB| j	
| n| j	  q |rKq |S )NTF)r   SSLWantReadErrorSSLWantWriteErrorr   readr   r   r   recv_bufsizer   write	write_eof)r:   r   r   	want_read
want_writeresultr   r=   r=   r>   r   F  s,   

zSSLSSLSocket.run_iobuflenintbytesc                 C  s*   z	|  | jj|W S  tjy   Y dS w )N    )r   r   r   r   SSLEOFError)r:   r   r=   r=   r>   r   d  s
   zSSLSSLSocket.recvr   r   c                 C  s   |  | jj|S N)r   r   r   )r:   r   r=   r=   r>   sendj  s   zSSLSSLSocket.sendc              	   C  s   d}t |=}|d}t|}||k r$|| ||d  7 }||k sW d    n1 s.w   Y  W d    d S W d    d S 1 sFw   Y  d S )Nr   B)
memoryviewr   lenr   )r:   r   countview	byte_viewamountr=   r=   r>   r   m  s   PzSSLSSLSocket.sendallnamerj   c                 C  s   t | j|S r   )getattrr   )r:   r   r=   r=   r>   __getattr__x  s   zSSLSSLSocket.__getattr__r   )r[   r0   rt   r   r]   rB   r4   r5   )r   r   r   r   r4   r   )r   r   r4   r   )r   r   r4   r   )r   r   r4   r5   )r   rj   r4   r   )rU   rV   rW   rX   r   r9   r   r   r   r   r   r=   r=   r=   r>   r   ,  s    



r   ).ri   rj   r[   rk   r\   rl   r]   rB   r^   rm   r_   rn   r`   ro   ra   rB   r?   r@   rA   rB   rb   rp   rc   rl   rd   rB   re   r2   r+   r2   r,   r2   r-   r2   rf   r3   r.   r3   rg   rq   rh   rr   rs   r   r4   r&   )NN)rv   rB   ri   rB   rs   r   r4   r&   )
rb   r   r   r   r   r#   rs   r   r4   r0   )r[   r0   r   r#   r4   r   )rb   r   r   r   r   r#   rA   rB   r\   rl   r]   rB   rs   r   r4   r0   )H
__future__r   r/   r\   r   r6   r   collections.abcr   typingr   r   r   r   r   clientr
   datastructuresr   
exceptionsr   r   r   extensions.baser   extensions.permessage_deflater   rG   r   http11r   r   r1   r   r   rb   r   r   r   r   streamsr   r   r   r   r   ri   r   r    r   r"   utilsr#   __all__r&   r$   r%   python_socksr   python_socks.syncr   r   r   SOCKS5SOCKS4r   r   r   r   r   r   r   r=   r=   r=   r>   <module>   s    i  

'&