license: BSD
[zonemaker.git] / zonemaker / zone.py
index 4da0906cb3bdb7490430689b929b65733326c2ea..b543d31c3c6d0456491519e2c21296f88b953271 100644 (file)
@@ -1,3 +1,30 @@
+# Copyright (c) 2014, Ralf Jung <post@ralfj.de>
+# All rights reserved.
+# 
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions are met:
+# 
+# 1. Redistributions of source code must retain the above copyright notice, this
+#    list of conditions and the following disclaimer. 
+# 2. Redistributions in binary form must reproduce the above copyright notice,
+#    this list of conditions and the following disclaimer in the documentation
+#    and/or other materials provided with the distribution.
+# 
+# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
+# ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+# 
+# The views and conclusions contained in the software and documentation are those
+# of the authors and should not be interpreted as representing official policies, 
+# either expressed or implied, of the FreeBSD Project.
+
 import re, datetime
 #from typing import *
 
@@ -13,12 +40,14 @@ REGEX_ipv4  = r'^\d{1,3}(\.\d{1,3}){3}$'
 REGEX_ipv6  = r'^[a-fA-F0-9]{1,4}(:[a-fA-F0-9]{1,4}){7}$'
 
 def check_label(label: str) -> str:
+    label = str(label)
     pattern = r'^{0}$'.format(REGEX_label)
     if re.match(pattern, label):
         return label
     raise Exception(label+" is not a valid label")
 
 def check_hostname(name: str) -> str:
+    name = str(name)
     # check hostname for validity
     pattern = r'^{0}(\.{0})*\.?$'.format(REGEX_label)
     if re.match(pattern, name):
@@ -26,16 +55,19 @@ def check_hostname(name: str) -> str:
     raise Exception(name+" is not a valid hostname")
 
 def check_hex(data: str) -> str:
+    data = str(data)
     if re.match('^[a-fA-F0-9]+$', data):
         return data
     raise Exception(data+" is not valid hex data")
 
 def check_ipv4(address: str) -> str:
+    address = str(address)
     if re.match(REGEX_ipv4, address):
         return address
     raise Exception(address+" is not a valid IPv4 address")
 
 def check_ipv6(address: str) -> str:
+    address = str(address)
     if re.match(REGEX_ipv6, address):
         return address
     raise Exception(address+" is not a valid IPv6 address")
@@ -202,43 +234,34 @@ def SecureDelegation(name: str, tag: int, alg: int, digest: int, key: str) -> Na
 
 
 class Zone:
-    def __init__(self, name: str, serialfile: str, mail: str, NS: 'List[str]',
+    def __init__(self, name: str, serialfile: str, mail: str, NS: 'List[str]', TTLs: 'Dict[str, int]',
                  secondary_refresh: int, secondary_retry: int, secondary_expire: int,
-                 NX_TTL: int = None, A_TTL: int = None, other_TTL: int = None,
-                 domains: 'Dict[str, Any]' = {}) -> None:
-        self._serialfile = serialfile
-        
+                 domains: 'Dict[str, Any]') -> None:
         if not name.endswith('.'): raise Exception("Expected an absolute hostname")
         self._name = check_hostname(name)
+        self._serialfile = serialfile
+        
         if not mail.endswith('.'): raise Exception("Mail must be absolute, end with a dot")
         atpos = mail.find('@')
         if atpos < 0 or atpos > mail.find('.'): raise Exception("Mail must contain an @ before the first dot")
         self._mail = check_hostname(mail.replace('@', '.', 1))
         self._NS = list(map(check_hostname, NS))
+        if '' not in TTLs: raise Exception("Must give a default TTL with empty key")
+        self._TTLs = TTLs
         
         self._refresh = secondary_refresh
         self._retry = secondary_retry
         self._expire = secondary_expire
         
-        if other_TTL is None: raise Exception("Must give other_TTL")
-        self._NX_TTL = NX_TTL
-        self._A_TTL = self._AAAA_TTL = A_TTL
-        self._other_TTL = other_TTL
-        
         self._domains = domains
     
+    def getTTL(self, recordType: str) -> str:
+        return self._TTLs.get(recordType, self._TTLs[''])
+    
     def RR(self, owner: str, recordType: str, data: str) -> str:
         '''generate given RR, in textual representation'''
         assert re.match(r'^[A-Z]+$', recordType), "got invalid record type"
-        # figure out TTL
-        attrname = "_"+recordType+"_TTL"
-        TTL = None # type: int
-        if hasattr(self, attrname):
-            TTL = getattr(self, attrname)
-        if TTL is None:
-            TTL = self._other_TTL
-        # be done
-        return column_widths((self.abs_hostname(owner), time(TTL), recordType, data), (32, 8, 8))
+        return column_widths((self.abs_hostname(owner), time(self.getTTL(recordType)), recordType, data), (32, 8, 8))
     
     def abs_hostname(self, name):
         if name == '.' or name == '@':
@@ -253,7 +276,7 @@ class Zone:
         try:
             with open(self._serialfile) as f:
                 cur_serial = int(f.read())
-        except FileNotFoundError:
+        except (OSError, IOError): # FileNotFoundError has been added in Python 3.3
             pass
         # increment serial
         cur_serial += 1
@@ -271,7 +294,7 @@ class Zone:
                       ' ; primns mail serial refresh retry expire NX_TTL').format(
                           NS=self.abs_hostname(self._NS[0]), mail=self._mail, serial=serial,
                           refresh=time(self._refresh), retry=time(self._retry), expire=time(self._expire),
-                          NX_TTL=time(self._NX_TTL))
+                          NX_TTL=time(self.getTTL('NX')))
                       )
         # NS records
         for name in self._NS: