#!/usr/bin/perl

eval 'exec /usr/bin/perl  -S $0 ${1+"$@"}'
    if 0; # not running under some shell

use Getopt::Std;

use FindBin;

BEGIN {
  # This code will track down the directories where WebMake
  # keeps its modules, portably, so it'll work on Macs, UNIX and Win32,
  # with or without a UNIX-style "make install" installation.
  # Sadly, we can't rely on File::Spec to do the slash-twiddling for us;
  # it's not included with some versions of MacPerl. :(
  #
  my $bin = $FindBin::Bin;
  my $slash = '/';              # between directories in a path
  my $dirtrailer = '';          # at the end of a directory's path

  if ($^O eq 'MacOS') {
    $slash = ':'; $dirtrailer = ':';
  } elsif ($^O =~ /(win|os2)/) {
    $slash = '\\';
  }

  # first, find the common candidates: "lib" and "site_perl" in
  # the same dir as the script. These are likely on all platforms.
  $_ = $bin.$slash. "lib" . $dirtrailer;
  push (@INC, $_);
  $_ = $bin.$slash. "site_perl" . $dirtrailer;
  push (@INC, $_);

  # next, support UNIX-style /usr-based installation, where the
  # script lives in /usr/*/bin and the support files in /usr/*/lib
  # or /usr/*/share. This only happens on UNIX afaik.
  if ($slash eq '/') {
    $_ = $bin . "/../lib/spamassassin";
    if (-d $_) {
      push (@INC, "$_/lib"); push (@INC, "$_/site_perl");
    }

    $_ = $bin . "/../share/spamassassin";
    if (-d $_) {
      push (@INC, "$_/lib"); push (@INC, "$_/site_perl");
    }
  }
}

use lib 'lib';
use lib '../lib';		# for testing in ./t

sub usage {
  my $ver = Mail::SpamAssassin::Version();
  my $rules = join ("\n\t\t\t\t", @Mail::SpamAssassin::default_rules_path);
  my $prefs = join ("\n\t\t\t\t", @Mail::SpamAssassin::default_userprefs_path);
  warn <<EOUSAGE;

Usage: spamassassin [option ...] < mailmessage
       spamassassin -P [option ...] < mailmessage > output

Options:

  -a               Use auto-whitelists
  -h		   print this help and terminate without further action
  -P               pipe message through, instead of delivering to mail spool
  -e               Exit with a non-zero exit code for spam messages
  -t               only testing; pipe message through and add extra report
  -r               mail message is verified as spam, report it
  -W               add all addresses in mail (from stdin) to whitelist
  -R               remove all addresses in mail (from stdin) from whitelist
  -F 0|1           remove/add 'From ' line at start of output (default: 1)
  -w fromaddr	   send a warning mail back to the sender of the message,
                   notifying them that their message has been marked as spam
		   (only useful if -r is used)
  -l filename      Log all mail messages to a mbox-format file
  -L               Local tests only, do not do internet-based checks
  -S               Stop testing when spam threshold is reached
  -d		   Remove SpamAssassin reports from a mail message and print
  -c config        configuration file
                   (default:	$rules )
  -p prefs         user preferences file
                   (default:	$prefs )
  -D		   log diagnostic messages

Version: $ver      Home: http://spamassassin.org/

EOUSAGE
  exit 64;		# == EX_USAGE
}


use vars qw{
  $opt_t $opt_c $opt_p $opt_h $opt_V $opt_D $opt_r $opt_P $opt_w $opt_l
  $opt_d $opt_L $opt_e $opt_W $opt_M $opt_R $opt_F $opt_a $opt_S
};

