Example #1
0
def findAMQHost():

    browse_sdRef = pybonjour.DNSServiceBrowse(regtype=regtype,
                                              callBack=browse_callback)
    try:
        while not hosts:
            logger.debug(' [*] doing bonjour resolve')
            ready = select.select([browse_sdRef], [], [])
            logger.debug(' [*] return from ready')
            if browse_sdRef in ready[0]:
                pybonjour.DNSServiceProcessResult(browse_sdRef)
    except:
        logger.debug(' [*] unknown error while attemping to resolve AMQP host')
    finally:
        browse_sdRef.close()

    # if this script is unable to handle multiple AMQP servers and so we
    # attempt to deal with it, and bail if we can't
    if len(hosts) > 1:
        # lets see if we're seeing multiple records for the same host
        if len(hosts) == hosts.count(hosts[0]):
            logger.debug(' [*] found multiple hosts but they are all the same')
            RabbitMQServer = hosts[0]
        else:
            logger.critical(
                'found too many AMQP (RabbitMQ) hosts, unable to cope!')
            return 0
    elif len(hosts) == 1:
        RabbitMQServer = hosts[0]
    else:
        logger.critical(' [*] couldn\'t resolve any AMQP hosts')
        return 0

    return RabbitMQServer
Example #2
0
    def locate(self):
        """When invoked, this populates the MirrorDetector object with
                URLs that name dynamically discovered content mirrors."""

        # Clear the list of mirrors.  It will be repopulated later.
        self._mirrors = []

        if not "pybonjour" in globals():
            return

        timedout = False
        tval = self.__timeout

        def browse_cb(sd_hdl, flags, interface_idx, error_code, service_name,
                      regtype, reply_domain):

            if error_code != pybonjour.kDNSServiceErr_NoError:
                return

            if not (flags & pybonjour.kDNSServiceFlagsAdd):
                return

            self._resolve_server(interface_idx, error_code, service_name,
                                 regtype, reply_domain)

        try:
            sd_hdl = pybonjour.DNSServiceBrowse(regtype=self.__service,
                                                callBack=browse_cb)
        except pybonjour.BonjourError, e:
            errstr = "mDNS Service Browse Failed: %s\n" % e[0][1]
            raise tx.mDNSException(errstr)
def discover(timeout=10):
	timeout = float(timeout)
	browse_sdRef = pybonjour.DNSServiceBrowse(regtype = regtype, callBack = browse_callback)
	cTime = time.time()
	try:
		try:
			while len(resolved_addrs) == 0 and time.time()-cTime < timeout:
				ready = select.select([browse_sdRef], [], [], timeout/2)
				if browse_sdRef in ready[0]:
					pybonjour.DNSServiceProcessResult(browse_sdRef)
		except KeyboardInterrupt:
			pass
	finally:
		browse_sdRef.close()
	
	if len(resolved_addrs) > 0:
		if len(resolved_addrs) == 1:
			print("Found 1 matching Service, connecting to %s:%d" % (resolved_addrs[0].get("host"), resolved_addrs[0].get("port")))
			return resolved_addrs[0].get("host"), resolved_addrs[0].get("port")
		else:
			print("Found Services:")
			print("#\tHost:Port")
			for i in range(0, len(resolved_addrs)):
				print("%d:\t%s:%d" % (i, resolved_addrs[i].get("host"), resolved_addrs[i].get("port")))
			user_option = input("Please choose service # to connect:")
			return resolved_addrs[user_option].get("host"), resolved_addrs[user_option].get("port")
	else:
		return None, None
Example #4
0
    def findAMQPHost(self):
        browse_sdRef = pybonjour.DNSServiceBrowse(
            regtype='_amqp._tcp', callBack=self.__browse_callback)
        try:
            while not self.hosts:
                #   logger.debug(' [*] doing bonjour resolve')
                ready = select.select([browse_sdRef], [], [])
                #  logger.debug(' [*] return from ready')
                if browse_sdRef in ready[0]:
                    pybonjour.DNSServiceProcessResult(browse_sdRef)
        except IOError:
            #logger.debug(' [*] unknown error while attemping to resolve AMQP host')
            pass
        finally:
            browse_sdRef.close()

        # if this script is unable to handle multiple AMQP servers and so we
        # attempt to deal with it, and bail if we can't
        if len(self.hosts) > 1:
            # lets see if we're seeing multiple records for the same host
            if len(self.hosts) == self.hosts.count(self.hosts[0]):
                #logger.debug(' [*] found multiple hosts but they are all the same')
                self.selectedHost = self.hosts[0]
            else:
                print 'found too many AMQP (RabbitMQ) hosts, unable to cope!'
                return 0
        elif len(self.hosts) == 1:
            self.selectedHost = self.hosts[0]
            return 1
        else:
            #logger.critical(' [*] couldn\'t resolve any AMQP hosts')

            return 0
