samba_dnsupdate: Always fill out the nameservers of a dns object.
[obnox/samba/samba-obnox.git] / source4 / scripting / bin / samba_dnsupdate
index 6729328d96de9b5a1a22ff04c96185524ddc650c..427b5dc869f1e42066116993d8ec35b262e653cb 100755 (executable)
@@ -1,4 +1,5 @@
 #!/usr/bin/env python
+# vim: expandtab
 #
 # update our DNS names using TSIG-GSS
 #
@@ -22,10 +23,17 @@ import os
 import fcntl
 import sys
 import tempfile
+import subprocess
 
 # ensure we get messages out immediately, so they get in the samba logs,
 # and don't get swallowed by a timeout
-os.putenv('PYTHONUNBUFFERED', '1')
+os.environ['PYTHONUNBUFFERED'] = '1'
+
+# forcing GMT avoids a problem in some timezones with kerberos. Both MIT
+# heimdal can get mutual authentication errors due to the 24 second difference
+# between UTC and GMT when using some zone files (eg. the PDT zone from
+# the US)
+os.environ["TZ"] = "GMT"
 
 # Find right directory when running from source tree
 sys.path.insert(0, "bin/python")
@@ -34,15 +42,18 @@ import samba
 import optparse
 from samba import getopt as options
 from ldb import SCOPE_BASE
+from samba import dsdb
 from samba.auth import system_session
 from samba.samdb import SamDB
 from samba.dcerpc import netlogon, winbind
 
-samba.ensure_external_module("dns", "dnspython")
-import dns.resolver as resolver
+samba.ensure_third_party_module("dns", "dnspython")
+import dns.resolver
+import dns.exception
 
 default_ttl = 900
 am_rodc = False
+error_count = 0
 
 parser = optparse.OptionParser("samba_dnsupdate")
 sambaopts = options.SambaOptions(parser)
@@ -52,6 +63,11 @@ parser.add_option("--verbose", action="store_true")
 parser.add_option("--all-names", action="store_true")
 parser.add_option("--all-interfaces", action="store_true")
 parser.add_option("--use-file", type="string", help="Use a file, rather than real DNS calls")
+parser.add_option("--update-list", type="string", help="Add DNS names from the given file")
+parser.add_option("--update-cache", type="string", help="Cache database of already registered records")
+parser.add_option("--fail-immediately", action='store_true', help="Exit on first failure")
+parser.add_option("--no-credentials", dest='nocreds', action='store_true', help="don't try and get credentials")
+parser.add_option("--no-substiutions", dest='nosubs', action='store_true', help="don't try and expands variables in file specified by --update-list")
 
 creds = None
 ccachename = None
@@ -78,12 +94,21 @@ if len(IPs) == 0:
     print "No IP interfaces - skipping DNS updates"
     sys.exit(0)
 
+IP6s = []
+IP4s = []
+for i in IPs:
+    if i.find(':') != -1:
+        IP6s.append(i)
+    else:
+        IP4s.append(i)
+
+
 if opts.verbose:
     print "IPs: %s" % IPs
 
-########################################################
-# get credentials if we haven't got them already
+
 def get_credentials(lp):
+    """# get credentials if we haven't got them already."""
     from samba import credentials
     global ccachename, creds
     if creds is not None:
@@ -93,14 +118,20 @@ def get_credentials(lp):
     creds.set_machine_account(lp)
     creds.set_krb_forwardable(credentials.NO_KRB_FORWARDABLE)
     (tmp_fd, ccachename) = tempfile.mkstemp()
-    creds.get_named_ccache(lp, ccachename)
+    try:
+        creds.get_named_ccache(lp, ccachename)
+    except RuntimeError as e:
+        os.unlink(ccachename)
+        raise e
 
 
-#############################################
-# an object to hold a parsed DNS line
 class dnsobj(object):
+    """an object to hold a parsed DNS line"""
+
     def __init__(self, string_form):
         list = string_form.split()
+        if len(list) < 3:
+            raise Exception("Invalid DNS entry %r" % string_form)
         self.dest = None
         self.port = None
         self.ip = None
@@ -108,51 +139,66 @@ class dnsobj(object):
         self.existing_weight = None
         self.type = list[0]
         self.name = list[1]
+        self.nameservers = []
         if self.type == 'SRV':
+            if len(list) < 4:
+                raise Exception("Invalid DNS entry %r" % string_form)
             self.dest = list[2]
             self.port = list[3]
