#!/usr/local/bin/perl -U

# Copyright 1992, D. Brent Chapman.  All Rights Reserved.  For use by
# permission only.
#
# $Source: /mycroft/brent/majordomo/RCS/resend,v $
# $Revision: 1.18 $
# $Date: 1993/09/05 22:03:42 $
# $Author: brent $
# $State: Exp $
#
# $Locker:  $
#

# set our path explicitly
$ENV{'PATH'} = "/bin:/usr/bin:/usr/ucb";

# What shall we use for temporary files?
$tmp = "/tmp/majordomo.$$";

# Read and execute the .cf file
$cf = $ENV{"MAJORDOMO_CF"} || "/etc/majordomo.cf";
if ($ARGV[0] eq "-C") {
    $cf = $ARGV[1];
    shift(@ARGV); 
    shift(@ARGV); 
}
if (! -r $cf) {
    die("$cf not readable; stopped");
}
eval(`cat $cf`);

chdir($homedir) || die("Can't chdir(\"$homedir\"): $!");
unshift(@INC, $homedir);
require "majordomo.pl";
require "getopts.pl";

&Getopts("Aa:df:h:I:l:m:M:p:Rr:s") || die("resend: Getopts(): $!");

if (! defined($opt_l) || ! defined($opt_h)) {
    die("resend: must specify both '-l list' and '-h host' arguments");
}

if (defined($opt_f)) {
    $sendmail_sender = $opt_f;
} else {
    $sendmail_sender = "$opt_l-request";
}

if (defined($opt_a)) {
    if ($opt_a =~ /^\//) {
	open(PWD, $opt_a) || die("resend: open(PWD, \"$opt_a\"): $!");
	$opt_a = &chop_nl(<PWD>);
    }
}

if (defined($opt_A) && ! defined($opt_a)) {
    die("resend: must also specify '-a passwd' if using '-A' flag");
}

$sender = "$sendmail_sender@$opt_h";

open(OUT, ">/tmp/resend.$$.out") ||
    die("resend: Can't open /tmp/resend.$$.out: $!");

open(IN, ">/tmp/resend.$$.in") ||
    die("resend: Can't open /tmp/resend.$$.in: $!");

while (<STDIN>) {
    print IN $_;
}

close(IN);

open(IN, "/tmp/resend.$$.in") || 
    die("resend: Can't open /tmp/resend.$$.tmp: $!");

do {
    $restart = 0;
    $pre_hdr = 1;
    while (<IN>) {
	if ($pre_hdr) {
	    if (/^\s*$/) {
		# skip leading blank lines; usually only there if this is a
		# restart after an in-body "Approved:" line
		next;
	    } else {
		$pre_hdr = 0;
		$in_hdr = 1;
		$kept_last = 0;
	    }
	}
	if ($in_hdr) {
	    if (/^\s*$/) {
		# end of header; add new header fields
		print OUT "Sender: $sender\n";
		if (defined($opt_p)) {
		    print OUT "Precedence: $opt_p\n";
		}
		if (defined($opt_r)) {
		    print OUT "Reply-To: $opt_r@$opt_h\n";
		}
		$in_hdr = 0;
		print OUT $_;
	    } elsif (/^approved:\s*(.*)/i && defined($opt_a)) {
		$approved = &chop_nl($1);
		if ($approved ne $opt_a) {
		    &bounce("Invalid 'Approved:' header");
		}
	    } elsif (/^from /i		# skip all these headers
		|| /^sender:/i
		|| /^return-receipt-to:/i
		|| /^errors-to:/i
		|| /^return-path:/i
		|| (/^reply-to:/i && defined($opt_r))	# skip only if "-r" set
		|| (/^precedence:/i && defined($opt_p))	# skip only if "-p" set
		|| (/^received:/i && defined($opt_R))	# skip only if "-R" set
		|| (/^\s/ && ! $kept_last)			# skip if skipped last
	    ) {
		# reset $kept_last in case next line is continuation
		$kept_last = 0;
	    } else {
		# check for administrivia requests 
		if (defined($opt_s) && ! defined($approved)
		    && (/^subject:\s*subscribe\b/i ||
			/^subject:\s*unsubscribe\b/i)) {
		    &bounce("Admin request");
		} 
		if (defined($opt_I))
		{
		    if ( /^from:\s*(.+)/i )
		    {
			$from = $1;
			$from_last = 1;
		    }
		    elsif ( defined($from_last) )
		    {
			if ( /^\s+(.+)/ )
			{
			    $from .= " $1";
			}
			else
			{
			    undef($from_last);
			}
		    }
		}
		&check_hdr_line($_);	# check for length & balance
		$kept_last = 1;
		print OUT $_;
	    }
	} else {
	    # this isn't a header line, so print it (maybe)
	    # first, though, is the first line of the body an "Approved:" line?
	    if (($body_len == 0) && /^approved:\s*(.*)/i && defined($opt_a)) {
		# OK, is it a valid "Approved:" line?
		$approved = &chop_nl($1);
		if ($approved ne $opt_a) {
		    &bounce("Invalid 'Approved:' header");
		} else {
		    # Yes, it's a valid "Approved:" line...
		    # So, we start over
		    $restart = 1;
		    close(OUT);
		    unlink("/tmp/resend.$$.out");
		    open(OUT, ">/tmp/resend.$$.out") ||
			die("resend: Can't open /tmp/resend.$$.out: $!");
		    last;
		}
	    }
	    # make sure it doesn't make the message too long
	    if (defined($opt_M) && ! defined($approved)
		    && ($body_len += length($_)) > $opt_M) {
		&bounce("Message too long (>$opt_M)");
	    }
	    # add admin-request recognition heuristics here... (body)
	    if (defined($opt_s) && ! defined($approved) && ($body_line++ < 5) && (
		/\badd me\b/i
		|| /\bdelete me\b/i
		|| /\bsubscribe\b/i || /^sub\b/i
		|| /\bunsubscribe\b/i || /^unsub\b/i
		)) {
		  &bounce("Admin request");
	    }
	    print OUT $_;
	}
    }
} while ($restart);

