Ejemplo n.º 1
0
    def _onGetRegister(self, iq):
        fromjid = jid.internJID(iq["from"])
        username = database.getUsername(fromjid)
        phone = database.getPhone(fromjid)
        smstyp = database.getDefaultMessageType(fromjid)

        reply = domish.Element((NS_REGISTER, "query"))
        xdata = reply.addElement("x", NS_XDATA)
        xdata.addElement("title", content=u"SMS77.de Gateway Registrierung")
        xdata.attributes["type"] = "form"

        instructions = u"Hier können Sie Ihren sms77.de Account mit dem Gateway\nregistrieren. Geben Sie dazu ihren sms77.de Benutzernamen\nsowie das dazugehörige Passwort an."

        xdata.addElement("instructions", content=instructions)
        reply.addElement("instructions", content=instructions)

        field = xdata.addElement("field")
        field.attributes["type"] = "hidden"
        field.attributes["var"] = "FORM_TYPE"
        field.addElement("value", content=NS_GATEWAY)

        field = xdata.addElement("field")
        field.attributes["type"] = "text-single"
        field.attributes["label"] = "Benutzername"
        field.attributes["var"] = "username"
        field.addElement("required")

        if username == None:
            reply.addElement("username")
        else:
            reply.addElement("username", content=username)
            field.addElement("value", content=username)

        field = xdata.addElement("field")
        field.attributes["type"] = "text-private"
        field.attributes["label"] = "Passwort"
        field.attributes["var"] = "password"
        field.addElement("required")
        reply.addElement("password")

        field = xdata.addElement("field")
        field.attributes["type"] = "text-single"
        field.attributes["label"] = "Telefonnummer"
        field.attributes["var"] = "phone"
        field.addElement("required")

        if username == None:
            reply.addElement("phone")
        else:
            reply.addElement("phone", content=phone)
            field.addElement("value", content=phone)

        field = xdata.addElement("field")
        field.attributes["type"] = "list-single"
        field.attributes["label"] = "Standard SMS Typ"
        field.attributes["var"] = "smstype"
        if smstyp != None: field.addElement("value", content=smstyp)

        option = field.addElement("option")
        option.attributes["label"] = "BasicPlus"
        option.addElement("value", content="basicplus")

        option = field.addElement("option")
        option.attributes["label"] = "Standard"
        option.addElement("value", content="standard")

        option = field.addElement("option")
        option.attributes["label"] = "Quality"
        option.addElement("value", content="quality")

        option = field.addElement("option")
        option.attributes["label"] = "Festnetz"
        option.addElement("value", content="festnetz")

        option = field.addElement("option")
        option.attributes["label"] = "Flash"
        option.addElement("value", content="flash")

        field = xdata.addElement("field")
        field.attributes["type"] = "list-single"
        field.attributes["label"] = "Eingehende SMS als"
        field.attributes["var"] = "msgtype"
        if database.getMessageAsChat(fromjid):
            field.addElement("value", content="chat")
        else:
            field.addElement("value", content="message")

        option = field.addElement("option")
        option.attributes["label"] = "Chat"
        option.addElement("value", content="chat")

        option = field.addElement("option")
        option.attributes["label"] = "Nachricht"
        option.addElement("value", content="message")

        field = xdata.addElement("field")
        field.attributes["type"] = "list-single"
        field.attributes["label"] = "Status Berichte"
        field.attributes["var"] = "report"
        if database.isReportRequested(fromjid):
            field.addElement("value", content="yes")
        else:
            field.addElement("value", content="no")

        option = field.addElement("option")
        option.attributes["label"] = "Ja"
        option.addElement("value", content="yes")

        option = field.addElement("option")
        option.attributes["label"] = "Nein"
        option.addElement("value", content="no")

        return reply
Ejemplo n.º 2
0
 def testChildSameDefaultNamespace(self):
     e = domish.Element(("testns", "foo"))
     e.addElement("bar", "testns")
     self.assertEqual(e.toXml(), "<foo xmlns='testns'><bar/></foo>")
Ejemplo n.º 3
0
 def testOnlyChildDefaultNamespace(self):
     e = domish.Element((None, "foo"))
     e.addElement(("ns2", "bar"), 'ns2')
     self.assertEqual(e.toXml(), "<foo><bar xmlns='ns2'/></foo>")
