Ϫfk8dZddlZddlmZmZmZddlmZddlm Z m Z m Z ddl m Z mZddlmZddlmZmZmZee j*e j,Gd d ZGd d eZGd deZGddZGddeZGddeZGddZej<e j>Z e jCee jDe j,GddeZ#ee jHGddejJZ&ejNe&e jDe jHee jDGddejJZ(ejNe(e jHe jDee jRGddeZ*Gdd Z+ee j,Gd!d"e+Z,Gd#d$e,Z-ee jGd%d&Z.gd'Z/y)(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)AnyCallableOptional) implementer)defererror interfaces)IAddress ITransport) _loggerFor) componentsfailurelogcfeZdZUdZdZded<dZdZedZ dZ d Z d Z d Z d Zd eddfdZy)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]]protocolrTc$||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)clsrargskwargsfactorys ;/usr/lib/python3/dist-packages/twisted/internet/protocol.py forProtocolzFactory.forProtocol&s t&v&#c.|jjS)z9 Describe this factory for log messages.  __class____name__selfs r logPrefixzFactory.logPrefix:s~~&&&rc|js8|jrt|jd||j |jdz|_y)zl Make sure startFactory is called. Users should not call this function themselves! zStarting factory {factory!r}rN)numPortsnoisyr info startFactoryrs rdoStartzFactory.doStart@sG }}zz4 %%&Dd%S     ) rc|jdk(ry|jdz |_|js9|jrt|jd||j yy)zk Make sure stopFactory is called. Users should not call this function themselves! rNr$zStopping factory {factory!r}r#)r%r&r r' stopFactoryrs rdoStopzFactory.doStopLs] ==A   ) }}zz4 %%&Dd%S    rcy)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. Nrs rr(zFactory.startFactory\rcy)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. Nr.rs rr+zFactory.stopFactoryhr/raddrreturnzOptional[Protocol]cP|jJ|j}||_|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} )rr)r r1ps r buildProtocolzFactory.buildProtocolts+}}((( MMO r)r __module__ __qualname____doc__r__annotations__r%r& classmethodrr!r)r,r(r+r r5r.rrrrs]48H07H E&' *    (/Crrc"eZdZdZdZdZdZy) ClientFactoryz} A Protocol factory for clients. This can be used together with the various connectXXX methods in reactors. cy)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 connectors rstartedConnectingzClientFactory.startedConnectingr/rcy)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} Nr.r r>reasons rclientConnectionFailedz$ClientFactory.clientConnectionFailedr/rcy)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} Nr.rAs rclientConnectionLostz"ClientFactory.clientConnectionLostr/rN)rr6r7r8r?rCrEr.rrr<r<s   rr<c<eZdZdZdZdZdZdefdZdZ dZ d Z y) _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. FNc.||_||_||_yN)reactorinstancedeferred)r rJrKrLs r__init__z_InstanceFactory.__init__s     rr2c"d|jdS)Nz)rKrs r__repr__z_InstanceFactory.__repr__s)$--):!<fs r cancelConnectz-ClientCreator._connect..cancelConnect s.  "yy$   "%rr)rDeferredrGrJr_rr)r methodrrredr>rds @@r_connectzClientCreator._connectsc" # NN= )  LL,$,,diiG4;;G t616v6 rNcV|j|jj||||S)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)rirJ connectTCP)r hostportrkrls rrmzClientCreator.connectTCPs3}} LL # #  #   rcT|j|jj|||S)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. )rkcheckPID)rirJ connectUNIX)r addressrkrqs rrrzClientCreator.connectUNIX,s-}} LL $ $gw  rcX|j|jj|||||S)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. )contextFactoryrkrl)rirJ connectSSL)r rnrorurkrls rrvzClientCreator.connectSSL;s6}} LL # #  )#   r)N)rwF) rr6r7r8rMrirmrrrvr.rrr]r]s ( : &   rr]cbeZdZdZdZdZdZdZeZdZ dZ dZ dZ dZ dZd Zd Zdd Zd Zd ZdZy)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؟?rNr$cL|jr||_|jyyrIcontinueTryingr>retryrAs rrCz0ReconnectingClientFactory.clientConnectionFailed~   &DN JJL rcL|jr||_|jyyrIr{)r r> unused_reasons rrEz.ReconnectingClientFactory.clientConnectionLostr~rctjs&jrtjddy#j t djxj dz c_jJj jkDr1jr$tjdj fzytjjzj_ jrr sr reconnectorz4ReconnectingClientFactory.retry..reconnectorsDL    rr)rJ)r|r&rmsgr> ValueErrorretries maxRetriesmindelayfactormaxDelayjitterrandom normalvariateclocktwisted.internetrJrRr)r r>rrJs`` rr}zReconnectingClientFactory.retrysK""zz+i[0DEF   ~~% !899 NN   ?? &DLL4??,Jzz9Y stopConnectingrNotConnectingErrorrs r stopTryingz$ReconnectingClientFactory.stopTryingse << LL   !DL >> --/ ++  sAA43A4cP|j|_d|_d|_d|_y)zt Call this method after a successful connection: it resets the delay and the retry counter. rNr$) initialDelayrrrr|rs r resetDelayz$ReconnectingClientFactory.resetDelays' &&   rcX|jj}dD] }||vs||= |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. )r>rrr|rr__dict__copy)r statekeys r __getstate__z&ReconnectingClientFactory.__getstate__s> ""$ Ce|#J  rrI)rr6r7r8rrrrrrrrr>rr|rCrEr}rrrr.rrryryPsd*HL  FF EGJGI EN  *EX  rryceZdZdZy) ServerFactoryzZ Subclass this to indicate that your protocol.Factory is only usable for servers. N)rr6r7r8r.rrrrsrrc6eZdZUdZdZdZeeed<dZ dZ y) 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 transportc@d|_||_|jy)z Make a connection to a transport and a server. This sets the 'transport' attribute of this Protocol, and calls the connectionMade() callback. r$N) connectedrconnectionMader rs rmakeConnectionzBaseProtocol.makeConnections" rcy)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. Nr.rs rrzBaseProtocol.connectionMader/r) rr6r7r8rrrr r9rrr.rrrrs'I&*Ix #*   rrcdeZdZUdZdZeeed<dZde ddfdZ e fde jddfd Zy) 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. Nrc.|jjSz~ Return a prefix matching the class name, to identify log messages related to this protocol instance. rrs rr!zProtocol.logPrefix% ~~&&&rdatar2cy)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. Nr.r rs r dataReceivedzProtocol.dataReceived,r/rrBcy)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} Nr.r rBs rconnectionLostzProtocol.connectionLost;r/r)rr6r7r8rrrr9r!bytesrconnectionDonerFailurerr.rrrrsM""&GXg %'    4  8F W__ $ rrc(eZdZdeddfdZdZdZy)ProtocolToConsumerAdapterrr2Nc:|jj|yrI)originalrrs rwritezProtocolToConsumerAdapter.writeHs ""4(rcyrIr.r producer streamings rregisterProducerz*ProtocolToConsumerAdapter.registerProducerK rcyrIr.rs runregisterProducerz,ProtocolToConsumerAdapter.unregisterProducerNrr)rr6r7rrrrr.rrrrFs)%)D)  rrcLeZdZdeddfdZdej ddfdZdZdZ y) ConsumerToProtocolAdapterrr2Nc:|jj|yrI)rrrs rrz&ConsumerToProtocolAdapter.dataReceivedYs D!rrBcyrIr.rs rrz(ConsumerToProtocolAdapter.connectionLost\rrcyrIr.rs rrz(ConsumerToProtocolAdapter.makeConnection_rrcyrIr.rs rrz(ConsumerToProtocolAdapter.connectionMadebrr) rr6r7rrrrrrrr.rrrrWs6""4" W__    rrceZdZUdZdZeejed<de de ddfdZ de ddfdZ de ddfd Z de ddfd Zd Zd Zd Zdej&ddfdZdej&ddfdZy)ProcessProtocolz Base process protocol implementation which does simple dispatching for stdin, stdout, and stderr file descriptors. NrchildFDrr2c`|dk(r|j|y|dk(r|j|yy)Nr$) outReceived errReceived)r rrs rchildDataReceivedz!ProcessProtocol.childDataReceivedts1 a<   T " \   T "rcy)z5 Some data was received from stdout. Nr.rs rrzProcessProtocol.outReceivedzr/rcy)z5 Some data was received from stderr. Nr.rs rrzProcessProtocol.errReceivedr/rc|dk(r|jy|dk(r|jy|dk(r|jyy)Nrr$r)inConnectionLostoutConnectionLosterrConnectionLost)r rs rchildConnectionLostz#ProcessProtocol.childConnectionLosts@ a<  ! ! # \  " " $ \  " " $rcy)z; This will be called when stdin is closed. Nr.rs rrz ProcessProtocol.inConnectionLostr/rcy)z< This will be called when stdout is closed. Nr.rs rrz!ProcessProtocol.outConnectionLostr/rcy)z< This will be called when stderr is closed. Nr.rs rrz!ProcessProtocol.errConnectionLostr/rrBcy)zy This will be called when the subprocess exits. @type reason: L{twisted.python.failure.Failure} Nr.rs r processExitedzProcessProtocol.processExitedr/rcy)z Called when the child process exits and all file descriptors associated with it have been closed. @type reason: L{twisted.python.failure.Failure} Nr.rs r processEndedzProcessProtocol.processEndedr/r)rr6r7r8rrr IProcessTransportr9intrrrrrrrrrrrrr.rrrrks 9=Ix 445<##E#d#   $   $ %3%4%    GOO   7?? t rrcTeZdZdZdZdZdZdZdZdZ dZ d Z d Z d e d ed dfdZy)AbstractDatagramProtocolzZ Abstract protocol for datagram-oriented transports, e.g. IP, ICMP, ARP, UDP. NrTcD|jj}d|d<|S)Nrr)r rhs rrz%AbstractDatagramProtocol.__getstate__s" MM   +rc|js4|jrtjd|z|j |jdz|_y)z Make sure startProtocol is called. This will be called by makeConnection(), users should not call it. zStarting protocol %sr$N)r%r&rr startProtocolrs rr)z AbstractDatagramProtocol.doStarts@ }}zz.56     ) rc|jdkDsJ|jdz |_d|_|js5|jrtjd|z|j yy)zw Make sure stopProtocol is called. This will be called by the port, users should not call it. rr$NzStopping protocol %s)r%rr&rr stopProtocolrs rr,zAbstractDatagramProtocol.doStops^ }}q    ) }}zz.56    rcy)z Called when a transport is connected to this protocol. Will only be called once, even if multiple ports are connected. Nr.rs rrz&AbstractDatagramProtocol.startProtocolr/rcy)z Called when the transport is disconnected. Will only be called once, after all ports are disconnected. Nr.rs rrz%AbstractDatagramProtocol.stopProtocolr/rcT|jdk(sJ||_|jy)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)rs rrz'AbstractDatagramProtocol.makeConnections&~~%%%" rdatagramr1r2cy)z Called when a datagram is received. @param datagram: the bytes received from the transport. @param addr: tuple of source of datagram. Nr.)r rr1s rdatagramReceivedz)AbstractDatagramProtocol.datagramReceivedr/r)rr6r7r8rr%r&rr)r,rrrrrrr.rrrrsP IH E *       c d rrceZdZdZdZdZy)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. c.|jjSrrrs rr!zDatagramProtocol.logPrefixrrcy)z Called due to error from write in connected mode. Note this is a result of ICMP message generated by *previous* write. Nr.rs rconnectionRefusedz"DatagramProtocol.connectionRefusedr/rN)rr6r7r8r!rr.rrrrs' rrc:eZdZdZdZdej ddfdZy)ConnectedDatagramProtocolz_ Protocol for connected datagram-oriented transport. No longer necessary for UDP. cy)zw Called when a datagram is received. @param datagram: the string received from the transport. Nr.)r rs rrz*ConnectedDatagramProtocol.datagramReceivedr/rrr2Ncy)zi Called if connecting failed. Usually this will be due to a DNS lookup failure. Nr.)r rs rconnectionFailedz*ConnectedDatagramProtocol.connectionFailedr/r)rr6r7r8rrrrr.rrrrs#    D rrc~eZdZdZdZdZdZdZdZde ddfdZ dZ d Z d Z d Zd Zd ZdZdZdZdZdZdZy) 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. rNc||_yrI)file)r rs rrMzFileWrapper.__init__5s  rrr2cz |jj|y#t$r|jYywxYwrI)rr BaseExceptionhandleExceptionrs rrzFileWrapper.write8s2 # IIOOD ! #  " #s ::cR|jr|jjyyrI)rresumeProducingrs r_checkProducerzFileWrapper._checkProducer>s  == MM ) ) + rcF||_||_|s|jyy)z. From abstract.FileDescriptor N)rstreamingProducerrrs rrzFileWrapper.registerProducerDs'! !*  $ $ &rcd|_yrI)rrs rrzFileWrapper.unregisterProducerMs  rcD|j|jyrI)rloseConnectionrs r stopConsumingzFileWrapper.stopConsumingPs ! rcD|jdj|y)Nr)rjoin)r iovecs r writeSequencezFileWrapper.writeSequenceTs 388E?#rcd|_ |jjy#t$r|j YywxYw)Nr$)closedrcloseOSErrorrrs rr zFileWrapper.loseConnectionWs7  # IIOO  #  " #s$AAcy)N)rrr.rs rgetPeerzFileWrapper.getPeer^srcy)Nrr.rs rgetHostzFileWrapper.getHostcsrcyrIr.rs rrzFileWrapper.handleExceptionhrrcyrIr.rs rrzFileWrapper.resumeProducingk rcyrIr.rs rpauseProducingzFileWrapper.pauseProducingorrc$|jyrI)r rs r stopProducingzFileWrapper.stopProducingss r)rr6r7r8r disconnectingrrrMrrrrrr rr rrrrrrr.rrrr'srFMH#%#D# , '$#     rr) rr<ryrrrrrrrrr])0r8rtypingrrrzope.interfacerrrrr twisted.internet.interfacesr r twisted.loggerr twisted.pythonr rrIProtocolFactoryILoggingContextrr<rGr]ryrrrConnectionDoner cleanFailure IProtocolr IConsumerAdapterrregisterAdapterrIProcessProtocolrrrrr__all__r.rrr0s: **&55<%33 Z ( (**D*DEmmFm`! G! H1}1hl l ^O OdG ! ! H!!5!5!5!78 Z ! !:#=#=>2 |2 ?2 j Z ! !" 2 2 #  z33Z5I5I  Z ! !"  2 2  #   z33Z5I5I  Z ( ()< l< *< ~H H V Z ' '( / ) 4 0 , Z " "#LL$L^ r