# dns/trunk/DNSDB.pm
# Abstraction functions for DNS administration
###
# SVN revision info
# $Date: 2011-07-15 19:41:54 +0000 (Fri, 15 Jul 2011) $
# SVN revision $Rev: 104 $
# Last update by $Author: kdeugau $
###
# Copyright (C) 2008 - Kris Deugau <kdeugau@deepnet.cx>

package DNSDB;

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

$VERSION	= 0.1;
@ISA		= qw(Exporter);
@EXPORT_OK	= qw(
	&initGlobals
	&initPermissions &getPermissions &changePermissions &comparePermissions
	&connectDB &finish
	&addDomain &delDomain &domainName &domainID
	&addGroup &delGroup &getChildren &groupName
	&addUser &updateUser &delUser &userFullName &userStatus &getUserData
	&getSOA	&getRecLine &getDomRecs &getRecCount
	&addRec &updateRec &delRec
	&domStatus &importAXFR
	&export
	%typemap %reverse_typemap
	%permissions @permtypes $permlist
	);

@EXPORT		= (); # Export nothing by default.
%EXPORT_TAGS	= ( ALL => [qw(
		&initGlobals
		&initPermissions &getPermissions &changePermissions &comparePermissions
		&connectDB &finish
		&addDomain &delDomain &domainName &domainID
		&addGroup &delGroup &getChildren &groupName
		&addUser &updateUser &delUser &userFullName &userStatus &getUserData
		&getSOA &getRecLine &getDomRecs &getRecCount
		&addRec &updateRec &delRec
		&domStatus &importAXFR
		&export
		%typemap %reverse_typemap
		%permissions @permtypes $permlist
		)]
	);

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

# 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;

##
## Initialization and cleanup subs
##


## 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);

# Return here if we can't select.  Note that this indicates a
# problem executing the select.
  my $sth = $dbh->prepare("select group_id from groups limit 1");
  $sth->execute();
  return (undef,$DBI::errstr) if ($sth->err);

# 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 system-wide site defaults and things from config file
  if (open SYSDEFAULTS, "</etc/dnsdb.conf") {
##fixme - error check!
    while (<SYSDEFAULTS>) {
      next if /^\s*#/;
      $def{contact}	= $1 if /contact ?= ?([a-z0-9_.-]+)/i;
      $def{prins}		= $1 if /prins ?= ?([a-z0-9_.-]+)/i;
      $def{soattl}	= $1 if /soattl ?= ?([a-z0-9_.-]+)/i;
      $def{refresh}	= $1 if /refresh ?= ?([a-z0-9_.-]+)/i;
      $def{retry}		= $1 if /retry ?= ?([a-z0-9_.-]+)/i;
      $def{expire}	= $1 if /expire ?= ?([a-z0-9_.-]+)/i;
      $def{minttl}	= $1 if /minttl ?= ?([a-z0-9_.-]+)/i;
      $def{ttl}		= $1 if /ttl ?= ?([a-z0-9_.-]+)/i;
##fixme?  load DB user/pass from config file?
    }
  }
# load from database
  my $sth = $dbh->prepare("select val,name from rectypes");
  $sth->execute;
  while (my ($recval,$recname) = $sth->fetchrow_array()) {
    $typemap{$recval} = $recname;
    $reverse_typemap{$recname} = $recval;
  }
} # end initGlobals


## 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::_log()
# Log an action
# Internal sub
# Takes a database handle, <foo>, <bar>
sub _log {
} # end _log


##
## Processing subs
##

## DNSDB::addDomain()
# Add a domain
# Takes a database handle, domain name, numeric group, and boolean(ish) state (active/inactive)
# 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 $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...
    my $sth = $dbh->prepare("insert into domains (domain,group_id,status) values (?,?,?)");
    $sth->execute($domain,$group,$state);

    # get the ID...
    $sth = $dbh->prepare("select domain_id from domains where domain='$domain'");
    $sth->execute;
    ($dom_id) = $sth->fetchrow_array();

    # ... and now we construct the standard records from the default set.  NB:  group should be variable.
    $sth = $dbh->prepare("select host,type,val,distance,weight,port,ttl from default_records where group_id=$group");
    my $sth_in = $dbh->prepare("insert into records (domain_id,host,type,val,distance,weight,port,ttl)".
	" values ($dom_id,?,?,?,?,?,?,?)");
    $sth->execute;
    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);
    }

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

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


