
    ,h	                       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	m
Z
mZmZmZ d dlmZ d dlmZmZmZmZ ddlmZ ddlmZ dd	lmZ dd
lmZ ddlmZmZm Z  ddl!m"Z"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-m.Z. ddl/m0Z0 ddl1m2Z2m3Z3 g dZ4 G d de2      Z5 G d d      Z6 G d d      Z7	 d	 	 	 	 	 	 	 ddZ8ddZ9	 	 	 d 	 	 	 	 	 	 	 d!dZ:y)"    )annotationsN)	Awaitable	GeneratorIterableSequence)TracebackType)AnyCallableMappingcast   )InvalidHeader)ServerExtensionFactory) enable_server_permessage_deflate)	CloseCode)build_www_authenticate_basicparse_authorization_basicvalidate_subprotocols)SERVERRequestResponse)
CONNECTINGOPENEvent)ServerProtocol)
LoggerLikeOrigin
StatusLikeSubprotocol   )asyncio_timeout)
Connection	broadcast)r#   serve
unix_serveServerConnectionServer
basic_authc                       e Zd ZdZdddddd	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d fdZddZd	d	ef	 	 	 	 	 	 	 dd
Zd fdZd fdZ	 xZ
S )r&   aT  
    :mod:`asyncio` implementation of a WebSocket server connection.

    :class:`ServerConnection` provides :meth:`recv` and :meth:`send` methods 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.

    The ``ping_interval``, ``ping_timeout``, ``close_timeout``, ``max_queue``,
    and ``write_limit`` arguments have the same meaning as in :func:`serve`.

    Args:
        protocol: Sans-I/O connection.
        server: Server that manages this connection.

       
         ping_intervalping_timeoutclose_timeout	max_queuewrite_limitc                   |  t         |   ||||||       || _        | j                  j	                         | _        |  |  |  y )Nr.   )super__init__serverloopcreate_futurerequest_rcvd)	selfprotocolr7   r/   r0   r1   r2   r3   	__class__s	           [/var/www/html/Resume-Scraper/venv/lib/python3.12/site-packages/websockets/asyncio/server.pyr6   zServerConnection.__init__C   sS     	'%'# 	 	
 26))2I2I2K    c                :    | j                   j                  ||      S )a  
        Create a plain text HTTP response.

        ``process_request`` and ``process_response`` may call this method to
        return an HTTP response instead of performing the WebSocket opening
        handshake.

        You can modify the response before returning it, for example by changing
        HTTP headers.

        Args:
            status: HTTP status code.
            text: HTTP response body; it will be encoded to UTF-8.

        Returns:
            HTTP response to send to the client.

        )r<   reject)r;   statustexts      r>   respondzServerConnection.respond]   s    & }}##FD11r?   Nc                  K   t        j                  | j                  | j                  gt         j                         d{    | j
                  | j                  t              4 d{    d}|.	  || | j
                        }t        |t              r
| d{   }|| j"                  j%                         r+| j                  j'                  | j
                        | _        nS| j                  j                  t        j                  j*                  d      | _        nt        |t,              sJ || _        |r|| j(                  j.                  d<   d}|9	  || | j
                  | j(                        }t        |t              r
| d{   }|t        |t,              sJ || _        | j                  j1                  | j(                         ddd      d{    | j                  j                  | j                  j                  y7 7 7 z# t        $ rP}|| j                  _        | j                  j                  t        j                  j                   d      }Y d}~d}~ww xY w7 # t        $ rP}|| j                  _        | j                  j                  t        j                  j                   d      }Y d}~8d}~ww xY w7 # 1 d{  7  sw Y   xY ww)z1
        Perform the opening handshake.

        )return_whenN)expected_statezLFailed to open a WebSocket connection.
See server log for more information.
zServer is shutting down.
r'   )asynciowaitr:   connection_lost_waiterFIRST_COMPLETEDrequestsend_contextr   
isinstancer   	Exceptionr<   handshake_excrA   http
HTTPStatusINTERNAL_SERVER_ERRORr7   
is_servingacceptresponseSERVICE_UNAVAILABLEr   headerssend_response)r;   process_requestprocess_responseserver_headerrV   excs         r>   	handshakezServerConnection.handshaker   sg    , ll ; ;<//
 	
 	

 <<#((
