#!/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: 2005-06-13 20:33:16 +0000 (Mon, 13 Jun 2005) $
# SVN revision $Rev: 259 $
# Last update by $Author: kdeugau $
###
# Copyright (C) 2004,2005 - Kris Deugau

use strict;
use warnings;
use CGI::Carp qw(fatalsToBrowser);
use DBI;
use CommonWeb qw(:ALL);
use MyIPDB;
#use POSIX qw(ceil);
use NetAddr::IP;

use Sys::Syslog;

openlog "IPDB-admin","pid","local2";

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

# 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) {
  printAndExit("Database error: $errstr\n");
}
initIPDBGlobals($ip_dbh);

if ($IPDBacl{$authuser} !~ /A/) {
  print "Content-Type: text/html\n\n".
	"<html><head><title>Access denied</title></head><body>\n".
	'Access to this tool is restricted.  Contact <a href="mailto:kdeugau@vianet.ca">Kris</a> '.
	"for more information.</body></html>\n";
  exit;
}

my %webvar = parse_post();
cleanInput(\%webvar);

print "Content-type: text/html\n\n".
	"<html>\n<head>\n\t<title>TEST [IPDB admin tools] TEST</title>\n".
	qq(\t<link rel="stylesheet" type="text/css" href="/ip/ipdb.css">\n).
	"</head>\n<body>\n".
	"<h2>IPDB - Administrative Tools</h2>\n<hr>\n";

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

  my $typelist = '';
  $sth = $ip_dbh->prepare("select type,listname from alloctypes where listorder < 900 order by listorder");
  $sth->execute;
  my @data = $sth->fetchrow_array;
  $typelist .= "<option value='$data[0]' selected>$data[1]</option>\n";
  while (my @data = $sth->fetchrow_array) {
    $typelist .= "<option value='$data[0]'>$data[1]</option>\n";
  }

  print qq(WARNING:  There are FAR fewer controls on what you can do here.  Use the
main interface if at all possible.
<hr>
<a href="admin.cgi?action=newalloc">Add allocation</a>
<hr>
<form action="admin.cgi" method="POST">
<input type=hidden name=action value=alloc>
Allocate block/IP: <input name=cidr> as <select name=alloctype>$typelist</select> to <input name=custid>
<input type=submit value=" GIMME!! "></form>
<hr><form action="admin.cgi" method="POST">
<input type=hidden name=action value=alloctweak>
Manually update allocation data in this /24: <input name=allocfrom>
<input type=submit value="Show allocations">
</form>
<hr><a href="admin.cgi?action=showpools">List IP Pools</a> for manual tweaking and updates
<hr><a href="admin.cgi?action=showusers">Manage users</a> (add/remove users;  change
internal access controls - note that this does NOT include IP-based limits)
);
} else {
  print '<a href="/ip/cgi-bin/admin.cgi">Back</a> to main<hr>';
}


