
    vKgR              	      v   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J	r	J
r
  S SKJrJrJr  SSKJrJr  SSKJrJrJrJrJrJr  SSKJrJr  SS	KJrJrJrJ r J!r!  SS
K"J#r#J$r$  SSK%J&r&  SSK'J(r(J)r)J*r*J+r+J,r,  SSKJ-r-J.r.J/r/J0r0J1r1J2r2J3r3  SSK4J5r5  S/r6 " S S\+5      r7 " S S\75      r8\&" \9" 5       SSSSSS.S9  g)    )annotationsN)	GeneratorSequence)AnyCallablecast   )HeadersMultipleValuesError)InvalidHandshakeInvalidHeaderInvalidHeaderValueInvalidOriginInvalidUpgradeNegotiationError)	ExtensionServerExtensionFactory)build_extensionparse_connectionparse_extensionparse_subprotocolparse_upgrade)RequestResponse)lazy_import)
CONNECTINGOPENSERVERProtocolState)ConnectionOptionExtensionHeader
LoggerLikeOrigin
StatusLikeSubprotocolUpgradeProtocol)
accept_keyServerProtocolc                     ^  \ rS rSrSrSSSS\SSS.               SU 4S jjjrSS jr    SS jrSS	 jr	    SS
 jr
SS jr    SS jrSS jrSS jrSU 4S jjrSrU =r$ )r)   .   a:  
Sans-I/O implementation of a WebSocket server connection.

Args:
    origins: Acceptable values of the ``Origin`` header; include
        :obj:`None` in the list if the lack of an origin is acceptable.
        This is useful for defending against Cross-Site WebSocket
        Hijacking attacks.
    extensions: List of supported extensions, in order in which they
        should be tried.
    subprotocols: List of supported subprotocols, in order of decreasing
        preference.
    select_subprotocol: Callback for selecting a subprotocol among
        those supported by the client and the server. It has the same
        signature as the :meth:`select_subprotocol` method, including a
        :class:`ServerProtocol` instance as first argument.
    state: Initial state of the WebSocket connection.
    max_size: Maximum size of incoming messages in bytes;
        :obj:`None` disables the limit.
    logger: Logger for this connection;
        defaults to ``logging.getLogger("websockets.server")``;
        see the :doc:`logging guide <../../topics/logging>` for details.

