#!/usr/bin/perl
	eval "exec perl -S $0 $*"
		if $running_under_some_shell;

# $Id: mailpatch.SH,v 3.0.1.4 1995/03/21 12:55:16 ram Exp $
#
#  Copyright (c) 1990-1993, Raphael Manfredi
#  
#  You may redistribute only under the terms of the Artistic License,
#  as specified in the README file that comes with the distribution.
#  You may reuse parts of this distribution only within the terms of
#  that same Artistic License; a copy of which may be found at the root
#  of the source tree for mailagent 3.0.
#
# $Log: mailpatch.SH,v $
# Revision 3.0.1.4  1995/03/21  12:55:16  ram
# patch35: added pl/cdir.pl to the list of appended files
#
# Revision 3.0.1.3  1994/10/10  10:22:57  ram
# patch19: added various escapes in strings for perl5 support
#
# Revision 3.0.1.2  1994/10/04  17:38:37  ram
# patch17: suppressed usage of Bcc in messages: user is on the command line
# patch17: no longer hardwires mailpatch name but uses prog_name variable
# patch17: now uses the email config parameter to send messages to user
# patch17: extended logging to get better error/failure tracking
#
# Revision 3.0.1.1  1994/04/25  15:12:06  ram
# patch7: removed incorrect sanity check for zcat (void when portable)
#
# Revision 3.0  1993/11/29  13:48:25  ram
# Baseline for mailagent 3.0 netwide release.
#

$cat = '/bin/cat';
$zcat = '/bin/zcat';
$mversion = '3.0';
$patchlevel = '44';

$prog_name = $0;				# Who I am
$prog_name =~ s|^.*/(.*)|$1|;	# Keep only base name

&read_config;		# First, read configuration file (in ~/.mailagent)

# take job number and command from environment
# (passed by mailagent)
$jobnum = $ENV{'jobnum'};
$fullcmd = $ENV{'fullcmd'};
$pack = $ENV{'pack'};
$path = $ENV{'path'};

&read_dist;			# Read distributions

$dest = shift;			# Who should the patches be sent to
$system = shift;		# Which system do patches belong
$version = shift;		# Which version it is

# A single '-' as first argument stands for return path
$dest = $path if $dest eq '-';

# A single '-' for version means "highest available" version.
$version = $Version{$system} if $version eq '-';

# Full name of system for H table access
$pname = $system . "|" . $version;

$maillist = "To obtain a list of what is available, send me the following mail:

	Subject: Command
	\@SH maillist $path
		^ note the l";

if (!$System{$system}) {
	open(MAILER, "|$cf'sendmail $cf'mailopt $path $cf'email") || &nofork;
	print MAILER
"To: $path
Subject: No program called $system
X-Mailer: mailagent [version $mversion PL$patchlevel]

I don't know how to send patches for a program called $system.  Sorry.

$maillist

If $cf'name can figure out what you meant, you'll get the patches anyway.

-- $prog_name speaking for $cf'user
";
	close MAILER;
	if ($?) {
		&add_log("ERROR cannot report system $system is unknown") if $loglvl;
	} else {
		&add_log("MSG system $system is unknown") if $loglvl > 6;
	}
    &add_log("FAILED (UNKNOWN SYSTEM)") if $loglvl > 1;
    exit 0;
}

if (!$Program{$pname}) {
	open(MAILER, "|$cf'sendmail $cf'mailopt $path $cf'email") || &nofork;
	print MAILER
"To: $path
Subject: No patches for $system version $version
X-Mailer: mailagent [version $mversion PL$patchlevel]

I don't know how to send patches for version $version of $system.  Sorry.";
	if ($Version{$system} ne '') {
		print MAILER "

[The highest version for $system is $Version{$system}.]";
		&add_log("MSG highest version is $Version{$system}") if $loglvl > 8;
	} else {
		print MAILER "

[There is no version number for $system.]";
		&add_log("MSG no version number") if $loglvl > 8;
	}
	print MAILER "

$maillist

If $cf'name can figure out what you meant, you'll get the patches anyway.

-- $prog_name speaking for $cf'user
";
	close MAILER;
	if ($?) {
		&add_log("ERROR cannot report no patches for $system $version")
			if $loglvl;
	} else {
		&add_log("MSG no patched for $system $version") if $loglvl > 6;
	}
    &add_log("FAILED (BAD SYSTEM NUMBER)") if $loglvl > 1;
    exit 0;
}

if (!($Maintained{$pname} || $Patches{$pname})) {
	open(MAILER, "|$cf'sendmail $cf'mailopt $path $cf'email") || &nofork;
	print MAILER
"To: $path
Subject: $system version $version is not maintained
X-Mailer: mailagent [version $mversion PL$patchlevel]

I can't send you patches for version $version of $system, because this code
is not maintained by $cf'name. There are no official patches available either...

$maillist

Anyway, if you discover a bug or have remarks about \"$system\", please
let me know. Better, if you know where patches for $system can be found,
well... you have my e-mail address ! :->

-- $prog_name speaking for $cf'user
";
	close MAILER;
	if ($?) {
		&add_log("ERROR cannot report $system $version is not maintained")
			if $loglvl;
	} else {
		&add_log("MSG $system $version is not maintained") if $loglvl > 6;
	}
    &add_log("FAILED (NOT MAINTAINED)") if $loglvl > 1;
    exit 0;
}