Ejemplo n.º 4
0
 def test_interface(self):
     """
     L{domish.Element} implements L{domish.IElement}.
     """
     verifyObject(domish.IElement, domish.Element((None, u"foo")))
Ejemplo n.º 5
0
 def testDefaultNamespace(self):
     e = domish.Element(("testns", "foo"))
     self.assertEqual(e.toXml(), "<foo xmlns='testns'/>")
Ejemplo n.º 6
0
    if error is None:
        d.addBoth((lambda *args: reactor.crash()))
    else:
        # please ignore the POSIX behind the curtain
        d.addBoth((lambda *args: os._exit(1)))


def exec_test(fun, params=None, protocol=None, timeout=None,
              authenticator=None, num_instances=1, do_connect=True):
    reactor.callWhenRunning(
        exec_test_deferred, fun, params, protocol, timeout, authenticator, num_instances,
        do_connect)
    reactor.run()

# Useful routines for server-side vCard handling
current_vcard = domish.Element(('vcard-temp', 'vCard'))

def expect_and_handle_get_vcard(q, stream):
    get_vcard_event = q.expect('stream-iq', query_ns=ns.VCARD_TEMP,
        query_name='vCard', iq_type='get')

    iq = get_vcard_event.stanza
    vcard = iq.firstChildElement()
    assert vcard.name == 'vCard', vcard.toXml()

    # Send back current vCard
    result = make_result_iq(stream, iq, add_query_node=False)
    result.addChild(current_vcard)
    stream.send(result)

def expect_and_handle_set_vcard(q, stream, check=None):
Ejemplo n.º 7
0
 def test_addContentBytes(self):
     """
     Byte strings passed to C{addContent} are not acceptable on Python 3.
     """
     element = domish.Element((u"testns", u"foo"))
     self.assertRaises(TypeError, element.addContent, b'bytes')
Ejemplo n.º 8
0
def test(q, bus, conn):
    conn.Connect()
    q.expect('dbus-signal', signal='StatusChanged', args=[0L, 0L])
    basic_txt = {"txtvers": "1", "status": "avail"}

    self_handle = conn.Properties.Get(cs.CONN, "SelfHandle")
    self_handle_name = conn.Properties.Get(cs.CONN, "SelfID")

    contact_name = "test-text-channel@" + get_host_name()
    listener, port = setup_stream_listener(q, contact_name)

    announcer = AvahiAnnouncer(contact_name, "_presence._tcp", port, basic_txt)

    handle = wait_for_contact_in_publish(q, bus, conn, contact_name)

    # create a clique room
    basic_txt = {"txtvers": "0"}
    AvahiAnnouncer("myroom", "_clique._udp", 41377, basic_txt)

    # connect a stream
    AvahiListener(q).listen_for_service("_presence._tcp")
    e = q.expect('service-added',
                 name=self_handle_name,
                 protocol=avahi.PROTO_INET)
    service = e.service
    service.resolve()

    e = q.expect('service-resolved', service=service)

    xmpp_connection = connect_to_stream(q, contact_name, self_handle_name,
                                        str(e.pt), e.port)

    e = q.expect('connection-result')
    assert e.succeeded, e.reason

    e = q.expect('stream-opened', connection=xmpp_connection)

    # send an invitation
    message = domish.Element(('', 'message'))
    message['type'] = 'normal'
    message.addElement('body', content='You got a Clique chatroom invitation')
    invite = message.addElement((NS_CLIQUE, 'invite'))
    invite.addElement('roomname', content='myroom')
    invite.addElement('reason', content='Inviting to this room')
    invite.addElement('address', content='127.0.0.1')
    invite.addElement('port', content='41377')
    xmpp_connection.send(message)

    # group channel is created
    e = q.expect('dbus-signal',
                 signal='NewChannel',
                 predicate=lambda e: e.args[1] == cs.CHANNEL_TYPE_TEXT and e.
                 args[2] == cs.HT_ROOM)
    path = e.args[0]
    channel = make_channel_proxy(conn, path, 'Channel')
    props_iface = dbus.Interface(bus.get_object(conn.object.bus_name, path),
                                 dbus.PROPERTIES_IFACE)

    q.expect('dbus-signal', signal='MembersChanged', path=path)

    lp_members = props_iface.Get(
        'org.freedesktop.Telepathy.Channel.Interface.Group',
        'LocalPendingMembers')

    assert len(lp_members) == 1
    added, actor, reason, msg = lp_members[0]

    assert added == self_handle
    assert actor == handle
    assert reason == 4  #invited
    assert msg == 'Inviting to this room'

    # decline invitation
    channel.Close()
    q.expect('dbus-signal', signal='Closed')
