# dns/trunk/DNSDB.pm
# Abstraction functions for DNS administration
##
# $Id: DNSDB.pm 289 2012-03-27 16:56:12Z kdeugau $
# Copyright 2008-2011 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;

use strict;
use warnings;
use Exporter;
use DBI;
use Net::DNS;
use Crypt::PasswdMD5;
use Net::SMTP;
use NetAddr::IP qw(:lower);
use POSIX;
use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);

$VERSION	= 0.1;	##VERSION##
@ISA		= qw(Exporter);
@EXPORT_OK	= qw(
	&initGlobals &login &initActionLog
	&initPermissions &getPermissions &changePermissions &comparePermissions
	&changeGroup
	&loadConfig &connectDB &finish
	&addDomain &delZone &domainName &revName &domainID &revID &addRDNS
	&getZoneCount &getZoneList
	&addGroup &delGroup &getChildren &groupName
	&addUser &updateUser &delUser &userFullName &userStatus &getUserData
	&getSOA	&updateSOA &getRecLine &getDomRecs &getRecCount
	&addRec &updateRec &delRec
	&getTypelist
	&parentID
	&isParent
	&zoneStatus &importAXFR
	&export
	&mailNotify
	%typemap %reverse_typemap %config
	%permissions @permtypes $permlist
	);

@EXPORT		= (); # Export nothing by default.
%EXPORT_TAGS	= ( ALL => [qw(
		&initGlobals &login &initActionLog
		&initPermissions &getPermissions &changePermissions &comparePermissions
		&changeGroup
		&loadConfig &connectDB &finish
		&addDomain &delZone &domainName &revName &domainID &revID &addRDNS
		&getZoneCount &getZoneList
		&addGroup &delGroup &getChildren &groupName
		&addUser &updateUser &delUser &userFullName &userStatus &getUserData
		&getSOA &updateSOA &getRecLine &getDomRecs &getRecCount
		&addRec &updateRec &delRec
		&getTypelist
		&parentID
		&isParent
		&zoneStatus &importAXFR
		&export
		&mailNotify
		%typemap %reverse_typemap %config
		%permissions @permtypes $permlist
		)]
	);

our $group = 1;
our $errstr = '';
our $resultstr = '';

# Halfway sane defaults for SOA, TTL, etc.
# serial defaults to 0 for convenience.
# value will be either YYYYMMDDNN for BIND/etc, or auto-internal for tinydns
our %def = qw (
	contact	hostmaster.DOMAIN
	prins	ns1.myserver.com
	serial	0
	soattl	86400
	refresh	10800
	retry	3600
	expire	604800
	minttl	10800
	ttl	10800
);

# Arguably defined wholly in the db, but little reason to change without supporting code changes
our @permtypes = qw (
	group_edit	group_create	group_delete
	user_edit	user_create	user_delete
	domain_edit	domain_create	domain_delete
	record_edit	record_create	record_delete
	self_edit	admin
);
our $permlist = join(',',@permtypes);

# DNS record type map and reverse map.
# loaded from the database, from http://www.iana.org/assignments/dns-parameters
our %typemap;
our %reverse_typemap;

our %permissions;

# Prepopulate a basic config.  Note some of these *will* cause errors if left unset.
# note:  add appropriate stanzas in loadConfig to parse these
our %config = (
		# Database connection info
		dbname	=> 'dnsdb',
		dbuser	=> 'dnsdb',
		dbpass	=> 'secret',
		dbhost	=> '',

		# Email notice settings
		mailhost	=> 'smtp.example.com',
		mailnotify	=> 'dnsdb@example.com',	# to
		mailsender	=> 'dnsdb@example.com',	# from
		mailname	=> 'DNS Administration',
		orgname		=> 'Example Corp',
		domain		=> 'example.com',

		# Template directory
		templatedir	=> 'templates/',
# fmeh.  this is a real web path, not a logical internal one.  hm..
#		cssdir	=> 'templates/',
		sessiondir	=> 'session/',

		# Session params
		timeout		=> '3600',	# 1 hour default

		# Other miscellanea
		log_failures	=> 1,	# log all evarthing by default
		perpage		=> 15,
	);

## (Semi)private variables

# Hash of functions for validating record types.  Filled in initGlobals() since
# it relies on visibility flags from the rectypes table in the DB
my %validators;

# Username, full name, ID - mainly for logging
my %userdata;


##
## utility functions
##

## DNSDB::_rectable()
# Takes default+rdns flags, returns appropriate table name
sub _rectable {
  my $def = shift;
  my $rev = shift;

  return 'records' if $def ne 'y';
  return 'default_records' if $rev ne 'y';
  return 'default_rev_records';
} # end _rectable()

## DNSDB::_recparent()
# Takes default+rdns flags, returns appropriate parent-id column name
sub _recparent {
  my $def = shift;
  my $rev = shift;

  return 'group_id' if $def eq 'y';
  return 'rdns_id' if $rev eq 'y';
  return 'domain_id';
} # end _recparent()

## DNSDB::_ipparent()
# Check an IP to be added in a reverse zone to see if it's really in the requested parent.
# Takes a database handle, default and reverse flags, IP (fragment) to check, parent zone ID,
# and a reference to a NetAddr::IP object (also used to pass back a fully-reconstructed IP for
# database insertion)
sub _ipparent {
  my $dbh = shift;
  my $defrec = shift;
  my $revrec = shift;
  my $val = shift;
  my $id = shift;
  my $addr = shift;

  return if $revrec ne 'y';	# this sub not useful in forward zones

  $$addr = NetAddr::IP->new($$val);	 #necessary?

  # subsub to split, reverse, and overlay an IP fragment on a netblock
  sub __rev_overlay {
    my $splitme = shift;	# ':' or '.', m'lud?
    my $parnet = shift;
    my $val = shift;
    my $addr = shift;

    my $joinme = $splitme;
    $splitme = '\.' if $splitme eq '.';
    my @working = reverse(split($splitme, $parnet->addr));
    my @parts = reverse(split($splitme, $$val));
    for (my $i = 0; $i <= $#parts; $i++) {
      $working[$i] = $parts[$i];
    }
    my $checkme = NetAddr::IP->new(join($joinme, reverse(@working))) or return 0;
    return 0 unless $checkme->within($parnet);
    $$addr = $checkme;	# force "correct" IP to be recorded.
    return 1;
  }

  my ($parstr) = $dbh->selectrow_array("SELECT revnet FROM revzones WHERE rdns_id = ?", undef, ($id));
  my $parnet = NetAddr::IP->new($parstr);

  # Fail early on v6-in-v4 or v4-in-v6.  We're not accepting these ATM.
  return 0 if $parnet->addr =~ /\./ && $$val =~ /:/;
  return 0 if $parnet->addr =~ /:/ && $$val =~ /\./;

  if ($$addr && $$val =~ /^[\da-fA-F][\da-fA-F:]+[\da-fA-F]$/) {
    # the only case where NetAddr::IP's acceptance of legitimate IPs is "correct" is for a proper IPv6 address.
    # the rest we have to restructure before fiddling.  *sigh*
    return 1 if $$addr->within($parnet);
  } else {
    # We don't have a complete IP in $$val (yet)
    if ($parnet->addr =~ /:/) {
      $$val =~ s/^:+//;	 # gotta strip'em all...
      return __rev_overlay(':', $parnet, $val, $addr);
    }
    if ($parnet->addr =~ /\./) {
      $$val =~ s/^\.+//;
      return __rev_overlay('.', $parnet, $val, $addr);
    }
    # should be impossible to get here...
  }
  # ... and here.
  # can't do nuttin' in forward zones
} # end _ipparent()

## DNSDB::_hostparent()
# A little different than _ipparent above;  this tries to *find* the parent zone of a hostname
# Takes a database handle and hostname.
# Returns the domain ID of the parent domain if one was found.
sub _hostparent {
  my $dbh = shift;
  my $hname = shift;
  
  my @hostbits = split /\./, $hname;
  my $sth = $dbh->prepare("SELECT count(*),domain_id FROM domains WHERE domain = ? GROUP BY domain_id");
  foreach (@hostbits) {
    $sth->execute($hname);
    my ($found, $parid) = $sth->fetchrow_array;
    if ($found) {
      return $parid;
    }
    $hname =~ s/^$_\.//;
  }
} # end _hostparent()

## DNSDB::_log()
# Log an action
# Takes a database handle and log entry hash containing at least:
#  group_id, log entry
# and optionally one or more of:
#  domain_id, rdns_id
# The %userdata hash provides the user ID, username, and fullname
sub _log {
  my $dbh = shift;

  my %args = @_;

  $args{rdns_id} = 0 if !$args{rdns_id};
  $args{domain_id} = 0 if !$args{domain_id};

##fixme:  farm out the actual logging to different subs for file, syslog, internal, etc based on config
#  if ($config{log_channel} eq 'sql') {
  $dbh->do("INSERT INTO log (domain_id,rdns_id,group_id,entry,user_id,email,name) VALUES (?,?,?,?,?,?,?)",
	undef,
	($args{domain_id}, $args{rdns_id}, $args{group_id}, $args{entry},
		$userdata{userid}, $userdata{username}, $userdata{fullname}) );
#  } elsif ($config{log_channel} eq 'file') {
#  } elsif ($config{log_channel} eq 'syslog') {
#  }
} # end _log


##
## Record validation subs.
##

## All of these subs take substantially the same arguments:
# a database handle
# a hash containing at least the following keys:
#  - defrec (default/live flag)
#  - revrec (forward/reverse flag)
#  - id (parent entity ID)
#  - host (hostname)
#  - rectype
#  - val (IP, hostname [CNAME/MX/SRV] or text)
#  - addr (NetAddr::IP object from val.  May be undef.)
# MX and SRV record validation also expect distance, and SRV records expect weight and port as well.
# host, rectype, and addr should be references as these may be modified in validation

# A record
sub _validate_1 {
  my $dbh = shift;

  my %args = @_;

  return ('FAIL', 'Reverse zones cannot contain A records') if $args{revrec} eq 'y';

  # Coerce all hostnames to end in ".DOMAIN" for group/default records,
  # or the intended parent domain for live records.
  my $pname = ($args{defrec} eq 'y' ? 'DOMAIN' : domainName($dbh,$args{id}));
  ${$args{host}} =~ s/\.*$/\.$pname/ if ${$args{host}} !~ /$pname$/;

  # Check IP is well-formed, and that it's a v4 address
  # Fail on "compact" IPv4 variants, because they are not consistent and predictable.
  return ('FAIL',"$typemap{${$args{rectype}}} record must be a valid IPv4 address")
	unless ${$args{val}} =~ /^\d+\.\d+\.\d+\.\d+$/;
  return ('FAIL',"$typemap{${$args{rectype}}} record must be a valid IPv4 address")
	unless $args{addr} && !$args{addr}->{isv6};
  # coerce IP/value to normalized form for storage
  ${$args{val}} = $args{addr}->addr;

  return ('OK','OK');
} # done A record

# NS record
sub _validate_2 {
  my $dbh = shift;

  my %args = @_;

  # Coerce the hostname to "DOMAIN" for forward default records, "ZONE" for reverse default records,
  # or the intended parent zone for live records.
##fixme:  allow for delegating <subdomain>.DOMAIN?
  if ($args{revrec} eq 'y') {
    my $pname = ($args{defrec} eq 'y' ? 'ZONE' : revName($dbh,$args{id}));
    ${$args{host}} = $pname if ${$args{host}} ne $pname;
  } else {
    my $pname = ($args{defrec} eq 'y' ? 'DOMAIN' : domainName($dbh,$args{id}));
    ${$args{host}} = $pname if ${$args{host}} ne $pname;
  }

# Let this lie for now.  Needs more magic.
#  # Check IP is well-formed, and that it's a v4 address
#  return ('FAIL',"A record must be a valid IPv4 address")
#	unless $addr && !$addr->{isv6};
#  # coerce IP/value to normalized form for storage
#  $$val = $addr->addr;

  return ('OK','OK');
} # done NS record

# CNAME record
sub _validate_5 {
  my $dbh = shift;

  my %args = @_;

# Not really true, but these are only useful for delegating smaller-than-/24 IP blocks.
# This is fundamentally a messy operation and should really just be taken care of by the
# export process, not manual maintenance of the necessary records.
  return ('FAIL', 'Reverse zones cannot contain CNAME records') if $args{revrec} eq 'y';

  # Coerce all hostnames to end in ".DOMAIN" for group/default records,
  # or the intended parent domain for live records.
  my $pname = ($args{defrec} eq 'y' ? 'DOMAIN' : domainName($dbh,$args{id}));
  ${$args{host}} =~ s/\.*$/\.$pname/ if ${$args{host}} !~ /$pname$/;

  return ('OK','OK');
} # done CNAME record

# SOA record
sub _validate_6 {
  # Smart monkeys won't stick their fingers in here;  we have
  # separate dedicated routines to deal with SOA records.
  return ('OK','OK');
} # done SOA record

# PTR record
sub _validate_12 {
  my $dbh = shift;

  my %args = @_;

  if ($args{revrec} eq 'y') {
    if ($args{defrec} eq 'n') {
      return ('FAIL', "IP or IP fragment ${$args{val}} is not within ".revName($dbh, $args{id}))
	unless _ipparent($dbh, $args{defrec}, $args{revrec}, $args{val}, $args{id}, \$args{addr});
      ${$args{val}} = $args{addr}->addr;
    } else {
      if (${$args{val}} =~ /\./) {
	# looks like a v4 or fragment
	if (${$args{val}} =~ /^\d+\.\d+\.\d+\.\d+$/) {
	  # woo!  a complete IP!  validate it and normalize, or fail.
	  $args{addr} = NetAddr::IP->new(${$args{val}})
		or return ('FAIL', "IP/value looks like IPv4 but isn't valid");
	  ${$args{val}} = $args{addr}->addr;
	} else {
	  ${$args{val}} =~ s/^\.*/ZONE./ unless ${$args{val}} =~ /^ZONE/;
	}
      } elsif (${$args{val}} =~ /[a-f:]/) {
	# looks like a v6 or fragment
	${$args{val}} =~ s/^:*/ZONE::/ if !$args{addr} && ${$args{val}} !~ /^ZONE/;
	if ($args{addr}) {
	  if ($args{addr}->addr =~ /^0/) {
	    ${$args{val}} =~ s/^:*/ZONE::/ unless ${$args{val}} =~ /^ZONE/;
	  } else {
	    ${$args{val}} = $args{addr}->addr;
	  }
	}
      } else {
	# bare number (probably).  These could be v4 or v6, so we'll
	# expand on these on creation of a reverse zone.
	${$args{val}} = "ZONE,${$args{val}}" unless ${$args{val}} =~ /^ZONE/;
      }
      ${$args{host}} =~ s/\.*$/\.$config{domain}/ if ${$args{host}} !~ /(?:$config{domain}|ADMINDOMAIN)$/;
    }

# Multiple PTR records do NOT generally do what most people believe they do,
# and tend to fail in the most awkward way possible.  Check and warn.
# We use $val instead of $addr->addr since we may be in a defrec, and may have eg "ZONE::42" or "ZONE.12"

    my @checkvals = (${$args{val}});
    if (${$args{val}} =~ /,/) {
      # push . and :: variants into checkvals if val has ,
      my $tmp;
      ($tmp = ${$args{val}}) =~ s/,/./;
      push @checkvals, $tmp;
      ($tmp = ${$args{val}}) =~ s/,/::/;
      push @checkvals, $tmp;
    }
    my $pcsth = $dbh->prepare("SELECT count(*) FROM "._rectable($args{defrec},$args{revrec})." WHERE val = ?");
    foreach my $checkme (@checkvals) {
      if ($args{update}) {
	# Record update.  There should usually be an existing PTR (the record being updated)
	my @ptrs = @{ $dbh->selectcol_arrayref("SELECT record_id FROM "._rectable($args{defrec},$args{revrec}).
		" WHERE val = ?", undef, ($checkme)) };
	return ('WARN', "PTR record for $checkme already exists;  adding another will probably not do what you want")
		if @ptrs && (!grep /^$args{update}$/, @ptrs);
      } else {
	# New record.  Always warn if a PTR exists
	my ($ptrcount) = $dbh->selectrow_array("SELECT count(*) FROM "._rectable($args{defrec},$args{revrec}).
		" WHERE val = ?", undef, ($checkme));
	return ('WARN', "PTR record for $checkme already exists;  adding another will probably not do what you want")
		if $ptrcount;
      }
    }

  } else {
    # Not absolutely true but only useful if you hack things up for sub-/24 v4 reverse delegations
    # Simpler to just create the reverse zone and grant access for the customer to edit it, and create direct
    # PTR records on export
    return ('FAIL',"Forward zones cannot contain PTR records");
  }

  return ('OK','OK');
} # done PTR record

