
    tni\V                       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Z5 G d de2          Z6ddddddddeddddddddddddd]dDZ7	 	 d^d_dFZ8	 d dGl9m:Z: d dHl;m$Z< e:j=        e:j=        e:j>        e:j>        dIZ?ddJddJdIZ@d`dQZAn# eB$ r d`dRZAY nw xY wdadTZCddddUdbdVZD edW          ZE edXedYeEf         Z          ZF G d[ d\          ZGdS )c    )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                  X     e Zd ZdZdddddd fdZdedfddZd  fdZd! fdZ x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/   r0   *int | None | tuple[int | None, int | None]returnNonec                   |  t          j                    | _        t                                          ||||||           d S )Nr,   )	threadingr   response_rcvdsuper__init__)selfr1   r3   r-   r.   r/   r0   	__class__s          S/var/www/html/gpu-tools/venv/lib/python3.11/site-packages/websockets/sync/client.pyr<   zClientConnection.__init__7   sX     	%&_..'%' 	 	
 	
 	
 	
 	
    Nadditional_headersHeadersLike | Noneuser_agent_header
str | Nonetimeoutc                   |                      t                    5  | j                                        | _        || j        j                            |           | | j        j                            d|           | j                            | j                   ddd           n# 1 swxY w Y   | j	        
                    |          st          d          | j        j        | j        j        dS )z1
        Perform the opening handshake.

        )expected_stateNz
User-Agentz.timed out while waiting for handshake response)send_contextr   r3   r%   requestheadersupdate
setdefaultsend_requestr:   waitTimeoutErrorhandshake_exc)r=   rA   rC   rE   s       r?   	handshakezClientConnection.handshakeL   s*    j99 	5 	5=0022DL!-$++,>??? ,$//>OPPPM&&t|444	5 	5 	5 	5 	5 	5 	5 	5 	5 	5 	5 	5 	5 	5 	5 !&&w// 	QOPPP =&2--- 32s   BB))B-0B-eventr   c                    | j         9t          |t                    sJ || _         | j                                         dS t                                          |           dS )z.
        Process one incoming event.

        N)response
isinstancer   r:   setr;   process_event)r=   rR   r>   s     r?   rW   zClientConnection.process_eventh   se     = eX.....!DM""$$$$$ GG!!%(((((r@   c                    	 t                                                       | j                                         dS # | j                                         w xY w)zI
        Read incoming data from the socket and process events.

        N)r;   recv_eventsr:   rV   )r=   r>   s    r?   rY   zClientConnection.recv_eventsv   sV    
	%GG!!! ""$$$$$D""$$$$s	    > A)r1   r2   r3   r   r-   r4   r.   r4   r/   r4   r0   r5   r6   r7   )rA   rB   rC   rD   rE   r4   r6   r7   )rR   r   r6   r7   )r6   r7   )
