
    tnioj                       d dl mZ d dlZd dlZd dlZd dlmZ ddlmZm	Z	m
Z
mZmZmZ ddlmZ ddlmZmZ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 dd
l m!Z!m"Z"m#Z#m$Z$ g dZ%eez  ez  Z&	  G d dej'                  Z(e(j)        Z)e(j*        Z* G d dej'                  Z+e+j,        Z,e+j-        Z-e+j.        Z.e+j/        Z/dZ0	  G d d          Z1dS )    )annotationsN)	Generator   )ConnectionClosedConnectionClosedErrorConnectionClosedOKInvalidStatePayloadTooBigProtocolError)	Extension)
OK_CLOSE_CODES	OP_BINARYOP_CLOSEOP_CONTOP_PINGOP_PONGOP_TEXTClose	CloseCodeFrame)RequestResponse)StreamReader)	BytesLike
LoggerLikeOriginSubprotocol)ProtocolSideStateSEND_EOFc                  .    e Zd ZdZ ed          \  ZZdS )r   z6A WebSocket connection is either a server or a client.   N)__name__
__module____qualname____doc__rangeSERVERCLIENT     P/var/www/html/gpu-tools/venv/lib/python3.11/site-packages/websockets/protocol.pyr   r   -   s%        @@U1XXNFFFFr,   r   c                  2    e Zd ZdZ ed          \  ZZZZdS )r    z6A WebSocket connection is in one of these four states.   N)	r$   r%   r&   r'   r(   
CONNECTINGOPENCLOSINGCLOSEDr+   r,   r-   r    r    7   s*        @@(-a%Jgvvvr,   r    r,   c                  6   e Zd ZdZedddd:dZed;d            Zej        d<d            Zed=d            Z	ed>d            Z
ed?d            Zd@dZdAdZdBdZdCdBd!ZdCdBd"ZdDdEd(ZdFd)ZdFd*ZdGdHd,ZdId.ZdJd0ZdKd1ZdLd3ZdLd4ZdMd7ZdMd8ZdAd9ZdS )Nr   a  
    Sans-I/O implementation of a WebSocket connection.

    Args:
        side: :attr:`~Side.CLIENT` or :attr:`~Side.SERVER`.
        state: Initial state of the WebSocket connection.
        max_size: Maximum size of incoming messages in bytes.
            :obj:`None` disables the limit. You may pass a ``(max_message_size,
            max_fragment_size)`` tuple to set different limits for messages and
            fragments when you expect long messages sent in short fragments.
        logger: Logger for this connection; depending on ``side``,
            defaults to ``logging.getLogger("websockets.client")``
            or ``logging.getLogger("websockets.server")``;
            see the :doc:`logging guide <../../topics/logging>` for details.

    i   N)statemax_sizeloggersider   r5   r    r6   *tuple[int | None, int | None] | int | Noner7   LoggerLike | NonereturnNonec                  t          j                    | _        	 |.t          j        d|j                                                   }|| _        	 |                    t          j	                  | _
        || _        || _        t          |t                    s||d c| _        | _        n|\  | _        | _        d | _        d| _        d | _        g | _        d | _        d | _        d | _        d | _        d | _        	 d| _        t7                      | _        g | _        g | _        |                                 | _         tC          | j                    d | _"        d S )Nzwebsockets.F)#uuiduuid4idlogging	getLoggernamelowerr7   isEnabledForDEBUGdebugr8   r5   
