
    Mh                        d Z ddlZddlZddlZddlZddl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 ddlmZ ddlmZ ddlmZmZmZ ddlmZ ddlZddlmZmZmZmZmZmZmZm Z m!Z! dd	l"m#Z# ej$        r
dd
lm%Z%m&Z&m'Z'  e dd          Z(ej)        ej*        ej+        ej,        fZ- e.ed          re-ej/        ej0        ej1        fz  Z-e	j2        dk    re-ej3        fz  Z-e	j2        4                    d          Z5 G d de6          Z7 G d de8          Z9 G d de8          Z: G d d          Z; G d d          Z< G d de<          Z= G d de=          Z> G d de<          Z?d efd!Z@dS )"aB  Utility classes to write to and read from non-blocking files and sockets.

Contents:

* `BaseIOStream`: Generic interface for reading and writing.
* `IOStream`: Implementation of BaseIOStream using non-blocking sockets.
* `SSLIOStream`: SSL-aware version of IOStream.
* `PipeIOStream`: Pipe-based IOStream implementation.
    N)Future"future_set_result_unless_cancelled)ioloop)gen_log)ssl_wrap_socket_client_ssl_defaults_server_ssl_defaults)errno_from_exception)	UnionOptional	AwaitableCallablePatternAnyDictTypeVarTuple)TracebackType)DequeListType_IOStreamTypeIOStream)boundWSAECONNRESETdarwinwinc                   :     e Zd ZdZddee         ddf fdZ xZS )StreamClosedErrora  Exception raised by `IOStream` methods when the stream is closed.

    Note that the close callback is scheduled to run *after* other
    callbacks on the stream (to allow for buffered data to be processed),
    so you may see this error before you see the close callback.

    The ``real_error`` attribute contains the underlying error that caused
    the stream to close (if any).

    .. versionchanged:: 4.3
       Added the ``real_error`` attribute.
    N
real_errorreturnc                 X    t                                          d           || _        d S )NzStream is closed)super__init__r    )selfr    	__class__s     P/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/tornado/iostream.pyr$   zStreamClosedError.__init__b   s'    +,,,$    N)__name__
__module____qualname____doc__r   BaseExceptionr$   __classcell__r&   s   @r'   r   r   T   s_         % %8M#: %d % % % % % % % % % %r(   r   c                       e Zd ZdZdS )UnsatisfiableReadErrorzException raised when a read cannot be satisfied.

    Raised by ``read_until`` and ``read_until_regex`` with a ``max_bytes``
    argument.
    Nr*   r+   r,   r-    r(   r'   r2   r2   g   s          	Dr(   r2   c                       e Zd ZdZdS )StreamBufferFullErrorz?Exception raised by `IOStream` methods when the buffer is full.Nr3   r4   r(   r'   r6   r6   q   s        IIIIr(   r6   c                   l    e Zd ZdZddZdefdZdZdee	e
ef         ddfdZd	edefd
Zd	eddfdZdS )_StreamBufferzh
    A specialized buffer that tries to avoid copies when large pieces
    of data are encountered.
    r!   Nc                 R    t          j                    | _        d| _        d| _        d S Nr   )collectionsdeque_buffers
_first_pos_sizer%   s    r'   r$   z_StreamBuffer.__init__{   s+      	 


r(   c                     | j         S r)   )r?   r@   s    r'   __len__z_StreamBuffer.__len__   s
    zr(   i   datac                    t          |          }|| j        k    rAt          |t                    st          |          }| j                            d|f           nk|dk    re| j        r+| j        d         \  }}|pt          |          | j        k    }nd}|r*| j                            dt          |          f           n||z  }| xj        |z  c_        dS )zX
        Append the given piece of data (should be a buffer-compatible object).
        Tr   FN)len_large_buf_threshold
isinstance
memoryviewr=   append	bytearrayr?   )r%   rC   size
is_memviewbnew_bufs         r'   rJ   z_StreamBuffer.append   s     4yy$+++dJ// (!$''M  $....AXX}  $b 1
A$KA$2K(K $$eYt__%=>>>>T	

d



r(   rL   c                    |dk    sJ 	 | j         d         \  }}n# t          $ r t          d          cY S w xY w| j        }|r%t	          j        t          ||||z                      S t          |          |||z            S )zq
        Get a view over at most ``size`` bytes (possibly fewer) at the
        current buffer position.
        r   r(   )r=   
IndexErrorrI   r>   typingcast)r%   rL   rM   rN   poss        r'   peekz_StreamBuffer.peek   s    
 axxxx	# M!,MJ 	# 	# 	#c??"""	# o 	3;z1S3:-=+>???a==sTz!122s    77c                    d|cxk     r| j         k    sn J | xj         |z  c_         | j        }| j        }|r|dk    r|d         \  }}t          |          |z
  |z
  }|dk    r,|                                 |t          |          |z
  z  }d}n0|r||z  }d}n&||z  }t          j        t          |          d|= d}d}|r|dk    |dk    sJ || _        dS )zH
        Advance the current buffer position by ``size`` bytes.
        r   N)r?   r>   r=   rF   popleftrR   rS   rK   )r%   rL   rT   buffersis_largerN   b_remains          r'   advancez_StreamBuffer.advance   s    4%%%%4:%%%%%%

d

