o [dCk@sddlZddlZzddlZWn eydZYnwddlmZddlmZddlmZddlm Z ddZ d Z d Z d Z d ZGd ddeZGdddejejZGdddejZdS)N) constants) protocols) transports)loggercCs"|rtdt}|sd|_|S)Nz(Server side SSL needs a valid SSLContextF) ValueErrorsslcreate_default_contextcheck_hostname) server_sideserver_hostname sslcontextr'/usr/lib/python3.10/asyncio/sslproto.py_create_transport_contexts r UNWRAPPED DO_HANDSHAKEWRAPPEDSHUTDOWNc@s~eZdZdZdZdddZeddZedd Zed d Z ed d Z dddZ dddZ ddZ dddZdddZdS)_SSLPipeaAn SSL "Pipe". An SSL pipe allows you to communicate with an SSL/TLS protocol instance through memory buffers. It can be used to implement a security layer for an existing connection where you don't have access to the connection's file descriptor, or for some reason you don't want to use it. An SSL pipe can be in "wrapped" and "unwrapped" mode. In unwrapped mode, data is passed through untransformed. In wrapped mode, application level data is encrypted to SSL record level data and vice versa. The SSL record level is the lowest level in the SSL protocol suite and is what travels as-is over the wire. An SslPipe initially is in "unwrapped" mode. To start SSL, call do_handshake(). To shutdown SSL again, call unwrap(). iNcCsH||_||_||_t|_t|_t|_d|_ d|_ d|_ d|_ dS)a The *context* argument specifies the ssl.SSLContext to use. The *server_side* argument indicates whether this is a server side or client side transport. The optional *server_hostname* argument can be used to specify the hostname you are connecting to. You may only specify this parameter if the _ssl module supports Server Name Indication (SNI). NF) _context _server_side_server_hostname _UNWRAPPED_stater MemoryBIO _incoming _outgoing_sslobj _need_ssldata _handshake_cb _shutdown_cb)selfcontextr r rrr__init__7s    z_SSLPipe.__init__cC|jS)z*The SSL context passed to the constructor.)rr"rrrr#Msz_SSLPipe.contextcCr%)z^The internal ssl.SSLObject instance. Return None if the pipe is not wrapped. )rr&rrr ssl_objectRsz_SSLPipe.ssl_objectcCr%)zgWhether more record level data is needed to complete a handshake that is currently in progress.)rr&rrr need_ssldataZsz_SSLPipe.need_ssldatacCs |jtkS)zj Whether a security layer is currently in effect. Return False during handshake. )r_WRAPPEDr&rrrwrapped`s z_SSLPipe.wrappedcCsb|jtkr td|jj|j|j|j|jd|_ t |_||_ |j ddd\}}t |dks/J|S)aLStart the SSL handshake. Return a list of ssldata. A ssldata element is a list of buffers The optional *callback* argument can be used to install a callback that will be called when the handshake is complete. The callback will be called with None if successful, else an exception instance. z"handshake in progress or completed)r r T)only_handshaker)rr RuntimeErrorrwrap_biorrrrr _DO_HANDSHAKEr feed_ssldatalenr"callbackssldataappdatarrr do_handshakeis z_SSLPipe.do_handshakecCsj|jtkr td|jtkrtd|jttfvsJt|_||_|d\}}|gks3|dgks3J|S)a1Start the SSL shutdown sequence. Return a list of ssldata. A ssldata element is a list of buffers The optional *callback* argument can be used to install a callback that will be called when the shutdown is complete. The callback will be called without arguments. zno security layer presentzshutdown in progressr+)rrr- _SHUTDOWNr)r/r!r0r2rrrshutdown~s  z_SSLPipe.shutdowncCs6|j|d\}}|gks|dgksJdSdS)zSend a potentially "ragged" EOF. This method will raise an SSL_ERROR_EOF exception if the EOF is unexpected. r+N)r write_eofr0)r"r4r5rrrfeed_eofs z_SSLPipe.feed_eofFc Cs|jtkr|r|g}g|fSg}g|fSd|_|r|j|g}g}zZ|jtkr@|jt|_|j r9| d|r@||fWS|jtkrW |j |j }| ||sUnqFn%|jt kro|jd|_t|_|jrn|n |jtkr|| |j Wn:tjtjfy}z*t|dd}|tjtjtjfvr|jtkr|j r| ||tjk|_WYd}~nd}~ww|jjr| |j ||fS)aFeed SSL record level data into the pipe. The data must be a bytes instance. It is OK to send an empty bytes instance. This can be used to get ssldata for a handshake initiated by this endpoint. Return a (ssldata, appdata) tuple. The ssldata element is a list of buffers containing SSL data that needs to be sent to the remote SSL. The appdata element is a list of buffers containing plaintext data that needs to be forwarded to the application. The appdata list may contain an empty buffer indicating an SSL "close_notify" alert. This alert must be acknowledged by calling shutdown(). FNTerrno)rrrrwriter/rr6r)r readmax_sizeappendr7unwrapr!rSSLErrorCertificateErrorgetattrSSL_ERROR_WANT_READSSL_ERROR_WANT_WRITESSL_ERROR_SYSCALLrpending)r"datar,r5r4chunkexc exc_errnorrrr0sh              z_SSLPipe.feed_ssldatarc Cs4d|kr t|ksJJ|jtkr+|t|kr#||dg}ng}|t|fSg}t|} d|_z|t|krH||j||d7}Wn5tjy~}z(t |dd}|j dkrctj }|_ |tj tj tjfvrn|tj k|_WYd}~nd}~ww|jjr||j|t|ks|jr ||fSq2)a Feed plaintext data into the pipe. Return an (ssldata, offset) tuple. The ssldata element is a list of buffers containing record level data that needs to be sent to the remote SSL instance. The offset is the number of plaintext bytes that were processed, which may be less than the length of data. NOTE: In case of short writes, this call MUST be retried with the SAME buffer passed into the *data* argument (i.e. the id() must be the same). This is an OpenSSL requirement. A further particularity is that a short write will always have offset == 0, because the _ssl module does not enable partial writes. And even though the offset is zero, there will still be encrypted data in ssldata. rNTFr;PROTOCOL_IS_SHUTDOWN)r1rr memoryviewrrr<rrArCreasonrDr;rErFrrGr?r=)r"rHoffsetr4viewrJrKrrr feed_appdatas@        z_SSLPipe.feed_appdataN)F)r)__name__ __module__ __qualname____doc__r>r$propertyr#r'r(r*r6r8r:r0rQrrrrr#s"        Krc@seZdZejjZddZd$ddZddZ dd Z d d Z d d Z e jfddZddZddZddZd%ddZddZddZeddZddZd d!Zd"d#ZdS)&_SSLProtocolTransportcCs||_||_d|_dS)NF)_loop _ssl_protocol_closed)r"loop ssl_protocolrrrr$ s z_SSLProtocolTransport.__init__NcCs|j||S)z#Get optional transport information.)rZ_get_extra_infor"namedefaultrrrget_extra_info&sz$_SSLProtocolTransport.get_extra_infocCs|j|dSrR)rZ_set_app_protocol)r"protocolrrr set_protocol*sz"_SSLProtocolTransport.set_protocolcCs|jjSrR)rZ _app_protocolr&rrr get_protocol-sz"_SSLProtocolTransport.get_protocolcCr%rR)r[r&rrr is_closing0sz _SSLProtocolTransport.is_closingcCsd|_|jdS)a Close the transport. Buffered data will be flushed asynchronously. No more data will be received. After all buffered data is flushed, the protocol's connection_lost() method will (eventually) called with None as its argument. TN)r[rZ_start_shutdownr&rrrclose3sz_SSLProtocolTransport.closecCs*|js|d|t|d|dSdS)Nzunclosed transport )source)r[ResourceWarningrj)r"_warnrrr__del__>s z_SSLProtocolTransport.__del__cCs |jj}|dur td|S)Nz*SSL transport has not been initialized yet)rZ _transportr- is_reading)r"trrrrrpCsz _SSLProtocolTransport.is_readingcC|jjdS)zPause the receiving end. No data will be passed to the protocol's data_received() method until resume_reading() is called. N)rZro pause_readingr&rrrrsIz#_SSLProtocolTransport.pause_readingcCrr)zResume the receiving end. Data received will once again be passed to the protocol's data_received() method. N)rZroresume_readingr&rrrruQrtz$_SSLProtocolTransport.resume_readingcCs|jj||dS)aSet the high- and low-water limits for write flow control. These two values control when to call the protocol's pause_writing() and resume_writing() methods. If specified, the low-water limit must be less than or equal to the high-water limit. Neither value can be negative. The defaults are implementation-specific. If only the high-water limit is given, the low-water limit defaults to an implementation-specific value less than or equal to the high-water limit. Setting high to zero forces low to zero as well, and causes pause_writing() to be called whenever the buffer becomes non-empty. Setting low to zero causes resume_writing() to be called only once the buffer is empty. Use of zero for either limit is generally sub-optimal as it reduces opportunities for doing I/O and computation concurrently. N)rZroset_write_buffer_limits)r"highlowrrrrvYsz-_SSLProtocolTransport.set_write_buffer_limitscC |jjS)z,Return the current size of the write buffer.)rZroget_write_buffer_sizer&rrrrzns z+_SSLProtocolTransport.get_write_buffer_sizecCry)zGet the high and low watermarks for write flow control. Return a tuple (low, high) where low and high are positive number of bytes.)rZroget_write_buffer_limitsr&rrrr{rs z-_SSLProtocolTransport.get_write_buffer_limitscCs |jjjSrR)rZro_protocol_pausedr&rrrr|xs z&_SSLProtocolTransport._protocol_pausedcCs<t|tttfstdt|j|sdS|j|dS)zWrite some data bytes to the transport. This does not block; it buffers the data and arranges for it to be sent out asynchronously. z+data: expecting a bytes-like instance, got N) isinstancebytes bytearrayrM TypeErrortyperSrZ_write_appdatar"rHrrrr<}sz_SSLProtocolTransport.writecCsdS)zAReturn True if this transport supports write_eof(), False if not.Frr&rrr can_write_eofsz#_SSLProtocolTransport.can_write_eofcCs|jd|_dS)zClose the transport immediately. Buffered data will be lost. No more data will be received. The protocol's connection_lost() method will (eventually) be called with None as its argument. TN)rZ_abortr[r&rrraborts  z_SSLProtocolTransport.abortrR)NN)rSrTrUr _SendfileModeFALLBACK_sendfile_compatibler$rbrergrhrjwarningswarnrnrprsrurvrzr{rWr|r<rrrrrrrXs(     rXc@seZdZdZ   d,ddZddZd-d d Zd d Zd dZddZ ddZ ddZ ddZ d-ddZ ddZddZddZdd Zd!d"Zd#d$Zd.d&d'Zd(d)Zd*d+ZdS)/ SSLProtocolzSSL protocol. Implementation of SSL on top of a socket using incoming and outgoing buffers which are ssl.MemoryBIO objects. FNTc Cstdurtd|durtj}n |dkrtd||s"t||}||_|r-|s-||_nd|_||_t |d|_ t |_ d|_||_||_||t|j||_d|_d|_d|_d|_d|_||_||_dS)Nzstdlib ssl module not availablerz7ssl_handshake_timeout should be a positive number, got )r F)rr-rSSL_HANDSHAKE_TIMEOUTrrrr _sslcontextdict_extra collectionsdeque_write_backlog_write_buffer_size_waiterrYrcrX_app_transport_sslpipe_session_established _in_handshake _in_shutdownro_call_connection_made_ssl_handshake_timeout) r"r\ app_protocolr waiterr r call_connection_madessl_handshake_timeoutrrrr$sB    zSSLProtocol.__init__cCs||_t|tj|_dSrR)rfr}rBufferedProtocol_app_protocol_is_buffer)r"rrrrrcs zSSLProtocol._set_app_protocolcCsD|jdurdS|js|dur|j|n|jdd|_dSrR)r cancelled set_exception set_resultr"rJrrr_wakeup_waiters    zSSLProtocol._wakeup_waitercCs&||_t|j|j|j|_|dS)zXCalled when the low-level connection is made. Start the SSL handshake. N)rorrrrr_start_handshake)r" transportrrrconnection_mades  zSSLProtocol.connection_madecCsn|jrd|_|j|jj|n |jdurd|j_d|_d|_t|ddr*|j | |d|_d|_ dS)zCalled when the low-level connection is lost or closed. The argument is an exception object or None (the latter meaning a regular EOF is received or the connection was aborted or closed). FNT_handshake_timeout_handle) rrY call_soonrfconnection_lostrr[rorCrcancelrrrrrrrs     zSSLProtocol.connection_lostcC|jdS)z\Called when the low-level transport's buffer goes over the high-water mark. N)rf pause_writingr&rrrrzSSLProtocol.pause_writingcCr)z^Called when the low-level transport's buffer drains below the low-water mark. N)rfresume_writingr&rrrrrzSSLProtocol.resume_writingc Cs |jdurdSz |j|\}}Wn"ttfyty3}z ||dWYd}~dSd}~ww|D]}|j|q6|D]A}|r|z|jrQt |j |n|j |WqAttfybty{}z||dWYd}~dSd}~ww| dSdS)zXCalled when some SSL data is received. The argument is a bytes object. NzSSL error in data receivedz/application protocol failed to receive SSL data)rr0 SystemExitKeyboardInterrupt BaseException _fatal_errorror<rr_feed_data_to_buffered_protorf data_receivedri)r"rHr4r5erIexrrrr sD   zSSLProtocol.data_receivedcCs|z7|jr td||t|js(|j}|r0t dW|j dSW|j dSW|j dS|j w)aCalled when the other end of the low-level stream is half-closed. If this returns a false value (including None), the transport will close itself. If it returns a true value, closing the transport is up to the protocol. z%r received EOFz?returning true from eof_received() has no effect when using sslN) rY get_debugrdebugrConnectionResetErrorrrf eof_receivedwarningrorj)r" keep_openrrrr2s     zSSLProtocol.eof_receivedcCs0||jvr |j|S|jdur|j||S|SrR)rrorbr_rrrr^Hs   zSSLProtocol._get_extra_infocCs0|jrdS|jr|dSd|_|ddS)NTr+)rrrrr&rrrriPs  zSSLProtocol._start_shutdowncCs.|j|df|jt|7_|dS)Nr)rr?rr1_process_write_backlogrrrrrYs zSSLProtocol._write_appdatacCs\|jrtd||j|_nd|_d|_|jd|j |j |j |_ | dS)Nz%r starts SSL handshakeT)r+r)rYrrrtime_handshake_start_timerrr? call_laterr_check_handshake_timeoutrrr&rrrr^s     zSSLProtocol._start_handshakecCs.|jdurd|jd}|t|dSdS)NTz$SSL handshake is taking longer than z! seconds: aborting the connection)rrrConnectionAbortedError)r"msgrrrrms z$SSLProtocol._check_handshake_timeoutc Csd|_|j|jj}z |dur||}Wn-ttfy"tyE}zt |t j r2d}nd}| ||WYd}~dSd}~ww|j r\|j |j}td||d|jj||||d|jrt|j|j|d|_|j |jdS)NFz1SSL handshake failed on verifying the certificatezSSL handshake failedz%r: SSL handshake took %.1f msg@@)peercertcipher compressionr'T)rrrrr' getpeercertrrrr}rrBrrYrrrrrrupdaterrrrfrrrrrr)r" handshake_excsslobjrrJrdtrrr_on_handshake_completevs<     z"SSLProtocol._on_handshake_completec CsX|jdus |jdur dSzmtt|jD]b}|jd\}}|r)|j||\}}n|r5|j|j}d}n |j|j }d}|D]}|j |q@|t|kri||f|jd<|jj s\J|jj re|j WdS|jd=|jt|8_qWdSttfyty}z|jr||n ||dWYd}~dSWYd}~dSd}~ww)NrrzFatal error on SSL transport)rorranger1rrQr6rr8 _finalizer<r(_pausedrurrrrrr)r"irHrOr4rIrJrrrrsD    z"SSLProtocol._process_write_backlogFatal error on transportcCsZt|tr|jrtjd||ddn |j|||j|d|jr+|j|dSdS)Nz%r: %sT)exc_info)message exceptionrrd) r}OSErrorrYrrrcall_exception_handlerro _force_close)r"rJrrrrrs  zSSLProtocol._fatal_errorcCs"d|_|jdur|jdSdSrR)rrorjr&rrrrs zSSLProtocol._finalizecCs<z|jdur|jW|dSW|dS|wrR)rorrr&rrrrs    zSSLProtocol._abort)FNTNrR)r)rSrTrUrVr$rcrrrrrrrr^rirrrrrrrrrrrrrs0 .   &   ) + r)rrr ImportErrorrrrlogrrrr/r)r7objectr_FlowControlMixin TransportrXProtocolrrrrrs,      y~