U
    W[                  (   @   s  d Z ddlmZmZ ddlZddlmZ ddlmZm	Z	 ddl
mZmZmZ ddlmZmZmZmZmZ ddlmZmZ dd	lmZ dd
lmZmZ ddlmZmZ ddlm Z  ddl!m"Z" ddl#m$Z$m%Z% ddl&m'Z'm(Z(m)Z)m*Z* ddl+m,Z, ddl-m.Z. ddl-m/Z/m0Z0 ddl-m1Z1m2Z2 ddl-m3Z3 ddl-m4Z4 ddl-m5Z5 ddl-m6Z6 ddl-m7Z7 ddl-m8Z8 ddl-m9Z9 ddl-m:Z: ddl-m;Z; ddl-m<Z< ddl-m=Z= ddl-m>Z> dd l-m?Z? dd!l-m@Z@ dd"l-mAZA d#ZBd$ZCG d%d& d&eDZEG d'd( d(eEZFG d)d* d*eDZGG d+d, d,eDZHeG d-d. d.ZIG d/d0 d0eDZJG d1d2 d2e	ZKeeKG d3d4 d4ZLG d5d6 d6e/ZMee%eG d7d8 d8e.e jNZOe<d9eO G d:d; d;ZPG d<d= d=ejQe5ZRG d>d? d?e8ejQZSe<eReS dld@dAZTG dBdC dCe,jUZVdDdE ZWdFdG ZXG dHdI dIejYZZG dJdK dKej[Z\G dLdM dMeZ]ee2G dNdO dOZ^e"e^ee2 G dPdQ dQZ_G dRdS dSe/e_Z`eee]G dTdU dUe/e_ZadVdWdXdYdZd[d\d]d^d_d`dadbdcdddedfdgdhdidjdkd&d(d*d0d.d2d4d6d8d=d?dAdCdEdGdIdKdMg(ZbdS )ma  
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
    )absolute_importdivisionN)md5)implementer	Interface)logfailurereflect)unicode	_bytesChrrange
comparablecmp)deferprotocol)Portal)
IAnonymousICredentials)IUsernameHashedPassword	Anonymous)styles)registerAdapter)
IJellyableIUnjellyable)jellyunjellyglobalSecurity_newInstance)banana)Serializable)ReferenceableNoSuchMethod)RootIPBRoot)	ViewPoint)Viewable)Copyable)	Jellyable)	Cacheable)
RemoteCopy)RemoteCache)RemoteCacheObserver)copyTags)setUnjellyableForClass)setUnjellyableFactoryForClass)setUnjellyableForClassTree)setCopierForClass)setFactoryForClass)setCopierForClassTreei   iS"  c                   @   s   e Zd ZdZdS )ProtocolErrorzN
    This error is raised when an invalid protocol statement is received.
    N__name__