Example #5
0
 def start_browser(self):
     self.browse_sdRef = pybonjour.DNSServiceBrowse(
         regtype=self.stype, callBack=self.on_browse_started)
     self.browse_thread = ProcessThread(sdRef=self.browse_sdRef,
                                        close_when_finished=True,
                                        _name='browse_%s' % (self.stype))
     self.browse_thread.start()
Example #6
0
    def discover(self):
        """Discover appropriate services on the .local domain"""
        global discovered

        if self.linux == True:

            cmdline = [
                "avahi-browse", "-t", "-r", "-l", "-p", "-k", "_iotas._tcp"
            ]
            try:
                d = subprocess.check_output(cmdline)
                print d
                ret = parse_avahi(data=d)
                discovered = ret
            except:
                print "Something went wrong!"
                return ""

        else:
            """Use the pybonjour module to do some cool thingage"""
            browse_sdRef = pybonjour.DNSServiceBrowse(regtype=self.regtype,
                                                      callBack=browse_callback)

            print "discover.select"
            starttime = time.time()
            while (time.time() - starttime) < 15:
                ready = select.select([browse_sdRef], [], [], timeout)
                if browse_sdRef in ready[0]:
                    pybonjour.DNSServiceProcessResult(browse_sdRef)

            print "discover.close"
            browse_sdRef.close()
    def __init__(self, type):   
            
        regtype  = type
        self.complete = False
        self.bonjourName = []
        self.bonjourPort = []
        self.bonjourIP = []
        self.timeout  = 5
        self.queried  = []
        self.resolved = []
                
        browse_sdRef = pybonjour.DNSServiceBrowse(regtype = regtype,
                                                  callBack = self.browse_callback)

        try:
            try:
                while True:
                    ready = select.select([browse_sdRef], [], [])
                    if browse_sdRef in ready[0]:
                        pybonjour.DNSServiceProcessResult(browse_sdRef)
                        break
            except:             
                pass
        finally:
            browse_sdRef.close()
Example #8
0
	def repeatloop(self):
		'''
		A loop that listens for the desired Bonjour service types and
		repeats all it finds. The loop will continue indefinitely so it
		should be invoked in a separate thread if additional action is
		required. In this case, just set self.browse to False to
		terminate the listening.

		When the loop is terminated, close the browse request.

		Listening is done for timeout seconds so that the loop can be
		terminated if desired. After termination, all repeated services
		are removed.
		'''

		# Attempt a browse of the service type
		browseref = mdns.DNSServiceBrowse(
				regtype = self.svctype, callBack = self.browser)

		self.browse = True

		try:
			while self.browse:
				ready = select.select([browseref], [], [], self.timeout)
				if browseref in ready[0]:
					mdns.DNSServiceProcessResult(browseref)
		finally:
			# Attempt to close all open repeater references
			for v in list(self.repeater.values()): v.close()
			# Reset the repeater dictionary
			self.repeater = {}
			# Close the open browse request
			browseref.close()
Example #9
0
    def run(self):
        if not self.mdnsd.is_alive():
            self.mdnsd.wait(timeout=10)

        sdRef = pybonjour.DNSServiceBrowse(regtype=self.regtype,
                                           callBack=self.on_discover)

        while True:
            r, w, x = select.select([sdRef, self.pipe[0]], [], [])
            if self.pipe[0] in r:
                break

            for ref in r:
                try:
                    pybonjour.DNSServiceProcessResult(ref)

                # mdnsd was probaly killed, so just continue since this thread will be restarted
                except pybonjour.BonjourError:
                    continue

            if self.finished.is_set():
                break

        if self.active(sdRef):
            sdRef.close()
