#! /usr/bin/perl -w
use lib '/usr/lib/perl'; use INN::Config;

# Author:       James Brister <brister@vix.com> -- berkeley-unix --
# Start Date:   Fri, 25 Apr 1997 14:11:23 +0200
# Project:      INN
# File:         innmail.pl
# Description:  A simple replacement for UCB Mail to avoid nasty security
#               problems.
#

use strict;
use Getopt::Std;

$0 =~ s!.*/!!;

die "$0: No \$INN::Config::mta variable defined.\n"
  if !defined($INN::Config::mta);

my $sm = $INN::Config::mta;

die "$0: MTA path is not absolute\n" unless ($sm =~ m!^/!);

my $usage
  = "usage: $0 -s subject addresses\n\n" . "Reads stdin for message body\n";

my (%opt, @addrs);
getopts("s:h", \%opt) || die $usage;

die $usage if $opt{'h'};

if (!defined($opt{'s'})) {
    warn "No subject given.  Hope that's OK.\n";
    $opt{'s'} = "NO SUBJECT";
} else {
    $opt{'s'} =~ s/\n+\Z//;
}

# Fix up any addresses.
foreach (@ARGV) {
    s![^-a-zA-Z0-9+_.@%]!!g;

    push(@addrs, $_) if ($_ ne "");
}

die "$0: No addresses specified\n\n$usage" unless @addrs;

if ($sm =~ m!%s!) {
    $sm = sprintf $sm, join(' ', @addrs);
} else {
    $sm .= " " . join(' ', @addrs);
}

my @smarr = split(/\s+/, $sm);

(my $t = $INN::Config::mta) =~ s!\s.*!!;
die "$0: MTA variable definition is changed after substitution\n"
  if ($t ne $smarr[0]);

die "$0: MTA excutable doesn't appear to exist: $smarr[0]\n"
  if !-x $smarr[0];

# Startup MTA without using the shell.
my $pid = open my $MTA, '|-';
if ($pid == 0) {
    exec(@smarr) || die "$0: exec of $sm failed: $!\n";
} elsif ($pid < 0) {
    die "$0: Fork failed: $!\n";
}

print $MTA "To: ", join(",\n\t", @addrs), "\n";
print $MTA "Subject: $opt{'s'}\n";
print $MTA "\n";
while (<STDIN>) {
    print $MTA $_;
}
close $MTA;
exit;