__module____qualname____doc__ r9   r9   3/usr/lib/python3/dist-packages/twisted/spread/pb.pyr3   Q   s   r3   c                   @   s   e Zd ZdZdS )DeadReferenceErrorzx
    This error is raised when a method is called on a dead reference (one whose
    broker has been disconnected).
    Nr4   r9   r9   r9   r:   r;   X   s   r;   c                   @   s   e Zd ZdZdS )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.
    Nr4   r9   r9   r9   r:   r<   `   s   r<   c                   @   s   e Zd ZdZdd ZdS )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.
    c                 C   s   t | | || _|| _d S N)	Exception__init__
remoteTyperemoteTraceback)selfrA   valuerB   r9   r9   r:   r@      s    zRemoteError.__init__Nr5   r6   r7   r8   r@   r9   r9   r9   r:   r=   l   s   r=   c                   @   s0   e Zd ZdZdd Zdd Zdd Zdd	 Zd
S )RemoteMethodz>
    This is a translucent reference to a remote message.
    c                 C   s   || _ || _dS )zT
        Initialize with a L{RemoteReference} and the name of this message.
        N)objname)rC   rG   rH   r9   r9   r:   r@      s    zRemoteMethod.__init__c                 C   s   t | j| jf|S r>   )r   rG   rH   rC   otherr9   r9   r:   __cmp__   s    zRemoteMethod.__cmp__c                 C   s   t | j| jfS r>   )hashrG   rH   rC   r9   r9   r:   __hash__   s    zRemoteMethod.__hash__c                 O   s(   | j jd| j j| j j| jd||S )z8
        Asynchronously invoke a remote method.
            utf-8)rG   broker_sendMessageperspectiveluidrH   encode)rC   argskwr9   r9   r:   __call__   s     
  zRemoteMethod.__call__N)r5   r6   r7   r8   r@   rK   rN   rX   r9   r9   r9   r:   rF      s
   rF   c                   @   s   e Zd ZdS )PBConnectionLostN)r5   r6   r7   r9   r9   r9   r:   rY      s   rY   c                   @   s   e Zd ZdZdd ZdS )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.
    c                 C   s   dS )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.
        Nr9   )rQ   messagerV   kwargsr9   r9   r:   perspectiveMessageReceived   s    z'IPerspective.perspectiveMessageReceivedNr5   r6   r7   r8   r]   r9   r9   r9   r:   rZ      s   rZ   c                   @   s   e Zd ZdZdd ZdS )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              	   C   sr   | || }| || }t| d| }z|||}W n* tk
r^   td|||f   Y nX ||| |||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.
        zperspective_%sz%s didn't accept %s and %s)unserializegetattr	TypeErrorr   msg	serialize)rC   rQ   r[   rV   rW   methodstater9   r9   r:   r]      s    z!Avatar.perspectiveMessageReceivedNr^   r9   r9   r9   r:   r_      s   r_   c                   @   s   e Zd ZdZdddZdS )AsReferenceablez6
    A reference directed towards another object.
    remotec                 C   s   t ||d | _d S )NZMessageReceived)ra   remoteMessageReceived)rC   objectZmessageTyper9   r9   r:   r@     s     zAsReferenceable.__init__N)rh   rE   r9   r9   r9   r:   rg      s   rg   c                   @   sh   e Zd ZdZdd Zdd Zdd Zdd	 Zd
d Zdd Z	dd Z
dd Zdd Zdd Zdd ZdS )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}
    c                 C   s"   || _ || _|| _|| _g | _dS )z(internal) Initialize me with a broker and a locally-unique ID.

        The ID is unique only to the particular Perspective Broker
        instance.
        N)rT   rQ   
doRefCountrS   disconnectCallbacks)rC   rS   rQ   rT   rl   r9   r9   r:   r@     s
    zRemoteReference.__init__c                 C   s8   t |st| j| t| jdkr4| j| j dS )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)callableAssertionErrorrm   appendlenrQ   notifyOnDisconnect_disconnectedrC   callbackr9   r9   r:   rs   *  s    z"RemoteReference.notifyOnDisconnectc                 C   s$   | j | | j s | j| j dS )zu
        Remove a callback that was registered with notifyOnDisconnect.

        @param callback: a callable
        N)rm   removerQ   dontNotifyOnDisconnectrt   ru   r9   r9   r:   rx   7  s    z&RemoteReference.dontNotifyOnDisconnectc                 C   s   | j D ]}||  qd| _ dS )zN
        Called if we are disconnected and have callbacks registered.
        N)rm   ru   r9   r9   r:   rt   B  s    

zRemoteReference._disconnectedc                 C   s,   |j r$| j|j kstdd| jfS dS dS )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.s   local)s   unpersistablezReferences cannot be serializedN)invokerrQ   rp   rT   )rC   Zjellierr9   r9   r:   jellyForK  s    
zRemoteReference.jellyForc                 C   s   |  |jj|j|d d | S )Nrn   )r@   ry   unserializingPerspective)rC   Z	unjellierZunjellyListr9   r9   r:   
unjellyForV  s    zRemoteReference.unjellyForc                 O   s.   t |ts|d}| jd| 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.
        utf8rO   )
isinstancebytesrU   rQ   rR   rS   rT   )rC   _namerV   rW   r9   r9   r:   
callRemote[  s    

  zRemoteReference.callRemotec                 C   s
   t | |S )zX

        @param key: The key.
        @return: A L{RemoteMethod} for this key.
        )rF   )rC   keyr9   r9   r:   remoteMethodq  s    zRemoteReference.remoteMethodc                 C   s0   t |tr$|j| jkr$t| j|jS t| j|S )zM

        @param other: another L{RemoteReference} to compare me to.
        )r~   rk   rQ   r   rT   rI   r9   r9   r:   rK   z  s    
zRemoteReference.__cmp__c                 C   s   | j S )z
        Hash me.
        )rT   rM   r9   r9   r:   rN     s    zRemoteReference.__hash__c                 C   s   | j r| j| j dS )zD
        Do distributed reference counting on finalization.
        N)rl   rQ   
sendDecRefrT   rM   r9   r9   r:   __del__  s    zRemoteReference.__del__N)r5   r6   r7   r8   r@   rs   rx   rt   rz   r|   r   r   rK   rN   r   r9   r9   r9   r:   rk     s   		rk   rh   c                   @   s2   e Zd ZdZdddZdd Zdd Zd	d
 ZdS )Localz3
    (internal) A reference to a local object.
    Nc                 C   s   || _ || _d| _dS )z
        Initialize.
        rn   N)rj   rS   refcount)rC   rj   rS   r9   r9   r:   r@     s    zLocal.__init__c                 C   s   d| j | jf S )Nz<pb.Local %r ref:%s>)rj   r   rM   r9   r9   r:   __repr__  s    zLocal.__repr__c                 C   s   | j d | _ | j S )zi
        Increment the reference count.

        @return: the reference count after incrementing
        rn   r   rM   r9   r9   r:   incref  s    zLocal.increfc                 C   s   | j d | _ | j S )zi
        Decrement the reference count.

        @return: the reference count after decrementing
        rn   r   rM   r9   r9   r:   decref  s    zLocal.decref)N)r5   r6   r7   r8   r@   r   r   r   r9   r9   r9   r:   r     s
   
	
r   c                   @   s   e Zd ZdZdZdd ZdS )CopyableFailurez}
    A L{flavors.RemoteCopy} and L{flavors.Copyable} version of
    L{twisted.python.failure.Failure} for serialization.
    r   c                 C   s~   | j  }d|d< g |d< g |d< t| j|d< t| jtrH| j|d< nt| j	d|d< | j
rr|  |d< nd	|d< |S )
z
        Collect state related to the exception which occurred, discarding
        state which cannot reasonably be serialized.
        NtbZframesstackrD   typerP   	tracebackzTraceback unavailable
)__dict__copystrrD   r~   r   r   r	   ZqualrU   unsafeTracebacksZgetTraceback)rC   rf   r9   r9   r:   getStateToCopy  s    
zCopyableFailure.getStateToCopyN)r5   r6   r7   r8   r   r   r9   r9   r9   r:   r     s   r   c                   @   s*   e Zd ZdZd	ddZdd ZeZeZdS )
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}
    Nr   defaultc                 C   sT   |d krt j}| j}t|ts(|d}|d ||d | j  |d d S )NrP   zTraceback from remote host -- z: 
)r   Zlogfiler   r~   r   decodewriterD   )rC   fileZelideFrameworkCodeZdetailZfailureTyper9   r9   r:   printTraceback  s    


zCopiedFailure.printTracebackc                 C   s   | t| j| j| jS )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=   r   rD   r   )rC   gr9   r9   r:   throwExceptionIntoGenerator  s    z)CopiedFailure.throwExceptionIntoGenerator)Nr   r   )r5   r6   r7   r8   r   r   ZprintBriefTracebackZprintDetailedTracebackr9   r9   r9   r:   r     s
   
r   c                 C   s   t t| j}||_|S r>   )r   r   r   r   )failr   fr9   r9   r:   failure2Copyable
  s    r   c                   @   s  e Zd ZdZdZdZdZdefddZdd Z	d	d
 Z
dd Zdd Zdd Zdd Zdd Zdd Zdd Zdd ZdZdd Zdd Zdd  Zd!d" Zd#d$ Zd%d& Zd'Zd(d) Zd*d+ Zd,d- Zd^d.d/Zd0d1 Zd2d3 Z d4d5 Z!d6d7 Z"d_d8d9Z#d`d:d;Z$d<d= Z%d>d? Z&d@dA Z'dBdC Z(dDdE Z)dFdG Z*dHdI Z+dJdK Z,dLdM Z-dNdO Z.dPdQ Z/dRdS Z0dTdU Z1dVdW Z2dXdY Z3dZd[ Z4d\d] Z5dS )aBrokerz$
    I am a broker for objects.
       Nrn   c                 C   sr   t j| | d| _g | _g | _g | _i | _|| _g | _	d| _
