2 from ipaddress import IPv4Address, IPv6Address
3 from typing import List, Dict, Any, Iterator, Tuple, Sequence
15 def check_hostname(name: str) -> str:
16 # check hostname for validity
17 label = r'[a-zA-Z90-9]([a-zA-Z90-9-]{0,61}[a-zA-Z90-9])?' # must not start or end with hyphen
18 pattern = r'^{0}(\.{0})*\.?'.format(label)
19 if re.match(pattern, name):
21 raise Exception(name+" is not a valid hostname")
23 def time(time: int) -> str:
26 elif time % week == 0:
27 return str(time//week)+"w"
29 return str(time//day)+"d"
30 elif time % hour == 0:
31 return str(time//hour)+"h"
32 elif time % minute == 0:
33 return str(time//minute)+"m"
37 def column_widths(datas: Sequence, widths: Sequence[int]):
38 assert len(datas) == len(widths)+1, "There must be as one more data points as widths"
41 for data, width in zip(datas, widths): # will *not* cover the last point
42 result += str(data)+" " # add data point, and a minimal space
44 if len(result) < width_sum: # add padding
45 result += (width_sum - len(result))*" "
47 return result+str(datas[-1])
52 def __init__(self, address: str) -> None:
53 self._address = IPv4Address(address)
55 def generate_rr(self, owner: str, zone: 'Zone') -> Any:
56 return zone.RR(owner, 'A', self._address)
60 def __init__(self, address: str) -> None:
61 self._address = IPv6Address(address)
63 def generate_rr(self, owner: str, zone: 'Zone') -> Any:
64 return zone.RR(owner, 'AAAA', self._address)
68 def __init__(self, name: str, prio: int = 10) -> None:
69 self._priority = int(prio)
70 self._name = check_hostname(name)
72 def generate_rr(self, owner: str, zone: 'Zone') -> Any:
73 return zone.RR(owner, 'MX', '{0} {1}'.format(self._priority, zone.abs_hostname(self._name)))
77 def __init__(self, protocol: str, service: str, name: str, port: int, prio: int, weight: int) -> None:
78 self._service = str(service)
79 self._protocol = str(protocol)
80 self._priority = int(prio)
81 self._weight = int(weight)
82 self._port = int(port)
83 self._name = check_hostname(name)
85 def generate_rr(self, owner: str, zone: 'Zone') -> Any:
86 return zone.RR('_{0}._{1}.{2}'.format(self._service, self._protocol, owner), 'SRV',
87 '{0} {1} {2} {3}'.format(self._priority, self._weight, self._port, zone.abs_hostname(self._name)))
91 def __init__(self, protocol: str, port: int, key: str) -> None:
93 self._port = int(port)
94 self._protocol = str(protocol)
97 def generate_rr(self, owner: str, zone: 'Zone') -> Any:
98 return zone.RR('_{0}._{1}.{2}'.format(self._port, self._protocol, owner), 'TLSA', self._key)
102 def __init__(self, name: str) -> None:
103 self._name = check_hostname(name)
105 def generate_rr(self, owner: str, zone: 'Zone') -> Any:
106 return zone.RR(owner, 'CNAME', zone.abs_hostname(self._name))
110 def __init__(self, name: str) -> None:
111 self._name = check_hostname(name)
113 def generate_rr(self, owner: str, zone: 'Zone') -> Any:
114 return zone.RR(owner, 'NS', zone.abs_hostname(self._name))
118 def __init__(self, key: str) -> None:
119 # TODO: fix key stuff
122 def generate_rr(self, owner: str, zone: 'Zone') -> Any:
123 return zone.RR(owner, 'DS', self._key)
125 ## Higher-level classes
127 def __init__(self, *records: List[Any]) -> None:
128 self._records = records
130 def generate_rrs(self, owner: str, zone: 'Zone') -> Iterator:
131 for record in self._records:
132 # this could still be a list
133 if isinstance(record, list):
134 for subrecord in record:
135 yield subrecord.generate_rr(owner, zone)
137 yield record.generate_rr(owner, zone)
140 def CName(name: str) -> Name:
141 return Name(CNAME(name))
144 def Delegation(name: str, key: str = None) -> Name:
147 records.append(DS(key))
148 return Name(*records)
152 def __init__(self, name: str, serialfile: str, dbfile: str, mail: str, NS: List[str],
153 secondary_refresh: int, secondary_retry: int, secondary_expire: int,
154 NX_TTL: int = None, A_TTL: int = None, other_TTL: int = None,
155 domains: Dict[str, Any] = {}) -> None:
156 self._serialfile = serialfile
157 self._dbfile = dbfile
159 if not name.endswith('.'): raise Exception("Expected an absolute hostname")
160 self._name = check_hostname(name)
161 if not mail.endswith('.'): raise Exception("Mail must be absolute, end with a dot")
162 atpos = mail.find('@')
163 if atpos < 0 or atpos > mail.find('.'): raise Exception("Mail must contain an @ before the first dot")
164 self._mail = check_hostname(mail.replace('@', '.', 1))
165 self._NS = list(map(check_hostname, NS))
167 self._refresh = secondary_refresh
168 self._retry = secondary_retry
169 self._expire = secondary_expire
171 if other_TTL is None: raise Exception("Must give other_TTL")
172 self._NX_TTL = NX_TTL
173 self._A_TTL = self._AAAA_TTL = A_TTL
174 self._other_TTL = other_TTL
176 self._domains = domains
178 def RR(self, owner: str, recordType: str, data: str) -> str:
179 '''generate given RR, in textual representation'''
180 assert re.match(r'^[A-Z]+$', recordType), "got invalid record type"
182 attrname = "_"+recordType+"_TTL"
183 TTL = None # type: int
184 if hasattr(self, attrname):
185 TTL = getattr(self, attrname)
187 TTL = self._other_TTL
189 return column_widths((self.abs_hostname(owner), time(TTL), recordType, data), (32, 8, 8))
191 def abs_hostname(self, name):
192 if name == '.' or name == '@':
194 if name.endswith('.'):
196 return name+"."+self._name
198 def inc_serial(self) -> int:
202 with open(self._serialfile) as f:
203 cur_serial = int(f.read())
204 except FileNotFoundError:
209 with open(self._serialfile, 'w') as f:
210 f.write(str(cur_serial))
214 def generate_rrs(self) -> Iterator:
216 serial = self.inc_serial()
217 yield self.RR(self._name, 'SOA',
218 ('{NS} {mail} ({serial} {refresh} {retry} {expire} {NX_TTL}) ; '+
219 '(serial refresh retry expire NX_TTL)').format(
220 NS=self.abs_hostname(self._NS[0]), mail=self._mail, serial=serial,
221 refresh=time(self._refresh), retry=time(self._retry), expire=time(self._expire),
222 NX_TTL=time(self._NX_TTL))
225 for name in self._NS:
226 yield NS(name).generate_rr(self._name, self)
228 for name in sorted(self._domains.keys(), key=lambda s: list(reversed(s.split('.')))):
229 for rr in self._domains[name].generate_rrs(name, self):
232 def write(self) -> None:
233 with open(self._dbfile, 'w') as f:
234 for rr in self.generate_rrs():