#!/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: 2010-09-21 04:19:32 +0000 (Tue, 21 Sep 2010) $ # SVN revision $Rev: 484 $ # 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 CommonWeb qw(:ALL); 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-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"; # 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); # 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"; 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; } # 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 Type:$disp_alloctypes{$webvar{alloctype}} Allocated from: $alloc_from Customer ID:$custid Customer location:  Add new location Circuit ID: Description/Name: Notes:
WARNING: This will IMMEDIATELY assign this block!!
); } elsif ($webvar{action} eq 'confirm') { print "Assigning $webvar{cidr} to $webvar{custid} (\"$webvar{desc}\") as ". "$disp_alloctypes{$webvar{alloctype}}...
\n"; # Only need to check city here. if ($webvar{city} eq '-') { printError("Invalid customer location! Go back and select customer's location."); } else { if ($webvar{alloctype} =~ /^.i$/) { $sth = $ip_dbh->prepare("update poolips set available='n', custid='$webvar{custid}', ". "city='$webvar{city}', description='$webvar{desc}', notes='$webvar{notes}' ". "where ip='$webvar{cidr}'"); $sth->execute; if ($sth->err) { print "Allocation failed! DBI said:\n".$sth->errstr."\n"; syslog "err", "($authuser) Allocation of '$webvar{cidr}' to '$webvar{custid}' as ". "'$webvar{alloctype}' failed: '".$sth->errstr."'"; } else { print "Allocation OK!\n"; syslog "notice", "$authuser allocated '$webvar{cidr}' to '$webvar{custid}' as ". "'$webvar{alloctype}'"; 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 { 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"; 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'"; } } # static IP vs netblock } # 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 =~ 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($_\n); } $html =~ s/\$\$BLOCKLIST\$\$/$availblocks/g; print $html; } elsif ($webvar{action} eq 'touch') { $page->param(master => $webvar{whichmaster}); $sth = $ip_dbh->prepare("update masterblocks set mtime=now() where cidr='$webvar{whichmaster}'"); $sth->execute; if ($sth->err) { $page->param(errmsg => $sth->errstr); } } elsif ($webvar{action} eq 'listcust') { $sth = $ip_dbh->prepare("select custid,name,tech_handle from customers order by custid"); $sth->execute; my @custlist; while (my @data = $sth->fetchrow_array) { my %row = ( custid => $data[0], custname => $data[1], tech => $data[2] ); push @custlist, \%row; } $page->param(custlist => \@custlist); } 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') { $sth = $ip_dbh->prepare("UPDATE customers SET". " name=?, street=?, city=?, province=?, country=?, pocode=?,". " phone=?, tech_handle=?, abuse_handle=?, admin_handle=?, special=?". " WHERE custid=?"); $sth->execute($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( 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') { $sth = $ip_dbh->prepare("select pool, count(*) from poolips where available='y' group by pool order by pool"); $sth->execute; my @poollist; while (my ($pool,$free) = $sth->fetchrow_array) { my %row = ( pool => $pool, free => $free ); push @poollist, \%row; } $page->param(poollist => \@poollist); } elsif ($webvar{action} eq 'tweakpool') { showPool($webvar{pool}); } elsif ($webvar{action} eq 'updatepool') { $sth = $ip_dbh->prepare("update poolips set custid='$webvar{custid}', ". "city=?, type='$webvar{type}', available='". (($webvar{available} eq 'y') ? 'y' : 'n'). "', notes=?, description=? ". "where ip='$webvar{ip}'"); $sth->execute($webvar{city},$webvar{notes},$webvar{desc}); if ($sth->err) { print "Error updating pool IP $webvar{ip}: $@
\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
\n"; syslog "notice", "$authuser updated pool IP $webvar{ip}"; } } 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') { print "

Email notice management:

\nClick the email addresses to edit that list."; $sth = $ip_dbh->prepare("SELECT action,reciplist FROM notify"); $sth->execute; print "\n"; 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); print "". qq(). qq(\n); } print qq(
$action_out$reciplistDelete
Known "special" codes:
  • swi: Notify if block being updated has SWIP flag set
); # add new entries from this tangle: print "

