def start_event_handler(self, event):
     self._log("Start event overlay_id {0}".format(self.overlay_id))
     try:
         # Get the friends list for the user
         self.get_roster()
         # Send sign-on presence
         # hold on sending "ident" presence, just send a regular blank presence.
         # self.send_presence(pstatus="ident#" + self.node_id)
         self.send_presence()
         # Notification of peer signon
         self.add_event_handler("presence_available",
                                self.presence_event_handler)
         # Register IPOP message with the server
         register_stanza_plugin(Message, IpopSignal)
         self.registerHandler(
             Callback("ipop", StanzaPath("message/ipop"),
                      self.message_listener))
         register_stanza_plugin(Message, remoteSignal)
         self.registerHandler(
             Callback("remote", StanzaPath("message/remote"),
                      self.remote_listener))
     except Exception as err:
         self._log("XmppTransport:Exception:{0} Event:{1}".format(
             err, event),
                   severity="LOG_ERROR")
Example #2
0
 def plugin_init(self):
     self.rooms = {}
     self.ourNicks = {}
     self.xep = '0045'
     # load MUC support in presence stanzas
     register_stanza_plugin(Presence, MUCPresence)
     self.xmpp.registerHandler(
         Callback(
             'MUCPresence',
             MatchXMLMask("<presence xmlns='%s' />" % self.xmpp.default_ns),
             self.handle_groupchat_presence))
     self.xmpp.registerHandler(
         Callback(
             'MUCMessage',
             MatchXMLMask(
                 "<message xmlns='%s' type='groupchat'><body/></message>" %
                 self.xmpp.default_ns), self.handle_groupchat_message))
     self.xmpp.registerHandler(
         Callback(
             'MUCSubject',
             MatchXMLMask(
                 "<message xmlns='%s' type='groupchat'><subject/></message>"
                 % self.xmpp.default_ns), self.handle_groupchat_subject))
     self.xmpp.registerHandler(
         Callback(
             'MUCInvite',
             MatchXPath(
                 "{%s}message/{http://jabber.org/protocol/muc#user}x/invite"
                 % self.xmpp.default_ns), self.handle_groupchat_invite))
Example #3
0
    def _bind(self):
        """ Registers needed handlers.
        """

        self.add_event_handler('session_start', self._on_session_start)
        self.add_event_handler('failed_auth', self._on_failed_auth)
        self.add_event_handler('socks_connected', self._on_socks_connected)

        self.register_handler(
            Callback('First Git Init Handler',
                     StanzaPath('iq@type=set/git-init'),
                     self._on_git_init_stanza))

        self.register_handler(
            Callback('RsyncStart Handler', StanzaPath('iq@type=set/rsync'),
                     self._on_rsync_stanza))

        self.register_handler(
            Callback('MergeVerification Handler',
                     StanzaPath('iq@type=set/merge'), self._on_merge_stanza))

        eventbus.register('rsync-finished-success', self._on_rsync_success)
        eventbus.register('rsync-finished-failure', self._on_rsync_failure)
        eventbus.register('git-init-success', self._on_git_init_success)
        eventbus.register('git-init-failure', self._on_git_init_failure)
Example #4
0
    def __init__(self, xmpp, thoonk, default_config={}, features=[]):
        self.xmpp = xmpp
        self.thoonk = thoonk
        self.default_config = default_config
        self.redis = thoonk.redis

        self.features = self.process_features(features)

        self.thoonk.register_handler('publish_notice', self.thoonk_publish)
        self.thoonk.register_handler('retract_notice', self.thoonk_retract)
        self.thoonk.register_handler('create_notice', self.thoonk_create)
        self.thoonk.register_handler('delete_notice', self.thoonk_delete)

        #self.xmpp.registerHandler(Callback('pubsub create', StanzaPath("iq@type=set/pubsub/create"), self.handleCreateNode))
        #self.xmpp.registerHandler(Callback('pubsub configure', StanzaPath("iq@type=set/pubsub_owner/configure"), self.handleConfigureNode))
        #self.xmpp.registerHandler(Callback('pubsub delete', StanzaPath('iq@type=set/pubsub_owner/delete'), self.handleDeleteNode))
        self.xmpp.registerHandler(
            Callback('pubsub publish',
                     StanzaPath("iq@type=set/pubsub/publish"),
                     self.handlePublish))
        #self.xmpp.registerHandler(Callback('pubsub getitems', StanzaPath('iq@type=get/pubsub/items'), self.handleGetItems))
        #self.xmpp.registerHandler(Callback('pubsub delete item', StanzaPath('iq@type=set/pubsub/retract'), self.handleRetractItem))
        #self.xmpp.registerHandler(Callback('pubsub get configure', StanzaPath('iq@type=get/pubsub_owner/configure'), self.handleGetNodeConfig))
        #self.xmpp.registerHandler(Callback('pubsub defaultconfig', StanzaPath('iq@type=get/pubsub_owner/default'), self.handleGetDefaultConfig))
        self.xmpp.registerHandler(
            Callback('pubsub subscribe',
                     StanzaPath('iq@type=set/pubsub/subscribe'),
                     self.handleSubscribe))
        self.xmpp.registerHandler(
            Callback('pubsub unsubscribe',
                     StanzaPath('iq@type=set/pubsub/unsubscribe'),
                     self.handleUnsubscribe))

        self.xmpp.registerHandler(
            Callback('pubsub getsubs',
                     StanzaPath('iq@type=get/pubsub/subscriptions'),
                     self.handleGetSubscriptions))

        #TODO: registerHandler for handleSetAffilation, handleGetAffilation, handleGetSubscriptions

        self.xmpp.add_event_handler("got_offline", self.handleGotOffline)

        keys = self.redis.keys('xmpp.sub_expires.presence.{*}')
        for key in keys:
            subs = self.redis.smembers(key)
            for sub in subs:
                node, subid = sub.split('\x00')
                logging.info("Cleaning up stale subscription %s %s" %
                             (node, subid))
                self.unsubscribe(node, subid)
