#!/usr/bin/perl
#
# Copyright 2005-2008 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.
#

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

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

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

my $ME		= "rollerd";

#
# Some path variables to be set from the config file.
#
my $rndc;
my $rrchk;
my $zonesigner;

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_LOGFILE	= "roll_logfile";
my $DT_LOGLEVEL	= "roll_loglevel";
my $DT_SLEEP	= "roll_sleeptime";

my $OPT_HELP	 = "help";
my $OPT_DIR	 = "directory";
my $OPT_DISPLAY	 = "display";
my $OPT_LOGFILE	 = "logfile";
my $OPT_LOGLEVEL = "loglevel";
my $OPT_PARAMS	 = "parameters";
my $OPT_RRFILE	 = "rrfile";
my $OPT_SLEEP	 = "sleep";
my $OPT_VERBOSE	 = "verbose";
my $OPT_VERSION	 = "Version";

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.
	"sleep=i",			# Sleep amount (in seconds.)
	"parameters",			# Display the parameters and exit.
	"help",				# Give a usage message and exit.
	"verbose",			# Verbose output.
	"Version",			# Display the version number.
);

#
# Flag values for the various options.  Variable/option connection should
# be obvious.
#
my $logfile;				# Log file.
my $loglevel;				# Logging level.
my $loglevel_save;			# Saved logging level.
my $sleeptime;				# Sleep interval in seconds.
my $sleep_override = 0;			# Sleep-override flag.
my $sleepcnt;				# Time we've slept so far.
my $verbose = 0;			# Verbose option.


my $display = 0;			# Do display processing.

my $boottime = gmtime();		# Timestamp of rollerd's start time.
my $version  = 0;			# Display the version number.

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