isinstanceintmax_message_sizemax_fragment_sizecurrent_sizeexpect_continuation_frameorigin
extensionssubprotocol
close_rcvd
close_sentclose_rcvd_then_senthandshake_exceof_sentr   readereventswritesparseparsernext
parser_exc)selfr8   r5   r6   r7   s        r-   __init__zProtocol.__init__Y   sU    "Z\\B >&'HTY__5F5F'H'HIIF"() ((77
 	 
 h$$ 	E(8<Dd9D!4#9#9<D9D!4#9 )- */& &*+-/3 )-(,15! 04	  #nn#%#%jjllT[,0r,   c                    | j         S )a  
        State of the WebSocket connection.

        Defined in 4.1_, 4.2_, 7.1.3_, and 7.1.4_ of :rfc:`6455`.

        .. _4.1: https://datatracker.ietf.org/doc/html/rfc6455#section-4.1
        .. _4.2: https://datatracker.ietf.org/doc/html/rfc6455#section-4.2
        .. _7.1.3: https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.3
        .. _7.1.4: https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.4

        )_stater]   s    r-   r5   zProtocol.state   s     {r,   c                b    | j         r | j                             d|j                   || _        d S )Nz= connection is %s)rG   r7   rC   r`   )r]   r5   s     r-   r5   zProtocol.state   s3    : 	@K2EJ???r,   
int | Nonec                `    | j         t          urdS | j        t          j        S | j        j        S )z
        WebSocket close code received from the remote endpoint.

        Defined in 7.1.5_ of :rfc:`6455`.

        .. _7.1.5: https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.5

        :obj:`None` if the connection isn't closed yet.

        N)r5   r3   rQ   r   ABNORMAL_CLOSUREcodera   s    r-   
close_codezProtocol.close_code   s2     :V##4_$--?''r,   
str | Nonec                L    | j         t          urdS | j        dS | j        j        S )a  
        WebSocket close reason  received from the remote endpoint.

        Defined in 7.1.6_ of :rfc:`6455`.

        .. _7.1.6: https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.6

        :obj:`None` if the connection isn't closed yet.

        N )r5   r3   rQ   reasonra   s    r-   close_reasonzProtocol.close_reason   s.     :V##4_$2?))r,   r   c                   | j         t          u s
J d            | j        5| j        .| j        j        t
          v r| j        j        t
          v rt          }nt          } || j        | j        | j                  }| j	        |_
        |S )a  
        Exception to raise when trying to interact with a closed connection.

        Don't raise this exception while the connection :attr:`state`
        is :attr:`~websockets.protocol.State.CLOSING`; wait until
        it's :attr:`~websockets.protocol.State.CLOSED`.

        Indeed, the exception includes the close code and reason, which are
        known only once the connection is closed.

        Raises:
            AssertionError: If the connection isn't closed yet.

        zconnection isn't closed yet)r5   r3   rQ   rR   rf   r   r   r   rS   r\   	__cause__)r]   exc_typeexcs      r-   	close_exczProtocol.close_exc   s      zV###%B### O'+$66$66)HH,H (OO%!
 !
 
r,   databytes | bytearrayc                b    | j                             |           t          | j                   dS )aH  
        Receive data from the network.

        After calling this method:

        - You must call :meth:`data_to_send` and send this data to the network.
        - You should call :meth:`events_received` and process resulting events.

        Raises:
            EOFError: If :meth:`receive_eof` was called earlier.

        N)rV   	feed_datar[   rZ   r]   rr   s     r-   receive_datazProtocol.receive_data  s0     	d###T[r,   c                |    | j         j        rdS | j                                          t          | j                   dS )a  
        Receive the end of the data stream from the network.

        After calling this method:

        - You must call :meth:`data_to_send` and send this data to the network;
          it will return ``[b""]``, signaling the end of the stream, or ``[]``.
        - You aren't expected to call :meth:`events_received`; it won't return
          any new events.

        :meth:`receive_eof` is idempotent.

        N)rV   eoffeed_eofr[   rZ   ra   s    r-   receive_eofzProtocol.receive_eof  s?     ;? 	FT[r,   r   finboolc                   | j         st          d          | j        t          ur.t	          d| j        j                                                   | | _         |                     t          t          ||                     dS )a  
        Send a `Continuation frame`_.

        .. _Continuation frame:
            https://datatracker.ietf.org/doc/html/rfc6455#section-5.6

        Parameters:
            data: payload containing the same kind of data
                as the initial frame.
            fin: FIN bit; set it to :obj:`True` if this is the last frame
                of a fragmented message and to :obj:`False` otherwise.

        Raises:
            ProtocolError: If a fragmented message isn't in progress.

        unexpected continuation frameconnection is N)rM   r   r`   r1   r	   r5   rC   rD   
send_framer   r   r]   rr   r|   s      r-   send_continuationzProtocol.send_continuation&  s    " - 	A ?@@@;d""I
0E0E0G0GIIJJJ-0&gtS1122222r,   Tc                   | j         rt          d          | j        t          ur.t	          d| j        j                                                   | | _         |                     t          t          ||                     dS )a  
        Send a `Text frame`_.

        .. _Text frame:
            https://datatracker.ietf.org/doc/html/rfc6455#section-5.6

        Parameters:
            data: payload containing text encoded with UTF-8.
            fin: FIN bit; set it to :obj:`False` if this is the first frame of
                a fragmented message.

        Raises:
            ProtocolError: If a fragmented message is in progress.

        expected a continuation framer   N)rM   r   r`   r1   r	   r5   rC   rD   r   r   r   r   s      r-   	send_textzProtocol.send_text>  s      ) 	A ?@@@;d""I
