U
    <{fR                     @  sZ  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m	Z	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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- ddlm.Z.m/Z/m0Z0m1Z1m2Z2m3Z3m4Z4 ddl5m6Z6 ddl7T ddl7m8Z9 dge9 Z8G dd de,Z:G dd de:Z;dS )    )annotationsN)AnyCallable	GeneratorListOptionalSequenceTuplecast   )HeadersMultipleValuesError)InvalidHandshakeInvalidHeaderInvalidHeaderValueInvalidOriginInvalidStatusInvalidUpgradeNegotiationError)	ExtensionServerExtensionFactory)build_extensionparse_connectionparse_extensionparse_subprotocolparse_upgrade)RequestResponse)
CONNECTINGOPENSERVERProtocolState)ConnectionOptionExtensionHeader
LoggerLikeOrigin
StatusLikeSubprotocolUpgradeProtocol)
accept_key)*)__all__ServerProtocolc                	      s   e Zd ZdZddddedddddddd	d
dd fddZdddddZdddddZdddddZdddddZ	ddddd Z
d!dd"d#d$Zd%d&dd'd(d)Zdd*d+d,d-Zd.d/ fd0d1Z  ZS )2r-   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.client")``;
            see the :doc:`logging guide <../../topics/logging>` for details.

    Ni   )origins
extensionssubprotocolsselect_subprotocolstatemax_sizeloggerz$Optional[Sequence[Optional[Origin]]]z*Optional[Sequence[ServerExtensionFactory]]zOptional[Sequence[Subprotocol]]zROptional[Callable[[ServerProtocol, Sequence[Subprotocol]], Optional[Subprotocol]]]r"   zOptional[int]zOptional[LoggerLike]c                  sH   t  jt|||d || _|| _|| _|d k	rDt| d|| | j d S )N)Zsider2   r3   r4   r1   )	super__init__r    r.   available_extensionsavailable_subprotocolssetattr__get__	__class__)selfr.   r/   r0   r1   r2   r3   r4   r;    P/var/www/html/Darija-Ai-API/env/lib/python3.8/site-packages/websockets/server.pyr6   M   s    zServerProtocol.__init__r   r   )requestreturnc              
   C  s  z|  |\}}}W n tk
rx } zB||_|| _| jrJ| jjddd | tjj	d| d W Y S d}~X Y n" t
k
r } zP||_|| _| jr| jjddd | tjjd| d}d	|jd
< | W Y S d}~X Y n tk
rF } zD||_|| _| jr| jjddd | tjjd| d W Y S d}~X Y nT tk
r } z4||_|| _| jjddd | tjjd W Y S d}~X Y nX t }tjjdd|d< d	|d
< d
|d< ||d< |dk	r||d< |dk	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 may modify it before sending it, for example to add HTTP headers.

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

        Returns:
            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Date
ConnectionzSec-WebSocket-AcceptSec-WebSocket-ExtensionsSec-WebSocket-Protocolzconnection opene   zSwitching Protocols)process_requestr   
_exceptionhandshake_excdebugr4   rejecthttp
HTTPStatus	FORBIDDENr   UPGRADE_REQUIREDheadersr   BAD_REQUEST	ExceptionerrorINTERNAL_SERVER_ERRORr   emailutils
formatdateinfor   )r<   r@   accept_headerextensions_headerprotocol_headerexcresponserU   r>   r>   r?   accepto   sn    

	



zServerProtocol.acceptz(Tuple[str, Optional[str], Optional[str]]c              
   C  s  |j }tdd |dD g }tdd |D sJtd|rDd|ndtdd |d	D g }t|d
kr|d  dkstd	|rd|ndz|d }W nX tk
r } zt	d|W 5 d}~X Y n. t
k
r } zt	dd|W 5 d}~X Y nX ztj| dd}W n2 tjk
rF } ztd||W 5 d}~X Y nX t|dkr`td|z|d }W n\ tk
r } zt	d|W 5 d}~X Y n0 t
k
r } zt	dd|W 5 d}~X Y nX |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  s   g | ]}t |qS r>   )r   .0valuer>   r>   r?   
<listcomp>   s     z2ServerProtocol.process_request.<locals>.<listcomp>rH   c                 s  s   | ]}|  d kV  qdS )upgradeN)lowerrd   r>   r>   r?   	<genexpr>   s     z1ServerProtocol.process_request.<locals>.<genexpr>, Nc                 S  s   g | ]}t |qS r>   )r   rd   r>   r>   r?   rg      s     rD   r   r   rC   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)rU   sumget_allanyr   joinlenri   KeyErrorr   r   base64	b64decodeencodebinasciiErrorr   r*   process_originoriginprocess_extensionsr/   process_subprotocolsubprotocol)r<   r@   rU   
connectionrh   keyra   Zraw_keyversionr^   r_   r`   r>   r>   r?   rL      sl        


