
    .Pht                        d Z ddlZddlZ	 ddlmZ n# e$ r  G d d          ZY nw xY w	 ddlmZ  ed	          Zn# e	$ r  e
            ZY nw xY wd
ZdZdZ G d d          Z G d dej                  Z G d de          Z G d de          Z G d dej        e          Z G d d          Z G d de          Z G d de          Z G d de          ZdS )as  At its heart, Python can be viewed as an extension of the C
programming language. Springing from the most popular systems
programming language has made Python itself a great language for
systems programming. One key to success in this domain is Python's
very serviceable :mod:`socket` module and its :class:`socket.socket`
type.

The ``socketutils`` module provides natural next steps to the ``socket``
builtin: straightforward, tested building blocks for higher-level
protocols.

The :class:`BufferedSocket` wraps an ordinary socket, providing a
layer of intuitive buffering for both sending and receiving. This
facilitates parsing messages from streams, i.e., all sockets with type
``SOCK_STREAM``. The BufferedSocket enables receiving until the next
relevant token, up to a certain size, or until the connection is
closed. For all of these, it provides consistent APIs to size
limiting, as well as timeouts that are compatible with multiple
concurrency paradigms. Use it to parse the next one-off text or binary
socket protocol you encounter.

This module also provides the :class:`NetstringSocket`, a pure-Python
implementation of `the Netstring protocol`_, built on top of the
:class:`BufferedSocket`, serving as a ready-made, production-grade example.

Special thanks to `Kurt Rose`_ for his original authorship and all his
contributions on this module. Also thanks to `Daniel J. Bernstein`_, the
original author of `Netstring`_.

.. _the Netstring protocol: https://en.wikipedia.org/wiki/Netstring
.. _Kurt Rose: https://github.com/doublereedkurt
.. _Daniel J. Bernstein: https://cr.yp.to/
.. _Netstring: https://cr.yp.to/proto/netstrings.txt

    N)RLockc                       e Zd ZdZd Zd ZdS )r   z/Dummy reentrant lock for builds without threadsc                     d S N selfs    S/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/boltons/socketutils.py	__enter__zRLock.__enter__K       D    c                     d S r   r   )r	   exctypeexcinstexctbs       r
   __exit__zRLock.__exit__N   r   r   N)__name__
__module____qualname____doc__r   r   r   r   r
   r   r   I   s8        99	 	 		 	 	 	 	r   r      )make_sentinel_UNSET)var_name
   i   l           c                      e Zd ZdZeeefdZd Zd Zd Z	d Z
d Zd Zd	efd
ZefdZeefdZeedfdZefdZd	efdZd	efdZd Zd Zd Zd ZddZd Zed             Zed             Zed             Zd Zd Zd Z dS ) BufferedSocketa	  Mainly provides recv_until and recv_size. recv, send, sendall, and
    peek all function as similarly as possible to the built-in socket
    API.

    This type has been tested against both the built-in socket type as
    well as those from gevent and eventlet. It also features support
    for sockets with timeouts set to 0 (aka nonblocking), provided the
    caller is prepared to handle the EWOULDBLOCK exceptions.

    Args:
        sock (socket): The connected socket to be wrapped.
        timeout (float): The default timeout for sends and recvs, in
            seconds. Set to ``None`` for no timeout, and 0 for
            nonblocking. Defaults to *sock*'s own timeout if already set,
            and 10 seconds otherwise.
        maxsize (int): The default maximum number of bytes to be received
            into the buffer before it is considered full and raises an
            exception. Defaults to 32 kilobytes.
        recvsize (int): The number of bytes to recv for every
            lower-level :meth:`socket.recv` call. Defaults to *maxsize*.

    *timeout* and *maxsize* can both be overridden on individual socket
    operations.

    All ``recv`` methods return bytestrings (:class:`bytes`) and can
    raise :exc:`socket.error`. :exc:`Timeout`,
    :exc:`ConnectionClosed`, and :exc:`MessageTooLong` all inherit
    from :exc:`socket.error` and exist to provide better error
    messages. Received bytes are always buffered, even if an exception
    is raised. Use :meth:`BufferedSocket.getrecvbuffer` to retrieve
    partial recvs.

    BufferedSocket does not replace the built-in socket by any
    means. While the overlapping parts of the API are kept parallel to
    the built-in :class:`socket.socket`, BufferedSocket does not
    inherit from socket, and most socket functionality is only
    available on the underlying socket. :meth:`socket.getpeername`,
    :meth:`socket.getsockname`, :meth:`socket.fileno`, and others are
    only available on the underlying socket that is wrapped. Use the
    ``BufferedSocket.sock`` attribute to access it. See the examples
    for more information on how to use BufferedSockets with built-in
    sockets.

    The BufferedSocket is threadsafe, but consider the semantics of
    your protocol before accessing a single socket from multiple
    threads. Similarly, once the BufferedSocket is constructed, avoid
    using the underlying socket directly. Only use it for operations
    unrelated to messages, e.g., :meth:`socket.getpeername`.

    c                    || _         d| _        g | _        t          |          | _        |t
          u rE| j                                         t          | _        n=| j                                         | _        n||| _        nt          |          | _        |t
          u r| j        | _
        nt          |          | _
        t                      | _        t                      | _        d S )Nr   )sockrbufsbufintmaxsizer   
