o b_@sdZddlZddlmZddlmZmZddlmZm Z m Z m Z ddl m Z ddlmZmZddlmZdd lmZmZmZdd lmZmZdd lmZdd lmZdd lmZm Z m!Z!m"Z"m#Z#m$Z$m%Z%m&Z&m'Z'm(Z(m)Z)m*Z*m+Z+m,Z,m-Z-m.Z.m/Z/m0Z0m1Z1m2Z2ddl3m4Z4m5Z5ddl6m7Z7m8Z8m9Z9m:Z:dZ;dZGddde>Z?Gddde=Z@Gddde=ZAeGdddZBGddde=ZCGdddeZDeeDGd d!d!ZEGd"d#d#e$ZFee5eGd$d%d%e)ejGZHe1d&eHGd'd(d(ZIGd)d*d*ejJe ZKGd+d,d,e'ejJZLe1eKeLdDd-d.ZMGd/d0d0ejNZOd1d2ZPd3d4ZQGd5d6d6ejRZSGd7d8d8ejTZUGd9d:d:e ZVee!Gd;d<d<ZWeeWe e!Gd=d>d>ZXGd?d@d@e$eXZYee eVGdAdBdBe$eXZZgdCZ[dS)Ea Perspective Broker "This isn't a professional opinion, but it's probably got enough internet to kill you." --glyph Introduction ============ This is a broker for proxies for and copies of objects. It provides a translucent interface layer to those proxies. The protocol is not opaque, because it provides objects which represent the remote proxies and require no context (server references, IDs) to operate on. It is not transparent because it does I{not} attempt to make remote objects behave identically, or even similarly, to local objects. Method calls are invoked asynchronously, and specific rules are applied when serializing arguments. To get started, begin with L{PBClientFactory} and L{PBServerFactory}. @author: Glyph Lefkowitz N)md5) Interface implementer) Anonymous IAnonymous ICredentialsIUsernameHashedPassword)Portal)deferprotocol)styles)failurelogreflect)cmp comparable)registerAdapter)banana) CacheableCopyableIPBRoot Jellyable NoSuchMethod Referenceable RemoteCacheRemoteCacheObserver RemoteCopyRoot SerializableViewable ViewPointcopyTagssetCopierForClasssetCopierForClassTreesetFactoryForClasssetUnjellyableFactoryForClasssetUnjellyableForClasssetUnjellyableForClassTree) IJellyable IUnjellyable) _newInstanceglobalSecurityjellyunjellyiiS"c@eZdZdZdS) ProtocolErrorzN This error is raised when an invalid protocol statement is received. N__name__ __module__ __qualname____doc__r5r53/usr/lib/python3/dist-packages/twisted/spread/pb.pyr/Tr/c@r.)DeadReferenceErrorzx This error is raised when a method is called on a dead reference (one whose broker has been disconnected). Nr0r5r5r5r6r8Zr7r8c@r.)Errora  This error can be raised to generate known error conditions. When a PB callable method (perspective_, remote_, view_) raises this error, it indicates that a traceback should not be printed, but instead, the string representation of the exception should be sent. Nr0r5r5r5r6r9ar7r9c@eZdZdZddZdS) RemoteErrora This class is used to wrap a string-ified exception from the remote side to be able to reraise it. (Raising string exceptions is no longer possible in Python 2.6+) The value of this exception will be a str() representation of the remote value. @ivar remoteType: The full import path of the exception class which was raised on the remote end. @type remoteType: C{str} @ivar remoteTraceback: The remote traceback. @type remoteTraceback: C{str} @note: It's not possible to include the remoteTraceback if this exception is thrown into a generator. It must be accessed as an attribute. cCst||||_||_dSN) Exception__init__ remoteTyperemoteTraceback)selfr?valuer@r5r5r6r>s  zRemoteError.__init__Nr1r2r3r4r>r5r5r5r6r;ls r;c@0eZdZdZddZddZddZdd Zd S) RemoteMethodz> This is a translucent reference to a remote message. cCs||_||_dS)zT Initialize with a L{RemoteReference} and the name of this message. N)objname)rArFrGr5r5r6r>s zRemoteMethod.__init__cCst|j|jf|Sr<)rrFrGrAotherr5r5r6__cmp__szRemoteMethod.__cmp__cCst|j|jfSr<)hashrFrGrAr5r5r6__hash__szRemoteMethod.__hash__cOs(|jjd|jj|jj|jd||S)z8 Asynchronously invoke a remote method. utf-8)rFbroker _sendMessage perspectiveluidrGencode)rAargskwr5r5r6__call__s zRemoteMethod.__call__N)r1r2r3r4r>rJrMrWr5r5r5r6rEs  rEc@s eZdZdS)PBConnectionLostN)r1r2r3r5r5r5r6rXsrXc@r:) IPerspectivea per*spec*tive, n. : The relationship of aspects of a subject to each other and to a whole: 'a perspective of history'; 'a need to view the problem in the proper perspective'. This is a Perspective Broker-specific wrapper for an avatar. That is to say, a PB-published view on to the business logic for the system's concept of a 'user'. The concept of attached/detached is no longer implemented by the framework. The realm is expected to implement such semantics if needed. cCdS)a This method is called when a network message is received. @arg broker: The Perspective Broker. @type message: str @arg message: The name of the method called by the other end. @type args: list in jelly format @arg args: The arguments that were passed by the other end. It is recommend that you use the `unserialize' method of the broker to decode this. @type kwargs: dict in jelly format @arg kwargs: The keyword arguments that were passed by the other end. It is recommended that you use the `unserialize' method of the broker to decode this. @rtype: A jelly list. @return: It is recommended that you use the `serialize' method of the broker on whatever object you need to return to generate the return value. Nr5)rPmessagerUkwargsr5r5r6perspectiveMessageReceivedz'IPerspective.perspectiveMessageReceivedNr1r2r3r4r]r5r5r5r6rYs rYc@r:)Avatara A default IPerspective implementor. This class is intended to be subclassed, and a realm should return an instance of such a subclass when IPerspective is requested of it. A peer requesting a perspective will receive only a L{RemoteReference} to a pb.Avatar. When a method is called on that L{RemoteReference}, it will translate to a method on the remote perspective named 'perspective_methodname'. (For more information on invoking methods on other objects, see L{flavors.ViewPoint}.) c Csv|||}|||}t|d|}z ||i|}Wnty1t|d|d|w||||||S)ai This method is called when a network message is received. This will call:: self.perspective_%(message)s(*broker.unserialize(args), **broker.unserialize(kw)) to handle the method; subclasses of Avatar are expected to implement methods using this naming convention. zperspective_%sz didn't accept z and ) unserializegetattr TypeErrorrmsg serialize)rArPr[rUrVmethodstater5r5r6r]s  z!Avatar.perspectiveMessageReceivedNr_r5r5r5r6r`s r`c@seZdZdZdddZdS)AsReferenceablez6 A reference directed towards another object. remotecCst||d|_dS)NMessageReceived)rbremoteMessageReceived)rAobject messageTyper5r5r6r>szAsReferenceable.__init__N)rirCr5r5r5r6rhsrhc@sheZdZdZddZddZddZdd Zd d Zd d Z ddZ ddZ ddZ ddZ ddZdS)RemoteReferencea] A translucent reference to a remote object. I may be a reference to a L{flavors.ViewPoint}, a L{flavors.Referenceable}, or an L{IPerspective} implementer (e.g., pb.Avatar). From the client's perspective, it is not possible to tell which except by convention. I am a "translucent" reference because although no additional bookkeeping overhead is given to the application programmer for manipulating a reference, return values are asynchronous. See also L{twisted.internet.defer}. @ivar broker: The broker I am obtained through. @type broker: L{Broker} cCs"||_||_||_||_g|_dS)z(internal) Initialize me with a broker and a locally-unique ID. The ID is unique only to the particular Perspective Broker instance. N)rSrP doRefCountrRdisconnectCallbacks)rArRrPrSror5r5r6r>s  zRemoteReference.__init__cCs<t|sJ|j|t|jdkr|j|jdSdS)z Register a callback to be called if our broker gets disconnected. @param callback: a callable which will be called with one argument, this instance. N)callablerpappendlenrPnotifyOnDisconnect _disconnectedrAcallbackr5r5r6ru's  z"RemoteReference.notifyOnDisconnectcCs(|j||js|j|jdSdS)zu Remove a callback that was registered with notifyOnDisconnect. @param callback: a callable N)rpremoverPdontNotifyOnDisconnectrvrwr5r5r6rz3s z&RemoteReference.dontNotifyOnDisconnectcCs|jD]}||qd|_dS)zN Called if we are disconnected and have callbacks registered. N)rprwr5r5r6rv=s   zRemoteReference._disconnectedcCs(|jr|j|jks Jdd|jfSdS)zc If I am being sent back to where I came from, serialize as a local backreference. z6Can't send references to brokers other than their own.slocal)s unpersistablezReferences cannot be serialized)invokerrPrS)rAjellierr5r5r6jellyForEs  zRemoteReference.jellyForcCs||jj|j|dd|S)Nrq)r>r{unserializingPerspective)rA unjellier unjellyListr5r5r6 unjellyForQszRemoteReference.unjellyForcOs.t|ts |d}|jd|j|j|||S)a Asynchronously invoke a remote method. @type _name: L{str} @param _name: the name of the remote method to invoke @param args: arguments to serialize for the remote function @param kw: keyword arguments to serialize for the remote function. @rtype: L{twisted.internet.defer.Deferred} @returns: a Deferred which will be fired when the result of this remote call is received. utf8rN) isinstancebytesrTrPrQrRrS)rA_namerUrVr5r5r6 callRemoteZs zRemoteReference.callRemotecCs t||S)zX @param key: The key. @return: A L{RemoteMethod} for this key. )rE)rAkeyr5r5r6 remoteMethodps zRemoteReference.remoteMethodcCs0t|tr|j|jkrt|j|jSt|j|S)zM @param other: another L{RemoteReference} to compare me to. )rrnrPrrSrHr5r5r6rJxs   zRemoteReference.__cmp__cCs|jS)z Hash me. )rSrLr5r5r6rMszRemoteReference.__hash__cCs|jr |j|jdSdS)zD Do distributed reference counting on finalization. N)rorP sendDecRefrSrLr5r5r6__del__szRemoteReference.__del__N)r1r2r3r4r>rurzrvr}rrrrJrMrr5r5r5r6rns      rnric@s8eZdZdZd ddZdefddZdd Zd d ZdS) Localz3 (internal) A reference to a local object. NcCs||_||_d|_dS)z Initialize. rqN)rlrRrefcount)rArlrRr5r5r6r>s zLocal.__init__returncCsd|jd|jdS)Nz )rlrrLr5r5r6__repr__szLocal.__repr__cC|jd|_|jS)zi Increment the reference count. @return: the reference count after incrementing rqrrLr5r5r6incref z Local.increfcCs|jd|_|jS)zi Decrement the reference count. @return: the reference count after decrementing rqrrLr5r5r6decrefrz Local.decrefr<) r1r2r3r4r>strrrrr5r5r5r6rs   rc@seZdZdZdZddZdS)CopyableFailurez} A L{flavors.RemoteCopy} and L{flavors.Copyable} version of L{twisted.python.failure.Failure} for serialization. rcCs|j}d|d<g|d<g|d<t|j|d<t|jtr$|j|d<n t|j d|d<|j r:| |d<|Sd |d<|S) z Collect state related to the exception which occurred, discarding state which cannot reasonably be serialized. NtbframesstackrBtyperO tracebackzTraceback unavailable ) __dict__copyrrBrrrrqualrTunsafeTracebacks getTraceback)rArgr5r5r6getStateToCopys    zCopyableFailure.getStateToCopyN)r1r2r3r4rrr5r5r5r6rs rc@s*eZdZdZd ddZddZeZeZdS) CopiedFailurea A L{CopiedFailure} is a L{pb.RemoteCopy} of a L{failure.Failure} transferred via PB. @ivar type: The full import path of the exception class which was raised on the remote end. @type type: C{str} @ivar value: A str() representation of the remote value. @type value: L{CopiedFailure} or C{str} @ivar traceback: The remote traceback. @type traceback: C{str} NrdefaultcCsT|durtj}|j}t|ts|d}|d||d|j|ddS)NrOzTraceback from remote host -- z:  )rlogfilerrrdecodewriterB)rAfileelideFrameworkCodedetail failureTyper5r5r6printTracebacks   zCopiedFailure.printTracebackcCs|t|j|j|jS)a Throw the original exception into the given generator, preserving traceback information if available. In the case of a L{CopiedFailure} where the exception type is a string, a L{pb.RemoteError} is thrown instead. @return: The next value yielded from the generator. @raise StopIteration: If there are no more values in the generator. @raise RemoteError: The wrapped remote exception. )throwr;rrBr)rAgr5r5r6throwExceptionIntoGenerators z)CopiedFailure.throwExceptionIntoGenerator)Nrr)r1r2r3r4rrprintBriefTracebackprintDetailedTracebackr5r5r5r6rs    rcCstt|j}||_|Sr<)r*rrr)failrfr5r5r6failure2Copyables rc@seZdZdZdZdZdZdefddZddZ d d Z d d Z d dZ ddZ ddZddZddZddZddZdZddZddZdd Zd!d"Zd#d$Zd%d&Zd'Zd(d)Zd*d+Zd,d-Zd^d.d/Zd0d1Zd2d3Z d4d5Z!d6d7Z"d_d8d9Z#d`d:d;Z$dd?Z&d@dAZ'dBdCZ(dDdEZ)dFdGZ*dHdIZ+dJdKZ,dLdMZ-dNdOZ.dPdQZ/dRdSZ0dTdUZ1dVdWZ2dXdYZ3dZd[Z4d\d]Z5dS)aBrokerz$ I am a broker for objects. NrqcCsrtj||d|_g|_g|_g|_i|_||_g|_ d|_ d|_ d|_ i|_ i|_i|_i|_i|_i|_dSNr)rBananar> disconnected disconnectsfailuresconnects localObjectssecurity pageProducerscurrentRequestIDcurrentLocalIDr~luidsremotelyCachedObjectsremotelyCachedLUIDslocallyCachedObjectswaitingForAnswers _localCleanup)rAisClientrr5r5r6r>s"  zBroker.__init__cCsVtt|jdddD]}|j|}||s|j|=q |js)|jdSdS)zM Called when the consumer attached to me runs out of buffer. rqN)rangertr sendNextPage stillPaging transportunregisterProducer)rApageridxpagerr5r5r6resumeProducing7s zBroker.resumeProducingcCdSr<r5rLr5r5r6pauseProducingDzBroker.pauseProducingcCrr<r5rLr5r5r6 stopProducingHrzBroker.stopProducingcCs0|j|t|jdkr|j|ddSdS)Nrqr)rrsrtrregisterProducer)rArr5r5r6registerPageProducerLs zBroker.registerPageProducercCsjt|tr1|d}t|ts|d}d|}t||d}|r)||dddS|d|dStd)z: Evaluate an expression as it's received. rrzproto_%sNrqsdidNotUnderstandzNon-list expression received.)rlistrrrbsendCallr/)rAsexpcommand methodNamerfr5r5r6expressionReceivedQs    zBroker.expressionReceivedcCs$||jkrtd|jd|dS)z Protocol message: (version version-number) Check to make sure that both ends of the protocol are speaking the same version dialect. @param vnum: The version number. zVersion Incompatibility:  N)versionr/)rAvnumr5r5r6 proto_versiones zBroker.proto_versioncGs||dS)z Utility method to send an expression to the other side of the connection. @param exp: The expression. N) sendEncoded)rAexpr5r5r6rrszBroker.sendCallcCstd|dS)a  Respond to stock 'C{didNotUnderstand}' message. Log the command that was not understood and continue. (Note: this will probably be changed to close the connection or raise an exception in the future.) @param command: The command to log. zDidn't understand command: %rN)rrd)rArr5r5r6proto_didNotUnderstandzs zBroker.proto_didNotUnderstandc CsT|d|j|jD]}z|Wq tytYq wd|_|j|dS)zF Initialize. Called after Banana negotiation is done. sversionN)rrr BaseExceptionrdeferrfactoryclientConnectionMaderAnotifierr5r5r6connectionReadys    zBroker.connectionReadyc Cs:|jD]}z|WqtytYqwd|_dSr<)rrrrrr5r5r6connectionFaileds     zBroker.connectionFailedc Csd|_d|_|jr*|jD]}z |tt|Wqty)t Yqw|j D]!}|j }|j }z ||t|||Wq/tyPt Yq/w|jddD]}z|WqXtylt YqXwd|_d|_d|_d|_d|_ d|_d|_d|_dS)zg The connection was lost. @param reason: message to put in L{failure.Failure} rqN)rrrvalueserrbackr FailurerXrrrrrlrRstoppedObservingrr localSecurityremoteSecurityrrr)rAreasondlobj cacheablerRrr5r5r6connectionLostsB         zBroker.connectionLostcCt|sJ|j|dS)zQ @param notifier: callback to call when the Broker disconnects. N)rrrrsrr5r5r6ru zBroker.notifyOnDisconnectcCr)zT @param notifier: callback to call if the Broker fails to connect. N)rrrrsrr5r5r6 notifyOnFailrzBroker.notifyOnFailcCsPt|sJ|jdur z|WdStytYdSw|j|dS)zN @param notifier: callback to call when the Broker connects. N)rrrrrerrrsrr5r5r6notifyOnConnects    zBroker.notifyOnConnectcCs(z |j|WdStyYdSw)zY @param notifier: callback to remove from list of disconnect callbacks. N)rry ValueErrorrr5r5r6rzs  zBroker.dontNotifyOnDisconnectcCs2t|tr |d}|j|}|durdS|jS)z Get a local object for a locally unique ID. @return: An object previously stored with L{registerReference} or L{None} if there is no object which corresponds to the given identifier. rN)rrrTrgetrl)rArSlobr5r5r6localObjectForIDs   zBroker.localObjectForIDrcCs|dusJ|}|j|}|durEt|jtkr3|jd|_|jdkr/|jt dt d| }t ||j|<||j|<|S|j| |S)z Store a persistent reference to a local object and map its id() to a generated, session-unique ID. @param object: a local object @return: the generated ID Nrqz.Maximum PB reference count exceeded. Goodbye.z$Maximum PB reference count exceeded.) processUniqueIDrrrtrMAX_BROKER_REFSmaxBrokerRefsViolationsrloseConnectionr9 newLocalIDrr)rArlpuidrSr5r5r6registerReferences      zBroker.registerReferencecCs2t|tr |d}|dusJt||j|<dS)z Store a special (string) ID for this object. This is how you specify a 'base' set of objects that the remote protocol can connect to. @param name: An ID. @param object: The object. rN)rrrTrr)rArGrlr5r5r6setNameForLocals  zBroker.setNameForLocalcCs"t|tr |d}td||dS)a Returns an object from the remote name mapping. Note that this does not check the validity of the name, only creates a translucent reference for it. @param name: The name to look up. @return: An object which maps to the name. rNr)rrrTrn)rArGr5r5r6 remoteForName,s zBroker.remoteForNamecCs2|}|j|}|dur|r|j||S)a @param instance: The instance to look up. @param incref: Flag to specify whether to increment the reference. @return: An ID that says what this instance is cached as remotely, or L{None} if it's not. N)rrrrr)rAinstancerrrSr5r5r6cachedRemotelyAs;s   zBroker.cachedRemotelyAscCs |j|jS)zk @param luid: The LUID to look up. @return: An instance which is cached remotely. )rrl)rArSr5r5r6remotelyCachedForLUIDKs zBroker.remotelyCachedForLUIDcCsn|}|}t|jtkr'|jd|_|jdkr#|jtdtd||j |<t ||j |j|<|S)z3 XXX @return: A new LUID. rqrz*Maximum PB cache count exceeded. Goodbye.z Maximum PB cache count exceeded.) rrrtrrrrrr9rrserializingPerspective)rAr rrSr5r5r6 cacheRemotelySs    zBroker.cacheRemotelycCs||j|<dS)zL(internal) Store a non-filled-out cached instance locally. NrrAcidr r5r5r6 cacheLocallyhszBroker.cacheLocallycCs|j|}|Sr<rrr5r5r6cachedLocallyAsos zBroker.cachedLocallyAscCst|tjr|j|jdd||||dd|S||_||_||_||_zt ||j d|Wd|_d|_d|_d|_Sd|_d|_d|_d|_w)a Jelly an object according to the remote security rules for this broker. @param object: The object to jelly. @param perspective: The perspective. @param method: The method. @param args: Arguments. @param kw: Keyword arguments. cSs|Sr<r5)xr5r5r6r^z"Broker.serialize..)rRrfrUrV)callbackKeywordsN) rr Deferred addCallbacksrer jellyMethod jellyArgsjellyKwr,r)rArlrRrfrUrVr5r5r6ress2  zBroker.serializecCs(||_z t||jd|Wd|_Sd|_w)z Unjelly an sexp according to the local security rules for this broker. @param sexp: The object to unjelly. @param perspective: The perspective. N)r~r-r)rArrRr5r5r6raszBroker.unserializecCr)z3 @return: A newly generated LUID. rq)rrLr5r5r6r zBroker.newLocalIDcCr)z9 @return: A newly generated request ID. rq)rrLr5r5r6 newRequestIDrzBroker.newRequestIDc Csd}d}d} d|vr|d}|d=d|vr|d}|d=d|vr/|s$|r(Jd|d} |d=|jr6tdz|j|||d} |j|||d} WntyXttYSw|} | rxt } | |j | <|sl|rwt d| ||nd} ||d | ||| | | | S) Nrq pbcallback pberrbackpbanswerz*You can't specify a no-answer requirement.zCalling Stale Broker)rRrfz&warning! using deprecated "pbcallback"smessage)rr8rerr rr rrrrrrdrr)rAprefixrRobjectIDr[rUrVpbcpbeanswerRequirednetArgsnetKw requestIDrvalr5r5r6rQsP     zBroker._sendMessagec C||j||||||dSr<) _recvMessagerrAr)r#r[r&r'r(r5r5r6 proto_messagezBroker.proto_messagec Cr+r<)r,rr-r5r5r6proto_cachemessager/zBroker.proto_cachemessagec Cs@t|ts |d}z||}|durtd|||||} Wn]ty^} z2|rLt| ts6|j| jr=| | |n| t | |WYd} ~ dSWYd} ~ dSWYd} ~ dSd} ~ wt y}|rvt j dddt } | | |t YdSw|rt| tjr|f} | j|j|j| | ddS|| |dSdS)a Received a message-send. Look up message based on object, unserialize the arguments, and invoke it with args, and send an 'answer' or 'error' response. @param findObjMethod: A callable which takes C{objectID} as argument. @param requestID: The requiest ID. @param objectID: The object ID. @param message: The message. @param answerRequired: @param netArgs: Arguments. @param netKw: Keyword arguments. rNzInvalid Object ID)Peer will receive following PB traceback:T)isError) callbackArgs errbackArgs)rrrr9rkrrisClassAllowed __class__ _sendErrorrrrrdrr rr _sendAnswer_sendFailureOrError) rA findObjMethodr)r#r[r&r'r(rl netResulterrUr5r5r6r,sF       zBroker._recvMessagecCs|d||dS)z (internal) Send an answer to a previously sent message. @param netResult: The answer. @param requestID: The request ID. sanswerNr)rAr;r)r5r5r6r8@zBroker._sendAnswercC&|j|}|j|=|||dS)z (internal) Got an answer to a previously sent message. Look up the appropriate callback and call it. @param requestID: The request ID. @param netResult: The answer. N)rrxra)rAr)r;rr5r5r6 proto_answerIs zBroker.proto_answercCs.|tdur|||dS|||dS)z Call L{_sendError} or L{_sendFailure}, depending on whether C{fail} represents an L{Error} subclass or not. @param fail: The failure. @param requestID: The request ID. N)checkr9 _sendFailurer7rArr)r5r5r6r9VszBroker._sendFailureOrErrorcCs$tdt||||dS)zz Log error and then send it. @param fail: The failure. @param requestID: The request ID. r1N)rrdrr7rCr5r5r6rBcs  zBroker._sendFailurecCstt|tjr$t|jts|j|jjr|j}n t|ts$t ||j j }t|tr.|j j |_ | d|| |dS)z (internal) Send an error for a previously sent message. @param fail: The failure. @param requestID: The request ID. serrorN)rr rrBrrr5r6rrrrrrerCr5r5r6r7ns    zBroker._sendErrorcCr?)z} (internal) Deal with an error. @param requestID: The request ID. @param fail: The failure. N)rrra)rAr)rrr5r5r6 proto_errors zBroker.proto_errorcC|d|dS)z^ (internal) Send a DECREF directive. @param objectID: The object ID. sdecrefNr=rAr#r5r5r6rzBroker.sendDecRefcCsft|tr |d}|j|}|dkr1|j|j}|j|=|j|=|j |dddSdS)z (internal) Decrement the reference count of an object. If the reference count is zero, it will free the reference to this object. @param objectID: The object ID. rrcSrr<r5r5r5r5r6rr^z%Broker.proto_decref..N) rrrTrrrlrrrpop)rAr#refsrr5r5r6 proto_decrefs zBroker.proto_decrefcCrE)z_ (internal) Send a DECACHE directive. @param objectID: The object ID. sdecacheNr=rFr5r5r6 decCacheRefrGzBroker.decCacheRefcCs|j|}|dkrD|j|}|j}|j}z ||t|||Wn ty/tYnw| }|j |=|j|=| d|dSdS)z (internal) Decrement the reference count of a cached object. If the reference count is zero, free the reference, then send an 'uncached' directive. @param objectID: The object ID. rsuncacheN) rrrlrRrrrrrrrr)rAr#rIrrrRrr5r5r6 proto_decaches"     zBroker.proto_decachecCs|j|}d|_|j|=dS)zx (internal) Tell the client it is now OK to uncache an object. @param objectID: The object ID. N)rrP)rAr#rFr5r5r6 proto_uncaches  zBroker.proto_uncacher)NNNNr<)6r1r2r3r4rusernamerr+r>rrrrrrrrrrrrrurrrzrrrr r r r rrrrerarrrQr.r0r,r8r@r9rBr7rDrrJrKrLrMr5r5r5r6rsf&     )    *)  B      rcCs>t}|||}t}|||||}|S)z Respond to a challenge. This is useful for challenge/response authentication. @param challenge: A challenge. @param password: A password. @return: The password hashed twice. )rupdatedigest) challengepasswordmhashedPassworddoubleHashedPasswordr5r5r6responds   rWcCs.tddttddD}t|}|S)z% @return: Some random data. css|] }tddVqdS)AZN)randomrandint).0rr5r5r6 szchallenge..)rrrZ randrangerrQ)crapr5r5r6rRs rRc@seZdZdZeZdZdefddZddZ ddZ d d Z d d Z dddZ ddZddZddZddZddZddZd ddZdS)!PBClientFactoryz Client factory for PB brokers. As with all client factories, use with reactor.connectTCP/SSL/etc.. getPerspective and getRootObject can be called either before or after the connect. FcCs||_||_|dS)aE @param unsafeTracebacks: if set, tracebacks for exceptions will be sent over the wire. @type unsafeTracebacks: C{bool} @param security: security options used by the broker, default to C{globalSecurity}. @type security: L{twisted.spread.jelly.SecurityOptions} N)rr_reset)rArrr5r5r6r>s  zPBClientFactory.__init__cCs|jd|jd}||_|S)zP Build the broker instance, passing the security options to it. Trr)r rr)rAaddrpr5r5r6 buildProtocolszPBClientFactory.buildProtocolcCsg|_d|_d|_dSr<)rootObjectRequests_broker_rootrLr5r5r6rcs zPBClientFactory._resetcCs&|j}||D]}||q dSr<)rhrcr)rAr deferredsrr5r5r6_failAlls  zPBClientFactory._failAllcCs||dSr<)rl)rA connectorrr5r5r6clientConnectionFailed%sz&PBClientFactory.clientConnectionFailedrcCs"|r d|_d|_dS||dS)zJ Reconnecting subclasses should call with reconnecting=1. N)rirjrl)rArmr reconnectingr5r5r6clientConnectionLost(s z$PBClientFactory.clientConnectionLostcCs8||_|d|_|j}g|_|D]}||jqdS)Nroot)rir rjrhrx)rArPdsrr5r5r6r4s z$PBClientFactory.clientConnectionMadecCs2|jr |jjs t|jSt}|j||S)ze Get root object of remote PB server. @return: Deferred of the root object. )rirr succeedrjrrhrs)rArr5r5r6 getRootObject<s   zPBClientFactory.getRootObjectcCs|jr |jjdSdS)z If the factory is connected, close the connection. Note that if you set up the factory to reconnect, you will need to implement extra logic to prevent automatic reconnection after this is called. N)rirrrLr5r5r6 disconnectHszPBClientFactory.disconnectcCs|d||j||S)Nlogin)r addCallback _cbResponse)rArqrOrSclientr5r5r6_cbSendUsernameSs zPBClientFactory._cbSendUsernamecCs|\}}|dt|||S)NrW)rrW)rA challengesrSryrR challengerr5r5r6rxXszPBClientFactory._cbResponsecCs |d|S)ab Attempt an anonymous login on the given remote root object. @type root: L{RemoteReference} @param root: The object on which to attempt the login, most likely returned by a call to L{PBClientFactory.getRootObject}. @param client: A jellyable object which will be used as the I{mind} parameter for the login attempt. @rtype: L{Deferred} @return: A L{Deferred} which will be called back with a L{RemoteReference} to an avatar when anonymous login succeeds, or which will errback if anonymous login fails. loginAnonymous)r)rArqryr5r5r6_cbLoginAnonymous\s z!PBClientFactory._cbLoginAnonymousNcCs>|}t|r||j||S||j|j|j||S)a Login and get perspective from remote PB server. Currently the following credentials are supported:: L{twisted.cred.credentials.IUsernamePassword} L{twisted.cred.credentials.IAnonymous} @rtype: L{Deferred} @return: A L{Deferred} which will be called back with a L{RemoteReference} for the avatar logged in to, or which will errback if login fails. )rtr providedByrwr~rzrOrS)rA credentialsryrr5r5r6rvns zPBClientFactory.loginrNr<)r1r2r3r4rr rr+r>rgrcrlrnrprrtrurzrxr~rvr5r5r5r6rbs"    rbc@s6eZdZdZdZeZdefddZddZ ddZ d S) PBServerFactorya Server factory for perspective broker. Login is done using a Portal object, whose realm is expected to return avatars implementing IPerspective. The credential checkers in the portal should accept IUsernameHashedPassword or IUsernameMD5Password. Alternatively, any object providing or adaptable to L{IPBRoot} can be used instead of a portal to provide the root object of the PB server. FcCst||_||_||_dS)a @param root: factory providing the root Referenceable used by the broker. @type root: object providing or adaptable to L{IPBRoot}. @param unsafeTracebacks: if set, tracebacks for exceptions will be sent over the wire. @type unsafeTracebacks: C{bool} @param security: security options used by the broker, default to C{globalSecurity}. @type security: L{twisted.spread.jelly.SecurityOptions} N)rrqrr)rArqrrr5r5r6r>s  zPBServerFactory.__init__cCs.|jd|jd}||_|d|j||S)zT Return a Broker attached to the factory (as the service provider). Frdrq)r rrr rq rootObject)rAreprotor5r5r6rgszPBServerFactory.buildProtocolcCrr<r5)rAr r5r5r6rrz$PBServerFactory.clientConnectionMadeN) r1r2r3r4rrr r+r>rgrr5r5r5r6rs  rc@ eZdZdZddZddZdS)IUsernameMD5Passwordab I encapsulate a username and a hashed password. This credential is used for username/password over PB. CredentialCheckers which check this kind of credential must store the passwords in plaintext form or as a MD5 digest. @type username: C{str} or C{Deferred} @ivar username: The username associated with these credentials. cCrZ)a Validate these credentials against the correct password. @type password: C{str} @param password: The correct, plaintext password against which to check. @rtype: C{bool} or L{Deferred} @return: C{True} if the credentials represented by this object match the given password, C{False} if they do not, or a L{Deferred} which will be called back with one of these values. Nr5rSr5r5r6 checkPasswordr^z"IUsernameMD5Password.checkPasswordcCrZ)a Validate these credentials against the correct MD5 digest of the password. @type password: C{str} @param password: The correct MD5 digest of a password against which to check. @rtype: C{bool} or L{Deferred} @return: C{True} if the credentials represented by this object match the given digest, C{False} if they do not, or a L{Deferred} which will be called back with one of these values. Nr5rr5r5r6checkMD5Passwordr^z%IUsernameMD5Password.checkMD5PasswordN)r1r2r3r4rrr5r5r5r6rs rc@r) _PortalRootz/ Root object, used to login to portal. cCs ||_dSr<)portal)rArr5r5r6r>s z_PortalRoot.__init__cCs t|j|Sr<)_PortalWrapperr)rArPr5r5r6rs z_PortalRoot.rootObjectN)r1r2r3r4r>rr5r5r5r6rs rc@r:)_JellyableAvatarMixinzk Helper class for code which deals with avatars which PB must be capable of sending to a peer. csT|\}}t|st|d}|}gfdd}||jj|<|j||S)z Ensure that the avatar to be returned to the client is jellyable and set up disconnection notification to call the realm's logout object. rRcs sdSd}d=|dSrr5)fnlogoutr5r6 maybeLogouts  z3_JellyableAvatarMixin._cbLogin..maybeLogout)r(rrhrrPrru)rAresult interfaceavatarrrr5rr6_cbLogins      z_JellyableAvatarMixin._cbLoginN)r1r2r3r4rr5r5r5r6rs rc@s(eZdZdZddZddZddZdS) rz= Root Referenceable object, used to login to portal. cCs||_||_dSr<)rrP)rArrPr5r5r6r>s z_PortalWrapper.__init__cCst}|t|j|j||fS)z[ Start of username/password login. @param username: The username. )rR_PortalAuthChallengerrrP)rArOcr5r5r6 remote_loginsz_PortalWrapper.remote_logincCs"|jt|t}||j|S)aU Attempt an anonymous login. @param mind: An object to use as the mind parameter to the portal login call (possibly None). @rtype: L{Deferred} @return: A Deferred which will be called back with an avatar when login succeeds or which will be errbacked if login fails somehow. )rrvrrYrwr)rAmindrr5r5r6remote_loginAnonymous&s z$_PortalWrapper.remote_loginAnonymousN)r1r2r3r4r>rrr5r5r5r6rs  rc@rD) rz5 Called with response to password challenge. cCs||_||_||_||_dSr<)rrPrOrR)rArrPrOrRr5r5r6r><s z_PortalAuthChallenger.__init__cCs&||_|j||t}||j|Sr<)responserrvrYrwr)rArrrr5r5r6remote_respondBs z$_PortalAuthChallenger.remote_respondcCs|t|S)z L{IUsernameHashedPassword} @param password: The password. @return: L{_PortalAuthChallenger.checkMD5Password} )rrrQ)rArSr5r5r6rHr>z#_PortalAuthChallenger.checkPasswordcCs.t}||||j|}|j|kS)z L{IUsernameMD5Password} @param md5Password: @rtype: L{bool} @return: L{True} if password matches. )rrPrRrQr)rA md5Passwordmdcorrectr5r5r6rQs    z&_PortalAuthChallenger.checkMD5PasswordN)r1r2r3r4r>rrrr5r5r5r6r6s  r)(rrrrrr rrrrrrrr!r&r%r'r"r$r#rportnor/r8r9rXrErYr`rhrnrrrrrWrRrbrrrN)\r4rZhashlibrzope.interfacerrtwisted.cred.credentialsrrrrtwisted.cred.portalr twisted.internetr r twisted.persistedr twisted.pythonr rrtwisted.python.compatrrtwisted.python.componentsrtwisted.spreadrtwisted.spread.flavorsrrrrrrrrrrrrr r!r"r#r$r%r&r'twisted.spread.interfacesr(r)twisted.spread.jellyr*r+r,r-rrr=r/r8r9r;rErXrYr`rh EphemeralrnrrrrrrrrWrR ClientFactoryrb ServerFactoryrrrrrr__all__r5r5r5r6st     X  )(  $ + W 0* #" )