if (defined($opt_A) && ! defined($approved)) {
    &bounce("Approval required");
}

close(OUT);

if ( defined($opt_I) && defined($from) && ! defined($approved) ) {
    local($infile) = 0;
 
    @files = split (/[:\t\n]+/, $opt_I);
 
    foreach $file (@files) {
        if ( open (LISTFD, "<${listdir}/${file}") != 0 ) {
	    @output = grep (&addr_match($from, $_), <LISTFD>);
            close (LISTFD);
   
            if ( $#output != -1 ) {
                $infile = 1;
                last;
            }
        }
    }
 
    if ( $infile == 0 ) {
        &bounce ("Non-member submission from [$from]");
    }
}
 
$sendmail_cmd = "/usr/lib/sendmail $opt_m -f$sendmail_sender " .
    join(" ", @ARGV);

if (defined($opt_d)) {
    $| = 1;
    print "Command: $sendmail_cmd\n";
    $status = (system("cat /tmp/resend.$$.out") >> 8);
    unlink(</tmp/resend.$$.*>);
    exit($status);
} else {
    system("$sendmail_cmd </tmp/resend.$$.out");
    unlink(</tmp/resend.$$.*>);
    exit(0);
}

sub check_balance {
    # set a temporary variable
    local($t) = shift;
    # strip out all nested parentheses
    1 while $t =~ s/\([^\(\)]*\)//g;
    # strip out all nested angle brackets
    1 while $t =~ s/\<[^\<\>]*\>//g;
    # if any parentheses or angle brackets remain, were imbalanced
    if ($t =~ /[\(\)\<\>]/ && ! defined($approved)) {
	&bounce("Imbalanced parentheses or angle brackets");
	return(undef);
    }
    return(1);
}

sub check_hdr_line {

    local($_) = shift;

    if (! /^\s/) {	# is this a continuation line?
	# Not a continuation line.
	# If $balanced_fld is defined, it means the last field was one
	# that needed to have balanced "()" and "<>" (i.e., "To:", "From:",
	# and "Cc:", so check it.  We do it here in case the last field was
	# multi-line.

	if (defined($balanced_fld)) {
	    &check_balance($balanced_fld);
	}

	# we undefine $balanced_fld and reset $field_len; these may be set below

	undef($balanced_fld);
	$field_len = 0;
    }

    # is this a field that must be checked for balanced "()" and "<>"?
    if (defined($balanced_fld) || /^from:/i || /^cc:/i || /^to:/i) {
	# yes it is, but we can't check it yet because there might be
	# continuation lines.  Buffer it to be checked at the beginning
	# of the next non-continuation line.

	# is this line too long?
	if ((length($_) > 128) && ! defined($approved)) {
	    &bounce("Header line too long (>128)");
	    return(undef);
	}

	# is this field too long?
	if ((($field_len += length($_)) > 1024) && ! defined($approved)) {
	    &bounce("Header field too long (>1024)");
	    return(undef);
	}

	$balanced_fld .= $_;
	chop($balanced_fld);
    }

    # if we get here, everything was OK.
    return(1);
}

sub bounce {
    local($reason) = shift;
    local($_);

    &resend_sendmail(BOUNCE, $sender, "BOUNCE $opt_l@$opt_h: $reason");
    
    seek(IN, 0, 0);
    while (<IN>) {
	print BOUNCE $_;
    }
    close(BOUNCE);
    unlink(</tmp/resend.$$.*>);
    exit(0);
}

sub resend_sendmail {
    local(*MAIL) = shift;
    local($to) = shift;
    local($subject) = shift;

    # clean up the addresses, for use on the sendmail command line
    local(@to) = &ParseAddrs($to);
    for (@to) {
        $_ = join(", ", &ParseAddrs($_));
    }
    $to = join(", ", @to);

    # open the process
    if (defined($opt_d)) {
	# debugging, so just say it, don't do it
	open(MAIL, ">-");
	print MAIL ">>> /usr/lib/sendmail -f$sendmail_sender -t\n";
    } else {
	open(MAIL, "|/usr/lib/sendmail -f$sendmail_sender -t") ||
	    &abort("Can't connect to sendmail: $!");
    }

    # generate the header
    print MAIL <<"EOM";
To: $to
From: $sender
Subject: $subject

EOM

    return;
}