d| _d | _i | _i | _i | _i | _i | _i | _d S Nr   )r   Bananar@   disconnecteddisconnectsfailuresconnectslocalObjectssecuritypageProducerscurrentRequestIDcurrentLocalIDr{   luidsremotelyCachedObjectsremotelyCachedLUIDslocallyCachedObjectswaitingForAnswers_localCleanup)rC   isClientr   r9   r9   r:   r@     s"    zBroker.__init__c                 C   sR   t t| jd ddD ]&}| j| }|  | s| j|= q| jsN| j  dS )zM
        Called when the consumer attached to me runs out of buffer.
        rn   N)r   rr   r   ZsendNextPageZstillPaging	transportZunregisterProducer)rC   Zpageridxpagerr9   r9   r:   resumeProducingA  s    

zBroker.resumeProducingc                 C   s   d S r>   r9   rM   r9   r9   r:   pauseProducingO  s    zBroker.pauseProducingc                 C   s   d S r>   r9   rM   r9   r9   r:   stopProducingT  s    zBroker.stopProducingc                 C   s,   | j | t| j dkr(| j| d d S )Nrn   r   )r   rq   rr   r   ZregisterProducer)rC   r   r9   r9   r:   registerPageProducerY  s    zBroker.registerPageProducerc                 C   sj   t |tr^|d }t |ts&|d}d| }t| |d}|rP||dd   qf| d| ntddS )z:
        Evaluate an expression as it's received.
        r   r}   zproto_%sNrn   s   didNotUnderstandzNon-list expression received.)r~   listr   r   ra   sendCallr3   )rC   sexpcommandZ
