Exemplo n.º 1
0
            def _continue(code, stanza, phone):
                status = self.send_sms(phone, code)

                if status:
                    # send response with sms sender number
                    iq = xmlstream.toResponse(stanza, 'result')
                    query = iq.addElement((xmlstream2.NS_IQ_REGISTER, 'query'))
                    query.addElement((None, 'instructions'),
                                     content=self.ack_instructions)

                    form = query.addElement(('jabber:x:data', 'x'))
                    form['type'] = 'form'

                    hidden = form.addElement((None, 'field'))
                    hidden['type'] = 'hidden'
                    hidden['var'] = 'FORM_TYPE'
                    hidden.addElement((None, 'value'),
                                      content=xmlstream2.NS_IQ_REGISTER)

                    phone = form.addElement((None, 'field'))
                    phone['type'] = 'text-single'
                    phone['label'] = 'SMS sender'
                    phone['var'] = 'from'
                    phone.addElement((None, 'value'),
                                     content=self.config['from'])

                else:
                    # send error
                    iq = xmlstream.toResponse(stanza, 'error')
                    e = error.StanzaError('not-acceptable', 'modify',
                                          'Unable to send SMS.')
                    iq.addChild(e.getElement())

                return manager.send(iq, True)
Exemplo n.º 2
0
            def _continue(userid):
                pkey = base64.b64decode(var_pkey.value.__str__().encode('utf-8'))
                signed_pkey = manager.link_public_key(pkey, userid)
                if signed_pkey:
                    iq = xmlstream.toResponse(stanza, 'result')
                    query = iq.addElement((xmlstream2.NS_IQ_REGISTER, 'query'))

                    form = query.addElement(('jabber:x:data', 'x'))
                    form['type'] = 'form'

                    hidden = form.addElement((None, 'field'))
                    hidden['type'] = 'hidden'
                    hidden['var'] = 'FORM_TYPE'
                    hidden.addElement((None, 'value'), content='http://kontalk.org/protocol/register#code')

                    signed = form.addElement((None, 'field'))
                    signed['type'] = 'text-single'
                    signed['label'] = 'Signed public key'
                    signed['var'] = 'publickey'
                    signed.addElement((None, 'value'), content=base64.b64encode(signed_pkey))

                    return manager.send(iq, True)

                else:
                    e = error.StanzaError('bad-request', 'modify', 'Invalid public key.')
                    iq = xmlstream.toResponse(stanza, 'error')
                    iq.addChild(e.getElement())
                    manager.send(iq, True)
Exemplo n.º 3
0
            def _continue(userid):
                pkey = base64.b64decode(
                    var_pkey.value.__str__().encode('utf-8'))
                signed_pkey = manager.link_public_key(pkey, userid)
                if signed_pkey:
                    iq = xmlstream.toResponse(stanza, 'result')
                    query = iq.addElement((xmlstream2.NS_IQ_REGISTER, 'query'))

                    form = query.addElement(('jabber:x:data', 'x'))
                    form['type'] = 'form'

                    hidden = form.addElement((None, 'field'))
                    hidden['type'] = 'hidden'
                    hidden['var'] = 'FORM_TYPE'
                    hidden.addElement(
                        (None, 'value'),
                        content='http://kontalk.org/protocol/register#code')

                    signed = form.addElement((None, 'field'))
                    signed['type'] = 'text-single'
                    signed['label'] = 'Signed public key'
                    signed['var'] = 'publickey'
                    signed.addElement((None, 'value'),
                                      content=base64.b64encode(signed_pkey))

                    return manager.send(iq, True)

                else:
                    e = error.StanzaError('bad-request', 'modify',
                                          'Invalid public key.')
                    iq = xmlstream.toResponse(stanza, 'error')
                    iq.addChild(e.getElement())
                    manager.send(iq, True)
Exemplo n.º 4
0
            def _continue(code, stanza, phone):
                status = self.send_sms(phone, code)

                if status:
                    # send response with sms sender number
                    iq = xmlstream.toResponse(stanza, 'result')
                    query = iq.addElement((xmlstream2.NS_IQ_REGISTER, 'query'))
                    query.addElement((None, 'instructions'), content=self.ack_instructions)

                    form = query.addElement(('jabber:x:data', 'x'))
                    form['type'] = 'form'

                    hidden = form.addElement((None, 'field'))
                    hidden['type'] = 'hidden'
                    hidden['var'] = 'FORM_TYPE'
                    hidden.addElement((None, 'value'), content=xmlstream2.NS_IQ_REGISTER)

                    phone = form.addElement((None, 'field'))
                    phone['type'] = 'text-single'
                    phone['label'] = 'SMS sender'
                    phone['var'] = 'from'
                    phone.addElement((None, 'value'), content=self.config['from'])

                else:
                    # send error
                    iq = xmlstream.toResponse(stanza, 'error')
                    e = error.StanzaError('not-acceptable', 'modify', 'Unable to send SMS.')
                    iq.addChild(e.getElement())

                return manager.send(iq, True)
Exemplo n.º 5
0
 def _onGetShadowCopyIQ(self, iq):
     node = iq.shadowcopy['node']
     sender = iq['from']
     try:
         if node not in self.node_participants or \
             sender not in self.node_participants[node]:
             raise DSCException("Unauthorized")
         response = toResponse(iq, u'result')
         sc = response.addElement((NS_CE, u'shadowcopy'), content=self.shadow_copies[node])
         sc['node'] = node
     except DSCException, reason:
         response = toResponse(iq, u'error')
         response.addElement((NS_CE, u'error'), content=reason.message)
 def _onGetShadowCopyIQ(self, iq):
     node = iq.shadowcopy['node']
     sender = iq['from']
     try:
         if node not in self.node_participants or \
             sender not in self.node_participants[node]:
             raise DSCException("Unauthorized")
         response = toResponse(iq, u'result')
         sc = response.addElement((NS_CE, u'shadowcopy'),
                                  content=self.shadow_copies[node])
         sc['node'] = node
     except DSCException, reason:
         response = toResponse(iq, u'error')
         response.addElement((NS_CE, u'error'), content=reason.message)
