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

# Copyright 1992, D. Brent Chapman.  All Rights Reserved.  For use by
# permission only.
#
# $Source: /sources/cvsrepos/majordomo/resend,v $
# $Revision: 1.28.2.2 $
# $Date: 1994/06/09 19:45:16 $
# $Author: rouilj $
# $State: Exp $
#
# $Locker:  $
#

# updated to
# Revision: 1.19 
# Date: 1993/11/11 02:23:37 
#

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

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

# Before doing anything else tell the world I am resend
# The mj_ prefix is reserved for tools that are part of majordomo proper.
$main'program_name = 'mj_resend';


# If the first argument is "@filename", read the real arguments
# from "filename", and shove them onto the ARGV for later processing
# by &Getopts()

if ($ARGV[0] =~ /^@/) {
    $fn = shift(@ARGV);
    $fn =~ s/^@//;
    open(AV, $fn) || die("open(AV, \"$fn\"): $!\nStopped");
    undef($/);	# set input field separator
    $av = <AV>;	# read whole file into string
    close(AV);
    @av = split(/\s+/, $av);
    unshift(@ARGV, @av);
    $/ = "\n";
}
    
# 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`)  || die 'eval of majordomo.cf failed';

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

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

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

# smash case for the list name
$opt_l =~ tr/A-Z/a-z/;

if ( ! @ARGV) {
    die("resend: must specify outgoing list as last arg(s)");
}

$opt_r = "$opt_r@$opt_h" if ( defined($opt_r) );

&get_config($listdir, $opt_l);

$opt_A = &cf_ck_bool($opt_l,"moderate") if &cf_ck_bool($opt_l,"moderate");
$opt_h = $config_opts{$opt_l,"resend_host"} 
			if($config_opts{$opt_l,"resend_host"} ne '');
$opt_a = $config_opts{$opt_l,"approve_passwd"}
			if ($config_opts{$opt_l,"approve_passwd"} ne '');
$opt_M = $config_opts{$opt_l,"maxlength"} 
			if ($config_opts{$opt_l,"maxlength"} ne '');

$opt_f = $config_opts{$opt_l,"sender"}
			if ($config_opts{$opt_l,"sender"} ne '');
$opt_p = $config_opts{$opt_l,"precedence"}
			if ($config_opts{$opt_l,"precedence"} ne '');
$opt_r = $config_opts{$opt_l,"reply_to"}
			if ($config_opts{$opt_l,"reply_to"} ne '');
$opt_I = $config_opts{$opt_l,"restrict_post"} 
			if ($config_opts{$opt_l,"restrict_post"} ne '');
$opt_R = &cf_ck_bool($opt_l,"purge_received")
			 if &cf_ck_bool($opt_l,"purge_received");
$opt_s = &cf_ck_bool($opt_l,"administrivia")
			if &cf_ck_bool($opt_l,"administrivia");
$opt_d = &cf_ck_bool($opt_l,"debug") 
			if &cf_ck_bool($opt_l,"debug");

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: ", &config'substitute_values($opt_r),
				 "\n";
		}

		# print out additonal headers
		if ( $config_opts{$opt_l,"message_headers"} ne '' ) {
			local($headers) = &config'substitute_values (
			$config_opts{$opt_l,"message_headers"}, $opt_l);
			$headers =~ s/\001/\n/g;
			print OUT $headers;
		}

		$in_hdr = 0;
		print OUT $_;

		# print out front matter
		if ( $config_opts{$opt_l,"message_fronter"} ne '' ) {
			local($fronter) = &config'substitute_values (
			$config_opts{$opt_l,"message_fronter"}, $opt_l);
			$fronter =~ s/\001|$/\n/g;
			print OUT $fronter;
		}		
	    } elsif (/^approved:\s*(.*)/i && defined($opt_a)) {
		$approved = &chop_nl($1);
		if ($approved ne $opt_a && 
			!(&main'valid_passwd($listdir, $opt_l, $approved))) {
		    &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 ||
			   /^subject:\s*help\b/i ||
			   /^subject:\s*RCPT:\b/ ||
			   /^subject:\s.*\bchange\b.*\baddress\b/ ||
			   /^subject:\s*request .* addition\b/i)) {
		       &bounce("Admin request");
		       } 

		    # prepend subject prefix
		    if (   (/^subject:\s*/i) &&
			   ($config_opts{$opt_l,"subject_prefix"} ne '') 
		       ) {
			 local($foo) = &config'substitute_values(
			    $config_opts{$opt_l,"subject_prefix"}, $opt_l);
			 local($foo_pat) = $foo;
			 $foo_pat =~ s/(\W)/\\$1/g;
			 s/^subject:\s*/Subject: $foo /i if !/$foo_pat/; 
			}

		    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 &&
			!(&main'valid_passwd($listdir, $opt_l, $approved))) {
		    &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;
		}
	    }
	    $body_len += length($_);
	    # make sure it doesn't make the message too long
	    if (defined($opt_M) && ! defined($approved)
		    && ($body_len > $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 || /\bremove\s+me\b/i
		|| /\bhelp\b/i
		|| /\bchange\b.*\baddress\b/
		|| /\bsubscribe\b/i || /^sub\b/i
		|| /\bunsubscribe\b/i || /^unsub\b/i
		)) {
		  &bounce("Admin request");
	    }
	    print OUT $_;
	}
    }
} while ($restart);

if ( $config_opts{$opt_l,"message_footer"} ne '' ) {
	local($footer) = &config'substitute_values(
	$config_opts{$opt_l,"message_footer"}, $opt_l);
	$footer =~ s/\001/\n/g;
	print OUT $footer;
}

close(OUT);

if ( defined($opt_I) && defined($from) && ! defined($approved) ) {
    local($infile) = 0;
 
    @files = split (/[:\t\n]+/, $opt_I);
 
    foreach $file (@files) {
	if ($file !~ /^\//) {
	    $file = "$listdir/$file";
	}
        if ( open (LISTFD, "<${file}") != 0 ) {
	    @output = grep (&addr_match($from, $_), <LISTFD>);
            close (LISTFD);
   
            if ( $#output != -1 ) {
                $infile = 1;
                last;
            }
        } else {
	    die("resend: Can't open $file: $!");
	}
    }
 
    if ( $infile == 0 ) {
        &bounce ("Non-member submission from [$from]");
    }
}

if (defined($opt_A) && ! defined($approved)) {
    &bounce("Approval required");
}
 
$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 {
    local(*MAILOUT, *MAILIN, @mailer);
    @mailer = split(' ', "$sendmail_cmd");
    open(MAILOUT, "|-") || &do_exec_sendmail(@mailer);
    open(MAILIN, "/tmp/resend.$$.out");
    while (<MAILIN>) {
      print MAILOUT $_;
    }
    close(MAILOUT);
    close(MAILIN);
    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 {
    local(@mailer) = split(' ',"/usr/lib/sendmail -f$sendmail_sender -t");
       open(MAIL, "|-") || &do_exec_sendmail(@mailer);
    }

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

EOM

    return;
}

sub do_exec_sendmail {
    exec(@_, "");
    die("Failed to exec mailer \"@_\": $!");
}
