=head1 NAME

autowhitelist_relayrcpt

=head1 DESCRIPTION

Plugin to implement automatic whitelisting for relayclient recipients
by adding them (if necessary) to the 'whitelistsenders' config file.
Should be called before the 'whitelist' or 'whitelist_soft' plugin.

Useful, for example, where you are using a denysoft plugin of some kind
in conjunction with whitelisting and don't want replies to your emails
to be delayed.

=head1 BUGS

Whitelisting recipients is obviously likely to be a fairly bad idea 
unless that list is reasonably small i.e. don't try this if you're an
ISP of any size. :-)

=head1 AUTHOR

Written by Gavin Carr <gavin@openfusion.com.au>.

=cut

my ($QPHOME) = ($0 =~ m!(.*?)/([^/]+)$!);
my $SENDERS = "$QPHOME/config/whitelistsenders";

sub register {
  my ($self, $qp, %arg) = @_;
  $self->register_hook("rcpt", "rcpt_handler");
}

sub rcpt_handler {
  my ($self, $transaction, $rcpt) = @_;
  my $addr = lc $rcpt->address or return (DECLINED);
  my $host = lc $rcpt->host or return (DECLINED);

  if (exists $ENV{RELAYCLIENT}) {
    # Check whether already whitelisted
    for my $sender ($self->qp->config('whitelistsenders')) {
      next unless $sender;
      $sender = lc $sender;
 
      if ($sender eq $addr || $sender eq $host) {
        $self->log(4,"recipient $addr in whitelistsenders");
        return (DECLINED);
      }
    }

    # Not found - append recipient
    if (!open SENDERS, ">>$SENDERS") {
      $self->log(2,"unable to append to whitelistsenders");
      return (DECLINED);
    }
    print SENDERS "$addr\n";
    close SENDERS;
    $self->log(2,"recipient $addr added to whitelistsenders");
  }

  return (DECLINED);
}

# arch-tag: 85745975-0278-41c4-9d88-210379364f9a