o- 	$((!!*KHa1vv}s*H1}}!!!A$ ttK	1--dsd3  	$((  qyyyyr(   r!   N)r*   r+   r,   r-   r$   intrB   rG   r   bytesrK   rI   rJ   rU   r[   r4   r(   r'   r8   r8   u   s         
       
  5	:!=> 4    ,3 3 3 3 3 3"C D      r(   r8   c                      e Zd ZdZ	 	 	 d?dee         dee         dee         ddfdZdeeej	        f         fdZ
d@d	Zd
edefdZdeeef         dee         fdZdee         fdZ	 dAdedee         dee         fdZ	 dAdedee         dee         fdZdBdededee         fdZdBdededee         fdZdee         fdZd
eeef         ddfdZdeeg df                  ddfdZ	 dBdedeeedee         ee         f         f         ddfd Z d@d!Z!defd"Z"defd#Z#defd$Z$d%eddfd&Z%d@d'Z&d(eeej	        f         d)eddfd*Z'dee         fd+Z(d@d,Z)de*fd-Z+d.eddfd/Z,d@d0Z-dee         fd1Z.d2eddfd3Z/dee         fd4Z0deee1f         d.eddfd5Z2d@d6Z3d7edefd8Z4d@d9Z5d@d:Z6d;eddfd<Z7d=edefd>Z8dS )CBaseIOStreama  A utility class to write to and read from a non-blocking file or socket.

    We support a non-blocking ``write()`` and a family of ``read_*()``
    methods. When the operation completes, the ``Awaitable`` will resolve
    with the data read (or ``None`` for ``write()``). All outstanding
    ``Awaitables`` will resolve with a `StreamClosedError` when the
    stream is closed; `.BaseIOStream.set_close_callback` can also be used
    to be notified of a closed stream.

    When a stream is closed due to an error, the IOStream's ``error``
    attribute contains the exception object.

    Subclasses must implement `fileno`, `close_fd`, `write_to_fd`,
    `read_from_fd`, and optionally `get_fd_error`.

    Nmax_buffer_sizeread_chunk_sizemax_write_buffer_sizer!   c                 0   t           j                                        | _        |pd| _        t          |pd| j        dz            | _        || _        d| _        t                      | _
        d| _        d| _        d| _        t                      | _        d| _        d| _        d| _        d| _        d| _        d| _        d| _        d| _        d| _        t3          j                    | _        d| _        d| _        d| _        d| _        d| _         d| _!        dS )a  `BaseIOStream` constructor.

        :arg max_buffer_size: Maximum amount of incoming data to buffer;
            defaults to 100MB.
        :arg read_chunk_size: Amount of data to read at one time from the
            underlying transport; defaults to 64KB.
        :arg max_write_buffer_size: Amount of outgoing data to buffer;
            defaults to unlimited.

        .. versionchanged:: 4.0
           Add the ``max_write_buffer_size`` parameter.  Changed default
           ``read_chunk_size`` to 64KB.
        .. versionchanged:: 5.0
           The ``io_loop`` argument (deprecated since version 4.1) has been
           removed.
        i  @i      Nr   F)"r   IOLoopcurrentio_loopra   minrb   rc   errorrK   _read_buffer_read_buffer_size_user_read_buffer_after_user_read_bufferr8   _write_buffer_total_write_index_total_write_done_index_read_delimiter_read_regex_read_max_bytes_read_bytes_read_partial_read_until_close_read_futurer;   r<   _write_futures_close_callback_connect_future_ssl_connect_future_connecting_state_closed)r%   ra   rb   rc   s       r'   r$   zBaseIOStream.__init__   s   , },,...;)  #?#;eT=QUV=VWW%:"
%KK!"!&'+$*__"#'($##"!&  	  $#
 $(  r(   c                     t                      )z,Returns the file descriptor for this stream.NotImplementedErrorr@   s    r'   filenozBaseIOStream.fileno  s    !###r(   c                     t                      )zCloses the file underlying this stream.

        ``close_fd`` is called by `BaseIOStream` and should not be called
        elsewhere; other users should call `close` instead.
        r   r@   s    r'   close_fdzBaseIOStream.close_fd  s     "###r(   rC   c                     t                      )ziAttempts to write ``data`` to the underlying file.

        Returns the number of bytes written.
        r   r%   rC   s     r'   write_to_fdzBaseIOStream.write_to_fd&  s    
 "###r(   bufc                     t                      )a  Attempts to read from the underlying file.

        Reads up to ``len(buf)`` bytes, storing them in the buffer.
        Returns the number of bytes read. Returns None if there was
        nothing to read (the socket returned `~errno.EWOULDBLOCK` or
        equivalent), and zero on EOF.

        .. versionchanged:: 5.0

           Interface redesigned to take a buffer and return a number
           of bytes instead of a freshly-allocated object.
        r   r%   r   s     r'   read_from_fdzBaseIOStream.read_from_fd-  s     "###r(   c                     dS )a>  Returns information about any error on the underlying file.

        This method is called after the `.IOLoop` has signaled an error on the
        file descriptor, and should return an Exception (such as `socket.error`
        with additional information, or None if no such information is
        available.
        Nr4   r@   s    r'   get_fd_errorzBaseIOStream.get_fd_error<  s	     tr(   regex	max_bytesc                 T   |                                  }t          j        |          | _        || _        	 |                                  n]# t          $ r9}t          j        d|z             | 	                    |           |cY d}~S d}~w |
                    d             xY w|S )a  Asynchronously read until we have matched the given regex.

        The result includes the data that matches the regex and anything
        that came before it.

        If ``max_bytes`` is not None, the connection will be closed
        if more than ``max_bytes`` bytes have been read and the regex is
        not satisfied.

        .. versionchanged:: 4.0
            Added the ``max_bytes`` argument.  The ``callback`` argument is
            now optional and a `.Future` will be returned if it is omitted.

        .. versionchanged:: 6.0

           The ``callback`` argument was removed. Use the returned
           `.Future` instead.

        *Unsatisfiable read, closing connection: %sexc_infoNc                 *    |                                  S r)   	exceptionfs    r'   <lambda>z/BaseIOStream.read_until_regex.<locals>.<lambda>i      q{{}} r(   )_start_readrecompilers   rt   _try_inline_readr2   r   infocloseadd_done_callback)r%   r   r   futurees        r'   read_until_regexzBaseIOStream.read_until_regexF  s    , !!##:e,,(	!!####% 	 	 	LEIJJJJJJ"""MMMMMM	 $$%<%<===s   A 
B%.B	B%	B%	delimiterc                 0   |                                  }|| _        || _        	 |                                  n]# t          $ r9}t          j        d|z             |                     |           |cY d}~S d}~w |                    d             xY w|S )an  Asynchronously read until we have found the given delimiter.

        The result includes all the data read including the delimiter.

        If ``max_bytes`` is not None, the connection will be closed
        if more than ``max_bytes`` bytes have been read and the delimiter
        is not found.

        .. versionchanged:: 4.0
            Added the ``max_bytes`` argument.  The ``callback`` argument is
            now optional and a `.Future` will be returned if it is omitted.

        .. versionchanged:: 6.0

           The ``callback`` argument was removed. Use the returned
           `.Future` instead.
        r   r   Nc                 *    |                                  S r)   r   r   s    r'   r   z)BaseIOStream.read_until.<locals>.<lambda>  r   r(   )	r   rr   rt   r   r2   r   r   r   r   )r%   r   r   r   r   s        r'   
read_untilzBaseIOStream.read_untilm  s    ( !!##((		!!####% 	 	 	LEIJJJJJJ"""MMMMMM	$$%<%<===s   9 
B.A71B7BF	num_bytespartialc                     |                                  }t          |t          j                  sJ || _        || _        	 |                                  n#  |                    d             xY w|S )aJ  Asynchronously read a number of bytes.

        If ``partial`` is true, data is returned as soon as we have
        any bytes to return (but never more than ``num_bytes``)

        .. versionchanged:: 4.0
            Added the ``partial`` argument.  The callback argument is now
            optional and a `.Future` will be returned if it is omitted.

        .. versionchanged:: 6.0

           The ``callback`` and ``streaming_callback`` arguments have
           been removed. Use the returned `.Future` (and
           ``partial=True`` for ``streaming_callback``) instead.

        c                 *    |                                  S r)   r   r   s    r'   r   z)BaseIOStream.read_bytes.<locals>.<lambda>  r   r(   )r   rH   numbersIntegralru   rv   r   r   )r%   r   r   r   s       r'   
