o
    [h                     @  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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mZmZmZmZ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!m"Z"m#Z#m$Z$m%Z%m&Z&m'Z' dd	l(m)Z)m*Z* dd
l+m,Z, ddl-m.Z.m/Z/m0Z0m1Z1 ddlm2Z2 ddlm3Z3m4Z4m5Z5m6Z6 ddl7m8Z8 ddl9m:Z:m;Z; ddlm<Z< ddl=m>Z> g dZ?eeee@egef f ZAeejBeeCf ZDG dd de>ZEG dd dZFG dd dZGeGZH	d&d'd!d"ZId(d$d%ZJdS ))    )annotationsN)TracebackType)Any	AwaitableCallable	GeneratorListOptionalSequenceSetTupleTypeUnioncast   )State)HeadersHeadersLikeMultipleValuesError)AbortHandshakeInvalidHandshakeInvalidHeaderInvalidMessageInvalidOriginInvalidUpgradeNegotiationError)	ExtensionServerExtensionFactory) enable_server_permessage_deflate)build_extensionparse_extensionparse_subprotocolvalidate_subprotocols)
USER_AGENT)ExtensionHeader
LoggerLikeOriginSubprotocol   )loop_if_py_lt_38)build_responsecheck_request)read_request)WebSocketCommonProtocol)serve
unix_serveWebSocketServerProtocolWebSocketServerc                      s   e Zd ZdZdZdZdddddddddG fddZdH fd d!ZdId"d#ZdJd%d&Z		dKdLd-d.Z
dMd3d4Ze	dKdNd6d7ZedOd:d;ZdPd>d?ZdQdCdDZ				dRdSdEdFZ  ZS )Tr0   ag  
    WebSocket server connection.

    :class:`WebSocketServerProtocol` provides :meth:`recv` and :meth:`send`
    coroutines for receiving and sending messages.

    It supports asynchronous iteration to receive messages::

        async for message in websocket:
            await process(message)

    The iterator exits normally when the connection is closed with close code
    1000 (OK) or 1001 (going away). It raises
    a :exc:`~websockets.exceptions.ConnectionClosedError` when the connection
    is closed with any other code.

    You may customize the opening handshake in a subclass by
    overriding :meth:`process_request` or :meth:`select_subprotocol`.

    Args:
        ws_server: WebSocket server that created this connection.

    See :func:`serve` for the documentation of ``ws_handler``, ``logger``, ``origins``,
    ``extensions``, ``subprotocols``, and ``extra_headers``.

    See :class:`~websockets.legacy.protocol.WebSocketCommonProtocol` for the
    documentation of ``ping_interval``, ``ping_timeout``, ``close_timeout``,
    ``max_size``, ``max_queue``, ``read_limit``, and ``write_limit``.

    FserverN)loggerorigins
extensionssubprotocolsextra_headersprocess_requestselect_subprotocol
ws_handlertUnion[Callable[[WebSocketServerProtocol], Awaitable[Any]], Callable[[WebSocketServerProtocol, str], Awaitable[Any]]]	ws_serverr1   r3   Optional[LoggerLike]r4   $Optional[Sequence[Optional[Origin]]]r5   *Optional[Sequence[ServerExtensionFactory]]r6   Optional[Sequence[Subprotocol]]r7   Optional[HeadersLikeOrCallable]r8   EOptional[Callable[[str, Headers], Awaitable[Optional[HTTPResponse]]]]r9   OOptional[Callable[[Sequence[Subprotocol], Sequence[Subprotocol]], Subprotocol]]kwargsr   returnNonec                  s   |d u r	t d}t jdd|i|
 |d ur)d|v r)tdt dd |D }t|| _|| _	|| _
