
    vKgRg                    H   S SK Jr  S SKrS SKrS SKrS SKrS SKrS SKrS SKr	S SK
r
S SKrS SKrS SKJrJr  S SKJr  S SKJrJrJr  SSKJr  SSKJr  SS	KJr  SS
KJr  SSKJrJ r J!r!  SSK"J#r#J$r$J%r%  SSK&J'r'J(r(J)r)  SSK*J+r+  SSKJ,r,J-r-J.r.J/r/  SSK0J1r1  SSK2J3r3  / SQr4 " S S\15      r5 " S S5      r6S"S jr7  S#SSSSSSSS\#SSSSSSSS.                                         S$S jjjr8 S%       S&S jjr9S'S  jr:   S(       S)S! jjr;g)*    )annotationsN)IterableSequence)TracebackType)AnyCallable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                     ^  \ rS rSrSrSSS.         SU 4S jjjrSS jrSS\S4         SS	 jjrSU 4S
 jjr	SU 4S jjr
SrU =r$ )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 ``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.


      close_timeout	max_queuec               b   > U   [         R                  " 5       U l        [        TU ]  UUUUS9  U   g )Nr)   )	threadingr   request_rcvdsuper__init__)selfsocketprotocolr*   r+   	__class__s        V/var/www/highfloat_scraper/venv/lib/python3.13/site-packages/websockets/sync/server.pyr0   ServerConnection.__init__?   s:     	%OO-'	 	 	
 	    c                8    U R                   R                  X5      $ )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.

)r3   reject)r1   statustexts      r5   respondServerConnection.respondQ   s    & }}##F11r7   Nc                   U R                   R                  U5      (       d  [        S5      eU R                  b  U R	                  [
        S9   SnUb   U" X R                  5      nUc+  U R                  R                  U R                  5      U l        OXPl        U(       a  X0R                  R                  S'   SnUb'   U" X R                  U R                  5      nUb  XPl        U R                  R!                  U R                  5        SSS5        U R                  R                  b  U R                  R                  eg! [         aO  nX`R                  l        U R                  R                  [        R                  R                  S5      n SnAGN.SnAff = f! [         aO  nX`R                  l        U R                  R                  [        R                  R                  S5      n SnAGNSnAff = f! , (       d  f       N= f)z!
Perform the opening handshake.

ztimed out during handshakeN)expected_statezLFailed to open a WebSocket connection.
See server log for more information.
r#   )r.   waitTimeoutErrorrequestsend_contextr   	Exceptionr3   handshake_excr9   http
HTTPStatusINTERNAL_SERVER_ERRORacceptresponseheaderssend_response)r1   process_requestprocess_responseserver_headertimeoutrJ   excs          r5   	handshakeServerConnection.handshakef   s   .   %%g..;<<<<#""*"=".
#24#F #$(MM$8$8$FDM$,M 6CMM))(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   G7D?%AG7>F.G7?
F	AFG7FG7
G4%AG/)G7/G44G77
Hc                   > U R                   c8  [        U[        5      (       d   eXl         U R                  R	                  5         g[
        TU ]  U5        g)z
Process one incoming event.

N)rB   
isinstancer   r.   setr/   process_event)r1   eventr4   s     r5   rW   ServerConnection.process_event   sH     <<eW---- L!!# G!%(r7   c                   >  [         TU ]  5         U R                  R                  5         g! U R                  R                  5         f = f)z9
Read incoming data from the socket and process events.

N)r/   recv_eventsr.   rV   )r1   r4   s    r5   r[   ServerConnection.recv_events   s:    
	$G! !!#D!!#s	   , A)rB   r.   rJ   )
r2   socket.socketr3   r   r*   float | Noner+   *int | None | tuple[int | None, int | None]returnNone)r:   r   r;   strr`   r   )
rM   =Callable[[ServerConnection, Request], Response | None] | NonerN   GCallable[[ServerConnection, Request, Response], Response | None] | NonerO   
str | NonerP   r^   r`   ra   )rX   r   r`   ra   r`   ra   )__name__
__module____qualname____firstlineno____doc__r0   r<   r   rR   rW   r[   __static_attributes____classcell__)r4   s   @r5   r"   r"   %   s    < ')@B !
 $ > 
 $2:  $* $#P.P.P.  "!P." #P.$ 
