Beispiel #1
0
    def test_ctor(self):
        e = message.Hello(u"realm1",
                          {u'publisher': role.RolePublisherFeatures()})
        msg = e.marshal()
        self.assertEqual(len(msg), 3)
        self.assertEqual(msg[0], message.Hello.MESSAGE_TYPE)
        self.assertEqual(msg[1], u"realm1")
        self.assertEqual(msg[2], {u'roles': {u'publisher': {}}})

        e = message.Hello(
            u"realm1", {
                u'publisher':
                role.RolePublisherFeatures(subscriber_blackwhite_listing=True)
            })
        msg = e.marshal()
        self.assertEqual(len(msg), 3)
        self.assertEqual(msg[0], message.Hello.MESSAGE_TYPE)
        self.assertEqual(msg[1], u"realm1")
        self.assertEqual(
            msg[2], {
                u'roles': {
                    u'publisher': {
                        u'features': {
                            u'subscriber_blackwhite_listing': True
                        }
                    }
                }
            })
Beispiel #2
0
    def test_router_session_lifecycle(self):
        """
        We see all 'lifecycle' notifications.
        """
        from crossbar.router.session import RouterApplicationSession

        def mock_fire(name, *args, **kw):
            fired.append(name)
            return defer.succeed(None)

        fired = []
        session = mock.Mock()
        session._realm = u'realm'
        session.fire = mock.Mock(side_effect=mock_fire)
        router_factory = mock.Mock()
        rap = RouterApplicationSession(session, router_factory)

        # we never fake out the 'Welcome' message, so there will be no
        # 'ready' notification...
        rap.send(
            message.Hello(u'realm', {u'caller': role.RoleCallerFeatures()}))
        rap.send(message.Goodbye(u'wamp.reason.logout',
                                 u'some custom message'))

        self.assertTrue('connect' in fired)
        self.assertTrue('join' in fired)
        self.assertTrue('ready' in fired)
        self.assertTrue('leave' in fired)
        self.assertTrue('disconnect' in fired)
    def test_router_session_internal_error_onHello(self):
        """
        similar to above, but during _RouterSession's onMessage handling,
        where it calls self.onHello
        """
        # setup
        transport = mock.MagicMock()
        transport.get_channel_id = mock.MagicMock(return_value=b'deadbeef')
        the_exception = RuntimeError("kerblam")

        def boom(*args, **kw):
            raise the_exception
        session = self.session_factory()  # __call__ on the _RouterSessionFactory
        session.onHello = boom
        session.onOpen(transport)
        msg = message.Hello(u'realm1', dict(caller=role.RoleCallerFeatures()))

        # XXX think: why isn't this using _RouterSession.log?
        from crossbar.router.session import RouterSession
        with mock.patch.object(RouterSession, 'log') as logger:
            # do the test; should call onHello which is now "boom", above
            session.onMessage(msg)

            # check we got the right log.failure() call
            self.assertTrue(len(logger.method_calls) > 0)
            call = logger.method_calls[0]
            # for a MagicMock call-object, 0th thing is the method-name, 1st
            # thing is the arg-tuple, 2nd thing is the kwargs.
            self.assertEqual(call[0], 'failure')
            self.assertTrue('failure' in call[2])
            self.assertEqual(call[2]['failure'].value, the_exception)
Beispiel #4
0
    def test_router_session_goodbye_fire_disconnect_error(self):
        """
        Reason should be propagated properly from Goodbye message
        """
        from crossbar.router.session import RouterApplicationSession
        session = mock.Mock()
        the_exception = RuntimeError("sad times at ridgemont high")

        def boom(*args, **kw):
            if args[0] == 'disconnect':
                return defer.fail(the_exception)
            return defer.succeed(None)

        session.fire = mock.Mock(side_effect=boom)
        session._realm = u'realm'
        router_factory = mock.Mock()
        rap = RouterApplicationSession(session, router_factory)

        rap.send(
            message.Hello(u'realm', {u'caller': role.RoleCallerFeatures()}))
        session.reset_mock()
        rap.send(message.Goodbye(u'wamp.reason.logout',
                                 u'some custom message'))

        errors = self.flushLoggedErrors()
        self.assertEqual(1, len(errors))
        self.assertEqual(the_exception, errors[0].value)
