Ejemplo n.º 1
0
def test(q, bus, conn, stream):
    # This sidecar sends a stanza, and waits for a reply, before being
    # created.
    pattern = EventPattern('stream-iq', to='sidecar.example.com',
        query_ns='http://example.com/sidecar')
    call_async(q, conn.Sidecars1, 'EnsureSidecar', TEST_PLUGIN_IFACE + ".IQ")
    e = q.expect_many(pattern)[0]

    # The server said yes, so we should get a sidecar back!
    acknowledge_iq(stream, e.stanza)
    q.expect('dbus-return', method='EnsureSidecar')

    identities = ["test/app-list//Test"]
    features = ["com.example.test1", "com.example.test2"]
    ver = compute_caps_hash(identities, features, {})

    iq = IQ(stream, "get")
    query = iq.addElement((ns.DISCO_INFO, 'query'))
    query['node'] = ns.GABBLE_CAPS + '#' + ver
    stream.send(iq)
    e = q.expect('stream-iq', query_ns='http://jabber.org/protocol/disco#info')

    returned_features = [feature['var']
        for feature in xpath.queryForNodes('/iq/query/feature', e.stanza)]
    assertEquals(features, returned_features)

    returned_identities = [identity['category'] + "/" + identity['type']+"//" + identity['name']
        for identity in xpath.queryForNodes('/iq/query/identity', e.stanza)]
    assertEquals(identities, returned_identities)

    new_ver = compute_caps_hash(returned_identities, returned_features, {})
    assertEquals(new_ver, ver)
Ejemplo n.º 2
0
 def on_presence(self, presence):
     print('received presence: %s' % presence.toXml().encode('utf-8'))
     user, host, res = parse(presence['from'])
     jid = '@'.join((user, host))
     if presence.hasAttribute('type'):
         if presence['type'] == 'subscribe':
             if jid in self.users:
                 print('received subscription')
                 if self.users[jid] is False:
                     iq = IQ(self.xmlstream, 'set')
                     query = domish.Element(('jabber:iq:roster', 'query'))
                     item = domish.Element((None, 'item'))
                     item['jid'] = jid
                     item['name'] = jid
                     item.addElement('group', content='controllers')
                     query.addChild(item)
                     iq.addChild(query)
                     iq.addCallback(self.subscribed, jid)
                     self.xmlstream.send(iq)
                     pres = domish.Element((None, 'presence'))
                     pres['type'] = 'subscribed'
                     pres['to'] = jid
                     self.xmlstream.send(pres)
                     
             else:
                 presence = domish.Element((None, 'presence'))
                 presence['type'] = 'unsubscribed'
                 presence['to'] = presence['from']
                 self.xmlstream.send(presence)
Ejemplo n.º 3
0
def sync_stream(q, xmpp_connection):
    """Used to ensure that Salut has processed all stanzas sent to it on this
       xmpp_connection."""

    iq = IQ(None, "get")
    iq.addElement(('http://jabber.org/protocol/disco#info', 'query'))
    xmpp_connection.send(iq)
    q.expect('stream-iq', query_ns='http://jabber.org/protocol/disco#info')
def sync_stream(q, xmpp_connection):
    """Used to ensure that Salut has processed all stanzas sent to it on this
       xmpp_connection."""

    iq = IQ(None, "get")
    iq.addElement(('http://jabber.org/protocol/disco#info', 'query'))
    xmpp_connection.send(iq)
    q.expect('stream-iq', query_ns='http://jabber.org/protocol/disco#info')
Ejemplo n.º 5
0
def make_result_iq(iq):
    result = IQ(None, "result")
    result["id"] = iq["id"]
    query = iq.firstChildElement()

    if query:
        result.addElement((query.uri, query.name))

    return result
Ejemplo n.º 6
0
def send_roster_push(stream, jid, groups):
    iq = IQ(stream, 'set')
    query = iq.addElement((ns.ROSTER, 'query'))
    item = query.addElement('item')
    item['jid'] = jid
    item['subscription'] = 'both'
    for group in groups:
        item.addElement('group', content=group)
    stream.send(iq)
 def send_roster_iq(stream, jid, subscription):
     iq = IQ(stream, "set")
     iq['id'] = 'push'
     query = iq.addElement('query')
     query['xmlns'] = ns.ROSTER
     item = query.addElement('item')
     item['jid'] = jid
     item['subscription'] = subscription
     stream.send(iq)
Ejemplo n.º 8
0
def send_roster_push(stream, jid, groups):
    iq = IQ(stream, 'set')
    query = iq.addElement((ns.ROSTER, 'query'))
    item = query.addElement('item')
    item['jid'] = jid
    item['subscription'] = 'both'
    for group in groups:
        item.addElement('group', content=group)
    stream.send(iq)
Ejemplo n.º 9
0
 def _send_socks5_reply(self, id, stream_used):
     result = IQ(self.stream, 'result')
     result['id'] = id
     result['from'] = self.target
     result['to'] = self.initiator
     query = result.addElement((ns.BYTESTREAMS, 'query'))
     streamhost_used = query.addElement((None, 'streamhost-used'))
     streamhost_used['jid'] = stream_used
     result.send()
