How do I make DNS lookups in the filter faster?
Since MIMEDefang 3.8 every worker has a shared DNS resolver (md_shared_resolver) and a
cache: md_dns_query keeps definitive answers for their TTL (at most five minutes,
NXDOMAIN and empty answers for one minute) and never caches timeouts or SERVFAIL. The
built-in SPF and DKIM checks already use it; use it in your own lookups too. DNS
blocklist answers are never cached.
# md_dns_query and md_shared_resolver are exported on request
use Mail::MIMEDefang::Net qw(:DEFAULT md_dns_query md_shared_resolver);
sub filter_sender {
my ($sender, $ip, $hostname, $helo) = @_;
my $domain = $sender;
$domain =~ s/^<?.*\@//;
$domain =~ s/>$//;
# Cached in the worker: the next message from the same domain
# does not hit the DNS again. 'send' returns the packet even
# for NXDOMAIN, so a DNS failure can be told apart from it.
my %found;
foreach my $type (qw(MX A AAAA)) {
my $pkt = md_dns_query(undef, $domain, $type, 'send');
return ('TEMPFAIL', "Cannot resolve $domain, try again later")
if !$pkt || $pkt->header->rcode !~ /^(?:NOERROR|NXDOMAIN)$/;
$found{$type} = grep { $_->type eq $type } $pkt->answer;
}
if (!$found{MX} && !$found{A} && !$found{AAAA}) {
return ('REJECT', "Domain $domain does not accept mail");
}
# Every TXT record, or only the ones matching a pattern
my @spf = md_dns_txt(md_shared_resolver(), $domain, qr/^v=spf1\b/i);
# MX host addresses, lowest preference first
my @mx_ips = get_mx_ip_addresses($domain, undef, 1);
return ('CONTINUE', 'ok');
}
md_dns_query has the same return values as the query (default), send or bgsend
method of Net::DNS::Resolver. The returned packets may be shared with other callers: treat them as
read-only.