#!/usr/bin/perl
# ipdb/cgi-bin/admin.cgi
# Hack interface to make specific changes to IPDB that (for one reason
# or another) can't be made through the main interface.
#
###
# SVN revision info
# $Date: 2015-03-20 19:14:06 +0000 (Fri, 20 Mar 2015) $
# SVN revision $Rev: 709 $
# Last update by $Author: kdeugau $
###
# Copyright (C) 2004-2010 - Kris Deugau

use strict;
use warnings;
use CGI::Carp qw(fatalsToBrowser);
use CGI::Simple;
use HTML::Template;
use DBI;
#use POSIX qw(ceil);
use NetAddr::IP;

use Sys::Syslog;

# don't remove!  required for GNU/FHS-ish install from tarball
##uselib##

use CustIDCK;
use MyIPDB;

openlog "IPDB-admin","pid","$IPDB::syslog_facility";

# Collect the username from HTTP auth.  If undefined, we're in a test environment.
my $authuser;
if (!defined($ENV{'REMOTE_USER'})) {
  $authuser = '__temptest';
} else {
  $authuser = $ENV{'REMOTE_USER'};
}

syslog "debug", "$authuser active";

# 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;

# Convenience;  saves changing all references to %webvar
##fixme:  tweak for handling <select multiple='y' size=3> (list with multiple selection)
my %webvar = $q->Vars;

# anyone got a better name?  :P
my $thingroot = $ENV{SCRIPT_FILENAME};
$thingroot =~ s|cgi-bin/admin.cgi||;

# Set up some globals
$ENV{HTML_TEMPLATE_ROOT} = $thingroot."templates";

# Why not a global DB handle?  (And a global statement handle, as well...)
# Use the connectDB function, otherwise we end up confusing ourselves
my $ip_dbh;
my $sth;
my $errstr;
($ip_dbh,$errstr) = connectDB_My;
if (!$ip_dbh) {
  $webvar{action} = "dberr";
} else {
  initIPDBGlobals($ip_dbh);
}

if(!defined($webvar{action})) {
  $webvar{action} = "main";   #shuts up the warnings.
}

# handle DB error output
if ($webvar{action} eq 'dberr') {
  my $page = HTML::Template->new(filename => "admin/dberr.tmpl");
  $page->param(errmsg => $errstr);
  print "Content-Type: text/html\n\n".$page->output;
  exit;
}

if ($IPDBacl{$authuser} !~ /A/) {
  my $page = HTML::Template->new(filename => "admin/aclerr.tmpl");
##fixme:  need params for IPDB admin email and name
  $page->param(ipdbadmin_email => 'ipdbadmin@example.com');
  $page->param(ipdbadmin_name => 'the IPDB administrator');
  print "Content-Type: text/html\n\n".$page->output;
  exit;
}

my $header = HTML::Template->new(filename => "admin/header.tmpl");
$header->param(mainpage => 1) if $webvar{action} eq 'main';
$header->param(webpath => $IPDB::webpath);
print "Content-type: text/html\n\n".$header->output;

my $page;
if (-e "$ENV{HTML_TEMPLATE_ROOT}/admin/$webvar{action}.tmpl") {
  $page = HTML::Template->new(filename => "admin/$webvar{action}.tmpl");
} else {
  $page = HTML::Template->new(filename => "admin/dunno.tmpl");
}

# handle index page
if ($webvar{action} eq 'main') {
  my $tlist = getTypeList($ip_dbh, 'a');
  $tlist->[0]->{sel} = 1;
  $page->param(typelist => $tlist);

  my $mlist = getMasterList($ip_dbh, 'm');
  $page->param(masterlist => $mlist);
}

## Non-default actions.