Ejemplo n.º 10
0
 def send_not_found(self, id):
     iq = IQ(self.stream, 'error')
     iq['to'] = self.initiator
     iq['from'] = self.target
     iq['id'] = id
     error = iq.addElement(('', 'error'))
     error['type'] = 'cancel'
     error['code'] = '404'
     self.stream.send(iq)
Ejemplo n.º 11
0
 def _send_socks5_reply(self, id, stream_used):
     result = IQ(self.stream, 'result')
     result['id'] = id
     result['from'] = self.target
     result['to'] = self.initiator
     query = result.addElement((ns.BYTESTREAMS, 'query'))
     streamhost_used = query.addElement((None, 'streamhost-used'))
     streamhost_used['jid'] = stream_used
     result.send()
Ejemplo n.º 12
0
 def send_not_found(self, id):
     iq = IQ(self.stream, 'error')
     iq['to'] = self.initiator
     iq['from'] = self.target
     iq['id'] = id
     error = iq.addElement(('', 'error'))
     error['type'] = 'cancel'
     error['code'] = '404'
     self.stream.send(iq)
def make_result_iq(iq):
    result = IQ(None, "result")
    result["id"] = iq["id"]
    query = iq.firstChildElement()

    if query:
        result.addElement((query.uri, query.name))

    return result
Ejemplo n.º 14
0
def test(q, bus, conn, stream):
    self_presence = q.expect('stream-presence')

    c = xpath.queryForNodes('/presence/c', self_presence.stanza)[0]

    jid = '[email protected]/omg'

    # Gabble shouldn't send any disco requests to our contact during this test.
    q.forbid_events([
        EventPattern('stream-iq', to=jid, iq_type='get',
            query_ns=ns.DISCO_INFO),
    ])

    # Check that Gabble doesn't disco other clients with the same caps hash.
    p = make_presence(jid,
        caps={'node': c['node'],
              'hash': c['hash'],
              'ver':  c['ver'],
             })
    stream.send(p)
    sync_stream(q, stream)

    # Check that Gabble doesn't disco its own ext='' bundles (well, its own
    # bundles as advertised by Gabbles that don't do hashed caps)
    p = make_presence(jid,
        caps={'node': c['node'],
              'ver':  c['ver'],
              # omitting hash='' so Gabble doesn't ignore ext=''
              'ext':  'voice-v1 video-v1',
            })
    stream.send(p)
    sync_stream(q, stream)

    # Advertise some different capabilities, to change our own caps hash.
    add = [(cs.CHANNEL_TYPE_STREAMED_MEDIA, 2L**32-1),
           (cs.CHANNEL_TYPE_STREAM_TUBE, 2L**32-1),
           (cs.CHANNEL_TYPE_STREAM_TUBE, 2L**32-1)]
    remove = []
    caps = conn.Capabilities.AdvertiseCapabilities(add, remove)

    self_presence = q.expect('stream-presence')
    c_ = xpath.queryForNodes('/presence/c', self_presence.stanza)[0]
    assertNotEquals(c['ver'], c_['ver'])

    # But then someone asks us for our old caps
    iq = IQ(stream, 'get')
    iq['from'] = jid
    query = iq.addElement((ns.DISCO_INFO, 'query'))
    query['node'] = c['node'] + '#' + c['ver']
    stream.send(iq)

    # Gabble should still know what they are, and reply. This is actually quite
    # important: there's a bug in iChat where if you return an error to a disco
    # query, it just asks again, and again, and again...
    reply = q.expect('stream-iq', to=jid)
    assertEquals('result', reply.iq_type)
Ejemplo n.º 15
0
 def _cb_bare_jid_disco_iq(self, iq):
     # Additionally, Prosody 0.6.1 doesn't like us discoing our own bare
     # JID, and responds with an error which doesn't have the 'from'
     # attribute. Wocky used to discard this, but now tolerates it.
     result = IQ(self, 'error')
     result['id'] = iq['id']
     error = result.addElement((None, 'error'))
     error['type'] = 'cancel'
     error.addElement((ns.STANZA, 'service-unavailable'))
     self.send(result)
Ejemplo n.º 16
0
def repeat_previous_vcard(stream, iq, previous):
    result = IQ(stream, 'result')
    result['id'] = iq['id']
    to = iq.getAttribute('to')

    if to is not None:
        result["from"] = to

    result.addRawXml(previous.firstChildElement().toXml())
    stream.send(result)
Ejemplo n.º 17
0
def sync_stream(q, stream):
    """Used to ensure that Gabble has processed all stanzas sent to it."""

    iq = IQ(stream, "get")
    id = iq['id']
    iq.addElement(('http://jabber.org/protocol/disco#info', 'query'))
    stream.send(iq)
    q.expect('stream-iq', query_ns='http://jabber.org/protocol/disco#info',
        predicate=(lambda event:
            event.stanza['id'] == id and event.iq_type == 'result'))
 def _cb_bare_jid_disco_iq(self, iq):
     # Additionally, Prosody 0.6.1 doesn't like us discoing our own bare
     # JID, and responds with an error which doesn't have the 'from'
     # attribute. Wocky used to discard this, but now tolerates it.
     result = IQ(self, 'error')
     result['id'] = iq['id']
     error = result.addElement((None, 'error'))
     error['type'] = 'cancel'
     error.addElement((ns.STANZA, 'service-unavailable'))
     self.send(result)