eval {
  require Mail::SpamAssassin;
  require Mail::SpamAssassin::NoMailAudit;

  getopts ('atc:p:ehVDrPw:l:dLSWRM:F:') or usage();

  if (defined $opt_h) { usage(); }
  if (defined $opt_V) {
    my $ver = Mail::SpamAssassin::Version();
    print <<EOVERSION;
SpamAssassin version $ver
EOVERSION
    exit 0;
  }

# 1.
# Standard Mail::Audit start.  No longer used due to bugs in M:A, regarding
# handling of slightly misformatted input.
#
# require Mail::Audit;
# my $mail = Mail::Audit->new();

# 2.
# Workaround Mail::Audit start.  No longer needed, since
# Mail::SpamAssassin::NoMailAudit provides the Mail::Audit features
# we need more efficiently and reliably.
#
#my @msglines = (<STDIN>);
#pre_chew_for_mail_audit (\@msglines);
#require Mail::SpamAssassin::MyMailAudit;
#my $mail = Mail::SpamAssassin::MyMailAudit->new ( data => \@msglines ); 

# 3.
# No use of Mail::Audit at all, apart from the accept(), reject() and
# resend() methods (which are proxied transparently).  Lovely.
#
use Mail::SpamAssassin::NoMailAudit;
my $mail = Mail::SpamAssassin::NoMailAudit->new ( add_From_line => $opt_F );

# For Mail::Audit users -- this is the magic. Just create a Mail::SpamAssassin
# object like this, then run the check() method as below; if it returns a
# non-undef value, then you've got spam, otherwise it's normal mail.
#
# You can then use the rewrite() method (passing in the Mail::Audit object) to
# rewrite the spam.
#
# (This implementation does other stuff though, such as -t support; ignore that
# stuff.)

# create the tester factory
  my $spamtest = new Mail::SpamAssassin ({
    'rules_filename'	=> $opt_c,
    'userprefs_filename' => $opt_p,
    'local_tests_only'	=> $opt_L,
    'stop_at_threshold' => $opt_S,
    'debug'		=> $opt_D
  });

# handle logging of received mails
  if ($opt_l) {
    $mail->{noexit} = 1;
    $mail->accept ($opt_l);
    $mail->{noexit} = 0;
  }

# handle removing reports
  if ($opt_d) {
    print $spamtest->remove_spamassassin_markup ($mail);
    $mail->ignore();		# will exit
  }

# handle unconditional reportage
  if ($opt_r) {
    $spamtest->report_as_spam ($mail);
    if ($opt_w) {
      $spamtest->reply_with_warning ($mail, $opt_w);
    }
    if ($opt_l) {
      $mail->{noexit} = 1;
      $mail->accept ($opt_l);
      $mail->{noexit} = 0;
    }
    $mail->ignore();		# will exit
  }

($opt_a or $opt_R or $opt_W) and eval
{
  # create a factory for the persistent address list.
  # choose one of these implementations!
  # The -M "Mail::SpamAssassin::ImplClassAddrList" flag can be used
  # to switch between them.

  my $addrlistfactory;
  if (defined $opt_M) {
    eval '
      require '.$opt_M.'; $addrlistfactory = '.$opt_M.'->new();
    ';
    if ($@) { warn $@; undef $addrlistfactory; }

  } else {

    require Mail::SpamAssassin::DBBasedAddrList;
    $addrlistfactory = Mail::SpamAssassin::DBBasedAddrList->new();

  }

  $spamtest->set_persistent_address_list_factory ($addrlistfactory);
};

  if ($opt_W) {
    $spamtest->add_all_addresses_to_whitelist ($mail);
    if ($opt_l) {
      $mail->{noexit} = 1;
      $mail->accept ($opt_l);
      $mail->{noexit} = 0;
    }
    $mail->ignore();		# will exit
  }

  if ($opt_R) {
    $spamtest->remove_all_addresses_from_whitelist ($mail);
    if ($opt_l) {
      $mail->{noexit} = 1;
      $mail->accept ($opt_l);
      $mail->{noexit} = 0;
    }
    $mail->ignore();		# will exit
  }

# not reporting? OK, do checks instead.  Create a status object which
# holds details of the message's spam/not-spam status.
  my $status = $spamtest->check ($mail);
  $status->rewrite_mail ();
  $status->handle_auto_report ();

  if ($opt_t) {
    # add the spam report to the end of the body as well, if testing.
    my $lines = $mail->body();
    push (@{$lines}, split (/$/, $status->get_report()));
    $mail->body ($lines);
  }

# if we're piping it, deliver it to stdout.
  if ($opt_t || $opt_P) {
    print $mail->header(), "\n", join ('', @{$mail->body()});
    if ($opt_e && $status->is_spam ()) { exit 5; }
    exit;
  }

# else, store it to the mail spool (thx to Mail::Audit)
# $MAIL: std on unix
# $DEFAULT: set by procmail
  my $where = $ENV{'MAIL'} || $ENV{'DEFAULT'} || undef;
  $mail->accept($where);
  if ($opt_e && $status->is_spam ()) { exit 5; }
  exit;
};

