package Parp::Blacklist;

=head1 NAME

Parp::Blacklist - Look up IP addresses on an internet blacklist via DNS

=head1 SYNOPSIS

Used internally; see L<Parp::Mail::Tests::Header>.

=head1 DESCRIPTION

Contains internal routines for determining whether IP addresses are
blacklisted.

=cut

use strict;
use warnings;

use Socket;

use base qw(Exporter);
our @EXPORT_OK = qw(blacklist_lookup);

sub blacklist_lookup {
  my ($ip) = @_;
  
  my @octets = split /\./, $ip;
  my $name = (join '.', reverse @octets) . '.relays.ordb.org';

  my $naddr = gethostbyname($name) or return 0;
  my $A_RR = inet_ntoa($naddr);
  return 0 unless $A_RR eq '127.0.0.2';

  my $TXT = '';

  if (Net::DNS::Resolver->can('new')) {
    my $resolver = Net::DNS::Resolver->new;
    my $reply = $resolver->query($name, "TXT");
    if ($reply) {
      foreach my $rr ($reply->answer) {
        next unless $rr->type eq "TXT";
        $TXT = $rr->txtdata;
      }
#      print "string: ", $reply->string, "\n";
    } else {
      my $error = $resolver->errorstring;
      print "lookup of $name failed: $error\n"
        unless $error eq 'NOERROR'; # huh?
    }
  }
  else {
#   vprint "Net::DNS not loaded; won't find out TXT RR\n";
  }

  return $TXT || 1;
}

1;