Ejemplo n.º 19
0
 def respondToInitialIq(self, iq):
     result = IQ(self.xmlstream, "result")
     result["id"] = iq["id"]
     query = result.addElement('query')
     query["xmlns"] = "jabber:iq:auth"
     query.addElement('username', content='test')
     query.addElement('password')
     query.addElement('digest')
     query.addElement('resource')
     self.xmlstream.send(result)
Ejemplo n.º 20
0
def repeat_previous_vcard(stream, iq, previous):
    result = IQ(stream, 'result')
    result['id'] = iq['id']
    to = iq.getAttribute('to')

    if to is not None:
        result["from"] = to

    result.addRawXml(previous.firstChildElement().toXml())
    stream.send(result)
Ejemplo n.º 21
0
 def respondToInitialIq(self, iq):
     result = IQ(self.xmlstream, "result")
     result["id"] = iq["id"]
     query = result.addElement('query')
     query["xmlns"] = "jabber:iq:auth"
     query.addElement('username', content='test')
     query.addElement('password')
     query.addElement('digest')
     query.addElement('resource')
     self.xmlstream.send(result)
Ejemplo n.º 22
0
 def on_description(self, iq):
     #         print(
     #             'Received description from %s: %s'
     #             % (iq['from'], iq.toXml().encode('utf-8')))
     pause = IQ(self.xmlstream, 'set')
     pause['to'] = iq['from']
     #         enveloppe = domish.Element(
     #             ('http://schemas.xmlsoap.org/soap/envelope/', 'Envelope'))
     enveloppe = domish.Element(
         ('http://schemas.xmlsoap.org/soap/envelope/', 'Envelope'),
         localPrefixes={'s': 'http://schemas.xmlsoap.org/soap/envelope/'})
     enveloppe[
         's:encodingStyle'] = "http://schemas.xmlsoap.org/soap/encoding/"
     header = domish.Element((None, 's:Header'))
     #         header = domish.Element(('http://schemas.xmlsoap.org/soap/envelope/', 'Header'))
     header['mustUnderstand'] = "1"
     uc = domish.Element(('urn:schemas-upnp-org:cloud-1-0', 'uc'))
     uc['serviceId'] = 'urn:av-openhome-org:serviceId:Playlist'
     header.addChild(uc)
     enveloppe.addChild(header)
     body = domish.Element((None, 's:Body'))
     #         body = domish.Element(('http://schemas.xmlsoap.org/soap/envelope/', 'Body'))
     action = domish.Element(
         ('urn:av-openhome-org:service:Playlist:1', 'Read'),
         localPrefixes={'u': 'urn:av-openhome-org:service:Playlist:1'})
     #         action = domish.Element(
     #             ('urn:av-openhome-org:service:Playlist:1', 'Pause'))
     body.addChild(action)
     enveloppe.addChild(body)
     pause.addChild(enveloppe)
     pause.addCallback(self.paused)
     print('send pause')
     print(pause.toXml())
     pause.send()
Ejemplo n.º 23
0
 def initialIq(self, iq):
     result = IQ(self.xmlstream, "result")
     result["id"] = iq["id"]
     query = result.addElement('query')
     query["xmlns"] = "jabber:iq:auth"
     query.addElement('username', content='test')
     query.addElement('password')
     query.addElement('digest')
     query.addElement('resource')
     self.xmlstream.addOnetimeObserver('/iq/query/username', self.secondIq)
     self.xmlstream.send(result)
Ejemplo n.º 24
0
def make_result_iq(stream, iq, add_query_node=True):
    result = IQ(stream, "result")
    result["id"] = iq["id"]
    to = iq.getAttribute('to')
    if to is not None:
        result["from"] = to
    query = iq.firstChildElement()

    if query and add_query_node:
        result.addElement((query.uri, query.name))

    return result
Ejemplo n.º 25
0
def make_result_iq(stream, iq, add_query_node=True):
    result = IQ(stream, "result")
    result["id"] = iq["id"]
    to = iq.getAttribute('to')
    if to is not None:
        result["from"] = to
    query = iq.firstChildElement()

    if query and add_query_node:
        result.addElement((query.uri, query.name))

    return result
Ejemplo n.º 26
0
 def moderate(self, jn, jid_nick, ra, set_to, reason=None):
  if not reason: reason = self.bot.nick
  packet = IQ(self.globalbot.wrapper.x, 'set')
  query = packet.addElement('query', 'http://jabber.org/protocol/muc#admin')
  i = query.addElement('item')
  i[jn] = jid_nick
  i[ra] = set_to
  i.addElement('reason').addContent(reason)
  d = Deferred()
  packet.addCallback(d.callback)
  #print packet.toXml()
  callFromThread(packet.send, self.jid)
  return d
