U
    Mf                     @  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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.m/Z/m0Z0 ddlm1Z1 ddl2m3Z3 ddlm4Z4m5Z5m6Z6m7Z7m8Z8 ddl9m:Z: ddl;m<Z<m=Z= ddlm>Z> ddl2m?Z? ddddgZ@eeeeAegef f ZBee7eeCf ZDG dd de?ZEG dd dZFG dd dZGeGZHd$dddddddZIdd d!d"d#ZJdS )%    )annotationsN)TracebackType)Any	AwaitableCallable	GeneratorIterableListOptionalSequenceSetTupleTypeUnioncast   )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)State)ExtensionHeader
LoggerLikeOrigin
StatusLikeSubprotocol   )asyncio_timeout)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edddd	ddd	d
dddddddddd fddZddd fddZddddZ	dddd Z
d?d!d"d#dd$d%d&Zd'd"d(d)d*d+Zed@d"d
d,d-d.d/Zed"dd0d1d2d3Zd"dd4d5d6d7Zd8d8d4d9d:d;ZdAd
dddd'd<d=d>Z  ZS )Br2   a  
    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) or without a close code. 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``, ``extra_headers``, and ``server_header``.

    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server_headerprocess_requestselect_subprotocolopen_timeouttUnion[Callable[[WebSocketServerProtocol], Awaitable[Any]], Callable[[WebSocketServerProtocol, str], Awaitable[Any]]]r3   Optional[LoggerLike]$Optional[Sequence[Optional[Origin]]]*Optional[Sequence[ServerExtensionFactory]]Optional[Sequence[Subprotocol]]Optional[HeadersLikeOrCallable]Optional[str]EOptional[Callable[[str, Headers], Awaitable[Optional[HTTPResponse]]]]OOptional[Callable[[Sequence[Subprotocol], Sequence[Subprotocol]], Subprotocol]]Optional[float]r   None)
ws_handler	ws_serverr6   r7   r8   r9   r:   r;   r<   r=   r>   kwargsreturnc       	           s   |d krt d}t jf d|i| |d k	rRd|krRtdt dd |D }t|| _|| _	|| _
|| _|| _|| _|| _|	| _|
| _|| _d S )Nwebsockets.serverr6    z!use None instead of '' in originsc                 S  s   g | ]}|d krdn|qS )rO   N ).0originrP   rP   </tmp/pip-unpacked-wheel-yzabpfcc/websockets/legacy/server.py
<listcomp>   s     z4WebSocketServerProtocol.__init__.<locals>.<listcomp>)logging	getLoggersuper__init__warningswarnDeprecationWarningremove_path_argumentrJ   rK   r7   available_extensionsavailable_subprotocolsr:   r;   _process_request_select_subprotocolr>   )selfrJ   rK   r6   r7   r8   r9   r:   r;   r<   r=   r>   rL   	__class__rP   rS   rX   b   s     

z WebSocketServerProtocol.__init__zasyncio.BaseTransport)	transportrM   c                   s.   t  | | j|  | j|  | _dS )zJ
        Register connection and initialize a task to handle it.

        N)rW   connection_maderK   registerloopcreate_taskhandlerhandler_task)ra   rd   rb   rP   rS   re      s    z'WebSocketServerProtocol.connection_maderM   c                   sd  zBzzJt| j4 I dH & | j| j| j| j	| j
dI dH  W 5 Q I dH R X W n tjk
rl    Y n tk
r    Y n tk
r^ } zt|tr|j|j|j  }}}nt|tr| jr| jjddd tjjt d| d   }}}nt|trH| jr | jjd	dd tjjtd
gd| d   }}}nnt|tr| jrl| 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 | j%dk	r|!d| j% |!dt&t'| |!dd |!dd | (||| | jd|j)|j* | + I dH  W Y 
W W dS d}~X Y nX z| ,| I dH  W n: tk
r   | jjddd | j-s| .d  Y nX z| / I dH  W n> tk
r    Y n( tk
r    | jjddd  Y nX W n< tk
r@   z| j0/  W n tk
r:   Y nX Y nX W 5 | j |  | jd X dS )a   
        Handle the lifecycle of a WebSocket connection.

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

        zconnection closedN)r7   r]   r^   r:   z! 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 rejected (%d %s)zconnection handler failedi  zclosing handshake failed)1rK   