if ($@) {	
  # eval failed; we died somewhere in there.
  warn $@;
  exit 70;		# == EX_SOFTWARE in sysexits.h. caught by MTA
}

# check for an assortment of crap that Mail::Audit cannot deal with: DOS
# line-endings, extra 'From ' lines, etc.
#
sub pre_chew_for_mail_audit {
    my ($msglines) = @_;

    my @newhdrs = (); while ($_ = shift (@{$msglines})) {
      /^From / and next;	# may fix the #1 M:A bug ;)
      s/\r\n/\n/s;		# clean off \r\n's
      push (@newhdrs, $_);
      /^$/ and last;
    }

    unshift (@{$msglines}, @newhdrs);
}


# this is never called, it's just used to shut up the warnings
sub NEVERCALLED {
  @Mail::SpamAssassin::default_rules_path =
  			@Mail::SpamAssassin::default_userprefs_path;
}

# ---------------------------------------------------------------------------

=head1 NAME

spamassassin - mail filter to identify spam using text analysis

=head1 SYNOPSIS

=over

=item spamassassin [option ...] < mailmessage

=item spamassassin -P [option ...] < mailmessage > output

=back

=head1 OPTIONS

=over 4

=item B<-P>

Normally SpamAssassin will write the rewritten message to the mail spool by
default.  The B<-P> parameter will cause it to pipe the output to STDOUT
instead.

=item B<-a>

Use auto-whitelists.  These will automatically create a list of
senders whose messages are to be considered non-spam by monitoring the total
number of received messages which weren't tagged as spam from that sender.
Once a threshold is exceeded, further messages from that sender will be given a
non-spam bonus (in case you correspond with people who occasionally swear in
their emails).

=item B<-e>

Exit with a non-zero error code, if the message is determined to be
spam.

=item B<-h>

Print help message and exit.

=item B<-t>

Test mode.  Pipe message through and add extra report.

=item B<-r>

Report this message as verified spam.  This will submit the mail message read
from STDIN to various spam-blocker databases, such as Vipul's Razor (
http://razor.sourceforge.net/ ).

If the message contains SpamAssassin markup, this will be stripped out
automatically before submission.

=item B<-W>

Add all email addresses, in the headers and body of the mail message read from
STDIN, to the automatic whitelist.

=item B<-R>

Remove all email addresses, in the headers and body of the mail message read
from STDIN, from the automatic whitelist.

=item B<-F> I<0 | 1>

Ensure that the output email message either always starts with a 'From ' line
(I<1>) for UNIX mbox format, or ensure that this line is stripped from
the output (I<0>).  (default: 1)

=item B<-w> I<fromaddr>

This flag is only useful in conjunction with B<-r>.  It will send a reply mail
to the sender of the tested mail, notifying them that their message has been
trapped as spam, from the address supplied in I<fromaddr>.  See L</SPAM TRAPPING>.

=item B<-l> I<filename>

Log all mail messages that pass through the filter, to an mbox-format file
named by I<filename>.  Handy for use with B<-r> and B<-w>.

=item B<-L>

Do only the ''local'' tests, ones that do not require an internet connection to
operate.  Normally, SpamAssassin will try to detect whether you are connected
to the net before doing these tests anyway, but for faster checks you may wish
to use this.

=item B<-S>

Stop spam checking as soon as the spam threshold is reached, to increase
performance. This option also turns off Razor reporting.

=item B<-d>

Remove SpamAssassin markup (the "SpamAssassin results" report, X-Spam-Status
headers, etc.) from the mail message.  The resulting message, which will be
more or less identical to the original, pre-SpamAssassin input, will be output
to stdout.

(Note: the message will not be exactly identical; some headers will be
reformatted due to some features of the Mail::Internet package, but the body
text will be.)

=item B<-c> I<config>

Read configuration from I<config>.

=item B<-p> I<prefs>

Read user score preferences from I<prefs>.

=item B<-D>

Produce diagnostic output.

=back

=head1 DESCRIPTION

SpamAssassin is a mail filter to identify spam using text analysis and several
internet-based realtime blacklists.

Using its rule base, it uses a wide range of heuristic tests on mail headers
and body text to identify "spam", also known as unsolicited commercial email.

Once identified, the mail is then tagged as spam for later filtering using the
user's own mail user-agent application.

