2 from ipaddress import IPv4Address, IPv6Address
3 from typing import List, Dict, Any, Iterator
12 def check_hostname(name: str) -> str:
13 # check hostname for validity
14 label = r'[a-zA-Z90-9]([a-zA-Z90-9-]{0,61}[a-zA-Z90-9])?' # must not start or end with hyphen
15 pattern = r'^{0}(\.{0})*\.?'.format(label)
16 if re.match(pattern, name):
18 raise Exception(name+" is not a valid hostname")
20 def time(time: int) -> str:
23 elif time % week == 0:
24 return str(time//week)+"w"
26 return str(time//day)+"d"
27 elif time % hour == 0:
28 return str(time//hour)+"h"
29 elif time % minute == 0:
30 return str(time//minute)+"m"
35 # mypy does not know about the ipaddress types, so leave this class unannotated for now
36 def __init__(self, IPv4 = None, IPv6 = None) -> None:
37 if IPv4 is None and IPv6 is None:
38 raise Exception("There has to be at least one valid address!")
39 self._IPv4 = None if IPv4 is None else IPv4Address(IPv4)
40 self._IPv6 = None if IPv6 is None else IPv6Address(IPv6)
43 return Address(IPv4 = self._IPv4)
46 return Address(IPv6 = self._IPv6)
48 def generate_rrs(self, owner: str, zone: 'Zone') -> Iterator:
49 if self._IPv4 is not None:
50 yield zone.RR(owner, 'A', self._IPv4)
51 if self._IPv6 is not None:
52 yield zone.RR(owner, 'AAAA', self._IPv6)
55 def __init__(self, address: Address = None, MX: List = None,
56 TCP: Dict[int, Any] = None, UDP: Dict[int, Any] = None) -> None:
57 self._address = address
59 def generate_rrs(self, owner: str, zone: 'Zone') -> Iterator:
60 if self._address is not None:
61 for rr in self._address.generate_rrs(owner, zone):
66 def __init__(self, SRV: str = None, TLSA: str=None) -> None:
67 self._SRV = None if SRV is None else check_hostname(SRV)
71 def __init__(self, name: str) -> None:
72 self._name = check_hostname(name)
74 def generate_rrs(self, owner: str, zone: 'Zone') -> Iterator:
75 yield zone.RR(owner, 'CNAME', zone.abs_hostname(self._name))
78 def __init__(self, NS: str, DS: str = None) -> None:
82 def generate_rrs(self, owner: str, zone: 'Zone') -> Iterator:
83 yield zone.RR(owner, 'NS', zone.abs_hostname(self._NS))
87 def __init__(self, name: str, serialfile: str, dbfile: str, mail: str, NS: List[str],
88 secondary_refresh: int, secondary_retry: int, secondary_expire: int,
89 NX_TTL: int = None, A_TTL: int = None, other_TTL: int = None,
90 domains: Dict[str, Any] = {}) -> None:
91 self._serialfile = serialfile
94 if not name.endswith('.'): raise Exception("Expected an absolute hostname")
95 self._name = check_hostname(name)
96 if not mail.endswith('.'): raise Exception("Mail must be absolute, end with a dot")
97 atpos = mail.find('@')
98 if atpos < 0 or atpos > mail.find('.'): raise Exception("Mail must contain an @ before the first dot")
99 self._mail = check_hostname(mail.replace('@', '.', 1))
100 self._NS = list(map(check_hostname, NS))
102 self._refresh = secondary_refresh
103 self._retry = secondary_retry
104 self._expire = secondary_expire
106 if other_TTL is None: raise Exception("Must give other_TTL")
107 self._NX_TTL = NX_TTL
108 self._A_TTL = self._AAAA_TTL = A_TTL
109 self._other_TTL = other_TTL
111 self._domains = domains
113 def RR(self, owner: str, recordType: str, data: str) -> str:
114 '''generate given RR, in textual representation'''
115 assert re.match(r'^[A-Z]+$', recordType), "got invalid record type"
117 attrname = "_"+recordType+"_TTL"
118 TTL = None # type: int
119 if hasattr(self, attrname):
120 TTL = getattr(self, attrname)
122 TTL = self._other_TTL
124 return "{0:<31} {1:<7} {2:<7} {3}".format(self.abs_hostname(owner), TTL, recordType, data)
126 def abs_hostname(self, name):
127 if name.endswith('.'):
129 return name+"."+self._name
131 def inc_serial(self) -> int:
135 with open(self._serialfile) as f:
136 cur_serial = int(f.read())
137 except FileNotFoundError:
142 with open(self._serialfile, 'w') as f:
143 f.write(str(cur_serial))
147 def generate_rrs(self) -> Iterator:
149 serial = self.inc_serial()
150 yield self.RR(self._name, 'SOA',
151 ('{NS} {mail} ({serial} {refresh} {retry} {expire} {NX_TTL}) ; '+
152 '(serial refresh retry expire NX_TTL)').format(
153 NS=self.abs_hostname(self._NS[0]), mail=self._mail, serial=serial,
154 refresh=time(self._refresh), retry=time(self._retry), expire=time(self._expire),
155 NX_TTL=time(self._NX_TTL))
159 yield self.RR(self._name, 'NS', self.abs_hostname(ns))
162 for name in sorted(self._domains.keys(), key=lambda s: list(reversed(s.split('.')))):
163 for rr in self._domains[name].generate_rrs(name, self):
166 def write(self) -> None:
167 with open(self._dbfile, 'w') as f:
168 for rr in self.generate_rrs():