-        elif self.type == 'A':
+        elif self.type in ['A', 'AAAA']:
             self.ip   = list[2] # usually $IP, which gets replaced
         elif self.type == 'CNAME':
             self.dest = list[2]
+        elif self.type == 'NS':
+            self.dest = list[2]
         else:
-            print "Received unexpected DNS reply of type %s" % self.type
-            raise
+            raise Exception("Received unexpected DNS reply of type %s: %s" % (self.type, string_form))
 
     def __str__(self):
-        if d.type == "A":     return "%s %s %s" % (self.type, self.name, self.ip)
-        if d.type == "SRV":   return "%s %s %s %s" % (self.type, self.name, self.dest, self.port)
-        if d.type == "CNAME": return "%s %s %s" % (self.type, self.name, self.dest)
+        if self.type == "A":
+            return "%s %s %s" % (self.type, self.name, self.ip)
+        if self.type == "AAAA":
+            return "%s %s %s" % (self.type, self.name, self.ip)
+        if self.type == "SRV":
+            return "%s %s %s %s" % (self.type, self.name, self.dest, self.port)
+        if self.type == "CNAME":
+            return "%s %s %s" % (self.type, self.name, self.dest)
+        if self.type == "NS":
+            return "%s %s %s" % (self.type, self.name, self.dest)
 
 
-################################################
-# parse a DNS line from
 def parse_dns_line(line, sub_vars):
+    """parse a DNS line from."""
+    if line.startswith("SRV _ldap._tcp.pdc._msdcs.") and not samdb.am_pdc():
+        # We keep this as compat to the dns_update_list of 4.0/4.1
+        if opts.verbose:
+            print "Skipping PDC entry (%s) as we are not a PDC" % line
+        return None
     subline = samba.substitute_var(line, sub_vars)
-    d = dnsobj(subline)
-    return d
+    if subline == '' or subline[0] == "#":
+        return None
+    return dnsobj(subline)
+
 
-############################################
-# see if two hostnames match
 def hostname_match(h1, h2):
+    """see if two hostnames match."""
     h1 = str(h1)
     h2 = str(h2)
     return h1.lower().rstrip('.') == h2.lower().rstrip('.')
 
 
-############################################
-# check that a DNS entry exists
 def check_dns_name(d):
+    """check that a DNS entry exists."""
     normalised_name = d.name.rstrip('.') + '.'
     if opts.verbose:
         print "Looking for DNS entry %s as %s" % (d, normalised_name)
+
     if opts.use_file is not None:
         try:
             dns_file = open(opts.use_file, "r")
         except IOError:
             return False
-        
+
         for line in dns_file:
             line = line.strip()
             if line == '' or line[0] == "#":
@@ -161,20 +207,33 @@ def check_dns_name(d):
                 return True
         return False
 
+    resolver = dns.resolver.Resolver()
+
+    if d.nameservers != []:
+        resolver.nameservers = d.nameservers
+    else:
+        d.nameservers = resolver.nameservers
+
     try:
         ans = resolver.query(normalised_name, d.type)
-    except resolver.NXDOMAIN:
+    except dns.exception.DNSException:
+        if opts.verbose:
+            print "Failed to find DNS entry %s" % d
         return False
-    if d.type == 'A':
+    if d.type in ['A', 'AAAA']:
         # we need to be sure that our IP is there
         for rdata in ans:
             if str(rdata) == str(d.ip):
                 return True
-    if d.type == 'CNAME':
+    elif d.type == 'CNAME':
+        for i in range(len(ans)):
+            if hostname_match(ans[i].target, d.dest):
+                return True
+    elif d.type == 'NS':
         for i in range(len(ans)):
             if hostname_match(ans[i].target, d.dest):
                 return True
-    if d.type == 'SRV':
+    elif d.type == 'SRV':
         for rdata in ans:
             if opts.verbose:
                 print "Checking %s against %s" % (rdata, d)
@@ -184,110 +243,238 @@ def check_dns_name(d):
                 else:
                     d.existing_port     = str(rdata.port)
                     d.existing_weight = str(rdata.weight)
+
     if opts.verbose:
-        print "Failed to find DNS entry %s" % d
+        print "Failed to find matching DNS entry %s" % d
 
     return False
 
 
-###########################################
-# get the list of substitution vars
-def get_subst_vars():
+def get_subst_vars(samdb):
+    """get the list of substitution vars."""
     global lp, am_rodc
     vars = {}
 