## Possible actions.
if ($webvar{action} eq 'alloc') {
  # OK, we know what we're allocating.

  if ($webvar{cidr} !~ /^\s*(\d{1,3}\.){3}\d{1,3}(\/\d{2})?\s*$/) {
    printAndExit("Can't allocate something that's not a netblock/ip");
  }

  $sth = $ip_dbh->prepare("select def_custid from alloctypes where type='$webvar{alloctype}'");
  $sth->execute;
  my @data = $sth->fetchrow_array;
  my $custid = $data[0];
  if ($custid eq '') {
    # Type that doesn't have a default custid
    $custid = $webvar{custid};
  }
##fixme Check billing DB here

  my $cidr = new NetAddr::IP $webvar{cidr};
  my @data;
  if ($webvar{alloctype} eq 'rm') {
    $sth = $ip_dbh->prepare("select cidr from freeblocks where cidr >>='$cidr' and routed='n'");
    $sth->execute;
    @data = $sth->fetchrow_array;
# User deserves errors if user can't be bothered to find the free block first.
    printAndExit("Can't allocate from outside a free block!!\n")
        if !$data[0];
  } elsif ($webvar{alloctype} =~ /^(.)i$/) {
    $sth = $ip_dbh->prepare("select cidr from allocations where cidr >>='$cidr' and (type like '_d' or type like '_p')");
    $sth->execute;
    @data = $sth->fetchrow_array;
# User deserves errors if user can't be bothered to find the pool and a free IP first.
    printAndExit("Can't allocate static IP from outside a pool!!\n")
	if !$data[0];
  } else {
    $sth = $ip_dbh->prepare("select cidr from freeblocks where cidr >>='$cidr' and not (routed='n')");
    $sth->execute;
    @data = $sth->fetchrow_array;
# User deserves errors if user can't be bothered to find the free block first.
    printAndExit("Can't allocate from outside a routed block!!\n")
        if !$data[0];
  }

  my $alloc_from = new NetAddr::IP $data[0];
  $sth->finish;

  my $cities = '';
  foreach my $city (@citylist) {
    $cities .= "<option>$city</option>\n";
  }

  print qq(<table class=regular>
<form method=POST action=admin.cgi>
<tr class=color1>
<td>Allocating:</td>
<td>$cidr<input type=hidden name=cidr value="$cidr"></td>
</tr><tr class=color2>
<td>Type:</td><td>$disp_alloctypes{$webvar{alloctype}}
<input type=hidden name=alloctype value="$webvar{alloctype}"></td>
</tr><tr class=color1>
<td>Allocated from:</td>
<td>$alloc_from<input type=hidden name=alloc_from value="$alloc_from"></td>
</tr><tr class="color2">
<td>Customer ID:</td><td>$custid<input type=hidden name=custid value="$custid"></td>
</tr><tr class=color1>
<td>Customer location:</td><td>
<select name="city"><option selected>-</option>
$cities
</select>
&nbsp;<a href="javascript:popNotes('/ip/newcity.html')">Add new location</a>
</td>
</tr>
<tr class="color2">
<td>Circuit ID:</td><td><input name=circid size=40></td>
</tr><tr class="color1">
<td>Description/Name:</td><td><input name="desc" size=40></td>
</tr><tr class="color2">
<td>Notes:</td><td><textarea name="notes" rows="3" cols="40"></textarea></td>
</tr><tr class="warning">
<td colspan=2><center>WARNING:  This will IMMEDIATELY assign this block!!</center></td>
</tr><tr class="color2">
<td class="center" colspan="2"><input type="submit" value="  Assign  "></td>
<input type="hidden" name="action" value="confirm">
</tr>
</table>
);


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

  print "Assigning $webvar{cidr} to $webvar{custid} (\"$webvar{desc}\") as ".
	"$disp_alloctypes{$webvar{alloctype}}...<br>\n";
  # Only need to check city here.
  if ($webvar{city} eq '-') {
    printError("Invalid customer location!  Go back and select customer's location.");
  } else {
    my ($retcode,$msg) = allocateBlock($ip_dbh, $webvar{cidr}, $webvar{alloc_from},
	$webvar{custid}, $webvar{alloctype}, $webvar{city}, $webvar{desc}, $webvar{notes},
	$webvar{circid});
    if ($retcode eq 'OK') {
      print "Allocation OK!\n";

      if ($webvar{alloctype} =~ /^.i$/) {
        # Notify tech@example.com
        mailNotify('tech@example.com',"$disp_alloctypes{$webvar{alloctype}} allocation",
          "$disp_alloctypes{$webvar{alloctype}} $msg allocated to customer $webvar{custid}\n".
          "Description: $webvar{desc}\n\nAllocated by: $authuser\n");
      }
      syslog "notice", "$authuser allocated '$webvar{cidr}' to '$webvar{custid}' as ".
	"'$webvar{alloctype}'";
    } else {
      print "Allocation failed!  IPDB::allocateBlock said:\n$msg\n";
      syslog "err", "($authuser) Allocation of '$webvar{cidr}' to '$webvar{custid}' as ".
	"'$webvar{alloctype}' failed: '$msg'";
    }
  } # done city check

} elsif ($webvar{action} eq 'alloctweak') {
  fix_allocfrom();
  showAllocs($webvar{allocfrom});
} elsif ($webvar{action} eq 'update') {
  update();
} elsif ($webvar{action} eq 'assign') {
  # Display a list of possible blocks within the requested block.
  open (HTML, "../admin_alloc.html")
	or croak "Could not open admin_alloc.html :$!";
  my $html = join('', <HTML>);
  $html =~ s/\$\$MASK\$\$/$webvar{masklen}/g;
  $html =~ s/\$\$ALLOCFROM\$\$/$webvar{allocfrom}/g;

  my $from = new NetAddr::IP $webvar{allocfrom};
  my @blocklist = $from->split($webvar{masklen});
  my $availblocks;
  foreach (@blocklist) {
    $availblocks .= qq(<tr><td colspan=2 align=center><input type=radio name=block value="$_">$_</td></tr>\n);
  }
  $html =~ s/\$\$BLOCKLIST\$\$/$availblocks/g;

  print $html;
} elsif ($webvar{action} eq 'showpools') {
  print "IP Pools currently allocated:\n".
	"<table border=1>\n<tr><td>Pool</td><td># of free IPs</td></tr>\n";
  $sth = $ip_dbh->prepare("select cidr from allocations where type like '%p' or type like '%d' order by cidr");
  $sth->execute;
  my %poolfree;
  while (my @data = $sth->fetchrow_array) {
    $poolfree{$data[0]} = 0;
  }
  $sth = $ip_dbh->prepare("select pool,ip from poolips where available='y' order by ip");
  $sth->execute;
  while (my @data = $sth->fetchrow_array) {
    $poolfree{$data[0]}++;
  }
  foreach my $key (keys %poolfree) {
    print qq(<tr><td><a href="admin.cgi?action=tweakpool&pool=$key">$key</a></td>).
	"<td>$poolfree{$key}</td></tr>\n";
  }
  print "</table>\n";
} elsif ($webvar{action} eq 'tweakpool') {
  showPool($webvar{pool});
} elsif ($webvar{action} eq 'updatepool') {

  $sth = $ip_dbh->prepare("update poolips set custid='$webvar{custid}', ".
	"city='$webvar{city}', type='$webvar{type}', available='".
	(($webvar{available} eq 'y') ? 'y' : 'n').
	"', notes='$webvar{notes}', description='$webvar{desc}' ".
	"where ip='$webvar{ip}'");
  $sth->execute;
  if ($sth->err) {
    print "Error updating pool IP $webvar{ip}: $@<hr>\n";
    syslog "err", "$authuser could not update pool IP $webvar{ip}: $@";
  } else {  
    $sth = $ip_dbh->prepare("select pool from poolips where ip='$webvar{ip}'");
    $sth->execute;
    my @data = $sth->fetchrow_array;
    print "$webvar{ip} in $data[0] updated\n<hr>\n";
    syslog "notice", "$authuser updated pool IP $webvar{ip}";
  }
} elsif ($webvar{action} eq 'showusers') {
  print "Notes:<br>\n".
	"<li>Admin users automatically get all other priviledges.\n".
	"<hr>Add new user:<form action=admin.cgi method=POST>\n".
	"Username: <input name=username><br>\n".
	"Password: <input name=password> <input type=checkbox name=preenc>Password is pre-encrypted (MUST be crypt() encrypted)<br>\n".
	"<input type=submit value='Add user'><input type=hidden name=action value=newuser></form>\n";

  print "<hr>Users with access:\n<table border=1>\n";
  print "<tr><td>Username</td><td>Add new</td><td>Change</td>".
	"<td>Delete</td><td>Admin user</td></tr>\n".
	"<form action=admin.cgi method=POST>\n";
  $sth = $ip_dbh->prepare("select username,acl from users order by username");
  $sth->execute;
  while (my @data = $sth->fetchrow_array) {
    print "<form action=admin.cgi method=POST><input type=hidden name=action value=updacl>".
	qq(<tr><td>$data[0]<input type=hidden name=username value="$data[0]"></td><td>).
    # Now for the fun bit.  We have to pull apart the ACL field and
    # output a bunch of checkboxes.
    	"<input type=checkbox name=add".($data[1] =~ /a/ ? ' checked=y' : '').
	"></td><td><input type=checkbox name=change".($data[1] =~ /c/ ? ' checked=y' : '').
	"></td><td><input type=checkbox name=del".($data[1] =~ /d/ ? ' checked=y' : '').
	"></td><td><input type=checkbox name=admin".($data[1] =~ /A/ ? ' checked=y' : '').
	qq(></td><td><input type=submit value="Update"></td></form>\n).
	"<form action=admin.cgi method=POST><td><input type=hidden name=action value=deluser>".
	"<input type=hidden name=username value=$data[0]>".
	qq(<input type=submit value="Delete user"></tr></form>\n);

  }
  print "</table>\n";
} elsif ($webvar{action} eq 'updacl') {
  print "Updating ACL for $webvar{username}:<br>\n";
  my $acl = 'b';
  if ($webvar{admin} eq 'on') {
    $acl .= "acdA";
  } else {
    $acl .= ($webvar{add} eq 'on' ? 'a' : '').
	($webvar{change} eq 'on' ? 'c' : '').
	($webvar{del} eq 'on' ? 'd' : '');
  }
  print "New ACL: $acl<br>\n";

  $sth = $ip_dbh->prepare("update users set acl='$acl' where username='$webvar{username}'");
  $sth->execute;
  print "OK\n" if !$sth->err;

  print qq(<hr><a href="admin.cgi?action=showusers">Back</a> to user listing\n);

} elsif ($webvar{action} eq 'newuser') {
  print "Adding user $webvar{username}...\n";
  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;
  if ($sth->err) {
    print "<br>Error adding user: ".$sth->errstr;
  } else {
    print "OK\n";
  }

  print qq(<hr><a href="admin.cgi?action=showusers">Back</a> to user listing\n);

} elsif ($webvar{action} eq 'deluser') {
  print "Deleting user $webvar{username}.<br>\n";
  $sth = $ip_dbh->prepare("delete from users where username='$webvar{username}'");
  $sth->execute;
  print "OK\n" if !$sth->err;

  print qq(<hr><a href="admin.cgi?action=showusers">Back</a> to user listing\n);

} elsif ($webvar{action} ne '<NULL>') {
  print "webvar{action} check failed: Don't know how to $webvar{action}";
}

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


