#!/usr/bin/perl
# Main add-IP-to-list CGI
##
# $Id: dnsbl.cgi 60 2015-03-10 16:26:24Z kdeugau $
# Copyright 2009-2011,2014 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;
no warnings qw(uninitialized);
use CGI::Carp qw (fatalsToBrowser);
use CGI::Simple;
use HTML::Template;

use DNSBL;
use DNSBLweb;

# Set up the CGI object...
my $q = new CGI::Simple;
# ... and get query-string params as well as POST params if necessary
$q->parse_query_string;

my %webvar;
# This is probably excessive fiddling, but it puts the parameters somewhere my fingers know about...
foreach ($q->param()) {
  $webvar{$_} = $q->param($_);
}

my $dnsbl = new DNSBL;
# here be drag'ns, should theoretically be $DNSBL::maxlvl, but we
# only have up to level 4 in the report HTML/template
my $maxlvl = 4;

# try to be friendly to non-US-ASCII characters.  Still need to find what
# difference from RH<->Debian is still at fault.
print $q->header(-charset=>'utf8');

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

# 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.
my $cfgname = $ENV{SERVER_NAME}.$ENV{REQUEST_URI};
$cfgname =~ s|[./-]|_|g;
$cfgname =~ s|_dnsbl_cgi.+||;
$cfgname =~ s|_$||;
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);

my $page;
my $templatedir = $ENV{SCRIPT_FILENAME};
$templatedir =~ s/dnsbl\.cgi//;
$templatedir .= "templates";
$ENV{HTML_TEMPLATE_ROOT} = $templatedir;

my %config;
my $sth = $dbh->prepare("SELECT key,value FROM misc");
$sth->execute;
while (my ($key,$value) = $sth->fetchrow_array) {
  $config{$key} = $value;
}

# decide which page to spit out...
if (!$webvar{page}) {
  $page = HTML::Template->new(filename => "index.tmpl");
} else {
  $page = HTML::Template->new(filename => "$webvar{page}.tmpl");
}

$page->param(pgtitle => $config{pgtitle}) if defined($config{pgtitle});
$page->param(pgcomment => $config{pgcomment}) if defined($config{pgcomment});

if ($webvar{page} eq 'report') {
  my $dnsblsiteroot = $ENV{REQUEST_URI};
  $dnsblsiteroot =~ s|/dnsbl\.cgi\?.+|/|;
  $page->param(dnsblsiteroot => $dnsblsiteroot);

  $webvar{ip} =~ s/^\s*//;
  $webvar{ip} =~ s/\s*$//;
  $page->param(ip => $webvar{ip});
  my $count = $dnsbl->ipexists($webvar{ip});
  $page->param(nreports => $count) if $count;
  $page->param(browsebits =>
	DNSBLweb::retlvl($dbh, $dnsbl, 0, ip => $webvar{ip}, block => $dnsbl->getcontainer($webvar{ip},0) ));
  for (my $i=0; $i <= $maxlvl; $i++) {
    my ($block,$org) = $dnsbl->getcontainer($webvar{ip},$i);
    if ($block) {
      my ($bcl,$bal) = $dnsbl->islisted($block);
      $page->param("autob$i" => $bcl);
      $page->param("listb$i" => $bal);
      my ($ol) = $dnsbl->islisted($org);
      $page->param("listorg$i" => $ol);
      $page->param("block$i" => $block);
      $page->param("org$i" => $org);
    }
  }
} elsif ($webvar{page} eq 'dbreport') {
  my $dnsblsiteroot = $ENV{REQUEST_URI};
  $dnsblsiteroot =~ s|/dnsbl\.cgi\?.+|/|;
  $page->param(dnsblsiteroot => $dnsblsiteroot);

  my $err = '';

  $webvar{ip} =~ s/^\s*//;
  $webvar{ip} =~ s/\s*$//;

  # basic algo:  for each listing level, add the org and block if not already present.
  # escape the loop if we check a level with no block entered.

  # there are still error checks that should probably be done.  changes in block
  # level/parenting should also Just Work(TM), rather than requiring setparents.pl
  # or setparents-full.pl
  for (my $i = 0; $i <= $maxlvl; $i++) {
    my $orgn = "org$i";
    my $blockn = "block$i";
    $webvar{$orgn} =~ s/^\s*//;
    $webvar{$orgn} =~ s/\s*$//;
    $webvar{$blockn} =~ s/^\s*//;
    $webvar{$blockn} =~ s/\s*$//;
    my $orgid = $dnsbl->orgexists($webvar{$orgn});
    if (!$orgid) {
      $orgid = $dnsbl->addorg($webvar{$orgn});
      $page->param($orgn => $webvar{$orgn});
    }
    if ($webvar{$blockn} =~ /-/) {
      my $tmp = new NetAddr::IP $webvar{$blockn};
      if (!$tmp) {
        # Don't need to autofind ranges that are already CIDR-matched
        $err .= "Autofinding CIDR block containing $webvar{ip} for range '$webvar{$blockn}': ";
        my ($s,$f) = split /[\s-]+/, $webvar{$blockn};
        my $cidr = $dnsbl->range2cidr($s, $f, $webvar{ip});
        $err .= "$cidr<br>\n";
        $webvar{$blockn} = $cidr;
      }
    }
    if (!$dnsbl->blockexists($webvar{$blockn})) {
      my $ret = $dnsbl->addblock($webvar{$blockn}, $orgid, $i);
      $err .= "error adding $webvar{$blockn}: $ret<br>\n" if $ret;
      $page->param($blockn => $webvar{$blockn});
    }
    last unless $webvar{"block".($i+1)};
  }

  my $count = $dnsbl->report($webvar{ip});

  $page->param(ip => $webvar{ip});
  $page->param(err => $err);

  $page->param(browsebits => 
	DNSBLweb::retlvl($dbh, $dnsbl, 0, ip => $webvar{ip}, block => $dnsbl->getcontainer($webvar{ip},0) ));
}

print $page->output;