Example #10
0
def list_presence_users(regtype='_presence._tcp', nb_try=10):
    resolved = []
    timeout = 1
    names = {}

    def resolve_callback(sdRef, flags, interfaceIndex, errorCode, fullname,
                         hosttarget, port, txtRecord):
        if errorCode == pybonjour.kDNSServiceErr_NoError:
            tmp = pybonjour.TXTRecord.parse(txtRecord)

            username = fullname.split(".")[0]
            ascii_pattern = re.compile(r"\\(\d\d\d)")
            username = ascii_pattern.sub(ascii_to_char,
                                         username.encode('utf-8'))
            ip = resolve(username, interfaceIndex)

            names[username] = {'host': ip,
                               'port': port}
            resolved.append(True)

    def browse_callback(sdRef, flags, interfaceIndex, errorCode, serviceName,
                        regtype, replyDomain):
        if errorCode != pybonjour.kDNSServiceErr_NoError:
            return

        if not (flags & pybonjour.kDNSServiceFlagsAdd):
            logger.debug("Service removed")
            return

        resolve_sdRef = pybonjour.DNSServiceResolve(0,
                                                    interfaceIndex,
                                                    serviceName,
                                                    regtype,
                                                    replyDomain,
                                                    resolve_callback)

        try:
            while not resolved:
                ready = select.select([resolve_sdRef], [], [], timeout)
                if resolve_sdRef not in ready[0]:
                    logger.debug("Resolve timed out")
                    break
                pybonjour.DNSServiceProcessResult(resolve_sdRef)
            else:
                resolved.pop()
        finally:
            resolve_sdRef.close()

    try:
        browse_sdRef = pybonjour.DNSServiceBrowse(regtype=regtype,
                                              callBack=browse_callback)
    except pybonjour.BonjourError,e :
        if e.errorCode == -65537:
            banner_notification("Please start Avahi Daemon:\n"
                                "sudo gainroot --use-su\n"
                                "/etc/init.d/avahi-daemon start")
            sleep(4)
        return names
Example #11
0
def get_services(regtype):
    global _services
    _services = []
    
    browse_sdRef = pybonjour.DNSServiceBrowse(regtype=regtype, callBack=browse_callback)
    pybonjour.DNSServiceProcessResult(browse_sdRef)
    browse_sdRef.close()
    
    return _services
Example #12
0
 def browse_domain(self, domain=None):
     gajim.log.debug('starting to browse')
     try:
         self.browse_sdRef = pybonjour.DNSServiceBrowse(
             regtype=self.stype,
             domain=domain,
             callBack=self.browse_callback)
     except pybonjour.BonjourError as e:
         self.error_CB("Error while browsing: %s" % str(e))
Example #13
0
def main():
    browser = pybonjour.DNSServiceBrowse(regtype=REGTYPE,
                                         callBack=BrowseCallback)
    try:
        ready = select.select([browser], [], [])
        if browser in ready[0]:
            pybonjour.DNSServiceProcessResult(browser)
    finally:
        browser.close()
Example #14
0
            def __inner(sdRef, flags, interfaceIndex, errorCode, replyDomain):
 #               print "_domain_callback(%r, %r, %r, %r, %r)" % (sdRef, flags, interfaceIndex, errorCode, replyDomain)
                if errorCode != pybonjour.kDNSServiceErr_NoError:
                    return

                sdRef = pybonjour.DNSServiceBrowse(regtype=regtype,
                                                    callBack=_browse_callback(callback),
                                                    domain=replyDomain)
                self.rlist.append((sdRef, pybonjour.DNSServiceProcessResult))
Example #15
0
 def _browse(self):
     self._browse_ref = pybonjour.DNSServiceBrowse(
         regtype=self._regtype, callBack=self._browse_callback)
     while True:
         ready = gevent.select.select([self._browse_ref], [], [])
         if self._browse_ref in ready[0]:
             try:
                 pybonjour.DNSServiceProcessResult(self._browse_ref)
             except pybonjour.BonjourError:
                 pass
Example #16
0
def bonjour_browse_service(regtype, callback):
    try:
        callback_obj = BonjourCallbacks(callback)
        ref = pybonjour.DNSServiceBrowse(regtype=regtype,
                                         callBack=callback_obj.browse_callback)
        callback_obj.host = dict()
        callback_obj.add_ref(ref)
        return callback_obj
    except pybonjour.BonjourError, e:
        logging.debug('bonjour_browse_service: %s', str(e))
        return None
Example #17
0
 def __init__(self, filepath):
     super(SlaveThread, self).__init__()
     self.filepath = filepath
     self.slave_player = None
     self.running = False
     self.sd_ref = pybonjour.DNSServiceBrowse(regtype=regtype,
                                              callBack=self.browse_callback)
     self.timeout = 5
     self.resolved = []
     self.context = zmq.Context()
     self.subscriber = None