methodNamere   r9   r9   r:   expressionReceived_  s    


zBroker.expressionReceivedc                 C   s    || j krtd| j |f dS )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.
        zVersion Incompatibility: %s %sN)versionr3   )rC   Zvnumr9   r9   r:   proto_versiont  s    

zBroker.proto_versionc                 G   s   |  | dS )z
        Utility method to send an expression to the other side of the connection.

        @param exp: The expression.
        N)ZsendEncoded)rC   Zexpr9   r9   r:   r     s    zBroker.sendCallc                 C   s   t d|  dS )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.
        zDidn't understand command: %rN)r   rc   )rC   r   r9   r9   r:   proto_didNotUnderstand  s    
zBroker.proto_didNotUnderstandc                 C   sP   |  d| j | jD ]$}z
|  W q   t  Y qX qd| _| j|  dS )zF
        Initialize. Called after Banana negotiation is done.
        s   versionN)r   r   r   r   deferrfactoryclientConnectionMaderC   notifierr9   r9   r:   connectionReady  s    

zBroker.connectionReadyc                 C   s6   | j D ]$}z
|  W q   t  Y qX qd | _ d S r>   )r   r   r   r   r9   r9   r:   connectionFailed  s    

zBroker.connectionFailedc                 C   s  d| _ d| _| jrP| j D ]2}z|tt| W q   t	  Y qX q| j
 D ]>}|j}|j}z||t| || W qZ   t	  Y qZX qZ| jdd D ]$}z
|  W q   t	  Y qX qd| _d| _d| _d| _d| _
d| _d| _d| _dS )zg
        The connection was lost.

        @param reason: message to put in L{failure.Failure}
        rn   N)r   r   r   valueserrbackr   FailurerY   r   r   r   rj   rS   stoppedObservingr+   r   ZlocalSecurityZremoteSecurityr   r   r   )rC   reasondlobj	cacheablerS   r   r9   r9   r:   connectionLost  s8    
zBroker.connectionLostc                 C   s   t |st| j| dS )zQ

        @param notifier: callback to call when the Broker disconnects.
        N)ro   rp   r   rq   r   r9   r9   r:   rs     s    zBroker.notifyOnDisconnectc                 C   s   t |st| j| dS )zT

        @param notifier: callback to call if the Broker fails to connect.
        N)ro   rp   r   rq   r   r9   r9   r:   notifyOnFail  s    zBroker.notifyOnFailc                 C   sH   t |st| jdkr8z
|  W qD   t  Y qDX n| j| dS )zN

        @param notifier: callback to call when the Broker connects.
        N)ro   rp   r   r   errrq   r   r9   r9   r:   notifyOnConnect  s    

zBroker.notifyOnConnectc                 C   s*   z| j | W n tk
r$   Y nX dS )zY

        @param notifier: callback to remove from list of disconnect callbacks.
        N)r   rw   
ValueErrorr   r9   r9   r:   rx     s    zBroker.dontNotifyOnDisconnectc                 C   s2   t |tr|d}| j|}|dkr,dS |jS )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.
        r}   N)r~   r
   rU   r   getrj   )rC   rT   Zlobr9   r9   r:   localObjectForID  s    

zBroker.localObjectForIDr   c                 C   s   |dk	st | }| j|}|dkrt| jtkrf| jd | _| jdkr^| j	  t
dt
d|  }t|| j|< || j|< n| 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
        Nrn      z.Maximum PB reference count exceeded.  Goodbye.z$Maximum PB reference count exceeded.)rp   processUniqueIDr   r   rr   r   MAX_BROKER_REFSmaxBrokerRefsViolationsr   loseConnectionr<   