0E0E0G0GIIJJJ-0&gtS1122222r,   c                   | j         rt          d          | j        t          ur.t	          d| j        j                                                   | | _         |                     t          t          ||                     dS )a  
        Send a `Binary frame`_.

        .. _Binary frame:
            https://datatracker.ietf.org/doc/html/rfc6455#section-5.6

        Parameters:
            data: payload containing arbitrary binary data.
            fin: FIN bit; set it to :obj:`False` if this is the first frame of
                a fragmented message.

        Raises:
            ProtocolError: If a fragmented message is in progress.

        r   r   N)rM   r   r`   r1   r	   r5   rC   rD   r   r   r   r   s      r-   send_binaryzProtocol.send_binaryU  s      ) 	A ?@@@;d""I
0E0E0G0GIIJJJ-0&is3344444r,   rj   rf   CloseCode | int | Nonerk   strc                   | j         t          ur.t          d| j        j                                                   |2|dk    rt          d          t          t          j	        d          }d}n$t          ||          }|
                                }|                     t          t          |                     | j        J || _        t           | _        dS )a_  
        Send a `Close frame`_.

        .. _Close frame:
            https://datatracker.ietf.org/doc/html/rfc6455#section-5.5.1

        Parameters:
            code: close code.
            reason: close reason.

        Raises:
            ProtocolError: If the code isn't valid or if a reason is provided
                without a code.

        r   Nrj   z#cannot send a reason without a coder,   )r`   r1   r	   r5   rC   rD   r   r   r   NO_STATUS_RCVD	serializer   r   r   rQ   rR   r2   r]   rf   rk   closerr   s        r-   
send_closezProtocol.send_closel  s    $ ;d""I
0E0E0G0GIIJJJ<||#$IJJJ)2B77EDD$''E??$$Dh--... &&&


r,   c                    | j         t          ur<| j         t          ur.t          d| j        j                                                   |                     t          t          |                     dS )z
        Send a `Ping frame`_.

        .. _Ping frame:
            https://datatracker.ietf.org/doc/html/rfc6455#section-5.5.2

        Parameters:
            data: payload containing arbitrary binary data.

        r   N)
