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

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

/trunk

Clean up and move SQL for static IP pool list to IPDB.pm. See #34.

  • Rename listPool in main.cgi to showPool, so that we can:
  • Add listPool sub in IPDB.pm
  • Convert getBlockData to return a hashref instead of an array, and update the one extant call

Tweak template to use odd for row colors

  • Property svn:executable set to *
  • Property svn:keywords set to Date Rev Author
File size: 34.3 KB
RevLine 
[4]1#!/usr/bin/perl
2# ipdb/cgi-bin/main.cgi
[8]3###
4# SVN revision info
5# $Date: 2012-10-24 20:34:36 +0000 (Wed, 24 Oct 2012) $
6# SVN revision $Rev: 528 $
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') {
[528]131 showPool();
[4]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
[528]269sub showPool {
[4]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
[528]282 my $poolinfo = getBlockData($ip_dbh, $webvar{pool});
[4]283
[528]284 $page->param(disptype => $disp_alloctypes{$poolinfo->{type}});
285 $page->param(city => $poolinfo->{city});
[517]286
[157]287 # Only display net/gw/bcast if it's a "real" netblock and not a PPP(oE) lunacy
[528]288 $page->param(realblock => $poolinfo->{type} =~ /^.d$/);
[4]289
290# probably have to add an "edit IP allocation" link here somewhere.
291
[528]292 my $plist = listPool($ip_dbh, $webvar{pool});
293 # technically slightly more efficient to check the ACL in an if () once outside the foreach
294 foreach (@{$plist}) {
295 $$_{maydel} = $IPDBacl{$authuser} =~ /d/;
[4]296 }
[528]297 $page->param(poolips => $plist);
298} # end showPool
[4]299
300
[106]301# Show "Add new allocation" page. Note that the actual page may
302# be one of two templates, and the lists come from the database.
[4]303sub assignBlock {
304
[233]305 if ($IPDBacl{$authuser} !~ /a/) {
[517]306 $aclerr = 'addblock';
[233]307 return;
308 }
309
[517]310 # hack pthbttt eww
311 $webvar{block} = '' if !$webvar{block};
[21]312
[517]313# hmm. TMPL_IF block and TMPL_ELSE block on these instead?
314 $page->param(rowa => 'row'.($webvar{block} eq '' ? 1 : 0));
315 $page->param(rowb => 'row'.($webvar{block} eq '' ? 0 : 1));
316 $page->param(block => $webvar{block}); # fb-assign flag, if block is set, we're in fb-assign
317 $page->param(iscontained => ($webvar{fbtype} && $webvar{fbtype} ne 'y'));
318
[21]319 # New special case- block to assign is specified
320 if ($webvar{block} ne '') {
321 my $block = new NetAddr::IP $webvar{block};
[187]322
[517]323 # Handle contained freeblock allocation.
[187]324 # This is a little dangerous, as it's *theoretically* possible to
325 # get fbtype='n' (aka a non-routed freeblock). However, should
326 # someone manage to get there, they get what they deserve.
327 if ($webvar{fbtype} ne 'y') {
[517]328 # Snag the type of the container block from the database.
[187]329 $sth = $ip_dbh->prepare("select type from allocations where cidr >>='$block'");
330 $sth->execute;
331 my @data = $sth->fetchrow_array;
332 $data[0] =~ s/c$/r/; # Munge the type into the correct form
[517]333 $page->param(fbdisptype => $list_alloctypes{$data[0]});
334 $page->param(type => $data[0]);
[187]335 } else {
336 $sth = $ip_dbh->prepare("select type,listname from alloctypes where listorder < 500 ".
[191]337 "and type not like '_i' and type not like '_r' order by listorder");
[187]338 $sth->execute;
[517]339 my @typelist;
340 my $selflag = 0;
[187]341 while (my @data = $sth->fetchrow_array) {
[517]342 my %row = (tval => $data[0],
343 type => $data[1],
344 sel => ($selflag == 0 ? ' selected' : '')
345 );
346 push (@typelist, \%row);
347 $selflag++;
[187]348 }
[517]349 $page->param(typelist => \@typelist);
[106]350 }
[21]351 } else {
[517]352 my @masterlist;
[31]353 foreach my $master (@masterblocks) {
[517]354 my %row = (master => "$master");
355 push (@masterlist, \%row);
[31]356 }
[517]357 $page->param(masterlist => \@masterlist);
358
359 my @pops;
[92]360 foreach my $pop (@poplist) {
[517]361 my %row = (pop => $pop);
362 push (@pops, \%row);
[92]363 }
[517]364 $page->param(pops => \@pops);
365
366 # could arguably include routing (500) in the list, but ATM it doesn't
367 # make sense, and in any case that shouldn't be structurally possible here.
368 $sth = $ip_dbh->prepare("select type,listname from alloctypes where listorder <= 500 order by listorder");
[106]369 $sth->execute;
[517]370 my @typelist;
371 my $selflag = 0;
[106]372 while (my @data = $sth->fetchrow_array) {
[517]373 my %row = (tval => $data[0],
374 type => $data[1],
375 sel => ($selflag == 0 ? ' selected' : '')
376 );
377 push (@typelist, \%row);
378 $selflag++;
[106]379 }
[517]380 $page->param(typelist => \@typelist);
[21]381 }
[517]382
383 my @cities;
[92]384 foreach my $city (@citylist) {
[517]385 my %row = (city => $city);
386 push (@cities, \%row);
[92]387 }
[517]388 $page->param(citylist => \@cities);
[4]389
[397]390## node hack
391 $sth = $ip_dbh->prepare("SELECT node_id, node_name FROM nodes ORDER BY node_type,node_id");
392 $sth->execute() or print "DEBUG: failed retrieval from nodes: ".$sth->errstr,"<br>\n";
[517]393 my @nodes;
[397]394 while (my ($nid,$nname) = $sth->fetchrow_array()) {
[517]395 my %row = (nid => $nid, nname => $nname);
396 push (@nodes, \%row);
[397]397 }
[517]398 $page->param(nodelist => \@nodes);
[397]399## end node hack
400
[517]401 $page->param(privdata => $IPDBacl{$authuser} =~ /s/);
[284]402
[4]403} # assignBlock
404
405
406# Take info on requested IP assignment and see what we can provide.
407sub confirmAssign {
[233]408 if ($IPDBacl{$authuser} !~ /a/) {
[517]409 $aclerr = 'addblock';
[233]410 return;
411 }
[4]412
413 my $cidr;
414 my $alloc_from;
415
416 # Going to manually validate some items.
417 # custid and city are automagic.
[111]418 return if !validateInput();
[4]419
420# Several different cases here.
421# Static IP vs netblock
422# + Different flavours of static IP
423# + Different flavours of netblock
424
[157]425 if ($webvar{alloctype} =~ /^.i$/) {
[4]426 my ($base,undef) = split //, $webvar{alloctype}; # split into individual chars
427
[214]428# Ewww. But it works.
429 $sth = $ip_dbh->prepare("SELECT (SELECT city FROM allocations WHERE cidr=poolips.pool), ".
430 "poolips.pool, COUNT(*) FROM poolips,allocations WHERE poolips.available='y' AND ".
[442]431 "poolips.pool=allocations.cidr AND allocations.city='$webvar{pop}' AND poolips.type LIKE '".$base."_' ".
[214]432 "GROUP BY pool");
[4]433 $sth->execute;
434 my $optionlist;
[517]435
436 my @poollist;
437 while (my ($poolcit,$poolblock,$poolfree) = $sth->fetchrow_array) {
[214]438 # city,pool cidr,free IP count
[517]439 if ($poolfree > 0) {
440 my %row = (poolcit => $poolcit, poolblock => $poolblock, poolfree => $poolfree);
441 push (@poollist, \%row);
[214]442 }
[4]443 }
[517]444 $page->param(staticip => 1);
445 $page->param(poollist => \@poollist);
[4]446 $cidr = "Single static IP";
[517]447##fixme: need to handle "no available pools"
[4]448
449 } else { # end show pool options
[21]450
451 if ($webvar{fbassign} eq 'y') {
452 $cidr = new NetAddr::IP $webvar{block};
453 $webvar{maskbits} = $cidr->masklen;
454 } else { # done with direct freeblocks assignment
455
456 if (!$webvar{maskbits}) {
[517]457 $page->param(err => "Please specify a CIDR mask length.");
[111]458 return;
[21]459 }
460 my $sql;
461 my $city;
462 my $failmsg;
[320]463 my $extracond = '';
464 if ($webvar{allocfrom} eq '-') {
465 $extracond = ($webvar{allowpriv} eq 'on' ? '' :
466 " and not (cidr <<= '192.168.0.0/16'".
467 " or cidr <<= '10.0.0.0/8'".
468 " or cidr <<= '172.16.0.0/12')");
469 }
470 my $sortorder;
[187]471 if ($webvar{alloctype} eq 'rm') {
[31]472 if ($webvar{allocfrom} ne '-') {
473 $sql = "select * from freeblocks where maskbits<=$webvar{maskbits} and routed='n'".
[320]474 " and cidr <<= '$webvar{allocfrom}'";
475 $sortorder = "maskbits desc";
[31]476 } else {
[320]477 $sql = "select * from freeblocks where maskbits<=$webvar{maskbits} and routed='n'";
478 $sortorder = "maskbits desc";
[31]479 }
[21]480 $failmsg = "No suitable free block found.<br>\nWe do not have a free".
481 " routeable block of that size.<br>\nYou will have to either route".
482 " a set of smaller netblocks or a single smaller netblock.";
[4]483 } else {
[118]484##fixme
485# This section needs serious Pondering.
[214]486 # Pools of most types get assigned to the POP they're "routed from"
[187]487 # This includes WAN blocks and other netblock "containers"
[214]488 # This does NOT include cable pools.
489 if ($webvar{alloctype} =~ /^.[pc]$/) {
[37]490 $city = $webvar{city};
[21]491 $failmsg = "No suitable free block found.<br>\nYou will have to route another".
[442]492 " superblock from one of the<br>\nmaster blocks or chose a smaller".
[21]493 " block size for the pool.";
494 } else {
[517]495 if (!$webvar{pop}) {
496 $page->param(err => 'Please select a POP to route the block from/through.');
497 return;
498 }
[21]499 $city = $webvar{pop};
500 $failmsg = "No suitable free block found.<br>\nYou will have to route another".
[442]501 " superblock to $webvar{pop}<br>\nfrom one of the master blocks or".
[21]502 " chose a smaller blocksize.";
503 }
[300]504 if (defined $webvar{allocfrom} && $webvar{allocfrom} ne '-') {
[157]505 $sql = "select cidr from freeblocks where city='$city' and maskbits<=$webvar{maskbits}".
[186]506 " and cidr <<= '$webvar{allocfrom}' and routed='".
[320]507 (($webvar{alloctype} =~ /^(.)r$/) ? "$1" : 'y')."'";
508 $sortorder = "maskbits desc,cidr";
[31]509 } else {
[157]510 $sql = "select cidr from freeblocks where city='$city' and maskbits<=$webvar{maskbits}".
[320]511 " and routed='".(($webvar{alloctype} =~ /^(.)r$/) ? "$1" : 'y')."'";
512 $sortorder = "maskbits desc,cidr";
[31]513 }
[4]514 }
[320]515 $sql = $sql.$extracond." order by ".$sortorder;
[21]516 $sth = $ip_dbh->prepare($sql);
517 $sth->execute;
518 my @data = $sth->fetchrow_array();
519 if ($data[0] eq "") {
[517]520 $page->param(err => $failmsg);
[111]521 return;
[21]522 }
523 $cidr = new NetAddr::IP $data[0];
524 } # check for freeblocks assignment or IPDB-controlled assignment
[4]525
[517]526 $alloc_from = "$cidr";
[4]527
528 # If the block to be allocated is smaller than the one we found,
529 # figure out the "real" block to be allocated.
530 if ($cidr->masklen() ne $webvar{maskbits}) {
531 my $maskbits = $cidr->masklen();
532 my @subblocks;
533 while ($maskbits++ < $webvar{maskbits}) {
534 @subblocks = $cidr->split($maskbits);
535 }
536 $cidr = $subblocks[0];
537 }
[157]538 } # if ($webvar{alloctype} =~ /^.i$/)
[4]539
[397]540## node hack
541 if ($webvar{node} && $webvar{node} ne '-') {
542 $sth = $ip_dbh->prepare("SELECT node_name FROM nodes WHERE node_id=?");
543 $sth->execute($webvar{node});
544 my ($nodename) = $sth->fetchrow_array();
[517]545 $page->param(nodename => $nodename);
546 $page->param(nodeid => $webvar{node});
[397]547 }
548## end node hack
549
[4]550 # Stick in the allocation data
[517]551 $page->param(alloc_type => $webvar{alloctype});
552 $page->param(typefull => $q->escapeHTML($disp_alloctypes{$webvar{alloctype}}));
553 $page->param(alloc_from => $alloc_from);
554 $page->param(cidr => $cidr);
555 $page->param(city => $q->escapeHTML($webvar{city}));
556 $page->param(custid => $webvar{custid});
557 $page->param(circid => $q->escapeHTML($webvar{circid}));
558 $page->param(desc => $q->escapeHTML($webvar{desc}));
[4]559
[517]560##fixme: find a way to have the displayed copy have <br> substitutions
561# for newlines, and the <input> value have either encoded or bare newlines.
562# Also applies to privdata.
563 $page->param(notes => $q->escapeHTML($webvar{notes},'y'));
564
[284]565 # Check to see if user is allowed to do anything with sensitive data
566 my $privdata = '';
[517]567 $page->param(privdata => $q->escapeHTML($webvar{privdata},'y'))
568 if $IPDBacl{$authuser} =~ /s/;
569
570 # Yay! This now has it's very own little home.
571 $page->param(billinguser => $webvar{userid})
[299]572 if $webvar{userid};
[284]573
[517]574##fixme: this is only needed iff confirm.tmpl and
575# confirmRemove.tmpl are merged (quite possible, just
576# a little tedious)
577 $page->param(action => "insert");
[284]578
[4]579} # end confirmAssign
580
581
582# Do the work of actually inserting a block in the database.
583sub insertAssign {
[233]584 if ($IPDBacl{$authuser} !~ /a/) {
[517]585 $aclerr = 'addblock';
[233]586 return;
587 }
[4]588 # Some things are done more than once.
[111]589 return if !validateInput();
[4]590
[284]591 if (!defined($webvar{privdata})) {
592 $webvar{privdata} = '';
593 }
[106]594 # $code is "success" vs "failure", $msg contains OK for a
595 # successful netblock allocation, the IP allocated for static
596 # IP, or the error message if an error occurred.
[517]597
[106]598 my ($code,$msg) = allocateBlock($ip_dbh, $webvar{fullcidr}, $webvar{alloc_from},
599 $webvar{custid}, $webvar{alloctype}, $webvar{city}, $webvar{desc}, $webvar{notes},
[397]600 $webvar{circid}, $webvar{privdata}, $webvar{node});
[4]601
[111]602 if ($code eq 'OK') {
[106]603 if ($webvar{alloctype} =~ /^.i$/) {
[300]604 $msg =~ s|/32||;
[517]605 $page->param(staticip => $msg);
606 $page->param(custid => $webvar{custid});
607 $page->param(billinguser => $webvar{billinguser});
[416]608 mailNotify($ip_dbh, "a$webvar{alloctype}", "ADDED: $disp_alloctypes{$webvar{alloctype}} allocation",
609 "$disp_alloctypes{$webvar{alloctype}} $msg allocated to customer $webvar{custid}\n".
610 "Description: $webvar{desc}\n\nAllocated by: $authuser\n");
[106]611 } else {
[301]612 my $netblock = new NetAddr::IP $webvar{fullcidr};
[517]613 $page->param(fullcidr => $webvar{fullcidr});
614 $page->param(alloctype => $disp_alloctypes{$webvar{alloctype}});
615 $page->param(custid => $webvar{custid});
616 if ($webvar{alloctype} eq 'pr' && $webvar{billinguser}) {
617 $page->param(billinguser => $webvar{billinguser});
618 $page->param(custid => $webvar{custid});
619 $page->param(netaddr => $netblock->addr);
620 $page->param(masklen => $netblock->masklen);
621 }
[416]622 mailNotify($ip_dbh, "a$webvar{alloctype}", "ADDED: $disp_alloctypes{$webvar{alloctype}} allocation",
623 "$disp_alloctypes{$webvar{alloctype}} $webvar{fullcidr} allocated to customer $webvar{custid}\n".
624 "Description: $webvar{desc}\n\nAllocated by: $authuser\n");
[4]625 }
[106]626 syslog "notice", "$authuser allocated '$webvar{fullcidr}' to '$webvar{custid}' as ".
[256]627 "'$webvar{alloctype}' ($msg)";
[111]628 } else {
629 syslog "err", "Allocation of '$webvar{fullcidr}' to '$webvar{custid}' as ".
630 "'$webvar{alloctype}' by $authuser failed: '$msg'";
[517]631 $page->param(err => "Allocation of $webvar{fullcidr} as '$disp_alloctypes{$webvar{alloctype}}'".
[157]632 " failed:<br>\n$msg\n");
[106]633 }
[4]634
635} # end insertAssign()
636
637
638# Does some basic checks on common input data to make sure nothing
639# *really* weird gets in to the database through this script.
640# Does NOT do complete input validation!!!
641sub validateInput {
642 if ($webvar{city} eq '-') {
[517]643 $page->param(err => 'Please choose a city');
[111]644 return;
[4]645 }
[138]646
647 # Alloctype check.
[4]648 chomp $webvar{alloctype};
[138]649 if (!grep /$webvar{alloctype}/, keys %disp_alloctypes) {
650 # Danger! Danger! alloctype should ALWAYS be set by a dropdown. Anyone
651 # managing to call things in such a way as to cause this deserves a cryptic error.
[517]652 $page->param(err => 'Invalid alloctype');
[138]653 return;
654 }
655
656 # CustID check
[4]657 # We have different handling for customer allocations and "internal" or "our" allocations
[214]658 if ($def_custids{$webvar{alloctype}} eq '') {
[4]659 if (!$webvar{custid}) {
[517]660 $page->param(err => 'Please enter a customer ID.');
[111]661 return;
[4]662 }
[400]663 if ($webvar{custid} !~ /^(?:\d{10}|\d{7}|STAFF)(?:-\d\d?)?$/) {
664 # Force uppercase for now...
665 $webvar{custid} =~ tr/a-z/A-Z/;
666 # Crosscheck with billing.
667 my $status = CustIDCK->custid_exist($webvar{custid});
668 if ($CustIDCK::Error) {
[517]669 $page->param(err => "Error verifying customer ID: ".$CustIDCK::ErrMsg);
[400]670 return;
671 }
672 if (!$status) {
[517]673 $page->param(err => "Customer ID not valid. Make sure the Customer ID ".
[420]674 "is correct.<br>\nUse STAFF for staff static IPs, and $IPDB::defcustid for any other ".
[400]675 "non-customer assignments.");
676 return;
677 }
[4]678 }
[400]679# print "<!-- [ In validateInput(). Insert customer ID cross-check here. ] -->\n";
[138]680 } else {
[167]681 # New! Improved! And now Loaded From The Database!!
[320]682 if ((!$webvar{custid}) || ($webvar{custid} ne 'STAFF')) {
683 $webvar{custid} = $def_custids{$webvar{alloctype}};
684 }
[4]685 }
[111]686
687 # Check POP location
688 my $flag;
[187]689 if ($webvar{alloctype} eq 'rm') {
[111]690 $flag = 'for a routed netblock';
691 foreach (@poplist) {
692 if (/^$webvar{city}$/) {
693 $flag = 'n';
694 last;
695 }
696 }
697 } else {
698 $flag = 'n';
[442]699##fixme: hook to force-set POP or city on certain alloctypes
700# if ($webvar{alloctype =~ /foo,bar,bz/ { $webvar{pop} = 'blah'; }
[400]701 if ($webvar{pop} =~ /^-$/) {
[111]702 $flag = 'to route the block from/through';
703 }
704 }
[517]705
706 # if the alloctype has a restricted city/POP list as determined above,
707 # and the reqested city/POP does not match that list, complain
[111]708 if ($flag ne 'n') {
[517]709 $page->param(err => "Please choose a valid POP location $flag. Valid ".
[111]710 "POP locations are currently:<br>\n".join (" - ", @poplist));
711 return;
712 }
713
714 return 'OK';
[4]715} # end validateInput
716
717
718# Displays details of a specific allocation in a form
719# Allows update/delete
720# action=edit
721sub edit {
722
723 my $sql;
724
725 # Two cases: block is a netblock, or block is a static IP from a pool
726 # because I'm lazy, we'll try to make the SELECT's bring out identical)ish) data
[517]727##fixme: allow "SWIP" (publication to rWHOIS) of static IP data
[4]728 if ($webvar{block} =~ /\/32$/) {
[455]729 $sql = "select ip,custid,type,city,circuitid,description,notes,modifystamp,privdata from poolips where ip='$webvar{block}'";
[4]730 } else {
[455]731 $sql = "select cidr,custid,type,city,circuitid,description,notes,modifystamp,privdata,swip from allocations where cidr='$webvar{block}'"
[4]732 }
733
734 # gotta snag block info from db
735 $sth = $ip_dbh->prepare($sql);
736 $sth->execute;
737 my @data = $sth->fetchrow_array;
738
739 # Clean up extra whitespace on alloc type
740 $data[2] =~ s/\s//;
741
742 # We can't let the city be changed here; this block is a part of
743 # a larger routed allocation and therefore by definition can't be moved.
744 # block and city are static.
745##fixme
746# Needs thinking. Have to allow changes to city to correct errors, no?
[517]747# Also have areas where a routed block at a POP serves "many" cities/towns/named crossroads
[4]748
[517]749# @data: cidr,custid,type,city,circuitid,description,notes,modifystamp,privdata,swip
[233]750
[517]751 $page->param(block => $webvar{block});
[4]752
[517]753 $page->param(custid => $data[1]);
754 $page->param(city => $data[3]);
755 $page->param(circid => $data[4]);
756 $page->param(desc => $data[5]);
757 $page->param(notes => $data[6]);
[4]758
[187]759##fixme The check here should be built from the database
[517]760# Need to expand to support pool types too
761 if ($data[2] =~ /^.[ne]$/ && $IPDBacl{$authuser} =~ /c/) {
762 $page->param(changetype => 1);
763 $page->param(alloctype => [
764 { selme => ($data[2] eq 'me'), type => "me", disptype => "Dialup netblock" },
765 { selme => ($data[2] eq 'de'), type => "de", disptype => "Dynamic DSL netblock" },
766 { selme => ($data[2] eq 'ce'), type => "ce", disptype => "Dynamic cable netblock" },
767 { selme => ($data[2] eq 'we'), type => "we", disptype => "Dynamic wireless netblock" },
768 { selme => ($data[2] eq 'cn'), type => "cn", disptype => "Customer netblock" },
769 { selme => ($data[2] eq 'en'), type => "en", disptype => "End-use netblock" },
770 { selme => ($data[2] eq 'in'), type => "in", disptype => "Internal netblock" },
771 ]
772 );
773 } else {
774 $page->param(disptype => $disp_alloctypes{$data[2]});
775 $page->param(type => $data[2]);
776 }
777
[397]778## node hack
[517]779 $sth = $ip_dbh->prepare("SELECT nodes.node_id,node_name FROM nodes INNER JOIN noderef".
780 " ON nodes.node_id=noderef.node_id WHERE noderef.block='$webvar{block}'");
[397]781 $sth->execute;
[517]782 my ($nodeid,$nodename) = $sth->fetchrow_array();
783 $page->param(havenodeid => $nodeid);
784
785 if ($data[2] eq 'fr' || $data[2] eq 'bi') {
786 $page->param(typesupportsnodes => 1);
787 $page->param(nodename => $nodename);
788
789##fixme: this whole hack needs cleanup and generalization for all alloctypes
790##fixme: arguably a bug that presence of a nodeid implies it can be changed..
791# but except for manual database changes, only the two types fr and bi can
792# (currently) have a nodeid set in the first place.
793 if ($IPDBacl{$authuser} =~ /c/) {
[397]794 $sth = $ip_dbh->prepare("SELECT node_id, node_name FROM nodes ORDER BY node_type,node_id");
[517]795 $sth->execute;
796 my @nodelist;
[397]797 while (my ($nid,$nname) = $sth->fetchrow_array()) {
[517]798 my %row = (
799 selme => ($nodeid == $nid),
800 nodeid => $nid,
801 nodename => $nname,
802 );
803 push (@nodelist, \%row);
[397]804 }
[517]805 $page->param(nodelist => \@nodelist);
[397]806 }
807 }
808## end node hack
[517]809
[255]810 my ($lastmod,undef) = split /\s+/, $data[7];
[517]811 $page->param(lastmod => $lastmod);
[33]812
[517]813 # not happy with the upside-down logic, but...
814 $page->param(swipable => $data[2] !~ /.i/);
815 $page->param(swip => $data[10] ne 'n');
[320]816
[284]817 # Check to see if we can display sensitive data
[517]818 $page->param(nocling => $IPDBacl{$authuser} =~ /s/);
819 $page->param(privdata => $data[8]);
[284]820
[517]821 # ACL trickery - these two template booleans control the presence of all form/input tags
822 $page->param(maychange => $IPDBacl{$authuser} =~ /c/);
823 $page->param(maydel => $IPDBacl{$authuser} =~ /d/);
[4]824
825} # edit()
826
827
828# Stuff new info about a block into the db
829# action=update
830sub update {
[284]831 if ($IPDBacl{$authuser} !~ /c/) {
[517]832 $aclerr = 'updateblock';
[284]833 return;
834 }
[4]835
[284]836 # Check to see if we can update restricted data
837 my $privdata = '';
838 if ($IPDBacl{$authuser} =~ /s/) {
839 $privdata = ",privdata='$webvar{privdata}'";
840 }
841
[4]842 # Make sure incoming data is in correct format - custID among other things.
[228]843 return if !validateInput;
[4]844
845 # SQL transaction wrapper
846 eval {
847 # Relatively simple SQL transaction here.
848 my $sql;
[157]849 if (my $pooltype = ($webvar{alloctype} =~ /^(.)i$/) ) {
[517]850 $sql = "UPDATE poolips SET custid='$webvar{custid}',".
851 "city=?,description=?,notes=?,".
852 "circuitid='$webvar{circid}',".
[284]853 "$privdata where ip='$webvar{block}'";
[4]854 } else {
[517]855 $sql = "UPDATE allocations SET custid='$webvar{custid}',".
856 "city=?,description=?,notes=?,".
857 "circuitid='$webvar{circid}'$privdata,".
858 "type='$webvar{alloctype}',".
[320]859 "swip='".($webvar{swip} eq 'on' ? 'y' : 'n')."' ".
[284]860 "where cidr='$webvar{block}'";
[4]861 }
[157]862 # Log the details of the change.
863 syslog "debug", $sql;
[4]864 $sth = $ip_dbh->prepare($sql);
[517]865 $sth->execute($webvar{city}, $webvar{desc}, $webvar{notes});
[397]866## node hack
867 if ($webvar{node}) {
[517]868 # done with delete/insert so we don't have to worry about funkyness updating a node ref that isn't there
[397]869 $ip_dbh->do("DELETE FROM noderef WHERE block='$webvar{block}'");
870 $sth = $ip_dbh->prepare("INSERT INTO noderef (block,node_id) VALUES (?,?)");
871 $sth->execute($webvar{block},$webvar{node});
872 }
873## end node hack
[4]874 $ip_dbh->commit;
875 };
876 if ($@) {
[166]877 my $msg = $@;
[4]878 eval { $ip_dbh->rollback; };
[166]879 syslog "err", "$authuser could not update block/IP '$webvar{block}': '$msg'";
[517]880 $page->param(err => "Could not update block/IP $webvar{block}: $msg");
[111]881 return;
[4]882 }
883
884 # If we get here, the operation succeeded.
885 syslog "notice", "$authuser updated $webvar{block}";
[416]886##fixme: need to wedge something in to allow "update:field" notifications
887## hmm. how to tell what changed? O_o
[426]888mailNotify($ip_dbh, 's:swi', "SWIPed: $disp_alloctypes{$webvar{alloctype}} $webvar{block}",
[416]889 "$webvar{block} had SWIP status changed to \"Yes\" by $authuser") if $webvar{swip} eq 'on';
[4]890
[517]891## node hack
892 if ($webvar{node} && $webvar{node} ne '-') {
893 $sth = $ip_dbh->prepare("SELECT node_name FROM nodes WHERE node_id=?");
894 $sth->execute($webvar{node});
895 my ($nodename) = $sth->fetchrow_array();
896 $page->param(nodename => $nodename);
897 }
898## end node hack
899
[380]900 # Link back to browse-routed or list-pool page on "Update complete" page.
901 my $cblock; # to contain the CIDR of the container block we're retrieving.
902 my $sql;
903 if (my $pooltype = ($webvar{alloctype} =~ /^(.)i$/) ) {
[517]904 $page->param(backpool => 1);
[380]905 $sql = "select pool from poolips where ip='$webvar{block}'";
906 } else {
907 $sql = "select cidr from routed where cidr >>= '$webvar{block}'";
908 }
909 # I define there to be no errors on this operation... so we don't need to check for them.
910 $sth = $ip_dbh->prepare($sql);
911 $sth->execute;
912 $sth->bind_columns(\$cblock);
913 $sth->fetch();
914 $sth->finish;
[517]915 $page->param(backblock => $cblock);
[380]916
[517]917 $page->param(cidr => $webvar{block});
918 $page->param(city => $webvar{city});
919 $page->param(disptype => $disp_alloctypes{$webvar{alloctype}});
920 $page->param(custid => $webvar{custid});
921 $page->param(swip => $webvar{swip} eq 'on' ? 'Yes' : 'No');
922 $page->param(circid => $q->escapeHTML($webvar{circid}));
923 $page->param(desc => $q->escapeHTML($webvar{desc}));
924 $page->param(notes => $q->escapeHTML($webvar{notes}));
925 $webvar{privdata} = ($webvar{privdata} ? $q->escapeHTML($webvar{privdata}) : "&nbsp;");
926 $page->param(privdata => $webvar{privdata})
927 if $IPDBacl{$authuser} =~ /s/;
[4]928
929} # update()
930
931
932# Delete an allocation.
[106]933sub remove {
[233]934 if ($IPDBacl{$authuser} !~ /d/) {
[517]935 $aclerr = 'delblock';
[233]936 return;
937 }
938
[4]939 # Serves'em right for getting here...
940 if (!defined($webvar{block})) {
[517]941 $page->param(err => "Can't delete a block that doesn't exist");
[111]942 return;
[4]943 }
944
[284]945 my ($cidr, $custid, $type, $city, $circid, $desc, $notes, $alloctype, $privdata);
[4]946
[187]947 if ($webvar{alloctype} eq 'rm') {
[4]948 $sth = $ip_dbh->prepare("select cidr,city from routed where cidr='$webvar{block}'");
949 $sth->execute();
950
951# This feels... extreme.
952 croak $sth->errstr() if($sth->errstr());
953
954 $sth->bind_columns(\$cidr,\$city);
955 $sth->execute();
956 $sth->fetch || croak $sth->errstr();
957 $custid = "N/A";
958 $alloctype = $webvar{alloctype};
[74]959 $circid = "N/A";
[4]960 $desc = "N/A";
961 $notes = "N/A";
[517]962 $privdata = "N/A";
[4]963
964 } elsif ($webvar{alloctype} eq 'mm') {
[517]965
[4]966 $cidr = $webvar{block};
967 $city = "N/A";
968 $custid = "N/A";
969 $alloctype = $webvar{alloctype};
[74]970 $circid = "N/A";
[4]971 $desc = "N/A";
972 $notes = "N/A";
[517]973 $privdata = "N/A";
974
[189]975 } elsif ($webvar{alloctype} =~ /^.i$/) { # done with alloctype=[rm]m
[4]976
977 # Unassigning a static IP
[284]978 my $sth = $ip_dbh->prepare("select ip,custid,city,type,notes,circuitid,privdata".
979 " from poolips where ip='$webvar{block}'");
[4]980 $sth->execute();
981# croak $sth->errstr() if($sth->errstr());
982
[284]983 $sth->bind_columns(\$cidr, \$custid, \$city, \$alloctype, \$notes, \$circid,
984 \$privdata);
[4]985 $sth->fetch() || croak $sth->errstr;
986
[157]987 } else { # done with alloctype=~ /^.i$/
[4]988
[284]989 my $sth = $ip_dbh->prepare("select cidr,custid,type,city,circuitid,description,notes,privdata".
990 " from allocations where cidr='$webvar{block}'");
[4]991 $sth->execute();
992# croak $sth->errstr() if($sth->errstr());
993
[284]994 $sth->bind_columns(\$cidr, \$custid, \$alloctype, \$city, \$circid, \$desc,
995 \$notes, \$privdata);
[74]996 $sth->fetch() || carp $sth->errstr;
[4]997 } # end cases for different alloctypes
998
[517]999 $page->param(block => $cidr);
1000 $page->param(disptype => $disp_alloctypes{$alloctype});
1001 $page->param(type => $alloctype);
1002 $page->param(city => $city);
1003 $page->param(custid => $custid);
1004 $page->param(circid => $circid);
1005 $page->param(desc => $desc);
1006 $page->param(notes => $notes);
1007 $privdata = '&nbsp;' if $privdata eq '';
1008 $page->param(privdata => $privdata) if $IPDBacl{$authuser} =~ /s/;
1009 $page->param(delpool => $alloctype =~ /^.[pd]$/);
[4]1010
[517]1011} # end remove()
[4]1012
1013
1014# Delete an allocation. Return it to the freeblocks table; munge
1015# data as necessary to keep as few records as possible in freeblocks
1016# to prevent weirdness when allocating blocks later.
1017# Remove IPs from pool listing if necessary
1018sub finalDelete {
[233]1019 if ($IPDBacl{$authuser} !~ /d/) {
[517]1020 $aclerr = 'delblock';
[233]1021 return;
1022 }
[4]1023
[370]1024 # need to retrieve block data before deleting so we can notify on that
[528]1025 my $blockinfo = getBlockData($ip_dbh, $webvar{block});
[370]1026
[106]1027 my ($code,$msg) = deleteBlock($ip_dbh, $webvar{block}, $webvar{alloctype});
[4]1028
[517]1029 $page->param(block => $webvar{block});
[106]1030 if ($code eq 'OK') {
[528]1031 syslog "notice", "$authuser deallocated '$webvar{alloctype}'-type netblock $webvar{block} ".
1032 $blockinfo->{custid}.", ".$blockinfo->{city}.", desc='".$blockinfo->{description}."'";
[416]1033 mailNotify($ip_dbh, 'da', "REMOVED: $disp_alloctypes{$webvar{alloctype}} $webvar{block}",
1034 "$disp_alloctypes{$webvar{alloctype}} $webvar{block} deallocated by $authuser\n".
[528]1035 "CustID: ".$blockinfo->{custid}."\nCity: ".$blockinfo->{city}.
1036 "\nDescription: ".$blockinfo->{description}."\n");
[106]1037 } else {
[517]1038 $page->param(failmsg => $msg);
[106]1039 if ($webvar{alloctype} =~ /^.i$/) {
1040 syslog "err", "$authuser could not deallocate static IP '$webvar{block}': '$msg'";
1041 } else {
1042 syslog "err", "$authuser could not deallocate netblock '$webvar{block}': '$msg'";
[517]1043 $page->param(netblock => 1);
[4]1044 }
[106]1045 }
[4]1046
1047} # finalDelete
Note: See TracBrowser for help on using the repository browser.