Ejemplo n.º 27
0
 def _send_socks5_init(self, port):
     iq = IQ(self.stream, 'set')
     iq['to'] = self.target
     iq['from'] = self.initiator
     query = iq.addElement((ns.BYTESTREAMS, 'query'))
     query['sid'] = self.stream_id
     query['mode'] = 'tcp'
     for jid, host in self.hosts:
         streamhost = query.addElement('streamhost')
         streamhost['jid'] = jid
         streamhost['host'] = host
         streamhost['port'] = str(port)
     self.stream.send(iq)
Ejemplo n.º 28
0
 def _send_socks5_init(self, port):
     iq = IQ(self.stream, 'set')
     iq['to'] = self.target
     iq['from'] = self.initiator
     query = iq.addElement((ns.BYTESTREAMS, 'query'))
     query['sid'] = self.stream_id
     query['mode'] = 'tcp'
     for jid, host in self.hosts:
         streamhost = query.addElement('streamhost')
         streamhost['jid'] = jid
         streamhost['host'] = host
         streamhost['port'] = str(port)
     self.stream.send(iq)
Ejemplo n.º 29
0
    def on_description(self, iq):
#         print(
#             'Received description from %s: %s'
#             % (iq['from'], iq.toXml().encode('utf-8')))
        pause = IQ(self.xmlstream, 'set')
        pause['to'] = iq['from']
#         enveloppe = domish.Element(
#             ('http://schemas.xmlsoap.org/soap/envelope/', 'Envelope'))
        enveloppe = domish.Element(
            ('http://schemas.xmlsoap.org/soap/envelope/', 'Envelope'), localPrefixes={'s': 'http://schemas.xmlsoap.org/soap/envelope/'})
        enveloppe['s:encodingStyle'] = "http://schemas.xmlsoap.org/soap/encoding/"
        header = domish.Element((None, 's:Header'))
#         header = domish.Element(('http://schemas.xmlsoap.org/soap/envelope/', 'Header'))
        header['mustUnderstand'] = "1"
        uc = domish.Element(('urn:schemas-upnp-org:cloud-1-0', 'uc'))
        uc['serviceId'] = 'urn:av-openhome-org:serviceId:Playlist'
        header.addChild(uc)
        enveloppe.addChild(header)
        body = domish.Element((None, 's:Body'))
#         body = domish.Element(('http://schemas.xmlsoap.org/soap/envelope/', 'Body'))
        action = domish.Element(
            ('urn:av-openhome-org:service:Playlist:1', 'Read'), localPrefixes={'u': 'urn:av-openhome-org:service:Playlist:1'})
#         action = domish.Element(
#             ('urn:av-openhome-org:service:Playlist:1', 'Pause'))
        body.addChild(action)
        enveloppe.addChild(body)
        pause.addChild(enveloppe)
        pause.addCallback(self.paused)
        print('send pause')
        print(pause.toXml())
        pause.send()
Ejemplo n.º 30
0
    def test_configureResponse(self):

        def _getChild(element, name):
            for child in element.elements():
                if child.name == name:
                    return child
            return None

        response = IQ(self.xmlStream, type="result")
        pubsubElement = response.addElement("pubsub")
        configElement = pubsubElement.addElement("configure")
        formElement = configElement.addElement("x")
        formElement["type"] = "form"
        fields = [
            ( "unknown", "don't edit me", "text-single" ),
            ( "pubsub#deliver_payloads", "0", "boolean" ),
            ( "pubsub#persist_items", "0", "boolean" ),
        ]
        expectedFields = {
            "unknown" : "don't edit me",
            "pubsub#deliver_payloads" : "1",
            "pubsub#persist_items" : "1",
        }
        for field in fields:
            fieldElement = formElement.addElement("field")
            fieldElement["var"] = field[0]
            fieldElement["type"] = field[2]
            fieldElement.addElement("value", content=field[1])

        self.assertEquals(len(self.xmlStream.elements), 1)
        self.notifier.requestConfigurationFormSuccess(response, "testNodeName",
            False)
        self.assertEquals(len(self.xmlStream.elements), 2)

        iq = self.xmlStream.elements[1]
        self.assertEquals(iq.name, "iq")
        self.assertEquals(iq["type"], "set")

        pubsubElement = list(iq.elements())[0]
        self.assertEquals(pubsubElement.name, "pubsub")
        configElement = list(pubsubElement.elements())[0]
        self.assertEquals(configElement.name, "configure")
        self.assertEquals(configElement["node"], "testNodeName")
        formElement = list(configElement.elements())[0]
        self.assertEquals(formElement["type"], "submit")
        for field in formElement.elements():
            valueElement = _getChild(field, "value")
            if valueElement is not None:
                self.assertEquals(expectedFields[field["var"]],
                    str(valueElement))
Ejemplo n.º 31
0
    def bindIq(self, iq):
        resource = xpath.queryForString('/iq/bind/resource', iq)
        if self.resource is not None:
            assertEquals(self.resource, resource)
        else:
            assert resource is not None

        result = IQ(self.xmlstream, "result")
        result["id"] = iq["id"]
        bind = result.addElement((NS_XMPP_BIND, 'bind'))
        jid = bind.addElement('jid', content=('test@localhost/%s' % resource))
        self.xmlstream.send(result)

        self.xmlstream.dispatch(self.xmlstream, xmlstream.STREAM_AUTHD_EVENT)