Ni   )origins
extensionssubprotocolsselect_subprotocolstatemax_sizeloggerc                  > [         TU ]  [        UUUS9  Xl        X l        X0l        Ub'  [        U SUR                  X R                  5      5        g g )N)sider0   r1   r2   r/   )	super__init__r   r,   available_extensionsavailable_subprotocolssetattr__get__	__class__)	selfr,   r-   r.   r/   r0   r1   r2   r;   s	           Q/var/www/highfloat_scraper/venv/lib/python3.13/site-packages/websockets/server.pyr6   ServerProtocol.__init__H   sc    " 		 	 	
 $.!&2#) $"**4@ *    c                    U R                  U5      u  nnn[+        5       n	[,        R.                  R1                  SS9U	S'   S	U	S
'   S
U	S'   X)S'   Ub  X9S'   Ub  XIS'   [3        SSU	5      $ ! [         ao  nXQl        XPl        U R                  (       a  U R
                  R	                  SSS9  U R                  [        R                  R                  SU S35      s SnA$ SnAf[         a  nXQl        XPl        U R                  (       a  U R
                  R	                  SSS9  U R                  [        R                  R                  SU S35      nS	UR                  S
'   Us SnA$ SnAf[         a  nXQl        XPl        U R                  (       a  U R
                  R	                  SSS9  [        [        U5      nU nUR                   b#  UR                   nUSU 3-  nUR                   b  M#  U R                  [        R                  R"                  SU S35      s SnA$ SnAf[$         aZ  nXQl        XPl        U R
                  R'                  SSS9  U R                  [        R                  R(                  S5      s SnA$ SnAff = f)a]  
Create a handshake response to accept the connection.

If the handshake request is valid and the handshake successful,
:meth:`accept` returns an HTTP response with status code 101.

Else, it returns an HTTP response with another status code. This rejects
the connection, like :meth:`reject` would.

You must send the handshake response with :meth:`send_response`.

You may modify the response before sending it, typically by adding HTTP
headers.

Args:
    request: WebSocket handshake request received from the client.

Returns:
    WebSocket handshake response or HTTP response to send to the client.

z! invalid originT)exc_infoz'Failed to open a WebSocket connection: z.
Nz! invalid upgradez^.

You cannot access a WebSocket server directly with a browser. You need a WebSocket client.
	websocketUpgradez! invalid handshakez; zopening handshake failedzLFailed to open a WebSocket connection.
See server log for more information.
usegmtDate
ConnectionzSec-WebSocket-AcceptSec-WebSocket-ExtensionsSec-WebSocket-Protocole   zSwitching Protocols)process_requestr   
_exceptionhandshake_excdebugr2   rejecthttp
HTTPStatus	FORBIDDENr   UPGRADE_REQUIREDheadersr   r   BaseException	__cause__BAD_REQUEST	ExceptionerrorINTERNAL_SERVER_ERRORr
   emailutils
formatdater   )
r<   requestaccept_headerextensions_headerprotocol_headerexcresponse	exc_chainexc_strrT   s
             r=   acceptServerProtocol.acceptk   sv   ,9	
 $$W-	!n )++000=(	 )*7&'(2C./&0?,-2G<<G  	!$!$zz!!"4t!D;;))9#cB   	!$!$zz!!"5!E{{00=cU CE FH +6HY'O 	!$!$zz!!"7$!G]C0I"G%%1%//	R	{++ %%1 ;;++9'#F   	 "%!$KK84H;;55= 	s]   A* *
J4A$CJJ+A5E& J&J3A8H --H J J-AJ<JJc                   UR                   n[        UR                  S5       Vs/ sH  n[        U5      PM     sn/ 5      n[	        S U 5       5      (       d(  [        SU(       a  SR                  U5      5      eS5      e[        UR                  S5       Vs/ sH  n[        U5      PM     sn/ 5      n[        U5      S:X  a  US   R                  5       S:X  d(  [        SU(       a  SR                  U5      5      eS5      e US	   n [        R                  " UR                  5       SS9n[        U5      S:w  a  [%        S	U5      e US   n	U	S:w  a  [%        SU	5      e['        U5      n
U R)                  U5      U l        U R-                  U5      u  ol        U R1                  U5      =ol        U
UU4$ s  snf s  snf ! [         a    [        S	5      Se[         a    [        S	S
5      Sef = f! [         R"                   a  n[%        S	U5      UeSnAff = f! [         a    [        S5      Se[         a    [        SS
5      Sef = f)a  
Check a handshake request and negotiate extensions and subprotocol.

This function doesn't verify that the request is an HTTP/1.1 or higher
GET request and doesn't check the ``Host`` header. These controls are
usually performed earlier in the HTTP request handling code. They're
the responsibility of the caller.

Args:
    request: WebSocket handshake request received from the client.

Returns:
    ``Sec-WebSocket-Accept``, ``Sec-WebSocket-Extensions``, and
    ``Sec-WebSocket-Protocol`` headers for the handshake response.

Raises:
    InvalidHandshake: If the handshake request is invalid;
        then the server must return 400 Bad Request error.

rG   c              3  D   #    U H  oR                  5       S :H  v   M     g7f)upgradeN)lower).0values     r=   	<genexpr>1ServerProtocol.process_request.<locals>.<genexpr>   s     F:%;;=I-:s    , NrC   r	   r   rB   zSec-WebSocket-Keymultiple valuesT)validate   zSec-WebSocket-Version13)rT   sumget_allr   anyr   joinr   lenrk   KeyErrorr   r   base64	b64decodeencodebinasciiErrorr   r(   process_originoriginprocess_extensionsr-   process_subprotocolsubprotocol)r<   r^   rT   rm   
connectionrj   keyraw_keyrb   versionr_   r`   ra   s                r=   rK   ServerProtocol.process_request   sd   0 //-029//,2OP2Oe$2OPRT.

 F:FFF zdii
3 GK  *-/6y/IJ/Ie]5!/IJB*
 G!gaj&6&6&8K&G 'DIIg,>TTtTT	R-.C	H&&szz|dCG w<2$%8#>>	V56G d?$%<gFF"3))'2-1-D-DW-M*?-1-E-Eg-NN* 
 	
e Q K  	? 34$>" 	R 35FGTQ	R
 ~~ 	H$%8#>CG	H  	C 78dB" 	V 79JKQUU	Vs;   F4F9F> 	#G. H >-G+.HHH-Ic                     UR                  S5      nUb  [        [        U5      nU R
                  b  X R
                  ;  a  [        U5      eU$ ! [         a    [        SS5      Sef = f)z
Handle the Origin HTTP request header.

Args:
    headers: WebSocket handshake request headers.

Returns:
   origin, if it is acceptable.

Raises:
    InvalidHandshake: If the Origin header is invalid.
    InvalidOrigin: If the origin isn't acceptable.

r$   rq   N)getr   r   r   r$   r,   r   )r<   rT   r   s      r=   r   ServerProtocol.process_origin  sq    "	G[[*F &&)F<<#\\)#F++ # 	G*;<$F	Gs   A A'c                   Sn/ n/ nUR                  S5      nU(       a  U R                  (       a  [        U Vs/ sH  n[        U5      PM     sn/ 5      nU Hb  u  pU R                   HM  n
U
R                  U:w  a  M   U
R                  X5      u  pUR                  X45        UR                  U5          M`     Md     U(       a  [        U5      nX$4$ s  snf ! [         a     M|  f = f)a  
Handle the Sec-WebSocket-Extensions HTTP request header.

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

Per :rfc:`6455`, negotiation rules are defined by 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: WebSocket handshake request headers.

Returns:
    ``Sec-WebSocket-Extensions`` HTTP response header and list of
    accepted extensions.

Raises:
    InvalidHandshake: If the Sec-WebSocket-Extensions header is invalid.

NrH   )	rv   r7   ru   r   nameprocess_request_paramsr   appendr   )r<   rT   response_header_valueextension_headersaccepted_extensionsheader_valuesheader_valueparsed_header_valuesr   request_paramsext_factoryresponse_params	extensions                r=   r   !ServerProtocol.process_extensions;  s    N -135/1(BCT66:=CPQ=<.=QSU;  )=$#'#<#<K"''4/ !5@5W5W*62 &,,d-DE'..y9 % $= )=2 $34E$F!$99? R , ! !s   C>C
C%$C%c                    [        UR                  S5       Vs/ sH  n[        U5      PM     sn/ 5      nU R                  U5      $ s  snf )aA  
Handle the Sec-WebSocket-Protocol HTTP request header.

Args:
    headers: WebSocket handshake request headers.

Returns:
   Subprotocol, if one was selected; this is also the value of the
   ``Sec-WebSocket-Protocol`` response header.

Raises:
    InvalidHandshake: If the Sec-WebSocket-Subprotocol header is invalid.

rI   )ru   rv   r   r/   )r<   rT   r   r.   s       r=   r   "ServerProtocol.process_subprotocol  sW     /2 %,OO4L$M$ML ",/$M /
 &&|44s   Ac                    U R                   (       d  gU(       d  [        S5      e[        U5      nU R                    H  nX2;   d  M
  Us  $    [        SSR                  U R                   5      -   5      e)a  
Pick a subprotocol among those offered by the client.

If several subprotocols are supported by both the client and the server,
pick the first one in the list declared the server.

If the server doesn't support any subprotocols, continue without a
subprotocol, regardless of what the client offers.

If the server supports at least one subprotocol and the client doesn't
offer any, abort the handshake with an HTTP 400 error.

You provide a ``select_subprotocol`` argument to :class:`ServerProtocol`
to override this logic. For example, you could accept the connection
even if client doesn't offer a subprotocol, rather than reject it.

Here's how to negotiate the ``chat`` subprotocol if the client supports
it and continue without a subprotocol otherwise::

    def select_subprotocol(protocol, subprotocols):
        if "chat" in subprotocols:
            return "chat"

Args:
    subprotocols: List of subprotocols offered by the client.

Returns:
    Selected subprotocol, if a common subprotocol was found.

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

Raises:
    NegotiationError: Custom implementations may raise this exception
        to abort the handshake with an HTTP 400 error.

Nzmissing subprotocolz%invalid subprotocol; expected one of rp   )r8   r   setrx   )r<   r.   proposed_subprotocolsr   s       r=   r/   !ServerProtocol.select_subprotocol  st    R ** "#899 !$L 166K3"" 7
 3ii3345
 	
r?   c           
        [         R                  " U5      nUR                  5       n[        S[        R
                  R                  SS94SS[        [        U5      5      4S/5      n[        UR                  UR                  XC5      $ )a  
Create a handshake response to reject the connection.

A short plain text response is the best fallback when failing to
establish a WebSocket connection.

You must send the handshake response with :meth:`send_response`.

You may modify the response before sending 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.

rF   TrD   )rG   closezContent-Length)zContent-Typeztext/plain; charset=utf-8)rP   rQ   r}   r
   r[   r\   r]   strry   r   rm   phrase)r<   statustextbodyrT   s        r=   rO   ServerProtocol.reject  su    * ({{}//t/<='!3s4y>2=	
 fmmWCCr?   c                B   U R                   (       a  UR                  UR                  p2U R                  R                  SX#5        UR                  R                  5        H!  u  pEU R                  R                  SXE5        M#     UR                  b/  U R                  R                  S[        UR                  5      5        U R                  R                  UR                  5       5        UR                  S:X  a<  U R                  [        L d   e[        U l        U R                  R                  S5        gU R                  R                  SUR                  UR                  5        U R                  5         U R!                  5       U l        [%        U R"                  5        g)zl
Send a handshake response to the client.

Args:
    response: WebSocket handshake response event to send.

z> HTTP/1.1 %d %sz> %s: %sNz> [body] (%d bytes)rJ   zconnection openzconnection rejected (%d %s))rN   status_codereason_phraser2   rT   	raw_itemsr   ry   writesr   	serializer0   r   r   infosend_eofdiscardparsernext)r<   rc   coder   r   rm   s         r=   send_responseServerProtocol.send_response  s,    ::#//1G1G&KK0$?&..88:
!!*c9 ;}}(!!"7X]]9KL8--/03&::+++DJKK./ KK-$$&& MMO,,.DKr?   c              #    >#    U R                   [        L a   [        R                  " U R                  R
                  5       S h  vN nU R                  (       ae  U R                  R                  SWR                  5        UR                  R!                  5        H!  u  p4U R                  R                  SX45        M#     U R"                  R%                  W5        [&        TU ]  5        S h  vN   g  N! [         aN  nX l        U R                  5         U R                  5       U l
        [        U R                  5        S v    S nANS nAff = f Nb7f)Nz< GET %s HTTP/1.1z< %s: %s)r0   r   r   parsereader	read_linerX   rM   r   r   r   r   rN   r2   pathrT   r   eventsr   r5   )r<   r^   rb   r   rm   r;   s        r=   r   ServerProtocol.parse$  s     ::#	%,]]KK))&  zz!!"5w||D")//";";"=JCKK%%j#= #> KKw'7=?""#  %(""llnT[[! 	#sN   E-C4 C2C4 
B"E,E-E2C4 4
E>AEEEE)	r7   r8   r-   rM   r   r,   r   r0   r   )r,   zSequence[Origin | None] | Noner-   z'Sequence[ServerExtensionFactory] | Noner.   zSequence[Subprotocol] | Noner/   zLCallable[[ServerProtocol, Sequence[Subprotocol]], Subprotocol | None] | Noner0   r    r1   z
int | Noner2   zLoggerLike | NonereturnNone)r^   r   r   r   )r^   r   r   z"tuple[str, str | None, str | None])rT   r
   r   zOrigin | None)rT   r
   r   z"tuple[str | None, list[Extension]])rT   r
   r   Subprotocol | None)r.   zSequence[Subprotocol]r   r   )r   r%   r   r   r   r   )rc   r   r   r   )r   zGenerator[None])__name__
__module____qualname____firstlineno____doc__r   r6   rf   rK   r   r   r   r/   rO   r   r   __static_attributes____classcell__r;   s   @r=   r)   r)   .   s    8 37>B59 !$$(! 0! <	!
 3!! ! ! "!  
!! !F_=BQ
Q
 
,Q
f8O:O: 
,O:b52:
+:
 
:
xDB D# #r?   c                  ,   ^  \ rS rSrSU 4S jjrSrU =r$ )ServerConnectioni;  c                \   > [         R                  " S[        5        [        TU ]  " U0 UD6  g )Nz.ServerConnection was renamed to ServerProtocol)warningswarnDeprecationWarningr5   r6   )r<   argskwargsr;   s      r=   r6   ServerConnection.__init__<  s)    <	
 	$)&)r?    )r   r   r   r   r   r   )r   r   r   r   r6   r   r   r   s   @r=   r   r   ;  s    * *r?   r   z.legacy.server)WebSocketServerWebSocketServerProtocol	broadcastserve
unix_serve)deprecated_aliases):
__future__r   r{   r~   email.utilsr[   rP   r   collections.abcr   r   typingr   r   r   datastructuresr
   r   
exceptionsr   r   r   r   r   r   r-   r   r   rT   r   r   r   r   r   http11r   r   importsr   protocolr   r   r   r   r    r!   r"   r#   r$   r%   r&   r'   r\   r(   __all__r)   r   globalsr   r?   r=   <module>r      s    "      / & & 8  :  &   ? ?    
J#X J#Z*~ * I ,#3%!&
r?   