#!/usr/bin/perl
#
# Copyright 2005-2010 SPARTA, Inc.  All rights reserved.  See the COPYING
# file distributed with this software for details.
#
#
# rollerd
#
#	This script manages the key rollover process.
#
#	ZSK rollover uses the Pre-Publish Method of rollover and takes
#	place in four phases:
#		- wait until it's time to perform a ZSK rollover
#		- sign the zone with the KSK and Published ZSK
#		- wait for old zone data to expire from caches
#		- sign the zone with the new Current ZSK key
#
#	KSK rollover uses the Double Signature Method of rollover and takes
#	place in seven phases:
#		- wait for cache data to expire
#		- generate a new (published) KSK
#		- wait for the old DNSKEY RRset to expire from caches
#		- roll the KSKs
#		- transfer new keyset to the parent
#			(currently, this is done manually)
#		- wait for parent to publish the new DS record
#			(currently, this is done manually)
#		- reload the zone
#
#	See the pod for much more information.
#

#
# If we're executing from a packed environment, make sure we've got the
# library path for the packed modules.
#
BEGIN
{
	if($ENV{'PAR_TEMP'})
	{
		unshift @INC, ("$ENV{'PAR_TEMP'}/inc/lib");
	}
}


use strict;

use Cwd;
use Getopt::Long qw(:config no_ignore_case_always);

use Net::DNS::SEC::Tools::dnssectools;
use Net::DNS::SEC::Tools::conf;
use Net::DNS::SEC::Tools::defaults;
use Net::DNS::SEC::Tools::keyrec;
use Net::DNS::SEC::Tools::rolllog;
use Net::DNS::SEC::Tools::rollmgr;
use Net::DNS::SEC::Tools::rollrec;
use Net::DNS::SEC::Tools::timetrans;
use Net::DNS::SEC::Tools::tooloptions;
use Net::DNS::SEC::Tools::BootStrap;

use Net::DNS::ZoneFile::Fast;

use POSIX qw(setsid);
use POSIX qw(setuid);

#
# Version information.
#
my $NAME   = "rollerd";
my $VERS   = "$NAME version: 1.5";
my $DTVERS = "DNSSEC-Tools Version: 1.7";

#######################################################################

my $ME		= "rollerd";

#
# Some path variables to be set from the config file.
#
my $dtconfig;				# DNSSEC-Tools configuration file.
my $rndc;				# BIND name server control program.
my $rrchk;				# Rollrec file checking program.
my $zonesigner;				# Zone-signing program.

my $PWD = '/bin/pwd';

my $DEFAULT_NAP	= 60;

##########################################
#
# Method selected for calculating rollover times.
#

my $RM_ENDROLL	  = 1;		# Calculate from end of last roll.
my $RM_KEYGEN	  = 2;		# Calculate from last key generation.
my $RM_STARTROLL  = 3;		# Calculate from start of last roll.  (NYI)

my $krollmethod = $RM_ENDROLL;	# Rollover calculation to use for KSKs.
my $zrollmethod = $RM_ENDROLL;	# Rollover calculation to use for ZSKs.

##########################################
#
# Data required for command line options.
#

my $rollrecfile;			# Rollrec file to be managed.

my %dtconf;				# DNSSEC-Tools config file.
my $DT_LOADZONE	= "roll_loadzone";
my $DT_LOGFILE	= "roll_logfile";
my $DT_LOGLEVEL	= "roll_loglevel";
my $DT_SLEEP	= "roll_sleeptime";
my $DT_USERNAME	= "roll_username";

my $OPT_HELP	   = "help";
my $OPT_DIR	   = "directory";
my $OPT_DISPLAY	   = "display";
my $OPT_DTCONF	   = "dtconfig";
my $OPT_LOGFILE	   = "logfile";
my $OPT_LOGLEVEL   = "loglevel";
my $OPT_NORELOAD   = "noreload";
my $OPT_PARAMS	   = "parameters";
my $OPT_SINGLERUN  = "singlerun";
my $OPT_FOREGROUND = "foreground";
my $OPT_ALWAYSSIGN = "alwayssign";
my $OPT_PIDFILE    = "pidfile";
my $OPT_RRFILE	   = "rrfile";
my $OPT_SLEEP	   = "sleep";
my $OPT_USERNAME   = "username";
my $OPT_VERBOSE	   = "verbose";
my $OPT_VERSION	   = "Version";
my $OPT_ZONESIGNER = "zonesigner";

my %opts = ();			# Filled option array.
my @opts =
(
	"rrfile=s",			# Rollrec file.
	"directory=s",			# Execution directory.
	"display",			# Use output GUI.
	"logfile=s",			# Log file.
	"loglevel=s",			# Logging level.
	"noreload",			# Don't reload zone files.
	"pidfile=s",			# pid storage file.
	"dtconfig=s",			# dnssec-tools config file to use.
	"sleep=i",			# Sleep amount (in seconds.)
	"parameters",			# Display the parameters and exit.
	"singlerun",			# Single run:  process everything once.
	"foreground",			# Run in the foreground; don't fork.
	"alwayssign",			# Always sign when running in singlerun.
	"username=s",			# User name for which to run as.
	"help",				# Give a usage message and exit.
	"verbose",			# Verbose output.
	"Version",			# Display the version number.
	"zonesigner=s",			# Location of zonesigner executable.
);

#
# Flag values for the various options.  Variable/option connection should
# be obvious.
#
my $alwayssign = 0;			# Always sign the zone in -singlerun.
my $dtcf;				# DNSSEC-Tools configuration file.
my $foreground = 0;			# Run in the foreground.
my $logfile;				# Log file.
my $loglevel;				# Logging level.
my $loglevel_save;			# Saved logging level.
my $zoneload = 1;			# Zone-reload flag.
my $pidfile;				# Pid storage file.
my $singlerun = 0;			# Single run only.
my $sleep_override = 0;			# Sleep-override flag.
my $sleepcnt;				# Time we've slept so far.
my $sleeptime;				# Sleep interval in seconds.
my $username;				# User name we'll change to.
my $verbose = 0;			# Verbose option.

my $display = 0;			# Do display processing.

my $boottime = gmtime();		# Timestamp of rollerd's start time.

my $MIN_SLEEP = 10;			# Minimum time rollerd will sleep.

my $curdir;				# Directory.
my $keyarch;				# Key-archive program.
my $packed = 0;				# Flag indicating if running packed.
my $xqtdir;				# Execution directory.

#######################################################################

my $ret;				# Return code from main().

#
# Detect required Perl modules.
#
dnssec_tools_load_mods('Date::Parse'	=> "",
		       'Date::Format'	=> "",);

#
# Do Everything.
#
$ret = main();
exit($ret);

#-----------------------------------------------------------------------------
# Routine:	main()
#
# Purpose:	Do Everything.
#
#			 steps:
#				while rollrec file is not empty
#					read rollrec file
#
#					for each rollrec in the rollrec file
#						handle according to its phase
#
sub main
{
	my $argc;			# Number of command line arguments.
	my $olderr;			# Saved error action.

	#
	# Initialize a few things...
	#	- force nonbuffered
	#	- default error action
	#	- set run-packed flag
	#
	$| = 1;
	erraction(ERR_MSG);
	$packed = runpacked();

	#
	# Parse our command line into an options hash.
	#
	GetOptions(\%opts,@opts) || usage();

	#
	# Set up the appropriate DNSSEC-Tools config file.  If we're running
	# in a packed configuration, we'll use the config file in the packed
	# environment's directory.
	#
	if($packed)
	{
		$opts{$OPT_DIR} = ".";
		setconffile("$ENV{'PAR_TEMP'}/inc/dnssec-tools.conf");
	}

	#
	# If there's a -dtconfig command line option, we'll use that,
	#
	if(exists($opts{$OPT_DTCONF}))
	{
		setconffile($opts{$OPT_DTCONF});
	}

	#
	# Check our options and arguments.
	#
	$dtconfig = getconffile();
	%dtconf = parseconfig();
	optsandargs();

	#
	# Run our configuration checks and make sure any error messages
	# will be printed.
	#
	$olderr = erraction(ERR_MSG);
	if(dt_confcheck(0) > 0)
	{
		dt_confcheck(1);
		print STDERR "\nrollerd:  configuration checks failed, halting\n";
		rolllog_log(LOG_ALWAYS,"","rollerd configuration checks failed");
		cleanup();
	}
	erraction($olderr);

	#
	# Check our required external commands.
	#
	getprogs();
	cmdcheck(\%opts);

	#
	# Daemonize ourself.
	#
	exit(0) if(!$singlerun && !$foreground && fork());
	POSIX::setsid();

	#
	# Ensure we're the only rollerd running and drop a pid file.
	#
	if(rollmgr_dropid() == 0)
	{
		print STDERR "another rollerd is already running\n";
		rolllog_log(LOG_ALWAYS,"","another rollerd tried to start");
		cleanup();
	}

	#
	# If it hasn't been set yet, get the pathname for zonesigner.
	#
	if(($zonesigner eq '') &&
	   (($zonesigner=dt_cmdpath('zonesigner')) eq ''))
	{
		print STDERR "no absolute path defined for zonesigner; exiting...\n";
		rolllog_log(LOG_ALWAYS,"","no absolute path defined for zonesigner; exiting...");
		cleanup();
	}

	#
	# Tell the log we're up.
	#
	bootmsg(1);

	#
	# Set up the command channel.
	#
	rollmgr_channel(1);

	#
	# Main event loop.  If the rollrec file is okay, we'll read it,
	# check its zones -- rolling 'em if need be -- and saving its state.
	# We'll always check for user commands and then sleep a bit.
	#
	while(42)
	{
# rolllog_log(LOG_ALWAYS,"","looping ------------------------------------------");

		#
		# Turn off signal handlers so they don't interrupt us
		# while we're running the queue.
		#
		controllers(0);
		$sleep_override = 0;

		#
		# If we have a valid rollrec file, we'll read its contents
		# and handle for expired KSKs and ZSKs.
		#
		if(rrfchk($rollrecfile))
		{
			my $kronos1;			# Check's start time.
			my $kronos2;			# Check's end time.
			my $kronodiff;			# Difference of times.
			my $kronos;			# difference string.

			#
			# Get the contents of the rollrec file and check
			# for expired KSKs and ZSKs.
			#
			rollrec_lock();
			if(rollrec_read($rollrecfile) > 0)
			{
				#
				# Check the zones for expired ZSKs.  We'll also
				# keep track of how long it takes to check the
				# ZSKs.
				#
				$kronos1 = time;
				rollkeys();
				$kronos2 = time;
				$kronodiff = $kronos2 - $kronos1;
				$kronos = timetrans($kronodiff);
				rolllog_log(LOG_TMI,"<timer>","keys checked in $kronos");

				#
				# Save the current rollrec file state.
				#
				rollrec_close();
			}
			rollrec_unlock();
		}

		#
		# Check for user commands.
		#
		commander();

		#
		# Turn on our signal handlers and then take a nap.
		#
		if($singlerun)
		{
			halt_handler();
			exit(0);
		}
		
		controllers(1);
		sleeper($sleeptime);

	}
}

#-----------------------------------------------------------------------------
# Routine:	rollkeys()
#
# Purpose:	Go through the zones in the rollrec file and start rolling
#		the ZSKs and KSKs for those which have expired.
#
sub rollkeys
{
	my @rrfstats;			# Stats for rollrec file.

	foreach my $rname (rollrec_names())
	{
		my $rrr;		# Reference to rollrec.
		my %rr;			# Rollrec hash.

		#
		# Return to our execution directory.
		#
		rolllog_log(LOG_TMI,$rname,"execution directory:  chdir($xqtdir)");
		chdir($xqtdir);

		#
		# Ensure the logging level is set correctly.
		#
		$loglevel = $loglevel_save;

		#
		# Get the rollrec for this name.  If it doesn't have one,
		# whinge and continue to the next.
		# (This should never happen, but...)
		#
		$rrr = rollrec_fullrec($rname);
		if(!defined($rrr))
		{
			rolllog_log(LOG_ERR,$rname,"no rollrec defined for zone");
			next;
		}
		%rr = %$rrr;

		#
		# Set the logging level to the rollrec entry's level (if it
		# has one) for the duration of processing this zone.
		#
		$loglevel_save = $loglevel;
		if(defined($rr{'loglevel'}))
		{
			my $llev;			# Logging level.

			$llev = rolllog_num($rr{'loglevel'});
			if($llev != -1)
			{
				$loglevel = $llev;
				rolllog_level($loglevel,0);
			}
			else
			{
				rolllog_log(LOG_ERR,$rname,"invalid rollrec logging level \"$rr{'loglevel'}\"");
			}
		}

		#
		# Don't do anything with skip records.
		#
		if($rr{'rollrec_type'} eq "skip")
		{
			rolllog_log(LOG_TMI,$rname,"is a skip rollrec");
			next;
		}

		#
		# If this rollrec has a directory record, we'll move into
		# that directory for execution.  If the chdir() fails, we'll
		# skip this rollrec.
		#
		if(exists($rr{'directory'}))
		{
			my $rrdir = $rr{'directory'};

			if(chdir($rrdir) == 0)
			{
				rolllog_log(LOG_ERR,$rname,"invalid rollrec directory \"$rrdir\"; skipping...");
				next;
			}
			rolllog_log(LOG_TMI,$rname,"using rollrec directory \"$rrdir\"");
		}

		#
		# Ensure the record has the KSK and ZSK phases.
		#
		if($rr{'kskphase'} == -1)
		{
			rolllog_log(LOG_TMI,$rname,"new kskphase entry");
			kskphase($rname,$rrr,0)
		}
		if($rr{'zskphase'} == -1)
		{
			rolllog_log(LOG_TMI,$rname,"new zskphase entry");
			zskphase($rname,$rrr,0)
		}

		#
		# If this zone's current KSK has expired, we'll get it rolling.
		# 
		if(ksk_expired($rname,$rrr,"kskcur"))
		{
			rolllog_log(LOG_TMI,$rname,"current KSK has expired\n") if($rr{'zskphase'} == 0);

			ksk_phaser($rname,$rrr);
		}
		else
		{
			rolllog_log(LOG_TMI,$rname,"current KSK still valid");
		}

		#
		# If this zone's current ZSK has expired, we'll get it rolling.
		# 
		if(zsk_expired($rname,$rrr,"zskcur"))
		{
			rolllog_log(LOG_INFO,$rname,"current ZSK has expired\n") if($rr{'zskphase'} == 0);
			zsk_phaser($rname,$rrr);
		}
		else
		{
			rolllog_log(LOG_TMI,$rname,"current ZSK still valid");
		}

		#
		# If -alwayssign was specified, always sign the zone
		# even if we didn't need to for this period.
		#

		#
		# XXX: this could double sign if some of the above steps
		# already signed the zone.  We should only sign if nothing
		# was done above.
		#
		if($alwayssign)
		{
			my $krr;		# Ref to keyrec data.
			my $extraargs = "";	# Phase-dependent argument.

			rolllog_log(LOG_TMI,$rname,
				    "Signing the zone (-alwayssign specified)");

			#
			# Check value and file existence, etc.
			#
			$krr = opts_zonekr($rrr->{'keyrec'},$rrr->{'zonename'});

			#
			# If we're in phases 2-3, make sure to use the
			# published zsk.
			#
			if(($rrr->{'zskphase'} >= 2) &&
			   ($rrr->{'zskphase'} <= 3))
			{
				$extraargs = "-usezskpub";
			}

			# KSK signing uses double-signature so nothing
			# is needed since zonesigner always uses all
			# available keys.

			#
			# Actually do the signing.
			#
			my $ret = signer($rname, "always-sign", $krr);
			if($ret)
			{
				rolllog_log(LOG_ERR, "signing $rname failed!");
			}
		}

	}

	#
	# Ensure the logging level is set correctly.
	#
	$loglevel = $loglevel_save;
	rolllog_level($loglevel,0);
}

###############################################################################