Example #5
0
    def __init__(self, jid, secret, server, port):
        ComponentXMPP.__init__(self, jid, secret, server, port)
        self.backend = SimpleBackend()
        # You don't need a session_start handler, but that is
        # where you would broadcast initial presence.

        # The message event is triggered whenever a message
        # stanza is received. Be aware that that includes
        # MUC messages and error messages.

        self.add_event_handler("session_start", self.start)
        # self.add_event_handler("message", self.message)
        self.add_event_handler("changed_subscription",
                               self.handleXMPPPresenceSubscription)
        self.add_event_handler("got_presence_probe",
                               self.handleXMPPPresenceProbe)
        for event in [
                "message", "got_online", "got_offline", "changed_status"
        ]:
            self.add_event_handler(event, self.handleIncomingXMPPEvent)
        #
        self.backend.addMessageHandler(self.handleMessageAddedToBackend)

        xpath = "{%s}iq/{cnry:sleep:1}sleep" % self.default_ns

        self.registerHandler(
            Callback('Sleep command handler', MatchXPath(xpath),
                     self.handle_sleep))
Example #6
0
 def start(self, event):
     try:
         for xmpp_detail in list(self.ipop_xmpp_details.values()):
             # Check whether Callback functions are configured for XMPP server messages
             if xmpp_detail["callbackinit"] is False:
                 xmpp_detail["callbackinit"] = True
                 xmpp_detail["XMPPObj"].get_roster(
                 )  # Obtains the friends list for the user
                 xmpp_detail["XMPPObj"].send_presence(
                 )  # Sends presence message when the XMPP user is online
                 # Event to capture all online peer nodes as seen by the XMPP server
                 xmpp_detail["XMPPObj"].add_event_handler(
                     "presence_available", self.handle_presence)
                 # Event to capture all offline peer nodes as seen by the XMPP server
                 xmpp_detail["XMPPObj"].add_event_handler(
                     "presence_unavailable", self.offline_xmpp_peers)
                 # Register IPOP message with the server
                 register_stanza_plugin(Message, IpopMsg)
                 xmpp_detail["XMPPObj"].registerHandler(
                     Callback('Ipop', StanzaPath('message/Ipop'),
                              self.xmppmessagelistener))
     except Exception as err:
         self.log("Exception in XMPPClient:{0} Event:{1}".format(
             err, event),
                  severity="error")
Example #7
0
    def __init__(self, user, pwd, server, controller=None, device_name=None):
        self.server_name = server
        self.controller = controller
        self.device_name = device_name
        self.pending_queries = {}
        self.xmpp_id = user
        self.xmpp_host = server
        self.xmpp_port = 5222
        self.timer = None
        sleekxmpp.ClientXMPP.__init__(self, user, pwd)
        register_stanza_plugin(Message, remoteSignal)
        self.register_handler(
            Callback('remote', StanzaPath('message/remote'), self.MSGListener))
        self.add_event_handler("session_start", self.start)
        self.xmpp_handler()

        # resource_file, is a dict that keeps track of my local resources.
        self.resources = {}
        # presently only defined for initiator
        self._task = None
        # short term fix, gateways need to remember who initiated the task, for emulation we only do one task at a time
        # so this short hack
        self.task_initiator = None
        self.broadcast_queue = queue.Queue()
        # contract variables for this social domain.
        self.Networking_Delegation = None
        self.blockChainEvents = []
        self.blockChainFlag = True
        self.blockChainListener = BlockChainListener("BlockChainListener",
                                                     self.blockChainFlag,
                                                     self.blockChainEvents)
        self.blockChainListener.start()
Example #8
0
 def __init__(self, user, pwd, server, controller=None, device_name=None):
     self.server_name = server
     self.controller = controller
     self.device_name = device_name
     self.pending_queries = {}
     self.xmpp_host = server
     self.xmpp_port = 5222
     sleekxmpp.ClientXMPP.__init__(self, user, pwd)
     register_stanza_plugin(Message, DNS_Msg)
     register_stanza_plugin(Message, remoteSignal)
     register_stanza_plugin(Message, IpopSignal)
     self.register_handler(
         Callback('DNS', StanzaPath('message/DNS'), self.MSGListener))
     self.register_handler(
         Callback('n_setup', StanzaPath('message/n_setup'),
                  self.MSGListener))
     self.add_event_handler("session_start", self.start)
     self.xmpp_handler()
Example #9
0
 def plugin_init(self):
     register_stanza_plugin(Message, ENCRYPT_IM)
     self.xmpp.register_handler(
         Callback(
             'MUCStealthMessage',
             MatchXMLMask(
                 "<message xmlns='%s' type='groupchat'><encrypted xmlns='%s'/></message>"
                 % (self.xmpp.default_ns, ENCRYPT_IM.namespace)),
             self.xmpp['xep_0045'].handle_groupchat_message))
Example #10
0
    def register_activity_callback(self, activity_callback):
        """Register a callback that is executed on activity changes."""
        def hub_event(xml):
            match = re.search('activityId=(-?\d+)', xml.get_payload()[0].text)
            activity_id = match.group(1)
            if activity_id is not None:
                activity_callback(int(activity_id))

        self.registerHandler(Callback('Activity Finished', MatchHarmonyEvent('startActivityFinished'), hub_event))
Example #11
0
 def on_register(self):
     self.shuttingDown = False
     thread.start_new(self.loop, ())
     self.bot.registerHandler(
         Callback(
             "groupchat_error",
             MatchXMLMask(
                 "<message xmlns='jabber:client' type='error'><error type='modify' code='406' ><not-acceptable xmlns='urn:ietf:params:xml:ns:xmpp-stanzas'/></error></message>"
             ), self.handle_message_error))
Example #12
0
    def __init__(self, jid, password, callback, basename=None, ssl=False):

        self.plugin_config = {}

        self.jid = jid
        self.password = password
        self.callback = callback

        if basename is None:
            self.basename = self.jid
        else:
            self.basename = basename

        self._priority = 100
        self.botActive = False

        sleekxmpp.ClientXMPP.__init__(self, self.jid, self.password, ssl,
                                      self.plugin_config, {})

        self.registerPlugin('xep_0092', {
            'name': 'XMPP Daemon',
            'version': __version__
        })
        self.registerPlugin('xep_0004')
        self.registerPlugin('xep_0030')
        self.registerPlugin('xep_0060', {})
        self.registerPlugin('xep_0045', {})

        self.site_values = []
        self.auto_authorize = True
        self.auto_subscribe = True

        self.pubsub = self.plugin['xep_0060']
        self.muc = self.plugin['xep_0045']

        # [(room, nick, password)]
        self.roomlist = []

        self.lasterror = ''

        self.add_event_handler("session_start", self.on_start, threaded=True)
        self.add_event_handler("message", self.on_message, threaded=True)
        self.add_event_handler("groupchat_message", self.on_muc, threaded=True)

        self.add_handler("<iq type='error' />", self.handleError)

        self.registerHandler(
            Callback(
                "payload",
                MatchXPath(
                    "{jabber:client}message/{http://jabber.org/protocol/pubsub#event}event"
                ),
                self.on_payload,
                thread=True))

        self.rootnode = 'pubsub.%s' % self.getjidbare(jid).split('@')[1]
Example #13
0
    def plugin_init(self):
        self.xep = 'docker'

        self.xmpp.registerHandler(
            Callback(
                'Docker',
                MatchXPath('{%s}iq/{jabber:iq:docker}query' %
                           self.xmpp.default_ns), self._handle_name_of_pods))

        register_stanza_plugin(Iq, Docker)
Example #14
0
 def __init__(self, pubsub):
     self.pubsub = pubsub
     self.pubsub.registerNodeClass(JobNode)
     self.xmpp = pubsub.xmpp
     self.xmpp.registerHandler(
         Callback(
             'job setstate',
             MatchXMLMask(
                 "<iq xmlns='%s' type='set'><pubsubjob xmlns='http://andyet.net/protocol/pubsubjob' /></iq>"
                 % self.xmpp.default_ns), self.handleJobState))