Ejemplo n.º 9
0
 def handleConnectionLost(self, session, args):
     ses = domish.Element((None, 'session'))
     ses['session'] = session
     self.broadcast('connectionlost', ses)
Ejemplo n.º 10
0
 def onChallenge(self, challenge):
     challenge_str = str(challenge)
     response = self.mechanism.getResponse(base64.b64decode(challenge_str))
     packet = domish.Element((sasl.NS_XMPP_SASL, 'response'))
     packet.addContent(base64.b64encode(response))
     self.xmlstream.send(packet)
Ejemplo n.º 11
0
    def authenticated(self, xs):
        self.handler.authenticated()

        xs.addObserver("/iq[@type='get']/ping[@xmlns='%s']" %
                       xmlstream2.NS_XMPP_PING,
                       self.pong,
                       xs=xs)

        xs.addObserver('/message', self.handler.message)
        xs.addObserver('/presence', self.handler.presence)
        xs.addObserver('/iq', self.handler.iq)

        # TODO if logged_in (was: if self.xmlstream.authenticator.token):
        if 'presence' in self.config:
            pcfg = self.config['presence']
            p = domish.Element((None, 'presence'))
            if pcfg['type'] != 'available':
                p['type'] = pcfg['type']
            p.addElement((None, 'status'), content=pcfg['status'])
            p.addElement((None, 'priority'), content=pcfg['priority'])
            p.addElement((None, 'show'), content=pcfg['show'])
            xs.send(p)

        self.handler.ready()
        """
        ver = client.IQ(xs, 'get')
        ver.addElement((xmlstream2.NS_IQ_VERSION, 'query'))
        ver.send(self.network)

        info = client.IQ(xs, 'get')
        info.addElement((xmlstream2.NS_DISCO_INFO, 'query'))
        info.send(self.network)

        items = client.IQ(xs, 'get')
        q = items.addElement((xmlstream2.NS_DISCO_ITEMS, 'query'))
        q['node'] = xmlstream2.NS_PROTO_COMMANDS
        items.send(self.network)

        items = client.IQ(xs, 'get')
        q = items.addElement((xmlstream2.NS_DISCO_ITEMS, 'query'))
        q['node'] = xmlstream2.NS_MESSAGE_UPLOAD
        items.send(self.network)
        """
        def testProbe():
            if self.peer is not None:
                userid, resource = util.split_userid(self.peer)
                presence = xmppim.Presence(
                    jid.JID(tuple=(userid, self.network, resource)), 'probe')
                presence['id'] = util.rand_str(8)
                xs.send(presence)

        def testMassProbe():
            global count, num
            num = 400
            count = 0

            def _presence(stanza):
                global count, num
                count += 1
                if count >= 400:
                    print 'received all presence'

            xs.addObserver('/presence', _presence)

            for n in range(num):
                userid = util.rand_str(util.USERID_LENGTH,
                                       util.CHARSBOX_HEX_LOWERCASE)
                presence = xmppim.Presence(
                    jid.JID(tuple=(userid, self.network, None)), 'probe')
                xs.send(presence)

        def testRoster():
            global count, num
            num = 400
            count = 0

            def _presence(stanza):
                global count, num
                count += 1
                if count >= 400:
                    print 'received all presence'

            xs.addObserver('/presence', _presence)

            _jid = jid.JID(tuple=(None, self.network, None))
            r = domish.Element((None, 'iq'))
            r.addUniqueId()
            r['type'] = 'get'
            q = r.addElement((xmppim.NS_ROSTER, 'query'))
            for n in range(num):
                _jid.user = util.rand_str(util.USERID_LENGTH,
                                          util.CHARSBOX_HEX_LOWERCASE)
                item = q.addElement((None, 'item'))
                item['jid'] = _jid.userhost()
            xs.send(r)

            if self.peer is not None:
                _jid = util.userid_to_jid(self.peer, self.network)
                r = domish.Element((None, 'iq'))
                r['type'] = 'get'
                r['id'] = util.rand_str(8)
                q = r.addElement((xmppim.NS_ROSTER, 'query'))
                item = q.addElement((None, 'item'))
                item['jid'] = _jid.userhost()
                xs.send(r)

        def testSubscribe():
            # subscription request
            self.index = 0
            if self.peer is not None:
                userid, resource = util.split_userid(self.peer)
                presence = xmppim.Presence(
                    jid.JID(tuple=(userid, self.network, None)), 'subscribe')
                presence['id'] = util.rand_str(8)
                xs.send(presence)
            else:

                def pres():
                    self.index += 1
                    presence = xmppim.AvailablePresence(
                        statuses={
                            None: 'status message (%d)' % (self.index, )
                        })
                    xs.send(presence)

                LoopingCall(pres).start(2, False)

        def testMsgLoop():
            global counter
            counter = 0

            def _loop():
                global counter
                counter += 1
                jid = xs.authenticator.jid
                message = domish.Element((None, 'message'))
                message['id'] = 'kontalk' + util.rand_str(
                    8, util.CHARSBOX_AZN_LOWERCASE)
                message['type'] = 'chat'
                if self.peer:
                    message['to'] = util.userid_to_jid(self.peer,
                                                       self.network).full()
                else:
                    message['to'] = jid.userhost()
                message.addElement((None, 'body'), content=('%d' % counter))
                message.addElement(('urn:xmpp:server-receipts', 'request'))
                xs.send(message)

            LoopingCall(_loop).start(1)

        def testRegisterRequest():
            reg = client.IQ(xs, 'get')
            reg.addElement((xmlstream2.NS_IQ_REGISTER, 'query'))
            reg.send(self.network)

        def testRegister():
            reg = client.IQ(xs, 'set')
            query = reg.addElement((xmlstream2.NS_IQ_REGISTER, 'query'))
            form = query.addElement(('jabber:x:data', 'x'))
            form['type'] = 'submit'

            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'] = 'Phone number'
            phone['var'] = 'phone'
            phone.addElement((None, 'value'), content='+39123456')

            reg.send(self.network)

        def testValidate():
            reg = client.IQ(xs, 'set')
            query = reg.addElement((xmlstream2.NS_IQ_REGISTER, 'query'))
            form = query.addElement(('jabber:x:data', 'x'))
            form['type'] = 'submit'

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

            code = form.addElement((None, 'field'))
            code['type'] = 'text-single'
            code['label'] = 'Validation code'
            code['var'] = 'code'
            code.addElement((None, 'value'), content='686129')

            reg.send(self.network)

        def testCommand():
            cmd = client.IQ(xs, 'set')
            ch = cmd.addElement((xmlstream2.NS_PROTO_COMMANDS, 'command'))
            ch['node'] = 'serverlist'
            ch['action'] = 'execute'
            cmd.send(self.network)

        def testUpload():
            cmd = client.IQ(xs, 'set')
            ch = cmd.addElement((xmlstream2.NS_MESSAGE_UPLOAD, 'upload'))
            ch['node'] = 'kontalkbox'
            media = ch.addElement((None, 'media'))
            media['type'] = 'image/png'
            cmd.send(self.network)