## DNSDB::delDomain()
# Delete a domain.
# 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 delDomain {
  my $dbh = shift;
  my $domid = 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 $failmsg = '';

  # Wrap all the SQL in a transaction
  eval {
    my $sth = $dbh->prepare("delete from records where domain_id=?");
    $failmsg = "Failure removing domain records";
    $sth->execute($domid);
    $sth = $dbh->prepare("delete from domains where domain_id=?");
    $failmsg = "Failure removing domain";
    $sth->execute($domid);

    # 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 delDomain()


## 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::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::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);

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

# 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
    $sth = $dbh->prepare("INSERT INTO default_records (group_id,host,type,val,distance,weight,port,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) {
	$sth->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.
      $sth->execute('ns1.example.com:hostmaster.example.com', 6, '10800:3600:604800:10800', 0, 0, 0, 86400);
      $sth->execute('DOMAIN', 1, '192.168.4.2', 0, 0, 0, 7200);
      $sth->execute('DOMAIN', 15, 'mx.example.com', 10, 0, 0, 7200);
      $sth->execute('DOMAIN', 2, 'ns1.example.com', 0, 0, 0, 7200);
      $sth->execute('DOMAIN', 2, 'ns2.example.com', 0, 0, 0, 7200);
      $sth->execute('www.DOMAIN', 5, 'DOMAIN', 0, 0, 0, 7200);
    }

    # 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::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;
  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, and group (default) or domain (live) ID
sub getSOA {
  $errstr = '';
  my $dbh = shift;
  my $def = shift;
  my $id = shift;
  my %ret;

  # (ab)use distance and weight columns to store SOA data

  my $sql = "SELECT record_id,host,val,ttl,distance from";
  if ($def eq 'def' or $def eq 'y') {
    $sql .= " default_records WHERE group_id=? AND type=$reverse_typemap{SOA}";
  } else {
    # we're editing a live SOA record;  find based on domain
    $sql .= " records WHERE domain_id=? AND type=$reverse_typemap{SOA}";
  }
  my $sth = $dbh->prepare($sql);
  $sth->execute($id);

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

  $ret{recid}	= $recid;
  $ret{ttl}	= $ttl;
  $ret{serial}	= $serial;
  $ret{prins}	= $prins;
  $ret{contact}	= $contact;
  $ret{refresh}	= $refresh;
  $ret{retry}	= $retry;
  $ret{expire}	= $expire;
  $ret{minttl}	= $minttl;

  return %ret;
} # end getSOA()


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

  my $sql = "SELECT r.record_id,r.host,r.type,r.val,r.distance,r.weight,r.port,r.ttl,r.longrec_id,l.recdata".
	(($def eq 'def' or $def eq 'y') ? ',r.group_id FROM default_' : ',r.domain_id FROM ').
	"records r LEFT OUTER JOIN longrecs l ON r.longrec_id=l.longrec_id WHERE record_id=?";
  my $ret = $dbh->selectrow_hashref($sql, undef, ($id) ) or warn $dbh->errstr;

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

  $ret->{val} = $ret->{recdata} if $ret->{longrec_id};	# put the long data in the real value space
  delete $ret->{longrec_id};	# remove these since they shouldn't be exposed - the caller
  delete $ret->{recdata};	# should not care about "long records" vs normal ones.

  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 $type = 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';

  $type = 'y' if $type eq 'def';

  my $sql = "SELECT r.record_id,r.host,r.type,r.val,r.distance,r.weight,r.port,r.ttl,r.longrec_id,l.recdata FROM ";
  $sql .= "default_" if $type eq 'y';
  $sql .= "records r ";
  $sql .= "INNER JOIN rectypes t ON r.type=t.val ";	# for sorting by type alphabetically
  $sql .= "LEFT OUTER JOIN longrecs l ON r.longrec_id=l.longrec_id ";
  if ($type eq 'y') {
    $sql .= "WHERE r.group_id=?";
  } else {
    $sql .= "WHERE r.domain_id=?";
  }
  $sql .= " AND NOT r.type=$reverse_typemap{SOA}";
  # 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";
  $sql .= " LIMIT $nrecs OFFSET ".($nstart*$nrecs) if $nstart ne 'all';

  my $sth = $dbh->prepare($sql) or warn $dbh->errstr;
  $sth->execute($id) or warn "$sql: ".$sth->errstr;

  my @retbase;
  while (my $ref = $sth->fetchrow_hashref()) {
    $ref->{val} = $ref->{recdata} if $ref->{longrec_id};	# put the long data in the real value space
    delete $ref->{longrec_id};	# remove these since they shouldn't be exposed - the caller
    delete $ref->{recdata};	# should not care about "long records" vs normal ones.
    push @retbase, $ref;
  }

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


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

  my ($count) = $dbh->selectrow_array("SELECT count(*) FROM ".
        ($defrec eq 'y' ? 'default_' : '')."records ".
        "WHERE ".($defrec eq 'y' ? 'group' : 'domain')."_id=? ".
        "AND NOT type=$reverse_typemap{SOA}", undef, ($id) );

  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
sub addRec {
  $errstr = '';
  my $dbh = shift;
  my $defrec = shift;
  my $id = shift;

  my $host = shift;
  my $rectype = shift;
  my $val = shift;
  my $ttl = shift;

  my $fields = ($defrec eq 'y' ? 'group_id' : 'domain_id').",host,type,val,ttl";
  my $vallen = "?,?,?,?,?";
  my @vallist = ($id,$host,$rectype,$val,$ttl);

  my $dist;
  if ($rectype == $reverse_typemap{MX} or $rectype == $reverse_typemap{SRV}) {
    $dist = shift;
    return ('FAIL',"Need distance for $typemap{$rectype} record") if !defined($dist);
    $fields .= ",distance";
    $vallen .= ",?";
    push @vallist, $dist;
  }
  my $weight;
  my $port;
  if ($rectype == $reverse_typemap{SRV}) {
    # check for _service._protocol.  NB:  RFC2782 does not say "MUST"...  nor "SHOULD"...
    # it just says (paraphrased) "... is prepended with _ to prevent DNS collisions"
    return ('FAIL',"SRV records must begin with _service._protocol")
	if $host !~ /^_[A-Za-z]+\._[A-Za-z]+\.[a-z0-9-]+/;
    $weight = shift;
    $port = shift;
    return ('FAIL',"Need weight and port for SRV record") if !defined($weight) or !defined($port);
    $fields .= ",weight,port";
    $vallen .= ",?,?";
    push @vallist, ($weight,$port);
  }

  # 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 {
    if (length($val) > 100 ) {
      # extralong records get an entry in a separate table.
      $dbh->do("INSERT INTO longrecs (recdata) VALUES (?)", undef, ($val) );
      my ($longid) = $dbh->selectrow_array("SELECT longrec_id FROM longrecs WHERE recdata=?", undef, ($val) );
      $fields .= ",longrec_id";
      $vallen .= ",?";
      push @vallist, $longid;
      $vallist[3] = '';	# so we don't barf when we insert the main record
    }
    $dbh->do("INSERT INTO ".($defrec eq 'y' ? 'default_' : '')."records ($fields) VALUES ($vallen)",
	undef, @vallist);
    $dbh->commit;
  };
  if ($@) {
    my $msg = $@;
    eval { $dbh->rollback; };
    return ('FAIL',$msg);
  }

  return ('OK','OK');

} # end addRec()