__name__
__module____qualname____doc__r<   r   rQ   rW   rY   __classcell__)r>   s   @r?   r'   r'      s         < ')%'&(@B
 
 
 
 
 
 
 
. 26(2 $	. . . . .8) ) ) ) ) )	% 	% 	% 	% 	% 	% 	% 	% 	% 	%r@   r'   deflateTr*   r)   i   r+   )socksslserver_hostnameorigin
extensionssubprotocolscompressionrA   rC   proxy	proxy_sslproxy_server_hostnameopen_timeoutr-   r.   r/   max_sizer0   loggercreate_connectionuristrr`   socket.socket | Nonera   ssl_module.SSLContext | Nonerb   rD   rc   Origin | Nonerd   'Sequence[ClientExtensionFactory] | Nonere   Sequence[Subprotocol] | Nonerf   rA   rB   rC   rg   str | Literal[True] | Nonerh   ri   rj   r4   r-   r.   r/   rk   r5   r0   rl   LoggerLike | Nonerm   type[ClientConnection] | Nonekwargsr   r6   c          	     J   |3d|v r/|                     d          }t          j        dt                     t	          |           }|j        s|t          d          |                     dd          }|                     dd          }|r&||t          d          ||t          d	          |t          |           |d
k    rt          |          }n|t          d|           |rd}
|d}
|
du rt          |          }
t          |          }|t          }	 |e|rjt          j        t          j        t          j                  }|                    |                                           |J |                    |           n|
t%          |
          }|j        dd         dk    r(t)          ||||                     dd                    }n|j        dd         dk    r0|j        dk    r|t          d          t+          |||f|	||d|}nUt-          d          |                    d|                                           t          j        |j        |j        ffi |}|                    d           |s+|                    t          j        t          j        d           |j        r|t=          j                    }||j        }|                    |                                           ||                     ||          }n,tC          |||          }tE          t          j        |          }|                    d           tG          ||||||          } |||||||          }n%# tH          $ r ||%                                  w xY w	 |&                    ||	|                                           n<# tH          $ r/ |'                                 |j(        )                                  w xY 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 incompatibler_   zunsupported compression: T   sockssource_address)
local_addr   httphttpsz8proxy_ssl argument is incompatible with an http:// proxyrC   ra   rb   zunsupported proxyrE   rb   )rc   rd   re   rk   rl   r,   )+popwarningswarnDeprecationWarningr!   secure
ValueErrorr   r   r   r$   r'   r1   AF_UNIXSOCK_STREAM
settimeoutrE   r%   r   schemeconnect_socks_proxyconnect_http_proxyAssertionErrorrL   rm   hostport
setsockoptIPPROTO_TCPTCP_NODELAY
ssl_modulecreate_default_contextwrap_socketSSLSSLSocketr	   r   	ExceptioncloserQ   close_socketrecv_events_threadjoinstart_keepalive)rn   r`   ra   rb   rc   rd   re   rf   rA   rC   rg   rh   ri   rj   r-   r.   r/   rk   r0   rl   rm   rx   ws_urir{   r|   deadlineproxy_parsedsock_2r3   
connections                                 r?   r%   r%      s   ` {}..jj'',	
 	
 	

 s^^F= JS_HIII FE**Dzz&$//D I<DL4555$"2GHHHl+++i5jAA

		 B[BBCCC }}&!!
 %%H ,\ < (}V^V5GHH 0 0 2 2333'''T"""""*511&rr*g55.$  $*::.>#E#E  DD "(!,66#*g55):O(V   .$  +<%(=  ! DD ))<===!!)X-=-=-?-?@@@/[&+.   OOD!!!  	JOOF.0BDIII = 	"{ 799&"(+OOH,,../// t_MM%dCQQQFM622OOD!!! "!%
 
 
 '&'%'
 
 


    JJLLL
		
 	
 	
 	

    !!!%**,,,
    s    I"N "N%))O 9Pr|   c                    |/|                     d          |                     d          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/``.

    Nra   rz   zws://localhost/zwss://localhost/T)rn   r{   r|    )getr%   )r|   rn   rx   s      r?   r&   r&     sU    * {::e$M)B)B)J#CC$C;sD;;F;;;r@   )	ProxyType)r   )socks5hsocks5socks4asocks4Fr   r   r    r   r$   r2   c           	        t          t          | j                 | j        | j        | j        | j        t          | j                           }|                    d|	                                           	  |j
        |j        |j        fi |S # t          t          t          j	        f$ r  t          $ r}t          d          |d}~ww xY w)z0Connect via a SOCKS proxy and return the socket.rE   z failed to connect to SOCKS proxyN)
SocksProxySOCKS_PROXY_TYPESr   r   r   usernamepasswordSOCKS_PROXY_RDNSrL   rE   r%   OSErrorrO   r1   r   r   )rg   r   r   rx   socks_proxyexcs         r?   r   r     s     !el+JJNNU\*
 
 	)X%5%5%7%7888	J&;&v{FKJJ6JJJv~6 	 	 	 	J 	J 	J?@@cI	Js   2B &C1CCc                     t          d          )Nz6connecting through a SOCKS proxy requires python-socks)ImportError)rg   r   r   rx   s       r?   r   r     s     RSSSr@   r   c                   t                      }t          j        |j        |j        |j        d          }	 	 |                     |                                           |                     d          }|r|	                    |           n|
                                 t          |           x# t          $ rh}t          |j        t                    sJ |j        }d|j        cxk    rdk     rn n|cY d }~|                     d            S t!          |          d }~wt"          j        $ r t%          d          t&          $ r}t)          d          |d }~ww xY w# |                     d            w xY w)NT)rg   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   rE   recv	feed_datafeed_eofnextStopIterationrU   valuestatus_coder   r1   rO   r   r   )r`   r   readerparserdatar   rT   s          r?   read_connect_responser     s   ^^F^	  F	OOH,,..///99T??D "  &&&&!!!LLL	  / / /#)X.....9(&,,,,,,,,,OOOOO 	 %X...> G G GEFFF   !>
 
	
 	sB   A9B0 0
E:9D3E4E D*EEEE E6r   c               <   |                     d|                                           t          j        | j        | j        ffi |}| j        dk    rq|t          j                    }|| j        }|	                    |                                           |
                    ||          }|	                    d            |                    t          | ||                     	 t          ||           n## t          $ r |                                  w xY w|S )NrE   r   r   )rL   rE   r1   rm   r   r   r   r   r   r   r   sendallr   r   r   r   )rg   r   r   rC   ra   rb   rx   r`   s           r?   r   r     s'    i!1!1!3!3444#UZ$<GGGGD |w;355C"#jO((**+++t_EE 	LL(8IJJKKKdH----   

 Ks   (C9 9 DTF.)boundc                  J    e Zd ZdZdZ	 dddZd dZd!dZd"dZd#dZ	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`   r2   rz   ssl_module.SSLContextrb   rD   r6   r7   c                    t          j                    | _        t          j                    | _        || _        |                    | j        | j        |          | _        |                     | j        j                   d S )Nr   )	r   	MemoryBIOincomingoutgoing
