#!/usr/bin/perl
# ipdb/cgi-bin/main.cgi
###
# SVN revision info
# $Date: 2012-09-27 22:13:16 +0000 (Thu, 27 Sep 2012) $
# SVN revision $Rev: 511 $
# 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 CustIDCK;
use POSIX qw(ceil);
use NetAddr::IP;

use Sys::Syslog;

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

use MyIPDB;

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

## Environment.  Collect some things, process some things, set some things...

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

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

syslog "debug", "$authuser active, $ENV{'REMOTE_ADDR'}";

##fixme there *must* be a better order to do things in so this can go back where it was
# CGI fiddling done here so we can declare %webvar so we can alter $webvar{action}
# to show the right page on DB errors.
# 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;

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

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

my $header = HTML::Template->new(filename => "header.tmpl");
my $footer = HTML::Template->new(filename => "footer.tmpl");

$header->param(version => $IPDB::VERSION);
$header->param(addperm => $IPDBacl{$authuser} =~ /a/);
$header->param(webpath => $IPDB::webpath);
print "Content-type: text/html\n\n", $header->output;


#main()
my $aclerr;

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

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

if($webvar{action} eq 'index') {
  showSummary();
} elsif ($webvar{action} eq 'addmaster') {
  if ($IPDBacl{$authuser} !~ /a/) {
    $aclerr = 'addmaster';
  }
} elsif ($webvar{action} eq 'newmaster') {

  if ($IPDBacl{$authuser} !~ /a/) {
    $aclerr = 'addmaster';
  } else {
    my $cidr = new NetAddr::IP $webvar{cidr};
    $page->param(cidr => "$cidr");

    my ($code,$msg) = addMaster($ip_dbh, $webvar{cidr});

    if ($code eq 'FAIL') {
      syslog "err", "Could not add master block '$webvar{cidr}' to database: '$msg'";
      $page->param(err => $msg);
    } else {
      syslog "info", "$authuser added master block $webvar{cidr}";
    }

  } # ACL check

} # end add new master

elsif($webvar{action} eq 'showmaster') {
  showMaster();
}
elsif($webvar{action} eq 'showrouted') {
  showRBlock();
}
elsif($webvar{action} eq 'listpool') {
  listPool();
}

# Not modified or added;  just shuffled
elsif($webvar{action} eq 'assign') {
  assignBlock();
}
elsif($webvar{action} eq 'confirm') {
  confirmAssign();
}
elsif($webvar{action} eq 'insert') {
  insertAssign();
}
elsif($webvar{action} eq 'edit') {
  edit();
}
elsif($webvar{action} eq 'update') {
  update();
}
elsif($webvar{action} eq 'delete') {
  remove();
}
elsif($webvar{action} eq 'finaldelete') {
  finalDelete();
}
elsif ($webvar{action} eq 'nodesearch') {
  $sth = $ip_dbh->prepare("SELECT node_id, node_name FROM nodes ORDER BY node_type,node_id");
  $sth->execute() or $page->param(errmsg => $sth->errstr);
  my @nodelist;
  while (my ($nid,$nname) = $sth->fetchrow_array()) {
    my %row = (nodeid => $nid, nodename => $nname);
    push @nodelist, \%row;
  }
  $page->param(nodelist => \@nodelist);
}

# DB failure.  Can't do much here, really.
elsif ($webvar{action} eq 'dberr') {
  $page->param(errmsg => $errstr);
}

# Default is an error.  It shouldn't be possible to get here unless you're
# randomly feeding in values for webvar{action}.
else {
  my $rnd = rand 500;
  my $boing = sprintf("%.2f", rand 500);
  my @excuses = (
	"Aether cloudy.  Ask again later about $webvar{action}.",
	"The gods are unhappy with your sacrificial $webvar{action}.",
	"Because one of $webvar{action}'s legs are both the same",
	"<b>wibble</b><br>Can't $webvar{action}, the grue will get me!<br>Can't $webvar{action}, the grue will get me!",
	"Hey, man, you've had your free $webvar{action}.  Next one's gonna...  <i>cost</i>....",
	"I ain't done $webvar{action}",
	"Oooo, look!  A flying $webvar{action}!",
	"$webvar{action} too evil, avoiding.",
	"Rocks fall, $webvar{action} dies.",
	"Bit bucket must be emptied before I can $webvar{action}..."
	);
  $page->param(dunno => $excuses[$rnd/50.0]);
}
## Finally! Done with that NASTY "case" emulation!


# Switch to a different template if we've tripped on an ACL error.
# Note that this should only be exercised in development, when
# deeplinked, or when being attacked;  normal ACL handling should
# remove the links a user is not allowed to click on.
if ($aclerr) {
  $page = HTML::Template->new(filename => "aclerror.tmpl");
  $page->param(ipdbfunc => $aclmsg{$aclerr});
}


# Clean up IPDB globals, DB handle, etc.
finish($ip_dbh);

## Do all our printing here so we can generate errors and stick them into the slots in the templates.

# can't do this yet, too many blowups
#print "Content-type: text/html\n\n", $header->output;
$page->param(webpath => $IPDB::webpath);
print $page->output;

# include the admin tools link in the output?
$footer->param(adminlink => ($IPDBacl{$authuser} =~ /A/));
$footer->param(webpath => $IPDB::webpath);
print $footer->output;

# Just in case something waaaayyy down isn't in place
# properly... we exit explicitly.
exit 0;