Beispiel #5
0
    def test_force_reregister_kick(self):
        """
        Kick an existing registration with force_reregister=True
        """
        raise unittest.SkipTest('FIXME: Adjust unit test mocks #1567')

        session = mock.Mock()
        session._realm = 'realm1'
        self.router.authorize = mock.Mock(return_value=defer.succeed({'allow': True, 'disclose': True}))
        rap = RouterApplicationSession(session, self.router_factory)

        rap.send(message.Hello("realm1", {'caller': role.RoleCallerFeatures()}))
        rap.send(message.Register(1, 'foo'))

        reg_id = session.mock_calls[-1][1][0].registration

        # re-set the authorize, as the Deferred from above is already
        # used-up and it gets called again to authorize the Call
        self.router.authorize = mock.Mock(return_value=defer.succeed({'allow': True, 'disclose': True}))

        # re-register the same procedure
        rap.send(message.Register(2, 'foo', force_reregister=True))

        # the first procedure with 'reg_id' as the Registration ID
        # should have gotten kicked out
        unregs = [
            call[1][0] for call in session.mock_calls
            if call[0] == 'onMessage' and isinstance(call[1][0], message.Unregistered)
        ]
        self.assertEqual(1, len(unregs))
        unreg = unregs[0]
        self.assertEqual(0, unreg.request)
        self.assertEqual(reg_id, unreg.registration)
Beispiel #6
0
    def test_router_session_goodbye_onLeave_error(self):
        """
        Reason should be propagated properly from Goodbye message
        """
        from crossbar.router.session import RouterApplicationSession
        session = mock.Mock()
        the_exception = RuntimeError("onLeave fails")

        def boom(*args, **kw):
            raise the_exception

        session.onLeave = mock.Mock(side_effect=boom)
        session._realm = u'realm'
        router_factory = mock.Mock()
        rap = RouterApplicationSession(session, router_factory)

        rap.send(
            message.Hello(u'realm', {u'caller': role.RoleCallerFeatures()}))
        session.reset_mock()
        rap.send(message.Goodbye(u'wamp.reason.logout',
                                 u'some custom message'))

        errors = self.flushLoggedErrors()
        self.assertEqual(1, len(errors))
        self.assertEqual(the_exception, errors[0].value)
Beispiel #7
0
    def test_outstanding_invoke(self):
        """
        When a call is pending and the callee goes away, it cancels the
        in-flight call
        """
        raise unittest.SkipTest('FIXME: Adjust unit test mocks #1567')

        session = mock.Mock()
        session._realm = 'realm1'
        self.router.authorize = mock.Mock(
            return_value=defer.succeed({
                'allow': True,
                'disclose': True
            }))
        rap = RouterApplicationSession(session, self.router_factory)

        rap.send(message.Hello("realm1",
                               {'caller': role.RoleCallerFeatures()}))
        rap.send(message.Register(1, 'foo'))

        # we can retrieve the Registration via
        # session.mock_calls[-1][1][0] if req'd

        # re-set the authorize, as the Deferred from above is already
        # used-up and it gets called again to authorize the Call
        self.router.authorize = mock.Mock(
            return_value=defer.succeed({
                'allow': True,
                'disclose': True
            }))
        rap.send(message.Call(42, 'foo'))

        orig = rap.send
        d = defer.Deferred()

        rap.send(message.Goodbye())

        def wrapper(*args, **kw):
            d.callback(args[0])
            return orig(*args, **kw)

        rap.send = wrapper

        # we can do this *after* the call to send() the Goodbye
        # (above) because it takes a reactor-turn to actually
        # process the cancel/errors etc -- hence the Deferred and
        # yield in this test...

        msg = yield d

        self.assertEqual(42, msg.request)
        self.assertEqual('wamp.error.canceled', msg.error)