Example #15
0
 def plugin_init(self):
     self.description = "upload files via http"
     self.xep = "0999"
     self.xmpp['xep_0030'].add_feature("eu:siacs:conversations:http:upload")
     self.xmpp.register_handler(
         Callback(
             'Upload request',
             MatchXPath(
                 '{%s}iq/{eu:siacs:conversations:http:upload}request' %
                 self.xmpp.default_ns), self._handleUpload))
     register_stanza_plugin(Iq, UploadRequest)
     register_stanza_plugin(Iq, UploadSlot)
def register_automation_callback(harmony_client, home_control_callback):
    """Register a callback with an existing pyharmony client that is executed on home control events."""
    def hub_automation_state_event(xml):
        payload = xml.get_payload()[0].text
        logger.debug("Harmony State Event: %s" % payload)
        home_control_callback("automation.state", payload)

    def hub_automation_button_event(xml):
        payload = xml.get_payload()[0].text
        assert (payload[:5] == "type="
                and (payload[5:] == "short" or payload[5:] == "long"))
        logger.debug("Harmony Button Event: %s button press" % payload[5:])
        home_control_callback("control.button", payload[5:])

    harmony_client.registerHandler(
        Callback('Home Control State', MatchHarmonyAutomationStateEvent(''),
                 hub_automation_state_event))
    harmony_client.registerHandler(
        Callback('Home Control Button',
                 MatchHarmonyControlButtonPressEvent(''),
                 hub_automation_button_event))
Example #17
0
 def __init__(self,CFxHandle,paramDict,ModuleName):
     ControllerModule.__init__(self,CFxHandle,paramDict,ModuleName)
     self.xmpp_peers = defaultdict(int)
     # need to maintain uid<->jid mapping to route xmpp messages.
     self.uid_jid = {}
     self.jid_uid = defaultdict(lambda:['',False])
     self.xmpp_username = self.CMConfig.get("username")
     self.xmpp_passwd = self.CMConfig.get("password")
     self.xmpp_host = self.CMConfig.get("xmpp_host")
     self.uid = ""
     # time of last recvd xmpp advt.
     self.last_sent_advt = 0
     # keeps track of if xmpp advt recvd in interval
     self.xmpp_advt_recvd = True
     # Initial ADVT Delay
     self.INITIAL_ADVT_DELAY =5
     # interval between sending advertisements
     self.advt_delay = self.INITIAL_ADVT_DELAY
     # Maximum delay between advertisements is 10 minutes
     self.MAX_ADVT_DELAY = 600 
     # initialize the base Xmpp client class
     sleekxmpp.ClientXMPP.__init__(self,self.xmpp_username,self.xmpp_passwd,sasl_mech='PLAIN')
     self['feature_mechanisms'].unencrypted_plain = True
     # register a new plugin stanza and handler for it,
     # whenever a matching message will be received on 
     # the xmpp stream , registered handler will be called.
     register_stanza_plugin(Message, Ipop_Msg)
     self.registerHandler(
             Callback('Ipop',
             StanzaPath('message/Ipop'),
             self.MsgListener))
     # Register event handler for session start 
     self.add_event_handler("session_start",self.start)
     # calculate UID, for the meantime
     # address mapping
     self.uid_ip4_table = {}
     self.ip4_uid_table = {}
     # populate uid_ip4_table and ip4_uid_table with all UID and IPv4
     # mappings within the /16 subnet
     parts = self.CMConfig["ip4"].split(".")
     ip_prefix = parts[0] + "." + parts[1] + "."
     for i in range(0, 255):
         for j in range(0, 255):
             ip4 = ip_prefix + str(i) + "." + str(j)
             uid = fxlib.gen_uid(ip4)
             self.uid_ip4_table[uid] = ip4
             self.ip4_uid_table[ip4] = uid
     self.uid = self.ip4_uid_table[self.CMConfig["ip4"]]
     # Start xmpp handling thread
     self.xmpp_handler()
Example #18
0
 def plugin_init(self):
     self.description = "upload files via http"
     self.xep = "0999"
     self.xmpp['xep_0030'].add_feature("urn:xmpp:http:upload")
     self.xmpp['xep_0030'].add_identity(category='store',
                                        itype='file',
                                        name='HTTP File Upload')
     self.xmpp.register_handler(
         Callback(
             'Upload request',
             MatchXPath('{%s}iq/{urn:xmpp:http:upload}request' %
                        self.xmpp.default_ns), self._handleUpload))
     register_stanza_plugin(Iq, UploadRequest)
     register_stanza_plugin(Iq, UploadSlot)