# Initial display:  Show master blocks with total allocated subnets, total free subnets
sub showSummary {
  my %allocated;
  my %free;
  my %routed;
  my %bigfree;

  # Count the allocations.
  $sth = $ip_dbh->prepare("select count(*) from allocations where cidr <<= ?");
  foreach my $master (@masterblocks) {
    $sth->execute("$master");
    $sth->bind_columns(\$allocated{"$master"});
    $sth->fetch();
  }

  # Count routed blocks
  $sth = $ip_dbh->prepare("select count(*) from routed where cidr <<= ?");
  foreach my $master (@masterblocks) {
    $sth->execute("$master");
    $sth->bind_columns(\$routed{"$master"});
    $sth->fetch();
  }

  # Count the free blocks.
  $sth = $ip_dbh->prepare("select count(*) from freeblocks where cidr <<= ? and ".
	"(routed='y' or routed='n')");
  foreach my $master (@masterblocks) {
    $sth->execute("$master");
    $sth->bind_columns(\$free{"$master"});
    $sth->fetch();
  }

  # Find the largest free block in each master
  $sth = $ip_dbh->prepare("select maskbits from freeblocks where cidr <<= ? and ".
	"(routed='y' or routed='n') order by maskbits limit 1");
  foreach my $master (@masterblocks) {
    $sth->execute("$master");
    $sth->bind_columns(\$bigfree{"$master"});
    $sth->fetch();
  }

  # Assemble the data to stuff into the template.
  my @masterlist;
  my $rowclass=0;
  foreach my $master (@masterblocks) {
    my %row = (
	rowclass => $rowclass++ % 2,
	master => "$master",
	routed => $routed{"$master"},
	allocated => $allocated{"$master"},
	free => $free{"$master"},
	bigfree => ( ($bigfree{"$master"} eq '') ? ("&lt;NONE&gt;") : ("/".$bigfree{"$master"}) )
	);
    push (@masterlist, \%row);
  }
  $page->param(masterlist => \@masterlist);

  $page->param(addmaster => ($IPDBacl{$authuser} =~ /a/) );

} # showSummary


# Display detail on master
# Alrighty then!  We're showing routed blocks within a single master this time.
# We should be able to steal code from showSummary(), and if I'm really smart
# I'll figger a way to munge the two together.  (Once I've done that, everything
# else should follow.  YMMV.)
sub showMaster {

  $page->param(master => $webvar{block});

  my %allocated;
  my %free;
  my %cities;
  my %bigfree;

  my $master = new NetAddr::IP $webvar{block};
  my @localmasters;

  # Fetch only the blocks relevant to this master
  $sth = $ip_dbh->prepare("select cidr,city from routed where cidr <<= '$master' order by cidr");
  $sth->execute();

  my $i=0;
  while (my @data = $sth->fetchrow_array()) {
    my $cidr = new NetAddr::IP $data[0];
    $localmasters[$i++] = $cidr;
    $free{"$cidr"} = 0;
    $allocated{"$cidr"} = 0;
    $bigfree{"$cidr"} = 128;
    # Retain the routing destination
    $cities{"$cidr"} = $data[1];
  }

  # Check if there were actually any blocks routed from this master
  if ($i > 0) {

    # Count the allocations
    $sth = $ip_dbh->prepare("select count(*) from allocations where cidr <<= ?");
    foreach my $master (@localmasters) {
      $sth->execute("$master");
      $sth->bind_columns(\$allocated{"$master"});
      $sth->fetch();
    }

    # Count the free blocks.
    $sth = $ip_dbh->prepare("select count(*) from freeblocks where cidr <<= ? and ".
	"(routed='y' or routed='n')");
    foreach my $master (@localmasters) {
      $sth->execute("$master");
      $sth->bind_columns(\$free{"$master"});
      $sth->fetch();
    }

    # Get the size of the largest free block
    $sth = $ip_dbh->prepare("select maskbits from freeblocks where cidr <<= ? and ".
	"(routed='y' or routed='n') order by maskbits limit 1");
    foreach my $master (@localmasters) {
      $sth->execute("$master");
      $sth->bind_columns(\$bigfree{"$master"});
      $sth->fetch();
    }

    my @routed;
    my $rowclass = 0;
    foreach my $master (@localmasters) {
      my %row = (
	rowclass => $rowclass++ % 2,
	block => "$master",
	city => $cities{"$master"},
	nsubs => $allocated{"$master"},
	nfree => $free{"$master"},
	lfree => ( ($bigfree{"$master"} eq 128) ? ("&lt;NONE&gt;") : ("/".$bigfree{"$master"}) )
	);
      push @routed, \%row;
    }
    $page->param(routedlist => \@routed);

  } # end check for existence of routed blocks in master

  $page->param(delmaster => ($IPDBacl{$authuser} =~ /d/));

  # Snag the free blocks.
  my $count = 0;
  $sth = $ip_dbh->prepare("select cidr from freeblocks where cidr <<='$master' and ".
	"routed='n' order by cidr");
  $sth->execute();
  my @unrouted;
  my $rowclass = 0;
  while (my @data = $sth->fetchrow_array()) {
    my $cidr = new NetAddr::IP $data[0];
    my %row = (
	rowclass => $rowclass++ % 2,
	fblock => "$cidr",
	frange => $cidr->range
	);
    push @unrouted, \%row;
  }
  $page->param(unrouted => \@unrouted);

} # showMaster