elsif ($webvar{action} eq 'alloc') {

  my $cidr = new NetAddr::IP $webvar{cidr};
  if (!$cidr || "$cidr" =~ /^0/) {
    $page->param(errmsg => "Can't allocate something that's not a netblock/ip");
    goto ERRJUMP;
  }

  my $custid = $def_custids{$webvar{alloctype}};
  if ($custid eq '') {
    # Crosscheck with billing.
    my $status = CustIDCK->custid_exist($webvar{custid});
    if ($CustIDCK::Error) {
      $page->param(errmsg => "Error verifying customer ID: ".$CustIDCK::ErrMsg);
      goto ERRJUMP;
    }
    if (!$status) {
      $page->param(errmsg => "Customer ID not valid.  Make sure the Customer ID ".
	"is correct.<br>\nUse STAFF for staff static IPs, and $IPDB::defcustid for any other ".
	"non-customer assignments.");
      goto ERRJUMP;
    }
    # Type that doesn't have a default custid
    $custid = $webvar{custid};
  }

  my $maskbits = $cidr->masklen;
  my ($fbid, $fb, $fbparent);
  ($fbid, $fb, $fbparent) = findAllocateFrom($ip_dbh, $maskbits, $webvar{alloctype}, '','',
	(gimme => "$cidr", allowpriv => 1));
  $page->param(fbid => $fbid);
  $page->param(parid => $fbparent);
  my $rdns = getBlockRDNS($ip_dbh, id => $fbparent, type => ($webvar{alloctype} =~ /^.i$/ ? 'i' : 'b'),
	user => $authuser);
  $page->param(rdns => $rdns);
  if ($webvar{alloctype} =~ /^(.)i$/) {
    my $iptype = $1;
    my $ptmp = getBlockData($ip_dbh, $fbparent);
    if ($ptmp->{type} =~ /^(.)[dp]$/) {
      my $newiptype = "$1i";
      if ($ptmp->{type} !~ /^$iptype./) {
	$page->param(warnmsg => "Warning:  Allocating IP as '".$disp_alloctypes{$newiptype}."' instead of '".
		$disp_alloctypes{$webvar{alloctype}}."' to match pool ".$ptmp->{block}."\n");
	$webvar{alloctype} = $newiptype;
      }
    }
    if (!$fbid) {
      $page->param(errmsg => "Can't allocate static IP from outside a pool!!");
      goto ERRJUMP;
    }
  } else {
    if (!$fbid) {
      $page->param(errmsg => "Can't allocate from outside a free block!!");
      goto ERRJUMP;
    }
  }

  my $alloc_from = new NetAddr::IP $fb;

  my @cities;
  foreach my $city (@citylist) {
     my %row = (city => $city);
     push @cities, \%row;
  }
  $page->param(
	cidr => $cidr,
	disptype => $disp_alloctypes{$webvar{alloctype}},
	type => $webvar{alloctype},
	alloc_from => $alloc_from,
	custid => $custid,
	citylist => \@cities
	);

} elsif ($webvar{action} eq 'confirm') {

  $page->param(
	cidr => $webvar{cidr},
	custid => $webvar{custid},
	desc => $webvar{desc},
	disptype => $disp_alloctypes{$webvar{alloctype}}
	);
  # Only need to check city here.
  if ($webvar{city} eq '-') {
    $page->param(locerr => "Invalid customer location!  Go back and select customer's location.");
    goto ERRJUMP;
  }

  my ($retcode,$msg) = allocateBlock($ip_dbh, cidr => $webvar{cidr}, fbid => $webvar{fbid},
	parent => $webvar{parent}, custid => $webvar{custid}, type => $webvar{alloctype}, city => $webvar{city},
	desc => $webvar{desc}, notes => $webvar{notes}, circid => $webvar{circid},
	privdata => $webvar{privdata}, nodeid => $webvar{node}, rdns => $webvar{rdns}, user => $authuser);

  if ($retcode eq 'OK') {
    syslog "notice", "$authuser allocated '$webvar{cidr}' to '$webvar{custid}' as ".
	"'$webvar{alloctype}'";
    if ($webvar{alloctype} =~ /^.i$/) {
      mailNotify($ip_dbh, "a$webvar{alloctype}", "ADDED: $disp_alloctypes{$webvar{alloctype}} allocation",
	"$disp_alloctypes{$webvar{alloctype}} $webvar{cidr} allocated to customer $webvar{custid}\n".
	"Description: $webvar{desc}\n\nAllocated by: $authuser\n");
    }
  } else {
    $page->param(errmsg => $msg);
    syslog "err", "($authuser) Allocation of '$webvar{cidr}' to '$webvar{custid}' as ".
	"'$webvar{alloctype}' failed: '$msg'";
  }

} elsif ($webvar{action} eq 'alloctweak') {

  fix_allocfrom();
  showAllocs($webvar{allocfrom});

} elsif ($webvar{action} eq 'update') {

  update();

} elsif ($webvar{action} eq 'touch') {

  my ($code,$msg) = touchMaster($ip_dbh, $webvar{whichmaster});
  $page->param(errmsg => $msg) if $code eq 'FAIL';

} elsif ($webvar{action} eq 'listcust') {

  my $clist = $ip_dbh->selectall_arrayref("SELECT custid,name AS custname,tech_handle AS tech ".
	"FROM customers ORDER BY custid", { Slice => {} } );
  $page->param(custlist => $clist);

} elsif ($webvar{action} eq 'edcust') {

  if ($webvar{newcust}) {
    $sth = $ip_dbh->prepare("INSERT INTO customers (custid) VALUES (?)");
    $sth->execute($webvar{custid});
  }
  $sth = $ip_dbh->prepare("select custid,name,street,city,province,".
	"country,pocode,phone,tech_handle,abuse_handle,admin_handle,special ".
	"from customers where custid='$webvar{custid}'");
  $sth->execute;
  my ($custid, $name, $street, $city, $prov, $country, $pocode, $phone, $tech, $abuse, $admin, $special) =
	$sth->fetchrow_array;

  $page->param(
	custid => $custid,
	name => $name,
	street => $street,
	city => $city,
	prov => $prov,
	country => $country,
	pocode => $pocode,
	phone => $phone,
	tech => $tech,
	abuse => $abuse,
	admin => $admin,
	special => $special
	);

} elsif ($webvar{action} eq 'updcust') {

  if ($webvar{abutton} eq 'Update') {
    $ip_dbh->do(q(
	UPDATE customers
	SET name = ?, street = ?, city = ?, province=?, country=?, pocode=?,
	phone = ?, tech_handle = ?, abuse_handle = ?, admin_handle = ?, special = ?
	WHERE custid = ?
	), undef,
	($webvar{name}, $webvar{street}, $webvar{city}, $webvar{province}, $webvar{country}, $webvar{pocode},
	$webvar{phone}, $webvar{tech_handle}, $webvar{abuse_handle}, $webvar{admin_handle}, $webvar{special},
	$webvar{custid})
	);
    $page->param(whatact => "Updated");
  } elsif ($webvar{abutton} eq 'Delete (immediate)') {
    $ip_dbh->do("DELETE FROM customers WHERE custid = ?", undef, $webvar{custid});
    $page->param(whatact => "Deleted");
  } else {
    # Your llama is on fire
  }
  # Show what we've just either updated or deleted.
  # Deleted, so that in case of "OOOPS!!", the "special" data can be recovered.
  $page->param(
	custid => $webvar{custid},
	name => $webvar{name},
	street => $webvar{street},
	city => $webvar{city},
	prov => $webvar{province},
	country => $webvar{country},
	pocode => $webvar{pocode},
	phone => $webvar{phone},
	tech => $webvar{tech_handle},
	abuse => $webvar{abuse_handle},
	admin => $webvar{admin_handle},
	special => $webvar{special}
	);

} elsif ($webvar{action} eq 'showpools') {

  my $plist = $ip_dbh->selectall_arrayref("SELECT a.id,a.cidr AS pool, count(*) AS free FROM poolips p ".
	"JOIN allocations a ON a.id=p.parent_id ".
	"WHERE available='y' GROUP BY a.cidr,a.id ORDER BY a.cidr", { Slice => {} });
  $page->param(poollist => $plist);

} elsif ($webvar{action} eq 'tweakpool') {

  showPool($webvar{pool});

} elsif ($webvar{action} eq 'updatepool') {

  my $ip = $ip_dbh->selectrow_array("SELECT ip FROM poolips WHERE id=?", undef, ($webvar{id}) );
  $page->param(ip => $ip);
  $sth = $ip_dbh->prepare("UPDATE poolips SET custid=?, city=?, type=?, available='".
	(($webvar{available} eq 'y') ? 'y' : 'n').
	"', notes=?, description=? ".
	"WHERE id=?");
  $sth->execute($webvar{custid}, $webvar{city}, $webvar{type}, $webvar{notes}, $webvar{desc}, $webvar{id});
  if ($sth->err) {
    $page->param(errmsg => $sth->errstr);
    syslog "err", "$authuser could not update pool IP $ip: ".$sth->errstr;
  } else {
    syslog "notice", "$authuser updated pool IP $ip";
  }
  my $poolid = $ip_dbh->selectrow_array("SELECT parent_id FROM poolips WHERE id=?", undef, ($webvar{id}) );
  $page->param(poolid => $poolid);
  my $pool = $ip_dbh->selectrow_array("SELECT cidr FROM allocations WHERE id=?", undef, ($poolid) );
  $page->param(pool => $pool);

} elsif ($webvar{action} eq 'showusers') {

  $sth = $ip_dbh->prepare("select username,acl from users order by username");
  $sth->execute;
  my @userlist;
  while (my ($username,$acl) = $sth->fetchrow_array) {
##fixme: funky things happening with HTML::Template here;  shouldn't need the "logic ? iftrue : iffalse" structure
    my %row = (
	username => $username,
	can_add => ($acl =~ /a/ ? 1 : 0),
	can_change => ($acl =~ /c/ ? 1 : 0),
	can_del => ($acl =~ /d/ ? 1 : 0),
	sysnet => ($acl =~ /s/ ? 1 : 0),
	is_admin => ($acl =~ /A/ ? 1 : 0),
	acl => $acl
	);
    push @userlist, \%row;
  }
  $page->param(userlist => \@userlist);

} elsif ($webvar{action} eq 'updacl') {

  $page->param(username => $webvar{username});
  my $acl = 'b';
  if ($webvar{admin} eq 'on') {
    $acl .= "acdsA";
  } else {
    $acl .= ($webvar{add} eq 'on' ? 'a' : '').
	($webvar{change} eq 'on' ? 'c' : '').
	($webvar{del} eq 'on' ? 'd' : '').
	($webvar{sysnet} eq 'on' ? 's' : '');
  }
  $page->param(acl => $acl);

  $sth = $ip_dbh->prepare("update users set acl='$acl' where username='$webvar{username}'");
  $sth->execute;
  $page->param(errmsg => $sth->errstr) if $sth->err;

} elsif ($webvar{action} eq 'newuser') {

  $page->param(username => $webvar{username});
  my $cr_pass = ($webvar{preenc} ? $webvar{password} :
	crypt $webvar{password}, join('',('.','/',0..9,'A'..'Z','a'..'z')[rand 64, rand 64]));
  $sth = $ip_dbh->prepare("insert into users (username,password,acl) values ".
	"('$webvar{username}','$cr_pass','b')");
  $sth->execute;
  $page->param(errmsg => $sth->errstr) if $sth->err;

} elsif ($webvar{action} eq 'deluser') {

  $page->param(username => $webvar{username});
  $sth = $ip_dbh->prepare("delete from users where username='$webvar{username}'");
  $sth->execute;
  $page->param(errmsg => $sth->errstr) if $sth->err;

} elsif ($webvar{action} eq 'emailnotice') {

  $sth = $ip_dbh->prepare("SELECT action,reciplist FROM notify");
  $sth->execute;
  my @spamlist;
  while (my ($notice_code,$reciplist) = $sth->fetchrow_array() ) {
##fixme: hairy mess, only a few things call mailNotify() anyway, so many possible notices won't work.
    my $action_out = dispNoticeCode($notice_code);
    my %row = (
	action => $action_out,
	code => $notice_code,
	recips => $reciplist
	);
    push @spamlist, \%row;
  }
  $page->param(spamlist => \@spamlist);

  $sth = $ip_dbh->prepare("SELECT type,dispname FROM alloctypes WHERE listorder < 500 ".
	"ORDER BY listorder");
  $sth->execute;
  my $i=0;
  my @typelist;
  while (my ($type,$disp) = $sth->fetchrow_array) {
    my %row = (
	type => $type,
	disptype => $disp,
# ahh, off-by-one counts, how we do love thee...  NOT!
	newrow => ($i+2 > $sth->rows ? 1 : (++$i % 4)),
	);
    push @typelist, \%row;
  }
  $page->param(typelist => \@typelist);

} elsif ($webvar{action} eq 'addnotice') {

  $webvar{alloctype} = $webvar{special} if $webvar{msgaction} eq 's:';
  if ($webvar{msgaction} && $webvar{alloctype} && $webvar{reciplist}) {
    $page->param(cantry => 1);
    $webvar{reciplist} =~ s/[\r\n]+/,/g;
    $webvar{msgaction} = "f:$webvar{msgaction}" if $webvar{onfail};
    $page->param(reciplist => $webvar{reciplist});
    $page->param(dispnotice => dispNoticeCode($webvar{msgaction}.$webvar{alloctype}));
    $sth = $ip_dbh->prepare("INSERT INTO notify (action, reciplist) VALUES (?,?)");
##fixme:  automagically merge reciplists iff action already exists
    $sth->execute($webvar{msgaction}.$webvar{alloctype}, $webvar{reciplist});
    $page->param(addfailed => $sth->errstr) if $sth->err;
  }

} elsif ($webvar{action} eq 'delnotice') {

  $page->param(dispnotice => dispNoticeCode($webvar{code}.$webvar{alloctype}));
  $sth = $ip_dbh->prepare("DELETE FROM notify WHERE action=?");
  $sth->execute($webvar{code});
  $page->param(delfailed => $sth->errstr) if $sth->err;

} elsif ($webvar{action} eq 'ednotice') {

  $page->param(dispnotice => dispNoticeCode($webvar{code}));
  $page->param(code => $webvar{code});
  $sth = $ip_dbh->prepare("SELECT reciplist FROM notify WHERE action=?");
  $sth->execute($webvar{code});
  my ($reciplist) = $sth->fetchrow_array;
  $reciplist =~ s/,/\n/g;
  $page->param(reciplist => $reciplist);

} elsif ($webvar{action} eq 'updnotice') {

  $page->param(dispnotice => dispNoticeCode($webvar{code}));
  $sth = $ip_dbh->prepare("UPDATE notify SET reciplist=? WHERE action=?");
  $webvar{reciplist} =~ s/[\r\n]+/,/g;
  $sth->execute($webvar{reciplist}, $webvar{code});
  $page->param(updfailed => $sth->errstr) if $sth->err;

} elsif ($webvar{action} ne '<NULL>') {
  $page->param(dunno => $webvar{action});
}