-    samdb = SamDB(url=lp.get("sam database"), session_info=system_session(),
-                  lp=lp)
-
-    vars['DNSDOMAIN'] = lp.get('realm').lower()
-    vars['DNSFOREST'] = lp.get('realm').lower()
-    vars['HOSTNAME']  = lp.get('netbios name').lower() + "." + vars['DNSDOMAIN']
+    vars['DNSDOMAIN'] = samdb.domain_dns_name()
+    vars['DNSFOREST'] = samdb.forest_dns_name()
+    vars['HOSTNAME']  = samdb.host_dns_name()
     vars['NTDSGUID']  = samdb.get_ntds_GUID()
     vars['SITE']      = samdb.server_site_name()
-    res = samdb.search(base=None, scope=SCOPE_BASE, attrs=["objectGUID"])
+    res = samdb.search(base=samdb.get_default_basedn(), scope=SCOPE_BASE, attrs=["objectGUID"])
     guid = samdb.schema_format_value("objectGUID", res[0]['objectGUID'][0])
     vars['DOMAINGUID'] = guid
+
+    vars['IF_DC'] = ""
+    vars['IF_RWDC'] = "# "
+    vars['IF_RODC'] = "# "
+    vars['IF_PDC'] = "# "
+    vars['IF_GC'] = "# "
+    vars['IF_RWGC'] = "# "
+    vars['IF_ROGC'] = "# "
+    vars['IF_DNS_DOMAIN'] = "# "
+    vars['IF_RWDNS_DOMAIN'] = "# "
+    vars['IF_RODNS_DOMAIN'] = "# "
+    vars['IF_DNS_FOREST'] = "# "
+    vars['IF_RWDNS_FOREST'] = "# "
+    vars['IF_R0DNS_FOREST'] = "# "
+
     am_rodc = samdb.am_rodc()
+    if am_rodc:
+        vars['IF_RODC'] = ""
+    else:
+        vars['IF_RWDC'] = ""
+
+    if samdb.am_pdc():
+        vars['IF_PDC'] = ""
+
+    # check if we "are DNS server"
+    res = samdb.search(base=samdb.get_config_basedn(),
+                   expression='(objectguid=%s)' % vars['NTDSGUID'],
+                   attrs=["options", "msDS-hasMasterNCs"])
+
+    if len(res) == 1:
+        if "options" in res[0]:
+            options = int(res[0]["options"][0])
+            if (options & dsdb.DS_NTDSDSA_OPT_IS_GC) != 0:
+                vars['IF_GC'] = ""
+                if am_rodc:
+                    vars['IF_ROGC'] = ""
+                else:
+                    vars['IF_RWGC'] = ""
+
+        basedn = str(samdb.get_default_basedn())
+        forestdn = str(samdb.get_root_basedn())
+
+        if "msDS-hasMasterNCs" in res[0]:
+            for e in res[0]["msDS-hasMasterNCs"]:
+                if str(e) == "DC=DomainDnsZones,%s" % basedn:
+                    vars['IF_DNS_DOMAIN'] = ""
+                    if am_rodc:
+                        vars['IF_RODNS_DOMAIN'] = ""
+                    else:
+                        vars['IF_RWDNS_DOMAIN'] = ""
+                if str(e) == "DC=ForestDnsZones,%s" % forestdn:
+                    vars['IF_DNS_FOREST'] = ""
+                    if am_rodc:
+                        vars['IF_RODNS_FOREST'] = ""
+                    else:
+                        vars['IF_RWDNS_FOREST'] = ""
 
     return vars
 
 
-############################################
-# call nsupdate for an entry
-def call_nsupdate(d):
-    global ccachename, nsupdate_cmd
+def call_nsupdate(d, op="add"):
+    """call nsupdate for an entry."""
+    global ccachename, nsupdate_cmd, krb5conf
+
+    assert(op in ["add", "delete"])
 
     if opts.verbose:
-        print "Calling nsupdate for %s" % d
+        print "Calling nsupdate for %s (%s)" % (d, op)
 
     if opts.use_file is not None:
