1
# -*- test-case-name: twisted.names.test.test_names -*-
2
# Copyright (c) 2001-2004 Twisted Matrix Laboratories.
3
# See LICENSE for details.
6
from __future__ import nested_scopes
11
from twisted.names import dns
12
from twisted.internet import defer
13
from twisted.python import failure
17
def getSerial(filename = '/tmp/twisted-names.serial'):
18
"""Return a monotonically increasing (across program runs) integer.
20
State is stored in the given file. If it does not exist, it is
21
created with rw-/---/--- permissions.
23
serial = time.strftime('%Y%m%d')
27
if not os.path.exists(filename):
28
f = file(filename, 'w')
29
f.write(serial + ' 0')
34
serialFile = file(filename, 'r')
35
lastSerial, ID = serialFile.readline().split()
36
ID = (lastSerial == serial) and (int(ID) + 1) or 0
38
serialFile = file(filename, 'w')
39
serialFile.write('%s %d' % (serial, ID))
41
serial = serial + ('%02d' % (ID,))
45
#class LookupCacherMixin(object):
48
# def _lookup(self, name, cls, type, timeout = 10):
51
# self._meth = super(LookupCacherMixin, self)._lookup
53
# if self._cache.has_key((name, cls, type)):
54
# return self._cache[(name, cls, type)]
56
# r = self._meth(name, cls, type, timeout)
57
# self._cache[(name, cls, type)] = r
61
class FileAuthority(common.ResolverBase):
62
"""An Authority that is loaded from a file."""
67
def __init__(self, filename):
68
common.ResolverBase.__init__(self)
69
self.loadFile(filename)
73
def __setstate__(self, state):
75
# print 'setstate ', self.soa
77
def _lookup(self, name, cls, type, timeout = None):
82
default_ttl = max(self.soa[1].minimum, self.soa[1].expire)
84
domain_records = self.records.get(name.lower())
87
for record in domain_records:
88
if record.ttl is not None:
93
if record.TYPE == type or type == dns.ALL_RECORDS:
95
dns.RRHeader(name, record.TYPE, dns.IN, ttl, record, auth=True)
97
elif record.TYPE == dns.NS and type != dns.ALL_RECORDS:
99
dns.RRHeader(name, record.TYPE, dns.IN, ttl, record, auth=True)
101
if record.TYPE == dns.CNAME:
103
dns.RRHeader(name, record.TYPE, dns.IN, ttl, record, auth=True)
108
for record in results + authority:
109
section = {dns.NS: additional, dns.CNAME: results, dns.MX: additional}.get(record.type)
110
if section is not None:
111
n = str(record.payload.name)
112
for rec in self.records.get(n.lower(), ()):
113
if rec.TYPE == dns.A:
115
dns.RRHeader(n, dns.A, dns.IN, rec.ttl or default_ttl, rec, auth=True)
118
return defer.succeed((results, authority, additional))
120
if name.lower().endswith(self.soa[0].lower()):
121
# We are the authority and we didn't find it. Goodbye.
122
return defer.fail(failure.Failure(dns.AuthoritativeDomainError(name)))
123
return defer.fail(failure.Failure(dns.DomainError(name)))
126
def lookupZone(self, name, timeout = 10):
127
if self.soa[0].lower() == name.lower():
128
# Wee hee hee hooo yea
129
default_ttl = max(self.soa[1].minimum, self.soa[1].expire)
130
if self.soa[1].ttl is not None:
131
soa_ttl = self.soa[1].ttl
133
soa_ttl = default_ttl
134
results = [dns.RRHeader(self.soa[0], dns.SOA, dns.IN, soa_ttl, self.soa[1], auth=True)]
135
for (k, r) in self.records.items():
137
if rec.ttl is not None:
141
if rec.TYPE != dns.SOA:
142
results.append(dns.RRHeader(k, rec.TYPE, dns.IN, ttl, rec, auth=True))
143
results.append(results[0])
144
return defer.succeed((results, (), ()))
145
return defer.fail(failure.Failure(dns.DomainError(name)))
147
def _cbAllRecords(self, results):
148
ans, auth, add = [], [], []
151
ans.extend(res[1][0])
152
auth.extend(res[1][1])
153
add.extend(res[1][2])
154
return ans, auth, add
157
class PySourceAuthority(FileAuthority):
158
"""A FileAuthority that is built up from Python source code."""
160
def loadFile(self, filename):
161
g, l = self.setupConfigNamespace(), {}
162
execfile(filename, g, l)
163
if not l.has_key('zone'):
164
raise ValueError, "No zone defined in " + filename
168
if isinstance(rr[1], dns.Record_SOA):
170
self.records.setdefault(rr[0].lower(), []).append(rr[1])
173
def wrapRecord(self, type):
174
return lambda name, *arg, **kw: (name, type(*arg, **kw))
177
def setupConfigNamespace(self):
179
items = dns.__dict__.iterkeys()
180
for record in [x for x in items if x.startswith('Record_')]:
181
type = getattr(dns, record)
182
f = self.wrapRecord(type)
183
r[record[len('Record_'):]] = f
187
class BindAuthority(FileAuthority):
188
"""An Authority that loads BIND configuration files"""
190
def loadFile(self, filename):
191
self.origin = os.path.basename(filename) + '.' # XXX - this might suck
192
lines = open(filename).readlines()
193
lines = self.stripComments(lines)
194
lines = self.collapseContinuations(lines)
195
self.parseLines(lines)
198
def stripComments(self, lines):
200
a.find(';') == -1 and a or a[:a.find(';')] for a in [
201
b.strip() for b in lines
206
def collapseContinuations(self, lines):
211
if line.find('(') == -1:
214
L.append(line[:line.find('(')])
217
if line.find(')') != -1:
218
L[-1] += ' ' + line[:line.find(')')]
225
L.append(line.split())
226
return filter(None, L)
229
def parseLines(self, lines):
235
for (line, index) in zip(lines, range(len(lines))):
236
if line[0] == '$TTL':
237
TTL = dns.str2time(line[1])
238
elif line[0] == '$ORIGIN':
240
elif line[0] == '$INCLUDE': # XXX - oh, fuck me
241
raise NotImplementedError('$INCLUDE directive not implemented')
242
elif line[0] == '$GENERATE':
243
raise NotImplementedError('$GENERATE directive not implemented')
245
self.parseRecordLine(ORIGIN, TTL, line)
248
def addRecord(self, owner, ttl, type, domain, cls, rdata):
249
if not domain.endswith('.'):
250
domain = domain + '.' + owner
253
f = getattr(self, 'class_%s' % cls, None)
255
f(ttl, type, domain, rdata)
257
raise NotImplementedError, "Record class %r not supported" % cls
260
def class_IN(self, ttl, type, domain, rdata):
261
record = getattr(dns, 'Record_%s' % type, None)
265
self.records.setdefault(domain.lower(), []).append(r)
267
print 'Adding IN Record', domain, ttl, r
269
self.soa = (domain, r)
271
raise NotImplementedError, "Record type %r not supported" % type
275
# This file ends here. Read no further.
277
def parseRecordLine(self, origin, ttl, line):
278
MARKERS = dns.QUERY_CLASSES.values() + dns.QUERY_TYPES.values()
285
# print 'default owner'
286
elif not line[0].isdigit() and line[0] not in MARKERS:
289
# print 'owner is ', owner
291
if line[0].isdigit() or line[0] in MARKERS:
294
# print 'woops, owner is ', owner, ' domain is ', domain
298
# print 'domain is ', domain
300
if line[0] in dns.QUERY_CLASSES.values():
303
# print 'cls is ', cls
304
if line[0].isdigit():
307
# print 'ttl is ', ttl
308
elif line[0].isdigit():
311
# print 'ttl is ', ttl
312
if line[0] in dns.QUERY_CLASSES.values():
315
# print 'cls is ', cls
318
# print 'type is ', type
320
# print 'rdata is ', rdata
322
self.addRecord(owner, ttl, type, domain, cls, rdata)