Beispiel #8
0
def generate_test_messages():
    """
    List of WAMP test message used for serializers. Expand this if you add more
    options or messages.

    This list of WAMP message does not contain any binary app payloads!
    """
    msgs = [
        message.Hello(u"realm1", {u'subscriber': role.RoleSubscriberFeatures()}),
        message.Goodbye(),
        message.Yield(123456),
        message.Yield(123456, args=[1, 2, 3], kwargs={u'foo': 23, u'bar': u'hello'}),
        message.Yield(123456, args=[u'hello']),
        message.Yield(123456, progress=True),
        message.Interrupt(123456),
        message.Interrupt(123456, mode=message.Interrupt.KILL),
        message.Invocation(123456, 789123),
        message.Invocation(123456, 789123, args=[1, 2, 3], kwargs={u'foo': 23, u'bar': u'hello'}),
        message.Invocation(123456, 789123, timeout=10000),
        message.Result(123456),
        message.Result(123456, args=[1, 2, 3], kwargs={u'foo': 23, u'bar': u'hello'}),
        message.Result(123456, progress=True),
        message.Cancel(123456),
        message.Cancel(123456, mode=message.Cancel.KILL),
        message.Call(123456, u'com.myapp.procedure1'),
        message.Call(123456, u'com.myapp.procedure1', args=[1, 2, 3], kwargs={u'foo': 23, u'bar': u'hello'}),
        message.Call(123456, u'com.myapp.procedure1', timeout=10000),
        message.Unregistered(123456),
        message.Unregister(123456, 789123),
        message.Registered(123456, 789123),
        message.Register(123456, u'com.myapp.procedure1'),
        message.Register(123456, u'com.myapp.procedure1', match=u'prefix'),
        message.Register(123456, u'com.myapp.procedure1', invoke=u'roundrobin'),
        message.Event(123456, 789123),
        message.Event(123456, 789123, args=[1, 2, 3], kwargs={u'foo': 23, u'bar': u'hello'}),
        message.Event(123456, 789123, publisher=300),
        message.Published(123456, 789123),
        message.Publish(123456, u'com.myapp.topic1'),
        message.Publish(123456, u'com.myapp.topic1', args=[1, 2, 3], kwargs={u'foo': 23, u'bar': u'hello'}),
        message.Publish(123456, u'com.myapp.topic1', exclude_me=False, exclude=[300], eligible=[100, 200, 300]),
        message.Unsubscribed(123456),
        message.Unsubscribe(123456, 789123),
        message.Subscribed(123456, 789123),
        message.Subscribe(123456, u'com.myapp.topic1'),
        message.Subscribe(123456, u'com.myapp.topic1', match=message.Subscribe.MATCH_PREFIX),
        message.Error(message.Call.MESSAGE_TYPE, 123456, u'com.myapp.error1'),
        message.Error(message.Call.MESSAGE_TYPE, 123456, u'com.myapp.error1', args=[1, 2, 3], kwargs={u'foo': 23, u'bar': u'hello'}),
        message.Call(123456, u'com.myapp.\u4f60\u597d\u4e16\u754c', args=[1, 2, 3]),
        message.Result(123456, args=[1, 2, 3], kwargs={u'en': u'Hello World', u'jp': u'\u3053\u3093\u306b\u3061\u306f\u4e16\u754c'})
    ]
    return [(False, msg) for msg in msgs]
Beispiel #9
0
    async def start(self):
        async with self.session.ws_connect(url=self.url,
                                           protocols=self.protocols) as ws:
            self.ws = ws

            if self.need_stop:
                await self.stop()
                return

            hello = message.Hello(self.realm, self.roles)
            self.send(hello)

            async for ws_msg in ws:
                wamp_msg = self.recv(ws_msg.data)
                wamp_handler = self.get_handler(wamp_msg.MESSAGE_TYPE)
                await wamp_handler(wamp_msg)