Example #18
0
 def __bonjour_start_listening(self):
     browse_sdRef = pybonjour.DNSServiceBrowse(regtype="_delugefs._tcp", callBack=self.__bonjour_browse_callback)
     try:
         try:
             while True:
                 ready = select.select([browse_sdRef], [], [])
                 if browse_sdRef in ready[0]:
                     pybonjour.DNSServiceProcessResult(browse_sdRef)
         except KeyboardInterrupt:
                 pass
     finally:
         browse_sdRef.close()
Example #19
0
def run():
    browse_sdRef = pybonjour.DNSServiceBrowse(regtype=SERVICE_TYPE,
                                              callBack=browse_callback)
    try:
        try:
            while True:
                ready = select.select([browse_sdRef], [], [])
                if browse_sdRef in ready[0]:
                    pybonjour.DNSServiceProcessResult(browse_sdRef)
        except KeyboardInterrupt:
            pass
    finally:
        browse_sdRef.close()
Example #20
0
        def locate(self):
                """When invoked, this populates the MirrorDetector object with
                URLs that name dynamically discovered content mirrors."""

                # Clear the list of mirrors.  It will be repopulated later.
                self._mirrors = []      

                if not "pybonjour" in globals():
                        return

                timedout = False
                tval = self.__timeout

                def browse_cb(sd_hdl, flags, interface_idx, error_code,
                    service_name, regtype, reply_domain):

                        if error_code != pybonjour.kDNSServiceErr_NoError:
                                return

                        if not (flags & pybonjour.kDNSServiceFlagsAdd):
                                return

                        self._resolve_server(interface_idx, error_code,
                            service_name, regtype, reply_domain)

                try:
                        sd_hdl = pybonjour.DNSServiceBrowse(
                            regtype=self.__service, callBack=browse_cb)
                except pybonjour.BonjourError as e:
                        errstr = "mDNS Service Browse Failed: {0}\n".format(
                            e.args[0][1])
                        raise tx.mDNSException(errstr)

                try:
                        while not timedout:
                                avail = select.select([sd_hdl], [], [], tval)
                                if sd_hdl in avail[0]:
                                        pybonjour.DNSServiceProcessResult(
                                            sd_hdl)
                                        tval = 0
                                else:
                                        timedout = True
                except select.error as e:
                        errstr = "Select failed: {0}\n".format(e.args[1])
                        raise tx.mDNSException(errstr)
                except pybonjour.BonjourError as e:
                        errstr = "mDNS Process Result failed: {0}\n".format(
                            e.args[0][1])
                        raise tx.mDNSException(errstr)
                finally:
                        sd_hdl.close()
Example #21
0
 def run(self):
     self.logger.threaddebug("__starting browser thread")
     try:
         browse_sdRef = pybonjour.DNSServiceBrowse(
             regtype=self.regtype, callBack=self.browse_callback)
         while self.shouldContinue:
             ready = select.select([browse_sdRef], [], [])
             if browse_sdRef in ready[0]:
                 self.logger.threaddebug("__found a service")
                 pybonjour.DNSServiceProcessResult(browse_sdRef)
     except Exception, e:
         self.logger.threaddebug(
             "__exception in bonjour browser thread: %s", str(e))
         pass
 def browse_domain(self, domain=None):
     try:
         self.browse_sdRef = pybonjour.DNSServiceBrowse(
             regtype=self.stype,
             domain=domain,
             callBack=self.browse_callback)
         log.info('Starting to browse .local')
         return True
     except pybonjour.BonjourError as error:
         if error.errorCode == pybonjour.kDNSServiceErr_ServiceNotRunning:
             log.info('Service not running')
         else:
             log.error('Error while browsing for services. %s', error)
         return False
Example #23
0
 def _setup_appletv(self):
     regtype = "_airplay._tcp"
     browse_sdRef = pybonjour.DNSServiceBrowse(
         regtype=regtype, callBack=self._browse_callback)
     try:
         try:
             while not self.host:
                 ready = select.select([browse_sdRef], [], [])
                 if browse_sdRef in ready[0]:
                     pybonjour.DNSServiceProcessResult(browse_sdRef)
         except KeyboardInterrupt:
             pass
     finally:
         browse_sdRef.close()