Ejemplo n.º 12
0
    def authenticated(self, xs):
        log.msg('Authenticated.')

        presence = domish.Element((None, 'presence'))
        xs.send(presence)
Ejemplo n.º 13
0
    def onMessage(self, msg):
        # return is there is no body or body is empty
        if not hasattr(msg, "body"): return
        if msg.body == None: return

        # don't react on messages with type 'error'
        try:
            if msg["type"] == "error":
                return
        except exceptions.KeyError:
            pass

        client = database.getSMS77Client(jid.JID(msg["from"]))

        # if a error is happened, then send a error message
        reply = domish.Element((None, "message"))
        reply["to"] = msg["from"]
        reply["from"] = msg["to"]

        # only send if the sms-account is available
        if client != None:
            types = ['basicplus', 'standard', 'quality', 'festnetz', 'flash']
            number = jid.parse(msg["to"])[0]

            # return if there is no number
            if number == None: return
            if number == "": return

            if str(msg.subject) in types:
                ret = client.sendMessage(msg.body, number, str(msg.subject))
            else:
                ret = client.sendMessage(msg.body, number)

            # store the sms for status reports
            if ret[2] != None:
                try:
                    database.storeMessage(JID(msg["from"]), ret[2], number,
                                          msg.body)
                except exceptions.KeyError:
                    pass

            reply.addElement("subject", content="Nachricht an " + number)
            reply.addElement("body", content=ret[1])

            if ret[0] != "100":
                reply["type"] = 'error'
                self.send(reply)
            else:
                if database.isReportRequested(jid.JID(msg["from"])):
                    self.send(reply)
        else:
            reply["type"] = 'error'
            reply.addElement("subject",
                             content="Benutzerdaten nicht vorhanden")
            reply.addElement(
                "body",
                content=
                "Es konnten keine Benutzerdaten gefunden werden. Bitte registrieren Sie sich zuerst am Gateway!"
            )
            self.send(reply)

        # update the balance in the status
        self.updateBalance(JID(msg["from"]).userhost())