Exemplo n.º 7
0
    def _onPatchIQ(self, iq):
        node = iq.patch['node']
        sender = iq['from']
        diff = iq.patch.children[0]
        patches = self.dmp.patch_fromText(diff)
        shadow = self.shadow_copies[node]
        # hack fruehwir: somehow linebreaks are encoded as \r - but  
        #  not in all cases and (confusingly) not in both shadow copy and patch (!!)
        #  which creates a digest mismatch
        #  so we purge shadow copy and new_text of \r's in order to
        #  get our patches processed. this is not very safe and elegant, but
        #  it seems to do the trick... 
        shadow = shadow.replace ( "\r", "" )

        (new_text, res) = self.dmp.patch_apply(patches, shadow)
        # hack fruehwir: see above
        new_text = new_text.replace ( "\r", "" )
        if False in res:
            response = toResponse(iq, u'error')
            response.addElement((NS_CE, u'error'), content='Error applying patch.')
            self.xmlstream.send(response)
            logger.error('Patch %s could not be applied on node %s' % \
                         (diff, node))
            return
        if iq.patch.hasAttribute('digest'):
            digest = iq.patch['digest']
            md5 = hashlib.md5()
            md5.update(new_text.encode('utf-8'))
            shadow_digest = md5.hexdigest()
            if shadow_digest!=digest:
                # There is a mismatch in the node's digest.
                # Presumably, this happens because the sender has not yet
                # received a previous patch. If that is the case and since
                # we already applied let him continue, otherwise return an
                # and let him get the shadow copy.
                if node not in self.pending_patches or sender not in self.pending_patches[node]:
                    response = toResponse(iq, u'error')
                    response.addElement((NS_CE, u'error'), content='Digest mismatch.')
                    self.xmlstream.send(response)
                    logger.error('MD5 digest did not match on node %s' % node)
                    return
                else:
                    logger.info('MD5 digest did not match. Continue as normal, this is probably due to lag.')
        self.shadow_copies[node] = new_text
        response = toResponse(iq, u'result')
        response.addElement((NS_CE, u'success',))
        self.xmlstream.send(response)
        for receiver in (self.node_participants[node] - set([sender])):
            self._sendPatchIQ(node, sender, receiver, diff)
        logger.info('Patch from %s applied on %s' % (sender, node))
    def _onPatchIQ(self, iq):
        node = iq.patch['node']
        sender = iq['from']
        if not iq.patch.children:
            return

        diff = iq.patch.children[0]
        patches = self.dmp.patch_fromText(diff)
        shadow = self.shadow_copies[node]

        (new_text, res) = self.dmp.patch_apply(patches, shadow)
        if False in res:
            response = toResponse(iq, u'error')
            response.addElement((NS_CE, u'error'),
                                content='Error applying patch.')
            self.xmlstream.send(response)
            log.warn('Patch %s could not be applied on node %s' % \
                         (diff, node))
            return
        if iq.patch.hasAttribute('digest'):
            digest = iq.patch['digest']
            md5 = hashlib.md5()
            md5.update(new_text.encode('utf-8'))
            shadow_digest = md5.hexdigest()
            if shadow_digest != digest:
                # There is a mismatch in the node's digest.
                # Presumably, this happens because the sender has not yet
                # received a previous patch. If that is the case and since
                # we already applied let him continue, otherwise return an
                # and let him get the shadow copy.
                if node not in self.pending_patches or sender not in self.pending_patches[
                        node]:
                    response = toResponse(iq, u'error')
                    response.addElement((NS_CE, u'error'),
                                        content='Digest mismatch.')
                    self.xmlstream.send(response)
                    log.warn('MD5 digest did not match on node %s' % node)
                    return
                else:
                    log.info(
                        'MD5 digest did not match. Continue as normal, this is probably due to lag.'
                    )
        self.shadow_copies[node] = new_text
        response = toResponse(iq, u'result')
        response.addElement((
            NS_CE,
            u'success',
        ))
        self.xmlstream.send(response)
        self._sendPatches(sender, node, diff)
Exemplo n.º 9
0
    def onMessage(self, message):
        # Ignore empty messages
        if not message.body or not unicode(message.body):
            return
        if message["type"] != "chat":
            return

        jid = message["from"].split("/")[0]
        if jid not in self.parent.authorized:
            # User is not authorized! Is it telling us the password?
            if unicode(message.body).strip() == self.parent.getPassword():
                self.parent.authorized.append(jid)
                answer = "Welcome!"
                log.msg("Accepting JID %s with the right password" % jid)
                self.parent.presence.subscribed(JID(jid))
                self.parent.presence.subscribe(JID(jid))
            else:
                answer = "Tell me the password or I won't speak to you."
            response = toResponse(message, "chat")
            response.addElement("body", content=unicode(answer))
            self.send(response)
            return

        # Tell the user we are building an answer
        response = toResponse(message, "chat")
        response.addElement("composing", "http://jabber.org/protocol/chatstates")
        self.send(response)

        # Get an answer from the first one able to answer
        answers = None
        for bot in self.bots:
            try:
                answers = yield bot.ask(message["from"], unicode(message.body).encode("ascii", "ignore"))
            except Exception as e:
                log.msg("Catch exception for bot %r: %s\n%s" % (bot, e, traceback.format_exc()))
                continue
            if answers:
                break
        if not answers:
            answers = ["Seven amazing hamsters make your day!"]

        for answer in answers:
            response = toResponse(message, message["type"])
            if not isinstance(answer, MixedMessage):
                response.addElement("body", content=unicode(answer))
            else:
                response.addElement("body", content=unicode(answer.plain))
                response.addElement("html", "http://jabber.org/protocol/xhtml-im").addChild(answer.html)
            yield self.send(response)
Exemplo n.º 10
0
    def presence(self, stanza):
        """Presence stanza received."""
        ptype = stanza.getAttribute('type')
        if ptype == 'subscribe':
            # sign received public key
            for child in stanza.pubkey.children:
                if child.name == 'print':
                    fpr = str(child)
                    break
            myfpr = str(self.config['publickey']['fingerprint'])

            ctx = gpgme.Context()
            ctx.signers = [ctx.get_key(myfpr, True)]
            gpgme.editutil.edit_sign(ctx, ctx.get_key(fpr), check=0)

            keydata = BytesIO()
            ctx.export(fpr, keydata)

            r = xmlstream.toResponse(stanza, 'subscribed')
            pubkey = r.addElement(('urn:xmpp:pubkey:2', 'pubkey'))
            key = pubkey.addElement((None, 'key'))
            key.addContent(base64.b64encode(keydata.getvalue()))
            fprint = pubkey.addElement((None, 'print'))
            fprint.addContent(fpr)
            self.client.send(r)
Exemplo n.º 11
0
    def test_discoServerSupport(self):
        """Disco support from client to server.
        """
        test_srv = 'shakespeare.lit'

        def cb(query):
            # check namespace
            self.failUnless(query.uri == disco.NS_INFO, 'Wrong namespace')

        d = self.protocol.disco(test_srv)
        d.addCallback(cb)

        iq = self.stub.output[-1]

        # send back a response
        response = toResponse(iq, 'result')
        response.addElement('query', disco.NS_INFO)
        # need to add information to response
        response.query.addChild(disco.DiscoFeature(muc.NS_MUC))
        response.query.addChild(
            disco.DiscoIdentity(category='conference',
                                name='Macbeth Chat Service',
                                type='text'))

        self.stub.send(response)
        return d
Exemplo n.º 12
0
    def test_ban(self):
        """Ban an entity in a room.
        """
        banned = JID('[email protected]/TroubleMakger')

        def cb(banned):
            self.failUnless(banned, 'Did not ban user')

        d = self.protocol.ban(self.room_jid,
                              banned,
                              self.user_jid,
                              reason='Spam')
        d.addCallback(cb)

        iq = self.stub.output[-1]

        self.failUnless(
            xpath.matches(
                "/iq[@type='set' and @to='%s']/query/item[@affiliation='outcast']"
                % (self.room_jid.userhost(), ), iq), 'Wrong ban stanza')

        response = toResponse(iq, 'result')

        self.stub.send(response)

        return d
Exemplo n.º 13
0
    def test_getRoster(self):
        """
        A request for the roster is sent out and the response is parsed.
        """
        def cb(roster):
            self.assertIn(JID('*****@*****.**'), roster)
            self.assertIdentical(None, getattr(roster, 'version'))

        d = self.service.getRoster()
        d.addCallback(cb)

        # Inspect outgoing iq request

        iq = self.stub.output[-1]
        self.assertEqual('get', iq.getAttribute('type'))
        self.assertNotIdentical(None, iq.query)
        self.assertEqual(NS_ROSTER, iq.query.uri)
        self.assertFalse(iq.query.hasAttribute('ver'))

        # Fake successful response
        response = toResponse(iq, 'result')
        query = response.addElement((NS_ROSTER, 'query'))
        item = query.addElement('item')
        item['jid'] = '*****@*****.**'

        d.callback(response)
        return d