Beispiel #10
0
    def join(self, realm, authmethods=None, authid=None):
        """
        Implements :func:`autobahn.wamp.interfaces.ISession.join`
        """
        if six.PY2 and type(realm) == str:
            realm = six.u(realm)
        if six.PY2 and type(authid) == str:
            authid = six.u(authid)

        if self._session_id:
            raise Exception("already joined")

        self._goodbye_sent = False

        msg = message.Hello(realm, role.DEFAULT_CLIENT_ROLES, authmethods, authid)
        self._realm = realm
        self._transport.send(msg)
def generate_test_messages():
   return [
      message.Hello(u"realm1", [role.RoleBrokerFeatures()]),
      message.Goodbye(),
      message.Heartbeat(123, 456),
      message.Yield(123456),
      message.Yield(123456, args = [1, 2, 3], kwargs = {u'foo': 23, u'bar': u'hello'}),
      message.Yield(123456, progress = True),
      message.Interrupt(123456),
      message.Interrupt(123456, mode = message.Interrupt.KILL),
      message.Invocation(123456, 789123),
      message.Invocation(123456, 789123, args = [1, 2, 3], kwargs = {u'foo': 23, u'bar': u'hello'}),
      message.Invocation(123456, 789123, timeout = 10000),
      message.Result(123456),
      message.Result(123456, args = [1, 2, 3], kwargs = {u'foo': 23, u'bar': u'hello'}),
      message.Result(123456, progress = True),
      message.Cancel(123456),
      message.Cancel(123456, mode = message.Cancel.KILL),
      message.Call(123456, u'com.myapp.procedure1'),
      message.Call(123456, u'com.myapp.procedure1', args = [1, 2, 3], kwargs = {u'foo': 23, u'bar': u'hello'}),
      message.Call(123456, u'com.myapp.procedure1', timeout = 10000),
      message.Unregistered(123456),
      message.Unregister(123456, 789123),
      message.Registered(123456, 789123),
      message.Register(123456, u'com.myapp.procedure1'),
      message.Register(123456, u'com.myapp.procedure1', pkeys = [10, 11, 12]),
      message.Event(123456, 789123),
      message.Event(123456, 789123, args = [1, 2, 3], kwargs = {u'foo': 23, u'bar': u'hello'}),
      message.Event(123456, 789123, publisher = 300),
      message.Published(123456, 789123),
      message.Publish(123456, u'com.myapp.topic1'),
      message.Publish(123456, u'com.myapp.topic1', args = [1, 2, 3], kwargs = {u'foo': 23, u'bar': u'hello'}),
      message.Publish(123456, u'com.myapp.topic1', excludeMe = False, exclude = [300], eligible = [100, 200, 300], discloseMe = True),
      message.Unsubscribed(123456),
      message.Unsubscribe(123456, 789123),
      message.Subscribed(123456, 789123),
      message.Subscribe(123456, u'com.myapp.topic1'),
      message.Subscribe(123456, u'com.myapp.topic1', match = message.Subscribe.MATCH_PREFIX),
      message.Error(message.Call.MESSAGE_TYPE, 123456, u'com.myapp.error1'),
      message.Error(message.Call.MESSAGE_TYPE, 123456, u'com.myapp.error1', args = [1, 2, 3], kwargs = {u'foo': 23, u'bar': u'hello'}),
      message.Call(123456, u'com.myapp.\u4f60\u597d\u4e16\u754c', args=[1, 2, 3]),
      message.Result(123456, args=[1, 2, 3], kwargs={u'en': u'Hello World', u'jp': u'\u3053\u3093\u306b\u3061\u306f\u4e16\u754c'})
   ]