Example #19
0
    def plugin_init(self):
        self.xep = '0009'
        self.description = 'Jabber-RPC'
        #self.stanza = sleekxmpp.plugins.xep_0009.stanza

        register_stanza_plugin(Iq, RPCQuery)
        register_stanza_plugin(RPCQuery, MethodCall)
        register_stanza_plugin(RPCQuery, MethodResponse)

        self.xmpp.registerHandler(
            Callback(
                'RPC Call',
                MatchXPath('{%s}iq/{%s}query/{%s}methodCall' %
                           (self.xmpp.default_ns, RPCQuery.namespace,
                            RPCQuery.namespace)), self._handle_method_call))
        self.xmpp.registerHandler(
            Callback(
                'RPC Call',
                MatchXPath('{%s}iq/{%s}query/{%s}methodResponse' %
                           (self.xmpp.default_ns, RPCQuery.namespace,
                            RPCQuery.namespace)),
                self._handle_method_response))
        self.xmpp.registerHandler(
            Callback(
                'RPC Call',
                MatchXPath('{%s}iq/{%s}error' %
                           (self.xmpp.default_ns, self.xmpp.default_ns)),
                self._handle_error))
        self.xmpp.add_event_handler('jabber_rpc_method_call',
                                    self._on_jabber_rpc_method_call)
        self.xmpp.add_event_handler('jabber_rpc_method_response',
                                    self._on_jabber_rpc_method_response)
        self.xmpp.add_event_handler('jabber_rpc_method_fault',
                                    self._on_jabber_rpc_method_fault)
        self.xmpp.add_event_handler('jabber_rpc_error',
                                    self._on_jabber_rpc_error)
        self.xmpp.add_event_handler('error', self._handle_error)
Example #20
0
 def __init__(self, social_info):
     print("initializing xmpp agent")
     self.user_id = social_info["username"]
     self.social_password = social_info["password"]
     self.xmpp_host = social_info["server"]
     self.controller = social_info["gateway"]
     self.device_names = social_info["devices"]
     self.pending_queries = {}
     self.xmpp_port = 5222
     sleekxmpp.ClientXMPP.__init__(self, self.user_id, self.social_password)
     register_stanza_plugin(Message, DNS_Msg)
     self.register_handler(
         Callback('DNS', StanzaPath('message/DNS'), self.MSGListener))
     self.add_event_handler("session_start", self.start)
     self.xmpp_handler()
Example #21
0
    def _start(self, _):
        self._xmpp.get_roster()
        self._xmpp.send_presence()

        try:
            xmpp = self._xmpp.plugin['xep_0045'].xmpp
            xmpp.registerHandler(
                Callback(
                    'MUCError',
                    MatchXPath("{%s}presence[@type='error']" %
                               xmpp.default_ns), self._error))
        except Exception as exception:
            print(exception)
            traceback.print_exc()
            raise

        self.join_mucs()
    def __init__(self, jid, password, room, nick, OI_URL):
        sleekxmpp.ClientXMPP.__init__(self, jid, password)
        #sleekxmpp.ssl_version = ssl.PROTOCOL_SSLv3

        self.jid
        self.room = room
        self.nick = "OPPSD.SEIT.OIMONITOR-{}/v1.0(http://n.a;[email protected])".format(nick)
        self.url = OI_URL
        
        register_stanza_plugin(Message, Stanza)
        self.registerHandler(Callback('NWWS-OI/X Message', StanzaPath('{%s}message/{%s}x' % (self.default_ns,self.default_ns)),self.onX))

        
        # The session_start event will be triggered when
        # the bot establishes its connection with the server
        # and the XML streams are ready for use. We want to
        # listen for this event so that we we can initialize
        # our roster.
        self.add_event_handler("session_start", self.start, threaded=True)

        # The groupchat_message event is triggered whenever a message
        # stanza is received from any chat room. If you also also
        # register a handler for the 'message' event, MUC messages
        # will be processed by both handlers.
        #self.add_event_handler("groupchat_message", self.muc_message)
        self.add_event_handler("custom_action", self.muc_message)
        
        self.add_event_handler("presence_available", self.muc_online)
        
        self.add_event_handler("presence_unavailable", self.muc_offline)
        self.add_event_handler("presence_unsubscribed", self.muc_offline)
        
        self.add_event_handler("roster_update", self.muc_roster_update)
        
        self.add_event_handler("connected", self.muc_connected)
        self.add_event_handler("disconnected", self.muc_disconnected)
        
        self.add_event_handler("Ping", self.ping_xmpp)
        
        self.member_list = []
        self.member_list_prev = []
        self.member_list_complete = False
        self.product_count = 0
Example #23
0
    def plugin_init(self):
        self.xep = "0012"

        self.xmpp.registerHandler(
            Callback(
                'Last Activity',
                MatchXPath('{%s}iq/{%s}query' %
                           (self.xmpp.default_ns, LastActivity.namespace)),
                self.handle_last_activity_query))
        register_stanza_plugin(Iq, LastActivity)

        self.xmpp.add_event_handler('last_activity_request',
                                    self.handle_last_activity)

        if self.xmpp.is_component:
            # We are a component, so we track the uptime
            self.xmpp.add_event_handler("session_start", self._reset_uptime)
            self._start_datetime = datetime.now()
        self.xmpp.plugin['xep_0030'].add_feature('jabber:iq:last')
