
    ,h,k                    N   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Zd dlZd dlZd dl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/m0Z0m1Z1 ddl2m3Z3 ddl4m5Z5 g dZ6 G d de3      Z7 G d d      Z8d#dZ9	 	 d$ddddddddde%ddddddddd	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d%dZ:	 d&	 	 	 	 	 	 	 d'd Z;d(d!Z<	 	 	 d)	 	 	 	 	 	 	 d*d"Z=y)+    )annotationsN)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   )
Connection)Deadline)serve
unix_serveServerConnectionServer
basic_authc                       e Zd ZdZddddd	 	 	 	 	 	 	 	 	 	 	 	 	 d fdZddZddedf	 	 	 	 	 	 	 	 	 dd	Zd fd
Zd fdZ	 xZ
S )r#   a/  
    :mod:`threading` implementation of a WebSocket server connection.

    :class:`ServerConnection` provides :meth:`recv` and :meth:`send` methods for
    receiving and sending messages.

    It supports iteration to receive messages::

        for message in websocket:
            process(message)

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

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

    Args:
        socket: Socket connected to a WebSocket client.
        protocol: Sans-I/O connection.

       
      ping_intervalping_timeoutclose_timeout	max_queuec               r    |  t        j                         | _        t        |   ||||||       |  |  |  y )Nr*   )	threadingr   request_rcvdsuper__init__)selfsocketprotocolr+   r,   r-   r.   	__class__s          X/var/www/html/Resume-Scraper/venv/lib/python3.12/site-packages/websockets/sync/server.pyr3   zServerConnection.__init__@   sF     	%OO-'%' 	 	
 	    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.

        )r6   reject)r4   statustexts      r8   respondzServerConnection.respondX   s    & }}##FD11r9   Nc                   | j                   j                  |      st        d      | j                  | j	                  t
              5  d}|	  || | j                        }|+| j                  j                  | j                        | _        n|| _        |r|| j                  j                  d<   d}|(	  || | j                  | j                        }||| _        | j                  j!                  | j                         ddd       | j                  j                  | j                  j                  y# t        $ rP}|| j                  _        | j                  j                  t        j                  j                  d      }Y d}~)d}~ww xY w# t        $ rP}|| j                  _        | j                  j                  t        j                  j                  d      }Y d}~d}~ww xY w# 1 sw Y   xY w)z1
        Perform the opening handshake.

        z-timed out while waiting for handshake requestN)expected_statezLFailed to open a WebSocket connection.
See server log for more information.
r$   )r1   waitTimeoutErrorrequestsend_contextr   	Exceptionr6   handshake_excr;   http
HTTPStatusINTERNAL_SERVER_ERRORacceptresponseheaderssend_response)r4   process_requestprocess_responseserver_headertimeoutrK   excs          r8   	handshakezServerConnection.handshakem   s   .   %%g.NOO<<#""*"= *;".
#24#F #$(MM$8$8$FDM$,DM 6CDMM))(3#/
#3D$,,#V  +(0++DMM:U*;h ==&&2----- 3] % 693#'==#7#7 OOAA!I$. % 693#'==#7#7 OOAA!I$;*; *;sc   	G/D7"AG/6F.G/7	F AFG/FG/	G,AG'!G/'G,,G//G8c                    | j                   4t        |t              sJ || _         | j                  j	                          yt
        |   |       y)z.
        Process one incoming event.

        N)rC   
isinstancer   r1   setr2   process_event)r4   eventr7   s     r8   rW   zServerConnection.process_event   sD     <<eW-- DL!!# G!%(r9   c                    	 t         |           | j                  j                          y# | j                  j                          w xY w)zI
        Read incoming data from the socket and process events.

        N)r2   recv_eventsr1   rV   )r4   r7   s    r8   rZ   zServerConnection.recv_events   s:    
	$G! !!#D!!#s	   , A)r5   socket.socketr6   r   r+   float | Noner,   r\   r-   r\   r.   *int | None | tuple[int | None, int | None]returnNone)r<   r   r=   strr^   r   )
rN   =Callable[[ServerConnection, Request], Response | None] | NonerO   GCallable[[ServerConnection, Request, Response], Response | None] | NonerP   
str | NonerQ   r\   r^   r_   )rX   r   r^   r_   r^   r_   )__name__
__module____qualname____doc__r3   r>   r   rS   rW   rZ   __classcell__)r7   s   @r8   r#   r#   &   s    < ')%'&(@B// !/
 $/ #/ $/ >/ 
/02:  $* $#P.P.P.  "!P." #P.$ 
%P.d)	$ 	$r9   r#   c                  b    e Zd ZdZ	 d		 	 	 	 	 	 	 d
dZddZddZddZddZ	 	 	 	 	 	 	 	 ddZ	y)r$   a  
    WebSocket server returned by :func:`serve`.

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

    Args:
        socket: Server socket listening for new connections.
        handler: Handler for one connection. Receives the socket and address
            returned by :meth:`~socket.socket.accept`.
        logger: Logger for this server.
            It defaults to ``logging.getLogger("websockets.server")``.
            See the :doc:`logging guide <../../topics/logging>` for details.

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

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

        Typical use::

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

        Nrl   )targetargs)	selectorsDefaultSelectorregisterr5   
