Package: aiodnsresolver
aiodnsresolverAsyncio Python DNS resolver. Pure Python, with no dependencies other than the standard library, threads are not used, no additional tasks are created, and all code is in a single module. The nameservers to query are taken from/etc/resolv.conf, and treats hosts in/etc/hostsas A or AAAA records with a TTL of 0.Designed for highly concurrent/HA situations. Based onhttps://github.com/gera2ld/async_dns.InstallationpipinstallaiodnsresolverUsagefromaiodnsresolverimportResolver,TYPESresolve,_=Resolver()ip_addresses=awaitresolve('www.google.com',TYPES.A)Returned are tuples of subclasses ofIPv4AddressorIPv6Address. Both support conversion to their usual string form by passing them tostr.CacheA cache is part of eachResolver(), expiring records automatically according to their TTL.importasynciofromaiodnsresolverimportResolver,TYPESresolve,clear_cache=Resolver()# Will make a request to the nameserver(s)ip_addresses=awaitresolve('www.google.com',TYPES.A)# Will only make another request to the nameserver(s) if the ip_addresses have expiredip_addresses=awaitresolve('www.google.com',TYPES.A)awaitclear_cache()# Will make another request to the nameserver(s)ip_addresses=awaitresolve('www.google.com',TYPES.A)The cache for each record starts on thestartof each request, so duplicate concurrent requests for the same record are not made.TTL / Record expiryThe address objects each have an extra property,expires_at, that returns the expiry time of the address, according to theloop.time()clock, and the TTL of the records involved to find that address.importasynciofromaiodnsresolverimportResolver,TYPESresolve,_=Resolver()ip_addresses=awaitresolve('www.google.com',TYPES.A)loop=asyncio.get_event_loop()forip_addressinip_address:print('TTL',max(0.0,ip_address.expires_at-loop.time())This can be used in HA situations to assist failovers. The timer forexpires_atstarts justbeforethe request to the nameserver is made.CNAMEsCNAME records are followed transparently. Theexpires_atof IP addresses found via intermediate CNAME(s) is determined by using the minimumexpires_atof all the records involved in determining those IP addresses.Custom nameservers and timeoutsIt is possible to query nameservers other than those in/etc/resolv.conf, and for each to specify a timeout in seconds to wait for a reply before querying the next.asyncdefget_nameservers(_,__):yield(0.5,('8.8.8.8',53))yield(0.5,('1.1.1.1',53))yield(1.0,('8.8.8.8',53))yield(1.0,('1.1.1.1',53))resolve,_=Resolver(get_nameservers=get_nameservers)ip_addresses=awaitresolve('www.google.com',TYPES.A)Parallel requests to multiple nameservers are also possible, where the first response from each set of requests is used.asyncdefget_nameservers(_,__):# For any record request, udp packets are sent to both 8.8.8.8 and 1.1.1.1, waiting 0.5 seconds# for the first response...yield(0.5,('8.8.8.8',53),('1.1.1.1',53))# ... if no response, make another set of requests, waiting 1.0 seconds before timing outyield(1.0,('8.8.8.8',53),('1.1.1.1',53))resolve,_=Resolver(get_nameservers=get_nameservers)ip_addresses=awaitresolve('www.google.com',TYPES.A)This can be used as part of a HA system: if a nameserver isn't contactable, this pattern avoids waiting for its timeout before querying another nameserver.Custom hostsIt's possible to specify hosts without editing the/etc/hostsfile.fromaiodnsresolverimportResolver,IPv4AddressExpiresAt,TYPESasyncdefget_host(_,fqdn,qtype):hosts={b'localhost':{TYPES.A:IPv4AddressExpiresAt('127.0.0.1',expires_at=0),},b'example.com':{TYPES.A:IPv4AddressExpiresAt('127.0.0.1',expires_at=0),},}try:returnhosts[qtype][fqdn]exceptKeyError:returnNoneresolve,_=Resolver(get_host=get_host)ip_addresses=awaitresolve('www.google.com',TYPES.A)ExceptionsExceptions are subclasses ofDnsError, and are raised if a record does not exist, on socket errors, timeouts, message parsing errors, or other errors returned from the nameserver.Specifically, if a record is determined to not exist,DnsRecordDoesNotExistis raised.fromaiodnsresolverimportResolver,TYPES,DnsRecordDoesNotExist,DnsErrorresolve,_=Resolver()try:ip_addresses=awaitresolve('www.google.com',TYPES.A)exceptDnsRecordDoesNotExist:print('domain does not exist')raiseexceptDnsErrorasexception:print(type(exception))raiseIf a lower-level exception caused theDnsError, it will be in the__cause__attribute of the exception.LoggingBy default logging is through theLoggernamedaiodnsresolver, and all messages are prefixed with[dns]or[dns:<fqdn>,<query-type>]through aLoggerAdapter. Each function acceptsget_logger_adapter: the default of which results in this behaviour, and can be overridden to set either theLoggeror theLoggerAdapter.importloggingfromaiodnsresolverimportResolver,ResolverLoggerAdapterresolve,clear_cache=Resolver(get_logger_adapter=lambdaextra:ResolverLoggerAdapter(logging.getLogger('my-application.dns'),extra),)TheLoggerAdapterused byresolveandclear_cachedefaults to the one passed toResolver.Chaining logging adaptersFor complex or highly concurrent applications, it may be desirable that logging adapters be chained to output log messages that incorporate a parent context. So the default ouput of[dns:my-domain.com,A] Concurrent request found, waiting for it to completewould be prefixed with aparentcontext to output something like[request:12345] [dns:my-domain.com,A] Concurrent request found, waiting for it to completeTo do this, setget_logger_adapteras a function that chains multipleLoggerAdapter.importloggingfromaiodnsresolverimportResolver,TYPES,ResolverLoggerAdapterclassRequestAdapter(logging.LoggerAdapter):defprocess(self,msg,kwargs):return'[request:%s]%s'%(self.extra['request-id'],msg),kwargsdefget_logger_adapter(extra):parent_adapter=RequestAdapter(logging.getLogger('my-application.dns'),{'request-id':'12345'})child_adapter=ResolverLoggerAdapter(parent_adapter,extra)returnchild_adapterresolve,_=Resolver()result=awaitresolve('www.google.com',TYPES.A,get_logger_adapter=get_logger_adapter)Log levelsA maximum of two messages per DNS query are logged atINFO. If a nameserver fails, aWARNINGis issued [although an exception will be raised if no nameservers succeed], and the remainder of messages are logged atDEBUG. NoERRORorCRITICALmessages are issued when exceptions are raised: it is the responsiblity of client code to log these if desired.Disable 0x20-bit encodingBy default each domain name is encoded with0x20-bit encodingbefore being sent to the nameservers. However, some nameservers, such as Docker's built-in, do not support this. So, to control or disable the encoding, you can pass a customtransform_fqdncoroutine to Resolver that does not perform any additional encoding.fromaiodnsresolverimportResolverasyncdeftransform_fqdn_no_0x20_encoding(fqdn):returnfqdnresolve,_=Resolver(transform_fqdn=transform_fqdn_no_0x20_encoding)or performs it conditionallyfromaiodnsresolverimportResolver,mix_caseasyncdeftransform_fqdn_0x20_encoding_conditionally(fqdn):return\fqdniffqdn.endswith(b'some-domain')else\awaitmix_case(fqdn)resolve,_=Resolver(transform_fqdn=transform_fqdn_0x20_encoding_conditionally)Security considerationsTo migitate spoofing, several techniques are used.Each query is given a random ID, which is checked against any response.By default each domain name is encoded with0x20-bit encoding, which is checked against any response.A new socket, and so a new random local port, is used for each query.Requests made for a domain while there is an in-flight query for that domain, wait for the the in-flight query to finish, and use its result.Also, to migitate the risk of evil responses/configurationPointer loopsare detected.CNAME chains have a maximum length.Event loop, tasks, and yieldingNo tasks are created, and the event loop is only yielded to during socket communication. Because fetching results from the cache involves no socket communication, this means that cached results are fetched without yielding. This introduces a small inconsistency between fetching cached and non-cached results, and so clients should be written to not depend on the presence or lack of a yield during resolution. This is a typically recommended process however: it should be expected that coroutines might yield.The trade-off for this inconsistency is that cached results are fetched slightly faster than if resolving were to yield in all cases.For CNAME chains, the event loop is yielded during each communication for non-cached parts of the chain.ScopeThe scope of this project is deliberately restricted to operations that are used to resolve A or AAAA records: to resolve a domain name to its IP addresses so that IP connections can be made, and have similar responsibilities togethostbyname. Some limited extra behaviour is present/may be added, but great care is taken to prevent scope creep, especially to not add complexity that isn't required to resolve A or AAAA records.UDP queries are made, but not TCP. DNS servers must support UDP, and it's impossible for a single A and AAAA record to not fit into the maximum size of a UDP DNS response, 512 bytes. There may be other data that the DNS server would return in TCP connections, but this isn't required to resolve a domain name to a single IP address.It is technically possible that in the case of extremely high numbers of A or AAAA records for a domain, they would not fit in a single UDP message. However, this is extremely unlikely, and in this unlikely case, extremely unlikely to affect target applications in any meaningful way. If a truncated message is received, a warning is logged.The resolver is astubresolver: it delegates the responsibility of recursion to the nameserver(s) it queries. In the vast majority of envisioned use cases this is acceptable, since the nameservers in/etc/resolv.confwill be recursive.Example: aiohttpimportasyncioimportsocketfromaiodnsresolverimport(TYPES,Resolver,DnsError,DnsRecordDoesNotExist,)importaiohttpclassAioHttpDnsResolver(aiohttp.abc.AbstractResolver):def__init__(self):super().__init__()self.resolver,self.clear_cache=Resolver()asyncdefresolve(self,host,port=0,family=socket.AF_INET):# Use ipv4 unless requested otherwise# This is consistent with the default aiohttp + aiodns AsyncResolverrecord_type=\TYPES.AAAAiffamily==socket.AF_INET6else\TYPES.Atry:ip_addresses=awaitself.resolver(host,record_type)exceptDnsRecordDoesNotExistasdoes_not_exist:raiseOSError(0,'{}does not exist'.format(host))fromdoes_not_existexceptDnsErrorasdns_error:raiseOSError(0,'{}failed to resolve'.format(host))fromdns_errorreturn[{'hostname':host,'host':str(ip_address),'port':port,'family':family,'proto':socket.IPPROTO_TCP,'flags':socket.AI_NUMERICHOST,}forip_addressinip_addresses]asyncdefclose(self):awaitself.clear_cache()asyncdefmain():asyncwithaiohttp.ClientSession(connector=aiohttp.TCPConnector(use_dns_cache=False,resolver=AioHttpDnsResolver()),)assession:asyncwithawaitsession.get('https://www.google.com/')asresult:print(result)loop=asyncio.get_event_loop()loop.run_until_complete(main())loop.close()Example: tornadoimportasyncioimportsocketfromaiodnsresolverimport(TYPES,DnsError,DnsRecordDoesNotExist,Resolver,)importtornado.httpclientimporttornado.netutilclassAioHttpDnsResolver(tornado.netutil.Resolver):definitialize(self):self.resolver,self.clear_cache=Resolver()asyncdefresolve(self,host,port=0,family=socket.AF_UNSPEC):# Use ipv4 unless ipv6 requestedrecord_type,family_conn=\(TYPES.AAAA,socket.AF_INET6)iffamily==socket.AF_INET6else\(TYPES.A,socket.AF_INET)try:ip_addresses=awaitself.resolver(host,record_type)exceptDnsRecordDoesNotExistasdoes_not_exist:raiseIOError('{}does not exist'.format(host))fromdoes_not_existexceptDnsErrorasdns_error:raiseIOError('{}failed to resolve'.format(host))fromdns_errorreturn[(family_conn,(str(ip_address),port))forip_addressinip_addresses]asyncdefclose(self):awaitself.clear_cache()asyncdefmain():tornado.netutil.Resolver.configure(AioHttpDnsResolver)http_client=tornado.httpclient.AsyncHTTPClient()response=awaithttp_client.fetch("http://www.google.com")print(response.body)loop=asyncio.get_event_loop()loop.run_until_complete(main())loop.close()Example: lowhaioNo extra code is needed to use aiodnsresolver withlowhaio: it is used by default.Testing strategyTests attempt to closly match real-world use, and assert on how input translate to output, i.e. thepublicbehaviour of the resolver. Therefore the tests avoid assumptions on implementation details.There are however exceptions.Many tests assume that timeouts are controlled byasyncio.sleep,loop.call_laterorloop.call_at. This is to allow time to be fast-forwarded through cache invalidation usingaiofastforwardwithout actually having to wait the corresponding time in the tests. Also, many tests assumeopenis used to access files, and patch it to allow assertions on what the code would do with different contents of/etc/resolv.confor/etc/hosts.While both being assumptions, they are both unlikely to change, and in the case that they are changed, this would much more likely result in tests failing incorrectly rather than passing incorrectly. Therefore these are low-risk assumptions.A higher risk assumption is that many tests use the, otherwise private,packandparsefunctions as part of the built-in DNS server that is used by the tests. These are the core functions used by the production code used to pack and parse DNS messages. While asserting that the resolver can communicate to the built-in nameserver, all the tests do is assert thatpackandparseare consistent with each other: it is an assumption that other nameservers have equivalent behaviour.To mitigate the risks that these assumptions bring, some "end to end"-style tests are included, which use whatever nameservers are in/etc/resolv.conf, and asserting on globally available DNS results. While not going through every possible case of input, they do validate that core behaviour is consistent with one other implementation of the protocol.