gettimeoutDEFAULT_TIMEOUTtimeoutfloat	_recvsizer   
_send_lock
_recv_lock)r	   r   r&   r#   recvsizes        r
   __init__zBufferedSocket.__init__   s    			7||fy##%%-.#y3355&$W~~v!\DNN ]]DN''''r   c                     || _         dS )z<Set the default *timeout* for future operations, in seconds.Nr&   r	   r&   s     r
   
settimeoutzBufferedSocket.settimeout   s    r   c                     | j         S r   r.   r   s    r
   r$   zBufferedSocket.gettimeout   s
    |r   c                     |rd nd| _         d S )N        r.   )r	   blockings     r
   setblockingzBufferedSocket.setblocking   s    '0ttSr   c                     || _         dS )zSet the default maximum buffer size *maxsize* for future
        operations, in bytes. Does not truncate the current buffer.
        N)r#   r	   r#   s     r
   
setmaxsizezBufferedSocket.setmaxsize   s     r   c                 R    | j         5  | j        cddd           S # 1 swxY w Y   dS )z-Returns the receive buffer bytestring (rbuf).N)r*   r    r   s    r
   getrecvbufferzBufferedSocket.getrecvbuffer   ss    _ 	 	9	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	s     c                 x    | j         5  d                    | j                  cddd           S # 1 swxY w Y   dS )z'Returns a copy of the send buffer list.r   N)r)   joinr!   r   s    r
   getsendbufferzBufferedSocket.getsendbuffer   s    _ 	' 	'88DI&&	' 	' 	' 	' 	' 	' 	' 	' 	' 	' 	' 	' 	' 	' 	' 	' 	' 	's   /33r   c                 |   | j         5  |t          u r| j        }|rt          d|z            t	          | j                  |k    r2| j        d|         | j        |d         c}| _        |cddd           S | j        r| j        dc}| _        |cddd           S | j                            |           	 | j                            | j	                  }n"# t          j        $ r t          |          w xY wt	          |          |k    r|d|         ||d         c}| _        ddd           n# 1 swxY w Y   |S )ao  Returns **up to** *size* bytes, using the internal buffer before
        performing a single :meth:`socket.recv` operation.

        Args:
            size (int): The maximum number of bytes to receive.
            flags (int): Kept for API compatibility with sockets. Only
                the default, ``0``, is valid.
            timeout (float): The timeout for this operation. Can be
                ``0`` for nonblocking and ``None`` for no
                timeout. Defaults to the value set in the constructor
                of BufferedSocket.

        If the operation does not complete in *timeout* seconds, a
        :exc:`Timeout` is raised. Much like the built-in
        :class:`socket.socket`, if this method returns an empty string,
        then the socket is closed and recv buffer is empty. Further
        calls to recv will raise :exc:`socket.error`.

        z non-zero flags not supported: %rNr   )r*   r   r&   