SpamAssassin also includes support for reporting spam messages to collaborative
filtering databases, such as Vipul's Razor ( http://razor.sourceforge.net/ ).

The default tagging operations that take place are detailed in L</TAGGING>.

=head1 CONFIGURATION FILES

The rule base, text templates, and rule description text are loaded from the
configuration files.

By default, configuration data is loaded from the first existing directory in:
F</usr/local/share/spamassassin>;F</usr/share/spamassassin>;F<./rules>;F<../rules>

The configuration data in the first existing directory in:
F</usr/local/etc/spamassassin>;F</usr/pkg/etc/spamassassin>;F</usr/etc/spamassassin>;F</etc/mail/spamassassin>;F</etc/spamassassin>
are used to override any values which had already been set

Spamassassin will read *.cf in these directories, in alphanumeric order within each directory
(similar to SysV-style startup scripts).  In other words, it will read F<10_misc.cf> before F<50_scores.cf> and F<20_body_tests.cf> before F<20_head_test.cf>.  Options in later files will override earlier files.

The user preferences (such as scores to attach to each rule), are loaded from
the file specified in the B<-p> argument.  If this is not specified,
F<~/.spamassassin/user_prefs> is used if it exists.  C<spamassassin> will create this
file if it does not exist, using F<user_prefs.template> as a template.  This file will be looked for in 
F</etc/spamassassin/user_prefs.template>;F</usr/local/share/spamassassin/user_prefs.template>;F</usr/share/spamassassin/user_prefs.template>

=head1 TAGGING

The following two sections detail the tagging that takes place for
spam messages, first of all, and for non-spam messages.

Note that if you use the B<-t> argument, all mails will be tagged
as if they are spam messages.

=head2 TAGGING FOR SPAM MAILS

The modifications made are as follows:

=over 4

=item Subject: header

The string C<*****SPAM*****> is prepended to the subject,
unless the C<rewrite_subject 0> configuration option is given.

=item X-Spam-Status: header

A string, C<Yes, hits=nn required=nn> is set in this header to reflect
the filter status.

=item X-Spam-Flag: header

Set to C<YES>.

=item X-Spam-Report: header for spam mails

The SpamAssassin report is added to the mail header if
the C<report_header = 1> configuration option is given.

=item Content-Type: header

Set to C<text/plain>, in order to defang HTML mail or other active
content that could "call back" to the spammer.

=item spam mail body text

The SpamAssassin report is added to top of the mail message body,
unless the C<report_header 1> configuration option is given.


=back

=head2 TAGGING FOR NON-SPAM MAILS

=over 4

=item X-Spam-Status: header

A string, C<No, hits=nn required=nn> is set in this header to reflect
the filter status.

=back

=head1 SPAM TRAPPING

Quite often, if you've been on the internet for a while, you'll have
accumulated a few old email accounts that nowadays get nothing but
spam.

SpamAssassin lets you set them up as aliases, as follows:

=over 4

=item spamtrap1: "| /path/to/spamassassin -r -w spamtrap1"

=back

This will add any incoming mail messages straight into spam-tracking databases,
such as Vipul's Razor; send an explanatory reply message to the sender, from
the I<spamtrap1> address; then drop the mail into the bit-bucket.

The explanatory reply text is taken from the SpamAssassin configuration file,
where it is stored in the C<spamtrap> lines.

If you want to keep a copy of the mails, use something like this:

=over 4

=item spamtrap1: "| /path/to/spamassassin -r -w spamtrap1 -l /var/spam/caught"

=back

It is suggested you familiarise yourself with how MTAs run programs specified
in aliases, if you plan to do this; for one thing, B<spamassassin> will not run
under your user id in this case.  If you are nervous about this, create a user
for spamtrapping, and set up spamassassin in its F<.forward> file.

=head1 INSTALLATION

The B<spamassassin> command is part of the B<Mail::SpamAssassin> Perl module.
Install this as a normal Perl module, using C<perl -MCPAN -e shell>, or by
hand.

=head1 ENVIRONMENT

No environment variables, aside from those used by perl, are required to
be set.

=head1 SEE ALSO

Mail::SpamAssassin(3)
Mail::Audit(3)
Razor(3)

=head1 AUTHOR

Justin Mason E<lt>jm /at/ jmason.orgE<gt>

=head1 PREREQUISITES

C<Mail::Audit>

=head1 COREQUISITES

C<Net::DNS>
C<Razor>

=cut

