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

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

/trunk

Clean up and move SQL for showmaster to IPDB.pm. See #34.
Tweak template to use odd for row colors

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