Exemplo n.º 14
0
    def test_requestItems(self):
        """
        Test request sent out by C{requestItems} and parsing of response.
        """
        def cb(items):
            items = list(items)
            self.assertEqual(2, len(items))
            self.assertEqual(JID(u'test.example.org'), items[0].entity)

        d = self.protocol.requestItems(JID(u'example.org'), u"foo")
        d.addCallback(cb)

        iq = self.stub.output[-1]
        self.assertEqual(u'example.org', iq.getAttribute(u'to'))
        self.assertEqual(u'get', iq.getAttribute(u'type'))
        self.assertEqual(u'foo', iq.query.getAttribute(u'node'))
        self.assertEqual(NS_DISCO_ITEMS, iq.query.uri)

        response = toResponse(iq, u'result')
        query = response.addElement((NS_DISCO_ITEMS, u'query'))

        element = query.addElement(u'item')
        element[u'jid'] = u'test.example.org'
        element[u'node'] = u'music'
        element[u'name'] = u'Music from the time of Shakespeare'

        element = query.addElement(u'item')
        element[u'jid'] = u"test2.example.org"

        self.stub.send(response)
        return d
Exemplo n.º 15
0
    def onBind(self, stanza):
        if not self.canInitialize(self):
            return

        if not stanza.bind.resource is None:
            resource = str(stanza.bind.resource)
            if resource == "":
                resource = md5.new(
                    "%s:%s:%s" % (str(random.random()), str(
                        time.gmtime()), str(os.getpid()))).hexdigest()

            try:
                resource = xmpp_stringprep.resourceprep.prepare(
                    unicode(resource))
            except UnicodeError:
                self._sendError(stanza, 'modify', 'bad-request')

            self.xmlstream.otherEntity.resource = resource

            response = xmlstream.toResponse(stanza, 'result')
            response.addElement(
                (None, 'jid'),
                content=self.xmlstream.otherEntity.full().encode('UTF-8'))
            self.xmlstream.send(response)
            self.xmlstream.dispatch(self, INIT_SUCCESS_EVENT)
        else:
            self._sendError(stanza, 'auth', 'not-authorized')
Exemplo n.º 16
0
    def test_getSubscriptions(self):
        d = self.protocol.getSubscriptions(JID(u'pubsub.example.com'),
                                           u'foo_node')
        iq = self.stub.output[-1]
        self.assertEqual(u'pubsub.example.com', iq.getAttribute(u'to'))
        self.assertEqual(u'get', iq.getAttribute(u'type'))
        self.failIf(iq.pubsub is None)
        self.assertEqual(protocols.NS_PUBSUB_OWNER, iq.pubsub.uri)
        self.failIf(iq.pubsub.subscriptions is None)
        self.assertEqual(u'foo_node',
                         iq.pubsub.subscriptions.getAttribute(u'node'))
        response = toResponse(iq, u'result')
        response['to'] = \
            self.protocol.xmlstream.factory.authenticator.jid.full()
        response.addElement((protocols.NS_PUBSUB_OWNER, u'pubsub'))
        subscriptions = response.pubsub.addElement(u'subscriptions')
        subscriptions[u'node'] = u'foo_node'
        subscription1 = subscriptions.addElement(u'subscription')
        subscription1[u'jid'] = u'*****@*****.**'
        subscription1[u'subscription'] = u'unconfigured'
        subscription2 = subscriptions.addElement(u'subscription')
        subscription2[u'jid'] = u'*****@*****.**'
        subscription2[u'subscription'] = u'subscribed'
        subscription2[u'subid'] = u'123-abc'

        self.stub.send(response)

        def cb(result):
            self.assertEqual(
                [(JID(u'*****@*****.**'), u'unconfigured'),
                 (JID(u'*****@*****.**'), u'subscribed')],
                 result)

        d.addCallback(cb)
        return d
 def test_noType(self):
     """
     Test that a proper response is generated without type attribute.
     """
     stanza = domish.Element(('jabber:client', 'message'))
     response = xmlstream.toResponse(stanza)
     self.assertFalse(response.hasAttribute('type'))
Exemplo n.º 18
0
    def test_getAffiliations(self):
        d = self.protocol.getAffiliations(JID(u'pubsub.example.com'),
                                          u'foo_node')
        iq = self.stub.output[-1]
        self.assertEqual(u'pubsub.example.com', iq.getAttribute(u'to'))
        self.assertEqual(u'get', iq.getAttribute(u'type'))
        self.failIf(iq.pubsub is None)
        self.assertEqual(protocols.NS_PUBSUB_OWNER, iq.pubsub.uri)
        self.failIf(iq.pubsub.affiliations is None)
        self.assertEqual('foo_node',
                         iq.pubsub.affiliations['node'])
        response = toResponse(iq, u'result')
        response['to'] = \
            self.protocol.xmlstream.factory.authenticator.jid.full()
        pubsub = response.addElement((protocols.NS_PUBSUB_OWNER, u'pubsub'))

        affiliations = pubsub.addElement(u'affiliations')
        affiliations['node'] = u'foo_node'
        user = affiliations.addElement(u'affiliation')
        user['jid'] = '*****@*****.**'
        user['affiliation'] = 'owner'
        foo = affiliations.addElement(u'affiliation')
        foo['jid'] = '*****@*****.**'
        foo['affiliation'] = 'publisher'
        self.stub.send(response)

        def cb(result):
            self.assertEqual(result,
            [(JID(u'*****@*****.**'), 'owner'),
             (JID(u'*****@*****.**'), 'publisher')])

        d.addCallback(cb)
        return d
Exemplo n.º 19
0
    def test_modifyAffiliations(self):
        d = self.protocol.modifyAffiliations(JID(u'pubsub.example.com'),
            u'foo_node', [(JID(u'*****@*****.**'), 'none')])
        iq = self.stub.output[-1]
        self.assertEqual(u'pubsub.example.com', iq.getAttribute(u'to'))
        self.assertEqual(u'set', iq.getAttribute(u'type'))
        self.failIf(iq.pubsub is None)
        self.assertEqual(protocols.NS_PUBSUB_OWNER, iq.pubsub.uri)
        self.failIf(iq.pubsub.affiliations is None)
        self.assertEqual('foo_node',
                         iq.pubsub.affiliations['node'])
        affiliation = iq.pubsub.affiliations.affiliation
        self.assertEqual('*****@*****.**', affiliation['jid'])
        self.assertEqual('none', affiliation['affiliation'])

        response = toResponse(iq, u'result')
        response['to'] = \
            self.protocol.xmlstream.factory.authenticator.jid.full()
        self.stub.send(response)

        def cb(result):
            self.assertEqual(result, True)

        d.addCallback(cb)
        return d
Exemplo n.º 20
0
    def test_associateNodeToCollection(self):
        d = self.protocol.associateNodeWithCollection(
            JID(u'pubsub.example.com'),
            u'foo_node',
            u'collection_node')
        iq = self.stub.output[-1]
        self.assertEqual(u'pubsub.example.com', iq.getAttribute(u'to'))
        self.assertEqual(u'set', iq.getAttribute(u'type'))
        self.failIf(iq.pubsub is None)
        self.assertEqual(protocols.NS_PUBSUB_OWNER, iq.pubsub.uri)
        self.failIf(iq.pubsub.collection is None)
        self.assertEqual('collection_node',
                         iq.pubsub.collection['node'])
        self.failIf(iq.pubsub.collection.associate is None)
        self.assertEqual('foo_node',
                         iq.pubsub.collection.associate['node'])

        response = toResponse(iq, u'result')
        response['to'] = \
         self.protocol.xmlstream.factory.authenticator.jid.full()

        self.stub.send(response)

        def cb(result):
            self.assertEqual(True, result)

        d.addCallback(cb)
        return d
