
    Vibu                        S r SSKrSSKr SSKJr   SSKJr  \" SS9r	S	rS
rSr " S S\5      r " S S\R                  5      r " S S\5      r " S S\5      r " S S\R&                  \5      r " S S\5      r " S S\5      r " S S\5      r " S S\5      rg! \ a     " S S\5      r Nf = f! \
 a
    \" 5       r	 Nf = f)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                   $    \ rS rSrSrS rS rSrg)r   K   z/Dummy reentrant lock for builds without threadsc                     g N selfs    f/home/james-whalen/.local/share/pipx/venvs/semgrep/lib/python3.13/site-packages/boltons/socketutils.py	__enter__RLock.__enter__M           c                     g r   r   )r
   exctypeexcinstexctbs       r   __exit__RLock.__exit__P   r   r   r   N)__name__
__module____qualname____firstlineno____doc__r   r   __static_attributes__r   r   r   r   r   K   s    9		r   r   )make_sentinel_UNSET)var_name
   i   l           c                      \ rS rSrSr\\\4S jrS rS r	S r
S rS rS	 rS
\4S jr\4S jr\\4S jr\\S4S jr\4S jrS
\4S jrS
\4S jrS rS rS rS rS!S jrS r\S 5       r\S 5       r\S 5       rS rS r S r!S r"g)"BufferedSocket`   a,	  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                    Xl         SU l        / U l        [        U5      U l        U[
        L aG  U R                   R                  5       c  [        U l        O:U R                   R                  5       U l        OUc  X l        O[        U5      U l        U[
        L a  U R                  U l
        O[        U5      U l
        [        5       U l        [        5       U l        g )Nr   )sockrbufsbufintmaxsizer   
gettimeoutDEFAULT_TIMEOUTtimeoutfloat	_recvsizer   
_send_lock
_recv_lock)r
   r$   r+   r(   recvsizes        r   __init__BufferedSocket.__init__   s    			7|fyy##%-.#yy335&$W~v!\\DN ]DN''r   c                     Xl         g)z<Set the default *timeout* for future operations, in seconds.Nr+   r
   r+   s     r   
settimeoutBufferedSocket.settimeout   s    r   c                     U R                   $ r   r4   r	   s    r   r)   BufferedSocket.gettimeout   s    ||r   c                 0    U(       a  S U l         g SU l         g )N        r4   )r
   blockings     r   setblockingBufferedSocket.setblocking   s    'tSr   c                     Xl         g)zuSet the default maximum buffer size *maxsize* for future
operations, in bytes. Does not truncate the current buffer.
N)r(   r
   r(   s     r   
setmaxsizeBufferedSocket.setmaxsize   s	     r   c                 h    U R                      U R                  sSSS5        $ ! , (       d  f       g= f)z-Returns the receive buffer bytestring (rbuf).N)r/   r%   r	   s    r   getrecvbufferBufferedSocket.getrecvbuffer   s    __99 __s   #
1c                     U R                      SR                  U R                  5      sSSS5        $ ! , (       d  f       g= f)z'Returns a copy of the send buffer list.r   N)r.   joinr&   r	   s    r   getsendbufferBufferedSocket.getsendbuffer   s#    __88DII& __s	   2
A r   c                    U R                      U[        L a  U R                  nU(       a  [        SU-  5      e[	        U R
                  5      U:  a.  U R
                  SU U R
                  US so@l        UsSSS5        $ U R
                  (       a  U R
                  SsoPl        UsSSS5        $ U R                  R                  U5         U R                  R                  U R                  5      n[	        U5      U:  a  USU XAS so@l        SSS5        U$ ! [        R                   a    [        U5      ef = f! , (       d  f       W$ = f)a  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$   r6   recvr-   socketTimeout)r
   sizeflagsr+   datarets         r   rM   BufferedSocket.recv   s   ( __& ,, !Ce!KLL499~%"&))ET"2DIIde4Di _ yy!%CY _ II  )'yy~~dnn5 4y4"&u+tE{i# $ 	 >> 'g&&' _$ s0   A(D9?%D9.D9
%D/D9 D66D99
Ec                     U R                      [        U R                  5      U:  a  U R                  SU sSSS5        $ U R                  XS9nX0R                  -   U l        SSS5        U$ ! , (       d  f       W$ = f)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.
Nr4   )r/   rL   r%   	recv_size)r
   rP   r+   rR   s       r   peekBufferedSocket.peek   sk      __499~%yy$' _ >>$>8Dyy(DI	 
  _
 s   (A+"A++
A:c                 ~   U R                      U[        L a  U R                  nUc  [        n U R	                  US-   U5      nX0R
                  -   U l        [        U[        U R
                  5      5      n[        U5      e! [         a    U R
                  SsoPl         Of = f SSS5        U$ ! , (       d  f       W$ = f)zReceive until the connection is closed, up to *maxsize* bytes. If
more than *maxsize* bytes are received, raises :exc:`MessageTooLong`.
N   r   )
r/   r   r(   _RECV_LARGE_MAXSIZErV   r%   minrL   MessageTooLongConnectionClosed)r
   r+   r(   recvd	size_readrS   s         r   
recv_closeBufferedSocket.recv_close  s     __& ,,-0w{G<
 "II-	TYY8	$Y// $ 0!%CY0  
 _ 
s.   B-A?=B-?BB-BB--
B<Fc                 d   U R                      U[        L a  U R                  nUc  [        nU[        L a  U R                  n[        U5      nU R                  n[        U R                  5      n[        R                  " 5       nSn	U(       d  UR                  U5          UR                  XU5      n
U
S:w  a  U(       a  X-  n
U
nOX-   nO[        U5      U:  a  [        X15      eU(       aG  U[        R                  " 5       U-
  -
  nUS::  a  [        R                  " 5       eUR                  U5        UR                  U R                  5      nU(       d  [        U5      U4nSU-  n[!        U5      eUR#                  U5        [        U5      * U-
  S-   n	M  [%        USU
 5      [%        X{S 5      snU l        SSS5        U$ ! [        R                   a/    [%        U5      U l        S[        U5      < SU< 3n['        X/5      e[(         a    [%        U5      U l        e f = f! , (       d  f       W$ = f)	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   rZ   r;   zCconnection closed after reading %s bytes without finding symbol: %rread z" bytes without finding delimiter: )r/   r   r(   r[   r+   rL   r$   	bytearrayr%   timer6   findr]   rN   rM   r-   r^   extendbytesrO   	Exception)r
   	delimiterr+   r(   with_delimiterlen_delimiterr$   r_   startfind_offset_startoffsetrbuf_offsetcur_timeoutnxtargsmsgvals                    r   
recv_untilBufferedSocket.recv_until  s   < __& ,,-& ,,	NM99Ddii(EIIKE !( "ZZ	gNF|)"3F*0K*0*@KUg-,W@@&-u1D&E&#-"(.."224))DNN3C #E
I6 =?C D.s33LL%),S	M(AA(E%/ @ #5&>2E%:M4NNCc d 
 >> ,!%L	e*i1g++ !%L	] _d 
s2   BH +G H 	CG !H  AHH  
H/c                 8   U R                      U[        L a  U R                  n/ nSn [        R                  " 5       nU R                  R                  U5        U R                  =(       d%    U R                  R                  U R                  5      nU(       a  U[        U5      -  nXA:  a  OUR                  U5        U(       aQ  U[        R                  " 5       U-
  -
  nUS::  a  [        R                  " 5       eU R                  R                  U5        U R                  R                  U R                  5      nU(       a  M  SU< SU< S3n[        U5      eXA-
  n	U	(       a  US	U	*  Xi* S	 sol        O	USsol        UR                  U
5        S	S	S	5        SR                  W5      $ ! [        R                   a-    SR                  U5      U l        SU< SU< S3n[        X(5      e[         a    SR                  U5      U l        e f = f! , (       d  f       N= f)
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   r;   z connection closed after reading z of z requested bytesr   re   z bytesN)r/   r   r+   rg   r$   r6   r%   rM   r-   rL   appendrN   r^   rG   rO   rk   )r
   rP   r+   chunkstotal_bytesro   rt   rs   rv   extra_byteslasts              r   rV   BufferedSocket.recv_sizep  s    __& ,,FK				$$W-iiA499>>$..#A3s8+K"*MM#&&-u1D&E&#-"(.."22		,,[9))..8C c (3D:C*3// &,K"%m|"4c,-6Hi"%siMM$K L xx >> ,HHV,	/:DAg++ HHV,	9 _s7   HBF'*H+BF'F'6H'A!HH
Hc           
      `   U R                      U[        L a  U R                  nU(       a  [        S5      eU R                  nUR                  U5        [        U5      S:  a.  SR                  U Vs/ s H  oU(       d  M  UPM     sn5      /USS& U R                  R                  U5        [        R                  " 5       Spv US   (       a  U R                  R                  US   5      nXx-  nUS   US US'   U(       aQ  U[        R                  " 5       U-
  -
  n	U	S::  a  [        R                  " 5       eU R                  R                  U	5        US   (       a  M  SSS5        U$ s  snf ! [        R                   a    [        US[        US   5      -  5      ef = f! , (       d  f       W$ = f)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 supportedrZ   r   Nr   r;   z%s bytes unsent)r.   r   r+   rK   r&   r{   rL   rG   r$   r6   rg   sendrN   rO   )
r
   rR   rQ   r+   r&   sro   
total_sentsentrs   s
             r   r   BufferedSocket.send  sl   & __& ,, !?@@99DKK4y1}88$:1Q$:;<QII  ) $		Q:I1g99>>$q'2D&J"1gdenDG&-u1D&E&#-"(.."22		,,[9 1gg .  %; >> Ig'83tAw<'GHHI+ _. s7   A#F0
E&
>E&
<FBE+&F+0FF
F-c                 &    U R                  XU5      $ )zkA passthrough to :meth:`~BufferedSocket.send`, retained for
parallelism to the :class:`socket.socket` API.
)r   )r
   rR   rQ   r+   s       r   sendallBufferedSocket.sendall  s     yyg..r   c                 r    U R                      U R                  S5        SSS5        g! , (       d  f       g= f)z.Send the contents of the internal send buffer.r   N)r.   r   r	   s    r   flushBufferedSocket.flush  s'    __IIcN  _s   (
6c                     U R                      U R                  R                  U5        SSS5        g! , (       d  f       g= f)z0Buffer *data* bytes for the next send operation.N)r.   r&   r{   )r
   rR   s     r   bufferBufferedSocket.buffer  s.    __IIT"  _s	   2