# Create a temporary directory
$tmp = "$cf'tmpdir/dmp$$";
mkdir($tmp, 0700) || &fatal("cannot create $tmp");

# Need to unarchive the distribution
if ($Archived{$pname}) {
	# Create a temporary directory for distribution
	$tmp_loc = "$cf'tmpdir/dmpl$$";
	mkdir($tmp_loc, 0700) || &fatal("cannot create $tmp_loc");
	$Location{$pname} =
		&unpack($Location{$pname}, $tmp_loc, $Compressed{$pname});
}

# Go to bugs sub-directory. It is possible to ask for patches for
# old systems. Such systems are identified by having the `patches'
# field from the distrib file set to "old". In that case, patches
# are taken from a bugs-version directory. Version has to be non null.

if ($Patch_only{$pname}) {
	&abort("old system has no version number") if $version eq '';
	chdir "$Location{$pname}/bugs-$version" ||
		&abort("cannot go to $Location{$pname}/bugs-$version");
	# There is no patchlevel to look at -- compute by hand.
	for ($maxnum = 1; ; $maxnum++) {
		last unless -f "patch$maxnum" || -f "patch$maxnum.Z";
	}
	$maxnum--;		# We've gone too far
} else {
	chdir "$Location{$pname}/bugs" ||
		&abort("cannot go to $Location{$pname}/bugs");
	open(PATCHLEVEL, "../patchlevel.h") ||
		&abort("cannot open patchlevel.h");
	$maxnum = 0;
	while (<PATCHLEVEL>) {
		if (/.*PATCHLEVEL[ \t]*(\d+)/) {
			$maxnum = $1;
			last;
		}
	}
	close PATCHLEVEL;
}

if (!$maxnum) {
	# If we get here, it must be for one of our systems. Indeed,
	# if we do not have any patches for a third party program, there
	# should be a "no" in the patches field of distribution file, and
	# in that case an error would have been reported before.
	open(MAILER, "|$cf'sendmail $cf'mailopt $path $cf'email") || &nofork;
	print MAILER
"To: $path
Subject: No patches yet for $system version $version
X-Mailer: mailagent [version $mversion PL$patchlevel]

There are no patches (yet) for $system version $version. Sorry.

-- $prog_name speaking for $cf'user
";
	close MAILER;
	if ($?) {
		&add_log("ERROR cannot report no patches yet for $system $version")
			if $loglvl;
	} else {
		&add_log("MSG no patches yet for $system $version") if $loglvl > 6;
	}
    &add_log("FAILED (NO PATCHES YET)") if $loglvl > 1;
	&clean_tmp;
    exit 0;
}

$patchlist = &rangeargs($maxnum, @ARGV);	# Generate patch list

if (! ($patchlist =~ /\d/)) {
	open(MAILER, "|$cf'sendmail $cf'mailopt $path $cf'email") || &nofork;
	print MAILER
"To: $path
Subject: Invalid patch request for $system $version
X-Mailer: mailagent [version $mversion PL$patchlevel]
";
	if ($Patches{$pname}) {
		print MAILER "
The highest patch I have for $system version $version is #$maxnum.";
	} else {
		print MAILER "
The latest patch for $system version $version is #$maxnum.";
	}
	print MAILER "
(Your command was: $fullcmd)";
	if ($Version{$system} > $version) {
		print MAILER "

Please note that the latest version for $system is $Version{$system}.

$maillist";
	}
	print MAILER "

-- $prog_name speaking for $cf'user
";
	close MAILER;
	if ($?) {
		&add_log("ERROR cannot report latest $system is $version PL$maxnum")
			if $loglvl;
	} else {
		&add_log("MSG latest $system is $version PL$maxnum") if $loglvl > 6;
	}
    &add_log("FAILED (INVALID PATCH LIST)") if $loglvl > 1;
	&clean_tmp;
    exit 0;
}

@numbers = split(/ /,$patchlist);

foreach $num (@numbers) {
	$patchfile = "patch" . $num;	# Base name of the patch
	if (-f $patchfile) {			# Normal patch
		$append = $cat;
		$extent = '';
	} elsif (-f "$patchfile.Z") {	# Compressed patch
		$append = $zcat;
		$extent = '.Z';
	} else {
		&add_log("ERROR no patch #$num ($system)") if $loglvl > 1;
		next;
	}
	open (TMP, ">$tmp/$patchfile");
	if ($Patches{$pname}) {
		print TMP "
This is an official patch for $system version $version, please apply it.
The highest patch I have for that version of $system is #$maxnum.";
	} else {
		print TMP "
The latest patch for $system version $version is #$maxnum.";
	}
	print TMP "

-- $prog_name speaking for $cf'user
";
	close TMP;
	system "$append <$patchfile$extent >>$tmp/$patchfile";
	if ($? && $loglvl > 1) {
		&add_log("ERROR can't uncompress patch #$num ($system)")
			if $append eq $zcat;
		&add_log("ERROR can't copy patch #$num ($system)")
			if $append eq $cat;
		next;
	}
	&add_log("copied file $patchfile into $tmp") if $loglvl > 17;
}

if ($#numbers > 0) {
	$subject = $#numbers + 1;		# Array count starts at 0
	$subject = "$system $version, $subject patches";
} else {
	$subject = "$system $version patch #$numbers[0]";
}
&sendfile($dest, $tmp, $pack, $subject);
&clean_tmp;