-        wfile = open(opts.use_file, 'a')
-        fcntl.lockf(wfile, fcntl.LOCK_EX)
-        wfile.write(str(d)+"\n")
-        fcntl.lockf(wfile, fcntl.LOCK_UN)
+        try:
+            rfile = open(opts.use_file, 'r+')
+        except IOError:
+            # Perhaps create it
+            rfile = open(opts.use_file, 'w+')
+            # Open it for reading again, in case someone else got to it first
+            rfile = open(opts.use_file, 'r+')
+        fcntl.lockf(rfile, fcntl.LOCK_EX)
+        (file_dir, file_name) = os.path.split(opts.use_file)
+        (tmp_fd, tmpfile) = tempfile.mkstemp(dir=file_dir, prefix=file_name, suffix="XXXXXX")
+        wfile = os.fdopen(tmp_fd, 'a')
+        rfile.seek(0)
+        for line in rfile:
+            if op == "delete":
+                l = parse_dns_line(line, {})
+                if str(l).lower() == str(d).lower():
+                    continue
+            wfile.write(line)
+        if op == "add":
+            wfile.write(str(d)+"\n")
+        os.rename(tmpfile, opts.use_file)
+        fcntl.lockf(rfile, fcntl.LOCK_UN)
         return
 
+    normalised_name = d.name.rstrip('.') + '.'
+
     (tmp_fd, tmpfile) = tempfile.mkstemp()
     f = os.fdopen(tmp_fd, 'w')
+    if d.nameservers != []:
+        f.write('server %s\n' % d.nameservers[0])
     if d.type == "A":
-        f.write("update add %s %u A %s\n" % (d.name, default_ttl, d.ip))
+        f.write("update %s %s %u A %s\n" % (op, normalised_name, default_ttl, d.ip))
+    if d.type == "AAAA":
+        f.write("update %s %s %u AAAA %s\n" % (op, normalised_name, default_ttl, d.ip))
     if d.type == "SRV":