printFooter;

$ip_dbh->disconnect;

exit;


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


# List free blocks in a /24 for arbitrary manual allocation
sub showfree($) {
  my $cidr = new NetAddr::IP $_[0];
  print "Showing free blocks in $cidr<br>\n".
	"<table border=1>\n";
  $sth = $ip_dbh->prepare("select * from freeblocks where cidr <<= '$cidr' order by cidr");
  $sth->execute;
  while (my @data = $sth->fetchrow_array) {
    my $temp = new NetAddr::IP $data[0];
    print "<tr><form action=admin.cgi method=POST><input type=hidden name=action value=assign>\n".
	qq(<td>$temp<input type=hidden name=allocfrom value="$temp"></td>\n).
	"<td>".
	(($temp->masklen == 30) ? '<input type=hidden name=masklen value=30>30'
	  : "<select name=masklen><option>30</option>\n<option>29</option>\n") .
	(($temp->masklen < 29) ? "<option>28</option>\n" : '') .
	(($temp->masklen < 28) ? "<option>27</option>\n" : '') .
	(($temp->masklen < 27) ? "<option>26</option>\n" : '') .
	(($temp->masklen < 26) ? "<option>25</option>\n" : '') .
	(($temp->masklen < 25) ? "<option>24</option>\n" : '') .
	"</td>".
	qq(<td>$data[2]</td><td><input type=submit value="Allocate from here"></td>).
	"\n</form></tr>\n";
  }
  print "</table>\n";
}


# Show allocations to allow editing.
sub showAllocs($) {
  my $cidr = new NetAddr::IP $_[0];
  print "Edit custID, allocation type, city for allocations in ".
	"$cidr:\n<table border=1>";
  $sth = $ip_dbh->prepare("select * from allocations where cidr <<= '$cidr' order by cidr");
  $sth->execute;
  while (my @data = $sth->fetchrow_array) {
    print "<tr><form action=admin.cgi method=POST><input type=hidden name=action value=update>\n".
	qq(<td>$data[0]<input type=hidden value="$data[0]" name=block></td>\n).
	qq(<td><input name=custid value="$data[1]"></td>\n);

    print "<td><select name=alloctype><option".
        (($data[2] eq 'cn') ? ' selected' : '') ." value='cn'>Customer netblock</option>\n<option".
	(($data[2] eq 'si') ? ' selected' : '') ." value='si'>Static IP - Server pool</option>\n<option".
	(($data[2] eq 'ci') ? ' selected' : '') ." value='ci'>Static IP - Cable</option>\n<option".
	(($data[2] eq 'di') ? ' selected' : '') ." value='di'>Static IP - DSL</option>\n<option".
	(($data[2] eq 'mi') ? ' selected' : '') ." value='mi'>Static IP - Dialup</option>\n<option".
	(($data[2] eq 'wi') ? ' selected' : '') ." value='wi'>Static IP - Wireless</option>\n<option".
	(($data[2] eq 'sd') ? ' selected' : '') ." value='sd'>Static Pool - Server pool</option>\n<option".
	(($data[2] eq 'cd') ? ' selected' : '') ." value='cd'>Static Pool - Cable</option>\n<option".
	(($data[2] eq 'dp') ? ' selected' : '') ." value='dp'>Static Pool - DSL</option>\n<option".
	(($data[2] eq 'mp') ? ' selected' : '') ." value='mp'>Static Pool - Dialup</option>\n<option".
	(($data[2] eq 'wp') ? ' selected' : '') ." value='wp'>Static Pool - Wireless</option>\n<option".
	(($data[2] eq 'en') ? ' selected' : '') ." value='en'>End-use netblock</option>\n<option".
	(($data[2] eq 'me') ? ' selected' : '') ." value='me'>Dialup netblock</option>\n<option".
	(($data[2] eq 'de') ? ' selected' : '') ." value='de'>Dynamic DSL netblock</option>\n<option".
	(($data[2] eq 'ce') ? ' selected' : '') ." value='ce'>Dynamic cable netblock</option>\n<option".
	(($data[2] eq 'we') ? ' selected' : '') ." value='we'>Dynamic WiFi netblock</option>\n<option".
	(($data[2] eq 'in') ? ' selected' : '') ." value='in'>Internal netblock</option>\n".
        "</select></td>\n";
    print qq(<td><input name=city value="$data[3]"></td>\n).
	"<td>$data[4]</td><td>$data[5]</td>".
	qq(<td><input type=submit value="Update"></td></form></tr>\n);
  }
  print "</table>\n";

  # notes
  print "<hr><b>Notes:</b>\n".
	"<ul>\n<li>Use the main interface to update description and notes fields\n".
	"<li>Changing the allocation type here will NOT affect IP pool data.\n".
	"</ul>\n";
}


# Stuff updates into DB
sub update {
  eval {
    # Relatively simple SQL transaction here.  Note that we're deliberately NOT
    # updating notes/desc here as it's available through the main interface.
    $sth = $ip_dbh->prepare("update allocations set custid='$webvar{custid}',".
	"city='$webvar{city}',type='$webvar{alloctype}' where cidr='$webvar{block}'");
    $sth->execute;
    $ip_dbh->commit;
  };
  if ($@) {
    carp "Transaction aborted because $@";
    eval { $ip_dbh->rollback; };
    syslog "err", "$authuser could not update block '$webvar{block}': '$@'";
  } else {
    # If we get here, the operation succeeded.
    syslog "notice", "$authuser updated $webvar{block}";
    print "Allocation $webvar{block} updated<hr>\n";
  }
  # need to get /24 that block is part of
  my @bits = split /\./, $webvar{block};
  $bits[3] = "0/24";
  showAllocs((join ".", @bits));
}


# showPool()
# List all IPs in a pool, and allow arbitrary admin changes to each
# Allow changes to ALL fields
sub showPool($) {
  my $pool = new NetAddr::IP $_[0];
  print qq(Listing pool $pool:\n<table border=1>
<form action=admin.cgi method=POST>
<input type=hidden name=action value=updatepool>
<tr><td align=right>Customer ID:</td><td><input name=custid></td></tr>
<tr><td align=right>Customer location:</td><td><input name=city></td></tr>
<tr><td align=right>Type:</td><td><select name=type><option selected>-</option>
<option value="si">Static IP - Server pool</option>
<option value="ci">Static IP - Cable</option>
<option value="di">Static IP - DSL</option>
<option value="mi">Static IP - Dialup</option>
<option value="wi">Static IP - Wireless</option>
</select></td></tr>
<tr><td align=right>Available?</td><td><input type=checkbox value=y></td></tr>
<tr><td align=right>Description/name:</td><td><input name=desc size=40></td></tr>
<tr><td align=right>Notes:</td><td><textarea name=notes rows=3 cols=40></textarea></td></tr>
<tr><td colspan=2 align=center><input type=submit value="Update"></td></tr>
).
	"</table>Update the following record:<table border=1>\n";
  $sth = $ip_dbh->prepare("select pool,ip,custid,city,type,available,description,notes from poolips where pool='$pool' order by ip");
  $sth->execute;
  while (my @data = $sth->fetchrow_array) {
    print qq(<tr><td><input type=radio name=ip value="$data[1]">$data[1]</td>).
	"<td>$data[2]</td><td>$data[3]</td><td>$data[4]</td>".
	"<td>$data[5]</td><td>$data[6]</td><td>$data[7]</td></tr>\n";
  }
  print "</form></table>\n";
}
