o
    /hH                     @  sz  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 de(Z,G dd dZ-		dGddddddddddeddddddddHd@dAZ.	dIdJdEdFZ/dS )K    )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                      sX   e Zd ZdZddd fddZddedfdddZd  fddZd! fddZ  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_timeoutsocketsocket.socketprotocolr   r!   Optional[float]returnNonec                  s$   |  t  | _t j|||d d S )Nr    )	threadingr   request_rcvdsuper__init__)selfr"   r$   r!   	__class__ O/var/www/html/govbot/env/lib/python3.10/site-packages/websockets/sync/server.pyr+   7   s   

zServerConnection.__init__Nprocess_requestCOptional[Callable[[ServerConnection, Request], Optional[Response]]]process_responseMOptional[Callable[[ServerConnection, Request, Response], Optional[Response]]]server_headerOptional[str]timeoutc                 C  s  | j |s|   | j  td| jdu r%|   | j  td| jt	d d| _
|durez	|| | j| _
W n( tyd } z|| j_| jjddd | jtjjd| _
W Y d}~nd}~ww | j
du rr| j| j| _
|dur||| j
jd	< |durz
|| | j| j
}W n( ty } z|| j_| jjddd | jtjjd| _
W Y d}~nd}~ww |dur|| _
| j| j
 W d   n1 sw   Y  | jjtur| j| j |   | j  | jjdur| jjdS )
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,   r1   r3   r5   r7   excrD   r/   r/   r0   	handshakeF   sb   



*
zServerConnection.handshakeeventr   c                   s<   | j du rt|tsJ || _ | j  dS t | dS )z.
        Process one incoming event.

        N)rA   
isinstancer   r)   setr*   process_event)r,   rS   r-   r/   r0   rV      s
   
zServerConnection.process_eventc                   s(   zt    W | j  dS | j  w )zI
        Read incoming data from the socket and process events.

        N)r*   recv_eventsr)   rU   r,   r-   r/   r0   rW      s   zServerConnection.recv_events)r"   r#   r$   r   r!   r%   r&   r'   )
r1   r2   r3   r4   r5   r6   r7   r%   r&   r'   )rS   r   r&   r'   r&   r'   )
__name__
__module____qualname____doc__r+   r   rR   rV   rW   __classcell__r/   r/   r-   r0   r      s    Qr   c                   @  sP   e 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   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.

    Nr"   r#   handler$Callable[[socket.socket, Any], None]rG   Optional[LoggerLike]c                 C  sF   || _ || _|d u rtd}|| _tjdkr!t \| _	| _
d S d S )Nzwebsockets.serverwin32)r"   r_   logging	getLoggerrG   sysplatformospipeshutdown_watchershutdown_notifier)r,   r"   r_   rG   r/   r/   r0   r+      s   

zWebSocketServer.__init__r&   r'   c                 C  s   t  }|| jt j tjdkr|| jt j 	 |  z	| j	 \}}W n
 t
y1   Y dS w tj| j||fd}|  q)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()

        rb   T)targetargsN)	selectorsDefaultSelectorregisterr"   
EVENT_READre   rf   ri   selectrM   OSErrorr(   Threadr_   start)r,   pollersockaddrthreadr/   r/   r0   serve_forever   s   
zWebSocketServer.serve_foreverc                 C  s*   | j   tjdkrt| jd dS dS )z@
        See :meth:`socketserver.BaseServer.shutdown`.

        rb      xN)r"   closere   rf   rg   writerj   rX   r/   r/   r0   shutdown   s   

zWebSocketServer.shutdownintc                 C  s
   | j  S )z>
        See :meth:`socketserver.BaseServer.fileno`.

        )r"   filenorX   r/   r/   r0   r      s   