unregisterr6   infor+   r>   	handshaker7   r]   r^   r:   asyncioTimeoutErrorConnectionError	Exception
isinstancer   statusheadersbodyr   debughttp
HTTPStatus	FORBIDDENr   encoder   UPGRADE_REQUIREDr   BAD_REQUESTerrorINTERNAL_SERVER_ERROR
setdefaultemailutils
formatdater;   strlenwrite_http_responsevaluephraseZclose_transportrJ   closedZfail_connectionrs   rd   )ra   excr|   r}   r~   rP   rP   rS   ri      s    	"




	  
zWebSocketServerProtocol.handlerzTuple[str, Headers]c              
     s   zt | jI dH \}}W nB tjk
r0    Y n, tk
rZ } ztd|W 5 d}~X Y nX | jr| jd| | D ]\}}| jd|| qx|| _	|| _
||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.   readerrw   ZCancelledErrorrz   r   r   r6   	raw_itemspathrequest_headers)ra   r   r}   r   keyr   rP   rP   rS   read_http_request
  s    z)WebSocketServerProtocol.read_http_requestzhttp.HTTPStatusr   zOptional[bytes])r|   r}   r~   rM   c                 C  s   || _ | jr\| jd|j|j | D ]\}}| jd|| q(|dk	r\| jdt| d|j d|j d}|t|7 }| j	|
  |dk	r| j	| 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_headersr   r6   r   r   r   r   r   rd   writer   )ra   r|   r}   r~   r   r   responserP   rP   rS   r   '  s    	z+WebSocketServerProtocol.write_http_responser   zOptional[HTTPResponse])r   r   rM   c                   s>   | j dk	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 an 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 an HTTP 401 Unauthorized or an
          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[StatusLike, 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)r_   r{   r   rY   rZ   r[   )ra   r   r   r   rP   rP   rS   r<   C  s    %


 z'WebSocketServerProtocol.process_requestzOptional[Origin])r}   r7   rM   c              
   C  sd   zt tt | d}W n. tk
rF } ztdd|W 5 d}~X Y nX |dk	r`||k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   )r}   r7   rR   r   rP   rP   rS   process_origint  s    z&WebSocketServerProtocol.process_originz%Tuple[Optional[str], List[Extension]])r}   r]   rM   c              
   C  s   d}g }g }|  d}|r|rtdd |D g }|D ]h\}}|D ]Z}	|	j|krRqBz|	||\}
}W n tk
r~   Y qBY nX |||
f ||  q6qBq6|rt|}||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  s   g | ]}t |qS rP   )r    rQ   header_valuerP   rP   rS   rT     s     z>WebSocketServerProtocol.process_extensions.<locals>.<listcomp>)get_allsumnameZprocess_request_paramsr   appendr   )r}   r]   Zresponse_header_valueZextension_headersZaccepted_extensionsheader_valuesparsed_header_valuesr   Zrequest_paramsZext_factoryZresponse_params	extensionrP   rP   rS   process_extensions  s4    (
 
 

z*WebSocketServerProtocol.process_extensionszOptional[Subprotocol])r}   r^   rM   c                 C  s:   d}| d}|r6|r6t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  s   g | ]}t |qS rP   )r!   r   rP   rP   rS   rT     s     z?WebSocketServerProtocol.process_subprotocol.<locals>.<listcomp>)r   r   r=   )ra   r}   r^   subprotocolr   r   rP   rP   rS   process_subprotocol  s    
  z+WebSocketServerProtocol.process_subprotocolzSequence[Subprotocol])client_subprotocolsserver_subprotocolsrM   c                   sH   | j dk	r|   S t t@ }|s.dS t| fdddd S )a  
        Pick a subprotocol among those supported by the client and the server.

        If several subprotocols are available, select the preferred subprotocol
        by giving equal weight to the preferences of the client and the server.

        If no subprotocol is available, proceed without a subprotocol.

        You may provide a ``select_subprotocol`` argument to :func:`serve` or
        :class:`WebSocketServerProtocol` to override this logic. For example,
        you could reject the handshake if the client doesn't support a
        particular subprotocol, rather than accept the handshake without that
        subprotocol.

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

        Returns:
            Optional[Subprotocol]: Selected subprotocol, if a common subprotocol
            was found.

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

        Nc                   s     |  |  S N)index)pr   r   rP   rS   <lambda>'      z<WebSocketServerProtocol.select_subprotocol.<locals>.<lambda>)r   r   )r`   setsorted)ra   r   r   r9   rP   r   rS   r=     s    