# Display details of a routed block
# Alrighty then!  We're showing allocations within a routed block this time.
# We should be able to steal code from showSummary() and showMaster(), and if
# I'm really smart I'll figger a way to munge all three together.  (Once I've
# done that, everything else should follow.  YMMV.
# This time, we check the database before spewing, because we may
# not have anything useful to spew.
sub showRBlock {

  my $master = new NetAddr::IP $webvar{block};

  $sth = $ip_dbh->prepare("select city from routed where cidr='$master'");
  $sth->execute;
  my ($rcity) = $sth->fetchrow_array;

  $page->param(master => "$master");
  $page->param(rcity => $rcity);

  # Snag the allocations for this block
  $sth = $ip_dbh->prepare("select cidr,city,type,custid,swip,description".
	" from allocations where cidr <<= '$master' order by cidr");
  $sth->execute();

  # hack hack hack
  # set up to flag swip=y records if they don't actually have supporting data in the customers table
  my $custsth = $ip_dbh->prepare("select count(*) from customers where custid=?");

  my $rowclass = 0;
  my @blocklist;
  while (my ($cidr,$city,$type,$custid,$swip,$desc) = $sth->fetchrow_array()) {
    $custsth->execute($custid);
    my ($ncust) = $custsth->fetchrow_array();

    my %row = (
	rowclass => $rowclass++ % 2,
	block => $cidr,
	city => $city,
	type => $disp_alloctypes{$type},
	custid => $custid,
	swip => ($swip eq 'y' ? ($ncust == 0 ? 'Yes<small>*</small>' : 'Yes') : 'No'),
	desc => $desc
	);
    $row{subblock} = ($type =~ /^.r$/);		# hmf.  wonder why these won't work in the hash declaration...
    $row{listpool} = ($type =~ /^.[pd]$/);
    push (@blocklist, \%row);
  }
  $page->param(blocklist => \@blocklist);

  $page->param(delrouted => $IPDBacl{$authuser} =~ /d/);

  # Snag the free blocks.  We don't really *need* to be pedantic about avoiding
  # unrouted free blocks, but it's better to let the database do the work if we can.
  $rowclass = 0;
  my @unassigned;
  $sth = $ip_dbh->prepare("select cidr,routed from freeblocks where cidr <<= '$master'".
	" order by cidr");
  $sth->execute();
  while (my ($cidr_db,$routed) = $sth->fetchrow_array()) {
    my $cidr = new NetAddr::IP $cidr_db;

    my %row = (
	rowclass => $rowclass++ % 2,
	subblock => ($routed ne 'y' && $routed ne 'n'),
	fblock => $cidr_db,
	fbtype => $routed,
	frange => $cidr->range,
	);
    push @unassigned, \%row;
  }
  $page->param(unassigned => \@unassigned);

} # showRBlock


# List the IPs used in a pool
sub listPool {

  my $cidr = new NetAddr::IP $webvar{pool};

  $page->param(block => $webvar{pool});
  $page->param(netip => $cidr->addr);
  $cidr++;
  $page->param(gate => $cidr->addr);
  $cidr--;  $cidr--;
  $page->param(bcast => $cidr->addr);
  $page->param(mask => $cidr->mask);

  # Snag pool info for heading
  $sth = $ip_dbh->prepare("select type,city from allocations where cidr=?");
  $sth->execute($webvar{pool});
  my ($pooltype, $poolcity) = $sth->fetchrow_array;

  $page->param(disptype => $disp_alloctypes{$pooltype});
  $page->param(city => $poolcity);

  # Only display net/gw/bcast if it's a "real" netblock and not a PPP(oE) lunacy
  $page->param(realblock => $pooltype =~ /^.d$/);

# probably have to add an "edit IP allocation" link here somewhere.

  $sth = $ip_dbh->prepare("select ip,custid,available,description,type".
	" from poolips where pool='$webvar{pool}' order by ip");
  $sth->execute;
  my @poolips;
  my $rowclass = 0;
  while (my ($ip,$custid,$available,$desc,$type) = $sth->fetchrow_array) {
    my %row = (
	rowclass => $rowclass++ % 2,
	ip => $ip,
	custid => $custid,
	available => $available,
	desc => $desc,
	maydel => $IPDBacl{$authuser} =~ /d/,
	delme => $available eq 'n'
	);
    push @poolips, \%row;
  }
  $page->param(poolips => \@poolips);

} # end listPool


