o
    _c0H                     @  s&  d dl mZ d dlZd dlZd dlZd dlZd dlmZm	Z	m
Z
mZ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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+m,Z,m-Z-m.Z.m/Z/m0Z0 ddl1m2Z2 ddl3T dgZ4G dd deZ5dS )    )annotationsN)	GeneratorListOptionalSequenceTuplecast   )
CONNECTINGOPENSERVER
ConnectionState)HeadersMultipleValuesError)InvalidHandshakeInvalidHeaderInvalidHeaderValueInvalidOriginInvalidStatusInvalidUpgradeNegotiationError)	ExtensionServerExtensionFactory)build_extensionparse_connectionparse_extensionparse_subprotocolparse_upgrade)RequestResponse)ConnectionOptionExtensionHeader
LoggerLikeOriginSubprotocolUpgradeProtocol)
accept_key)*ServerConnectionc                      s   e Zd ZdZdddeddfd8 fddZd9ddZd:ddZd;ddZd<d!d"Z	d=d$d%Z
d>d)d*Zd?d/d0Zd@d3d4ZdA fd6d7Z  ZS )Br)   ap  
    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.
        state: initial state of the WebSocket connection.
        max_size: maximum size of incoming messages in bytes;
            :obj:`None` to disable the limit.
        logger: logger for this connection;
            defaults to ``logging.getLogger("websockets.client")``;
            see the :doc:`logging guide <../topics/logging>` for details.

    Ni   origins$Optional[Sequence[Optional[Origin]]]
extensions*Optional[Sequence[ServerExtensionFactory]]subprotocolsOptional[Sequence[Subprotocol]]stater   max_sizeOptional[int]loggerOptional[LoggerLike]c                   s*   t  jt|||d || _|| _|| _d S )N)Zsider0   r1   r3   )super__init__r   r*   available_extensionsavailable_subprotocols)selfr*   r,   r.   r0   r1   r3   	__class__ </usr/local/lib/python3.10/dist-packages/websockets/server.pyr6   E   s   	
zServerConnection.__init__requestr   returnr    c              
   C  s  z
|  |\}}}W n ty9 } z#||_|| _| jr#| jjddd | tjj	d| dW  Y d}~S d}~w t
yn } z*||_|| _| jrQ| jjddd | tjjd| d}d	|jd
< |W  Y d}~S d}~w ty } z#||_|| _| jr| jjddd | tjjd| dW  Y d}~S d}~w ty } z||_|| _| jjddd | tjjdW  Y d}~S d}~ww t }tjjdd|d< d	|d
< d
|d< ||d< |dur||d< |dur||d< | jd tdd|S )a  
        Create a handshake response to accept the connection.

        If the connection cannot be established, the handshake response
        actually rejects the handshake.

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

        You can modify it before sending it, for example to add HTTP headers.

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

        Returns:
            Response: WebSocket handshake response event 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opening handshake failedzLFailed to open a WebSocket connection.
See server log for more information.
usegmtDater   zSec-WebSocket-AcceptSec-WebSocket-ExtensionsSec-WebSocket-Protocolzconnection opene   zSwitching Protocols)process_requestr   
_exceptionhandshake_excdebugr3   rejecthttp
HTTPStatus	FORBIDDENr   UPGRADE_REQUIREDheadersr   BAD_REQUEST	ExceptionerrorINTERNAL_SERVER_ERRORr   emailutils
formatdateinfor    )r9   r>   accept_headerextensions_headerprotocol_headerexcresponserR   r<   r<   r=   acceptX   sv   


	
zServerConnection.accept(Tuple[str, Optional[str], Optional[str]]c              
   C  s  |j }tdd |dD g }tdd |D s&td|r#d|dtdd |d	D g }t|d
krA|d  dksNtd	|rKd|dz|d }W n" tye } zt	d|d}~w t
yv } zt	dd|d}~ww ztj| dd}W n tjy } ztd||d}~ww t|dkrtd|z|d }W n" ty } zt	d|d}~w t
y } zt	dd|d}~ww |dkrtd|t|}	| || _| |\}
| _| | }| _|	|
|fS )a7  
        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:
            Tuple[str, Optional[str], Optional[str]]:
            ``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.

        c                 S     g | ]}t |qS r<   )r   .0valuer<   r<   r=   
<listcomp>       z4ServerConnection.process_request.<locals>.<listcomp>r   c                 s  s    | ]	}|  d kV  qdS )upgradeN)lowerrc   r<   r<   r=   	<genexpr>   s    z3ServerConnection.process_request.<locals>.<genexpr>z, Nc                 S  rb   r<   )r   rc   r<   r<   r=   rf      rg   rB   r	   r   rA   zSec-WebSocket-Keyz,more than one Sec-WebSocket-Key header foundT)validate   zSec-WebSocket-Versionz0more than one Sec-WebSocket-Version header foundZ13)rR   sumget_allanyr   joinlenri   KeyErrorr   r   base64	b64decodeencodebinasciiErrorr   r'   process_originoriginprocess_extensionsr,   process_subprotocolsubprotocol)r9   r>   rR   
connectionrh   keyr^   Zraw_keyversionr[   r\   r]   r<   r<   r=   rI      sx   



z ServerConnection.process_requestrR   r   Optional[Origin]c              
   C  s^   zt tt |d}W n ty } ztdd|d}~ww | jdur-|| jvr-t||S )a  
        Handle the Origin HTTP request header.

        Args:
            headers: WebSocket handshake request headers.

        Returns:
           Optional[Origin]: origin, if it is acceptable.

        Raises:
            InvalidOrigin: if the origin isn't acceptable.

        r$   z!more than one Origin header foundN)r   r   r$   getr   r   r*   r   )r9   rR   ry   r^   r<   r<   r=   rx     s   