ERRJUMP:
print $page->output;

##fixme:  make me a footer param!
print qq(<hr><div><a href="$IPDB::webpath/">Back</a> to the main IPDB</div>\n);

# We print the footer here, so we don't have to do it elsewhere.
my $footer = HTML::Template->new(filename => "footer.tmpl");
# we're already in the admin tools, no need to provide a bottom link.  maybe.
#$footer->param(adminlink => ($IPDBacl{$authuser} =~ /A/));

print $footer->output;

$sth->finish if $sth;
$ip_dbh->disconnect;

exit;


# Hokay.  This is a little different.  We have a few specific functions here:
#  -> Assign arbitrary subnet from arbitrary free space
#  -> Tweak individual DB fields
#


# Tweak allocfrom into shape.
sub fix_allocfrom {
  if ($webvar{allocfrom} =~ /^(\d+\.){2}\d+$/) {
    # 3-octet class C specified
    $webvar{allocfrom} .= ".0/24";
  } elsif ($webvar{allocfrom} =~ /^(\d+\.){3}\d+$/) {
    # 4-octet IP specified;  
    $webvar{allocfrom} .= "/24";
  }
}


# Show allocations to allow editing.
sub showAllocs {

  my $within = new NetAddr::IP $_[0];
  $page->param(within => $within);


  $sth = $ip_dbh->prepare("SELECT id,vrf,cidr,custid,type,city,description FROM allocations".
	" WHERE cidr <<= ? ORDER BY vrf,cidr");
  $sth->execute($within);
  my @blocklist;
  while (my ($id,$vrf,$cidr,$custid,$type,$city,$desc) = $sth->fetchrow_array) {
    my %row = (
	id => $id,
	cidr => $cidr,
	custid => $custid,
	city => $city,
	desc => $desc,
	);

##fixme:  don't wanna retrieve the whole type list *every time around the outer loop*
    my $sth2 = $ip_dbh->prepare("SELECT type,listname FROM alloctypes".
	" WHERE listorder < 999 AND NOT (type LIKE '_i') ORDER BY listorder");
    $sth2->execute;
    my @typelist;
    while (my ($listtype,$dispname) = $sth2->fetchrow_array) {
      my %subrow = (
	type => $listtype,
	dispname => $dispname,
	selected => ($listtype eq $type)
	);
      push @typelist, \%subrow;
    }
    $row{typelist} = \@typelist;
    push @blocklist, \%row;
  }
  $page->param(blocklist => \@blocklist);
} # end showAllocs()