exit 0;		# Ok

sub clean_tmp {
	# Do not stay in the directories we are removing...
	chdir $cf'home;
	if ($tmp ne '') {
		system '/bin/rm', '-rf', $tmp;
		&add_log("removed dir $tmp") if $loglvl > 19;
	}
	if ($Archived{$pname}) {
		system '/bin/rm', '-rf', $tmp_loc;
		&add_log("removed dir $tmp_loc") if $loglvl > 19;
	}
}

# Emergency exit with clean-up
sub abort {
	local($reason) = shift(@_);		# Why we are exiting
	&clean_tmp;
	&fatal($reason);
}


# Report error while forking a sendmail process
sub nofork {
	&add_log("SYSERR fork: $!") if $loglvl;
	&add_log("ERROR cannot launch $cf'sendmail") if $loglvl;
}

# In case of fatal error, the program does not simply die
# but also records the failure in the log.
sub fatal {
	local($reason) = @_;			# Why did we get here ?
	&add_log("FAILED ($reason)") if $loglvl > 0;
	die "$prog_name: $reason\n";
}

# Emergency signal was caught
sub emergency {
	local($sig) = @_;			# First argument is signal name
	&fatal("trapped SIG$sig");
}

# Add an entry to logfile
# There is no need to lock logfile as print is sandwiched betweeen
# an open and a close (kernel will flush at the end of the file).
sub add_log {
	# Indirection needed, so that we may remap add_log on stderr_log via a
	# type glob assignment.
	&usrlog'write_log($cf'logfile, $_[0], undef);
}

# When mailagent is used interactively, log messages are also printed on
# the standard error.
# NB: this function is not called directly, but via a type glob *add_log.
sub stderr_log {
	print STDERR "$prog_name: $_[0]\n";
	&usrlog'write_log($cf'logfile, $_[0], undef);
}

# Routine used to emit logs when no logging has been configured yet.
# As soon as a valid configuration has been loaded, logs will also be
# duplicated into the logfile. Used solely by &cf'setup.
# NB: this function is not called directly, but via a type glob *add_log.
sub stdout_log {
	print STDOUT "$prog_name: $_[0]\n";
	&usrlog'write_log($cf'logfile, $_[0], undef) if defined $cf'logfile;
}

#
# User-defined log files
#

package usrlog;

# Record a new logfile by storing its pathname in the %Logpath hash table
# indexed by names and the carbon-copy flag in the %Cc table.
sub new {
	local($name, $path, $cc) = @_;
	return if defined $Logpath{$name};	# Logfile already recorded
	return if $name eq 'default';		# Cannot redefined defaul log
	$path = "$cf'logdir/$path" unless $path =~ m|^/|;
	$Logpath{$name} = $path;			# Where logfile should be stored
	$Cc{$name} = $cc ? 1 : 0;			# Should we cc the default logfile?
	$Map{$path} = $name;				# Two-way hash table
}

# Delete user-defined logfile.
sub delete {
	local($name) = @_;
	return unless defined $Logpath{$name};
	local($path) = $Logpath{$name};
	delete $Logpath{$name};
	delete $Cc{$name};
	delete $Map{$path};
}

# User-level logging main entry point
sub main'usr_log {
	local($name, $message) = @_;	# Logfile name and message to be logged
	local($file);
	$file = ($name eq 'default' || !defined $Logpath{$name}) ?
		$cf'logfile : $Logpath{$name};
	&write_log($file, $message, $Cc{$name});
}

# Log message into logfile, using jobnum to identify process.
sub write_log {
	local($file, $msg, $cc) = @_;	# Logfile, message to be logged, cc flag
	local($date);
	local($log);

	local ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) =
		localtime(time);
	$date = sprintf("%.2d/%.2d/%.2d %.2d:%.2d:%.2d",
		$year,++$mon,$mday,$hour,$min,$sec);
	$log = $date . " $'prog_name\[$'jobnum\]: $msg\n";

	# If we cannot append to the logfile, first check whether it is the default
	# logfile or not. If it is not, then add a log entry to state the error in
	# the default log and then delete that user logname entry, assuming the
	# fault we get is of a permanent nature and not an NFS failure for instance.

	unless (open(LOGFILE, ">>$file")) {
		if ($file ne $cf'logfile) {
			local($name) = $Map{$file};	# Name under which it was registered
			&'add_log("ERROR cannot append to $name logfile $file: $!")
				if $'loglvl > 1;
			&'add_log("NOTICE removing logging to $file") if $'loglvl > 6;
			&delete($Map{$file});
			$cc = 1;				# Force logging to default file
		} else {					# We were already writing to default log
			return;					# Cannot log message at all
		}
	}

	print LOGFILE $log;
	close LOGFILE;

	# If $cc is set, a copy of the same log message (same time stamp guaranteed)
	# is made to the default logfile. If called with $file set to that default
	# logfile, $cc will be undef by construction.

	if ($cc) {
		open(LOGFILE, ">>$cf'logfile");
		print LOGFILE $log;
		close LOGFILE;
	}
}

package main;

package cf;

# This package is responsible for keeping track of the configuration variables.