Example #24
0
 def start_event_handler(self, event):
     """Registers custom event handlers at the start of XMPP session"""
     self._sig.sig_log("XMPP Signalling started for overlay: {0}".format(self._overlay_id))
     # pylint: disable=broad-except
     try:
         # Notification of peer signon
         self.add_event_handler("presence_available",
                                self.presence_event_handler)
         # Register IPOP message with the server
         register_stanza_plugin(Message, IpopSignal)
         self.registerHandler(
             Callback("ipop", StanzaPath("message/ipop"), self.message_listener))
         # Get the friends list for the user
         self.get_roster()
         # Send sign-on presence
         self.send_presence(pstatus="ident#" + self._node_id)
     except Exception as err:
         self._sig.sig_log("XmppTransport: Exception:{0} Event:{1}"
                           .format(err, event), "LOG_ERROR")
Example #25
0
 def __init__(self, user, password, host, nick, room_passwd=None):
     sleekxmpp.ClientXMPP.__init__(self, user, password)
     #Initially the values are undefined, will either be provided
     #by admin via XMPP message or existing cached values will be
     #used
     self.room = None
     self.ip4 = None
     self.uid = None
     self.nick = nick
     #dict for keeping track of JID's and their
     #connection status. ie. req_send
     #,resp_recvd etc
     self.xmpp_peers = {}
     #dict for keeping track of peer's xmpp_overlay status
     self.peer_xmpp_status = {}
     #uid-jid mapping,key = uid, val = jid
     self.uid_jid = {}
     #register new plugin stanza and the handler
     #for , whenever a matching
     #msg will be rcvd on xmpp stream
     #MsgListener method will be triggered.
     register_stanza_plugin(Message, Ipop_Msg)
     self.registerHandler(
         Callback('Ipop', StanzaPath('message/Ipop'), self.MsgListener))
     #Register event handler for session
     #initialization/called after session
     #with xmpp server established.
     self.add_event_handler("session_start", self.start)
     #Register handlers for groupchat messages and MuC invitations,
     #any invitation will be accepted automatically
     self.add_event_handler("groupchat_message", self.muc_message)
     self.add_event_handler("groupchat_invite", self.accept_invite)
     #Initialize other parameters
     self.user = user
     self.password = password
     self.room_passwd = room_passwd
     self.host = host
     self.uid_ip_table = {}
Example #26
0
 def __init__(self, CFxHandle, paramDict, ModuleName):
     ControllerModule.__init__(self, CFxHandle, paramDict, ModuleName)
     self.xmpp_peers = defaultdict(int)
     # need to maintain uid<->jid mapping to route xmpp messages.
     self.uid_jid = {}
     self.xmpp_username = self.CMConfig.get("username")
     self.xmpp_passwd = self.CMConfig.get("password")
     self.xmpp_host = self.CMConfig.get("xmpp_host")
     self.uid = ""
     # initialize the base Xmpp client class
     sleekxmpp.ClientXMPP.__init__(self, self.xmpp_username,
                                   self.xmpp_passwd)
     # register a new plugin stanza and handler for it,
     # whenever a matching message will be received on
     # the xmpp stream , registered handler will be called.
     register_stanza_plugin(Message, Ipop_Msg)
     self.registerHandler(
         Callback('Ipop', StanzaPath('message/Ipop'), self.MsgListener))
     # Register event handler for session start
     self.add_event_handler("session_start", self.start)
     # calculate UID, for the meantime
     # address mapping
     self.uid_ip4_table = {}
     self.ip4_uid_table = {}
     # populate uid_ip4_table and ip4_uid_table with all UID and IPv4
     # mappings within the /16 subnet
     parts = self.CMConfig["ip4"].split(".")
     ip_prefix = parts[0] + "." + parts[1] + "."
     for i in range(0, 255):
         for j in range(0, 255):
             ip4 = ip_prefix + str(i) + "." + str(j)
             uid = fxlib.gen_uid(ip4)
             self.uid_ip4_table[uid] = ip4
             self.ip4_uid_table[ip4] = uid
     self.uid = self.ip4_uid_table[self.CMConfig["ip4"]]
     # Start xmpp handling thread
     self.xmpp_handler()