#-----------------------------------------------------------------------------
# Routine:	zsk_expired()
#
# Purpose:	This routine returns a boolean indicating if the specified
#		zone has an expired ZSK key of the given type.
#
#		The zone's keyrec file name is taken from the given rollrec
#		entry.  The keyrec file is read and the zone's entry found.
#		The key keyrec of the specified key type (currently, just
#		"zskcur") is pulled from the keyrec file.  Each key in the
#		named signing set will be checked.
#		
#		Key expiration is determined by comparing the key keyrec's
#		gensecs field to the current time.  The key hasn't expired
#		if the current time is less than the gensecs; the key has
#		expired if the current time is greater than the gensecs.
#
sub zsk_expired
{
	my $rname = shift;			# Name of rollrec rec.
	my $rrr = shift;			# Reference to rollrec.
	my $keyset = shift;			# Key to check.

	my %rr;					# Rollrec hash.

	my $krname;				# Name of keyrec.
	my $krec;				# Keyrec reference.
	my %set;				# Keyrec hash.

	my $khr;				# Ref to key's hash.
	my %kh;					# Key's hash.

	my @signset;				# Key's signing set.

	my $chronostr;				# Text expiration time.
	my $cronus;				# Current time.
	my $expired = 0;			# Expired-zone flag.
	my $minlife = -1;			# Minimum ZSK life.
	my $minhr;				# Ref to min-key's keyrec.
	my $rolltime;				# Time roll should occur.
	my $starter;				# Time 0 for calc'ing rolltime.
	my $waitsecs;				# Time to expiration.

	#
	# Get the rollrec's hash.
	#
	%rr = %$rrr;

	#
	# If this zone is in the middle of KSK rollover, we'll stop
	# working on ZSK rollover.
	#
	if($rr{'kskphase'} > 0)
	{
		my $pstr;				# Phase string.

		$pstr = ": " . rollmgr_get_phase('KSK', $rr{'kskphase'});
		$pstr = '' if($pstr eq ": ");

		rolllog_log(LOG_TMI,$rname,"in KSK rollover (phase $rr{'kskphase'}$pstr); not attempting ZSK rollover");
		return(0);
	}

	#
	# If this zone is in the middle of rollover processing, we'll
	# immediately assume the key has expired.
	#
	return(1) if($rr{'zskphase'} > 0);

	#
	# Get the rollin' key's keyrec for our zone.
	#
	$krname = $rr{'keyrec'};
	$krec = zonekeykr($rname,$rr{'zonename'},$krname,$keyset);
	if($krec == 0)
	{
		rolllog_log(LOG_ERR,$rname,"unable to find a keyrec for ZSK \"$keyset\" in \"$krname\"");
		return(0);
	}
	%set   = %$krec;

	#
	# Make sure we've got an actual set keyrec and keys.
	#
	if($set{'keyrec_type'} ne 'set')
	{
		rolllog_log(LOG_ERR,$rname,"\"$keyset\"'s keyrec is not a set keyrec");
		return(0);
	}
	if(!defined($set{'keys'}) || ($set{'keys'} eq ""))
	{
		rolllog_log(LOG_ERR,$rname,"\"$krname\" has no keys; unable to check expiration");
		return(0);
	}

	#
	# Ensure that there's a signing set.
	#
	@signset = split / /, $set{'keys'};
	if(@signset == 0)
	{
		rolllog_log(LOG_ERR,$rname,"\"$krname\" has no keys; unable to check expiration");
		return(0);
	}

	#
	# Check each key in the signing set to find the one with the shortest
	# lifespan.  We'll calculate rollover times based on that.
	#
	foreach my $keyname (@signset)
	{
		my $keylife;			# Key's life value.

		#
		# Get the key's keyrec hash.
		#
		$khr = keyrec_fullrec($keyname);
		next if(!$khr);
		%kh = %$khr;

		#
		# Ensure that required keyrec field exists.
		#
		if(!defined($kh{"zsklife"}))
		{
			rolllog_log(LOG_ERR,$rname,"keyrec does not contain a zsklife record");
			return(0);
		}

		#
		# If this key's life is shorter than any we've seen, it
		# becomes the new minimum.  If this is the first key we're
		# looking at, we'll save it as the minimum.
		#
		$keylife = $kh{'zsklife'};
		if($minlife == -1)
		{
			$minlife = $keylife;
			$minhr	 = $khr;
		}
		else
		{
			if($keylife < $minlife)
			{
				$minlife = $keylife;
				$minhr	 = $khr;
			}
		}
	}

if(!defined($minhr))
{
rolllog_log(LOG_ALWAYS,$rname,"--------> zsk_expired:  couldn't find minimum key keyrec");
return(0);
}

	#
	# Get the minimum key's keyrec hash.
	#
	%kh = %$minhr;

	#
	# Get the start time on which the expiration time is based.
	#
	if($zrollmethod == $RM_ENDROLL)
	{
		#
		# Ensure that required rollrec field exists.
		#
		if(!defined($rr{'zsk_rollsecs'}))
		{
			rolllog_log(LOG_INFO,$rname,"creating new zsk_rollsecs record and forcing ZSK rollover");
			rollstamp($rname,'zsk');
			return(1);
		}
		$starter = $rr{'zsk_rollsecs'};
	}
	elsif($zrollmethod == $RM_KEYGEN)
	{
		#
		# Ensure that required keyrec field exists.
		#
		if(!defined($kh{'keyrec_gensecs'}))
		{
			rolllog_log(LOG_ERR,$rname,"keyrec does not contain a keyrec_gensecs record");
			return(0);
		}
		$starter = $kh{'keyrec_gensecs'};
	}
	elsif($zrollmethod == $RM_STARTROLL)
	{
		rolllog_log(LOG_ERR,$rname,"RM_STARTROLL not yet implemented");
		return(0);
	}

	#
	# Don't roll immediately if the rollrec file was newly created.
	#
	if($starter == 0)
	{
		rollstamp($rname,'zsk');
		return(0);
	}

	#
	# Get the key's expiration time.
	#
	$rolltime = $starter + $minlife;

	#
	# Get the current time.
	#
	$cronus	 = time;

	#
	# Figure out the log message we should give.
	#
	$waitsecs = $rolltime - $cronus;
	if($waitsecs >= 0)
	{
		$chronostr = timetrans($waitsecs);
		rolllog_log(LOG_EXPIRE,$rname,"        expiration in $chronostr\n");
		display("expiration $rname 0 ZSK $waitsecs");
	}
	else
	{
		$waitsecs = $cronus - $rolltime;
		$chronostr = timetrans($waitsecs);
		rolllog_log(LOG_EXPIRE,$rname,"        expired $chronostr ago\n");
		display("zskphase $rname 0");
	}

	#
	# The key has expired if the current time has passed the key's lifespan.
	# The key has not expired if the key's lifespan has yet to reach the
	# current time.
	#
	$expired = 1 if($cronus > $rolltime);

	#
	# Return the success/failure indication.
	#
	return($expired);
}

#-----------------------------------------------------------------------------
# Routine:	zsk_phaser()
#
# Purpose:	Move the specified zone's ZSKs through the appropriate phases.
#
sub zsk_phaser
{
	my $rname = shift;		# Zone name.
	my $rrr = shift;		# Reference to rollrec.

	my %rr;				# Rollrec hash.
	my $phase;			# Zone's current rollover phase.

	#
	# Get this rollrec record's current phase.
	#
	%rr = %$rrr;
	$phase = $rr{'zskphase'};

	#
	# Work on this rollrec's phase.
	#
	$phase = zskphase($rname,$rrr,1)	if($phase == 0);
	$phase = zsk_phasewait($rname,$rrr,1)	if($phase == 1);
	$phase = zsk_phase2($rname,$rrr)	if($phase == 2);
	$phase = zsk_phasewait($rname,$rrr,3)	if($phase == 3);
	$phase = zsk_phase4($rname,$rrr)	if($phase == 4);
}

#-----------------------------------------------------------------------------
# Routine:	zsk_phasewait()
#
# Purpose:	Check if this zone's rollover-wait phase is over.
#		The zone's phase number -- current or new -- is returned.
#
sub zsk_phasewait
{
	my $rname = shift;			# Name of rollrec.
	my $rrr	  = shift;			# Reference to rollrec.
	my $phase = shift;			# Rollover phase.

	my %rr;					# Rollrec hash.

	#
	# Get the rollrec.
	#
	$rrr = rollrec_fullrec($rname);
	%rr = %$rrr;

	#
	# Check if we can go to the next rollover phase.  If not, we'll
	# go to the next rollrec entry and return to this later.
	#
	if(!ttlexpire($rname,$rrr,$phase,'ZSK'))
	{
		return($phase);
	}

	#
	# Bump this rollrec's phase number and return the new phase.
	#
	$phase++;
	zskphase($rname,$rrr,$phase);
	return($phase);
}

#-----------------------------------------------------------------------------
# Routine:	zsk_phase2()
#
# Purpose:	Perform the phase 2 steps of the ZSK rollover.  These are:
#
#			- sign the zone with the KSK and Published ZSK
#			- reload the zone
#			- wait for old zone data to expire
#
sub zsk_phase2
{
	my $rname = shift;		# Name of rollrec.
	my $rrr = shift;		# Reference to rollrec.

	my %rr = %$rrr;			# Rollrec hash.

	my $krf;			# Rollrec's keyrec name.
	my %krf;			# Keyrec hash.
	my $krr;			# Keyrec reference.

	my $ret;			# Result from command executions.

	#
	# Get the rollrec's associated keyrec file and ensure that it exists.
	#
	$krf = $rr{'keyrec'};
	if(!$krf  || ($krf eq ""))
	{
		rolllog_log(LOG_ERR,$rname,"ZSK phase 2:  no keyrec for zone specified");
		return;
	}
	if(! -e $krf)
	{
		rolllog_log(LOG_ERR,$rname,"ZSK phase 2:  keyrec \"$krf\" for zone does not exist");
		return;
	}

	#
	# Get the keyrec.
	#
	$krr = opts_zonekr($krf,$rr{'zonename'});
	%krf = %$krr;

	#
	# Sign the zone with the Published ZSK.
	#
	$ret = signer($rname,"ZSK phase 2",$krr);
	if($ret)
	{
		rolllog_log(LOG_ERR,$rname,"ZSK phase 2:  unable to sign zone with the Published ZSK");
	}

	#
	# Re-read the keyrec file, since it was rewritten by zonesigner.
	# Also, we'll get rid of any changes we've made to the keyrec.
	# (This *shouldn't* be a problem; further testing will tell...)
	#
	keyrec_discard();
	$ret = keyrec_read($krf);
	if($ret < 0)
	{
		if($ret == -3)
		{
			rolllog_log(LOG_ERR,$rname,"ZSK phase 2:  keyname collision in keyrec \"$krf\"; marking $rname as skipped");
		}
		else
		{
			rolllog_log(LOG_ERR,$rname,"ZSK phase 2:  unable to read keyrec \"$krf\"; marking $rname as skipped");
		}
		skipnow($rname);
	}

	#
	# Update the timestamp in the zone's keyrec.
	#
	keyrec_settime("zone",$rname);
	keyrec_write();

	#
	# Reload the zone.
	#
	$ret = loadzone($rndc,$rname,$rr{'zonename'},"ZSK phase 2");
	if($ret != 0)
	{
		rolllog_log(LOG_ERR,$rname,"ZSK phase 2:  unable to reload zone, rc - $ret");
	}

	#
	# Bump this rollrec's phase number and return the new phase.
	#
	zskphase($rname,$rrr,3);
	return(3);

}

#-----------------------------------------------------------------------------
# Routine:	zsk_phase4()
#
# Purpose:	Perform the phase 4 steps of the rollover.  These are:
#
#			- juggle the ZSKs in the zone's keyrec
#			- sign the zone with the KSK and new current ZSK
#			- reload the zone
#			- return the zone to the pre-rollover state
#
sub zsk_phase4
{
	my $rname = shift;		# Name of rollrec.
	my $rrr = shift;		# Reference to rollrec.

	my %rr = %$rrr;			# Rollrec hash.

	my $krf;			# Rollrec's keyrec name.
	my $krr;			# Keyrec reference.

	my $ret;			# Result from command executions.

	#
	# Get the rollrec's associated keyrec file and ensure that it
	# exists.
	#
	$krf = $rr{'keyrec'};
	if(!$krf  || ($krf eq ""))
	{
		rolllog_log(LOG_ERR,$rname,"ZSK phase 4:  no keyrec for zone specified");
		return;
	}
	if(! -e $krf)
	{
		rolllog_log(LOG_ERR,$rname,"ZSK phase 4:  keyrec \"$krf\" for zone does not exist");
		return;
	}

	#
	# Get the keyrec.
	#
	rolllog_log(LOG_TMI,$rname,"keyrec file is $krf");
	$krr = opts_zonekr($krf,$rr{'zonename'});

	#
	# Adjust ZSKs in the zone's keyrec.
	#
	$ret = signer($rname,"ZSK phase 4a",$krr);
	if($ret)
	{
		rolllog_log(LOG_ERR,$rname,"ZSK phase 4:  unable to adjust ZSK keyrec");
	}

	#
	# Sign the zone with the Current ZSK.
	#
	$ret = signer($rname,"ZSK phase 4b",$krr);
	if($ret)
	{
		rolllog_log(LOG_ERR,$rname,"ZSK phase 4:  unable to sign zone with the Current ZSK");
	}

	#
	# Reload the zone.
	#
	$ret = loadzone($rndc,$rname,$rr{'zonename'},"ZSK phase 4");
	if($ret != 0)
	{
		rolllog_log(LOG_ERR,$rname,"ZSK phase 4:  unable to reload zone, rc - $ret");
	}

	#
	# Put ourselves back in the pre-roll state.
	#
	zskphase($rname,$rrr,0);

	#
	# Set a timestamp for the completion of the ZSK roll.
	#
	rollstamp($rname,'zsk');
	return(0);
}

###############################################################################

#-----------------------------------------------------------------------------
# Routine:	ksk_expired()
#
# Purpose:	This routine determines if the specified zone has an expired
#		KSK and returns a boolean indicating this.  The given KSK
#		type is checked for expiration.
#
#		The zone's keyrec file name is taken from the given rollrec
#		entry.  The keyrec file is read and the zone's entry found.
#		The key keyrec of the specified key type (currently, just
#		"kskcur") is pulled from the keyrec file.  Each key in the
#		named signing set will be checked.
#
#		Key expiration is determined by comparing the key keyrec's
#		gensecs field to the current time.  The key hasn't expired
#		if the current time is less than the gensecs; the key has
#		expired if the current time is greater than the gensecs.
#
sub ksk_expired
{
	my $rname = shift;			# Name of rollrec rec.
	my $rrr = shift;			# Reference to rollrec.
	my $keyset = shift;			# Key to check.

	my %rr;					# Rollrec hash.

	my $krname;				# Name of keyrec.
	my $krec;				# Keyrec reference.
	my %set;				# Keyrec hash.

	my $khr;				# Ref to key's hash.
	my %kh;					# Key's hash.

	my @signset;				# Key's signing set.

	my $chronostr;				# Text expiration time.
	my $cronus;				# Current time.
	my $expired = 0;			# Expired-zone flag.
	my $minlife = -1;			# Minimum KSK life.
	my $minhr;				# Ref to min-key's keyrec.
	my $rolltime;				# Time roll should occur.
	my $starter;				# Time 0 for calc'ing rolltime.
	my $waitsecs;				# Time to expiration.

	#
	# Get the rollrec's hash.
	#
	%rr = %$rrr;

	#
	# If this zone is in the middle of ZSK rollover, we'll stop
	# working on KSK rollover.
	#
	if($rr{'zskphase'} > 0)
	{
		my $pstr;				# Phase string.

		$pstr = ": " . rollmgr_get_phase('KSK', $rr{'kskphase'});
		$pstr = '' if($pstr eq ": ");

		rolllog_log(LOG_TMI,$rname,"in ZSK rollover (phase $rr{'zskphase'}$pstr); not attempting KSK rollover");
		return(0);
	}

	#
	# If this zone is in the middle of rollover processing, we'll
	# immediately assume the key has expired.
	#
	return(1) if($rr{'kskphase'} > 0);

	#
	# Get the rollin' key's keyrec for our zone.
	#
	$krname = $rr{'keyrec'};
	$krec = zonekeykr($rname,$rr{'zonename'},$krname,$keyset);
	if($krec == 0)
	{
		rolllog_log(LOG_ERR,$rname,"unable to find a KSK keyrec for \"$keyset\" in \"$krname\"");
		return(0);
	}
	%set   = %$krec;

	#
	# Make sure we've got an actual set keyrec and keys.
	#
	if($set{'keyrec_type'} ne 'set')
	{
		rolllog_log(LOG_ERR,$rname,"\"$keyset\"'s keyrec is not a set keyrec");
		return(0);
	}
	if(!defined($set{'keys'}) || ($set{'keys'} eq ""))
	{
		rolllog_log(LOG_ERR,$rname,"\"$krname\" has no keys; unable to check expiration");
		return(0);
	}

	#
	# Ensure that there's a signing set.
	#
	@signset = split / /, $set{'keys'};
	if(@signset == 0)
	{
		rolllog_log(LOG_ERR,$rname,"\"$krname\" has no keys; unable to check expiration");
		return(0);
	}

	#
	# Check each key in the signing set to find the one with the shortest
	# lifespan.  We'll calculate rollover times based on that.
	#
	foreach my $keyname (@signset)
	{
		my $keylife;			# Key's life value.

		#
		# Get the key's keyrec hash.
		#
		$khr = keyrec_fullrec($keyname);
		%kh = %$khr;

		#
		# Ensure that required keyrec field exists.
		#
		if(!defined($kh{"ksklife"}))
		{
			rolllog_log(LOG_ERR,$rname,"keyrec does not contain a ksklife record");
			return(0);
		}

		#
		# If this key's life is shorter than any we've seen, it
		# becomes the new minimum.  If this is the first key we're
		# looking at, we'll save it as the minimum.
		#
		$keylife = $kh{'ksklife'};
		if($minlife == -1)
		{
			$minlife = $keylife;
			$minhr	 = $khr;
		}
		else
		{
			if($keylife < $minlife)
			{
				$minlife = $keylife;
				$minhr	 = $khr;
			}
		}
	}

	#
	# Get the minimum key's keyrec hash.
	#
	%kh = %$minhr;

	#
	# Get the start time on which the expiration time is based.
	#
	if($krollmethod == $RM_ENDROLL)
	{
		#
		# Ensure that required rollrec field exists.
		#
		if(!defined($rr{'ksk_rollsecs'}))
		{
			rolllog_log(LOG_INFO,$rname,"creating new ksk_rollsecs record and forcing KSK rollover");
			rollstamp($rname,'ksk');
			return(1);
		}
		$starter = $rr{'ksk_rollsecs'};
	}
	elsif($krollmethod == $RM_KEYGEN)
	{
		#
		# Ensure that required keyrec field exists.
		#
		if(!defined($kh{'keyrec_gensecs'}))
		{
			rolllog_log(LOG_ERR,$rname,"keyrec does not contain a keyrec_gensecs record");
			return(0);
		}
		$starter = $kh{'keyrec_gensecs'};
	}
	elsif($krollmethod == $RM_STARTROLL)
	{
		rolllog_log(LOG_ERR,$rname,"RM_STARTROLL not yet implemented");
		return(0);
	}

	#
	# Don't roll immediately if the rollrec file was newly created.
	#
	if($starter == 0)
	{
		rollstamp($rname,'ksk');
		return(0);
	}

	#
	# Get the key's expiration time.
	#
	$rolltime = $starter + $minlife;

	#
	# Get the current time.
	#
	$cronus	 = time;

	#
	# Figure out the log message we should give.
	#
	$waitsecs = $rolltime - $cronus;
	if($waitsecs >= 0)
	{
		$chronostr = timetrans($waitsecs);
		rolllog_log(LOG_EXPIRE,$rname,"        expiration in $chronostr\n");
		display("expiration $rname 0 KSK $waitsecs");
	}
	else
	{
		$waitsecs = $cronus - $rolltime;
		$chronostr = timetrans($waitsecs);
		rolllog_log(LOG_EXPIRE,$rname,"        expired $chronostr ago\n");
		display("kskphase $rname 0");
	}

	#
	# The key has expired if the current time has passed the key's lifespan.
	# The key has not expired if the key's lifespan has yet to reach the
	# current time.
	#
	$expired = 1 if($cronus > $rolltime);

	#
	# Return the success/failure indication.
	#
	return($expired);
}