(C 6; 6;".#24#F%h	:-5~H #{{--/(,(<(<T\\(J(,(<(< OO??8)
 &h99$,DM 6CDMM))(3#/#3D$,,#V%h	:-5~H '%h99$,DM++DMM:m6; 6;@ ==&&2----- 3M	
6; (6$ 693#'==#7#7 OOAA!I$> (6$ 693#'==#7#7 OOAA!I$Q6; 6; 6; 6;s   ?K.H+K.-H.K.1K7(HH H$B9K3I:I8I:A KK.!K"2K.K.H	I5%AI0*K0I55K8I::	KAKKKKK.K+K!K+&K.c                    | j                   5t        |t              sJ || _         | j                  j	                  d       yt
        |   |       y)z.
        Process one incoming event.

        N)rL   rN   r   r:   
set_resultr5   process_event)r;   eventr=   s     r>   ra   zServerConnection.process_event   sF     <<eW-- DL((. G!%(r?   c                Z    t         |   |       | j                  j                  |        y N)r5   connection_mader7   start_connection_handler)r;   	transportr=   s     r>   re   z ServerConnection.connection_made   s"    	*,,T2r?   )r<   r   r7   r'   r/   float | Noner0   rh   r1   rh   r2   *int | None | tuple[int | None, int | None]r3   int | tuple[int, int | None]returnNone)rB   r   rC   strrk   r   )rZ   ZCallable[[ServerConnection, Request], Awaitable[Response | None] | Response | None] | Noner[   dCallable[[ServerConnection, Request, Response], Awaitable[Response | None] | Response | None] | Noner\   
str | Nonerk   rl   )rb   r   rk   rl   )rg   zasyncio.BaseTransportrk   rl   )__name__
__module____qualname____doc__r6   rD   r   r^   ra   re   __classcell__)r=   s   @r>   r&   r&   )   s    < ')%'&(@B49/ / /
 $/ #/ $/ >/ 2/ 
/42:  $*!].].].  "!]." 
#].~)3 3r?   r&   c                      e Zd ZdZddeddd	 	 	 	 	 	 	 	 	 	 	 	 	 ddZedd       ZddZddZ	dd	Z
ddd
ZddZddZddZddZddZddZedd       ZddZ	 	 	 	 	 	 	 	 ddZy) r'   ah  
    WebSocket server returned by :func:`serve`.

    This class mirrors the API of :class:`asyncio.Server`.

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

    Args:
        handler: Connection handler. It receives the WebSocket connection,
            which is a :class:`ServerConnection`, in argument.
        process_request: Intercept the request during the opening handshake.
            Return an HTTP response to force the response. Return :obj:`None` to
            continue normally. When you force an HTTP 101 Continue response, the
            handshake is successful. Else, the connection is aborted.
            ``process_request`` may be a function or a coroutine.
        process_response: Intercept the response during the opening handshake.
            Modify the response or return a new HTTP response to force the
            response. Return :obj:`None` to continue normally. When you force an
            HTTP 101 Continue response, the handshake is successful. Else, the
            connection is aborted. ``process_response`` may be a function or a
            coroutine.
        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.
        open_timeout: Timeout for opening connections in seconds.
            :obj:`None` disables the timeout.
        logger: Logger for this server.
            It defaults to ``logging.getLogger("websockets.server")``.
            See the :doc:`logging guide <../../topics/logging>` for details.

    Nr+   rZ   r[   r\   open_timeoutloggerc                  t        j                         | _        || _        || _        || _        || _        || _        |t        j                  d      }|| _
        i | _        d | _        | j                  j                         | _        y )Nzwebsockets.server)rH   get_running_loopr8   handlerrZ   r[   r\   rx   logging	getLoggerry   handlers
close_taskr9   closed_waiter)r;   r|   rZ   r[   r\   rx   ry   s          r>   r6   zServer.__init__  s    , ,,.	. 0*(>&&':;F EG 6: 48993J3J3Lr?   c                f    | j                   D ch c]  }|j                  t        u s| c}S c c}w )a  
        Set of active connections.

        This property contains all connections that completed the opening
        handshake successfully and didn't start the closing handshake yet.
        It can be useful in combination with :func:`~broadcast`.

        )r   stater   r;   
connections     r>   connectionszServer.connections/  s*     .2]]Wzj>N>NRV>V
WWWs   ..c                   || _         |j                  D ]  }|j                  t        j                  k(  rd|j                         z  }n{|j                  t        j                  k(  rd|j                         dd z  }nG|j                  t        j                  k(  r|j                         }nt        |j                               }| j                  j                  d|        y)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:`Server`
        - 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)r7   socketsfamilysocketAF_INETgetsocknameAF_INET6AF_UNIXrm   ry   info)r;   r7   socknames       r>   wrapzServer.wrap;  s     NN 	=D{{fnn,!1!1!33/ 4#3#3#5bq#99.'') 4++-.KK5t<	=r?   c                  K   	 t        | j                        4 d{    	 |j                  | j                  | j                  | j
                         d{    ddd      d{    |j                  j                  t         ur)|j                  j                          	 | j                  |= y	 |j#                          | j%                  |       d{    |j'                          d{    | j                  |= y7 7 # t        j                  $ r |j                  j                           t        $ rX |j                  j                  dd       |j                  j                          Y ddd      d{  7   | j                  |= yw xY w7 /# 1 d{  7  sw Y   @xY w7 7 # t        $ rI |j                  j                  dd       |j'                  t(        j*                         d{  7   Y w xY w# t,        $ r Y !t        $ r |j                  j                          Y Fw xY w# | j                  |= w xY ww)a  
        Handle the lifecycle of a WebSocket connection.

        Since this method doesn't have a caller that can handle exceptions,
        it attempts to log relevant ones.

        It guarantees that the TCP connection is closed before exiting.

        Nzopening handshake failedT)exc_infozconnection handler failed)r!   rx   r^   rZ   r[   r\   rH   CancelledErrorrg   abortrO   ry   errorr   r<   r   r   start_keepaliver|   closer   INTERNAL_ERRORTimeoutErrorr   s     r>   conn_handlerzServer.conn_handlerW  s    *	*&t'8'89  $..,,--**    ""((4$$**,. j)+)**,ll:...
 !&&((( j)S
 -- ((..0  %%++,FQU+V((..0  R j)?   , /
 )	  A!!''(Cd'S &&y'?'?@@@A  	 	)  &&(	) j)s(  IH DH F4DDDH 'F(:H #I2$F3 F/F3 H .F1/H 3IH DA-F2F3H >F?H IFFH F,F" F,'H /F3 1H 3AH;G><HH HH 	H:H= "H:6H= 9H::H= =IIc                r    | j                   j                  | j                  |            | j                  |<   y)z:
        Register a connection with this server.

        N)r8   create_taskr   r   r   s     r>   rf   zServer.start_connection_handler  s,     %)II$9$9$:K:KJ:W$Xj!r?   c                    | j                   4| j                         j                  | j                  |            | _         yy)av  
        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   get_loopr   _close)r;   close_connectionss     r>   r   zServer.close  s8    $ ??""mmo99-.DO #r?   c                  K   | j                   j                  d       | j                  j                          t	        j
                  d       d{    |rv| j                  D cg c]B  }|j                  j                  t        ur$t	        j                  |j                  d            D }}|rt	        j                  |       d{    | j                  j                          d{    | j                  r5t	        j                  | j                  j                                d{    | j                  j                  d       | j                   j                  d       y7 c c}w 7 7 7 Gw)z
        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   Ni  zserver closed)ry   r   r7   r   rH   sleepr   r<   r   r   r   rI   wait_closedvaluesr   r`   )r;   r   r   close_taskss       r>   r   zServer._close  s+     	)* 	
 mmA
 #'--&&,,J> ##J$4$4T$:;K  ll;/// kk%%''' ==,,t}}335666 	%%d+)3 	
 0 	(
 7sV   AE5E'E5%AE*,E5E/	!E5*E1+A E5+E3,<E5*E51E53E5c                ^   K   t        j                  | j                         d{    y7 w)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:`~ServerConnection.recv`: when the connection is closed,
          it raises :exc:`~websockets.exceptions.ConnectionClosedOK`;
        * :meth:`~ServerConnection.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)rH   shieldr   r;   s    r>   r   zServer.wait_closed  s      & nnT//000s   #-+-c                6    | j                   j                         S )z7
        See :meth:`asyncio.Server.get_loop`.

        )r7   r   r   s    r>   r   zServer.get_loop  s    
 {{##%%r?   c                6    | j                   j                         S )z9
        See :meth:`asyncio.Server.is_serving`.

        )r7   rT   r   s    r>   rT   zServer.is_serving  s    
 {{%%''r?   c                T   K   | j                   j                          d{    y7 w)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)r7   start_servingr   s    r>   r   zServer.start_serving  s      kk'')))   (&(c                T   K   | j                   j                          d{    y7 w)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)r7   serve_foreverr   s    r>   r   zServer.serve_forever  s       kk'')))r   c                .    | j                   j                  S )z6
        See :attr:`asyncio.Server.sockets`.

        )r7   r   r   s    r>   r   zServer.sockets  s     {{"""r?   c                   K   | S wrd    r   s    r>   
__aenter__zServer.__aenter__&  s     s   c                `   K   | j                          | j                          d {    y 7 wrd   )r   r   r;   exc_type	exc_value	tracebacks       r>   	__aexit__zServer.__aexit__)  s#      	

   s   $.,.)r|   -Callable[[ServerConnection], Awaitable[None]]rZ   rn   r[   ro   r\   rp   rx   rh   ry   LoggerLike | Nonerk   rl   )rk   zset[ServerConnection])r7   zasyncio.Serverrk   rl   )r   r&   rk   rl   )T)r   boolrk   rl   )rk   rl   )rk   zasyncio.AbstractEventLoop)rk   r   )rk   zIterable[socket.socket]rk   r'   r   ztype[BaseException] | Noner   zBaseException | Noner   zTracebackType | Nonerk   rl   )rq   rr   rs   rt   r   r6   propertyr   r   r   rf   r   r   r   r   rT   r   r   r   r   r   r   r?   r>   r'   r'      s    V  $*%'$()'M>'M
'M'M$ "%'M& #''M( ")'M* 
+'MR 	X 	X=84*l	Y.**X1*&(**$ # #!,! (! (	!
 
!r?   r'   c                      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
ZddZ	 	 	 	 	 	 	 	 ddZddZddZ	eZ
y)r$   u  
    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`` coroutine.

    The handler receives the :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.

    This coroutine returns a :class:`Server` whose API mirrors
    :class:`asyncio.Server`. Treat it as an asynchronous context manager to
    ensure that the server will be closed::

        from websockets.asyncio.server import serve

        def handler(websocket):
            ...

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

        async with serve(handler, host, port):
            await stop

    Alternatively, call :meth:`~Server.serve_forever` to serve requests and
    cancel it to stop the server::

        server = await serve(handler, host, port)
        await 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 :meth:`~asyncio.loop.create_server` for details.
        port: TCP port the server listens on.
            See :meth:`~asyncio.loop.create_server` for details.
        origins: Acceptable values of the ``Origin`` header, for defending
            against Cross-Site WebSocket Hijacking attacks. Values can be
            :class:`str` to test for an exact match or regular expressions
            compiled by :func:`re.compile` to test against a pattern. 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.
        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.
        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_request`` may be a function or a coroutine.
        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.
            ``process_response`` may be a function or a coroutine.
        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.
        open_timeout: Timeout for opening connections in seconds.
            :obj:`None` disables the timeout.
        ping_interval: Interval between keepalive pings in seconds.
            :obj:`None` disables keepalive.
        ping_timeout: Timeout for keepalive pings in seconds.
            :obj:`None` disables timeouts.
        close_timeout: Timeout for closing connections in seconds.
            :obj:`None` disables the timeout.
        max_size: Maximum size of incoming messages in bytes.
            :obj:`None` disables the limit.
        max_queue: High-water mark of the buffer where frames are received.
            It defaults to 16 frames. The low-water mark defaults to ``max_queue
            // 4``. You may pass a ``(high, low)`` tuple to set the high-water
            and low-water marks. If you want to disable flow control entirely,
            you may set it to ``None``, although that's a bad idea.
        write_limit: High-water mark of write buffer in bytes. It is passed to
            :meth:`~asyncio.WriteTransport.set_write_buffer_limits`. It defaults
            to 32 KiB. You may pass a ``(high, low)`` tuple to set the
            high-water and low-water marks.
        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.

    Any other keyword arguments are passed to 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 provide a preexisting TCP socket. You may call
      :func:`socket.create_server` (not to be confused with the event loop's
      :meth:`~asyncio.loop.create_server` method) to create a suitable server
      socket and customize it.

    * You can set ``start_serving`` to ``False`` to start accepting connections
      only after you call :meth:`~Server.start_serving()` or
      :meth:`~Server.serve_forever()`.

    Ndeflater+   r*   i   r,   r-   )origins
extensionssubprotocolsselect_subprotocolcompressionrZ   r[   r\   rx   r/   r0   r1   max_sizer2   r3   ry   create_connectionc               "    t               |dk(  rt              n|t        d|       t        t	        ||	|
||       _        |j                  d      :|j                  d|       t        j                  d d dk\  r|j                  d       d fd	}t        j                         }|j                  d
d      r |j                  |fi | _        y  |j                  |||fi | _        y )Nr   zunsupported compression: rw   sslssl_handshake_timeoutr   )      ssl_shutdown_timeoutc            	         d} 	 	 	 	 	 	 dfd} t        	|       } |j                  
      S )zZ
            Create an asyncio protocol for managing a WebSocket connection.

            Nc                >    J | j                   u sJ  |      S rd   )r<   )r<   r   r   r   s     r>   protocol_select_subprotocolzDserve.__init__.<locals>.factory.<locals>.protocol_select_subprotocol  s,    
 .99#z':':::-j,GGr?   )r   r   r   r   r   ry   r.   )r<   r   r   zSequence[Subprotocol]rk   zSubprotocol | None)r   r7   )r   r<   r   r1   r   r   ry   r2   r   r   r/   r0   r   r;   r   r3   s     @r>   factoryzserve.__init__.<locals>.factory  s      ( "-H,H"7H (H &%)#>!H ++)+#'J r?   unixF)rk   r&   )r   r   
ValueErrorr&   r'   r7   get
setdefaultsysversion_inforH   r{   popcreate_unix_servercreate_server)r;   r|   hostportr   r   r   r   r   rZ   r[   r\   rx   r/   r0   r1   r   r2   r3   ry   r   kwargsr   r8   s   `   ````     ````````   r>   r6   zserve.__init__  s   d #!,/)#9*EJ$8FGG$ 0+-'%
 ::e(5|D#w.!!"8-H,	 ,	 ,	\ '')::fe$!8!8!8!KF!KD "4!3!3GT4!R6!RDr?   c                "   K   |  d {   S 7 wrd   r   r   s    r>   r   zserve.__aenter__,  s     zzs   c                   K   | j                   j                          | j                   j                          d {    y 7 wrd   )r7   r   r   r   s       r>   r   zserve.__aexit__/  s.      	kk%%'''s   8AA Ac                >    | j                         j                         S rd   )__await_impl__	__await__r   s    r>   r   zserve.__await__:  s    ""$..00r?   c                   K   | j                    d {   }| j                  j                  |       | j                  S 7 +wrd   )r   r7   r   )r;   r7   s     r>   r   zserve.__await_impl__>  s5     ))) {{ *s   A >,A )NN),r|   r   r   rp   r   
int | Noner   z0Sequence[Origin | re.Pattern[str] | None] | Noner   z'Sequence[ServerExtensionFactory] | Noner   zSequence[Subprotocol] | Noner   zNCallable[[ServerConnection, Sequence[Subprotocol]], Subprotocol | None] | Noner   rp   rZ   rn   r[   ro   r\   rp   rx   rh   r/   rh   r0   rh   r1   rh   r   r   r2   ri   r3   rj   ry   r   r   ztype[ServerConnection] | Noner   r	   rk   rl   r   r   )rk   zGenerator[Any, None, Server])rq   rr   rs   rt   r   r6   r   r   r   r   __iter__r   r?   r>   r$   r$   4  s   sp  	~S EI>B59 "+  $*%'&(%'&($@B49$(;?]~S>~S ~S 	~S B~S <~S 3~S~S"  #~S()~S67~SB "C~SF #G~SH $I~SJ #K~SL $M~SP Q~SR >S~ST 2U~SX "Y~S\ 9]~S` a~Sb 
c~SD(,( (( (	(
 
(1 Hr?   r$   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   path)r$   )r|   r   r   s      r>   r%   r%   H  s    & 9t$9&99r?   c                |    	 | \  }}t        |t              xr t        |t              S # t        t        f$ r Y yw xY wNF)rN   rm   	TypeErrorr   )credentialsusernamepasswords      r>   is_credentialsr   ^  sF    G(( (C(FZ#-FF z" s   ) ;;c                    |du du k(  rt        d      |t        |      rt        t        t        t        f   |      g}nkt        |t              rMt        t        t        t        t        t        f      |            }t        d |D              st        d|       t        d|       t        |      dfdJ 	 	 	 	 	 	 d fd}|S )	a~  
    Factory for ``process_request`` to enforce HTTP Basic Authentication.

    :func:`basic_auth` is designed to integrate with :func:`serve` as follows::

        from websockets.asyncio.server import basic_auth, serve

        async with serve(
            ...,
            process_request=basic_auth(
                realm="my dev server",
                credentials=("hello", "iloveyou"),
            ),
        ):

    If authentication succeeds, the connection's ``username`` attribute is set.
    If it fails, the server responds with an HTTP 401 Unauthorized status.

    One of ``credentials`` or ``check_credentials`` must be provided; not both.

    Args:
        realm: Scope of protection. It should contain only ASCII characters
            because the encoding of non-ASCII characters is undefined. Refer to
            section 2.2 of :rfc:`7235` for details.
        credentials: Hard coded authorized credentials. It can be a
            ``(username, password)`` pair or a list of such pairs.
        check_credentials: Function or coroutine that verifies credentials.
            It receives ``username`` and ``password`` arguments and returns
            whether they're valid.
    Raises:
        TypeError: If ``credentials`` or ``check_credentials`` is wrong.
        ValueError: If ``credentials`` and ``check_credentials`` are both
            provided or both not provided.

    Nz/provide either credentials or check_credentialsc              3  2   K   | ]  }t        |        y wrd   )r   ).0items     r>   	<genexpr>zbasic_auth.<locals>.<genexpr>  s     I~d+Is   zinvalid credentials argument: c                Z    	 |    }t        j                  ||      S # t         $ r Y yw xY wr   )KeyErrorhmaccompare_digest)r   r   expected_passwordcredentials_dicts      r>   check_credentialsz%basic_auth.<locals>.check_credentials  s=    $4X$>! &&'8(CC  s    	**c                |  K   	 |j                   d   }	 t        |      \  }} ||      }t        |t              r
| d{   }|sD| j                  t        j                  j
                  d      }t              |j                   d<   |S || _        y# t        $ rG | j                  t        j                  j
                  d      }t              |j                   d<   |cY S w xY w# t        $ rG | j                  t        j                  j
                  d      }t              |j                   d<   |cY S w xY w7 w)z
        Perform HTTP Basic Authentication.

        If it succeeds, set the connection's ``username`` attribute and return
        :obj:`None`. If it fails, return an HTTP 401 Unauthorized responss.

        AuthorizationzMissing credentials
zWWW-AuthenticatezUnsupported credentials
NzInvalid credentials
)rX   r   rD   rQ   rR   UNAUTHORIZEDr   r   r   rN   r   r   )	r   rL   authorizationrV   r   r   valid_credentialsr   realms	          r>   rZ   z#basic_auth.<locals>.process_request  sB    	#OOO<M	!:=!IHh .hA'3&7 7 !)),,'H 4PPU3VH/0O&
?  	!)),,'H 4PPU3VH/0O	  	!)),,+H 4PPU3VH/0O	 !8sS   D<B C' D<D:AD<AC$!D<#C$$D<'AD74D<6D77D<)r   rm   r   rm   rk   r   )r   r&   rL   r   rk   zResponse | None)r   r   r   tuplerm   rN   r   listallr   dict)r  r   r   credentials_listrZ   r   s   ` `  @r>   r(   r(   g  s    P 	t!2d!:;JKK+& $U38_k BCX.#D%S/)BK$PQI8HII"@ NOO<[MJKK 01	D ((,$,, 
,\ r?   rd   )r|   r   r   rp   r   r	   rk   zAwaitable[Server])r   r	   rk   r   ) NN)r  rm   r   z2tuple[str, str] | Iterable[tuple[str, str]] | Noner   z3Callable[[str, str], Awaitable[bool] | bool] | Nonerk   zACallable[[ServerConnection, Request], Awaitable[Response | None]]);
__future__r   rH   r   rQ   r}   rer   r   collections.abcr   r   r   r   typesr   typingr	   r
   r   r   
exceptionsr   extensions.baser   extensions.permessage_deflater   framesr   rX   r   r   r   http11r   r   r   r<   r   r   r   r7   r   r   r   r   r   compatibilityr!   r   r"   r#   __all__r&   r'   r$   r%   r   r(   r   r?   r>   <module>r     s    "     	  
 D D  / / & 4 L  
 / . . . # @ @ * -x3z x3vL! L!`
Q Ql :::
: : 	:,G FJMQnnCn Kn G	nr?   