# MX record
sub _validate_15 {
  my $dbh = shift;

  my %args = @_;

# Not absolutely true but WTF use is an MX record for a reverse zone?
  return ('FAIL', 'Reverse zones cannot contain MX records') if $args{revrec} eq 'y';

  return ('FAIL', "Distance is required for MX records") unless defined(${$args{dist}});
  ${$args{dist}} =~ s/\s*//g;
  return ('FAIL',"Distance is required, and must be numeric") unless ${$args{dist}} =~ /^\d+$/;

  ${$args{fields}} = "distance,";
  push @{$args{vallist}}, ${$args{dist}};

  # Coerce all hostnames to end in ".DOMAIN" for group/default records,
  # or the intended parent domain for live records.
  my $pname = ($args{defrec} eq 'y' ? 'DOMAIN' : domainName($dbh,$args{id}));
  ${$args{host}} =~ s/\.*$/\.$pname/ if ${$args{host}} !~ /$pname$/;

# hmm..  this might work.  except possibly for something pointing to "deadbeef.ca".  <g>
#  if ($type == $reverse_typemap{NS} || $type == $reverse_typemap{MX} || $type == $reverse_typemap{SRV}) {
#    if ($val =~ /^\s*[\da-f:.]+\s*$/) {
#      return ('FAIL',"$val is not a valid IP address") if !$addr;
#    }
#  }

  return ('OK','OK');
} # done MX record

# TXT record
sub _validate_16 {
  # Could arguably put a WARN return here on very long (>512) records
  return ('OK','OK');
} # done TXT record

# RP record
sub _validate_17 {
  # Probably have to validate these some day
  return ('OK','OK');
} # done RP record

# AAAA record
sub _validate_28 {
  my $dbh = shift;

  my %args = @_;

  return ('FAIL', 'Reverse zones cannot contain AAAA records') if $args{revrec} eq 'y';

  # Coerce all hostnames to end in ".DOMAIN" for group/default records,
  # or the intended parent domain for live records.
  my $pname = ($args{defrec} eq 'y' ? 'DOMAIN' : domainName($dbh,$args{id}));
  ${$args{host}} =~ s/\.*$/\.$pname/ if ${$args{host}} !~ /$pname$/;

  # Check IP is well-formed, and that it's a v6 address
  return ('FAIL',"$typemap{${$args{rectype}}} record must be a valid IPv6 address")
	unless $args{addr} && $args{addr}->{isv6};
  # coerce IP/value to normalized form for storage
  ${$args{val}} = $args{addr}->addr;

  return ('OK','OK');
} # done AAAA record

# SRV record
sub _validate_33 {
  my $dbh = shift;

  my %args = @_;

# Not absolutely true but WTF use is an SRV record for a reverse zone?
  return ('FAIL', 'Reverse zones cannot contain SRV records') if $args{revrec} eq 'y';

  return ('FAIL', "Distance is required for SRV records") unless defined(${$args{dist}});
  ${$args{dist}} =~ s/\s*//g;
  return ('FAIL',"Distance is required, and must be numeric") unless ${$args{dist}} =~ /^\d+$/;

  return ('FAIL',"SRV records must begin with _service._protocol [${$args{host}}]")
	unless ${$args{host}} =~ /^_[A-Za-z]+\._[A-Za-z]+\.[a-zA-Z0-9-]+/;
  return ('FAIL',"Port and weight are required for SRV records")
	unless defined(${$args{weight}}) && defined(${$args{port}});
  ${$args{weight}} =~ s/\s*//g;
  ${$args{port}} =~ s/\s*//g;

  return ('FAIL',"Port and weight are required, and must be numeric")
	unless ${$args{weight}} =~ /^\d+$/ && ${$args{port}} =~ /^\d+$/;

  ${$args{fields}} = "distance,weight,port,";
  push @{$args{vallist}}, (${$args{dist}}, ${$args{weight}}, ${$args{port}});

  # Coerce all hostnames to end in ".DOMAIN" for group/default records,
  # or the intended parent domain for live records.
  my $pname = ($args{defrec} eq 'y' ? 'DOMAIN' : domainName($dbh,$args{id}));
  ${$args{host}} =~ s/\.*$/\.$pname/ if ${$args{host}} !~ /$pname$/;

  return ('OK','OK');
} # done SRV record

# Now the custom types

# A+PTR record.  With a very little bit of magic we can also use this sub to validate AAAA+PTR.  Whee!
sub _validate_65280 {
  my $dbh = shift;

  my %args = @_;

  my $code = 'OK';
  my $msg = 'OK';

  if ($args{defrec} eq 'n') {
    # live record;  revrec determines whether we validate the PTR or A component first.

    if ($args{revrec} eq 'y') {
      ($code,$msg) = _validate_12($dbh, %args);
      return ($code,$msg) if $code eq 'FAIL';

      # Check if the reqested domain exists.  If not, coerce the type down to PTR and warn.
      if (!(${$args{domid}} = _hostparent($dbh, ${$args{host}}))) {
	my $addmsg = "Record ".($args{update} ? 'updated' : 'added').
		" as PTR instead of $typemap{${$args{rectype}}};  domain not found for ${$args{host}}";
	$msg .= "\n$addmsg" if $code eq 'WARN';
	$msg = $addmsg if $code eq 'OK';
        ${$args{rectype}} = $reverse_typemap{PTR};
        return ('WARN', $msg);
      }

      # Add domain ID to field list and values
      ${$args{fields}} .= "domain_id,";
      push @{$args{vallist}}, ${$args{domid}};

    } else {
      ($code,$msg) = _validate_1($dbh, %args) if ${$args{rectype}} == 65280;
      ($code,$msg) = _validate_28($dbh, %args) if ${$args{rectype}} == 65281;
      return ($code,$msg) if $code eq 'FAIL';

      # Check if the requested reverse zone exists - note, an IP fragment won't
      # work here since we don't *know* which parent to put it in.
      # ${$args{val}} has been validated as a valid IP by now, in one of the above calls.
      my ($revid) = $dbh->selectrow_array("SELECT rdns_id FROM revzones WHERE revnet >> ?".
	" ORDER BY masklen(revnet) DESC", undef, (${$args{val}}));
      if (!$revid) {
        $msg = "Record ".($args{update} ? 'updated' : 'added')." as ".(${$args{rectype}} == 65280 ? 'A' : 'AAAA').
		" instead of $typemap{${$args{rectype}}};  reverse zone not found for ${$args{val}}";
	${$args{rectype}} = (${$args{rectype}} == 65280 ? $reverse_typemap{A} : $reverse_typemap{AAAA});
	return ('WARN', $msg);
      }

      # Check for duplicate PTRs.  Note we don't have to play games with $code and $msg, because
      # by definition there can't be duplicate PTRs if the reverse zone isn't managed here.
      if ($args{update}) {
	# Record update.  There should usually be an existing PTR (the record being updated)
	my @ptrs = @{ $dbh->selectcol_arrayref("SELECT record_id FROM "._rectable($args{defrec},$args{revrec}).
		" WHERE val = ?", undef, (${$args{val}})) };
	if (@ptrs && (!grep /^$args{update}$/, @ptrs)) {
	  $msg = "PTR record for ${$args{val}} already exists;  adding another will probably not do what you want";
	  $code = 'WARN';
	}
      } else {
	# New record.  Always warn if a PTR exists
	my ($ptrcount) = $dbh->selectrow_array("SELECT count(*) FROM "._rectable($args{defrec},$args{revrec}).
		" WHERE val = ?", undef, (${$args{val}}));
	$msg = "PTR record for ${$args{val}} already exists;  adding another will probably not do what you want"
		if $ptrcount;
	$code = 'WARN' if $ptrcount;
      }

#      my ($ptrcount) = $dbh->selectrow_array("SELECT count(*) FROM "._rectable($args{defrec},$args{revrec}).
#	" WHERE val = ?", undef, ${$args{val}});
#      if ($ptrcount) {
#        my $curid = $dbh->selectrow_array("SELECT record_id FROM "._rectable($args{defrec},$args{revrec}).
#		" WHERE val = ?
#	$msg = "PTR record for ${$args{val}} already exists;  adding another will probably not do what you want";
#	$code = 'WARN';
#      }

      ${$args{fields}} .= "rdns_id,";
      push @{$args{vallist}}, $revid;
    }

  } else {	# defrec eq 'y'
    if ($args{revrec} eq 'y') {
      ($code,$msg) = _validate_12($dbh, %args);
      return ($code,$msg) if $code eq 'FAIL';
      if (${$args{rectype}} == 65280) {
	return ('FAIL',"A+PTR record must be a valid IPv4 address or fragment")
		if ${$args{val}} =~ /:/;
	${$args{val}} =~ s/^ZONE,/ZONE./;       # Clean up after uncertain IP-fragment-type from _validate_12
      } elsif (${$args{rectype}} == 65281) {
	return ('FAIL',"AAAA+PTR record must be a valid IPv6 address or fragment")
		if ${$args{val}} =~ /\./;
	${$args{val}} =~ s/^ZONE,/ZONE::/;      # Clean up after uncertain IP-fragment-type from _validate_12
      }
    } else {
      # This is easy.  I also can't see a real use-case for A/AAAA+PTR in *all* forward
      # domains, since you wouldn't be able to substitute both domain and reverse zone
      # sanely, and you'd end up with guaranteed over-replicated PTR records that would
      # confuse the hell out of pretty much anything that uses them.
##fixme: make this a config flag?
      return ('FAIL', "$typemap{${$args{rectype}}} records not allowed in default domains");
    }
  }

  return ($code, $msg);
} # done A+PTR record

# AAAA+PTR record
# A+PTR above has been magicked to handle AAAA+PTR as well.
sub _validate_65281 {
  return _validate_65280(@_);
} # done AAAA+PTR record

# PTR template record
sub _validate_65282 {
  return ('OK','OK');
} # done PTR template record

# A+PTR template record
sub _validate_65283 {
  return ('OK','OK');
} # done AAAA+PTR template record

# AAAA+PTR template record
sub _validate_65284 {
  return ('OK','OK');
} # done AAAA+PTR template record


##
## Record data substitution subs
##

# Replace ZONE in hostname
sub _ZONE {
  my $zone = shift;
  my $string = shift;
  my $fr = shift || 'f';	# flag for forward/reverse order?  nb: ignored for IP

  my $prefix = $zone->network->addr;	# Just In Case someone managed to slip in
					# a funky subnet that had host bits set.

  $string =~ s/,/./ if !$zone->{isv6};
  $string =~ s/,/::/ if $zone->{isv6};

#  if ($zone->{isv6} && ($zone->masklen % 4) != 0) {
#    # grumpyfail, non-nibble zone.  shouldn't happen
#    return;
#  }

    # Subbing ZONE in the host.  We need to properly ID the netblock range
    # The subbed text should have "network IP with trailing zeros stripped" for
    # blocks lined up on octet (for v4) or 16-bit (for v6) boundaries
    # For blocks that do NOT line up on these boundaries, we tack on an extra "-0",
    # then take the most significant octet or 16-bit chunk of the "broadcast" IP and
    # append it after a double-dash
    # ie:
    # 8.0.0.0/6 -> 8.0.0.0 -> 11.255.255.255;  sub should be 8--11
    # 10.0.0.0/12 -> 10.0.0.0 -> 10.0.0.0 -> 10.15.255.255;  sub should be 10-0--15
    # 192.168.4.0/22 -> 192.168.4.0 -> 192.168.7.255;  sub should be 192-168-4--7
    # 192.168.0.8/29 -> 192.168.0.8 -> 192.168.0.15;  sub should be 192-168-0-8--15
    # Similar for v6
    if (!$zone->{isv6}) {
      my $bc = $zone->broadcast->addr;
      if ($zone->masklen > 24) {
      	$bc =~ s/^\d+\.\d+\.\d+\.//;
      } elsif ($zone->masklen > 16) {
	$prefix =~ s/\.0$//;
      	$bc =~ s/^\d+\.\d+\.//;
      } elsif ($zone->masklen > 8) {
      	$bc =~ s/^\d+\.//;
	$prefix =~ s/\.0\.0$//;
      } else {
	$prefix =~ s/\.0\.0\.0$//;
      }
      if ($zone->masklen % 8) {
	$bc =~ s/(\.255)+$//;
	$prefix .= "--$bc";	#"--".zone->masklen;	# use range or mask length?
      }
    } else {
      if (($zone->masklen % 16) != 0) {
	# Strip trailing :0 off $prefix, and :ffff off the broadcast IP
	# Strip the leading 16-bit chunks off the front of the broadcast IP
	# Append the remaining 16-bit chunk to the prefix after "--"
	my $bc = $zone->broadcast->addr;
	for (my $i=0; $i<(7-int($zone->masklen / 16)); $i++) {
	  $prefix =~ s/:0$//;
	  $bc =~ s/:ffff$//;
	}
	$bc =~ s/^([a-f0-9]+:)+//;
	$prefix .= "--$bc";
      } else {
	# Strip off :0 from the end until we reach the netblock length.
	for (my $i=0; $i<(8-$zone->masklen / 16); $i++) {
	  $prefix =~ s/:0$//;
	}
      }
    }

  # Replace . and : with -
  # If flagged for reverse-order, split on . or :, reverse, and join with -
    if ($fr eq 'f') {
      $prefix =~ s/[:.]+/-/g;
    } else {
      $prefix = join('-', reverse(split(/[:.]/, $prefix)));
    }
    $string =~ s/ZONE/$prefix/;
#  }
  return $string;
} # done _ZONE



##
## Initialization and cleanup subs
##


## DNSDB::loadConfig()
# Load the minimum required initial state (DB connect info) from a config file
# Load misc other bits while we're at it.
# Takes an optional basename and config path to look for
# Populates the %config and %def hashes
sub loadConfig {
  my $basename = shift || '';	# this will work OK
##fixme  $basename isn't doing what I think I thought I was trying to do.

  my $deferr = '';	# place to put error from default config file in case we can't find either one

  my $configroot = "/etc/dnsdb";	##CFG_LEAF##
  $configroot = '' if $basename =~ m|^/|;
  $basename .= ".conf" if $basename !~ /\.conf$/;
  my $defconfig = "$configroot/dnsdb.conf";
  my $siteconfig = "$configroot/$basename";

  # System defaults
  __cfgload("$defconfig") or $deferr = $errstr;

  # Per-site-ish settings.
  if ($basename ne '.conf') {
    unless (__cfgload("$siteconfig")) {
      $errstr = ($deferr ? "Error opening default config file $defconfig: $deferr\n" : '').
	"Error opening site config file $siteconfig";
      return;
    }
  }

  # Munge log_failures.
  if ($config{log_failures} ne '1' && $config{log_failures} ne '0') {
    # true/false, on/off, yes/no all valid.
    if ($config{log_failures} =~ /^(?:true|false|on|off|yes|no)$/) {
      if ($config{log_failures} =~ /(?:true|on|yes)/) {
	$config{log_failures} = 1;
      } else {
	$config{log_failures} = 0;
      }
    } else {
      $errstr = "Bad log_failures setting $config{log_failures}";
      $config{log_failures} = 1;
      # Bad setting shouldn't be fatal.
      # return 2;
    }
  }

  # All good, clear the error and go home.
  $errstr = '';
  return 1;
} # end loadConfig()