EVENT_READ
ValueErrorrq   rr   ru   selectrJ   OSErrorr0   Threadrm   start)r4   pollersockaddrthreads        r8   serve_foreverzServer.serve_forever   s     **,	OODKK)=)=> <<7"OOD1193G3GHMMO "[[//1
d %%T\\tMFLLN   	 		  s#   *C  C/  	C,+C,/	C;:C;c                    | j                   j                          t        j                  dk7  r!t	        j
                  | j                  d       yy)z@
        See :meth:`socketserver.BaseServer.shutdown`.

        rl      xN)r5   closerq   rr   rs   writerv   r4   s    r8   shutdownzServer.shutdown   s9    
 	<<7"HHT++T2 #r9   c                6    | j                   j                         S )z>
        See :meth:`socketserver.BaseServer.fileno`.

        )r5   filenor   s    r8   r   zServer.fileno)  s    
 {{!!##r9   c                    | S N r   s    r8   	__enter__zServer.__enter__0  s    r9   c                $    | j                          y r   )r   )r4   exc_type	exc_value	tracebacks       r8   __exit__zServer.__exit__3  s     	r9   r   )r5   r[   rm   z$Callable[[socket.socket, Any], None]rp   LoggerLike | Noner^   r_   rd   )r^   int)r^   r$   )r   ztype[BaseException] | Noner   zBaseException | Noner   zTracebackType | Noner^   r_   )
re   rf   rg   rh   r3   r   r   r   r   r   r   r9   r8   r$   r$      s|    , %)	FF 6F "	F
 
F$L3$, ( (	
 
r9   r$   c                v    | dk(  r t        j                  dt               t        S t	        dt
        d|       )NWebSocketServerz%WebSocketServer was renamed to Serverzmodule z has no attribute )warningswarnDeprecationWarningr$   AttributeErrorre   )names    r8   __getattr__r   <  s=      3	
 
78,.@I
JJr9   deflater(   r'   i   r)   )r   sslorigins
extensionssubprotocolsselect_subprotocolcompressionrN   rO   rP   open_timeoutr+   r,   r-   max_sizer.   rp   create_connectionc                  
 /d|v r+|j                  d      t        j                  dt               t	               |	dk(  rt              n|	t        d|	       t        |j                  dd      |j                  dd      }|_rD|t        d	      |j                  d
t        j                         t        j                  |fi |}n&t        j                  ||ffi |}n|t        d      j                  |dd      }d 
fd}t        ||      S )a  
    Create a WebSocket server listening on ``host`` and ``port``.

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

    The handler receives 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 function returns a :class:`Server` whose API mirrors
    :class:`~socketserver.BaseServer`. Treat it as a context manager to ensure
    that it will be closed and call :meth:`~Server.serve_forever` to serve
    requests::

        from websockets.sync.server import serve

        def handler(websocket):
            ...

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

    Args:
        handler: Connection handler. It receives the WebSocket connection,
            which is a :class:`ServerConnection`, in argument.
        host: Network interfaces the server binds to.
            See :func:`~socket.create_server` for details.
        port: TCP port the server listens on.
            See :func:`~socket.create_server` for details.
        sock: Preexisting TCP socket. ``sock`` replaces ``host`` and ``port``.
            You may call :func:`socket.create_server` to create a suitable TCP
            socket.
        ssl: Configuration for enabling TLS on the connection.
        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. 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: 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.
        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.
        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 :func:`~socket.create_server`.

    Nssl_contextzssl_context was renamed to sslr   zunsupported compression: unixFpathzmissing path argumentfamilyz(path and sock arguments are incompatibleT)server_sidedo_handshake_on_connectc                   t              }	 s/| j                  t        j                  t        j                  d       \| j                  |j                                t        | t        j                        sJ | j                          | j                  d        d }	 	 	 	 	 	 dfd}t        |
      }J  | |      	 	 j                  |j                                j*                  j,                  t.        u sJ 	 j1                           	       j                          y # t        $ r | j                          Y y w xY w# t        $ r- j!                          j"                  j%                          Y y t        $ rJ j&                  j)                  dd       j!                          j"                  j%                          Y y w xY w# t        $ r? j&                  j)                  dd       j                  t2        j4                         Y y w xY w# t        $ r | j                          Y y w xY w)	NTc                >    J | j                   u sJ  |      S r   )r6   )r6   r   