Example #27
0
    def __init__(self):
        # Create client with FCM server login info
        super(Client, self).__init__(FCM_JID,
                                     FCM_SERVER_KEY,
                                     sasl_mech='PLAIN')

        # Create pending command queue
        self.cmd_q = []

        # Create handler for received messages
        self.registerHandler(
            Callback(
                'FCM Message Receive',
                MatchXPath('{%s}message/{%s}gcm' %
                           (self.default_ns, 'google:mobile:data')),
                self.recv_message))

        # Connect to server and begin processing XML stream
        self.auto_reconnect = False
        self.connect((_get_fcm_server_ip(), FCM_SERVER_PORT),
                     use_tls=True,
                     use_ssl=True,
                     reattempt=False)
        self.process(threaded=True)
Example #28
0
 def _on_register(self):
     """ Register stanza and corresponding handler."""
     callback = Callback("groupchat_error", MatchXMLMask(MASK),
                         self.handle_message_error)
     self.bot.registerHandler(callback)
     threading.Thread(target=self.loop).start()
Example #29
0
    def __init__(self, xmpp, dbfile, settings, rest, overridedefault=None):

        self.admin = None
        self.admin_loggedin = False

        self.camp_init = False

        self.xmpp = xmpp
        self.dbfile = dbfile
        self.db = None
        self.nodeplugins = []

        self.config = {'settings': settings, 'rest': rest}
        if overridedefault is None:
            self.config['defaultnodeconfig'] = {}
        else:
            self.config['defaultnodeconfig'] = overridedefault
        self.default_config = self.getDefaultConfig()

        self.admins = []
        self.node_classes = {
            'leaf': BaseNode,
            'collection': CollectionNode,
            'queue': QueueNode,
            'job': JobNode2
        }
        self.nodes = NodeCache(self)
        self.adhoc = PubsubAdhoc(self)
        if self.config['rest']['enabled']:
            self.http = HTTPD(self)

        self.presence_expire = {}

        #self.xmpp.registerHandler(Callback('pubsub publish', MatchXMLMask("<iq xmlns='%s' type='set'><pubsub xmlns='http://jabber.org/protocol/pubsub'><publish xmlns='http://jabber.org/protocol/pubsub' /></pubsub></iq>" % self.xmpp.default_ns), self.handlePublish))
        self.xmpp.registerHandler(
            Callback('pubsub state', StanzaPath('iq@type=set/psstate'),
                     self.handleSetState))
        self.xmpp.registerHandler(
            Callback('pubsub publish',
                     StanzaPath("iq@type=set/pubsub/publish"),
                     self.handlePublish))
        self.xmpp.registerHandler(
            Callback('pubsub create', StanzaPath("iq@type=set/pubsub/create"),
                     self.handleCreateNode))
        self.xmpp.registerHandler(
            Callback('pubsub configure',
                     StanzaPath("iq@type=set/pubsub_owner/configure"),
                     self.handleConfigureNode))
        self.xmpp.registerHandler(
            Callback('pubsub delete',
                     StanzaPath('iq@type=set/pubsub_owner/delete'),
                     self.handleDeleteNode))
        self.xmpp.registerHandler(
            Callback('pubsub getitems', StanzaPath('iq@type=get/pubsub/items'),
                     self.handleGetItems))
        self.xmpp.registerHandler(
            Callback('pubsub delete item',
                     StanzaPath('iq@type=set/pubsub/retract'),
                     self.handleRetractItem))

        #self.xmpp.registerHandler(Callback('pubsub configure', MatchXMLMask("<iq xmlns='%s' type='set'><pubsub xmlns='http://jabber.org/protocol/pubsub#owner'><configure xmlns='http://jabber.org/protocol/pubsub#owner' /></pubsub></iq>" % self.xmpp.default_ns), self.handleConfigureNode))
        self.xmpp.registerHandler(
            Callback(
                'pubsub get configure',
                MatchXMLMask(
                    "<iq xmlns='%s' type='get'><pubsub xmlns='http://jabber.org/protocol/pubsub#owner'><configure xmlns='http://jabber.org/protocol/pubsub#owner' /></pubsub></iq>"
                    % self.xmpp.default_ns), self.handleGetNodeConfig))
        self.xmpp.registerHandler(
            Callback(
                'pubsub defaultconfig',
                MatchXMLMask(
                    "<iq xmlns='%s' type='get'><pubsub xmlns='http://jabber.org/protocol/pubsub#owner'><default xmlns='http://jabber.org/protocol/pubsub#owner' /></pubsub></iq>"
                    % self.xmpp.default_ns), self.handleGetDefaultConfig))
        self.xmpp.registerHandler(
            Callback(
                'pubsub subscribe',
                MatchXMLMask(
                    "<iq xmlns='%s' type='set'><pubsub xmlns='http://jabber.org/protocol/pubsub'><subscribe xmlns='http://jabber.org/protocol/pubsub' /></pubsub></iq>"
                    % self.xmpp.default_ns), self.handleSubscribe))
        self.xmpp.registerHandler(
            Callback(
                'pubsub unsubscribe',
                MatchXMLMask(
                    "<iq xmlns='%s' type='set'><pubsub xmlns='http://jabber.org/protocol/pubsub'><unsubscribe xmlns='http://jabber.org/protocol/pubsub' /></pubsub></iq>"
                    % self.xmpp.default_ns), self.handleUnsubscribe))
        self.xmpp.add_event_handler("session_start", self.start)
        self.xmpp.add_event_handler("changed_subscription",
                                    self.handleXMPPPresenceSubscription)
        self.xmpp.add_event_handler("got_online", self.handleGotOnline)
        self.xmpp.add_event_handler("got_offline", self.handleGotOffline)
        self.xmpp.add_event_handler("message", self.handleIncomingMessage)
        self.xmpp.add_event_handler("got_presence_probe",
                                    self.handleXMPPPresenceProbe)