r`   r1   r2   r	   r5   rC   rD   r   r   r   rv   s     r-   	send_pingzProtocol.send_ping  f     ;d""t{''A'AI
0E0E0G0GIIJJJgt,,-----r,   c                    | j         t          ur<| j         t          ur.t          d| j        j                                                   |                     t          t          |                     dS )z
        Send a `Pong frame`_.

        .. _Pong frame:
            https://datatracker.ietf.org/doc/html/rfc6455#section-5.5.3

        Parameters:
            data: payload containing arbitrary binary data.

        r   N)
r`   r1   r2   r	   r5   rC   rD   r   r   r   rv   s     r-   	send_pongzProtocol.send_pong  r   r,   CloseCode | intc                   | j         t          u r}|t          j        k    rmt	          ||          }|                                }|                     t          t          |                     || _	        | j
        d| _        t          | _         | j        t          u r| j        s|                                  |                                 | _        t'          | j                   dS )a?  
        `Fail the WebSocket connection`_.

        .. _Fail the WebSocket connection:
            https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.7

        Parameters:
            code: close code
            reason: close reason

        Raises:
            ProtocolError: If the code isn't valid.
        NT)r5   r1   r   re   r   r   r   r   r   rR   rQ   rS   r2   r8   r)   rU   send_eofdiscardrZ   r[   r   s        r-   failzProtocol.fail  s    & :y111dF++((h 5 5666"'
 ?.04D-$
 9t}MMOOO llnnT[r,   list[Event]c                $    | j         g c}| _         |S )a*  
        Fetch events generated from data received from the network.

        Call this method immediately after any of the ``receive_*()`` methods.

        Process resulting events, likely by passing them to the application.

        Returns:
            Events read from the connection.
        )rW   )r]   rW   s     r-   events_receivedzProtocol.events_received  s     #k2r,   list[bytes]c                $    | j         g c}| _         |S )a  
        Obtain data to send to the network.

        Call this method immediately after any of the ``receive_*()``,
        ``send_*()``, or :meth:`fail` methods.

        Write resulting data to the connection.

        The empty bytestring :data:`~websockets.protocol.SEND_EOF` signals
        the end of the data stream. When you receive it, half-close the TCP
        connection.

        Returns:
            Data to write to the connection.

        )rX   )r]   rX   s     r-   data_to_sendzProtocol.data_to_send  s    " #k2r,   c                    | j         t          u rdS | j         t          u rdS | j         t          u rdS | j         t          u sJ | j        S )a  
        Tell if the TCP connection is expected to close soon.

        Call this method immediately after any of the ``receive_*()``,
        ``send_close()``, or :meth:`fail` methods.

        If it returns :obj:`True`, schedule closing the TCP connection after a
        short timeout if the other side hasn't already closed it.

        Returns:
            Whether the TCP connection is expected to close soon.

        FT)r5   r1   r2   r3   r0   rU   ra   s    r-   close_expectedzProtocol.close_expected  sV    D :5:  4:5zZ''''}r,   Generator[None]c              #  j  K   	 	 | j                                         E d{V r0| j        r| j                            d           t	          d          d}| j        | j        | j        }n| j        | j        z
  }| j        || j        }nt          || j                  }t          j
        | j         j        | j        t          u || j                  E d{V }| j        r| j                            d|           |                     |           # t           $ r?}|                     t$          j        t)          |                     || _        Y d}~nKd}~wt          $ r?}|                     t$          j        t)          |                     || _        Y d}~nd}~wt.          $ r@}|                     t$          j        |j         d|j                    || _        Y d}~nd}~wt6          $ rX}|                    | j                   |                     t$          j        t)          |                     || _        Y d}~n\d}~wt<          $ rL}| j                            dd	           |                     t$          j                    || _        Y d}~nd}~ww xY wdV  tC          d
          )a-  
        Parse incoming data into frames.

        :meth:`receive_data` and :meth:`receive_eof` run this generator
        coroutine until it needs more data or reaches EOF.

        :meth:`parse` never raises an exception. Instead, it sets the
        :attr:`parser_exc` and yields control.

        TN< EOFzunexpected end of stream)maskr6   rO   z< %sz at position zparser failed)exc_infoz"parse() shouldn't step after error)"rV   at_eofrG   r7   EOFErrorrJ   rL   rK   minr   rY   
read_exactr8   r)   rO   
recv_framer   r   r   PROTOCOL_ERRORr   r\   re   UnicodeDecodeErrorINVALID_DATArk   startr
   set_current_sizeMESSAGE_TOO_BIG	ExceptionerrorINTERNAL_ERRORAssertionError)r]   r6   framerp   s       r-   rY   zProtocol.parse2  s     =	"%'#{1133333333 ?z 3))'222
 ##=>>>(4(0#'#8#'#84;L#L)5'#'#9#&x1G#H#H
 $);K*f,%#	$ $ $       : 5K%%fe444&&&K%'N  	" 	" 	"IIi.C999!DOOOOOO 	" 	" 	"IIi0#c((;;;!DOOOOOO! 	" 	" 	"IIi,.U.U#).U.UVVV!DOOOOOO 	" 	" 	"  !2333IIi/S:::!DOOOOOO 	" 	" 	"Ko===IIi.///!DOOOOOO		" 	ABBBsJ   DD 
J4EJ$4FJ+6G&&J3AIJAJJc              #    K   | j         t          u p| j        t          u | j        k    sJ | j                                        E d{V s8| j                                         | j                                        E d{V 8| j        r| j	                            d           | j         t          u r"| j        t          ur|                                  t          | _        dV  t          d          )z
        Discard incoming data.

        This coroutine replaces :meth:`parse`:

        - after receiving a close frame, during a normal closure (1.4);
        - after sending a close frame, during an abnormal closure (7.1.7).

        Nr   z"discard() shouldn't step after EOF)r8   r)   r5   r0   rU   rV   r   r   rG   r7   r*   r   r3   r   ra   s    r-   r   zProtocol.discard  s       	V#?tzZ'?T]SSSS"k0022222222 	"K!!! #k0022222222 	": 	'Kg&&& 94:Z#?#?MMOOO
 ABBBr,   r   r   c                t   |j         t          u s|j         t          u r8| j        t	          d          |j        st          |j                  | _        n|j         t          u rJ| j        t	          d          |j        r	d| _        n| xj        t          |j                  z  c_        nq|j         t          u r1t          t          |j                  }|                     |           n2|j         t          u rn"|j         t          u rt          j        |j                  | _        | j        t$          u r| j        J d| _        | j        t	          d          | j        t*          u rL|                     t          t          |j                             | j        | _        d| _        t$          | _        | j        t.          u r|                                  |                                 | _        t7          | j                   nt9          d|j         d          | j                            |           dS )	z-
        Process an incoming frame.

        Nr   r   Fzincomplete fragmented messageTzunexpected opcode: 02x)opcoder   r   rL   r   r|   lenrr   r   r   r   r   r   r   r   rY   rQ   r5   r2   rR   rS   r1   r8   r)   r   r   rZ   r[   r   rW   append)r]   r   
pong_frames      r-   r   zProtocol.recv_frame  s   
 <7""eli&?&? ,#$CDDD9 4$'
OO!\W$$ (#$CDDDy 5$(!!!!S__4!!!\W$$ w
33JOOJ''''\W$$ \X%% $k%*55DOzW$$222,1) ,#$CDDD zT!!
 h
 ; ;<<<"&/,0)$
 yF"" ,,..DK !!Iu|!I!I!IJJJ5!!!!!r,   c                    | j         r| j                             d|           | j                            |                    | j        t          u | j                             d S )Nz> %s)r   rO   )rG   r7   rX   r   r   r8   r*   rO   )r]   r   s     r-   r   zProtocol.send_frame  sm    : 	-Kfe,,,OOY&(?   	
 	
 	
 	
 	
r,   c                    | j         rJ d| _         | j        r| j                            d           | j                            t
                     d S )NTz> EOF)rU   rG   r7   rX   r   r!   ra   s    r-   r   zProtocol.send_eof  sS    =   : 	'Kg&&&8$$$$$r,   )
