o b_K@sdZddlmZmZmZddlmZmZmZddl m Z ddl m Z m Z ddlmZmZddlmZdd Zd d ZGd d d Ze e jGdddZe e je je je je jGdddeeZefdedede fddZ!dede fddZ"gdZ#dS)z+ Support for generic select()able objects. )AF_INETAF_INET6 inet_pton)IterableListOptional) implementer) interfacesmain)failurereflect) lazyByteSlicecCst|ts tddS)NzData must be bytes) isinstancebytes TypeError)objr;/usr/lib/python3/dist-packages/twisted/internet/abstract.py_dataMustBeBytess rcCsdt||dg|S)N)join memoryview)bObjoffsetbArrayrrr _concatenatesrc@s4eZdZdZdZdZdZddZddZdd Z dS) _ConsumerMixina L{IConsumer} implementations can mix this in to get C{registerProducer} and C{unregisterProducer} methods which take care of keeping track of a producer's state. Subclasses must provide three attributes which L{_ConsumerMixin} will read but not write: - connected: A C{bool} which is C{True} as long as the consumer has someplace to send bytes (for example, a TCP connection), and then C{False} when it no longer does. - disconnecting: A C{bool} which is C{False} until something like L{ITransport.loseConnection} is called, indicating that the send buffer should be flushed and the connection lost afterwards. Afterwards, C{True}. - disconnected: A C{bool} which is C{False} until the consumer no longer has a place to send bytes, then C{True}. Subclasses must also override the C{startWriting} method. @ivar producer: L{None} if no producer is registered, otherwise the registered producer. @ivar producerPaused: A flag indicating whether the producer is currently paused. @type producerPaused: L{bool} @ivar streamingProducer: A flag indicating whether the producer was registered as a streaming (ie push) producer or not (ie a pull producer). This will determine whether the consumer may ever need to pause and resume it, or if it can merely call C{resumeProducing} on it when buffer space is available. @ivar streamingProducer: C{bool} or C{int} NFcCstd)a Override in a subclass to cause the reactor to monitor this selectable for write events. This will be called once in C{unregisterProducer} if C{loseConnection} has previously been called, so that the connection can actually close. z!%r did not implement startWritingNotImplementedErrorselfrrr startWritingLsz_ConsumerMixin.startWritingcCsN|jdurtd||jf|jr|dS||_||_|s%|dSdS)a" Register to receive data from a producer. This sets this selectable to be a consumer for a producer. When this selectable runs out of data on a write() call, it will ask the producer to resumeProducing(). When the FileDescriptor's internal data buffer is filled, it will ask the producer to pauseProducing(). If the connection is lost, FileDescriptor calls producer's stopProducing() method. If streaming is true, the producer should provide the IPushProducer interface. Otherwise, it is assumed that producer provides the IPullProducer interface. In this case, the producer won't be asked to pauseProducing(), but it has to be careful to write() data only when its resumeProducing() method is called. NzHCannot register producer %s, because producer %s was never unregistered.)producer RuntimeError disconnected stopProducingstreamingProducerresumeProducing)r r" streamingrrrregisterProducerUs   z_ConsumerMixin.registerProducercCs&d|_|jr|jr|dSdSdS)zM Stop consuming data from a producer, without disconnecting. N)r" connected disconnectingr!rrrrunregisterProducerrs  z!_ConsumerMixin.unregisterProducer) __name__ __module__ __qualname____doc__r"producerPausedr&r!r)r,rrrrr!s& rc@s*eZdZdZdedefddZddZdS) _LogOwnerz Mixin to help implement L{interfaces.ILoggingContext} for transports which have a protocol, the log prefix of which should also appear in the transport's log prefix. applicationObjectreturncCstj|r |S|jjS)z Determine the log prefix to use for messages related to C{applicationObject}, which may or may not be an L{interfaces.ILoggingContext} provider. @return: A C{str} giving the log prefix to use. )r ILoggingContext providedBy logPrefix __class__r-)r r3rrr _getLogPrefixs z_LogOwner._getLogPrefixcCdS)z Override this method to insert custom logging behavior. Its return value will be inserted in front of every line. It may be called more times than the number of output lines. -rrrrrr7z_LogOwner.logPrefixN)r-r.r/r0objectstrr9r7rrrrr2{s r2c@sDeZdZdZdZdZdZdZdZdZ dZ dZ dAde e jfdd Zd d Zd ed dfddZddZddZddZddZddZdejd dfddZddZdd Zd!d"Zd#d$Zd ed dfd%d&Zd'e ed dfd(d)Z!d*d+Z"d,d-Z#d.d/Z$d0d1Z%d2d3Z&d4d5Z'dZ(d6Z)d7d8Z*d9d:Z+d;d<Z,d=d>Z-d?d@Z.dS)BFileDescriptorz An object which can be operated on by select(). This is an abstract superclass of all objects which may be notified when they are readable or writable; e.g. they have a file-descriptor that is valid to be passed to select(2). rFriNreactorcCs*|s ddlm}|}||_g|_d|_dS)z @param reactor: An L{IReactorFDSet} provider which this descriptor will use to get readable and writeable event notifications. If no value is given, the global reactor will be used. r)r@N)twisted.internetr@_tempDataBuffer _tempDataLen)r r@_reactorrrr__init__s   zFileDescriptor.__init__cCs:d|_d|_|jdur|jd|_||dS)azThe connection was lost. This is called when the connection on a selectable object has been lost. It will be called whether the connection was closed explicitly, an exception occurred in an event handler, or the other end of the connection closed it first. Clean up state here, but make sure to call back up to FileDescriptor. rN)r$r*r"r% stopReading stopWritingr reasonrrrconnectionLosts    zFileDescriptor.connectionLostdatar4cCtdt|j)a Write as much as possible of the given data, immediately. This is called to invoke the lower-level writing functionality, such as a socket's send() method, or a file's write(); this method returns an integer or an exception. If an integer, it is the number of bytes written (possibly zero); if an exception, it indicates the connection was lost. z#%s does not implement writeSomeDatarr qualr8r rLrrr writeSomeDatas zFileDescriptor.writeSomeDatacCrM)z Called when data is available for reading. Subclasses must override this method. The result will be interpreted in the same way as a result of doWrite(). z%s does not implement doReadrNrrrrdoReadszFileDescriptor.doReadcCst|j|j|jkrt|j|j|j|_d|_g|_d|_|jr,|t|j|j}n||j}t |t s;|dkr=|S|j|7_|jt|jkr|jsd|_d|_| |j durn|j rd|jrnd|_|j dS|jru|S|jrd|_|}|SdS)z Called when data can be written. @return: L{None} on success, an exception or a negative integer on failure. @see: L{twisted.internet.interfaces.IWriteDescriptor.doWrite}. rrNFT)len dataBufferr SEND_LIMITrrBrCrQr r ExceptionrHr"r&r1r'r+_postLoseConnection_writeDisconnecting_writeDisconnected_closeWriteConnection)r lresultrrrdoWrites@      zFileDescriptor.doWritecCstjS)zCalled after a loseConnection(), when all data has been written. Whatever this returns is then returned by doWrite. )r CONNECTION_DONErrrrrW'sz"FileDescriptor._postLoseConnectioncCsdSNrrrrrrZ/sz$FileDescriptor._closeWriteConnectioncC||dSr_rKrIrrrwriteConnectionLost3z"FileDescriptor.writeConnectionLostrJcCr`r_rarIrrrreadConnectionLost7rcz!FileDescriptor.readConnectionLostcCtr_rrrrrgetHost;zFileDescriptor.getHostcCrer_rrrrrgetPeer?rgzFileDescriptor.getPeercCst|j|j|jkS)ay Determine whether the user-space send buffer for this transport is full or not. When the buffer contains more than C{self.bufferSize} bytes, it is considered full. This might be improved by considering the size of the kernel send buffer and how much of it is free. @return: C{True} if it is full, C{False} otherwise. )rSrTrC bufferSizerrrr_isSendBufferFullCs z FileDescriptor._isSendBufferFullcCs8|jdur|jr|rd|_|jdSdSdSdS)zY Possibly pause a producer, if there is one and the send buffer is full. NT)r"r&rjr1pauseProducingrrrr_maybePauseProducerPs z"FileDescriptor._maybePauseProducercCsRt||jr |jr dS|r'|j||jt|7_||dSdS)a7Reliably write some data. The data is buffered until the underlying file descriptor is ready for writing. If there is more than C{self.bufferSize} data in the buffer and this descriptor has a registered streaming producer, its C{pauseProducing()} method will be called. N) rr*rYrBappendrCrSrlr!rPrrrwrite\s   zFileDescriptor.writeioveccCsb|D]}t|q|jr|r|jrdS|j||D] }|jt|7_q||dS)a Reliably write a sequence of data. Currently, this is a convenience method roughly equivalent to:: for chunk in iovec: fd.write(chunk) It may have a more efficient implementation at a later time or in a different reactor. As with the C{write()} method, if a buffer size limit is reached and a streaming producer is registered, it will be paused until the buffered data is written to the underlying file descriptor. N) rr*rYrBextendrCrSrlr!)r roirrr writeSequencems   zFileDescriptor.writeSequencecCsZ|jr)|js+|jr|||ttj dS|| d|_dSdSdS)a[Close the connection at the next available opportunity. Call this to cause this FileDescriptor to lose its connection. It will first write any data that it has buffered. If there is data buffered yet to be written, this method will cause the transport to lose its connection as soon as it's done flushing its write buffer. If you have a producer registered, the connection won't be closed until the producer is finished. Therefore, make sure you unregister your producer when it's finished, or the connection will never close. rFN) r*r+rYrGrHrKr Failurer r^r!rrrrloseConnections  zFileDescriptor.loseConnectioncCsd|_|dS)NT)rXr!rrrrloseWriteConnections z"FileDescriptor.loseWriteConnectioncC|j|dS)zStop waiting for read availability. Call this to remove this selectable from being notified when it is ready for reading. N)r@ removeReaderrrrrrGzFileDescriptor.stopReadingcCrv)zStop waiting for write availability. Call this to remove this selectable from being notified when it is ready for writing. N)r@ removeWriterrrrrrHrxzFileDescriptor.stopWritingcCrv)z$Start waiting for read availability.N)r@ addReaderrrrr startReadingszFileDescriptor.startReadingcCrv)zStart waiting for write availability. Call this to have this FileDescriptor be notified whenever it is ready for writing. N)r@ addWriterrrrrr!rxzFileDescriptor.startWritingicCs||dS)zStop consuming data. This is called when a producer has lost its connection, to tell the consumer to go lose its connection (and break potential circular references). N)r,rtrrrr stopConsumings zFileDescriptor.stopConsumingcCs |jr |js|dSdSdSr_)r*r+r{rrrrr's  zFileDescriptor.resumeProducingcC |dSr_)rGrrrrrk zFileDescriptor.pauseProducingcCr~r_)rtrrrrr%rzFileDescriptor.stopProducingcCr:)zFile Descriptor number for select(). This method must be overridden or assigned in subclasses to indicate a valid file descriptor for the operating system. rrrrrfilenor<zFileDescriptor.filenor_)/r-r.r/r0r*r$r+rXrYrTrrUrr IReactorFDSetrErKrrQrRr]rWrZrbr rsrdrfrhrjrlrnrrrrtrurGrHr{r!r"rir}r'rkr%rrrrrr?sL ;     r?addrfamilyr4c Cst|trz|d}Wn tyYdSw|tkr$|ddd}n|tkr2|ddkr1dSntd|zt ||Wd Stt fyMYdSw) a> Determine whether the given string represents an IP address of the given family; by default, an IPv4 address. @param addr: A string which may or may not be the decimal dotted representation of an IPv4 address. @param family: The address family to test for; one of the C{AF_*} constants from the L{socket} module. (This parameter has only been available since Twisted 17.1.0; previously L{isIPAddress} could only test for IPv4 addresses.) @return: C{True} if C{addr} represents an IPv4 address, C{False} otherwise. asciiF%rFr.zunknown address family T) rrdecodeUnicodeDecodeErrorrsplitrcount ValueErrorrOSError)rrrrr isIPAddresss&   rcCs t|tS)a2 Determine whether the given string represents an IPv6 address. @param addr: A string which may or may not be the hex representation of an IPv6 address. @type addr: C{str} @return: C{True} if C{addr} represents an IPv6 address, C{False} otherwise. @rtype: C{bool} )rr)rrrr isIPv6Addresss r)r?rrN)$r0socketrrrtypingrrrzope.interfacerrAr r twisted.pythonr r twisted.python.compatr rrrr5r2 IPushProducerIReadWriteDescriptor IConsumer ITransportIHalfCloseableDescriptorr?r>intboolrr__all__rrrrs2  ZJ(