#!/usr/bin/perl
# Integrity/data-correctness checker
##
# $Id$
# Copyright 2009-2011 Kris Deugau <kdeugau@deepnet.cx>
# 
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version. 
# 
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
# 
#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
##

use strict;
use warnings;
use DBI;

use DNSBL;

my $dnsbl = new DNSBL;

# default DB info - all other settings should be loaded from the DB.
my $dbhost = "localhost";
my $dbname = "dnsbl";
my $dbuser = "dnsbl";
my $dbpass = "spambgone";

die "Need config argument\n" if !$ARGV[0];
my $cfgname = shift @ARGV;

# Load a config ref containing DB host, name, user, and pass info based on
# from the server name + full script web path.  This allows us to host
# multiple instances without having to duplicate the code.
# This file is a Perl fragment to be processed inline.
if (-e "/etc/dnsbl/$cfgname.conf") {
  my $cfg = `cat /etc/dnsbl/$cfgname.conf`;
  ($cfg) = ($cfg =~ /^(.+)$/s);         # avoid warnings, failures, and general nastiness with taint mode
  eval $cfg;
}

my $dbh = $dnsbl->connect($dbhost, $dbname, $dbuser, $dbpass);

print "checking IP containment...\n";
my $sth = $dbh->prepare("select ip from iplist order by ip");
$sth->execute;
my $cksth = $dbh->prepare("select block from blocks where block >> ?");
while (my @data = $sth->fetchrow_array) {
  $cksth->execute($data[0]);
  print "$data[0] has no container\n" if $cksth->rows == 0;
}

print "checking level 2 blocks...\n";
$sth = $dbh->prepare("select block from blocks where level=2");
$sth->execute;
$cksth = $dbh->prepare("select block from blocks where block >> ? and level=1");
while (my @data = $sth->fetchrow_array) {
  $cksth->execute($data[0]);
  print "$data[0] has no container\n" if $cksth->rows == 0;
}

print "checking level 1 blocks...\n";
$sth = $dbh->prepare("select block from blocks where level=1");
$sth->execute;
$cksth = $dbh->prepare("select block from blocks where block >> ? and level=0");
while (my @data = $sth->fetchrow_array) {
  $cksth->execute($data[0]);
  print "$data[0] has no container\n" if $cksth->rows == 0;
}

print "checking for empty blocks\n";
$sth = $dbh->prepare("select block from blocks");
$sth->execute;
$cksth = $dbh->prepare("select ip from iplist where ip << ?");
while (my @data = $sth->fetchrow_array) {
  $cksth->execute($data[0]);
  print "$data[0] has no IPs\n" if $cksth->rows == 0;
}