Add new notification:

\n". "Note: Failure notices on most conditions are not yet supported.\n"; print qq(
Recipients
Action
Add   Update   Delete   New listitem
Special: (requires code changes)
Failure?
Event/Allocation type: ); $sth = $ip_dbh->prepare("SELECT type,dispname FROM alloctypes WHERE listorder < 500 ". "ORDER BY listorder"); $sth->execute; my $i=0; while (my ($type,$disp) = $sth->fetchrow_array) { print " "; $i++; print " \n\t" if ($i % 4 == 0); } print qq(
All allocations All static IPs New city New node
$disp
); ## done spitting out add-new-spam-me-now table } elsif ($webvar{action} eq 'addnotice') { $webvar{alloctype} = $webvar{special} if $webvar{msgaction} eq 's:'; if ($webvar{msgaction} && $webvar{alloctype} && $webvar{reciplist}) { $webvar{reciplist} =~ s/[\r\n]+/,/g; $webvar{msgaction} = "f:$webvar{msgaction}" if $webvar{onfail}; print "Adding notice to $webvar{reciplist} for ".dispNoticeCode($webvar{msgaction}.$webvar{alloctype}).":\n"; $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}); if ($sth->err) { print "Failed: DB error: ".$sth->errstr."\n"; } else { print "OK!
\n" } } else { print "Need to specify at least one recipient, an action, and an allocation type. ". qq{("Special" content is considered an allocation type). Hit the Back button and try again.
\n}; } print qq(Back to email notice list\n); } elsif ($webvar{action} eq 'delnotice') { print "Deleting notices on ".dispNoticeCode($webvar{code}.$webvar{alloctype}).":\n"; $sth = $ip_dbh->prepare("DELETE FROM notify WHERE action=?"); $sth->execute($webvar{code}); if ($sth->err) { print "Failed: DB error: ".$sth->errstr."\n"; } else { print "OK!
\n" } print qq(Back to email notice list\n); } elsif ($webvar{action} eq 'ednotice') { print "

Editing recipient list for '".dispNoticeCode($webvar{code})."':

\n"; $sth = $ip_dbh->prepare("SELECT reciplist FROM notify WHERE action=?"); $sth->execute($webvar{code}); my ($reciplist) = $sth->fetchrow_array; $reciplist =~ s/,/\n/g; print qq(
\n). qq(
). qq(\n). "
\n"; } elsif ($webvar{action} eq 'updnotice') { print "

Updating recipient list for '".dispNoticeCode($webvar{code})."':

\n"; $sth = $ip_dbh->prepare("UPDATE notify SET reciplist=? WHERE action=?"); $webvar{reciplist} =~ s/[\r\n]+/,/g; $sth->execute($webvar{reciplist}, $webvar{code}); if ($sth->err) { print "Failed: DB error: ".$sth->errstr."\n"; } else { print "OK!
\n" } print qq(Back to email notice list\n); } elsif ($webvar{action} ne '') { print "webvar{action} check failed: Don't know how to $webvar{action}"; } print "Content-type: text/html\n\n".$header->output; print $page->output; ##fixme: make me a footer param! print qq(
Back to main interface
\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; $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"; } } # List free blocks in a /24 for arbitrary manual allocation sub showfree($) { my $cidr = new NetAddr::IP $_[0]; print "Showing free blocks in $cidr
\n". "\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 "\n". qq(\n). "". qq(). "\n\n"; } print "
$temp". (($temp->masklen == 30) ? '30' : "$data[2]
\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"; $sth = $ip_dbh->prepare("select * from allocations where cidr <<= '$cidr' order by cidr"); $sth->execute; while (my @data = $sth->fetchrow_array) { print "\n". qq(\n). qq(\n). "\n). "". qq(\n); } print "
$data[0]$data[4]$data[5]
\n"; # notes print "
Notes:\n". "\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
\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 ). "
Customer ID:
Customer location:
Type:
Available?
Description/name:
Notes:
Update the following record:\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(). "". "\n"; } print "
$data[1]$data[2]$data[3]$data[4]$data[5]$data[6]$data[7]
\n"; } # 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 .= '<unknown>'; } } 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; }