o bj@sdZddlZddlmZmZddlmZddlmZm Z m Z ddl m Z m Z ddlmZddlmZmZmZee je jGd d d ZGd d d eZGd ddeZGdddZGdddeZGdddeZGdddZee Ze ee j!e jGdddeZ"ee j#Gdddej$Z%e&e%e j!e j#ee j!Gdddej$Z'e&e'e j#e j!ee j(GdddeZ)Gdd d Z*ee jGd!d"d"e*Z+Gd#d$d$e+Z,ee j Gd%d&d&Z-gd'Z.dS)(z Standard implementations of Twisted protocol-related interfaces. Start here if you are looking to write a new protocol implementation for Twisted. The Protocol class contains some introductory material. N)CallableOptional) implementer)defererror interfaces)IAddress ITransport) _loggerFor) componentsfailurelogc@sleZdZUdZdZded<dZdZeddZ d d Z d d Z d dZ ddZ ddZdeddfddZdS)Factoryz This is a factory which produces protocols. By default, buildProtocol will create a protocol of the class given in self.protocol. Nz Optional[Callable[[], Protocol]]protocolrTcOs||i|}||_|S)a Create a factory for the given protocol. It sets the C{protocol} attribute and returns the constructed factory instance. @param protocol: A L{Protocol} subclass @param args: Positional arguments for the factory. @param kwargs: Keyword arguments for the factory. @return: A L{Factory} instance wired up to C{protocol}. )r)clsrargskwargsfactoryr;/usr/lib/python3/dist-packages/twisted/internet/protocol.py forProtocol&szFactory.forProtocolcC|jjS)z9 Describe this factory for log messages.  __class____name__selfrrr logPrefix:szFactory.logPrefixcCs6|js|jrt|jd|d||jd|_dS)zl Make sure startFactory is called. Users should not call this function themselves! zStarting factory {factory!r}rN)numPortsnoisyr info startFactoryrrrrdoStart@s zFactory.doStartcCsH|jdkrdS|jd|_|js"|jrt|jd|d|dSdS)zk Make sure stopFactory is called. Users should not call this function themselves! rNrzStopping factory {factory!r}r)r r!r r" stopFactoryrrrrdoStopLs   zFactory.doStopcCdS)ay This will be called before I begin listening on a Port or Connector. It will only be called once, even if the factory is connected to multiple ports. This can be used to perform 'unserialization' tasks that are best put off until things are actually running, such as connecting to a database, opening files, etcetera. Nrrrrrr#\zFactory.startFactorycCr')a This will be called before I stop listening on all Ports/Connectors. This can be overridden to perform 'shutdown' tasks such as disconnecting database connections, closing files, etc. It will be called, for example, before an application shuts down, if it was connected to a port. User code should not call this function directly. Nrrrrrr%hr(zFactory.stopFactoryaddrreturnzOptional[Protocol]cCs |jdusJ|}||_|S)a Create an instance of a subclass of Protocol. The returned instance will handle input on an incoming server connection, and an attribute "factory" pointing to the creating factory. Alternatively, L{None} may be returned to immediately close the new connection. Override this method to alter how Protocol instances get created. @param addr: an object implementing L{IAddress} N)rr)rr)prrr buildProtocoltszFactory.buildProtocol)r __module__ __qualname____doc__r__annotations__r r! classmethodrrr$r&r#r%rr,rrrrrs      rc@s(eZdZdZddZddZddZdS) ClientFactoryz} A Protocol factory for clients. This can be used together with the various connectXXX methods in reactors. cCr')z Called when a connection has been started. You can call connector.stopConnecting() to stop the connection attempt. @param connector: a Connector object. Nr)r connectorrrrstartedConnectingr(zClientFactory.startedConnectingcCr')z Called when a connection has failed to connect. It may be useful to call connector.connect() - this will reconnect. @type reason: L{twisted.python.failure.Failure} Nrrr3reasonrrrclientConnectionFailedr(z$ClientFactory.clientConnectionFailedcCr')z Called when an established connection is lost. It may be useful to call connector.connect() - this will reconnect. @type reason: L{twisted.python.failure.Failure} Nrr5rrrclientConnectionLostr(z"ClientFactory.clientConnectionLostN)rr-r.r/r4r7r8rrrrr2s  r2c@sFeZdZdZdZdZddZdefddZd d Z d d Z d dZ dS)_InstanceFactoryaP Factory used by ClientCreator. @ivar deferred: The L{Deferred} which represents this connection attempt and which will be fired when it succeeds or fails. @ivar pending: After a connection attempt succeeds or fails, a delayed call which will fire the L{Deferred} representing this connection attempt. FNcCs||_||_||_dSN)reactorinstancedeferred)rr;r<r=rrr__init__s z_InstanceFactory.__init__r*cCsd|jdS)Nz)r<rrrr__repr__sz_InstanceFactory.__repr__cCs(|jd|j|jj|j|_d|_|jS)z Return the pre-constructed protocol instance and arrange to fire the waiting L{Deferred} to indicate success establishing the connection. rN)r; callLaterfirer=callbackr<pending)rr)rrrr,s z_InstanceFactory.buildProtocolcCs$|jd|j|jj||_d|_dS)z Arrange to fire the waiting L{Deferred} with the given failure to indicate the connection could not be established. rN)r;rArBr=errbackrDr5rrrr7s z'_InstanceFactory.clientConnectionFailedcCsd|_||dS)zo Clear C{self.pending} to avoid a reference cycle and then invoke func with the value. N)rD)rfuncvaluerrrrBs z_InstanceFactory.fire) rr-r.r/r!rDr>strr@r,r7rBrrrrr9s  r9c@s>eZdZdZddZddZddd Zdd d Zdd dZdS) ClientCreatora Client connections that do not require a factory. The various connect* methods create a protocol instance using the given protocol class and arguments, and connect it, returning a Deferred of the resulting protocol instance. Useful for cases when we don't really need a factory. Mainly this is when there is no shared state between protocol instances, and no need to reconnect. The C{connectTCP}, C{connectUNIX}, and C{connectSSL} methods each return a L{Deferred} which will fire with an instance of the protocol class passed to L{ClientCreator.__init__}. These Deferred can be cancelled to abort the connection attempt (in a very unlikely case, cancelling the Deferred may not prevent the protocol from being instantiated and connected to a transport; if this happens, it will be disconnected immediately afterwards and the Deferred will still errback with L{CancelledError}). cOs||_||_||_||_dSr:)r; protocolClassrr)rr;rJrrrrrr>s zClientCreator.__init__csLfdd}t|}t|j|j|ji|j|||di||S)a0 Initiate a connection attempt. @param method: A callable which will actually start the connection attempt. For example, C{reactor.connectTCP}. @param args: Positional arguments to pass to C{method}, excluding the factory. @param kwargs: Keyword arguments to pass to C{method}. @return: A L{Deferred} which fires with an instance of the protocol class passed to this L{ClientCreator}'s initializer or fails if the connection cannot be set up for some reason. cs$jdurjdSdSr:) disconnectrDcancel)r=r3frr cancelConnect s z-ClientCreator._connect..cancelConnectr)rDeferredr9r;rJrr)rmethodrrrOdrrMr_connects zClientCreator._connectNcCs|j|jj||||dS)a Connect to a TCP server. The parameters are all the same as to L{IReactorTCP.connectTCP} except that the factory parameter is omitted. @return: A L{Deferred} which fires with an instance of the protocol class passed to this L{ClientCreator}'s initializer or fails if the connection cannot be set up for some reason. )timeout bindAddress)rSr; connectTCP)rhostportrUrVrrrrWs zClientCreator.connectTCPFcCs|j|jj|||dS)a Connect to a Unix socket. The parameters are all the same as to L{IReactorUNIX.connectUNIX} except that the factory parameter is omitted. @return: A L{Deferred} which fires with an instance of the protocol class passed to this L{ClientCreator}'s initializer or fails if the connection cannot be set up for some reason. )rUcheckPID)rSr; connectUNIX)raddressrUrZrrrr[,s zClientCreator.connectUNIXcCs|j|jj|||||dS)a Connect to an SSL server. The parameters are all the same as to L{IReactorSSL.connectSSL} except that the factory parameter is omitted. @return: A L{Deferred} which fires with an instance of the protocol class passed to this L{ClientCreator}'s initializer or fails if the connection cannot be set up for some reason. )contextFactoryrUrV)rSr; connectSSL)rrXrYr]rUrVrrrr^;s zClientCreator.connectSSL)rTN)rTF) rr-r.r/r>rSrWr[r^rrrrrIs  rIc@sneZdZdZdZdZdZdZeZdZ dZ dZ dZ dZ dZd d Zd d Zdd dZddZddZddZdS)ReconnectingClientFactorya Factory which auto-reconnects clients with an exponential back-off. Note that clients should call my resetDelay method after they have connected successfully. @ivar maxDelay: Maximum number of seconds between connection attempts. @ivar initialDelay: Delay for the first reconnection attempt. @ivar factor: A multiplicitive factor by which the delay grows @ivar jitter: Percentage of randomness to introduce into the delay length to prevent stampeding. @ivar clock: The clock used to schedule reconnection. It's mainly useful to be parametrized in tests. If the factory is serialized, this attribute will not be serialized, and the default value (the reactor) will be restored when deserialized. @type clock: L{IReactorTime} @ivar maxRetries: Maximum number of consecutive unsuccessful connection attempts, after which no further connection attempts will be made. If this is not explicitly set, no maximum is applied. ig?giW @g6Q؟?rNrcC|jr ||_|dSdSr:continueTryingr3retryr5rrrr7~ z0ReconnectingClientFactory.clientConnectionFailedcCr`r:ra)rr3 unused_reasonrrrr8rdz.ReconnectingClientFactory.clientConnectionLostcsjsjrtdddSdur!jdurtdjjd7_jdurBjjkrBjr@tdjfdStj j j _ j r\t j j j _ jritdj ffdd }jdur~d d lm}|_jj |_dS) zL Have this connector connect again, after a suitable delay. z Abandoning z on explicit requestNzno connector to retryrzAbandoning %s after %d retries.z%s will retry in %d secondscsd_dSr:)_callIDconnectrr3rrr reconnectors z4ReconnectingClientFactory.retry..reconnectorr)r;)rbr!r msgr3 ValueErrorretries maxRetriesmindelayfactormaxDelayjitterrandom normalvariateclocktwisted.internetr;rArf)rr3rir;rrhrrcs:   zReconnectingClientFactory.retrycCsN|jr |jd|_d|_|jr%z|jWdStjy$YdSwdS)zE Put a stop to any attempt to reconnect in progress. Nr)rfrLrbr3stopConnectingrNotConnectingErrorrrrr stopTryings z$ReconnectingClientFactory.stopTryingcCs|j|_d|_d|_d|_dS)zt Call this method after a successful connection: it resets the delay and the retry counter. rNr) initialDelayrorlrfrbrrrr resetDelays z$ReconnectingClientFactory.resetDelaycCs&|j}dD] }||vr||=q|S)a- Remove all of the state which is mutated by connection attempts and failures, returning just the state which describes how reconnections should be attempted. This will make the unserialized instance behave just as this one did when it was first instantiated. )r3rlrorbrfru__dict__copy)rstatekeyrrr __getstate__s z&ReconnectingClientFactory.__getstate__r:)rr-r.r/rqrzrprrrorlrmrfr3rurbr7r8rcryr{rrrrrr_Ps& , r_c@seZdZdZdS) ServerFactoryzZ Subclass this to indicate that your protocol.Factory is only usable for servers. N)rr-r.r/rrrrrsrc@s6eZdZUdZdZdZeeed<ddZ ddZ dS) BaseProtocola This is the abstract superclass of all protocols. Some methods have helpful default implementations here so that they can easily be shared, but otherwise the direct subclasses of this class are more interesting, L{Protocol} and L{ProcessProtocol}. rN transportcCsd|_||_|dS)z Make a connection to a transport and a server. This sets the 'transport' attribute of this Protocol, and calls the connectionMade() callback. rN) connectedrconnectionMaderrrrrmakeConnections zBaseProtocol.makeConnectioncCr')a Called when a connection is made. This may be considered the initializer of the protocol, because it is called when the connection is completed. For clients, this is called once the connection to the server has been established; for servers, this is called after an accept() call stops blocking and a socket has been received. If you need to send any greeting or initial message, do it here. Nrrrrrrr(zBaseProtocol.connectionMade) rr-r.r/rrrr r0rrrrrrrs  rc@sLeZdZUdZdZeeed<ddZde fddZ e fd e j fd d ZdS) Protocola This is the base class for streaming connection-oriented protocols. If you are going to write a new connection-oriented protocol for Twisted, start here. Any protocol implementation, either client or server, should be a subclass of this class. The API is quite simple. Implement L{dataReceived} to handle both event-based and synchronous input; output can be sent through the 'transport' attribute, which is to be an instance that implements L{twisted.internet.interfaces.ITransport}. Override C{connectionLost} to be notified when the connection ends. Some subclasses exist already to help you write common types of protocols: see the L{twisted.protocols.basic} module for a few of them. NrcCrz~ Return a prefix matching the class name, to identify log messages related to this protocol instance. rrrrrr%zProtocol.logPrefixdatacCr')aF Called whenever data is received. Use this method to translate to a higher-level message. Usually, some callback will be made upon the receipt of each complete protocol message. @param data: a string of indeterminate length. Please keep in mind that you will probably need to buffer some data, as partial (or multiple) protocol messages may be received! I recommend that unit tests for protocols call through to this method with differing chunk sizes, down to one byte at a time. Nrrrrrr dataReceived,r(zProtocol.dataReceivedr6cCr')z Called when the connection is shut down. Clear any circular references here, and any external references to this Protocol. The connection has been closed. @type reason: L{twisted.python.failure.Failure} Nrrr6rrrconnectionLost;r(zProtocol.connectionLost)rr-r.r/rrrr0rbytesrconnectionDoner Failurerrrrrrs rc@s*eZdZdefddZddZddZdS) ProtocolToConsumerAdapterrcC|j|dSr:)originalrrrrrwriteHzProtocolToConsumerAdapter.writecCdSr:rrproducer streamingrrrregisterProducerKz*ProtocolToConsumerAdapter.registerProducercCrr:rrrrrunregisterProducerNrz,ProtocolToConsumerAdapter.unregisterProducerN)rr-r.rrrrrrrrrFs rc@s:eZdZdefddZdejfddZddZd d Z d S) ConsumerToProtocolAdapterrcCrr:)rrrrrrrYrz&ConsumerToProtocolAdapter.dataReceivedr6cCrr:rrrrrr\rz(ConsumerToProtocolAdapter.connectionLostcCrr:rrrrrr_rz(ConsumerToProtocolAdapter.makeConnectioncCrr:rrrrrrbrz(ConsumerToProtocolAdapter.connectionMadeN) rr-r.rrr rrrrrrrrrWs  rc@seZdZdZdedefddZdefddZdefdd Zdefd d Z d d Z ddZ ddZ de jfddZde jfddZdS)ProcessProtocolz Base process protocol implementation which does simple dispatching for stdin, stdout, and stderr file descriptors. childFDrcCs0|dkr ||dS|dkr||dSdS)Nr) outReceived errReceived)rrrrrrchildDataReceivedrs z!ProcessProtocol.childDataReceivedcCr')z5 Some data was received from stdout. Nrrrrrrxr(zProcessProtocol.outReceivedcCr')z5 Some data was received from stderr. Nrrrrrr}r(zProcessProtocol.errReceivedcCs@|dkr |dS|dkr|dS|dkr|dSdS)Nrrr)inConnectionLostoutConnectionLosterrConnectionLost)rrrrrchildConnectionLosts   z#ProcessProtocol.childConnectionLostcCr')z; This will be called when stdin is closed. Nrrrrrrr(z ProcessProtocol.inConnectionLostcCr')z< This will be called when stdout is closed. Nrrrrrrr(z!ProcessProtocol.outConnectionLostcCr')z< This will be called when stderr is closed. Nrrrrrrr(z!ProcessProtocol.errConnectionLostr6cCr')zy This will be called when the subprocess exits. @type reason: L{twisted.python.failure.Failure} Nrrrrr processExitedr(zProcessProtocol.processExitedcCr')z Called when the child process exits and all file descriptors associated with it have been closed. @type reason: L{twisted.python.failure.Failure} Nrrrrr processEndedr(zProcessProtocol.processEndedN)rr-r.r/intrrrrrrrrr rrrrrrrrksrc@sZeZdZdZdZdZdZddZddZd d Z d d Z d dZ ddZ de fddZdS)AbstractDatagramProtocolzZ Abstract protocol for datagram-oriented transports, e.g. IP, ICMP, ARP, UDP. NrTcCs|j}d|d<|S)Nrr|)rrRrrrrs z%AbstractDatagramProtocol.__getstate__cCs2|js|jr td|||jd|_dS)z Make sure startProtocol is called. This will be called by makeConnection(), users should not call it. zStarting protocol %srN)r r!r rj startProtocolrrrrr$s z AbstractDatagramProtocol.doStartcCsJ|jdksJ|jd|_d|_|js#|jrtd||dSdS)zw Make sure stopProtocol is called. This will be called by the port, users should not call it. rrNzStopping protocol %s)r rr!r rj stopProtocolrrrrr&s  zAbstractDatagramProtocol.doStopcCr')z Called when a transport is connected to this protocol. Will only be called once, even if multiple ports are connected. Nrrrrrrr(z&AbstractDatagramProtocol.startProtocolcCr')z Called when the transport is disconnected. Will only be called once, after all ports are disconnected. Nrrrrrrr(z%AbstractDatagramProtocol.stopProtocolcCs |jdksJ||_|dS)z Make a connection to a transport and a server. This sets the 'transport' attribute of this DatagramProtocol, and calls the doStart() callback. N)rr$rrrrrs z'AbstractDatagramProtocol.makeConnectiondatagramcCr')z Called when a datagram is received. @param datagram: the bytes received from the transport. @param addr: tuple of source of datagram. Nr)rrr)rrrdatagramReceivedr(z)AbstractDatagramProtocol.datagramReceived)rr-r.r/rr r!rr$r&rrrrrrrrrrs  rc@s eZdZdZddZddZdS)DatagramProtocola Protocol for datagram-oriented transport, e.g. UDP. @type transport: L{None} or L{IUDPTransport} provider @ivar transport: The transport with which this protocol is associated, if it is associated with one. cCrrrrrrrrrzDatagramProtocol.logPrefixcCr')z Called due to error from write in connected mode. Note this is a result of ICMP message generated by *previous* write. NrrrrrconnectionRefusedr(z"DatagramProtocol.connectionRefusedN)rr-r.r/rrrrrrrs rc@s(eZdZdZddZdejfddZdS)ConnectedDatagramProtocolz_ Protocol for connected datagram-oriented transport. No longer necessary for UDP. cCr')zw Called when a datagram is received. @param datagram: the string received from the transport. Nr)rrrrrrr(z*ConnectedDatagramProtocol.datagramReceivedr cCr')zi Called if connecting failed. Usually this will be due to a DNS lookup failure. Nr)rr rrrconnectionFailedr(z*ConnectedDatagramProtocol.connectionFailedN)rr-r.r/rr rrrrrrrsrc@seZdZdZdZdZdZdZddZde fddZ d d Z d d Z d dZ ddZddZddZddZddZddZddZddZdd ZdS)! FileWrapperz A wrapper around a file-like object to make it behave as a Transport. This doesn't actually stream the file to the attached protocol, and is thus useful mainly as a utility for debugging protocols. rNcCs ||_dSr:)file)rrrrrr>3 zFileWrapper.__init__rcCs0z |j|WdSty|YdSwr:)rr BaseExceptionhandleExceptionrrrrr6s  zFileWrapper.writecCs|jr |jdSdSr:)rresumeProducingrrrr_checkProducer<szFileWrapper._checkProducercCs ||_||_|s|dSdS)z. From abstract.FileDescriptor N)rstreamingProducerrrrrrrBs  zFileWrapper.registerProducercCs d|_dSr:)rrrrrrKrzFileWrapper.unregisterProducercCs||dSr:)rloseConnectionrrrr stopConsumingNs zFileWrapper.stopConsumingcCs|d|dS)N)rjoin)riovecrrr writeSequenceRszFileWrapper.writeSequencecCs4d|_z|jWdSty|YdSw)Nr)closedrcloseOSErrorrrrrrrUs  zFileWrapper.loseConnectioncCr')N)rrrrrrrgetPeer\zFileWrapper.getPeercCr')NrrrrrrgetHostarzFileWrapper.getHostcCrr:rrrrrrfrzFileWrapper.handleExceptioncCrr:rrrrrrizFileWrapper.resumeProducingcCrr:rrrrrpauseProducingmrzFileWrapper.pauseProducingcCs |dSr:)rrrrr stopProducingqs zFileWrapper.stopProducing)rr-r.r/r disconnectingrrr>rrrrrrrrrrrrrrrrrrr%s(  r) rr2r_rrrrrrrrrI)/r/rstypingrrzope.interfacerrvrrrtwisted.internet.interfacesrr twisted.loggerr twisted.pythonr r r IProtocolFactoryILoggingContextrr2r9rIr_rrrConnectionDoner cleanFailure IProtocolr IConsumerAdapterrregisterAdapterrIProcessProtocolrrrrr__all__rrrrsP   p$4o$ 5  =K O