%P.d)	$ 	$r7   r"   c                  x    \ rS rSrSr S       SS jjrSS jrSS jrSS jrSS jr	        SS	 jr
S
rg)r#      aw  
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                    Xl         X l        Uc  [        R                  " S5      nX0l        [
        R                  S:w  a#  [        R                  " 5       u  U l	        U l
        g g )Nzwebsockets.serverwin32)r2   handlerlogging	getLoggerloggersysplatformospipeshutdown_watchershutdown_notifier)r1   r2   rr   ru   s       r5   r0   Server.__init__   sP     >&&':;F<<7"<>GGI9D!4#9 #r7   c                   [         R                  " 5       n UR                  U R                  [         R                  5        [        R                  S:w  a*  UR                  U R                  [         R                  5         UR                  5          U R                  R                  5       u  p#[        R                  " U R                  X#4S9nUR                  5         M_  ! [
         a     gf = f! [         a     gf = f)z
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()

Nrq   )targetargs)	selectorsDefaultSelectorregisterr2   
EVENT_READ
ValueErrorrv   rw   rz   selectrI   OSErrorr-   Threadrr   start)r1   pollersockaddrthreads        r5   serve_foreverServer.serve_forever   s     **,	OODKK)=)=> <<7"OOD1193G3GHMMO "[[//1
 %%T\\MFLLN   	 		  s#   *C C/ 
C,+C,/
C<;C<c                    U R                   R                  5         [        R                  S:w  a"  [        R
                  " U R                  S5        gg)z0
See :meth:`socketserver.BaseServer.shutdown`.

rq      xN)r2   closerv   rw   rx   writer{   r1   s    r5   shutdownServer.shutdown  s9    
 	<<7"HHT++T2 #r7   c                6    U R                   R                  5       $ )z.
See :meth:`socketserver.BaseServer.fileno`.

)r2   filenor   s    r5   r   Server.fileno"  s    
 {{!!##r7   c                    U $ N r   s    r5   	__enter__Server.__enter__)  s    r7   c                $    U R                  5         g r   )r   )r1   exc_type	exc_value	tracebacks       r5   __exit__Server.__exit__,  s     	r7   )rr   ru   r{   rz   r2   r   )r2   r]   rr   z$Callable[[socket.socket, Any], None]ru   LoggerLike | Noner`   ra   rf   )r`   int)r`   r#   )r   ztype[BaseException] | Noner   zBaseException | Noner   zTracebackType | Noner`   ra   )rg   rh   ri   rj   rk   r0   r   r   r   r   r   rl   r   r7   r5   r#   r#      s|    , %)	FF 6F "	F
 
F$L3$, ( (	
 
r7   r#   c                ~    U S:X  a!  [         R                  " S[        5        [        $ [	        S[
        < SU < 35      e)NWebSocketServerz%WebSocketServer was renamed to Serverzmodule z has no attribute )warningswarnDeprecationWarningr#   AttributeErrorrg   )names    r5   __getattr__r   5  s=      3	
 
78,.@I
JJr7   deflater'   i   r(   )r   sslorigins
extensionssubprotocolsselect_subprotocolrM   rN   rO   compressionopen_timeoutr*   max_sizer+   ru   create_connectionc                 ^ ^^^^^^	^
^^^^^^^^ Tc2  SU;   a,  UR                  S5      m[        R                  " S[        5        Tb  [	        T5        US:X  a  [        T5      mOUb  [        SU 35      eTc  [        mUR                  SS5      mUR                  SS5      nUcf  T(       aF  Uc  [        S	5      eUR                  S
[        R                  5        [        R                  " U40 UD6nO'[        R                  " X440 UD6nOUb  [        S5      eTb  TR                  USSS9nSUUUU UUUUUU	U
UUUUU4S jjn[        UUT5      $ )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. Include :obj:`None`
        in the list if the lack of an origin is acceptable.
    extensions: List of supported extensions, in order in which they
        should be negotiated and run.
    subprotocols: List of supported subprotocols, in order of decreasing
        preference.
    select_subprotocol: Callback for selecting a subprotocol among
        those supported by the client and the server. It receives a
        :class:`ServerConnection` (not a
        :class:`~websockets.server.ServerProtocol`!) instance and a list of
        subprotocols offered by the client. Other than the first argument,
        it has the same behavior as the
        :meth:`ServerProtocol.select_subprotocol
        <websockets.server.ServerProtocol.select_subprotocol>` method.
    process_request: Intercept the request during the opening handshake.
        Return an HTTP response to force the response. 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.
    compression: The "permessage-deflate" extension is enabled by default.
        Set ``compression`` to :obj:`None` to disable it. See the
        :doc:`compression guide <../../topics/compression>` for details.
    open_timeout: Timeout for opening connections in seconds.
        :obj:`None` disables the timeout.
    close_timeout: Timeout for closing connections in seconds.
        :obj:`None` disables the timeout.
    max_size: Maximum size of incoming messages in bytes.
        :obj:`None` disables the limit.
    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5      n T(       d/  U R                  [        R                  [        R                  S5        Tba  U R                  UR                  5       5        [        U [        R                  5      (       d   eU R                  5         U R                  S 5        S nTb        SUU4S jjn[        TTTUTT
S9nTc   eT" U UTTS9m  TR                  TTTUR                  5       5        TR*                  R,                  [.        L d   e T	" T5        TR                  5         g ! [         a    U R                  5          g f = f! [         a-    TR!                  5         TR"                  R%                  5          g [         aG    TR&                  R)                  SSS9  TR!                  5         TR"                  R%                  5          g f = f! [         a<    TR&                  R)                  SSS9  TR                  [0        R2                  5         g f = f! [         a    U R                  5          g f = f)	NTc                B   > Tc   eU TR                   L d   eT" TU5      $ r   )r3   )r3   r   
connectionr   s     r5   protocol_select_subprotocol@serve.<locals>.conn_handler.<locals>.protocol_select_subprotocol  s2    
 .999#z':'::::-j,GGr7   )r   r   r   r   r   ru   r)   zopening handshake failed)exc_infozconnection handler failed)r3   r   r   zSequence[Subprotocol]r`   zSubprotocol | None)r   
setsockoptr2   IPPROTO_TCPTCP_NODELAY
settimeoutrP   rU   
ssl_module	SSLSocketdo_handshaker   rD   r   rR   rA   close_socketrecv_events_threadjoinru   errorr3   stater   r   INTERNAL_ERROR)r   r   deadliner   r3   r   r*   r   r   rr   ru   r+   r   r   r   rM   rN   r   rO   r   r   r   s        @r5   conn_handlerserve.<locals>.conn_handler  sK    L)9	  2 2F4F4FM  0 0 23!$
(<(<====!!#%  ( "-H,H"7H (H H &%)#>!H %000*+#	J	$$#$!$$&	  &&,,444#
#
   ";  	JJL	   '')--224 !!''(BT'R'')--224	  ;!!''(Cd'S  !9!9:;  	JJL	st   C
D6 "E =H( G %H( 6EE4G
H( AGH( GH( AH%"H( $H%%H( (II)r   r]   r   r   r`   ra   )popr   r   r   r   r   r   r"   
setdefaultr2   AF_UNIXcreate_serverwrap_socketr#   )rr   hostportr   r   r   r   r   r   rM   rN   rO   r   r   r*   r   r+   ru   r   kwargsr   r   r   s   `   ```````` ``````   @r5   r    r    ?  sN   T {}.jj',	

 l+i5jA
		 4[MBCC ,
 FE*Dzz&$/D|| !899h7''77D''??DGHH $)	  
^ ^ ^D $f--r7   c                     [        U 4SUS.UD6$ )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    )rr   r   r   s      r5   r!   r!   ^  s    ( 9t$9&99r7   c                     U u  p[        U[        5      =(       a    [        U[        5      $ ! [        [        4 a     gf = fNF)rU   rb   	TypeErrorr   )credentialsusernamepasswords      r5   is_credentialsr   u  sD    G( (C(FZ#-FF z" s   - A A c                  ^ ^^ USL TSL :X  a  [        S5      eUb  [        U5      (       a  [        [        [        [        4   U5      /nOv[        U[        5      (       aS  [        [        [        [        [        [        4      U5      5      n[        S U 5       5      (       d  [        SU 35      eO[        SU 35      e[        U5      mSU4S jjmTc   e      SUU 4S jjnU$ )	a  
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  6   #    U H  n[        U5      v   M     g 7fr   )r   ).0items     r5   	<genexpr>basic_auth.<locals>.<genexpr>  s     I8H~d++8Hs   zinvalid credentials argument: c                \   >  TU    n[        R                  " X!5      $ ! [          a     gf = fr   )KeyErrorhmaccompare_digest)r   r   expected_passwordcredentials_dicts      r5   check_credentials%basic_auth.<locals>.check_credentials  s;    $4X$>! &&'8CC  s    
++c                @  >  UR                   S   n [        U5      u  pET" XE5      (       dD  U R                  [        R                  R
                  S5      n[        T5      UR                   S'   U$ X@l	        g! [         aG    U R                  [        R                  R
                  S5      n[        T5      UR                   S'   Us $ f = f! [         aG    U R                  [        R                  R
                  S5      n[        T5      UR                   S'   Us $ f = f)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)
rK   r   r<   rF   rG   UNAUTHORIZEDr   r   r   r   )r   rB   authorizationrJ   r   r   r   realms         r5   rM   #basic_auth.<locals>.process_request  s   	#OOO<M	!:=!IH !44!)),,'H 4PPU3VH/0O&7  	!)),,'H 4PPU3VH/0O	  	!)),,+H 4PPU3VH/0O	s$   A8 C 8AC	C	ADD)r   rb   r   rb   r`   bool)r   r"   rB   r   r`   zResponse | None)r   r   r	   tuplerb   rU   r   listallr   dict)r   r   r   credentials_listrM   r   s   ` `  @r5   r$   r$   ~  s   P 	t!2d!:;JKK+&& $U38_k BCX..#D%S/)BK$PQI8HIII"@ NOO J <[MJKK 01	D (((($(( 
( (T r7   )r   rb   r`   r   )NN)*rr   "Callable[[ServerConnection], None]r   re   r   
int | Noner   zsocket.socket | Noner   zssl_module.SSLContext | Noner   zSequence[Origin | None] | Noner   z'Sequence[ServerExtensionFactory] | Noner   zSequence[Subprotocol] | Noner   zNCallable[[ServerConnection, Sequence[Subprotocol]], Subprotocol | None] | NonerM   rc   rN   rd   rO   re   r   re   r   r^   r*   r^   r   r   r+   r_   ru   r   r   ztype[ServerConnection] | Noner   r   r`   r#   r   )rr   r   r   re   r   r   r`   r#   )r   r   r`   r   ) NN)r   rb   r   z2tuple[str, str] | Iterable[tuple[str, str]] | Noner   z!Callable[[str, str], bool] | Noner`   z6Callable[[ServerConnection, Request], Response | None])<
__future__r   r   rF   rs   rx   r   r2   r   r   rv   r-   r   collections.abcr   r   typesr   typingr   r   r	   
exceptionsr   extensions.baser   extensions.permessage_deflater   framesr   rK   r   r   r   http11r   r   r   r3   r   r   r   serverr   r   r   r   r   r   r   utilsr   __all__r"   r#   r   r    r!   r   r$   r   r7   r5   <module>r     sA   "    	    
   .  & & & 4 L  
 / . . . # @ @ "  Nj$z j$Z` `FK \. "&(,.2:>15 	 	 	 &'!#"$ <> $7;Y\./\.
\. \. \. 
&\. ,\. 8\. /\.	\.(	)\.6	7\.B C\.D E\.H I\.J  K\.N O\.P :Q\.T U\.X 5Y\.Z [\.\ ]\.B	 :/:
: : 	:.G FJ;?jjCj 9j <	jr7   