Ejemplo n.º 32
0
    def _jingle_stanza(self, action):
        iq = IQ(self.stream, 'set')
        iq['from'] = self.remote_jid
        iq['to'] = self.local_jid
        jingle = domish.Element(("http://jabber.org/protocol/jingle", 'jingle'))
        if self.direction == 'incoming':
            jingle['initiator'] = self.remote_jid
        elif self.direction == 'outgoing':
            jingle['initiator'] = self.local_jid

        jingle['action'] = action
        jingle['sid'] = self.session_id
        iq.addChild(jingle)
        return (iq, jingle)
Ejemplo n.º 33
0
    def _gtalk_stanza(self, action):
        iq = IQ(self.stream, 'set')
        iq['from'] = self.remote_jid
        iq['to'] = self.local_jid
        sess = domish.Element(("http://www.google.com/session", 'session'))
        if self.direction == 'incoming':
            sess['initiator'] = self.remote_jid
        elif self.direction == 'outgoing':
            sess['initiator'] = self.local_jid

        sess['type'] = action
        sess['id'] = self.session_id
        iq.addChild(sess)
        return (iq, sess)
Ejemplo n.º 34
0
    def getStats(self, jid = "icq.netlab.cz"):
        iq = IQ(self.xmlstream, "get")
        iq['to'] = jid
        iq.addElement(("http://jabber.org/protocol/stats", "query"))

        iq.addCallback(self._statsReceived)
        iq.send()
Ejemplo n.º 35
0
def send_error_reply(stream, iq, error_stanza=None):
    result = IQ(stream, "error")
    result["id"] = iq["id"]
    query = iq.firstChildElement()
    to = iq.getAttribute('to')
    if to is not None:
        result["from"] = to

    if query:
        result.addElement((query.uri, query.name))

    if error_stanza:
        result.addChild(error_stanza)

    stream.send(result)
Ejemplo n.º 36
0
    def open_bytestream(self, expected_before=[], expected_after=[]):
        # open IBB bytestream
        iq = IQ(self.stream, 'set')
        iq['to'] = self.target
        iq['from'] = self.initiator
        open = iq.addElement((ns.IBB, 'open'))
        open['sid'] = self.stream_id
        # set a ridiculously small block size to stress test IBB buffering
        open['block-size'] = '1'
        self.stream.send(iq)

        events_before = self.q.expect_many(*expected_before)
        events_after = self.q.expect_many(*expected_after)

        return events_before, events_after
Ejemplo n.º 37
0
 def moderate(self, jn, jid_nick, ra, set_to, reason=None):
  if not reason:
   try: reason = self.bot.nick
   except: reason = 'freQ'
  packet = IQ(self.globalbot.wrapper.x, 'set')
  query = packet.addElement('query', 'http://jabber.org/protocol/muc#admin')
  i = query.addElement('item')
  i[jn] = jid_nick
  i[ra] = set_to
  i.addElement('reason').addContent(reason)
  d = Deferred()
  packet.addCallback(d.callback)
  #print packet.toXml()
  callFromThread(packet.send, self.jid)
  return d
Ejemplo n.º 38
0
def test(q, bus, conn, stream):
    amy_handle = conn.get_contact_handle_sync('*****@*****.**')

    # Divergence from Gabble: hazetest responds to all roster gets with an
    # empty roster, so we need to push the roster.
    iq = IQ(stream, 'set')
    query = iq.addElement(('jabber:iq:roster', 'query'))
    item = query.addElement('item')
    item['jid'] = '*****@*****.**'
    item['subscription'] = 'both'

    stream.send(iq)

    presence = domish.Element((None, 'presence'))
    presence['from'] = '*****@*****.**'
    show = presence.addElement((None, 'show'))
    show.addContent('away')
    status = presence.addElement((None, 'status'))
    status.addContent('At the pub')
    stream.send(presence)

    event = q.expect('dbus-signal', signal='PresencesChanged')
    assert event.args[0] == { amy_handle: (3, 'away', 'At the pub') }

    presence = domish.Element((None, 'presence'))
    presence['from'] = '*****@*****.**'
    show = presence.addElement((None, 'show'))
    show.addContent('chat')
    status = presence.addElement((None, 'status'))
    status.addContent('I may have been drinking')
    stream.send(presence)

    event = q.expect('dbus-signal', signal='PresencesChanged')
    # FIXME: 'chat' gets lost somewhere between the XMPP stream and what Haze
    # produces.
    assert event.args[0] == { amy_handle: (2, 'available', 'I may have been drinking') }

    amy_handle, asv = conn.Contacts.GetContactByID('*****@*****.**',
            [cs.CONN_IFACE_SIMPLE_PRESENCE])
    assertEquals(event.args[0][amy_handle], asv.get(cs.ATTR_PRESENCE))

    bob_handle, asv = conn.Contacts.GetContactByID('*****@*****.**',
            [cs.CONN_IFACE_SIMPLE_PRESENCE])
    assertEquals((cs.PRESENCE_UNKNOWN, 'unknown', ''),
            asv.get(cs.ATTR_PRESENCE))

    conn.Disconnect()
    q.expect('dbus-signal', signal='StatusChanged', args=[2, 1])
