samba_dnsupdate: Fix typo in -no-substitutions name
[kai/samba-autobuild/.git] / source4 / scripting / bin / samba_dnsupdate
1 #!/usr/bin/env python
2 # vim: expandtab
3 #
4 # update our DNS names using TSIG-GSS
5 #
6 # Copyright (C) Andrew Tridgell 2010
7 #
8 # This program is free software; you can redistribute it and/or modify
9 # it under the terms of the GNU General Public License as published by
10 # the Free Software Foundation; either version 3 of the License, or
11 # (at your option) any later version.
12 #
13 # This program is distributed in the hope that it will be useful,
14 # but WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 # GNU General Public License for more details.
17 #
18 # You should have received a copy of the GNU General Public License
19 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
20
21
22 import os
23 import fcntl
24 import sys
25 import tempfile
26 import subprocess
27
28 # ensure we get messages out immediately, so they get in the samba logs,
29 # and don't get swallowed by a timeout
30 os.environ['PYTHONUNBUFFERED'] = '1'
31
32 # forcing GMT avoids a problem in some timezones with kerberos. Both MIT
33 # heimdal can get mutual authentication errors due to the 24 second difference
34 # between UTC and GMT when using some zone files (eg. the PDT zone from
35 # the US)
36 os.environ["TZ"] = "GMT"
37
38 # Find right directory when running from source tree
39 sys.path.insert(0, "bin/python")
40
41 import samba
42 import optparse
43 from samba import getopt as options
44 from ldb import SCOPE_BASE
45 from samba import dsdb
46 from samba.auth import system_session
47 from samba.samdb import SamDB
48 from samba.dcerpc import netlogon, winbind
49
50 samba.ensure_third_party_module("dns", "dnspython")
51 import dns.resolver
52 import dns.exception
53
54 default_ttl = 900
55 am_rodc = False
56 error_count = 0
57
58 parser = optparse.OptionParser("samba_dnsupdate")
59 sambaopts = options.SambaOptions(parser)
60 parser.add_option_group(sambaopts)
61 parser.add_option_group(options.VersionOptions(parser))
62 parser.add_option("--verbose", action="store_true")
63 parser.add_option("--all-names", action="store_true")
64 parser.add_option("--all-interfaces", action="store_true")
65 parser.add_option("--use-file", type="string", help="Use a file, rather than real DNS calls")
66 parser.add_option("--update-list", type="string", help="Add DNS names from the given file")
67 parser.add_option("--update-cache", type="string", help="Cache database of already registered records")
68 parser.add_option("--fail-immediately", action='store_true', help="Exit on first failure")
69 parser.add_option("--no-credentials", dest='nocreds', action='store_true', help="don't try and get credentials")
70 parser.add_option("--no-substitutions", dest='nosubs', action='store_true', help="don't try and expands variables in file specified by --update-list")
71
72 creds = None
73 ccachename = None
74
75 opts, args = parser.parse_args()
76
77 if len(args) != 0:
78     parser.print_usage()
79     sys.exit(1)
80
81 lp = sambaopts.get_loadparm()
82
83 domain = lp.get("realm")
84 host = lp.get("netbios name")
85 if opts.all_interfaces:
86     all_interfaces = True
87 else:
88     all_interfaces = False
89
90 IPs = samba.interface_ips(lp, all_interfaces)
91 nsupdate_cmd = lp.get('nsupdate command')
92
93 if len(IPs) == 0:
94     print "No IP interfaces - skipping DNS updates"
95     sys.exit(0)
96
97 IP6s = []
98 IP4s = []
99 for i in IPs:
100     if i.find(':') != -1:
101         IP6s.append(i)
102     else:
103         IP4s.append(i)
104
105
106 if opts.verbose:
107     print "IPs: %s" % IPs
108
109
110 def get_credentials(lp):
111     """# get credentials if we haven't got them already."""
112     from samba import credentials
113     global ccachename
114     creds = credentials.Credentials()
115     creds.guess(lp)
116     creds.set_machine_account(lp)
117     creds.set_krb_forwardable(credentials.NO_KRB_FORWARDABLE)
118     (tmp_fd, ccachename) = tempfile.mkstemp()
119     try:
120         creds.get_named_ccache(lp, ccachename)
121     except RuntimeError as e:
122         os.unlink(ccachename)
123         raise e
124
125
126 class dnsobj(object):
127     """an object to hold a parsed DNS line"""
128
129     def __init__(self, string_form):
130         list = string_form.split()
131         if len(list) < 3:
132             raise Exception("Invalid DNS entry %r" % string_form)
133         self.dest = None
134         self.port = None
135         self.ip = None
136         self.existing_port = None
137         self.existing_weight = None
138         self.type = list[0]
139         self.name = list[1]
140         self.nameservers = []
141         if self.type == 'SRV':
142             if len(list) < 4:
143                 raise Exception("Invalid DNS entry %r" % string_form)
144             self.dest = list[2]
145             self.port = list[3]
146         elif self.type in ['A', 'AAAA']:
147             self.ip   = list[2] # usually $IP, which gets replaced
148         elif self.type == 'CNAME':
149             self.dest = list[2]
150         elif self.type == 'NS':
151             self.dest = list[2]
152         else:
153             raise Exception("Received unexpected DNS reply of type %s: %s" % (self.type, string_form))
154
155     def __str__(self):
156         if self.type == "A":
157             return "%s %s %s" % (self.type, self.name, self.ip)
158         if self.type == "AAAA":
159             return "%s %s %s" % (self.type, self.name, self.ip)
160         if self.type == "SRV":
161             return "%s %s %s %s" % (self.type, self.name, self.dest, self.port)
162         if self.type == "CNAME":
163             return "%s %s %s" % (self.type, self.name, self.dest)
164         if self.type == "NS":
165             return "%s %s %s" % (self.type, self.name, self.dest)
166
167
168 def parse_dns_line(line, sub_vars):
169     """parse a DNS line from."""
170     if line.startswith("SRV _ldap._tcp.pdc._msdcs.") and not samdb.am_pdc():
171         # We keep this as compat to the dns_update_list of 4.0/4.1
172         if opts.verbose:
173             print "Skipping PDC entry (%s) as we are not a PDC" % line
174         return None
175     subline = samba.substitute_var(line, sub_vars)
176     if subline == '' or subline[0] == "#":
177         return None
178     return dnsobj(subline)
179
180
181 def hostname_match(h1, h2):
182     """see if two hostnames match."""
183     h1 = str(h1)
184     h2 = str(h2)
185     return h1.lower().rstrip('.') == h2.lower().rstrip('.')
186
187
188 def check_dns_name(d):
189     """check that a DNS entry exists."""
190     normalised_name = d.name.rstrip('.') + '.'
191     if opts.verbose:
192         print "Looking for DNS entry %s as %s" % (d, normalised_name)
193
194     if opts.use_file is not None:
195         try:
196             dns_file = open(opts.use_file, "r")
197         except IOError:
198             return False
199
200         for line in dns_file:
201             line = line.strip()
202             if line == '' or line[0] == "#":
203                 continue
204             if line.lower() == str(d).lower():
205                 return True
206         return False
207
208     resolv_conf = os.getenv('RESOLV_WRAPPER_CONF')
209     if not resolv_conf:
210         resolv_conf = '/etc/resolv.conf'
211     resolver = dns.resolver.Resolver(filename=resolv_conf, configure=True)
212
213     if d.nameservers != []:
214         resolver.nameservers = d.nameservers
215     else:
216         d.nameservers = resolver.nameservers
217
218     try:
219         ans = resolver.query(normalised_name, d.type)
220     except dns.exception.DNSException:
221         if opts.verbose:
222             print "Failed to find DNS entry %s" % d
223         return False
224     if d.type in ['A', 'AAAA']:
225         # we need to be sure that our IP is there
226         for rdata in ans:
227             if str(rdata) == str(d.ip):
228                 return True
229     elif d.type == 'CNAME':
230         for i in range(len(ans)):
231             if hostname_match(ans[i].target, d.dest):
232                 return True
233     elif d.type == 'NS':
234         for i in range(len(ans)):
235             if hostname_match(ans[i].target, d.dest):
236                 return True
237     elif d.type == 'SRV':
238         for rdata in ans:
239             if opts.verbose:
240                 print "Checking %s against %s" % (rdata, d)
241             if hostname_match(rdata.target, d.dest):
242                 if str(rdata.port) == str(d.port):
243                     return True
244                 else:
245                     d.existing_port     = str(rdata.port)
246                     d.existing_weight = str(rdata.weight)
247
248     if opts.verbose:
249         print "Failed to find matching DNS entry %s" % d
250
251     return False
252
253
254 def get_subst_vars(samdb):
255     """get the list of substitution vars."""
256     global lp, am_rodc
257     vars = {}
258
259     vars['DNSDOMAIN'] = samdb.domain_dns_name()
260     vars['DNSFOREST'] = samdb.forest_dns_name()
261     vars['HOSTNAME']  = samdb.host_dns_name()
262     vars['NTDSGUID']  = samdb.get_ntds_GUID()
263     vars['SITE']      = samdb.server_site_name()
264     res = samdb.search(base=samdb.get_default_basedn(), scope=SCOPE_BASE, attrs=["objectGUID"])
265     guid = samdb.schema_format_value("objectGUID", res[0]['objectGUID'][0])
266     vars['DOMAINGUID'] = guid
267
268     vars['IF_DC'] = ""
269     vars['IF_RWDC'] = "# "
270     vars['IF_RODC'] = "# "
271     vars['IF_PDC'] = "# "
272     vars['IF_GC'] = "# "
273     vars['IF_RWGC'] = "# "
274     vars['IF_ROGC'] = "# "
275     vars['IF_DNS_DOMAIN'] = "# "
276     vars['IF_RWDNS_DOMAIN'] = "# "
277     vars['IF_RODNS_DOMAIN'] = "# "
278     vars['IF_DNS_FOREST'] = "# "
279     vars['IF_RWDNS_FOREST'] = "# "
280     vars['IF_R0DNS_FOREST'] = "# "
281
282     am_rodc = samdb.am_rodc()
283     if am_rodc:
284         vars['IF_RODC'] = ""
285     else:
286         vars['IF_RWDC'] = ""
287
288     if samdb.am_pdc():
289         vars['IF_PDC'] = ""
290
291     # check if we "are DNS server"
292     res = samdb.search(base=samdb.get_config_basedn(),
293                    expression='(objectguid=%s)' % vars['NTDSGUID'],
294                    attrs=["options", "msDS-hasMasterNCs"])
295
296     if len(res) == 1:
297         if "options" in res[0]:
298             options = int(res[0]["options"][0])
299             if (options & dsdb.DS_NTDSDSA_OPT_IS_GC) != 0:
300                 vars['IF_GC'] = ""
301                 if am_rodc:
302                     vars['IF_ROGC'] = ""
303                 else:
304                     vars['IF_RWGC'] = ""
305
306         basedn = str(samdb.get_default_basedn())
307         forestdn = str(samdb.get_root_basedn())
308
309         if "msDS-hasMasterNCs" in res[0]:
310             for e in res[0]["msDS-hasMasterNCs"]:
311                 if str(e) == "DC=DomainDnsZones,%s" % basedn:
312                     vars['IF_DNS_DOMAIN'] = ""
313                     if am_rodc:
314                         vars['IF_RODNS_DOMAIN'] = ""
315                     else:
316                         vars['IF_RWDNS_DOMAIN'] = ""
317                 if str(e) == "DC=ForestDnsZones,%s" % forestdn:
318                     vars['IF_DNS_FOREST'] = ""
319                     if am_rodc:
320                         vars['IF_RODNS_FOREST'] = ""
321                     else:
322                         vars['IF_RWDNS_FOREST'] = ""
323
324     return vars
325
326
327 def call_nsupdate(d, op="add"):
328     """call nsupdate for an entry."""
329     global ccachename, nsupdate_cmd, krb5conf
330
331     assert(op in ["add", "delete"])
332
333     if opts.verbose:
334         print "Calling nsupdate for %s (%s)" % (d, op)
335
336     if opts.use_file is not None:
337         try:
338             rfile = open(opts.use_file, 'r+')
339         except IOError:
340             # Perhaps create it
341             rfile = open(opts.use_file, 'w+')
342             # Open it for reading again, in case someone else got to it first
343             rfile = open(opts.use_file, 'r+')
344         fcntl.lockf(rfile, fcntl.LOCK_EX)
345         (file_dir, file_name) = os.path.split(opts.use_file)
346         (tmp_fd, tmpfile) = tempfile.mkstemp(dir=file_dir, prefix=file_name, suffix="XXXXXX")
347         wfile = os.fdopen(tmp_fd, 'a')
348         rfile.seek(0)
349         for line in rfile:
350             if op == "delete":
351                 l = parse_dns_line(line, {})
352                 if str(l).lower() == str(d).lower():
353                     continue
354             wfile.write(line)
355         if op == "add":
356             wfile.write(str(d)+"\n")
357         os.rename(tmpfile, opts.use_file)
358         fcntl.lockf(rfile, fcntl.LOCK_UN)
359         return
360
361     normalised_name = d.name.rstrip('.') + '.'
362
363     (tmp_fd, tmpfile) = tempfile.mkstemp()
364     f = os.fdopen(tmp_fd, 'w')
365     if d.nameservers != []:
366         f.write('server %s\n' % d.nameservers[0])
367     if d.type == "A":
368         f.write("update %s %s %u A %s\n" % (op, normalised_name, default_ttl, d.ip))
369     if d.type == "AAAA":
370         f.write("update %s %s %u AAAA %s\n" % (op, normalised_name, default_ttl, d.ip))
371     if d.type == "SRV":
372         if op == "add" and d.existing_port is not None:
373             f.write("update delete %s SRV 0 %s %s %s\n" % (normalised_name, d.existing_weight,
374                                                            d.existing_port, d.dest))
375         f.write("update %s %s %u SRV 0 100 %s %s\n" % (op, normalised_name, default_ttl, d.port, d.dest))
376     if d.type == "CNAME":
377         f.write("update %s %s %u CNAME %s\n" % (op, normalised_name, default_ttl, d.dest))
378     if d.type == "NS":
379         f.write("update %s %s %u NS %s\n" % (op, normalised_name, default_ttl, d.dest))
380     if opts.verbose:
381         f.write("show\n")
382     f.write("send\n")
383     f.close()
384
385     global error_count
386     if ccachename:
387         os.environ["KRB5CCNAME"] = ccachename
388     try:
389         cmd = nsupdate_cmd[:]
390         cmd.append(tmpfile)
391         env = os.environ
392         if krb5conf:
393             env["KRB5_CONFIG"] = krb5conf
394         if ccachename:
395             env["KRB5CCNAME"] = ccachename
396         ret = subprocess.call(cmd, shell=False, env=env)
397         if ret != 0:
398             if opts.fail_immediately:
399                 if opts.verbose:
400                     print("Failed update with %s" % tmpfile)
401                 sys.exit(1)
402             error_count = error_count + 1
403             if opts.verbose:
404                 print("Failed nsupdate: %d" % ret)
405     except Exception, estr:
406         if opts.fail_immediately:
407             sys.exit(1)
408         error_count = error_count + 1
409         if opts.verbose:
410             print("Failed nsupdate: %s : %s" % (str(d), estr))
411     os.unlink(tmpfile)
412
413
414
415 def rodc_dns_update(d, t, op):
416     '''a single DNS update via the RODC netlogon call'''
417     global sub_vars
418
419     assert(op in ["add", "delete"])
420
421     if opts.verbose:
422         print "Calling netlogon RODC update for %s" % d
423
424     typemap = {
425         netlogon.NlDnsLdapAtSite       : netlogon.NlDnsInfoTypeNone,
426         netlogon.NlDnsGcAtSite         : netlogon.NlDnsDomainNameAlias,
427         netlogon.NlDnsDsaCname         : netlogon.NlDnsDomainNameAlias,
428         netlogon.NlDnsKdcAtSite        : netlogon.NlDnsInfoTypeNone,
429         netlogon.NlDnsDcAtSite         : netlogon.NlDnsInfoTypeNone,
430         netlogon.NlDnsRfc1510KdcAtSite : netlogon.NlDnsInfoTypeNone,
431         netlogon.NlDnsGenericGcAtSite  : netlogon.NlDnsDomainNameAlias
432         }
433
434     w = winbind.winbind("irpc:winbind_server", lp)
435     dns_names = netlogon.NL_DNS_NAME_INFO_ARRAY()
436     dns_names.count = 1
437     name = netlogon.NL_DNS_NAME_INFO()
438     name.type = t
439     name.dns_domain_info_type = typemap[t]
440     name.priority = 0
441     name.weight   = 0
442     if d.port is not None:
443         name.port = int(d.port)
444     if op == "add":
445         name.dns_register = True
446     else:
447         name.dns_register = False
448     dns_names.names = [ name ]
449     site_name = sub_vars['SITE'].decode('utf-8')
450
451     global error_count
452
453     try:
454         ret_names = w.DsrUpdateReadOnlyServerDnsRecords(site_name, default_ttl, dns_names)
455         if ret_names.names[0].status != 0:
456             print("Failed to set DNS entry: %s (status %u)" % (d, ret_names.names[0].status))
457             error_count = error_count + 1
458     except RuntimeError, reason:
459         print("Error setting DNS entry of type %u: %s: %s" % (t, d, reason))
460         error_count = error_count + 1
461
462     if error_count != 0 and opts.fail_immediately:
463         sys.exit(1)
464
465
466 def call_rodc_update(d, op="add"):
467     '''RODCs need to use the netlogon API for nsupdate'''
468     global lp, sub_vars
469
470     assert(op in ["add", "delete"])
471
472     # we expect failure for 3268 if we aren't a GC
473     if d.port is not None and int(d.port) == 3268:
474         return
475
476     # map the DNS request to a netlogon update type
477     map = {
478         netlogon.NlDnsLdapAtSite       : '_ldap._tcp.${SITE}._sites.${DNSDOMAIN}',
479         netlogon.NlDnsGcAtSite         : '_ldap._tcp.${SITE}._sites.gc._msdcs.${DNSDOMAIN}',
480         netlogon.NlDnsDsaCname         : '${NTDSGUID}._msdcs.${DNSFOREST}',
481         netlogon.NlDnsKdcAtSite        : '_kerberos._tcp.${SITE}._sites.dc._msdcs.${DNSDOMAIN}',
482         netlogon.NlDnsDcAtSite         : '_ldap._tcp.${SITE}._sites.dc._msdcs.${DNSDOMAIN}',
483         netlogon.NlDnsRfc1510KdcAtSite : '_kerberos._tcp.${SITE}._sites.${DNSDOMAIN}',
484         netlogon.NlDnsGenericGcAtSite  : '_gc._tcp.${SITE}._sites.${DNSFOREST}'
485         }
486
487     for t in map:
488         subname = samba.substitute_var(map[t], sub_vars)
489         if subname.lower() == d.name.lower():
490             # found a match - do the update
491             rodc_dns_update(d, t, op)
492             return
493     if opts.verbose:
494         print("Unable to map to netlogon DNS update: %s" % d)
495
496
497 # get the list of DNS entries we should have
498 if opts.update_list:
499     dns_update_list = opts.update_list
500 else:
501     dns_update_list = lp.private_path('dns_update_list')
502
503 if opts.update_cache:
504     dns_update_cache = opts.update_cache
505 else:
506     dns_update_cache = lp.private_path('dns_update_cache')
507
508 # use our private krb5.conf to avoid problems with the wrong domain
509 # bind9 nsupdate wants the default domain set
510 krb5conf = lp.private_path('krb5.conf')
511 os.environ['KRB5_CONFIG'] = krb5conf
512
513 file = open(dns_update_list, "r")
514
515 if opts.nosubs:
516     sub_vars = {}
517 else:
518     samdb = SamDB(url=lp.samdb_url(), session_info=system_session(), lp=lp)
519
520     # get the substitution dictionary
521     sub_vars = get_subst_vars(samdb)
522
523 # build up a list of update commands to pass to nsupdate
524 update_list = []
525 dns_list = []
526 cache_list = []
527 delete_list = []
528
529 dup_set = set()
530 cache_set = set()
531
532 rebuild_cache = False
533 try:
534     cfile = open(dns_update_cache, 'r+')
535 except IOError:
536     # Perhaps create it
537     cfile = open(dns_update_cache, 'w+')
538     # Open it for reading again, in case someone else got to it first
539     cfile = open(dns_update_cache, 'r+')
540 fcntl.lockf(cfile, fcntl.LOCK_EX)
541 for line in cfile:
542     line = line.strip()
543     if line == '' or line[0] == "#":
544         continue
545     c = parse_dns_line(line, {})
546     if c is None:
547         continue
548     if str(c) not in cache_set:
549         cache_list.append(c)
550         cache_set.add(str(c))
551
552 # read each line, and check that the DNS name exists
553 for line in file:
554     line = line.strip()
555     if line == '' or line[0] == "#":
556         continue
557     d = parse_dns_line(line, sub_vars)
558     if d is None:
559         continue
560     if d.type == 'A' and len(IP4s) == 0:
561         continue
562     if d.type == 'AAAA' and len(IP6s) == 0:
563         continue
564     if str(d) not in dup_set:
565         dns_list.append(d)
566         dup_set.add(str(d))
567
568 # now expand the entries, if any are A record with ip set to $IP
569 # then replace with multiple entries, one for each interface IP
570 for d in dns_list:
571     if d.ip != "$IP":
572         continue
573     if d.type == 'A':
574         d.ip = IP4s[0]
575         for i in range(len(IP4s)-1):
576             d2 = dnsobj(str(d))
577             d2.ip = IP4s[i+1]
578             dns_list.append(d2)
579     if d.type == 'AAAA':
580         d.ip = IP6s[0]
581         for i in range(len(IP6s)-1):
582             d2 = dnsobj(str(d))
583             d2.ip = IP6s[i+1]
584             dns_list.append(d2)
585
586 # now check if the entries already exist on the DNS server
587 for d in dns_list:
588     found = False
589     for c in cache_list:
590         if str(c).lower() == str(d).lower():
591             found = True
592             break
593     if not found:
594         rebuild_cache = True
595     if opts.all_names:
596         update_list.append(d)
597         if opts.verbose:
598             print "force update: %s" % d
599     elif not check_dns_name(d):
600         update_list.append(d)
601         if opts.verbose:
602             print "need update: %s" % d
603
604
605 for c in cache_list:
606     found = False
607     for d in dns_list:
608         if str(c).lower() == str(d).lower():
609             found = True
610             break
611     if found:
612         continue
613     rebuild_cache = True
614     if not opts.all_names and not check_dns_name(c):
615         continue
616     delete_list.append(c)
617     if opts.verbose:
618         print "need delete: %s" % c
619
620 if len(delete_list) == 0 and len(update_list) == 0 and not rebuild_cache:
621     if opts.verbose:
622         print "No DNS updates needed"
623     sys.exit(0)
624 else:
625     if opts.verbose:
626         print "%d DNS updates and %d DNS deletes needed" % (len(update_list), len(delete_list))
627
628 # get our krb5 creds
629 if len(delete_list) != 0 or len(update_list) != 0:
630     if not opts.nocreds:
631         get_credentials(lp)
632
633 # ask nsupdate to delete entries as needed
634 for d in delete_list:
635     if am_rodc:
636         if d.name.lower() == domain.lower():
637             if opts.verbose:
638                 print "skip delete (rodc): %s" % d
639             continue
640         if not d.type in [ 'A', 'AAAA' ]:
641             if opts.verbose:
642                 print "delete (rodc): %s" % d
643             call_rodc_update(d, op="delete")
644         else:
645             if opts.verbose:
646                 print "delete (nsupdate): %s" % d
647             call_nsupdate(d, op="delete")
648     else:
649         if opts.verbose:
650             print "delete (nsupdate): %s" % d
651         call_nsupdate(d, op="delete")
652
653 # ask nsupdate to add entries as needed
654 for d in update_list:
655     if am_rodc:
656         if d.name.lower() == domain.lower():
657             if opts.verbose:
658                 print "skip (rodc): %s" % d
659             continue
660         if not d.type in [ 'A', 'AAAA' ]:
661             if opts.verbose:
662                 print "update (rodc): %s" % d
663             call_rodc_update(d)
664         else:
665             if opts.verbose:
666                 print "update (nsupdate): %s" % d
667             call_nsupdate(d)
668     else:
669         if opts.verbose:
670             print "update(nsupdate): %s" % d
671         call_nsupdate(d)
672
673 if rebuild_cache:
674     (file_dir, file_name) = os.path.split(dns_update_cache)
675     (tmp_fd, tmpfile) = tempfile.mkstemp(dir=file_dir, prefix=file_name, suffix="XXXXXX")
676     wfile = os.fdopen(tmp_fd, 'a')
677     for d in dns_list:
678         wfile.write(str(d)+"\n")
679     os.rename(tmpfile, dns_update_cache)
680 fcntl.lockf(cfile, fcntl.LOCK_UN)
681
682 # delete the ccache if we created it
683 if ccachename is not None:
684     os.unlink(ccachename)
685
686 if error_count != 0:
687     print("Failed update of %u entries" % error_count)
688 sys.exit(error_count)