def get_resolver(): resolver = dns.resolver.Resolver() resolver.reset() # Configure our test resolver to resolve against localhost resolver.read_resolv_conf(StringIO.StringIO('nameserver 127.0.0.1')) return resolver
def query_dns(self, address, resolver): ''' Will query for a dns record. Checks for an SRV dns record first, if found it will return a random record from the highest priority. If no SRV record is found, the domain of the jid will be used. ''' ret_addr = address # call res_init to refresh name resolution is necessary: try: Socket.getaddrinfo(ret_addr[0], ret_addr[1]) except Socket.gaierror as e: if e.errno == 2: # name resolution error logging.warn("Name resolution error; calling res_init()") try: import ctypes libresolv = ctypes.CDLL('libresolv.so.2') result = getattr(libresolv,'__res_init')() if result != 0: logging.warn( "res_init() call returned " + result ) except: logging.exception( "Error while calling res_init" ) try: resolver.nameservers = [] resolver.read_resolv_conf(f='/etc/resolv.conf') logging.debug(resolver.nameservers) xmpp_srv = "_xmpp-client._tcp.%s" % address[0] answers = dns.resolver.query(xmpp_srv, dns.rdatatype.SRV) except (dns.resolver.NXDOMAIN, dns.resolver.NoAnswer, dns.exception.Timeout): log.debug("No appropriate SRV record found." + \ " Using %s" %self.address[0]) else: # Pick a random server, weighted by priority. addresses = {} intmax = 0 for answer in answers: intmax += answer.priority addresses[intmax] = (answer.target.to_text()[:-1], answer.port) #python3 returns a generator for dictionary keys priorities = [x for x in addresses.keys()] priorities.sort() picked = random.randint(0, intmax) for priority in priorities: if picked <= priority: ret_addr = (addresses[priority][0], addresses[priority][1]) break return ret_addr