Ejemplo n.º 14
0
    def _onSetRegister(self, iq):
        fromjid = jid.internJID(iq["from"])
        data = iq.query

        username = None
        password = None
        phone = None
        msgtype = "message"
        report = False

        if data.x == None:
            """ use standard form if no xdata is returned """
            username = data.username
            password = data.password
            phone = data.phone
        else:
            """ xdata available, take it! """
            for field in data.x.elements():
                if field.name == "field":
                    if field.getAttribute("var") == "username":
                        username = str(field.value)
                    if field.getAttribute("var") == "smstype":
                        smstyp = str(field.value)
                    if field.getAttribute("var") == "password":
                        password = str(field.value)
                    if field.getAttribute("var") == "phone":
                        phone = str(field.value)
                    if field.getAttribute("var") == "msgtype":
                        msgtype = str(field.value)
                    if field.getAttribute("var") == "report":
                        report = str(field.value)

        # set password to None if there isn't one
        if password == "": password = None

        # remove or register?
        if data.remove == None:
            # register new account
            database.createUser(fromjid, username, phone, password)

            # set the default message type if set
            if smstyp != None:
                database.setDefaultMessageType(fromjid, smstyp)

            database.setMessageAsChat(fromjid, (msgtype == "chat"))
            database.setReportRequested(fromjid, (report == "yes"))

            # send own subscribe
            self.send(Presence(to=fromjid, type='subscribe'))

            # create welcome message
            httpkey = database.getHTTPGetKey(fromjid.userhost())
            welcomemsg = messages.getInfoMessage("welcome",
                                                 str(fromjid.userhost()),
                                                 httpkey)

            # send welcome message
            welcome = domish.Element((None, "message"))
            welcome["to"] = iq["from"]
            welcome.addElement("subject", content=welcomemsg[0])
            welcome.addElement("body", content=welcomemsg[1])
            self.send(welcome)
        else:
            # remove the account
            database.removeUser(fromjid)
Ejemplo n.º 15
0
    def subscribe_cloud(
            self, device, svc, var, callback_fct=None, callback_args=()):
        #         print('suscribe to %s' % var)
        name = device.keys()[0]
        dev = device[name]
        if not callback_fct:
            callback_fct = self.log.debug
        d = defer.Deferred()

        def subscribe_failed(err, name):
            self.parent.remove_device(name.split('_')[0])

        def subscribed(node_name, deferred, iq):
            if iq['type'] == 'result':
                self.subscriptions_cloud[str(node_name)] = True
#                 print('%s suscribed !' % str(node_name))
#                 iq = IQ(self.xmlstream, 'get')
#                 ps = domish.Element(
#                     ('http://jabber.org/protocol/pubsub', 'pubsub'))
#                 items = domish.Element((None, 'items'))
#                 items['node'] = node_name
#                 items['max_items'] = '1'
#                 ps.addChild(items)
#                 iq.addChild(ps)
#                 iq.addCallback(self.on_event)
#                 iq.send(to='pubsub.' + self.jid.host)
#                 print(iq.toXml())
                deferred.callback(str(node_name))
            else:
                deferred.errback(Exception('subscription to %s failed: %s'
                                           % (node_name, iq.toXml())))

        if svc in dev['services']:
            #             print('service %s ok' % svc)
            #             print('subscriptions :%s' % self.subscriptions_cloud)
            if not self.cloud_event_catcher:
                self.cloud_event_catcher = CloudEventCatcher(
                    {}, {}, logger=self.log)
            subscription_name = '/'.join((dev['location'], svc, var))
            #  subscription_service = svc
            if subscription_name in self.cloud_event_catcher.callbacks:
                self.cloud_event_catcher.callbacks[subscription_name].update(
                    {var: (callback_fct, callback_args,)})
            else:
                self.cloud_event_catcher.callbacks.update(
                    {subscription_name: {var: (callback_fct, callback_args,)}})
