
    :"ri\V                    B   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	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d0dZ7	 	 d1	 	 	 	 	 	 	 d2d Z8	 d d!l9m:Z: d d"l;m$Z< e:jz                  e:jz                  e:j|                  e:j|                  d#Z?dd$dd$d#Z@	 	 	 	 	 	 	 	 	 	 d3d%ZAd4d'ZCdddd(	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d5d)ZD ed*      ZE ed+ed,eEf   -      ZF G d. d/      ZGy# eB$ r 	 	 	 	 	 	 	 	 	 	 d3d&ZAY Sw xY w)6    )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                       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_queuec               f    |  t        j                         | _        t        |   ||||||       y )Nr,   )	threadingr   response_rcvdsuper__init__)selfsocketprotocolr-   r.   r/   r0   	__class__s          ^/var/www/fortnox.pascalinesoft.com/venv/lib/python3.12/site-packages/websockets/sync/client.pyr5   zClientConnection.__init__7   s;     	&__.'%' 	 	
    Nc                $   | j                  t              5  | j                  j                         | _        |%| j                  j
                  j                  |       |&| j                  j
                  j                  d|       | j                  j                  | j                         ddd       | j                  j                  |      st        d      | j                  j                  | j                  j                  y# 1 sw Y   \xY w)z1
        Perform the opening handshake.

        )expected_stateNz
User-Agentz.timed out while waiting for handshake response)send_contextr   r8   r%   requestheadersupdate
setdefaultsend_requestr3   waitTimeoutErrorhandshake_exc)r6   additional_headersuser_agent_headertimeouts       r:   	handshakezClientConnection.handshakeL   s     j9 	5==002DL!-$$++,>? ,$$//>OPMM&&t||4	5 !!&&w/OPP ==&&2----- 3	5 	5s   BDDc                    | j                   4t        |t              sJ || _         | j                  j	                          yt
        |   |       y)z.
        Process one incoming event.

        N)response
isinstancer   r3   setr4   process_event)r6   eventr9   s     r:   rO   zClientConnection.process_eventh   sG     == eX...!DM""$ G!%(r;   c                    	 t         |           | j                  j                          y# | j                  j                          w xY w)zI
        Read incoming data from the socket and process events.

        N)r4   recv_eventsr3   rN   )r6   r9   s    r:   rR   zClientConnection.recv_eventsv   s:    
	%G! ""$D""$s	   , A)r7   socket.socketr8   r   r-   float | Noner.   rT   r/   rT   r0   *int | None | tuple[int | None, int | None]returnNone)rG   HeadersLike | NonerH   
str | NonerI   rT   rV   rW   )rP   r   rV   rW   )rV   rW   )
__name__
__module____qualname____doc__r5   r   rJ   rO   rR   __classcell__)r9   s   @r:   r'   r'      s    < ')%'&(@B

 !

 $
 #
 $
 >
 

. 26(2 $	... &. 	.
 
.8)	% 	%r;   r'   deflateTr*   r)   i   r+   )socksslserver_hostnameorigin
extensionssubprotocolscompressionrG   rH   proxy	proxy_sslproxy_server_hostnameopen_timeoutr-   r.   r/   max_sizer0   loggercreate_connectionc          	        |/d|v r+|j                  d      }t        j                  dt               t	        |       }|j
                  s|t        d      |j                  dd      }|j                  dd      }|r||t        d      ||t        d	      |t        |       |d
k(  rt        |      }n|t        d|       |rd}
|d}
|
du rt        |      }
t        |      }|t        }	 |Q|rgt        j                  t        j                  t        j                        }|j                  |j!                                |J |j#                  |       n|
t%        |
      }|j&                  dd dk(  r t)        ||||j                  dd            }n|j&                  dd dk(  r/|j&                  dk7  r|t        d      t+        |||f|	||d|}nWt-        d      |j/                  d|j!                                t        j0                  |j2                  |j4                  ffi |}|j                  d       |s/|j7                  t        j8                  t        j:                  d       |j
                  r|t=        j>                         }||j2                  }|j                  |j!                                ||jA                  ||      }n(tC        |||      }tE        t        j                  |      }|j                  d       tG        ||||||      } |||||||      }	 |jM                  ||	|j!                                |jU                          |S # tH        $ r ||jK                           w xY w# tH        $ r, |jO                          |jP                  jS                           w xY w)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rH   ra   rb   zunsupported proxyrI   rb   )rc   rd   re   rk   rl   r,   )+popwarningswarnDeprecationWarningr!   secure