read_byteszBaseIOStream.read_bytes  s    " !!##)W%566666$$	!!####	$$%<%<===s    A A.c                    |                                  }| j        }t          |          }||k    r8t          | j                  d|         |dd<   | j        d|= | j        | _        n'|dk    r!t          | j                  dd         |d|<   d| _        || _        || _        || _        || _        	 | 	                                 n#  |
                    d             xY w|S )a  Asynchronously read a number of bytes.

        ``buf`` must be a writable buffer into which data will be read.

        If ``partial`` is true, the callback is run as soon as any bytes
        have been read.  Otherwise, it is run when the ``buf`` has been
        entirely filled with read data.

        .. versionadded:: 5.0

        .. versionchanged:: 6.0

           The ``callback`` argument was removed. Use the returned
           `.Future` instead.

        Nr   Tc                 *    |                                  S r)   r   r   s    r'   r   z(BaseIOStream.read_into.<locals>.<lambda>  r   r(   )r   rl   rF   rI   rk   rn   rm   ru   rv   r   r   )r%   r   r   r   available_bytesns         r'   	read_intozBaseIOStream.read_into  s   " !!## 0HHa 1222A26CF!"1"%+/+<D((q  $.t/@$A$A!!!$DC  !
 "&!0$	!!####	$$%<%<===s   4C	 	C"c                     |                                  }|                                 r|                     | j                   |S d| _        	 |                                  n#  |                    d             xY w|S )a  Asynchronously reads all data from the socket until it is closed.

        This will buffer all available data until ``max_buffer_size``
        is reached. If flow control or cancellation are desired, use a
        loop with `read_bytes(partial=True) <.read_bytes>` instead.

        .. versionchanged:: 4.0
            The callback argument is now optional and a `.Future` will
            be returned if it is omitted.

        .. versionchanged:: 6.0

           The ``callback`` and ``streaming_callback`` arguments have
           been removed. Use the returned `.Future` (and `read_bytes`
           with ``partial=True`` for ``streaming_callback``) instead.

        Tc                 *    |                                  S r)   r   r   s    r'   r   z/BaseIOStream.read_until_close.<locals>.<lambda>  r   r(   )r   closed_finish_readrl   rw   r   r   r%   r   s     r'   read_until_closezBaseIOStream.read_until_close  s    $ !!##;;== 	d4555M!%	!!####	$$%<%<===s   A" "A;zFuture[None]c                    |                                   |rt          |t                    r"t          |                              d          }| j        <t          | j                  t          |          z   | j        k    rt          d          | j                            |           | xj	        t          |          z  c_	        t                      }|                    d            | j                            | j	        |f           | j        sN|                                  | j        r|                     | j        j                   |                                  |S )a:  Asynchronously write the given data to this stream.

        This method returns a `.Future` that resolves (with a result
        of ``None``) when the write has been completed.

        The ``data`` argument may be of type `bytes` or `memoryview`.

        .. versionchanged:: 4.0
            Now returns a `.Future` if no callback is given.

        .. versionchanged:: 4.5
            Added support for `memoryview` arguments.

        .. versionchanged:: 6.0

           The ``callback`` argument was removed. Use the returned
           `.Future` instead.

        BNz!Reached maximum write buffer sizec                 *    |                                  S r)   r   r   s    r'   r   z$BaseIOStream.write.<locals>.<lambda>  s    1;;== r(   )_check_closedrH   rI   rS   rc   rF   ro   r6   rJ   rp   r   r   ry   r}   _handle_write_add_io_staterh   WRITE_maybe_add_error_listener)r%   rC   r   s      r'   writezBaseIOStream.write  sP   ( 	 
	1$
++ 2!$'',,S11*6*++c$ii7$:TTT+,OPPP%%d+++##s4yy0##  !8!8999""D$;V#DEEE 	-   ! 7""4<#5666**,,,r(   callbackc                 <    || _         |                                  dS )a  Call the given callback when the stream is closed.

        This mostly is not necessary for applications that use the
        `.Future` interface; all outstanding ``Futures`` will resolve
        with a `StreamClosedError` when the stream is closed. However,
        it is still useful as a way to signal that the stream has been
        closed while no other read or write is in progress.

        Unlike other callback-based interfaces, ``set_close_callback``
        was not removed in Tornado 6.0.
        N)rz   r   )r%   r   s     r'   set_close_callbackzBaseIOStream.set_close_callback!  s$      (&&(((((r(   r   zOptional[Type[BaseException]]c                    |                                  s3|rot          |t                    r|d         | _        nLt          |t                    r|| _        n/t          j                    }t          |          r|d         | _        | j        r"d| _        | 	                    | j
                   nD| j        =	 |                                 }||                     |           n# t          $ r Y nw xY w| j        3| j                            |                                            d| _        |                                  d| _        |                                  dS )zClose this stream.

        If ``exc_info`` is true, set the ``error`` attribute to the current
        exception from `sys.exc_info` (or if ``exc_info`` is a tuple,
        use that instead of `sys.exc_info`).
           FNT)r   rH   tuplerj   r.   sysr   anyrw   r   rl   rx   _find_read_pos_read_from_bufferr2   r~   rh   remove_handlerr   r   r   _signal_closed)r%   r   rT   s      r'   r   zBaseIOStream.close0  s_   & {{}} 	  1h.. 1!)!DJJ-88 1!)DJJ"|~~H8}} 1%-a[