Exemplo n.º 21
0
    def test_configureNode(self):
        d = self.protocol.configureNode(JID(u'pubsub.example.com'),
                                        u'foo_node',
                                        {u'pubsub#collection': u'bar_node'})
        iq = self.stub.output[-1]
        self.assertEqual(u'pubsub.example.com', iq.getAttribute(u'to'))
        self.assertEqual(u'set', iq.getAttribute(u'type'))
        self.failIf(iq.pubsub is None)
        self.assertEqual(protocols.NS_PUBSUB_OWNER, iq.pubsub.uri)
        self.failIf(iq.pubsub.configure is None)
        self.assertEqual(u'foo_node',
                         iq.pubsub.configure.getAttribute(u'node'))
        self.failIf(iq.pubsub.configure.x is None)
        x = iq.pubsub.configure.x
        self.assertEqual(data_form.NS_X_DATA, x.uri)
        self.assertEqual(u'submit', x.getAttribute('type'))
        self.assertEqual(2, len(x.children))
        fields = x.children
        self.failIf(fields[0].value is None)
        self.assertEqual([protocols.NS_PUBSUB_NODE_CONFIG],
                         fields[0].value.children)
        self.assertEqual(u'pubsub#collection', fields[1].getAttribute(u'var'))
        self.failIf(fields[1].value is None)
        self.assertEqual([u'bar_node'], fields[1].value.children)
        self.assertEqual(fields[0].value.children,
            [protocols.NS_PUBSUB_NODE_CONFIG])

        response = toResponse(iq, u'result')
        self.stub.send(response)

        def cb(result):
            self.assertEqual(True, result)

        d.addCallback(cb)
        return d
Exemplo n.º 22
0
    def test_getNodes(self):
        d = self.protocol.getNodes(JID(u'pubsub.example.com'),
                                   u'foo_node')
        iq = self.stub.output[-1]
        self.assertEqual(u'pubsub.example.com', iq.getAttribute(u'to'))
        self.assertEqual(u'get', iq.getAttribute(u'type'))
        self.failIf(iq.query is None)
        self.assertEqual(protocols.NS_DISCO_ITEMS, iq.query.uri)
        self.assertEqual(u'foo_node', iq.query.getAttribute(u'node'))
        response = toResponse(iq, u'result')
        response['to'] = \
            self.protocol.xmlstream.factory.authenticator.jid.full()
        query = response.addElement((protocols.NS_DISCO_ITEMS, u'query'))
        query[u'node'] = u'foo_node'
        child1 = query.addElement('item')
        child1['node'] = 'foodoo_child_1'
        child1['name'] = 'Foodoo child one'
        child1['jid'] = u'pubsub.example.com'
        child2 = query.addElement('item')
        child2['node'] = 'foodoo_child_2'
        child2['jid'] = u'pubsub.example.com'

        self.stub.send(response)

        def cb(result):
            self.assertEqual(
                [{'node': 'foodoo_child_1',
                  'jid': u'pubsub.example.com',
                  'name': 'Foodoo child one'},
                 {'node': 'foodoo_child_2',
                  'jid': u'pubsub.example.com'}],
                 result)

        d.addCallback(cb)
        return d
Exemplo n.º 23
0
    def test_getNodeType(self):
        d = self.protocol.getNodeType(JID(u'pubsub.example.com'),
                                      u'foo_node')
        iq = self.stub.output[-1]
        self.assertEqual(u'pubsub.example.com', iq.getAttribute(u'to'))
        self.assertEqual(u'get', iq.getAttribute(u'type'))
        self.failIf(iq.query is None)
        self.assertEqual(protocols.NS_DISCO_INFO, iq.query.uri)
        self.assertEqual(u'foo_node', iq.query['node'])

        response = toResponse(iq, u'result')
        response['to'] = \
            self.protocol.xmlstream.factory.authenticator.jid.full()
        query = response.addElement((protocols.NS_DISCO_INFO, u'query'))
        query[u'node'] = u'foo_node'
        identity = query.addElement(u'identity')
        identity[u'category'] = u'pubsub'
        identity[u'type'] = u'collection'

        self.stub.send(response)

        def cb(result):
            self.assertEqual(u'collection', result)

        d.addCallback(cb)
        return d
Exemplo n.º 24
0
    def test_setSubscriptions(self):
        d = self.protocol.setSubscriptions(
            JID(u'pubsub.example.com'),
            u'foo_node',
            [(JID(u'*****@*****.**'), u'subscribed'),
             (JID(u'*****@*****.**'), u'none')])

        iq = self.stub.output[-1]
        self.assertEqual(u'pubsub.example.com', iq.getAttribute(u'to'))
        self.assertEqual(u'set', iq.getAttribute(u'type'))
        self.failIf(iq.pubsub is None)
        self.assertEqual(protocols.NS_PUBSUB_OWNER, iq.pubsub.uri)
        self.failIf(iq.pubsub.subscriptions is None)
        self.assertEqual(u'foo_node',
                         iq.pubsub.subscriptions.getAttribute(u'node'))
        subscriptions = iq.pubsub.subscriptions.children
        self.assertEqual(2, len(subscriptions))
        self.assertEqual(u'*****@*****.**', subscriptions[0]['jid'])
        self.assertEqual(u'subscribed', subscriptions[0]['subscription'])
        self.assertEqual(u'*****@*****.**', subscriptions[1]['jid'])
        self.assertEqual(u'none', subscriptions[1]['subscription'])

        response = toResponse(iq, u'result')
        response['to'] = \
            self.protocol.xmlstream.factory.authenticator.jid.full()
        self.stub.send(response)

        def cb(result):
            self.assertEqual(True, result)

        d.addCallback(cb)
        return d
Exemplo n.º 25
0
    def presence(self, stanza):
        """Presence stanza received."""
        ptype = stanza.getAttribute('type')
        if ptype == 'subscribe':
            # sign received public key
            for child in stanza.pubkey.children:
                if child.name == 'print':
                    fpr = str(child)
                    break
            myfpr = str(self.config['publickey']['fingerprint'])

            ctx = gpgme.Context()
            ctx.signers = [ctx.get_key(myfpr, True)]
            gpgme.editutil.edit_sign(ctx, ctx.get_key(fpr), check=0)

            keydata = BytesIO()
            ctx.export(fpr, keydata)

            r = xmlstream.toResponse(stanza, 'subscribed')
            pubkey = r.addElement(('urn:xmpp:pubkey:2', 'pubkey'))
            key = pubkey.addElement((None, 'key'))
            key.addContent(base64.b64encode(keydata.getvalue()))
            fprint = pubkey.addElement((None, 'print'))
            fprint.addContent(fpr)
            self.client.send(r)
Exemplo n.º 26
0
    def test_createNode(self):
        """
        Test sending create request.
        """

        def cb(nodeIdentifier):
            self.assertEquals('test', nodeIdentifier)

        d = self.protocol.createNode(JID('pubsub.example.org'), 'test')
        d.addCallback(cb)

        iq = self.stub.output[-1]
        self.assertEquals('pubsub.example.org', iq.getAttribute('to'))
        self.assertEquals('set', iq.getAttribute('type'))
        self.assertEquals('pubsub', iq.pubsub.name)
        self.assertEquals(NS_PUBSUB, iq.pubsub.uri)
        children = list(domish.generateElementsQNamed(iq.pubsub.children,
                                                      'create', NS_PUBSUB))
        self.assertEquals(1, len(children))
        child = children[0]
        self.assertEquals('test', child['node'])

        response = toResponse(iq, 'result')
        self.stub.send(response)
        return d
 def test_noID(self):
     """
     Test that a proper response is generated without id attribute.
     """
     stanza = domish.Element(("jabber:client", "message"))
     response = xmlstream.toResponse(stanza)
     self.assertFalse(response.hasAttribute("id"))