-        if d.existing_port is not None:
-            f.write("update delete %s SRV 0 %s %s %s\n" % (d.name, d.existing_weight,
+        if op == "add" and d.existing_port is not None:
+            f.write("update delete %s SRV 0 %s %s %s\n" % (normalised_name, d.existing_weight,
                                                            d.existing_port, d.dest))
-        f.write("update add %s %u SRV 0 100 %s %s\n" % (d.name, default_ttl, d.port, d.dest))
+        f.write("update %s %s %u SRV 0 100 %s %s\n" % (op, normalised_name, default_ttl, d.port, d.dest))
     if d.type == "CNAME":
-        f.write("update add %s %u CNAME %s\n" % (d.name, default_ttl, d.dest))
+        f.write("update %s %s %u CNAME %s\n" % (op, normalised_name, default_ttl, d.dest))
+    if d.type == "NS":
+        f.write("update %s %s %u NS %s\n" % (op, normalised_name, default_ttl, d.dest))
     if opts.verbose:
         f.write("show\n")
     f.write("send\n")
     f.close()
 
-    os.putenv("KRB5CCNAME", ccachename)
-    os.system("%s %s" % (nsupdate_cmd, tmpfile))
+    global error_count
+    if ccachename:
+        os.environ["KRB5CCNAME"] = ccachename
+    try:
+        cmd = nsupdate_cmd[:]
+        cmd.append(tmpfile)
+        env = {}
+        if krb5conf:
+            env["KRB5_CONFIG"] = krb5conf
+        if ccachename:
+            env["KRB5CCNAME"] = ccachename
+        ret = subprocess.call(cmd, shell=False, env=env)
+        if ret != 0:
+            if opts.fail_immediately:
+                if opts.verbose:
+                    print("Failed update with %s" % tmpfile)
+                sys.exit(1)
+            error_count = error_count + 1
+            if opts.verbose:
+                print("Failed nsupdate: %d" % ret)
+    except Exception, estr:
+        if opts.fail_immediately:
+            sys.exit(1)
+        error_count = error_count + 1
+        if opts.verbose:
+            print("Failed nsupdate: %s : %s" % (str(d), estr))
     os.unlink(tmpfile)
 
 
 
-def rodc_dns_update(d, t):
+def rodc_dns_update(d, t, op):
     '''a single DNS update via the RODC netlogon call'''
     global sub_vars
 
+    assert(op in ["add", "delete"])
+
     if opts.verbose:
         print "Calling netlogon RODC update for %s" % d
 
+    typemap = {
+        netlogon.NlDnsLdapAtSite       : netlogon.NlDnsInfoTypeNone,
+        netlogon.NlDnsGcAtSite         : netlogon.NlDnsDomainNameAlias,
+        netlogon.NlDnsDsaCname         : netlogon.NlDnsDomainNameAlias,
+        netlogon.NlDnsKdcAtSite        : netlogon.NlDnsInfoTypeNone,
+        netlogon.NlDnsDcAtSite         : netlogon.NlDnsInfoTypeNone,
+        netlogon.NlDnsRfc1510KdcAtSite : netlogon.NlDnsInfoTypeNone,
+        netlogon.NlDnsGenericGcAtSite  : netlogon.NlDnsDomainNameAlias
+        }
+
     w = winbind.winbind("irpc:winbind_server", lp)
     dns_names = netlogon.NL_DNS_NAME_INFO_ARRAY()
     dns_names.count = 1
     name = netlogon.NL_DNS_NAME_INFO()
     name.type = t
+    name.dns_domain_info_type = typemap[t]
     name.priority = 0
     name.weight   = 0
     if d.port is not None:
         name.port = int(d.port)
-    name.dns_register = True
+    if op == "add":
+        name.dns_register = True
+    else:
+        name.dns_register = False
     dns_names.names = [ name ]
     site_name = sub_vars['SITE'].decode('utf-8')
 
+    global error_count
+
     try:
         ret_names = w.DsrUpdateReadOnlyServerDnsRecords(site_name, default_ttl, dns_names)
         if ret_names.names[0].status != 0:
             print("Failed to set DNS entry: %s (status %u)" % (d, ret_names.names[0].status))
-    except:
-        print("Error setting DNS entry: %s" % d)
+            error_count = error_count + 1
+    except RuntimeError, reason:
+        print("Error setting DNS entry of type %u: %s: %s" % (t, d, reason))
+        error_count = error_count + 1
+
+    if error_count != 0 and opts.fail_immediately:
+        sys.exit(1)
 
 
-def call_rodc_update(d):
+def call_rodc_update(d, op="add"):
     '''RODCs need to use the netlogon API for nsupdate'''
     global lp, sub_vars
 
+    assert(op in ["add", "delete"])
+
     # we expect failure for 3268 if we aren't a GC
     if d.port is not None and int(d.port) == 3268:
         return
 
     # map the DNS request to a netlogon update type
     map = {
-        netlogon.NlDnsLdapAtSite :     '_ldap._tcp.${SITE}._sites.${DNSDOMAIN}',
+        netlogon.NlDnsLdapAtSite       : '_ldap._tcp.${SITE}._sites.${DNSDOMAIN}',
         netlogon.NlDnsGcAtSite         : '_ldap._tcp.${SITE}._sites.gc._msdcs.${DNSDOMAIN}',
         netlogon.NlDnsDsaCname         : '${NTDSGUID}._msdcs.${DNSFOREST}',
         netlogon.NlDnsKdcAtSite        : '_kerberos._tcp.${SITE}._sites.dc._msdcs.${DNSDOMAIN}',
@@ -300,23 +487,66 @@ def call_rodc_update(d):
         subname = samba.substitute_var(map[t], sub_vars)
         if subname.lower() == d.name.lower():
             # found a match - do the update
-            rodc_dns_update(d, t)
+            rodc_dns_update(d, t, op)
             return
     if opts.verbose:
         print("Unable to map to netlogon DNS update: %s" % d)
 
 
 # get the list of DNS entries we should have
-dns_update_list = lp.private_path('dns_update_list')
+if opts.update_list:
+    dns_update_list = opts.update_list
+else:
+    dns_update_list = lp.private_path('dns_update_list')
+
+if opts.update_cache:
+    dns_update_cache = opts.update_cache
+else:
+    dns_update_cache = lp.private_path('dns_update_cache')
+
+# use our private krb5.conf to avoid problems with the wrong domain
+# bind9 nsupdate wants the default domain set
+krb5conf = lp.private_path('krb5.conf')
+os.environ['KRB5_CONFIG'] = krb5conf
 
 file = open(dns_update_list, "r")
 
-# get the substitution dictionary
-sub_vars = get_subst_vars()
+if opts.nosubs:
+    sub_vars = {}
+else:
+    samdb = SamDB(url=lp.samdb_url(), session_info=system_session(), lp=lp)
+
+    # get the substitution dictionary
+    sub_vars = get_subst_vars(samdb)
 
 # build up a list of update commands to pass to nsupdate
 update_list = []
 dns_list = []
+cache_list = []
+delete_list = []
+
+dup_set = set()
+cache_set = set()
+
+rebuild_cache = False
+try:
+    cfile = open(dns_update_cache, 'r+')
+except IOError:
+    # Perhaps create it
+    cfile = open(dns_update_cache, 'w+')
+    # Open it for reading again, in case someone else got to it first
+    cfile = open(dns_update_cache, 'r+')
+fcntl.lockf(cfile, fcntl.LOCK_EX)
+for line in cfile:
+    line = line.strip()
+    if line == '' or line[0] == "#":
+        continue
+    c = parse_dns_line(line, {})
+    if c is None:
+        continue
+    if str(c) not in cache_set:
+        cache_list.append(c)
+        cache_set.add(str(c))
 
 # read each line, and check that the DNS name exists
 for line in file:
@@ -324,38 +554,106 @@ for line in file:
     if line == '' or line[0] == "#":
         continue
     d = parse_dns_line(line, sub_vars)
-    dns_list.append(d)
+    if d is None:
+        continue
+    if d.type == 'A' and len(IP4s) == 0:
+        continue
+    if d.type == 'AAAA' and len(IP6s) == 0:
+        continue
+    if str(d) not in dup_set:
+        dns_list.append(d)
+        dup_set.add(str(d))
 
 # now expand the entries, if any are A record with ip set to $IP
 # then replace with multiple entries, one for each interface IP
 for d in dns_list:
-    if d.type == 'A' and d.ip == "$IP":
-        d.ip = IPs[0]
-        for i in range(len(IPs)-1):
-            d2 = d
-            d2.ip = IPs[i+1]
+    if d.ip != "$IP":
+        continue
+    if d.type == 'A':
+        d.ip = IP4s[0]
+        for i in range(len(IP4s)-1):
+            d2 = dnsobj(str(d))
+            d2.ip = IP4s[i+1]
+            dns_list.append(d2)
+    if d.type == 'AAAA':
+        d.ip = IP6s[0]
+        for i in range(len(IP6s)-1):
+            d2 = dnsobj(str(d))
+            d2.ip = IP6s[i+1]
             dns_list.append(d2)
 
 # now check if the entries already exist on the DNS server
 for d in dns_list:
+    found = False
+    for c in cache_list:
+        if str(c).lower() == str(d).lower():
+            found = True
+            break
+    if not found:
+        rebuild_cache = True
     if opts.all_names or not check_dns_name(d):
         update_list.append(d)
 
-if len(update_list) == 0:
+for c in cache_list:
+    found = False
+    for d in dns_list:
+        if str(c).lower() == str(d).lower():
+            found = True
+            break
+    if found:
+        continue
+    rebuild_cache = True
+    if not opts.all_names and not check_dns_name(c):
+        continue
+    delete_list.append(c)
+
+if len(delete_list) == 0 and len(update_list) == 0 and not rebuild_cache:
     if opts.verbose:
         print "No DNS updates needed"
     sys.exit(0)
 
 # get our krb5 creds
-get_credentials(lp)
+if len(delete_list) != 0 or len(update_list) != 0:
+    if not opts.nocreds:
+        get_credentials(lp)
+
+# ask nsupdate to delete entries as needed
+for d in delete_list:
+    if am_rodc:
+        if d.name.lower() == domain.lower():
+            continue
+        if not d.type in [ 'A', 'AAAA' ]:
+            call_rodc_update(d, op="delete")
+        else:
+            call_nsupdate(d, op="delete")
+    else:
+        call_nsupdate(d, op="delete")
 
 # ask nsupdate to add entries as needed
 for d in update_list:
     if am_rodc:
-        call_rodc_update(d)
+        if d.name.lower() == domain.lower():
+            continue
+        if not d.type in [ 'A', 'AAAA' ]:
+            call_rodc_update(d)
+        else:
+            call_nsupdate(d)
     else:
         call_nsupdate(d)
 
+if rebuild_cache:
+    (file_dir, file_name) = os.path.split(dns_update_cache)
+    (tmp_fd, tmpfile) = tempfile.mkstemp(dir=file_dir, prefix=file_name, suffix="XXXXXX")
+    wfile = os.fdopen(tmp_fd, 'a')
+    for d in dns_list:
+        wfile.write(str(d)+"\n")
+    os.rename(tmpfile, dns_update_cache)
+fcntl.lockf(cfile, fcntl.LOCK_UN)
+
 # delete the ccache if we created it
 if ccachename is not None:
     os.unlink(ccachename)
+
+if error_count != 0:
+    print("Failed update of %u entries" % error_count)
+sys.exit(error_count)