|| _|| _|| _|| _|	| _d S )Nwebsockets.serverr3    z!use None instead of '' in originsc                 S  s   g | ]
}|d kr
dn|qS )rH   N ).0originrI   rI   /home/ubuntu/experiments/live_experiments/Pythonexperiments/Otree/venv/lib/python3.10/site-packages/websockets/legacy/server.py
<listcomp>|   s    z4WebSocketServerProtocol.__init__.<locals>.<listcomp>rI   )logging	getLoggersuper__init__warningswarnDeprecationWarningremove_path_argumentr:   r<   r4   available_extensionsavailable_subprotocolsr7   _process_request_select_subprotocol)selfr:   r<   r3   r4   r5   r6   r7   r8   r9   rD   	__class__rI   rL   rQ   a   s   


z WebSocketServerProtocol.__init__	transportasyncio.BaseTransportc                   s.   t  | | j|  | j|  | _dS )zJ
        Register connection and initialize a task to handle it.

        N)rP   connection_mader<   registerloopcreate_taskhandlerhandler_task)rZ   r]   r[   rI   rL   r_      s   z'WebSocketServerProtocol.connection_madec                   sJ  zzYz| j | j| j| j| jdI dH  W n tjy      ty'     ty } zt	|t
r@|j|j|j}}}n{t	|trb| jrP| jjddd tjjt d| d }}}nYt	|tr| jrr| jjddd tjjtd	gd| d
 }}}n5t	|tr| jr| jjddd tjjt d| d }}}n| jjddd tjjt d}}}|dtjjdd |dt  |dt!t"| |dd |dd | #||| | j$d|j%|j& | ' I dH  W Y d}~W W | j()|  | j$d dS d}~ww z
| *| I dH  W n ty8   | jjddd | j+s7| ,d  w z	| - I dH  W n tyK     ty[   | jjddd  w W n tyy   z| j.-  W n
 tyv   Y nw Y nw W | j()|  | j$d dS W | j()|  | j$d dS | j()|  | j$d w )z
        Handle the lifecycle of a WebSocket connection.

        Since this method doesn't have a caller able to handle exceptions, it
        attemps to log relevant ones and guarantees that the TCP connection is
        closed before exiting.

        )r4   rV   rW   r7   Nz! invalid originT)exc_infoz'Failed to open a WebSocket connection: z.
z! invalid upgrade)ZUpgrade	websocketz^.

You cannot access a WebSocket server directly with a browser. You need a WebSocket client.
z! invalid handshakezopening handshake failedsL   Failed to open a WebSocket connection.
See server log for more information.
DateusegmtServerzContent-LengthzContent-Typez
text/plain
Connectionclosezconnection failed (%d %s)zconnection closedzconnection handler failedi  zclosing handshake failed)/	handshaker4   rV   rW   r7   asyncioCancelledErrorConnectionError	Exception
isinstancer   statusheadersbodyr   debugr3   http
HTTPStatus	FORBIDDENr   encoder   UPGRADE_REQUIREDr   BAD_REQUESTerrorINTERNAL_SERVER_ERROR
setdefaultemailutils
formatdater#   strlenwrite_http_responseinfovaluephraseZclose_transportr<   
unregisterr:   closedZfail_connectionrl   r]   )rZ   excrs   rt   ru   rI   rI   rL   rc      s   	






	
8
zWebSocketServerProtocol.handlerTuple[str, Headers]c              
     s   zt | jI dH \}}W n tjy     ty& } ztd|d}~ww | jrB| jd| | D ]\}}| jd|| q5|| _	|| _
||fS )a:  
        Read request line and headers from the HTTP request.

        If the request contains a body, it may be read from ``self.reader``
        after this coroutine returns.

        Raises:
            InvalidMessage: if the HTTP message is malformed or isn't an
                HTTP/1.1 GET request.

        Nz$did not receive a valid HTTP requestz< GET %s HTTP/1.1z< %s: %s)r,   readerrn   ro   rq   r   rv   r3   	raw_itemspathrequest_headers)rZ   r   rt   r   keyr   rI   rI   rL   read_http_request  s    
z)WebSocketServerProtocol.read_http_requestrs   http.HTTPStatusrt   r   ru   Optional[bytes]c                 C  s   || _ | jr.| jd|j|j | D ]\}}| jd|| q|dur.| jdt| d|j d|j d}|t|7 }| j	|
  |durS| j	| dS dS )z
        Write status line and headers to the HTTP response.

        This coroutine is also able to write a response body.

        z> HTTP/1.1 %d %sz> %s: %sNz> [body] (%d bytes)z	HTTP/1.1  z
)response_headersrv   r3   r   r   r   r   r   r]   writerz   )rZ   rs   rt   ru   r   r   responserI   rI   rL   r   "  s   	z+WebSocketServerProtocol.write_http_responser   r   r   Optional[HTTPResponse]c                   s@   | j dur|  ||}t|tr|I dH S tdt |S dS )a  
        Intercept the HTTP request and return an HTTP response if appropriate.

        You may override this method in a :class:`WebSocketServerProtocol`
        subclass, for example:

        * to return a HTTP 200 OK response on a given path; then a load
          balancer can use this path for a health check;
        * to authenticate the request and return a HTTP 401 Unauthorized or a
          HTTP 403 Forbidden when authentication fails.

        You may also override this method with the ``process_request``
        argument of :func:`serve` and :class:`WebSocketServerProtocol`. This
        is equivalent, except ``process_request`` won't have access to the
        protocol instance, so it can't store information for later use.

        :meth:`process_request` is expected to complete quickly. If it may run
        for a long time, then it should await :meth:`wait_closed` and exit if
        :meth:`wait_closed` completes, or else it could prevent the server
        from shutting down.

        Args:
            path: request path, including optional query string.
            request_headers: request headers.

        Returns:
            Optional[Tuple[http.HTTPStatus, HeadersLike, bytes]]: :obj:`None`
            to continue the WebSocket handshake normally.

            An HTTP response, represented by a 3-uple of the response status,
            headers, and body, to abort the WebSocket handshake and return
            that HTTP response instead.

        N&declare process_request as a coroutine)rX   rr   r   rR   rS   rT   )rZ   r   r   r   rI   rI   rL   r8   >  s   
%

z'WebSocketServerProtocol.process_requestOptional[Origin]c              
   C  sZ   zt tt | d}W n ty } ztdd|d}~ww |dur+||vr+t||S )z
        Handle the Origin HTTP request header.

        Args:
            headers: request headers.
            origins: optional list of acceptable origins.

        Raises:
            InvalidOrigin: if the origin isn't acceptable.

        r&   z!more than one Origin header foundN)r   r	   r&   getr   r   r   )rt   r4   rK   r   rI   rI   rL   process_origino  s   z&WebSocketServerProtocol.process_originrV   %Tuple[Optional[str], List[Extension]]c              
   C  s   d}g }g }|  d}|rK|rKtdd |D g }|D ]/\}}|D ](}	|	j|kr)q!z
|	||\}
}W n	 ty<   Y q!w |||
f ||  q|rQt|}||fS )a  
        Handle the Sec-WebSocket-Extensions HTTP request header.

        Accept or reject each extension proposed in the client request.
        Negotiate parameters for accepted extensions.

        Return the Sec-WebSocket-Extensions HTTP response header and the list
        of accepted extensions.

        :rfc:`6455` leaves the rules up to the specification of each
        :extension.

        To provide this level of flexibility, for each extension proposed by
        the client, we check for a match with each extension available in the
        server configuration. If no match is found, the extension is ignored.

        If several variants of the same extension are proposed by the client,
        it may be accepted several times, which won't make sense in general.
        Extensions must implement their own requirements. For this purpose,
        the list of previously accepted extensions is provided.

        This process doesn't allow the server to reorder extensions. It can
        only select a subset of the extensions proposed by the client.

        Other requirements, for example related to mandatory extensions or the
        order of extensions, may be implemented by overriding this method.

        Args:
            headers: request headers.
            extensions: optional list of supported extensions.

        Raises:
            InvalidHandshake: to abort the handshake with an HTTP 400 error.

        NSec-WebSocket-Extensionsc                 S     g | ]}t |qS rI   )r    rJ   header_valuerI   rI   rL   rM         z>WebSocketServerProtocol.process_extensions.<locals>.<listcomp>)get_allsumnameZprocess_request_paramsr   appendr   )rt   rV   Zresponse_header_valueZextension_headersZaccepted_extensionsheader_valuesparsed_header_valuesr   Zrequest_paramsZext_factoryZresponse_params	extensionrI   rI   rL   process_extensions  s4   (


z*WebSocketServerProtocol.process_extensionsrW   Optional[Subprotocol]c                 C  s:   d}| d}|r|rtdd |D g }| ||}|S )a  
        Handle the Sec-WebSocket-Protocol HTTP request header.

        Return Sec-WebSocket-Protocol HTTP response header, which is the same
        as the selected subprotocol.

        Args:
            headers: request headers.
            available_subprotocols: optional list of supported subprotocols.

        Raises:
            InvalidHandshake: to abort the handshake with an HTTP 400 error.

        NSec-WebSocket-Protocolc                 S  r   rI   )r!   r   rI   rI   rL   rM     r   z?WebSocketServerProtocol.process_subprotocol.<locals>.<listcomp>)r   r   r9   )rZ   rt   rW   subprotocolr   r   rI   rI   rL   process_subprotocol  s   
z+WebSocketServerProtocol.process_subprotocolclient_subprotocolsSequence[Subprotocol]server_subprotocolsc                   sL   | j dur|   S t t@ }|sdS  fdd}t||dd S )a@  
        Pick a subprotocol among those offered by the client.

        If several subprotocols are supported by the client and the server,
        the default implementation selects the preferred subprotocol by
        giving equal value to the priorities of the client and the server.
        If no subprotocol is supported by the client and the server, it
        proceeds without a subprotocol.

        This is unlikely to be the most useful implementation in practice.
        Many servers providing a subprotocol will require that the client
        uses that subprotocol. Such rules can be implemented in a subclass.

        You may also override this method with the ``select_subprotocol``
        argument of :func:`serve` and :class:`WebSocketServerProtocol`.

        Args:
            client_subprotocols: list of subprotocols offered by the client.
            server_subprotocols: list of subprotocols available on the server.

        Returns:
            Optional[Subprotocol]: Selected subprotocol.

            :obj:`None` to continue without a subprotocol.


        Nc                   s     |  |  S N)index)pr   r   rI   rL   <lambda>&  s   z<WebSocketServerProtocol.select_subprotocol.<locals>.<lambda>)r   r   )rY   setsorted)rZ   r   r   r6   priorityrI   r   rL   r9      s   
 z*WebSocketServerProtocol.select_subprotocolc                   s\  |   I dH \}}| ||}t|tr|I dH }ntdt |}| jtj	u r-| 
 | j s9tjjg df}|durAt| t|}	| ||| _| ||\}
| _| || }| _t }t||	 |
durn|
|d< |durv||d< t|r||| j}|dur|| |dtjj dd |d	t! | "tjj#| | j$%d
 | &  |S )a  
        Perform the server side of the opening handshake.

        Args:
            origins: list of acceptable values of the Origin HTTP header;
                include :obj:`None` if the lack of an origin is acceptable.
            extensions: list of supported extensions, in order in which they
                should be tried.
            subprotocols: list of supported subprotocols, in order of
                decreasing preference.
            extra_headers: arbitrary HTTP headers to add to the response when
                the handshake succeeds.

        Returns:
            str: path of the URI of the request.

        Raises:
            InvalidHandshake: if the handshake fails.

        Nr   s   Server is shutting down.