#-----------------------------------------------------------------------------
# Routine:	ksk_phaser()
#
# Purpose:	Move the specified zone's KSKs through the appropriate phases.
#
#		Phases:
#			1 - wait for cache data to expire
#			2 - generate a new (published) KSK
#			3 - wait for the old DNSKEY RRset to expire from caches
#			4 - roll the KSKs
#			5 - transfer new keyset to the parent
#			6 - wait for parent to publish the new DS record
#			7 - reload the zone
#
sub ksk_phaser
{
	my $rname = shift;		# Zone name.
	my $rrr = shift;		# Reference to rollrec.

	my %rr;				# Rollrec hash.
	my $phase;			# Zone's current rollover phase.

	#
	# Get this rollrec record's current phase.
	#
	%rr = %$rrr;
	$phase = $rr{'kskphase'};

	#
	# Work on this rollrec's phase.
	#
	$phase = kskphase($rname,$rrr,1)	if($phase == 0);
	$phase = ksk_phasewait($rname,$rrr,1)	if($phase == 1);
	$phase = ksk_phase2($rname,$rrr)	if($phase == 2);
	$phase = ksk_phasewait($rname,$rrr,3)	if($phase == 3);
	$phase = ksk_phase4($rname,$rrr)	if($phase == 4);
	$phase = ksk_phase5($rname,$rrr)	if($phase == 5);
	$phase = ksk_phase6($rname,$rrr)	if($phase == 6);
	$phase = ksk_phase7($rname,$rrr)	if($phase == 7);

}

#-----------------------------------------------------------------------------
# Routine:	ksk_phasewait()
#
# Purpose:	Check if this zone's KSK rollover-wait phase is over.
#		The zone's KSK phase number -- current or new -- is returned.
#
sub ksk_phasewait
{
	my $rname = shift;			# Name of rollrec.
	my $rrr	  = shift;			# Reference to rollrec.
	my $phase = shift;			# Rollover phase.

	my %rr;					# Rollrec hash.

	#
	# Get the rollrec.
	#
	$rrr = rollrec_fullrec($rname);
	%rr = %$rrr;

	#
	# Check if we can go to the next rollover phase.  If not, we'll
	# go to the next rollrec entry and return to this later.
	#
	return($phase) if(!ttlexpire($rname,$rrr,$phase,'KSK'));
	return($phase) if((boolconvert($rrr->{'istrustanchor'}) == 1) &&
			  !holddownexpire($rname,$rrr,$phase));

	#
	# Bump this rollrec's KSK phase number and return the new phase.
	#
	$phase++;
	kskphase($rname,$rrr,$phase);
	return($phase);
}

#-----------------------------------------------------------------------------
# Routine:	ksk_phase2()
#
# Purpose:	Perform the phase 2 steps of the KSK rollover.  These are:
#			- generate a new KSK to be the Published KSK
#			- add the new Published KSK to the zone file
#			- re-sign the zone file with the Current KSK, the (new)
#			  Published KSK, and the Current ZSK
#			- reload the zone file
#		The first three steps are handled by zonesigner.
#
sub ksk_phase2
{
	my $rname = shift;		# Name of rollrec.
	my $rrr = shift;		# Reference to rollrec.

	my %rr = %$rrr;			# Rollrec hash.

	my $krf;			# Rollrec's keyrec name.
	my $krr;			# Keyrec reference.

	my $ret;			# Result from command executions.

	#
	# Get the rollrec's associated keyrec file and ensure that it exists.
	#
	$krf = $rr{'keyrec'};
	if(!$krf || ($krf eq ""))
	{
		rolllog_log(LOG_ERR,$rname,"KSK phase 2:  no keyrec for zone specified");
		return;
	}
	if(! -e $krf)
	{
		rolllog_log(LOG_ERR,$rname,"KSK phase 2:  keyrec \"$krf\" for zone does not exist");
		return;
	}

	#
	# Get the keyrec.
	#
	$krr = opts_zonekr($krf,$rr{'zonename'});

	#
	# Sign the zone with a new Published KSK.
	#
	$ret = signer($rname,"KSK phase 2",$krr);
	if($ret)
	{
		rolllog_log(LOG_ERR,$rname,"KSK phase 2:  unable to sign zone with the Published KSK");
	}

	#
	# Reload the zone.
	#
	$ret = loadzone($rndc,$rname,$rr{'zonename'},"KSK phase 2");
	if($ret != 0)
	{
		rolllog_log(LOG_ERR,$rname,"KSK phase 2:  unable to reload zone, rc - $ret");
	}

	#
	# On to the phase 3.
	#
	kskphase($rname,$rrr,3);
	return(3);
}

#-----------------------------------------------------------------------------
# Routine:	ksk_phase4()
#
# Purpose:	Perform the phase 4 steps of the KSK rollover.  These are:
#			- delete the Current KSK from the zone file
#			- move the Published KSK to be the Current KSK
#			- sign the zone file with the (new) Current KSK
#		These steps are handled by zonesigner.
#
sub ksk_phase4
{
	my $rname = shift;		# Name of rollrec.
	my $rrr = shift;		# Reference to rollrec.

	my %rr = %$rrr;			# Rollrec hash.
	my $krf;			# Rollrec's keyrec name.
	my $krr;			# Keyrec reference.

	my $ret;			# Result from command executions.

	#
	# Get the rollrec's associated keyrec file and ensure that it exists.
	#
	$krf = $rr{'keyrec'};
	if(!$krf || ($krf eq ""))
	{
		rolllog_log(LOG_ERR,$rname,"KSK phase 4:  no keyrec for zone specified");
		return;
	}
	if(! -e $krf)
	{
		rolllog_log(LOG_ERR,$rname,"KSK phase 4:  keyrec \"$krf\" for zone does not exist");
		return;
	}

	#
	# Get the keyrec.
	#
	$krr = opts_zonekr($krf,$rr{'zonename'});

	#
	# Roll the Published KSK to the Current KSK.
	#
	$ret = signer($rname,"KSK phase 4",$krr);
	if($ret)
	{
		rolllog_log(LOG_ERR,$rname,"KSK phase 4:  unable to roll the Published KSK to the Current KSK");
	}

	#
	# Now to the phase 5.
	#
	kskphase($rname,$rrr,5);
	return(5);
}

#-----------------------------------------------------------------------------
# Routine:	ksk_phase5()
#
# Purpose:	Perform the phase 5 steps of the KSK rollover.  These are:
#			- notify the admin that the new keyset should be
#			  transferred to the parent zone
#
#		This is currently handled by telling the admin to transfer
#		the keyset.  It would be nice to have an automated method
#		of keyset transfer; one may be added in future.
#
#
sub ksk_phase5
{
	my $rname = shift;		# Name of rollrec.
	my $rrr = shift;		# Reference to rollrec.

	my $ret;			# Return code from mail
	my $auto = 0;			# Automatic-transfer flag.

	if($auto)
	{
		rolllog_log(LOG_ERR,$rname,"KSK phase 5:  automatic keyset transfer not yet supported");
		return;
	}
	else
	{
		my $subject;			# Subject for email to admin.
		my $msg;			# Message to admin.
		my $admin;			# Zone's administrator.

		$subject = "assistance needed with KSK rollover of zone $rname";
		$msg = "
The zone \"$rname\" is in the middle of KSK rollover.  In order for rollover
to continue, its keyset must be transferred to its parent.";

		#
		# If this zone has its own administrator listed, we won't use
		# the default.
		#
		if(exists($rrr->{'administrator'}))
		{
			$admin = $rrr->{'administrator'};
			$ret = dt_adminmail($subject,$msg,$admin);
		}
		else
		{
			$ret = dt_adminmail($subject,$msg);
		}

		if($ret == 1)
		{
			rolllog_log(LOG_INFO,$rname,"KSK phase 5:  admin notified to transfer keyset");
		}
		else
		{
			rolllog_log(LOG_INFO,$rname,"KSK phase 5:  admin must transfer keyset");
			rolllog_log(LOG_ERR,$rname,"KSK phase 5:  invalid admin; unable to notify about transferring keyset");
		}
	}

	#
	# Pressing on to phase 6.
	#
	kskphase($rname,$rrr,6);
	return(6);
}

#-----------------------------------------------------------------------------
# Routine:	ksk_phase6()
#
# Purpose:	Perform the phase 6 steps of the KSK rollover.  These are:
#			- wait for the parent to publish the DS record
#
#		This is currently handled by the admin telling us that the
#		DS record has been published.  It would be nice to have an
#		automated method of determining this; one may be added in
#		future.
#
sub ksk_phase6
{
	my $rname = shift;		# Name of rollrec.
	my $rrr = shift;		# Reference to rollrec.

	my $auto = 0;			# Automatic-transfer flag.

	if($auto)
	{
		rolllog_log(LOG_ERR,$rname,"KSK phase 6:  automatic DS-record determination not yet supported");
		return;
	}
	else
	{
		rolllog_log(LOG_INFO,$rname,"KSK phase 6:  waiting for parental publication of DS record");
	}

	return(6);
}

#-----------------------------------------------------------------------------
# Routine:	ksk_phase7()
#
# Purpose:	Perform the phase 7 steps of the KSK rollover.  These are:
#			- load the zone
#			- archive keys that need to be archived
#			- move to phase 0
#			- save a timestamp for rollover completion
#
#
sub ksk_phase7
{
	my $rname = shift;		# Name of rolling rollrec.
	my $rrr = shift;		# Reference to zone's rollrec record.

	my %rr = %$rrr;			# Rollrec hash.
	my $krf;			# Rollrec's keyrec name.
	my $zname;			# Name of rolling zone.
	my $keyarch_cmd;		# Keyarch command string.

	my $ret;			# Result from command executions.

	#
	# Reload the zone.
	#
	$ret = loadzone($rndc,$rname,$rr{'zonename'},"KSK phase 7");
	if($ret != 0)
	{
		rolllog_log(LOG_ERR,$rname,"KSK phase 7:  unable to reload zone, rc - $ret");
	}

	#
	# Reload the zone.
	#
	$krf = $rr{'keyrec'};

	#
	# Set up the keyarch command we'll be executing.
	#
	$zname = $rr{'zonename'};
	$keyarch_cmd = "$keyarch -dtconf $dtcf -zone $zname $krf -verbose";

	rolllog_log(LOG_TMI,$rname,"keyarch:  running <$keyarch_cmd>");
	$ret = runner($rname,"$keyarch_cmd",$krf,1,1);
	if($ret < 0)
	{
		rolllog_log(LOG_ERR,$rname,"KSK phase 7:  unable to archive KSK keys, rc - $ret");
	}
	else
	{
		rolllog_log(LOG_INFO,$rname,"KSK phase 7:  zone, key files archived");
	}

	#
	# Move the rollrec back to phase 0.
	#
	kskphase($rname,$rrr,0);

	#
	# Set a timestamp for the completion of the KSK roll.
	#
	rollstamp($rname,'ksk');

	return(0);
}

###############################################################################

#-----------------------------------------------------------------------------
# Routine:	maxttl()
#
# Purpose:	Calculate the zone's maximum TTL value, based on the largest
#		TTL in its zone file.
#
sub maxttl
{
	my $signdb = shift;		# Signed zone's db filename.

	my $rrsref;			# Reference to zone's resource records.
	my @rrs;			# Zone's resource records.
	my $numrrs;			# Number of resource records in zone.
	my $rrref;			# Reference to a resource record.
	my %rr;				# A resource record to examine.
	my $maxttl = -1;		# Zone's maximum time-to-live value.
	my $ttl;			# Time-to-live value from a record.

	#
	# Ensure the zone file exists.
	#
	if(! -e $signdb)
	{
		rolllog_log(LOG_ERR,$signdb,"zone file does not exist");
		return(-1);
	}

	#
	# Get the zone's resource record collection.
	#
	$rrsref = Net::DNS::ZoneFile::Fast::parse(file => $signdb);

	#
	# Get the number of resource records in the zone.
	#
	@rrs = @$rrsref;
	$numrrs = @rrs;

	#
	# Look at each resource record and save the largest value.
	#
	for(my $ind=0;$ind<$numrrs;$ind++)
	{
		$rrref = $rrs[$ind];
		%rr = %$rrref;

		$ttl = $rr{'ttl'};
		$maxttl = $ttl if($ttl > $maxttl);
	}

	#
	# Return the zone's maximum TTL value to our caller.
	#
	return($maxttl);
}

#-----------------------------------------------------------------------------
# Routine:	ttlexpire()
#
# Purpose:	Returns a boolean indicating if we can move to the next phase
#		of rollover.  This is calculated by adding twice the TTL
#		length to the time we entered this phase.  If this is greater
#		than the current time, then we must wait a bit longer.  If
#		this is less than the current time, then we can proceed to
#		the next rollover phase.
#
# Return Values:
#		0 - Zone's expiry date has not passed.
#		1 - Zone's expiry date has passed.
#
sub ttlexpire
{
	my $rname   = shift;			# Name of rollrec.
	my $rrr	    = shift;			# Reference to rollrec.
	my $phase   = shift;			# Zone's current phase.
	my $keytype = shift;			# Type of key.

	my $phasedesc = rollmgr_get_phase($keytype, $phase);

	my %rr;					# Rollrec hash.

	my $zonefile;				# Zone file.
	my $maxttl;				# Zone's maximum TTL value.
	my $phstart;				# Start of zone's phase.

	my $curtime;				# Current time string.
	my $curtempus;				# Current time in seconds.
	my $endtempus;				# End-date in seconds.

	my $timediff;				# Time until expiration.
	my $tdstr;				# String of timediff.

	#
	# Get a few fields from the rollrec.
	#
	%rr = %$rrr;
	$zonefile = $rr{'zonefile'};
	$phstart  = $rr{'phasestart'};

	#
	# Get the signed zonefile's maximum TTL and save it into the
	# rollrec.  We'll then double it as a safety margin.
	#
	$maxttl	= maxttl($zonefile);
	rollrec_setval($rname,"maxttl",$maxttl);
	$maxttl	*= 2;

	#
	# Get the current time in seconds.
	#
	$curtime = gmtime;
	$curtempus = str2time($curtime);

	#
	# Get the end-time (in seconds) and add the TTL.
	#
	$endtempus = str2time($phstart);
	$endtempus += $maxttl;

	#
	# Give any desired verbose output.
	#
	if($verbose)
	{
		my $endtime;				# End-date string.

		$endtime = ctime($endtempus);
		chomp $endtime;

		rolllog_log(LOG_TMI,$rname,"$keytype phase $phase rollover TTL check");
		rolllog_log(LOG_TMI,$rname,"$keytype phase $phase endtime\t$endtime");
		rolllog_log(LOG_TMI,$rname,"$keytype phase $phase curtime\t$curtime");
	}

	#
	# Return success if we've passed the zone's adjusted end-date.
	# Return failure (not expired) if the zone's adjusted end-date
	# is in the future.
	#
	return(1) if($curtempus >= $endtempus);

	$timediff = $endtempus - $curtempus;
	$tdstr = timetrans($timediff);

	$phasedesc = " ($phasedesc)";
	$phasedesc = '' if($phasedesc eq ' ()');

	rolllog_log(LOG_INFO,$rname,"$keytype phase $phase$phasedesc; cache expires in $tdstr");
	display("expiration $rname $phase $keytype $timediff");

	return(0)
}

#-----------------------------------------------------------------------------
# Routine:	holddownexpire()
#
# Purpose:	Returns a boolean indicating if we can move to the next phase
#		of rollover based on the hold-down timer of RFC5011,
#		which is 30 days long.
#
# Return Values:
#		0 - Zone's hold-down timer is still active.
#		1 - Zone's hold-down timer date/time has passed.
#
sub holddownexpire
{
	my $rname   = shift;			# Name of rollrec.
	my $rrr	    = shift;			# Reference to rollrec.
	my $phase   = shift;			# Zone's current phase.
	my $keytype = shift;			# Type of key.

	my $phasedesc = rollmgr_get_phase($keytype, $phase);

	my %rr;					# Rollrec hash.

	my $zonefile;				# Zone file.
	my $maxttl;				# Zone's maximum TTL value.
	my $phstart;				# Start of zone's phase.
	my $holddowntime;			# Hold-down time.

	my $curtime;				# Current time string.
	my $curtempus;				# Current time in seconds.
	my $endtempus;				# End-date in seconds.

	my $timediff;				# Time until expiration.
	my $tdstr;				# String of timediff.

	my $addholddown;

	#
	# This is only needed for phase 3 (currently, at least.)
	#
	return(1) if($phase != 3);

	#
	# Get a few fields from the rollrec.
	#
	%rr = %$rrr;
	$zonefile = $rr{'zonefile'};
	$phstart  = $rr{'phasestart'};

	#
	# By default, we use a hold-down time of 60 days which is twice what
	# is required for validators to use as a add-hold-time (RFC5011).
	# (Ideally this should be longer and can be set by the user if needed.)
	#
	$holddowntime =
	    Net::DNS::ZoneFile::Fast::ttl_fromtext($rr{'holddowntime'});

	#
	# Default to 60 days.
	# lsdnssec should change too if this default is changed.
	#
	$holddowntime ||= 2*30*24*60*60;

#	print "here: $rr{'holddowntime'} $holddowntime\n";
	
	#
	# Get the current time in seconds.
	#
	$curtime = gmtime;
	$curtempus = str2time($curtime);

	#
	# Get the end-time (in seconds) and add the hold-down.
	#
	$endtempus = str2time($phstart);
	$endtempus += $holddowntime;

	#
	# Give any desired verbose output.
	#
	if($verbose)
	{
		my $endtime;				# End-date string.

		$endtime = ctime($endtempus);
		chomp $endtime;

		rolllog_log(LOG_TMI,$rname,"$keytype phase $phase hold-down time check");
		rolllog_log(LOG_TMI,$rname,"$keytype phase $phase endtime\t$endtime");
		rolllog_log(LOG_TMI,$rname,"$keytype phase $phase curtime\t$curtime");
	}

	#
	# Return success if we've passed the zone's adjusted end-date.
	# Return failure (not expired) if the zone's adjusted end-date
	# is in the future.
	#
	return(1) if($curtempus >= $endtempus);

	$timediff = $endtempus - $curtempus;
	$tdstr = timetrans($timediff);

	$phasedesc = " ($phasedesc)";
	$phasedesc = '' if($phasedesc eq ' ()');

	rolllog_log(LOG_INFO,$rname,"$keytype phase $phase$phasedesc; hold-down timer expires in $tdstr");
	display("holddown $rname $phase $keytype $timediff");

	return(0)
}

