
    ,h=T              	         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	m
Z
mZ d dlmZmZmZ ddlmZmZ ddlmZmZmZmZmZmZmZ ddlmZmZ dd	lmZm Z m!Z!m"Z"m#Z# dd
l$m%Z%m&Z& ddl'm(Z( ddl)m*Z*m+Z+m,Z,m-Z-m.Z. ddlm/Z/m0Z0m1Z1m2Z2m3Z3m4Z4m5Z5 ddl6m7Z7 dgZ8 G d de-      Z9 G d de9      Z: e( e;       dddddd       y)    )annotationsN)	GeneratorSequence)AnyCallablecast   )HeadersMultipleValuesError)InvalidHandshakeInvalidHeaderInvalidHeaderValueInvalidMessage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                       e Zd ZdZddddeddd	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d fdZddZ	 	 	 	 ddZddZ	 	 	 	 dd	Z	dd
Z
	 	 	 	 ddZddZddZd fdZ xZS )r*   a-  
    Sans-I/O implementation of a WebSocket server connection.

    Args:
        origins: Acceptable values of the ``Origin`` header. 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.
            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         |   t        |||       || _        || _        || _        |(t        | d|j                  | | j                               y y )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	           S/var/www/html/Resume-Scraper/venv/lib/python3.12/site-packages/websockets/server.pyr6   zServerProtocol.__init__L   sk    " 		 	 	
 $.!&2#) $"**4@ *    c                   	 | j                  |      \  }}}t+               }	t,        j.                  j1                  d      |	d<   d	|	d
<   d
|	d<   ||	d<   |||	d<   |||	d<   t3        dd|	      S # t        $ ro}||_        || _        | j                  r| j
                  j	                  dd       | j                  t        j                  j                  d| d      cY d}~S d}~wt        $ r}||_        || _        | j                  r| j
                  j	                  dd       | j                  t        j                  j                  d| d      }d	|j                  d
<   |cY d}~S d}~wt        $ r}||_        || _        | j                  r| j
                  j	                  dd       t        t        |      }| }|j                   !|j                   }|d| z  }|j                   !| j                  t        j                  j"                  d| d      cY d}~S d}~wt$        $ r_}||_        || _        | j
                  j'                  dd       | j                  t        j                  j(                  d      cY d}~S d}~ww xY w)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_strrS   s
             r=   acceptzServerProtocol.accepto   s   ,9	
 $$W-	!n )++000=(	 )*7&'(2CG./&0?G,-2G<<}  	!$G!$Dzz!!"4t!D;;))9#cB   	!$G!$Dzz!!"5!E{{00=cU CE FH +6HY'O 	!$G!$Dzz!!"7$!G]C0I"G%%1%//	R	{++ %%1 ;;++9'#F   	 "%G!$DKK84H;;55= 	s]   A. .	J	7A$C!J	!J	-A5E("J	(J	4A6H+-HJ	J	*AJ>J	J	c                ^   |j                   }t        |j                  d      D cg c]  }t        |       c}g       }t	        d |D              s#t        d|rdj                  |            d      t        |j                  d      D cg c]  }t        |       c}g       }t        |      dk(  r|d   j                         dk(  s#t        d|rdj                  |            d      	 |d	   }	 t        j                  |j                         d      }t        |      dk7  rt%        d	|      t'        |      }		 |d   }
|
dk7  rt%        d|
      | j)                  |      | _        | j-                  |      \  }| _        | j1                  |      x}| _        |	||fS c c}w c c}w # t        $ r t        d	      dt        $ r t        d	d
      dw xY w# t         j"                  $ r}t%        d	|      |d}~ww xY w# t        $ r t        d      dt        $ r t        dd
      dw xY w)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.

        rF   c              3  B   K   | ]  }|j                         d k(    yw)upgradeN)lower).0values     r=   	<genexpr>z1ServerProtocol.process_request.<locals>.<genexpr>   s     F%5;;=I-Fs   , NrB   r	   r   rA   zSec-WebSocket-Keymultiple valuesT)validate   zSec-WebSocket-Version13)rS   sumget_allr   anyr   joinr   lenri   KeyErrorr   r   base64	b64decodeencodebinasciiErrorr   r)   process_originoriginprocess_extensionsr-   process_subprotocolsubprotocol)r<   r]   rS   rk   
