# dns/trunk/DNSDB/ExportBIND.pm
# BIND data export/publication
# Call through DNSDB.pm's export() sub
##
# $Id: ExportBIND.pm 859 2022-09-15 22:02:12Z kdeugau $
# Copyright 2022 Kris Deugau <kdeugau@deepnet.cx>
# 
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version. 
# 
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
# 
#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
##

package DNSDB::ExportBIND;

use strict;
use warnings;

sub export {
  # expected to be a DNSDB object
  my $dnsdb = shift;

  # to be a hash of views/locations, containing lists of zones
  my %viewzones;

  # allow for future exports of subgroups of records
  my $viewlist = $dnsdb->getLocList(curgroup => 1);

  my $soasth = $dnsdb->{dbh}->prepare("SELECT host,type,val,distance,weight,port,ttl,record_id,location ".
	"FROM records WHERE rdns_id=? AND type=6");
  my $recsth = $dnsdb->{dbh}->prepare("SELECT host,type,val,distance,weight,port,ttl,record_id,location,extract(epoch from stamp),expires,stampactive ".
	"FROM records WHERE rdns_id=? AND NOT type=6 ".
	"ORDER BY masklen(inetlazy(val)) DESC, inetlazy(val)");

  # Fetch active zone list
  my $revsth = $dnsdb->{dbh}->prepare("SELECT rdns_id,revnet,status,changed,default_location FROM revzones WHERE status=1 ".
	"ORDER BY masklen(revnet) DESC, rdns_id");
  # Unflag changed zones, so we can maybe cache the export and not redo everything every time
  my $zonesth = $dnsdb->{dbh}->prepare("UPDATE revzones SET changed='n' WHERE rdns_id=?");
  $revsth->execute();
  while (my ($revid,$revzone,$revstat,$changed,$defloc) = $revsth->fetchrow_array) {
    my $cidr = NetAddr::IP->new($revzone);
    my $zfile = $cidr->network->addr."-".$cidr->masklen;
#    my $cachefile = "$dnsdb->{exportcache}/$zfile";
#    my $tmpcache = "$dnsdb->{exportcache}/tmp.$zfile.$$";
    my $tmpcache = "tmp.$zfile.$$";      # safety net.  don't overwrite a previous known-good file

##fixme:  convert logical revzone into .arpa name?  maybe take a slice of showrev_arpa?
##fixme:  need to bodge logical non-octet-boundary revzones into octet-boundary revzones
##fixme:  do we do cache files?  views balloon the file count stupidly
## foreach $octetzone $cidr->split(octet-boundary)
##   loclist = SELECT DISTINCT location FROM records WHERE rdns_id = $zid AND inetlazy(val) <<= $octetzone

#printf "non-octet? %s, %i\n", $cidr->masklen, $cidr->masklen % 8;


    eval {

      my $arpazone = DNSDB::_ZONE($cidr, 'ZONE', 'r', '.').($cidr->{isv6} ? '.ip6.arpa' : '.in-addr.arpa');

      # write fresh records if:
      #  - we are not using the cache
      #  - force_refresh is set
      #  - the zone has changed
      #  - the cache file does not exist
      #  - the cache file is empty
      if (!$dnsdb->{usecache} || $dnsdb->{force_refresh} || $changed || !-e $cachefile || -z $cachefile) {
        if ($dnsdb->{usecache}) {
          open ZONECACHE, ">$tmpcache" or die "Error creating temporary file $tmpcache: $!\n";
          $zonefilehandle = *ZONECACHE;
        }

        # fetch a list of views/locations present in the zone.  we need to publish a file for each one.
        # in the event that no locations are present (~~ $viewlist is empty), /%view collapses to nothing in the zone path
        my (@loclist) = $dnsdb->{dbh}->selectrow_array("SELECT DISTINCT location FROM records WHERE rdns_id = ?", undef, $revid);
        push @loclist, $defloc unless grep /$defloc/, @loclist;
        my $zonepath = $dnsdb->{bind_export_reverse_zone_path};
        my %zonefiles;  # to be a hash of file handles.
##fixme:  need to open separate zone files for aggregated metazones eg /22 or /14
        foreach my $loc (@loclist) {
          my $zfilepath = $zonepath;
          $zfilepath =~ s/\%view/$loc/;
          $zfilepath =~ s/\%zone/$revzone/;
          $zfilepath =~ s/\%arpazone/$arpazone/;
          # Just In Case(TM)
          $zfilepath =~ s,[^\w./-],_,g;
          open $zonefiles{$loc}, ">", $zfilepath;
          print {$zonefiles{$loc}} "; $arpazone in view $loc\n";
print "open zonefile for '$loc', '$zfilepath'\n";
        }

        # need to fetch this separately since the rest of the records all (should) have real IPs in val
        $soasth->execute($revid);
        my (@zsoa) = $soasth->fetchrow_array();
        printrec_bind(\%zonefiles, $zsoa[7], 'y', \@loclist, $revzone,
          $zsoa[0],$zsoa[1],$zsoa[2],$zsoa[3],$zsoa[4],$zsoa[5],$zsoa[6],$zsoa[8],'');

        $recsth->execute($revid);
        my $fullzone = _ZONE($tmpzone, 'ZONE', 'r', '.').($tmpzone->{isv6} ? '.ip6.arpa' : '.in-addr.arpa');

        while (my ($host, $type, $val, $dist, $weight, $port, $ttl, $recid, $loc, $stamp, $expires, $stampactive)
                = $recsth->fetchrow_array) {
          next if $recflags{$recid};

          # Check for out-of-zone data
          if ($val =~ /\.arpa$/) {
            # val is non-IP
            if ($val !~ /$fullzone$/) {
              warn "Not exporting out-of-zone record $val $typemap{$type} $host, $ttl (zone $tmpzone)\n";
              next;
            }
          } else {
            my $ipval = new NetAddr::IP $val;
            if (!$tmpzone->contains($ipval)) {
              warn "Not exporting out-of-zone record $val $typemap{$type} $host, $ttl (zone $tmpzone)\n";
              next;
            }
          } # is $val a raw .arpa name?

          # Spaces are evil.
          $val =~ s/^\s+//;
          $val =~ s/\s+$//;
          if ($typemap{$type} ne 'TXT') {
            # Leading or trailng spaces could be legit in TXT records.
            $host =~ s/^\s+//;
            $host =~ s/\s+$//;
          }

          printrec_bind($zonefilehandle, $recid, 'y', \%recflags, $revzone,
            $host, $type, $val, $dist, $weight, $port, $ttl, $loc, $stamp, $expires, $stampactive);

          $recflags{$recid} = 1;

        } # while ($recsth)

        if ($dnsdb->{usecache}) {
          close ZONECACHE; # force the file to be written
          # catch obvious write errors that leave an empty temp file
          if (-s $tmpcache) {
            rename $tmpcache, $cachefile
              or die "Error overwriting cache file $cachefile with temporary file: $!\n";
          }
        }

      } # if $changed or cache filesize is 0

    };
    if ($@) {
      die "error writing ".($dnsdb->{usecache} ? 'new data for ' : '')."$revzone: $@\n";
      # error!  something borked, and we should be able to fall back on the old cache file
      # report the error, somehow.
    } else {
      # mark zone as unmodified.  Only do this if no errors, that way
      # export failures should recover a little more automatically.
      $zonesth->execute($revid);
    }

#    if ($dnsdb->{usecache}) {
#      # We've already made as sure as we can that a cached zone file is "good",
#      # although possibly stale/obsolete due to errors creating a new one.
#      eval {
#        open CACHE, "<$cachefile" or die $!;
#        print $datafile $_ or die "error copying cached $revzone to master file: $!" while <CACHE>;
#        close CACHE;
#      };
#      die $@ if $@;
#    }



  } # revsth->fetch


  # Write the view configuration last, because otherwise we have to be horribly inefficient
  # at figuring out which zones are visible/present in which views
  if ($viewlist) {
    my $tmpconf = "$dnsdb->{bind_zone_conf}.$$"; ##fixme:  split filename for prefixing
    open BINDCONF, ">", $tmpconf;

    foreach my $view (@{$viewlist}) {
#print Dumper($view);
      print BINDCONF "view $view->{location} {\n";
#      print "view $view->{location} {\n";
      # could also use an acl { ... }; statement, then match-clients { aclname; };, but that gets hairy
      # note that some semantics of data visibility need to be handled by the record export, since it's
      # not 100% clear if the semantics of a tinydns view with an empty IP list (matches anyone) are the
      # same as a BIND view with match-clients { any; };
      if ($view->{iplist}) {
         print BINDCONF "  match-clients { ".join("; ", $view->iplist)."; };\n";
#         print "  match-clients { ".join("; ", split(/[\s,]+/, $view->{iplist}))."; };\n";
      } else {
         print BINDCONF "  match-clients { any; };\n";
#         print "  match-clients { any; };\n";
      }
      foreach my $zone (@{$viewzones{$view->{location}}}) {
##fixme:  notify settings, maybe per-zone?
        print qq(  zone "$zone" IN {\n\ttype master;\n\tnotify no;\n\tfile "db.$zone";\n  };\n);
      }
      print "};\n\n";
    } # foreach @$viewlist
    rename $tmpconf, $dnsdb->{bind_zone_conf};
  } # if $viewlist

} # export()