ValueErrorlenr    r   r0   recvr(   socketTimeout)r	   sizeflagsr&   datarets         r
   rA   zBufferedSocket.recv   s   ( _ 	; 	;&  , M !Ce!KLLL49~~%%"&)ETE"2DIdee4Ddi	; 	; 	; 	; 	; 	; 	; 	; y !%CTY	; 	; 	; 	; 	; 	; 	; 	; I  )))'y~~dn55> ' ' 'g&&&'4yy4"&uu+tDEE{di#	; 	; 	; 	; 	; 	; 	; 	; 	; 	; 	; 	; 	; 	; 	;$ s6   A"D17D1D16CD1C550D11D58D5c                     | j         5  t          | j                  |k    r| j        d|         cddd           S |                     ||          }|| j        z   | _        ddd           n# 1 swxY w Y   |S )a  Returns *size* bytes from the socket and/or internal buffer. Bytes
        are retained in BufferedSocket's internal recv buffer. To only
        see bytes in the recv buffer, use :meth:`getrecvbuffer`.

        Args:
            size (int): The exact number of bytes to peek at
            timeout (float): The timeout for this operation. Can be 0 for
                nonblocking and None for no timeout. Defaults to the value
                set in the constructor of BufferedSocket.

        If the appropriate number of bytes cannot be fetched from the
        buffer and socket before *timeout* expires, then a
        :exc:`Timeout` will be raised. If the connection is closed, a
        :exc:`ConnectionClosed` will be raised.
        Nr.   )r*   r@   r    	recv_size)r	   rD   r&   rF   s       r
   peekzBufferedSocket.peek   s      _ 	) 	)49~~%%y$'	) 	) 	) 	) 	) 	) 	) 	) >>$>88Dty(DI		) 	) 	) 	) 	) 	) 	) 	) 	) 	) 	) 	) 	) 	) 	)
 s   'A.&A..A25A2c                 j   | j         5  |t          u r| j        }|t          }	 |                     |dz   |          }|| j        z   | _        t          |t          | j                            }t          |          # t          $ r | j        dc}| _        Y nw xY w	 ddd           n# 1 swxY w Y   |S )zReceive until the connection is closed, up to *maxsize* bytes. If
        more than *maxsize* bytes are received, raises :exc:`MessageTooLong`.
        Nr   r   )
r*   r   r#   _RECV_LARGE_MAXSIZErI   r    minr@   MessageTooLongConnectionClosed)r	   r&   r#   recvd	size_readrG   s         r
   
recv_closezBufferedSocket.recv_close  s    _ 	0 	0&  ,-0w{G<<
 "DI-	TY88	$Y/// $ 0 0 0!%CTYYY0	0 	0 	0 	0 	0 	0 	0 	0 	0 	0 	0 	0 	0 	0 	0 
s4   B(A<A B(<BB(BB((B,/B,Fc                    | j         5  |t          u r| j        }|t          }|t          u r| j        }t          |          }| j        }t          | j                  }t          j	                    }d}	|s|
                    |           	 	 |                    ||	|          }
|
dk    r|r|
|z  }
|
}n|
|z   }nt          |          |k    rt          ||          |rG|t          j	                    |z
  z
  }|dk    rt          j                    |
                    |           |                    | j                  }|s%t          |          |f}d|z  }t!          |          |                    |           t          |           |z
  dz   }	nj# t          j        $ r: t%          |          | _        dt          |          d|}t'          ||          t(          $ r t%          |          | _         w xY wt%          |d|
                   t%          ||d                   c}| _        ddd           n# 1 swxY w Y   |S )	a:  Receive until *delimiter* is found, *maxsize* bytes have been read,
        or *timeout* is exceeded.

        Args:
            delimiter (bytes): One or more bytes to be searched for
                in the socket stream.
            timeout (float): The timeout for this operation. Can be 0 for
                nonblocking and None for no timeout. Defaults to the value
                set in the constructor of BufferedSocket.
            maxsize (int): The maximum size for the internal buffer.
                Defaults to the value set in the constructor.
            with_delimiter (bool): Whether or not to include the
                delimiter in the output. ``False`` by default, but
                ``True`` is useful in cases where one is simply
                forwarding the messages.

        ``recv_until`` will raise the following exceptions:

          * :exc:`Timeout` if more than *timeout* seconds expire.
          * :exc:`ConnectionClosed` if the underlying socket is closed
            by the sending end.
          * :exc:`MessageTooLong` if the delimiter is not found in the
            first *maxsize* bytes.
          * :exc:`socket.error` if operating in nonblocking mode
            (*timeout* equal to 0), or if some unexpected socket error
            occurs, such as operating on a closed socket.

        Nr   r   r3   zCconnection closed after reading %s bytes without finding symbol: %rread z" bytes without finding delimiter: )r*   r   r#   rL   r&   r@   r   	bytearrayr    timer0   findrN   rB   rA   r(   rO   extendbytesrC   	Exception)r	   	delimiterr&   r#   with_delimiterlen_delimiterr   rP   startfind_offset_startoffsetrbuf_offsetcur_timeoutnxtargsmsgvals                    r
   
