
    2BfH                       d dl mZ d dlZd dlZd dlZd dl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 dd	l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$m%Z%m&Z& ddl'm(Z( ddl)m*Z* g dZ+ G d de(      Z, G d d      Z-	 	 dddddddddddeddddddd	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 ddZ.	 d 	 	 	 	 	 	 	 d!dZ/y)"    )annotationsN)TracebackType)AnyCallableOptionalSequenceType)	CloseCode   )ServerExtensionFactory) enable_server_permessage_deflate)validate_subprotocols)
USER_AGENT)RequestResponse)
CONNECTINGOPENEvent)ServerProtocol)
LoggerLikeOriginSubprotocol   )
Connection)Deadline)serve
unix_serveServerConnectionWebSocketServerc                  t     e Zd ZdZdd	 	 	 	 	 	 	 d	 fdZddedf	 	 	 	 	 	 	 	 	 d
dZd fdZd fdZ xZ	S )r   a  
    Threaded implementation of a WebSocket server connection.

    :class:`ServerConnection` 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.

    Args:
        socket: Socket connected to a WebSocket client.
        protocol: Sans-I/O connection.
        close_timeout: Timeout for closing the connection in seconds.

    
   close_timeoutc               `    |  t        j                         | _        t        |   |||       y )Nr"   )	threadingr   request_rcvdsuper__init__)selfsocketprotocolr#   	__class__s       V/var/www/highfloat_scraper/venv/lib/python3.12/site-packages/websockets/sync/server.pyr(   zServerConnection.__init__7   s2     	%OO-' 	 	
    Nc                *   | j                   j                  |      s5| j                          | j                  j	                          t        d      | j                  5| j                          | j                  j	                          t        d      | j                  t              5  d| _
        |	  || | j                        | _
        | j                  *| j                  j)                  | j                        | _
        ||| j                  j*                  d	<   |)	  || | j                  | j                        }||| _
        	 | j                  j-                  | j                         ddd       | j                  j.                  t0        urO| j                  j	                  | j2                         | j                          | j                  j	                          | j                  j                  | j                  j                  y# t        $ rr}|| j                  _        | j                  j                  dd       | j                  j!                  t"        j$                  j&                  d      | _
        Y d}~d}~ww xY w# t        $ rr}|| j                  _        | j                  j                  dd       | j                  j!                  t"        j$                  j&                  d      | _
        Y d}~d}~ww xY w# 1 sw Y   xY w)
z1
        Perform the opening handshake.

        ztimed out during handshakeNz"connection closed during handshake)expected_statezopening handshake failedTexc_infozLFailed to open a WebSocket connection.
See server log for more information.
Server)r&   waitclose_socketrecv_events_threadjoinTimeoutErrorrequestConnectionErrorsend_contextr   response	Exceptionr+   handshake_excloggererrorrejecthttp
HTTPStatusINTERNAL_SERVER_ERRORacceptheaderssend_responsestater   r#   )r)   process_requestprocess_responseserver_headertimeoutexcr<   s          r-   	handshakezServerConnection.handshakeF   s{   *   %%g.##((*;<<<<##((*!"FGGj9 (	7 DM*$3D$,,$GDM }}$ $ 4 4T\\ B(2?%%h/+1/dllDMMRH  +(0MM''6Q(	7T ==d*##((););<##((*==&&2----- 3S ! 	25DMM/KK%%&@4%P$(MM$8$8==E%DMM	( ! 	25DMM/KK%%&@4%P$(MM$8$8==E%DMM	5(	7 (	7sc   (
L3HALJ
=/L	JA'J<LJL
	LA'L :L LLLc                    | j                   4t        |t              sJ || _         | j                  j	                          yt
        |   |       y)z.
        Process one incoming event.

        N)r9   
isinstancer   r&   setr'   process_event)r)   eventr,   s     r-   rR   zServerConnection.process_event   sG     <<eW--- DL!!# G!%(r.   c                    	 t         |           | j                  j                          y# | j                  j                          w xY w)zI
        Read incoming data from the socket and process events.

        N)r'   recv_eventsr&   rQ   )r)   r,   s    r-   rU   zServerConnection.recv_events   s:    
	$G! !!#D!!#s	   , A)r*   socket.socketr+   r   r#   Optional[float]returnNone)
rI   COptional[Callable[[ServerConnection, Request], Optional[Response]]]rJ   MOptional[Callable[[ServerConnection, Request, Response], Optional[Response]]]rK   Optional[str]rL   rW   rX   rY   )rS   r   rX   rY   rX   rY   )
__name__
__module____qualname____doc__r(   r   rN   rR   rU   __classcell__)r,   s   @r-   r   r      s    8 *,

 !

 '
 

,  '1#'O.
O.
O. %O. !O.  
!O.b)	$ 	$r.   r   c                  ^    e 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   a  
    WebSocket server returned by :func:`serve`.

    This class mirrors the API of :class:`~socketserver.BaseServer`, notably the
    :meth:`~socketserver.BaseServer.serve_forever` and
    :meth:`~socketserver.BaseServer.shutdown` methods, as well as the context
    manager protocol.

    Args:
        socket: Server socket listening for new connections.
        handler: Handler for one connection. Receives the socket and address
            returned by :meth:`~socket.socket.accept`.
        logger: Logger for this server.

    Nc                    || _         || _        |t        j                  d      }|| _        t
        j                  dk7  r"t        j                         \  | _	        | _
        y y )Nzwebsockets.serverwin32)r*   handlerlogging	getLoggerr?   sysplatformospipeshutdown_watchershutdown_notifier)r)   r*   rf   r?   s       r-   r(   zWebSocketServer.__init__   sV     >&&':;F<<7"<>GGI9D!4#9 #r.   c                   t        j                         }|j                  | j                  t         j                         t
        j                  dk7  r*|j                  | j                  t         j                         	 |j                          	 | j                  j                         \  }}t        j                  | j                  ||f      }|j                          b# t        $ r Y yw xY w)a  
        See :meth:`socketserver.BaseServer.serve_forever`.

        This method doesn't return. Calling :meth:`shutdown` from another thread
        stops the server.

        Typical use::

            with serve(...) as server:
                server.serve_forever()

        re   )targetargsN)	selectorsDefaultSelectorregisterr*   
EVENT_READri   rj   rm   selectrE   OSErrorr%   Threadrf   start)r)   pollersockaddrthreads        r-   serve_foreverzWebSocketServer.serve_forever   s     **,Y%9%9:<<7"OOD1193G3GHMMO "[[//1
d %%T\\tMFLLN   s   C 	C+*C+c                    | j                   j                          t        j                  dk7  r!t	        j
                  | j                  d       yy)z@
        See :meth:`socketserver.BaseServer.shutdown`.

        re      xN)r*   closeri   rj   rk   writern   r)   s    r-   shutdownzWebSocketServer.shutdown   s9    
 	<<7"HHT++T2 #r.   c                6    | j                   j                         S )z>
        See :meth:`socketserver.BaseServer.fileno`.

        )r*   filenor   s    r-   r   zWebSocketServer.fileno   s    
 {{!!##r.   c                    | S N r   s    r-   	__enter__zWebSocketServer.__enter__   s    r.   c                $    | j                          y r   )r   )r)   exc_type	exc_value	tracebacks       r-   __exit__zWebSocketServer.__exit__   s     	r.   r   )r*   rV   rf   z$Callable[[socket.socket, Any], None]r?   Optional[LoggerLike]r]   )rX   int)rX   r   )r   zOptional[Type[BaseException]]r   zOptional[BaseException]r   zOptional[TracebackType]rX   rY   )
r^   r_   r`   ra   r(   r~   r   r   r   r   r   r.   r-   r   r      sp    ( (,	FF 6F %	F:3$/ + +	
 
r.   r   Fdeflater!   i   )r{   ssl_contextunixpathorigins
extensionssubprotocolsselect_subprotocolrI   rJ   rK   compressionopen_timeoutr#   max_sizer?   create_connectionc                  	
 	t        	       |dk(  rt              n|t        d|       t        |Mr3|t	        d      t        j                  |t
        j                        }n%t        j                  ||f      }n|t	        d      j                  |dd      }d
 
	fd	}t        ||      S )aH  
    Create a WebSocket server listening on ``host`` and ``port``.

    Whenever a client connects, the server creates a :class:`ServerConnection`,
    performs the opening handshake, and delegates to the ``handler``.

    The handler receives a :class:`ServerConnection` instance, which you can use
    to send and receive messages.

    Once the handler completes, either normally or with an exception, the server
    performs the closing handshake and closes the connection.

    :class:`WebSocketServer` mirrors the API of
    :class:`~socketserver.BaseServer`. Treat it as a context manager to ensure
    that it will be closed and call the :meth:`~WebSocketServer.serve_forever`
    method to serve requests::

        def handler(websocket):
            ...

        with websockets.sync.server.serve(handler, ...) as server:
            server.serve_forever()

    Args:
        handler: Connection handler. It receives the WebSocket connection,
            which is a :class:`ServerConnection`, in argument.
        host: Network interfaces the server binds to.
            See :func:`~socket.create_server` for details.
        port: TCP port the server listens on.
            See :func:`~socket.create_server` for details.
        sock: Preexisting TCP socket. ``sock`` replaces ``host`` and ``port``.
            You may call :func:`socket.create_server` to create a suitable TCP
            socket.
        ssl_context: Configuration for enabling TLS on the connection.
        origins: Acceptable values of the ``Origin`` header, for defending
            against Cross-Site WebSocket Hijacking attacks. Include :obj:`None`
            in the list if the lack of an origin is acceptable.
        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.
        select_subprotocol: Callback for selecting a subprotocol among
            those supported by the client and the server. It receives a
            :class:`ServerConnection` (not a
            :class:`~websockets.server.ServerProtocol`!) instance and a list of
            subprotocols offered by the client. Other than the first argument,
            it has the same behavior as the
            :meth:`ServerProtocol.select_subprotocol
            <websockets.server.ServerProtocol.select_subprotocol>` method.
        process_request: Intercept the request during the opening handshake.
            Return an HTTP response to force the response or :obj:`None` to
            continue normally. When you force an HTTP 101 Continue response,
            the handshake is successful. Else, the connection is aborted.
        process_response: Intercept the response during the opening handshake.
            Return an HTTP response to force the response or :obj:`None` to
            continue normally. When you force an HTTP 101 Continue response,
            the handshake is successful. Else, the connection is aborted.
        server_header: Value of  the ``Server`` response header.
            It defaults to ``"Python/x.y.z websockets/X.Y"``. Setting it to
            :obj:`None` removes the header.
        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.
        open_timeout: Timeout for opening connections in seconds.
            :obj:`None` disables the timeout.
        close_timeout: Timeout for closing connections in seconds.
            :obj:`None` disables the timeout.
        max_size: Maximum size of incoming messages in bytes.
            :obj:`None` disables the limit.
        logger: Logger for this server.
            It defaults to ``logging.getLogger("websockets.server")``. See the
            :doc:`logging guide <../../topics/logging>` for details.
        create_connection: Factory for the :class:`ServerConnection` managing
            the connection. Set it to a wrapper or a subclass to customize
            connection handling.
    r   zunsupported compression: zmissing path argument)familyz(path and sock arguments are incompatibleTF)server_sidedo_handshake_on_connectc           	        t              }	 s/| j                  t        j                  t        j                  d       \| j                  |j                                t        | t        j                        sJ | j                          | j                  d        d }	 	 	 	 	 	 dfd}t        |t        
      }J  | |      j                  |j                                	  	       j                          y # t        $ r | j                          Y y w xY w# t        $ r? |j                   j#                  dd       j                  t$        j&                         Y y w xY w)NTc                >    J | j                   u sJ  |      S r   )r+   )r+   r   