# Print individual records in BIND format
sub printrec_bind {
  my $dnsdb = shift;
  my ($zonefiles, $recid, $revrec, $loclist, $zone, $host, $type, $val, $distance, $weight, $port, $ttl,
	$loc, $stamp, $expires, $stampactive) = @_;

  # Just In Case something is lingering in the DB
  $loc = '' if !$loc;

  ## And now to the records!

  if ($typemap{$type} eq 'SOA') {
    # host contains pri-ns:responsible
    # val is abused to contain refresh:retry:expire:minttl
    # let's be explicit about abusing $host and $val
    my ($email, $primary) = (split /:/, $host)[0,1];
    my ($refresh, $retry, $expire, $min_ttl) = (split /:/, $val)[0,1,2,3];
    my $serial = 0;  # fail less horribly than leaving it empty?
    # just snarfing the right SOA serial for the zone type
    if ($revrec eq 'y') {
      ($serial) = $dnsdb->{dbh}->selectrow_array("SELECT zserial FROM revzones WHERE revnet=?", undef, $zone);
    } else {
      ($serial) = $dnsdb->{dbh}->selectrow_array("SELECT zserial FROM domains WHERE domain=?", undef, $zone);
    } # revrec <> 'y'
    # suppress a "uninitialized value" warning.  should be impossible but...
    # abuse hours as the last digit pair of the serial for simplicity
##fixme?:  alternate SOA serial schemes?
    $serial = strftime("%Y%m%d%H", localtime()) if !$serial;
    $primary .= "." if $primary !~ /\.$/;
    $email .= "." if $email !~ /\.$/;
#    print *{$zonefiles->{$loc}} "Z$zone:$primary:$email:$serial:$refresh:$retry:$expire:$min_ttl:$ttl:$stamp:$loc\n"
#      or die $!;
    print *{$zonefiles->{$loc}} "$zone	$ttl	IN	SOA	$primary	$email	( $serial $refresh $retry $expire $min_ttl )\n"
       or die "couldn't write $zone SOA: $!";
  } # SOA

} # printrec_bind()


1;