zWebSocketServer.filenoc                 C  s   | S Nr/   rX   r/   r/   r0   	__enter__   s   zWebSocketServer.__enter__exc_typeOptional[Type[BaseException]]	exc_valueOptional[BaseException]	tracebackOptional[TracebackType]c                 C  s   |    d S r   )r}   )r,   r   r   r   r/   r/   r0   __exit__   s   zWebSocketServer.__exit__r   )r"   r#   r_   r`   rG   ra   rY   )r&   r~   )r&   r   )r   r   r   r   r   r   r&   r'   )
rZ   r[   r\   r]   r+   ry   r}   r   r   r   r/   r/   r/   r0   r      s    


	
r   Fdeflater   i   )rv   ssl_contextunixpathorigins
extensionssubprotocolsselect_subprotocolr1   r3   r5   compressionopen_timeoutr!   max_sizerG   create_connectionr_   "Callable[[ServerConnection], None]hostr6   portOptional[int]rv   Optional[socket.socket]r   Optional[ssl.SSLContext]r   boolr   r   $Optional[Sequence[Optional[Origin]]]r   *Optional[Sequence[ServerExtensionFactory]]r   Optional[Sequence[Subprotocol]]r   TOptional[Callable[[ServerConnection, Sequence[Subprotocol]], Optional[Subprotocol]]]r1   r2   r3   r4   r5   r   r   r%   r!   r   rG   ra   r    Optional[Type[ServerConnection]]r&   c                  s   durt  |dkrtn|durtd| du r"t|du rAr9|du r0tdtj|tjd}nt||f}n|durItddurUj|ddd	}d 	
fd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.
    Nr   zunsupported compression: zmissing path argument)familyz(path and sock arguments are incompatibleTF)server_sidedo_handshake_on_connectrv   r#   rw   r   r&   r'   c              	     s"  t }zYs| tjtjd d ur,| |  t| tj	s#J | 
  | d  d }d ur:d fdd	}t|td
}d usKJ | |d  	
|  W n tyk   |   Y d S w z  W n ty   |jjddd  tj Y d S w    d S )NTr$   r   r   Sequence[Subprotocol]r&   Optional[Subprotocol]c                   s$   d usJ |  j u sJ  |S r   )r$   )r$   r   )
connectionr   r/   r0   protocol_select_subprotocol  s   
z@serve.<locals>.conn_handler.<locals>.protocol_select_subprotocol)r   r   r   r   rP   r   rG   r    zconnection handler failedr9   )r$   r   r   r   r&   r   )r   
setsockoptr"   IPPROTO_TCPTCP_NODELAY
settimeoutr7   rT   ssl	SSLSocketdo_handshaker   r   rR   rE   r{   rG   rH   r	   INTERNAL_ERROR)rv   rw   deadliner   r$   r!   r   r   r_   rG   r   r   r   r1   r3   r   r5   r   r   r   )r   r0   conn_handler  sZ   
	zserve.<locals>.conn_handler)rv   r#   rw   r   r&   r'   )
r   r   
ValueErrorr   	TypeErrorr"   create_serverAF_UNIXwrap_socketr   )r_   r   r   rv   r   r   r   r   r   r   r   r1   r3   r5   r   r   r!   r   rG   r   r   r/   r   r0   r   	  s0   {
*	Tr   !Callable[[ServerConnection], Any]kwargsr   c                 K  s   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   )r_   r   r   r/   r/   r0   r     s   r   )NN)*r_   r   r   r6   r   r   rv   r   r   r   r   r   r   r6   r   r   r   r   r   r   r   r   r1   r2   r3   r4   r5   r6   r   r6   r   r%   r!   r%   r   r   rG   ra   r   r   r&   r   r   )r_   r   r   r6   r   r   r&   r   )0
__future__r   rJ   rc   rg   rm   r"   r   re   r(   typesr   typingr   r   r   r   r   websockets.framesr	   extensions.baser   extensions.permessage_deflater   rN   r   r   http11r   r   r$   r   r   r   serverr   r   r   r   r   r   utilsr   __all__r   r   r   r   r/   r/   r/   r0   <module>   sd     Z y