def __init__(self, local_domains=("localhost")): self.local_domains = local_domains self.loop = ioloop.IOLoop() self.ctx = zmq.Context() log.debug('Registering StanzaProcessor at forwarder..') # connect push socket to forwarder self.forwarder = self.ctx.socket(zmq.PUSH) self.forwarder.connect(config.get('ipc', 'forwarder')) pull_socket = self.ctx.socket(zmq.PULL) stream = zmqstream.ZMQStream(pull_socket, self.loop) stream.on_recv(self.handle_stanza, False) port = pull_socket.bind_to_random_port('tcp://127.0.0.1') # register connection at forwarder reg_msg = ZMQForwarder_message('REGISTER') reg_msg.attributes = (config.get('ipc', 'password'), 'tcp://127.0.0.1:' + str(port), local_domains) self.forwarder.send_pyobj(reg_msg) # init the handlers self.stanza_handlers = { 'iq': iq.Iq(), 'message': message.Message(), 'presence': presence.Presence() }
def __init__(self): self.zmq_context = zmq.Context() # connect to forwarder/router log.debug('Connecting StanzaPublisher to forwarder..') self.router = self.zmq_context.socket(zmq.PUSH) self.router.connect(config.get('ipc', 'forwarder'))
def handle_forwarder_message(self, msg): """Handles incoming command requests from peer""" if msg.command == 'REGISTER': (password, push_url, jids) = msg.attributes log.info('peer is trying to register') if password != config.get('ipc', 'password'): log.info('Authorization failed') return log.info('registering new peer at ' + push_url) peer = self.ctx.socket(zmq.PUSH) peer.connect(push_url) if isinstance(jids, JID): jids = [jids, ] for jid in jids: log.info('adding routing entry for ' + unicode(jid)) jid = JID(jid) try: # append to bare jids list of existing connections self.peers[jid.bare].append((jid, peer)) except KeyError: # create new entry self.peers[jid.bare] = [(jid, peer), ] elif msg.command == 'UNREGISTER': push_url = msg.attributes log.info('unregistering peer at ' + push_url) for bare_jid in self.peers.keys(): for peer in self.peers[bare_jid]: if peer[1] == push_url: self.peers.remove(peer) if len(self.peers) == 0: del self.peers[bare_jid] else: raise InternalServerError()
def start_client_listener(): publisher = get_publisher() validation_registry = get_validation_registry() validator = DummyTrueValidator() validation_registry.register('dummy', validator) io_loop = ioloop.IOLoop.instance() server = XMPPServer(io_loop) server.bind(config.get('listeners', 'clientport'), config.get('listeners', 'ip')) server.start() try: io_loop.start() except (KeyboardInterrupt, SystemExit): io_loop.stop() print "exited cleanly"
def __init__(self, name): classname = name.replace('.', '_').lower() if classname.startswith("pyfire_"): classname = classname[7:] try: level = config.get('logging', classname).upper() except config.NoOptionError: level = '' if not level: level = config.get('logging', 'global_level').upper() if level not in frozenset(['CRITICAL', 'ERROR', 'WARNING', 'INFO', 'DEBUG', 'NOTSET']): warnings.warn("No such loglevel %s" % level, RuntimeWarning) level = 'ERROR' super(Logger, self).__init__(classname, getattr(logbook, level)) self.handlers.append(logbook.more.ColorizedStderrHandler()) self._disabled = False
def set_resource(self, tree): """Set a resource on our JID""" bind_element = tree[0] if tree.get("type") != "set" or \ bind_element.tag != 'bind' or\ bind_element.get("xmlns") != BIND_NS: raise NotAuthorizedError resource_element = bind_element.find("resource") if resource_element is None: # No prefered resource was set, generate one self.jid.resource = uuid.uuid4().hex else: self.jid.resource = resource_element.text if not self.jid.validate(): raise BadRequestError # Check if given resource is already in use known_jids = get_known_jids() try: known_jids.append(self.jid) except ValueError: raise ConflictError log.info("Bound connection as %s" % str(self.jid)) # Connect to forwarder to receive stanzas sent back to client log.debug('Registering Client at forwarder..') self.pull_socket = zmq.Context().socket(zmq.PULL) self.processed_stream = ZMQStream(self.pull_socket, self.connection.stream.io_loop) self.processed_stream.on_recv(self.masked_send_list, False) port = self.pull_socket.bind_to_random_port('tcp://127.0.0.1') self.pull_url = 'tcp://127.0.0.1:' + str(port) reg_msg = ZMQForwarder_message('REGISTER') reg_msg.attributes = (config.get('ipc', 'password'), self.pull_url, self.jid) self.publisher.send_pyobj(reg_msg) # Send registered resource back to client response_element = ET.Element("iq") response_element.set("type", "result") response_element.set("id", tree.get("id")) bind_element = ET.SubElement(response_element, "bind") bind_element.set("xmlns", BIND_NS) jid_element = ET.SubElement(bind_element, "jid") jid_element.text = str(self.jid) self.send_element(response_element)
def fire_up(): import pyfire.storage import pyfire.contact pyfire.storage.Base.metadata.create_all(pyfire.storage.engine) # create a forwader/router for internal communication fwd = zmq_forwarder.ZMQForwarder(config.get('ipc', 'forwarder')) thread.start_new_thread(fwd.start, ()) # create a stamza processor for local domains stanza_proc = stanza_processor.StanzaProcessor(config.getlist('listeners', 'domains')) thread.start_new_thread(stanza_proc.start, ()) # start listener for incomming Connections start_client_listener()
def handle_forwarder_message(self, msg): """Handles incoming command requests from peer""" if msg.command == 'REGISTER': (password, push_url, jids) = msg.attributes log.info('peer is trying to register') if password != config.get('ipc', 'password'): log.info('Authorization failed') return log.info('registering new peer at ' + push_url) peer = self.ctx.socket(zmq.PUSH) peer.connect(push_url) if isinstance(jids, JID): jids = [ jids, ] for jid in jids: log.info('adding routing entry for ' + unicode(jid)) jid = JID(jid) try: # append to bare jids list of existing connections self.peers[jid.bare].append((jid, peer)) except KeyError: # create new entry self.peers[jid.bare] = [ (jid, peer), ] elif msg.command == 'UNREGISTER': push_url = msg.attributes log.info('unregistering peer at ' + push_url) for bare_jid in self.peers.keys(): for peer in self.peers[bare_jid]: if peer[1] == push_url: self.peers.remove(peer) if len(self.peers) == 0: del self.peers[bare_jid] else: raise InternalServerError()
:license: BSD, see LICENSE for more details. """ __all__ = ['engine', 'Base', 'Session'] from sqlalchemy import create_engine from sqlalchemy.orm import scoped_session, sessionmaker from sqlalchemy.ext.declarative import declarative_base import pyfire.configuration as config from pyfire.jid import JID from pyfire.logger import Logger log = Logger(__name__) engine = create_engine(config.get('database', 'dburi')) Base = declarative_base(bind=engine) Session = scoped_session(sessionmaker()) from sqlalchemy.types import TypeDecorator, VARCHAR class JIDString(TypeDecorator): """Represents a full JID encoded as unicode string. Usage:: JIDString """