Beispiel #12
0
    def test_router_session_goodbye_custom_message(self):
        """
        Reason should be propagated properly from Goodbye message
        """
        from crossbar.router.session import RouterApplicationSession
        session = mock.Mock()
        session._realm = u'realm'
        router_factory = mock.Mock()
        rap = RouterApplicationSession(session, router_factory)

        rap.send(message.Hello(u'realm', {u'caller': role.RoleCallerFeatures()}))
        session.reset_mock()
        rap.send(message.Goodbye(u'wamp.reason.logout', u'some custom message'))

        leaves = [call for call in session.mock_calls if call[0] == 'onLeave']
        self.assertEqual(1, len(leaves))
        details = leaves[0][1][0]
        self.assertEqual(u'wamp.reason.logout', details.reason)
        self.assertEqual(u'some custom message', details.message)
Beispiel #13
0
   def join(self, realm, authmethods = None, authid = None):
      """
      Implements :func:`autobahn.wamp.interfaces.ISession.join`
      """
      if six.PY2 and type(realm) == str:
         realm = six.u(realm)

      if self._session_id:
         raise Exception("already joined")

      self._goodbye_sent = False

      roles = [
         role.RolePublisherFeatures(),
         role.RoleSubscriberFeatures(),
         role.RoleCallerFeatures(),
         role.RoleCalleeFeatures()
      ]

      msg = message.Hello(realm, roles, authmethods, authid)
      self._realm = realm
      self._transport.send(msg)
Beispiel #14
0
 def test_str(self):
     e = message.Hello(u"realm1",
                       {u'publisher': role.RolePublisherFeatures()})
     self.assertIsInstance(str(e), str)
Beispiel #15
0
    def process_connect(self, packet):
        """
        Process the initial Connect message from the MQTT client.

        This should return a pair `(accept_conn, session_present)`, where
        `accept_conn` is a return code:

        0: connection accepted
        1-5: connection refused (see MQTT spec 3.2.2.3)
        """

        # Connect(client_id='paho/4E23D8C09DD9C6CF2C',
        #         flags=ConnectFlags(username=False,
        #                            password=False,
        #                            will=False,
        #                            will_retain=False,
        #                            will_qos=0,
        #                            clean_session=True,
        #                            reserved=False),
        #         keep_alive=60,
        #         will_topic=None,
        #         will_message=None,
        #         username=None,
        #         password=None)
        self.log.info(
            'WampMQTTServerProtocol.process_connect(packet={packet})',
            packet=packet)

        # we don't support session resumption: https://github.com/crossbario/crossbar/issues/892
        if not packet.flags.clean_session:
            self.log.warn(
                'denying MQTT connect from {peer}, as the clients wants to resume a session (which we do not support)',
                peer=peer2str(self.transport.getPeer()))
            return succeed((1, False))

        # we won't support QoS 2: https://github.com/crossbario/crossbar/issues/1046
        if packet.flags.will and packet.flags.will_qos not in [0, 1]:
            self.log.warn(
                'denying MQTT connect from {peer}, as the clients wants to provide a "last will" event with QoS {will_qos} (and we only support QoS 0/1 here)',
                peer=peer2str(self.transport.getPeer()),
                will_qos=packet.flags.will_qos)
            return succeed((1, False))

        # this will be resolved when the MQTT connect handshake is completed
        self._waiting_for_connect = Deferred()

        roles = {
            "subscriber":
            role.RoleSubscriberFeatures(payload_transparency=True,
                                        pattern_based_subscription=True),
            "publisher":
            role.RolePublisherFeatures(payload_transparency=True,
                                       x_acknowledged_event_delivery=True)
        }

        realm = self.factory._options.get('realm', None)

        authmethods = []
        authextra = {
            'mqtt': {
                'client_id': packet.client_id,
                'will': bool(packet.flags.will),
                'will_topic': packet.will_topic
            }
        }

        if ISSLTransport.providedBy(self.transport):
            authmethods.append("tls")

        if packet.username and packet.password:
            authmethods.append("ticket")
            msg = message.Hello(realm=realm,
                                roles=roles,
                                authmethods=authmethods,
                                authid=packet.username,
                                authextra=authextra)
            self._pw_challenge = packet.password

        else:
            authmethods.append("anonymous")
            msg = message.Hello(realm=realm,
                                roles=roles,
                                authmethods=authmethods,
                                authid=packet.client_id,
                                authextra=authextra)

        self._wamp_session.onMessage(msg)

        if packet.flags.will:

            # it's unclear from the MQTT spec whether a) the publication of the last will
            # is to happen in-band during "connect", and if it fails, deny the connection,
            # or b) the last will publication happens _after_ "connect", and the connection
            # succeeds regardless whether the last will publication succeeds or not.
            #
            # we opt for b) here!
            #
            @inlineCallbacks
            @self._waiting_for_connect.addCallback
            def process_will(res):

                self.log.info()

                payload_format, mapped_topic, options = yield self.factory.transform_mqtt(
                    packet.will_topic, packet.will_message)

                request = util.id()

                msg = message.Call(
                    request=request,
                    procedure="wamp.session.add_testament",
                    args=[
                        mapped_topic,
                        options.get('args', None),
                        options.get('kwargs', None),
                        {
                            # specifiy "retain" for when the testament (last will)
                            # will be auto-published by the broker later
                            'retain': bool(packet.flags.will_retain)
                        }
                    ])

                self._wamp_session.onMessage(msg)

                returnValue(res)

        return self._waiting_for_connect