r   r   rg   Trh   rj   zconnection open)'r   r8   rr   r   rR   rS   rT   stater   ZCLOSEDZconnection_closed_excr<   
is_servingrw   rx   SERVICE_UNAVAILABLEr   r+   r   rK   r   r5   r   r   r   r*   callabler   updater   r   r   r   r#   r   SWITCHING_PROTOCOLSr3   r   Zconnection_open)rZ   r4   rV   rW   r7   r   r   Zearly_response_awaitableZearly_responser   Zextensions_headerZprotocol_headerr   rI   rI   rL   rm   +  sP   





z!WebSocketServerProtocol.handshake)r:   r;   r<   r1   r3   r=   r4   r>   r5   r?   r6   r@   r7   rA   r8   rB   r9   rC   rD   r   rE   rF   )r]   r^   rE   rF   rE   rF   )rE   r   r   )rs   r   rt   r   ru   r   rE   rF   )r   r   r   r   rE   r   )rt   r   r4   r>   rE   r   )rt   r   rV   r?   rE   r   )rt   r   rW   r@   rE   r   )r   r   r   r   rE   r   )NNNN)
r4   r>   rV   r?   rW   r@   r7   rA   rE   r   )__name__
__module____qualname____doc__Z	is_clientZsiderQ   r_   rc   r   r   r8   staticmethodr   r   r   r9   rm   __classcell__rI   rI   r[   rL   r0   >   s<    
(

o
1
U
!-r0   c                   @  s   e Zd ZdZd0d1ddZd2ddZd3ddZd3ddZd4ddZd4ddZ	d4ddZ
d5ddZd6ddZd4dd Zd4d!d"Zed7d$d%Zd8d&d'Zd9d.d/ZdS ):r1   a  
    WebSocket server returned by :func:`serve`.

    This class provides the same interface as :class:`~asyncio.Server`,
    notably the :meth:`~asyncio.Server.close`
    and :meth:`~asyncio.Server.wait_closed` methods.

    It keeps track of WebSocket connections in order to close them properly
    when shutting down.

    Args:
        logger: logger for this server;
            defaults to ``logging.getLogger("websockets.server")``;
            see the :doc:`logging guide <../topics/logging>` for details.

    Nr3   r=   c                 C  s.   |d u r	t d}|| _t | _d | _|  d S )NrG   )rN   rO   r3   r   
websockets
close_task)rZ   r3   rI   rI   rL   rQ     s   
zWebSocketServer.__init__r2   asyncio.AbstractServerrE   rF   c                 C  s   || _ |jdus
J |jD ]8}|jtjkrd|  }n"|jtjkr-d| dd  }n|jtjkr8| }nt| }| j	
d| q|  | _dS )a  
        Attach to a given :class:`~asyncio.Server`.

        Since :meth:`~asyncio.loop.create_server` doesn't support injecting a
        custom ``Server`` class, the easiest solution that doesn't rely on
        private :mod:`asyncio` APIs is to:

        - instantiate a :class:`WebSocketServer`
        - give the protocol factory a reference to that instance
        - call :meth:`~asyncio.loop.create_server` with the factory
        - attach the resulting :class:`~asyncio.Server` with this method

        Nz%s:%dz[%s]:%dr   zserver listening on %s)r2   socketsfamilysocketAF_INETgetsocknameAF_INET6AF_UNIXr   r3   r   get_loopZcreate_futureclosed_waiter)rZ   r2   sockr   rI   rI   rL   wrap  s   