recv_untilzBufferedSocket.recv_until  s   < _ 1	O 1	O&  ,-&  ,	NNM9Ddi((EIKKE ! )((( F"ZZ	3DgNNF||) A"m3F*0KK*0=*@KUg--,Wi@@@ 5&-u1D&E&#--"(."2"22444))DN33C 4 #E

I6 =?C D.s333LL%%%),S	M(AA(E%/F   > , , ,!%LL		e****ii1gs+++   !%LL	 #5&>22E%:M4N4NNCc1	O 1	O 1	O 1	O 1	O 1	O 1	O 1	O 1	O 1	O 1	O 1	O 1	O 1	O 1	Od 
s,   B H<	DFH<A'G997H<<I I c                    | j         5  |t          u r| j        }g }d}	 t          j                    }| j                            |           | j        p| j                            | j                  }|r|t          |          z  }||k    rn|
                    |           |rL|t          j                    |z
  z
  }|dk    rt          j                    | j                            |           | j                            | j                  }|d|d|d}t          |          nj# t          j        $ r4 d                    |          | _        d| d| d}t          ||          t          $ r d                    |          | _         w xY w||z
  }	|	r|d	|	          ||	 d	         c}
| _        n
|dc}
| _        |
                    |
           d	d	d	           n# 1 swxY w Y   d                    |          S )
a  Read off of the internal buffer, then off the socket, until
        *size* bytes have been read.

        Args:
            size (int): number of bytes to read before returning.
            timeout (float): The timeout for this operation. Can be 0 for
                nonblocking and None for no timeout. Defaults to the value
                set in the constructor of BufferedSocket.

        If the appropriate number of bytes cannot be fetched from the
        buffer and socket before *timeout* expires, then a
        :exc:`Timeout` will be raised. If the connection is closed, a
        :exc:`ConnectionClosed` will be raised.
        r   r3   z connection closed after reading z of z requested bytesr   rU   z bytesN)r*   r   r&   rW   r   r0   r    rA   r(   r@   appendrB   rO   r<   rC   r[   )r	   rD   r&   chunkstotal_bytesr_   rd   rc   rf   extra_byteslasts              r
   rI   zBufferedSocket.recv_sizen  s|    _ %	  %	 &  ,FK		$$W---iA49>>$.#A#A 03s88+K"d**MM#&&& :&-u1D&E&#--"(."2"22	,,[999)..88C  0 (3{{DDD:C*3///  > , , ,HHV,,	;k;;t;;;gs+++   HHV,,	 &,K +"%m|m"4c;,--6Hdii"%sdiMM$K%	  %	  %	  %	  %	  %	  %	  %	  %	  %	  %	  %	  %	  %	  %	 L xxs+   G"D
D)(G")A'FAG""G&)G&c           
      .   | j         5  |t          u r| j        }|rt          d          | j        }|                    |           t          |          dk    r%d                    d |D                       g|dd<   | j        	                    |           t          j
                    d}}	 |d         r| j                            |d                   }||z  }|d         |d         |d<   |rL|t          j
                    |z
  z
  }|dk    rt          j                    | j        	                    |           |d         n9# t          j        $ r' t          |dt          |d                   z            w xY wddd           n# 1 swxY w Y   |S )	a_  Send the contents of the internal send buffer, as well as *data*,
        to the receiving end of the connection. Returns the total
        number of bytes sent. If no exception is raised, all of *data* was
        sent and the internal send buffer is empty.

        Args:
            data (bytes): The bytes to send.
            flags (int): Kept for API compatibility with sockets. Only
                the default 0 is valid.
            timeout (float): The timeout for this operation. Can be 0 for
                nonblocking and None for no timeout. Defaults to the value
                set in the constructor of BufferedSocket.

        Will raise :exc:`Timeout` if the send operation fails to
        complete before *timeout*. In the event of an exception, use
        :meth:`BufferedSocket.getsendbuffer` to see which data was
        unsent.
        znon-zero flags not supportedr   r   c                     g | ]}||S r   r   ).0ss     r
   