z*WebSocketServerProtocol.select_subprotocol)r7   r]   r^   r:   rM   c                   sj  |   I dH \}}| ||}t|tr4|I dH }ntdt |}| jtj	krXt
d| j sptjjg df}|dk	rt| t|}	| ||| _| ||\}
| _| || }| _t }t||	 |
dk	r|
|d< |dk	r||d< t|r||| j}|dk	r|| |dtjj dd	 | j!dk	rB|d
| j! | "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   z*connection closed during opening handshakes   Server is shutting down.
r   r   rn   Tro   rq   zconnection open)'r   r<   r{   r   rY   rZ   r[   stater$   ZCLOSEDBrokenPipeErrorrK   
is_servingr   r   SERVICE_UNAVAILABLEr   r-   r   rR   r   r8   r   r   r   r,   callabler   updater   r   r   r   r;   r   SWITCHING_PROTOCOLSr6   ru   Zconnection_open)ra   r7   r]   r^   r:   r   r   Zearly_response_awaitableZearly_responser   Zextensions_headerZprotocol_headerr   rP   rP   rS   rv   *  sT    

 
 



z!WebSocketServerProtocol.handshake)N)N)NNNN)__name__
__module____qualname____doc__Z	is_clientZsider#   rX   re   ri   r   r   r<   staticmethodr   r   r   r=   rv   __classcell__rP   rP   rb   rS   r2   ?   s>   
.,o 1 R +    c                   @  s   e Zd ZdZd0ddddZddd	d
dZdddddZdddddZd1dddddZdddddZ	ddddZ
ddddZdddd Zddd!d"Zddd#d$Zed%dd&d'Zd dd(d)Zd*d+d,dd-d.d/ZdS )2r3   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.
            It defaults to ``logging.getLogger("websockets.server")``.
            See the :doc:`logging guide <../../topics/logging>` for details.

    Nr@   r6   c                 C  s.   |d krt d}|| _t | _d | _|  d S )NrN   )rU   rV   r6   r   
websockets
close_task)ra   r6   rP   rP   rS   rX     s    
zWebSocketServer.__init__zasyncio.base_events.ServerrI   )r4   rM   c                 C  s   || _ |jD ]p}|jtjkr*d|  }nD|jtjkrLd| dd  }n"|jtjkrb| }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

        z%s:%dz[%s]:%dNr   zserver listening on %s)r4   socketsfamilysocketAF_INETgetsocknameAF_INET6AF_UNIXr   r6   ru   get_loopZcreate_futureclosed_waiter)ra   r4   sockr   rP   rP   rS   wrap  s    

zWebSocketServer.wrapr2   )protocolrM   c                 C  s   | j | dS )z:
        Register a connection with this server.

        N)r   addra   r   rP   rP   rS   rf     s    zWebSocketServer.registerc                 C  s   | j | dS )z<
        Unregister a connection with this server.

        N)r   remover   rP   rP   rS   rt     s    zWebSocketServer.unregisterTbool)close_connectionsrM   c                 C  s$   | j dkr |  | || _ dS )aw  
        Close the server.

        * Close the underlying :class:`~asyncio.Server`.
        * When ``close_connections`` is :obj:`True`, which is the default,
          close existing connections. Specifically:

          * Reject opening WebSocket connections with an HTTP 503 (service
            unavailable) error. This happens when the server accepted the TCP
            connection but didn't complete the opening handshake before closing.
          * Close open WebSocket connections with close code 1001 (going away).

        * Wait until all connection handlers terminate.

        :meth:`close` is idempotent.

        N)r   r   rh   _close)ra   r   rP   rP   rS   rs     s    