Example #24
0
    def browse(self):
        '''Method: browse
        Description:
            browse all available _OSInstall._tcp services.

        Args
            None

        Returns
                True  -- if a service is found -- OR --
                False -- if a service is not found -- OR --
                sdref -- if actually in find mode

        Raises
            AImDNSError - if there are no service references available
        '''
        self.sdrefs = dict()
        self._found = False
        self._resolved = list()

        # only browse over the number of interfaces available
        self.count = len(self.interfaces)

        if self.verbose:
            print _('Browsing for services...')

        # pybonjour bug -- can not Browse on a specific interfaceIndex
        # thus only Browsing on all interfaces (0).  If and when this
        # bug gets fixed up stream then the iteration over the interfaces
        # would be appropriate.  The code should look like what is in
        # the find() method.
        # Resolve the DNS service
        sdref = pyb.DNSServiceBrowse(flags=0,
                                     regtype=common.REGTYPE,
                                     domain=common.DOMAIN,
                                     interfaceIndex=0,
                                     callBack=self._browse_callback)

        # save the service reference
        if sdref:
            self.sdrefs['browse'] = [sdref]
        else:
            raise AIMDNSError(_('error: aiMDNSError: mDNS browse failed'))

        # cause the event loop to loop only 5 times
        self._do_lookup = True
        self._handle_events()

        return self._found
Example #25
0
    def serve_forever(self):
        # print "TouchOSC starting serve_forever"
        browse_sdRef = pybonjour.DNSServiceBrowse(
            regtype="_osc._udp", callBack=self.browse_callback)

        try:
            try:
                while True:
                    ready = select.select([browse_sdRef], [], [])
                    if browse_sdRef in ready[0]:
                        pybonjour.DNSServiceProcessResult(browse_sdRef)
            except KeyboardInterrupt:
                pass
        finally:
            browse_sdRef.close()
Example #26
0
    def run(self):
        browse_sdRef = pybonjour.DNSServiceBrowse(regtype=self.reg_type,
                                                  callBack=self.browse_cb)

        try:
            try:
                while True:
                    discovered_event.clear()
                    ready = select.select([browse_sdRef], [], [])
                    if browse_sdRef in ready[0]:
                        pybonjour.DNSServiceProcessResult(browse_sdRef)
                    # time.sleep(0.1)
            except KeyboardInterrupt:
                pass
        finally:
            browse_sdRef.close()
def get_mesh_root_ip(service_name):

    regtype = service_name  #"_ESP_MESH._tcp"
    browse_sdRef = pybonjour.DNSServiceBrowse(regtype=regtype,
                                              callBack=browse_callback)
    #print "debug: browse_sdRef:",browse_sdRef
    ready = select.select([browse_sdRef], [], [], 5)
    #print "debug: ready:",ready
    if browse_sdRef in ready[0]:
        res = pybonjour.DNSServiceProcessResult(browse_sdRef)
        #print "debug:res:",res
    browse_sdRef.close()

    print "m_ip:", m_ip
    print "m_port:", m_port
    return [m_ip, m_port]
def browse_for_services(regtype):
    global service_address
    browse_sdRef = pybonjour.DNSServiceBrowse(regtype=regtype,
                                              callBack=browse_callback)

    try:
        try:
            while service_address is None:
                ready = select.select([browse_sdRef], [], [])
                if browse_sdRef in ready[0]:
                    pybonjour.DNSServiceProcessResult(browse_sdRef)
        except KeyboardInterrupt:
            pass
    finally:
        browse_sdRef.close()
    return service_address
Example #29
0
    def run(self):
        sdRef = pybonjour.DNSServiceBrowse(regtype=self.regtype,
                                           callBack=self.on_discover)

        while True:
            r, w, x = select.select([sdRef, self.pipe[0]], [], [])
            if self.pipe[0] in r:
                break

            for ref in r:
                pybonjour.DNSServiceProcessResult(ref)

            if self.finished.is_set():
                break

        if self.active(sdRef):
            sdRef.close()
Example #30
0
		def browse():
			sd_ref = pybonjour.DNSServiceBrowse(regtype=service_type, callBack=browse_callback)
			try:
				while True:
					ready = select.select([sd_ref], [], [], browse_timeout)

					if not ready[0]:
						break

					if sd_ref in ready[0]:
						pybonjour.DNSServiceProcessResult(sd_ref)
			finally:
				sd_ref.close()

			if callback:
				callback(result)
			result_available.set()