<listcomp>z'BufferedSocket.send.<locals>.<listcomp>  s    $:$:$:1$:Q$:$:$:r   Nr   r3   z%s bytes unsent)r)   r   r&   r?   r!   rj   r@   r<   r   r0   rW   sendrB   rC   )	r	   rF   rE   r&   r!   r_   
total_sentsentrc   s	            r
   rt   zBufferedSocket.send  s   & _ 	I 	I&  , A !?@@@9DKK4yy1}}88$:$:$:$:$:;;<QQQI  ))) $	Q:EI1g :9>>$q'22D$&J"1gdeenDG :&-u1D&E&#--"(."2"22	,,[999 1g : > I I Ig'83tAw<<'GHHHI+	I 	I 	I 	I 	I 	I 	I 	I 	I 	I 	I 	I 	I 	I 	I. s+   B%F
.BEF
6E;;F

FFc                 0    |                      |||          S )z{A passthrough to :meth:`~BufferedSocket.send`, retained for
        parallelism to the :class:`socket.socket` API.
        )rt   )r	   rF   rE   r&   s       r
   sendallzBufferedSocket.sendall  s     yyug...r   c                 n    | j         5  |                     d           ddd           n# 1 swxY w Y   dS )z.Send the contents of the internal send buffer.r   N)r)   rt   r   s    r
   flushzBufferedSocket.flush  ss    _ 	 	IIcNNN	 	 	 	 	 	 	 	 	 	 	 	 	 	 	s   *..c                 x    | j         5  | j                            |           ddd           n# 1 swxY w Y   dS )z0Buffer *data* bytes for the next send operation.N)r)   r!   rj   )r	   rF   s     r
   bufferzBufferedSocket.buffer  sz    _ 	# 	#IT"""	# 	# 	# 	# 	# 	# 	# 	# 	# 	# 	# 	# 	# 	# 	#s   /33c                 4    | j                                         S )zConvenience function to return the wrapped socket's own address.
        See :meth:`socket.getsockname` for more details.
        )r   getsocknamer   s    r
   r~   zBufferedSocket.getsockname  s     y$$&&&r   c                 4    | j                                         S )zConvenience function to return the remote address to which the
        wrapped socket is connected.  See :meth:`socket.getpeername`
        for more details.
        )r   getpeernamer   s    r
   r   zBufferedSocket.getpeername  s    
 y$$&&&r   Nc                 8    ||f}|||fz  } | j         j        | S )zhConvenience function passing through to the wrapped socket's
        :meth:`socket.getsockopt`.
        )r   
getsockopt)r	   leveloptnamebuflenre   s        r
   r   zBufferedSocket.getsockopt  s2     wVID#ty#T**r   c                 :    | j                             |||          S )zhConvenience function passing through to the wrapped socket's
        :meth:`socket.setsockopt`.
        )r   