#             if var in self.cloud_event_catcher.callbacks:
#                 self.cloud_event_catcher.callbacks[var].update(
#                     {var: (callback_fct, callback_args,)})
#             else:
#                 self.cloud_event_catcher.callbacks.update(
#                     {var: {var: (callback_fct, callback_args,)}})
    #         log.error(self.event_catcher.catcher.childs)
            if subscription_name in self.subscriptions_cloud:
                if self.subscriptions_cloud[subscription_name]:
                    #                     print('already subscribed: %s' % subscription_name)
                    for k, value in\
                            self.cloud_event_catcher.unfiltered_dict.items():
                        #                         print('is %s == %s ?' % (k, var))
                        if k == var:
                            if value == 'False':
                                value = False
                            elif value == 'True':
                                value = True
                            if isinstance(callback_args, str)\
                                    or isinstance(callback_args, bool):
                                callback_fct(value, callback_args)
                            else:
                                callback_fct(value, *callback_args)
                            del self.cloud_event_catcher.unfiltered_dict[k]
                    return defer.succeed(None)
            self.subscriptions_cloud.update({str(subscription_name): False})
#             print(subscription_name)
#             print(subscription_service)
            iq = IQ(self.xmlstream, 'set')
            ps = domish.Element(
                ('http://jabber.org/protocol/pubsub', 'pubsub'))
            subscribe = domish.Element((None, 'subscribe'))
            subscribe['node'] = subscription_name
            subscribe['jid'] = self.jid.full()
            ps.addChild(subscribe)
            iq.addChild(ps)
            iq.addCallback(subscribed, subscription_name, d)
            iq.send(to='pubsub.' + self.jid.host)
            return d
        return defer.fail(Exception('Service unknow'))
Ejemplo n.º 16
0
 def handleLoginSucceeded(self, session, args):
     ses = domish.Element((None, 'credentials'))
     ses['session'] = session
     ses['username'] = args['username']
     ses['password'] = args['password']
     self.broadcast('loginsucceeded', ses)
Ejemplo n.º 17
0
 def reply(validity):
     reply = domish.Element((NS_DIALBACK, 'result'))
     reply['from'] = result['to']
     reply['to'] = result['from']
     reply['type'] = validity
     self.xmlstream.send(reply)
Ejemplo n.º 18
0
 def handleUnknownCommand(self, session, args):
     ses = domish.Element((None, 'command'))
     ses['session'] = session
     ses['command'] = 'unknown'
     ses.addContent(args['input'])
     self.broadcast('command', ses)
Ejemplo n.º 19
0
 def setUp(self):
     self.error = domish.Element((None, 'error'))
Ejemplo n.º 20
0
 def handleInput(self, session, args):
     ses = domish.Element((None, 'input'))
     ses['session'] = session
     ses['realm'] = args['realm']
     ses.addContent(args['input'])
     self.broadcast('input', ses)
Ejemplo n.º 21
0
 def test_addContentBytesNonASCII(self):
     """
     Non-ASCII byte strings passed to C{addContent} yield L{UnicodeError}.
     """
     element = domish.Element((u"testns", u"foo"))
     self.assertRaises(UnicodeError, element.addContent, b'\xe2\x98\x83')
Ejemplo n.º 22
0
 def handleClientVersion(self, session, args):
     ses = domish.Element((None, 'version'))
     ses['session'] = session
     ses['version'] = args['version']
     self.broadcast('clientversion', ses)
Ejemplo n.º 23
0
 def testNoNamespace(self):
     e = domish.Element((None, "foo"))
     self.assertEqual(e.toXml(), "<foo/>")
     self.assertEqual(e.toXml(closeElement = 0), "<foo>")
