o
    KK&hxX                     @  sD  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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mZm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)m*Z* ddl+m,Z,m-Z-m.Z.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dedDdEZ7		dfdgdGdHZ8z%d dIl9m:Z: d dJl;m,Z< e:j=e:j=e:j>e:j>dKZ?ddLddLdKZ@dhdSdTZAW n eBy   dhdUdTZAY nw 	didjdWdXZCdkdZd[ZDdddd\dld]d^ZEed_ZFed`edaeFf dbZGG dcdd ddZHdS )m    )annotationsN)Sequence)AnyCallableLiteralTypeVarcast   )ClientProtocol)HeadersHeadersLike)InvalidProxyMessageInvalidProxyStatus
ProxyError)ClientExtensionFactory) enable_client_permessage_deflate)build_authorization_basic
build_hostvalidate_subprotocols)
USER_AGENTResponse)
CONNECTINGEvent)StreamReader)
LoggerLikeOriginSubprotocol)ProxyWebSocketURI	get_proxyparse_proxy	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'   a1  
    :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 close 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__)selfr0   r2   r,   r-   r.   r/   	__class__ I/var/www/html/venv/lib/python3.10/site-packages/websockets/sync/client.pyr:   6   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_stateN
User-Agentz.timed out while waiting for handshake response)send_contextr   r2   r%   requestheadersupdate
setdefaultsend_requestr8   waitTimeoutErrorhandshake_exc)r;   r@   rB   rD   r>   r>   r?   	handshakeK   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   r8   setr9   process_event)r;   rQ   r<   r>   r?   rU   g   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)r9   recv_eventsr8   rT   )r;   r<   r>   r?   rV   u   s   zClientConnection.recv_events)r0   r1   r2   r
   r,   r3   r-   r3   r.   r3   r/   r4   r5   r6   )r@   rA   rB   rC   rD   r3   r5   r6   )rQ   r   r5   r6   )r5   r6   )
__name__
__module____qualname____doc__r:   r   rP   rU   rV   __classcell__r>   r>   r<   r?   r'      s    r'   deflateTr)   r(   i   r*   )socksslserver_hostnameorigin
extensionssubprotocolscompressionr@   rB   proxy	proxy_sslproxy_server_hostnameopen_timeoutr,   r-   r.   max_sizer/   loggercreate_connectionuristrr]   socket.socket | Noner^   ssl_module.SSLContext | Noner_   rC   r`   Origin | Nonera   'Sequence[ClientExtensionFactory] | Nonerb   Sequence[Subprotocol] | Nonerc   r@   rA   rB   rd   str | Literal[True] | Nonere   rf   rg   r3   r,   r-   r.   rh   
int | Noner/   r4   ri   LoggerLike | Nonerj   type[ClientConnection] | Nonekwargsr   r5   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.
        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rB   r^   r_   zunsupported proxyrD   r_   )r`   ra   rb   rh   ri   r+   )+popwarningswarnDeprecationWarningr!   secure
ValueErrorr   r   r   r$   r'   r0   AF_UNIXSOCK_STREAM
settimeoutrD   r%   r    schemeconnect_socks_proxyconnect_http_proxyAssertionErrorrK   rj   hostport
setsockoptIPPROTO_TCPTCP_NODELAY
ssl_modulecreate_default_contextwrap_socketSSLSSLSocketr   r
   	ExceptioncloserP   close_socketrecv_events_threadjoinstart_keepalive)rk   r]   r^   r_   r`   ra   rb   rc   r@   rB   rd   re   rf   rg   r,   r-   r.   rh   r/   ri   rj   rv   ws_urirx   ry   deadlineproxy_parsedsock_2r2   
connectionr>   r>   r?   r%      s   n













r%   ry   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^   rw   zws://localhost/zwss://localhost/T)rk   rx   ry   r>   )getr%   )ry   rk   rv   r>   r>   r?   r&     s
   r&   )	ProxyType)r   )socks5hsocks5socks4asocks4Fr   r   r   r   r$   r1   c              
   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.rD   z failed to connect to SOCKS proxyN)
SocksProxySOCKS_PROXY_TYPESr   r   r   usernamepasswordSOCKS_PROXY_RDNSrK   rD   r%   OSErrorrN   r0   r   r   )rd   r   r   rv   socks_proxyexcr>   r>   r?   r     s"   
r   c                 K  s   t d)Nz-python-socks is required to use a SOCKS proxy)ImportError)rd   r   r   rv   r>   r>   r?   r     s   bytesc                 C  s   t |j|j|jdd}t }t |j|j|j|d< |d ur!||d< | jd ur6| jd us-J t| j| j|d< d| d |	  S )NT)always_include_portHostrF   zProxy-AuthorizationzCONNECT z HTTP/1.1
)
r   r   r   r   r   r   r   r   encode	serialize)rd   r   rB   r   rI   r>   r>   r?   prepare_connect_request  s   
r   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 )	NF)include_bodyTi      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   rD   recv	feed_datafeed_eofnextStopIterationrS   valuestatus_coder   r0   rN   r   r   )r]   r   readerparserdatar   rR   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 )NrD   r   r   )rK   rD   r0   rj   r   r   r   r   r   r   r   sendallr   r   r   r   )rd   r   r   rB   r^   r_   rv   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]   r1   rw   ssl_module.SSLContextr_   rC   r5   r6   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]   rw   r_   r>   r>   r?   r:   E  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   U  s,   

zSSLSSLSocket.run_iobuflenintr   c                 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   s  s
   zSSLSSLSocket.recvr   c                 C  s   |  | jj|S N)r   r   r   )r;   r   r>   r>   r?   sendy  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   |  s   PzSSLSSLSocket.sendallnamerl   c                 C  s   t | j|S r   )getattrr   )r;   r   r>   r>   r?   __getattr__  s   zSSLSSLSocket.__getattr__r   )r]   r1   rw   r   r_   rC   r5   r6   )r   r   r   r   r5   r   )r   r   r5   r   )r   r   r5   r   )r   r   r5   r6   )r   rl   r5   r   )rW   rX   rY   rZ   r   r:   r   r   r   r   r   r>   r>   r>   r?   r   ;  s    



r   ).rk   rl   r]   rm   r^   rn   r_   rC   r`   ro   ra   rp   rb   rq   rc   rC   r@   rA   rB   rC   rd   rr   re   rn   rf   rC   rg   r3   r,   r3   r-   r3   r.   r3   rh   rs   r/   r4   ri   rt   rj   ru   rv   r   r5   r'   )NN)ry   rC   rk   rC   rv   r   r5   r'   )
rd   r   r   r   r   r$   rv   r   r5   r1   r   )rd   r   r   r   rB   rC   r5   r   )r]   r1   r   r$   r5   r   )rd   r   r   r   r   r$   rB   rC   r^   rn   r_   rC   rv   r   r5   r1   )I
__future__r   r0   r^   r   r7   r   collections.abcr   typingr   r   r   r   r   clientr
   datastructuresr   r   
exceptionsr   r   r   extensions.baser   extensions.permessage_deflater   rI   r   r   r   http11r   r   r2   r   r   streamsr   r   r   r   rk   r   r   r   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>   r>   r?   <module>   s    i  

'&