setsockopt)r	   r   r   values       r
   r   zBufferedSocket.setsockopt  s     y##E7E:::r   c                     | j         j        S )zzA passthrough to the wrapped socket's type. Valid usages should
        only ever see :data:`socket.SOCK_STREAM`.
        )r   typer   s    r
   r   zBufferedSocket.type  s    
 y~r   c                     | j         j        S )a  A passthrough to the wrapped socket's family. BufferedSocket
        supports all widely-used families, so this read-only attribute
        can be one of :data:`socket.AF_INET` for IP,
        :data:`socket.AF_INET6` for IPv6, and :data:`socket.AF_UNIX`
        for UDS.
        )r   familyr   s    r
   r   zBufferedSocket.family
  s     yr   c                     | j         j        S )aa  A passthrough to the wrapped socket's protocol. The ``proto``
        attribute is very rarely used, so it's always 0, meaning "the
        default" protocol. Pretty much all the practical information
        is in :attr:`~BufferedSocket.type` and
        :attr:`~BufferedSocket.family`, so you can go back to never
        thinking about this.
        )r   protor   s    r
   r   zBufferedSocket.proto  s     yr   c                 4    | j                                         S )a  Returns the file descriptor of the wrapped socket. -1 if it has
        been closed on this end.

        Note that this makes the BufferedSocket selectable, i.e.,
        usable for operating system event loops without any external
        libraries. Keep in mind that the operating system cannot know
        about data in BufferedSocket's internal buffer. Exercise
        discipline with calling ``recv*`` functions.
        )r   filenor   s    r
   r   zBufferedSocket.fileno#  s     y!!!r   c                     | j         5  | j        5  d| _        | j        | _        g | j        dd<   | j                                         ddd           n# 1 swxY w Y   ddd           n# 1 swxY w Y   dS )au  Closes the wrapped socket, and empties the internal buffers. The
        send buffer is not flushed automatically, so if you have been
        calling :meth:`~BufferedSocket.buffer`, be sure to call
        :meth:`~BufferedSocket.flush` before calling this
        method. After calling this method, future socket operations
        will raise :exc:`socket.error`.
        r   N)r*   r)   r    rbuf_unconsumedr!   r   closer   s    r
   r   zBufferedSocket.close/  s     _ 	" 	" " "	'+y$!	!!!	!!!	" " " " " " " " " " " " " " "	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	s4   A,9A	A,A	A,A	A,,A03A0c                     | j         5  | j        5  | j                            |           ddd           n# 1 swxY w Y   ddd           n# 1 swxY w Y   dS )a  Convenience method which passes through to the wrapped socket's
        :meth:`~socket.shutdown`. Semantics vary by platform, so no
        special internal handling is done with the buffers. This
        method exists to facilitate the most common usage, wherein a
        full ``shutdown`` is followed by a
        :meth:`~BufferedSocket.close`. Developers requiring more
        support, please open `an issue`_.

        .. _an issue: https://github.com/mahmoud/boltons/issues
        N)r*   r)   r   shutdown)r	   hows     r
   r   zBufferedSocket.shutdown?  s     _ 	( 	( ( (	""3'''( ( ( ( ( ( ( ( ( ( ( ( ( ( (	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	s,   A7A;	A;	AAAr   )!r   r   r   r   r   DEFAULT_MAXSIZEr,   r0   r$   r5   r8   r:   r=   rA   rJ   rR   rh   rI   rt   rx   rz   r|   r~   r   r   r   propertyr   r   r   r   r   r   r   r   r
   r   r   ^   s8       1 1d &,(6" " " "4    1 1 1    
' ' '
  !& & & & &P "(    . "(    0 -3F"'P P P Pd '- 5  5  5  5 n  !& * * * *X #$V / / / /    ' ' '' ' '+ + + +; ; ;   X     X    X
" 
" 
"       r   r   c                       e Zd ZdZdS )Errora  A subclass of :exc:`socket.error` from which all other
    ``socketutils`` exceptions inherit.

    When using :class:`BufferedSocket` and other ``socketutils``
    types, generally you want to catch one of the specific exception
    types below, or :exc:`socket.error`.
    Nr   r   r   r   r   r   r
   r   r   R            	Dr   r   c                       e Zd ZdZdS )rO   aT  Raised when receiving and the connection is unexpectedly closed
    from the sending end. Raised from :class:`BufferedSocket`'s
    :meth:`~BufferedSocket.peek`, :meth:`~BufferedSocket.recv_until`,
    and :meth:`~BufferedSocket.recv_size`, and never from its
    :meth:`~BufferedSocket.recv` or
    :meth:`~BufferedSocket.recv_close`.
    Nr   r   r   r
   rO   rO   ]  r   r   rO   c                   $     e Zd ZdZd fd	Z xZS )rN   zRaised from :meth:`BufferedSocket.recv_until` and
    :meth:`BufferedSocket.recv_closed` when more than *maxsize* bytes are
    read without encountering the delimiter or a closed connection,
    respectively.
    Nc                 x    d}|	|d| dz  }||d|z  }t                                          |           d S )Nzmessage exceeded maximum sizez. z bytes readz. Delimiter not found: superr,   )r	   
bytes_readr\   rf   	__class__s       r
   r,   zMessageTooLong.__init__n  s[    -!/
////C :Y:::Cr   )NNr   r   r   r   r,   __classcell__r   s   @r
   rN   rN   h  G         
         r   rN   c                   $     e Zd ZdZd fd	Z xZS )rC   zInheriting from :exc:`socket.timeout`, Timeout is used to indicate
    when a socket operation did not complete within the time
    specified. Raised from any of :class:`BufferedSocket`'s ``recv``
    methods.
     c                 |    d}||d|dz  z  z  }|r|d|z   z  }t                                          |           d S )Nzsocket operation timed outz after %sms.i   r   )r	   r&   extrarf   r   s       r
   r,   zTimeout.__init__}  sU    *>Wt^44C 	3;Cr   )r   r   r   s   @r
   rC   rC   w  r   r   rC   c                   H    e Zd ZdZeefdZd Zd Zd Z	d Z
eefdZd Zd	S )
NetstringSocketz
    Reads and writes using the netstring protocol.

    More info: https://en.wikipedia.org/wiki/Netstring
    Even more info: http://cr.yp.to/proto/netstrings.txt
    c                     t          |          | _        || _        || _        t	          t          |                    dz   | _        d S Nr   )r   bsockr&   r#   r@   str_msgsize_maxsize)r	   r   r&   r#   s       r
   r,   zNetstringSocket.__init__  s@    #D))
 #CLL 1 1A 5r   c                 4    | j                                         S r   )r   r   r   s    r
   r   zNetstringSocket.fileno  s    z  """r   c                     || _         d S r   r.   r/   s     r
   r0   zNetstringSocket.settimeout  s    r   c                 H    || _         |                     |          | _        d S r   )r#   _calc_msgsize_maxsizer   r7   s     r
   r8   zNetstringSocket.setmaxsize  s%     $ : :7 C Cr   c                 @    t          t          |                    dz   S r   )r@   r   r7   s     r
   r   z%NetstringSocket._calc_msgsize_maxsize  s    3w<<  1$$r   c                    |t           u r| j        }|t           u r| j        }| j        }n|                     |          }| j                            d||          }	 t          |          }n # t          $ r t          d|z            w xY w||k    rt          ||          | j                            |          }| j                            d          dk    rt          d          |S )N   :)r&   r#   z4netstring message size must be valid integer, not %rr      ,z#expected trailing ',' after message)r   r&   r#   r   r   r   rh   r"   r?   NetstringInvalidSizeNetstringMessageTooLongrI   rA   NetstringProtocolError)r	   r&   r#   msgsize_maxsizesize_prefixrD   payloads          r
   read_nszNetstringSocket.read_ns  s   flGflG"3OO"88AAOj++D4;4C , E E	I{##DD 	I 	I 	I& (:<G(H I I I	I '>>)$888*&&t,,:??1%%()NOOOs   A, ,B	c                     t          |          }|| j        k    rt          || j                  t          |                              d          dz   |z   dz   }| j                            |           d S )Nasciir   r   )r@   r#   r   r   encoder   rt   )r	   r   rD   rF   s       r
   write_nszNetstringSocket.write_ns  sn    7||$,)$===4yy((4/'9D@
r   N)r   r   r   r   r%   r   r,   r   r0   r8   r   r   r   r   r   r   r
   r   r     s          &5o 6 6 6 6# # #  D D D% % % %f    6    r   r   c                       e Zd ZdZdS )r   z=Base class for all of socketutils' Netstring exception types.Nr   r   r   r
   r   r     s        CCDr   r   c                   "     e Zd ZdZ fdZ xZS )r   aR  NetstringInvalidSize is raised when the ``:``-delimited size prefix
    of the message does not contain a valid integer.

    Message showing valid size::

      5:hello,

    Here the ``5`` is the size. Anything in this prefix position that
    is not parsable as a Python integer (i.e., :class:`int`) will raise
    this exception.
    c                 J    t                                          |           d S r   r   )r	   rf   r   s     r
   r,   zNetstringInvalidSize.__init__  s!    r   r   r   s   @r
   r   r     sB        
 
        r   r   c                   "     e Zd ZdZ fdZ xZS )r   a(  NetstringMessageTooLong is raised when the size prefix contains a
    valid integer, but that integer is larger than the
    :class:`NetstringSocket`'s configured *maxsize*.

    When this exception is raised, it's recommended to simply close
    the connection instead of trying to recover.
    c                 Z    d|d|}t                                          |           d S )Nz5netstring message length exceeds configured maxsize: z > r   )r	   rD   r#   rf   r   s       r
   r,   z NetstringMessageTooLong.__init__  s5     $$!r   r   r   s   @r
   r   r     sB                 r   r   )r   rW   rB   	threadingr   r[   	typeutilsr   r   ImportErrorobjectr%   r   rL   r   errorr   rO   rN   r&   rC   r   r   r   r   r   r   r
   <module>r      s  >" "H  	            ((((((]H---FF   VXXFFF  o o o o o o o oh	 	 	 	 	FL 	 	 		 	 	 	 	u 	 	 	    U       fne   : : : : : : : :z	 	 	 	 	U 	 	 	
    1        4    s    ((? AA