Example #30
0
    def __init__(self, CFxHandle, paramDict, ModuleName):
        ControllerModule.__init__(self, CFxHandle, paramDict, ModuleName)
        # keeps track of last recvd advertisement and if node is active on XMPP.
        self.xmpp_peers = defaultdict(lambda: [0, False])
        # need to maintain uid<->jid mapping to route xmpp messages.
        self.uid_jid = {}
        # FullJID,Knows my UID,num(Correct advts recvd)
        self.jid_uid = defaultdict(lambda: ['', False, 1])
        self.xmpp_username = self.CMConfig.get("Username")
        self.xmpp_passwd = self.CMConfig.get("Password", "None")
        self.xmpp_host = self.CMConfig.get("AddressHost")
        self.xmpp_port = self.CMConfig.get("Port")
        self.vpn_type = self.CFxHandle.queryParam("CFx", "Model")
        self.interface_name = self.CMConfig.get("TapName")
        self.uid = ""
        self.update_peerlist = False
        # time of last recvd xmpp advt.
        self.last_sent_advt = 0
        # keeps track of if xmpp advt recvd in interval
        self.xmpp_advt_recvd = True
        # Initial ADVT Delay
        self.INITIAL_ADVT_DELAY = 5
        # interval between sending advertisements
        self.advt_delay = self.INITIAL_ADVT_DELAY
        # Maximum delay between advertisements is 10 minutes
        self.MAX_ADVT_DELAY = 600
        # initialize the base Xmpp client class, handle login/authentication.
        if self.CMConfig.get("AuthenticationMethod") == "x509" and \
                (self.xmpp_username != None \
                         or self.xmpp_passwd != None):
            raise RuntimeError(
                "x509 Authentication Error: Username/Password in IPOP configuration file."
            )

        use_tls = True
        if self.CMConfig.get("AuthenticationMethod") == "x509":
            sleekxmpp.ClientXMPP.__init__(self,
                                          self.xmpp_host,
                                          self.xmpp_passwd,
                                          sasl_mech='EXTERNAL')
            self.ssl_version = ssl.PROTOCOL_TLSv1
            self.ca_certs = self.CMConfig.get("TrustStore")
            self.certfile = self.CMConfig.get(
                "CertDirectory") + self.CMConfig.get("CertFile")
            self.keyfile = self.CMConfig.get(
                "CertDirectory") + self.CMConfig.get("Keyfile")
        else:
            sleekxmpp.ClientXMPP.__init__(self,
                                          self.xmpp_username,
                                          self.xmpp_passwd,
                                          sasl_mech='PLAIN')
            if self.CMConfig.get("AcceptUntrustedServer") == True:
                self['feature_mechanisms'].unencrypted_plain = True
                use_tls = False
            else:
                self.ca_certs = self.CMConfig.get("TrustStore")

        # register a new plugin stanza and handler for it,
        # whenever a matching message will be received on
        # the xmpp stream , registered handler will be called.
        register_stanza_plugin(Message, Ipop_Msg)
        self.registerHandler(
            Callback('Ipop', StanzaPath('message/Ipop'), self.MsgListener))

        # Register event handler for session start
        self.add_event_handler("session_start", self.start)

        self.add_event_handler("roster_update", self.deletepeerjid)

        # populate uid_ip4_table and ip4_uid_table with all UID and IPv4
        # mappings within the /16 subnet

        if (self.vpn_type == "GroupVPN"):
            ipop_interfaces = self.CFxHandle.queryParam("Tincan", "Vnets")
            for interface_details in ipop_interfaces:
                if interface_details["TapName"] == self.interface_name:
                    self.uid = interface_details["uid"]
        elif (self.vpn_type == "SocialVPN"):
            self.registerCBT('Watchdog', 'QUERY_IPOP_STATE')
        # Start xmpp handling thread
        self.xmpp_handler()