my $curdir;				# Directory.
my $keyarch;				# Key-archive program.
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 $errors = 0;			# Total error count.

	$| = 1;

	erraction(ERR_MSG);

	#
	# Check our options and arguments.
	#
	%dtconf = parseconfig();
	optsandargs();
	getprogs();

	#
	# Daemonize ourself.
	#
	exit(0) if(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();
	}

	#
	# Get the pathname for zonesigner.
	#
	if(($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.
		#
		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");
		}

	}

	#
	# 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 $key = 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)
	{
		rolllog_log(LOG_TMI,$rname,"in KSK rollover (phase $rr{'kskphase'}); 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,$krname,$key);
	if($krec == 0)
	{
		rolllog_log(LOG_ERR,$rname,"unable to find a keyrec for \"$key\" is \"$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,"\"$key\"'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;
			}
		}
	}

	#
	# 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,$rname);
	%krf = %$krr;

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

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

	#
	# Reload the zone.
	#
	$ret = rollmgr_loadzone($rndc,$rname);
	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 %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 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,$rname);
	%krf = %$krr;

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

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

	#
	# Reload the zone.
	#
	$ret = rollmgr_loadzone($rndc,$rname);
	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 $key = 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)
	{
		rolllog_log(LOG_TMI,$rname,"in ZSK rollover (phase $rr{'zskphase'}); 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,$krname,$key);
	if($krec == 0)
	{
		rolllog_log(LOG_ERR,$rname,"unable to find a keyrec for \"$key\" is \"$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,"\"$key\"'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'));

	#
	# 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 %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,"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,$rname);
	%krf = %$krr;

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

	#
	# Reload the zone.
	#
	$ret = rollmgr_loadzone($rndc,$rname);
	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 %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,"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,$rname);
	%krf = %$krr;

	#
	# Roll the Published KSK to the Current KSK.
	#
	$ret = signer($rname,"-rollksk",$krr);
	if($ret eq "")
	{
		rolllog_log(LOG_ERR,$rname,"KSK phase 4:  unable to sign zone with the Published ZSK");
	}

	#
	# 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:
#
#
sub ksk_phase7
{
	my $rname = shift;		# Name of rolling zone.
	my $rrr = shift;		# Reference to zone's rollrec record.

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

	my $ret;			# Result from command executions.

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

	#
	# Reload the zone.
	#
	$krf = $rr{'keyrec'};
#	$ret = system("$keyarch -verbose -zone $rname $krf");
	$ret = system("$keyarch -quiet -zone $rname $krf");
	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 %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);
	rolllog_log(LOG_INFO,$rname,"$keytype phase $phase; cache expires in $tdstr");
	display("expiration $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 %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.

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

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

	$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,$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 %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.

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

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

	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,$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");
		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");
		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 $rrr	   = shift;			# Reference to rollrec.

	my %rr;					# Rollrec hash.

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

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

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

	#
	# Have zonesigner sign the zone for us.
	#
	$cmdstr = "$zonesigner $zsflag $zonefile $zonesigned";
	rolllog_log(LOG_INFO,$rname,"executing \"$cmdstr\"");

	$ret = `$cmdstr`;

	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 rec.
	my $krname = shift;			# Name of keyrec.
	my $key = shift;			# Key to check.

	my $krec;				# Keyrec reference.
	my %kh;					# Keyrec hash.

	#
	# Get the keyrec file's name and then read the file.
	#
	keyrec_read($krname);

	#
	# Get the zone's keyrec and complain if it doesn't exist.
	#
	$krec = keyrec_fullrec($rname);
	if(!defined($krec))
	{
		rolllog_log(LOG_ERR,$rname,"keyrec file \"$krname\" does not contain a keyrec for zone \"$rname\"");
		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");
		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 $name = shift;				# Owner'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,$name,"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,$name,"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.
	#
	GetOptions(\%opts,@opts) || usage();
	opts_onerr(0);

	$version   = $opts{$OPT_VERSION};
	$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;

	$display = $opts{$OPT_DISPLAY}	  || 0;

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

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

	#
	# Validate our execution directory.
	#
	$xqtdir = $opts{$OPT_DIR} || getconfdir();
	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);
	}

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

	#
	# Complain and die if a log file wasn't 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);
	}

	#
	# If the log file contains any directories, complain and die if the
	# directory doesn't exist.
	#
	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 the user only wants the parameters, print 'em and exit.
	#
	if($opts{$OPT_PARAMS})
	{
		print "$ME parameters:\n";
		print "	rollrec file	\"$rollrecfile\"\n";
		print "	directory	\"$xqtdir\"\n";
		print "	logfile		\"$logfile\"\n";
		print "	loglevel	\"$loglevel\"\n";
		print "	sleeptime	\"$sleeptime\"\n";
		exit(0)
	}

	#
	# 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
{
	#
	# 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("bind_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,"","		logfile		\"$logfile\"");
	rolllog_log(LOG_ALWAYS,"","		loglevel	\"$loglevel\"");
	rolllog_log(LOG_ALWAYS,"","		sleeptime	\"$sleeptime\"");
	rolllog_log(LOG_ALWAYS,""," ");
}

#-----------------------------------------------------------------------------
# Routine:	rrfchk()
#
# Purpose:	This routine performs initial checking of the rollrec file.
#		It checks each roll rollrec to ensure its zonefile and keyrec
#		file exist.  If one or both don't exist, the rollrec's type
#		will be changed into a skip rollrec.  This prevents lots of
#		unnecessary repeated log messages of an invalid rollrec.
#
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'}));

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

		#
		# 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);
		}
		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\"");

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

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

#-----------------------------------------------------------------------------
# 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 rollever type.
	my $rollret;					# Retcode from rolling.
	my $rrr;					# Rollrec reference.
	my %rr;						# Rollrec hash.

	$rtlc = lower($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");
	}
	%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 .= "logfile:            $lfile\n";
	$outbuf .= "loglevel:           $lvl\n";
	$outbuf .= "sleeptime:          $sleeptime\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)
		{
			$phase = 'KSK ' . $rr{'kskphase'};
		}
		else
		{
			$phase = 'ZSK ' . $rr{'zskphase'};
		}
		$rtype = $rr{'rollrec_type'};

		$phase = '-' if($rtype eq 'skip');

		#
		# Add the data to the output buffer and bump our zone count.
		#
		$outbuf .= "$rname\t$rtype\t$phase\n";
		rolllog_log(LOG_ALWAYS,"<command>","\t$rname\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:	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 2.  This bypasses
		# the initial rollover waiting period and gets right to the
		# nitty gritty of doing a rollover.
		#
		if($rolltype eq 'KSK')
		{
			kskphase($zone,$rrr,2);
		}
		elsif($rolltype eq 'ZSK')
		{
			zskphase($zone,$rrr,2);
		}

		#
		# 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 rollover.
	#
	rollrec_lock();
	if(rollrec_read($rollrecfile) > 0)
	{
		#
		# A roll record is changed to a skip rollrec and its
		# phase 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.
#
sub controllers
{
	my $onflag = shift;				# Handler on/off flag.

	#
	# Set the signal handlers that will manage incoming commands.
	#
	if($onflag)
	{
		$SIG{'HUP'} = \&intcmd_handler;
		$SIG{'INT'} = \&halt_handler;
	}
	else
	{
		$SIG{'HUP'} = 'IGNORE';
		$SIG{'INT'} = 'IGNORE';
	}
}

#-----------------------------------------------------------------------------
# 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");
	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-sleep <sleeptime>\n";
	print STDERR "\t\t-display\n";
	print STDERR "\t\t-parameters\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 ZSK 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, steps 5 and 6 are handled manually.  In step 5, B<rollerd> informs
the administrator that the zone's keyset must be transferred to its parent
in order for rollover to continue.  In step 6, after 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 I<rollrec> Files

The zones to be managed by B<rollerd> are described in a I<rollrec> file.
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"
		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"

The first line gives the I<rollrec> entry's name.  The following lines give
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 I<-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 root.
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 I<-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 I<-rrfile rollrec_file>

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

=item I<-directory dir>

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

=item I<-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 I<-loglevel level>

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

=item I<-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 I<-parameters>

Prints a set of B<rollerd> parameters and then exits.

=item I<-display>

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

=item B<-Version>

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

=item -help

Display a usage message.

=item -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.

=item -

Very little testing was done with zone files and key files not in the process'
directory.

=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-2008 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