zWebSocketServer.closec                   s   | j d | j  tdI dH  |rNdd | jD }|rNt|I dH  | j I dH  | jrtdd | jD 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 closingr   Nc                 S  s(   g | ] }|j tjk	rt|d qS )i  )r   r$   Z
CONNECTINGrw   rh   rs   rQ   rm   rP   rP   rS   rT     s   z*WebSocketServer._close.<locals>.<listcomp>c                 S  s   g | ]
}|j qS rP   )rj   r   rP   rP   rS   rT     s     zserver closed)r6   ru   r4   rs   rw   sleepr   waitwait_closedr   Z
set_result)ra   r   Zclose_tasksrP   rP   rS   r     s     	

zWebSocketServer._closerk   c                   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)rw   Zshieldr   ra   rP   rP   rS   r     s    zWebSocketServer.wait_closedzasyncio.AbstractEventLoopc                 C  s
   | j  S )z7
        See :meth:`asyncio.Server.get_loop`.

        )r4   r   r   rP   rP   rS   r   0  s    zWebSocketServer.get_loopc                 C  s
   | j  S )z9
        See :meth:`asyncio.Server.is_serving`.

        )r4   r   r   rP   rP   rS   r   7  s    zWebSocketServer.is_servingc                   s   | j  I dH  dS )a  
        See :meth:`asyncio.Server.start_serving`.

        Typical use::

            server = await serve(..., start_serving=False)
            # perform additional setup here...
            # ... then start the server
            await server.start_serving()

        N)r4   start_servingr   rP   rP   rS   r   >  s    zWebSocketServer.start_servingc                   s   | j  I dH  dS )a  
        See :meth:`asyncio.Server.serve_forever`.

        Typical use::

            server = await serve(...)
            # this coroutine doesn't return
            # canceling it stops the server
            await server.serve_forever()

        This is an alternative to using :func:`serve` as an asynchronous context
        manager. Shutdown is triggered by canceling :meth:`serve_forever`
        instead of exiting a :func:`serve` context.

        N)r4   serve_foreverr   rP   rP   rS   r   L  s    zWebSocketServer.serve_foreverzIterable[socket.socket]c                 C  s   | j jS )z6
        See :attr:`asyncio.Server.sockets`.

        )r4   r   r   rP   rP   rS   r   ^  s    zWebSocketServer.socketsc                   s   | S r   rP   r   rP   rP   rS   