# Read configuration file (usually in ~/.mailagent)
sub main'read_config {
	local($file) = @_;				# where config file is located
	local($_);
	$file = '~/.mailagent' unless $file;
	local($myhome) = $ENV{'HOME'};	# must be correctly set by filter
	$file =~ s/~/$myhome/;			# ~ substitution
	local($main'config) = $file;	# Save it: could be modified by config
	open(CONFIG, "$file") ||
		&'fatal("can't open config file $file");
	local($config) = ' ' x 2000;	# pre-extend to avoid realloc()
	$config = '';
	while (<CONFIG>) {
		next if /^[ \t]*#/;			# skip comments
		next if /^[ \t]*\n/;		# skip empy lines
		s/([^\\](\\\\)*)@/$1\\@/g;	# escape all un-escaped @ in string
		$config .= $_;
	}
	&parse($config) || &'fatal('bad configuration');
	close CONFIG;

	# Security checks, pending of those performed by the C filter. They are
	# somewhat necessary, even though the mailagent does not run setuid
	# (because anybody may activate the mailagent for any user by sending him
	# a mail, and world writable configuration files makes the task too easy
	# for a potential hacker). The tests are performed once the configuration
	# file has been parsed, so logging of fatal errors may occur.

	local($unsecure) = 0;

	$unsecure++ unless &'file_secure($'config, 'config');
	$unsecure++ unless &'file_secure($rules, 'rule');
	&'fatal("unsecure configuration!") if $unsecure;

	return unless -f "$rules";		# No rule file
}

