Example #1
0
    def checkBadMessage2(self):
        # just like a real message, but with an unpicklable argument
        global Hack
        class Hack:
            pass

        msg = Marshaller().encode(1, 0, "foo", (Hack(),))
        self._bad_message(msg)
        del Hack
Example #2
0
    def __init__(self, sock, addr, obj, tag, map=None):
        self.obj = None
        self.marshal = Marshaller()
        self.closed = False
        self.peer_protocol_version = None # set in recv_handshake()

        assert tag in "CS"
        self.tag = tag
        self.logger = logging.getLogger('ZEO.zrpc.Connection(%c)' % tag)
        if isinstance(addr, tuple):
            self.log_label = "(%s:%d) " % addr
        else:
            self.log_label = "(%s) " % addr

        # Supply our own socket map, so that we don't get registered with
        # the asyncore socket map just yet.  The initial protocol messages
        # are treated very specially, and we dare not get invoked by asyncore
        # before that special-case setup is complete.  Some of that setup
        # occurs near the end of this constructor, and the rest is done by
        # a concrete subclass's handshake() method.  Unfortunately, because
        # we ultimately derive from asyncore.dispatcher, it's not possible
        # to invoke the superclass constructor without asyncore stuffing
        # us into _some_ socket map.
        ourmap = {}
        self.__super_init(sock, addr, map=ourmap)

        # The singleton dict is used in synchronous mode when a method
        # needs to call into asyncore to try to force some I/O to occur.
        # The singleton dict is a socket map containing only this object.
        self._singleton = {self._fileno: self}

        # msgid_lock guards access to msgid
        self.msgid = 0
        self.msgid_lock = threading.Lock()

        # replies_cond is used to block when a synchronous call is
        # waiting for a response
        self.replies_cond = threading.Condition()
        self.replies = {}

        # waiting_for_reply is used internally to indicate whether
        # a call is in progress.  setting a session key is deferred
        # until after the call returns.
        self.waiting_for_reply = False
        self.delay_sesskey = None
        self.register_object(obj)

        # The first message we see is a protocol handshake.  message_input()
        # is temporarily replaced by recv_handshake() to treat that message
        # specially.  revc_handshake() does "del self.message_input", which
        # uncovers the normal message_input() method thereafter.
        self.message_input = self.recv_handshake

        # Server and client need to do different things for protocol
        # negotiation, and handshake() is implemented differently in each.
        self.handshake()

        # Now it's safe to register with asyncore's socket map; it was not
        # safe before message_input was replaced, or before handshake() was
        # invoked.
        # Obscure:  in Python 2.4, the base asyncore.dispatcher class grew
        # a ._map attribute, which is used instead of asyncore's global
        # socket map when ._map isn't None.  Because we passed `ourmap` to
        # the base class constructor above, in 2.4 asyncore believes we want
        # to use `ourmap` instead of the global socket map -- but we don't.
        # So we have to replace our ._map with the global socket map, and
        # update the global socket map with `ourmap`.  Replacing our ._map
        # isn't necessary before Python 2.4, but doesn't hurt then (it just
        # gives us an unused attribute in 2.3); updating the global socket
        # map is necessary regardless of Python version.
        if map is None:
            map = asyncore.socket_map
        self._map = map
        map.update(ourmap)