ValueErrorr   r   r   r$   r'   r7   AF_UNIXSOCK_STREAM
settimeoutrI   r%   r   schemeconnect_socks_proxyconnect_http_proxyAssertionErrorrB   rm   hostport
setsockoptIPPROTO_TCPTCP_NODELAY
ssl_modulecreate_default_contextwrap_socketSSLSSLSocketr	   r   	ExceptioncloserJ   close_socketrecv_events_threadjoinstart_keepalive)urir`   ra   rb   rc   rd   re   rf   rG   rH   rg   rh   ri   rj   r-   r.   r/   rk   r0   rl   rm   kwargsws_urirp   rq   deadlineproxy_parsedsock_2r8   
connections                                 r:   r%   r%      s   ` {}.jj',	

 s^F==S_HII FE*Dzz&$/D<DL455$"2GHHl+i5jA
		 4[MBCC}&!
 %H ,\ <}}V^^V5G5GH 0 0 23'''T""*51&&r*g5.$  $*::.>#ED "((!,6#**g5):O(V  .$  +<%(= !D ))<==!!)X-=-=-?@//[[&++. OOD! OOF..0B0BDI =={ 779&"(++OOH,,./ t_M%dCQFMM62OOD! "!%
 ''%'

		
  #  JJL  !%%**,s   3IM) 6!N	 )N	5N>c                r    |'|j                  d      |j                  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/``.

    ra   ro   zws://localhost/zwss://localhost/T)r   rp   rq    )getr%   )rq   r   r   s      r:   r&   r&     sG    * {::e$M)B)J#C$C;sD;F;;r;   )	ProxyType)r   )socks5hsocks5socks4asocks4Fc           	        t        t        | j                     | j                  | j                  | j
                  | j                  t        | j                           }|j                  d|j                                	  |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.rI   z failed to connect to SOCKS proxyN)
SocksProxySOCKS_PROXY_TYPESr   r   r   usernamepasswordSOCKS_PROXY_RDNSrB   rI   r%   OSErrorrE   r7   r   r   )rg   r   r   r   socks_proxyexcs         r:   r   r     s     !ell+JJJJNNNNU\\*
 	)X%5%5%78	J&;&&v{{FKKJ6JJv~~6 	 	J?@cI	Js   <'B$ $'CCCc                    t        d      )Nz6connecting through a SOCKS proxy requires python-socks)ImportError)rg   r   r   r   s       r:   r   r     s     RSSr;   c                   t               }t        j                  |j                  |j                  |j
                  d      }	 	 | j                  |j                                | j                  d      }|r|j                  |       n|j                          t        |       `# t        $ rr}t        |j                  t              sJ |j                  }d|j                  cxk  rdk  r%n t!        |      |cY d }~| j                  d        S t!        |      d }~wt"        j                  $ r t%        d      t&        $ r}t)        d      |d }~ww xY w# | j                  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   rI   recv	feed_datafeed_eofnextStopIterationrM   valuestatus_coder   r7   rE   r   r   )r`   r   readerparserdatar   rL   s          r:   read_connect_responser     s;   ^F^^	FOOH,,./99T?D  &!L   /#))X...99(&&,, %X.. O 	 %X..>> GEFF !>
	
 	sD   A!B$ $	E-AD8E9E D)EEEE E*ry   c                  |j                  d|j                                t        j                  | j                  | j
                  ffi |}| j                  dk(  rg|t        j                         }|| j                  }|j                  |j                                |j                  ||      }|j                  d        |j                  t        | ||             	 t        ||       |S # t        $ r |j                           w xY w)NrI   rx   rz   )rB   rI   r7   rm   r   r   r   r   r   r   r   sendallr   r   r   r   )rg   r   r   rH   ra   rb   r   r`   s           r:   r   r     s     i!1!1!34##UZZ$<GGD ||w;335C"#jjO((*+t_E 	LL(8IJKdH-
 K	  

s    C. .D	TF.)boundc                  V    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
y)r   zr
    Socket-like object providing TLS-in-TLS.

    Only methods that are used by websockets are implemented.

    i   Nc                   t        j                         | _        t        j                         | _        || _        |j                  | j                  | j                  |      | _        | j                  | j                  j                         y )Nrz   )	r   	MemoryBIOincomingoutgoing
ssl_socketwrap_bio
ssl_objectrun_iodo_handshake)r6   r`   ro   rb   s       r:   r5   zSSLSSLSocket.__init__6  sk     #,,.",,.%..MMMM+ / 

 	DOO001r;   c                   	 d}d}	  || }| j                  j	                         }|r| j
                  j                  |       |r^| j
                  j                  | j                        }|r| j                  j                  |       n| j                  j                          |rS # t         j                  $ r d}Y t         j                  $ r d}Y w xY w)NTF)r   SSLWantReadErrorSSLWantWriteErrorr   readr   r   r   recv_bufsizer   write	write_eof)r6   funcargs	want_read
want_writeresultr   s          r:   r   zSSLSSLSocket.run_ioF  s    IJ"t ==%%'D''- ++D,=,=>MM''-MM++-M- .. ! 	// "!
"s   B( (C?CCc                    	 | j                  | j                  j                  |      S # t        j                  $ r Y yw xY w)Nr;   )r   r   r   r   SSLEOFError)r6   buflens     r:   r   zSSLSSLSocket.recvd  s:    	;;t33V<<%% 		s   %( >>c                N    | j                  | j                  j                  |      S N)r   r   r   )r6   r   s     r:   sendzSSLSSLSocket.sendj  s    {{4??00$77r;   c                    d}t        |      5 }|j                  d      5 }t        |      }||k  r|| j                  ||d        z  }||k  rd d d        d d d        y # 1 sw Y   xY w# 1 sw Y   y xY w)Nr   B)
memoryviewr	   lenr   )r6   r   countview	byte_viewamounts         r:   r   zSSLSSLSocket.sendallm  sz     	6tyy~ 	6^F&.9UV#455 &.	6 	6 	6 	6 	6 	6s"   A+-AA+A(	$A++A4c                .    t        | j                  |      S r   )getattrr   )r6   names     r:   __getattr__zSSLSSLSocket.__getattr__x  s    t--r;   r   )r`   rS   ro   zssl_module.SSLContextrb   rY   rV   rW   )r   zCallable[..., T]r   r   rV   r   )r   intrV   bytes)r   r   rV   r   )r   r   rV   rW   )r   strrV   r   )rZ   r[   r\   r]   r   r5   r   r   r   r   r   r   r;   r:   r   r   ,  sW     L '+	22 +2 $	2
 
2 <86.r;   r   ).r   r   r`   zsocket.socket | Nonera   ssl_module.SSLContext | Nonerb   rY   rc   zOrigin | Nonerd   z'Sequence[ClientExtensionFactory] | Nonere   zSequence[Subprotocol] | Nonerf   rY   rG   rX   rH   rY   rg   zstr | Literal[True] | Nonerh   r   ri   rY   rj   rT   r-   rT   r.   rT   r/   rT   rk   rU   r0   rU   rl   zLoggerLike | Nonerm   ztype[ClientConnection] | Noner   r   rV   r'   )NN)rq   rY   r   rY   r   r   rV   r'   )
rg   r   r   r    r   r$   r   r   rV   rS   )r`   rS   r   r$   rV   r   )rg   r   r   r    r   r$   rH   rY   ra   r   rb   rY   r   r   rV   rS   )H
__future__r   r7   ra   r   r2   r|   collections.abcr   typingr   r   r   r   r	   clientr   datastructuresr   
exceptionsr   r   r   extensions.baser   extensions.permessage_deflater   r@   r   http11r   r   r8   r   r   rg   r   r   r   r   streamsr   r   r   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:   <module>r     s<   "     $ 8 8 # ( L L 4 L + ) ( J J " ? ? ) "  :b%z b%R "&(,"& :>15'-1$.(,.2(,!#"$!#"$;@<> $7;;F	F 	F
 
&F  F F 8F /F F +F "F &F  ,!F" &#F& 'F(  )F* +F,  -F0 91F2 :3F6 7F: 5;F< =F> ?FT <
<	< < 	<<4J&5 ##""##""	 	JJJ J 	J
 
J4N %)(,"&### #
 "# 
&#  # # #L CLCxQ'(M. M.  TTTT T 	T
 
TTs   :F FF