a
    њhxX                     @  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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ddd d!d"d#d$d!d%d!d&d d!d'd'd'd'd(d)d*d+d,dd-d.d/Z7dQd!d!d,dd0d1d2Z8zVd d3l9m:Z: d d4l;m,Z< e:j=e:j=e:j>e:j>d5Z?dd6dd6d5Z@d7d8d9d,d:d;d<d=ZAW n* eBy8   d7d8d9d,d:d;d>d=ZAY n0 dRd7d8d!d?d@dAdBZCd:d9dCdDdEdFZDddddGd7d8d9d!d d!d,d:dHdIdJZEedKZFedLedMeFf dNZGG dOdP dPZHdS )S    )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ddddd	d
d fddZdedfdddd
dddZdd
d fddZd
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.socketr
   float | None*int | None | tuple[int | None, int | None]None)socketprotocolr,   r-   r.   r/   returnc                  s*   |  t  | _t j||||||d d S )Nr+   )	threadingr   response_rcvdsuper__init__)selfr4   r5   r,   r-   r.   r/   	__class__ Q/wd/webapps/venvs/v2025_4um/lib/python3.9/site-packages/websockets/sync/client.pyr:   6   s    

zClientConnection.__init__NHeadersLike | None
str | None)additional_headersuser_agent_headertimeoutr6   c                 C  s   | j tdX | j | _|dur0| jj| |durH| jjd| | j| j W d   n1 sj0    Y  | j	
|std| jjdur| jjdS )z1
        Perform the opening handshake.

        )Zexpected_stateN
User-Agentz.timed out while waiting for handshake response)Zsend_contextr   r5   r%   requestheadersupdate
setdefaultsend_requestr8   waitTimeoutErrorZhandshake_exc)r;   rB   rC   rD   r>   r>   r?   	handshakeK   s    
,zClientConnection.handshaker   )eventr6   c                   s:   | j du r*t|tsJ || _ | j  nt | dS )z.
        Process one incoming event.

        N)response
isinstancer   r8   setr9   process_event)r;   rN   r<   r>   r?   rR   g   s
    
zClientConnection.process_event)r6   c                   s*   zt    W | j  n| j  0 dS )zI
        Read incoming data from the socket and process events.

        N)r9   recv_eventsr8   rQ   )r;   r<   r>   r?   rS   u   s    zClientConnection.recv_events)
__name__
__module____qualname____doc__r:   r   rM   rR   rS   __classcell__r>   r>   r<   r?   r'      s   "r'   deflateTr)   r(   i   r*   )socksslserver_hostnameorigin
extensionssubprotocolscompressionrB   rC   proxy	proxy_sslproxy_server_hostnameopen_timeoutr,   r-   r.   max_sizer/   loggercreate_connectionstrzsocket.socket | Nonezssl_module.SSLContext | NonerA   zOrigin | Nonez'Sequence[ClientExtensionFactory] | NonezSequence[Subprotocol] | Noner@   zstr | Literal[True] | Noner1   z
int | Noner2   zLoggerLike | Noneztype[ClientConnection] | Noner   )urirZ   r[   r\   r]   r^   r_   r`   rB   rC   ra   rb   rc   rd   r,   r-   r.   re   r/   rf   rg   kwargsr6   c                K  sL  |du r&d|v r&| d}tdt t| }|jsD|durDtd| dd}| dd}|r|du rz|du rztdn|dur|durtd	|durt| |d
krt|}n|durtd| |rd}
|durd}
|
du rt	|}
t
|}|du rt}z|du r|rPttjtj}||  |dusDJ || n|
durt|
}|jdd dkrt|||| ddd}nX|jdd dkr|jdkr|durtdt|||f|	||d|}ntdn*|d|  tj|j|jffi |}|d |s6|tjtjd |jr|du rPt }|du r`|j}||  |du r|j ||d}nt!|||d}t"tj|}|d t#||||||d}|||||||d}W n( t$y   |dur|%   Y n0 z|&||	|  W n( t$y>   |'  |j()   Y n0 |*  |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 incompatiblerY   zunsupported compression: T   sockssource_address)Z
local_addr   httphttpsz8proxy_ssl argument is incompatible with an http:// proxyrC   r[   r\   zunsupported proxyrD   r\   )r]   r^   r_   re   rf   r+   )+popwarningswarnDeprecationWarningr!   secure
ValueErrorr   r   r   r$   r'   r4   AF_UNIXSOCK_STREAM
settimeoutrD   r%   r    schemeconnect_socks_proxyconnect_http_proxyAssertionErrorrI   rg   hostport
setsockoptIPPROTO_TCPTCP_NODELAY
ssl_modulecreate_default_contextwrap_socketSSLSSLSocketr   r
   	ExceptioncloserM   Zclose_socketZrecv_events_threadjoinZstart_keepalive)ri   rZ   r[   r\   r]   r^   r_   r`   rB   rC   ra   rb   rc   rd   r,   r-   r.   re   r/   rf   rg   rj   ws_urirl   rm   deadlineZproxy_parsedZsock_2r5   
connectionr>   r>   r?   r%      s    n

















r%   )rm   ri   rj   r6   c                 K  sD   |du r.| ddu r*| ddu r*d}nd}tf |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[   rk   zws://localhost/zwss://localhost/T)ri   rl   rm   )getr%   )rm   ri   rj   r>   r>   r?   r&     s
    r&   )	ProxyType)r   )Zsocks5hZsocks5Zsocks4aZsocks4Fr   r   r$   r0   )ra   r   r   rj   r6   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yl    Y n. ty } ztd|W Y d}~n
d}~0 0 dS )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_RDNSrI   rD   r%   OSErrorrL   r4   r   r   )ra   r   r   rj   Zsocks_proxyexcr>   r>   r?   r     s    r   c                 K  s   t dd S )Nz-python-socks is required to use a SOCKS proxy)ImportError)ra   r   r   rj   r>   r>   r?   r     s    bytes)ra   r   rC   r6   c                 C  s   t |j|j|jdd}t }t |j|j|j|d< |d urB||d< | jd url| jd usZJ t| j| j|d< d| d |	  S )NT)Zalways_include_portHostrE   zProxy-AuthorizationzCONNECT z HTTP/1.1
)
r   r   r   rz   r   r   r   r   encode	serialize)ra   r   rC   r   rG   r>   r>   r?   prepare_connect_request  s    
r   r   )rZ   r   r6   c              
   C  s@  t  }tj|j|j|jdd}zz>| |  | d}|rL|	| n|
  t| q$W n ty } z`t|jtsJ |j}d|j  krdk rn n|W  Y d }~W | d  S t|W Y d }~nRd }~0  tjy   tdY n0 ty  } ztd|W Y d }~n
