#!perl -w
=head1 NAME

forcespamcheck - SpamAssassin integration for qpsmtpd

=head1 DESCRIPTION

Plugin that forces check if the mail is spam by using the "spamd" daemon
from the SpamAssassin package.  F<http://www.spamassassin.org>

=head1 CONFIG
This plugins needs spamassassin like arguments
Refer to spamassassin plugin 

On top of that it uses a config file with an ip per line corresponding of
local_ip of the qpsmtpd server on which the remote client is trying to deliver
the mail. Please be cautious this is not the remote client ip !
THe initial idea is to force spam check for some deamons by making them 
sending to 127.0.0.200:25 so other daemons trying to deliver on 127.0.0.1:25
or LAN client delivering on 192.168.0.1:25 will avoid the spam check, unless you 
also specify those ips in forcespamcheck file.

=cut

use strict;
use warnings;
use Qpsmtpd::Constants;
use Qpsmtpd::DSN;
use Socket qw(:DEFAULT :crlf);
use IO::Handle;

sub register {
    my ($self, $qp, %args) = @_;
    $self->log(LOGERROR, "Bad parameters for the forcespamcheck plugin")
      if @_ % 2;
    #first if spamassassin already loaded return DECLINED; not to load it twice
    my @datahooked = $qp->hooks('data_post');
    for my $item (@datahooked) {
	 $self->log(LOGNOTICE,"spamassassin aleady loaded") if $item->{name} eq "spamassassin";
	 return DECLINED  if $item->{name} eq "spamassassin";
    }
    # else we can go on
    my $param = join(q{ }, map{qq{$_ $args{$_}}} keys %args); 
    my $ip = $self->qp->connection->local_ip;
    # read here list of ip from file; or default on 127.0.0.200
    my %forcespamcheck = map { $_ => 1 } $self->qp->config('forcespamcheck');
    # we force spamcheck on 127.0.0.200 as used by fetchmail
    $forcespamcheck{'127.0.0.200'} = 1; 
    return DECLINED unless (exists $forcespamcheck{$ip});
    my $plugin_line = "spamassassin " . $param;
    my $this_plugin = $self->qp->_load_plugin($plugin_line, $self->qp->plugin_dirs);
    $self->register_hook('data', 'data_handler');
}

sub data_handler {
    my ($self, $transaction) = @_;
    my $ip = $self->qp->connection->local_ip;
    # logged only there to avoid double line in log in register.
    $self->log(LOGINFO,
                   "forcing spamassassin check for connection on $ip");
}