# Show "Add new allocation" page.  Note that the actual page may
# be one of two templates, and the lists come from the database.
sub assignBlock {

  if ($IPDBacl{$authuser} !~ /a/) {
    $aclerr = 'addblock';
    return;
  }

  # hack pthbttt eww
  $webvar{block} = '' if !$webvar{block};

# hmm.  TMPL_IF block and TMPL_ELSE block on these instead?
  $page->param(rowa => 'row'.($webvar{block} eq '' ? 1 : 0));
  $page->param(rowb => 'row'.($webvar{block} eq '' ? 0 : 1));
  $page->param(block => $webvar{block});	# fb-assign flag, if block is set, we're in fb-assign
  $page->param(iscontained => ($webvar{fbtype} && $webvar{fbtype} ne 'y'));

  # New special case- block to assign is specified
  if ($webvar{block} ne '') {
    my $block = new NetAddr::IP $webvar{block};

    # Handle contained freeblock allocation.
    # This is a little dangerous, as it's *theoretically* possible to
    # get fbtype='n' (aka a non-routed freeblock).  However, should
    # someone manage to get there, they get what they deserve.
    if ($webvar{fbtype} ne 'y') {
      # Snag the type of the container block from the database.
      $sth = $ip_dbh->prepare("select type from allocations where cidr >>='$block'");
      $sth->execute;
      my @data = $sth->fetchrow_array;
      $data[0] =~ s/c$/r/;	# Munge the type into the correct form
      $page->param(fbdisptype => $list_alloctypes{$data[0]});
      $page->param(type => $data[0]);
    } else {
      $sth = $ip_dbh->prepare("select type,listname from alloctypes where listorder < 500 ".
	"and type not like '_i' and type not like '_r' order by listorder");
      $sth->execute;
      my @typelist;
      my $selflag = 0;
      while (my @data = $sth->fetchrow_array) {
        my %row = (tval => $data[0],
                type => $data[1],
                sel => ($selflag == 0 ? ' selected' : '')
                );
        push (@typelist, \%row);
        $selflag++;
      }
      $page->param(typelist => \@typelist);
    }
  } else {
    my @masterlist;
    foreach my $master (@masterblocks) {
      my %row = (master => "$master");
      push (@masterlist, \%row);
    }
    $page->param(masterlist => \@masterlist);

    my @pops;
    foreach my $pop (@poplist) {
      my %row = (pop => $pop);
      push (@pops, \%row);
    }
    $page->param(pops => \@pops);

    # could arguably include routing (500) in the list, but ATM it doesn't
    # make sense, and in any case that shouldn't be structurally possible here.
    $sth = $ip_dbh->prepare("select type,listname from alloctypes where listorder <= 500 order by listorder");
    $sth->execute;
    my @typelist;
    my $selflag = 0;
    while (my @data = $sth->fetchrow_array) {
      my %row = (tval => $data[0],
        type => $data[1],
        sel => ($selflag == 0 ? ' selected' : '')
        );
      push (@typelist, \%row);
      $selflag++;
    }
    $page->param(typelist => \@typelist);
  }

  my @cities;
  foreach my $city (@citylist) {
    my %row = (city => $city);
    push (@cities, \%row);
  }
  $page->param(citylist => \@cities);

## node hack
  $sth = $ip_dbh->prepare("SELECT node_id, node_name FROM nodes ORDER BY node_type,node_id");
  $sth->execute() or print "DEBUG: failed retrieval from nodes: ".$sth->errstr,"<br>\n";
  my @nodes;
  while (my ($nid,$nname) = $sth->fetchrow_array()) {
    my %row = (nid => $nid, nname => $nname);
    push (@nodes, \%row);
  }
  $page->param(nodelist => \@nodes);
## end node hack

  $page->param(privdata => $IPDBacl{$authuser} =~ /s/);

} # assignBlock


# Take info on requested IP assignment and see what we can provide.
sub confirmAssign {
  if ($IPDBacl{$authuser} !~ /a/) {
    $aclerr = 'addblock';
    return;
  }

  my $cidr;
  my $alloc_from;

  # Going to manually validate some items.
  # custid and city are automagic.
  return if !validateInput();

# Several different cases here.
# Static IP vs netblock
#  + Different flavours of static IP
#  + Different flavours of netblock

  if ($webvar{alloctype} =~ /^.i$/) {
    my ($base,undef) = split //, $webvar{alloctype};	# split into individual chars

# Ewww.  But it works.
    $sth = $ip_dbh->prepare("SELECT (SELECT city FROM allocations WHERE cidr=poolips.pool), ".
	"poolips.pool, COUNT(*) FROM poolips,allocations WHERE poolips.available='y' AND ".
	"poolips.pool=allocations.cidr AND allocations.city='$webvar{pop}' AND poolips.type LIKE '".$base."_' ".
	"GROUP BY pool");
    $sth->execute;
    my $optionlist;

    my @poollist;
    while (my ($poolcit,$poolblock,$poolfree) = $sth->fetchrow_array) {
      # city,pool cidr,free IP count
      if ($poolfree > 0) {
	my %row = (poolcit => $poolcit, poolblock => $poolblock, poolfree => $poolfree);
	push (@poollist, \%row);
      }
    }
    $page->param(staticip => 1);
    $page->param(poollist => \@poollist);
    $cidr = "Single static IP";
##fixme:  need to handle "no available pools"

  } else { # end show pool options

    if ($webvar{fbassign} eq 'y') {
      $cidr = new NetAddr::IP $webvar{block};
      $webvar{maskbits} = $cidr->masklen;
    } else { # done with direct freeblocks assignment

      if (!$webvar{maskbits}) {
        $page->param(err => "Please specify a CIDR mask length.");
	return;
      }
      my $sql;
      my $city;
      my $failmsg;
      my $extracond = '';
      if ($webvar{allocfrom} eq '-') {
	$extracond = ($webvar{allowpriv} eq 'on' ? '' : 
		" and not (cidr <<= '192.168.0.0/16'".
			" or cidr <<= '10.0.0.0/8'".
			" or cidr <<= '172.16.0.0/12')");
      }
      my $sortorder;
      if ($webvar{alloctype} eq 'rm') {
        if ($webvar{allocfrom} ne '-') {
	  $sql = "select * from freeblocks where maskbits<=$webvar{maskbits} and routed='n'".
		" and cidr <<= '$webvar{allocfrom}'";
	  $sortorder = "maskbits desc";
	} else {
	  $sql = "select * from freeblocks where maskbits<=$webvar{maskbits} and routed='n'";
	  $sortorder = "maskbits desc";
	}
	$failmsg = "No suitable free block found.<br>\nWe do not have a free".
	  " routeable block of that size.<br>\nYou will have to either route".
	  " a set of smaller netblocks or a single smaller netblock.";
      } else {
##fixme
# This section needs serious Pondering.
	# Pools of most types get assigned to the POP they're "routed from"
	# This includes WAN blocks and other netblock "containers"
	# This does NOT include cable pools.
	if ($webvar{alloctype} =~ /^.[pc]$/) {
	  $city = $webvar{city};
	  $failmsg = "No suitable free block found.<br>\nYou will have to route another".
	    " superblock from one of the<br>\nmaster blocks or chose a smaller".
	    " block size for the pool.";
	} else {
	  if (!$webvar{pop}) {
	    $page->param(err => 'Please select a POP to route the block from/through.');
	    return;
	  }
	  $city = $webvar{pop};
	  $failmsg = "No suitable free block found.<br>\nYou will have to route another".
	    " superblock to $webvar{pop}<br>\nfrom one of the master blocks or".
	    " chose a smaller blocksize.";
	}
	if (defined $webvar{allocfrom} && $webvar{allocfrom} ne '-') {
	  $sql = "select cidr from freeblocks where city='$city' and maskbits<=$webvar{maskbits}".
		" and cidr <<= '$webvar{allocfrom}' and routed='".
		(($webvar{alloctype} =~ /^(.)r$/) ? "$1" : 'y')."'";
	  $sortorder = "maskbits desc,cidr";
	} else {
	  $sql = "select cidr from freeblocks where city='$city' and maskbits<=$webvar{maskbits}".
		" and routed='".(($webvar{alloctype} =~ /^(.)r$/) ? "$1" : 'y')."'";
	  $sortorder = "maskbits desc,cidr";
	}
      }
      $sql = $sql.$extracond." order by ".$sortorder;
      $sth = $ip_dbh->prepare($sql);
      $sth->execute;
      my @data = $sth->fetchrow_array();
      if ($data[0] eq "") {
	$page->param(err => $failmsg);
	return;
      }
      $cidr = new NetAddr::IP $data[0];
    } # check for freeblocks assignment or IPDB-controlled assignment

    $alloc_from = "$cidr";

    # If the block to be allocated is smaller than the one we found,
    # figure out the "real" block to be allocated.
    if ($cidr->masklen() ne $webvar{maskbits}) {
      my $maskbits = $cidr->masklen();
      my @subblocks;
      while ($maskbits++ < $webvar{maskbits}) {
	@subblocks = $cidr->split($maskbits);
      }
      $cidr = $subblocks[0];
    }
  } # if ($webvar{alloctype} =~ /^.i$/)

## node hack
  if ($webvar{node} && $webvar{node} ne '-') {
    $sth = $ip_dbh->prepare("SELECT node_name FROM nodes WHERE node_id=?");
    $sth->execute($webvar{node});
    my ($nodename) = $sth->fetchrow_array();
    $page->param(nodename => $nodename);
    $page->param(nodeid => $webvar{node});
  }
## end node hack

  # Stick in the allocation data
  $page->param(alloc_type => $webvar{alloctype});
  $page->param(typefull => $q->escapeHTML($disp_alloctypes{$webvar{alloctype}}));
  $page->param(alloc_from => $alloc_from);
  $page->param(cidr => $cidr);
  $page->param(city => $q->escapeHTML($webvar{city}));
  $page->param(custid => $webvar{custid});
  $page->param(circid => $q->escapeHTML($webvar{circid}));
  $page->param(desc => $q->escapeHTML($webvar{desc}));

##fixme: find a way to have the displayed copy have <br> substitutions
# for newlines, and the <input> value have either encoded or bare newlines.
# Also applies to privdata.
  $page->param(notes => $q->escapeHTML($webvar{notes},'y'));

  # Check to see if user is allowed to do anything with sensitive data
  my $privdata = '';
  $page->param(privdata => $q->escapeHTML($webvar{privdata},'y'))
	if $IPDBacl{$authuser} =~ /s/;

  # Yay!  This now has it's very own little home.
  $page->param(billinguser => $webvar{userid})
	if $webvar{userid};

##fixme:  this is only needed iff confirm.tmpl and
# confirmRemove.tmpl are merged (quite possible, just
# a little tedious)
  $page->param(action => "insert");

} # end confirmAssign