Exemplo n.º 28
0
    def test_publish(self):
        """
        Test sending publish request.
        """

        item = pubsub.Item()
        d = self.protocol.publish(JID('pubsub.example.org'), 'test', [item])

        iq = self.stub.output[-1]
        self.assertEquals('pubsub.example.org', iq.getAttribute('to'))
        self.assertEquals('set', iq.getAttribute('type'))
        self.assertEquals('pubsub', iq.pubsub.name)
        self.assertEquals(NS_PUBSUB, iq.pubsub.uri)
        children = list(domish.generateElementsQNamed(iq.pubsub.children,
                                                      'publish', NS_PUBSUB))
        self.assertEquals(1, len(children))
        child = children[0]
        self.assertEquals('test', child['node'])
        items = list(domish.generateElementsQNamed(child.children,
                                                   'item', NS_PUBSUB))
        self.assertEquals(1, len(items))
        self.assertIdentical(item, items[0])

        response = toResponse(iq, 'result')
        self.stub.send(response)
        return d
Exemplo n.º 29
0
    def test_kick(self):
        """Kick an entity from a room.
        """
        kicked = JID('[email protected]/TroubleMakger')

        def cb(kicked):
            self.failUnless(kicked, 'Did not kick user')

        d = self.protocol.kick(self.room_jid,
                               kicked,
                               self.user_jid,
                               reason='Spam')
        d.addCallback(cb)

        iq = self.stub.output[-1]

        self.failUnless(
            xpath.matches(
                "/iq[@type='set' and @to='%s']/query/item[@affiliation='none']"
                % (self.room_jid.userhost(), ), iq), 'Wrong kick stanza')

        response = toResponse(iq, 'result')

        self.stub.send(response)

        return d
Exemplo n.º 30
0
    def test_subscribe(self):
        """
        Test sending subscription request.
        """
        d = self.protocol.subscribe(JID('pubsub.example.org'), 'test',
                                      JID('*****@*****.**'))

        iq = self.stub.output[-1]
        self.assertEquals('pubsub.example.org', iq.getAttribute('to'))
        self.assertEquals('set', iq.getAttribute('type'))
        self.assertEquals('pubsub', iq.pubsub.name)
        self.assertEquals(NS_PUBSUB, iq.pubsub.uri)
        children = list(domish.generateElementsQNamed(iq.pubsub.children,
                                                      'subscribe', NS_PUBSUB))
        self.assertEquals(1, len(children))
        child = children[0]
        self.assertEquals('test', child['node'])
        self.assertEquals('*****@*****.**', child['jid'])

        response = toResponse(iq, 'result')
        pubsub = response.addElement((NS_PUBSUB, 'pubsub'))
        subscription = pubsub.addElement('subscription')
        subscription['node'] = 'test'
        subscription['jid'] = '*****@*****.**'
        subscription['subscription'] = 'subscribed'
        self.stub.send(response)
        return d
Exemplo n.º 31
0
    def test_requestInfo(self):
        """
        Test request sent out by C{requestInfo} and parsing of response.
        """
        def cb(info):
            self.assertIn((u'conference', u'text'), info.identities)
            self.assertIn(u'http://jabber.org/protocol/disco#info',
                          info.features)
            self.assertIn(u'http://jabber.org/protocol/muc', info.features)

        d = self.protocol.requestInfo(JID(u'example.org'), 'foo')
        d.addCallback(cb)

        iq = self.stub.output[-1]
        self.assertEqual(u'example.org', iq.getAttribute(u'to'))
        self.assertEqual(u'get', iq.getAttribute(u'type'))
        self.assertEqual(u'foo', iq.query.getAttribute(u'node'))
        self.assertEqual(NS_DISCO_INFO, iq.query.uri)

        response = toResponse(iq, u'result')
        query = response.addElement((NS_DISCO_INFO, u'query'))

        element = query.addElement(u"identity")
        element[u'category'] = u'conference'  # required
        element[u'type'] = u'text'  # required
        element[u"name"] = u'Romeo and Juliet, Act II, Scene II'  # optional

        element = query.addElement("feature")
        element[u'var'] = u'http://jabber.org/protocol/disco#info'  # required

        element = query.addElement(u"feature")
        element[u'var'] = u'http://jabber.org/protocol/muc'

        self.stub.send(response)
        return d
Exemplo n.º 32
0
    def test_itemsMaxItems(self):
        """
        Test sending items request, with limit on the number of items.
        """
        def cb(items):
            self.assertEquals(2, len(items))
            self.assertEquals([item1, item2], items)

        d = self.protocol.items(JID('pubsub.example.org'), 'test', maxItems=2)
        d.addCallback(cb)

        iq = self.stub.output[-1]
        self.assertEquals('pubsub.example.org', iq.getAttribute('to'))
        self.assertEquals('get', iq.getAttribute('type'))
        self.assertEquals('pubsub', iq.pubsub.name)
        self.assertEquals(NS_PUBSUB, iq.pubsub.uri)
        children = list(domish.generateElementsQNamed(iq.pubsub.children,
                                                      'items', NS_PUBSUB))
        self.assertEquals(1, len(children))
        child = children[0]
        self.assertEquals('test', child['node'])
        self.assertEquals('2', child['max_items'])

        response = toResponse(iq, 'result')
        items = response.addElement((NS_PUBSUB, 'pubsub')).addElement('items')
        items['node'] = 'test'
        item1 = items.addElement('item')
        item1['id'] = 'item1'
        item2 = items.addElement('item')
        item2['id'] = 'item2'

        self.stub.send(response)

        return d
Exemplo n.º 33
0
    def test_setItemIgnoreAttributes(self):
        """
        Certain attributes should be rendered for roster set.
        """
        item = xmppim.RosterItem(JID('*****@*****.**'),
                                 subscriptionTo=True,
                                 subscriptionFrom=False,
                                 name='Joe User',
                                 groups=set(['Friends', 'Jabber']))
        item.pendingOut = True
        item.approved = True
        d = self.service.setItem(item)

        # Inspect outgoing iq request

        iq = self.stub.output[-1]
        self.assertEqual('set', iq.getAttribute('type'))
        self.assertNotIdentical(None, iq.query)
        self.assertEqual(NS_ROSTER, iq.query.uri)

        children = list(domish.generateElementsQNamed(iq.query.children,
                                                      'item', NS_ROSTER))
        self.assertEqual(1, len(children))
        child = children[0]
        self.assertIdentical(None, child.getAttribute('ask'))
        self.assertIdentical(None, child.getAttribute('approved'))
        self.assertIdentical(None, child.getAttribute('subscription'))

        # Fake successful response

        response = toResponse(iq, 'result')
        d.callback(response)
        return d
Exemplo n.º 34
0
    def test_getNodeType(self):
        d = self.protocol.getNodeType(JID(u'pubsub.example.com'), u'foo_node')
        iq = self.stub.output[-1]
        self.assertEqual(u'pubsub.example.com', iq.getAttribute(u'to'))
        self.assertEqual(u'get', iq.getAttribute(u'type'))
        self.failIf(iq.query is None)
        self.assertEqual(protocols.NS_DISCO_INFO, iq.query.uri)
        self.assertEqual(u'foo_node', iq.query['node'])

        response = toResponse(iq, u'result')
        response['to'] = \
            self.protocol.xmlstream.factory.authenticator.jid.full()
        query = response.addElement((protocols.NS_DISCO_INFO, u'query'))
        query[u'node'] = u'foo_node'
        identity = query.addElement(u'identity')
        identity[u'category'] = u'pubsub'
        identity[u'type'] = u'collection'

        self.stub.send(response)

        def cb(result):
            self.assertEqual(u'collection', result)

        d.addCallback(cb)
        return d