% 4).&!!$"89999".4--//C ..s333	 .   D
 {&++DKKMM:::"MMOOODLs   8C$ $
C10C1c                 `   g }| j         !|                    | j                    d | _         |d | j        D             z  }| j                                         | j        !|                    | j                   d | _        |D ]h}|                                s(|                    t          | j                             	 |	                                 T# t          j        $ r Y ew xY w| j        | j                                        sM| j         | j                            | j                   n&| j                            t                                 | j        	                                 d | _        | j        (| j        }d | _        | j                            |           d | _        d S )Nc                     g | ]\  }}|S r4   r4   ).0_r   s      r'   
<listcomp>z/BaseIOStream._signal_closed.<locals>.<listcomp>e  s    @@@yq&F@@@r(   r    )rx   rJ   ry   clearr{   doneset_exceptionr   rj   r   asyncioCancelledErrorr|   rz   rh   add_callbackro   )r%   futuresr   cbs       r'   r   zBaseIOStream._signal_closed`  s   (NN4,--- $D@@D,?@@@@!!###+NN4/000#'D  		 		F;;== O$$%6$*%M%M%MNNN  """")   #/ +0022 P:),::4:FFFF,::;L;N;NOOO$..000'+D$+%B#'D L%%b))) "s   CC('C(c                     | j         duS )z=Returns ``True`` if we are currently reading from the stream.N)rx   r@   s    r'   readingzBaseIOStream.reading  s     ,,r(   c                 *    t          | j                  S )z;Returns ``True`` if we are currently writing to the stream.)boolro   r@   s    r'   writingzBaseIOStream.writing  s    D&'''r(   c                     | j         S )z/Returns ``True`` if the stream has been closed.)r   r@   s    r'   r   zBaseIOStream.closed  s
    |r(   valuec                     dS )a  Sets the no-delay flag for this stream.

        By default, data written to TCP streams may be held for a time
        to make the most efficient use of bandwidth (according to
        Nagle's algorithm).  The no-delay flag requests that data be
        written as soon as possible, even if doing so would consume
        additional bandwidth.

        This flag is currently defined only for TCP-based ``IOStreams``.

        .. versionadded:: 3.1
        Nr4   )r%   r   s     r'   set_nodelayzBaseIOStream.set_nodelay  s	     	r(   c                     t                      r)   r   r@   s    r'   _handle_connectzBaseIOStream._handle_connect  s    !###r(   fdeventsc                    |                                  rt          j        d|           d S 	 | j        r|                                  |                                  rd S || j        j        z  r|                                  |                                  rd S || j        j        z  r| 	                                 |                                  rd S || j        j
        z  r:|                                 | _        | j                            | j                   d S | j        j
        }|                                 r|| j        j        z  }|                                 r|| j        j        z  }|| j        j
        k    r| j        dk    r|| j        j        z  }|| j        k    rL| j        
J d            || _        | j                            |                                 | j                   d S d S # t*          $ r8}t          j        d|z             |                     |           Y d }~d S d }~wt.          $ r2}t          j        dd           |                     |            d }~ww xY w)NzGot events for closed stream %sr   z4shouldn't happen: _handle_events without self._stater   r   z'Uncaught exception, closing connection.T)r   r   warningr}   r   rh   READ_handle_readr   r   ERRORr   rj   r   r   r   r   rl   r~   update_handlerr   r2   r   	Exception)r%   r   r   stater   s        r'   _handle_eventszBaseIOStream._handle_events  s   ;;== 	O=rBBBF/	 '
 $$&&&{{}} )) $!!###{{}} ** %""$$${{}} ** !..00
 ))$*555L&E||~~ +**||~~ ,++***t/E/J/J
 **##K++I ,++#++DKKMM4;GGGGG $# & 	# 	# 	#LEIJJJJJJ""""""""" 	 	 	MCdSSSSJJJ"""	s=   /G. 7G. 7G. AG. CG. .