## DNSDB::__cfgload()
# Private sub to parse a config file and load it into %config
# Takes a file handle on an open config file
sub __cfgload {
  $errstr = '';
  my $cfgfile = shift;

  if (open CFG, "<$cfgfile") {
    while (<CFG>) {
      chomp;
      s/^\s*//;
      next if /^#/;
      next if /^$/;
# hmm.  more complex bits in this file might require [heading] headers, maybe?
#    $mode = $1 if /^\[(a-z)+]/;
    # DB connect info
      $config{dbname}	= $1 if /^dbname\s*=\s*([a-z0-9_.-]+)/i;
      $config{dbuser}	= $1 if /^dbuser\s*=\s*([a-z0-9_.-]+)/i;
      $config{dbpass}	= $1 if /^dbpass\s*=\s*([a-z0-9_.-]+)/i;
      $config{dbhost}	= $1 if /^dbhost\s*=\s*([a-z0-9_.-]+)/i;
      # SOA defaults
      $def{contact}	= $1 if /^contact\s*=\s*([a-z0-9_.-]+)/i;
      $def{prins}	= $1 if /^prins\s*=\s*([a-z0-9_.-]+)/i;
      $def{soattl}	= $1 if /^soattl\s*=\s*(\d+)/i;
      $def{refresh}	= $1 if /^refresh\s*=\s*(\d+)/i;
      $def{retry}	= $1 if /^retry\s*=\s*(\d+)/i;
      $def{expire}	= $1 if /^expire\s*=\s*(\d+)/i;
      $def{minttl}	= $1 if /^minttl\s*=\s*(\d+)/i;
      $def{ttl}		= $1 if /^ttl\s*=\s*(\d+)/i;
      # Mail settings
      $config{mailhost}		= $1 if /^mailhost\s*=\s*([a-z0-9_.-]+)/i;
      $config{mailnotify}	= $1 if /^mailnotify\s*=\s*([a-z0-9_.\@-]+)/i;
      $config{mailsender}	= $1 if /^mailsender\s*=\s*([a-z0-9_.\@-]+)/i;
      $config{mailname}		= $1 if /^mailname\s*=\s*([a-z0-9\s_.-]+)/i;
      $config{orgname}		= $1 if /^orgname\s*=\s*([a-z0-9\s_.,'-]+)/i;
      $config{domain}		= $1 if /^domain\s*=\s*([a-z0-9_.-]+)/i;
      # session - note this is fed directly to CGI::Session
      $config{timeout}		= $1 if /^[tT][iI][mM][eE][oO][uU][tT]\s*=\s*(\d+[smhdwMy]?)/;
      $config{sessiondir}	= $1 if m{^sessiondir\s*=\s*([a-z0-9/_.-]+)}i;
      # misc
      $config{log_failures}	= $1 if /^log_failures\s*=\s*([a-z01]+)/i;
      $config{perpage}		= $1 if /^perpage\s*=\s*(\d+)/i;
    }
    close CFG;
  } else {
    $errstr = $!;
    return;
  }
  return 1;
} # end __cfgload()


## DNSDB::connectDB()
# Creates connection to DNS database.
# Requires the database name, username, and password.
# Returns a handle to the db.
# Set up for a PostgreSQL db;  could be any transactional DBMS with the
# right changes.
sub connectDB {
  $errstr = '';
  my $dbname = shift;
  my $user = shift;
  my $pass = shift;
  my $dbh;
  my $DSN = "DBI:Pg:dbname=$dbname";

  my $host = shift;
  $DSN .= ";host=$host" if $host;

# Note that we want to autocommit by default, and we will turn it off locally as necessary.
# We may not want to print gobbledygook errors;  YMMV.  Have to ponder that further.
  $dbh = DBI->connect($DSN, $user, $pass, {
	AutoCommit => 1,
	PrintError => 0
	})
    or return (undef, $DBI::errstr) if(!$dbh);

##fixme:  initialize the DB if we can't find the table (since, by definition, there's
# nothing there if we can't select from it...)
  my $tblsth = $dbh->prepare("SELECT count(*) FROM pg_catalog.pg_class WHERE relkind='r' AND relname=?");
  my ($tblcount) = $dbh->selectrow_array($tblsth, undef, ('misc'));
  return (undef,$DBI::errstr) if $dbh->err;

#if ($tblcount == 0) {
#  # create tables one at a time, checking for each.
#  return (undef, "check table misc missing");
#}


# Return here if we can't select.
# This should retrieve the dbversion key.
  my $sth = $dbh->prepare("SELECT key,value FROM misc WHERE misc_id=1");
  $sth->execute();
  return (undef,$DBI::errstr) if ($sth->err);

##fixme:  do stuff to the DB on version mismatch
# x.y series should upgrade on $DNSDB::VERSION > misc(key=>version)
# DB should be downward-compatible;  column defaults should give sane (if possibly
# useless-and-needs-help) values in columns an older software stack doesn't know about.

# See if the select returned anything (or null data).  This should
# succeed if the select executed, but...
  $sth->fetchrow();
  return (undef,$DBI::errstr)  if ($sth->err);

  $sth->finish;

# If we get here, we should be OK.
  return ($dbh,"DB connection OK");
} # end connectDB


## DNSDB::finish()
# Cleans up after database handles and so on.
# Requires a database handle
sub finish {
  my $dbh = $_[0];
  $dbh->disconnect;
} # end finish


## DNSDB::initGlobals()
# Initialize global variables
# NB: this does NOT include web-specific session variables!
# Requires a database handle
sub initGlobals {
  my $dbh = shift;

# load record types from database
  my $sth = $dbh->prepare("SELECT val,name,stdflag FROM rectypes");
  $sth->execute;
  while (my ($recval,$recname,$stdflag) = $sth->fetchrow_array()) {
    $typemap{$recval} = $recname;
    $reverse_typemap{$recname} = $recval;
    # now we fill the record validation function hash
    if ($stdflag < 5) {
      my $fn = "_validate_$recval";
      $validators{$recval} = \&$fn;
    } else {
      my $fn = "sub { return ('FAIL','Type $recval ($recname) not supported'); }";
      $validators{$recval} = eval $fn;
    }
  }
} # end initGlobals


## DNSDB::login()
# Takes a database handle, username and password
# Returns a userdata hash (UID, GID, username, fullname parts) if username exists
# and password matches the one on file
# Returns undef otherwise
sub login {
  my $dbh = shift;
  my $user = shift;
  my $pass = shift;

  my $userinfo = $dbh->selectrow_hashref("SELECT user_id,group_id,password,firstname,lastname FROM users WHERE username=?",
	undef, ($user) );
  return if !$userinfo;

  if ($userinfo->{password} =~ m|^\$1\$([A-Za-z0-9/.]+)\$|) {
    # native passwords (crypt-md5)
    return if $userinfo->{password} ne unix_md5_crypt($pass,$1);
  } elsif ($userinfo->{password} =~ /^[0-9a-f]{32}$/) {
    # VegaDNS import (hex-coded MD5)
    return if $userinfo->{password} ne md5_hex($pass);
  } else {
    # plaintext (convenient now and then)
    return if $userinfo->{password} ne $pass;
  }

  return $userinfo;
} # end login()


## DNSDB::initActionLog()
# Set up action logging.  Takes a database handle and user ID
# Sets some internal globals and Does The Right Thing to set up a logging channel.
# This sets up _log() to spew out log entries to the defined channel without worrying
# about having to open a file or a syslog channel
##fixme Need to call _initActionLog_blah() for various logging channels, configured
# via dnsdb.conf, in $config{log_channel} or something
# See https://secure.deepnet.cx/trac/dnsadmin/ticket/21
sub initActionLog {
  my $dbh = shift;
  my $uid = shift;

  return if !$uid;

  # snag user info for logging.  there's got to be a way to not have to pass this back
  # and forth from a caller, but web usage means no persistence we can rely on from
  # the server side.
  my ($username,$fullname) = $dbh->selectrow_array("SELECT username, firstname || ' ' || lastname".
	" FROM users WHERE user_id=?", undef, ($uid));
##fixme: errors are unpossible!

  $userdata{username} = $username;
  $userdata{userid} = $uid;
  $userdata{fullname} = $fullname;

  # convert to real check once we have other logging channels
  # if ($config{log_channel} eq 'sql') {
  #   Open Log, Sez Me!
  # }

} # end initActionLog


## DNSDB::initPermissions()
# Set up permissions global
# Takes database handle and UID
sub initPermissions {
  my $dbh = shift;
  my $uid = shift;

#  %permissions = $(getPermissions($dbh,'user',$uid));
  getPermissions($dbh, 'user', $uid, \%permissions);

} # end initPermissions()


## DNSDB::getPermissions()
# Get permissions from DB
# Requires DB handle, group or user flag, ID, and hashref.
sub getPermissions {
  my $dbh = shift;
  my $type = shift;
  my $id = shift;
  my $hash = shift;

  my $sql = qq(
	SELECT
	p.admin,p.self_edit,
	p.group_create,p.group_edit,p.group_delete,
	p.user_create,p.user_edit,p.user_delete,
	p.domain_create,p.domain_edit,p.domain_delete,
	p.record_create,p.record_edit,p.record_delete
	FROM permissions p
	);
  if ($type eq 'group') {
    $sql .= qq(
	JOIN groups g ON g.permission_id=p.permission_id
	WHERE g.group_id=?
	);
  } else {
    $sql .= qq(
	JOIN users u ON u.permission_id=p.permission_id
	WHERE u.user_id=?
	);
  }

  my $sth = $dbh->prepare($sql);

  $sth->execute($id) or die "argh: ".$sth->errstr;

#  my $permref = $sth->fetchrow_hashref;
#  return $permref;
#  $hash = $permref;
# Eww.  Need to learn how to forcibly drop a hashref onto an existing hash.
  ($hash->{admin},$hash->{self_edit},
	$hash->{group_create},$hash->{group_edit},$hash->{group_delete},
	$hash->{user_create},$hash->{user_edit},$hash->{user_delete},
	$hash->{domain_create},$hash->{domain_edit},$hash->{domain_delete},
	$hash->{record_create},$hash->{record_edit},$hash->{record_delete})
	= $sth->fetchrow_array;

} # end getPermissions()


## DNSDB::changePermissions()
# Update an ACL entry
# Takes a db handle, type, owner-id, and hashref for the changed permissions.
sub changePermissions {
  my $dbh = shift;
  my $type = shift;
  my $id = shift;
  my $newperms = shift;
  my $inherit = shift || 0;

  my $failmsg = '';

  # see if we're switching from inherited to custom.  for bonus points,
  # snag the permid and parent permid anyway, since we'll need the permid
  # to set/alter custom perms, and both if we're switching from custom to
  # inherited.
  my $sth = $dbh->prepare("SELECT (u.permission_id=g.permission_id) AS was_inherited,u.permission_id,g.permission_id".
	" FROM ".($type eq 'user' ? 'users' : 'groups')." u ".
	" JOIN groups g ON u.".($type eq 'user' ? '' : 'parent_')."group_id=g.group_id ".
	" WHERE u.".($type eq 'user' ? 'user' : 'group')."_id=?");
  $sth->execute($id);

  my ($wasinherited,$permid,$parpermid) = $sth->fetchrow_array;

# hack phtoui
# group id 1 is "special" in that it's it's own parent (err...  possibly.)
# may make its parent id 0 which doesn't exist, and as a bonus is Perl-false.
  $wasinherited = 0 if ($type eq 'group' && $id == 1);

  local $dbh->{AutoCommit} = 0;
  local $dbh->{RaiseError} = 1;

  # Wrap all the SQL in a transaction
  eval {
    if ($inherit) {

      $dbh->do("UPDATE ".($type eq 'user' ? 'users' : 'groups')." SET inherit_perm='t',permission_id=? ".
	"WHERE ".($type eq 'user' ? 'user' : 'group')."_id=?", undef, ($parpermid, $id) );
      $dbh->do("DELETE FROM permissions WHERE permission_id=?", undef, ($permid) );

    } else {

      if ($wasinherited) {	# munge new permission entry in if we're switching from inherited perms
##fixme: need to add semirecursive bit to properly munge inherited permission ID on subgroups and users
# ... if'n'when we have groups with fully inherited permissions.
        # SQL is coo
	$dbh->do("INSERT INTO permissions ($permlist,".($type eq 'user' ? 'user' : 'group')."_id) ".
		"SELECT $permlist,? FROM permissions WHERE permission_id=?", undef, ($id,$permid) );
	($permid) = $dbh->selectrow_array("SELECT permission_id FROM permissions ".
		"WHERE ".($type eq 'user' ? 'user' : 'group')."_id=?", undef, ($id) );
	$dbh->do("UPDATE ".($type eq 'user' ? 'users' : 'groups')." SET inherit_perm='f',permission_id=? ".
		"WHERE ".($type eq 'user' ? 'user' : 'group')."_id=?", undef, ($permid, $id) );
      }

      # and now set the permissions we were passed
      foreach (@permtypes) {
	if (defined ($newperms->{$_})) {
	  $dbh->do("UPDATE permissions SET $_=? WHERE permission_id=?", undef, ($newperms->{$_},$permid) );
	}
      }

    } # (inherited->)? custom

    $dbh->commit;
  }; # end eval
  if ($@) {
    my $msg = $@;
    eval { $dbh->rollback; };
    return ('FAIL',"$failmsg: $msg ($permid)");
  } else {
    return ('OK',$permid);
  }

} # end changePermissions()


## DNSDB::comparePermissions()
# Compare two permission hashes
# Returns '>', '<', '=', '!'
sub comparePermissions {
  my $p1 = shift;
  my $p2 = shift;

  my $retval = '=';	# assume equality until proven otherwise

  no warnings "uninitialized";

  foreach (@permtypes) {
    next if $p1->{$_} == $p2->{$_};	# equal is good
    if ($p1->{$_} && !$p2->{$_}) {
      if ($retval eq '<') {	# if we've already found an unequal pair where
        $retval = '!';		# $p2 has more access, and we now find a pair
        last;			# where $p1 has more access, the overall access
      }				# is neither greater or lesser, it's unequal.
      $retval = '>';
    }
    if (!$p1->{$_} && $p2->{$_}) {
      if ($retval eq '>') {	# if we've already found an unequal pair where
        $retval = '!';		# $p1 has more access, and we now find a pair
        last;			# where $p2 has more access, the overall access
      }				# is neither greater or lesser, it's unequal.
      $retval = '<';
    }
  }
  return $retval;
} # end comparePermissions()


## DNSDB::changeGroup()
# Change group ID of an entity
# Takes a database handle, entity type, entity ID, and new group ID
sub changeGroup {
  my $dbh = shift;
  my $type = shift;
  my $id = shift;
  my $newgrp = shift;

##fixme:  fail on not enough args
  #return ('FAIL', "Missing 

  if ($type eq 'domain') {
    $dbh->do("UPDATE domains SET group_id=? WHERE domain_id=?", undef, ($newgrp, $id))
	or return ('FAIL','Group change failed: '.$dbh->errstr);
  } elsif ($type eq 'user') {
    $dbh->do("UPDATE users SET group_id=? WHERE user_id=?", undef, ($newgrp, $id))
	or return ('FAIL','Group change failed: '.$dbh->errstr);
  } elsif ($type eq 'group') {
    $dbh->do("UPDATE groups SET parent_group_id=? WHERE group_id=?", undef, ($newgrp, $id))
	or return ('FAIL','Group change failed: '.$dbh->errstr);
  }
  return ('OK','OK');
} # end changeGroup()


##
## Processing subs
##

## DNSDB::addDomain()
# Add a domain
# Takes a database handle, domain name, numeric group, boolean(ish) state (active/inactive),
# and user info hash (for logging).
# Returns a status code and message
sub addDomain {
  $errstr = '';
  my $dbh = shift;
  return ('FAIL',"Need database handle") if !$dbh;
  my $domain = shift;
  return ('FAIL',"Domain must not be blank") if !$domain;
  my $group = shift;
  return ('FAIL',"Need group") if !defined($group);
  my $state = shift;
  return ('FAIL',"Need domain status") if !defined($state);

  my %userinfo = @_;	# remaining bits.
# user ID, username, user full name

  $state = 1 if $state =~ /^active$/;
  $state = 1 if $state =~ /^on$/;
  $state = 0 if $state =~ /^inactive$/;
  $state = 0 if $state =~ /^off$/;

  return ('FAIL',"Invalid domain status") if $state !~ /^\d+$/;

  return ('FAIL', "Invalid characters in domain") if $domain !~ /^[a-zA-Z0-9_.-]+$/;

  my $sth = $dbh->prepare("SELECT domain_id FROM domains WHERE domain=?");
  my $dom_id;

# quick check to start to see if we've already got one
  $sth->execute($domain);
  ($dom_id) = $sth->fetchrow_array;

  return ('FAIL', "Domain already exists") if $dom_id;

  # Allow transactions, and raise an exception on errors so we can catch it later.
  # Use local to make sure these get "reset" properly on exiting this block
  local $dbh->{AutoCommit} = 0;
  local $dbh->{RaiseError} = 1;

  # Wrap all the SQL in a transaction
  eval {
    # insert the domain...
    $dbh->do("INSERT INTO domains (domain,group_id,status) VALUES (?,?,?)", undef, ($domain, $group, $state));

    # get the ID...
    ($dom_id) = $dbh->selectrow_array("SELECT domain_id FROM domains WHERE domain=?", undef, ($domain));

    _log($dbh, (domain_id => $dom_id, group_id => $group,
	entry => "Added ".($state ? 'active' : 'inactive')." domain $domain"));

    # ... and now we construct the standard records from the default set.  NB:  group should be variable.
    my $sth = $dbh->prepare("SELECT host,type,val,distance,weight,port,ttl FROM default_records WHERE group_id=?");
    my $sth_in = $dbh->prepare("INSERT INTO records (domain_id,host,type,val,distance,weight,port,ttl)".
	" VALUES ($dom_id,?,?,?,?,?,?,?)");
    $sth->execute($group);
    while (my ($host,$type,$val,$dist,$weight,$port,$ttl) = $sth->fetchrow_array()) {
      $host =~ s/DOMAIN/$domain/g;
      $val =~ s/DOMAIN/$domain/g;
      $sth_in->execute($host,$type,$val,$dist,$weight,$port,$ttl);
      if ($typemap{$type} eq 'SOA') {
	my @tmp1 = split /:/, $host;
	my @tmp2 = split /:/, $val;
	_log($dbh, (domain_id => $dom_id, group_id => $group,
		entry => "[new $domain] Added SOA record [contact $tmp1[0]] [master $tmp1[1]] ".
		"[refresh $tmp2[0]] [retry $tmp2[1]] [expire $tmp2[2]] [minttl $tmp2[3]], TTL $ttl"));
      } else {
	my $logentry = "[new $domain] Added record '$host $typemap{$type}";
	$logentry .= " [distance $dist]" if $typemap{$type} eq 'MX';
	$logentry .= " [priority $dist] [weight $weight] [port $port]" if $typemap{$type} eq 'SRV';
	_log($dbh, (domain_id => $dom_id, group_id => $group,
		entry => $logentry." $val', TTL $ttl"));
      }
    }

    # once we get here, we should have suceeded.
    $dbh->commit;
  }; # end eval

  if ($@) {
    my $msg = $@;
    eval { $dbh->rollback; };
    _log($dbh, (group_id => $group, entry => "Failed adding domain $domain ($msg)"))
	if $config{log_failures};
    $dbh->commit;	# since we enabled transactions earlier
    return ('FAIL',$msg);
  } else {
    return ('OK',$dom_id);
  }
} # end addDomain


## DNSDB::delZone()
# Delete a forward or reverse zone.
# Takes a database handle, zone ID, and forward/reverse flag.
# for now, just delete the records, then the domain.
# later we may want to archive it in some way instead (status code 2, for example?)
sub delZone {
  my $dbh = shift;
  my $zoneid = shift;
  my $revrec = shift;

  # Allow transactions, and raise an exception on errors so we can catch it later.
  # Use local to make sure these get "reset" properly on exiting this block
  local $dbh->{AutoCommit} = 0;
  local $dbh->{RaiseError} = 1;

  my $msg = '';
  my $failmsg = '';
  my $zone = ($revrec eq 'n' ? domainName($dbh, $zoneid) : revName($dbh, $zoneid));

  # Set this up here since we may use if if $config{log_failures} is enabled
  my %loghash;
  $loghash{domain_id} = $zoneid if $revrec eq 'n';
  $loghash{rdns_id} = $zoneid if $revrec eq 'y';
  $loghash{group_id} = parentID($dbh,
	(id => $zoneid, type => ($revrec eq 'n' ? 'domain' : 'revzone'), revrec => $revrec) );

  # Wrap all the SQL in a transaction
  eval {
    # Disentangle custom record types before removing the
    # ones that are only in the zone to be deleted
    if ($revrec eq 'n') {
      my $sth = $dbh->prepare("UPDATE records SET type=?,domain_id=0 WHERE domain_id=? AND type=?");
      $failmsg = "Failure converting multizone types to single-zone";
      $sth->execute($reverse_typemap{PTR}, $zoneid, 65280);
      $sth->execute($reverse_typemap{PTR}, $zoneid, 65281);
      $sth->execute(65282, $zoneid, 65283);
      $sth->execute(65282, $zoneid, 65284);
      $failmsg = "Failure removing domain records";
      $dbh->do("DELETE FROM records WHERE domain_id=?", undef, ($zoneid));
      $failmsg = "Failure removing domain";
      $dbh->do("DELETE FROM domains WHERE domain_id=?", undef, ($zoneid));
    } else {
      my $sth = $dbh->prepare("UPDATE records SET type=?,rdns_id=0 WHERE rdns_id=? AND type=?");
      $failmsg = "Failure converting multizone types to single-zone";
      $sth->execute($reverse_typemap{A}, $zoneid, 65280);
      $sth->execute($reverse_typemap{AAAA}, $zoneid, 65281);
# We don't have an "A template" or "AAAA template" type, although it might be useful for symmetry.
#      $sth->execute(65285?, $zoneid, 65283);
#      $sth->execute(65285?, $zoneid, 65284);
      $failmsg = "Failure removing reverse records";
      $dbh->do("DELETE FROM records WHERE rdns_id=?", undef, ($zoneid));
      $failmsg = "Failure removing reverse zone";
      $dbh->do("DELETE FROM revzones WHERE rdns_id=?", undef, ($zoneid));
    }

    $msg = "Deleted ".($revrec eq 'n' ? 'domain' : 'reverse zone')." $zone";
    $loghash{entry} = $msg;
    _log($dbh, %loghash);

    # once we get here, we should have suceeded.
    $dbh->commit;
  }; # end eval

  if ($@) {
    $msg = $@;
    eval { $dbh->rollback; };
    $loghash{entry} = "Delete $zone: $failmsg: $msg";
    _log($dbh, %loghash) if $config{log_failures};
    $dbh->commit;	# since we enabled transactions earlier
    return ('FAIL',"Delete $zone: $failmsg: $msg");
  } else {
    return ('OK',$msg);
  }

} # end delZone()


## DNSDB::domainName()
# Return the domain name based on a domain ID
# Takes a database handle and the domain ID
# Returns the domain name or undef on failure
sub domainName {
  $errstr = '';
  my $dbh = shift;
  my $domid = shift;
  my ($domname) = $dbh->selectrow_array("SELECT domain FROM domains WHERE domain_id=?", undef, ($domid) );
  $errstr = $DBI::errstr if !$domname;
  return $domname if $domname;
} # end domainName()


## DNSDB::revName()
# Return the reverse zone name based on an rDNS ID
# Takes a database handle and the rDNS ID
# Returns the reverse zone name or undef on failure
sub revName {
  $errstr = '';
  my $dbh = shift;
  my $revid = shift;
  my ($revname) = $dbh->selectrow_array("SELECT revnet FROM revzones WHERE rdns_id=?", undef, ($revid) );
  $errstr = $DBI::errstr if !$revname;
  return $revname if $revname;
} # end revName()


## DNSDB::domainID()
# Takes a database handle and domain name
# Returns the domain ID number
sub domainID {
  $errstr = '';
  my $dbh = shift;
  my $domain = shift;
  my ($domid) = $dbh->selectrow_array("SELECT domain_id FROM domains WHERE domain=?", undef, ($domain) );
  $errstr = $DBI::errstr if !$domid;
  return $domid if $domid;
} # end domainID()


## DNSDB::revID()
# Takes a database handle and reverse zone name
# Returns the rDNS ID number
sub revID {
  $errstr = '';
  my $dbh = shift;
  my $revzone = shift;
  my ($revid) = $dbh->selectrow_array("SELECT rdns_id FROM revzones WHERE revnet=?", undef, ($revzone) );
  $errstr = $DBI::errstr if !$revid;
  return $revid if $revid;
} # end revID()


## DNSDB::addRDNS
# Adds a reverse DNS zone
# Takes a database handle, CIDR block, reverse DNS pattern, numeric group,
# and boolean(ish) state (active/inactive)
# Returns a status code and message
sub addRDNS {
  my $dbh = shift;
  my $zone = NetAddr::IP->new(shift);
  return ('FAIL',"Zone name must be a valid CIDR netblock") unless ($zone && $zone->addr !~ /^0/);
  my $revpatt = shift;	# construct a custom (A/AAAA+)? PTR template record
  my $group = shift;
  my $state = shift;

  $state = 1 if $state =~ /^active$/;
  $state = 1 if $state =~ /^on$/;
  $state = 0 if $state =~ /^inactive$/;
  $state = 0 if $state =~ /^off$/;

  return ('FAIL',"Invalid zone status") if $state !~ /^\d+$/;

# quick check to start to see if we've already got one
  my ($rdns_id) = $dbh->selectrow_array("SELECT rdns_id FROM revzones WHERE revzone=?", undef, ("$zone"));

  return ('FAIL', "Zone already exists") if $rdns_id;

  # Allow transactions, and raise an exception on errors so we can catch it later.
  # Use local to make sure these get "reset" properly on exiting this block
  local $dbh->{AutoCommit} = 0;
  local $dbh->{RaiseError} = 1;

  my $warnstr = '';
  my $defttl = 3600;	# 1 hour should be reasonable.  And unless things have gone horribly
			# wrong, we should have a value to override this anyway.

  # Wrap all the SQL in a transaction
  eval {
    # insert the domain...
    $dbh->do("INSERT INTO revzones (revnet,group_id,status) VALUES (?,?,?)", undef, ($zone, $group, $state));

    # get the ID...
    ($rdns_id) = $dbh->selectrow_array("SELECT currval('revzones_rdns_id_seq')");

    _log($dbh, (rdns_id => $rdns_id, group_id => $group,
	entry => "Added ".($state ? 'active' : 'inactive')." reverse zone $zone"));

    # ... and now we construct the standard records from the default set.  NB:  group should be variable.
    my $sth = $dbh->prepare("SELECT host,type,val,ttl FROM default_rev_records WHERE group_id=?");
    my $sth_in = $dbh->prepare("INSERT INTO records (rdns_id,domain_id,host,type,val,ttl)".
	" VALUES ($rdns_id,?,?,?,?,?)");
    $sth->execute($group);
    while (my ($host,$type,$val,$ttl) = $sth->fetchrow_array()) {
      # Silently skip v4/v6 mismatches.  This is not an error, this is expected.
      if ($zone->{isv6}) {
	next if ($type == 65280 || $type == 65283);
      } else {
	next if ($type == 65281 || $type == 65284);
      }

      $host =~ s/ADMINDOMAIN/$config{domain}/g;

      # Check to make sure the IP stubs will fit in the zone.  Under most usage failures here should be rare.
      # On failure, tack a note on to a warning string and continue without adding this record.
      # While we're at it, we substitute $zone for ZONE in the value.
      if ($val eq 'ZONE') {
	next if $revpatt;	# If we've got a pattern, we skip the default record version.
##fixme?  do we care if we have multiple whole-zone templates?
	$val = $zone->network;
      } elsif ($val =~ /ZONE/) {
	my $tmpval = $val;
	$tmpval =~ s/ZONE//;
	# Bend the rules and allow single-trailing-number PTR or PTR template records to be inserted
	# as either v4 or v6.  May make this an off-by-default config flag
	# Note that the origin records that may trigger this **SHOULD** already have ZONE,\d
	if ($type == 12 || $type == 65282) {
	  $tmpval =~ s/[,.]/::/ if ($tmpval =~ /^[,.]\d+$/ && $zone->{isv6});
	  $tmpval =~ s/[,:]+/./ if ($tmpval =~ /^(?:,|::)\d+$/ && !$zone->{isv6});
	}
	my $addr;
	if (_ipparent($dbh, 'n', 'y', \$tmpval, $rdns_id, \$addr)) {
	  $val = $addr->addr;
	} else {
	  $warnstr .= "\nDefault record '$val $typemap{$type} $host' doesn't fit in $zone, skipping";
	  next;
	}
      }

      # Substitute $zone for ZONE in the hostname.
      $host = _ZONE($zone, $host);

      # Fill in the forward domain ID if we can find it, otherwise:
      # Coerce type down to PTR or PTR template if we can't
      my $domid = 0;
      if ($type >= 65280) {
	if (!($domid = _hostparent($dbh, $host))) {
	  $warnstr .= "\nRecord added as PTR instead of $typemap{$type};  domain not found for $host";
	  $type = $reverse_typemap{PTR};
	  $domid = 0;	# just to be explicit.
	}
      }

      $sth_in->execute($domid,$host,$type,$val,$ttl);

      if ($typemap{$type} eq 'SOA') {
	my @tmp1 = split /:/, $host;
	my @tmp2 = split /:/, $val;
	_log($dbh, (rdns_id => $rdns_id, group_id => $group,
		entry => "[new $zone] Added SOA record [contact $tmp1[0]] [master $tmp1[1]] ".
		"[refresh $tmp2[0]] [retry $tmp2[1]] [expire $tmp2[2]] [minttl $tmp2[3]], TTL $ttl"));
	$defttl = $tmp2[3];
      } else {
	my $logentry = "[new $zone] Added record '$host $typemap{$type}";
	_log($dbh, (rdns_id => $rdns_id, domain_id => $domid, group_id => $group,
		entry => $logentry." $val', TTL $ttl"));
      }
    }

    # Generate record based on provided pattern.  
    if ($revpatt) {
      my $host;
      my $type = ($zone->{isv6} ? 65284 : 65283);
      my $val = $zone->network;

      # Substitute $zone for ZONE in the hostname.
      $host = _ZONE($zone, $revpatt);

      my $domid = 0;
      if (!($domid = _hostparent($dbh, $host))) {
	$warnstr .= "\nDefault pattern added as PTR template instead of $typemap{$type};  domain not found for $host";
	$type = 65282;
	$domid = 0;	# just to be explicit.
      }

      $sth_in->execute($domid,$host,$type,$val,$defttl);
      my $logentry = "[new $zone] Added record '$host $typemap{$type}";
      _log($dbh, (rdns_id => $rdns_id, domain_id => $domid, group_id => $group,
	entry => $logentry." $val', TTL $defttl from pattern"));
    }

    # If there are warnings (presumably about default records skipped for cause) log them
    _log($dbh, (rdns_id => $rdns_id, group_id => $group, entry => "Warning(s) adding $zone:$warnstr"))
	if $warnstr;

    # once we get here, we should have suceeded.
    $dbh->commit;
  }; # end eval

  if ($@) {
    my $msg = $@;
    eval { $dbh->rollback; };
    _log($dbh, (group_id => $group, entry => "Failed adding reverse zone $zone ($msg)"))
	if $config{log_failures};
    $dbh->commit;	# since we enabled transactions earlier
    return ('FAIL',$msg);
  } else {
    my $retcode = 'OK';
    if ($warnstr) {
      $resultstr = $warnstr;
      $retcode = 'WARN';
    }
    return ($retcode, $rdns_id);
  }

} # end addRDNS()


## DNSDB::getZoneCount
# Get count of zones in group or groups
# Takes a database handle and hash containing:
#  - the "current" group
#  - an array of "acceptable" groups
#  - a flag for forward/reverse zones
#  - Optionally accept a "starts with" and/or "contains" filter argument
# Returns an integer count of the resulting zone list.
sub getZoneCount {
  my $dbh = shift;

  my %args = @_;

  my @filterargs;
  $args{startwith} = undef if $args{startwith} && $args{startwith} !~ /^(?:[a-z]|0-9)$/;
  push @filterargs, "^$args{startwith}" if $args{startwith};
  $args{filter} =~ s/\./\[\.\]/g if $args{filter};	# only match literal dots, usually in reverse zones
  push @filterargs, $args{filter} if $args{filter};

  my $sql;
  # Not as compact, and fix-me-twice if the common bits get wrong, but much easier to read
  if ($args{revrec} eq 'n') {
    $sql = "SELECT count(*) FROM domains".
	" WHERE group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
	($args{startwith} ? " AND domain ~* ?" : '').
	($args{filter} ? " AND domain ~* ?" : '');
  } else {
    $sql = "SELECT count(*) FROM revzones".
	" WHERE group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
	($args{startwith} ? " AND CAST(revnet AS VARCHAR) ~* ?" : '').
	($args{filter} ? " AND CAST(revnet AS VARCHAR) ~* ?" : '');
  }
  my ($count) = $dbh->selectrow_array($sql, undef, @filterargs);
  return $count;
} # end getZoneCount()


## DNSDB::getZoneList()
# Get a list of zones in the specified group(s)
# Takes the same arguments as getZoneCount() above
# Returns a reference to an array of hashrefs suitable for feeding to HTML::Template
sub getZoneList {
  my $dbh = shift;

  my %args = @_;

  my @zonelist;

  $args{sortorder} = 'ASC' if !grep $args{sortorder}, ('ASC','DESC');
  $args{offset} = 0 if !$args{offset} || $args{offset} !~ /^(?:all|\d+)$/;

  my @filterargs;
  $args{startwith} = undef if $args{startwith} && $args{startwith} !~ /^(?:[a-z]|0-9)$/;
  push @filterargs, "^$args{startwith}" if $args{startwith};
  $args{filter} =~ s/\./\[\.\]/g if $args{filter};	# only match literal dots, usually in reverse zones
  push @filterargs, $args{filter} if $args{filter};

  my $sql;
  # Not as compact, and fix-me-twice if the common bits get wrong, but much easier to read
  if ($args{revrec} eq 'n') {
    $args{sortby} = 'domain' if !grep $args{sortby}, ('revnet','group','status');
    $sql = "SELECT domain_id,domain,status,groups.group_name AS group FROM domains".
	" INNER JOIN groups ON domains.group_id=groups.group_id".
	" WHERE domains.group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
	($args{startwith} ? " AND domain ~* ?" : '').
	($args{filter} ? " AND domain ~* ?" : '');
  } else {
##fixme:  arguably startwith here is irrelevant.  depends on the UI though.
    $args{sortby} = 'revnet' if !grep $args{sortby}, ('domain','group','status');
    $sql = "SELECT rdns_id,revnet,status,groups.group_name AS group FROM revzones".
	" INNER JOIN groups ON revzones.group_id=groups.group_id".
	" WHERE revzones.group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
	($args{startwith} ? " AND CAST(revnet AS VARCHAR) ~* ?" : '').
	($args{filter} ? " AND CAST(revnet AS VARCHAR) ~* ?" : '');
  }
  # A common tail.
  $sql .= " ORDER BY ".($args{sortby} eq 'group' ? 'groups.group_name' : $args{sortby})." $args{sortorder} ".
	($args{offset} eq 'all' ? '' : " LIMIT $config{perpage}".
	" OFFSET ".$args{offset}*$config{perpage});
  my $sth = $dbh->prepare($sql);
  $sth->execute(@filterargs);
  my $rownum = 0;

  while (my @data = $sth->fetchrow_array) {
    my %row;
    $row{domainid} = $data[0];
    $row{domain} = $data[1];
    $row{status} = $data[2];
    $row{group} = $data[3];
    push @zonelist, \%row;
  }

  return \@zonelist;
} # end getZoneList()


## DNSDB::addGroup()
# Add a group
# Takes a database handle, group name, parent group, hashref for permissions,
# and optional template-vs-cloneme flag
# Returns a status code and message
sub addGroup {
  $errstr = '';
  my $dbh = shift;
  my $groupname = shift;
  my $pargroup = shift;
  my $permissions = shift;

  # 0 indicates "custom", hardcoded.
  # Any other value clones that group's default records, if it exists.
  my $inherit = shift || 0;	
##fixme:  need a flag to indicate clone records or <?> ?

  # Allow transactions, and raise an exception on errors so we can catch it later.
  # Use local to make sure these get "reset" properly on exiting this block
  local $dbh->{AutoCommit} = 0;
  local $dbh->{RaiseError} = 1;

  my $sth = $dbh->prepare("SELECT group_id FROM groups WHERE group_name=?");
  my $group_id;

# quick check to start to see if we've already got one
  $sth->execute($groupname);
  ($group_id) = $sth->fetchrow_array;

  return ('FAIL', "Group already exists") if $group_id;

  # Wrap all the SQL in a transaction
  eval {
    $sth = $dbh->prepare("INSERT INTO groups (parent_group_id,group_name) VALUES (?,?)");
    $sth->execute($pargroup,$groupname);

    my ($groupid) = $dbh->selectrow_array("SELECT group_id FROM groups WHERE group_name=?", undef, ($groupname));

# Permissions
    if ($inherit) {
    } else {
      my @permvals;
      foreach (@permtypes) {
	if (!defined ($permissions->{$_})) {
	  push @permvals, 0;
	} else {
	  push @permvals, $permissions->{$_};
	}
      }

      $sth = $dbh->prepare("INSERT INTO permissions (group_id,$permlist) values (?".',?'x($#permtypes+1).")");
      $sth->execute($groupid,@permvals);

      $sth = $dbh->prepare("SELECT permission_id FROM permissions WHERE group_id=?");
      $sth->execute($groupid);
      my ($permid) = $sth->fetchrow_array();

      $dbh->do("UPDATE groups SET permission_id=$permid WHERE group_id=$groupid");
    } # done permission fiddling

# Default records
    my $sthf = $dbh->prepare("INSERT INTO default_records (group_id,host,type,val,distance,weight,port,ttl) ".
	"VALUES ($groupid,?,?,?,?,?,?,?)");
    my $sthr = $dbh->prepare("INSERT INTO default_rev_records (group_id,host,type,val,ttl) ".
	"VALUES ($groupid,?,?,?,?)");
    if ($inherit) {
      # Duplicate records from parent.  Actually relying on inherited records feels
      # very fragile, and it would be problematic to roll over at a later time.
      my $sth2 = $dbh->prepare("SELECT host,type,val,distance,weight,port,ttl FROM default_records WHERE group_id=?");
      $sth2->execute($pargroup);
      while (my @clonedata = $sth2->fetchrow_array) {
	$sthf->execute(@clonedata);
      }
      # And now the reverse records
      $sth2 = $dbh->prepare("SELECT group_id,host,type,val,ttl FROM default_rev_records WHERE group_id=?");
      $sth2->execute($pargroup);
      while (my @clonedata = $sth2->fetchrow_array) {
	$sthr->execute(@clonedata);
      }
    } else {
##fixme: Hardcoding is Bad, mmmmkaaaay?
      # reasonable basic defaults for SOA, MX, NS, and minimal hosting
      # could load from a config file, but somewhere along the line we need hardcoded bits.
      $sthf->execute('ns1.example.com:hostmaster.example.com', 6, '10800:3600:604800:10800', 0, 0, 0, 86400);
      $sthf->execute('DOMAIN', 1, '192.168.4.2', 0, 0, 0, 7200);
      $sthf->execute('DOMAIN', 15, 'mx.example.com', 10, 0, 0, 7200);
      $sthf->execute('DOMAIN', 2, 'ns1.example.com', 0, 0, 0, 7200);
      $sthf->execute('DOMAIN', 2, 'ns2.example.com', 0, 0, 0, 7200);
      $sthf->execute('www.DOMAIN', 5, 'DOMAIN', 0, 0, 0, 7200);
      # reasonable basic defaults for generic reverse zone.  Same as initial SQL tabledef.
      $sthr->execute('hostmaster.ADMINDOMAIN:ns1.ADMINDOMAIN', 6, '10800:3600:604800:10800', 86400);
      $sthr->execute('unused-%r.ADMINDOMAIN', 65283, 'ZONE', 3600);
    }

    # once we get here, we should have suceeded.
    $dbh->commit;
  }; # end eval

  if ($@) {
    my $msg = $@;
    eval { $dbh->rollback; };
    return ('FAIL',$msg);
  } else {
    return ('OK','OK');
  }

} # end addGroup()


## DNSDB::delGroup()
# Delete a group.
# Takes a group ID
# Returns a status code and message
sub delGroup {
  my $dbh = shift;
  my $groupid = shift;

  # Allow transactions, and raise an exception on errors so we can catch it later.
  # Use local to make sure these get "reset" properly on exiting this block
  local $dbh->{AutoCommit} = 0;
  local $dbh->{RaiseError} = 1;

##fixme:  locate "knowable" error conditions and deal with them before the eval
# ... or inside, whatever.
# -> domains still exist in group
# -> ...
  my $failmsg = '';

  # Wrap all the SQL in a transaction
  eval {
    my $sth = $dbh->prepare("SELECT count(*) FROM domains WHERE group_id=?");
    $sth->execute($groupid);
    my ($domcnt) = $sth->fetchrow_array;
    $failmsg = "Can't remove group ".groupName($dbh,$groupid);
    die "$domcnt domains still in group\n" if $domcnt;

    $sth = $dbh->prepare("delete from default_records where group_id=?");
    $failmsg = "Failed to delete default records for ".groupName($dbh,$groupid);
    $sth->execute($groupid);
    $sth = $dbh->prepare("delete from groups where group_id=?");
    $failmsg = "Failed to remove group ".groupName($dbh,$groupid);
    $sth->execute($groupid);

    # once we get here, we should have suceeded.
    $dbh->commit;
  }; # end eval

  if ($@) {
    my $msg = $@;
    eval { $dbh->rollback; };
    return ('FAIL',"$failmsg: $msg");
  } else {
    return ('OK','OK');
  }
} # end delGroup()


## DNSDB::getChildren()
# Get a list of all groups whose parent^n is group <n>
# Takes a database handle, group ID, reference to an array to put the group IDs in,
# and an optional flag to return only immediate children or all children-of-children
# default to returning all children
# Calls itself
sub getChildren {
  $errstr = '';
  my $dbh = shift;
  my $rootgroup = shift;
  my $groupdest = shift;
  my $immed = shift || 'all';

  # special break for default group;  otherwise we get stuck.
  if ($rootgroup == 1) {
    # by definition, group 1 is the Root Of All Groups
    my $sth = $dbh->prepare("SELECT group_id FROM groups WHERE NOT (group_id=1)".
	($immed ne 'all' ? " AND parent_group_id=1" : ''));
    $sth->execute;
    while (my @this = $sth->fetchrow_array) {
      push @$groupdest, @this;
    }
  } else {
    my $sth = $dbh->prepare("SELECT group_id FROM groups WHERE parent_group_id=?");
    $sth->execute($rootgroup);
    return if $sth->rows == 0;
    my @grouplist;
    while (my ($group) = $sth->fetchrow_array) {
      push @$groupdest, $group;
      getChildren($dbh,$group,$groupdest) if $immed eq 'all';
    }
  }
} # end getChildren()


## DNSDB::groupName()
# Return the group name based on a group ID
# Takes a database handle and the group ID
# Returns the group name or undef on failure
sub groupName {
  $errstr = '';
  my $dbh = shift;
  my $groupid = shift;
  my $sth = $dbh->prepare("SELECT group_name FROM groups WHERE group_id=?");
  $sth->execute($groupid);
  my ($groupname) = $sth->fetchrow_array();
  $errstr = $DBI::errstr if !$groupname;
  return $groupname if $groupname;
} # end groupName


## DNSDB::groupID()
# Return the group ID based on the group name
# Takes a database handle and the group name
# Returns the group ID or undef on failure
sub groupID {
  $errstr = '';
  my $dbh = shift;
  my $group = shift;
  my ($grpid) = $dbh->selectrow_array("SELECT group_id FROM groups WHERE group=?", undef, ($group) );
  $errstr = $DBI::errstr if !$grpid;
  return $grpid if $grpid;
} # end groupID()


## DNSDB::addUser()
# Add a user.
# Takes a DB handle, username, group ID, password, state (active/inactive).
# Optionally accepts:
#   user type (user/admin)	- defaults to user
#   permissions string		- defaults to inherit from group
#      three valid forms:
#	i		     - Inherit permissions
#	c:<user_id>	     - Clone permissions from <user_id>
#	C:<permission list>  - Set these specific permissions
#   first name			- defaults to username
#   last name			- defaults to blank
#   phone			- defaults to blank (could put other data within column def)
# Returns (OK,<uid>) on success, (FAIL,<message>) on failure
sub addUser {
  $errstr = '';
  my $dbh = shift;
  my $username = shift;
  my $group = shift;
  my $pass = shift;
  my $state = shift;

  return ('FAIL', "Missing one or more required entries") if !defined($state);
  return ('FAIL', "Username must not be blank") if !$username;

  my $type = shift || 'u';	# create limited users by default - fwiw, not sure yet how this will interact with ACLs
  
  my $permstring = shift || 'i';	# default is to inhert permissions from group

  my $fname = shift || $username;
  my $lname = shift || '';
  my $phone = shift || '';	# not going format-check

  my $sth = $dbh->prepare("SELECT user_id FROM users WHERE username=?");
  my $user_id;

# quick check to start to see if we've already got one
  $sth->execute($username);
  ($user_id) = $sth->fetchrow_array;

  return ('FAIL', "User already exists") if $user_id;

  # Allow transactions, and raise an exception on errors so we can catch it later.
  # Use local to make sure these get "reset" properly on exiting this block
  local $dbh->{AutoCommit} = 0;
  local $dbh->{RaiseError} = 1;

  my $failmsg = '';

  # Wrap all the SQL in a transaction
  eval {
    # insert the user...  note we set inherited perms by default since
    # it's simple and cleans up some other bits of state
    my $sth = $dbh->prepare("INSERT INTO users ".
	"(group_id,username,password,firstname,lastname,phone,type,status,permission_id,inherit_perm) ".
	"VALUES (?,?,?,?,?,?,?,?,(SELECT permission_id FROM permissions WHERE group_id=?),'t')");
    $sth->execute($group,$username,unix_md5_crypt($pass),$fname,$lname,$phone,$type,$state,$group);

    # get the ID...
    ($user_id) = $dbh->selectrow_array("SELECT currval('users_user_id_seq')");

# Permissions!  Gotta set'em all!
    die "Invalid permission string $permstring"
	if $permstring !~ /^(?:
		i	# inherit
		|c:\d+	# clone
			# custom.  no, the leading , is not a typo
		|C:(?:,(?:group|user|domain|record|self)_(?:edit|create|delete))*
		)$/x;
# bleh.  I'd call another function to do my dirty work, but we're in the middle of a transaction already.
    if ($permstring ne 'i') {
      # for cloned or custom permissions, we have to create a new permissions entry.
      my $clonesrc = $group;
      if ($permstring =~ /^c:(\d+)/) { $clonesrc = $1; }
      $dbh->do("INSERT INTO permissions ($permlist,user_id) ".
	"SELECT $permlist,? FROM permissions WHERE permission_id=".
	"(SELECT permission_id FROM permissions WHERE ".($permstring =~ /^c:/ ? 'user' : 'group')."_id=?)",
	undef, ($user_id,$clonesrc) );
      $dbh->do("UPDATE users SET permission_id=".
	"(SELECT permission_id FROM permissions WHERE user_id=?) ".
	"WHERE user_id=?", undef, ($user_id, $user_id) );
    }
    if ($permstring =~ /^C:/) {
      # finally for custom permissions, we set the passed-in permissions (and unset
      # any that might have been brought in by the clone operation above)
      my ($permid) = $dbh->selectrow_array("SELECT permission_id FROM permissions WHERE user_id=?",
	undef, ($user_id) );
      foreach (@permtypes) {
	if ($permstring =~ /,$_/) {
	  $dbh->do("UPDATE permissions SET $_='t' WHERE permission_id=?", undef, ($permid) );
	} else {
	  $dbh->do("UPDATE permissions SET $_='f' WHERE permission_id=?", undef, ($permid) );
	}
      }
    }

    $dbh->do("UPDATE users SET inherit_perm='n' WHERE user_id=?", undef, ($user_id) );

##fixme: add another table to hold name/email for log table?

    # once we get here, we should have suceeded.
    $dbh->commit;
  }; # end eval

  if ($@) {
    my $msg = $@;
    eval { $dbh->rollback; };
    return ('FAIL',$msg." $failmsg");
  } else {
    return ('OK',$user_id);
  }
} # end addUser


## DNSDB::checkUser()
# Check user/pass combo on login
sub checkUser {
  my $dbh = shift;
  my $user = shift;
  my $inpass = shift;

  my $sth = $dbh->prepare("SELECT user_id,group_id,password,firstname,lastname FROM users WHERE username=?");
  $sth->execute($user);
  my ($uid,$gid,$pass,$fname,$lname) = $sth->fetchrow_array;
  my $loginfailed = 1 if !defined($uid);

  if ($pass =~ m|^\$1\$([A-Za-z0-9/.]+)\$|) {
    $loginfailed = 1 if $pass ne unix_md5_crypt($inpass,$1);
  } else {
    $loginfailed = 1 if $pass ne $inpass;
  }

  # nnnngggg
  return ($uid, $gid);
} # end checkUser


## DNSDB:: updateUser()
# Update general data about user
sub updateUser {
  my $dbh = shift;

##fixme:  tweak calling convention so that we can update any given bit of data
  my $uid = shift;
  my $username = shift;
  my $group = shift;
  my $pass = shift;
  my $state = shift;
  my $type = shift || 'u';
  my $fname = shift || $username;
  my $lname = shift || '';
  my $phone = shift || '';	# not going format-check

  my $failmsg = '';

  # Allow transactions, and raise an exception on errors so we can catch it later.
  # Use local to make sure these get "reset" properly on exiting this block
  local $dbh->{AutoCommit} = 0;
  local $dbh->{RaiseError} = 1;

  my $sth;

  # Password can be left blank;  if so we assume there's one on file.
  # Actual blank passwords are bad, mm'kay?
  if (!$pass) {
    $sth = $dbh->prepare("SELECT password FROM users WHERE user_id=?");
    $sth->execute($uid);
    ($pass) = $sth->fetchrow_array;
  } else {
    $pass = unix_md5_crypt($pass);
  }

  eval {
    my $sth = $dbh->prepare(q(
	UPDATE users
	SET username=?, password=?, firstname=?, lastname=?, phone=?, type=?, status=?
	WHERE user_id=?
	)
      );
    $sth->execute($username, $pass, $fname, $lname, $phone, $type, $state, $uid);
    $dbh->commit;
  };
  if ($@) {
    my $msg = $@;
    eval { $dbh->rollback; };
    return ('FAIL',"$failmsg: $msg");
  } else {
    return ('OK','OK');
  }
} # end updateUser()


## DNSDB::delUser()
#
sub delUser {
  my $dbh = shift;
  return ('FAIL',"Need database handle") if !$dbh;
  my $userid = shift;
  return ('FAIL',"Missing userid") if !defined($userid);

  my $sth = $dbh->prepare("delete from users where user_id=?");
  $sth->execute($userid);

  return ('FAIL',"Couldn't remove user: ".$sth->errstr) if $sth->err;

  return ('OK','OK');

} # end delUser


## DNSDB::userFullName()
# Return a pretty string!
# Takes a user_id and optional printf-ish string to indicate which pieces where:
# %u for the username
# %f for the first name
# %l for the last name
# All other text in the passed string will be left as-is.
##fixme:  need a "smart" option too, so that missing/null/blank first/last names don't give funky output
sub userFullName {
  $errstr = '';
  my $dbh = shift;
  my $userid = shift;
  my $fullformat = shift || '%f %l (%u)';
  my $sth = $dbh->prepare("select username,firstname,lastname from users where user_id=?");
  $sth->execute($userid);
  my ($uname,$fname,$lname) = $sth->fetchrow_array();
  $errstr = $DBI::errstr if !$uname;

  $fullformat =~ s/\%u/$uname/g;
  $fullformat =~ s/\%f/$fname/g;
  $fullformat =~ s/\%l/$lname/g;

  return $fullformat;
} # end userFullName


## DNSDB::userStatus()
# Sets and/or returns a user's status
# Takes a database handle, user ID and optionally a status argument
# Returns undef on errors.
sub userStatus {
  my $dbh = shift;
  my $id = shift;
  my $newstatus = shift;

  return undef if $id !~ /^\d+$/;

  my $sth;

# ooo, fun!  let's see what we were passed for status
  if ($newstatus) {
    $sth = $dbh->prepare("update users set status=? where user_id=?");
    # ass-u-me caller knows what's going on in full
    if ($newstatus =~ /^[01]$/) {	# only two valid for now.
      $sth->execute($newstatus,$id);
    } elsif ($newstatus =~ /^usero(?:n|ff)$/) {
      $sth->execute(($newstatus eq 'useron' ? 1 : 0),$id);
    }
  }

  $sth = $dbh->prepare("select status from users where user_id=?");
  $sth->execute($id);
  my ($status) = $sth->fetchrow_array;
  return $status;
} # end userStatus()


## DNSDB::getUserData()
# Get misc user data for display
sub getUserData {
  my $dbh = shift;
  my $uid = shift;

  my $sth = $dbh->prepare("SELECT group_id,username,firstname,lastname,phone,type,status,inherit_perm ".
	"FROM users WHERE user_id=?");
  $sth->execute($uid);
  return $sth->fetchrow_hashref();

} # end getUserData()


## DNSDB::getSOA()
# Return all suitable fields from an SOA record in separate elements of a hash
# Takes a database handle, default/live flag, domain/reverse flag, and parent ID
sub getSOA {
  $errstr = '';
  my $dbh = shift;
  my $def = shift;
  my $rev = shift;
  my $id = shift;
  my %ret;

  # (ab)use distance and weight columns to store SOA data?  can't for default_rev_records...
  # - should really attach serial to the zone parent somewhere

  my $sql = "SELECT record_id,host,val,ttl from "._rectable($def,$rev).
	" WHERE "._recparent($def,$rev)." = ? AND type=$reverse_typemap{SOA}";

  my $sth = $dbh->prepare($sql);
  $sth->execute($id);
##fixme:  stick a flag somewhere if the record doesn't exist.  by the API, this is an impossible case, but...

  my ($recid,$host,$val,$ttl) = $sth->fetchrow_array() or return;
  my ($contact,$prins) = split /:/, $host;
  my ($refresh,$retry,$expire,$minttl) = split /:/, $val;

  $ret{recid}	= $recid;
  $ret{ttl}	= $ttl;
#  $ret{serial}	= $serial;	# ca't use distance for serial with default_rev_records
  $ret{prins}	= $prins;
  $ret{contact}	= $contact;
  $ret{refresh}	= $refresh;
  $ret{retry}	= $retry;
  $ret{expire}	= $expire;
  $ret{minttl}	= $minttl;

  return %ret;
} # end getSOA()


## DNSDB::updateSOA()
# Update the specified SOA record
# Takes a database handle, default/live flag, forward/reverse flag, and SOA data hash
# Returns a two-element list with a result code and message
sub updateSOA {
  my $dbh = shift;
  my $defrec = shift;
  my $revrec = shift;

  my %soa = @_;

  my %oldsoa = getSOA($dbh, $defrec, $revrec, $soa{recid});

  # Allow transactions, and raise an exception on errors so we can catch it later.
  # Use local to make sure these get "reset" properly on exiting this block
  local $dbh->{AutoCommit} = 0;
  local $dbh->{RaiseError} = 1;

  my $msg;

  eval {
##fixme: data validation: make sure {recid} is really the SOA for {parent}
    my $sql = "UPDATE "._rectable($defrec, $revrec)." SET host=?, val=?, ttl=? WHERE record_id=? AND type=6";
    $dbh->do($sql, undef, ("$soa{contact}:$soa{prins}", "$soa{refresh}:$soa{retry}:$soa{expire}:$soa{minttl}",
        $soa{ttl}, $soa{recid}) );

    $msg = "Updated ".($defrec eq 'y' ? 'default ' : '')."SOA for ".
	($defrec eq 'y' ? groupName($dbh, $soa{recid}) : 
		($revrec eq 'n' ? domainName($dbh, $soa{recid}) : revName($dbh, $soa{recid}) ) ).
	": (ns $oldsoa{prins}, contact $oldsoa{contact}, refresh $oldsoa{refresh},".
	" retry $oldsoa{retry}, expire $oldsoa{expire}, minTTL $oldsoa{minttl}, TTL $oldsoa{ttl}) to ".
	"(ns $soa{prins}, contact $soa{contact}, refresh $soa{refresh},".
	" retry $soa{retry}, expire $soa{expire}, minTTL $soa{minttl}, TTL $soa{ttl})";

#    _log($dbh, (rdns_id => $rdns_id, user_id => $userinfo{id}, group_id => $group,
#	username => $userinfo{name}, entry => $msg) );

    $dbh->commit;
  };
  if ($@) {
    $msg = $@;
    eval { $dbh->rollback; };
    return ('FAIL',$msg);
  } else {
    return ('OK', $msg);
  }
} # end updateSOA()


## DNSDB::getRecLine()
# Return all data fields for a zone record in separate elements of a hash
# Takes a database handle, default/live flag, forward/reverse flag, and record ID
sub getRecLine {
  $errstr = '';
  my $dbh = shift;
  my $defrec = shift;
  my $revrec = shift;
  my $id = shift;

  my $sql = "SELECT record_id,host,type,val,ttl".($revrec eq 'n' ? ',distance,weight,port' : '').
	(($defrec eq 'y') ? ',group_id FROM ' : ',domain_id,rdns_id FROM ').
	_rectable($defrec,$revrec)." WHERE record_id=?";
  my $ret = $dbh->selectrow_hashref($sql, undef, ($id) );

  if ($dbh->err) {
    $errstr = $DBI::errstr;
    return undef;
  }

  if (!$ret) {
    $errstr = "No such record";
    return undef;
  }

  # explicitly set a parent id
  if ($defrec eq 'y') {
    $ret->{parid} = $ret->{group_id};
  } else {
    $ret->{parid} = (($revrec eq 'n') ? $ret->{domain_id} : $ret->{rdns_id});
    # and a secondary if we have a custom type that lives in both a forward and reverse zone
    $ret->{secid} = (($revrec eq 'y') ? $ret->{domain_id} : $ret->{rdns_id}) if $ret->{type} > 65279;
  }

  return $ret;
}


##fixme: should use above (getRecLine()) to get lines for below?
## DNSDB::getDomRecs()
# Return records for a domain
# Takes a database handle, default/live flag, group/domain ID, start,
# number of records, sort field, and sort order
# Returns a reference to an array of hashes
sub getDomRecs {
  $errstr = '';
  my $dbh = shift;
  my $def = shift;
  my $rev = shift;
  my $id = shift;
  my $nrecs = shift || 'all';
  my $nstart = shift || 0;

## for order, need to map input to column names
  my $order = shift || 'host';
  my $direction = shift || 'ASC';

  my $filter = shift || '';

  my $sql = "SELECT r.record_id,r.host,r.type,r.val,r.ttl";
  $sql .= ",r.distance,r.weight,r.port" if $rev eq 'n';
  $sql .= " FROM "._rectable($def,$rev)." r ";
  $sql .= "INNER JOIN rectypes t ON r.type=t.val ";	# for sorting by type alphabetically
  $sql .= "WHERE "._recparent($def,$rev)." = ?";
  $sql .= " AND NOT r.type=$reverse_typemap{SOA}";
  $sql .= " AND host ~* ?" if $filter;
  # use alphaorder column for "correct" ordering of sort-by-type instead of DNS RR type number
  $sql .= " ORDER BY ".($order eq 'type' ? 't.alphaorder' : "r.$order")." $direction";

  my @bindvars = ($id);
  push @bindvars, $filter if $filter;

  # just to be ultraparanoid about SQL injection vectors
  if ($nstart ne 'all') {
    $sql .= " LIMIT ? OFFSET ?";
    push @bindvars, $nrecs;
    push @bindvars, ($nstart*$nrecs);
  }
  my $sth = $dbh->prepare($sql) or warn $dbh->errstr;
  $sth->execute(@bindvars) or warn "$sql: ".$sth->errstr;

  my @retbase;
  while (my $ref = $sth->fetchrow_hashref()) {
    push @retbase, $ref;
  }

  my $ret = \@retbase;
  return $ret;
} # end getDomRecs()


## DNSDB::getRecCount()
# Return count of non-SOA records in zone (or default records in a group)
# Takes a database handle, default/live flag, reverse/forward flag, group/domain ID,
# and optional filtering modifier
# Returns the count
sub getRecCount {
  my $dbh = shift;
  my $defrec = shift;
  my $revrec = shift;
  my $id = shift;
  my $filter = shift || '';

  # keep the nasties down, since we can't ?-sub this bit.  :/
  # note this is chars allowed in DNS hostnames
  $filter =~ s/[^a-zA-Z0-9_.:-]//g;

  my @bindvars = ($id);
  push @bindvars, $filter if $filter;
  my $sql = "SELECT count(*) FROM ".
	_rectable($defrec,$revrec).
	" WHERE "._recparent($defrec,$revrec)."=? ".
	"AND NOT type=$reverse_typemap{SOA}".
	($filter ? " AND host ~* ?" : '');
  my ($count) = $dbh->selectrow_array($sql, undef, (@bindvars) );

  return $count;

} # end getRecCount()


## DNSDB::addRec()
# Add a new record to a domain or a group's default records
# Takes a database handle, default/live flag, group/domain ID,
# host, type, value, and TTL
# Some types require additional detail: "distance" for MX and SRV,
# and weight/port for SRV
# Returns a status code and detail message in case of error
##fixme:  pass a hash with the record data, not a series of separate values
sub addRec {
  $errstr = '';
  my $dbh = shift;
  my $defrec = shift;
  my $revrec = shift;
  my $id = shift;	# parent (group_id for defrecs, rdns_id for reverse records,
			# domain_id for domain records)

  my $host = shift;
  my $rectype = shift;	# reference so we can coerce it if "+"-types can't find both zones
  my $val = shift;
  my $ttl = shift;

  # prep for validation
  my $addr = NetAddr::IP->new($$val);
  $$host =~ s/\.+$//;	# FQDNs ending in . are an internal detail, and really shouldn't be exposed in the UI.

  my $domid = 0;
  my $revid = 0;

  my $retcode = 'OK';	# assume everything will go OK
  my $retmsg = '';

  # do simple validation first
  return ('FAIL', "TTL must be numeric") unless $ttl =~ /^\d+$/;

  # Quick check on hostname parts.  Note the regex is more forgiving than the error message;
  # domain names technically are case-insensitive, and we use printf-like % codes for a couple
  # of types.  Other things may also be added to validate default records of several flavours.
  return ('FAIL', "Hostnames may not contain anything other than (0-9 a-z . _)")
	if $defrec eq 'n' && $$host !~ /^[0-9a-z_%.-]+$/i;

  # Collect these even if we're only doing a simple A record so we can call *any* validation sub
  my $dist = shift;
  my $weight = shift;
  my $port = shift;

  my $fields;
  my @vallist;

  # Call the validation sub for the type requested.
  ($retcode,$retmsg) = $validators{$$rectype}($dbh, (defrec => $defrec, revrec => $revrec, id => $id,
	host => $host, rectype => $rectype, val => $val, addr => $addr,
	dist => \$dist, port => \$port, weight => \$weight,
	fields => \$fields, vallist => \@vallist) );

  return ($retcode,$retmsg) if $retcode eq 'FAIL';

  # Set up database fields and bind parameters
  $fields .= "host,type,val,ttl,"._recparent($defrec,$revrec);
  push @vallist, ($$host,$$rectype,$$val,$ttl,$id);
  my $vallen = '?'.(',?'x$#vallist);

  # Put together the success log entry.  We have to use this horrible kludge
  # because domain_id and rdns_id may or may not be present, and if they are,
  # they're not at a guaranteed consistent index in the array.  wheee!
  my %logdata;
  my @ftmp = split /,/, $fields;
  for (my $i=0; $i <= $#vallist; $i++) {
    $logdata{domain_id} = $vallist[$i] if $ftmp[$i] eq 'domain_id';
    $logdata{rdns_id} = $vallist[$i] if $ftmp[$i] eq 'rdns_id';
  }
  $logdata{group_id} = $id if $defrec eq 'y';
  $logdata{group_id} = parentID($dbh,
		(id => $id, type => ($revrec eq 'n' ? 'domain' : 'revzone'), revrec => $revrec) )
	if $defrec eq 'n';
  $logdata{entry} = "Added ".($defrec eq 'y' ? 'default record' : 'record')." '$$host $typemap{$$rectype} $$val";
  $logdata{entry} .= " [distance $dist]" if $typemap{$$rectype} eq 'MX';
  $logdata{entry} .= " [priority $dist] [weight $weight] [port $port]"
	if $typemap{$$rectype} eq 'SRV';
  $logdata{entry} .= "', TTL $ttl";

  # Allow transactions, and raise an exception on errors so we can catch it later.
  # Use local to make sure these get "reset" properly on exiting this block
  local $dbh->{AutoCommit} = 0;
  local $dbh->{RaiseError} = 1;

  eval {
    $dbh->do("INSERT INTO "._rectable($defrec, $revrec)." ($fields) VALUES ($vallen)",
	undef, @vallist);
    _log($dbh, %logdata);
    $dbh->commit;
  };
  if ($@) {
    my $msg = $@;
    eval { $dbh->rollback; };
    if ($config{log_failures}) {
      $logdata{entry} = "Failed adding ".($defrec eq 'y' ? 'default ' : '').
	"record '$$host $typemap{$$rectype} $$val', TTL $ttl ($msg)";
      _log($dbh, %logdata);
      $dbh->commit;
    }
    return ('FAIL',$msg);
  }

  $resultstr = $logdata{entry};
  return ($retcode, $retmsg);

} # end addRec()


## DNSDB::updateRec()
# Update a record
# Takes a database handle, default and reverse flags, record ID, immediate parent ID, and new record data.
# Returns a status code and message
sub updateRec {
  $errstr = '';

  my $dbh = shift;
  my $defrec = shift;
  my $revrec = shift;
  my $id = shift;
  my $parid = shift;	# immediate parent entity that we're descending from to update the record

  # all records have these
  my $host = shift;
  my $hostbk = $$host;	# Keep a backup copy of the original, so we can WARN if the update mangles the domain
  my $rectype = shift;
  my $val = shift;
  my $ttl = shift;

  # prep for validation
  my $addr = NetAddr::IP->new($$val);
  $$host =~ s/\.+$//;	# FQDNs ending in . are an internal detail, and really shouldn't be exposed in the UI.

  my $domid = 0;
  my $revid = 0;

  my $retcode = 'OK';	# assume everything will go OK
  my $retmsg = '';

  # do simple validation first
  return ('FAIL', "TTL must be numeric") unless $ttl =~ /^\d+$/;

  # Quick check on hostname parts.  Note the regex is more forgiving than the error message;
  # domain names technically are case-insensitive, and we use printf-like % codes for a couple
  # of types.  Other things may also be added to validate default records of several flavours.
  return ('FAIL', "Hostnames may not contain anything other than (0-9 a-z - . _)")
	if $defrec eq 'n' && $$host !~ /^[0-9a-z_%.-]+$/i;

  # only MX and SRV will use these
  my $dist = shift || 0;
  my $weight = shift || 0;
  my $port = shift || 0;

  my $fields;
  my @vallist;

  # get old record data so we have the right parent ID
  # and for logging (eventually)
  my $oldrec = getRecLine($dbh, $defrec, $revrec, $id);

  # Call the validation sub for the type requested.
  # Note the ID to pass here is the *parent*, not the record
  ($retcode,$retmsg) = $validators{$$rectype}($dbh, (defrec => $defrec, revrec => $revrec,
	id => ($defrec eq 'y' ? $oldrec->{group_id} : ($revrec eq 'n' ? $oldrec->{domain_id} : $oldrec->{rdns_id})),
	host => $host, rectype => $rectype, val => $val, addr => $addr,
	dist => \$dist, port => \$port, weight => \$weight,
	fields => \$fields, vallist => \@vallist,
	update => $id) );

  return ($retcode,$retmsg) if $retcode eq 'FAIL';

  # Set up database fields and bind parameters.  Note only the optional fields
  # (distance, weight, port, secondary parent ID) are added in the validation call above
  $fields .= "host,type,val,ttl,"._recparent($defrec,$revrec);
  push @vallist, ($$host,$$rectype,$$val,$ttl,
	($defrec eq 'y' ? $oldrec->{group_id} : ($revrec eq 'n' ? $oldrec->{domain_id} : $oldrec->{rdns_id})) );

  # hack hack PTHUI
  # need to forcibly make sure we disassociate a record with a parent it's no longer related to.
  # eg, PTR records may not have a domain parent, or A/AAAA records may not have a revzone parent.
  # mainly needed for crossover types that got coerced down to "standard" types
  if ($defrec eq 'n') {
    if ($$rectype == $reverse_typemap{PTR}) {
      $fields .= ",domain_id";
      push @vallist, 0;
    }
    if ($$rectype == $reverse_typemap{A} || $$rectype == $reverse_typemap{AAAA}) {
      $fields .= ",rdns_id";
      push @vallist, 0;
    }
  }

  # Fiddle the field list into something suitable for updates
  $fields =~ s/,/=?,/g;
  $fields .= "=?";

  # Put together the success log entry.  Horrible kludge from addRec() copied as-is since
  # we don't know whether the passed arguments or retrieved values for domain_id and rdns_id
  # will be maintained (due to "not-in-zone" validation changes)
  my %logdata;
  my @ftmp = split /,/, $fields;
  for (my $i=0; $i <= $#vallist; $i++) {
    $logdata{domain_id} = $vallist[$i] if $ftmp[$i] eq 'domain_id';
    $logdata{rdns_id} = $vallist[$i] if $ftmp[$i] eq 'rdns_id';
  }
  $logdata{group_id} = $parid if $defrec eq 'y';
  $logdata{group_id} = parentID($dbh,
		(id => $parid, type => ($revrec eq 'n' ? 'domain' : 'revzone'), revrec => $revrec) )
	if $defrec eq 'n';
  $logdata{entry} = "Updated ".($defrec eq 'y' ? 'default record' : 'record')." from\n".
	"'$oldrec->{host} $typemap{$oldrec->{type}} $oldrec->{val}";
  $logdata{entry} .= " [distance $oldrec->{distance}]" if $typemap{$oldrec->{type}} eq 'MX';
  $logdata{entry} .= " [priority $oldrec->{distance}] [weight $oldrec->{weight}] [port $oldrec->{port}]"
	if $typemap{$oldrec->{type}} eq 'SRV';
  $logdata{entry} .= "', TTL $oldrec->{ttl}\nto\n'$$host $typemap{$$rectype} $$val";
  $logdata{entry} .= " [distance $dist]" if $typemap{$$rectype} eq 'MX';
  $logdata{entry} .= " [priority $dist] [weight $weight] [port $port]" if $typemap{$$rectype} eq 'SRV';
  $logdata{entry} .= "', TTL $ttl";

  local $dbh->{AutoCommit} = 0;
  local $dbh->{RaiseError} = 1;

  eval {
    $dbh->do("UPDATE "._rectable($defrec,$revrec)." SET $fields WHERE record_id=?", undef, (@vallist, $id) );
    _log($dbh, %logdata);
    $dbh->commit;
  };
  if ($@) {
    my $msg = $@;
    eval { $dbh->rollback; };
    if ($config{log_failures}) {
      $logdata{entry} = "Failed updating ".($defrec eq 'y' ? 'default ' : '').
	"record '$oldrec->{host} $typemap{$oldrec->{type}} $oldrec->{val}', TTL $oldrec->{ttl} ($msg)";
      _log($dbh, %logdata);
      $dbh->commit;
    }
    return ('FAIL', $msg);
  }

  $resultstr = $logdata{entry};
  return ($retcode, $retmsg);
} # end updateRec()


## DNSDB::delRec()
# Delete a record.  
sub delRec {
  $errstr = '';
  my $dbh = shift;
  my $defrec = shift;
  my $revrec = shift;
  my $id = shift;

  my $sth = $dbh->prepare("DELETE FROM "._rectable($defrec,$revrec)." WHERE record_id=?");
  $sth->execute($id);

  return ('FAIL',"Couldn't remove record: ".$sth->errstr) if $sth->err;

  return ('OK','OK');
} # end delRec()


  # Reference hashes.
my %par_tbl = (
		group	=> 'groups',
		user	=> 'users',
		defrec	=> 'default_records',
		defrevrec	=> 'default_rev_records',
		domain	=> 'domains',
		revzone	=> 'revzones',
		record	=> 'records'
	);
my %id_col = (
		group	=> 'group_id',
		user	=> 'user_id',
		defrec	=> 'record_id',
		defrevrec	=> 'record_id',
		domain	=> 'domain_id',
		revzone	=> 'rdns_id',
		record	=> 'record_id'
	);
my %par_col = (
		group	=> 'parent_group_id',
		user	=> 'group_id',
		defrec	=> 'group_id',
		defrevrec	=> 'group_id',
		domain	=> 'group_id',
		revzone	=> 'group_id',
		record	=> 'domain_id'
	);
my %par_type = (
		group	=> 'group',
		user	=> 'group',
		defrec	=> 'group',
		defrevrec	=> 'group',
		domain	=> 'group',
		revzone	=> 'group',
		record	=> 'domain'
	);


## DNSDB::getTypelist()
# Get a list of record types for various UI dropdowns
# Takes database handle, forward/reverse/lookup flag, and optional "tag as selected" indicator (defaults to A)
# Returns an arrayref to list of hashrefs perfect for HTML::Template
sub getTypelist {
  my $dbh = shift;
  my $recgroup = shift;
  my $type = shift || $reverse_typemap{A};

  # also accepting $webvar{revrec}!
  $recgroup = 'f' if $recgroup eq 'n';
  $recgroup = 'r' if $recgroup eq 'y';

  my $sql = "SELECT val,name FROM rectypes WHERE ";
  if ($recgroup eq 'r') {
    # reverse zone types
    $sql .= "stdflag=2 OR stdflag=3";
  } elsif ($recgroup eq 'l') {
    # DNS lookup types.  Note we avoid our custom types >= 65280, since those are entirely internal.
    $sql .= "(stdflag=1 OR stdflag=2 OR stdflag=3) AND val < 65280";
  } else {
    # default;  forward zone types.  technically $type eq 'f' but not worth the error message.
    $sql .= "stdflag=1 OR stdflag=2";
  }
  $sql .= " ORDER BY listorder";

  my $sth = $dbh->prepare($sql);
  $sth->execute;
  my @typelist;
  while (my ($rval,$rname) = $sth->fetchrow_array()) {
    my %row = ( recval => $rval, recname => $rname );
    $row{tselect} = 1 if $rval == $type;
    push @typelist, \%row;
  }

  # Add SOA on lookups since it's not listed in other dropdowns.
  if ($recgroup eq 'l') {
    my %row = ( recval => $reverse_typemap{SOA}, recname => 'SOA' );
    $row{tselect} = 1 if $reverse_typemap{SOA} == $type;
    push @typelist, \%row;
  }

  return \@typelist;
} # end getTypelist()


## DNSDB::parentID()
# Get ID of entity that is nearest parent to requested id
# Takes a database handle and a hash of entity ID, entity type, optional parent type flag
# (domain/reverse zone or group), and optional default/live and forward/reverse flags
# Returns the ID or undef on failure
sub parentID {
  my $dbh = shift;

  my %args = @_;

  # clean up the parent-type.  Set it to group if not set;  coerce revzone to domain for simpler logic
  $args{partype} = 'group' if !$args{partype};
  $args{partype} = 'domain' if $args{partype} eq 'revzone';

  # clean up defrec and revrec.  default to live record, forward zone
  $args{defrec} = 'n' if !$args{defrec};
  $args{revrec} = 'n' if !$args{revrec};

  if ($par_type{$args{partype}} eq 'domain') {
    # only live records can have a domain/zone parent
    return unless ($args{type} eq 'record' && $args{defrec} eq 'n');
    my $result = $dbh->selectrow_hashref("SELECT ".($args{revrec} eq 'n' ? 'domain_id' : 'rdns_id').
	" FROM records WHERE record_id = ?",
	undef, ($args{id}) ) or return;
    return $result;
  } else {
    # snag some arguments that will either fall through or be overwritten to save some code duplication
    my $tmpid = $args{id};
    my $type = $args{type};
    if ($type eq 'record' && $args{defrec} eq 'n') {
      # Live records go through the records table first.
      ($tmpid) = $dbh->selectrow_array("SELECT ".($args{revrec} eq 'n' ? 'domain_id' : 'rdns_id').
	" FROM records WHERE record_id = ?",
	undef, ($args{id}) ) or return;
      $type = ($args{revrec} eq 'n' ? 'domain' : 'revzone');
    }
    my ($result) = $dbh->selectrow_array("SELECT $par_col{$type} FROM $par_tbl{$type} WHERE $id_col{$type} = ?",
	undef, ($tmpid) );
    return $result;
  }
# should be impossible to get here with even remotely sane arguments
  return;
} # end parentID()


## DNSDB::isParent()
# Returns true if $id1 is a parent of $id2, false otherwise
sub isParent {
  my $dbh = shift;
  my $id1 = shift;
  my $type1 = shift; 
  my $id2 = shift;
  my $type2 = shift;
##todo:  immediate, secondary, full (default)

  # Return false on invalid types
  return 0 if !grep /^$type1$/, ('record','defrec','defrevrec','user','domain','revzone','group');
  return 0 if !grep /^$type2$/, ('record','defrec','defrevrec','user','domain','revzone','group');

  # Return false on impossible relations
  return 0 if $type1 eq 'record';	# nothing may be a child of a record
  return 0 if $type1 eq 'defrec';	# nothing may be a child of a record
  return 0 if $type1 eq 'defrevrec';	# nothing may be a child of a record
  return 0 if $type1 eq 'user';		# nothing may be child of a user
  return 0 if $type1 eq 'domain' && $type2 ne 'record';	# domain may not be a parent of anything other than a record
  return 0 if $type1 eq 'revzone' && $type2 ne 'record';# reverse zone may not be a parent of anything other than a record

  # ennnhhhh....  if we're passed an id of 0, it will never be found.  usual
  # case would be the UI creating a new <thing>, and so we don't have an ID for
  # <thing> to look up yet.  in that case the UI should check the parent as well.
  return 0 if $id1 == 0;	# nothing can have a parent id of 0
  return 1 if $id2 == 0;	# anything could have a child id of 0 (or "unknown")

  # group 1 is the ultimate root parent
  return 1 if $type1 eq 'group' && $id1 == 1;

  # groups are always (a) parent of themselves
  return 1 if $type1 eq 'group' && $type2 eq 'group' && $id1 == $id2;

  my $id = $id2;
  my $type = $type2;
  my $foundparent = 0;

  # Records are the only entity with two possible parents.  We need to split the parent checks on
  # domain/rdns.
  if ($type eq 'record') {
    my ($dom,$rdns) = $dbh->selectrow_array("SELECT domain_id,rdns_id FROM records WHERE record_id=?",
	undef, ($id));
    # check immediate parent against request
    return 1 if $type1 eq 'domain' && $id1 == $dom;
    return 1 if $type1 eq 'revzone' && $id1 == $rdns;
    # if request is group, check *both* parents.  Only check if the parent is nonzero though.
    return 1 if $dom && isParent($dbh, $id1, $type1, $dom, 'domain');
    return 1 if $rdns && isParent($dbh, $id1, $type1, $rdns, 'revzone');
    # exit here since we've executed the loop below by proxy in the above recursive calls.
    return 0;
  }

# almost the same loop as getParents() above
  my $limiter = 0;
  while (1) {
    my $sql = "SELECT $par_col{$type} FROM $par_tbl{$type} WHERE $id_col{$type} = ?";
    my $result = $dbh->selectrow_hashref($sql,
	undef, ($id) );
    if (!$result) {
      $limiter++;
##fixme:  how often will this happen on a live site?  fail at max limiter <n>?
      warn "no results looking for $sql with id $id (depth $limiter)\n";
      last;
    }
    if ($result && $result->{$par_col{$type}} == $id1) {
      $foundparent = 1;
      last;
    } else {
##fixme: do we care about trying to return a "no such record/domain/user/group" error?
# should be impossible to create an inconsistent DB just with API calls.
      warn $dbh->errstr." $sql, $id" if $dbh->errstr;
    }
    # group 1 is its own parent.  need this here more to break strange loops than for detecting a parent
    last if $result->{$par_col{$type}} == 1;
    $id = $result->{$par_col{$type}};
    $type = $par_type{$type};
  }

  return $foundparent;
} # end isParent()


## DNSDB::zoneStatus()
# Returns and optionally sets a zone's status
# Takes a database handle, domain/revzone ID, forward/reverse flag, and optionally a status argument
# Returns status, or undef on errors.
sub zoneStatus {
  my $dbh = shift;
  my $id = shift;
  my $revrec = shift;
  my $newstatus = shift || 'mu';

  return undef if $id !~ /^\d+$/;

  # Allow transactions, and raise an exception on errors so we can catch it later.
  # Use local to make sure these get "reset" properly on exiting this block
  local $dbh->{AutoCommit} = 0;
  local $dbh->{RaiseError} = 1;

  if ($newstatus ne 'mu') {
    # ooo, fun!  let's see what we were passed for status
    eval {
      $newstatus = 0 if $newstatus eq 'domoff';
      $newstatus = 1 if $newstatus eq 'domon';
      $dbh->do("UPDATE ".($revrec eq 'n' ? 'domains' : 'revzones')." SET status=? WHERE ".
	($revrec eq 'n' ? 'domain_id' : 'rdns_id')."=?", undef, ($newstatus,$id) );

##fixme  switch to more consise "Enabled <domain"/"Disabled <domain>" as with users?
      $resultstr = "Changed ".($revrec eq 'n' ? domainName($dbh, $id) : revName($dbh, $id)).
	" state to ".($newstatus ? 'active' : 'inactive');

      my %loghash;
      $loghash{domain_id} = $id if $revrec eq 'n';
      $loghash{rdns_id} = $id if $revrec eq 'y';
      $loghash{group_id} = parentID($dbh,
	(id => $id, type => ($revrec eq 'n' ? 'domain' : 'revzone'), revrec => $revrec) );
      $loghash{entry} = $resultstr;
      _log($dbh, %loghash);

      $dbh->commit;
    };
    if ($@) {
      my $msg = $@;
      eval { $dbh->rollback; };
      $resultstr = '';
      $errstr = $msg;
      return;
    }
  }

  my ($status) = $dbh->selectrow_array("SELECT status FROM ".
	($revrec eq 'n' ? "domains WHERE domain_id=?" : "revzones WHERE rdns_id=?"),
	undef, ($id) );
  return $status;
} # end zoneStatus()


## DNSDB::importAXFR
# Import a domain via AXFR
# Takes AXFR host, domain to transfer, group to put the domain in,
# and optionally:
#  - active/inactive state flag (defaults to active)
#  - overwrite-SOA flag (defaults to off)
#  - overwrite-NS flag (defaults to off, doesn't affect subdomain NS records)
# Returns a status code (OK, WARN, or FAIL) and message - message should be blank
# if status is OK, but WARN includes conditions that are not fatal but should
# really be reported.
sub importAXFR {
  my $dbh = shift;
  my $ifrom_in = shift;
  my $domain = shift;
  my $group = shift;
  my $status = shift || 1;
  my $rwsoa = shift || 0;
  my $rwns = shift || 0;

##fixme:  add mode to delete&replace, merge+overwrite, merge new?

  my $nrecs = 0;
  my $soaflag = 0;
  my $nsflag = 0;
  my $warnmsg = '';
  my $ifrom;

  # choke on possible bad setting in ifrom
  # IPv4 and v6, and valid hostnames!
  ($ifrom) = ($ifrom_in =~ /^([0-9a-f\:.]+|[0-9a-z_.-]+)$/i);
  return ('FAIL', "Bad AXFR source host $ifrom")
	unless ($ifrom) = ($ifrom_in =~ /^([0-9a-f\:.]+|[0-9a-z_.-]+)$/i);

  # Allow transactions, and raise an exception on errors so we can catch it later.
  # Use local to make sure these get "reset" properly on exiting this block
  local $dbh->{AutoCommit} = 0;
  local $dbh->{RaiseError} = 1;

  my $sth = $dbh->prepare("SELECT domain_id FROM domains WHERE domain=?");
  my $dom_id;

# quick check to start to see if we've already got one
  $sth->execute($domain);
  ($dom_id) = $sth->fetchrow_array;

  return ('FAIL', "Domain already exists") if $dom_id;

  eval {
    # can't do this, can't nest transactions.  sigh.
    #my ($dcode, $dmsg) = addDomain(dbh, domain, group, status);

##fixme:  serial
    my $sth = $dbh->prepare("INSERT INTO domains (domain,group_id,status) VALUES (?,?,?)");
    $sth->execute($domain,$group,$status);

## bizarre DBI<->Net::DNS interaction bug:
## sometimes a zone will cause an immediate commit-and-exit (sort of) of the while()
## fixed, apparently I was doing *something* odd, but not certain what it was that
## caused a commit instead of barfing

    # get domain id so we can do the records
    $sth = $dbh->prepare("SELECT domain_id FROM domains WHERE domain=?");
    $sth->execute($domain);
    ($dom_id) = $sth->fetchrow_array();

    my $res = Net::DNS::Resolver->new;
    $res->nameservers($ifrom);
    $res->axfr_start($domain)
	or die "Couldn't begin AXFR\n";

    while (my $rr = $res->axfr_next()) {
      my $type = $rr->type;

      my $sql = "INSERT INTO records (domain_id,host,type,ttl,val";
      my $vallen = "?,?,?,?,?";

      $soaflag = 1 if $type eq 'SOA';
      $nsflag = 1 if $type eq 'NS';

      my @vallist = ($dom_id, $rr->name, $reverse_typemap{$type}, $rr->ttl);

# "Primary" types:
# A, NS, CNAME, SOA, PTR(warn in forward), MX, TXT, AAAA, SRV, A6(ob), SPF
# maybe KEY

# nasty big ugly case-like thing here, since we have to do *some* different
# processing depending on the record.  le sigh.

##fixme:  what record types other than TXT can/will have >255-byte payloads?

      if ($type eq 'A') {
	push @vallist, $rr->address;
      } elsif ($type eq 'NS') {
# hmm.  should we warn here if subdomain NS'es are left alone?
	next if ($rwns && ($rr->name eq $domain));
	push @vallist, $rr->nsdname;
	$nsflag = 1;
      } elsif ($type eq 'CNAME') {
	push @vallist, $rr->cname;
      } elsif ($type eq 'SOA') {
	next if $rwsoa;
	$vallist[1] = $rr->mname.":".$rr->rname;
	push @vallist, ($rr->refresh.":".$rr->retry.":".$rr->expire.":".$rr->minimum);
	$soaflag = 1;
      } elsif ($type eq 'PTR') {
	push @vallist, $rr->ptrdname;
	# hmm.  PTR records should not be in forward zones.
      } elsif ($type eq 'MX') {
	$sql .= ",distance";
	$vallen .= ",?";
	push @vallist, $rr->exchange;
	push @vallist, $rr->preference;
      } elsif ($type eq 'TXT') {
##fixme:  Net::DNS docs say this should be deprecated for rdatastr() or char_str_list(),
## but don't really seem enthusiastic about it.
	my $rrdata = $rr->txtdata;
	push @vallist, $rrdata;
      } elsif ($type eq 'SPF') {
##fixme: and the same caveat here, since it is apparently a clone of ::TXT
	my $rrdata = $rr->txtdata;
	push @vallist, $rrdata;
      } elsif ($type eq 'AAAA') {
	push @vallist, $rr->address;
      } elsif ($type eq 'SRV') {
	$sql .= ",distance,weight,port" if $type eq 'SRV';
	$vallen .= ",?,?,?" if $type eq 'SRV';
	push @vallist, $rr->target;
	push @vallist, $rr->priority;
	push @vallist, $rr->weight;
	push @vallist, $rr->port;
      } elsif ($type eq 'KEY') {
	# we don't actually know what to do with these...
	push @vallist, ($rr->flags.":".$rr->protocol.":".$rr->algorithm.":".$rr->key.":".$rr->keytag.":".$rr->privatekeyname);
      } else {
	my $rrdata = $rr->rdatastr;
	push @vallist, $rrdata;
	# Finding a different record type is not fatal.... just problematic.
	# We may not be able to export it correctly.
	$warnmsg .= "Unusual record ".$rr->name." ($type) found\n";
      }

# BIND supports:
# A CNAME HINFO MB(ex) MD(ob) MF(ob) MG(ex) MINFO(ex) MR(ex) MX NS NULL
# PTR SOA TXT WKS AFSDB(ex) ISDN(ex) RP(ex) RT(ex) X25(ex) PX
# ... if one can ever find the right magic to format them correctly

# Net::DNS supports:
# RRSIG SIG NSAP NS NIMLOC NAPTR MX MR MINFO MG MB LOC ISDN IPSECKEY HINFO
# EID DNAME CNAME CERT APL AFSDB AAAA A DS NXT NSEC3PARAM NSEC3 NSEC KEY
# DNSKEY DLV X25 TXT TSIG TKEY SSHFP SRV SPF SOA RT RP PX PTR NULL APL::AplItem

      $sth = $dbh->prepare($sql.") VALUES (".$vallen.")") or die "problem preparing record insert SQL\n";
      $sth->execute(@vallist) or die "failed to insert ".$rr->string.": ".$sth->errstr."\n";

      $nrecs++;

    } # while axfr_next

    # Overwrite SOA record
    if ($rwsoa) {
      $soaflag = 1;
      my $sthgetsoa = $dbh->prepare("SELECT host,val,ttl FROM default_records WHERE group_id=? AND type=?");
      my $sthputsoa = $dbh->prepare("INSERT INTO records (domain_id,host,type,val,ttl) VALUES (?,?,?,?,?)");
      $sthgetsoa->execute($group,$reverse_typemap{SOA});
      while (my ($host,$val,$ttl) = $sthgetsoa->fetchrow_array()) {
	$host =~ s/DOMAIN/$domain/g;
	$val =~ s/DOMAIN/$domain/g;
	$sthputsoa->execute($dom_id,$host,$reverse_typemap{SOA},$val,$ttl);
      }
    }

    # Overwrite NS records
    if ($rwns) {
      $nsflag = 1;
      my $sthgetns = $dbh->prepare("SELECT host,val,ttl FROM default_records WHERE group_id=? AND type=?");
      my $sthputns = $dbh->prepare("INSERT INTO records (domain_id,host,type,val,ttl) VALUES (?,?,?,?,?)");
      $sthgetns->execute($group,$reverse_typemap{NS});
      while (my ($host,$val,$ttl) = $sthgetns->fetchrow_array()) {
	$host =~ s/DOMAIN/$domain/g;
	$val =~ s/DOMAIN/$domain/g;
	$sthputns->execute($dom_id,$host,$reverse_typemap{NS},$val,$ttl);
      }
    }

    die "No records found;  either $ifrom is not authoritative or doesn't allow transfers\n" if !$nrecs;
    die "Bad zone:  No SOA record!\n" if !$soaflag;
    die "Bad zone:  No NS records!\n" if !$nsflag;

    $dbh->commit;

  };

  if ($@) {
    my $msg = $@;
    eval { $dbh->rollback; };
    return ('FAIL',$msg." $warnmsg");
  } else {
    return ('WARN', $warnmsg) if $warnmsg;
    return ('OK',"Imported OK");
  }

  # it should be impossible to get here.
  return ('WARN',"OOOK!");
} # end importAXFR()


## DNSDB::export()
# Export the DNS database, or a part of it
# Takes database handle, export type, optional arguments depending on type
# Writes zone data to targets as appropriate for type
sub export {
  my $dbh = shift;
  my $target = shift;

  if ($target eq 'tiny') {
    __export_tiny($dbh,@_);
  }
# elsif ($target eq 'foo') {
#   __export_foo($dbh,@_);
#}
# etc

} # end export()


## DNSDB::__export_tiny
# Internal sub to implement tinyDNS (compatible) export
# Takes database handle, filehandle to write export to, optional argument(s)
# to determine which data gets exported
sub __export_tiny {
  my $dbh = shift;
  my $datafile = shift;

##fixme: slurp up further options to specify particular zone(s) to export

  ## Convert a bare number into an octal-coded pair of octets.
  # Take optional arg to indicate a decimal or hex input.  Defaults to hex.
  sub octalize {
    my $tmp = shift;
    my $srctype = shift || 'h';	# default assumes hex string
    $tmp = sprintf "%0.4x", hex($tmp) if $srctype eq 'h';	# 0-pad hex to 4 digits
    $tmp = sprintf "%0.4x", $tmp if $srctype eq 'd';	# 0-pad decimal to 4 hex digits
    my @o = ($tmp =~ /^(..)(..)$/);	# split into octets
    return sprintf "\\%0.3o\\%0.3o", hex($o[0]), hex($o[1]);;
  }

##fixme: fail if $datafile isn't an open, writable file

  # easy case - export all evarything
  # not-so-easy case - export item(s) specified
  # todo:  figure out what kind of list we use to export items

  my $domsth = $dbh->prepare("SELECT domain_id,domain,status FROM domains WHERE status=1");
  my $recsth = $dbh->prepare("SELECT host,type,val,distance,weight,port,ttl ".
	"FROM records WHERE domain_id=?");
  $domsth->execute();
  while (my ($domid,$dom,$domstat) = $domsth->fetchrow_array) {
    $recsth->execute($domid);
    while (my ($host,$type,$val,$dist,$weight,$port,$ttl) = $recsth->fetchrow_array) {
##fixme:  need to store location in the db, and retrieve it here.
# temporarily hardcoded to empty so we can include it further down.
my $loc = '';

##fixme:  record validity timestamp. tinydns supports fiddling with timestamps.
# note $ttl must be set to 0 if we want to use tinydns's auto-expiring timestamps.
# timestamps are TAI64
# ~~ 2^62 + time()
my $stamp = '';

# raw packet in unknown format:  first byte indicates length
# of remaining data, allows up to 255 raw bytes

##fixme?  append . to all host/val hostnames
      if ($typemap{$type} eq 'SOA') {

	# host contains pri-ns:responsible
	# val is abused to contain refresh:retry:expire:minttl
##fixme:  "manual" serial vs tinydns-autoserial
	# 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];
	print $datafile "Z$dom:$primary:$email"."::$refresh:$retry:$expire:$min_ttl:$ttl:$stamp:$loc\n";

      } elsif ($typemap{$type} eq 'A') {

	print $datafile "+$host:$val:$ttl:$stamp:$loc\n";

      } elsif ($typemap{$type} eq 'NS') {

	print $datafile "\&$host"."::$val:$ttl:$stamp:$loc\n";

      } elsif ($typemap{$type} eq 'AAAA') {

	print $datafile ":$host:28:";
	my $altgrp = 0;
	my @altconv;
	# Split in to up to 8 groups of hex digits (allows for IPv6 :: 0-collapsing)
	foreach (split /:/, $val) {
	  if (/^$/) {
	    # flag blank entry;  this is a series of 0's of (currently) unknown length
	    $altconv[$altgrp++] = 's';
	  } else {
	    # call sub to convert 1-4 hex digits to 2 string-rep octal bytes
	    $altconv[$altgrp++] = octalize($_)
	  }
	}
	foreach my $octet (@altconv) {
	  # if not 's', output
	  print $datafile $octet unless $octet =~ /^s$/;
	  # if 's', output (9-array length)x literal '\000\000'
	  print $datafile '\000\000'x(9-$altgrp) if $octet =~ /^s$/;
	}
	print $datafile ":$ttl:$stamp:$loc\n";

      } elsif ($typemap{$type} eq 'MX') {

	print $datafile "\@$host"."::$val:$dist:$ttl:$stamp:$loc\n";

      } elsif ($typemap{$type} eq 'TXT') {

##fixme:  split v-e-r-y long TXT strings?  will need to do so for BIND export, at least
	$val =~ s/:/\\072/g;	# may need to replace other symbols
	print $datafile "'$host:$val:$ttl:$stamp:$loc\n";

# by-hand TXT
#:deepnet.cx:16:2v\075spf1\040a\040a\072bacon.deepnet.cx\040a\072home.deepnet.cx\040-all:3600
#@       IN      TXT     "v=spf1 a a:bacon.deepnet.cx a:home.deepnet.cx -all"
#'deepnet.cx:v=spf1 a a\072bacon.deepnet.cx a\072home.deepnet.cx -all:3600

#txttest IN      TXT     "v=foo bar:bob kn;ob' \" !@#$%^&*()-=_+[]{}<>?"
#:txttest.deepnet.cx:16:\054v\075foo\040bar\072bob\040kn\073ob\047\040\042\040\041\100\043\044\045\136\046\052\050\051-\075\137\053\133\135\173\175\074\076\077:3600

# very long TXT record as brought in by axfr-get
# note tinydns does not support >512-byte RR data, need axfr-dns (for TCP support) for that
# also note, tinydns does not seem to support <512, >256-byte RRdata from axfr-get either.  :/
#:longtxt.deepnet.cx:16:
#\170this is a very long txt record.  it is really long.  long. very long.  really very long. this is a very long txt record.
#\263  it is really long.  long. very long.  really very long. this is a very long txt record.  it is really long.  long. very long.  really very long. this is a very long txt record. 
#\351 it is really long.  long. very long.  really very long.this is a very long txt record.  it is really long.  long. very long.  really very long. this is a very long txt record.  it is really long.  long. very long.  really very long.
#:3600

      } elsif ($typemap{$type} eq 'CNAME') {

	print $datafile "C$host:$val:$ttl:$stamp:$loc\n";

      } elsif ($typemap{$type} eq 'SRV') {

	# data is two-byte values for priority, weight, port, in that order,
	# followed by length/string data

	print $datafile ":$host:33:".octalize($dist,'d').octalize($weight,'d').octalize($port,'d');

	$val .= '.' if $val !~ /\.$/;
	foreach (split /\./, $val) {
	  printf $datafile "\\%0.3o%s", length($_), $_;
	}
	print $datafile "\\000:$ttl:$stamp:$loc\n";

      } elsif ($typemap{$type} eq 'RP') {

	# RP consists of two mostly free-form strings.
	# The first is supposed to be an email address with @ replaced by . (as with the SOA contact)
	# The second is the "hostname" of a TXT record with more info.
	print $datafile ":$host:17:";
	my ($who,$what) = split /\s/, $val;
	foreach (split /\./, $who) {
	  printf $datafile "\\%0.3o%s", length($_), $_;
	}
	print $datafile '\000';
	foreach (split /\./, $what) {
	  printf $datafile "\\%0.3o%s", length($_), $_;
	}
	print $datafile "\\000:$ttl:$stamp:$loc\n";

      } elsif ($typemap{$type} eq 'PTR') {

	# must handle both IPv4 and IPv6
##work
	# data should already be in suitable reverse order.
	print $datafile "^$host:$val:$ttl:$stamp:$loc\n";

      } else {
	# raw record.  we don't know what's in here, so we ASS-U-ME the user has
	# put it in correctly, since either the user is messing directly with the
	# database, or the record was imported via AXFR
	# <split by char>
	# convert anything not a-zA-Z0-9.- to octal coding

##fixme: add flag to export "unknown" record types - note we'll probably end up
# mangling them since they were written to the DB from Net::DNS::RR::<type>->rdatastr.
	#print $datafile ":$host:$type:$val:$ttl:$stamp:$loc\n";

      } # record type if-else

    } # while ($recsth)
  } # while ($domsth)
} # end __export_tiny()


## DNSDB::mailNotify()
# Sends notification mail to recipients regarding a DNSDB operation
sub mailNotify {
  my $dbh = shift;
  my ($subj,$message) = @_;

  return if $config{mailhost} eq 'smtp.example.com';   # do nothing if still using default SMTP host.

  my $mailer = Net::SMTP->new($config{mailhost}, Hello => "dnsadmin.$config{domain}");

  my $mailsender = ($config{mailsender} ? $config{mailsender} : $config{mailnotify});

  $mailer->mail($mailsender);
  $mailer->to($config{mailnotify});
  $mailer->data("From: \"$config{mailname}\" <$mailsender>\n",
	"To: <$config{mailnotify}>\n",
	"Date: ".strftime("%a, %d %b %Y %H:%M:%S %z",localtime)."\n",
	"Subject: $subj\n",
	"X-Mailer: DNSAdmin Notify v".sprintf("%.1d",$DNSDB::VERSION)."\n",
	"Organization: $config{orgname}\n",
	"\n$message\n");
  $mailer->quit;
}

# shut Perl up
1;