Ejemplo n.º 39
0
def make_roster_push(stream, jid, subscription, ask_subscribe=False, name=None):
    iq = IQ(stream, "set")
    iq['id'] = 'push'
    query = iq.addElement('query')
    query['xmlns'] = ns.ROSTER
    item = query.addElement('item')
    item['jid'] = jid
    item['subscription'] = subscription

    if name is not None:
        item['name'] = name

    if ask_subscribe:
        item['ask'] = 'subscribe'

    return iq
Ejemplo n.º 40
0
    def bindIq(self, iq):
        resource = xpath.queryForString('/iq/bind/resource', iq)
        if self.resource is not None:
            assertEquals(self.resource, resource)
        else:
            assert resource is not None

        result = IQ(self.xmlstream, "result")
        result["id"] = iq["id"]
        bind = result.addElement((ns.NS_XMPP_BIND, 'bind'))
        self.bare_jid = '%s@%s' % (self.username, self.xmlstream.domain)
        self.full_jid = '%s/%s' % (self.bare_jid, resource)
        jid = bind.addElement('jid', content=self.full_jid)
        self.xmlstream.send(result)

        self.xmlstream.dispatch(self.xmlstream, xmlstream.STREAM_AUTHD_EVENT)
Ejemplo n.º 41
0
    def __init__(self, iq: IQ):
        self.iq = iq

        # Create form element
        self.form = iq.addElement("x")
        self.form.attributes["xmlns"] = "jabber:x:data"
        self.form.attributes["type"] = "form"
Ejemplo n.º 42
0
def answer_error_to_pubsub_request(stream, request):
    # look for node's name in the request
    items = xpath.queryForNodes('/iq/pubsub/items', request)[0]
    node = items['node']

    reply = IQ(stream, "error")
    reply['id'] = request['id']
    reply['from'] = request['to']
    pubsub = reply.addElement((ns.PUBSUB, 'pubsub'))
    items = pubsub.addElement((None, 'items'))
    items['node'] = node
    error = reply.addElement((None, 'error'))
    error['type'] = 'auth'
    error.addElement((ns.STANZA, 'not-authorized'))
    error.addElement(("%s#errors" % ns.PUBSUB, 'presence-subscription-required'))
    stream.send(reply)
Ejemplo n.º 43
0
    def bindIq(self, iq):
        resource = xpath.queryForString('/iq/bind/resource', iq)
        if self.resource is not None:
            assertEquals(self.resource, resource)
        else:
            assert resource is not None

        result = IQ(self.xmlstream, "result")
        result["id"] = iq["id"]
        bind = result.addElement((ns.NS_XMPP_BIND, 'bind'))
        self.bare_jid = '%s@%s' % (self.username, self.xmlstream.domain)
        self.full_jid = '%s/%s' % (self.bare_jid, resource)
        jid = bind.addElement('jid', content=self.full_jid)
        self.xmlstream.send(result)

        self.xmlstream.dispatch(self.xmlstream, xmlstream.STREAM_AUTHD_EVENT)
Ejemplo n.º 44
0
def answer_error_to_pubsub_request(stream, request):
    # look for node's name in the request
    items = xpath.queryForNodes('/iq/pubsub/items', request)[0]
    node = items['node']

    reply = IQ(stream, "error")
    reply['id'] = request['id']
    reply['from'] = request['to']
    pubsub = reply.addElement((ns.PUBSUB, 'pubsub'))
    items = pubsub.addElement((None, 'items'))
    items['node'] = node
    error = reply.addElement((None, 'error'))
    error['type'] = 'auth'
    error.addElement((ns.STANZA, 'not-authorized'))
    error.addElement(
        ("%s#errors" % ns.PUBSUB, 'presence-subscription-required'))
    stream.send(reply)
Ejemplo n.º 45
0
    def open_bytestream(self, expected_before=[], expected_after=[]):
        # open IBB bytestream
        iq = IQ(self.stream, 'set')
        iq['to'] = self.target
        iq['from'] = self.initiator
        open = iq.addElement((ns.IBB, 'open'))
        open['sid'] = self.stream_id
        # set a ridiculously small block size to stress test IBB buffering
        open['block-size'] = '1'

        assert self.checked

        events_before = self.q.expect_many(*expected_before)
        self.stream.send(iq)
        events_after = self.q.expect_many(*expected_after)

        return events_before, events_after
Ejemplo n.º 46
0
 def check_users(self):
     for user, value in self.users.items():
         if value['state'] is False:
             iq = IQ(self.xmlstream, 'set')
             query = domish.Element(('jabber:iq:roster', 'query'))
             item = domish.Element((None, 'item'))
             item['name'] = user
             item['jid'] = user
             item.addElement('group', content='hosts')
             query.addChild(item)
             iq.addChild(query)
             iq.addCallback(self.subscribe, user)
             print('send IQ: %s' % (iq.toXml().encode('utf-8')))
             iq.send()