## DNSDB::updateRec()
# Update a record
sub updateRec {
  $errstr = '';

  my $dbh = shift;
  my $defrec = shift;
  my $id = shift;

# all records have these
  my $host = shift;
  my $type = shift;
  my $val = shift;
  my $ttl = shift;

  return('FAIL',"Missing standard argument(s)") if !defined($ttl);

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

  if ($type == $reverse_typemap{MX} || $type == $reverse_typemap{SRV}) {
    $dist = shift;
    return ('FAIL',"MX or SRV requires distance") if !defined($dist);
    if ($type == $reverse_typemap{SRV}) {
      $weight = shift;
      return ('FAIL',"SRV requires weight") if !defined($weight);
      $port = shift;
      return ('FAIL',"SRV requires port") if !defined($port);
    }
  }

#  my $sql = "SELECT r.record_id,r.host,r.type,r.val,r.distance,r.weight,r.port,r.ttl,r.longrec_id,l.recdata FROM ";
#  $sql .= "default_" if $type eq 'y';
#  $sql .= "records r ";
#  $sql .= "LEFT OUTER JOIN longrecs l ON r.longrec_id=l.longrec_id ";

  # get the long record ID, if any
  my ($longid) = $dbh->selectrow_array("SELECT longrec_id FROM ".($defrec eq 'y' ? 'default_' : '')."records ".
	"WHERE record_id=?", undef, ($id) );

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

  eval {
    # there's really no tidy way to squash this down.  :/
    if (length($val) > 100) {
      if ($longid) {
	$dbh->do("UPDATE longrecs SET recdata=? WHERE longrec_id=?", undef, ($val, $longid) );
      } else {
##fixme:  has to be a better way to be sure we get the right recid back once inserted...
	$dbh->do("INSERT INTO longrecs (recdata) VALUES (?)", undef, ($val) );
	my ($newlongid) = $dbh->selectrow_array("SELECT currval('longrecs_longrec_id_seq')");
        $dbh->do("UPDATE ".($defrec eq 'y' ? 'default_' : '')."records SET val=?,longrec_id=? ".
		"WHERE record_id=?", undef, ('', $newlongid, $id) );
      }
    } else {
      if ($longid) {
	$dbh->do("DELETE FROM longrecs WHERE longrec_id=?", undef, ($longid) );
	$dbh->do("UPDATE ".($defrec eq 'y' ? 'default_' : '')."records SET val=?,longrec_id=NULL ".
		"WHERE record_id=?", undef, ($val, $id) );
      } else {
	$dbh->do("UPDATE ".($defrec eq 'y' ? 'default_' : '')."records SET val=? ".
		"WHERE record_id=?", undef, ($val, $id) );
      }
    }

    $dbh->do("UPDATE ".($defrec eq 'y' ? 'default_' : '')."records ".
	"SET host=?,type=?,ttl=?,distance=?,weight=?,port=? ".
	"WHERE record_id=?", undef, ($host, $type, $ttl, $dist, $weight, $port, $id) );

  };
  if ($@) {
    my $msg = $@;
    $dbh->rollback;
    return ('FAIL', $msg);
  }
#  return ('FAIL',$sth->errstr."<br>\n$errstr<br>\n") if $sth->err;

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


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

  my $sth = $dbh->prepare("DELETE FROM ".($defrec eq 'y' ? 'default_' : '')."records WHERE record_id=?");
  $sth->execute($id);

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

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


## DNSDB::domStatus()
# Sets and/or returns a domain's status
# Takes a database handle, domain ID and optionally a status argument
# Returns undef on errors.
sub domStatus {
  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 domains set status=? where domain_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 =~ /^domo(?:n|ff)$/) {
      $sth->execute(($newstatus eq 'domon' ? 1 : 0),$id);
    }
  }

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


## 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.

      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') {
	# 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.
	push @vallist, $rr->txtdata;
      } elsif ($type eq 'SPF') {
##fixme: and the same caveat here, since it is apparently a clone of ::TXT
	push @vallist, $rr->txtdata;
      } 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 {
	push @vallist, $rr->rdatastr;
	# 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 r.host,r.type,r.val,r.distance,r.weight,r.port,r.ttl,l.recdata ".
	"FROM records r LEFT OUTER JOIN longrecs l ON r.longrec_id=l.longrec_id 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,$lval) = $recsth->fetchrow_array) {
      $val = $lval if $lval;

# 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
	print $datafile "Z$host"."::$val:$ttl\n";

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

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

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

	print $datafile "\&$host"."::$val:$ttl\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 :: 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\n";

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

	print $datafile "\@$host"."::$val:$dist:$ttl\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\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\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\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\n";

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

	# must handle both IPv4 and IPv6
##work

      } # record type if-else

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


# shut Perl up
1;