zWebSocketServer.wrapprotocolr0   c                 C     | j | dS )z:
        Register a connection with this server.

        N)r   addrZ   r   rI   rI   rL   r`        zWebSocketServer.registerc                 C  r   )z<
        Unregister a connection with this server.

        N)r   remover   rI   rI   rL   r     r   zWebSocketServer.unregisterc                 C  s&   | j du r|  |  | _ dS dS )a  
        Close the server.

        This method:

        * closes the underlying :class:`~asyncio.Server`;
        * rejects new WebSocket connections with an HTTP 503 (service
          unavailable) error; this happens when the server accepted the TCP
          connection but didn't complete the WebSocket opening handshake prior
          to closing;
        * closes open WebSocket connections with close code 1001 (going away).

        :meth:`close` is idempotent.

        N)r   r   rb   _closerZ   rI   rI   rL   rl     s   
zWebSocketServer.closec                   s   | j d | j  | j I dH  tjdi t|  I dH  | j	r<tj
dd | j	D fi t|  I dH  | j	rUtj
dd | j	D fi t|  I dH  | jd | j d dS )	a   
        Implementation of :meth:`close`.

        This calls :meth:`~asyncio.Server.close` on the underlying
        :class:`~asyncio.Server` object to stop accepting new connections and
        then closes open connections with close code 1001.

        zserver closingNr   c                 S  s   g | ]
}t |d qS )i  )rn   rb   rl   rJ   rf   rI   rI   rL   rM     s    z*WebSocketServer._close.<locals>.<listcomp>c                 S  s   g | ]}|j qS rI   )rd   r   rI   rI   rL   rM     s    zserver closed)r   )r3   r   r2   rl   wait_closedrn   sleepr)   r   r   waitr   Z
set_resultr   rI   rI   rL   r     s*   	


zWebSocketServer._closec                   s   t | jI dH  dS )a  
        Wait until the server is closed.

        When :meth:`wait_closed` returns, all TCP connections are closed and
        all connection handlers have returned.

        To ensure a fast shutdown, a connection handler should always be
        awaiting at least one of:

        * :meth:`~WebSocketServerProtocol.recv`: when the connection is closed,
          it raises :exc:`~websockets.exceptions.ConnectionClosedOK`;
        * :meth:`~WebSocketServerProtocol.wait_closed`: when the connection is
          closed, it returns.

        Then the connection handler is immediately notified of the shutdown;
        it can clean up and exit.

        N)rn   shieldr   r   rI   rI   rL   r     s   zWebSocketServer.wait_closedasyncio.AbstractEventLoopc                 C  
   | j  S )z7
        See :meth:`asyncio.Server.get_loop`.

        )r2   r   r   rI   rI   rL   r   0     
zWebSocketServer.get_loopboolc                 C  r   )z9
        See :meth:`asyncio.Server.is_serving`.

        )r2   r   r   rI   rI   rL   r   7  r   zWebSocketServer.is_servingc                      | j  I dH  dS )z<
        See :meth:`asyncio.Server.start_serving`.

        N)r2   start_servingr   rI   rI   rL   r   >     zWebSocketServer.start_servingc                   r   )z<
        See :meth:`asyncio.Server.serve_forever`.

        N)r2   serve_foreverr   rI   rI   rL   r   E  r   zWebSocketServer.serve_foreverOptional[List[socket.socket]]c                 C  s   | j jS )z6
        See :attr:`asyncio.Server.sockets`.

        )r2   r   r   rI   rI   rL   r   L  s   zWebSocketServer.socketsc                   s   | S r   rI   r   rI   rI   rL   
__aenter__T  s   zWebSocketServer.__aenter__exc_typeOptional[Type[BaseException]]	exc_valueOptional[BaseException]	tracebackOptional[TracebackType]c                   s   |    |  I d H  d S r   )rl   r   rZ   r   r   r   rI   rI   rL   	__aexit__W  s   zWebSocketServer.__aexit__r   )r3   r=   )r2   r   rE   rF   )r   r0   rE   rF   r   )rE   r   )rE   r   )rE   r   rE   r1   r   r   r   r   r   r   rE   rF   )r   r   r   r   rQ   r   r`   r   rl   r   r   r   r   r   r   propertyr   r   r   rI   rI   rI   rL   r1     s"    

!



1