A c                 6    U R                   R                  5       $ )zrConvenience function to return the wrapped socket's own address.
See :meth:`socket.getsockname` for more details.
)r$   getsocknamer	   s    r   r   BufferedSocket.getsockname  s     yy$$&&r   c                 6    U R                   R                  5       $ )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   BufferedSocket.getpeername  s    
 yy$$&&r   Nc                 J    X4nUb  XC4-  nU R                   R                  " U6 $ )zXConvenience function passing through to the wrapped socket's
:meth:`socket.getsockopt`.
)r$   
getsockopt)r
   leveloptnamebuflenru   s        r   r   BufferedSocket.getsockopt  s1     IDyy##T**r   c                 :    U R                   R                  XU5      $ )zXConvenience function passing through to the wrapped socket's
:meth:`socket.setsockopt`.
)r$   
setsockopt)r
   r   r   values       r   r   BufferedSocket.setsockopt  s     yy##EE::r   c                 .    U R                   R                  $ )zjA passthrough to the wrapped socket's type. Valid usages should
only ever see :data:`socket.SOCK_STREAM`.
)r$   typer	   s    r   r   BufferedSocket.type  s    
 yy~~r   c                 .    U R                   R                  $ )zA 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   BufferedSocket.family  s     yyr   c                 .    U R                   R                  $ )a1  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   BufferedSocket.proto  s     yyr   c                 6    U R                   R                  5       $ )au  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   BufferedSocket.fileno%  s     yy!!r   c                    U R                      U R                     SU l        U R                  U l        / U R                  SS& U R
                  R                  5         SSS5        SSS5        g! , (       d  f       N= f! , (       d  f       g= f)aE  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   BufferedSocket.close1  sd     __	'+yy$!		!		!	 !  	 ! _ 	s#   A>AA-A>-
A;	7A>>
Bc                     U R                      U R                     U R                  R                  U5        SSS5        SSS5        g! , (       d  f       N= f! , (       d  f       g= f)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   BufferedSocket.shutdownA  sH     __		""3' !  	 ! _ 	s!   AAA
A	A
A&)	r/   r-   r.   r(   r%   r   r&   r$   r+   r   )#r   r   r   r   r   r   DEFAULT_MAXSIZEr1   r6   r)   r=   rA   rD   rH   rM   rW   ra   rx   rV   r   r   r   r   r   r   r   r   propertyr   r   r   r   r   r   r   r   r   r   r!   r!   `   s    1d &,(6"41
'
  !& &P "( . "( 0 -3F"'Pd '- 5 n  !& *X #$V /''+;        
" r   r!   c                       \ rS rSrSrSrg)ErroriT  zA 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`.
r   Nr   r   r   r   r   r   r   r   r   r   r   T       	r   r   c                       \ rS rSrSrSrg)r^   i_  a<  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`.
r   Nr   r   r   r   r^   r^   _  r   r   r^   c                   0   ^  \ rS rSrSrSU 4S jjrSrU =r$ )r]   ij  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.
c                 b   > SnUb
  USU< S3-  nUb	  USU< 3-  n[         [        U ]  U5        g )Nzmessage exceeded maximum sizez. z bytes readz. Delimiter not found: )superr]   r1   )r
   
bytes_readrl   rv   	__class__s       r   r1   MessageTooLong.__init__p  s=    -!
44C )==Cnd,S1r   r   )NNr   r   r   r   r   r1   r   __classcell__r   s   @r   r]   r]   j  s    
2 2r   r]   c                   0   ^  \ rS rSrSrSU 4S jjrSrU =r$ )rO   iy  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                 j   > SnUb  USUS-  -  -  nU(       a  USU-   -  n[         [        U ]  U5        g )Nzsocket operation timed outz after %sms.i   )r   rO   r1   )r
   r+   extrarv   r   s       r   r1   Timeout.__init__  sA    *>Wt^44C3;Cgt%c*r   r   ) r   r   s   @r   rO   rO   y  s    
+ +r   rO   c                   R    \ rS rSrSr\\4S jrS rS r	S r
S r\\4S jrS	 rS
rg)NetstringSocketi  z
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    [        U5      U l        X l        X0l        [	        [        U5      5      S-   U l        g NrZ   )r!   bsockr+   r(   rL   str_msgsize_maxsize)r
   r$   r+   r(   s       r   r1   NetstringSocket.__init__  s.    #D)
 #CL 1A 5r   c                 6    U R                   R                  5       $ r   )r   r   r	   s    r   r   NetstringSocket.fileno  s    zz  ""r   c                     Xl         g r   r4   r5   s     r   r6   NetstringSocket.settimeout  s    r   c                 <    Xl         U R                  U5      U l        g r   )r(   _calc_msgsize_maxsizer   r@   s     r   rA   NetstringSocket.setmaxsize  s     $ : :7 Cr   c                 0    [        [        U5      5      S-   $ r   )rL   r   r@   s     r   r   %NetstringSocket._calc_msgsize_maxsize  s    3w< 1$$r   c                    U[         L a  U R                  nU[         L a  U R                  nU R                  nOU R	                  U5      nU R
                  R                  SUUS9n [        U5      nXR:  a  [        XR5      eU R
                  R                  U5      nU R
                  R                  S5      S:w  a  [        S5      eU$ ! [         a    [        SU-  5      ef = f)N   :)r+   r(   z4netstring message size must be valid integer, not %rrZ      ,z#expected trailing ',' after message)r   r+   r(   r   r   r   rx   r'   rK   NetstringInvalidSizeNetstringMessageTooLongrV   rM   NetstringProtocolError)r
   r+   r(   msgsize_maxsizesize_prefixrP   payloads          r   read_nsNetstringSocket.read_ns  s    fllGfllG"33O"88AOjj++D4;4C , E	I{#D
 >)$88**&&t,::??1%()NOO  	I& (:<G(H I I	Is   %C C c                     [        U5      nX R                  :  a  [        X R                  5      e[        U5      R	                  S5      S-   U-   S-   nU R
                  R                  U5        g )Nasciir   r   )rL   r(   r   r   encoder   r   )r
   r   rP   rR   s       r   write_nsNetstringSocket.write_ns  sW    7|,,)$==4y(4/'9D@

r   )r   r   r(   r+   N)r   r   r   r   r   r*   r   r1   r   r6   rA   r   r   r   r   r   r   r   r   r   r     s9     &5o 6#D% %f 6r   r   c                       \ rS rSrSrSrg)r   i  z=Base class for all of socketutils' Netstring exception types.r   Nr   r   r   r   r   r     s    Cr   r   c                   ,   ^  \ rS rSrSrU 4S jrSrU =r$ )r   i  a6  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                 ,   > [         [        U ]  U5        g r   )r   r   r1   )r
   rv   r   s     r   r1   NetstringInvalidSize.__init__  s    "D237r   r   r   r   s   @r   r   r     s    
8 8r   r   c                   ,   ^  \ rS rSrSrU 4S jrSrU =r$ )r   i  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                 @   > SU< SU< 3n[         [        U ]  U5        g )Nz5netstring message length exceeds configured maxsize: z > )r   r   r1   )r
   rP   r(   rv   r   s       r   r1    NetstringMessageTooLong.__init__  s    !%t5c:r   r   r   r   s   @r   r   r     s    ; ;r   r   )r   rg   rN   	threadingr   rk   object	typeutilsr   r   ImportErrorr*   r   r[   r!   errorr   r^   r]   r+   rO   r   r   r   r   r   r   r   <module>r      s   B"H  	'H-F
  oV oh	FLL 		u 	2U 2+fnne +:f :z	U 	
81 8 ;4 ;}     XFs"   B B5 B21B25CC