snippets

How do I run virus and spam scans in parallel?

Since MIMEDefang 3.8, the virus and spam scanners can be part of an md_async_run_checks batch, so they run at the same time: the message waits for the slowest scanner instead of for the sum of all of them. The check builders are md_async_check_clamd (local clamd), md_async_check_clamdscan (local or remote clamd), md_async_check_spamc and md_async_check_rspamd.

use Mail::MIMEDefang::Async;
use Mail::MIMEDefang::Async::Checks;
use Mail::MIMEDefang::Async::Results;

sub filter_end {
    my ($entity) = @_;

    # The batch timeout must cover the slowest scan
    md_async_init(global_timeout => 60);
    my $out = md_async_run_checks([
        md_async_check_clamd(sock => '/run/clamd.scan/clamd.sock'),
        md_async_check_spamc(host => '127.0.0.1', port => 783),
    ]);

    my $av = md_async_interpret_clamav(raw   => $out->{results}{clamd},
                                       error => $out->{errors}{clamd});
    my $spam = md_async_interpret_spamassassin(raw   => $out->{results}{spamc},
                                               error => $out->{errors}{spamc});

    return action_tempfail('Virus scan failed, please retry') if $av->{error};
    if ($av->{virus}) {
        md_graphdefang_log('virus', $av->{name}, $RelayAddr);
        return action_bounce("Message rejected: virus detected ($av->{name})");
    }

    if (!$spam->{error}) {
        action_change_header('X-Spam-Score', "$spam->{score} / $spam->{threshold}");
        action_change_header('X-Spam-Flag', $spam->{is_spam} ? 'YES' : 'NO');
    }
}

md_async_check_clamd sends an nSCAN of the work directory, so clamd must run on the same host; use md_async_check_clamdscan(conf => '/etc/clamd.d/remote.conf') for a remote clamd. An unrecognized clamd reply is reported as an error, never as clean.