# Do the work of actually inserting a block in the database.
sub insertAssign {
  if ($IPDBacl{$authuser} !~ /a/) {
    $aclerr = 'addblock';
    return;
  }
  # Some things are done more than once.
  return if !validateInput();

  if (!defined($webvar{privdata})) {
    $webvar{privdata} = '';
  }
  # $code is "success" vs "failure", $msg contains OK for a
  # successful netblock allocation, the IP allocated for static
  # IP, or the error message if an error occurred.

  my ($code,$msg) = allocateBlock($ip_dbh, $webvar{fullcidr}, $webvar{alloc_from},
	$webvar{custid}, $webvar{alloctype}, $webvar{city}, $webvar{desc}, $webvar{notes},
	$webvar{circid}, $webvar{privdata}, $webvar{node});

  if ($code eq 'OK') {
    if ($webvar{alloctype} =~ /^.i$/) {
      $msg =~ s|/32||;
      $page->param(staticip => $msg);
      $page->param(custid => $webvar{custid});
      $page->param(billinguser => $webvar{billinguser});
      mailNotify($ip_dbh, "a$webvar{alloctype}", "ADDED: $disp_alloctypes{$webvar{alloctype}} allocation",
	"$disp_alloctypes{$webvar{alloctype}} $msg allocated to customer $webvar{custid}\n".
	"Description: $webvar{desc}\n\nAllocated by: $authuser\n");
    } else {
      my $netblock = new NetAddr::IP $webvar{fullcidr};
      $page->param(fullcidr => $webvar{fullcidr});
      $page->param(alloctype => $disp_alloctypes{$webvar{alloctype}});
      $page->param(custid => $webvar{custid});
      if ($webvar{alloctype} eq 'pr' && $webvar{billinguser}) {
	$page->param(billinguser => $webvar{billinguser});
	$page->param(custid => $webvar{custid});
	$page->param(netaddr => $netblock->addr);
	$page->param(masklen => $netblock->masklen);
      }
      mailNotify($ip_dbh, "a$webvar{alloctype}", "ADDED: $disp_alloctypes{$webvar{alloctype}} allocation",
	"$disp_alloctypes{$webvar{alloctype}} $webvar{fullcidr} allocated to customer $webvar{custid}\n".
	"Description: $webvar{desc}\n\nAllocated by: $authuser\n");
    }
    syslog "notice", "$authuser allocated '$webvar{fullcidr}' to '$webvar{custid}' as ".
	"'$webvar{alloctype}' ($msg)";
  } else {
    syslog "err", "Allocation of '$webvar{fullcidr}' to '$webvar{custid}' as ".
	"'$webvar{alloctype}' by $authuser failed: '$msg'";
    $page->param(err => "Allocation of $webvar{fullcidr} as '$disp_alloctypes{$webvar{alloctype}}'".
	" failed:<br>\n$msg\n");
  }

} # end insertAssign()