# Parse config file held in variable and return 1 if ok, 0 for errors
sub parse {
	local($config) = @_;
	return 1 unless defined $config;
	local($eval) = ' ' x 1000;		# Pre-extend
	local($myhome) = $ENV{'HOME'};	# must be correctly set by filter
	local($var, $value);
	local($_);
	$eval = '';
	foreach (split(/\n/, $config)) {
		if (/^[ \t]*([^ \t\n:\/]*)[ \t]*:[ \t]*([^#\n]*)/) {
			$var = $1;
			$value = $2;
			$value =~ s/\s*$//;						# remove trailing spaces
			$eval .= "\$$var = \"$value\";\n";
			$eval .= "\$$var =~ s|~|$myhome|g;\n";	# ~ substitution
		}
	}
	eval $eval;			# evaluate configuration parameters within package

	if ($@ ne '') {				# Parsing error detected
		local($error) = $@;		# Logged error
		local($*) = 1;
		$error = (split(/\n/, $error))[0];		# Keep only first line
		# Dump error message on stderr, as well as faulty configuration file.
		# The original is restored out of the perl form to avoid surprise.
		$eval =~ s/^\$.* =~ s\|~\|.*\n//g;		# Remove added ~ substitutions
		$eval =~ s/^\$//g;						# Remove leading '$'
		$eval =~ s/ = "(.*)";/: $1/g;			# Keep only variable value
		chop($eval);
		print STDERR <<EOM;
**** Syntax error in configuration:
$error

---- Begin of Faulty Configuration
$eval
---- End of Faulty Configuration

EOM
		&'add_log("syntax error in configuration: $error") if $'loglvl > 1;
		return 0;
	}

	# Define the mailagent parameters from those in config file
	$logfile = $logdir . "/$log";
	$seqfile = $spool . "/$seq";
	$hashdir = $spool . "/$hash";
	$main'loglvl = int($level);		# This one is visible in the main package
	$main'track_all = 1 if $track =~ /on/i;		# Option -t set by config
	$sendmail = $'mailer if $sendmail eq '';	# No sendmail program specified
	$sendnews = $'inews if $sendnews eq '';		# No news posting program
	$mailopt = '-odq' if $mailopt eq '' && $sendmail =~ /sendmail/;

	# Backward compatibility -- RAM, 25/04/94
	$fromesc = 'ON' unless defined $fromesc;	# If absent from ~/.mailagent
	$lockmax = 20 unless defined $lockmax;
	$lockdelay = 2 unless defined $lockdelay;
	$lockhold = 3600 unless defined $lockhold;
	$queuewait = 60 unless defined $queuewait;
	$queuehold = 1800 unless defined $queuehold;
	$queuelost = 86400 unless defined $queuelost;
	$runmax = 3600 unless defined $runmax;
	$umask = 077 unless defined $umask;
	$email = $user unless defined $email;
	$compspec = "$spool/compressors" unless defined $compspec;
	$comptag = 'compress' unless defined $comptag;
	$locksafe = 'ON' unless defined $locksafe;

	# For backward compatibility, we force a .lock locking on mailboxes.
	# For system ones (name = login), there's no problem because the lock
	# file is still under the 14 characters limit. If mail is saved in folders
	# whose name is longer, there might be problems though. There's little we
	# can do about it here, lest they choose an alternate locking name.
	# Note that mailagent's $lockext global variable setting depends on the
	# fact that the target system supports flexible filenames or not, so only
	# mailbox locking is a problem -- RAM, 18/07/95

	$mboxlock = '%f.lock' unless defined $mboxlock;

	$umask = oct($umask) if $umask =~ /^0/;	 # Translate umask into decimal

	# Update @INC perlib search path with the perlib variable. Paths not
	# starting by a '/' are supposed to be under the mailagent private lib
	# directory.

	local(%seen);		# Avoid dups in @INC (might be called more than once)

	foreach (@INC) { $seen{$_}++; }

	if (defined $perlib) {
		foreach (split(':', $perlib)) {
			s/^~/$home/;
			$_ = $'privlib . '/' . $_ unless m|^/|;
			push(@INC, $_) unless $seen{$_}++;
		}
	}

	1;		# Ok
}

package main;

# Expands an archive's name
sub expand {
	local($path) = shift;		# The archive
	# Look for extension of base path (eg: .cpio.Z)
	local(@fullpath) = <${path}.*>;
	if (-1 == $#fullpath) {
		&clean_tmp;
		&fatal("no archive file");
	}
	$path = $fullpath[0];		# Name with archive extension
}

# Unpack(path,dir,flag) restores archive `path' into `dir'
# and returns the location of the main directory.
sub unpack {
	local($path) = shift;		# The archive
	local($dir) = shift;		# Storage place
	local($compflag) = shift;	# Flag for compression (useful for short names)
	local($unpack) = "";		# Will hold the restore command
	$path = &expand($path);		# Name with archive extension
	&add_log("archive is $path") if $loglvl > 19;
	# First determine wether it is compressed
	if ($compflag) {
		$unpack = "zcat | ";
	}
	# Cpio or tar ?
	if ($path =~ /\.tar/) {
		$unpack .= "tar xof -";
	} else {
		$unpack .= "cpio -icmd";
	}
	system "< $path (cd $dir; $unpack)";
	$path =~ s|.*/(\w+)|$1|;	# Keep only basename
	local ($stat) = $?;			# Return status
	if ($stat) {
		&clean_tmp;
		&fatal("unable to unpack $path");
	}
	&add_log("unpacked $path with \"$unpack\"") if $loglvl > 12;

	# The top level directory is the only file in $dir
	local(@top) = <${dir}/*>;
	if ($#top < 0) {
		&clean_tmp;
		&fatal("$prog_name: no top-level dir for $path");
	}
	if ($#top > 0) {
		&add_log("WARNING more than one file in $dir") if $loglvl > 4;
	}
	&add_log("top-level dir for $path is $top[0]") if $loglvl > 19;
	$top[0];		# Top-level directory
}

# Expand a patch list
sub rangeargs {
	local(@val);
	local($maxspec) = shift;	# maximum patch value
	local($args) = $#_;			# number of parameters

	while ($args-- >= 0) {
		$_ = shift;		# first value remaining in @_
		while (/./) {
			if (s/^(\d+)-(\d+)//) {
				$min = $1;
				$max = $2;
			} elsif (s/^(\d+)-//) {
				$min = $1;
				$max = $maxspec;
			} elsif (s/^-(\d+)//) {
				$max = $1;
				$min = 1;
			} elsif (s/^(\d+)//) {
				$max = $min = $1;
			} elsif (s/^,//) {
				$min = 1;
				$max = 0;	# won't print anything
			} else {
				# error in format: skip char
				s/.//;
			}
			for ($i = $min; $i <= $max; ++$i) {
				push(@val, $i) unless $wanted{$i};	# record only once
				$wanted{$i} = 1;
			}
		}
	}
	join(' ', @val);
}

# Send a set of files
sub sendfile {
	local($dest, $cf'tmpdir, $pack, $subject) = @_;
	&add_log("sending dir $cf'tmpdir to $dest, mode $pack") if $loglvl > 9;

	# A little help message
	local($mail_help) = "Detailed intructions can be obtained by:

	Subject: Command
	\@SH mailhelp $dest";

	# Go to tmpdir where files are stored
	chdir $cf'tmpdir || &abort("NO TMP DIRECTORY");

	# Build a list of files to send
	local($list) = "";		# List of plain files
	local($dlist) = "";		# List with directories (for makekit)
	local($nbyte) = 0;
	local($nsend) = 0;
	open(FIND, "find . -print |") || &abort("CANNOT RUN FIND");
	while (<FIND>) {
		chop;
		next if $_ eq '.';		# Skip current directory `.'
		s|^\./||;
		$dlist .= $_ . " ";		# Save file/dir name
		if (-f $_) {			# If plain file
			$list .= $_ . " ";	# Save plain file
			$nsend++;			# One more file to send
			($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,$atime,$mtime,$ctime,
				$blksize,$blocks) = stat($_);
			$nbyte += $size;	# Update total size
		}
	}
	close FIND;

	&abort("NO FILE TO SEND") unless $nsend;
	if ($nsend > 1) {
		&add_log("$nsend files to pack ($nbyte bytes)") if $loglvl > 9;
	} else {
		&add_log("1 file to pack ($nbyte bytes)") if $loglvl > 9;
	}

	# Pack files
	if ($pack =~ /kit/) {
		system "kit -n Part $list" || &abort("CANNOT KIT FILES");
		$packed = "kit";
	} elsif ($pack =~ /shar/) {
		# Create a manifest, so that we can easily run maniscan
		# Leave a PACKNOTES file with non-zero length if problems.
		local($mani) = $dlist;
		$mani =~ s/ /\n/g;
		local($packlist) = "pack.$$";	# Pack list used as manifest
		if (open(PACKLIST, ">$packlist")) {
			print PACKLIST $mani;
			close PACKLIST;
			system 'maniscan', "-i$packlist",
				"-o$packlist", '-w0', '-n', '-lPACKNOTES';
			&add_log("ERROR maniscan returned non-zero status")
				if $loglvl > 5 && $?;
			if (-s 'PACKNOTES') {		# Files split or uu-encoded
				system 'makekit', "-i$packlist", '-t',
					"Now run 'sh PACKNOTES'." || &abort("CANNOT SHAR FILES");
			} else {
				system 'makekit', "-i$packlist" || &abort("CANNOT SHAR FILES");
			}
		} else {
			&add_log("ERROR cannot create packlist") if $loglvl > 5;
			system "makekit $dlist" || &abort("CANNOT SHAR FILES");
		}
		$packed = "shar";
	} else {
		if ($nbyte > $cf'maxsize) {		# Defined in ~/.mailagent
			system "kit -M -n Part $list" || &abort("CANNOT KIT FILES");
			$packed = "minikit";		# The minikit is included
		} else {
			# Try with makekit first
			if (system "makekit $dlist") {	# If failed
				system "kit -M -n Part $list" || &abort("CANNOT KIT FILES");
				$packed = "minikit";	# The minikit is included
			} else {
				$packed = "shar";
			}
		}
	}

	# How many parts are there ?
	@parts = <Part*>;
	$npart = $#parts + 1;		# Number of parts made
	&abort("NO PART TO SEND -- $packed failed") unless $npart;
	if ($npart > 1) {
		&add_log("$npart $packed parts to send") if $loglvl > 19;
	} else {
		&add_log("$npart $packed part to send") if $loglvl > 19;
	}

	# Now send the parts
	$nbyte = 0;				# How many bytes do we send ?
	$part_num = 0;
	$signal="";				# To signal parts number if more than 1
	local($partsent) = 0;	# Number of parts actually sent
	local($bytesent) = 0;	# Amount of bytes actually sent
	foreach $part (@parts) {
		($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,$atime,$mtime,$ctime,
			$blksize,$blocks) = stat($part);
		$nbyte += $size;	# Update total size

		&add_log("dealing with $part ($size bytes)") if $loglvl > 19;

		# See if we need to signal other parts
		$part_num++;			# Update part number
		if ($npart > 1) {
			$signal=" (Part $part_num/$npart)";
		}

		# Send part
		open(MAILER, "|$cf'sendmail $cf'mailopt $dest");
		print MAILER
"To: $dest
Subject: $subject$signal
Precedence: bulk
X-Mailer: mailagent [version $mversion PL$patchlevel]

Here is the answer to your request:

	$fullcmd


";
		if ($packed eq 'minikit') {		# Kit with minikit included
			print MAILER
"This is a kit file. It will be simpler to unkit it if you own the kit
package (latest patchlevel), but you can use the minikit provided with
this set of file (please see instructions provided by kit itself at the
head of each part). If you wish to get kit, send me the following mail:

";
		} elsif ($packed eq 'kit') {	# Plain kit files
			print MAILER
"This is a kit file. You need the kit package (latest patchlevel) to
unkit it. If you do not have kit, send me the following mail:

";
		}
		if ($packed =~ /kit/) {		# Kit parts
			print MAILER
"	Subject: Command
	\@PACK shar
	\@SH maildist $dest kit -

and you will get the latest release of kit as shell archives.

$mail_help

";
			# Repeat instructions which should be provided by kit anyway
			if ($npart > 1) {
				print MAILER
"Unkit:	Save this mail into a file, e.g. \"foo$part_num\" and wait until
	you have received the $npart parts. Then, do \"unkit foo*\". To see
	what will be extracted, you may wish to do \"unkit -l foo*\" before.
";
			} else {
				print MAILER
"Unkit:	Save this mail into a file, e.g. \"foo\". Then do \"unkit foo\". To see
	what will be extracted, you may wish to do \"unkit -l foo\" before.
";
			}
			# If we used the minikit, signal where instruction may be found
			if ($packed eq 'minikit') {
				print MAILER
"	This kit archive also contains a minikit which will enable you to
	extract the files even if you do not have kit. Please follow the
	instructions kit has provided for you at the head of each part. Should
	the minikit prove itself useless, you may wish to get kit.
";
			}
		} else {			# Shar parts
			print MAILER
"This is a shar file. It will be simpler to unshar it if you own the Rich Salz's
cshar package. If you do not have it, send me the following mail:

	Subject: Command
	\@PACK shar
	\@SH maildist $dest cshar 3.0

and you will get cshar as shell archives.

$mail_help

";
			if (-s 'PACKNOTES') {		# Problems detected by maniscan
				print MAILER
"
Warning:
	Some minor problems were encountered during the building of the
	shell archives. Perhaps a big file has been split, a binary has been
	uu-encoded, or some lines were too long. Once you have unpacked the
	whole distribution, see file PACKNOTES for more information. You can
	run it through sh by typing 'sh PACKNOTES' to restore possible splited
	or encoded files.

";
			}
			if ($npart > 1) {
				print MAILER
"Unshar: Save this mail into a file, e.g. \"foo$part_num\" and wait until
	you have received the $npart parts. Then, do \"unshar -n foo*\". If you
	do not own \"unshar\", edit the $npart files and remove the mail header
	by hand before feeding into sh.
";
			} else {
				print MAILER
"Unshar: Save this mail into a file, e.g. \"foo\". Then do \"unshar -n foo\". If
	you do not own \"unshar\", edit the file and remove the mail header by
	hand before feeding into sh.
";
			}
		}
		print MAILER
"
-- $prog_name speaking for $cf'user


";
		open(PART, $part) || &abort("CANNOT OPEN $part");
		while (<PART>) {
			print MAILER;
		}
		close PART;
		close MAILER;
		if ($?) {
			&add_log("ERROR couldn't send $size bytes to $dest")
				if $loglvl > 1;
		} else {
			&add_log("SENT $size bytes to $dest") if $loglvl > 2;
			$partsent++;
			$bytesent += $size;
		}
	}

	# Prepare log message
	local($partof) = "";
	local($byteof) = "";
	local($part);
	local($byte);
	if ($partsent > 1) {
		$part = "parts";
	} else {
		$part = "part";
	}
	if ($bytesent > 1) {
		$byte = "bytes";
	} else {
		$byte = "byte";
	}
	if ($partsent != $npart) {
		$partof = " (of $npart)";
		$byteof = "/$nbyte";
	}
	&add_log(
		"SENT $partsent$partof $packed $part ($bytesent$byteof $byte) to $dest"
	) if $loglvl > 4;
}

# In case something got wrong
# We call the clean_tmp routine, which must be defined in the
# main program that will use abort.
sub abort {
	local($reason) = shift;		# Why do we abort ?
	local($cmd) = $fullcmd =~ /^(\S+)/;
	open(MAILER, "|$cf'sendmail $cf'mailopt $path $cf'email");
	print MAILER
"To: $path
Subject: $cmd failed
X-Mailer: mailagent [version $mversion PL$patchlevel]

Sorry, the $prog_name command failed while sending files.

Your command was: $fullcmd
Error message I got:

	>>>> $reason <<<<

If $cf'name can figure out what you meant, he may answer anyway.

-- $prog_name speaking for $cf'user
";
	close MAILER;
	&add_log("FAILED ($reason)") if $loglvl > 1;
	&clean_tmp;
	exit 0;			# Scheduled error
}

# Read a distribution file and fill in data structures for
# the query functions. All the data are stored in associative
# arrays, indexed by the system's name and version number.
# Associative arrays are:
#
# name          indexed by       information
#
# %Program      name + version   have we seen that line ?
# %System       name             is name a valid system ?
# %Version      name             latest version for system
# %Location		name + version   location of the distribution
# %Archived     name + version   is distribution archived ?
# %Compressed   name + version   is archive compressed ?
# %Patch_only   name + version   true if only patches delivered
# %Maintained   name + version   true if distribution is maintained
# %Patches      name + version   true if official patches available
#
# For systems with a version of '---' in the file, the version
# for accessing the data has to be a "0" string.
#
# Expected format for the distribution file:
#     system version location archive compress patches
#
# The `archive', `compress' and `patches' fields can take one
# of the following states: "yes" and "no". An additional state
# for `patches' is "old", which means that only patches are
# available for the version, and not the distribution. Another is
# "patch" which means that official patches are available.
# All these states can be abbreviated with the first letter.
#
sub read_dist {
	local($fullname);
	open(DIST, "$cf'distlist") ||
		&fatal("cannot open distribution file");
	while (<DIST>) {
		next if /^\s*#/;	# skip comments
		next if /^\s*$/;	# skip empty lines
		next unless s/^\s*(\w+)\s+([.\-0-9]+)//;
		$fullname = $1 . "|" . ($2 eq '---'? "0" : $2);
		if (defined $Program{$fullname}) {
			&add_log("WARNING duplicate distlist entry $1 $2 ignored")
				if $loglvl > 5;
			next;
		}
		$Program{$fullname}++;
		$Version{$1} = ($2 eq '---' ? "0" : $2) unless
			defined($System{$1}) && $Version{$1} > ($2 eq '---' ? "0":$2);
		$System{$1}++;
		unless (/^\s*(\S+)\s+(\w+)\s+(\w+)\s+(\w+)/) {
			&add_log("WARNING bad system description line $.")
				if $loglvl > 5;
			next;	# Ignore, but it may corrupt further processing
		}
		local($location) = $1;
		local($archive) = $2;
		local($compress) = $3;
		local($patch) = $4;
		$location =~ s/~\//$cf'home\//;		# ~ expansion
		$Location{$fullname} = $location;
		$Archived{$fullname}++ if $archive =~ /^y/;
		$Compressed{$fullname}++ if $compress =~ /^y/;
		$Patch_only{$fullname}++ if $patch =~ /^o/;
		$Maintained{$fullname}++ if $patch =~ /^y|o/;
		$Patches{$fullname}++ if $patch =~ /^p/;
	}
	close DIST;
}

# A file "secure" if it is owned by the user and not world writable. Some key
# file within the mailagent have to be kept secure or they might compromise the
# security of the user account. Additionally, for 'root' users or if the
# 'secure' parameter in the config file is set to ON, checks are made for
# group writable files and suspicious directory as well.
# Return true if the file is secure or missing, false otherwise.
sub file_secure {
	local($file, $type) = @_;	# File to be checked
	return 1 unless -e $file;	# Missing file considered secure
	if (-l $file) {				# File is a symbolic link
		&add_log("WARNING sensitive $type file $file is a symbolic link")
			if $loglvl > 5;
		return 0;		# Unsecure file
	}
	local($ST_MODE) = 2 + $[;	# Field st_mode from inode structure
	unless (-O _) {				# Reuse stat info from -e
		&add_log("WARNING you do not own $type file $file") if $loglvl > 5;
		return 0;		# Unsecure file
	}
	local($st_mode) = (stat(_))[$ST_MODE];
	if ($st_mode & $S_IWOTH) {
		&add_log("WARNING $type file is world writable!") if $loglvl > 5;
		return 0;		# Unsecure file
	}

	return 1 unless $cf'secure =~ /on/i || $< == 0;

	# Extra checks for secure mode (or if root user). We make sure the
	# file is not writable by group and then we conduct the same secure tests
	# on the directory itself
	if ($st_mode & $S_IWGRP) {
		&add_log("WARNING $type file is group writable!") if $loglvl > 5;
		return 0;		# Unsecure file
	}
	local($dir);		# directory where file is located
	$dir = '.' unless ($dir) = ($file =~ m|(.*)/.*|);
	unless (-O $dir) {
		&add_log("WARNING you do not own directory of $type file")
			if $loglvl > 5;
		return 0;		# Unsecure directory, therefore unsecure file
	}
	$st_mode = (stat(_))[$ST_MODE];
	return 0 unless &check_st_mode($dir, 1);

	# If linkdirs is OFF, we do not check further when faced with a symbolic
	# link to a directory.
	if (-l $dir && $cf'linkdirs !~ /^off/i && !&symdir_secure($dir, $type)) {
		&add_log("WARNING directory of $type file $file is an unsecure symlink")
			if $loglvl > 5;
		return 0;		# Unsecure directory
	}

	1;		# At last! File is secure...
}

# Is a symbolic link to a directory secure?
sub symdir_secure {
	local($dir, $type) = @_;
	if (&symdir_check($dir, 0)) {
		&add_log("symbolic directory $dir for $type file is secure")
			if $loglvl > 11;
		return 1;
	}
	0;	# Not secure
}

# A symbolic directory (that is a symlink pointing to a directory) is secure
# if and only if:
#   - its target is a symlink that recursively proves to be secure.
#   - the target lies in a non world-writable directory
#   - the final directory at the end of the symlink chain is not world-writable
#   - less than $MAX_LINKS levels of indirection are needed to reach a real dir
# Unfortunately, we cannot check for group writability here for the parent
# target directory since the target might lie in a system directory which may
# have a legitimate need to be read/write for root and wheel, for instance.
# The routine returns 1 if the file is secure, 0 otherwise.
sub symdir_check {
	local($dir, $level) = @_;	# Directory, indirection level
	return 0 if $level++ > $MAX_LINKS;
	local($ndir) = readlink($dir);
	unless (defined $ndir) {
		&add_log("SYSERR readlink: $!") if $loglvl;
		return 0;
	}
	$dir =~ s|(.*)/.*|$1|;		# Suppress link component (tail)
	$dir = &cdir($ndir, $dir);	# Follow symlink to get its final path target
	local($still_link) = -l $dir;
	unless (-d $dir || $still_link) {
		&add_log("ERROR inconsistency: $dir is a plain file?") if $loglvl;
		return 0;		# Reached a plain file while following links to a dir!
	}
	unless (-d "$dir/..") {
		&add_log("ERROR inconsistency: $dir/.. is not a directory?") if $loglvl;
		return 0;		# Reached a file hooked nowhere in the file system!
	}
	# Check parent directory
	local($ST_MODE) = 2 + $[;	# Field st_mode from inode structure
	$st_mode = (stat(_))[$ST_MODE];
	return 0 unless &check_st_mode("$dir/..", 0);
	# Recurse if still a symbolic link
	if ($still_link) {
		return 0 unless &symdir_check($dir, $level);
	} else {
		$st_mode = (stat($dir))[$ST_MODE];
		return 0 unless &check_st_mode($dir, 1);
	}
	1;	# Ok, link is secure
}

# Returns true if mode in $st_mode does not include world or group writable
# bits, false otherwise. This helps factorizing code used in both &file_secure
# and &symdir_check. Set $both to true if both world/group checks are desirable,
# false to get only world checks.
sub check_st_mode {
	local($dir, $both) = @_;
	if ($st_mode & $S_IWOTH) {
		&add_log("WARNING directory of $type file $dir is world writable!")
			if $loglvl > 5;
		return 0;		# Unsecure directory
	}
	return 1 unless $both;
	if ($st_mode & $S_IWGRP) {
		&add_log("WARNING directory of $type file $dir is group writable!")
			if $loglvl > 5;
		return 0;		# Unsecure directory
	}
	1;
}

# Apply directory changes into current path and return new directory
sub cdir {
	local($dir, $cur) = @_;			# New relative path, current directory
	return $dir if $dir =~ m|^/|;	# Already an absolute path
	chop($cur = `pwd`) unless defined $cur;
	local(@cur) = split(/\//, $cur);
	local(@dir) = split(/\//, $dir);
	local($path);
	foreach $item (@dir) {
		next if $item eq '.';	# Stay in same dir
		if ($item eq '..') {	# Move up
			pop(@cur);
		} else {
			push(@cur, $item);	# Move down
		}
	}
	local($path) = '/' . join('/', @cur);
	$path =~ tr|/||s;			# Successive '/' are useless
	$path;
}