connectionr   s     r8   protocol_select_subprotocolz@serve.<locals>.conn_handler.<locals>.protocol_select_subprotocol(  s,    
 .99#z':':::-j,GGr9   )r   r   r   r   r   rp   r*   zopening handshake failed)exc_infozconnection handler failed)r6   r   r   zSequence[Subprotocol]r^   zSubprotocol | None)r    
setsockoptr5   IPPROTO_TCPTCP_NODELAY
settimeoutrQ   rU   
ssl_module	SSLSocketdo_handshaker   rE   r   rS   rB   close_socketrecv_events_threadjoinrp   errorr6   stater   start_keepaliver   INTERNAL_ERROR)r   r   deadliner   r6   r   r-   r   r   rm   rp   r.   r   r   r   r+   r,   rN   rO   r   rP   r   r   r   s        @r8   conn_handlerzserve.<locals>.conn_handler	  sK    L);	  2 2F4F4FM  0 0 23!$
(<(<==!!#%  ( "-H,H"7H (H &%)#>!H %00*+)+#J	$$#$!$$&	  &&,,44#**,
#
   "=  	JJL	   '')--224 !!''(BT'R'')--224	  ;!!''(Cd'S  !9!9:;  	JJL	st   CD> "E 6H2 G' -H2 >EE3G$H2 AG$!H2 #G$$H2 'AH/,H2 .H//H2 2II)r   r[   r   r   r^   r_   )popr   r   r   r   r   r~   r#   
setdefaultr5   AF_UNIXcreate_serverwrap_socketr$   )rm   hostportr   r   r   r   r   r   r   rN   rO   rP   r   r+   r,   r-   r   r.   rp   r   kwargsr   r   r   s   `   ````` ```````````   @r8   r!   r!   F  sQ   f {}.jj',	

 l+i5jA
		 4[MBCC ,
 FE*Dzz&$/D|| !899h7''77D''t??DGHH $)	  
a a aJ $f--r9   c                     t        | fd|d|S )a  
    Create a WebSocket server listening on a Unix socket.

    This function accepts the same keyword arguments as :func:`serve`.

    It's only available on Unix.

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

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

    T)r   r   )r!   )rm   r   r   s      r8   r"   r"   q  s    ( 9t$9&99r9   c                |    	 | \  }}t        |t              xr t        |t              S # t        t        f$ r Y yw xY wNF)rU   r`   	TypeErrorr~   )credentialsusernamepasswords      r8   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 )	ah  
    Factory for ``process_request`` to enforce HTTP Basic Authentication.

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

        from websockets.sync.server import basic_auth, serve

        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 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r   )r   ).0items     r8   	<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      r8   check_credentialsz%basic_auth.<locals>.check_credentials  s=    $4X$>! &&'8(CC  s    	**c                8   	 |j                   d   }	 t        |      \  }} ||      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)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
zInvalid credentials
N)
rL   r   r>   rG   rH   UNAUTHORIZEDr   r   r   r   )r   rC   authorizationrK   r   r   r   realms         r8   rN   z#basic_auth.<locals>.process_request  s   	#OOO<M	!:=!IHh !84!)),,'H 4PPU3VH/0O&
7  	!)),,'H 4PPU3VH/0O	  	!)),,+H 4PPU3VH/0O	s$   A6 C	 6ACC	ADD)r   r`   r   r`   r^   bool)r   r#   rC   r   r^   zResponse | None)r~   r   r
   tupler`   rU   r   listallr   dict)r   r   r   credentials_listrN   r   s   ` `  @r8   r%   r%     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 ((($(( 
(T r9   )r   r`   r^   r   )NN).rm   "Callable[[ServerConnection], None]r   rc   r   
int | Noner   zsocket.socket | Noner   zssl_module.SSLContext | Noner   z0Sequence[Origin | re.Pattern[str] | None] | Noner   z'Sequence[ServerExtensionFactory] | Noner   zSequence[Subprotocol] | Noner   zNCallable[[ServerConnection, Sequence[Subprotocol]], Subprotocol | None] | Noner   rc   rN   ra   rO   rb   rP   rc   r   r\   r+   r\   r,   r\   r-   r\   r   r   r.   r]   rp   r   r   ztype[ServerConnection] | Noner   r   r^   r$   r   )rm   r   r   rc   r   r   r^   r$   )r   r   r^   r   ) NN)r   r`   r   z2tuple[str, str] | Iterable[tuple[str, str]] | Noner   z!Callable[[str, str], bool] | Noner^   z6Callable[[ServerConnection, Request], Response | None])>
__future__r   r   rG   rn   rs   rerz   r5   r   r   rq   r0   r   collections.abcr   r   typesr   typingr   r   r	   r
   
exceptionsr   extensions.baser   extensions.permessage_deflater   framesr   rL   r   r   r   http11r   r   r   r6   r   r   r   serverr   r   r   r   r   r   r   utilsr    __all__r#   r$   r   r!   r"   r   r%   r   r9   r8   <module>r      sb   "    	 	    
   .  / / & 4 L  
 / . . . # @ @ "  Np$z p$f` `FK h. "&(,@D:>15 	' 	 	 &!#"$!#"$ <> $7;_h./h.
h. h. h. 
&h. >h. 8h. /h.	h.& 'h.,	-h.:	;h.F Gh.J Kh.L  Mh.N Oh.P  Qh.T Uh.V :Wh.Z [h.^ 5_h.` ah.b ch.Z	 :/:
: : 	:.G FJ;?jjCj 9j <	jr9   