connectionr   s     r-   protocol_select_subprotocolz@serve.<locals>.conn_handler.<locals>.protocol_select_subprotocol  s2    
 .999#z':'::::-j,GGr.   )r   r   r   r   rH   r   r?   r"   zconnection handler failedr1   )r+   r   r   zSequence[Subprotocol]rX   zOptional[Subprotocol])r   
setsockoptr*   IPPROTO_TCPTCP_NODELAY
settimeoutrL   rP   ssl	SSLSocketdo_handshaker   r   rN   r=   r   r?   r@   r
   INTERNAL_ERROR)r{   r|   deadliner   r+   r   r#   r   r   rf   r?   r   r   r   rI   rJ   r   rK   r   r   r   s        @r-   conn_handlerzserve.<locals>.conn_handler  s    L)B	  2 2F4F4FM & 0 0 23!$666!!#%  ( "-H,H"7H +H &%)#> !H %000*+J      "		J
   	JJL	  	7OO!!"=!MY556	7s%   C'D 7D/ D,+D,/AE76E7)r{   rV   r|   r   rX   rY   )
r   r   
ValueErrorr   	TypeErrorr*   create_serverAF_UNIXwrap_socketr   )rf   hostportr{   r   r   r   r   r   r   r   rI   rJ   rK   r   r   r#   r   r?   r   r   s   `   `` ``````` ````` r-   r   r   	  s    v l+i5jA
		 4[MBCC , || 788''V^^DD''t5DFGG &&$)	 ' 
P P Ph 4v66r.   c                     t        | f|dd|S )a  
    Create a WebSocket server listening on a Unix socket.

    This function is identical to :func:`serve`, except the ``host`` and
    ``port`` arguments are replaced by ``path``. It's only available on Unix.

    It's useful for deploying a server behind a reverse proxy such as nginx.

    Args:
        handler: Connection handler. It receives the WebSocket connection,
            which is a :class:`ServerConnection`, in argument.
        path: File system path to the Unix socket.

    T)r   r   )r   )rf   r   kwargss      r-   r   r     s    & 9t$9&99r.   )NN)*rf   z"Callable[[ServerConnection], None]r   r\   r   Optional[int]r{   zOptional[socket.socket]r   zOptional[ssl.SSLContext]r   boolr   r\   r   z$Optional[Sequence[Optional[Origin]]]r   z*Optional[Sequence[ServerExtensionFactory]]r   zOptional[Sequence[Subprotocol]]r   zTOptional[Callable[[ServerConnection, Sequence[Subprotocol]], Optional[Subprotocol]]]rI   rZ   rJ   r[   rK   r\   r   r\   r   rW   r#   rW   r   r   r?   r   r   z Optional[Type[ServerConnection]]rX   r   r   )rf   z!Callable[[ServerConnection], Any]r   r\   r   r   rX   r   )0
__future__r   rB   rg   rk   rr   r*   r   ri   r%   typesr   typingr   r   r   r   r	   websockets.framesr
   extensions.baser   extensions.permessage_deflater   rF   r   r   http11r   r   r+   r   r   r   serverr   r   r   r   r   r   utilsr   __all__r   r   r   r   r   r.   r-   <module>r      s   "   	   
 
   : : ' 4 L +  & . . # 4 4 "  IO$z O$dU Ut s7 %),048=A48 	 	 	#-!*$&%'##':>Us7/s7
s7 s7 "s7 *s7 s7 s7 2s7 ;s7 2s7s7()s745s7@ !As7B Cs7F "Gs7H #Is7L Ms7P !Qs7T 8Us7V Ws7p :.:
: : 	:r.   