ssl_socketwrap_bio
ssl_objectrun_iodo_handshake)r=   r`   rz   rb   s       r?   r<   zSSLSSLSocket.__init__6  ss     #,..",..%..MM+ / 
 

 	DO011111r@   funcCallable[..., T]argsr   r   c                   	 d}d}	  || }n)# t           j        $ r d}Y nt           j        $ r d}Y nw xY w| j                                        }|r| j                            |           |rV| j                            | j                  }|r| j	        
                    |           n| j	                                         |r|S )NTF)r   SSLWantReadErrorSSLWantWriteErrorr   readr   r   r   recv_bufsizer   write	write_eof)r=   r   r   	want_read
want_writeresultr   s          r?   r   zSSLSSLSocket.run_ioF  s   	IJ"t. ! ! ! 			/ " " "!


" =%%''D .''---  ++D,=>> .M''----M++--- Ms    333buflenintbytesc                p    	 |                      | j        j        |          S # t          j        $ r Y dS w xY w)Nr@   )r   r   r   r   SSLEOFError)r=   r   s     r?   r   zSSLSSLSocket.recvd  sE    	;;t3V<<<% 	 	 	33	s   " 55r   r   c                B    |                      | j        j        |          S N)r   r   r   )r=   r   s     r?   sendzSSLSSLSocket.sendj  s    {{4?0$777r@   c                *   d}t          |          5 }|                    d          5 }t          |          }||k     r&||                     ||d                    z  }||k     &d d d            n# 1 swxY w Y   d d d            d S # 1 swxY w Y   d S )Nr   B)
memoryviewr	   lenr   )r=   r   countview	byte_viewamounts         r?   r   zSSLSSLSocket.sendallm  s    	6tyy~~ 	6^^F&..9UVV#4555 &..	6 	6 	6 	6 	6 	6 	6 	6 	6 	6 	6 	6 	6 	6 	6 	6 	6 	6 	6 	6 	6 	6 	6 	6 	6 	6 	6 	6 	6 	6 	6 	6 	6s4   B<A0$B0A4	4B7A4	8BBBnamero   c                ,    t          | j        |          S r   )getattrr   )r=   r   s     r?   __getattr__zSSLSSLSocket.__getattr__x  s    t---r@   r   )r`   r2   rz   r   rb   rD   r6   r7   )r   r   r   r   r6   r   )r   r   r6   r   )r   r   r6   r   )r   r   r6   r7   )r   ro   r6   r   )rZ   r[   r\   r]   r   r<   r   r   r   r   r   r   r@   r?   r   r   ,  s          L '+	2 2 2 2 2    <   8 8 8 86 6 6 6. . . . . .r@   r   ).rn   ro   r`   rp   ra   rq   rb   rD   rc   rr   rd   rs   re   rt   rf   rD   rA   rB   rC   rD   rg   ru   rh   rq   ri   rD   rj   r4   r-   r4   r.   r4   r/   r4   rk   r5   r0   r5   rl   rv   rm   rw   rx   r   r6   r'   )NN)r|   rD   rn   rD   rx   r   r6   r'   )
rg   r   r   r    r   r$   rx   r   r6   r2   )r`   r2   r   r$   r6   r   )rg   r   r   r    r   r$   rC   rD   ra   rq   rb   rD   rx   r   r6   r2   )H
__future__r   r1   ra   r   r9   r   collections.abcr   typingr   r   r   r   r	   clientr   datastructuresr   
exceptionsr   r   r   extensions.baser   extensions.permessage_deflater   rJ   r   http11r   r   r3   r   r   rg   r   r   r   r   streamsr   r   r   r   r   rn   r    r!   r   r#   utilsr$   __all__r'   r%   r&   python_socksr   python_socks.syncr   SOCKS5SOCKS4r   r   r   r   r   r   r   r   r   r   r@   r?   <module>r     s   " " " " " "           $ $ $ $ $ $ 8 8 8 8 8 8 8 8 8 8 8 8 8 8 # # # # # # ( ( ( ( ( ( L L L L L L L L L L 4 4 4 4 4 4 L L L L L L + + + + + + ) ) ) ) ) ) ) ) ( ( ( ( ( ( ( ( J J J J J J J J J J J J " " " " " " ? ? ? ? ? ? ? ? ? ? ? ? ) ) ) ) ) ) ) ) " " " " " "       :
9
9b% b% b% b% b%z b% b% b%R "&(,"& :>15'-1$.(,.2(,!#"$!#"$;@<> $7;;F F F F F FT < < < < <<4J&&&&&&555555 #"#"	  	 J J J J J3  T T TT T T T T TTf   N %)(,"&# # # # # #L GCLLGCxQ'(((M. M. M. M. M. M. M. M. M. M.s   	C< <	DD