r1   c                   @  sp   e Zd ZdZ		d@ddddddddddddddddddAd.d/ZdBd1d2ZdCd9d:ZdDd<d=ZdBd>d?ZeZ	dS )EServea	  
    Start a WebSocket server listening on ``host`` and ``port``.

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

    The handler receives the :class:`WebSocketServerProtocol` and uses it 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.

    Awaiting :func:`serve` yields a :class:`WebSocketServer`. This object
    provides :meth:`~WebSocketServer.close` and
    :meth:`~WebSocketServer.wait_closed` methods for shutting down the server.

    :func:`serve` can be used as an asynchronous context manager::

        stop = asyncio.Future()  # set this future to exit the server

        async with serve(...):
            await stop

    The server is shut down automatically when exiting the context.

    Args:
        ws_handler: connection handler. It receives the WebSocket connection,
            which is a :class:`WebSocketServerProtocol`, in argument.
        host: network interfaces the server is bound to;
            see :meth:`~asyncio.loop.create_server` for details.
        port: TCP port the server listens on;
            see :meth:`~asyncio.loop.create_server` for details.
        create_protocol: factory for the :class:`asyncio.Protocol` managing
            the connection; defaults to :class:`WebSocketServerProtocol`; may
            be set to a wrapper or a subclass to customize connection handling.
        logger: logger for this server;
            defaults to ``logging.getLogger("websockets.server")``;
            see the :doc:`logging guide <../topics/logging>` for details.
        compression: shortcut that enables the "permessage-deflate" extension
            by default; may be set to :obj:`None` to disable compression;
            see the :doc:`compression guide <../topics/compression>` for details.
        origins: acceptable values of the ``Origin`` header; include
            :obj:`None` in the list if the lack of an origin is acceptable.
            This is useful for defending against Cross-Site WebSocket
            Hijacking attacks.
        extensions: list of supported extensions, in order in which they
            should be tried.
        subprotocols: list of supported subprotocols, in order of decreasing
            preference.
        extra_headers (Union[HeadersLike, Callable[[str, Headers], HeadersLike]]):
            arbitrary HTTP headers to add to the request; this can be
            a :data:`~websockets.datastructures.HeadersLike` or a callable
            taking the request path and headers in arguments and returning
            a :data:`~websockets.datastructures.HeadersLike`.
        process_request (Optional[Callable[[str, Headers],             Awaitable[Optional[Tuple[http.HTTPStatus, HeadersLike, bytes]]]]]):
            intercept HTTP request before the opening handshake;
            see :meth:`~WebSocketServerProtocol.process_request` for details.
        select_subprotocol: select a subprotocol supported by the client;
            see :meth:`~WebSocketServerProtocol.select_subprotocol` for details.

    See :class:`~websockets.legacy.protocol.WebSocketCommonProtocol` for the
    documentation of ``ping_interval``, ``ping_timeout``, ``close_timeout``,
    ``max_size``, ``max_queue``, ``read_limit``, and ``write_limit``.

    Any other keyword arguments are passed the event loop's
    :meth:`~asyncio.loop.create_server` method.

    For example:

    * You can set ``ssl`` to a :class:`~ssl.SSLContext` to enable TLS.

    * You can set ``sock`` to a :obj:`~socket.socket` that you created
      outside of websockets.

    Returns:
        WebSocketServer: WebSocket server.

    Ndeflate   i       i   )create_protocolr3   compressionr4   r5   r6   r7   r8   r9   ping_intervalping_timeoutclose_timeoutmax_size	max_queue