d }~0 0 W | d  n| d  0 d S )NF)Zinclude_bodyi      i,  z(timed out while connecting to HTTP proxyz0did not receive a valid HTTP response from proxy)r   r   parseZ	read_lineZ
read_exactZread_to_eofr~   rD   recvZ	feed_dataZfeed_eofnextStopIterationrP   valuestatus_coder   r4   rL   r   r   )rZ   r   readerparserdatar   rO   r>   r>   r?   read_connect_response  s>    


r   rt   )ra   r   r   rC   r[   r\   rj   r6   c                K  s   | d|  tj| j| jffi |}| jdkrx|d u rDt }|d u rR| j}|	|  |j
||d}|	d  |t| || zt|| W n ty   |   Y n0 |S )NrD   rs   ru   )rI   rD   r4   rg   r   r   r   r   r   r~   r   sendallr   r   r   r   )ra   r   r   rC   r[   r\   rj   rZ   r>   r>   r?   r     s"    

r   TF.)boundc                   @  s|   e Zd ZdZdZddddddd	d
ZddddddZdddddZdddddZdddddZ	dd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   Nr0   zssl_module.SSLContextrA   r3   )rZ   rk   r\   r6   c                 C  sB   t  | _t  | _|| _|j| j| j|d| _| | jj d S )Nru   )	r   	MemoryBIOincomingoutgoing
ssl_socketwrap_bio
ssl_objectrun_iodo_handshake)r;   rZ   rk   r\   r>   r>   r?   r:   E  s    

zSSLSSLSocket.__init__zCallable[..., T]r   r   )funcargsr6   c                 G  s   d}d}z|| }W n. t jy,   d}Y n t jyB   d}Y n0 | j }|r^| j| |r| j| j}|r| j	
| q | j	  q |rq |S )NFT)r   SSLWantReadErrorSSLWantWriteErrorr   readr   r   r   recv_bufsizer   write	write_eof)r;   r   r   Z	want_readZ
want_writeresultr   r>   r>   r?   r   U  s(    


zSSLSSLSocket.run_iointr   )buflenr6   c                 C  s.   z|  | jj|W S  tjy(   Y dS 0 d S )N    )r   r   r   r   SSLEOFError)r;   r   r>   r>   r?   r   s  s    zSSLSSLSocket.recv)r   r6   c                 C  s   |  | jj|S N)r   r   r   )r;   r   r>   r>   r?   sendy  s    zSSLSSLSocket.sendc              	   C  s   d}t |b}|d8}t|}||k rB|| ||d  7 }q"W d    n1 sV0    Y  W d    n1 st0    Y  d S )Nr   B)
memoryviewr   lenr   )r;   r   countview	byte_viewamountr>   r>   r?   r   |  s
    zSSLSSLSocket.sendallrh   )namer6   c                 C  s   t | j|S r   )getattrr   )r;   r   r>   r>   r?   __getattr__  s    zSSLSSLSocket.__getattr__)N)rT   rU   rV   rW   r   r:   r   r   r   r   r   r>   r>   r>   r?   r   ;  s    r   )NN)N)I
__future__r   r4   r[   r   r7   rw   collections.abcr   typingr   r   r   r   r   clientr
   Zdatastructuresr   r   
exceptionsr   r   r   Zextensions.baser   Zextensions.permessage_deflater   rG   r   r   r   Zhttp11r   r   r5   r   r   streamsr   r   r   r   ri   r   r   r   r    r!   r   r#   utilsr$   __all__r'   r%   r&   Zpython_socksr   Zpython_socks.syncr   ZSOCKS5ZSOCKS4r   r   r   r   r   r   r   r   r   r   r>   r>   r>   r?   <module>   s   i>  
   ' &