source: trunk/DNSDB/ExportBIND.pm@ 856

Last change on this file since 856 was 856, checked in by Kris Deugau, 2 years ago

/trunk

BIND export, unwinding dev saves, 8 of many many

  • More minor naming convention fiddles
  • Start eying up removing zone split from SOA record publication, because we need a zone file for each formal .arpa zone in an aggregated metazone (eg /22 or /14)
  • Introduce bind_export_reverse_zone_path config variable, so we can use either the CIDR address or the formal .arpa name for reverse zone file paths
  • Property svn:keywords set to Date Rev Author Id
File size: 11.3 KB
Line 
1# dns/trunk/DNSDB/ExportBIND.pm
2# BIND data export/publication
3# Call through DNSDB.pm's export() sub
4##
5# $Id: ExportBIND.pm 856 2022-09-15 20:56:41Z kdeugau $
6# Copyright 2022 Kris Deugau <kdeugau@deepnet.cx>
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
22package DNSDB::ExportBIND;
23
24use strict;
25use warnings;
26
27sub export {
28 # expected to be a DNSDB object
29 my $dnsdb = shift;
30
31 # to be a hash of views/locations, containing lists of zones
32 my %viewzones;
33
34 # allow for future exports of subgroups of records
35 my $viewlist = $dnsdb->getLocList(curgroup => 1);
36
37 my $soasth = $dnsdb->{dbh}->prepare("SELECT host,type,val,distance,weight,port,ttl,record_id,location ".
38 "FROM records WHERE rdns_id=? AND type=6");
39 my $recsth = $dnsdb->{dbh}->prepare("SELECT host,type,val,distance,weight,port,ttl,record_id,location,extract(epoch from stamp),expires,stampactive ".
40 "FROM records WHERE rdns_id=? AND NOT type=6 ".
41 "ORDER BY masklen(inetlazy(val)) DESC, inetlazy(val)");
42
43 # Fetch active zone list
44 my $revsth = $dnsdb->{dbh}->prepare("SELECT rdns_id,revnet,status,changed,default_location FROM revzones WHERE status=1 ".
45 "ORDER BY masklen(revnet) DESC, rdns_id");
46 # Unflag changed zones, so we can maybe cache the export and not redo everything every time
47 my $zonesth = $dnsdb->{dbh}->prepare("UPDATE revzones SET changed='n' WHERE rdns_id=?");
48 $revsth->execute();
49 while (my ($revid,$revzone,$revstat,$changed,$defloc) = $revsth->fetchrow_array) {
50 my $cidr = NetAddr::IP->new($revzone);
51 my $zfile = $cidr->network->addr."-".$cidr->masklen;
52# my $cachefile = "$dnsdb->{exportcache}/$zfile";
53# my $tmpcache = "$dnsdb->{exportcache}/tmp.$zfile.$$";
54 my $tmpcache = "tmp.$zfile.$$"; # safety net. don't overwrite a previous known-good file
55
56##fixme: convert logical revzone into .arpa name? maybe take a slice of showrev_arpa?
57##fixme: need to bodge logical non-octet-boundary revzones into octet-boundary revzones
58##fixme: do we do cache files? views balloon the file count stupidly
59## foreach $octetzone $cidr->split(octet-boundary)
60## loclist = SELECT DISTINCT location FROM records WHERE rdns_id = $zid AND inetlazy(val) <<= $octetzone
61
62#printf "non-octet? %s, %i\n", $cidr->masklen, $cidr->masklen % 8;
63
64
65 eval {
66
67 # write fresh records if:
68 # - we are not using the cache
69 # - force_refresh is set
70 # - the zone has changed
71 # - the cache file does not exist
72 # - the cache file is empty
73 if (!$dnsdb->{usecache} || $dnsdb->{force_refresh} || $changed || !-e $cachefile || -z $cachefile) {
74 if ($dnsdb->{usecache}) {
75 open ZONECACHE, ">$tmpcache" or die "Error creating temporary file $tmpcache: $!\n";
76 $zonefilehandle = *ZONECACHE;
77 }
78
79 # fetch a list of views/locations present in the zone. we need to publish a file for each one.
80 # in the event that no locations are present (~~ $viewlist is empty), /%view collapses to nothing in the zone path
81 my (@loclist) = $dnsdb->{dbh}->selectrow_array("SELECT DISTINCT location FROM records WHERE rdns_id = ?", undef, $revid);
82 push @loclist, $defloc unless grep /$defloc/, @loclist;
83 my $zonepath = $dnsdb->{bind_export_reverse_zone_path};
84 my %zonefiles; # to be a list of file handles.
85##fixme: need to open separate zone files for aggregated metazones eg /22 or /14
86 foreach my $loc (@loclist) {
87 my $zfilepath = $zonepath;
88 $zfilepath =~ s/\%view/$loc/;
89 $zfilepath =~ s/\%zone/$revzone/;
90 my $arpazone = DNSDB::_ZONE($cidr, 'ZONE', 'r', '.').($cidr->{isv6} ? '.ip6.arpa' : '.in-addr.arpa');
91 $zfilepath =~ s/\%arpazone/$arpazone/;
92 # Just In Case(TM)
93 $zfilepath =~ s,[^\w./-],_,g;
94 #open $zonefiles{$loc}, ">", $zfilepath;
95print "open zonefile for '$loc', '$zfilepath'\n";
96 }
97
98 # need to fetch this separately since the rest of the records all (should) have real IPs in val
99 $soasth->execute($revid);
100 my (@zsoa) = $soasth->fetchrow_array();
101 printrec_bind($zonefilehandle, $zsoa[7], 'y', \@loclist, $revzone,
102 $zsoa[0],$zsoa[1],$zsoa[2],$zsoa[3],$zsoa[4],$zsoa[5],$zsoa[6],$zsoa[8],'');
103
104 $recsth->execute($revid);
105 my $fullzone = _ZONE($tmpzone, 'ZONE', 'r', '.').($tmpzone->{isv6} ? '.ip6.arpa' : '.in-addr.arpa');
106
107 while (my ($host, $type, $val, $dist, $weight, $port, $ttl, $recid, $loc, $stamp, $expires, $stampactive)
108 = $recsth->fetchrow_array) {
109 next if $recflags{$recid};
110
111 # Check for out-of-zone data
112 if ($val =~ /\.arpa$/) {
113 # val is non-IP
114 if ($val !~ /$fullzone$/) {
115 warn "Not exporting out-of-zone record $val $typemap{$type} $host, $ttl (zone $tmpzone)\n";
116 next;
117 }
118 } else {
119 my $ipval = new NetAddr::IP $val;
120 if (!$tmpzone->contains($ipval)) {
121 warn "Not exporting out-of-zone record $val $typemap{$type} $host, $ttl (zone $tmpzone)\n";
122 next;
123 }
124 } # is $val a raw .arpa name?
125
126 # Spaces are evil.
127 $val =~ s/^\s+//;
128 $val =~ s/\s+$//;
129 if ($typemap{$type} ne 'TXT') {
130 # Leading or trailng spaces could be legit in TXT records.
131 $host =~ s/^\s+//;
132 $host =~ s/\s+$//;
133 }
134
135 printrec_bind($zonefilehandle, $recid, 'y', \%recflags, $revzone,
136 $host, $type, $val, $dist, $weight, $port, $ttl, $loc, $stamp, $expires, $stampactive);
137
138 $recflags{$recid} = 1;
139
140 } # while ($recsth)
141
142 if ($dnsdb->{usecache}) {
143 close ZONECACHE; # force the file to be written
144 # catch obvious write errors that leave an empty temp file
145 if (-s $tmpcache) {
146 rename $tmpcache, $cachefile
147 or die "Error overwriting cache file $cachefile with temporary file: $!\n";
148 }
149 }
150
151 } # if $changed or cache filesize is 0
152
153 };
154 if ($@) {
155 die "error writing ".($dnsdb->{usecache} ? 'new data for ' : '')."$revzone: $@\n";
156 # error! something borked, and we should be able to fall back on the old cache file
157 # report the error, somehow.
158 } else {
159 # mark zone as unmodified. Only do this if no errors, that way
160 # export failures should recover a little more automatically.
161 $zonesth->execute($revid);
162 }
163
164# if ($dnsdb->{usecache}) {
165# # We've already made as sure as we can that a cached zone file is "good",
166# # although possibly stale/obsolete due to errors creating a new one.
167# eval {
168# open CACHE, "<$cachefile" or die $!;
169# print $datafile $_ or die "error copying cached $revzone to master file: $!" while <CACHE>;
170# close CACHE;
171# };
172# die $@ if $@;
173# }
174
175
176
177 } # revsth->fetch
178
179
180 # Write the view configuration last, because otherwise we have to be horribly inefficient
181 # at figuring out which zones are visible/present in which views
182 if ($viewlist) {
183 foreach my $view (@{$viewlist}) {
184#print Dumper($view);
185# print BINDCONF "view $view->{location} {\n";
186 print "view $view->{location} {\n";
187 # could also use an acl { ... }; statement, then match-clients { aclname; };, but that gets hairy
188 # note that some semantics of data visibility need to be handled by the record export, since it's
189 # not 100% clear if the semantics of a tinydns view with an empty IP list (matches anyone) are the
190 # same as a BIND view with match-clients { any; };
191 if ($view->{iplist}) {
192# print BINDCONF " match-clients { ".join("; ", $view->iplist)."; };\n";
193 print " match-clients { ".join("; ", split(/[\s,]+/, $view->{iplist}))."; };\n";
194 } else {
195# print BINDCONF " match-clients { any; };\n";
196 print " match-clients { any; };\n";
197 }
198 foreach my $zone (@{$viewzones{$view->{location}}}) {
199##fixme: notify settings, maybe per-zone?
200 print qq( zone "$zone" IN {\n\ttype master;\n\tnotify no;\n\tfile "db.$zone";\n };\n);
201 }
202 print "};\n\n";
203 } # foreach @$viewlist
204 } # if $viewlist
205
206} # export()
207
208
209# Print individual records in BIND format
210sub printrec_bind {
211 my $dnsdb = shift;
212 my ($zonefiles, $recid, $revrec, $loclist, $zone, $host, $type, $val, $distance, $weight, $port, $ttl,
213 $loc, $stamp, $expires, $stampactive) = @_;
214
215 # Just In Case something is lingering in the DB
216 $loc = '' if !$loc;
217
218 ## And now to the records!
219
220 if ($typemap{$type} eq 'SOA') {
221 # host contains pri-ns:responsible
222 # val is abused to contain refresh:retry:expire:minttl
223 # let's be explicit about abusing $host and $val
224 my ($email, $primary) = (split /:/, $host)[0,1];
225 my ($refresh, $retry, $expire, $min_ttl) = (split /:/, $val)[0,1,2,3];
226 my $serial = 0; # fail less horribly than leaving it empty?
227 if ($revrec eq 'y') {
228##fixme: have to publish SOA records for each v4 /24 in sub-/16, and each /16 in sub-/8
229# what about v6?
230# -> only need SOA for local chunks offset from reverse delegation boundaries, so v6 is fine
231# anyone who says they need sub-nibble v6 delegations, at this time, needs their head examined.
232##fixme?: alternate SOA serial schemes?
233 ($serial) = $dnsdb->{dbh}->selectrow_array("SELECT zserial FROM revzones WHERE revnet=?", undef, $zone);
234 $zone = NetAddr::IP->new($zone);
235 # handle split-n-multiply SOA for off-octet (8 < mask < 16) or (16 < mask < 24) v4 zones
236 if (!$zone->{isv6} && ($zone->masklen < 24) && ($zone->masklen % 8 != 0)) {
237 foreach my $szone ($zone->split($zone->masklen + (8 - $zone->masklen % 8))) {
238 $szone = DNSDB::_ZONE($szone, 'ZONE.in-addr.arpa', 'r', '.');
239# print $datafile "Z$szone:$primary:$email:$serial:$refresh:$retry:$expire:$min_ttl:$ttl:$stamp:$loc\n"
240print "$szone $ttl IN SOA $primary $email ( $serial $refresh $retry $expire $min_ttl )\n"
241 or die $!;
242 }
243 return; # skips "default" bits just below
244 }
245 $zone = DNSDB::_ZONE($zone, 'ZONE', 'r', '.').($zone->{isv6} ? '.ip6.arpa' : '.in-addr.arpa');
246 } else {
247 # just snarfing the right SOA serial for the zone type
248##fixme?: alternate SOA serial schemes?
249 ($serial) = $dnsdb->{dbh}->selectrow_array("SELECT zserial FROM domains WHERE domain=?", undef, $zone);
250 } # revrec <> 'y'
251 # suppress a "uninitialized value" warning. should be impossible but...
252 # abuse hours as the last digit pair of the serial for simplicity
253 $serial = strftime("%Y%m%d%H", localtime()) if !$serial;
254# print *{$zonefiles->{$loc}} "Z$zone:$primary:$email:$serial:$refresh:$retry:$expire:$min_ttl:$ttl:$stamp:$loc\n"
255# or die $!;
256 print *{$zonefiles->{$loc}} "$zone $ttl IN SOA $primary $email ( $serial $refresh $retry $expire $min_ttl )\n"
257 or die $!;
258 } # SOA
259
260} # printrec_bind()
261
262
2631;
Note: See TracBrowser for help on using the repository browser.