newLocalIDr   r   )rC   rj   puidrT   r9   r9   r:   registerReference  s    	

zBroker.registerReferencec                 C   s2   t |tr|d}|dk	s tt|| j|< dS )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.
        r}   N)r~   r
   rU   rp   r   r   )rC   rH   rj   r9   r9   r:   setNameForLocal6  s    


zBroker.setNameForLocalc                 C   s"   t |tr|d}td| |dS )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.
        r}   Nr   )r~   r
   rU   rk   )rC   rH   r9   r9   r:   remoteForNameG  s    


zBroker.remoteForNamec                 C   s2   |  }| j|}|dk	r.|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)r   r   r   r   r   )rC   instancer   r   rT   r9   r9   r:   cachedRemotelyAsW  s
    
zBroker.cachedRemotelyAsc                 C   s   | j | jS )zk

        @param luid: The LUID to look up.
        @return: An instance which is cached remotely.
        )r   rj   )rC   rT   r9   r9   r:   remotelyCachedForLUIDh  s    zBroker.remotelyCachedForLUIDc                 C   sn   |  }|  }t| jtkrN| jd | _| jdkrF| j  tdtd|| j	|< t
|| j| j|< |S )z3
        XXX

        @return: A new LUID.
        rn   r   z*Maximum PB cache count exceeded.  Goodbye.z Maximum PB cache count exceeded.)r   r   rr   r   r   r   r   r   r<   r   r   serializingPerspective)rC   r   r   rT   r9   r9   r:   cacheRemotelyq  s    


zBroker.cacheRemotelyc                 C   s   || j |< dS )zL(internal)

        Store a non-filled-out cached instance locally.
        Nr   rC   Zcidr   r9   r9   r:   cacheLocally  s    zBroker.cacheLocallyc                 C   s   | j | }|S r>   r   r   r9   r9   r:   cachedLocallyAs  s    
zBroker.cachedLocallyAsc                 C   s|   t |tjr0|j| jdd ||||dd |S || _|| _|| _|| _zt	|| j
d| W S d| _d| _d| _d| _X dS )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.
        c                 S   s   | S r>   r9   )xr9   r9   r:   <lambda>  rO   z"Broker.serialize.<locals>.<lambda>)rS   re   rV   rW   )ZcallbackKeywordsN)r~   r   DeferredaddCallbacksrd   r   ZjellyMethodZ	jellyArgsZjellyKwr   r   )rC   rj   rS   re   rV   rW   r9   r9   r:   rd     s&    zBroker.serializec                 C   s(   || _ zt|| jd| W S d| _ X dS )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   )rC   r   rS   r9   r9   r:   r`     s    zBroker.unserializec                 C   s   | j d | _ | j S )z3

        @return: A newly generated LUID.
        rn   )r   rM   r9   r9   r:   r     s    zBroker.newLocalIDc                 C   s   | j d | _ | j S )z9

        @return: A newly generated request ID.
        rn   )r   rM   r9   r9   r:   newRequestID  s    zBroker.newRequestIDc              	   C   s  d }d }d}	d|kr"|d }|d= d|kr8|d }|d= d|kr^|sH|rPt d|d }	|d= | jrltdz$| j|||d}
| j|||d}W n   tt  Y S X |  }|	rt	 }|| j
|< |s|rtd ||| nd }| |d	 ||||	|
| |S )
Nrn   Z
pbcallbackZ	pberrbackZpbanswerz*You can't specify a no-answer requirement.zCalling Stale Broker)rS   re   z&warning! using deprecated "pbcallback"s   message)rp   r   r;   rd   r   r   r   r   r   r   r   r   rc   r   r   )rC   prefixrS   objectIDr[   rV   rW   ZpbcZpbeanswerRequirednetArgsnetKw	requestIDZrvalr9   r9   r:   rR     s<    

zBroker._sendMessagec              	   C   s   |  | j|||||| d S r>   )_recvMessager   rC   r   r   r[   r   r   r   r9   r9   r:   proto_message   s    zBroker.proto_messagec              	   C   s   |  | j|||||| d S r>   )r   r   r   r9   r9   r:   proto_cachemessage  s    zBroker.proto_cachemessagec              
   C   s  t |ts|d}z,||}|dkr.td|| |||}	W n tk
r }
 z>|rt |
tsn| j|
jr|| 	|
| n| 	t
|
| W 5 d}
~
X Y nv   |rtjddd t
 }| 	|| t  Y n@X |rt |	tjr|f}|	j| j| j||d n| |	| dS )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.
        r}   NzInvalid Object ID)Peer will receive following PB traceback:T)ZisError)ZcallbackArgsZerrbackArgs)r~   r   r   r<   ri   r'   r   isClassAllowed	__class__
