2 from twisted.internet import reactor
3 from twisted.names import server
4 from twisted.names import dns
5 from twisted.names import common
6 from twisted.names import authority
7 from twisted.internet import defer
8 from twisted.python import failure
10 from invirt.config import structs as config
11 import invirt.database
17 class DatabaseAuthority(common.ResolverBase):
18 """An Authority that is loaded from a file."""
22 def __init__(self, domains=None, database=None):
23 common.ResolverBase.__init__(self)
24 if database is not None:
25 invirt.database.connect(database)
27 invirt.database.connect()
28 if domains is not None:
29 self.domains = domains
31 self.domains = config.dns.domains
32 ns = config.dns.nameservers[0]
33 self.soa = dns.Record_SOA(mname=ns.hostname,
34 rname=config.dns.contact.replace('@','.',1),
35 serial=1, refresh=3600, retry=900,
36 expire=3600000, minimum=21600, ttl=3600)
37 self.ns = dns.Record_NS(name=ns.hostname, ttl=3600)
38 record = dns.Record_A(address=ns.ip, ttl=3600)
39 self.ns1 = dns.RRHeader(ns.hostname, dns.A, dns.IN,
40 3600, record, auth=True)
43 def _lookup(self, name, cls, type, timeout = None):
46 value = self._lookup_unsafe(name, cls, type, timeout = None)
47 except (psycopg2.OperationalError, sqlalchemy.exceptions.SQLError):
50 print "Reloading database"
56 def _lookup_unsafe(self, name, cls, type, timeout):
57 invirt.database.clear_cache()
62 if name in self.domains:
65 # Look for the longest-matching domain. (This works because domain
66 # will remain bound after breaking out of the loop.)
68 for domain in self.domains:
69 if name.endswith('.'+domain) and len(domain) > len(best_domain):
72 return defer.fail(failure.Failure(dns.DomainError(name)))
76 additional = [self.ns1]
77 authority.append(dns.RRHeader(domain, dns.NS, dns.IN,
78 3600, self.ns, auth=True))
81 host = name[:-len(domain)-1]
82 if not host: # Request for the domain itself.
83 if type in (dns.A, dns.ALL_RECORDS):
84 record = dns.Record_A(config.dns.nameservers[0].ip, ttl)
85 results.append(dns.RRHeader(name, dns.A, dns.IN,
86 ttl, record, auth=True))
88 results.append(dns.RRHeader(domain, dns.NS, dns.IN,
89 ttl, self.ns, auth=True))
92 results.append(dns.RRHeader(domain, dns.SOA, dns.IN,
93 ttl, self.soa, auth=True))
94 else: # Request for a subdomain.
95 value = invirt.database.NIC.query.filter_by(hostname=host).first()
99 value = invirt.database.Machine.query().filter_by(name=host).first()
101 ip = value.nics[0].ip
103 return defer.fail(failure.Failure(dns.AuthoritativeDomainError(name)))
106 return defer.fail(failure.Failure(dns.AuthoritativeDomainError(name)))
108 if type in (dns.A, dns.ALL_RECORDS):
109 record = dns.Record_A(ip, ttl)
110 results.append(dns.RRHeader(name, dns.A, dns.IN,
111 ttl, record, auth=True))
112 elif type == dns.SOA:
113 results.append(dns.RRHeader(domain, dns.SOA, dns.IN,
114 ttl, self.soa, auth=True))
115 if len(results) == 0:
118 return defer.succeed((results, authority, additional))
121 return defer.fail(failure.Failure(dns.AuthoritativeDomainError(name)))
123 class QuotingBindAuthority(authority.BindAuthority):
125 A BindAuthority that (almost) deals with quoting correctly
127 This will catch double quotes as marking the start or end of a
128 quoted phrase, unless the double quote is escaped by a backslash
130 # Match either a quoted or unquoted string literal followed by
131 # whitespace or the end of line. This yields two groups, one of
132 # which has a match, and the other of which is None, depending on
133 # whether the string literal was quoted or unquoted; this is what
134 # necessitates the subsequent filtering out of groups that are
137 re.compile(r'"((?:[^"\\]|\\.)*)"|((?:[^\\\s]|\\.)+)(?:\s+|\s*$)')
139 # For interpreting escapes.
140 escape_pat = re.compile(r'\\(.)')
142 def collapseContinuations(self, lines):
147 if line.find('(') == -1:
150 L.append(line[:line.find('(')])
153 if line.find(')') != -1:
154 L[-1] += ' ' + line[:line.find(')')]
164 for m in self.string_pat.finditer(line):
165 [x] = [x for x in m.groups() if x is not None]
166 split_line.append(self.escape_pat.sub(r'\1', x))
168 return filter(None, L)
170 if '__main__' == __name__:
172 for zone in config.dns.zone_files:
173 for origin in config.dns.domains:
174 r = QuotingBindAuthority(zone)
175 # This sucks, but if I want a generic zone file, I have to
176 # reload the information by hand
178 lines = open(zone).readlines()
179 lines = r.collapseContinuations(r.stripComments(lines))
183 resolvers.append(DatabaseAuthority())
186 f = server.DNSServerFactory(authorities=resolvers, verbose=verbosity)
187 p = dns.DNSDatagramProtocol(f)
188 f.noisy = p.noisy = verbosity
190 reactor.listenUDP(53, p)
191 reactor.listenTCP(53, f)