zServerConnection.process_origin%Tuple[Optional[str], List[Extension]]c              
   C  s   d}g }g }| d}|rM| jrMtdd |D g }|D ]0\}}| jD ](}	|	j|kr+q#z
|	||\}
}W n	 ty>   Y q#w |||
f ||  q|rSt|}||fS )a  
        Handle the Sec-WebSocket-Extensions HTTP request header.

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

        :rfc:`6455` leaves the rules up to 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:
            Tuple[Optional[str], List[Extension]]: ``Sec-WebSocket-Extensions``
            HTTP response header and list of accepted extensions.

        Raises:
            InvalidHandshake: to abort the handshake with an HTTP 400 error.

        NrF   c                 S  rb   r<   )r   rd   header_valuer<   r<   r=   rf   Q  rg   z7ServerConnection.process_extensions.<locals>.<listcomp>)rn   r7   rm   nameZprocess_request_paramsr   appendr   )r9   rR   Zresponse_header_valueZextension_headersZaccepted_extensionsheader_valuesparsed_header_valuesr   Zrequest_paramsZext_factoryZresponse_params	extensionr<   r<   r=   rz      s4   '




z#ServerConnection.process_extensionsOptional[Subprotocol]c                 C  s>   d}| d}|r| jrtdd |D g }| || j}|S )a  
        Handle the Sec-WebSocket-Protocol HTTP request header.

        Args:
            headers: WebSocket handshake request headers.

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

        Raises:
            InvalidHandshake: to abort the handshake with an HTTP 400 error.

        NrG   c                 S  rb   r<   )r   r   r<   r<   r=   rf     rg   z8ServerConnection.process_subprotocol.<locals>.<listcomp>)rn   r8   rm   select_subprotocol)r9   rR   r|   r   r   r<   r<   r=   r{   t  s   

z$ServerConnection.process_subprotocolclient_subprotocolsSequence[Subprotocol]server_subprotocolsc                   s6   t  t @ }|sdS  fdd}t||dd S )au  
        Pick a subprotocol among those offered by the client.

        If several subprotocols are supported by the client and the server,
        the default implementation selects the preferred subprotocols by
        giving equal value to the priorities of the client and the server.

        If no common subprotocol is supported by the client and the server, it
        proceeds without a subprotocol.

        This is unlikely to be the most useful implementation in practice, as
        many servers providing a subprotocol will require that the client uses
        that subprotocol.

        Args:
            client_subprotocols: list of subprotocols offered by the client.
            server_subprotocols: list of subprotocols available on the server.

        Returns:
            Optional[Subprotocol]: Subprotocol, if a common subprotocol was
            found.

        Nc                   s     |  |  S )N)index)pr   r   r<   r=   <lambda>  s   z5ServerConnection.select_subprotocol.<locals>.<lambda>)r~   r   )setsorted)r9   r   r   r.   priorityr<   r   r=   r     s
   z#ServerConnection.select_subprotocolstatushttp.HTTPStatustextstrc                 C  sp   |  }tdtjjddfddtt|fdg}t|j|j	||}| j
du r,t|| _
| jd|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 can modify it before sending it, for example to alter HTTP headers.

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

        Returns:
            Response: WebSocket handshake response event to send to the client.

        rE   TrC   )r   closezContent-Length)zContent-Typeztext/plain; charset=utf-8Nzconnection failed (%d %s))ru   r   rW   rX   rY   r   rq   r    re   phraserK   r   r3   rZ   )r9   r   r   bodyrR   r_   r<   r<   r=   rM     s   

zServerConnection.rejectr_   Nonec                 C  s   | j r3|j|j}}| j d|| |j D ]\}}| j d|| q|jdur3| j dt|j | j	|
  |jdkrL| jtu sGJ t| _dS |   |  | _t| j dS )z
        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)rH   )rL   status_codeZreason_phraser3   rR   	raw_itemsr   rq   Zwritesr   	serializer0   r
   r   Zsend_eofdiscardparsernext)r9   r_   coder   r~   re   r<   r<   r=   send_response  s   



zServerConnection.send_responseGenerator[None, None, None]c                 #  sz    | j tu r3t| jjE d H }| jr-| jd|j |j	
 D ]\}}| jd|| q | j| t  E d H  d S )Nz< GET %s HTTP/1.1z< %s: %s)r0   r
   r   parsereaderZ	read_linerL   r3   pathrR   r   eventsr   r5   )r9   r>   r~   re   r:   r<   r=   r     s   
zServerConnection.parse)r*   r+   r,   r-   r.   r/   r0   r   r1   r2   r3   r4   )r>   r   r?   r    )r>   r   r?   ra   )rR   r   r?   r   )rR   r   r?   r   )rR   r   r?   r   )r   r   r   r   r?   r   )r   r   r   r   r?   r    )r_   r    r?   r   )r?   r   )__name__
__module____qualname____doc__r
   r6   r`   rI   rx   rz   r{   r   rM   r   r   __classcell__r<   r<   r:   r=   r)   /   s$    

W
X

T

$
))6
__future__r   rs   rv   email.utilsrW   rN   typingr   r   r   r   r   r   r}   r
   r   r   r   r   Zdatastructuresr   r   
exceptionsr   r   r   r   r   r   r   r,   r   r   rR   r   r   r   r   r   Zhttp11r   r    r!   r"   r#   r$   r%   r&   rX   r'   Zlegacy.server__all__r)   r<   r<   r<   r=   <module>   s"     $	 