# Does some basic checks on common input data to make sure nothing
# *really* weird gets in to the database through this script.
# Does NOT do complete input validation!!!
sub validateInput {
  if ($webvar{city} eq '-') {
    $page->param(err => 'Please choose a city');
    return;
  }

  # Alloctype check.
  chomp $webvar{alloctype};
  if (!grep /$webvar{alloctype}/, keys %disp_alloctypes) {
    # Danger! Danger!  alloctype should ALWAYS be set by a dropdown.  Anyone
    # managing to call things in such a way as to cause this deserves a cryptic error.
    $page->param(err => 'Invalid alloctype');
    return;
  }

  # CustID check
  # We have different handling for customer allocations and "internal" or "our" allocations
  if ($def_custids{$webvar{alloctype}} eq '') {
    if (!$webvar{custid}) {
      $page->param(err => 'Please enter a customer ID.');
      return;
    }
    if ($webvar{custid} !~ /^(?:\d{10}|\d{7}|STAFF)(?:-\d\d?)?$/) {
      # Force uppercase for now...
      $webvar{custid} =~ tr/a-z/A-Z/;
      # Crosscheck with billing.
      my $status = CustIDCK->custid_exist($webvar{custid});
      if ($CustIDCK::Error) {
	$page->param(err => "Error verifying customer ID: ".$CustIDCK::ErrMsg);
	return;
      }
      if (!$status) {
	$page->param(err => "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.");
	return;
      }
    }
#    print "<!-- [ In validateInput().  Insert customer ID cross-check here. ] -->\n";
  } else {
    # New!  Improved!  And now Loaded From The Database!!
    if ((!$webvar{custid}) || ($webvar{custid} ne 'STAFF')) {
      $webvar{custid} = $def_custids{$webvar{alloctype}};
    }
  }

  # Check POP location
  my $flag;
  if ($webvar{alloctype} eq 'rm') {
    $flag = 'for a routed netblock';
    foreach (@poplist) {
      if (/^$webvar{city}$/) {
	$flag = 'n';
	last;
      }
    }
  } else {
    $flag = 'n';
##fixme:  hook to force-set POP or city on certain alloctypes
# if ($webvar{alloctype =~ /foo,bar,bz/ { $webvar{pop} = 'blah'; }
    if ($webvar{pop} =~ /^-$/) {
      $flag = 'to route the block from/through';
    }
  }

  # if the alloctype has a restricted city/POP list as determined above,
  # and the reqested city/POP does not match that list, complain
  if ($flag ne 'n') {
    $page->param(err => "Please choose a valid POP location $flag.  Valid ".
	"POP locations are currently:<br>\n".join (" - ", @poplist));
    return;
  }

  return 'OK';
} # end validateInput


