-
-
Save fcoury/1074348 to your computer and use it in GitHub Desktop.
Python/Twisted/Redis backed DNS server.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Python/Twisted/Redis backed DNS server - resolves from NAME to IP addrs | |
# fallback to google or any other DNS server to resolv domains not present on Redis | |
# to set a new domain on redis, just issue a SET domain.tld ip_addr | |
# run with twistd -ny txredns.tac | |
# gleicon 2011 | |
from twisted.names import dns, server, client, cache | |
from twisted.application import service, internet | |
from twisted.internet import defer | |
from twisted.python import log | |
import txredisapi | |
class RedisResolverBackend(client.Resolver): | |
def __init__(self, redis, servers=None): | |
self.redis = redis | |
client.Resolver.__init__(self, servers=servers) | |
self.ttl = 5 | |
@defer.inlineCallbacks | |
def _get_ip_addr(self, hostname, timeout): | |
ip = yield self.redis.get(hostname) | |
log.msg('redis: %s'% ip) | |
r = None | |
if ip: | |
defer.returnValue([(dns.RRHeader(hostname, dns.A, dns.IN, self.ttl, dns.Record_A(ip, self.ttl)),), (), ()]) | |
else: | |
i = yield self._lookup(hostname, dns.IN, dns.A, timeout) | |
defer.returnValue(i) | |
def lookupAddress(self, name, timeout = None): | |
return self._get_ip_addr(name, timeout) | |
def create_application(): | |
rd = txredisapi.lazyRedisConnectionPool() | |
redisBackend = RedisResolverBackend(rd, servers=[('8.8.8.8', 53)]) | |
application = service.Application("txdnsredis") | |
srv_collection = service.IServiceCollection(application) | |
dnsFactory = server.DNSServerFactory(caches=[cache.CacheResolver()], clients=[redisBackend]) | |
internet.TCPServer(53, dnsFactory).setServiceParent(srv_collection) | |
internet.UDPServer(53, dns.DNSDatagramProtocol(dnsFactory)).setServiceParent(srv_collection) | |
return application | |
# .tac app | |
application = create_application() | |
will this work with wildcard entries? e.g *.myapp.dev
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I am new to twisted. This works perfectly for something that I am working on -- but I need to derive the source IP on the DNS requester. There seems to be no obvious way to do this using twisted.names.client.Resolver. Can someone comment on how I might be able to achieve this?