#-----------------------------------------------------------------------------
# Routine:	rollstamp()
#
# Purpose:	This routine sets the timestamp records for a KSK or
#		ZSK roll in the rollrec file.
#
sub rollstamp
{
	my $rname  = shift;			# Rollrec name.
	my $prefix = shift;			# Key-type prefix.

	my $date;				# Date key.
	my $secs;				# Seconds key.

	my $timesecs;				# Current-time seconds count.
	my $timestr;				# Current-time string.

	#
	# Build the rollrec keys we'll be using.
	#
	$date = $prefix . "_rolldate";
	$secs = $prefix . "_rollsecs";

	#
	# Get the timestamps.
	#
	$timesecs = time();
	$timestr  = gmtime($timesecs);

	#
	# Set the rollrec records to now and write the file.
	#
	rollrec_setval($rname,$date,$timestr);
	rollrec_setval($rname,$secs,$timesecs);
	rollrec_write();
}

#-----------------------------------------------------------------------------
# Routine:	zskphase()
#
# Purpose:	Moves a rollrec into the next ZSK phase, setting both the
#		phase number and the phase start time.
#
sub zskphase
{
	my $rname = shift;				# Name of rollrec.
	my $rrr	  = shift;				# Rollrec reference.
	my $phase = shift;				# New phase.

	my $phasedesc = rollmgr_get_phase('ZSK', $phase); # human phase descr

	my %rr = %$rrr;					# Rollrec hash.

	my $krname;					# Name of key's rollrec.
	my $krec;					# Key's keyrec.

	my $setrec;					# Set's keyrec.
	my $setlist;					# Set's key list.

	my $exptime;					# Key's time to expiry.
	my $chronostr;					# Pretty rollover time.

	$phasedesc = " ($phasedesc)";
	$phasedesc = '' if($phasedesc eq ' ()');

	if($phase == 1)
	{
		rolllog_log(LOG_TMI,$rname,"starting ZSK rollover");
	}
	else
	{
		rolllog_log(LOG_TMI,$rname,"moving to ZSK phase $phase$phasedesc");
	}

	rolllog_log(LOG_PHASE,$rname,"ZSK phase $phase$phasedesc");

	$rrr->{'zskphase'} = $phase;
	rollrec_setval($rname,"zskphase",$phase);
	rollrec_settime($rname);
	rollrec_write();
	rollrec_close();
	rollrec_read($rollrecfile);

	display("zskphase $rname $phase");

	#
	# If we're at the start of a rollover, we'll log the expiration time.
	#
	return if($phase != 0);

	#
	# Get the rollin' key's keyrec for our zone.
	#
	$krname = $rr{'keyrec'};
	$setrec = zonekeykr($rname,$rr{'zonename'},$krname,"zskcur");
	if($setrec == 0)
	{
		rolllog_log(LOG_ERR,$rname,"unable to find a keyrec for the zskcur signing set in \"$krname\"");
		return(0);
	}

	#
	# Make sure we've got an actual set keyrec and keys.
	#
	if($setrec->{'keyrec_type'} ne 'set')
	{
		rolllog_log(LOG_ERR,$rname,"\"$krname\"'s keyrec is not a set keyrec; unable to move to ZSK phase $phase");
		return(0);
	}
	if(!defined($setrec->{'keys'}) || ($setrec->{'keys'} eq ""))
	{
		rolllog_log(LOG_ERR,$rname,"\"$krname\" has no keys; unable to move to ZSK phase $phase");
		return(0);
	}

	#
	# Find the key with the shortest lifetime.
	#
	$setlist = $setrec->{'keys'};
	foreach my $key (split / /, $setlist)
	{
		my $lifetime = keyrec_recval($key,'zsklife');
		if(($exptime == 0) || ($lifetime < $exptime))
		{
			$exptime = $lifetime;
		}
	}

	#
	# Tell the log when the zone will expire, based on the lifespan.
	#
	$chronostr = timetrans($exptime);
	rolllog_log(LOG_INFO,$rname,"    ZSK expiration in $chronostr\n");

	#
	# Reset the phasestart field.
	#
	rollrec_settime($rname,0);
	rollrec_write();
	rollrec_close();
	rollrec_read($rollrecfile);
}

#-----------------------------------------------------------------------------
# Routine:	kskphase()
#
# Purpose:	Moves a rollrec into the next phase of KSK rollover, setting
#		both the phase number and the phase start time.
#
sub kskphase
{
	my $rname = shift;				# Name of rollrec.
	my $rrr	  = shift;				# Rollrec reference.
	my $phase = shift;				# New phase.

	my $phasedesc = rollmgr_get_phase('KSK', $phase); # human phase descr

	my %rr = %$rrr;					# Rollrec hash.

	my $krname;					# Name of key's rollrec.
	my $krec;					# Key's keyrec.

	my $setrec;					# Set's keyrec.
	my $setlist;					# Set's key list.

	my $exptime;					# Key's time to expiry.
	my $chronostr;					# Pretty rollover time.

	$phasedesc = " ($phasedesc)";
	$phasedesc = '' if($phasedesc eq ' ()');

	if($phase == 1)
	{
		rolllog_log(LOG_TMI,$rname,"starting KSK rollover");
	}
	else
	{
		rolllog_log(LOG_TMI,$rname,"moving to KSK phase $phase$phasedesc");
	}

	rolllog_log(LOG_PHASE,$rname,"KSK phase $phase$phasedesc");

	rollrec_close();
	rollrec_read($rollrecfile);
	$rrr->{'kskphase'} = $phase;
	rollrec_setval($rname,"kskphase",$phase);
	rollrec_settime($rname);
	rollrec_write();
	rollrec_close();
	rollrec_read($rollrecfile);

	display("kskphase $rname $phase");

	#
	# If we're at the start of a rollover, we'll log the expiration time.
	#
	return if($phase != 0);

	#
	# Get the rollin' KSK's keyrec for our zone.
	#
	$krname = $rr{'keyrec'};
	$setrec = zonekeykr($rname,$rr{'zonename'},$krname,"kskcur");
	if($setrec == 0)
	{
		rolllog_log(LOG_ERR,$rname,"unable to find a keyrec for the kskcur signing set in \"$krname\"");
		return(0);
	}

	#
	# Make sure we've got an actual set keyrec and keys.
	#
	if($setrec->{'keyrec_type'} ne 'set')
	{
		rolllog_log(LOG_ERR,$rname,"\"$krname\"'s keyrec is not a set keyrec; unable to move to KSK phase $phase$phasedesc");
		return(0);
	}
	if(!defined($setrec->{'keys'}) || ($setrec->{'keys'} eq ""))
	{
		rolllog_log(LOG_ERR,$rname,"\"$krname\" has no keys; unable to move to KSK phase $phase$phasedesc");
		return(0);
	}

	#
	# Find the key with the shortest lifetime.
	#
	$setlist = $setrec->{'keys'};
	foreach my $key (split / /, $setlist)
	{
		my $lifetime = keyrec_recval($key,'ksklife');
		if(($exptime == 0) || ($lifetime < $exptime))
		{
			$exptime = $lifetime;
		}
	}

	#
	# Tell the log when the zone will expire, based on the lifespan.
	#
	$chronostr = timetrans($exptime);
	rolllog_log(LOG_INFO,$rname,"    KSK expiration in $chronostr\n");

	#
	# Reset the phasestart field.
	#
	rollrec_settime($rname,0);
	rollrec_write();
	rollrec_close();
	rollrec_read($rollrecfile);
}

#-----------------------------------------------------------------------------
# Routine:	signer()
#
# Purpose:	Signs a zone with a specified ZSK.
#
#		On success, the return value of the zone-signing command
#			is returned.
#		On failure, "" is returned.
#
sub signer
{
	my $rname  = shift;			# Name of rollrec.
	my $zsflag = shift;			# Flag for key generation.
	my $krr	   = shift;			# Reference to zone's keyrec.

	my $rrr;				# Reference to zone's rollrec.
	my $zsargs;				# Zonesigner args from rollrec.

	my $zonefile;				# Zone file from keyrec.
	my $zonesigned;				# Signed zone file from keyrec.
	my $cmdstr;				# Command to be executed.

	#
	# Convert the caller's version of $zsflag into what it actually
	# means for the zonesigner execution.
	#
	if($zsflag eq 'KSK phase 2')
	{
		$zsflag = '-newpubksk';
	}
	elsif($zsflag eq 'KSK phase 4')
	{
		$zsflag = '-rollksk';
	}
	elsif($zsflag eq 'ZSK phase 2')
	{
		$zsflag = '-usezskpub';
	}
	elsif($zsflag eq 'ZSK phase 4a')
	{
		$zsflag = '-rollzsk';
	}
	elsif($zsflag eq 'ZSK phase 4b')
	{
		$zsflag = '';
	}
	elsif($zsflag eq 'always-sign')
	{
		$zsflag = '-usezskpub';
	}

	#
	# Get the rollrec for this name and check if there are any
	# user-specified zonesigner arguments.
	#
	$rrr = rollrec_fullrec($rname);
	$zsargs = $rrr->{'zsargs'};

	$zsflag = "$zsflag $zsargs" if($zsargs ne '');

	#
	# If the -zone flag wasn't specified, we'll force it in here.
	#
	if($zsflag !~ /-zone/)
	{
		$zsflag .= " -zone $rrr->{'zonename'}";
	}

	#
	# If the -krf flag wasn't specified, we'll force it in here.
	#
	if($zsflag !~ /-krf/)
	{
		$zsflag .= " -krf $rrr->{'keyrec'}";
	}

	#
	# Dig a few data out of the zone's keyrec file.
	#
	$zonefile = getkrval($rname,$krr,"zonefile");
	return("") if($zonefile eq "");

	$zonesigned = getkrval($rname,$krr,"signedzone");
	return("") if($zonesigned eq "");

	#
	# Build the command to execute.
	#
	$cmdstr = "$zonesigner -dtconfig $dtcf $zsflag $zonefile $zonesigned";

	rolllog_log(LOG_INFO,$rname,"executing \"$cmdstr\"");

	#
	# Have zonesigner sign the zone for us.
	#
	$ret = runner($rname,$cmdstr,$rrr->{'keyrec'},1,0);
	$ret >>= 8;

	if($ret != 0)
	{
		skipnow($rname);
	}
	else
	{
		$rrr->{'signed'} = 1;
	}

	return($ret);
}

#-----------------------------------------------------------------------------
# Routine:	runner()
#
# Purpose:	This routine returns the specified key's keyrec from the
#
sub runner
{
	my $rname = shift;			# Name of rollrec rec.
	my $cmd = shift;			# Command to execute.
	my $krf = shift;			# Zone's keyrec file.
	my $errflag = shift;			# On-error flag.
	my $negerrflag = shift;			# Only-negative-error flag.

	my $ret;				# Command's return code.
	my $out = '';				# Command's output.

	#
	# Close the current keyrec file.
	#
	keyrec_close();

	#
	# Execute the specific command.
	#
	rolllog_log(LOG_TMI,$rname,"executing \"$cmd\"");

	#
	# Execute the given command.  We'll save the stdout and stderr
	# output in case it's needed later.
	#
	open(ZS,"$cmd 2>&1 |");
	while(<ZS>)
	{
		$out .= $_;
	}
	chomp $out;
	close(ZS);
	$ret = $? >> 8;;

	#
	# If the error flag is set and the command exited with an error,
	# we'll log the output.
	#
	if($errflag)
	{
		if((! $negerrflag && ($ret != 0)) ||
		   (  $negerrflag && ($ret <  0)))
		{

			rolllog_log(LOG_ERR,$rname,"execution error for command \"$cmd\"");
			rolllog_log(LOG_ERR,$rname,"error output - \"$out\"");
		}
	}

	#
	# Re-read current keyrec file.
	#
	keyrec_read($krf);

	return($ret);
}

#-----------------------------------------------------------------------------
# Routine:	zonekeykr()
#
# Purpose:	This routine returns the specified key's keyrec from the
#		specified zone from the specified keyrec file.
#		This routine is big on specified things.
#
sub zonekeykr
{
	my $rname = shift;			# Name of rollrec record.
	my $zname = shift;			# Name of zone.
	my $krname = shift;			# Name of keyrec.
	my $key = shift;			# Key to check.

	my $ret;				# Return code.
	my $krec;				# Keyrec reference.
	my %kh;					# Keyrec hash.

	#
	# Close the open keyrec file.
	#
	keyrec_close();

	#
	# Read the keyrec file.
	#
	$ret = keyrec_read($krname);
	if($ret < 0)
	{
		if($ret == -3)
		{
			rolllog_log(LOG_ERR,$rname,"keyname collision in keyrec \"$krname\"; marking $rname as skipped");
		}
		else
		{
			rolllog_log(LOG_ERR,$rname,"unable to read keyrec \"$krname\"; marking $rname as skipped");
		}
		skipnow($rname);
	}

	#
	# Get the zone's keyrec and complain if it doesn't exist.
	#
	$krec = keyrec_fullrec($zname);
	if(!defined($krec))
	{
		rolllog_log(LOG_ERR,$rname,"keyrec file \"$krname\" does not contain a keyrec for zone \"$zname\"");
		return(0);
	}
	%kh   = %$krec;

	#
	# Get the key's keyrec and complain if it doesn't exist.
	#
	$key = $kh{$key};
	$krec = keyrec_fullrec($key);
	if(!defined($krec))
	{
		rolllog_log(LOG_ERR,$rname,"keyrec file \"$krname\" does not contain a keyrec for key \"$key\"");
		return(0);
	}

	#
	# Return the keyrec reference.
	#
	return($krec);
}

#-----------------------------------------------------------------------------
# Routine:	getkrval()
#
# Purpose:	This routine returns the value of a specified field in a
#		keyrec.  Error checking is performed to ensure that the
#		field exists in the keyrec and that it doesn't have an
#		empty value.
#
sub getkrval
{
	my $rname = shift;				# Rollrec's name.
	my $krr	  = shift;				# Keyrec reference.
	my $field = shift;				# Keyrec's field.

	my %kh = %$krr;					# Keyrec hash.
	my $val;					# Field's value.

	#
	# Ensure that the requested field exists.
	#
	if(!defined($kh{$field}))
	{
		rolllog_log(LOG_ERR,$rname,"keyrec has no entry for \"$field\"");
		return("");
	}

	#
	# Get the field from the keyrec.
	#
	$val = $kh{$field};

	#
	# Give an error if the value is empty.
	#
	if($val eq "")
	{
		rolllog_log(LOG_ERR,$rname,"keyrec has an empty entry for \"$field\"");
	}

	#
	# Return the keyrec field.
	#
	return($val);
}

##############################################################################