# Displays details of a specific allocation in a form
# Allows update/delete
# action=edit
sub edit {

  my $sql;

  # Two cases:  block is a netblock, or block is a static IP from a pool
  # because I'm lazy, we'll try to make the SELECT's bring out identical)ish) data
##fixme:  allow "SWIP" (publication to rWHOIS) of static IP data
  if ($webvar{block} =~ /\/32$/) {
    $sql = "select ip,custid,type,city,circuitid,description,notes,modifystamp,privdata from poolips where ip='$webvar{block}'";
  } else {
    $sql = "select cidr,custid,type,city,circuitid,description,notes,modifystamp,privdata,swip from allocations where cidr='$webvar{block}'"
  }

  # gotta snag block info from db
  $sth = $ip_dbh->prepare($sql);
  $sth->execute;
  my @data = $sth->fetchrow_array;

  # Clean up extra whitespace on alloc type
  $data[2] =~ s/\s//;

  # We can't let the city be changed here;  this block is a part of
  # a larger routed allocation and therefore by definition can't be moved.
  # block and city are static.
##fixme
# Needs thinking.  Have to allow changes to city to correct errors, no?
# Also have areas where a routed block at a POP serves "many" cities/towns/named crossroads

# @data: cidr,custid,type,city,circuitid,description,notes,modifystamp,privdata,swip

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

  $page->param(custid => $data[1]);
  $page->param(city => $data[3]);
  $page->param(circid => $data[4]);
  $page->param(desc => $data[5]);
  $page->param(notes => $data[6]);

##fixme The check here should be built from the database
# Need to expand to support pool types too
  if ($data[2] =~ /^.[ne]$/ && $IPDBacl{$authuser} =~ /c/) {
    $page->param(changetype => 1);
    $page->param(alloctype => [
		{ selme => ($data[2] eq 'me'), type => "me", disptype => "Dialup netblock" },
		{ selme => ($data[2] eq 'de'), type => "de", disptype => "Dynamic DSL netblock" },
		{ selme => ($data[2] eq 'ce'), type => "ce", disptype => "Dynamic cable netblock" },
		{ selme => ($data[2] eq 'we'), type => "we", disptype => "Dynamic wireless netblock" },
		{ selme => ($data[2] eq 'cn'), type => "cn", disptype => "Customer netblock" },
		{ selme => ($data[2] eq 'en'), type => "en", disptype => "End-use netblock" },
		{ selme => ($data[2] eq 'in'), type => "in", disptype => "Internal netblock" },
		]
	);
  } else {
    $page->param(disptype => $disp_alloctypes{$data[2]});
    $page->param(type => $data[2]);
  }

## node hack
  $sth = $ip_dbh->prepare("SELECT nodes.node_id,node_name FROM nodes INNER JOIN noderef".
	" ON nodes.node_id=noderef.node_id WHERE noderef.block='$webvar{block}'");
  $sth->execute;
  my ($nodeid,$nodename) = $sth->fetchrow_array();
  $page->param(havenodeid => $nodeid);

  if ($data[2] eq 'fr' || $data[2] eq 'bi') {
    $page->param(typesupportsnodes => 1);
    $page->param(nodename => $nodename);

##fixme:  this whole hack needs cleanup and generalization for all alloctypes
##fixme:  arguably a bug that presence of a nodeid implies it can be changed..
#  but except for manual database changes, only the two types fr and bi can
#  (currently) have a nodeid set in the first place.
    if ($IPDBacl{$authuser} =~ /c/) {
      $sth = $ip_dbh->prepare("SELECT node_id, node_name FROM nodes ORDER BY node_type,node_id");
      $sth->execute;
      my @nodelist;
      while (my ($nid,$nname) = $sth->fetchrow_array()) {
        my %row = (
		selme => ($nodeid == $nid),
		nodeid => $nid,
		nodename => $nname,
		);
        push (@nodelist, \%row);
      }
      $page->param(nodelist => \@nodelist);
    }
  }
## end node hack

  my ($lastmod,undef) = split /\s+/, $data[7];
  $page->param(lastmod => $lastmod);

  # not happy with the upside-down logic, but...
  $page->param(swipable => $data[2] !~ /.i/);
  $page->param(swip => $data[10] ne 'n');

  # Check to see if we can display sensitive data
  $page->param(nocling => $IPDBacl{$authuser} =~ /s/);
  $page->param(privdata => $data[8]);

  # ACL trickery - these two template booleans control the presence of all form/input tags
  $page->param(maychange => $IPDBacl{$authuser} =~ /c/);
  $page->param(maydel => $IPDBacl{$authuser} =~ /d/);

} # edit()


# Stuff new info about a block into the db
# action=update
sub update {
  if ($IPDBacl{$authuser} !~ /c/) {
    $aclerr = 'updateblock';
    return;
  }

  # Check to see if we can update restricted data
  my $privdata = '';
  if ($IPDBacl{$authuser} =~ /s/) {
    $privdata = ",privdata='$webvar{privdata}'";
  }

  # Make sure incoming data is in correct format - custID among other things.
  return if !validateInput;

  # SQL transaction wrapper
  eval {
    # Relatively simple SQL transaction here.
    my $sql;
    if (my $pooltype = ($webvar{alloctype} =~ /^(.)i$/) ) {
      $sql = "UPDATE poolips SET custid='$webvar{custid}',".
	"city=?,description=?,notes=?,".
	"circuitid='$webvar{circid}',".
	"$privdata where ip='$webvar{block}'";
    } else {
      $sql = "UPDATE allocations SET custid='$webvar{custid}',".
	"city=?,description=?,notes=?,".
	"circuitid='$webvar{circid}'$privdata,".
	"type='$webvar{alloctype}',".
	"swip='".($webvar{swip} eq 'on' ? 'y' : 'n')."' ".
	"where cidr='$webvar{block}'";
    }
    # Log the details of the change.
    syslog "debug", $sql;
    $sth = $ip_dbh->prepare($sql);
    $sth->execute($webvar{city}, $webvar{desc}, $webvar{notes});
## node hack
    if ($webvar{node}) {
      # done with delete/insert so we don't have to worry about funkyness updating a node ref that isn't there
      $ip_dbh->do("DELETE FROM noderef WHERE block='$webvar{block}'");
      $sth = $ip_dbh->prepare("INSERT INTO noderef (block,node_id) VALUES (?,?)");
      $sth->execute($webvar{block},$webvar{node});
    }
## end node hack
    $ip_dbh->commit;
  };
  if ($@) {
    my $msg = $@;
    eval { $ip_dbh->rollback; };
    syslog "err", "$authuser could not update block/IP '$webvar{block}': '$msg'";
    $page->param(err => "Could not update block/IP $webvar{block}: $msg");
    return;
  }

  # If we get here, the operation succeeded.
  syslog "notice", "$authuser updated $webvar{block}";
##fixme:  need to wedge something in to allow "update:field" notifications
## hmm.  how to tell what changed?  O_o
mailNotify($ip_dbh, 's:swi', "SWIPed: $disp_alloctypes{$webvar{alloctype}} $webvar{block}",
	"$webvar{block} had SWIP status changed to \"Yes\" by $authuser") if $webvar{swip} eq 'on';

## node hack
  if ($webvar{node} && $webvar{node} ne '-') {
    $sth = $ip_dbh->prepare("SELECT node_name FROM nodes WHERE node_id=?");
    $sth->execute($webvar{node});
    my ($nodename) = $sth->fetchrow_array();
    $page->param(nodename => $nodename);
  }
## end node hack

  # Link back to browse-routed or list-pool page on "Update complete" page.
  my $cblock;	# to contain the CIDR of the container block we're retrieving.
  my $sql;
  if (my $pooltype = ($webvar{alloctype} =~ /^(.)i$/) ) {
    $page->param(backpool => 1);
    $sql = "select pool from poolips where ip='$webvar{block}'";
  } else {
    $sql = "select cidr from routed where cidr >>= '$webvar{block}'";
  }
  # I define there to be no errors on this operation...  so we don't need to check for them.
  $sth = $ip_dbh->prepare($sql);
  $sth->execute;
  $sth->bind_columns(\$cblock);
  $sth->fetch();
  $sth->finish;
  $page->param(backblock => $cblock);

  $page->param(cidr => $webvar{block});
  $page->param(city => $webvar{city});
  $page->param(disptype => $disp_alloctypes{$webvar{alloctype}});
  $page->param(custid => $webvar{custid});
  $page->param(swip => $webvar{swip} eq 'on' ? 'Yes' : 'No');
  $page->param(circid => $q->escapeHTML($webvar{circid}));
  $page->param(desc => $q->escapeHTML($webvar{desc}));
  $page->param(notes => $q->escapeHTML($webvar{notes}));
  $webvar{privdata} = ($webvar{privdata} ? $q->escapeHTML($webvar{privdata}) : "&nbsp;");
  $page->param(privdata => $webvar{privdata})
	if $IPDBacl{$authuser} =~ /s/;

} # update()


