K idZddlZddlZddlZddlZddlZddlZddlZddlZddl Z ddl Z ddl m Z m Z ddlmZddlmZddlmZmZmZddlmZddlZddlmZmZmZmZmZmZmZm Z m!Z!dd l"m#Z#ejHr dd lm%Z%m&Z&m'Z'e d d Z(ejRejTejVejXfZ-e.edr&e-ej^ej`ejbfz Z-e jddk(re-ejffz Z-e jdjidZ5Gdde6Z7Gdde8Z9Gdde8Z:GddZ;GddZ<Gdd e<Z=Gdde=Z>Gdde<Z?d efd!Z@y)"aBUtility 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) UnionOptional AwaitableCallablePatternAnyDictTypeVarTuple) TracebackType)DequeListType _IOStreamTypeIOStream)bound WSAECONNRESETdarwinwinc4eZdZdZddeeddffd ZxZS)StreamClosedErroraException 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_errorreturnc2t|d||_y)NzStream is closed)super__init__r )selfr __class__s V/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/tornado/iostream.pyr$zStreamClosedError.__init__bs +,$N)__name__ __module__ __qualname____doc__r BaseExceptionr$ __classcell__r&s@r'rrTs% %8M#:%d%%r(rceZdZdZy)UnsatisfiableReadErrorzException raised when a read cannot be satisfied. Raised by ``read_until`` and ``read_until_regex`` with a ``max_bytes`` argument. Nr*r+r,r-r(r'r2r2gs   r(r2ceZdZdZy)StreamBufferFullErrorz?Exception raised by `IOStream` methods when the buffer is full.Nr3r4r(r'r6r6qsIr(r6cdeZdZdZd dZdefdZdZdee e e fddfdZ d ede fd Z d eddfd Zy) _StreamBufferzh A specialized buffer that tries to avoid copies when large pieces of data are encountered. r!NcRtj|_d|_d|_yNr) collectionsdeque_buffers _first_pos_sizer%s r'r$z_StreamBuffer.__init__{s'      r(c|jSr))r?r@s r'__len__z_StreamBuffer.__len__s zzr(idatact|}||jkDr9t|ts t|}|jj d|fnp|dkDrk|jr/|jd\}}|xst||jk\}nd}|r'|jj dt |fn|z }|xj|z c_y)zX Append the given piece of data (should be a buffer-compatible object). TrFN)len_large_buf_threshold isinstance memoryviewr=append bytearrayr?)r%rCsize is_memviewbnew_bufs r'rJz_StreamBuffer.appends4y $++ +dJ/!$' MM $ . AX}} $ b 1 A$KA$2K2K(K $$eYt_%=>T  d r(rLc|dkDsJ |jd\}}|j}|r t j t||||zSt||||zS#t$rtdcYSwxYw)zq Get a view over at most ``size`` bytes (possibly fewer) at the current buffer position. rr()r= IndexErrorrIr>typingcast)r%rLrMrNposs r'peekz_StreamBuffer.peeks axx # MM!,MJoo ;;z1S3:+>? ?a=sTz2 2 #c? " #sAA10A1cd|cxkr|jksJJ|xj|zc_|j}|j}|r|dkDrz|d\}}t||z |z }|dkr$|j |t||z z}d}n0|r||z }d}n&||z }t j t|d|=d}d}|r|dkDrz|dk(sJ||_y)zH Advance the current buffer position by ``size`` bytes. rN)r?r>r=rFpopleftrRrSrK)r%rLrTbuffersis_largerNb_remains r'advancez_StreamBuffer.advances4%4::%%%%% d oo--$(!!*KHa1v}s*H1}!A $t t KK 1-dsd3$( qyyr(r!N)r*r+r,r-r$intrBrGr bytesrKrIrJrUr[r4r(r'r8r8use   5 :!=>4,333"CDr(r8c eZdZdZ d>deedeedeeddfdZdeeejffdZ d?d Z d e defd Z d eee fdeefd ZdeefdZ d@dedeedeefdZ d@dedeedeefdZdAdededeefdZdAd ededeefdZdeefdZd eee fddfdZdeegdfddfdZ dAdedeeedeeeeffddfdZ d?d Z!defd!Z"defd"Z#defd#Z$d$eddfd%Z%d?d&Z&d'eeejfd(eddfd)Z'deefd*Z(d?d+Z)de*fd,Z+d-eddfd.Z,d?d/Z-deefd0Z.d1eddfd2Z/deefd3Z0deee1fd-eddfd4Z2d?d5Z3d6edefd7Z4d?d8Z5d?d9Z6d:eddfd;Z7dReturns 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. Nr4r@s r' get_fd_errorzBaseIOStream.get_fd_error<sr(regex max_bytesc4|j}tj||_||_ |j |S#t $r6}tjd|z|j||cYd}~Sd}~w|jdxYw)aAsynchronously 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: %sexc_infoNc"|jSr) exceptionfs r'z/BaseIOStream.read_until_regex..i q{{}r() _start_readrecompilersrt_try_inline_readr2rinfocloseadd_done_callback)r%rrfuturees r'read_until_regexzBaseIOStream.read_until_regexFs,!!#::e,(   ! ! # &  LLEI J JJJ "M   $ $%< = sA B+A?9B?B delimiterc|j}||_||_ |j|S#t$r6}t j d|z|j||cYd}~Sd}~w|jdxYw)anAsynchronously 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. rrNc"|jSr)rrs r'rz)BaseIOStream.read_until..rr() rrrrtrr2rrrr)r%rrrrs r' read_untilzBaseIOStream.read_untilms(!!#((   ! ! # &  LLEI J JJJ "M   $ $%< = s2 B+A,&B,B num_bytespartialc|j}t|tjsJ||_||_ |j |S#|jdxYw)aJAsynchronously 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"|jSr)rrs r'rz)BaseIOStream.read_bytes..rr()rrHnumbersIntegralrurvrr)r%rrrs r' read_byteszBaseIOStream.read_bytessi"!!#)W%5%5666$$   ! ! #    $ $%< = s AA#c|j}|j}t|}||k\r.rr() rrlrFrIrkrnrmrurvrr)r%rrravailable_bytesns r' read_intozBaseIOStream.read_intos"!!#00 H a  1 122A6CF!!"1"%+/+<+` 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"|jSr)rrs r'rz/BaseIOStream.read_until_close..rr()rclosed _finish_readrlrwrrr%rs r'read_until_closezBaseIOStream.read_until_closesm$!!# ;;=   d44 5M!%   ! ! #    $ $%< = s AA-z Future[None]c|j|rt|trt|jd}|j9t |j t |z|jkDr td|j j||xjt |z c_ t}|jd|jj|j|f|jsQ|j|j r%|j|j 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. Bz!Reached maximum write buffer sizec"|jSr)rrs r'rz$BaseIOStream.write..s 1;;=r() _check_closedrHrIrSrcrFror6rJrprrryr} _handle_write _add_io_staterhWRITE_maybe_add_error_listener)r%rCrs r'writezBaseIOStream.writes(  $ +!$',,S1**6**+c$i7$:T:TT+,OPP    % %d +  # #s4y 0 #  !89 ""D$;$;V#DE    !!""4<<#5#56  * * , r(callbackc2||_|jy)aCall 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)rzr)r%rs r'set_close_callbackzBaseIOStream.set_close_callback!s ( &&(r(rzOptional[Type[BaseException]]c|js|r\t|tr |d|_nAt|tr||_n)t j }t|r |d|_|jr#d|_|j|jn1|j% |j}||j| |j0|j j#|j%d|_|j'd|_|j+y#t$rYowxYw)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)rrHtuplerjr.sysranyrwrrlrx_find_read_pos_read_from_bufferr2r~rhremove_handlerrrr_signal_closed)r%rrTs r'rzBaseIOStream.close0s&{{}h.!)!DJ-8!)DJ"||~H8}%-a[ %%).&!!$"8"89"".4--/C..s3{{& ++DKKM:" MMODL .s,D44 E?Ecg}|j"|j|jd|_||jDcgc]\}}| c}}z }|jj|j"|j|jd|_|D]H}|j s%|j t|j |jJ|j|jj sU|j&|jj |jn#|jj t|jjd|_ |j.|j}d|_ |jj|d|_ycc}}w#tj$rYEwxYwN)r )rxrJryclearr{done set_exceptionrrjrasyncioCancelledErrorr|rzrh add_callbackro)r%futures_rcbs r'rzBaseIOStream._signal_closed`s    ( NN4,, - $D D,?,?@yq&F@@ !!#    + NN4// 0#'D  F;;=$$%6$**%MN   "   # # /++002::),,::4::F,,::;L;NO  $ $ . . 0'+D $    +%%B#'D LL % %b )"AA))  s GG  G#"G#c|jduS)z=Returns ``True`` if we are currently reading from the stream.N)rxr@s r'readingzBaseIOStream.readings  ,,r(c,t|jS)z;Returns ``True`` if we are currently writing to the stream.)boolror@s r'writingzBaseIOStream.writingsD&&''r(c|jS)z/Returns ``True`` if the stream has been closed.)rr@s r'rzBaseIOStream.closeds ||r(valuecy)aSets 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%rs r' set_nodelayzBaseIOStream.set_nodelays r(ctr)rr@s r'_handle_connectzBaseIOStream._handle_connects !##r(fdeventsc8|jrtjd|y |jr|j |jry||j j zr|j|jry||j jzr|j|jry||j jzr;|j|_ |j j|jy|j j}|jr||j j z}|j!r||j jz}||j jk(r(|j"dk(r||j j z}||j$k7rO|j$Jd||_|j j'|j)|j$yy#t*$r4}tj,d|z|j|Yd}~yd}~wt.$r/}tjdd|j|d}~wwxYw)NzGot events for closed stream %srz4shouldn't happen: _handle_events without self._staterrz'Uncaught exception, closing connection.T)rrwarningr}rrhREAD _handle_readrrERRORrrjrrrrrlr~update_handlerrr2r Exception)r%rrstaters r'_handle_eventszBaseIOStream._handle_eventss ;;= OO=r B /  $$&{{} )))!!#{{} ***""${{} ***!..0  ))$**5LL&&E||~***||~+++ ***t/E/E/J *** #KK+JIJ+#  ++DKKM4;;G $ & # LLEI J JJJ " "  MMCd S JJJ "  s=,H&9H&9H& AH&DH&& J/*I J**JJc|j |j}n.|j |j}n|jrd}nd}d}|js|j dk(r |j S| |j |k\r |j S|j |k\r#|j }||S|j dz}|js|j S)Nrre)rurtrr_read_to_bufferrlr)r% target_bytes next_find_posrTs r'_read_to_buffer_loopz!BaseIOStream._read_to_buffer_loops    '++L  ! ! -//L \\^ LL ++- ##%*$""$$'D,B,Bl,R""$$ %%6))+?J $ 6 6 : 1++-2""$$r(c |j}||j|yy#t$rtj$rt$r4}t j d|z|j|Yd}~yd}~wwxYw)Nzerror on read: %sr) rr2rrrrrrr)r%rTrs r'rzBaseIOStream._handle_reads ++-C ?  " "3 ' &  %%    OO/!3 4 JJJ "  s'%B *A;;Bc|j#|j|jJdt|_|jS)NzAlready reading)rxrrr@s r'rzBaseIOStream._start_readsJ    ("    $$, ?.? ?,"H   r(rLcD|jrH|jxs t|_d|_t |j|_d|_|}n|j |}|j|j}d|_t|||jyNF) rmrnrKrkrFrl_consumerxrr)r%rLresultrs r'rzBaseIOStream._finish_read(s  ! ! $ < < K D +/D (%():):%;D "%*D "F]]4(F    (&&F $D  .vv > &&(r(c(|j}||j|y|j|j}||j|y|j s*|j t jjyy)aAttempt 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) rrrrrrrrfrr%rTs r'rzBaseIOStream._try_inline_read7s!!# ?  " "3 '  '') ?  " "3 ' {{}   v}}11 2r(c |jr#t|j|jd}nt |j }|j |} | ~y|dk(r|j ~y|js!|xjt|d|z c_|xj|z c_~|j|jkDr0tjd|jtd|S#t$rA}|j|r|j|Yd}~~y|j|d}~wwxYw#~wxYw)aReads 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. Nrrz Reached maximum read buffer size)rmrIrkrlrKrbrOSError _is_connresetrrarrjr6)r%r bytes_readrs r'rzBaseIOStream._read_to_bufferMsR --():):; 224((<(<=!%!2!23!7J!q  ))!!Z_[j%AA!  " "j 0 "  ! !D$8$8 8 MM< = JJL'(JK K7 ))!, A .#JJJ* ,sHEADEE7AE E#E 1E7E  EEErTc^dx|_x|_|_d|_|j |y)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)rurrrsrvrrs r'rzBaseIOStream._read_from_buffer{s4 FJII4/$2B" #r(c2|jV|j|jk\s|jr1|jdkDr"t|j|j}|S|j|j r|j j |j}|dk7r9t|j}|j|j||z||zS|j|j|jy|j|j r{|jj|j }|.|j}|j|j||S|j|j|jy)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. NrrE) rurlrvrirrrkfindrF_check_max_bytesrssearchend)r%rloc delimiter_lenms r'rzBaseIOStream._find_read_possf    '  " "d&6&6 6""t'='='AD,,d.D.DEI   ! ! -  '',,T-A-AB"9$'(<(<$=M))$*>*>m@ST..%%d&:&:D=%%'C))$*:*:C@J%%d&6&68N8NOr(cp|j*||jkDrtd||jfzyy)Nz&delimiter %r not found within %d bytes)rtr2)r%rrLs r'rzBaseIOStream._check_max_bytessG    +t7K7K0K(8d2234 1L +r(c t|j}|snq|dkDsJ trd}|j|jj |}|dk(rn1|jj ||xj |z c_|jrV|jd\}}||j kDry|jjt!|d|jrUyy#t$rYnt$rR}|j|s%tjd|j||j|Yd}~yd}~wwxYw)NrizWrite error on %s: %sr)rFro_WINDOWSrrUr[rqBlockingIOErrorrrrrrrryrWr)r%rLrrindexrs r'rzBaseIOStream._handle_writes6t))*D!8O8  &D ,,T-?-?-D-DT-JK >""**95,, 9,%<!! //2ME6t333    ' ' ) .vt < !!#  ))!,OO$;T[[]AN A & s$7C.0C.. E9EAEEr c|dk(ry||jksJt|jd|j}|xj|zc_|jd|=|S)Nrr()rlrIrktobytes)r%r rNs r'rzBaseIOStream._consumesh !8d,,,,, )) *4C 0 9 9 ; #%   dsd #r(cP|jrt|jyr)rrrjr@s r'rzBaseIOStream._check_closeds ;;=#tzz: : r(c|j'|jtjjk(rX|j sG|j dk(r7|j *|jtjjyyyyyr:) r~rrfrrrlrzrrr@s r'rz&BaseIOStream._maybe_add_error_listenerss ;; $++1D1D"DKKM**a/((4""6==#5#5650"#Er(rc|jry|jbtjj|z|_|j j |j|j|jy|j|zsI|j|z|_|j j|j|jyy)aAdds `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) rr~rrfrrh add_handlerrrr)r%rs r'rzBaseIOStream._add_io_states& ;;=  ;;  ----5DK LL $ $T[[]D4G4G Uu$++-DK LL ' ' t{{ C%r(exccht|tjtfxrt |t vS)zfReturn ``True`` if exc is ECONNRESET or equivalent. May be overridden in subclasses. )rHsocketrjIOErrorr _ERRNO_CONNRESET)r%rs r'rzBaseIOStream._is_connresets/ sV\\73 4 >$S)-== r()NNNr\r))F)9r*r+r,r-r r]r$r r _SelectablerrrIrrKrrrr^r rrrrrrrrrr.rrrrrrrrrrrrrrrrrrrrrrrrrrrr4r(r'r`r`s3&*.)-/3 7!#7"#7 (} 7  7r$c6#5#556$$$ $s$ $i&; < $# $hy18<%%'/}% 5 %P<@!!+3C=! 5 !FC$9UCS8+Y++)C.+Z)E"2<(%z 12(~(T )8HRX4F+G )D )4 .    /'')    . .`%"N--((    $  $3sF,>,>'>!?33QU3j'%hsm'%R (!V!. ) ) )3,,#,\ST% %N%w*?st$=L C E ; 7D3D4D:  4 r(r`c NeZdZdZdejdededdffd Zdeee jffdZ dd Z de efd Zd eeefde efd Zd edefdZ ddedede eddfdZ ddede eeeefej4fde ededfdZddZdeddfdZxZS)razSocket-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 `. 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()) rargskwargsr!Nch||_|jjdt| |i|yr)r setblockingr#r$)r%rrrr&s r'r$zIOStream.__init__Gs.  & $)&)r(c|jSr))rr@s r'rzIOStream.filenoLs {{r(cF|jjd|_yr))rrr@s r'rzIOStream.close_fdOs  r(c|jjtjtj}tj|t j |Sr))r getsockopt SOL_SOCKETSO_ERRORrjosstrerror)r%errnos r'rzIOStream.get_fd_errorSs< &&v'8'8&//J||E2;;u#566r(rc| |jj|t|~S#t$rY~ywxYw#~wxYwr))r recv_intorFrrs r'rzIOStream.read_from_fdWsA ;;((c#h7  s$( 5858;rCcH |jj|~S#~wxYwr))rsendrs r'rzIOStream.write_to_fd_s" ;;##D)s!r%addressserver_hostnamezFuture[_IOStreamType]cd|_t}tjd||_ |j j ||j|jj|S#t$rY2t$rO}|/tjd|j j||j||cYd}~Sd}~wwxYw)aConnects 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 ` 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 ` 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. TzFuture[IOStream]NConnect error on fd %s: %sr)r}rrRrSr{rconnectrrrrrrrrhr)r%r/r0rrs r'r3zIOStream.connectgs\ %{{+=vF  KK   ( 4<<--.     ~ P>P>RTUV JJJ "M s$A00 C;CAC C C server_side ssl_options SSLIOStreamc|js<|js0|js$|js|js |j r t d||rt}nt}|j}|jj|d|_ t||||d}|j}d|_ t}t||}|j!|||_|j$|_|j&|_|S)aConvert 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)r0r4do_handshake_on_connect)r5)rxryr{rrkro ValueErrorr rrrhrrrzrr6rr|rarb)r%r4r5r0rorig_close_callbackr ssl_streams r' start_tlszIOStream.start_tlssR   ""##||  !!JK K  2 2  ##F+   +#$)  #22# [A %%&9:)/ &%)%9%9 "%)%9%9 " r(cb |jjtjtj}dk7rtj|tj||_|j@tjd|jjt j||j!y|j|j}d|_ t#||d|_y#t$r(}t |t jk(rd}Yd}~d}~wwxYw)Nrr2F)rr%r&r'rr r* ENOPROTOOPTrjr(r)r{rrr errorcoderrr})r%errrrs r'rzIOStream._handle_connects ++(():):FOOLC !8c2;;s+;}|jtjk7r|j|sYd}~yYd}~yd}~wwxYw)Nrr) rfamilyAF_INETAF_INET6 setsockopt IPPROTO_TCP TCP_NODELAYrr*EINVALr)r%rrs r'rzIOStream.set_nodelays ;; "t{{'9'9 NN OO> (   &&&&(:(:ALM ( " 77ell*43E3Ea3H4I*  s;B B C/C  Cr\r))NN) r*r+r,r-rrr$r r]rrrrr rrrKrIrrrstrr3rrssl SSLContextr r<rrr/r0s@r'rrsA%N*v}}*S*C*D* c6#5#5567hy17i&; <# sMQAA&)A.s  r()rSr#r3rwait_for_handshake)r%r/r0futr&s r'r3zSSLIOStream.connects;!0gog& 56&&((r(cDt||jry|jj |j |j }|Jd|_t|j |j|jdd|_|j|y)NF)r0r8r4) r#rrrhrrr~rrOrSr)r% old_stater&s r'rzSSLIOStream._handle_connects ! ;;=  ##DKK0KK $$$ % KK    11$)    9%r(c|j tdtx}|_|js|j |S)avWait 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. zAlready waiting)r| RuntimeErrorrrPr\rs r'rozSSLIOStream.wait_for_handshakesE2  # # /01 1,2H4)""  $ $ & r(rCct|dz rt|dd} |jj|~S#tj $r,}|j dtjk(rYd}~~yd}~wwxYw#~wxYwNi@r)rFrIrr.rJr]rr_)r%rCrs r'rzSSLIOStream.write_to_fds} t9?d#Ig.D ;;##D)|| vvayC444   s-:A9 A4-A<3A44A99A<<A?rcN |jr ~yt|dz rt|dd} |jj |t|~S#t j $r,}|jdt jk(rYd}~~yd}~wt$rY~ywxYw#~wxYwrv) rPrFrIrr,rJr]rr^rr%rrs r'rzSSLIOStream.read_from_fds ""$3x2~ oi0 {{,,S#c(;<< 66!9 7 77  "  sE B!B!$AB' BB! B BB!BB!!B$rct|tjr!|jdtjk(ryt ||S)NrT)rHrJr]rr`r#r)r%rr&s r'rzSSLIOStream._is_connresets9 a &166!98I8I+Iw$Q''r(r\r))r!rl)r*r+r,r-rrr$rrrrhr\rrrr rIr3rrorIr]rr rKrr.rr/r0s@r'r6r6#s F3c3S3T3.<<<<1'f=   @D))/7}) )&&8@ s.i&; <#4(}(((r(r6cxeZdZdZdedededdffd ZdefdZdd Zd e defd Z d e e e fde efd ZxZS) PipeIOStreamaUPipe-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. rrrr!Nc||_tj|jd|_tj dk(r t dtj|dt|(|i|y)Nzr+win32z(PipeIOStream is not supported on WindowsF) rioFileIO_fiorplatformAssertionErrorr( set_blockingr#r$)r%rrrr&s r'r$zPipeIOStream.__init__$sZIIdggt, <<7 " !!KL L E" $)&)r(c|jSr))rr@s r'rzPipeIOStream.fileno1s wwr(c8|jjyr))rrr@s r'rzPipeIOStream.close_fd4s r(rCcR tj|j|~S#~wxYwr))r(rrrs r'rzPipeIOStream.write_to_fd7s" 88DGGT*s#&rc |jj|~S#t$r:}t|tj k(r|j |Yd}~~yd}~wwxYw#~wxYw)Nr)rreadintorr r*rdrrys r'rzPipeIOStream.read_from_fd?sd 99%%c* #A&%++5 A & s, A!.AA$AA!!A$$A'r\)r*r+r,r-r]rr$rrrIrr rKr rr/r0s@r'r|r|sn *3 *s *c *d * s i&; < # r(r|r!c*ddl}|jSr:)doctest DocTestSuite)rs r'doctestsrNs    !!r()Ar-rr;r*rrr(rrJrrtornado.concurrentrrtornador tornado.logrtornado.netutilrrr tornado.utilr rRr r r rrrrrrtypesr TYPE_CHECKINGrrrr ECONNRESET ECONNABORTEDEPIPE ETIMEDOUTrhasattrrWSAECONNABORTED WSAETIMEDOUTr EPROTOTYPE startswithrrrrr2r6r8r`rr6r|rr4r(r'rsw   IWW-      ((z: $$e&8&8%++uW 5/"    <<8 ))++ << " "5 )%%& Y JIJWWtM  M  `A|AHs((s(l2<2j"#"r(