Example #3
0
class Connection(smac.SizedMessageAsyncConnection, object):
    """Dispatcher for RPC on object on both sides of socket.

    The connection supports synchronous calls, which expect a return,
    and asynchronous calls, which do not.

    It uses the Marshaller class to handle encoding and decoding of
    method calls and arguments.  Marshaller uses pickle to encode
    arbitrary Python objects.  The code here doesn't ever see the wire
    format.

    A Connection is designed for use in a multithreaded application,
    where a synchronous call must block until a response is ready.

    A socket connection between a client and a server allows either
    side to invoke methods on the other side.  The processes on each
    end of the socket use a Connection object to manage communication.

    The Connection deals with decoded RPC messages.  They are
    represented as four-tuples containing: msgid, flags, method name,
    and a tuple of method arguments.

    The msgid starts at zero and is incremented by one each time a
    method call message is sent.  Each side of the connection has a
    separate msgid state.

    When one side of the connection (the client) calls a method, it
    sends a message with a new msgid.  The other side (the server),
    replies with a message that has the same msgid, the string
    ".reply" (the global variable REPLY) as the method name, and the
    actual return value in the args position.  Note that each side of
    the Connection can initiate a call, in which case it will be the
    client for that particular call.

    The protocol also supports asynchronous calls.  The client does
    not wait for a return value for an asynchronous call.  The only
    defined flag is ASYNC.  If a method call message has the ASYNC
    flag set, the server will raise an exception.

    If a method call raises an Exception, the exception is propagated
    back to the client via the REPLY message.  The client side will
    raise any exception it receives instead of returning the value to
    the caller.
    """

    __super_init = smac.SizedMessageAsyncConnection.__init__
    __super_close = smac.SizedMessageAsyncConnection.close
    __super_setSessionKey = smac.SizedMessageAsyncConnection.setSessionKey

    # Protocol history:
    #
    # Z200 -- Original ZEO 2.0 protocol
    #
    # Z201 -- Added invalidateTransaction() to client.
    #         Renamed several client methods.
    #         Added several sever methods:
    #             lastTransaction()
    #             getAuthProtocol() and scheme-specific authentication methods
    #             getExtensionMethods().
    #             getInvalidations().
    #
    # Z303 -- named after the ZODB release 3.3
    #         Added methods for MVCC:
    #             loadBefore()
    #         A Z303 client cannot talk to a Z201 server, because the latter
    #         doesn't support MVCC.  A Z201 client can talk to a Z303 server,
    #         but because (at least) the type of the root object changed
    #         from ZODB.PersistentMapping to persistent.mapping, the older
    #         client can't actually make progress if a Z303 client created,
    #         or ever modified, the root.
    #
    # Z308 -- named after the ZODB release 3.8
    #         Added blob-support server methods:
    #             sendBlob
    #             storeBlobStart
    #             storeBlobChunk
    #             storeBlobEnd
    #             storeBlobShared
    #         Added blob-support client methods:
    #             receiveBlobStart
    #             receiveBlobChunk
    #             receiveBlobStop
    #
    # Z309 -- named after the ZODB release 3.9
    #         New server methods:
    #             restorea, iterator_start, iterator_next,
    #             iterator_record_start, iterator_record_next,
    #             iterator_gc

    # Protocol variables:
    # Our preferred protocol.
    current_protocol = "Z309"

    # If we're a client, an exhaustive list of the server protocols we
    # can accept.
    servers_we_can_talk_to = ["Z308", current_protocol]

    # If we're a server, an exhaustive list of the client protocols we
    # can accept.
    clients_we_can_talk_to = ["Z200", "Z201", "Z303", "Z308", current_protocol]

    # This is pretty excruciating.  Details:
    #
    # 3.3 server 3.2 client
    #     server sends Z303 to client
    #     client computes min(Z303, Z201) == Z201 as the protocol to use
    #     client sends Z201 to server
    #     OK, because Z201 is in the server's clients_we_can_talk_to
    #
    # 3.2 server 3.3 client
    #     server sends Z201 to client
    #     client computes min(Z303, Z201) == Z201 as the protocol to use
    #     Z201 isn't in the client's servers_we_can_talk_to, so client
    #         raises exception
    #
    # 3.3 server 3.3 client
    #     server sends Z303 to client
    #     client computes min(Z303, Z303) == Z303 as the protocol to use
    #     Z303 is in the client's servers_we_can_talk_to, so client
    #         sends Z303 to server
    #     OK, because Z303 is in the server's clients_we_can_talk_to

    # Exception types that should not be logged:
    unlogged_exception_types = ()

    # Client constructor passes 'C' for tag, server constructor 'S'.  This
    # is used in log messages, and to determine whether we can speak with
    # our peer.
    def __init__(self, sock, addr, obj, tag, map=None):
        self.obj = None
        self.marshal = Marshaller()
        self.closed = False
        self.peer_protocol_version = None # set in recv_handshake()

        assert tag in "CS"
        self.tag = tag
        self.logger = logging.getLogger('ZEO.zrpc.Connection(%c)' % tag)
        if isinstance(addr, tuple):
            self.log_label = "(%s:%d) " % addr
        else:
            self.log_label = "(%s) " % addr

        # Supply our own socket map, so that we don't get registered with
        # the asyncore socket map just yet.  The initial protocol messages
        # are treated very specially, and we dare not get invoked by asyncore
        # before that special-case setup is complete.  Some of that setup
        # occurs near the end of this constructor, and the rest is done by
        # a concrete subclass's handshake() method.  Unfortunately, because
        # we ultimately derive from asyncore.dispatcher, it's not possible
        # to invoke the superclass constructor without asyncore stuffing
        # us into _some_ socket map.
        ourmap = {}
        self.__super_init(sock, addr, map=ourmap)

        # The singleton dict is used in synchronous mode when a method
        # needs to call into asyncore to try to force some I/O to occur.
        # The singleton dict is a socket map containing only this object.
        self._singleton = {self._fileno: self}

        # msgid_lock guards access to msgid
        self.msgid = 0
        self.msgid_lock = threading.Lock()

        # replies_cond is used to block when a synchronous call is
        # waiting for a response
        self.replies_cond = threading.Condition()
        self.replies = {}

        # waiting_for_reply is used internally to indicate whether
        # a call is in progress.  setting a session key is deferred
        # until after the call returns.
        self.waiting_for_reply = False
        self.delay_sesskey = None
        self.register_object(obj)

        # The first message we see is a protocol handshake.  message_input()
        # is temporarily replaced by recv_handshake() to treat that message
        # specially.  revc_handshake() does "del self.message_input", which
        # uncovers the normal message_input() method thereafter.
        self.message_input = self.recv_handshake

        # Server and client need to do different things for protocol
        # negotiation, and handshake() is implemented differently in each.
        self.handshake()

        # Now it's safe to register with asyncore's socket map; it was not
        # safe before message_input was replaced, or before handshake() was
        # invoked.
        # Obscure:  in Python 2.4, the base asyncore.dispatcher class grew
        # a ._map attribute, which is used instead of asyncore's global
        # socket map when ._map isn't None.  Because we passed `ourmap` to
        # the base class constructor above, in 2.4 asyncore believes we want
        # to use `ourmap` instead of the global socket map -- but we don't.
        # So we have to replace our ._map with the global socket map, and
        # update the global socket map with `ourmap`.  Replacing our ._map
        # isn't necessary before Python 2.4, but doesn't hurt then (it just
        # gives us an unused attribute in 2.3); updating the global socket
        # map is necessary regardless of Python version.
        if map is None:
            map = asyncore.socket_map
        self._map = map
        map.update(ourmap)

    def __repr__(self):
        return "<%s %s>" % (self.__class__.__name__, self.addr)

    __str__ = __repr__ # Defeat asyncore's dreaded __getattr__

    def log(self, message, level=BLATHER, exc_info=False):
        self.logger.log(level, self.log_label + message, exc_info=exc_info)

    def close(self):
        self.mgr.close_conn(self)
        if self.closed:
            return
        self._singleton.clear()
        self.closed = True
        self.__super_close()
        self.trigger.pull_trigger()
        self.replies_cond.acquire()
        self.replies_cond.notifyAll()
        self.replies_cond.release()

    def register_object(self, obj):
        """Register obj as the true object to invoke methods on."""
        self.obj = obj

    # Subclass must implement.  handshake() is called by the constructor,
    # near its end, but before self is added to asyncore's socket map.
    # When a connection is created the first message sent is a 4-byte
    # protocol version.  This allows the protocol to evolve over time, and
    # lets servers handle clients using multiple versions of the protocol.
    # In general, the server's handshake() just needs to send the server's
    # preferred protocol; the client's also needs to queue (delay) outgoing
    # messages until it sees the handshake from the server.
    def handshake(self):
        raise NotImplementedError

    # Replaces message_input() for the first message received.  Records the
    # protocol sent by the peer in `peer_protocol_version`, restores the
    # normal message_input() method, and raises an exception if the peer's
    # protocol is unacceptable.  That's all the server needs to do.  The
    # client needs to do additional work in response to the server's
    # handshake, and extends this method.
    def recv_handshake(self, proto):
        # Extended by ManagedClientConnection.
        del self.message_input  # uncover normal-case message_input()
        self.peer_protocol_version = proto

        if self.tag == 'C':
            good_protos = self.servers_we_can_talk_to
        else:
            assert self.tag == 'S'
            good_protos = self.clients_we_can_talk_to

        if proto in good_protos:
            self.log("received handshake %r" % proto, level=logging.INFO)
        else:
            self.log("bad handshake %s" % short_repr(proto),
                     level=logging.ERROR)
            raise ZRPCError("bad handshake %r" % proto)

    def message_input(self, message):
        """Decode an incoming message and dispatch it"""
        # If something goes wrong during decoding, the marshaller
        # will raise an exception.  The exception will ultimately
        # result in asycnore calling handle_error(), which will
        # close the connection.
        msgid, flags, name, args = self.marshal.decode(message)

        if __debug__:
            self.log("recv msg: %s, %s, %s, %s" % (msgid, flags, name,
                                                   short_repr(args)),
                     level=TRACE)
        if name == REPLY:
            self.handle_reply(msgid, flags, args)
        else:
            self.handle_request(msgid, flags, name, args)

    def handle_reply(self, msgid, flags, args):
        if __debug__:
            self.log("recv reply: %s, %s, %s"
                     % (msgid, flags, short_repr(args)), level=TRACE)
        self.replies_cond.acquire()
        try:
            self.replies[msgid] = flags, args
            self.replies_cond.notifyAll()
        finally:
            self.replies_cond.release()

    def handle_request(self, msgid, flags, name, args):
        obj = self.obj

        if name.startswith('_') or not hasattr(obj, name):
            if obj is None:
                if __debug__:
                    self.log("no object calling %s%s"
                             % (name, short_repr(args)),
                             level=logging.DEBUG)
                return

            msg = "Invalid method name: %s on %s" % (name, repr(obj))
            raise ZRPCError(msg)
        if __debug__:
            self.log("calling %s%s" % (name, short_repr(args)),
                     level=logging.DEBUG)

        meth = getattr(obj, name)
        try:
            self.waiting_for_reply = True
            try:
                ret = meth(*args)
            finally:
                self.waiting_for_reply = False
        except (SystemExit, KeyboardInterrupt):
            raise
        except Exception, msg:
            if not isinstance(msg, self.unlogged_exception_types):
                self.log("%s() raised exception: %s" % (name, msg),
                         logging.ERROR, exc_info=True)
            error = sys.exc_info()[:2]
            return self.return_error(msgid, flags, *error)

        if flags & ASYNC:
            if ret is not None:
                raise ZRPCError("async method %s returned value %s" %
                                (name, short_repr(ret)))
        else:
            if __debug__:
                self.log("%s returns %s" % (name, short_repr(ret)),
                         logging.DEBUG)
            if isinstance(ret, Delay):
                ret.set_sender(msgid, self.send_reply, self.return_error)
            else:
                self.send_reply(msgid, ret)

        if self.delay_sesskey:
            self.__super_setSessionKey(self.delay_sesskey)
            self.delay_sesskey = None