# Stuff updates into DB
sub update {
  my $cidr = $ip_dbh->selectrow_array("SELECT cidr FROM allocations WHERE id=?", undef, ($webvar{block}) );

  # Relatively simple SQL transaction here.  Note that we're deliberately NOT
  # updating notes/desc here as it's available through the main interface.
  $ip_dbh->do("UPDATE allocations SET custid=?, city=?, type=? WHERE id=?", undef,
	($webvar{custid}, $webvar{city}, $webvar{alloctype}, $webvar{block}) );

  $page->param(block => $cidr);
  if ($ip_dbh->err) {
    $page->param(updfailed => $ip_dbh->errstr);
    syslog "err", "$authuser could not update block '$cidr': '".$ip_dbh->errstr."'";
  } else {
    syslog "notice", "$authuser updated $cidr";
  }
  # need to get /24 that block is part of
  my @bits = split /\./, $cidr;
  $bits[3] = "0/24";
  showAllocs((join ".", @bits));
} # end update()


# showPool()
# List all IPs in a pool, and allow arbitrary admin changes to each
# Allow changes to ALL fields
sub showPool {
  my $pool = shift;

  # arguably even presenting a list here is Wrong, because Pool IPs Should Alwasy Match The Pool Type, but...
  # could also set "selected" on the "correct" type
  my $tlist = getTypeList($ip_dbh, 'i');
  $page->param(typelist => $tlist);

  $sth = $ip_dbh->prepare("SELECT id,ip,custid,city,type,available,description,notes from poolips".
	" WHERE parent_id=? ORDER BY ip");
  $sth->execute($pool);
  my @iplist;
  while (my ($id,$ip,$custid,$city,$type,$avail,$desc,$notes) = $sth->fetchrow_array) {
    my %row = (
	id => $id,
	ip => $ip,
	custid => $custid,
	city => $city,
	type => $type,
	avail => $avail,
	desc => $desc,
	notes => $notes
	);
    push @iplist, \%row;
  }
  $page->param(iplist => \@iplist);
} # end showPool()


