#!/usr/bin/perl -w
#
# fwdmail:
# Forward mail with an empty return-path, so that it does not generate a
# bounce. Relies on the local mailer daemon being happy to relay for us.
#
# Copyright (c) 2001 Chris Lightfoot. All rights reserved.
#

my $rcsid = '$Id: fwdmail,v 1.3 2002/05/31 18:23:11 chris Exp $';

use IO::Socket;

@addresses = @ARGV;

# get_smtp_response:
# Get a response from the SMTP server, perhaps including continuation lines.
sub get_smtp_response ($) {
    my $h = shift;
    my ($line, $code, $resp);

    do {
        $line = $h->getline();
        $line =~ s/[$cr$lf]+$//;

        if ($line =~ /^([0-9]{3})/) {
            $code = $1;
        }
        if (defined($resp)) {
            $resp .= "\n " . substr($line, 4);
        } else {
            $resp = substr($line, 4);
        }
    } while ($line =~ /^[0-9]{3}-/);

    return ($code, $resp);
}

$cr = "\015";
$lf = "\012";

$sock = new IO::Socket::INET("localhost:smtp");
if (!defined($sock)) {
    print STDERR "fwdmail: $!";
    exit 1;
}

my ($code, $resp);

($code, $resp) = get_smtp_response($sock);
if ($code != 220) {
    print STDERR "fwdmail: smtp connect: $code $resp\n";
    $sock->print("QUIT$cr$lf");
    exit 1;
}

$sock->print("HELO localhost$cr$lf");
($code, $resp) = get_smtp_response($sock);
if ($code > 299) {
    print STDERR "fwdmail: HELO localhost: $code $resp\n";
    $sock->print("QUIT$cr$lf");
    exit 1;
}

$sock->print("MAIL FROM: <>$cr$lf");
($code, $resp) = get_smtp_response($sock);
if ($code > 299) {
    print STDERR "fwdmail: MAIL FROM <>: $code $resp\n";
    $sock->print("QUIT$cr$lf");
    exit 1;
}

foreach (@addresses) {
    $sock->print("RCPT TO: $_$cr$lf");
    ($code, $resp) = get_smtp_response($sock);
    if ($code > 299) {
        print STDERR "fwdmail: RCPT TO: $_: $code $resp\n";
        $sock->print("QUIT$cr$lf");
        exit 1;
    }
}

$sock->print("DATA$cr$lf");
($code, $resp) = get_smtp_response($sock);
if ($code != 354) {
    print STDERR "fwdmail: DATA: $code $resp\n";
    $sock->print("QUIT$cr$lf");
    exit 1;
}

$k = 0;

while ($_ = <STDIN>) {
    chomp;
    if ($k || !/^From /) {
        s/^\./../;
        $sock->print("$_$cr$lf");
    }
    $k = 1;
}

$sock->print(".$cr$lf");

($code, $resp) = get_smtp_response($sock);
if ($code > 299) {
    print STDERR "fwdmail: mail to send: $code $resp\n";
    $sock->print("QUIT$cr$lf");
    exit 1;
}

$sock->print("QUIT$cr$lf");
($code, $resp) = get_smtp_response($sock);
if ($code != 221) {
    print STDERR "fwdmail: QUIT: $code $resp\n";
    exit 1;
}

exit 0;