Example #4
0
    def __init__(self, sock, addr, obj, tag, map=None):
        self.obj = None
        self.marshal = Marshaller()
        self.closed = False
        self.peer_protocol_version = None  # set in recv_handshake()

        assert tag in "CS"
        self.tag = tag
        self.logger = logging.getLogger('ZEO.zrpc.Connection(%c)' % tag)
        if isinstance(addr, tuple):
            self.log_label = "(%s:%d) " % addr
        else:
            self.log_label = "(%s) " % addr

        # Supply our own socket map, so that we don't get registered with
        # the asyncore socket map just yet.  The initial protocol messages
        # are treated very specially, and we dare not get invoked by asyncore
        # before that special-case setup is complete.  Some of that setup
        # occurs near the end of this constructor, and the rest is done by
        # a concrete subclass's handshake() method.  Unfortunately, because
        # we ultimately derive from asyncore.dispatcher, it's not possible
        # to invoke the superclass constructor without asyncore stuffing
        # us into _some_ socket map.
        ourmap = {}
        self.__super_init(sock, addr, map=ourmap)

        # A Connection either uses asyncore directly or relies on an
        # asyncore mainloop running in a separate thread.  If
        # thr_async is true, then the mainloop is running in a
        # separate thread.  If thr_async is true, then the asyncore
        # trigger (self.trigger) is used to notify that thread of
        # activity on the current thread.
        self.thr_async = False
        self.trigger = None
        self._prepare_async()

        # The singleton dict is used in synchronous mode when a method
        # needs to call into asyncore to try to force some I/O to occur.
        # The singleton dict is a socket map containing only this object.
        self._singleton = {self._fileno: self}

        # msgid_lock guards access to msgid
        self.msgid = 0
        self.msgid_lock = threading.Lock()

        # replies_cond is used to block when a synchronous call is
        # waiting for a response
        self.replies_cond = threading.Condition()
        self.replies = {}

        # waiting_for_reply is used internally to indicate whether
        # a call is in progress.  setting a session key is deferred
        # until after the call returns.
        self.waiting_for_reply = False
        self.delay_sesskey = None
        self.register_object(obj)

        # The first message we see is a protocol handshake.  message_input()
        # is temporarily replaced by recv_handshake() to treat that message
        # specially.  revc_handshake() does "del self.message_input", which
        # uncovers the normal message_input() method thereafter.
        self.message_input = self.recv_handshake

        # Server and client need to do different things for protocol
        # negotiation, and handshake() is implemented differently in each.
        self.handshake()

        # Now it's safe to register with asyncore's socket map; it was not
        # safe before message_input was replaced, or before handshake() was
        # invoked.
        # Obscure:  in Python 2.4, the base asyncore.dispatcher class grew
        # a ._map attribute, which is used instead of asyncore's global
        # socket map when ._map isn't None.  Because we passed `ourmap` to
        # the base class constructor above, in 2.4 asyncore believes we want
        # to use `ourmap` instead of the global socket map -- but we don't.
        # So we have to replace our ._map with the global socket map, and
        # update the global socket map with `ourmap`.  Replacing our ._map
        # isn't necessary before Python 2.4, but doesn't hurt then (it just
        # gives us an unused attribute in 2.3); updating the global socket
        # map is necessary regardless of Python version.
        if map is None:
            map = asyncore.socket_map
        self._map = map
        map.update(ourmap)