Beispiel #16
0
def generate_test_messages():
    """
    List of WAMP test message used for serializers. Expand this if you add more
    options or messages.

    This list of WAMP message does not contain any binary app payloads!
    """
    some_bytes = os.urandom(32)
    some_unicode = '\u3053\u3093\u306b\u3061\u306f\u4e16\u754c'

    some_uri = 'com.myapp.foobar'
    some_unicode_uri = 'com.myapp.\u4f60\u597d\u4e16\u754c.baz'

    some_args = [1, 2, 3, 'hello', some_bytes, some_unicode, {'foo': 23, 'bar': 'hello', 'baz': some_bytes, 'moo': some_unicode}]
    some_kwargs = {'foo': 23, 'bar': 'hello', 'baz': some_bytes, 'moo': some_unicode, 'arr': some_args}

    msgs = [
        message.Hello("realm1", {'subscriber': role.RoleSubscriberFeatures()}),
        message.Hello("realm1", {'publisher': role.RolePublisherFeatures()}),
        message.Hello("realm1", {'caller': role.RoleCallerFeatures()}),
        message.Hello("realm1", {'callee': role.RoleCalleeFeatures()}),
        message.Hello("realm1", {
            'subscriber': role.RoleSubscriberFeatures(),
            'publisher': role.RolePublisherFeatures(),
            'caller': role.RoleCallerFeatures(),
            'callee': role.RoleCalleeFeatures(),
        }),
        message.Goodbye(),
        message.Yield(123456),
        message.Yield(123456, args=some_args),
        message.Yield(123456, args=[], kwargs=some_kwargs),
        message.Yield(123456, args=some_args, kwargs=some_kwargs),
        message.Yield(123456, progress=True),
        message.Interrupt(123456),
        message.Interrupt(123456, mode=message.Interrupt.KILL),
        message.Invocation(123456, 789123),
        message.Invocation(123456, 789123, args=some_args),
        message.Invocation(123456, 789123, args=[], kwargs=some_kwargs),
        message.Invocation(123456, 789123, args=some_args, kwargs=some_kwargs),
        message.Invocation(123456, 789123, timeout=10000),
        message.Result(123456),
        message.Result(123456, args=some_args),
        message.Result(123456, args=[], kwargs=some_kwargs),
        message.Result(123456, args=some_args, kwargs=some_kwargs),
        message.Result(123456, progress=True),
        message.Cancel(123456),
        message.Cancel(123456, mode=message.Cancel.KILL),
        message.Call(123456, some_uri),
        message.Call(123456, some_uri, args=some_args),
        message.Call(123456, some_uri, args=[], kwargs=some_kwargs),
        message.Call(123456, some_uri, args=some_args, kwargs=some_kwargs),
        message.Call(123456, some_uri, timeout=10000),
        message.Call(123456, some_unicode_uri),
        message.Call(123456, some_unicode_uri, args=some_args),
        message.Call(123456, some_unicode_uri, args=[], kwargs=some_kwargs),
        message.Call(123456, some_unicode_uri, args=some_args, kwargs=some_kwargs),
        message.Call(123456, some_unicode_uri, timeout=10000),
        message.Unregistered(123456),
        message.Unregister(123456, 789123),
        message.Registered(123456, 789123),
        message.Register(123456, some_uri),
        message.Register(123456, some_uri, match='prefix'),
        message.Register(123456, some_uri, invoke='roundrobin'),
        message.Register(123456, some_unicode_uri),
        message.Register(123456, some_unicode_uri, match='prefix'),
        message.Register(123456, some_unicode_uri, invoke='roundrobin'),
        message.Event(123456, 789123),
        message.Event(123456, 789123, args=some_args),
        message.Event(123456, 789123, args=[], kwargs=some_kwargs),
        message.Event(123456, 789123, args=some_args, kwargs=some_kwargs),
        message.Event(123456, 789123, publisher=300),
        message.Published(123456, 789123),
        message.Publish(123456, some_uri),
        message.Publish(123456, some_uri, args=some_args),
        message.Publish(123456, some_uri, args=[], kwargs=some_kwargs),
        message.Publish(123456, some_uri, args=some_args, kwargs=some_kwargs),
        message.Publish(123456, some_uri, exclude_me=False, exclude=[300], eligible=[100, 200, 300]),
        message.Publish(123456, some_unicode_uri),
        message.Publish(123456, some_unicode_uri, args=some_args),
        message.Publish(123456, some_unicode_uri, args=[], kwargs=some_kwargs),
        message.Publish(123456, some_unicode_uri, args=some_args, kwargs=some_kwargs),
        message.Publish(123456, some_unicode_uri, exclude_me=False, exclude=[300], eligible=[100, 200, 300]),
        message.Unsubscribed(123456),
        message.Unsubscribe(123456, 789123),
        message.Subscribed(123456, 789123),
        message.Subscribe(123456, some_uri),
        message.Subscribe(123456, some_uri, match=message.Subscribe.MATCH_PREFIX),
        message.Subscribe(123456, some_unicode_uri),
        message.Subscribe(123456, some_unicode_uri, match=message.Subscribe.MATCH_PREFIX),
        message.Error(message.Call.MESSAGE_TYPE, 123456, some_uri),
        message.Error(message.Call.MESSAGE_TYPE, 123456, some_uri, args=some_args),
        message.Error(message.Call.MESSAGE_TYPE, 123456, some_uri, args=[], kwargs=some_kwargs),
        message.Error(message.Call.MESSAGE_TYPE, 123456, some_uri, args=some_args, kwargs=some_kwargs),
        message.Error(message.Call.MESSAGE_TYPE, 123456, some_unicode_uri),
        message.Error(message.Call.MESSAGE_TYPE, 123456, some_unicode_uri, args=some_args),
        message.Error(message.Call.MESSAGE_TYPE, 123456, some_unicode_uri, args=[], kwargs=some_kwargs),
        message.Error(message.Call.MESSAGE_TYPE, 123456, some_unicode_uri, args=some_args, kwargs=some_kwargs),
        message.Result(123456),
        message.Result(123456, args=some_args),
        message.Result(123456, args=some_args, kwargs=some_kwargs),
    ]
    return [(False, msg) for msg in msgs]
