[181] | 1 | #!/usr/bin/python |
---|
| 2 | from twisted.internet import reactor |
---|
| 3 | from twisted.names import server |
---|
| 4 | from twisted.names import dns |
---|
| 5 | from twisted.names import common |
---|
[1477] | 6 | from twisted.names import authority |
---|
[181] | 7 | from twisted.internet import defer |
---|
| 8 | from twisted.python import failure |
---|
| 9 | |
---|
[2037] | 10 | from invirt.common import InvirtConfigError |
---|
[851] | 11 | from invirt.config import structs as config |
---|
| 12 | import invirt.database |
---|
[302] | 13 | import psycopg2 |
---|
| 14 | import sqlalchemy |
---|
| 15 | import time |
---|
[1490] | 16 | import re |
---|
[181] | 17 | |
---|
| 18 | class DatabaseAuthority(common.ResolverBase): |
---|
| 19 | """An Authority that is loaded from a file.""" |
---|
| 20 | |
---|
| 21 | soa = None |
---|
| 22 | |
---|
[851] | 23 | def __init__(self, domains=None, database=None): |
---|
[181] | 24 | common.ResolverBase.__init__(self) |
---|
| 25 | if database is not None: |
---|
[851] | 26 | invirt.database.connect(database) |
---|
| 27 | else: |
---|
| 28 | invirt.database.connect() |
---|
| 29 | if domains is not None: |
---|
| 30 | self.domains = domains |
---|
| 31 | else: |
---|
| 32 | self.domains = config.dns.domains |
---|
| 33 | ns = config.dns.nameservers[0] |
---|
| 34 | self.soa = dns.Record_SOA(mname=ns.hostname, |
---|
| 35 | rname=config.dns.contact.replace('@','.',1), |
---|
[181] | 36 | serial=1, refresh=3600, retry=900, |
---|
| 37 | expire=3600000, minimum=21600, ttl=3600) |
---|
[851] | 38 | self.ns = dns.Record_NS(name=ns.hostname, ttl=3600) |
---|
| 39 | record = dns.Record_A(address=ns.ip, ttl=3600) |
---|
| 40 | self.ns1 = dns.RRHeader(ns.hostname, dns.A, dns.IN, |
---|
[645] | 41 | 3600, record, auth=True) |
---|
| 42 | |
---|
[582] | 43 | |
---|
[181] | 44 | def _lookup(self, name, cls, type, timeout = None): |
---|
[302] | 45 | for i in range(3): |
---|
| 46 | try: |
---|
| 47 | value = self._lookup_unsafe(name, cls, type, timeout = None) |
---|
| 48 | except (psycopg2.OperationalError, sqlalchemy.exceptions.SQLError): |
---|
| 49 | if i == 2: |
---|
| 50 | raise |
---|
| 51 | print "Reloading database" |
---|
| 52 | time.sleep(0.5) |
---|
| 53 | continue |
---|
| 54 | else: |
---|
| 55 | return value |
---|
| 56 | |
---|
| 57 | def _lookup_unsafe(self, name, cls, type, timeout): |
---|
[851] | 58 | invirt.database.clear_cache() |
---|
[582] | 59 | |
---|
| 60 | ttl = 900 |
---|
[646] | 61 | name = name.lower() |
---|
[922] | 62 | |
---|
[646] | 63 | if name in self.domains: |
---|
| 64 | domain = name |
---|
[505] | 65 | else: |
---|
[922] | 66 | # Look for the longest-matching domain. (This works because domain |
---|
| 67 | # will remain bound after breaking out of the loop.) |
---|
| 68 | best_domain = '' |
---|
[505] | 69 | for domain in self.domains: |
---|
[922] | 70 | if name.endswith('.'+domain) and len(domain) > len(best_domain): |
---|
| 71 | best_domain = domain |
---|
| 72 | if best_domain == '': |
---|
[505] | 73 | return defer.fail(failure.Failure(dns.DomainError(name))) |
---|
[922] | 74 | domain = best_domain |
---|
[181] | 75 | results = [] |
---|
| 76 | authority = [] |
---|
[645] | 77 | additional = [self.ns1] |
---|
[541] | 78 | authority.append(dns.RRHeader(domain, dns.NS, dns.IN, |
---|
[582] | 79 | 3600, self.ns, auth=True)) |
---|
[922] | 80 | |
---|
[582] | 81 | if cls == dns.IN: |
---|
[651] | 82 | host = name[:-len(domain)-1] |
---|
[922] | 83 | if not host: # Request for the domain itself. |
---|
[651] | 84 | if type in (dns.A, dns.ALL_RECORDS): |
---|
[851] | 85 | record = dns.Record_A(config.dns.nameservers[0].ip, ttl) |
---|
[643] | 86 | results.append(dns.RRHeader(name, dns.A, dns.IN, |
---|
[582] | 87 | ttl, record, auth=True)) |
---|
[651] | 88 | elif type == dns.NS: |
---|
| 89 | results.append(dns.RRHeader(domain, dns.NS, dns.IN, |
---|
| 90 | ttl, self.ns, auth=True)) |
---|
| 91 | authority = [] |
---|
| 92 | elif type == dns.SOA: |
---|
| 93 | results.append(dns.RRHeader(domain, dns.SOA, dns.IN, |
---|
| 94 | ttl, self.soa, auth=True)) |
---|
[922] | 95 | else: # Request for a subdomain. |
---|
[1974] | 96 | value = invirt.database.NIC.query.filter_by(hostname=host).first() |
---|
| 97 | if value: |
---|
| 98 | ip = value.ip |
---|
| 99 | else: |
---|
| 100 | value = invirt.database.Machine.query().filter_by(name=host).first() |
---|
| 101 | if value: |
---|
| 102 | ip = value.nics[0].ip |
---|
| 103 | else: |
---|
| 104 | return defer.fail(failure.Failure(dns.AuthoritativeDomainError(name))) |
---|
| 105 | |
---|
| 106 | if ip is None: |
---|
[922] | 107 | return defer.fail(failure.Failure(dns.AuthoritativeDomainError(name))) |
---|
| 108 | |
---|
[651] | 109 | if type in (dns.A, dns.ALL_RECORDS): |
---|
[582] | 110 | record = dns.Record_A(ip, ttl) |
---|
| 111 | results.append(dns.RRHeader(name, dns.A, dns.IN, |
---|
| 112 | ttl, record, auth=True)) |
---|
[651] | 113 | elif type == dns.SOA: |
---|
| 114 | results.append(dns.RRHeader(domain, dns.SOA, dns.IN, |
---|
| 115 | ttl, self.soa, auth=True)) |
---|
[650] | 116 | if len(results) == 0: |
---|
| 117 | authority = [] |
---|
| 118 | additional = [] |
---|
[582] | 119 | return defer.succeed((results, authority, additional)) |
---|
| 120 | else: |
---|
| 121 | #Doesn't exist |
---|
| 122 | return defer.fail(failure.Failure(dns.AuthoritativeDomainError(name))) |
---|
[181] | 123 | |
---|
[1490] | 124 | class QuotingBindAuthority(authority.BindAuthority): |
---|
| 125 | """ |
---|
| 126 | A BindAuthority that (almost) deals with quoting correctly |
---|
| 127 | |
---|
| 128 | This will catch double quotes as marking the start or end of a |
---|
| 129 | quoted phrase, unless the double quote is escaped by a backslash |
---|
| 130 | """ |
---|
[1511] | 131 | # Match either a quoted or unquoted string literal followed by |
---|
| 132 | # whitespace or the end of line. This yields two groups, one of |
---|
| 133 | # which has a match, and the other of which is None, depending on |
---|
| 134 | # whether the string literal was quoted or unquoted; this is what |
---|
| 135 | # necessitates the subsequent filtering out of groups that are |
---|
| 136 | # None. |
---|
| 137 | string_pat = \ |
---|
| 138 | re.compile(r'"((?:[^"\\]|\\.)*)"|((?:[^\\\s]|\\.)+)(?:\s+|\s*$)') |
---|
| 139 | |
---|
| 140 | # For interpreting escapes. |
---|
| 141 | escape_pat = re.compile(r'\\(.)') |
---|
| 142 | |
---|
[1490] | 143 | def collapseContinuations(self, lines): |
---|
| 144 | L = [] |
---|
| 145 | state = 0 |
---|
| 146 | for line in lines: |
---|
| 147 | if state == 0: |
---|
| 148 | if line.find('(') == -1: |
---|
| 149 | L.append(line) |
---|
| 150 | else: |
---|
| 151 | L.append(line[:line.find('(')]) |
---|
| 152 | state = 1 |
---|
| 153 | else: |
---|
| 154 | if line.find(')') != -1: |
---|
| 155 | L[-1] += ' ' + line[:line.find(')')] |
---|
| 156 | state = 0 |
---|
| 157 | else: |
---|
| 158 | L[-1] += ' ' + line |
---|
| 159 | lines = L |
---|
| 160 | L = [] |
---|
[1511] | 161 | |
---|
[1490] | 162 | for line in lines: |
---|
| 163 | in_quote = False |
---|
| 164 | split_line = [] |
---|
[1631] | 165 | for m in self.string_pat.finditer(line): |
---|
[1511] | 166 | [x] = [x for x in m.groups() if x is not None] |
---|
[1631] | 167 | split_line.append(self.escape_pat.sub(r'\1', x)) |
---|
[1490] | 168 | L.append(split_line) |
---|
| 169 | return filter(None, L) |
---|
| 170 | |
---|
[181] | 171 | if '__main__' == __name__: |
---|
[1477] | 172 | resolvers = [] |
---|
[2037] | 173 | try: |
---|
| 174 | for zone in config.dns.zone_files: |
---|
| 175 | for origin in config.dns.domains: |
---|
| 176 | r = QuotingBindAuthority(zone) |
---|
| 177 | # This sucks, but if I want a generic zone file, I have to |
---|
| 178 | # reload the information by hand |
---|
| 179 | r.origin = origin |
---|
| 180 | lines = open(zone).readlines() |
---|
| 181 | lines = r.collapseContinuations(r.stripComments(lines)) |
---|
| 182 | r.parseLines(lines) |
---|
| 183 | |
---|
| 184 | resolvers.append(r) |
---|
| 185 | except InvirtConfigError: |
---|
| 186 | # Don't care if zone_files isn't defined |
---|
| 187 | pass |
---|
[1477] | 188 | resolvers.append(DatabaseAuthority()) |
---|
[181] | 189 | |
---|
| 190 | verbosity = 0 |
---|
[1477] | 191 | f = server.DNSServerFactory(authorities=resolvers, verbose=verbosity) |
---|
[181] | 192 | p = dns.DNSDatagramProtocol(f) |
---|
| 193 | f.noisy = p.noisy = verbosity |
---|
| 194 | |
---|
| 195 | reactor.listenUDP(53, p) |
---|
| 196 | reactor.listenTCP(53, f) |
---|
| 197 | reactor.run() |
---|