Ejemplo n.º 47
0
	def getStats(self, jid = "icq.netlab.cz"):
		iq = IQ(self.xmlstream, "get")
		iq['to'] = jid
		iq.addElement(("http://jabber.org/protocol/stats", "query"))

		iq.addCallback(self._statsReceived)
		iq.send()
Ejemplo n.º 48
0
def test_jabber_pass_fail(q, bus, conn, stream, which):
    conn.Connect()

    q.expect('dbus-signal',
             signal='StatusChanged',
             args=[cs.CONN_STATUS_CONNECTING, cs.CSR_REQUESTED])

    e = q.expect('auth-initial-iq')
    authenticator = e.authenticator
    authenticator.respondToInitialIq(e.iq)

    chan, props = expect_sasl_channel(q, bus, conn)

    assertSameSets(['X-TELEPATHY-PASSWORD'],
                   props.get(cs.SASL_AVAILABLE_MECHANISMS))

    chan.SASLAuthentication.StartMechanismWithData('X-TELEPATHY-PASSWORD',
                                                   PASSWORD)

    e = q.expect('auth-second-iq')

    result = IQ(stream, 'error')
    result['id'] = e.id
    error = result.addElement('error')
    error['code'] = str(CODES[which])
    error['type'] = TYPES[which]
    error.addElement((ns.STANZA, which))
    stream.send(result)

    e = q.expect('dbus-signal',
                 signal='SASLStatusChanged',
                 interface=cs.CHANNEL_IFACE_SASL_AUTH,
                 predicate=lambda e: e.args[0] == cs.SASL_STATUS_SERVER_FAILED)
    assertEquals(ERRORS[which], e.args[1])
    assertContains('debug-message', e.args[2])

    e = q.expect('dbus-signal', signal='ConnectionError')
    assertEquals(ERRORS[which], e.args[0])
    assertContains('debug-message', e.args[1])

    e = q.expect('dbus-signal', signal='StatusChanged')
    assertEquals(cs.CONN_STATUS_DISCONNECTED, e.args[0])
    assertEquals(CSRS[which], e.args[1])
def make_roster_push(stream,
                     jid,
                     subscription,
                     ask_subscribe=False,
                     name=None):
    iq = IQ(stream, "set")
    iq['id'] = 'push'
    query = iq.addElement('query')
    query['xmlns'] = ns.ROSTER
    item = query.addElement('item')
    item['jid'] = jid
    item['subscription'] = subscription

    if name is not None:
        item['name'] = name

    if ask_subscribe:
        item['ask'] = 'subscribe'

    return iq
Ejemplo n.º 50
0
    def _create_si_offer(self, profile, to=None):
        assert self.initiated

        iq = IQ(self.stream, 'set')
        iq['from'] = self.initiator
        if to is None:
            iq['to'] = self.target
        else:
            iq['to'] = to
        si = iq.addElement((ns.SI, 'si'))
        si['id'] = self.stream_id
        si['profile'] = profile
        feature = si.addElement((ns.FEATURE_NEG, 'feature'))
        x = feature.addElement((ns.X_DATA, 'x'))
        x['type'] = 'form'
        field = x.addElement((None, 'field'))
        field['var'] = 'stream-method'
        field['type'] = 'list-single'

        return iq, si, field
Ejemplo n.º 51
0
def outgoing_fail(q, bus, conn):
    path, incoming, stanza = setup_outgoing_tests(q, bus, conn)

    # construct a nice error reply
    reply = IQ(None, 'error')
    reply['id'] = stanza['id']
    error = reply.addElement('error')
    error['type'] = 'cancel'
    error['code'] = '409'
    error.addElement((ns.STANZA, 'conflict'))
    error.addElement((ycs.MESSAGE_NS, 'yodawg'))
    text = error.addElement((ns.STANZA, 'text'), content='imma let you finish')

    incoming.send(reply)

    e = q.expect('dbus-signal', signal='Failed', path=path)
    error_type, stanza_error_name, yst_error_name, text = e.args
    assertEquals(ycs.ERROR_TYPE_CANCEL, error_type)
    assertEquals('conflict', stanza_error_name)
    assertEquals('yodawg', yst_error_name)
    assertEquals('imma let you finish', text)
Ejemplo n.º 52
0
    def on_presence(self, presence):
        print('received presence: %s' % presence.toXml().encode('utf-8'))
        user, host, res = parse(presence['from'])
        jid = '@'.join((user, host))
        if presence.hasAttribute('type'):
            if presence['type'] == 'subscribe':
                if jid in self.users:
                    print('received subscription')
                    if self.users[jid] is False:
                        iq = IQ(self.xmlstream, 'set')
                        query = domish.Element(('jabber:iq:roster', 'query'))
                        item = domish.Element((None, 'item'))
                        item['jid'] = jid
                        item['name'] = jid
                        item.addElement('group', content='controllers')
                        query.addChild(item)
                        iq.addChild(query)
                        iq.addCallback(self.subscribed, jid)
                        self.xmlstream.send(iq)
                        pres = domish.Element((None, 'presence'))
                        pres['type'] = 'subscribed'
                        pres['to'] = jid
                        self.xmlstream.send(pres)

                else:
                    presence = domish.Element((None, 'presence'))
                    presence['type'] = 'unsubscribed'
                    presence['to'] = presence['from']
                    self.xmlstream.send(presence)