Exemplo n.º 35
0
    def test_setItem(self):
        """
        Setting a roster item renders the item and sends it out.
        """
        item = xmppim.RosterItem(JID('*****@*****.**'),
                                 name='Joe User',
                                 groups=set(['Friends', 'Jabber']))
        d = self.service.setItem(item)

        # Inspect outgoing iq request

        iq = self.stub.output[-1]
        self.assertEqual('set', iq.getAttribute('type'))
        self.assertNotIdentical(None, iq.query)
        self.assertEqual(NS_ROSTER, iq.query.uri)

        children = list(domish.generateElementsQNamed(iq.query.children,
                                                      'item', NS_ROSTER))
        self.assertEqual(1, len(children))
        child = children[0]
        self.assertEqual('*****@*****.**', child['jid'])
        self.assertIdentical(None, child.getAttribute('subscription'))

        # Fake successful response

        response = toResponse(iq, 'result')
        d.callback(response)
        return d
Exemplo n.º 36
0
    def test_setItem(self):
        """
        Setting a roster item renders the item and sends it out.
        """
        item = xmppim.RosterItem(JID('*****@*****.**'),
                                 name='Joe User',
                                 groups=set(['Friends', 'Jabber']))
        d = self.service.setItem(item)

        # Inspect outgoing iq request

        iq = self.stub.output[-1]
        self.assertEqual('set', iq.getAttribute('type'))
        self.assertNotIdentical(None, iq.query)
        self.assertEqual(NS_ROSTER, iq.query.uri)

        children = list(
            domish.generateElementsQNamed(iq.query.children, 'item',
                                          NS_ROSTER))
        self.assertEqual(1, len(children))
        child = children[0]
        self.assertEqual('*****@*****.**', child['jid'])
        self.assertIdentical(None, child.getAttribute('subscription'))

        # Fake successful response

        response = toResponse(iq, 'result')
        d.callback(response)
        return d
Exemplo n.º 37
0
            def _send_signed(userid, var_pkey):
                # verify and link key
                pkey = base64.b64decode(var_pkey.value.__str__().encode('utf-8'))
                signed_pkey = self.parent.link_public_key(pkey, userid)
                if signed_pkey:
                    iq = xmlstream.toResponse(stanza, 'result')
                    query = iq.addElement((xmlstream2.NS_IQ_REGISTER, 'query'))

                    form = query.addElement(('jabber:x:data', 'x'))
                    form['type'] = 'form'

                    hidden = form.addElement((None, 'field'))
                    hidden['type'] = 'hidden'
                    hidden['var'] = 'FORM_TYPE'
                    hidden.addElement((None, 'value'), content='http://kontalk.org/protocol/register#key')

                    signed = form.addElement((None, 'field'))
                    signed['type'] = 'text-single'
                    signed['label'] = 'Signed public key'
                    signed['var'] = 'publickey'
                    signed.addElement((None, 'value'), content=base64.b64encode(signed_pkey))

                    self.parent.send(iq, True)

                else:
                    # key not signed or verified
                    self.parent.error(stanza, 'forbidden', 'Invalid public key.')
Exemplo n.º 38
0
    def test_removeItem(self):
        """
        Removing a roster item is setting an item with subscription C{remove}.
        """
        d = self.service.removeItem(JID('*****@*****.**'))

        # Inspect outgoing iq request

        iq = self.stub.output[-1]
        self.assertEqual('set', iq.getAttribute('type'))
        self.assertNotIdentical(None, iq.query)
        self.assertEqual(NS_ROSTER, iq.query.uri)

        children = list(
            domish.generateElementsQNamed(iq.query.children, 'item',
                                          NS_ROSTER))
        self.assertEqual(1, len(children))
        child = children[0]
        self.assertEqual('*****@*****.**', child['jid'])
        self.assertEqual('remove', child.getAttribute('subscription'))

        # Fake successful response

        response = toResponse(iq, 'result')
        d.callback(response)
        return d
Exemplo n.º 39
0
    def test_getNodes(self):
        d = self.protocol.getNodes(JID(u'pubsub.example.com'), u'foo_node')
        iq = self.stub.output[-1]
        self.assertEqual(u'pubsub.example.com', iq.getAttribute(u'to'))
        self.assertEqual(u'get', iq.getAttribute(u'type'))
        self.failIf(iq.query is None)
        self.assertEqual(protocols.NS_DISCO_ITEMS, iq.query.uri)
        self.assertEqual(u'foo_node', iq.query.getAttribute(u'node'))
        response = toResponse(iq, u'result')
        response['to'] = \
            self.protocol.xmlstream.factory.authenticator.jid.full()
        query = response.addElement((protocols.NS_DISCO_ITEMS, u'query'))
        query[u'node'] = u'foo_node'
        child1 = query.addElement('item')
        child1['node'] = 'foodoo_child_1'
        child1['name'] = 'Foodoo child one'
        child1['jid'] = u'pubsub.example.com'
        child2 = query.addElement('item')
        child2['node'] = 'foodoo_child_2'
        child2['jid'] = u'pubsub.example.com'

        self.stub.send(response)

        def cb(result):
            self.assertEqual([{
                'node': 'foodoo_child_1',
                'jid': u'pubsub.example.com',
                'name': 'Foodoo child one'
            }, {
                'node': 'foodoo_child_2',
                'jid': u'pubsub.example.com'
            }], result)

        d.addCallback(cb)
        return d
Exemplo n.º 40
0
    def onVersion(self, iq):
        response = toResponse(iq, "result")

        query = response.addElement((NS_VERSION, "query"))
        name = query.addElement("name", content=self.name)
        version = query.addElement("version", content=self.version)
        self.send(response)
Exemplo n.º 41
0
    def test_setItemIgnoreAttributes(self):
        """
        Certain attributes should be rendered for roster set.
        """
        item = xmppim.RosterItem(JID('*****@*****.**'),
                                 subscriptionTo=True,
                                 subscriptionFrom=False,
                                 name='Joe User',
                                 groups=set(['Friends', 'Jabber']))
        item.pendingOut = True
        item.approved = True
        d = self.service.setItem(item)

        # Inspect outgoing iq request

        iq = self.stub.output[-1]
        self.assertEqual('set', iq.getAttribute('type'))
        self.assertNotIdentical(None, iq.query)
        self.assertEqual(NS_ROSTER, iq.query.uri)

        children = list(
            domish.generateElementsQNamed(iq.query.children, 'item',
                                          NS_ROSTER))
        self.assertEqual(1, len(children))
        child = children[0]
        self.assertIdentical(None, child.getAttribute('ask'))
        self.assertIdentical(None, child.getAttribute('approved'))
        self.assertIdentical(None, child.getAttribute('subscription'))

        # Fake successful response

        response = toResponse(iq, 'result')
        d.callback(response)
        return d
Exemplo n.º 42
0
    def test_configureNode(self):
        d = self.protocol.configureNode(JID(u'pubsub.example.com'),
                                        u'foo_node',
                                        {u'pubsub#collection': u'bar_node'})
        iq = self.stub.output[-1]
        self.assertEqual(u'pubsub.example.com', iq.getAttribute(u'to'))
        self.assertEqual(u'set', iq.getAttribute(u'type'))
        self.failIf(iq.pubsub is None)
        self.assertEqual(protocols.NS_PUBSUB_OWNER, iq.pubsub.uri)
        self.failIf(iq.pubsub.configure is None)
        self.assertEqual(u'foo_node',
                         iq.pubsub.configure.getAttribute(u'node'))
        self.failIf(iq.pubsub.configure.x is None)
        x = iq.pubsub.configure.x
        self.assertEqual(data_form.NS_X_DATA, x.uri)
        self.assertEqual(u'submit', x.getAttribute('type'))
        self.assertEqual(2, len(x.children))
        fields = x.children
        self.failIf(fields[0].value is None)
        self.assertEqual([protocols.NS_PUBSUB_NODE_CONFIG],
                         fields[0].value.children)
        self.assertEqual(u'pubsub#collection', fields[1].getAttribute(u'var'))
        self.failIf(fields[1].value is None)
        self.assertEqual([u'bar_node'], fields[1].value.children)
        self.assertEqual(fields[0].value.children,
                         [protocols.NS_PUBSUB_NODE_CONFIG])

        response = toResponse(iq, u'result')
        self.stub.send(response)

        def cb(result):
            self.assertEqual(True, result)

        d.addCallback(cb)
        return d