connectionrh   keyraw_keyra   r^   versionr_   r`   s                r=   rJ   zServerProtocol.process_request   sR   0 //-029//,2OPe$PRT.

 F:FF zdii
3 GK  *-/6y/IJe]5!JB*
 G!gaj&6&6&8K&G 'DIIg,>TTtTT	R-.C
	H&&szz|dCG w<2$%8#>>"3	V56G
 d?$%<gFF))'2-1-D-DW-M*4?-1-E-Eg-NN$*0/BBW Q K  	? 34$>" 	R 35FGTQ	R ~~ 	H$%8#>CG	H  	C 78dB" 	V 79JKQUU	Vs;   F!F&.F+ 4%G ?H ++GG>,G99G>+H,c                @   	 |j                  d      }|t        t        |      }| j
                  S| j
                  D ]9  }||k(  s0t        |t        j                        s#|&|j                  |      8 |S  t        |      |S # t        $ r t        dd      dw xY w)aG  
        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%   rn   N)getr   r   r   r%   r,   
isinstancerePattern	fullmatchr   )r<   rS   r~   origin_or_regexs       r=   r}   zServerProtocol.process_origin  s    "	G[[*F &&)F<<##'<< ,"f,

;*'11&9E , $F++ # 	G*;<$F	Gs   B Bc                   d}g }g }|j                  d      }|r| j                  rt        |D cg c]  }t        |       c}g       }|D ]a  \  }}	| j                  D ]M  }
|
j                  |k7  r	 |
j                  |	|      \  }}|j                  ||f       |j                  |        a c |rt        |      }||fS c c}w # t        $ r Y sw xY w)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.

        NrG   )	rs   r7   rr   r   nameprocess_request_paramsr   appendr   )r<   rS   response_header_valueextension_headersaccepted_extensionsheader_valuesheader_valueparsed_header_valuesr   request_paramsext_factoryresponse_params	extensions                r=   r   z!ServerProtocol.process_extensions6  s   N -135/1(BCT66:=CPQ<.QSU;  )= $n#'#<#< K"''4/ !5@5W5W*,?62 &,,dO-DE'..y9 %2 $34E$F!$&999? R , ! !s   C 1C	CCc                    t        |j                  d      D cg c]  }t        |       c}g       }| j                  |      S c c}w )a  
        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.

        rH   )rr   rs   r   r/   )r<   rS   r   r.   s       r=   r   z"ServerProtocol.process_subprotocol  sR     /2 %,OO4L$M  ",/ /
 &&|44s   Ac                    | j                   sy|st        d      t        |      }| j                   D ]
  }||v s|c S  t        ddj                  | j                         z         )aq  
        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 rm   )r8   r   setru   )r<   r.   proposed_subprotocolsr   s       r=   r/   z!ServerProtocol.select_subprotocol  s|    R ** "#899 !$L 166 	#K33""	#
 3ii3345
 	
r>   c           
        t        j                  |      }|j                         }t        dt        j
                  j                  d      fddt        t        |            fdg      }t        |j                  |j                  ||      S )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.

        rE   TrC   )rF   closezContent-Length)zContent-Typeztext/plain; charset=utf-8)rO   rP   rz   r
   rZ   r[   r\   strrv   r   rk   phrase)r<   statustextbodyrS   s        r=   rN   zServerProtocol.reject  sw    * ({{}//t/<='!3s4y>2=	
 fmmWdCCr>   c                6   | j                   r|j                  |j                  }}| j                  j                  d||       |j                  j                         D ]"  \  }}| j                  j                  d||       $ |j                  r/| j                  j                  dt        |j                               | j                  j                  |j                                |j                  dk(  r;| j                  t        u sJ t        | _        | j                  j                  d       y| j                  j                  d|j                  |j                         | j                          | j!                         | _        t%        | j"                         y)z
        Send a handshake response to the client.

        Args:
            response: WebSocket handshake response event to send.

        z> HTTP/1.1 %d %sz> %s: %sz> [body] (%d bytes)rI   zconnection openzconnection rejected (%d %s)N)rM   status_codereason_phraser2   rS   	raw_itemsr   rv   writesr   	serializer0   r   r   infosend_eofdiscardparsernext)r<   rb   coder   r   rk   s         r=   send_responsezServerProtocol.send_response  s3    ::#//1G1G&DKK0$?&..88: :
U!!*c59:}}!!"7X]]9KL8--/03&::++DJKK./ KK-$$&& MMO,,.DKr>   c              #    K   | j                   t        u r	 t        j                  | j                  j
                        E d {   }| j                  re| j                  j                  dj                          |j"                  j%                         D ]"  \  }}| j                  j                  d||       $ | j&                  j)                         t*        |          E d {    y 7 # t        $ rj}t        d      | _        || j                  _	        | j                          | j                         | _        t        | j                         d  Y d }~d }~ww xY w7 }w)Nz$did not receive a valid HTTP requestz< GET %s HTTP/1.1z< %s: %s)r0   r   r   parsereader	read_linerW   r   rL   rU   r   r   r   r   rM   r2   pathrS   r   eventsr   r5   )r<   r]   ra   r   rk   r;   s        r=   r   zServerProtocol.parse  s    ::#%,]]KK))&  zz!!"5w||D")//";";"= >JCKK%%j#u=> KKw'7=?"")  %3:&" 03"","llnT[[!" 	#sN   E%,C- C+C- BE%%E#&E%+C- -	E 6AEE%E  E%)r,   z0Sequence[Origin | re.Pattern[str] | 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])rS   r
   r   zOrigin | None)rS   r
   r   z"tuple[str | None, list[Extension]])rS   r
   r   Subprotocol | None)r.   zSequence[Subprotocol]r   r   )r   r&   r   r   r   r   )rb   r   r   r   )r   zGenerator[None])__name__
__module____qualname____doc__r   r6   re   rJ   r}   r   r   r/   rN   r   r   __classcell__r;   s   @r=   r*   r*   0   s    < EI>B59 !$$(! B! <	!
 3!! ! ! "!  
!!FZ=xFCFC 
,FCP!FO:O: 
,O:b50:
+:
 
:
xDB D# #r>   c                        e Zd Zd fdZ xZS )ServerConnectionc                X    t        j                  dt               t        |   |i | y )Nz.ServerConnection was renamed to ServerProtocol)warningswarnDeprecationWarningr5   r6   )r<   argskwargsr;   s      r=   r6   zServerConnection.__init__9  s)    <	
 	$)&)r>   )r   r   r   r   r   r   )r   r   r   r6   r   r   s   @r=   r   r   8  s    * *r>   r   z.legacy.server)WebSocketServerWebSocketServerProtocol	broadcastserve
unix_serve)deprecated_aliases)<
__future__r   rx   r{   email.utilsrZ   rO   r   r   collections.abcr   r   typingr   r   r   datastructuresr
   r   
exceptionsr   r   r   r   r   r   r   r-   r   r   rS   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   globals r>   r=   <module>r      s    "     	  / & & 8   :  &   ? ?    
E#X E#P*~ * I ,#3%!&
r>   