Ejemplo n.º 53
0
    def authenticated(self, xs):

        self.log.debug('Cloud Authenticated')
        presence = domish.Element((None, 'presence'))
        xs.send(presence)
        xs.addObserver('/presence', self.on_presence)
        xs.addObserver('/iq', self.on_iq)
        xs.addObserver('/message', self.on_event)
        disco = IQ(xs, 'get')
        disco.addElement(('http://jabber.org/protocol/disco#items', 'query'))
        disco.addCallback(self.cloud_discovered)
        disco.send()
#         self.reactor.callLater(120, xs.sendFooter)
        self.reactor.callLater(5, self.check_users)
Ejemplo n.º 54
0
 def __call__(self, *args, **kwargs):
     d = defer.Deferred()
     self.ctx, = self.contexts
     self.get_out_object(self.ctx, args, kwargs)
     self.get_out_string(self.ctx)
     self.ctx.in_string = []
     action = IQ(self.url[0], 'set')
     for item in self.ctx.out_string:
         action.addRawXml(item)
     if action.callbacks:
         action.addCallback(self.on_response, d)
     else:
         print('wtf?')
     action.send(to=self.url[1])
     return d
Ejemplo n.º 55
0
    def create_ps_node(self, node):
        def registered(node, iq):
            if iq['type'] == 'result':
                node_name = '/'.join((self._jid, node[1]))
                if node_name in self.registrations:
                    return
                event = XmppEvent(node_name, self, 'pubsub.' + self.jid.host)
                node[2].subscribe(event, 100)
                self.reactor.callLater(95, self.renew_subscription,
                                       *(node_name, node))
                self.registrations.append(node_name)
                self.log.debug('node {node} registered', node=node_name)
            else:
                self.log.error('node creation {name} failed:{iq}',
                               name=node,
                               iq=iq.toXml())

        iq = IQ(self.xmlstream, 'set')
        ps = domish.Element(('http://jabber.org/protocol/pubsub', 'pubsub'))
        create = domish.Element((None, 'create'))
        create['node'] = '/'.join((self._jid, node[1], node[0].name))
        ps.addChild(create)
        configure = domish.Element((None, 'configure'))
        x = domish.Element(('jabber:x:data', 'x'))
        x['type'] = 'submit'
        field = domish.Element((None, 'field'))
        field['var'] = 'FORM_TYPE'
        field['type'] = 'hidden'
        field.addElement(
            'value', content='http://jabber.org/protocol/pubsub#node_config')
        x.addChild(field)
        access = domish.Element((None, 'field'))
        access['var'] = 'pubsub#access_model'
        access.addElement('value', content='roster')
        x.addChild(access)
        #         expire = domish.Element((None, 'field'))
        #         expire['var'] = 'pubsub#item_expire'
        #         expire.addElement('value', content='60')
        #         x.addChild(expire)
        last = domish.Element((None, 'field'))
        last['var'] = 'pubsub#send_last_published_item'
        last.addElement('value', content='on_sub_and_presence')
        x.addChild(last)
        configure.addChild(x)
        ps.addChild(configure)
        iq.addChild(ps)
        iq.addCallback(registered, node)
        iq.send(to='pubsub.' + self.jid.host)
Ejemplo n.º 56
0
 def respond_rpc(self, resp, to, queryID):
     #         print('send: %s' % resp)
     #         self.log.debug('respond rpc: %s' % resp[0][39:])
     res = IQ(self.xmlstream, 'result')
     res['id'] = queryID
     if resp:
         for item in resp:
             res.addRawXml(item[39:].decode('utf-8'))  # Skip the xml header
     res.send(to=to)
Ejemplo n.º 57
0
def returns_bees_from_search(q, stream, conn):
    server = 'hivemind.localhost'
    iq = call_create(q, conn, server)

    result = make_result_iq(stream, iq)
    query = result.firstChildElement()
    query.addElement("nick")
    stream.send(result)

    event = q.expect('dbus-return', method='CreateChannel')
    c = make_channel_proxy(conn, event.value[0], 'Channel')
    c_search = dbus.Interface(c, cs.CHANNEL_TYPE_CONTACT_SEARCH)

    call_async(q, c_search, 'Search', {'nickname': 'Buzzy'})
    iq_event, _ = q.expect_many(
        EventPattern('stream-iq', to=server, query_ns=ns.SEARCH),
        EventPattern('dbus-signal', signal='SearchStateChanged'),
    )
    iq = iq_event.stanza

    result = IQ(stream, 'result')
    result['id'] = iq['id']
    result['from'] = iq['to']
    result.addElement((ns.SEARCH, 'bees')).addElement('bzzzzzzz')
    stream.send(result)

    ssc = q.expect('dbus-signal', signal='SearchStateChanged')
    new_state, reason, details = ssc.args

    assert new_state == cs.SEARCH_FAILED, new_state
    assert reason == cs.NOT_AVAILABLE, reason

    # We call stop after the search has failed; it should succeed and do nothing.
    call_async(q, c_search, 'Stop')
    event = q.expect('dbus-return', method='Stop')

    c.Close()