#-----------------------------------------------------------------------------
# Routine:	optsandargs()
#
# Purpose:	Parse our options and arguments.
#
sub optsandargs
{
	my $argc = @ARGV;				# Number of arguments.

	#
	# Check our options.
	#
	opts_onerr(0);

	$singlerun  = $opts{$OPT_SINGLERUN};
	$foreground = $opts{$OPT_FOREGROUND};
	$alwayssign = $opts{$OPT_ALWAYSSIGN};
	$pidfile    = $opts{$OPT_PIDFILE};
	$verbose    = $opts{$OPT_VERBOSE};
	$logfile    = $opts{$OPT_LOGFILE}    || $dtconf{$DT_LOGFILE};
	$loglevel   = $opts{$OPT_LOGLEVEL}   || $dtconf{$DT_LOGLEVEL} || LOG_DEFAULT;
	$sleeptime  = $opts{$OPT_SLEEP}	     || $dtconf{$DT_SLEEP}    || $DEFAULT_NAP;
	$dtcf	    = $opts{$OPT_DTCONF}     || getconffile();
	$display    = $opts{$OPT_DISPLAY}    || 0;
	$username   = $opts{$OPT_USERNAME}   || $dtconf{$DT_USERNAME} || '';
	$xqtdir	    = $opts{$OPT_DIR}	     || ".";
	$zonesigner = $opts{$OPT_ZONESIGNER} || '';

	#
	# Determine whether or not we'll load zones.
	#
	$zoneload = dnssec_tools_default($DT_LOADZONE);
	$zoneload = $dtconf{$DT_LOADZONE} if(defined($dtconf{$DT_LOADZONE}));
	$zoneload = 0 if(defined($opts{$OPT_NORELOAD}));
	$zoneload = boolconvert($zoneload);

	#
	# Show the version number if requested
	#
	usage()   if(defined($opts{$OPT_HELP}));
	version() if(defined($opts{$OPT_VERSION}));

	#
	# Check for a rollrec file name.
	#
	$rollrecfile = $opts{$OPT_RRFILE} || rollrec_default();
	$curdir = getcwd();
	if($rollrecfile !~ /^\//)
	{
		$rollrecfile = "$curdir/$rollrecfile";
	}

	#
	# Validate and switch to the given username -- if we can.
	#
	if($username ne '')
	{
		my $uid;			# Uid we're switching to.
		my $ret;			# Return from setuid().

		#
		# If the username is really a uid, we'll convert it to a name.
		#
		if($username =~ /^[0-9]+$/)
		{
			$username = getpwuid($username);
		}

		#
		# Convert the name to a uid.
		#
		$uid = getpwnam($username);
		if($uid eq '')
		{
			print STDERR "rollerd:  unknown user \"$username\"\n";
			exit(1);
		}

		#
		# Change the uid of the process.
		#
		$! = '';
		$> = $uid;
#		POSIX::setuid($uid);
		$ret = $!;
		if($ret ne '')
		{
			print STDERR "rollerd:  unable to switch to user \"$username\" -- $ret\n";
			exit(1);
		}
	}

	#
	# Validate our execution directory.
	#
	if($xqtdir eq ".")
	{
		$xqtdir = `$PWD`;
		chomp($xqtdir);
	}
	if(!defined($xqtdir))
	{
		print STDERR "rollerd:  no execution directory defined\n";
		exit(1);
	}
	if(! -e $xqtdir)
	{
		print STDERR "rollerd:  execution directory \"$xqtdir\" does not exist\n";
		exit(1);
	}
	if(! -d $xqtdir)
	{
		print STDERR "rollerd:  execution directory \"$xqtdir\" is not a directory\n";
		exit(1);
	}

	#
	# If the user only wants the parameters, print 'em and exit.
	#
	if($opts{$OPT_PARAMS})
	{
		print "$ME parameters:\n";
		print "\trollrec file   \"$rollrecfile\"\n";
		print "\tdirectory      \"$xqtdir\"\n";
		print "\tconfig file    \"$dtconfig\"\n";
		print "\tlogfile        \"$logfile\"\n";
		print "\tloglevel       \"$loglevel\"\n";
		print "\tzone reload    \"$zoneload\"\n";
		print "\tsleeptime      \"$sleeptime\"\n";
		exit(0)
	}

	#
	# Whine and die if the rollrec file doesn't exist.
	#
	if(! -e $rollrecfile)
	{
		print STDERR "rollerd:  rollrec file \"$rollrecfile\" does not exist\n";
		exit(1);
	}

	#
	# Move into our execution directory.
	#
	chdir($xqtdir);

	#
	# Ensure a log file was given on the command line or in the config file.
	#
	if(!defined($logfile))
	{
		print STDERR "rollerd:  no logfile specified on command line or in dnssec-tools.conf\n";
		exit(1);
	}

	#
	# Ensure the log file's directory actually exists.
	#
	if($logfile =~ /\//)
	{
		my @logbits;			# Components of logfile's path.
		my $logdir;			# Logfile's directory.

		#
		# Get the log directory without the logfile.
		#
		@logbits = split /\//, $logfile;
		pop @logbits;
		$logdir = join '/', @logbits;
		$logdir = '/' if($logdir eq '');

		#
		# Check for the existence of the log directory.
		#
		if(! -e $logdir)
		{
			print STDERR "rollerd:  logfile's directory \"$logdir\" does not exist\n";
			exit(1);
		}
	}

	#
	# If a pid file was specified, we'll pass it to the rollmgr module.
	#
	if(defined($pidfile) && ($pidfile ne ''))
	{
		rollmgr_set_idfile($pidfile);
	}

	#
	# Set the logging level and file.
	#
	$loglevel_save = $loglevel;
	rolllog_level($loglevel,1);
	rolllog_file($logfile,1);

	#
	# Start up our display program if -display was given.
	#
	displayer($display);

}

#-----------------------------------------------------------------------------
# Routine:	getprogs()
#
# Purpose:	Get some program paths.
#
sub getprogs
{
	#
	# If we're running packed, we'll force the command paths to be taken
	# from the packed versions.
	#
	#	NOTE:  In this version of packed rollerd, we're assuming
	#	       that rollerd will not be interacting with named.
	#	       Consequently, we won't be using rndc.
	#
	if($packed)
	{
		$rndc 	    = '';
		$keyarch    = "$ENV{'PAR_TEMP'}/inc/keyarch";
		$rrchk	    = "$ENV{'PAR_TEMP'}/inc/rollchk";
		$zonesigner = "$ENV{'PAR_TEMP'}/inc/zonesigner";

		delete($opts{'rndc'});
		$opts{'keyarch'}     = "keyarch";
		$opts{'rollchk'}     = "rollchk";
		$opts{'zonesigner'}  = "zonesigner";
		$opts{'keygen'}	     = "dnssec-keygen";
		$opts{'zonesign'}    = "dnssec-signzone";
		$opts{'zonecheck'}   = "named-checkzone";

		return;
	}

	#
	# Get the paths to the external commands.  If they aren't defined,
	# use the default command names.
	#
	$keyarch = $dtconf{'keyarch'}	  || dnssec_tools_default("keyarch");
	$rndc 	 = $dtconf{'rndc'}	  || dnssec_tools_default("rndc");
	$rrchk	 = $dtconf{'rollrec_chk'} || dnssec_tools_default("rollrec_check");
}

#-----------------------------------------------------------------------------
# Routine:	bootmsg()
#
# Purpose:	Write a start-up message to the log.
#
sub bootmsg
{
	my $bootflag = shift;				# Boot flag.

	if($bootflag)
	{
		rolllog_log(LOG_ALWAYS,"","$ME starting " . ("-" x 40));
	}
	else
	{
		rolllog_log(LOG_ALWAYS,"","$ME changing logfiles " . ("-" x 31));
	}

	rolllog_log(LOG_ALWAYS,"","$ME parameters:");
	rolllog_log(LOG_ALWAYS,"","		rollrec file	\"$rollrecfile\"");
	rolllog_log(LOG_ALWAYS,"","		directory	\"$xqtdir\"");
	rolllog_log(LOG_ALWAYS,"","		config file	\"$dtconfig\"");
	rolllog_log(LOG_ALWAYS,"","		logfile		\"$logfile\"");
	rolllog_log(LOG_ALWAYS,"","		loglevel	\"$loglevel\"");
	rolllog_log(LOG_ALWAYS,"","		zone reload	\"$zoneload\"");
	rolllog_log(LOG_ALWAYS,"","		sleeptime	\"$sleeptime\"");

	if($username ne '')
	{
		rolllog_log(LOG_ALWAYS,"","		running as	\"$username\"");
	}

	rolllog_log(LOG_ALWAYS,""," ");
}

#-----------------------------------------------------------------------------
# Routine:	rrfchk()
#
# Purpose:	This routine performs initial checking of the rollrec file.
#		Several errors and problems are checked for in each rollrec
#		marked as a a roll rollrec.
#
#		Errors:
#			The following errors are checked:
#				- the zonefile exists
#				- the keyrec file exists
#
#			If any of these are violated, the rollrec's type will
#			be changed to a skip rollrec.  This prevents lots of
#			unnecessary repeated log messages of an invalid rollrec.
#
#		Problems:
#			The following problems are checked:
#				- no zonename field exists
#
#			If any of these problems are found, they will be fixed.
#			
#
sub rrfchk
{
	my $rrf	 = shift;				# Rollrec file.
	my $modified = 0;				# Modified flag.

	#
	# Return failure if the rollrec file is bad.
	# 
	if(!rrfokay($rrf,""))
	{
		return(0);
	}

	#
	# Get the current contents of the rollrec file.
	#
	rollrec_lock();
	rollrec_read($rollrecfile);

	#
	# For each roll rollrec, check if its zonefile and keyrec file exist.
	# If not, we'll change it to being a skip rollrec.
	#
	foreach my $rname (rollrec_names())
	{
		my $rrr;		# Reference to rollrec.
		my %rr;			# Rollrec hash.
		my $phase;		# Rollrec's phase.

		my $errs = 0;		# Missing file errors.
		my $prefix;		# Rollrec's directory field.
		my $keyrec;		# Keyrec's filename.
		my $zonefile;		# Zone's filename.

		#
		# Get the rollrec for this name.  If it doesn't have one,
		# whinge and continue to the next.
		#
		$rrr = rollrec_fullrec($rname);
		if(!defined($rrr))
		{
			rolllog_log(LOG_ERR,$rname,"no rollrec defined for zone");
			next;
		}
		%rr = %$rrr;

		#
		# Don't look at skip records.
		#
		next if($rr{'rollrec_type'} eq "skip");

		#
		# Check for a directory.  We'll use rollerd's execution
		# directory if one isn't defined.
		#
		$prefix = $xqtdir;
		$prefix = $rr{'directory'} if(defined($rr{'directory'}));

		#--------------------------------------------------
		# Errors...
		#

		#
		# Get our important files.
		#
		$zonefile = $rr{'zonefile'};
		$zonefile = "$prefix/$zonefile" if($zonefile !~ /^\//);
		$keyrec	  = $rr{'keyrec'};
		$keyrec	  = "$prefix/$keyrec" if($keyrec !~ /^\//);

		#
		# Set the error flag if either the zonefile or the keyrec
		# file don't exist.
		#
		if(! -e $zonefile)
		{
			rolllog_log(LOG_ERR,$rname,"zonefile \"$zonefile\" does not exist");
			$errs++;
		}
		if(! -e $keyrec)
		{
			rolllog_log(LOG_ERR,$rname,"keyrec \"$keyrec\" does not exist");
			$errs++;
		}

		#--------------------------------------------------
		# Problems...
		#

		#
		# Add a zonename field to the file and our rollrec hash
		# if it isn't already in the hash.
		#
		if(!defined($rr{'zonename'}))
		{
			rolllog_log(LOG_INFO,$rname,"adding missing zonename field ($rname) to rollrec");
			$rr{'zonename'} = $rname;
			rollrec_setval($rname,'zonename',$rname);
		}

		#
		# Get our important files.
		#
		$zonefile = $rr{'zonefile'};
		$zonefile = "$prefix/$zonefile" if($zonefile !~ /^\//);
		$keyrec	  = $rr{'keyrec'};
		$keyrec	  = "$prefix/$keyrec" if($keyrec !~ /^\//);

		#
		# Skip this record if the zonefile and keyrec file exist.
		#
		next if(!$errs);

		#
		# If one of the files doesn't exist, then change the rollrec
		# to a skip record.  There's no reason we should bang our
		# head against non-existent files.
		#
		rolllog_log(LOG_ERR,$rname,"changing roll record to a skip record");
		rollrec_rectype($rname,"skip");
		$modified++;
		display("badzone $rname 0");

	}

	#
	# Save the current rollrec file state.
	#
	rollrec_close();
	rollrec_unlock();

	#
	# Return success.
	# 
	return(1);
}

#-----------------------------------------------------------------------------
# Routine:	rrfokay()
#
# Purpose:	This routine checks to see if a rollrec file is okay.
#
#		Returns:
#			0 - file is in error
#			1 - file is okay
#
sub rrfokay
{
	my $rrf = shift;				# Rollrec file to check.
	my $mp  = shift;				# Message prefix.

	if(! -e $rrf)
	{
		rolllog_log(LOG_ERR,$mp,"rollrec file \"$rrf\" does not exist");
		return(0);
	}
	elsif(-z $rrf)
	{
		rolllog_log(LOG_ERR,$mp,"rollrec file \"$rrf\" is zero length");
		return(0);
	}
	return(1);
}

#-----------------------------------------------------------------------------
# Routine:	sleeper()
#
# Purpose:	Sleep for a specific amount of time.  This will take into
#		account interrupts we've taken from rollctl.
#		We may be overridden by a rollctl command.
#
sub sleeper
{
	my $nap;				# Time left to sleep.

	return if($sleep_override);

	rolllog_log(LOG_TMI,"","sleeping for $sleeptime seconds");

	$sleepcnt = 0;

	while($sleepcnt < $sleeptime)
	{
		$nap = $sleeptime - $sleepcnt;

		$sleepcnt += sleep($nap);
	}
}

#-----------------------------------------------------------------------------
# Routine:	sleeper_awake()
#
# Purpose:	This routine forces rollerd to run its queue.  It does this
#		by setting the elapsed-sleep-time equal to the time-to-sleep.
#
sub sleeper_awake
{
	$sleepcnt = $sleeptime;
}

#-----------------------------------------------------------------------------
# Routine:	sleeper_override()
#
# Purpose:	This routine forces rollerd to run its queue.  It does this
#		by setting the elapsed-sleep-time equal to the time-to-sleep.
#
sub sleeper_override
{
	$sleep_override = 1;
}

#-----------------------------------------------------------------------------
# Routine:	commander()
#
# Purpose:	Get any commands sent to rollerd's command socket.
#
sub commander
{
	my $cmd;					# Client's command.
	my $data;					# Command's data.

	rolllog_log(LOG_TMI,'<command>',"checking commands");

	#
	# Read and handle all the commands we've been sent.
	#
	while(42)
	{
		#
		# Get the command, return if there wasn't one.
		#
		($cmd,$data) = rollmgr_getcmd(5);
		return if(!defined($cmd));

		rolllog_log(LOG_TMI,'<command>',"cmd   - \"$cmd\"");
		rolllog_log(LOG_TMI,'<command>',"data  - \"$data\"") if($data ne "");

		if($cmd eq ROLLCMD_DISPLAY())
		{
			cmd_display($data);
		}
		elsif($cmd eq ROLLCMD_DSPUB())
		{
			cmd_dspub($data);
		}
		elsif($cmd eq ROLLCMD_DSPUBALL())
		{
			cmd_dspuball();
		}
		elsif($cmd eq ROLLCMD_LOGFILE())
		{
			cmd_logfile($data);
		}
		elsif($cmd eq ROLLCMD_LOGLEVEL())
		{
			cmd_loglevel($data);
		}
		elsif($cmd eq ROLLCMD_LOGMSG())
		{
			cmd_logmsg($data);
		}
		elsif($cmd eq ROLLCMD_ROLLALL())
		{
			cmd_rollallzsks();
		}
		elsif($cmd eq ROLLCMD_ROLLREC())
		{
			if(cmd_rollrec($data))
			{
				last;
			}
		}
		elsif($cmd eq ROLLCMD_ROLLKSK())
		{
			cmd_rollnow($data,'KSK');
		}
		elsif($cmd eq ROLLCMD_ROLLZSK())
		{
			cmd_rollnow($data,'ZSK');
		}
		elsif($cmd eq ROLLCMD_RUNQUEUE())
		{
			cmd_runqueue($data);
		}
		elsif($cmd eq ROLLCMD_SHUTDOWN())
		{
			cmd_shutdown($data);
		}
		elsif($cmd eq ROLLCMD_SKIPALL())
		{
			cmd_skipall();
		}
		elsif($cmd eq ROLLCMD_SKIPZONE())
		{
			cmd_skipzone($data);
		}
		elsif($cmd eq ROLLCMD_SLEEPTIME())
		{
			cmd_sleeptime($data);
		}
		elsif($cmd eq ROLLCMD_STATUS())
		{
			cmd_status($data);
		}
		elsif($cmd eq ROLLCMD_ZONELOG())
		{
			cmd_zonelog($data);
		}
		elsif($cmd eq ROLLCMD_ZONESTATUS())
		{
			cmd_zonestatus($data);
		}
		elsif($cmd eq ROLLCMD_ZSARGS())
		{
			cmd_zsargs($data);
		}
		else
		{
			rolllog_log(LOG_ERR,'<command>',"invalid command  - \"$cmd\"");
		}

		rollmgr_closechan();
	}

}

#-----------------------------------------------------------------------------
# Routine:	cmd_display()
#
# Purpose:	Set the logfile to the user's specified file.  Nothing is done
#		if the user requests the same log file as is currently in use.
#
sub cmd_display
{
	my $onflag = shift;				# Display-on flag.

	rolllog_log(LOG_TMI,'<command>',"display command received; status flag - \"$onflag\"");

	#
	# Do nothing if the we're already doing what the user wants.
	#
	if($display == $onflag)
	{
		if($display == 1)
		{
			rolllog_log(LOG_INFO,'<command>',"graphical display is already on");
		}
		else
		{
			rolllog_log(LOG_INFO,'<command>',"graphical display is already off");
		}
		rollmgr_sendresp(ROLLCMD_RC_DISPLAY,"display status already as requested");
		return;
	}

	#
	# Change the logfile and give an appropriate set of log messages.
	#
	if($onflag)
	{
		displayer(1);
		rolllog_log(LOG_INFO,'<command>',"rollerd display started");
		rollmgr_sendresp(ROLLCMD_RC_OKAY,"rollerd display started");
	}
	else
	{
		displayer(0);
		rolllog_log(LOG_INFO,'<command>',"rollerd display stopped");
		rollmgr_sendresp(ROLLCMD_RC_OKAY,"rollerd display stopped");
	}
}

#-----------------------------------------------------------------------------
# Routine:	cmd_dspub()
#
# Purpose:	Move a zone from KSK rollover phase 6 to phase 7.
#
sub cmd_dspub
{
	my $zone = shift;				# Command's data.

	my $rrr;					# Reference to rollrec.
	my $phase;					# Zone's phase.

	rolllog_log(LOG_TMI,'<command>',"dspub command received; zone - \"$zone\"");

	#
	# Get the zone's rollrec.
	#
	$rrr = rollrec_fullrec($zone);
	if(!defined($rrr))
	{
		rolllog_log(LOG_ERR,'<command>',"no rollrec defined for zone $zone");
		rollmgr_sendresp(ROLLCMD_RC_BADZONE,"$zone not in rollrec file $rollrecfile");
		return;
	}

	#
	# Ensure we're in the proper KSK-rollover phase to do this command.
	#
	$phase = rollrec_recval($zone,'kskphase');
	if($phase != 6)
	{
		rolllog_log(LOG_INFO,'<command>',"zone not in KSK-rollover phase 6");
		return;
	}

	#
	# Change the zone's rollover phase to phase 7 (the final phase) and
	# re-run the queue now.
	#
	kskphase($zone,$rrr,7);
	rollmgr_sendresp(ROLLCMD_RC_OKAY,"zone \"$zone\" now in KSK rollover phase 7");
	sleeper_override();
}

#-----------------------------------------------------------------------------
# Routine:	cmd_dspuball()
#
# Purpose:	Move all zones that are currently in KSK rollover phase 6
#		to phase 7.
#
sub cmd_dspuball
{
	my $rrr;					# Reference to rollrec.
	my $phase;					# Zone's phase.

	rolllog_log(LOG_TMI,'<command>',"dspuball command received");

	foreach my $zone (sort(rollrec_names()))
	{
		#
		# Ensure we're in the proper KSK-rollover phase.
		#
		$phase = rollrec_recval($zone,'kskphase');
		next if($phase != 6);

		#
		# Get the rollrec for this name.
		#
		$rrr = rollrec_fullrec($zone);
		if(!defined($rrr))
		{
			rollmgr_sendresp(ROLLCMD_RC_BADZONE,"$zone not in rollrec file $rollrecfile");
		}

		#
		# Change the zone's rollover phase to phase 7.
		#
		kskphase($zone,$rrr,7);
		rollmgr_sendresp(ROLLCMD_RC_OKAY,"zone \"$zone\" now in KSK rollover phase 7");
	}

	sleeper_override();
}

#-----------------------------------------------------------------------------
# Routine:	cmd_logfile()
#
# Purpose:	Set the logfile to the user's specified file.  Nothing is done
#		if the user requests the same log file as is currently in use.
#
sub cmd_logfile
{
	my $newlog = shift;				# New log file.
	my $oldlog;					# Old log file.

	rolllog_log(LOG_TMI,'<command>',"logfile command received; new log file - \"$newlog\"");

	#
	# Do nothing if the new logfile is the same as the current logfile.
	#
	$oldlog = rolllog_file();
	if($oldlog eq $newlog)
	{
		rolllog_log(LOG_INFO,'<command>',"new logfile ($newlog) same as the old logfile");
		return;
	}

	#
	# Change the logfile and give an appropriate set of log messages.
	#
	rolllog_log(LOG_INFO,'<command>',"logfile changed from $oldlog to $newlog");
	rolllog_log(LOG_INFO,'<command>',"closing logfile $oldlog");
	$oldlog = rolllog_file($newlog,0);
	if($oldlog ne "")
	{
		rolllog_log(LOG_INFO,'<command>',"logfile changed from $oldlog to $newlog");
		bootmsg(0);
		rollmgr_sendresp(ROLLCMD_RC_OKAY,"logfile changed to \"$newlog\"");
	}
	else
	{
		rolllog_log(LOG_ERR,'<command>',"unable to change logfile to $newlog");
		rollmgr_sendresp(ROLLCMD_RC_BADFILE,"unable to change logfile to \"$newlog\"");
	}
}

#-----------------------------------------------------------------------------
# Routine:	cmd_loglevel()
#
# Purpose:	Set the logging level to the user's specified level.
#
sub cmd_loglevel
{
	my $newlvl = shift;				# New level.
	my $oldlvl;					# Old level.

	my $oldstr;					# Old level's string.
	my $newstr;					# New level's string.

	$newstr = rolllog_str($newlvl);
	rolllog_log(LOG_TMI,'<command>',"loglevel command received; new logging level - \"$newstr\"");

	$oldlvl = rolllog_level($newlvl,0);
	if($oldlvl >= 0)
	{
		$oldstr = rolllog_str($oldlvl);

		rolllog_log(LOG_INFO,'<command>',"loglevel changed from $oldstr to $newstr");
		rollmgr_sendresp(ROLLCMD_RC_OKAY,"loglevel changed from \"$oldstr\" to \"$newstr\"");

		$loglevel	= $newlvl;
		$loglevel_save	= $newlvl;
	}
	else
	{
		rolllog_log(LOG_ERR,'<command>',"unable to change loglevel to $newlvl");
		rollmgr_sendresp(ROLLCMD_RC_BADLEVEL,"invalid loglevel \"$newlvl\"");
	}
}

#-----------------------------------------------------------------------------
# Routine:	cmd_logmsg()
#
# Purpose:	Write a log message to the log file.
#
#		The way we check for a valid log level is only good in a
#		single-threaded environment.
#
sub cmd_logmsg
{
	my $logstr = shift;			# Log level and message.

	my $loglvl;				# Logging level.
	my $logmsg;				# Log message.

	my $oldlvl;				# Real logging level.
	my $goodlvl;				# Real version of new level.

	rolllog_log(LOG_TMI,'<command>',"logmsg command received");

	#
	# Dig the log level and message out of our argument.
	#
	$logstr =~ /^\((\w+)\)(.*)$/;
	$loglvl = $1;
	$logmsg = $2;

	#
	# Check the validity of the caller's log level.  If it's invalid,
	# rolllog_level() will return a failure and we'll return.
	#
	$oldlvl = rolllog_level($loglvl,0);
	if($oldlvl < 0)
	{
		rolllog_log(LOG_INFO,'<command>',"invalid loglevel ($loglvl) specified for logmsg command");
		rollmgr_sendresp(ROLLCMD_RC_BADLEVEL,"invalid loglevel \"$loglvl\"");
		return;
	}

	#
	# Reset the logging level and write the caller's message.
	#
	$goodlvl = rolllog_level($oldlvl,0);
	rolllog_log($goodlvl,"<user msg>",$logmsg);
	rollmgr_sendresp(ROLLCMD_RC_OKAY,"message written to log");
}

#-----------------------------------------------------------------------------
# Routine:	cmd_rollallzsks()
#
# Purpose:	This command moves all the zones in the rollrec file into
#		immediate ZSK rollover.  rollnow() is called for each zone,
#		in order to start rollover.  We'll also keep track of the
#		zones we were and weren't able to put in rollover, and
#		report them to the caller.
#
sub cmd_rollallzsks
{
	my $good = "";					# Rolled zones.
	my $bad	 = "";					# Unrolled zones.

	my $cnt	 = 0;					# Total count.
	my $gcnt = 0;					# Rolled count.
	my $bcnt = 0;					# Unrolled count.

	rolllog_log(LOG_TMI,'<command>',"rollallzsks command received");

	#
	# Each zone in the rollrec file will be put in the rollover process,
	# starting after that initial wait period.  We'll keep track of the
	# zones that were rolled and those that weren't in order to provide
	# an appropriate response message.
	#
	foreach my $zone (rollrec_names())
	{
		$cnt++;

		#
		# If the rollover worked, increment the good count and add
		# the domain name to the list of good zones.  If it didn't
		# work, do the same for the bad count and bad-zone list.
		#
		if(rollnow($zone,'ZSK') == 1)
		{
			$gcnt++;
			$good .= "$zone ";
		}
		else
		{
			$bcnt++;
			$bad .= "$zone ";
		}
	}

	#
	# We don't need no steenkin' trailing whitespace.
	#
	chomp $good;
	chomp $bad;

	#
	# Send a response message to the caller.
	#
	if($gcnt == $cnt)
	{
		rollmgr_sendresp(ROLLCMD_RC_OKAY,$good);
	}
	else
	{
		my $resp;				# Response message.

		$resp = "zones not in rollrec file $rollrecfile:  $bad\n";

		#
		# If there were any zones that were put into rollover,
		# we'll add them to the message as well.
		#
		if($gcnt > 0)
		{
			$resp .= "zones now in rollover:  $good\n";
		}

		rollmgr_sendresp(ROLLCMD_RC_BADZONE,$resp);
	}
}

#-----------------------------------------------------------------------------
# Routine:	cmd_rollrec()
#
# Purpose:	This routine changes the rollrec file being used by rollerd.
#		If this command is successful, then the communications channel
#		will be closed.
#
sub cmd_rollrec
{
	my $rrf = shift;				# New rollrec file.

	rolllog_log(LOG_TMI,'<command>',"rollrec command received; rollrec file - \"$rrf\"");

	if(rrfokay($rrf,'<command>'))
	{
		rolllog_log(LOG_INFO,'<command>',"------------------------------------------------");
		rolllog_log(LOG_INFO,'<command>',"setting rollrec file from \"$rollrecfile\" to \"$rrf\"");
		$rollrecfile = $rrf;

		rollmgr_sendresp(ROLLCMD_RC_OKAY,"rollerd now using rollrec file $rrf");
		display("rollrec $rrf 0");

		#
		# Close the channel and return success.
		#
		rollmgr_closechan();
		return(1);
	}

	rolllog_log(LOG_ERR,'<command>',"invalid rollrec file \"$rrf\"");
	rollmgr_sendresp(ROLLCMD_RC_BADROLLREC,"invalid rollrec file \"$rrf\"");
	return(0);
}

#-----------------------------------------------------------------------------
# Routine:	cmd_rollnow()
#
# Purpose:	This command moves a zone into immediate KSK or ZSK rollover.
#		It calls rollnow() to move the zone into immediate rollover.
#
sub cmd_rollnow
{
	my $zone = shift;				# Command's data.
	my $rolltype = shift;				# Type of rollover.

	my $rtlc;					# LC rollover type.
	my $rollret;					# Retcode from rolling.
	my $rrr;					# Rollrec reference.
	my %rr;						# Rollrec hash.

	$rtlc = lc($rolltype);
	rolllog_log(LOG_TMI,'<command>',"roll" . $rtlc . " command received; zone - \"$zone\"");

	#
	# Get the zone's rollrec.
	#
	$rrr = rollrec_fullrec($zone);
	if(!defined($rrr))
	{
		rolllog_log(LOG_ERR,'<command>',"no rollrec defined for zone $zone");
		rollmgr_sendresp(ROLLCMD_RC_BADZONE,"$zone not in rollrec file $rollrecfile");
		return(0);
	}
	%rr = %$rrr;

	#
	# Don't proceed if this zone is in the middle of KSK rollover.
	#
	if($rr{'kskphase'} > 0)
	{
		rolllog_log(LOG_TMI,'<command>',"in KSK rollover (phase $rr{'kskphase'}); not attempting ZSK rollover");
		rollmgr_sendresp(ROLLCMD_RC_KSKROLL,"$zone is already engaged in a KSK rollover");
		return(0);
	}

	#
	# Don't proceed if this zone is in the middle of ZSK rollover.
	#
	if($rr{'zskphase'} > 0)
	{
		rolllog_log(LOG_TMI,'<command>',"in ZSK rollover (phase $rr{'zskphase'});\nnot attempting ZSK rollover");
		rollmgr_sendresp(ROLLCMD_RC_ZSKROLL,"$zone is already engaged in a ZSK rollover");
		return(0);
	}

	#
	# Do the rollover and send an appropriate response.
	#
	$rollret = rollnow($zone,$rolltype);
	if($rollret == 1)
	{
		rollmgr_sendresp(ROLLCMD_RC_OKAY,"$zone $rolltype rollover started");
	}
	elsif($rollret == 0)
	{
		rolllog_log(LOG_ERR,'<command>',"$zone not in rollrec file $rollrecfile");
		rollmgr_sendresp(ROLLCMD_RC_BADZONE,"$zone not in rollrec file $rollrecfile");
	}
	elsif($rollret == -1)
	{
		rolllog_log(LOG_ERR,'<command>',"$zone has bad values in rollrec file $rollrecfile");
		rollmgr_sendresp(ROLLCMD_RC_BADZONEDATA,"$zone has bad values in rollrec file $rollrecfile");
	}
}

#-----------------------------------------------------------------------------
# Routine:	cmd_rollzsk()
#
# Purpose:	This command moves a zone into immediate rollover.  It calls
#		rollnow() to move the zone into immediate ZSK rollover.
#
sub cmd_rollzsk
{
	my $zone = shift;				# Command's data.
	my $rollret;					# Retcode from rolling.

	my $rrr;					# Rollrec reference.
	my %rr;						# Rollrec hash.

	rolllog_log(LOG_TMI,'<command>',"rollzsk command received; zone - \"$zone\"");

	#
	# Get the zone's rollrec.
	#
	$rrr = rollrec_fullrec($zone);
	if(!defined($rrr))
	{
		rolllog_log(LOG_ERR,'<command>',"no rollrec defined for zone $zone");
		rollmgr_sendresp(ROLLCMD_RC_BADZONE,"$zone not in rollrec file $rollrecfile");
	}
	%rr = %$rrr;

	#
	# Don't proceed if this zone is in the middle of KSK rollover.
	#
	if($rr{'kskphase'} > 0)
	{
		rolllog_log(LOG_TMI,'<command>',"in KSK rollover (phase $rr{'kskphase'}); not attempting ZSK rollover");
		rollmgr_sendresp(ROLLCMD_RC_KSKROLL,"$zone is already engaged in a KSK rollover");
		return(0);
	}

	#
	# Don't proceed if this zone is in the middle of ZSK rollover.
	#
	if($rr{'zskphase'} > 0)
	{
		rolllog_log(LOG_TMI,'<command>',"in ZSK rollover (phase $rr{'zskphase'}); not attempting ZSK rollover");
		rollmgr_sendresp(ROLLCMD_RC_ZSKROLL,"$zone is already engaged in a ZSK rollover");
		return(0);
	}

	#
	# Do the ZSK rollover and send an appropriate response.
	#
	$rollret = rollnow($zone,'ZSK');
	if($rollret == 1)
	{
		rollmgr_sendresp(ROLLCMD_RC_OKAY,"$zone ZSK rollover started");
	}
	elsif($rollret == 0)
	{
		rolllog_log(LOG_ERR,'<command>',"$zone not in rollrec file $rollrecfile");
		rollmgr_sendresp(ROLLCMD_RC_BADZONE,"$zone not in rollrec file $rollrecfile");
	}
	elsif($rollret == -1)
	{
		rolllog_log(LOG_ERR,'<command>',"$zone has bad values in rollrec file $rollrecfile");
		rollmgr_sendresp(ROLLCMD_RC_BADZONEDATA,"$zone has bad values in rollrec file $rollrecfile");
	}
}

#-----------------------------------------------------------------------------
# Routine:	cmd_runqueue()
#
# Purpose:	This command forces rollerd to run its queue.  It does this
#		by setting the elapsed-sleep-time equal to the time-to-sleep.
#		Upon return, sleeper() will see that sleepers must awake, 
#		and rollerd will go run its rollrec queue.
#
sub cmd_runqueue
{
	rolllog_log(LOG_TMI,'<command>',"runqueue command received");

	rolllog_log(LOG_INFO,'<command>',"checking rollrec queue");
	rollmgr_sendresp(ROLLCMD_RC_OKAY,"rollerd checking rollrec queue");
	sleeper_awake();
}

#-----------------------------------------------------------------------------
# Routine:	cmd_shutdown()
#
# Purpose:	This command forces rollerd to shut down.
#
sub cmd_shutdown
{
	rolllog_log(LOG_TMI,'<command>',"shutdown command received");
	rollmgr_sendresp(ROLLCMD_RC_OKAY,"rollerd shutting down");

	halt_handler();
}

#-----------------------------------------------------------------------------
# Routine:	cmd_skipall()
#
# Purpose:	This command stops rollover for all the zones in the rollrec
#		file.  The zones' rollrec records are marked as being "skip"
#		records, which will cause rollerd to ignore them.  This change
#		is reflected in the rollrec file.  skipnow() is called for each
#		zone, in order to stop rollover.  We'll also keep track of the
#		zones we were and weren't able to stop and report them to the
#		caller.
#
sub cmd_skipall
{
	my $good = "";					# Skipped zones.
	my $bad	 = "";					# Unskipped zones.

	my $cnt	 = 0;					# Total count.
	my $gcnt = 0;					# Skipped count.
	my $bcnt = 0;					# Unskipped count.

	rolllog_log(LOG_TMI,'<command>',"skipall command received");

	#
	# Each zone in the rollrec file will be removed from the rollover
	# process.  We'll keep track of the zones that were skipped and those
	# that weren't in order to provide an appropriate response message.
	#
	foreach my $zone (rollrec_names())
	{
		$cnt++;

		#
		# If the skip worked, increment the good count and add
		# the domain name to the list of good zones.  If it didn't
		# work, do the same for the bad count and bad-zone list.
		#
		if(skipnow($zone) == 1)
		{
			$gcnt++;
			$good .= "$zone ";
		}
		else
		{
			$bcnt++;
			$bad .= "$zone ";
		}
	}

	#
	# We still don't need no steenkin' trailing whitespace.
	#
	chomp $good;
	chomp $bad;

	#
	# Send a response message to the caller.
	#
	if($gcnt == $cnt)
	{
		rollmgr_sendresp(ROLLCMD_RC_OKAY,$good);
	}
	else
	{
		my $resp;				# Response message.

		$resp = "zones not in rollrec file $rollrecfile:  $bad\n";

		#
		# If there were any zones that were removed from rollover,
		# we'll add them to the message as well.
		#
		if($gcnt > 0)
		{
			$resp .= "zones now skipped:  $good\n";
		}

		rollmgr_sendresp(ROLLCMD_RC_BADZONE,$resp);
	}
}

#-----------------------------------------------------------------------------
# Routine:	cmd_skipzone()
#
# Purpose:	This command removes a zone from rollover processing. 
#
sub cmd_skipzone
{
	my $zone = shift;				# Command's data.

	rolllog_log(LOG_TMI,'<command>',"skipzone command received; zone - \"$zone\"");

	if(skipnow($zone) == 1)
	{
		rollmgr_sendresp(ROLLCMD_RC_OKAY,"$zone rollover stopped");
	}
	else
	{
		rollmgr_sendresp(ROLLCMD_RC_BADZONE,"$zone not in rollrec file $rollrecfile");
	}
}

#-----------------------------------------------------------------------------
# Routine:	cmd_sleeptime()
#
# Purpose:	This command sets rollerd's time-to-sleep to the user's
#		specified value.  This must be above a "constant" minimum
#		sleep time in order to prevent malicious users from making
#		rollerd continually run its queue without any resting.
#
#		It might be good to also enforce a maximum sleep time.
#
sub cmd_sleeptime
{
	my $newnap = shift;				# New sleep time.

	rolllog_log(LOG_TMI,'<command>',"sleeptime command received; new sleep time - \"$newnap\"");

	if($newnap < $MIN_SLEEP)
	{
		rolllog_log(LOG_ERR,'<command>',"sleep-time must be >= $MIN_SLEEP");
		rollmgr_sendresp(ROLLCMD_RC_BADSLEEP,"invalid sleep-time \"$newnap\"");
	}
	else
	{
		rolllog_log(LOG_INFO,'<command>',"setting sleep-time to $newnap");
		$sleeptime = $newnap;
		$sleepcnt  = $newnap;

		rollmgr_sendresp(ROLLCMD_RC_OKAY,"sleep-time set to $newnap");
		display("sleeptime all $sleeptime");
	}
}

#-----------------------------------------------------------------------------
# Routine:	cmd_status()
#
# Purpose:	Give a caller some rollerd settings.
#
sub cmd_status
{
	my $data = shift;				# Command's data.

	my $lfile;					# Log file.
	my $lvl;					# Logging level.
	my $lvlstr;					# Logging level string.
	my $outbuf = "";				# Response buffer.

	#
	# Get the info to report.
	#
	$lfile	= rolllog_file();
	$lvl	= rolllog_level();
	$lvlstr	= rolllog_str($lvl);

	#
	# Build status report.
	#
	$outbuf  = "boot-time:          $boottime\n";
	$outbuf .= "directory:          $curdir\n";
	$outbuf .= "rollrec file:       $rollrecfile\n";
	$outbuf .= "config file:        $dtconfig\n";
	$outbuf .= "logfile:            $lfile\n";
	$outbuf .= "loglevel:           $lvl\n";
	$outbuf .= "zone reload:        $zoneload\n";
	$outbuf .= "sleeptime:          $sleeptime\n";

	if($username ne '')
	{
		$outbuf .= "running as:         $username\n";
	}

	#
	# Send the status report to the caller.
	#
	rolllog_log(LOG_TMI,'<command>',"status command received");
	rollmgr_sendresp(ROLLCMD_RC_OKAY,$outbuf);
}

#-----------------------------------------------------------------------------
# Routine:	cmd_zonelog()
#
# Purpose:	Set the logging level for a zone.
#
sub cmd_zonelog
{
	my $data = shift;				# Command's data.

	my $rrr;					# Reference to rollrec.
	my %rr;						# Rollrec hash.

	my $zone;					# User's zone.
	my $llev;					# User's logging level.
	my $llevstr;					# String of log level.

	rolllog_log(LOG_TMI,'<command>',"zonelog command received");

	#
	# Get the zone and logging level from the command data.
	#
	$data =~ /^(.*):(.*)$/;
	$zone = $1;
	$llev = $2;

	#
	# Convert the user's logging level to its numeric form.
	#
	$llev = rolllog_num($llev);

	#
	# Ensure that the logging level is valid.
	#
	if($llev == -1)
	{
		rollmgr_sendresp(ROLLCMD_RC_BADLEVEL,"invalid logging level \"$llev\"");
		rolllog_log(LOG_ALWAYS,'<command>',"invalid logging level \"$llev\" specified for zone \"$zone\"\n");
		return;
	}

	#
	# Read the rollrec file.  Complain and return if we couldn't.
	#
	rollrec_lock();
	if(rollrec_read($rollrecfile) <= 0)
	{
		rollrec_unlock();
		rollmgr_sendresp(ROLLCMD_RC_RRFOPEN,"unable to open rollrec file $rollrecfile");
		rolllog_log(LOG_ALWAYS,'<command>',"unable to open rollrec file $rollrecfile\n");
		return;
	}

	#
	# Get the specified zone's roll record.
	#
	$rrr = rollrec_fullrec($zone);
	if(!defined($rrr))
	{
		rollrec_unlock();
		rollmgr_sendresp(ROLLCMD_RC_BADZONE,"invalid zone \"$zone\" specified");
		rolllog_log(LOG_ALWAYS,'<command>',"invalid zone \"$zone\" specified for zonelog command\n");
		return;
	}
	%rr = %$rrr;

	#
	# Set the zone's logging level.
	#
	rollrec_setval($zone,"loglevel",$llev);

	#
	# Write and unlock the rollrec file.
	#
	rollrec_close();
	rollrec_unlock();

	#
	# Report the command and return.
	#
	$llevstr = rolllog_str($llev);
	rolllog_log(LOG_INFO,'<command>',"set the logging level for zone $zone to $llevstr");
	return(1);
}

#-----------------------------------------------------------------------------
# Routine:	cmd_zonestatus()
#
# Purpose:	Return zone status to the control program.
#
sub cmd_zonestatus
{
	my $data = shift;				# Command's data.

	my $cnt = 0;					# Zone count.
	my $outbuf = "";				# Zone status line.

	rolllog_log(LOG_TMI,'<command>',"zonestatus command received");

	rollrec_lock();

	#
	# Read the rollrec file.  If we couldn't, complain and return.
	#
	if(rollrec_read($rollrecfile) <= 0)
	{
		rollrec_unlock();
		rollmgr_sendresp(ROLLCMD_RC_RRFOPEN,"unable to open rollrec file $rollrecfile");
		rolllog_log(LOG_ALWAYS,'<command>',"unable to open rollrec file $rollrecfile\n");
		return;
	}

	rolllog_log(LOG_ALWAYS,'<command>',"zone status:");

	#
	# Add the status of each zone in the rollrec file to our output buffer.
	#
	foreach my $rname (rollrec_names())
	{
		my $rrr;		# Reference to rollrec.
		my %rr;			# Rollrec hash.

		my $phase;		# Rollrec's phase.
		my $rtype;		# Rollrec's record type.

		#
		# Get the rollrec for this name.
		#
		$rrr = rollrec_fullrec($rname);
		next if(!defined($rrr));
		%rr = %$rrr;

		#
		# Get the data we're interested in.
		#
		if($rr{'kskphase'} > 0)
		{
			my $pstr;			# Phase string.

			$phase = 'KSK ' . $rr{'kskphase'};
			$pstr = rollmgr_get_phase('KSK', $rr{'kskphase'});

			$phase = "$phase: $pstr" if($pstr ne '');
		}
		else
		{
			my $pstr;			# Phase string.

			$phase = 'ZSK ' . $rr{'zskphase'};
			$pstr = rollmgr_get_phase('ZSK', $rr{'zskphase'});

			$phase = "$phase: $pstr" if($pstr ne '');
		}

		$rtype = $rr{'rollrec_type'};
		$phase = '-' if($rtype eq 'skip');

		#
		# Add the data to the output buffer and bump our zone count.
		#
		$outbuf .= "$rname/$rr{'zonename'}\t$rtype\t$phase\n";
		rolllog_log(LOG_ALWAYS,'<command>',"\t$rname/$rr{'zonename'}\t$rtype\t$phase\n");
		$cnt++;
	}

	#
	# Send a response to the control program.
	#
	if($cnt == 0)
	{
		rollmgr_sendresp(ROLLCMD_RC_NOZONES,"no zones defined in $rollrecfile");
		rolllog_log(LOG_ALWAYS,'<command>',"no zones defined in $rollrecfile\n");
	}
	else
	{
		rollmgr_sendresp(ROLLCMD_RC_OKAY,$outbuf);
	}

	rollrec_unlock();
}

#-----------------------------------------------------------------------------
# Routine:	cmd_zsargs()
#
# Purpose:	Set zone-specific arguments.
#
sub cmd_zsargs
{
	my $data = shift;			# Command's data.

	my @args = ();				# Command's split args.
	my @zsargs = ();			# Zonesigner's args.
	my @zones = ();				# Zones to modify.
	my @badzones = ();			# Invalid zones.

	my $zsargstr = '';			# Final argument string.
	my $clear = 0;				# Flag for zapping argstr.

	rolllog_log(LOG_TMI,'<command>',"zsargs command received");

	#
	# Split the argument into its molecules.
	#
	@args = split /,/, $data;

	#
	# Divide up the arguments between zones and zonesigner arguments.
	# Zonesigner arguments have equal signs; zones don't.
	#
	foreach my $arg (@args)
	{
		if($arg =~ /\=/)
		{
			push @zsargs, $arg;
		}
		else
		{
			push @zones, $arg;
		}
	}

	#
	# Ensure we've got both zones and zonesigner arguments.
	#
	if(@zsargs == 0)
	{
		rollmgr_sendresp(ROLLCMD_RC_NOARGS,"no arguments given to zsargs command");
		rolllog_log(LOG_ALWAYS,'<command>',"no arguments given to zsargs command\n");
		return;
	}
	if(@zones == 0)
	{
		rollmgr_sendresp(ROLLCMD_RC_NOZONES,"no zones given to zsargs command");
		rolllog_log(LOG_ALWAYS,'<command>',"no zones given to zsargs command\n");
		return;
	}

	#
	# Put the arguments into the form zonesigner is expecting and join
	# up the bits into a single argument string.
	#
	for(my $ind=0; $ind < @zsargs; $ind++)
	{
		$zsargs[$ind] =~ s/^=/-/;
		$zsargs[$ind] =~ s/=/ /;
	}

	$zsargstr = join ' ', @zsargs;

	#
	# Set the "clear argument" flag if the fake "clear" option is given.
	#
	$clear = 1 if($zsargstr =~ /-clear/);

	#
	# Read the rollrec file.  If we couldn't read it, complain and return.
	#
	rollrec_lock();
	if(rollrec_read($rollrecfile) <= 0)
	{
		rollrec_unlock();
		rollmgr_sendresp(ROLLCMD_RC_RRFOPEN,"unable to open rollrec file $rollrecfile");
		rolllog_log(LOG_ALWAYS,'<command>',"unable to open rollrec file $rollrecfile\n");
		return;
	}

	#
	# Ensure the specified zones are in the rollrec file.
	# 
	foreach my $rname (@zones)
	{
		my $rrr;		# Reference to rollrec.

		$rrr = rollrec_fullrec($rname);
		if(!defined($rrr))
		{
			push @badzones, $rname;
		}
	}

	#
	# Return an error if any zones were specified that aren't in the
	# rollrec file,
	# 
	if(@badzones > 0)
	{
		rollrec_unlock();
		rollmgr_sendresp(ROLLCMD_RC_BADZONE,"non-existent zones specified - @badzones");
		rolllog_log(LOG_ALWAYS,'<command>',"non-existent zones specified - @badzones\n");
		return;
	}

	#
	# Set (or clear) the new zsargs field in the rollrec entries for the
	# given zones.
	#
	foreach my $zone (@zones)
	{
		if($clear)
		{
			rollrec_delfield($zone,"zsargs");
			rolllog_log(LOG_INFO,'<command>',"clearing zsargs from zone $zone to $zsargstr");
		}
		else
		{
			rollrec_setval($zone,"zsargs",$zsargstr);
			rolllog_log(LOG_INFO,'<command>',"setting zsargs for zone $zone to $zsargstr");
		}
	}

	#
	# Tidy up the rollrec file and tell the user we're done.
	#
	rollrec_write();
	rollrec_close();
	rollrec_unlock();
	rollmgr_sendresp(ROLLCMD_RC_OKAY,"zsargs command completed\n");
}

#-----------------------------------------------------------------------------
# Routine:	rollnow()
#
# Purpose:	This command moves a zone into immediate rollover for the.
#		specified key type.  It doesn't sit in the initial waiting
#		period, but starts right off in rollover phase 2.
#
sub rollnow
{
	my $zone = shift;				# Zone to roll.
	my $rolltype = shift;				# Type of roll to start.

	#
	# Re-read the rollrec file and change the record's type.  We'll
	# also move the zone to phase 2 of rollover.
	#
	rollrec_lock();
	if(rollrec_read($rollrecfile) > 0)
	{
		my $rrr;				# Reference to rollrec.
		my %rr;					# Rollrec hash.

		my $dir;				# Zone's directory.
		my $krf;				# Zone's keyrec.
		my $znf;				# Zone's zonefile.

		#
		# Get the rollrec for the zone.
		#
		$rrr = rollrec_fullrec($zone);
		if(!defined($rrr))
		{
			rolllog_log(LOG_ERR,'<command>',"no rollrec defined for zone $zone");
			rollrec_close();
			rollrec_unlock();
			return(0);
		}
		%rr = %$rrr;

		#
		# Do a few *very* simple validation checks.
		#
		$dir = '.';
		$krf = $rr{'keyrec'};
		$znf = $rr{'zonefile'};
		if(exists($rr{'directory'}))
		{
			$dir = $rr{'directory'};
			$krf = "$dir/$krf" if($krf !~ /^\//);
			$znf = "$dir/$znf" if($znf !~ /^\//);
		}
		if((! -e $dir) || (! -e $krf) || (! -e $znf))
		{
			rollrec_close();
			rollrec_unlock();
			return(-1);
		}

		#
		# A skip record is changed to a regular rollrec.
		#
		if($rr{'rollrec_type'} eq "skip")
		{
			rolllog_log(LOG_INFO,'<command>',"$zone skip rollrec changed to a roll rollrec");
			rollrec_rectype($zone,"roll");
			$rrr = rollrec_fullrec($zone);
		}

		#
		# Change the zone's phase to rollover phase 1 (starting).
		#
		# WJH: This used to be set to phase 2 to bypass
		# the initial rollover waiting period and get right to the
		# nitty gritty of doing a rollover.  But I changed it back
		# to phase one, which is especially important for frequent
		# or sudden rollovers.
		#
		if($rolltype eq 'KSK')
		{
			kskphase($zone,$rrr,1);
		}
		elsif($rolltype eq 'ZSK')
		{
			zskphase($zone,$rrr,1);
		}

		#
		# Write the rollrec file.
		#
		rollrec_write();
	}

	#
	# Unlock the rollrec file.
	#
	rollrec_close();
	rollrec_unlock();

	#
	# Set the sleep values such that the queue will be run.
	#
	sleeper_awake();
	rolllog_log(LOG_INFO,'<command>',"forcing a $rolltype rollover for zone $zone");
	display("startroll $zone 0");
	return(1);
}

#-----------------------------------------------------------------------------
# Routine:	skipnow()
#
# Purpose:	This command prevents a zone from rolling over.  It is marked
#		as a skip record in the rollrec file.
#
sub skipnow
{
	my $zone = shift;				# Command's data.
	my $rrr;					# Reference to rollrec.
	my %rr;						# Rollrec hash.

	#
	# Get the rollrec for the zone.
	#
	$rrr = rollrec_fullrec($zone);
	if(!defined($rrr))
	{
		rolllog_log(LOG_ERR,'<command>',"no rollrec defined for zone $zone");
		return(0);
	}
	%rr = %$rrr;

	#
	# Re-read the rollrec file and change the record's type.  We'll
	# also move the zone to phase 0 of both KSK and ZSK rollover.
	#
	rollrec_lock();
	if(rollrec_read($rollrecfile) > 0)
	{
		#
		# A roll record is changed to a skip rollrec and its
		# phases set to 0.
		#
		if($rr{'rollrec_type'} eq "roll")
		{
			rolllog_log(LOG_INFO,'<command>',"$zone roll rollrec changed to a skip rollrec");

			rollrec_rectype($zone,"skip");
			display("stoproll $zone 0");
		}

		#
		# Set the zone's KSK and ZSK rollover phases to 0.
		#
		rollrec_setval($zone,"kskphase",0);
		rollrec_setval($zone,"zskphase",0);

		#
		# Write the rollrec file.
		#
		rollrec_write();

	}

	#
	# Unlock the rollrec file.
	#
	rollrec_close();
	rollrec_unlock();

	#
	# Log the event and return success.
	#
	rolllog_log(LOG_INFO,'<command>',"forcing a skiproll for zone $zone");
	return(1);
}

#-----------------------------------------------------------------------------
# Routine:	controllers()
#
# Purpose:	Initialize handlers for our externally provided commands.
#
my $queued_int = 0;
my $queued_hup = 0;

sub controllers
{
	my $onflag = shift;				# Handler on/off flag.

	#
	# Set the signal handlers that will manage incoming commands.
	#
	if($onflag)
	{
		if($queued_int)
		{
			$queued_int = 0;
			halt_handler();
		}

		if($queued_hup)
		{
			$queued_hup = 0;
			intcmd_handler();
		}

		$SIG{'HUP'} = \&intcmd_handler;
		$SIG{'INT'} = \&halt_handler;
	}
	else
	{
		$SIG{'HUP'} = \&queue_hup_handler;
		$SIG{'INT'} = \&queue_int_handler;
	}
}

#-----------------------------------------------------------------------------
# Routine:	loadzone()
#
# Purpose:	Initiates zone-reload, but obeys the $zoneload flag.
#
sub loadzone
{
	my $rndc = shift;				# Zone-loading program.
	my $rname = shift;				# Rollrec name of zone.
	my $zonename = shift;				# Zone to reload.
	my $phase = shift;				# Zone's current phase.
	my $ret;					# Return code.

	#
	# If the user doesn't want to reload the zone, we'll pretend we have.
	#
	if(!$zoneload)
	{
		rolllog_log(LOG_INFO,$rname,"not reloading zone for $phase\n");
		return(0);
	}

	#
	# Reload the zone for real.
	#
	rolllog_log(LOG_INFO,$rname,"reloading zone for $phase\n");
	$ret = rollmgr_loadzone($rndc,$zonename);
	return($ret);
}


#-----------------------------------------------------------------------------
# Routine:	queue_int_handler()
#
# Purpose:	Remember that a sig INT was received for later processing.
#
sub queue_int_handler
{
	$queued_int = 1;
}

#-----------------------------------------------------------------------------
# Routine:	queue_hup_handler()
#
# Purpose:	Remember that a sig HUP was received for later processing.
#
sub queue_hup_handler
{
	$queued_hup = 1;
}

#-----------------------------------------------------------------------------
# Routine:	intcmd_handler()
#
# Purpose:	Handle an interrupt and get a command.
#
sub intcmd_handler
{
	rolllog_log(LOG_TMI,'<command>',"rollover manager:  got a command interrupt\n");

	controllers(0);
	commander();
	controllers(1);
}

#-----------------------------------------------------------------------------
# Routine:	halt_handler()
#
# Purpose:	Handle the "halt" command.
#
sub halt_handler
{
	display("halt woof 0");

	rolllog_log(LOG_ALWAYS,"","rollover manager shutting down...\n");
	rollrec_write(1);	# dump the current file with commands
	rollmgr_rmid();
	exit(0);
}

#-----------------------------------------------------------------------------
# Routine:	cleanup()
#
# Purpose:	Perform whatever clean-up is required.
#
sub cleanup
{
	rolllog_log(LOG_ALWAYS,"cleaning up...") if($loglevel == LOG_TMI);
	rollmgr_rmid();
	exit(0);
}

#-----------------------------------------------------------------------------
# Routine:	displayer()
#
# Purpose:	Turn on/off the graphical display, depending on the display
#		flag.
#
sub displayer
{
	#
	# Set the global display flag to an argument -- iff we got one.
	#
	if(@_ == 1)
	{
		$display = shift;
	}

	#
	# Turn on or off the graphical display, depending on the display flag.
	#
	if($display)
	{
		open(DISPLAY, "|blinkenlights $rollrecfile");
	}
	else
	{
		display("halt");
		close(DISPLAY);
	}
}

#-----------------------------------------------------------------------------
# Routine:	display()
#
# Purpose:	Send a message to the display program iff the display flag
#		is on.  If we couldn't send the message, then we'll turn
#		the flag off.
#
sub display
{
	my $dmsg = shift;				# Message to send.
	my $savedsel;					# Saved descriptor.
	my $ret;					# Retcode from print.

	return if(!$display);

	#
	# Force this message to be unbuffered.
	#
	$savedsel = select(DISPLAY);
	$| = 1;
	$ret = print DISPLAY "$dmsg\n";
	select($savedsel);

	if(!$ret)
	{
		rolllog_log(LOG_INFO,'<command>',"unable to send message to blinkenlights; turning off display");
		$display = 0;
	}
}

#----------------------------------------------------------------------
# Routine:	version()
#
# Purpose:	Print the version number(s) and exit.
#
sub version
{
	print STDERR "$VERS\n";
	print STDERR "$DTVERS\n";

	exit(1);
}

#-----------------------------------------------------------------------------
# Routine:	usage()
#
# Purpose:	Print a usage message and exit.
#
sub usage
{
	print STDERR "usage:  rollerd [options]\n";
	print STDERR "\toptions:\n";
	print STDERR "\t\t-rrfile <rollrec-file>\n";
	print STDERR "\t\t-directory <dir>\n";
	print STDERR "\t\t-logfile <logfile>\n";
	print STDERR "\t\t-loglevel <level>\n";
	print STDERR "\t\t-noreload\n";
	print STDERR "\t\t-pidfile <pidfile>\n";
	print STDERR "\t\t-sleep <sleeptime>\n";
	print STDERR "\t\t-dtconfig <dnssec-tools-config-file>\n";
	print STDERR "\t\t-zonesigner <full-path-to-zonesigner>\n";
	print STDERR "\t\t-display\n";
	print STDERR "\t\t-parameters\n";
	print STDERR "\t\t-singlerun\n";
	print STDERR "\t\t-foreground\n";
	print STDERR "\t\t-alwayssign\n";
	print STDERR "\t\t-username <username>\n";
	print STDERR "\t\t-verbose\n";
	print STDERR "\t\t-Version\n";
	print STDERR "\t\t-help\n";
	exit(0);
}

1;

##############################################################################
#

=pod

=head1 NAME

rollerd - DNSSEC-Tools daemon to manage DNSSEC key rollover

=head1 SYNOPSIS

  rollerd [-options] -rrfile <rollrec_file>

=head1 DESCRIPTION

The B<rollerd> daemon manages key rollover for zones.  B<rollerd> handles
both KSK and ZSK rollover, though only one rollover may take place at a time.
Initiation of KSK rollovers takes precedence over the initiation of ZSK
rollovers.  The Pre-Publish Method of key rollover is used for ZSK key
rollovers.  The Double Signature Method of key rollover is used for KSK
rollovers.  B<rollerd> maintains zone rollover state in files called
I<rollrec> files.  The administrator may control B<rollerd> with the
B<rollctl> command.  These are described in their own sections below.

=head2 ZSK Rollover Using the Pre-Publish Method

The Pre-Publish Method has four phases that are entered when it is time to
perform ZSK rollover:

    1. wait for old zone data to expire from caches
    2. sign the zone with the KSK and Published ZSK
    3. wait for old zone data to expire from caches
    4. adjust keys in keyrec and sign the zone with new Current ZSK

B<rollerd> uses the B<zonesigner> command during ZSK rollover phases 2 and 4.
B<zonesigner> will generate keys as required and sign the zone during these
two phases.

The Pre-Publish Method of key rollover is defined in the Step-by-Step DNS
Security Operator Guidance Document.  See that document for more detailed
information.

=head2 KSK Rollover Using the Double Signature Method

The Double Signature Method has seven phases that are entered when it is time
to perform KSK rollover:

    1. wait for old zone data to expire from caches
    2. generate a new (published) KSK
    3. wait for the old DNSKEY RRset to expire from caches
    4. roll the KSKs
    5. transfer new keyset to the parent
    6. wait for parent to publish the new DS record
    7. reload the zone

B<rollerd> uses the B<zonesigner> command during KSK rollover phases 2 and 4.
B<zonesigner> will generate keys as required and sign the zone during these
two phases.

Currently, step 6 is handled manually.  In step 5, B<rollerd> informs the
administrator via email that the zone's keyset must be transferred to its
parent in order for rollover to continue.  In step 6, after the keyset has
been transferred to the parent and the parent has published a new DS record,
the administrator uses B<rollctl> to inform B<rollerd> that the DS record has
been published and rollover may continue.

The Double Signature Method of key rollover is defined in the Step-by-Step
DNS Security Operator Guidance Document.  See that document for more detailed
information.

=head2 KSK Rollover Using the Double Signature Method and RFC5011

RFC5011 describes how remote-validating resolvers must track KSK changes
within a zone.  If configured for RFC5011 behavior, B<rollerd> and
B<zonesigner> add an extra-long period of time between the point a new KSK is
created and published and the point where the actual switch to using it takes
place.  RFC5011 specifies that remote validators should add a "hold-down
timer" to the rollover process, such that the new key is not added as a
trust-anchor until 30 days have past.  Thus, B<rollerd> will wait for 60 days
(by default) during phase 3 of the KSK rollover process if the "istrustanchor"
field of the I<rollrec> definition has been set to either 1 or "yes".  To wait
for a different length of time other than 60 days, use the B<holddowntime>
field.

At this time, the other conventions of RFC5011 are not being followed.
Specifically, it's not waiting for a while before removing the old key
and it's not adding the revoke bit to the old key after switching.

=head2 Zone Reloading

B<rollerd> has the opportunity to inform the DNS daemon to reload a zone in
KSK phase 2, KSK phase 7, ZSK phase 2, and ZSK phase 4.  This is the
B<rollerd>'s default behavior.  However, there are situations where this
shouldn't be done, such as for off-line signing.

The B<roll_loadzone> field of the DNSSEC-Tools configuration file is a boolean
field that overrides the default to force the zone-reload behavior either on
or off.  This field takes precedence over the default.

Similarly, the B<-noreload> option prevents B<rollerd> from requesting a zone
reload, and it takes precedence over the B<roll_loadzone> configuration field
and the default.

=head2 I<rollrec> Files

The zones to be managed by B<rollerd> are described in a I<rollrec>
file.  Generally speaking most people will want to use the B<rollinit>
command to create an initial I<rollrec> file instead of typing their
own from scratch.  See the INITIALIZATION AND USAGE section below and
the B<rollinit> manual page for details. Each zone's entry contains
data needed by B<rollerd> and some data useful to a user.  Below is a
sample I<rollrec> entry:

	roll "example.com"
		zonename        "example.com"
		zonefile        "example.com.signed"
		keyrec          "example.com.krf"
		directory	"dir-example.com"
		kskphase        "0"
		zskphase        "3"
		ksk_rollsecs    "1172614842"
		ksk_rolldate    "Tue Feb 27 22:20:42 2007"
		zsk_rollsecs    "1172615087"
		zsk_rolldate    "Tue Feb 27 22:24:47 2007"
		maxttl          "60"
		display         "1"
		phasestart      "Tue Feb 27 22:25:07 2007"
        	# optional records for RFC5011 rolling:
		istrustanchor   "no"
        	holddowntime    "60D"

The first line gives the I<rollrec> entry's name.  The name distinguishes it
from other I<rollrec> entries and must be unique.  This may be the zone's
name, but this is not a requirement.  The following lines give the zone's
name, the zone's signed zone file, I<keyrec> file, the current rollover
phases, the rollover timestamps, and other information.

If either of the I<zonefile> or I<keyrec> files do not exist, then a "roll"
I<rollrec> will be changed into a "skip" I<rollrec>.  That record will not be
processed.

A more detailed explanation may be found in I<rollrec(5)>.

=head2 Directories

B<rollerd>'s execution directory is either the directory in which it is
executed or the directory passed in the B<-directory> command-line option.
Any files used by B<rollerd> that were not specified with absolute paths use
this directory as their base.

A I<rollrec> file's I<directory> field informs B<rollerd> where the zone's
files may be found.  For that zone, B<rollerd> will move into that directory,
then return to its execution directory when it finishes rollover operations
for that zone.  If the I<directory> value is a relative path, it will be
appended to B<rollerd>'s execution directory.  If the I<directory> value is an
absolute path, it will be used as is.

=head2 Controlling B<rollerd> with B<rollctl>

The B<rollctl> command is used to control the behavior of B<rollerd>.  A
number of commands are available, such as starting or stopping rollover for a
selected zone or all zones, turning on or off a GUI rollover display, and
halting B<rollerd> execution.  The communications path between B<rollerd> and
B<rollctl> is operating system-dependent.  On Unix-like systems, it is a Unix
pipe that should B<only> be writable by the user which runs I<rollerd>.  A
more detailed explanation of B<rollctl> may be found in I<rollctl(8)>.

=head2 A Note About Files and Filenames

There are a number of files and filenames used by B<rollerd> and
B<zonesigner>.  The user must be aware of the files used by these programs,
where the files are located, and where the programs are executed.

By default, B<rollerd> will change directory to the DNSSEC-Tools directory,
though this may be changed by the B<-directory> option.  Any programs started
by B<rollerd>, most importantly B<zonesigner>, will run in this same
directory.  If files and directories referenced by these programs are named
with relative paths, those paths must be relative to this directory.

The I<rollrec> entry name is used as a key to the I<rollrec> file and to the
zone's I<keyrec> file.  This entry does not have to be the name of the
entry's domain, but it is a very good idea to make it so.  Whatever is used
for this entry name, the same name B<must> be used for the zone I<keyrec> in
that zone's I<keyrec> file.

It is probably easiest to store I<rollrec> files, I<keyrec> files, zone
files, and key files in a single directory.

=head1 INITIALIZATION AND USAGE

The following steps must be taken to initialize and use B<rollerd>.  This
assumes that zone files have been created, and that BIND and DNSSEC-Tools
have been installed.

=over 4

=item 0. sign zones

The zones to be managed by B<rollerd> must be signed.  Use B<zonesigner> to
create the signed zone files and the I<keyrec> files needed by B<rollerd>.
The I<rollrec> file created in the next step B<must> use the I<keyrec> file
names and the signed zone file names created here.

=item 1. create I<rollrec> file

Before B<rollerd> may be used, a I<rollrec> file must first be created.
While this file may be built by hand, the B<rollinit> command was
written specifically to build the file.

=item 2. select operational parameters

A number of B<rollerd>'s operational parameters are taken from the
DNSSEC-Tools configuration file.  However, these may be overridden
by command-line options.  See the OPTIONS section below for more details.
If non-standard parameters are desired to always be used, the appropriate
fields in the DNSSEC-Tools configuration file may be modified to use these
values.

=item 3. install the rollover configuration

The complete rollover configuration -- B<rollerd>, I<rollrec> file,
DNSSEC-Tools configuration file values, zone files -- should be installed.  
The appropriate places for these locations are both installation-dependent
and operating system-dependent.

=item 4. test the rollover configuration

The complete rollover configuration should be tested.  

Edit the zone files so that their zones have short TTL values.  A minute TTL
should be sufficient.  Test rollovers of this speed should B<only> be done
in a test environment without the real signed zone.

Run the following command:

    rollerd -rrfile test.rollrec -logfile - -loglevel info -sleep 60

This command assumes the test I<rollrec> file is B<test.rollrec>.  It writes
a fair amount of log messages to the terminal, and checks its queue every 60
seconds.  Follow the messages to ensure that the appropriate actions, as
required by the Pre-Publish Method, are taking place.

=item 5. set B<rollerd> to start at boot

Once the configuration is found to work, B<rollerd> should be set to start
at system boot.  The actual operations required for this step are operating
system-dependent.

=item 6. reboot and verify

The system should be rebooted and the B<rollerd> logfile checked to ensure
that B<rollerd> is operating properly.

=back

=head1 OPTIONS

There are a number of operational parameters that define how B<rollerd> works.
These parameters define things such as the I<rollrec> file, the logging level,
and the log file.  These parameters can be set in the DNSSEC-Tools
configuration file or given as options on the B<rollerd> command line.
The command line options override values in the configuration file.

The following options are recognized:

=over 4

=item B<-alwayssign>

Tells B<rollerd> to sign the zones that aren't in the middle of being
rolled.  This allows B<rollerd> to refresh signed zone signatures and
allows complete management of zone signing to be taken over by B<rollerd>.

The downside to using this option is that all the non-rolling zones will be
signed after every sleep, which may be expensive computationally.

Note:  The zone files are not updated or installed at this time.
Manual copying and installation is still needed.

=item B<-directory dir>

Sets the B<rollerd> execution directory.  This must be a valid directory.

=item B<-display>

Starts the B<blinkenlights> graphical display program to show the status of
zones managed by B<rollerd>.

=item B<-dtconfig config_file>

Name of an alternate DNSSEC-Tools configuration file to be processed.
If specified, this configuration file is used I<in place> of the normal
DNSSEC-Tools configuration file B<not> in addition to it.  Also, it will be
handled prior to I<keyrec> files, I<rollrec> files, and command-line options.

=item B<-foreground>

Run in the foreground and do not fork into a daemon.

=item B<-logfile log_file>

Sets the B<rollerd> log file to I<log_file>.
This must be a valid logging file, meaning that if I<log_file> already
exists, it must be a regular file.  The only exceptions to this are if
I<logfile> is B</dev/stdout>, B</dev/tty>, B<->.  Of these three, using a
I<log_file> of B<-> is preferable since Perl will properly convert the B<->
to the process' standard output.

=item B<-loglevel level>

Sets B<rollerd>'s logging level to I<level>.  B<rollmgr.pm(3)> contains a list
of the valid logging levels.

=item B<-noreload>

Prevents B<rollerd> from telling the DNS daemon to reload zones.

=item B<-parameters>

Prints a set of B<rollerd> parameters and then exits.  This shows the
parameters with which B<rollerd> will execute, but very little parameter
validation is performed.

=item B<-pidfile pid_file>

Stores the running process PID into I<pid_file>.  This defaults to
B</var/run/rollerd.pid> on most systems.

=item B<-rrfile rollrec_file>

Name of the I<rollrec> file to be processed.  This is the only required
"option".

=item B<-singlerun>

Processes all needed steps once and exits.  This is not the ideal way to run
B<rollerd>, but it is potentially useful for environments where keying
material is only available when specific hardware tokens have been made
available.

The timing between the steps will be potentially longer since the
time between B<rollerd> runs is dependent on when B<rollerd> is executed.
"cmd" lines must be added to the I<rollrec> file to do particular actions.

The following lines should serve as examples:

  cmd "rollzsk example.com"
  cmd "rollksk example.com"
  cmd "dspub example.com"   # (for when the parent publishes
			    # the new ksk)

The I<-singlerun> option implicitly implies I<-foreground> as well.

=item B<-sleep sleeptime>

Sets B<rollerd>'s sleep time to I<sleeptime>.  The sleep time is the amount
of time (in seconds) B<rollerd> waits between processing its I<rollrec>-based
queue.

=item B<-username username>

B<username> is the user for which the B<rollerd> daemon will be executed.
The B<rollerd> process' effective uid will be set to the uid corresponding
to B<username>.

If B<username> is a username, it must correspond to a valid uid; if it is
a uid, it must correspond to a valid username.

If B<rollerd> does not have the appropriate O/S magic (e.g., for Unix,
installed as I<setuid> program and owned by root) then it will only be able
to switch to those users to which the executing user has privilege to switch.
This restriction is dependent on the operating system and the manner by which
B<rollerd> is installed.

When using this option, the target user must have access to the various
directories, logs, and data files that B<rollerd> requires to execute.
Without this access, proper execution cannot occur.

=item B<-Version>

Displays the version information for B<rollerd> and the DNSSEC-Tools package.

=item B<-help>

Display a usage message.

=item B<-verbose>

Verbose output will be given.

=back

=head1 ASSUMPTIONS

B<rollerd> uses the B<rndc> command to communicate with the BIND
B<named> daemon.  Therefore, it assumes that appropriate measures have been
taken so that this communication is possible.

=head1 KNOWN PROBLEMS

The following problems (or potential problems) are known:

=over 4

=item -

Any process that can write to the rollover socket can send commands to
B<rollerd>.  This is probably not a Good Thing.

=back

=head1 POSSIBLE ENHANCEMENTS

The following potential enhancements may be made:

=over 4

=item -

It'd be good to base B<rollerd>'s sleep time on when the next operation must
take place, rather than a simple seconds count.

=back

=head1 COPYRIGHT

Copyright 2005-2010 SPARTA, Inc.  All rights reserved.
See the COPYING file included with the DNSSEC-Tools package for details.

=head1 AUTHOR

Wayne Morrison, tewok@users.sourceforge.net

=head1 SEE ALSO

B<blinkenlights(8)>,
B<named(8)>,
B<rndc(8)>,
B<rollchk(8)>,
B<rollctl(8)>,
B<rollinit(8)>,
B<zonesigner(8)>

B<Net::DNS::SEC::Tools::conf.pm(3)>,
B<Net::DNS::SEC::Tools::defaults.pm(3)>,
B<Net::DNS::SEC::Tools::keyrec.pm(3)>,
B<Net::DNS::SEC::Tools::rolllog.pm(3)>,
B<Net::DNS::SEC::Tools::rollmgr.pm(3)>,
B<Net::DNS::SEC::Tools::rollrec.pm(3)>

B<rollrec(5)>

=cut