_sendErrorr   r   rc   r   r   r   r   _sendAnswer_sendFailureOrError)rC   ZfindObjMethodr   r   r[   r   r   r   rj   	netResulter   rV   r9   r9   r:   r     s4    

  zBroker._recvMessagec                 C   s   |  d|| dS )z
        (internal) Send an answer to a previously sent message.

        @param netResult: The answer.
        @param requestID: The request ID.
        s   answerNr   )rC   r  r   r9   r9   r:   r  <  s    zBroker._sendAnswerc                 C   s&   | j | }| j |= || | dS )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)r   rv   r`   )rC   r   r  r   r9   r9   r:   proto_answerF  s    	
zBroker.proto_answerc                 C   s,   | tdkr| || n| || dS )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)Zcheckr<   _sendFailurer  rC   r   r   r9   r9   r:   r  T  s    zBroker._sendFailureOrErrorc                 C   s$   t d t | | || dS )zz
        Log error and then send it.

        @param fail: The failure.
        @param requestID: The request ID.
        r   N)r   rc   r   r  r	  r9   r9   r:   r  b  s    

zBroker._sendFailurec                 C   st   t |tjrHt |jts(| j|jjr0|j}nt |tsHt	|| j
j}t |tr\| j
j|_| d|| | dS )z
        (internal) Send an error for a previously sent message.

        @param fail: The failure.
        @param requestID: The request ID.
        s   errorN)r~   r   r   rD   r'   r   r   r   r   r   r   r   r   rd   r	  r9   r9   r:   r  n  s    


zBroker._sendErrorc                 C   s&   | j | }| j |= || | dS )z}
        (internal) Deal with an error.

        @param requestID: The request ID.
        @param fail: The failure.
        N)r   r   r`   )rC   r   r   r   r9   r9   r:   proto_error  s    
zBroker.proto_errorc                 C   s   |  d| dS )z^
        (internal) Send a DECREF directive.

        @param objectID: The object ID.
        s   decrefNr  rC   r   r9   r9   r:   r     s    zBroker.sendDecRefc                 C   sb   t |tr|d}| j|  }|dkr^| j| j }| j|= | j|= | j	|dd   dS )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.
        r}   r   c                   S   s   d S r>   r9   r9   r9   r9   r:   r     rO   z%Broker.proto_decref.<locals>.<lambda>N)
r~   r
   rU   r   r   rj   r   r   r   pop)rC   r   refsr   r9   r9   r:   proto_decref  s    	

zBroker.proto_decrefc                 C   s   |  d| dS )z_
        (internal) Send a DECACHE directive.

        @param objectID: The object ID.
        s   decacheNr  r  r9   r9   r:   decCacheRef  s    zBroker.decCacheRefc                 C   s   | j |  }|dkr~| j | }|j}|j}z||t| || W n   t  Y nX | }| j	|= | j |= | 
d| dS )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.
        r   s   uncacheN)r   r   rj   rS   r   r+   r   r   r   r   r   )rC   r   r  r   r   rS   r   r9   r9   r:   proto_decache  s    	
zBroker.proto_decachec                 C   s   | j | }d|_| j |= dS )zx
        (internal) Tell the client it is now OK to uncache an object.

        @param objectID: The object ID.
        N)r   rQ   )rC   r   rG   r9   r9   r:   proto_uncache  s    
