chiark / gitweb /
4c401f4e47568d3c6c8cf73f5651ed01351ad3a4
[chiark-utils.git] / scripts / named-conf
1 #!/usr/bin/perl -w
2
3 use strict;
4 use IO::File;
5 use Data::Dumper;
6
7 use vars qw($etcfile $where);
8 $etcfile= "/etc/bind/chiark-conf-gen.zones";
9 $where= '<built-in>';
10
11 use vars qw($mode $verbosity $debug);
12 $mode= '';
13 $verbosity= 1;
14 $debug= 0;
15
16 while (@ARGV && $ARGV[0] =~ m/^\-/) {
17     $_= shift @ARGV;
18     if (s/^\-\-//) {
19         last if m/^$/;
20         if (m/^quiet$/) { $verbosity=0; }
21         elsif (m/^verbose$/) { $verbosity=2; }
22         elsif (m/^(yes|no|force)$/) { m/^./; $mode= $&; }
23         elsif (m/^config$/) { $etcfile= loarg(); $where= '--config option'; }
24         else { usageerr("unknown option --$_"); }
25     } else {
26         s/^\-//;
27         last if m/^$/;
28         while (m/^./) {
29             if (s/^[ynf]//) { $mode=$&; }
30             elsif (s/^v//) { $verbosity=2; }
31             elsif (s/^q//) { $verbosity=0; }
32             elsif (s/^D//) { $debug=1; }
33             elsif (s/^C//) { $etcfile= soarg(); $where= '-C option'; }
34             else { usageerr("unknown option -$&"); }
35         }
36     }
37 }
38
39 sub loarg() { usageerr("missing option value") if !@ARGV; return shift @ARGV; }
40 sub soarg() { my ($rv); $rv=$_; $_=''; return length $rv ? $rv : loarg(); }
41
42 usageerr("must specify either -f|-y|-n or zones (and not both)")
43     if !!$mode == !!@ARGV;
44
45 sub usageerr ($) {
46     die
47 "$_[0]
48 usage: named-conf-regen [-rvq] -f|-y|-n|<zone>...\n".
49 "operation modes:\n".
50 " -f --force   install without checking\n".
51 " -y --yes     check and install\n".
52 " -n --no      check only\n".
53 "additional options:\n".
54 " -q --quiet   no output for OK zones\n".
55 " -v --verbose extra verbose\n";
56 }
57
58 cfg_fail("config filename $etcfile should have been absolute path of a file")
59     unless $etcfile =~ m,^/, && $etcfile !~ m,/$,;
60
61 use vars qw($default_dir);
62 $default_dir= $etcfile;
63 $default_dir =~ s,/[^/]+$,,;
64
65 use vars qw($slave_dir $slave_prefix $slave_suffix);
66 $slave_dir= 'slave';
67 $slave_prefix= '';
68 $slave_suffix= '';
69
70 use vars qw(@self_ns @self_soa);
71 @self_ns= @self_soa= ();
72
73 use vars qw(%zone_cfg @zone_cfg_list);
74 %zone_cfg= ();
75 @zone_cfg_list= ();
76
77 use vars qw($output $default_output %output_contents);
78 $output= '';
79 $default_output= '';
80 %output_contents= ();
81
82 use vars qw($check $install);
83 $check= $mode !~ m/^n/;
84 $install= $mode =~ m/^[yf]/;
85
86 read_config($etcfile);
87 debug_dump('@zone_cfg_list %zone_cfg');
88 process_zones($mode ? @zone_cfg_list : @ARGV);
89 debug_dump('%output_contents');
90
91 use vars qw($zone $cfg $warnings);
92 $warnings= 0;
93
94 sub progress ($) {
95     return if !$verbosity;
96     print "$_[0]\n";
97 }
98
99 sub process_zones (@) {
100     my (@zones) = @_;
101     local ($zone,$cfg);
102
103     foreach $zone (@zones) {
104         $cfg= $zone_cfg{$zone} || { 'style' => 'foreign' };
105         progress(sprintf "%-40s %s", $zone, $$cfg{'style'});
106         if ($check) {
107             eval { zone_check() };
108             zone_warning("checks failed: $@") if length $@;
109         }
110         zone_output() if $install;
111     }
112 }
113
114 sub zone_warning ($) {
115     my ($w) = @_;
116     $w =~ s/\n$//;
117     $w =~ s,\n, // ,g;
118     print STDERR "$zone: warning: $w\n" or die $!;
119     $warnings++;
120 }
121
122 sub zone_warnmore ($) {
123     print STDERR " $_[0]\n" or die $!;
124 }
125
126 use vars qw(%delgs # $delgs{$nameserver_list} = [ $whosaidandwhy ]
127             %auths # $auths{$nameserver_list} = [ $whosaidandwhy ]
128             %glue  # $glue{$name}{$addr_list} = [ $whosaidandwhy ]
129             %soas  # $soa{"$origin $serial"} = [ $whosaidandwhy ]
130             @to_check # ($addr,$whyask,\%delgs_or_auths,$glueless_ok, ...)
131             @to_check_soa # ($addr,$whyask, ...)
132             );
133
134 sub zone_check () {
135     my ($super_zone, @super_nsnames,
136         $super_ns, @super_ns_addrs, $super_ns_addr, $s, $wa, $zcr,
137         %nsrrset_checked, %soa_checked);
138
139     %delgs= %auths= %glue= ();
140     @to_check= @to_check_soa= ();
141
142     $super_zone= $zone;
143     for (;;) {
144         debug_trace("zone $zone superzone $super_zone");
145         $super_zone =~ s/^[^.]+\.// or die "no superzone ? ($super_zone)\n";
146         ($rcode,@super_nsnames)= lookup($super_zone,'ns-','06');
147         last if !$rcode;
148     }
149     for $super_ns (@super_nsnames) {
150         $super_ns= lc $super_ns;
151         ($rcode,@this_ns_addrs)= lookup($super_ns,'a','0');
152         foreach $super_ns_addr (@this_ns_addrs) {
153             push @to_check,
154                  $super_ns_addr,
155                  "addr for $super_ns, server for $super_zone, parent"
156                  \%delgs, 0;
157         }
158     }
159     for (;;) {
160         # We do these in order so that we always do NS RRset checks on
161         # nameservers that came from other NS RRsets first; otherwise
162         # we might set nsrrset_checked due to a glueless_ok check,
163         # and then not check for gluefulness later.
164         if (($addr,$wa,$nsrrset_ref,$glueless_ok,@to_check) = @to_check) {
165             next if $nsrrset_checked{$ns}++;
166             push @to_check_soa, $addr, $why;
167             zone_check_nsrrset($super_ns_addr,"$addr, $wa",
168                                %$delgs_or_auths,$glueless_ok);
169         } elsif (($addr,$wa) = @to_check_soa) {
170             next if !$soa_checked{$ns}++;
171             zone_check_soa($addr,"$addr, $wa");
172         }
173     }
174     zone_consistency();
175 }
176
177 sub zone_consistency() {
178     my ($d);
179     zone_consistency_set('delegations',%delgs);
180     foreach $d (keys %delgs) { delete $auths{$d}; }
181     zone_consistency_set('zone nameserver rrset',%auths);
182     foreach $h (keys %glue) {
183         zone_consistency_set("glue for $h", %{ $glue{$h} });
184     }
185 }
186
187 sub zone_consistency_set ($\%) {
188     my ($msg,$set) = @_;
189     my ($d,$o);
190     if (keys(%$set) != 1) {
191         zone_warning("inconsistent $msg:");
192         foreach $d (keys %$set) {
193             foreach $o (@$d) { zone_warnmore(" $d from $o"); }
194         }
195     }
196 }
197
198 sub zone_check_soa ($$) {
199     my ($uaddr,$ww) = @_;
200     my ($lame,$origin,$got,$rcode,@soa_addrs,$soa_addr);
201     $lame= 'dead or lame';
202     dig::dig({
203         if ($dig::type eq 'flags:') {
204             $lame= $dig::rdata =~ m/ aa / ? 'lame' : '';
205         } elsif ($dig::type eq 'soa' && $dig::owner eq $zone && !$lame) {
206             die "several SOAs ? $why" if defined $origin;
207             $dig::rdata =~ m/^(\S+) \S+ (\d+) /
208                 or die "soa $dig::rdata ? $why";
209             $origin= $1;
210             $got= "$1 $2";
211         }
212     },
213              $zone,'soa',$uaddr);
214     $lame= 'broken' if !$lame && !defined $origin;
215     if ($lame) { zone_warning("$lame server $ww"); return; }
216     push @{ $soas{$got} }, $why;
217     ($rcode,@soa_addrs)= lookup($origin,'a','0');
218     foreach $soa_addr (@soa_addrs) {
219         push @to_check,
220              $soa_addr,
221              "addr for $origin, SOA ORIGIN from $why";
222     }
223 }
224
225 sub zone_check_nsrrset ($$\%\%) {
226     my ($uaddr,$ww, $delgs_or_auths,$glueless_ok) = @_;
227     my (@s, $s, %s2g, @glue, $glue);
228     dig::dig({
229         if ($dig::type eq 'ns' && $dig::owner eq $zone) {
230             $s2g{lc $dig::rdata} = [ ];
231         } elsif ($dig::type eq 'a' && exists $s2g{$dig::owner}) {
232             push @to_check,
233                  $dig::rdata,
234                  "glue for $dig::owner, from (eg) $why",
235                  \%auths, 0;
236             push @{ $s2g{$dig::rdata} }, $dig::rdata;
237         }
238     },
239              $zone,'ns',$uaddr);
240     @s= sort keys %s2g;
241     foreach $s (@s) {
242         @glue= @{ $s2g{$s} };
243         if (!length @glue) {
244             zone_warning("glueless NS $s, from $ww") unless $glueless_ok;
245             next;
246         }
247         $glue= join ' ', sort @glue;
248         push @{ $glue{$s}{$glue} }, $why;
249     }
250     $s= join ' ', @s;
251     push @{ $nsrrset_ref->{$s} }, $why;
252 }
253
254 sub zone_output () {
255     $output_contents{$$cfg{'output'}}.=
256         sprintf(<<'END',
257 zone "%s" {
258     type %s;
259     file "%s";
260 };
261 END
262                 $zone,
263                 $$cfg{'style'} eq 'primary' ? 'master' : 'slave',
264                 $$cfg{'file'});
265 }
266
267 sub debug_dump ($) {
268     my ($vn);
269     return unless $debug;
270     local $Data::Dumper::Terse=1;
271     foreach $vn (split /\s+/, $_[0]) {
272         print "$vn := ", eval "Dumper(\\$vn)";
273     }
274 }
275
276 sub cfg_fail ($) { die "$0: $where:\n $_[0]\n"; }
277
278 sub read_config ($) {
279     my ($if) = @_;
280     my ($fh,$z,@self, $dir,$prefix,$suffix,$lprefix,$lsuffix);
281     local ($_,$1,$2,$3);
282
283     $fh= new IO::File $if,'r' or cfg_fail("open $if:\n $!");
284     for (;;) {
285         if (!defined($_= <$fh>)) {
286             cfg_fail("read config file $if:\n $!") if $fh->error();
287             last;
288         }
289         $where= "$if:$.";
290         s/^\s+//; chomp; s/\s+$//;
291         next if m/^\#/;
292         last if m/^end$/;
293         next unless m/\S/;
294         if (m/^self(\-ns|\-soa|)\s+(\S.*\S)/) {
295             @self= split /\s+/, $2;
296             @self_ns= @self if $1 ne '-soa';
297             @self_soa= @self if $1 ne '-ns';
298         } elsif (m/^primary\-dir\s+(\S+)((?:\s+(\S+))??:\s+(\S+))?$/) {
299             ($dir, $prefix, $suffix) = (qualify($1),$2,$3);
300             $suffix= '_db' if !length $suffix;
301             opendir D, $dir or cfg_fail("open primary-dir $dir:\n $!");
302             $lprefix= length $prefix; $lsuffix= length $suffix;
303             while ($!=0, $_= readdir D) {
304                 next if m/^\./ && !$lprefix;
305                 next unless length > $lprefix+$lsuffix;
306                 next unless substr($_,0,$lprefix) eq $prefix;
307                 next unless substr($_,length($_)-$lsuffix) eq $suffix;
308                 $z= substr($_,$lprefix,length($_)-($lprefix+$lsuffix));
309                 zone_conf($z,'primary',"$dir/$_");
310             }
311             $! and cfg_fail("read primary-dir $dir:\n $!");
312             closedir D or cfg_fail("close primary-dir $dir:\n $!");
313         } elsif (m/^primary\s+(\S+)\s+(\S+)$/) {
314             zone_conf($1,'primary',qualify($2));
315         } elsif (m/^secondary\s+(\S+)\s+([0-9.\t]+)$/) {
316             zone_conf($1,'secondary','',$2);
317         } elsif (m/^stealth\s+(\S+)\s+([0-9. \t]+)$/) {
318             zone_conf($1,'stealth','',split /\s+/, $2);
319         } elsif (m/^slave\-dir\s+(\S+)((?:\s+(\S+))??:\s+(\S+))?$/) {
320             ($slave_dir, $slave_prefix, $slave_suffix) = (qualify($1),$2,$3);
321         } elsif (m/^output\s+bind8\+(\S+)$/) {
322             cfg_fail("default output may not apply to only some zones")
323                 if @zone_cfg_list && length $default_output;
324             set_output(qualify($1));
325         } elsif (m/^include\s+(\S+)$/) {
326             read_config($1);
327         } else {
328             cfg_fail("unknown configuration directive".
329                      " or incorrect syntax or arguments");
330         }
331     }
332     $fh->close or cfg_fail("close config file $if:\n $!");
333 }
334
335 sub qualify ($) {
336     my ($i) = @_;
337     $i= "$default_dir/$i" unless $i =~ m,^/,;
338 }
339
340 sub zone_conf ($$@) {
341     my ($zone,$style,$file,@servers) = @_;
342     $file= qualify("$slave_dir/$slave_prefix".$zone.$slave_suffix)
343         unless length $file;
344     if (!length $output) {
345         $default_output= qualify('chiark-conf-gen.bind8')
346             unless length $default_output;
347         set_output($default_output);
348     }
349     cfg_fail("redefined zone $zone") if exists $zone_cfg{$zone};
350     $zone_cfg{$zone}{'file'}= $file;
351     $zone_cfg{$zone}{'style'}= $style;
352     $zone_cfg{$zone}{'servers'}= [ @servers ];
353     $zone_cfg{$zone}{'self_soa'}= [ @self_soa ];
354     $zone_cfg{$zone}{'self_ns'}= [ @self_ns ];
355     $zone_cfg{$zone}{'output'}= $output;
356     push @zone_cfg_list, $zone;
357 }
358
359 sub set_output($) {
360     my ($newout) = @_;
361     $output= $newout;
362     $output_contents{$output}= '';
363 }
364
365 sub lookup ($$$) {
366     my ($type,$domain,$okrcodes) = @_;
367     my ($c,@result);
368     defined($c= open ADH, "-|") or die "$0: fork adnshost:\n $!\n";
369     if (!$c) {
370         exec 'adnshost','-Fi','+Do','+Dt','+Dc','-Cf',"-t$type",
371              '-',"$domain.";
372         die "$0: exec adnshost:\n $!\n";
373     }
374     @result= <ADH>;
375     chomp @result;
376     $!=0; close ADH;
377     die "$0: lookup -t$type $domain $okrcodes failed $? $!\n"
378         if $! or $?>6 or index($okrcodes,$?)<0;
379     return ($?,@result);
380 }
381
382 __DATA__
383
384
385
386
387 sub lookup1 ($$) {
388     my ($type,$domain) = @_;
389     my (@result)= lookup($type,$domain);
390     @result==1 or die "$0: lookup -t$type $domain gave more than one RR\n";
391     return $result[0];
392 }
393
394 sub check () {
395     return unless $check;
396     eval {
397         $soa= lookup1('soa',$zone);
398         $soa_origin=$soa; $soa_origin =~ s/ .*//;
399         $soa_origin_addr= lookup1('a',$soa_origin);
400
401         @zone_ns= lookup('ns-',$zone);
402
403         @ok_sources= ($soa_origin_addr);
404         $ok_sources_descr= "SOA ORIGIN $soa_origin [$soa_origin_addr]";
405
406         if ($style eq 'unoff' || $style eq 'backup') {
407             for $zone_ns (@zone_ns) {
408                 @zone_ns_addrs= lookup('a',$zone_ns);
409                 push @ok_sources, @zone_ns_addrs;
410                 $ok_sources_descr.= ", NS $zone_ns [@zone_ns_addrs]";
411             }
412         }
413
414         for $server (@servers) {
415             grep { $server eq $_ } @ok_sources
416                 or warn "secondarying from $server which is not ".
417                         "$ok_sources_desc\n";
418         }
419
420         if ($style eq 'secondary') {
421             grep { $zone_ns=$_, grep { $myname eq $_ } @mynames } @zone_n
422                 or warn "supposedly published secondary but we ".
423                         "(@mynames) are not published ($@zone_ns)\n";
424         }
425     }
426     check_after_eval();
427     
428
429                          
430 #       $superzone= $zone; $superzone =~ s/^[^\.]+\.//;
431 #       @super_ns= lookup('ns-',$zone);
432     }
433
434     eval {
435
436         for $super_ns (@super_ns) {
437             @deleg_ns= ();
438             open DIG, "dig @$super_ns. -t ns +norecurse $zone."
439                 or die "$0: fork for dig:\n $!\n";
440             while (<DIG>) {
441                 
442
443             split /\n/, lookup("
444         
445                 case "$style" in
446                 secondary|backup)
447                         if [ $meadvert = 0 ]
448                         then
449                                 warning "$myname unlisted NS $nsnames"
450                         fi
451                         ;;
452                 unoff)
453                         if $meadvert = 0
454                         then
455                                 warning "$myname advertised NS $nsnames"
456                         fi
457                         ;;
458                 esac
459
460                 addrs=''
461                 for ns in $names
462                 do
463                         set -e; a="`host -t a \"$ns\".`"; set +e
464                         taddrs="`echo \" $a\" | expand | sed -n '
465                                  1s/^ //
466                                 s/^[^ ][^ ]*  *A  *\([0-9][.0-9]*\)/\1/p
467                         '`"
468                         equlines "A $ns" "$a" "$taddrs"
469                         addrs="$addrs $taddrs"
470                 done
471         fi
472
473         cat <<END
474 zone "$zone" {
475         type slave;
476         file "$file";
477         masters {
478 END
479         for server in $servers
480         do
481                 echo "          $server;"
482                 if $check
483                 then
484                         notfound=1
485                         for addr in $addrs
486                         do
487                                 if [ "x$addr" = "x$server" ]
488                                 then
489                                         notfound=0
490                                 fi
491                         done
492                         if $notfound
493                         then
494  warning "server $server? but $rectype $names" $addrs
495                         fi
496                 fi
497         done
498         cat <<END
499         };
500 };
501 END
502         hostfirstwarn=1
503         if $hostdelg
504         then
505                 checkhostout -C
506         fi
507         if $hostzone
508         then
509                 checkhostout -val localhost
510         fi
511 done
512 endfile
513
514     
515 chdir "$base/primary" or die "$0: chdir $base/primary:\n $!";
516 beginfile('primary.zones');
517
518 for $f (<*_db>) {
519     $zone= $f; $zone =~ s/_db$//;
520     
521
522 for f in $zones
523 do
524         zone="`echo $f | sed -e 's/_db$//'`"
525 END
526 done
527 endfile
528
529
530     
531 sub beginfile ($) {
532     $currentfile= $_[0];
533     $currentfile_opened= $install ? "$conf/$currentfile.new" : "/dev/null";
534     open CFF, "> $toopen" or die "$0: begin $currentfile_opened:\n $!\n";
535 }
536
537 endfile () {
538     close CFF or die "$0: close $currentfile_opened:\n $!\n";
539     push @files, $currentfile;
540 }
541
542 sub installfiles () {
543     return unless $install;
544     chdir $conf or die "$0: chdir $conf:\n $!\n";
545     for $f (@files) {
546         rename "$f.new", $f or die "$0: install new $f:\n $!\n";
547     }
548 }
549
550 warning () {
551         echo >&2 "$zone $style: $*"
552         warnings=$[$warnings+1]
553 }
554
555 equlines () {
556         if [ "x`echo \" $2\" | wc -l`" != "x`echo \" $3\" | wc -l`" ]
557         then
558                 warning "$1 >$2|$3<"
559         fi
560 }
561
562 checkhostout () {
563         set +e
564         hostout="`host $1 \"$zone\" 2>&1 >/dev/null $2 | egrep -v \
565 '^ \!\!\! .* SOA primary .* is not advertised via NS$'`"
566         set -e
567         if [ "x$hostout" = x ]; then return; fi
568         if $hostfirstwarn
569         then
570                 warning "warnings from host:"
571                 hostfirstwarn=0
572         fi
573         echo >&2 "$hostout"
574 }
575
576 progress () {
577         if $progress
578         then
579                 echo -n "$zone $style                    " >&2
580                 echo -ne '\r' >&2
581         fi
582 }
583
584 myname=''
585
586 if [ $warnings != 0 ]
587 then
588         echo >&2 "$warnings warnings                                        "
589 fi
590
591 installfiles