__aenter__f  s    zWebSocketServer.__aenter__Optional[Type[BaseException]]Optional[BaseException]Optional[TracebackType]exc_type	exc_value	tracebackrM   c                   s   |    |  I d H  d S r   )rs   r   ra   r   r   r   rP   rP   rS   	__aexit__i  s    zWebSocketServer.__aexit__)N)T)r   r   r   r   rX   r   rf   rt   rs   r   r   r   r   r   r   propertyr   r   r   rP   rP   rP   rS   r3     s     -c                   @  s   e Zd ZdZd,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Zdddd Zd!d"d#dd$d%d&Zd'dd(d)Zddd*d+Z	eZ
dS )-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 a :meth:`~WebSocketServer.close` method to shut down the server::

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

        server = await serve(...)
        await stop
        await server.close()

    :func:`serve` can be used as an asynchronous context manager. Then, the
    server is shut down automatically when exiting the context::

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

        async with serve(...):
            await stop

    Args:
        ws_handler: Connection handler. It receives the WebSocket connection,
            which is a :class:`WebSocketServerProtocol`, in argument.
        host: Network interfaces the server binds 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. It defaults to :class:`WebSocketServerProtocol`.
            Set it to a wrapper or a subclass to customize connection handling.
        logger: Logger for this server.
            It defaults to ``logging.getLogger("websockets.server")``.
            See the :doc:`logging guide <../../topics/logging>` for details.
        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.
        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.
        extra_headers (Union[HeadersLike, Callable[[str, Headers], HeadersLike]]):
            Arbitrary HTTP headers to add to the response. 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`.
        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.
        process_request (Optional[Callable[[str, Headers],             Awaitable[Optional[Tuple[StatusLike, 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.
        open_timeout: Timeout for opening connections in seconds.
            :obj:`None` disables the timeout.

    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deflater5      i       i   )create_protocolr6   compressionr7   r8   r9   r:   r;   r<   r=   r>   ping_intervalping_timeoutclose_timeoutmax_size	max_queue
read_limitwrite_limitr?   z#Optional[Union[str, Sequence[str]]]zOptional[int]z0Optional[Callable[..., WebSocketServerProtocol]]r@   rE   rA   rB   rC   rD   rF   rG   rH   intr   rI   )rJ   hostportr   r6   r   r7   r8   r9   r:   r;   r<   r=   r>   r   r   r   r   r   r   r   rL   rM   c          !      K  s  | dd }|d krd}ntdt |d kr2|}| dd }|d krLt}ntdt |d krd|}| dd}| dd }|d krt }n|}td	t t|d
}|dd k	}|dkrt	|}n|d k	rt
d| |	d k	rt|	 tj|t||||||||||||||||||	|
||||d}| ddrt| dd }|d krZ|d ks^ttj|j||f|} ntj|j|||f|} | | _|| _d S )Ntimeoutr5   zrename timeout to close_timeoutklasszrename klass to create_protocollegacy_recvFrg   zremove loop argumentr   sslr   zunsupported compression: )r   r   securer>   r   r   r   r   r   r   r   rg   r   r7   r8   r9   r:   r;   r<   r=   r6   unixr   )poprY   rZ   r[   r2   rw   Zget_event_loopr3   r   r   
ValueErrorr"   	functoolspartialr\   AssertionErrorZcreate_unix_servercreate_server_create_serverrK   )!ra   rJ   r   r   r   r6   r   r7   r8   r9   r:   r;   r<   r=   r>   r   r   r   r   r   r   r   rL   r   r   r   Z_looprg   rK   r   factoryr   r  rP   rP   rS   rX     s    "


     zServe.__init__r3   rk   c                   s
   | I d H S r   rP   r   rP   rP   rS   r   I  s    zServe.__aenter__r   r   r   r   c                   s   | j   | j  I d H  d S r   )rK   rs   r   r   rP   rP   rS   r   L  s    
zServe.__aexit__z%Generator[Any, None, WebSocketServer]c                 C  s   |    S r   )__await_impl__	__await__r   rP   rP   rS   r  W  s    zServe.__await__c                   s    |   I d H }| j| | jS r   )r  rK   r   )ra   r4   rP   rP   rS   r
  [  s    zServe.__await_impl__)NN)r   r   r   r   r#   rX   r   r   r  r
  __iter__rP   rP   rP   rS   r   s  s8   _  	>|r   r?   rE   r   )rJ   r   rL   rM   c                 K  s   t | f|dd|S )a  
    Start 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 is only available on Unix.

    Unrecognized keyword arguments are passed the event loop's
    :meth:`~asyncio.loop.create_unix_server` method.

    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  )r0   )rJ   r   rL   rP   rP   rS   r1   h  s    z3Callable[[WebSocketServerProtocol], Awaitable[Any]])rJ   rM   c                   s   zt  d  W n\ tk
rp   zt  d d W n tk
rN   Y nX ddd fdd}| Y S Y nX tttgtt f  S )NrO   r2   r   )rm   rM   c                   s(   t tttgtt f  | | jI d H S r   )r   r   r2   r   r   r   r   )rm   rJ   rP   rS   _ws_handler  s     z)remove_path_argument.<locals>._ws_handler)	inspect	signaturebind	TypeErrorr   r   r2   r   r   )rJ   r  rP   r  rS   r\     s    r\   )N)K
__future__r   rw   email.utilsr   r  r   r  rU   r   rY   typesr   typingr   r   r   r   r   r	   r
   r   r   r   r   r   r   Zdatastructuresr   r   r   
exceptionsr   r   r   r   r   r   r   r8   r   r   Zextensions.permessage_deflater   r}   r   r    r!   r"   r#   r   r$   r%   r&   r'   r(   r)   Zcompatibilityr+   rv   r,   r-   r.   r/   __all__r   ZHeadersLikeOrCallablebytesHTTPResponser2   r3   r   r0   r1   r\   rP   rP   rP   rS   <module>   sL   <$	    N k s 