Exemplo n.º 43
0
    def test_getRoster(self):
        """
        A request for the roster is sent out and the response is parsed.
        """
        def cb(roster):
            self.assertIn(JID('*****@*****.**'), roster)
            self.assertIdentical(None, getattr(roster, 'version'))

        d = self.service.getRoster()
        d.addCallback(cb)

        # Inspect outgoing iq request

        iq = self.stub.output[-1]
        self.assertEqual('get', iq.getAttribute('type'))
        self.assertNotIdentical(None, iq.query)
        self.assertEqual(NS_ROSTER, iq.query.uri)
        self.assertFalse(iq.query.hasAttribute('ver'))

        # Fake successful response
        response = toResponse(iq, 'result')
        query = response.addElement((NS_ROSTER, 'query'))
        item = query.addElement('item')
        item['jid'] = '*****@*****.**'

        d.callback(response)
        return d
Exemplo n.º 44
0
    def _register_success(self, userid, var_pkey, stanza):
        # verify and link key
        pkey = base64.b64decode(var_pkey.value.__str__().encode('utf-8'))
        signed_pkey = self.parent.link_public_key(pkey, userid)
        if signed_pkey:
            iq = xmlstream.toResponse(stanza, 'result')
            query = iq.addElement((xmlstream2.NS_IQ_REGISTER, 'query'))

            form = query.addElement(('jabber:x:data', 'x'))
            form['type'] = 'form'

            hidden = form.addElement((None, 'field'))
            hidden['type'] = 'hidden'
            hidden['var'] = 'FORM_TYPE'
            hidden.addElement(
                (None, 'value'),
                content='http://kontalk.org/protocol/register#key')

            signed = form.addElement((None, 'field'))
            signed['type'] = 'text-single'
            signed['label'] = 'Signed public key'
            signed['var'] = 'publickey'
            signed.addElement((None, 'value'),
                              content=base64.b64encode(signed_pkey))

            self.parent.send(iq, True)

        else:
            # key not signed or verified
            stanza.consumed = False
            self.parent.error(stanza, 'forbidden', text='Invalid public key.')
 def test_noID(self):
     """
     Test that a proper response is generated without id attribute.
     """
     stanza = domish.Element(('jabber:client', 'message'))
     response = xmlstream.toResponse(stanza)
     self.failIf(response.hasAttribute('id'))
Exemplo n.º 46
0
    def onVCardGet(self, stanza):
        log.debug("%s requested vCard for %s" % (stanza['from'], stanza['to']))
        jid_from = jid.JID(stanza['from'])
        jid_to = jid.JID(stanza['to'])
        try:
            # are we requesting vCard for a user we have blocked?
            if self.parent.is_presence_allowed(jid_to, jid_from) == -1:
                log.debug("requesting vCard for a blocked user, bouncing error")
                e = error.StanzaError('not-acceptable', 'cancel')
                errstanza = e.toResponse(stanza)
                errstanza.error.addElement((xmlstream2.NS_IQ_BLOCKING_ERRORS, 'blocked'))
                self.send(errstanza)

            else:
                fpr = self.parent.is_presence_allowed(jid_from, jid_to)
                log.debug("is_presence_allowed: %d" % (fpr, ))
                if fpr != 1:
                    raise Exception()

                fpr = self.parent.keyring.get_fingerprint(jid_to.user)
                keydata = self.parent.keyring.get_key(jid_to.user, fpr)

                iq = xmlstream.toResponse(stanza, 'result')
                # add vcard
                vcard = iq.addElement((xmlstream2.NS_XMPP_VCARD4, 'vcard'))
                vcard_key = vcard.addElement((None, 'key'))
                vcard_data = vcard_key.addElement((None, 'uri'))
                vcard_data.addContent(xmlstream2.DATA_PGP_PREFIX + base64.b64encode(keydata))
                self.send(iq)

        except:
            self.parent.error(stanza)
Exemplo n.º 47
0
        def _db(presence, stanza):
            log.debug("iq/last: presence=%r" % (presence, ))
            if type(presence) == list and len(presence) > 0:
                user = presence[0]

                response = xmlstream.toResponse(stanza, 'result')
                response_from = util.userid_to_jid(
                    user['userid'], self.xmlstream.thisEntity.host)
                response['from'] = response_from.userhost()

                query = response.addElement((xmlstream2.NS_IQ_LAST, 'query'))
                if self.parent.sfactory.client_connected(response_from):
                    query['seconds'] = '0'
                else:
                    latest = None
                    for user in presence:
                        if latest is None or latest['timestamp'] > user[
                                'timestamp']:
                            latest = user
                    # TODO timediff from latest
                    #log.debug("max timestamp: %r" % (max, ))
                    query['seconds'] = '123456'

                self.send(response)
                log.debug("iq/last result sent: %s" %
                          (response.toXml().encode('utf-8'), ))

            else:
                # TODO return error?
                log.debug("iq/last: user not found")
Exemplo n.º 48
0
    def toResponse(self, stanza):
        """
        Construct error response stanza.

        The C{stanza} is transformed into an error response stanza by
        swapping the C{to} and C{from} addresses and inserting an error
        element.

        @note: This creates a shallow copy of the list of child elements of the
               stanza. The child elements themselves are not copied themselves,
               and references to their parent element will still point to the
               original stanza element.

               The serialization of an element does not use the reference to
               its parent, so the typical use case of immediately sending out
               the constructed error response is not affected.

        @param stanza: the stanza to respond to
        @type stanza: L{domish.Element}
        """
        from twisted.words.protocols.jabber.xmlstream import toResponse

        response = toResponse(stanza, stanzaType="error")
        response.children = copy.copy(stanza.children)
        response.addChild(self.getElement())
        return response
Exemplo n.º 49
0
    def test_getAffiliations(self):
        d = self.protocol.getAffiliations(JID(u'pubsub.example.com'),
                                          u'foo_node')
        iq = self.stub.output[-1]
        self.assertEqual(u'pubsub.example.com', iq.getAttribute(u'to'))
        self.assertEqual(u'get', iq.getAttribute(u'type'))
        self.failIf(iq.pubsub is None)
        self.assertEqual(protocols.NS_PUBSUB_OWNER, iq.pubsub.uri)
        self.failIf(iq.pubsub.affiliations is None)
        self.assertEqual('foo_node', iq.pubsub.affiliations['node'])
        response = toResponse(iq, u'result')
        response['to'] = \
            self.protocol.xmlstream.factory.authenticator.jid.full()
        pubsub = response.addElement((protocols.NS_PUBSUB_OWNER, u'pubsub'))

        affiliations = pubsub.addElement(u'affiliations')
        affiliations['node'] = u'foo_node'
        user = affiliations.addElement(u'affiliation')
        user['jid'] = '*****@*****.**'
        user['affiliation'] = 'owner'
        foo = affiliations.addElement(u'affiliation')
        foo['jid'] = '*****@*****.**'
        foo['affiliation'] = 'publisher'
        self.stub.send(response)

        def cb(result):
            self.assertEqual(result, [(JID(u'*****@*****.**'), 'owner'),
                                      (JID(u'*****@*****.**'), 'publisher')])

        d.addCallback(cb)
        return d