r8   r   r5   r    r6   r9   r7   r:   r;   r<   )r;   r    )r5   r    r;   r<   )r;   rc   )r;   rh   )r;   r   )rr   rs   r;   r<   )r;   r<   )rr   r   r|   r}   r;   r<   )T)Nrj   )rf   r   rk   r   r;   r<   )rr   r   r;   r<   )rj   )rf   r   rk   r   r;   r<   )r;   r   )r;   r   )r;   r}   )r;   r   )r   r   r;   r<   )r$   r%   r&   r'   r1   r^   propertyr5   setterrg   rl   rq   rw   r{   r   r   r   r   r   r   r   r   r   r   rY   r   r   r   r   r+   r,   r-   r   r   G   sn        * ?D$(E1 E1 E1 E1 E1 E1N    X \   \
 ( ( ( X($ * * * X*$ ! ! ! X!J       *3 3 3 303 3 3 3 3.5 5 5 5 5." " " " "H. . . . . . . . - - - - -b       () ) ) )ZMC MC MC MC^C C C C<N" N" N" N"d
 
 
 
% % % % % %r,   r   )2
__future__r   enumrA   r>   collections.abcr   
exceptionsr   r   r   r	   r
   r   rO   r   framesr   r   r   r   r   r   r   r   r   r   http11r   r   streamsr   typingr   r   r   r   __all__EventIntEnumr   r)   r*   r    r0   r1   r2   r3   r!   r   r+   r,   r-   <module>r      sb   " " " " " "    % % % % % %                " ! ! ! ! !                        & % % % % % % % ! ! ! ! ! ! > > > > > > > > > > > >   	(U" ?    4<    
	1 1 1 1 1DL 1 1 1 
z
-	  Ey
% y
% y
% y
% y
% y
% y
% y
% y
% y
%r,   