read_limitwrite_limitr:   r;   host#Optional[Union[str, Sequence[str]]]portOptional[int]r   2Optional[Callable[[Any], WebSocketServerProtocol]]r3   r=   r   Optional[str]r4   r>   r5   r?   r6   r@   r7   rA   r8   rB   r9   rC   r   Optional[float]r   r   r  r  r  intr  rD   r   rE   rF   c                K  s  | dd }|d u rd}ntdt |d u r|}| dd }|d u r&t}ntdt |d u r2|}| dd}| dd }|d u rGt }n|}td	t t|d
}|dd u}|dkrdt	|}n|d urot
d| |	d urwt|	 tj|t||fi d|d|d|d|d|d|d|d|d|d|d|d|d|d|d|	d|
d|d|d|}| ddr| d d }|d u r|d u sJ tj|j||fi |}ntj|j|||fi |}|| _|| _d S )!Ntimeout
   zrename timeout to close_timeoutklasszrename klass to create_protocollegacy_recvFra   zremove loop argument)r3   sslr   zunsupported compression: r  r  securer   r   r   r  r  r  r  r4   r5   r6   r7   r8   r9   r3   unixr   )poprR   rS   rT   r0   rn   Zget_event_loopr1   r   r   
ValueErrorr"   	functoolspartialrU   Zcreate_unix_servercreate_server_create_serverr<   )rZ   r:   r  r  r   r3   r   r4   r5   r6   r7   r8   r9   r   r   r   r  r  r  r  rD   r  r  r  _loopra   r<   r  factoryr   r  rI   rI   rL   rQ     s    


	


zServe.__init__r1   c                   s   | I d H S r   rI   r   rI   rI   rL   r   +  s   
zServe.__aenter__r   r   r   r   r   r   c                   s    | j   | j  I d H  d S r   )r<   rl   r   r   rI   rI   rL   r   .  s   
zServe.__aexit__%Generator[Any, None, WebSocketServer]c                 C  s   |    S r   )__await_impl__	__await__r   rI   rI   rL   r  9  s   zServe.__await__c                   s"   |   I d H }| j| | jS r   )r  r<   r   )rZ   r2   rI   rI   rL   r  =  s   zServe.__await_impl__)NN)*r:   r;   r  r  r  r  r   r	  r3   r=   r   r
  r4   r>   r5   r?   r6   r@   r7   rA   r8   rB   r9   rC   r   r  r   r  r   r  r  r  r  r  r  r  r  r  rD   r   rE   rF   r   r   )rE   r  )
r   r   r   r   rQ   r   r   r  r  __iter__rI   rI   rI   rL   r   a  s6    W	
x


r   r:   r;   r   r
  rD   r   rE   c                 K  s   t | f|dd|S )a[  
    Similar to :func:`serve`, but for listening on Unix sockets.

    This function builds upon the event
    loop's :meth:`~asyncio.loop.create_unix_server` method.

    It is only available on Unix.

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

    Args:
        path: file system path to the Unix socket.

    T)r   r  )r.   )r:   r   rD   rI   rI   rL   r/   J  s   r/   3Callable[[WebSocketServerProtocol], Awaitable[Any]]c                   s>   t t jdkrd fdd}|S tttgtt f  S )	Nr   rf   r0   rE   r   c                   s*   t tttgtt f  | | jI d H S r   )r   r   r0   r   r   r   r   )rf   r:   rI   rL   _ws_handlerm  s   
z)remove_path_argument.<locals>._ws_handler)rf   r0   rE   r   )	r   inspect	signature
parametersr   r   r0   r   r   )r:   r"  rI   r!  rL   rU   c  s   rU   r   )r:   r;   r   r
  rD   r   rE   r   )r:   r;   rE   r   )K
__future__r   rn   email.utilsr   r  rw   r#  rN   r   rR   typesr   typingr   r   r   r   r   r	   r
   r   r   r   r   r   
connectionr   Zdatastructuresr   r   r   
exceptionsr   r   r   r   r   r   r   r5   r   r   Zextensions.permessage_deflater   rt   r   r    r!   r"   r#   r$   r%   r&   r'   Zcompatibilityr)   rm   r*   r+   r,   r   r-   __all__r   ZHeadersLikeOrCallablerx   bytesHTTPResponser0   r1   r   r.   r/   rU   rI   rI   rI   rL   <module>   sN    8$	    N Z g