Exemplo n.º 50
0
 def test_noID(self):
     """
     Test that a proper response is generated without id attribute.
     """
     stanza = domish.Element(('jabber:client', 'message'))
     response = xmlstream.toResponse(stanza)
     self.failIf(response.hasAttribute('id'))
Exemplo n.º 51
0
    def test_removeItem(self):
        """
        Removing a roster item is setting an item with subscription C{remove}.
        """
        d = self.protocol.removeItem(JID('*****@*****.**'))

        # Inspect outgoing iq request

        iq = self.stub.output[-1]
        self.assertEquals('set', iq.getAttribute('type'))
        self.assertNotIdentical(None, iq.query)
        self.assertEquals(NS_ROSTER, iq.query.uri)

        children = list(domish.generateElementsQNamed(iq.query.children,
                                                      'item', NS_ROSTER))
        self.assertEquals(1, len(children))
        child = children[0]
        self.assertEquals('*****@*****.**', child['jid'])
        self.assertEquals('remove', child['subscription'])

        # Fake successful response

        response = toResponse(iq, 'result')
        self.stub.send(response)
        return d
Exemplo n.º 52
0
    def test_modifyAffiliations(self):
        d = self.protocol.modifyAffiliations(
            JID(u'pubsub.example.com'), u'foo_node',
            [(JID(u'*****@*****.**'), 'none')])
        iq = self.stub.output[-1]
        self.assertEqual(u'pubsub.example.com', iq.getAttribute(u'to'))
        self.assertEqual(u'set', iq.getAttribute(u'type'))
        self.failIf(iq.pubsub is None)
        self.assertEqual(protocols.NS_PUBSUB_OWNER, iq.pubsub.uri)
        self.failIf(iq.pubsub.affiliations is None)
        self.assertEqual('foo_node', iq.pubsub.affiliations['node'])
        affiliation = iq.pubsub.affiliations.affiliation
        self.assertEqual('*****@*****.**', affiliation['jid'])
        self.assertEqual('none', affiliation['affiliation'])

        response = toResponse(iq, u'result')
        response['to'] = \
            self.protocol.xmlstream.factory.authenticator.jid.full()
        self.stub.send(response)

        def cb(result):
            self.assertEqual(result, True)

        d.addCallback(cb)
        return d
Exemplo n.º 53
0
    def toResponse(self, stanza):
        """
        Construct error response stanza.

        The C{stanza} is transformed into an error response stanza by
        swapping the C{to} and C{from} addresses and inserting an error
        element.

        @note: This creates a shallow copy of the list of child elements of the
               stanza. The child elements themselves are not copied themselves,
               and references to their parent element will still point to the
               original stanza element.

               The serialization of an element does not use the reference to
               its parent, so the typical use case of immediately sending out
               the constructed error response is not affected.

        @param stanza: the stanza to respond to
        @type stanza: L{domish.Element}
        """
        from twisted.words.protocols.jabber.xmlstream import toResponse
        response = toResponse(stanza, stanzaType='error')
        response.children = copy.copy(stanza.children)
        response.addChild(self.getElement())
        return response
Exemplo n.º 54
0
    def test_getSubscriptions(self):
        d = self.protocol.getSubscriptions(JID(u'pubsub.example.com'),
                                           u'foo_node')
        iq = self.stub.output[-1]
        self.assertEqual(u'pubsub.example.com', iq.getAttribute(u'to'))
        self.assertEqual(u'get', iq.getAttribute(u'type'))
        self.failIf(iq.pubsub is None)
        self.assertEqual(protocols.NS_PUBSUB_OWNER, iq.pubsub.uri)
        self.failIf(iq.pubsub.subscriptions is None)
        self.assertEqual(u'foo_node',
                         iq.pubsub.subscriptions.getAttribute(u'node'))
        response = toResponse(iq, u'result')
        response['to'] = \
            self.protocol.xmlstream.factory.authenticator.jid.full()
        response.addElement((protocols.NS_PUBSUB_OWNER, u'pubsub'))
        subscriptions = response.pubsub.addElement(u'subscriptions')
        subscriptions[u'node'] = u'foo_node'
        subscription1 = subscriptions.addElement(u'subscription')
        subscription1[u'jid'] = u'*****@*****.**'
        subscription1[u'subscription'] = u'unconfigured'
        subscription2 = subscriptions.addElement(u'subscription')
        subscription2[u'jid'] = u'*****@*****.**'
        subscription2[u'subscription'] = u'subscribed'
        subscription2[u'subid'] = u'123-abc'

        self.stub.send(response)

        def cb(result):
            self.assertEqual([(JID(u'*****@*****.**'), u'unconfigured'),
                              (JID(u'*****@*****.**'), u'subscribed')],
                             result)

        d.addCallback(cb)
        return d
Exemplo n.º 55
0
    def onProbe(self, stanza):
        """Handle presence probes."""

        if stanza.consumed:
            return

        log.debug("probe request: %s" % (stanza.toXml(), ))
        stanza.consumed = True
        to = jid.JID(stanza['to'])
        sender = jid.JID(stanza['from'])

        # are we probing a user we have blocked?
        if self.parent.is_presence_allowed(to, sender) == -1:
            log.debug("probing blocked user, bouncing error")
            e = error.StanzaError('not-acceptable', 'cancel')
            errstanza = e.toResponse(stanza)
            errstanza.error.addElement((xmlstream2.NS_IQ_BLOCKING_ERRORS, 'blocked'))
            self.send(errstanza)

        elif self.parent.is_presence_allowed(sender, to) == 1:
            gid = stanza.getAttribute('id')
            if not self.send_user_presence(gid, sender, to):
                response = xmlstream.toResponse(stanza, 'error')
                # TODO include error cause?
                self.send(response)
Exemplo n.º 56
0
    def test_setSubscriptions(self):
        d = self.protocol.setSubscriptions(
            JID(u'pubsub.example.com'), u'foo_node',
            [(JID(u'*****@*****.**'), u'subscribed'),
             (JID(u'*****@*****.**'), u'none')])

        iq = self.stub.output[-1]
        self.assertEqual(u'pubsub.example.com', iq.getAttribute(u'to'))
        self.assertEqual(u'set', iq.getAttribute(u'type'))
        self.failIf(iq.pubsub is None)
        self.assertEqual(protocols.NS_PUBSUB_OWNER, iq.pubsub.uri)
        self.failIf(iq.pubsub.subscriptions is None)
        self.assertEqual(u'foo_node',
                         iq.pubsub.subscriptions.getAttribute(u'node'))
        subscriptions = iq.pubsub.subscriptions.children
        self.assertEqual(2, len(subscriptions))
        self.assertEqual(u'*****@*****.**', subscriptions[0]['jid'])
        self.assertEqual(u'subscribed', subscriptions[0]['subscription'])
        self.assertEqual(u'*****@*****.**', subscriptions[1]['jid'])
        self.assertEqual(u'none', subscriptions[1]['subscription'])

        response = toResponse(iq, u'result')
        response['to'] = \
            self.protocol.xmlstream.factory.authenticator.jid.full()
        self.stub.send(response)

        def cb(result):
            self.assertEqual(True, result)

        d.addCallback(cb)
        return d
Exemplo n.º 57
0
 def test_noType(self):
     """
     Test that a proper response is generated without type attribute.
     """
     stanza = domish.Element(('jabber:client', 'message'))
     response = xmlstream.toResponse(stanza)
     self.assertFalse(response.hasAttribute('type'))
Exemplo n.º 58
0
 def cancel_page(self, iq, s):
     self.reset()
     response = xmlstream.toResponse(stanza=iq, stanzaType='result')
     cmd = getCommand(iq)
     cmd.status = 'canceled'
     response.addChild(cmd.toElement())
     return defer.succeed(response)