Beispiel #17
0
def send(msg):
    bytes, _ = serializer.serialize(msg)
    l = struct.pack("!I", len(bytes))
    sys.stdout.write(l)
    sys.stdout.write(bytes)


msgs = []

## HELLO
##
roles = [
    role.RolePublisherFeatures(),
    role.RoleSubscriberFeatures(),
    role.RoleCallerFeatures(),
    role.RoleCalleeFeatures()
]

msgs.append(message.Hello("foobar", roles))

## CHALLENGE
##
msgs.append(message.Challenge("cookie"))

## HEARTBEAT
##
msgs.append(message.Heartbeat(3, 7, "throw me away"))

for msg in msgs:
    send(msg)
Beispiel #18
0
    def process_connect(self, packet):

        self._waiting_for_connect = Deferred()

        roles = {
            u"subscriber":
            role.RoleSubscriberFeatures(payload_transparency=True),
            u"publisher":
            role.RolePublisherFeatures(payload_transparency=True,
                                       x_acknowledged_event_delivery=True)
        }

        # Will be autoassigned
        realm = None
        methods = []

        if ISSLTransport.providedBy(self.transport):
            methods.append(u"tls")

        if packet.username and packet.password:
            methods.append(u"ticket")
            msg = message.Hello(realm=realm,
                                roles=roles,
                                authmethods=methods,
                                authid=packet.username)
            self._pw_challenge = packet.password

        else:
            methods.append(u"anonymous")
            msg = message.Hello(realm=realm,
                                roles=roles,
                                authmethods=methods,
                                authid=packet.client_id)

        self._wamp_session.onMessage(msg)

        if packet.flags.will:

            @self._waiting_for_connect.addCallback
            def process_will(res):

                akw = mqtt_payload_transform(
                    self._wamp_session._router._mqtt_payload_format,
                    packet.will_message)

                if not akw:
                    # Drop it I guess :(
                    return res

                args, kwargs = akw

                msg = message.Call(
                    request=util.id(),
                    procedure=u"wamp.session.add_testament",
                    args=[
                        u".".join(tokenise_mqtt_topic(packet.will_topic)),
                        args, kwargs, {
                            "retain": bool(packet.flags.will_retain)
                        }
                    ])

                self._wamp_session.onMessage(msg)

                return res

        return self._waiting_for_connect