Ejemplo n.º 24
0
class XMPPListenAuthenticator(xmlstream.ListenAuthenticator):
    """
    Initializes an XmlStream accepted from an XMPP client as a Server.

    This authenticator performs the initialization steps needed to start
    exchanging XML stanzas with an XMPP cient as an XMPP server. It checks if
    the client advertises XML stream version 1.0, performs TLS encryption, SASL
    authentication, and binds a resource. Note: This does not establish a
    session. Sessions are part of XMPP-IM, not XMPP Core.

    Upon successful stream initialization, the L{xmlstream.STREAM_AUTHD_EVENT}
    event will be dispatched through the XML stream object. Otherwise, the
    L{xmlstream.INIT_FAILED_EVENT} event will be dispatched with a failure
    object.
    """

    namespace = 'jabber:client'

    def __init__(self, network):
        xmlstream.ListenAuthenticator.__init__(self)
        self.network = network

    def associateWithStream(self, xs):
        """
        Perform stream initialization procedures.

        An L{XmlStream} holds a list of initializer objects in its
        C{initializers} attribute. This method calls these initializers in
        order up to the first required initializer. This way, a client
        cannot use an initializer before passing all the previous initializers that
        are marked as required. When a required initializer is successful it is removed,
        and all preceding optional initializers are removed as well.

        It dispatches the C{STREAM_AUTHD_EVENT} event when the list has
        been successfully processed. The initializers themselves are responsible
        for sending an C{INIT_FAILED_EVENT} event on failure.
        """

        xmlstream.ListenAuthenticator.associateWithStream(self, xs)
        xs.addObserver(xmlstream2.INIT_SUCCESS_EVENT, self.onSuccess)

        xs.initializers = []
        inits = (
            (xmlstream2.TLSReceivingInitializer, True, False),
            (xmlstream2.SASLReceivingInitializer, True, True),
            (xmlstream2.RegistrationInitializer, True, True),
            # doesn't work yet -- (compression.CompressReceivingInitializer, False, False),
            (xmlstream2.BindInitializer, True, False),
            (xmlstream2.SessionInitializer, False, False),
        )
        for initClass, required, exclusive in inits:
            init = initClass(xs, self.canInitialize)
            init.required = required
            init.exclusive = exclusive
            xs.initializers.append(init)
            init.initialize()

    def streamStarted(self, rootElement):
        xmlstream.ListenAuthenticator.streamStarted(self, rootElement)

        self.xmlstream.sendHeader()

        try:
            if self.xmlstream.version < (1, 0):
                raise error.StreamError('unsupported-version')
            if self.xmlstream.thisEntity.host != self.network:
                raise error.StreamError('not-authorized')
        except error.StreamError, exc:
            self.xmlstream.sendHeader()
            self.xmlstream.sendStreamError(exc)
            return

        if self.xmlstream.version >= (1, 0):
            features = domish.Element((xmlstream.NS_STREAMS, 'features'))

            required = False
            for initializer in self.xmlstream.initializers:
                if required and (not hasattr(initializer, 'exclusive')
                                 or not initializer.exclusive):
                    log.debug("skipping %r" % (initializer, ))
                    continue

                feature = initializer.feature()
                if feature is not None:
                    features.addChild(feature)
                if hasattr(initializer, 'required') and initializer.required and \
                        hasattr(initializer, 'exclusive') and initializer.exclusive:
                    log.debug("required and exclusive: %r" % (initializer, ))
                    if not required:
                        required = True

            self.xmlstream.send(features)
Ejemplo n.º 25
0
 def testOtherNamespace(self):
     e = domish.Element(("testns", "foo"), "testns2")
     self.assertEqual(e.toXml({'testns': 'bar'}),
                       "<bar:foo xmlns:bar='testns' xmlns='testns2'/>")
Ejemplo n.º 26
0
 def setUp(self):
     self.error = domish.Element((None, "error"))
Ejemplo n.º 27
0
 def testChildOtherDefaultNamespace(self):
     e = domish.Element(("testns", "foo"))
     e.addElement(("testns2", "bar"), 'testns2')
     self.assertEqual(e.toXml(), "<foo xmlns='testns'><bar xmlns='testns2'/></foo>")
Ejemplo n.º 28
0
 def cloud_subscribe(self, jid, result):
     self.log.debug('Subscribe callback from %s' % jid)
     presence = domish.Element((None, 'presence'))
     presence['type'] = 'subscribe'
     presence['to'] = jid
     self.xmlstream.send(presence)
Ejemplo n.º 29
0
 def testOnlyChildDefaultNamespace2(self):
     e = domish.Element((None, "foo"))
     e.addElement("bar")
     self.assertEqual(e.toXml(), "<foo><bar/></foo>")
Ejemplo n.º 30
0
 def _onSetGateway(self, iq):
     reply = domish.Element((NS_GATEWAY, "query"))
     reply.addElement("prompt",
                      content=str(iq.query.prompt) + "@" +
                      configuration.getConfig().jabberComponentName)
     return reply