# Delete an allocation.
sub remove {
  if ($IPDBacl{$authuser} !~ /d/) {
    $aclerr = 'delblock';
    return;
  }

  # Serves'em right for getting here...
  if (!defined($webvar{block})) {
    $page->param(err => "Can't delete a block that doesn't exist");
    return;
  }

  my ($cidr, $custid, $type, $city, $circid, $desc, $notes, $alloctype, $privdata);

  if ($webvar{alloctype} eq 'rm') {
    $sth = $ip_dbh->prepare("select cidr,city from routed where cidr='$webvar{block}'");
    $sth->execute();

# This feels...  extreme.
    croak $sth->errstr() if($sth->errstr());

    $sth->bind_columns(\$cidr,\$city);
    $sth->execute();
    $sth->fetch || croak $sth->errstr();
    $custid = "N/A";
    $alloctype = $webvar{alloctype};
    $circid = "N/A";
    $desc = "N/A";
    $notes = "N/A";
    $privdata = "N/A";

  } elsif ($webvar{alloctype} eq 'mm') {

    $cidr = $webvar{block};
    $city = "N/A";
    $custid = "N/A";
    $alloctype = $webvar{alloctype};
    $circid = "N/A";
    $desc = "N/A";
    $notes = "N/A";
    $privdata = "N/A";

  } elsif ($webvar{alloctype} =~ /^.i$/) { # done with alloctype=[rm]m

    # Unassigning a static IP
    my $sth = $ip_dbh->prepare("select ip,custid,city,type,notes,circuitid,privdata".
	" from poolips where ip='$webvar{block}'");
    $sth->execute();
#  croak $sth->errstr() if($sth->errstr());

    $sth->bind_columns(\$cidr, \$custid, \$city, \$alloctype, \$notes, \$circid,
	\$privdata);
    $sth->fetch() || croak $sth->errstr;

  } else { # done with alloctype=~ /^.i$/

    my $sth = $ip_dbh->prepare("select cidr,custid,type,city,circuitid,description,notes,privdata".
	" from allocations where cidr='$webvar{block}'");
    $sth->execute();
#	croak $sth->errstr() if($sth->errstr());

    $sth->bind_columns(\$cidr, \$custid, \$alloctype, \$city, \$circid, \$desc,
	\$notes, \$privdata);
    $sth->fetch() || carp $sth->errstr;
  } # end cases for different alloctypes

  $page->param(block => $cidr);
  $page->param(disptype => $disp_alloctypes{$alloctype});
  $page->param(type => $alloctype);
  $page->param(city => $city);
  $page->param(custid => $custid);
  $page->param(circid => $circid);
  $page->param(desc => $desc);
  $page->param(notes => $notes);
  $privdata = '&nbsp;' if $privdata eq '';
  $page->param(privdata => $privdata) if $IPDBacl{$authuser} =~ /s/;
  $page->param(delpool => $alloctype =~ /^.[pd]$/);

} # end remove()


# Delete an allocation.  Return it to the freeblocks table;  munge
# data as necessary to keep as few records as possible in freeblocks
# to prevent weirdness when allocating blocks later.
# Remove IPs from pool listing if necessary
sub finalDelete {
  if ($IPDBacl{$authuser} !~ /d/) {
    $aclerr = 'delblock';
    return;
  }

  # need to retrieve block data before deleting so we can notify on that
  my ($cidr,$custid,$type,$city,$description) = getBlockData($ip_dbh, $webvar{block});

  my ($code,$msg) = deleteBlock($ip_dbh, $webvar{block}, $webvar{alloctype});

  $page->param(block => $webvar{block});
  if ($code eq 'OK') {
    syslog "notice", "$authuser deallocated '$webvar{alloctype}'-type netblock $webvar{block}".
	" $custid, $city, desc='$description'";
    mailNotify($ip_dbh, 'da', "REMOVED: $disp_alloctypes{$webvar{alloctype}} $webvar{block}",
	"$disp_alloctypes{$webvar{alloctype}} $webvar{block} deallocated by $authuser\n".
	"CustID: $custid\nCity: $city\nDescription: $description\n");
  } else {
    $page->param(failmsg => $msg);
    if ($webvar{alloctype} =~ /^.i$/) {
      syslog "err", "$authuser could not deallocate static IP '$webvar{block}': '$msg'";
    } else {
      syslog "err", "$authuser could not deallocate netblock '$webvar{block}': '$msg'";
      $page->param(netblock => 1);
    }
  }

} # finalDelete