zServerProtocol.process_requestr   zOptional[Origin])rU   rA   c              
   C  sh   zt tt |d}W n. tk
rF } ztdd|W 5 d}~X Y nX | jdk	rd|| jkrdt||S )aY  
        Handle the Origin HTTP request header.

        Args:
            headers: WebSocket handshake request headers.

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

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

        r&   z!more than one Origin header foundN)r
   r   r&   getr   r   r.   r   )r<   rU   rz   ra   r>   r>   r?   ry   !  s    

zServerProtocol.process_originz%Tuple[Optional[str], List[Extension]]c              
   C  s   d}g }g }| d}|r| jrtdd |D g }|D ]j\}}| jD ]Z}	|	j|krVqFz|	||\}
}W n tk
r   Y qFY nX |||
f ||  q8qFq8|rt|}||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.

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

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

        NrI   c                 S  s   g | ]}t |qS r>   )r   re   header_valuer>   r>   r?   rg   k  s     z5ServerProtocol.process_extensions.<locals>.<listcomp>)ro   r7   rn   nameZprocess_request_paramsr   appendr   )r<   rU   Zresponse_header_valueZextension_headersZaccepted_extensionsheader_valuesZparsed_header_valuesr   Zrequest_paramsZext_factoryZresponse_params	extensionr>   r>   r?   r{   ;  s4    '

 

 

z!ServerProtocol.process_extensionszOptional[Subprotocol]c                 C  s$   t dd |dD g }| |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: if the Sec-WebSocket-Subprotocol header is invalid.

        c                 S  s   g | ]}t |qS r>   )r   r   r>   r>   r?   rg     s   z6ServerProtocol.process_subprotocol.<locals>.<listcomp>rJ   )rn   ro   r1   )r<   rU   r0   r>   r>   r?   r|     s    z"ServerProtocol.process_subprotocolzSequence[Subprotocol])r0   rA   c                 C  sR   | j s
dS |stdt|}| j D ]}||kr$|  S q$tdd| j  dS )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:
            Optional[Subprotocol]: 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 rk   )r8   r   setrq   )r<   r0   Zproposed_subprotocolsr}   r>   r>   r?   r1     s    *


z!ServerProtocol.select_subprotocolr'   str)statustextrA   c                 C  sz   t |}| }tdtjjddfddtt|fdg}t	|j
|j||}| jdkrbt|| _| 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.

        rG   TrE   )rH   closezContent-Length)zContent-Typeztext/plain; charset=utf-8Nzconnection rejected (%d %s))rQ   rR   rv   r   rZ   r[   r\   r   rr   r   rf   phraserN   r   r4   r]   )r<   r   r   bodyrU   rb   r>   r>   r?   rP     s    


zServerProtocol.rejectNone)rb   rA   c                 C  s   | j rf|j|j }}| j d|| |j D ]\}}| j d|| q.|jdk	rf| j dt|j | j	|
  |jdkr| jtkstt| _n|   |  | _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)rK   )rO   status_codeZreason_phraser4   rU   	raw_itemsr   rr   Zwritesr   	serializer2   r   AssertionErrorr   send_eofdiscardparsernext)r<   rb   coder   r   rf   r>   r>   r?   send_response  s    


zServerProtocol.send_responsezGenerator[(None, None, None)])rA   c              
   #  s   | j tkrzt| jjE d H }W nJ tk
rl } z,|| _|   | 	 | _
t| j
 d V  W 5 d }~X Y nX | 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)r2   r   r   parsereaderZ	read_linerW   rN   r   r   r   r   rO   r4   pathrU   r   eventsr   r5   )r<   r@   ra   r   rf   r=   r>   r?   r   '  s"    


zServerProtocol.parse)__name__
__module____qualname____doc__r   r6   rc   rL   ry   r{   r|   r1   rP   r   r   __classcell__r>   r>   r=   r?   r-   3   s$   ""YYQ=+c                      s&   e Zd Zdddd fddZ  ZS )ServerConnectionr   r   )argskwargsrA   c                   s   t dt t j|| d S )Nz.ServerConnection was renamed to ServerProtocol)warningswarnDeprecationWarningr5   r6   )r<   r   r   r=   r>   r?   r6   ?  s
    zServerConnection.__init__)r   r   r   r6   r   r>   r>   r=   r?   r   >  s   r   )<
__future__r   rt   rw   email.utilsrZ   rQ   r   typingr   r   r   r   r   r   r	   r
   Zdatastructuresr   r   
exceptionsr   r   r   r   r   r   r   r/   r   r   rU   r   r   r   r   r   Zhttp11r   r   protocolr   r   r    r!   r"   r#   r$   r%   r&   r'   r(   r)   r[   r*   Zlegacy.serverr,   Zlegacy__all__r-   r   r>   r>   r>   r?   <module>   s.   ($	$	
    