source: trunk/cgi-bin/main.cgi@ 527

Last change on this file since 527 was 527, checked in by Kris Deugau, 12 years ago

/trunk

Clean up and move SQL for showRBlock to IPDB.pm
Tweak listFree() since the segments in showMaster and showRBlock it
replaced weren't quite as identical as I thought
Convert template to use odd and squeeze a bit more HTML out of
main.cgi and IPDB.pm

See #34.

  • Property svn:executable set to *
  • Property svn:keywords set to Date Rev Author
File size: 34.5 KB
RevLine 
[4]1#!/usr/bin/perl
2# ipdb/cgi-bin/main.cgi
[8]3###
4# SVN revision info
5# $Date: 2012-10-23 17:32:47 +0000 (Tue, 23 Oct 2012) $
6# SVN revision $Rev: 527 $
7# Last update by $Author: kdeugau $
8###
[417]9# Copyright (C) 2004-2010 - Kris Deugau
[4]10
11use strict;
12use warnings;
13use CGI::Carp qw(fatalsToBrowser);
[517]14use CGI::Simple;
15use HTML::Template;
[4]16use DBI;
17use POSIX qw(ceil);
18use NetAddr::IP;
19
20use Sys::Syslog;
21
[417]22# don't remove! required for GNU/FHS-ish install from tarball
23##uselib##
24
[515]25use CustIDCK;
[417]26use MyIPDB;
27
[431]28openlog "IPDB","pid","$IPDB::syslog_facility";
[4]29
[517]30## Environment. Collect some things, process some things, set some things...
31
[233]32# Collect the username from HTTP auth. If undefined, we're in
33# a test environment, or called without a username.
[4]34my $authuser;
35if (!defined($ENV{'REMOTE_USER'})) {
36 $authuser = '__temptest';
37} else {
38 $authuser = $ENV{'REMOTE_USER'};
39}
40
[517]41# anyone got a better name? :P
42my $thingroot = $ENV{SCRIPT_FILENAME};
43$thingroot =~ s|cgi-bin/main.cgi||;
44
[402]45syslog "debug", "$authuser active, $ENV{'REMOTE_ADDR'}";
[4]46
[517]47##fixme there *must* be a better order to do things in so this can go back where it was
48# CGI fiddling done here so we can declare %webvar so we can alter $webvar{action}
49# to show the right page on DB errors.
50# Set up the CGI object...
51my $q = new CGI::Simple;
52# ... and get query-string params as well as POST params if necessary
53$q->parse_query_string;
54
55# Convenience; saves changing all references to %webvar
56##fixme: tweak for handling <select multiple='y' size=3> (list with multiple selection)
57my %webvar = $q->Vars;
58
[106]59# Why not a global DB handle? (And a global statement handle, as well...)
60# Use the connectDB function, otherwise we end up confusing ourselves
61my $ip_dbh;
62my $sth;
63my $errstr;
[142]64($ip_dbh,$errstr) = connectDB_My;
[106]65if (!$ip_dbh) {
[517]66 $webvar{action} = "dberr";
67} else {
68 initIPDBGlobals($ip_dbh);
[106]69}
[4]70
[517]71# Set up some globals
72$ENV{HTML_TEMPLATE_ROOT} = $thingroot."templates";
[233]73
[517]74my $header = HTML::Template->new(filename => "header.tmpl");
75my $footer = HTML::Template->new(filename => "footer.tmpl");
[233]76
[517]77$header->param(version => $IPDB::VERSION);
78$header->param(addperm => $IPDBacl{$authuser} =~ /a/);
79$header->param(webpath => $IPDB::webpath);
80print "Content-type: text/html\n\n", $header->output;
[4]81
82
83#main()
[517]84my $aclerr;
[4]85
86if(!defined($webvar{action})) {
[517]87 $webvar{action} = "index"; #shuts up the warnings.
[4]88}
89
[517]90my $page;
91if (-e "$ENV{HTML_TEMPLATE_ROOT}/$webvar{action}.tmpl") {
[523]92 $page = HTML::Template->new(filename => "$webvar{action}.tmpl", loop_context_vars => 1);
[517]93} else {
94 $page = HTML::Template->new(filename => "dunno.tmpl");
95}
96
[4]97if($webvar{action} eq 'index') {
98 showSummary();
[233]99} elsif ($webvar{action} eq 'addmaster') {
100 if ($IPDBacl{$authuser} !~ /a/) {
[517]101 $aclerr = 'addmaster';
[233]102 }
[4]103} elsif ($webvar{action} eq 'newmaster') {
104
[233]105 if ($IPDBacl{$authuser} !~ /a/) {
[517]106 $aclerr = 'addmaster';
[233]107 } else {
108 my $cidr = new NetAddr::IP $webvar{cidr};
[517]109 $page->param(cidr => "$cidr");
[4]110
[371]111 my ($code,$msg) = addMaster($ip_dbh, $webvar{cidr});
[4]112
[371]113 if ($code eq 'FAIL') {
[320]114 syslog "err", "Could not add master block '$webvar{cidr}' to database: '$msg'";
[517]115 $page->param(err => $msg);
[233]116 } else {
117 syslog "info", "$authuser added master block $webvar{cidr}";
118 }
[4]119
[233]120 } # ACL check
121
[4]122} # end add new master
123
124elsif($webvar{action} eq 'showmaster') {
125 showMaster();
126}
127elsif($webvar{action} eq 'showrouted') {
128 showRBlock();
129}
130elsif($webvar{action} eq 'listpool') {
131 listPool();
132}
133
134# Not modified or added; just shuffled
135elsif($webvar{action} eq 'assign') {
136 assignBlock();
137}
138elsif($webvar{action} eq 'confirm') {
139 confirmAssign();
140}
141elsif($webvar{action} eq 'insert') {
142 insertAssign();
143}
144elsif($webvar{action} eq 'edit') {
145 edit();
146}
147elsif($webvar{action} eq 'update') {
148 update();
149}
150elsif($webvar{action} eq 'delete') {
151 remove();
152}
153elsif($webvar{action} eq 'finaldelete') {
154 finalDelete();
155}
[397]156elsif ($webvar{action} eq 'nodesearch') {
[519]157 my $nodelist = getNodeList($ip_dbh);
158 $page->param(nodelist => $nodelist);
[517]159}
[397]160
[517]161# DB failure. Can't do much here, really.
162elsif ($webvar{action} eq 'dberr') {
163 $page->param(errmsg => $errstr);
[397]164}
165
[517]166# Default is an error. It shouldn't be possible to get here unless you're
167# randomly feeding in values for webvar{action}.
[4]168else {
169 my $rnd = rand 500;
170 my $boing = sprintf("%.2f", rand 500);
[517]171 my @excuses = (
172 "Aether cloudy. Ask again later about $webvar{action}.",
173 "The gods are unhappy with your sacrificial $webvar{action}.",
174 "Because one of $webvar{action}'s legs are both the same",
175 "<b>wibble</b><br>Can't $webvar{action}, the grue will get me!<br>Can't $webvar{action}, the grue will get me!",
176 "Hey, man, you've had your free $webvar{action}. Next one's gonna... <i>cost</i>....",
177 "I ain't done $webvar{action}",
178 "Oooo, look! A flying $webvar{action}!",
179 "$webvar{action} too evil, avoiding.",
180 "Rocks fall, $webvar{action} dies.",
181 "Bit bucket must be emptied before I can $webvar{action}..."
182 );
183 $page->param(dunno => $excuses[$rnd/50.0]);
[4]184}
[111]185## Finally! Done with that NASTY "case" emulation!
[4]186
187
[517]188# Switch to a different template if we've tripped on an ACL error.
189# Note that this should only be exercised in development, when
190# deeplinked, or when being attacked; normal ACL handling should
191# remove the links a user is not allowed to click on.
192if ($aclerr) {
193 $page = HTML::Template->new(filename => "aclerror.tmpl");
194 $page->param(ipdbfunc => $aclmsg{$aclerr});
195}
[4]196
[519]197$sth->finish if $sth;
[106]198# Clean up IPDB globals, DB handle, etc.
[111]199finish($ip_dbh);
[199]200
[517]201## Do all our printing here so we can generate errors and stick them into the slots in the templates.
[199]202
[517]203# can't do this yet, too many blowups
204#print "Content-type: text/html\n\n", $header->output;
205$page->param(webpath => $IPDB::webpath);
206print $page->output;
207
208# include the admin tools link in the output?
209$footer->param(adminlink => ($IPDBacl{$authuser} =~ /A/));
210$footer->param(webpath => $IPDB::webpath);
211print $footer->output;
212
[106]213# Just in case something waaaayyy down isn't in place
214# properly... we exit explicitly.
[517]215exit 0;
[4]216
217
218# Initial display: Show master blocks with total allocated subnets, total free subnets
[118]219sub showSummary {
[523]220 my $masterlist = listSummary($ip_dbh);
221 $page->param(masterlist => $masterlist);
[106]222
[517]223 $page->param(addmaster => ($IPDBacl{$authuser} =~ /a/) );
[4]224} # showSummary
225
226
227# Display detail on master
228# Alrighty then! We're showing routed blocks within a single master this time.
229# We should be able to steal code from showSummary(), and if I'm really smart
230# I'll figger a way to munge the two together. (Once I've done that, everything
231# else should follow. YMMV.)
232sub showMaster {
233
[517]234 $page->param(master => $webvar{block});
235 $page->param(delmaster => ($IPDBacl{$authuser} =~ /d/));
[4]236
[524]237 my $rlist = listMaster($ip_dbh, $webvar{block});
238 $page->param(routedlist => $rlist);
[4]239
[527]240 my $flist = listFree($ip_dbh, $webvar{block});
[524]241 $page->param(unrouted => $flist);
[4]242} # showMaster
243
244
245# Display details of a routed block
246# Alrighty then! We're showing allocations within a routed block this time.
247# We should be able to steal code from showSummary() and showMaster(), and if
248# I'm really smart I'll figger a way to munge all three together. (Once I've
249# done that, everything else should follow. YMMV.
250# This time, we check the database before spewing, because we may
251# not have anything useful to spew.
252sub showRBlock {
253
[527]254 $page->param(master => $webvar{block});
255 $page->param(delrouted => $IPDBacl{$authuser} =~ /d/);
[4]256
[527]257 my $rcity = getRoutedCity($ip_dbh, $webvar{block});
[517]258 $page->param(rcity => $rcity);
[4]259
[527]260 my $blist = listRBlock($ip_dbh, $webvar{block});
261 $page->param(blocklist => $blist);
[4]262
[527]263 my $flist = listFree($ip_dbh, $webvar{block}, 'y');
264 $page->param(unassigned => $flist);
[4]265} # showRBlock
266
267
268# List the IPs used in a pool
269sub listPool {
270
271 my $cidr = new NetAddr::IP $webvar{pool};
272
[517]273 $page->param(block => $webvar{pool});
274 $page->param(netip => $cidr->addr);
275 $cidr++;
276 $page->param(gate => $cidr->addr);
277 $cidr--; $cidr--;
278 $page->param(bcast => $cidr->addr);
279 $page->param(mask => $cidr->mask);
[157]280
[4]281 # Snag pool info for heading
[517]282 $sth = $ip_dbh->prepare("select type,city from allocations where cidr=?");
283 $sth->execute($webvar{pool});
284 my ($pooltype, $poolcity) = $sth->fetchrow_array;
[4]285
[517]286 $page->param(disptype => $disp_alloctypes{$pooltype});
287 $page->param(city => $poolcity);
288
[157]289 # Only display net/gw/bcast if it's a "real" netblock and not a PPP(oE) lunacy
[517]290 $page->param(realblock => $pooltype =~ /^.d$/);
[4]291
292# probably have to add an "edit IP allocation" link here somewhere.
293
[157]294 $sth = $ip_dbh->prepare("select ip,custid,available,description,type".
295 " from poolips where pool='$webvar{pool}' order by ip");
[4]296 $sth->execute;
[517]297 my @poolips;
298 my $rowclass = 0;
299 while (my ($ip,$custid,$available,$desc,$type) = $sth->fetchrow_array) {
300 my %row = (
301 rowclass => $rowclass++ % 2,
302 ip => $ip,
303 custid => $custid,
304 available => $available,
305 desc => $desc,
306 maydel => $IPDBacl{$authuser} =~ /d/,
307 delme => $available eq 'n'
[4]308 );
[517]309 push @poolips, \%row;
[4]310 }
[517]311 $page->param(poolips => \@poolips);
[4]312
313} # end listPool
314
315
[106]316# Show "Add new allocation" page. Note that the actual page may
317# be one of two templates, and the lists come from the database.
[4]318sub assignBlock {
319
[233]320 if ($IPDBacl{$authuser} !~ /a/) {
[517]321 $aclerr = 'addblock';
[233]322 return;
323 }
324
[517]325 # hack pthbttt eww
326 $webvar{block} = '' if !$webvar{block};
[21]327
[517]328# hmm. TMPL_IF block and TMPL_ELSE block on these instead?
329 $page->param(rowa => 'row'.($webvar{block} eq '' ? 1 : 0));
330 $page->param(rowb => 'row'.($webvar{block} eq '' ? 0 : 1));
331 $page->param(block => $webvar{block}); # fb-assign flag, if block is set, we're in fb-assign
332 $page->param(iscontained => ($webvar{fbtype} && $webvar{fbtype} ne 'y'));
333
[21]334 # New special case- block to assign is specified
335 if ($webvar{block} ne '') {
336 my $block = new NetAddr::IP $webvar{block};
[187]337
[517]338 # Handle contained freeblock allocation.
[187]339 # This is a little dangerous, as it's *theoretically* possible to
340 # get fbtype='n' (aka a non-routed freeblock). However, should
341 # someone manage to get there, they get what they deserve.
342 if ($webvar{fbtype} ne 'y') {
[517]343 # Snag the type of the container block from the database.
[187]344 $sth = $ip_dbh->prepare("select type from allocations where cidr >>='$block'");
345 $sth->execute;
346 my @data = $sth->fetchrow_array;
347 $data[0] =~ s/c$/r/; # Munge the type into the correct form
[517]348 $page->param(fbdisptype => $list_alloctypes{$data[0]});
349 $page->param(type => $data[0]);
[187]350 } else {
351 $sth = $ip_dbh->prepare("select type,listname from alloctypes where listorder < 500 ".
[191]352 "and type not like '_i' and type not like '_r' order by listorder");
[187]353 $sth->execute;
[517]354 my @typelist;
355 my $selflag = 0;
[187]356 while (my @data = $sth->fetchrow_array) {
[517]357 my %row = (tval => $data[0],
358 type => $data[1],
359 sel => ($selflag == 0 ? ' selected' : '')
360 );
361 push (@typelist, \%row);
362 $selflag++;
[187]363 }
[517]364 $page->param(typelist => \@typelist);
[106]365 }
[21]366 } else {
[517]367 my @masterlist;
[31]368 foreach my $master (@masterblocks) {
[517]369 my %row = (master => "$master");
370 push (@masterlist, \%row);
[31]371 }
[517]372 $page->param(masterlist => \@masterlist);
373
374 my @pops;
[92]375 foreach my $pop (@poplist) {
[517]376 my %row = (pop => $pop);
377 push (@pops, \%row);
[92]378 }
[517]379 $page->param(pops => \@pops);
380
381 # could arguably include routing (500) in the list, but ATM it doesn't
382 # make sense, and in any case that shouldn't be structurally possible here.
383 $sth = $ip_dbh->prepare("select type,listname from alloctypes where listorder <= 500 order by listorder");
[106]384 $sth->execute;
[517]385 my @typelist;
386 my $selflag = 0;
[106]387 while (my @data = $sth->fetchrow_array) {
[517]388 my %row = (tval => $data[0],
389 type => $data[1],
390 sel => ($selflag == 0 ? ' selected' : '')
391 );
392 push (@typelist, \%row);
393 $selflag++;
[106]394 }
[517]395 $page->param(typelist => \@typelist);
[21]396 }
[517]397
398 my @cities;
[92]399 foreach my $city (@citylist) {
[517]400 my %row = (city => $city);
401 push (@cities, \%row);
[92]402 }
[517]403 $page->param(citylist => \@cities);
[4]404
[397]405## node hack
406 $sth = $ip_dbh->prepare("SELECT node_id, node_name FROM nodes ORDER BY node_type,node_id");
407 $sth->execute() or print "DEBUG: failed retrieval from nodes: ".$sth->errstr,"<br>\n";
[517]408 my @nodes;
[397]409 while (my ($nid,$nname) = $sth->fetchrow_array()) {
[517]410 my %row = (nid => $nid, nname => $nname);
411 push (@nodes, \%row);
[397]412 }
[517]413 $page->param(nodelist => \@nodes);
[397]414## end node hack
415
[517]416 $page->param(privdata => $IPDBacl{$authuser} =~ /s/);
[284]417
[4]418} # assignBlock
419
420
421# Take info on requested IP assignment and see what we can provide.
422sub confirmAssign {
[233]423 if ($IPDBacl{$authuser} !~ /a/) {
[517]424 $aclerr = 'addblock';
[233]425 return;
426 }
[4]427
428 my $cidr;
429 my $alloc_from;
430
431 # Going to manually validate some items.
432 # custid and city are automagic.
[111]433 return if !validateInput();
[4]434
435# Several different cases here.
436# Static IP vs netblock
437# + Different flavours of static IP
438# + Different flavours of netblock
439
[157]440 if ($webvar{alloctype} =~ /^.i$/) {
[4]441 my ($base,undef) = split //, $webvar{alloctype}; # split into individual chars
442
[214]443# Ewww. But it works.
444 $sth = $ip_dbh->prepare("SELECT (SELECT city FROM allocations WHERE cidr=poolips.pool), ".
445 "poolips.pool, COUNT(*) FROM poolips,allocations WHERE poolips.available='y' AND ".
[442]446 "poolips.pool=allocations.cidr AND allocations.city='$webvar{pop}' AND poolips.type LIKE '".$base."_' ".
[214]447 "GROUP BY pool");
[4]448 $sth->execute;
449 my $optionlist;
[517]450
451 my @poollist;
452 while (my ($poolcit,$poolblock,$poolfree) = $sth->fetchrow_array) {
[214]453 # city,pool cidr,free IP count
[517]454 if ($poolfree > 0) {
455 my %row = (poolcit => $poolcit, poolblock => $poolblock, poolfree => $poolfree);
456 push (@poollist, \%row);
[214]457 }
[4]458 }
[517]459 $page->param(staticip => 1);
460 $page->param(poollist => \@poollist);
[4]461 $cidr = "Single static IP";
[517]462##fixme: need to handle "no available pools"
[4]463
464 } else { # end show pool options
[21]465
466 if ($webvar{fbassign} eq 'y') {
467 $cidr = new NetAddr::IP $webvar{block};
468 $webvar{maskbits} = $cidr->masklen;
469 } else { # done with direct freeblocks assignment
470
471 if (!$webvar{maskbits}) {
[517]472 $page->param(err => "Please specify a CIDR mask length.");
[111]473 return;
[21]474 }
475 my $sql;
476 my $city;
477 my $failmsg;
[320]478 my $extracond = '';
479 if ($webvar{allocfrom} eq '-') {
480 $extracond = ($webvar{allowpriv} eq 'on' ? '' :
481 " and not (cidr <<= '192.168.0.0/16'".
482 " or cidr <<= '10.0.0.0/8'".
483 " or cidr <<= '172.16.0.0/12')");
484 }
485 my $sortorder;
[187]486 if ($webvar{alloctype} eq 'rm') {
[31]487 if ($webvar{allocfrom} ne '-') {
488 $sql = "select * from freeblocks where maskbits<=$webvar{maskbits} and routed='n'".
[320]489 " and cidr <<= '$webvar{allocfrom}'";
490 $sortorder = "maskbits desc";
[31]491 } else {
[320]492 $sql = "select * from freeblocks where maskbits<=$webvar{maskbits} and routed='n'";
493 $sortorder = "maskbits desc";
[31]494 }
[21]495 $failmsg = "No suitable free block found.<br>\nWe do not have a free".
496 " routeable block of that size.<br>\nYou will have to either route".
497 " a set of smaller netblocks or a single smaller netblock.";
[4]498 } else {
[118]499##fixme
500# This section needs serious Pondering.
[214]501 # Pools of most types get assigned to the POP they're "routed from"
[187]502 # This includes WAN blocks and other netblock "containers"
[214]503 # This does NOT include cable pools.
504 if ($webvar{alloctype} =~ /^.[pc]$/) {
[37]505 $city = $webvar{city};
[21]506 $failmsg = "No suitable free block found.<br>\nYou will have to route another".
[442]507 " superblock from one of the<br>\nmaster blocks or chose a smaller".
[21]508 " block size for the pool.";
509 } else {
[517]510 if (!$webvar{pop}) {
511 $page->param(err => 'Please select a POP to route the block from/through.');
512 return;
513 }
[21]514 $city = $webvar{pop};
515 $failmsg = "No suitable free block found.<br>\nYou will have to route another".
[442]516 " superblock to $webvar{pop}<br>\nfrom one of the master blocks or".
[21]517 " chose a smaller blocksize.";
518 }
[300]519 if (defined $webvar{allocfrom} && $webvar{allocfrom} ne '-') {
[157]520 $sql = "select cidr from freeblocks where city='$city' and maskbits<=$webvar{maskbits}".
[186]521 " and cidr <<= '$webvar{allocfrom}' and routed='".
[320]522 (($webvar{alloctype} =~ /^(.)r$/) ? "$1" : 'y')."'";
523 $sortorder = "maskbits desc,cidr";
[31]524 } else {
[157]525 $sql = "select cidr from freeblocks where city='$city' and maskbits<=$webvar{maskbits}".
[320]526 " and routed='".(($webvar{alloctype} =~ /^(.)r$/) ? "$1" : 'y')."'";
527 $sortorder = "maskbits desc,cidr";
[31]528 }
[4]529 }
[320]530 $sql = $sql.$extracond." order by ".$sortorder;
[21]531 $sth = $ip_dbh->prepare($sql);
532 $sth->execute;
533 my @data = $sth->fetchrow_array();
534 if ($data[0] eq "") {
[517]535 $page->param(err => $failmsg);
[111]536 return;
[21]537 }
538 $cidr = new NetAddr::IP $data[0];
539 } # check for freeblocks assignment or IPDB-controlled assignment
[4]540
[517]541 $alloc_from = "$cidr";
[4]542
543 # If the block to be allocated is smaller than the one we found,
544 # figure out the "real" block to be allocated.
545 if ($cidr->masklen() ne $webvar{maskbits}) {
546 my $maskbits = $cidr->masklen();
547 my @subblocks;
548 while ($maskbits++ < $webvar{maskbits}) {
549 @subblocks = $cidr->split($maskbits);
550 }
551 $cidr = $subblocks[0];
552 }
[157]553 } # if ($webvar{alloctype} =~ /^.i$/)
[4]554
[397]555## node hack
556 if ($webvar{node} && $webvar{node} ne '-') {
557 $sth = $ip_dbh->prepare("SELECT node_name FROM nodes WHERE node_id=?");
558 $sth->execute($webvar{node});
559 my ($nodename) = $sth->fetchrow_array();
[517]560 $page->param(nodename => $nodename);
561 $page->param(nodeid => $webvar{node});
[397]562 }
563## end node hack
564
[4]565 # Stick in the allocation data
[517]566 $page->param(alloc_type => $webvar{alloctype});
567 $page->param(typefull => $q->escapeHTML($disp_alloctypes{$webvar{alloctype}}));
568 $page->param(alloc_from => $alloc_from);
569 $page->param(cidr => $cidr);
570 $page->param(city => $q->escapeHTML($webvar{city}));
571 $page->param(custid => $webvar{custid});
572 $page->param(circid => $q->escapeHTML($webvar{circid}));
573 $page->param(desc => $q->escapeHTML($webvar{desc}));
[4]574
[517]575##fixme: find a way to have the displayed copy have <br> substitutions
576# for newlines, and the <input> value have either encoded or bare newlines.
577# Also applies to privdata.
578 $page->param(notes => $q->escapeHTML($webvar{notes},'y'));
579
[284]580 # Check to see if user is allowed to do anything with sensitive data
581 my $privdata = '';
[517]582 $page->param(privdata => $q->escapeHTML($webvar{privdata},'y'))
583 if $IPDBacl{$authuser} =~ /s/;
584
585 # Yay! This now has it's very own little home.
586 $page->param(billinguser => $webvar{userid})
[299]587 if $webvar{userid};
[284]588
[517]589##fixme: this is only needed iff confirm.tmpl and
590# confirmRemove.tmpl are merged (quite possible, just
591# a little tedious)
592 $page->param(action => "insert");
[284]593
[4]594} # end confirmAssign
595
596
597# Do the work of actually inserting a block in the database.
598sub insertAssign {
[233]599 if ($IPDBacl{$authuser} !~ /a/) {
[517]600 $aclerr = 'addblock';
[233]601 return;
602 }
[4]603 # Some things are done more than once.
[111]604 return if !validateInput();
[4]605
[284]606 if (!defined($webvar{privdata})) {
607 $webvar{privdata} = '';
608 }
[106]609 # $code is "success" vs "failure", $msg contains OK for a
610 # successful netblock allocation, the IP allocated for static
611 # IP, or the error message if an error occurred.
[517]612
[106]613 my ($code,$msg) = allocateBlock($ip_dbh, $webvar{fullcidr}, $webvar{alloc_from},
614 $webvar{custid}, $webvar{alloctype}, $webvar{city}, $webvar{desc}, $webvar{notes},
[397]615 $webvar{circid}, $webvar{privdata}, $webvar{node});
[4]616
[111]617 if ($code eq 'OK') {
[106]618 if ($webvar{alloctype} =~ /^.i$/) {
[300]619 $msg =~ s|/32||;
[517]620 $page->param(staticip => $msg);
621 $page->param(custid => $webvar{custid});
622 $page->param(billinguser => $webvar{billinguser});
[416]623 mailNotify($ip_dbh, "a$webvar{alloctype}", "ADDED: $disp_alloctypes{$webvar{alloctype}} allocation",
624 "$disp_alloctypes{$webvar{alloctype}} $msg allocated to customer $webvar{custid}\n".
625 "Description: $webvar{desc}\n\nAllocated by: $authuser\n");
[106]626 } else {
[301]627 my $netblock = new NetAddr::IP $webvar{fullcidr};
[517]628 $page->param(fullcidr => $webvar{fullcidr});
629 $page->param(alloctype => $disp_alloctypes{$webvar{alloctype}});
630 $page->param(custid => $webvar{custid});
631 if ($webvar{alloctype} eq 'pr' && $webvar{billinguser}) {
632 $page->param(billinguser => $webvar{billinguser});
633 $page->param(custid => $webvar{custid});
634 $page->param(netaddr => $netblock->addr);
635 $page->param(masklen => $netblock->masklen);
636 }
[416]637 mailNotify($ip_dbh, "a$webvar{alloctype}", "ADDED: $disp_alloctypes{$webvar{alloctype}} allocation",
638 "$disp_alloctypes{$webvar{alloctype}} $webvar{fullcidr} allocated to customer $webvar{custid}\n".
639 "Description: $webvar{desc}\n\nAllocated by: $authuser\n");
[4]640 }
[106]641 syslog "notice", "$authuser allocated '$webvar{fullcidr}' to '$webvar{custid}' as ".
[256]642 "'$webvar{alloctype}' ($msg)";
[111]643 } else {
644 syslog "err", "Allocation of '$webvar{fullcidr}' to '$webvar{custid}' as ".
645 "'$webvar{alloctype}' by $authuser failed: '$msg'";
[517]646 $page->param(err => "Allocation of $webvar{fullcidr} as '$disp_alloctypes{$webvar{alloctype}}'".
[157]647 " failed:<br>\n$msg\n");
[106]648 }
[4]649
650} # end insertAssign()
651
652
653# Does some basic checks on common input data to make sure nothing
654# *really* weird gets in to the database through this script.
655# Does NOT do complete input validation!!!
656sub validateInput {
657 if ($webvar{city} eq '-') {
[517]658 $page->param(err => 'Please choose a city');
[111]659 return;
[4]660 }
[138]661
662 # Alloctype check.
[4]663 chomp $webvar{alloctype};
[138]664 if (!grep /$webvar{alloctype}/, keys %disp_alloctypes) {
665 # Danger! Danger! alloctype should ALWAYS be set by a dropdown. Anyone
666 # managing to call things in such a way as to cause this deserves a cryptic error.
[517]667 $page->param(err => 'Invalid alloctype');
[138]668 return;
669 }
670
671 # CustID check
[4]672 # We have different handling for customer allocations and "internal" or "our" allocations
[214]673 if ($def_custids{$webvar{alloctype}} eq '') {
[4]674 if (!$webvar{custid}) {
[517]675 $page->param(err => 'Please enter a customer ID.');
[111]676 return;
[4]677 }
[400]678 if ($webvar{custid} !~ /^(?:\d{10}|\d{7}|STAFF)(?:-\d\d?)?$/) {
679 # Force uppercase for now...
680 $webvar{custid} =~ tr/a-z/A-Z/;
681 # Crosscheck with billing.
682 my $status = CustIDCK->custid_exist($webvar{custid});
683 if ($CustIDCK::Error) {
[517]684 $page->param(err => "Error verifying customer ID: ".$CustIDCK::ErrMsg);
[400]685 return;
686 }
687 if (!$status) {
[517]688 $page->param(err => "Customer ID not valid. Make sure the Customer ID ".
[420]689 "is correct.<br>\nUse STAFF for staff static IPs, and $IPDB::defcustid for any other ".
[400]690 "non-customer assignments.");
691 return;
692 }
[4]693 }
[400]694# print "<!-- [ In validateInput(). Insert customer ID cross-check here. ] -->\n";
[138]695 } else {
[167]696 # New! Improved! And now Loaded From The Database!!
[320]697 if ((!$webvar{custid}) || ($webvar{custid} ne 'STAFF')) {
698 $webvar{custid} = $def_custids{$webvar{alloctype}};
699 }
[4]700 }
[111]701
702 # Check POP location
703 my $flag;
[187]704 if ($webvar{alloctype} eq 'rm') {
[111]705 $flag = 'for a routed netblock';
706 foreach (@poplist) {
707 if (/^$webvar{city}$/) {
708 $flag = 'n';
709 last;
710 }
711 }
712 } else {
713 $flag = 'n';
[442]714##fixme: hook to force-set POP or city on certain alloctypes
715# if ($webvar{alloctype =~ /foo,bar,bz/ { $webvar{pop} = 'blah'; }
[400]716 if ($webvar{pop} =~ /^-$/) {
[111]717 $flag = 'to route the block from/through';
718 }
719 }
[517]720
721 # if the alloctype has a restricted city/POP list as determined above,
722 # and the reqested city/POP does not match that list, complain
[111]723 if ($flag ne 'n') {
[517]724 $page->param(err => "Please choose a valid POP location $flag. Valid ".
[111]725 "POP locations are currently:<br>\n".join (" - ", @poplist));
726 return;
727 }
728
729 return 'OK';
[4]730} # end validateInput
731
732
733# Displays details of a specific allocation in a form
734# Allows update/delete
735# action=edit
736sub edit {
737
738 my $sql;
739
740 # Two cases: block is a netblock, or block is a static IP from a pool
741 # because I'm lazy, we'll try to make the SELECT's bring out identical)ish) data
[517]742##fixme: allow "SWIP" (publication to rWHOIS) of static IP data
[4]743 if ($webvar{block} =~ /\/32$/) {
[455]744 $sql = "select ip,custid,type,city,circuitid,description,notes,modifystamp,privdata from poolips where ip='$webvar{block}'";
[4]745 } else {
[455]746 $sql = "select cidr,custid,type,city,circuitid,description,notes,modifystamp,privdata,swip from allocations where cidr='$webvar{block}'"
[4]747 }
748
749 # gotta snag block info from db
750 $sth = $ip_dbh->prepare($sql);
751 $sth->execute;
752 my @data = $sth->fetchrow_array;
753
754 # Clean up extra whitespace on alloc type
755 $data[2] =~ s/\s//;
756
757 # We can't let the city be changed here; this block is a part of
758 # a larger routed allocation and therefore by definition can't be moved.
759 # block and city are static.
760##fixme
761# Needs thinking. Have to allow changes to city to correct errors, no?
[517]762# Also have areas where a routed block at a POP serves "many" cities/towns/named crossroads
[4]763
[517]764# @data: cidr,custid,type,city,circuitid,description,notes,modifystamp,privdata,swip
[233]765
[517]766 $page->param(block => $webvar{block});
[4]767
[517]768 $page->param(custid => $data[1]);
769 $page->param(city => $data[3]);
770 $page->param(circid => $data[4]);
771 $page->param(desc => $data[5]);
772 $page->param(notes => $data[6]);
[4]773
[187]774##fixme The check here should be built from the database
[517]775# Need to expand to support pool types too
776 if ($data[2] =~ /^.[ne]$/ && $IPDBacl{$authuser} =~ /c/) {
777 $page->param(changetype => 1);
778 $page->param(alloctype => [
779 { selme => ($data[2] eq 'me'), type => "me", disptype => "Dialup netblock" },
780 { selme => ($data[2] eq 'de'), type => "de", disptype => "Dynamic DSL netblock" },
781 { selme => ($data[2] eq 'ce'), type => "ce", disptype => "Dynamic cable netblock" },
782 { selme => ($data[2] eq 'we'), type => "we", disptype => "Dynamic wireless netblock" },
783 { selme => ($data[2] eq 'cn'), type => "cn", disptype => "Customer netblock" },
784 { selme => ($data[2] eq 'en'), type => "en", disptype => "End-use netblock" },
785 { selme => ($data[2] eq 'in'), type => "in", disptype => "Internal netblock" },
786 ]
787 );
788 } else {
789 $page->param(disptype => $disp_alloctypes{$data[2]});
790 $page->param(type => $data[2]);
791 }
792
[397]793## node hack
[517]794 $sth = $ip_dbh->prepare("SELECT nodes.node_id,node_name FROM nodes INNER JOIN noderef".
795 " ON nodes.node_id=noderef.node_id WHERE noderef.block='$webvar{block}'");
[397]796 $sth->execute;
[517]797 my ($nodeid,$nodename) = $sth->fetchrow_array();
798 $page->param(havenodeid => $nodeid);
799
800 if ($data[2] eq 'fr' || $data[2] eq 'bi') {
801 $page->param(typesupportsnodes => 1);
802 $page->param(nodename => $nodename);
803
804##fixme: this whole hack needs cleanup and generalization for all alloctypes
805##fixme: arguably a bug that presence of a nodeid implies it can be changed..
806# but except for manual database changes, only the two types fr and bi can
807# (currently) have a nodeid set in the first place.
808 if ($IPDBacl{$authuser} =~ /c/) {
[397]809 $sth = $ip_dbh->prepare("SELECT node_id, node_name FROM nodes ORDER BY node_type,node_id");
[517]810 $sth->execute;
811 my @nodelist;
[397]812 while (my ($nid,$nname) = $sth->fetchrow_array()) {
[517]813 my %row = (
814 selme => ($nodeid == $nid),
815 nodeid => $nid,
816 nodename => $nname,
817 );
818 push (@nodelist, \%row);
[397]819 }
[517]820 $page->param(nodelist => \@nodelist);
[397]821 }
822 }
823## end node hack
[517]824
[255]825 my ($lastmod,undef) = split /\s+/, $data[7];
[517]826 $page->param(lastmod => $lastmod);
[33]827
[517]828 # not happy with the upside-down logic, but...
829 $page->param(swipable => $data[2] !~ /.i/);
830 $page->param(swip => $data[10] ne 'n');
[320]831
[284]832 # Check to see if we can display sensitive data
[517]833 $page->param(nocling => $IPDBacl{$authuser} =~ /s/);
834 $page->param(privdata => $data[8]);
[284]835
[517]836 # ACL trickery - these two template booleans control the presence of all form/input tags
837 $page->param(maychange => $IPDBacl{$authuser} =~ /c/);
838 $page->param(maydel => $IPDBacl{$authuser} =~ /d/);
[4]839
840} # edit()
841
842
843# Stuff new info about a block into the db
844# action=update
845sub update {
[284]846 if ($IPDBacl{$authuser} !~ /c/) {
[517]847 $aclerr = 'updateblock';
[284]848 return;
849 }
[4]850
[284]851 # Check to see if we can update restricted data
852 my $privdata = '';
853 if ($IPDBacl{$authuser} =~ /s/) {
854 $privdata = ",privdata='$webvar{privdata}'";
855 }
856
[4]857 # Make sure incoming data is in correct format - custID among other things.
[228]858 return if !validateInput;
[4]859
860 # SQL transaction wrapper
861 eval {
862 # Relatively simple SQL transaction here.
863 my $sql;
[157]864 if (my $pooltype = ($webvar{alloctype} =~ /^(.)i$/) ) {
[517]865 $sql = "UPDATE poolips SET custid='$webvar{custid}',".
866 "city=?,description=?,notes=?,".
867 "circuitid='$webvar{circid}',".
[284]868 "$privdata where ip='$webvar{block}'";
[4]869 } else {
[517]870 $sql = "UPDATE allocations SET custid='$webvar{custid}',".
871 "city=?,description=?,notes=?,".
872 "circuitid='$webvar{circid}'$privdata,".
873 "type='$webvar{alloctype}',".
[320]874 "swip='".($webvar{swip} eq 'on' ? 'y' : 'n')."' ".
[284]875 "where cidr='$webvar{block}'";
[4]876 }
[157]877 # Log the details of the change.
878 syslog "debug", $sql;
[4]879 $sth = $ip_dbh->prepare($sql);
[517]880 $sth->execute($webvar{city}, $webvar{desc}, $webvar{notes});
[397]881## node hack
882 if ($webvar{node}) {
[517]883 # done with delete/insert so we don't have to worry about funkyness updating a node ref that isn't there
[397]884 $ip_dbh->do("DELETE FROM noderef WHERE block='$webvar{block}'");
885 $sth = $ip_dbh->prepare("INSERT INTO noderef (block,node_id) VALUES (?,?)");
886 $sth->execute($webvar{block},$webvar{node});
887 }
888## end node hack
[4]889 $ip_dbh->commit;
890 };
891 if ($@) {
[166]892 my $msg = $@;
[4]893 eval { $ip_dbh->rollback; };
[166]894 syslog "err", "$authuser could not update block/IP '$webvar{block}': '$msg'";
[517]895 $page->param(err => "Could not update block/IP $webvar{block}: $msg");
[111]896 return;
[4]897 }
898
899 # If we get here, the operation succeeded.
900 syslog "notice", "$authuser updated $webvar{block}";
[416]901##fixme: need to wedge something in to allow "update:field" notifications
902## hmm. how to tell what changed? O_o
[426]903mailNotify($ip_dbh, 's:swi', "SWIPed: $disp_alloctypes{$webvar{alloctype}} $webvar{block}",
[416]904 "$webvar{block} had SWIP status changed to \"Yes\" by $authuser") if $webvar{swip} eq 'on';
[4]905
[517]906## node hack
907 if ($webvar{node} && $webvar{node} ne '-') {
908 $sth = $ip_dbh->prepare("SELECT node_name FROM nodes WHERE node_id=?");
909 $sth->execute($webvar{node});
910 my ($nodename) = $sth->fetchrow_array();
911 $page->param(nodename => $nodename);
912 }
913## end node hack
914
[380]915 # Link back to browse-routed or list-pool page on "Update complete" page.
916 my $cblock; # to contain the CIDR of the container block we're retrieving.
917 my $sql;
918 if (my $pooltype = ($webvar{alloctype} =~ /^(.)i$/) ) {
[517]919 $page->param(backpool => 1);
[380]920 $sql = "select pool from poolips where ip='$webvar{block}'";
921 } else {
922 $sql = "select cidr from routed where cidr >>= '$webvar{block}'";
923 }
924 # I define there to be no errors on this operation... so we don't need to check for them.
925 $sth = $ip_dbh->prepare($sql);
926 $sth->execute;
927 $sth->bind_columns(\$cblock);
928 $sth->fetch();
929 $sth->finish;
[517]930 $page->param(backblock => $cblock);
[380]931
[517]932 $page->param(cidr => $webvar{block});
933 $page->param(city => $webvar{city});
934 $page->param(disptype => $disp_alloctypes{$webvar{alloctype}});
935 $page->param(custid => $webvar{custid});
936 $page->param(swip => $webvar{swip} eq 'on' ? 'Yes' : 'No');
937 $page->param(circid => $q->escapeHTML($webvar{circid}));
938 $page->param(desc => $q->escapeHTML($webvar{desc}));
939 $page->param(notes => $q->escapeHTML($webvar{notes}));
940 $webvar{privdata} = ($webvar{privdata} ? $q->escapeHTML($webvar{privdata}) : "&nbsp;");
941 $page->param(privdata => $webvar{privdata})
942 if $IPDBacl{$authuser} =~ /s/;
[4]943
944} # update()
945
946
947# Delete an allocation.
[106]948sub remove {
[233]949 if ($IPDBacl{$authuser} !~ /d/) {
[517]950 $aclerr = 'delblock';
[233]951 return;
952 }
953
[4]954 # Serves'em right for getting here...
955 if (!defined($webvar{block})) {
[517]956 $page->param(err => "Can't delete a block that doesn't exist");
[111]957 return;
[4]958 }
959
[284]960 my ($cidr, $custid, $type, $city, $circid, $desc, $notes, $alloctype, $privdata);
[4]961
[187]962 if ($webvar{alloctype} eq 'rm') {
[4]963 $sth = $ip_dbh->prepare("select cidr,city from routed where cidr='$webvar{block}'");
964 $sth->execute();
965
966# This feels... extreme.
967 croak $sth->errstr() if($sth->errstr());
968
969 $sth->bind_columns(\$cidr,\$city);
970 $sth->execute();
971 $sth->fetch || croak $sth->errstr();
972 $custid = "N/A";
973 $alloctype = $webvar{alloctype};
[74]974 $circid = "N/A";
[4]975 $desc = "N/A";
976 $notes = "N/A";
[517]977 $privdata = "N/A";
[4]978
979 } elsif ($webvar{alloctype} eq 'mm') {
[517]980
[4]981 $cidr = $webvar{block};
982 $city = "N/A";
983 $custid = "N/A";
984 $alloctype = $webvar{alloctype};
[74]985 $circid = "N/A";
[4]986 $desc = "N/A";
987 $notes = "N/A";
[517]988 $privdata = "N/A";
989
[189]990 } elsif ($webvar{alloctype} =~ /^.i$/) { # done with alloctype=[rm]m
[4]991
992 # Unassigning a static IP
[284]993 my $sth = $ip_dbh->prepare("select ip,custid,city,type,notes,circuitid,privdata".
994 " from poolips where ip='$webvar{block}'");
[4]995 $sth->execute();
996# croak $sth->errstr() if($sth->errstr());
997
[284]998 $sth->bind_columns(\$cidr, \$custid, \$city, \$alloctype, \$notes, \$circid,
999 \$privdata);
[4]1000 $sth->fetch() || croak $sth->errstr;
1001
[157]1002 } else { # done with alloctype=~ /^.i$/
[4]1003
[284]1004 my $sth = $ip_dbh->prepare("select cidr,custid,type,city,circuitid,description,notes,privdata".
1005 " from allocations where cidr='$webvar{block}'");
[4]1006 $sth->execute();
1007# croak $sth->errstr() if($sth->errstr());
1008
[284]1009 $sth->bind_columns(\$cidr, \$custid, \$alloctype, \$city, \$circid, \$desc,
1010 \$notes, \$privdata);
[74]1011 $sth->fetch() || carp $sth->errstr;
[4]1012 } # end cases for different alloctypes
1013
[517]1014 $page->param(block => $cidr);
1015 $page->param(disptype => $disp_alloctypes{$alloctype});
1016 $page->param(type => $alloctype);
1017 $page->param(city => $city);
1018 $page->param(custid => $custid);
1019 $page->param(circid => $circid);
1020 $page->param(desc => $desc);
1021 $page->param(notes => $notes);
1022 $privdata = '&nbsp;' if $privdata eq '';
1023 $page->param(privdata => $privdata) if $IPDBacl{$authuser} =~ /s/;
1024 $page->param(delpool => $alloctype =~ /^.[pd]$/);
[4]1025
[517]1026} # end remove()
[4]1027
1028
1029# Delete an allocation. Return it to the freeblocks table; munge
1030# data as necessary to keep as few records as possible in freeblocks
1031# to prevent weirdness when allocating blocks later.
1032# Remove IPs from pool listing if necessary
1033sub finalDelete {
[233]1034 if ($IPDBacl{$authuser} !~ /d/) {
[517]1035 $aclerr = 'delblock';
[233]1036 return;
1037 }
[4]1038
[370]1039 # need to retrieve block data before deleting so we can notify on that
1040 my ($cidr,$custid,$type,$city,$description) = getBlockData($ip_dbh, $webvar{block});
1041
[106]1042 my ($code,$msg) = deleteBlock($ip_dbh, $webvar{block}, $webvar{alloctype});
[4]1043
[517]1044 $page->param(block => $webvar{block});
[106]1045 if ($code eq 'OK') {
[370]1046 syslog "notice", "$authuser deallocated '$webvar{alloctype}'-type netblock $webvar{block}".
1047 " $custid, $city, desc='$description'";
[416]1048 mailNotify($ip_dbh, 'da', "REMOVED: $disp_alloctypes{$webvar{alloctype}} $webvar{block}",
1049 "$disp_alloctypes{$webvar{alloctype}} $webvar{block} deallocated by $authuser\n".
1050 "CustID: $custid\nCity: $city\nDescription: $description\n");
[106]1051 } else {
[517]1052 $page->param(failmsg => $msg);
[106]1053 if ($webvar{alloctype} =~ /^.i$/) {
1054 syslog "err", "$authuser could not deallocate static IP '$webvar{block}': '$msg'";
1055 } else {
1056 syslog "err", "$authuser could not deallocate netblock '$webvar{block}': '$msg'";
[517]1057 $page->param(netblock => 1);
[4]1058 }
[106]1059 }
[4]1060
1061} # finalDelete
Note: See TracBrowser for help on using the repository browser.