Example #5
0
class Connection(smac.SizedMessageAsyncConnection, object):
    """Dispatcher for RPC on object on both sides of socket.

    The connection supports synchronous calls, which expect a return,
    and asynchronous calls, which do not.

    It uses the Marshaller class to handle encoding and decoding of
    method calls and arguments.  Marshaller uses pickle to encode
    arbitrary Python objects.  The code here doesn't ever see the wire
    format.

    A Connection is designed for use in a multithreaded application,
    where a synchronous call must block until a response is ready.

    A socket connection between a client and a server allows either
    side to invoke methods on the other side.  The processes on each
    end of the socket use a Connection object to manage communication.

    The Connection deals with decoded RPC messages.  They are
    represented as four-tuples containing: msgid, flags, method name,
    and a tuple of method arguments.

    The msgid starts at zero and is incremented by one each time a
    method call message is sent.  Each side of the connection has a
    separate msgid state.

    When one side of the connection (the client) calls a method, it
    sends a message with a new msgid.  The other side (the server),
    replies with a message that has the same msgid, the string
    ".reply" (the global variable REPLY) as the method name, and the
    actual return value in the args position.  Note that each side of
    the Connection can initiate a call, in which case it will be the
    client for that particular call.

    The protocol also supports asynchronous calls.  The client does
    not wait for a return value for an asynchronous call.  The only
    defined flag is ASYNC.  If a method call message has the ASYNC
    flag set, the server will raise an exception.

    If a method call raises an Exception, the exception is propagated
    back to the client via the REPLY message.  The client side will
    raise any exception it receives instead of returning the value to
    the caller.
    """

    __super_init = smac.SizedMessageAsyncConnection.__init__
    __super_close = smac.SizedMessageAsyncConnection.close
    __super_setSessionKey = smac.SizedMessageAsyncConnection.setSessionKey

    # Protocol history:
    #
    # Z200 -- Original ZEO 2.0 protocol
    #
    # Z201 -- Added invalidateTransaction() to client.
    #         Renamed several client methods.
    #         Added several sever methods:
    #             lastTransaction()
    #             getAuthProtocol() and scheme-specific authentication methods
    #             getExtensionMethods().
    #             getInvalidations().
    #
    # Z303 -- named after the ZODB release 3.3
    #         Added methods for MVCC:
    #             loadBefore()
    #         A Z303 client cannot talk to a Z201 server, because the latter
    #         doesn't support MVCC.  A Z201 client can talk to a Z303 server,
    #         but because (at least) the type of the root object changed
    #         from ZODB.PersistentMapping to persistent.mapping, the older
    #         client can't actually make progress if a Z303 client created,
    #         or ever modified, the root.
    #
    # Z308 -- named after the ZODB release 3.8
    #         Added blob-support server methods:
    #             sendBlob
    #             storeBlobStart
    #             storeBlobChunk
    #             storeBlobEnd
    #             storeBlobShared
    #         Added blob-support client methods:
    #             receiveBlobStart
    #             receiveBlobChunk
    #             receiveBlobStop

    # XXX add blob methods

    # Protocol variables:
    # Our preferred protocol.
    current_protocol = "Z308"

    # If we're a client, an exhaustive list of the server protocols we
    # can accept.
    servers_we_can_talk_to = [current_protocol]

    # If we're a server, an exhaustive list of the client protocols we
    # can accept.
    clients_we_can_talk_to = ["Z200", "Z201", "Z303", current_protocol]

    # This is pretty excruciating.  Details:
    #
    # 3.3 server 3.2 client
    #     server sends Z303 to client
    #     client computes min(Z303, Z201) == Z201 as the protocol to use
    #     client sends Z201 to server
    #     OK, because Z201 is in the server's clients_we_can_talk_to
    #
    # 3.2 server 3.3 client
    #     server sends Z201 to client
    #     client computes min(Z303, Z201) == Z201 as the protocol to use
    #     Z201 isn't in the client's servers_we_can_talk_to, so client
    #         raises exception
    #
    # 3.3 server 3.3 client
    #     server sends Z303 to client
    #     client computes min(Z303, Z303) == Z303 as the protocol to use
    #     Z303 is in the client's servers_we_can_talk_to, so client
    #         sends Z303 to server
    #     OK, because Z303 is in the server's clients_we_can_talk_to

    # Client constructor passes 'C' for tag, server constructor 'S'.  This
    # is used in log messages, and to determine whether we can speak with
    # our peer.
    def __init__(self, sock, addr, obj, tag, map=None):
        self.obj = None
        self.marshal = Marshaller()
        self.closed = False
        self.peer_protocol_version = None  # set in recv_handshake()

        assert tag in "CS"
        self.tag = tag
        self.logger = logging.getLogger('ZEO.zrpc.Connection(%c)' % tag)
        if isinstance(addr, tuple):
            self.log_label = "(%s:%d) " % addr
        else:
            self.log_label = "(%s) " % addr

        # Supply our own socket map, so that we don't get registered with
        # the asyncore socket map just yet.  The initial protocol messages
        # are treated very specially, and we dare not get invoked by asyncore
        # before that special-case setup is complete.  Some of that setup
        # occurs near the end of this constructor, and the rest is done by
        # a concrete subclass's handshake() method.  Unfortunately, because
        # we ultimately derive from asyncore.dispatcher, it's not possible
        # to invoke the superclass constructor without asyncore stuffing
        # us into _some_ socket map.
        ourmap = {}
        self.__super_init(sock, addr, map=ourmap)

        # A Connection either uses asyncore directly or relies on an
        # asyncore mainloop running in a separate thread.  If
        # thr_async is true, then the mainloop is running in a
        # separate thread.  If thr_async is true, then the asyncore
        # trigger (self.trigger) is used to notify that thread of
        # activity on the current thread.
        self.thr_async = False
        self.trigger = None
        self._prepare_async()

        # The singleton dict is used in synchronous mode when a method
        # needs to call into asyncore to try to force some I/O to occur.
        # The singleton dict is a socket map containing only this object.
        self._singleton = {self._fileno: self}

        # msgid_lock guards access to msgid
        self.msgid = 0
        self.msgid_lock = threading.Lock()

        # replies_cond is used to block when a synchronous call is
        # waiting for a response
        self.replies_cond = threading.Condition()
        self.replies = {}

        # waiting_for_reply is used internally to indicate whether
        # a call is in progress.  setting a session key is deferred
        # until after the call returns.
        self.waiting_for_reply = False
        self.delay_sesskey = None
        self.register_object(obj)

        # The first message we see is a protocol handshake.  message_input()
        # is temporarily replaced by recv_handshake() to treat that message
        # specially.  revc_handshake() does "del self.message_input", which
        # uncovers the normal message_input() method thereafter.
        self.message_input = self.recv_handshake

        # Server and client need to do different things for protocol
        # negotiation, and handshake() is implemented differently in each.
        self.handshake()

        # Now it's safe to register with asyncore's socket map; it was not
        # safe before message_input was replaced, or before handshake() was
        # invoked.
        # Obscure:  in Python 2.4, the base asyncore.dispatcher class grew
        # a ._map attribute, which is used instead of asyncore's global
        # socket map when ._map isn't None.  Because we passed `ourmap` to
        # the base class constructor above, in 2.4 asyncore believes we want
        # to use `ourmap` instead of the global socket map -- but we don't.
        # So we have to replace our ._map with the global socket map, and
        # update the global socket map with `ourmap`.  Replacing our ._map
        # isn't necessary before Python 2.4, but doesn't hurt then (it just
        # gives us an unused attribute in 2.3); updating the global socket
        # map is necessary regardless of Python version.
        if map is None:
            map = asyncore.socket_map
        self._map = map
        map.update(ourmap)

    def __repr__(self):
        return "<%s %s>" % (self.__class__.__name__, self.addr)

    __str__ = __repr__  # Defeat asyncore's dreaded __getattr__

    def log(self, message, level=BLATHER, exc_info=False):
        self.logger.log(level, self.log_label + message, exc_info=exc_info)

    def close(self):
        if self.closed:
            return
        self._singleton.clear()
        self.closed = True
        self.__super_close()
        self.close_trigger()
        self.replies_cond.acquire()
        self.replies_cond.notifyAll()
        self.replies_cond.release()

    def close_trigger(self):
        # Overridden by ManagedClientConnection.
        if self.trigger is not None:
            self.trigger.pull_trigger()
            self.trigger.close()

    def register_object(self, obj):
        """Register obj as the true object to invoke methods on."""
        self.obj = obj

    # Subclass must implement.  handshake() is called by the constructor,
    # near its end, but before self is added to asyncore's socket map.
    # When a connection is created the first message sent is a 4-byte
    # protocol version.  This allows the protocol to evolve over time, and
    # lets servers handle clients using multiple versions of the protocol.
    # In general, the server's handshake() just needs to send the server's
    # preferred protocol; the client's also needs to queue (delay) outgoing
    # messages until it sees the handshake from the server.
    def handshake(self):
        raise NotImplementedError

    # Replaces message_input() for the first message received.  Records the
    # protocol sent by the peer in `peer_protocol_version`, restores the
    # normal message_input() method, and raises an exception if the peer's
    # protocol is unacceptable.  That's all the server needs to do.  The
    # client needs to do additional work in response to the server's
    # handshake, and extends this method.
    def recv_handshake(self, proto):
        # Extended by ManagedClientConnection.
        del self.message_input  # uncover normal-case message_input()
        self.peer_protocol_version = proto

        if self.tag == 'C':
            good_protos = self.servers_we_can_talk_to
        else:
            assert self.tag == 'S'
            good_protos = self.clients_we_can_talk_to

        if proto in good_protos:
            self.log("received handshake %r" % proto, level=logging.INFO)
        else:
            self.log("bad handshake %s" % short_repr(proto),
                     level=logging.ERROR)
            raise ZRPCError("bad handshake %r" % proto)

    def message_input(self, message):
        """Decode an incoming message and dispatch it"""
        # If something goes wrong during decoding, the marshaller
        # will raise an exception.  The exception will ultimately
        # result in asycnore calling handle_error(), which will
        # close the connection.
        msgid, flags, name, args = self.marshal.decode(message)

        if __debug__:
            self.log("recv msg: %s, %s, %s, %s" %
                     (msgid, flags, name, short_repr(args)),
                     level=TRACE)
        if name == REPLY:
            self.handle_reply(msgid, flags, args)
        else:
            self.handle_request(msgid, flags, name, args)

    def handle_reply(self, msgid, flags, args):
        if __debug__:
            self.log("recv reply: %s, %s, %s" %
                     (msgid, flags, short_repr(args)),
                     level=TRACE)
        self.replies_cond.acquire()
        try:
            self.replies[msgid] = flags, args
            self.replies_cond.notifyAll()
        finally:
            self.replies_cond.release()

    def handle_request(self, msgid, flags, name, args):
        obj = self.obj

        if name.startswith('_') or not hasattr(obj, name):
            if obj is None:
                if __debug__:
                    self.log("no object calling %s%s" %
                             (name, short_repr(args)),
                             level=logging.DEBUG)
                return

            msg = "Invalid method name: %s on %s" % (name, repr(obj))
            raise ZRPCError(msg)
        if __debug__:
            self.log("calling %s%s" % (name, short_repr(args)),
                     level=logging.DEBUG)

        meth = getattr(obj, name)
        try:
            self.waiting_for_reply = True
            try:
                ret = meth(*args)
            finally:
                self.waiting_for_reply = False
        except (SystemExit, KeyboardInterrupt):
            raise
        except Exception, msg:
            self.log("%s() raised exception: %s" % (name, msg),
                     logging.INFO,
                     exc_info=True)
            error = sys.exc_info()[:2]
            return self.return_error(msgid, flags, *error)

        if flags & ASYNC:
            if ret is not None:
                raise ZRPCError("async method %s returned value %s" %
                                (name, short_repr(ret)))
        else:
            if __debug__:
                self.log("%s returns %s" % (name, short_repr(ret)),
                         logging.DEBUG)
            if isinstance(ret, Delay):
                ret.set_sender(msgid, self.send_reply, self.return_error)
            else:
                self.send_reply(msgid, ret)

        if self.delay_sesskey:
            self.__super_setSessionKey(self.delay_sesskey)
            self.delay_sesskey = None