I*8-H++I*8-I%%I*c                    | j         | j         }n(| j        | j        }n|                                 rd }nd}d}|                                 sh|                                 dk    rnO|| j        |k    rnA| j        |k    r"|                                 }||S | j        dz  }|                                 h|                                 S )Nr   re   )ru   rt   r   r   _read_to_bufferrl   r   )r%   target_bytesnext_find_posrT   s       r'   _read_to_buffer_loopz!BaseIOStream._read_to_buffer_loop  s    '+LL!-/LL\\^^ 	  LLL++-- 	; ##%%** 'D,Bl,R,R %66))++?J $ 6 :1 ++-- 	;2 ""$$$r(   c                     	 |                                  }n^# t          $ r  t          j        $ r  t          $ r8}t          j        d|z             |                     |           Y d }~d S d }~ww xY w||                     |           d S d S )Nzerror on read: %sr   )	r   r2   r   r   r   r   r   r   r   )r%   rT   r   s      r'   r   zBaseIOStream._handle_read  s    		++--CC% 	 	 	% 	 	 	 	 	 	O/!3444JJJ"""FFFFF	 ?""3''''' ?s    #A2-A--A2c                     | j         %|                                  | j         
J d            t                      | _         | j         S )NzAlready reading)rx   r   r   r@   s    r'   r   zBaseIOStream._start_read  sL    ("    $,,.?,,,"HH  r(   rL   c                 8   | j         rD| j        pt                      | _        d | _        t	          | j                  | _        d| _         |}n|                     |          }| j        | j        }d | _        t          ||           | 	                                 d S NF)
rm   rn   rK   rk   rF   rl   _consumerx   r   r   )r%   rL   resultr   s       r'   r   zBaseIOStream._finish_read(  s    ! 	) $ < K	D+/D(%():%;%;D"%*D"FF]]4((F(&F $D.vv>>>&&(((((r(   c                 V   |                                  }||                     |           dS |                                  |                                 }||                     |           dS |                                 s&|                     t          j        j                   dS dS )a  Attempt to complete the current read operation from buffered data.

        If the read can be completed without blocking, schedules the
        read callback on the next IOLoop iteration; otherwise starts
        listening for reads on the socket.
        N)	r   r   r   r   r   r   r   rf   r   r%   rT   s     r'   r   zBaseIOStream._try_inline_read7  s     !!##?""3'''F''))?""3'''F {{}} 	3v}122222	3 	3r(   c                    	 	 	 | j         r"t          | j                  | j        d         }nt	          | j                  }|                     |          }n[# t          $ rN}|                     |          r| 	                    |           Y d}~~dS | 	                    |            d}~ww xY w	 |	 ~dS |dk    r| 	                                 	 ~dS | j         s%| xj        t          |          d|         z  c_        | xj        |z  c_        ~n# ~w xY w| j        | j
        k    r7t          j        d           | 	                                 t          d          |S )a  Reads from the socket and appends the result to the read buffer.

        Returns the number of bytes read.  Returns 0 if there is nothing
        to read (i.e. the read returns EWOULDBLOCK or equivalent).  On
        error closes the socket and raises an exception.
        TNr   r   z Reached maximum read buffer size)rm   rI   rk   rl   rK   rb   r   OSError_is_connresetr   ra   r   rj   r6   )r%   r   
bytes_readr   s       r'   r   zBaseIOStream._read_to_bufferM  s    	- >():;; 244 ((<==!%!2!23!7!7JJ 	 	 	))!,, $ 

A
...#ttt  JJJ***	 !  q

  ) B!!Z__[j[%AA!!""j0"" GGGG!D$888M<===JJLLL'(JKKKsG   D AA D 
B/!+B*D B**B//D 9D <D DrT   c                 h    dx| _         x| _        | _        d| _        |                     |           dS )zAttempts to complete the currently-pending read from the buffer.

        The argument is either a position in the read buffer or None,
        as returned by _find_read_pos.
        NF)ru   rr   rs   rv   r   r  s     r'   r   zBaseIOStream._read_from_buffer{  s@     FJII4/$2B"#r(   c                    | j         >| j        | j         k    s| j        r'| j        dk    rt          | j         | j                  }|S | j        | j        r|| j                            | j                  }|dk    r7t          | j                  }|                     | j        ||z              ||z   S |                     | j        | j                   n| j	        y| j        rr| j	        
                    | j                  }|1|                                }|                     | j	        |           |S |                     | j	        | j                   dS )zAttempts to find a position in the read buffer that satisfies
        the currently-pending read.

        Returns a position in the buffer if the current read can be satisfied,
        or None if it cannot.
        Nr   rE   )ru   rl   rv   ri   rr   rk   findrF   _check_max_bytesrs   searchend)r%   r   locdelimiter_lenms        r'   r   zBaseIOStream._find_read_pos  s`    '"d&666" 7'+'='A'AD,d.DEEI!-   T',,T-ABB"99$'(<$=$=M))$*>m@STTT..%%d&:D<RSSS)  P$++D,=>>=%%''C))$*:C@@@J%%d&68NOOOtr(   c                 `    | j         $|| j         k    rt          d|| j         fz            d S d S )Nz&delimiter %r not found within %d bytes)rt   r2   )r%   r   rL   s      r'   r	  zBaseIOStream._check_max_bytes  sK    +t7K0K0K(8d234   ,+0K0Kr(   c                    	 t          | j                  }|sn|dk    sJ 	 t          rd}|                     | j                            |                    }|dk    rn| j                            |           | xj        |z  c_        nv# t          $ r Y nkt          $ r^}| 	                    |          s(t          j        d|                                 |           |                     |           Y d }~d S d }~ww xY w| j        rO| j        d         \  }}|| j        k    rd S | j                                         t!          |d            | j        Md S d S )NTr   i   zWrite error on %s: %sr   )rF   ro   _WINDOWSr   rU   r[   rq   BlockingIOErrorr  r  r   r   r   r   ry   rW   r   )r%   rL   r   r   indexr   s         r'   r   zBaseIOStream._handle_write  s   	t)**D !8888 & &D ,,T-?-D-DT-J-JKK	>>"**9555,,	9,,,"      ))!,, O O$;T[[]]ANNN

A
&&&+	< ! 	= /2ME6t333''))).vt<<< ! 	= 	= 	= 	= 	=s$   <B
 *B
 

C=	C=AC88C=r  c                     |dk    rdS || j         k    sJ t          | j                  d |                                         }| xj         |z  c_         | j        d |= |S )Nr   r(   )rl   rI   rk   tobytes)r%   r  rN   s      r'   r   zBaseIOStream._consume  sq    !883d,,,,,)**4C4099;;#%dsd#r(   c                 X    |                                  rt          | j                  d S )Nr   )r   r   rj   r@   s    r'   r   zBaseIOStream._check_closed  s/    ;;== 	;#tz::::	; 	;r(   c                     | j         | j         t          j        j        k    rN|                                 s8| j        dk    r1| j        ,|                     t          j        j                   d S d S d S d S d S r:   )	r~   r   rf   r   r   rl   rz   r   r   r@   s    r'   r   z&BaseIOStream._maybe_add_error_listener  s     ;$+1D"D"DKKMM7*a//(4""6=#5666667 7 #E"D 0/44r(   r   c                    |                                  rdS | j        St          j        j        |z  | _        | j                            |                                 | j        | j                   dS | j        |z  sC| j        |z  | _        | j        	                    |                                 | j                   dS dS )a  Adds `state` (IOLoop.{READ,WRITE} flags) to our event handler.

        Implementation notes: Reads and writes have a fast path and a
        slow path.  The fast path reads synchronously from socket
        buffers, while the slow path uses `_add_io_state` to schedule
        an IOLoop callback.

        To detect closed connections, we must have called
        `_add_io_state` at some point, but we want to delay this as
        much as possible so we don't have to set an `IOLoop.ERROR`
        listener that will be overwritten by the next slow-path
        operation. If a sequence of fast-path ops do not end in a
        slow-path op, (e.g. for an @asynchronous long-poll request),
        we must add the error handler.

        TODO: reevaluate this now that callbacks are gone.

        N)
r   r~   r   rf   r   rh   add_handlerr   r   r   )r%   r   s     r'   r   zBaseIOStream._add_io_state  s    & ;;== 	F; --5DKL$$T[[]]D4GUUUUUu$ 	D+-DKL''t{CCCCC	D 	Dr(   excc                 p    t          |t          j        t          f          ot	          |          t
          v S )zfReturn ``True`` if exc is ECONNRESET or equivalent.

        May be overridden in subclasses.
        )rH   socketrj   IOErrorr
   _ERRNO_CONNRESET)r%   r  s     r'   r  zBaseIOStream._is_connreset  s3     sV\7344 >$S))-==	
r(   )NNNr\   r)   )F)9r*   r+   r,   r-   r   r]   r$   r   r   _Selectabler   r   rI   r   rK   r   r   r   r^   r   r   r   r   r   r   r   r   r   r   r.   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r	  r   r   r   r   r   r  r4   r(   r'   r`   r`      s        & *.)-/3	7 7!#7 "#7  (}	7
 
7 7 7 7r$c6#556 $ $ $ $$ $ $ $$
 $s $ $ $ $$i&; < $# $ $ $ $hy1     8<% %%'/}%	5	% % % %P <@! !!+3C=!	5	! ! ! !F C $ 9UCS    8+ +Y + +)C. + + + +Z)E"2    <(%z 12 (~ ( ( ( (T)8HRX4F+G )D ) ) ) )4 . ./'')	
. 
. . . .`%" %" %" %"N- - - - -( ( ( ( (     $    $ $ $ $3sF,>'>!? 3 3QU 3 3 3 3j'%hsm '% '% '% '%R( ( ( (!V ! ! ! !.) ) ) ) ) )3 3 3 3,,# , , , ,\S T    % % % % %N%w*? s t    $= $= $= $=L	C 	E 	 	 	 	; ; ; ;7 7 7 7D3 D4 D D D D:
 
4 
 
 
 
 
 
r(   r`   c            
       l    e Zd ZdZdej        dededdf fdZdeee	j
        f         fdZdd	Zdee         fd
Zdeeef         dee         fdZdedefdZ	 ddededee         ddfdZ	 	 ddedeeeeef         ej        f                  dee         ded         fdZddZdeddfdZ xZS )r   az  Socket-based `IOStream` implementation.

    This class supports the read and write methods from `BaseIOStream`
    plus a `connect` method.

    The ``socket`` parameter may either be connected or unconnected.
    For server operations the socket is the result of calling
    `socket.accept <socket.socket.accept>`.  For client operations the
    socket is created with `socket.socket`, and may either be
    connected before passing it to the `IOStream` or connected with
    `IOStream.connect`.

    A very simple (and broken) HTTP client using this class:

    .. testcode::

        import socket
        import tornado

        async def main():
            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0)
            stream = tornado.iostream.IOStream(s)
            await stream.connect(("friendfeed.com", 80))
            await stream.write(b"GET / HTTP/1.0\r\nHost: friendfeed.com\r\n\r\n")
            header_data = await stream.read_until(b"\r\n\r\n")
            headers = {}
            for line in header_data.split(b"\r\n"):
                parts = line.split(b":")
                if len(parts) == 2:
                    headers[parts[0].strip()] = parts[1].strip()
            body_data = await stream.read_bytes(int(headers[b"Content-Length"]))
            print(body_data)
            stream.close()

        if __name__ == '__main__':
            asyncio.run(main())

    r  argskwargsr!   Nc                 |    || _         | j                             d            t                      j        |i | d S r   )r  setblockingr#   r$   )r%   r  r!  r"  r&   s       r'   r$   zIOStream.__init__G  sB    &&&$)&)))))r(   c                     | j         S r)   )r  r@   s    r'   r   zIOStream.filenoL  s
    {r(   c                 F    | j                                          d | _         d S r)   )r  r   r@   s    r'   r   zIOStream.close_fdO  s!    r(   c                     | j                             t           j        t           j                  }t          j        |t          j        |                    S r)   )r  
getsockopt
SOL_SOCKETSO_ERRORrj   osstrerror)r%   errnos     r'   r   zIOStream.get_fd_errorS  s:    &&v'8&/JJ|E2;u#5#5666r(   r   c                     	 | j                             |t          |                    ~S # t          $ r Y ~d S w xY w# ~w xY wr)   )r  	recv_intorF   r  r   s     r'   r   zIOStream.read_from_fdW  s^    	;((c#hh77   	 	 		 GGGGs   '+ 
:= := A rC   c                 F    	 | j                             |          ~S # ~w xY wr)   )r  sendr   s     r'   r   zIOStream.write_to_fd_  s,    	;##D)) HHHH     r%   addressserver_hostnamezFuture[_IOStreamType]c                    d| _         t                      }t          j        d|          | _        	 | j                            |           ni# t          $ r Y n]t          $ rQ}|-t          j
        d| j                                        |           |                     |           |cY d}~S d}~ww xY w|                     | j        j                   |S )a  Connects the socket to a remote address without blocking.

        May only be called if the socket passed to the constructor was
        not previously connected.  The address parameter is in the
        same format as for `socket.connect <socket.socket.connect>` for
        the type of socket passed to the IOStream constructor,
        e.g. an ``(ip, port)`` tuple.  Hostnames are accepted here,
        but will be resolved synchronously and block the IOLoop.
        If you have a hostname instead of an IP address, the `.TCPClient`
        class is recommended instead of calling this method directly.
        `.TCPClient` will do asynchronous DNS resolution and handle
        both IPv4 and IPv6.

        If ``callback`` is specified, it will be called with no
        arguments when the connection is completed; if not this method
        returns a `.Future` (whose result after a successful
        connection will be the stream itself).

        In SSL mode, the ``server_hostname`` parameter will be used
        for certificate validation (unless disabled in the
        ``ssl_options``) and SNI.

        Note that it is safe to call `IOStream.write
        <BaseIOStream.write>` while the connection is pending, in
        which case the data will be written as soon as the connection
        is ready.  Calling `IOStream` read methods before the socket is
        connected works on some platforms but is non-portable.

        .. versionchanged:: 4.0
            If no callback is given, returns a `.Future`.

        .. versionchanged:: 4.2
           SSL certificates are validated by default; pass
           ``ssl_options=dict(cert_reqs=ssl.CERT_NONE)`` or a
           suitably-configured `ssl.SSLContext` to the
           `SSLIOStream` constructor to disable.

        .. versionchanged:: 6.0

           The ``callback`` argument was removed. Use the returned
           `.Future` instead.

        TzFuture[IOStream]NConnect error on fd %s: %sr   )r}   r   rR   rS   r{   r  connectr  r  r   r   r   r   r   rh   r   )r%   r3  r4  r   r   s        r'   r7  zIOStream.connectg  s    \  %{+=vFF	K(((( 	 	 	 D 	 	 	
 ~ <dk>P>P>R>RTUVVVJJJ"""MMMMMM	 	4<-...s$   A 
B2	B2!AB-'B2-B2server_sidessl_optionsSSLIOStreamc                    | j         s#| j        s| j        s| j        s| j        s| j        rt          d          ||rt          }nt          }| j	        }| j
                            |           d| _	        t          ||||d          }| j        }d| _        t                      }t          ||          }|                    |           ||_        | j        |_        | j        |_        |S )a  Convert this `IOStream` to an `SSLIOStream`.

        This enables protocols that begin in clear-text mode and
        switch to SSL after some initial negotiation (such as the
        ``STARTTLS`` extension to SMTP and IMAP).

        This method cannot be used if there are outstanding reads
        or writes on the stream, or if there is any data in the
        IOStream's buffer (data in the operating system's socket
        buffer is allowed).  This means it must generally be used
        immediately after reading or writing the last clear-text
        data.  It can also be used immediately after connecting,
        before any reads or writes.

        The ``ssl_options`` argument may be either an `ssl.SSLContext`
        object or a dictionary of keyword arguments for the
        `ssl.SSLContext.wrap_socket` function.  The ``server_hostname`` argument
        will be used for certificate validation unless disabled
        in the ``ssl_options``.

        This method returns a `.Future` whose result is the new
        `SSLIOStream`.  After this method has been called,
        any other operation on the original stream is undefined.

        If a close callback is defined on this stream, it will be
        transferred to the new stream.

        .. versionadded:: 4.0

        .. versionchanged:: 4.2
           SSL certificates are validated by default; pass
           ``ssl_options=dict(cert_reqs=ssl.CERT_NONE)`` or a
           suitably-configured `ssl.SSLContext` to disable.
        z+IOStream is not idle; cannot convert to SSLNF)r4  r8  do_handshake_on_connect)r9  )rx   ry   r{   r   rk   ro   
ValueErrorr	   r   r  rh   r   r   rz   r   r:  r   r|   ra   rb   )r%   r8  r9  r4  r  orig_close_callbackr   
ssl_streams           r'   	start_tlszIOStream.start_tls  s,   R 	L"	L #	L |		L
  	L !	L JKKK 322##F+++ +#$)
 
 
 #2# [AAA
%%&9:::)/
&%)%9
"%)%9
"r(   c                 D   	 | j                             t           j        t           j                  }n6# t          $ r)}t          |          t          j        k    rd}Y d }~nd }~ww xY w|dk    rt          j        |t          j
        |                    | _        | j        =t          j        d| j                                         t          j        |                    |                                  d S | j        | j        }d | _        t#          ||            d| _        d S )Nr   r6  F)r  r(  r)  r*  r  r
   r-  ENOPROTOOPTrj   r+  r,  r{   r   r   r   	errorcoder   r   r}   )r%   errr   r   s       r'   r   zIOStream._handle_connect  s   	+(():FOLLCC 	 	 	 $A&&%*;;;		
 !88c2;s+;+;<<DJ
 #+0K&&((OC(  
 JJLLLF+)F#'D .vt<<< s   /2 
A%A  A%r   c                 `   | j         | j         j        t           j        t           j        fv r	 | j                             t           j        t           j        |rdnd           d S # t          $ r<}|j        t          j	        k    r| 
                    |          s Y d }~d S Y d }~d S d }~ww xY wd S d S )Nr   r   )r  familyAF_INETAF_INET6
setsockoptIPPROTO_TCPTCP_NODELAYr  r-  EINVALr  )r%   r   r   s      r'   r   zIOStream.set_nodelay  s    ;"t{'9NO>
 (
 (
	&&&(:<MAAA         7el**43E3Ea3H3H* +***********	 #" (
 (
s   4A# #
B)-+B$$B)r\   r)   )NN) r*   r+   r,   r-   r  r   r$   r   r]   r   r  r   r   r   r   r   rK   rI   r   r   r   strr7  r   r   ssl
SSLContextr   r@  r   r   r/   r0   s   @r'   r   r     s       % %N*v} *S *C *D * * * * * *
c6#556       7hy1 7 7 7 7i&; < #    
 s     MQA AA&)A<DSMA	 A A A AL HL)-	J JJ eDcNCN$BCDJ "#	J
 
=	!J J J JX! ! ! !8 $        r(   c                       e Zd ZdZdZdededdf fdZdef fdZdef fdZ	dd	Z
dd
Zd fdZd fdZ	 ddedee         ddf fdZd fdZddZdedefdZdeeef         dee         fdZdedef fdZ xZS )r:  a~  A utility class to write to and read from a non-blocking SSL socket.

    If the socket passed to the constructor is already connected,
    it should be wrapped with::

        ssl.SSLContext(...).wrap_socket(sock, do_handshake_on_connect=False, **kwargs)

    before constructing the `SSLIOStream`.  Unconnected sockets will be
    wrapped when `IOStream.connect` is finished.
    Nr!  r"  r!   c                 F   |                     dt                    | _         t                      j        |i | d| _        d| _        d| _        d| _        	 | j	        
                                 |                     | j        j                   dS # t          $ r Y dS w xY w)zThe ``ssl_options`` keyword argument may either be an
        `ssl.SSLContext` object or a dictionary of keywords arguments
        for `ssl.SSLContext.wrap_socket`
        r9  TFN)popr   _ssl_optionsr#   r$   _ssl_accepting_handshake_reading_handshake_writing_server_hostnamer  getpeernamer   rh   r   r  )r%   r!  r"  r&   s      r'   r$   zSSLIOStream.__init__1  s    
 #JJ}6JKK$)&)))""'"' $	3K##%%% t|122222  	 	 	DD	s   B 
B B c                 R    | j         pt                                                      S r)   )rU  r#   r   r%   r&   s    r'   r   zSSLIOStream.readingH      &;%''//*;*;;r(   c                 R    | j         pt                                                      S r)   )rV  r#   r   rZ  s    r'   r   zSSLIOStream.writingK  r[  r(   c                 H   	 d| _         d| _        | j                                         d| _        t
          j        sJ |                                  d S # t
          j        $ r1}|j	        d         t
          j
        k    rd| _         Y d }~d S |j	        d         t
          j        k    rd| _        Y d }~d S |j	        d         t
          j        t
          j        fv r|                     |          cY d }~S |j	        d         t
          j        t
          j        fv rv	 | j                                        }n# t$          $ r d}Y nw xY wt'          j        d| j                                        ||           |                     |          cY d }~S  d }~wt,          $ r\}|                     |          s&|j	        d         dt0          j        t0          j        fv r|                     |          cY d }~S  d }~wt6          $ r }|                     |          cY d }~S d }~ww xY w)NFr   Tr   z(not connected)zSSL Error on %s %s: %s)rU  rV  r  do_handshakerT  rN  HAS_SNI_finish_ssl_connectSSLErrorr!  SSL_ERROR_WANT_READSSL_ERROR_WANT_WRITESSL_ERROR_EOFSSL_ERROR_ZERO_RETURNr   SSL_ERROR_SSLSSL_ERROR_SYSCALLrX  r   r   r   r   r  r  r-  EBADFENOTCONNAttributeError)r%   rD  peers      r'   _do_ssl_handshakezSSLIOStream._do_ssl_handshakeN  su   /	'&+D#&+D#K$$&&&P #(D ;$$&&&&&W | 	 	 	x{c555*.'! 888*.'!!2C4M NNNzz3z////////!!2C4I JJJ-;2244DD  - - -,DDD-,dk.@.@.B.BD#   zz3z//////// 	 	 	 !!#&& 0#(1+: + +
 zz3z//////// 	, 	, 	, ::s:++++++++		,s   'A H!$"F"F4:F.H!4%FD43F4E FEAF	H!FH!AG4-H!3G44H!HH!H!c                 T    | j          | j         }d | _         t          ||            d S d S r)   )r|   r   r   s     r'   r`  zSSLIOStream._finish_ssl_connect  s9    #/-F'+D$.vt<<<<< 0/r(   c                     | j         r|                                  d S t                                                       d S r)   )rT  rl  r#   r   rZ  s    r'   r   zSSLIOStream._handle_read  sA     	""$$$Fr(   c                     | j         r|                                  d S t                                                       d S r)   )rT  rl  r#   r   rZ  s    r'   r   zSSLIOStream._handle_write  sA     	""$$$Fr(   r3  r4  Future[SSLIOStream]c                     || _         t                                          |          }|                    d            |                                 S )Nc                 *    |                                  S r)   r   r   s    r'   r   z%SSLIOStream.connect.<locals>.<lambda>  s     r(   )rW  r#   r7  r   wait_for_handshake)r%   r3  r4  futr&   s       r'   r7  zSSLIOStream.connect  sN     !0 ggoog&&55666&&(((r(   c                 P   t                                                       |                                 rd S | j                            | j                   | j        }|J d | _        t          | j        | j        | j	        dd          | _        | 
                    |           d S )NF)r4  r<  r8  )r#   r   r   rh   r   r  r~   r   rS  rW  r   )r%   	old_stater&   s     r'   r   zSSLIOStream._handle_connect  s    !!!;;== 	F 	##DK000K	$$$%K 1$)
 
 
 	9%%%%%r(   c                     | j         t          d          t                      x}| _         | j        s|                                  |S )av  Wait for the initial SSL handshake to complete.

        If a ``callback`` is given, it will be called with no
        arguments once the handshake is complete; otherwise this
        method returns a `.Future` which will resolve to the
        stream itself after the handshake is complete.

        Once the handshake is complete, information such as
        the peer's certificate and NPN/ALPN selections may be
        accessed on ``self.socket``.

        This method is intended for use on server-side streams
        or after using `IOStream.start_tls`; it should not be used
        with `IOStream.connect` (which already waits for the
        handshake to complete). It may only be called once per stream.

        .. versionadded:: 4.2

        .. versionchanged:: 6.0

           The ``callback`` argument was removed. Use the returned
           `.Future` instead.

        NzAlready waiting)r|   RuntimeErrorr   rT  r`  r   s     r'   rs  zSSLIOStream.wait_for_handshake  sO    2 #/0111,2HH4)" 	'$$&&&r(   rC   c                    t          |          dz	  rt          |          d d         }	 | j                            |          ~S # t          j        $ r(}|j        d         t          j        k    rY d }~~dS  d }~ww xY w# ~w xY wN   i   @r   )rF   rI   r  r1  rN  ra  r!  rc  )r%   rC   r   s      r'   r   zSSLIOStream.write_to_fd  s     t99? 	/d##IgI.D	;##D))  | 		 		 		vayC444 qqq
 	 		 HHHHs/   A A=A80B  7A88A==B   Br   c                 Z   	 | j         r	 ~d S t          |          dz	  rt          |          d d         }	 | j                            |t          |                    ~S # t
          j        $ r(}|j        d         t
          j        k    rY d }~~d S  d }~wt          $ r Y ~d S w xY w# ~w xY wrz  )
rT  rF   rI   r  r/  rN  ra  r!  rb  r  r%   r   r   s      r'   r   zSSLIOStream.read_from_fd  s    	"  $  3xx2~ 1 ooii0
{,,S#c((;;  <    6!9 777444 	 "    GGGGsE   B' )B' 'A   B$/B
B' BB$B' #B$$B' 'B*r   c                     t          |t          j                  r|j        d         t          j        k    rdS t                                          |          S )Nr   T)rH   rN  ra  r!  rd  r#   r  )r%   r   r&   s     r'   r  zSSLIOStream._is_connreset  sG    a&& 	16!98I+I+I4ww$$Q'''r(   r\   r)   )r!   rp  )r*   r+   r,   r-   r  r   r$   r   r   r   rl  r`  r   r   r   r   rM  r7  r   rs  rI   r]   r   r   rK   r   r.   r  r/   r0   s   @r'   r:  r:  #  s	       	 	 F3c 3S 3T 3 3 3 3 3 3.< < < < < < << < < < < < <1' 1' 1' 1'f= = = =                 @D) ))/7})	) ) ) ) ) )&& & & & & &8   @
 s    .i&; < #    4(} ( ( ( ( ( ( ( ( ( ( (r(   r:  c                        e Zd ZdZdedededdf fdZdefdZdd	Zd
e	defdZ
deee	f         dee         fdZ xZS )PipeIOStreamaU  Pipe-based `IOStream` implementation.

    The constructor takes an integer file descriptor (such as one returned
    by `os.pipe`) rather than an open file object.  Pipes are generally
    one-way, so a `PipeIOStream` can be used for reading or writing but not
    both.

    ``PipeIOStream`` is only available on Unix-based platforms.
    r   r!  r"  r!   Nc                     || _         t          j        | j         d          | _        t          j        dk    rt          d          t          j        |d            t                      j
        |i | d S )Nzr+win32z(PipeIOStream is not supported on WindowsF)r   ioFileIO_fior   platformAssertionErrorr+  set_blockingr#   r$   )r%   r   r!  r"  r&   s       r'   r$   zPipeIOStream.__init__$  sq    Idgt,,	<7"" !!KLLL
E"""$)&)))))r(   c                     | j         S r)   )r   r@   s    r'   r   zPipeIOStream.fileno1  s	    wr(   c                 8    | j                                          d S r)   )r  r   r@   s    r'   r   zPipeIOStream.close_fd4  s    	r(   rC   c                 F    	 t          j        | j        |          ~S # ~w xY wr)   )r+  r   r   r   s     r'   r   zPipeIOStream.write_to_fd7  s*    	8DGT** HHHHr2  r   c                     	 | j                             |          ~S # t          $ r@}t          |          t          j        k    r|                     |           Y d }~~d S  d }~ww xY w# ~w xY w)Nr   )r  readintor  r
   r-  rh  r   r}  s      r'   r   zPipeIOStream.read_from_fd?  s    	9%%c**   	 	 	#A&&%+55 

A
&&&ttt  	 GGGGs,    
A'3A"A* !A""A''A* *A-r\   )r*   r+   r,   r-   r]   r   r$   r   r   rI   r   r   rK   r   r   r/   r0   s   @r'   r  r    s         *3 *s *c *d * * * * * *       
 s    i&; < #        r(   r  r!   c                  2    dd l } |                                 S r:   )doctestDocTestSuite)r  s    r'   doctestsr  N  s    NNN!!!r(   )Ar-   r   r;   r-  r  r   r+  r  rN  r   r   tornado.concurrentr   r   tornador   tornado.logr   tornado.netutilr   r   r	   tornado.utilr
   rR   r   r   r   r   r   r   r   r   r   typesr   TYPE_CHECKINGr   r   r   r   
ECONNRESETECONNABORTEDEPIPE	ETIMEDOUTr  hasattrr   WSAECONNABORTEDWSAETIMEDOUTr  
EPROTOTYPE
startswithr  r  r   r   r2   r6   r8   r`   r   r:  r  r  r4   r(   r'   <module>r     s           				  				  



 



 				 I I I I I I I I             W W W W W W W W W W - - - - - - 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
       	 )((((((((((z::: $e&8%+uW 
75/""   <8 )++<""5))% % % % % % % %&	 	 	 	 	Y 	 	 	J J J J JI J J JW W W W W W W WtM
 M
 M
 M
 M
 M
 M
 M
`A A A A A| A A AHs( s( s( s( s(( s( s( s(l2 2 2 2 2< 2 2 2j"# " " " " " "r(   