# interpret the notify codes
sub dispNoticeCode {
  my $code = shift;
  my $action_out = '';

  if ($code =~ /^s:/) {
    $code =~ s/^s:/Special: /;
    return $code;
  }
  if ($code =~ /^f:(.+)$/) {
    $code =~ s/^f://;
    $action_out = "Failure on ";
  }
  if (my $target = $code =~ /^n(.+)/) {
    $action_out .= "New ";
    if ($1 eq 'ci') { $action_out .= "city"; }
    elsif ($1 eq 'no') { $action_out .= "node"; }
    else { $action_out .= '&lt;unknown&gt;'; }
  } else {
    my ($action,$target) = ($code =~ /^(.)(.+)$/);
    if ($action eq 'a')      { $action_out .= 'Add '; }
    elsif ($action eq 'u')   { $action_out .= 'Update '; }
    elsif ($action eq 'd')   { $action_out .= 'Delete '; }
##fixme:  what if we get something funky?
# What about the eleventy-billion odd combinations possible?
# this should give an idea of the structure tho
    if ($target eq 'a') { $action_out .= "all"; }
    elsif ($target eq '.i') {
      $action_out .= "all static IPs";
    }
    else { $action_out .= $disp_alloctypes{$target}; }
  }
  return $action_out;
}