Beispiel #19
0
 def test_str(self):
    e = message.Hello(u"realm1", [role.RoleBrokerFeatures()])
    self.assertIsInstance(str(e), str)
Beispiel #20
0
    def process_connect(self, packet):

        try:
            self.log.debug(
                'WampMQTTServerProtocol.process_connect(packet={packet})',
                packet=packet)

            self._waiting_for_connect = Deferred()

            roles = {
                u"subscriber":
                role.RoleSubscriberFeatures(payload_transparency=True),
                u"publisher":
                role.RolePublisherFeatures(payload_transparency=True,
                                           x_acknowledged_event_delivery=True)
            }

            realm = self.factory._options.get('realm', None)
            methods = []

            if ISSLTransport.providedBy(self.transport):
                methods.append(u"tls")

            if packet.username and packet.password:
                methods.append(u"ticket")
                msg = message.Hello(realm=realm,
                                    roles=roles,
                                    authmethods=methods,
                                    authid=packet.username)
                self._pw_challenge = packet.password

            else:
                methods.append(u"anonymous")
                msg = message.Hello(realm=realm,
                                    roles=roles,
                                    authmethods=methods,
                                    authid=packet.client_id)

            self._wamp_session.onMessage(msg)

            if packet.flags.will:

                @inlineCallbacks
                @self._waiting_for_connect.addCallback
                def process_will(res):

                    payload_format, mapped_topic, options = yield self.factory.transform_mqtt(
                        packet.will_topic, packet.will_message)

                    request = util.id()

                    msg = message.Call(request=request,
                                       procedure=u"wamp.session.add_testament",
                                       args=[
                                           mapped_topic,
                                           options.get('args', None),
                                           options.get('kwargs', None), {
                                               'retain':
                                               bool(packet.flags.will_retain)
                                           }
                                       ])

                    self._wamp_session.onMessage(msg)

                    returnValue(res)

            return self._waiting_for_connect
        except:
            self.log.failure()