zBroker.proto_uncache)r   )NNNN)N)6r5   r6   r7   r8   r   usernamer   r   r@   r   r   r   r   r   r   r   r   r   r   r   r   rs   r   r   rx   r   r   r   r   r   r   r   r   r   r   rd   r`   r   r   rR   r   r   r   r  r  r  r  r  r
  r   r  r  r  r  r9   r9   r9   r:   r     sd   '		(		
	
(
		"4
		r   c                 C   s>   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.
    )r   updatedigest)	challengepasswordmZhashedPasswordZdoubleHashedPasswordr9   r9   r:   respond  s    



r  c                  C   s>   d} t tddD ]}| ttdd } qt|  } | S )z%

    @return: Some random data.
    rO         A   Z   )r   randomZ	randrangechrZrandintr   r  )Zcrapr   r9   r9   r:   r    s
    r  c                   @   s   e Zd ZdZeZdZdefddZdd Z	dd Z
d	d
 Zdd ZdddZdd Zdd Zdd Zdd Zdd Zdd Zd ddZdS )!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.
    Fc                 C   s   || _ || _|   dS )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)r   r   _reset)rC   r   r   r9   r9   r:   r@     s    
zPBClientFactory.__init__c                 C   s   | j d| jd}| |_|S )zP
        Build the broker instance, passing the security options to it.
        Tr   r   )r   r   r   )rC   addrpr9   r9   r:   buildProtocol  s    zPBClientFactory.buildProtocolc                 C   s   g | _ d | _d | _d S r>   )rootObjectRequests_broker_rootrM   r9   r9   r:   r   $  s    zPBClientFactory._resetc                 C   s&   | j }|   |D ]}|| qd S r>   )r%  r   r   )rC   r   Z	deferredsr   r9   r9   r:   _failAll*  s    zPBClientFactory._failAllc                 C   s   |  | d S r>   )r(  )rC   	connectorr   r9   r9   r:   clientConnectionFailed1  s    z&PBClientFactory.clientConnectionFailedr   c                 C   s    |rd| _ d| _n
| | dS )zJ
        Reconnecting subclasses should call with reconnecting=1.
        N)r&  r'  r(  )rC   r)  r   Zreconnectingr9   r9   r:   clientConnectionLost5  s    z$PBClientFactory.clientConnectionLostc                 C   s8   || _ |d| _| j}g | _|D ]}|| j q"d S )Nroot)r&  r   r'  r%  rv   )rC   rQ   Zdsr   r9   r9   r:   r   B  s    z$PBClientFactory.clientConnectionMadec                 C   s2   | j r| j jst| jS t }| j| |S )ze
        Get root object of remote PB server.

        @return: Deferred of the root object.
        )r&  r   r   Zsucceedr'  r   r%  rq   )rC   r   r9   r9   r:   getRootObjectK  s
    zPBClientFactory.getRootObjectc                 C   s   | j r| j j  dS )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)r&  r   r   rM   r9   r9   r:   
disconnectX  s    zPBClientFactory.disconnectc                 C   s   | d|| j||S )Nlogin)r   addCallback_cbResponse)rC   r,  r  r  clientr9   r9   r:   _cbSendUsernamed  s
      zPBClientFactory._cbSendUsernamec                 C   s   |\}}| dt|||S )Nr  )r   r  )rC   Z
challengesr  r2  r  Z
challengerr9   r9   r:   r1  i  s    zPBClientFactory._cbResponsec                 C   s   | 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.
        ZloginAnonymous)r   )rC   r,  r2  r9   r9   r:   _cbLoginAnonymousn  s    z!PBClientFactory._cbLoginAnonymousNc                 C   s<   |   }t|r"|| j| n|| 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.
        )r-  r   
providedByr0  r4  r3  r  r  )rC   Zcredentialsr2  r   r9   r9   r:   r/    s    
  zPBClientFactory.login)r   )N)r5   r6   r7   r8   r   r   r   r   r@   r$  r   r(  r*  r+  r   r-  r.  r3  r1  r4  r/  r9   r9   r9   r:   r     s    	
	r  c                   @   s6   e Zd ZdZdZeZdefddZdd Z	dd Z
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.
    Fc                 C   s   t || _|| _|| _dS )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)r#   r,  r   r   )rC   r,  r   r   r9   r9   r:   r@     s    
zPBServerFactory.__init__c                 C   s.   | j d| jd}| |_|d| j| |S )zT
        Return a Broker attached to the factory (as the service provider).
        Fr!  r,  )r   r   r   r   r,  
rootObject)rC   r"  protor9   r9   r:   r$    s    zPBServerFactory.buildProtocolc                 C   s   d S r>   r9   )rC   r   r9   r9   r:   r     s    z$PBServerFactory.clientConnectionMadeN)r5   r6   r7   r8   r   r   r   r   r@   r$  r   r9   r9   r9   r:   r6    s   
r6  c                   @   s    e Zd ZdZdd Zdd ZdS )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.
    c                 C   s   dS )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.
        Nr9   r  r9   r9   r:   checkPassword  s    z"IUsernameMD5Password.checkPasswordc                 C   s   dS )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.
        Nr9   r:  r9   r9   r:   checkMD5Password  s    z%IUsernameMD5Password.checkMD5PasswordN)r5   r6   r7   r8   r;  r<  r9   r9   r9   r:   r9    s   r9  c                   @   s    e Zd ZdZdd Zdd ZdS )_PortalRootz/
    Root object, used to login to portal.
    c                 C   s
   || _ d S r>   )portal)rC   r>  r9   r9   r:   r@      s    z_PortalRoot.__init__c                 C   s   t | j|S r>   )_PortalWrapperr>  )rC   rQ   r9   r9   r:   r7    s    z_PortalRoot.rootObjectN)r5   r6   r7   r8   r@   r7  r9   r9   r9   r:   r=    s   r=  c                   @   s   e Zd ZdZdd ZdS )_JellyableAvatarMixinzk
    Helper class for code which deals with avatars which PB must be capable of
    sending to a peer.
    c                    sT   |\}} t |st|d}| } g  fdd}|| jj|< | 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.
        rS   c                     s     sd S  d }  d= |   d S r   r9   )fnZlogoutr9   r:   maybeLogout  s
    z3_JellyableAvatarMixin._cbLogin.<locals>.maybeLogout)r   r5  rg   r   rQ   r   rs   )rC   resultZ	interfaceZavatarr   rC  r9   rB  r:   _cbLogin  s    


z_JellyableAvatarMixin._cbLoginN)r5   r6   r7   r8   rE  r9   r9   r9   r:   r@    s   r@  c                   @   s(   e Zd ZdZdd Zdd Zdd ZdS )	r?  z=
    Root Referenceable object, used to login to portal.
    c                 C   s   || _ || _d S r>   )r>  rQ   )rC   r>  rQ   r9   r9   r:   r@   1  s    z_PortalWrapper.__init__c                 C   s   t  }|t| j| j||fS )z[
        Start of username/password login.

        @param username: The username.
        )r  _PortalAuthChallengerr>  rQ   )rC   r  cr9   r9   r:   remote_login6  s    z_PortalWrapper.remote_loginc                 C   s"   | j t |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.
        )r>  r/  r   rZ   r0  rE  )rC   mindr   r9   r9   r:   remote_loginAnonymous@  s    z$_PortalWrapper.remote_loginAnonymousN)r5   r6   r7   r8   r@   rH  rJ  r9   r9   r9   r:   r?  ,  s   
r?  c                   @   s0   e Zd ZdZdd Zdd Zdd Zdd	 Zd
S )rF  z5
    Called with response to password challenge.
    c                 C   s   || _ || _|| _|| _d S r>   )r>  rQ   r  r  )rC   r>  rQ   r  r  r9   r9   r:   r@   V  s    z_PortalAuthChallenger.__init__c                 C   s&   || _ | j| |t}|| j |S r>   )responser>  r/  rZ   r0  rE  )rC   rK  rI  r   r9   r9   r:   remote_respond]  s    z$_PortalAuthChallenger.remote_respondc                 C   s   |  t| S )z
        L{IUsernameHashedPassword}

        @param password: The password.
        @return: L{_PortalAuthChallenger.checkMD5Password}
        )r<  r   r  )rC   r  r9   r9   r:   r;  d  s    z#_PortalAuthChallenger.checkPasswordc                 C   s.   t  }|| || j | }| j|kS )z
        L{IUsernameMD5Password}

        @param md5Password:
        @rtype: L{bool}
        @return: L{True} if password matches.
        )r   r  r  r  rK  )rC   Zmd5PasswordZmdZcorrectr9   r9   r:   r<  n  s
    
z&_PortalAuthChallenger.checkMD5PasswordN)r5   r6   r7   r8   r@   rL  r;  r<  r9   r9   r9   r:   rF  Q  s
   
rF  r#   r   r    r!   r"   r$   r%   r&   r'   r(   r)   r*   r+   r,   r-   r.   r/   r0   r1   r2   r   portno)r   )cr8   Z
__future__r   r   r  Zhashlibr   Zzope.interfacer   r   Ztwisted.pythonr   r   r	   Ztwisted.python.compatr
   r   r  r   r   r   Ztwisted.internetr   r   Ztwisted.cred.portalr   Ztwisted.cred.credentialsr   r   r   r   Ztwisted.persistedr   Ztwisted.python.componentsr   Ztwisted.spread.interfacesr   r   Ztwisted.spread.jellyr   r   r   r   Ztwisted.spreadr   Ztwisted.spread.flavorsr   r    r!   r"   r#   r$   r%   r&   r'   r(   r)   r*   r+   r,   r-   r.   r/   r0   r1   r2   r   rM  r?   r3   r;   r<   r=   rF   rY   rZ   r_   rg   Z	Ephemeralrk   r   r   r   r   r   r   r   r  r  ZClientFactoryr  ZServerFactoryr6  r9  r=  r@  r?  rF  __all__r9   r9   r9   r:   <module>   s   *) 

(+

     R 3,!%-                            