def _check_sadmin(self, room, user): juser = jid.internJID(user).userhost().lower() members = self.sadmins for m in members: if jid.internJID(m).userhost().lower() == juser: return True return False
def dispatch(self, xs, stanza): """ Send a stanza to the router, checking some stuff first. """ log.debug("stanza from %s: %s" % (xs.otherEntity.full(), stanza.toXml())) util.resetNamespace(stanza, xs.namespace) stanzaFrom = stanza.getAttribute('from') stanzaTo = stanza.getAttribute('to') if not stanzaFrom or not stanzaTo: xs.sendStreamError(error.StreamError('improper-addressing')) else: try: sender = jid.internJID(stanzaFrom) jid.internJID(stanzaTo) except jid.InvalidFormat: log.debug("dropping stanza with malformed JID") log.debug("sender = %s, otherEntity = %s" % (sender.full(), xs.otherEntity.full())) if sender.host != xs.otherEntity.host and sender.host != self.defaultDomain: xs.sendStreamError(error.StreamError('invalid-from')) else: # replace to with destination destination = stanza.getAttribute('destination') if destination: stanza['to'] = destination del stanza['destination'] self.router.send(stanza)
def valid(xs): reply('valid') if not self.xmlstream.thisEntity: self.xmlstream.thisEntity = jid.internJID(receivingServer) self.xmlstream.otherEntity = jid.internJID(originatingServer) self.xmlstream.dispatch(self.xmlstream, xmlstream.STREAM_AUTHD_EVENT)
def cb(subs): actual = [a.toElement().toXml() for a in subs] expected = [ ps.Subscription( nodeIdentifier='node1', subscriber=jid.internJID('*****@*****.**').userhostJID(), state='subscribed'), ps.Subscription( nodeIdentifier='node2', subscriber=jid.internJID('*****@*****.**').userhostJID(), state='subscribed'), ps.Subscription( nodeIdentifier='node5', subscriber=jid.internJID('*****@*****.**').userhostJID(), state='unconfigured'), ps.Subscription( nodeIdentifier='node6', subscriber=jid.internJID('*****@*****.**').userhostJID(), state='subscribed', subscriptionIdentifier='123-abc'), ps.Subscription( nodeIdentifier='node6', subscriber=jid.internJID('*****@*****.**').userhostJID(), state='subscribed', subscriptionIdentifier='004-yyy'), ] self.assertEquals(len(actual), 5) for ex in expected: self.assertIn(ex.toElement().toXml(), actual) sendMock.assert_called_once_with(xs)
def postOptions(self): if not self['jid']: raise usage.UsageError("Missing client JID") else: try: self['jid'] = jid.internJID(self['jid']) except jid.invalidFormat: raise usage.UsageError("Invalid client JID") if self['secret'] is None: raise usage.UsageError("Missing client secret") if not self['service']: raise usage.UsageError("Missing publish-subscribe service JID") else: try: self['service'] = jid.internJID(self['service']) except jid.invalidFormat: raise usage.UsageError("Invalid publish-subscribe service JID") try: self['twitter-oauth-consumer'] = OAuthConsumer( key=self['twitter-oauth-consumer-key'], secret=self['twitter-oauth-consumer-secret']) self['twitter-oauth-token'] = OAuthToken( key=self['twitter-oauth-token-key'], secret=self['twitter-oauth-token-secret']) except KeyError: self['twitter-oauth-consumer'] = None self['twitter-oauth-token'] = None if not self['twitter-user'] or not self['twitter-password']: raise usage.UsageError("Missing twitter credentials")
def cb(affs): expected = { jid.internJID('*****@*****.**').userhostJID(): 'owner', jid.internJID('*****@*****.**').userhostJID(): 'outcast', } self.assertEquals(expected, affs) sendMock.assert_called_once_with(xs)
def resetHistory(self, room=None, frm=None): if room != None: # room needs to be a returned room hash from the backend if self.checkAdmin(room, jid.internJID(frm).userhost()): self.parent._clean_up_history(True, room['name']) elif jid.internJID(frm).userhost() in self.sadmins: self.HISTORY = {}
def _onDiscoInfo(self, iq): """ Called for incoming disco info requests. @param iq: The request iq element. @type iq: L{Element<twisted.words.xish.domish.Element>} """ requestor = jid.internJID(iq["from"]) target = jid.internJID(iq["to"]) nodeIdentifier = iq.query.getAttribute("node", '') def toResponse(info): if nodeIdentifier and not info: raise error.StanzaError('item-not-found') else: response = DiscoInfo() response.nodeIdentifier = nodeIdentifier for item in info: response.append(item) return response.toElement() d = self.info(requestor, target, nodeIdentifier) d.addCallback(toResponse) return d
def incomingRegisterIq(self, incoming): # Check what type the Iq is.. itype = incoming.getAttribute("type") LogEvent(INFO) if itype == "get": if config.authRegister: # Check to see if they're registered source = internJID(incoming.getAttribute("from")).userhost() result = self.pytrans.xdb.getRegistration(source) if result: self.sendRegistrationFields(incoming) else: # Must first submit local credentials self.sendLocalRegistrationFields(incoming) else: # Send real registration form self.sendRegistrationFields(incoming) elif itype == "set": if config.authRegister: # Check to see if they're registered by local credentials source = internJID(incoming.getAttribute("from")).userhost() result = self.pytrans.xdb.getRegistration(source) username = "" password = "" if result: username, password = result if username == "local" and password == "local": # Update real credentials self.updateRegistration(incoming) else: # Must first validate local credentials self.validateLocalRegistration(incoming) else: # Update real credentials self.updateRegistration(incoming)
def _onDiscoInfo(self, iq): requestor = jid.internJID(iq["from"]) target = jid.internJID(iq["to"]) nodeIdentifier = iq.query.getAttribute("node", '') def toResponse(results): info = [] for i in results: info.extend(i[1]) if nodeIdentifier and not info: raise error.StanzaError('item-not-found') else: response = domish.Element((NS_INFO, 'query')) for item in info: response.addChild(item) return response dl = [] for handler in self.parent: if IDisco.providedBy(handler): dl.append(handler.getDiscoInfo(requestor, target, nodeIdentifier)) d = defer.DeferredList(dl, fireOnOneErrback=1, consumeErrors=1) d.addCallbacks(toResponse, self._error) return d
def dispatch(self, xs, stanza): """ Send a stanza to the router, checking some stuff first. """ log.debug("stanza from %s: %s" % (xs.otherEntity.full(), stanza.toXml())) util.resetNamespace(stanza, xs.namespace) stanzaFrom = stanza.getAttribute('from') stanzaTo = stanza.getAttribute('to') if not stanza.bind and not stanzaFrom or not stanzaTo: xs.sendStreamError(error.StreamError('improper-addressing')) else: try: sender = jid.internJID(stanzaFrom) jid.internJID(stanzaTo) except jid.InvalidFormat: log.debug("dropping stanza with malformed JID") log.debug("sender = %s, otherEntity = %s" % (sender.full(), xs.otherEntity.full())) try: unused, host = util.jid_component(sender.host) if host in self.keyring.hostlist(): self.router.send(stanza) else: raise Exception() except: xs.sendStreamError(error.StreamError('invalid-from'))
def incomingIq(self, el): itype = el.getAttribute("type") fro = el.getAttribute("from") froj = internJID(fro) to = el.getAttribute("to") toj = internJID(to) ID = el.getAttribute("id")
def test_identity(self): """ Test that two interned JIDs yield the same object. """ j1 = jid.internJID("user@host") j2 = jid.internJID("user@host") self.assertIdentical(j1, j2)
def createRoom(self, room, frm, nick, status = None, show = None, legacy = True, host=None): """ Create and join the room """ def created(rname): self.parent.HISTORY[room] = [] return self.joinRoom(room, frm, nick, status = status, show = show, legacy = legacy, host = host, do_check = False) def create_room(doCreate, error_code=NotAllowed): if not doCreate: raise error_code d = self.parent.storage.createRoom(room, jid.internJID(frm).userhost(), legacy=legacy, host=host) d.addCallback(created) return d if self.create_rooms == 1 or jid.internJID(frm).userhost() in self.sadmins: if self.plugins and self.plugins.has_key('create-room'): d = self.plugins['create-room'].create(room, jid.internJID(frm).userhost(), legacy=legacy, host=host) d.addCallback(create_room, error_code = NotMember) else: d = create_room(True) return d else: raise NotAllowed
def handle_action(self, action): self.log.debug('XMPP ACTION : {0!r}'.format(action)) if action.action_type != 'message': return body = str(action.meta.get('body')) if not body: return if not action.destination_rooms: return for room in action.destination_rooms: if action.scope == 'public': room_jid = jid.internJID(room) message = muc.GroupChat(recipient=room_jid, body=body) self.client.send(message.toElement()) if action.scope == 'private': if room is not None: msg = xmppim.Message(recipient=jid.internJID(room), sender=self.bot_jid, body=body) self.client.send(msg.toElement())
def set_kick(r, user): if self.checkAdmin(r, admin): kuser = None if self.checkOwner(r, user): raise NotAllowed user_check = jid.internJID(user).userhost().lower() for u in r['roster'].values(): if jid.internJID(u['jid']).userhost().lower() == user_check \ or u['nick'] == user: kuser = u['jid'] knick = u['nick'] if self.checkSelf(user, admin): raise NotAllowed if self.checkAdmin(r, user): raise NotAllowed r['roster'][u['jid'].lower()]['role'] = 'none' r['roster'][u['jid'].lower()]['affiliation'] = 'none' break if not kuser: raise RoomNotFound d = self.parent.storage.partRoom(room, kuser, knick, host=host) d.addCallback(ret_kick, room, r['roster']) d.addErrback(lambda x: self.error(NotAllowed, x)) return d else: raise NotAllowed
def _onDiscoItems(self, iq): requestor = jid.internJID(iq["from"]) target = jid.internJID(iq["to"]) nodeIdentifier = iq.query.getAttribute("node", '') def toResponse(results): items = [] for i in results: items.extend(i[1]) response = domish.Element((NS_ITEMS, 'query')) for item in items: response.addChild(item) return response dl = [] for handler in self.parent: if IDisco.providedBy(handler): dl.append(handler.getDiscoItems(requestor, target, nodeIdentifier)) d = defer.DeferredList(dl, fireOnOneErrback=1, consumeErrors=1) d.addCallbacks(toResponse, self._error) return d
def onActivateStream(self, iq): try: fromJID = jid.internJID(iq["from"]) # check the sender is authorized if self.allowed_domains and fromJID.host not in self.allowed_domains: raise UnauthorizedException activateJID = jid.internJID(unicode(iq.query.activate)).full() sid = hashSID( iq.query["sid"].encode("utf-8"), fromJID.full().encode("utf-8"), activateJID.encode("utf-8") ) log.msg("Activation requested for: ", sid) # Get list of objects for this sid olist = self.pendingConns[sid] # Remove sid from pending del self.pendingConns[sid] # Ensure there are the correct # of participants if len(olist) != 2: log.msg("Activation for %s failed: insufficient participants", sid) raise UnauthorizedException # Send iq result iq.swapAttributeValues("to", "from") iq["type"] = "result" iq.query.children = [] self.send(iq) # Remove sid from pending and mark as active assert sid not in self.activeConns self.activeConns[sid] = None # Complete connection log.msg("Activating ", sid) olist[0].peersock = olist[1] olist[1].peersock = olist[0] olist[0].transport.registerProducer(olist[1], 0) olist[1].transport.registerProducer(olist[0], 0) except UnauthorizedException, e: # Send an error iq.swapAttributeValues("to", "from") iq["type"] = "error" iq.query.children = [] e = iq.addElement("error") e["code"] = "405" e["type"] = "cancel" c = e.addElement("not-allowed") c["xmlns"] = "urn:ietf:params:xml:ns:xmpp-stanzas" self.send(iq) # Close all connected for c in olist: c.transport.loseConnection()
def createPurger(domain, service, node, username, password, debug=False): factory = client.DeferredClientFactory(jid.internJID(username), password) factory.streamManager.logTraffic = debug purger = Purger(jid.internJID(service), node) purger.setHandlerParent(factory.streamManager) yield client.clientCreator(factory)
def set_member(r, user): mjid = None if r == None: raise RoomNotFound if self.checkAdmin(r, admin): juser = jid.internJID(user) # TODO - clean this up roster = r['roster'] set_role = False for m in roster.values(): idx = m['jid'].lower() rjid = jid.internJID(m['jid']) if juser.resource: mjids = rjid.full().lower() else: mjids = rjid.userhost().lower() if mjids == user.lower() or m['nick'].lower() == user.lower(): if self.checkSelf(m['jid'], admin): raise NotAllowed # if self.checkAdmin(r, m['jid']): # raise NotAllowed mjid = m['jid'] if roster[idx]['role'] == 'none' or \ roster[idx]['role'] == 'visitor' or \ roster[idx]['role'] == 'player': roster[idx]['role'] = 'participant' set_role = True roster[idx]['affiliation'] = 'member' break dlist = [] if user: # This sets it in storage dm = self.parent.storage.setMember(room, user, host = host) dlist.append(dm) if mjid and set_role: # This sets it in the roster dr = self.parent.storage.setRole(room, mjid, 'participant', host=host) dlist.append(dr) d = defer.DeferredList(dlist) d.addErrback(lambda x: self.error(NotAllowed, x)) d.addCallback(lambda _: roster) return d else: raise NotAllowed
def sendPresence(pytrans, to, fro, show=None, status=None, priority=None, ptype=None, avatarHash=None, nickname=None, payload=[], url=None): if ptype in ["subscribe", "subscribed", "unsubscribe", "unsubscribed"]: to = internJID(to).userhost() fro = internJID(fro).userhost() el = Element((None, "presence")) el.attributes["to"] = to el.attributes["from"] = fro if ptype: el.attributes["type"] = ptype if show: s = el.addElement("show") s.addContent(utils.xmlify(show)) if status: s = el.addElement("status") s.addContent(utils.xmlify(status)) if priority: s = el.addElement("priority") s.addContent(priority) if url: s = el.addElement("x") s.attributes["xmlns"] = globals.XOOB s = el.addElement("url") s.addContent(url) if not ptype: if avatarHash and not config.disableAvatars and not config.disableVCardAvatars: x = el.addElement("x") x.attributes["xmlns"] = globals.VCARDUPDATE p = x.addElement("photo") p.addContent(avatarHash) if nickname: x = el.addElement("x") x.attributes["xmlns"] = globals.VCARDUPDATE n = x.addElement("nickname") n.addContent(nickname) if avatarHash and not config.disableAvatars and not config.disableIQAvatars: x = el.addElement("x") x.attributes["xmlns"] = globals.XAVATAR h = x.addElement("hash") h.addContent(avatarHash) if nickname and ptype == "subscribe": n = el.addElement("nick") n.attributes["xmlns"] = globals.NICK n.addContent(nickname) if payload: for p in payload: el.addChild(p) pytrans.send(el)
def onPresence(self, el): fro = el.getAttribute("from") to = el.getAttribute("to") # Ignore any presence broadcasts about other JD2 components if to == None: return try: froj = internJID(fro) toj = internJID(to) except Exception, e: LogEvent(WARN, msg="Failed stringprep") return
def createPublisher(domain, service, node, username, password, blog, author=None, debug=False): factory = client.DeferredClientFactory(jid.internJID(username), password) factory.streamManager.logTraffic = debug blogger = Blogger(jid.internJID(service), node) blogger.blog = blog if author is not None: blogger.author_name = author blogger.setHandlerParent(factory.streamManager) yield client.clientCreator(factory)
def incomingIq(self, el): """ Decides what to do with an IQ """ fro = el.getAttribute("from") to = el.getAttribute("to") ID = el.getAttribute("id") iqType = el.getAttribute("type") ulang = utils.getLang(el) try: # StringPrep froj = internJID(fro) to = internJID(to).full() except Exception, e: LogEvent(INFO, msg="Dropping IQ because of stringprep error")
def onMessage(self, el): """ Handles incoming message packets """ if not self.checkFrom(el): return LogEvent(INFO, self.jabberID) fro = el.getAttribute("from") to = el.getAttribute("to") try: froj = internJID(fro) toj = internJID(to) except Exception, e: LogEvent(WARN, self.jabberID) return
def getMember(self, members, mid, host=None): """ grab the member from the roster list. """ ret_m = members.get(mid) if not ret_m: ret_m = members.get(mid.lower()) if not ret_m: ret_m = members.get(jid.internJID(mid).userhost()) if not ret_m: ret_m = members.get(jid.internJID(mid).userhost().lower()) return ret_m
def createClient(bosh, domain, debug): if bosh: factory = BOSHClientFactory(jid.internJID(domain), None) else: factory = ClientFactory(jid.internJID(domain), None) factory.streamManager.logTraffic = debug protocol = MessageProtocol() protocol.setHandlerParent(factory.streamManager) if bosh: yield boshClientCreator(bosh, factory) else: yield client.clientCreator(factory)
def streamStarted(self, rootElement): """ Called by the XmlStream when the stream has started. This extends L{Authenticator.streamStarted} to extract further stream headers from L{rootElement}, optionally wait for stream features being received and then call C{initializeStream}. """ Authenticator.streamStarted(self, rootElement) self.xmlstream.sid = rootElement.getAttribute("id") if rootElement.hasAttribute("from"): self.xmlstream.otherEntity = jid.internJID(rootElement["from"]) # Setup observer for stream features, if applicable if self.xmlstream.version >= (1, 0): def onFeatures(element): features = {} for feature in element.elements(): features[(feature.uri, feature.name)] = feature self.xmlstream.features = features self.initializeStream() self.xmlstream.addOnetimeObserver('/features[@xmlns="%s"]' % NS_STREAMS, onFeatures) else: self.initializeStream()
def incomingIq(self, el): to = el.getAttribute("from") toj = internJID(to) ID = el.getAttribute("id") ulang = utils.getLang(el) sessionid = None email = None for command in el.elements(): sessionid = command.getAttribute("sessionid") if command.getAttribute("action") == "cancel": self.pytrans.adhoc.sendCancellation("emaillookup", el, sessionid) return for child in command.elements(): if child.name == "x" and child.getAttribute("type") == "submit": for field in child.elements(): if field.name == "field" and field.getAttribute("var") == "email": for value in field.elements(): if value.name == "value": email = value.__str__() if not self.pytrans.sessions.has_key(toj.userhost()) or not hasattr(self.pytrans.sessions[toj.userhost()].legacycon, "bos"): self.pytrans.adhoc.sendError("emaillookup", el, errormsg=lang.get("command_NoSession", ulang), sessionid=sessionid) elif email: self.lookupEmail(el, email, sessionid=sessionid) else: self.sendForm(el)
def doSpoolPrepCheck(): pre = os.path.abspath(config.spooldir) + X + config.jid + X print "Checking spool files and stringprepping any if necessary...", for file in os.listdir(pre): if os.path.isfile(pre + file) and file.find(".xml") != -1: file = utils.unmangle(file).decode("utf-8", "replace") try: filej = internJID(file).full() except InvalidFormat, UnicodeDecodeError: print "Unable to stringprep "+file+". Putting into BAD directory." file = utils.mangle(file) if not os.path.isdir(pre + "BAD"): os.makedirs(pre + "BAD") shutil.move(pre + file, pre + "BAD" + X + file) continue if file != filej: file = utils.mangle(file) filej = utils.mangle(filej) if os.path.exists(filej): print "Need to move "+file+" to "+filej+" but the latter exists!\nAborting!" sys.exit(1) else: shutil.move(pre + file, pre + filej)
def route(self, stanza): """ Route a stanza. (subclassed to avoid vebose logging) @param stanza: The stanza to be routed. @type stanza: L{domish.Element}. """ destination = internJID(stanza['to']) if destination.host in self.routes: self.routes[destination.host].send(stanza) else: self.routes[None].send(stanza)
def __init__(self, jidString, password, host=None, port=5222): XMPPClient.__init__(self, internJID(jidString), password, host=host, port=port) self.logTraffic = False self.messagebot = MessageBot() self.messagebot.setHandlerParent(self) self.rosterManager = RosterManager() self.rosterManager.setHandlerParent(self)
def send(self, stanza): """ Send stanza to the proper XML Stream. This uses addressing embedded in the stanza to find the correct stream to forward the stanza to. """ otherHost = jid.internJID(stanza["to"]).host thisHost = jid.internJID(stanza["from"]).host if (thisHost, otherHost) not in self._outgoingStreams: # There is no connection with the destination (yet). Cache the # outgoing stanza until the connection has been established. # XXX: If the connection cannot be established, the queue should # be emptied at some point. if (thisHost, otherHost) not in self._outgoingQueues: self._outgoingQueues[(thisHost, otherHost)] = [] self._outgoingQueues[(thisHost, otherHost)].append(stanza) self.initiateOutgoingStream(thisHost, otherHost) else: self._outgoingStreams[(thisHost, otherHost)].send(stanza)
def __init__(self, str_jid, password, farm_jid, farm_password=None): """ Establish connection with XMPP server, subscript to farm. """ self.RESOURCE = "villein-%x" % random.getrandbits( 16) # Generate random 'resource' URI. self.STR_JID = str_jid + self.RESOURCE # Called str_jid, because jid is taken. (twisted.protocols.jabber.jid) self.JID = jid.internJID(self.STR_JID) self.FARM_PASSWORD = farm_password self.XMLNS = "http://linkedprocess.org/protocol" self.PACKET = packet_manager() self.MACHINES = vm_manager()
def send(self, obj): if self.routewrap == 1 and type(obj) == Element: to = obj.getAttribute("to") route = Element((None, "route")) route.attributes["from"] = config.jid route.attributes["to"] = internJID(to).host route.addChild(obj) obj.attributes["xmlns"] = "jabber:client" component.Service.send(self, route.toXml()) else: if type(obj) == Element: obj = obj.toXml() component.Service.send(self, obj)
def parseElement(self, element): if element.hasAttribute('from'): self.sender = jid.internJID(element['from']) if element.hasAttribute('to'): self.recipient = jid.internJID(element['to']) self.stanzaType = element.getAttribute('type') self.stanzaID = element.getAttribute('id') # Save element stripNamespace(element) self.element = element # accumulate all childHandlers in the class hierarchy of Class handlers = {} reflect.accumulateClassDict(self.__class__, 'childParsers', handlers) for child in element.elements(): try: handler = handlers[child.uri, child.name] except KeyError: pass else: getattr(self, handler)(child)
def _onDiscoItems(self, iq): """ Called for incoming disco items requests. @param iq: The request iq element. @type iq: L{Element<twisted.words.xish.domish.Element>} """ requestor = jid.internJID(iq["from"]) target = jid.internJID(iq["to"]) nodeIdentifier = iq.query.getAttribute("node", '') def toResponse(items): response = DiscoItems() response.nodeIdentifier = nodeIdentifier for item in items: response.append(item) return response.toElement() d = self.items(requestor, target, nodeIdentifier) d.addCallback(toResponse) return d
def handle_action(self, action): #self.log.debug(': {0!r}'.format(action)) if action.action_type == 'message': body = action.meta.get('body') if body: if action.destination_rooms: for room in action.destination_rooms: if action.scope == 'public': # TODO: replace this with an actual room lookup of known rooms room_jid = jid.internJID(room) message = muc.GroupChat(recipient=room_jid, body=body) self.client.send(message.toElement())
def __init__(self, myjid, mysecret): application = service.Application("Xmpp XiVO CTI") xmppclient = XMPPClient(jid.internJID(myjid), mysecret) xmppclient.setServiceParent(application) xmppclient.startService() xmppclient.logTraffic = DEBUG self.factory = xmppProtocol() self.factory.setHandlerParent(xmppclient) self.pubsub_factory = ctiPubSubClient(CONFIG["xmpp"]["jid"]) self.pubsub_factory.setHandlerParent(xmppclient)
def _onSubject(self, msg): """A subject has been sent from a MUC room. """ if not msg.hasAttribute('from'): return room_jid = jid.internJID(msg['from']) # grab room room = self._getRoom(room_jid) if room is None: # not in the room yet return self.receivedSubject(room_jid, unicode(msg.subject))
def getBot(botjid, botpass, logTraffic): botjid = jid.internJID(botjid) xmppclient = client.XMPPClient(botjid, botpass) xmppclient.logTraffic = logTraffic presenceProt = BotPresenceProtocol() presenceProt.setHandlerParent(xmppclient) rosterProt = BotRosterProtocol() rosterProt.setHandlerParent(xmppclient) messageBot = BotMessageProtocol(botjid, presenceProt, rosterProt) messageBot.setHandlerParent(xmppclient) return xmppclient, messageBot
def dispatch(self, xs, stanza): """ Send a stanza to the router, checking some stuff first. """ if self.logTraffic: try: log.debug( "stanza from %s: %s" % (xs.otherEntity.full(), stanza.toXml().encode('utf-8'))) except UnicodeDecodeError: log.debug("stanza from %s: <%s/> (cannot encode)" % (xs.otherEntity.full(), stanza.name)) util.resetNamespace(stanza, xs.namespace) stanzaFrom = stanza.getAttribute('from') stanzaTo = stanza.getAttribute('to') if not stanza.bind and not stanzaFrom or not stanzaTo: xs.sendStreamError(error.StreamError('improper-addressing')) else: try: sender = jid.internJID(stanzaFrom) jid.internJID(stanzaTo) except jid.InvalidFormat: log.debug("dropping stanza with malformed JID") log.debug("sender = %s, otherEntity = %s" % (sender.full(), xs.otherEntity.full())) try: unused, host = util.jid_component(sender.host) if host in self.keyring.hostlist(): self.router.send(stanza) else: raise Exception() except: xs.sendStreamError(error.StreamError('invalid-from'))
def auth(self, elem): """Do not auth the user, anyone can log in""" username = elem.query.username.__str__() resource = elem.query.resource.__str__() user = jid.internJID(username+'@'+self.xmlstream.host+'/'+resource) resp = domish.Element(('iq', ns.NS_CLIENT)) resp['type'] = 'result' resp['id'] = elem['id'] self.xmlstream.send(resp) self.xmlstream.authenticated(user)
def dispatch(self, xs, stanza): """ Send a stanza to the router, checking some stuff first. """ util.resetNamespace(stanza, xs.namespace) stanzaFrom = stanza.getAttribute('from') stanzaTo = stanza.getAttribute('to') if not stanzaFrom or not stanzaTo: xs.sendStreamError(error.StreamError('improper-addressing')) else: try: sender = jid.internJID(stanzaFrom) jid.internJID(stanzaTo) except jid.InvalidFormat: log.debug("Dropping error stanza with malformed JID") log.debug("sender = %s, otherEntity = %s" % (sender.full(), xs.otherEntity.full())) if sender.host != xs.otherEntity.host and sender.host != self.defaultDomain: xs.sendStreamError(error.StreamError('invalid-from')) else: self.router.send(stanza)
def _leftRoom(self, d, prs): """We have presence that says we joined a room. """ room_jid = jid.internJID(prs['from']) # check for errors if prs.hasAttribute('type') and prs['type'] == 'error': d.errback(self._getExceptionFromElement(prs)) else: # change the state of the room r = self._getRoom(room_jid) if r is None: raise NotFound self._removeRoom(room_jid) d.callback(True)
def getRegInfo(self, jabberID): LogEvent(INFO) result = self.pytrans.xdb.request( internJID(jabberID).userhost(), legacy.namespace) if (result == None): LogEvent(INFO, "", "Not registered!") return None username, password = legacy.getAttributes(result) if (username and password and len(username) > 0 and len(password) > 0): LogEvent(INFO, "", "Returning reg info.") return (username, password) else: LogEvent(WARN, "", "Registration data corrupted!") return None
def login(self, username, password): self.d = defer.Deferred() self.myJid = internJID(username) if self.myJid.resource is None: self.myJid.resource = 'XMPPCred' self.jfactory = client.basicClientFactory(self.myJid, password) # TODO - clean this up self.jfactory.addBootstrap("//event/stream/authd", self.authd) self.jfactory.addBootstrap("//event/client/basicauth/invaliduser", self.authe) self.jfactory.addBootstrap("//event/client/basicauth/authfailed", self.authe) self.jfactory.addBootstrap("//event/stream/error", self.authe) reactor.connectTCP(self.server, self.port, self.jfactory) return self.d
def run(self, application, jidstr, password, muc, channels, anon=True): self.xmppclient = XMPPClient(jid.internJID(jidstr), password) if self.cfg.has_option('database_xmpp', 'debug') and \ self.cfg.get('database_xmpp', 'debug') in ('1', 'true', 'yes'): self.xmppclient.logTraffic = True # DEBUG HERE (user, host, resource) = jid.parse(jidstr) self.muc = XMPPLoggerProtocol( muc, channels.keys(), user + '-' + resource) self.muc.setHandlerParent(self.xmppclient) self.xmppclient.setServiceParent(application) self.signals = {} for channel in channels: for signal in channels[channel]: self.signals[signal] = channel self.anonymous = True self.xmppclient.startService()
def send(self, stanza): """ Send stanza to the proper XML Stream. This uses addressing embedded in the stanza to find the correct stream to forward the stanza to. """ otherHost = jid.internJID(stanza['to']).host log.debug("sending data to %s [%r]" % ( otherHost, self._outgoingStreams, )) for host in self._outgoingStreams.iterkeys(): if util.hostjid_server(otherHost, host): self._outgoingStreams[host].send(stanza)
def streamStarted(self, rootElement): """ Called by the XmlStream when the stream has started. This extends L{Authenticator.streamStarted} to extract further information from the stream headers from L{rootElement}. """ Authenticator.streamStarted(self, rootElement) self.xmlstream.namespace = rootElement.defaultUri if rootElement.hasAttribute("to"): self.xmlstream.thisEntity = jid.internJID(rootElement["to"]) self.xmlstream.prefixes = {} for prefix, uri in rootElement.localPrefixes.iteritems(): self.xmlstream.prefixes[uri] = prefix
def validateLocalRegistration(self, incoming): # Grab the username and password LogEvent(INFO) source = internJID(incoming.getAttribute("from")).userhost() ulang = utils.getLang(incoming) username = None password = None for queryFind in incoming.elements(): if queryFind.name == "query": for child in queryFind.elements(): try: if child.name == "username": username = child.__str__().lower() elif child.name == "password": password = child.__str__() except AttributeError, TypeError: continue # Ignore any errors, we'll check everything below
def _onXPresence(self, prs): """ A muc presence has been received. """ if not prs.hasAttribute('from'): return room_jid = jid.internJID(prs.getAttribute('from', '')) status = getattr(prs, 'status', None) show = getattr(prs, 'show', None) # grab room room = self._getRoom(room_jid) if room is None: # not in the room yet return user = self._changeUserStatus(room, room_jid, status, show) if room.inRoster(user): # we changed status or nick muc_status = getattr(prs.x, 'status', None) if muc_status: code = muc_status.getAttribute('code', 0) else: self.userUpdatedStatus(room, user, show, status) else: resource = None #grab user's resource for element in prs.children: if type(element) == type(prs): if element.name == "x": for sub in element.children: if type(sub) == type(prs): if sub.name == "item": resource = sub.getAttribute('jid', '') if resource is None: resource = "unknown/unknown" user.unique_resource = resource user.resource = resource.split('/')[0] room.addUser(user) self.userJoinedRoom(room, user)
def doDiscoRequest(self): def userDiscoInfoReceived(el): if not self.alive: return LogEvent(INFO, self.jabberID) fro = el.getAttribute("from") for e in el.elements(): if e.name == "query" and e.uri == globals.DISCO_INFO: for item in e.elements(): if item.name == "feature": var = item.getAttribute("var") self.capabilities.append(var) LogEvent( INFO, self.jabberID, "Capabilities of %r:\n\t%s" % (fro, "\n\t".join(self.capabilities))) def serverDiscoInfoReceived(el): if not self.alive: return LogEvent(INFO, self.jabberID) fro = el.getAttribute("from") for e in el.elements(): if e.name == "query" and e.uri == globals.DISCO_INFO: for item in e.elements(): if item.name == "feature": var = item.getAttribute("var") self.capabilities.append(var) LogEvent( INFO, self.jabberID, "Capabilities of %r:\n\t%s" % (fro, "\n\t".join(self.capabilities))) def errback(args=None): LogEvent(INFO, self.jabberID, "Error fetching disco info") LogEvent(INFO, self.jabberID, "Fetching disco info from %r" % self.jabberID) d = self.sendDiscoRequest(to=self.jabberID, fro=config.jid) d.addCallback(userDiscoInfoReceived) d.addErrback(errback) sjid = internJID(self.jabberID).host LogEvent(INFO, self.jabberID, "Fetching disco info from %r" % sjid) d = self.sendDiscoRequest(to=sjid, fro=config.jid) d.addCallback(serverDiscoInfoReceived) d.addErrback(errback)
def streamStarted(self, rootElement): """ Called by the XmlStream when the stream has started. This extends L{Authenticator.streamStarted} to extract further information from the stream headers from C{rootElement}. """ Authenticator.streamStarted(self, rootElement) self.xmlstream.namespace = rootElement.defaultUri if rootElement.hasAttribute("to"): self.xmlstream.thisEntity = jid.internJID(rootElement["to"]) self.xmlstream.prefixes = {} for prefix, uri in iteritems(rootElement.localPrefixes): self.xmlstream.prefixes[uri] = prefix self.xmlstream.sid = hexlify(randbytes.secureRandom(8)).decode('ascii')
def _parse_affiliations(self, verbElement): self.affiliations = {} for element in verbElement.elements(): if (element.uri == NS_PUBSUB_OWNER and element.name == 'affiliation'): try: entity = jid.internJID(element['jid']).userhostJID() except KeyError: raise BadRequest(text='Missing jid attribute') if entity in self.affiliations: raise BadRequest( text='Multiple affiliations for an entity') try: affiliation = element['affiliation'] except KeyError: raise BadRequest(text='Missing affiliation attribute') self.affiliations[entity] = affiliation
def __init__(self, rooms, nick, backend): super(MucBot, self).__init__() self.log = logging.getLogger('{0}.{1}'.format( self.__class__.__module__, self.__class__.__name__)) self.backend = backend self.raw_rooms = rooms or [] self.room_jids = [] self.nick = nick for room in self.raw_rooms: password = None if type(room) is tuple: if len(room) > 1: room, password = room else: room = room[0] self.room_jids.append((jid.internJID(room), password))
def getMyVCard(self, el): to = el.getAttribute("from") fro = el.getAttribute("from") froj = internJID(fro) ID = el.getAttribute("id") ulang = utils.getLang(el) if not self.pytrans.sessions.has_key(froj.userhost()): self.pytrans.iq.sendIqError(to=fro, fro=config.jid, ID=ID, xmlns="vcard-temp", etype="auth", condition="not-authorized") return s = self.pytrans.sessions[froj.userhost()] if not s.ready: self.pytrans.iq.sendIqError(to=fro, fro=config.jid, ID=ID, xmlns="vcard-temp", etype="auth", condition="not-authorized") return s.doVCardUpdate() iq = Element((None, "iq")) iq.attributes["to"] = to iq.attributes["from"] = config.jid if ID: iq.attributes["id"] = ID iq.attributes["type"] = "result" command = iq.addElement("command") command.attributes["sessionid"] = self.pytrans.makeMessageID() command.attributes["xmlns"] = globals.COMMANDS command.attributes["status"] = "completed" x = command.addElement("x") x.attributes["xmlns"] = globals.XDATA x.attributes["type"] = "result" title = x.addElement("title") title.addContent(lang.get("command_UpdateMyVCard", ulang)) field = x.addElement("field") field.attributes["type"] = "fixed" field.addElement("value").addContent(lang.get("command_Done", ulang)) self.pytrans.send(iq)
def configure(self, *args, **kwargs): # user args self.nick = kwargs.get('nick') # TODO: remove, make this just the bot name... self.room_nick = kwargs.get('room_nick') if self.room_nick is None: self.room_nick = self.nick self.log_traffic = kwargs.get('log_traffic', False) #TODO: remove localhost default, fail. self.server = kwargs.get('server', 'localhost') self.port = kwargs.get('port', XMPP_DEFAULT_PORT) self.use_ssl = kwargs.get('use_ssl', True) self.keepalive_freq = kwargs.get('keepalive_freq') # defaults to None if type(self.keepalive_freq) not in (None, float): try: self.keepalive_freq = float(self.keepalive_freq) except Exception as e: self.log.error( 'invalid keepalive passed in, {0!r}: {1!r}'.format( self.keepalive_freq, e)) self.keepalive_freq = None #TODO: have this default to botname @ . self.jabber_id = kwargs.get('jabber_id', self.nick + '@' + self.server) #self.room_jabber_id = # do we need this for servers that act wonky? maybe. self.password = kwargs.get('password') self.rooms = kwargs.get('rooms') # allow users to define custom handlers? not now. #self.subprotocol_handlers = kwargs.get() # internal self.bot_jid = jid.internJID(self.jabber_id) # probably want to override client? self.client = XMPPClient(self.bot_jid, self.password, host=self.server) if self.log_traffic is True: self.client.logTraffic = True
def _joinedRoom(self, d, prs): """We have presence that says we joined a room. """ room_jid = jid.internJID(prs['from']) # check for errors if prs.hasAttribute('type') and prs['type'] == 'error': d.errback(self._getExceptionFromElement(prs)) else: # change the state of the room r = self._getRoom(room_jid) if r is None: raise NotFound r.state = 'joined' # grab status status = getattr(prs.x, 'status', None) if status: r.status = status.getAttribute('code', None) d.callback(r)
def emailLookupResults(self, results, el, sessionid): LogEvent(INFO) to = el.getAttribute("from") toj = internJID(to) ID = el.getAttribute("id") ulang = utils.getLang(el) iq = Element((None, "iq")) iq.attributes["to"] = to iq.attributes["from"] = config.jid if ID: iq.attributes["id"] = ID iq.attributes["type"] = "result" command = iq.addElement("command") if sessionid: command.attributes["sessionid"] = sessionid else: command.attributes["sessionid"] = self.pytrans.makeMessageID() command.attributes["node"] = "emaillookup" command.attributes["xmlns"] = globals.COMMANDS command.attributes["status"] = "completed" note = command.addElement("note") note.attributes["type"] = "info" note.addContent(lang.get("command_EmailLookup_Results", ulang)) x = command.addElement("x") x.attributes["xmlns"] = "jabber:x:data" x.attributes["type"] = "form" title = x.addElement("title") title.addContent(lang.get("command_EmailLookup", ulang)) for r in results: email = x.addElement("field") email.attributes["type"] = "fixed" email.addElement("value").addContent(r) self.pytrans.send(iq)