#!/usr/bin/perl
#
# Sendmail "program" map script to rewrite envelope-from
# address to SRS0 address. Called from macro EnvFromSMTP.
#
# Code by Mark Kramer <admin@asarian-host.net>
#
# Version 0.30
#
# Last revision: March 24, 2004
#
# Licensed under GPL
#
# For detailed installation notes, read:
#
#           http://asarian-host.net/srs/sendmailsrs.htm
#
# See also: http://www.anarres.org/projects/srs/
#           http://spf.pobox.com/
#
# This version requires at least Sendmail 8.12.10 + Mail::SRS 0.30



use Mail::SRS;
use strict;

# No funny business in our output, please

close (STDERR);

my $old_address = $ARGV[0];
my $secret = 'REDACTED';
my ($new_address, $use_address);
my $fwdomain = 'REDACTED';
my $srs = new Mail::SRS (Secret => $secret, HashLength => 8, AlwaysRewrite => 1);

###
open(my $fh, '>>', '/tmp/mylog.txt');
print $fh "$old_address\n";
close $fh;
###

# Our original envelope-from may look funny on entry
# of this Ruleset:
#
#     admin<@asarian-host.net.>
#
# We need to preprocess it some:

   ($use_address = $old_address) =~ s/[<>]//g;
    $use_address =~ s/\.$//g;

# Here, at EnvFromSMTP, we do not loop our address through an
# extra IsSrs macro: we want SRS1 forwarding functionality!
# (relaying reversed third-party SRS1 addresses is a
# different story, though; but here we just allow for SRS0
# addresses to be promoted to SRS1 ones).
#
# Ok, first check whether we already have a signed SRS address;
# if so, just return the old address: we do not want to double-sign
# by accident! (Non-locally generated SRS0 addresses, by nature
# of the protocol, will not 'eval'; so, they will simply become
# SRS1 addresses. Thus, only locally generated SRS0 addresses are
# exempted from double-signing.)
#
# Else, gimme a valid SRS signed address, munge it back the way
# sendmail wants it at this point; or just return the old address,
# in case nothing went.

if (eval {$new_address = $srs -> reverse ($use_address)}) {
    print "$old_address\n";
} elsif (eval {$new_address = $srs -> forward ($use_address, $fwdomain)}) {
    $new_address .= '.>';
    $new_address =~ s/\@/<@/;
    print "$new_address\n";
} else {
    print "$old_address\n";
}

exit 0;
