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
Line 
1#!/usr/bin/perl
2# ipdb/cgi-bin/main.cgi
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###
9# Copyright (C) 2004-2010 - Kris Deugau
10
11use strict;
12use warnings;
13use CGI::Carp qw(fatalsToBrowser);
14use CGI::Simple;
15use HTML::Template;
16use DBI;
17use POSIX qw(ceil);
18use NetAddr::IP;
19
20use Sys::Syslog;
21
22# don't remove! required for GNU/FHS-ish install from tarball
23##uselib##
24
25use CustIDCK;
26use MyIPDB;
27
28openlog "IPDB","pid","$IPDB::syslog_facility";
29
30## Environment. Collect some things, process some things, set some things...
31
32# Collect the username from HTTP auth. If undefined, we're in
33# a test environment, or called without a username.
34my $authuser;
35if (!defined($ENV{'REMOTE_USER'})) {
36 $authuser = '__temptest';
37} else {
38 $authuser = $ENV{'REMOTE_USER'};
39}
40
41# anyone got a better name? :P
42my $thingroot = $ENV{SCRIPT_FILENAME};
43$thingroot =~ s|cgi-bin/main.cgi||;
44
45syslog "debug", "$authuser active, $ENV{'REMOTE_ADDR'}";
46
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
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;
64($ip_dbh,$errstr) = connectDB_My;
65if (!$ip_dbh) {
66 $webvar{action} = "dberr";
67} else {
68 initIPDBGlobals($ip_dbh);
69}
70
71# Set up some globals
72$ENV{HTML_TEMPLATE_ROOT} = $thingroot."templates";
73
74my $header = HTML::Template->new(filename => "header.tmpl");
75my $footer = HTML::Template->new(filename => "footer.tmpl");
76
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;
81
82
83#main()
84my $aclerr;
85
86if(!defined($webvar{action})) {
87 $webvar{action} = "index"; #shuts up the warnings.
88}
89
90my $page;
91if (-e "$ENV{HTML_TEMPLATE_ROOT}/$webvar{action}.tmpl") {
92 $page = HTML::Template->new(filename => "$webvar{action}.tmpl", loop_context_vars => 1);
93} else {
94 $page = HTML::Template->new(filename => "dunno.tmpl");
95}
96
97if($webvar{action} eq 'index') {
98 showSummary();
99} elsif ($webvar{action} eq 'addmaster') {
100 if ($IPDBacl{$authuser} !~ /a/) {
101 $aclerr = 'addmaster';
102 }
103} elsif ($webvar{action} eq 'newmaster') {
104
105 if ($IPDBacl{$authuser} !~ /a/) {
106 $aclerr = 'addmaster';
107 } else {
108 my $cidr = new NetAddr::IP $webvar{cidr};
109 $page->param(cidr => "$cidr");
110
111 my ($code,$msg) = addMaster($ip_dbh, $webvar{cidr});
112
113 if ($code eq 'FAIL') {
114 syslog "err", "Could not add master block '$webvar{cidr}' to database: '$msg'";
115 $page->param(err => $msg);
116 } else {
117 syslog "info", "$authuser added master block $webvar{cidr}";
118 }
119
120 } # ACL check
121
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 showPool();
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}
156elsif ($webvar{action} eq 'nodesearch') {
157 my $nodelist = getNodeList($ip_dbh);
158 $page->param(nodelist => $nodelist);
159}
160
161# DB failure. Can't do much here, really.
162elsif ($webvar{action} eq 'dberr') {
163 $page->param(errmsg => $errstr);
164}
165
166# Default is an error. It shouldn't be possible to get here unless you're
167# randomly feeding in values for webvar{action}.
168else {
169 my $rnd = rand 500;
170 my $boing = sprintf("%.2f", rand 500);
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]);
184}
185## Finally! Done with that NASTY "case" emulation!
186
187
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}
196
197$sth->finish if $sth;
198# Clean up IPDB globals, DB handle, etc.
199finish($ip_dbh);
200
201## Do all our printing here so we can generate errors and stick them into the slots in the templates.
202
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
213# Just in case something waaaayyy down isn't in place
214# properly... we exit explicitly.
215exit 0;
216
217
218# Initial display: Show master blocks with total allocated subnets, total free subnets
219sub showSummary {
220 my $masterlist = listSummary($ip_dbh);
221 $page->param(masterlist => $masterlist);
222
223 $page->param(addmaster => ($IPDBacl{$authuser} =~ /a/) );
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
234 $page->param(master => $webvar{block});
235 $page->param(delmaster => ($IPDBacl{$authuser} =~ /d/));
236
237 my $rlist = listMaster($ip_dbh, $webvar{block});
238 $page->param(routedlist => $rlist);
239
240 my $flist = listFree($ip_dbh, $webvar{block});
241 $page->param(unrouted => $flist);
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 $page->param(master => $webvar{block});
255 $page->param(delrouted => $IPDBacl{$authuser} =~ /d/);
256
257 my $rcity = getRoutedCity($ip_dbh, $webvar{block});
258 $page->param(rcity => $rcity);
259
260 my $blist = listRBlock($ip_dbh, $webvar{block});
261 $page->param(blocklist => $blist);
262
263 my $flist = listFree($ip_dbh, $webvar{block}, 'y');
264 $page->param(unassigned => $flist);
265} # showRBlock
266
267
268# List the IPs used in a pool
269sub showPool {
270
271 my $cidr = new NetAddr::IP $webvar{pool};
272
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);
280
281 # Snag pool info for heading
282 my $poolinfo = getBlockData($ip_dbh, $webvar{pool});
283
284 $page->param(disptype => $disp_alloctypes{$poolinfo->{type}});
285 $page->param(city => $poolinfo->{city});
286
287 # Only display net/gw/bcast if it's a "real" netblock and not a PPP(oE) lunacy
288 $page->param(realblock => $poolinfo->{type} =~ /^.d$/);
289
290# probably have to add an "edit IP allocation" link here somewhere.
291
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/;
296 }
297 $page->param(poolips => $plist);
298} # end showPool
299
300
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.
303sub assignBlock {
304
305 if ($IPDBacl{$authuser} !~ /a/) {
306 $aclerr = 'addblock';
307 return;
308 }
309
310 # hack pthbttt eww
311 $webvar{block} = '' if !$webvar{block};
312
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
319 # New special case- block to assign is specified
320 if ($webvar{block} ne '') {
321 my $block = new NetAddr::IP $webvar{block};
322
323 # Handle contained freeblock allocation.
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') {
328 # Snag the type of the container block from the database.
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
333 $page->param(fbdisptype => $list_alloctypes{$data[0]});
334 $page->param(type => $data[0]);
335 } else {
336 $sth = $ip_dbh->prepare("select type,listname from alloctypes where listorder < 500 ".
337 "and type not like '_i' and type not like '_r' order by listorder");
338 $sth->execute;
339 my @typelist;
340 my $selflag = 0;
341 while (my @data = $sth->fetchrow_array) {
342 my %row = (tval => $data[0],
343 type => $data[1],
344 sel => ($selflag == 0 ? ' selected' : '')
345 );
346 push (@typelist, \%row);
347 $selflag++;
348 }
349 $page->param(typelist => \@typelist);
350 }
351 } else {
352 my @masterlist;
353 foreach my $master (@masterblocks) {
354 my %row = (master => "$master");
355 push (@masterlist, \%row);
356 }
357 $page->param(masterlist => \@masterlist);
358
359 my @pops;
360 foreach my $pop (@poplist) {
361 my %row = (pop => $pop);
362 push (@pops, \%row);
363 }
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");
369 $sth->execute;
370 my @typelist;
371 my $selflag = 0;
372 while (my @data = $sth->fetchrow_array) {
373 my %row = (tval => $data[0],
374 type => $data[1],
375 sel => ($selflag == 0 ? ' selected' : '')
376 );
377 push (@typelist, \%row);
378 $selflag++;
379 }
380 $page->param(typelist => \@typelist);
381 }
382
383 my @cities;
384 foreach my $city (@citylist) {
385 my %row = (city => $city);
386 push (@cities, \%row);
387 }
388 $page->param(citylist => \@cities);
389
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";
393 my @nodes;
394 while (my ($nid,$nname) = $sth->fetchrow_array()) {
395 my %row = (nid => $nid, nname => $nname);
396 push (@nodes, \%row);
397 }
398 $page->param(nodelist => \@nodes);
399## end node hack
400
401 $page->param(privdata => $IPDBacl{$authuser} =~ /s/);
402
403} # assignBlock
404
405
406# Take info on requested IP assignment and see what we can provide.
407sub confirmAssign {
408 if ($IPDBacl{$authuser} !~ /a/) {
409 $aclerr = 'addblock';
410 return;
411 }
412
413 my $cidr;
414 my $alloc_from;
415
416 # Going to manually validate some items.
417 # custid and city are automagic.
418 return if !validateInput();
419
420# Several different cases here.
421# Static IP vs netblock
422# + Different flavours of static IP
423# + Different flavours of netblock
424
425 if ($webvar{alloctype} =~ /^.i$/) {
426 my ($base,undef) = split //, $webvar{alloctype}; # split into individual chars
427
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 ".
431 "poolips.pool=allocations.cidr AND allocations.city='$webvar{pop}' AND poolips.type LIKE '".$base."_' ".
432 "GROUP BY pool");
433 $sth->execute;
434 my $optionlist;
435
436 my @poollist;
437 while (my ($poolcit,$poolblock,$poolfree) = $sth->fetchrow_array) {
438 # city,pool cidr,free IP count
439 if ($poolfree > 0) {
440 my %row = (poolcit => $poolcit, poolblock => $poolblock, poolfree => $poolfree);
441 push (@poollist, \%row);
442 }
443 }
444 $page->param(staticip => 1);
445 $page->param(poollist => \@poollist);
446 $cidr = "Single static IP";
447##fixme: need to handle "no available pools"
448
449 } else { # end show pool options
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}) {
457 $page->param(err => "Please specify a CIDR mask length.");
458 return;
459 }
460 my $sql;
461 my $city;
462 my $failmsg;
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;
471 if ($webvar{alloctype} eq 'rm') {
472 if ($webvar{allocfrom} ne '-') {
473 $sql = "select * from freeblocks where maskbits<=$webvar{maskbits} and routed='n'".
474 " and cidr <<= '$webvar{allocfrom}'";
475 $sortorder = "maskbits desc";
476 } else {
477 $sql = "select * from freeblocks where maskbits<=$webvar{maskbits} and routed='n'";
478 $sortorder = "maskbits desc";
479 }
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.";
483 } else {
484##fixme
485# This section needs serious Pondering.
486 # Pools of most types get assigned to the POP they're "routed from"
487 # This includes WAN blocks and other netblock "containers"
488 # This does NOT include cable pools.
489 if ($webvar{alloctype} =~ /^.[pc]$/) {
490 $city = $webvar{city};
491 $failmsg = "No suitable free block found.<br>\nYou will have to route another".
492 " superblock from one of the<br>\nmaster blocks or chose a smaller".
493 " block size for the pool.";
494 } else {
495 if (!$webvar{pop}) {
496 $page->param(err => 'Please select a POP to route the block from/through.');
497 return;
498 }
499 $city = $webvar{pop};
500 $failmsg = "No suitable free block found.<br>\nYou will have to route another".
501 " superblock to $webvar{pop}<br>\nfrom one of the master blocks or".
502 " chose a smaller blocksize.";
503 }
504 if (defined $webvar{allocfrom} && $webvar{allocfrom} ne '-') {
505 $sql = "select cidr from freeblocks where city='$city' and maskbits<=$webvar{maskbits}".
506 " and cidr <<= '$webvar{allocfrom}' and routed='".
507 (($webvar{alloctype} =~ /^(.)r$/) ? "$1" : 'y')."'";
508 $sortorder = "maskbits desc,cidr";
509 } else {
510 $sql = "select cidr from freeblocks where city='$city' and maskbits<=$webvar{maskbits}".
511 " and routed='".(($webvar{alloctype} =~ /^(.)r$/) ? "$1" : 'y')."'";
512 $sortorder = "maskbits desc,cidr";
513 }
514 }
515 $sql = $sql.$extracond." order by ".$sortorder;
516 $sth = $ip_dbh->prepare($sql);
517 $sth->execute;
518 my @data = $sth->fetchrow_array();
519 if ($data[0] eq "") {
520 $page->param(err => $failmsg);
521 return;
522 }
523 $cidr = new NetAddr::IP $data[0];
524 } # check for freeblocks assignment or IPDB-controlled assignment
525
526 $alloc_from = "$cidr";
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 }
538 } # if ($webvar{alloctype} =~ /^.i$/)
539
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();
545 $page->param(nodename => $nodename);
546 $page->param(nodeid => $webvar{node});
547 }
548## end node hack
549
550 # Stick in the allocation data
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}));
559
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
565 # Check to see if user is allowed to do anything with sensitive data
566 my $privdata = '';
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})
572 if $webvar{userid};
573
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");
578
579} # end confirmAssign
580
581
582# Do the work of actually inserting a block in the database.
583sub insertAssign {
584 if ($IPDBacl{$authuser} !~ /a/) {
585 $aclerr = 'addblock';
586 return;
587 }
588 # Some things are done more than once.
589 return if !validateInput();
590
591 if (!defined($webvar{privdata})) {
592 $webvar{privdata} = '';
593 }
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.
597
598 my ($code,$msg) = allocateBlock($ip_dbh, $webvar{fullcidr}, $webvar{alloc_from},
599 $webvar{custid}, $webvar{alloctype}, $webvar{city}, $webvar{desc}, $webvar{notes},
600 $webvar{circid}, $webvar{privdata}, $webvar{node});
601
602 if ($code eq 'OK') {
603 if ($webvar{alloctype} =~ /^.i$/) {
604 $msg =~ s|/32||;
605 $page->param(staticip => $msg);
606 $page->param(custid => $webvar{custid});
607 $page->param(billinguser => $webvar{billinguser});
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");
611 } else {
612 my $netblock = new NetAddr::IP $webvar{fullcidr};
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 }
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");
625 }
626 syslog "notice", "$authuser allocated '$webvar{fullcidr}' to '$webvar{custid}' as ".
627 "'$webvar{alloctype}' ($msg)";
628 } else {
629 syslog "err", "Allocation of '$webvar{fullcidr}' to '$webvar{custid}' as ".
630 "'$webvar{alloctype}' by $authuser failed: '$msg'";
631 $page->param(err => "Allocation of $webvar{fullcidr} as '$disp_alloctypes{$webvar{alloctype}}'".
632 " failed:<br>\n$msg\n");
633 }
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 '-') {
643 $page->param(err => 'Please choose a city');
644 return;
645 }
646
647 # Alloctype check.
648 chomp $webvar{alloctype};
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.
652 $page->param(err => 'Invalid alloctype');
653 return;
654 }
655
656 # CustID check
657 # We have different handling for customer allocations and "internal" or "our" allocations
658 if ($def_custids{$webvar{alloctype}} eq '') {
659 if (!$webvar{custid}) {
660 $page->param(err => 'Please enter a customer ID.');
661 return;
662 }
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) {
669 $page->param(err => "Error verifying customer ID: ".$CustIDCK::ErrMsg);
670 return;
671 }
672 if (!$status) {
673 $page->param(err => "Customer ID not valid. Make sure the Customer ID ".
674 "is correct.<br>\nUse STAFF for staff static IPs, and $IPDB::defcustid for any other ".
675 "non-customer assignments.");
676 return;
677 }
678 }
679# print "<!-- [ In validateInput(). Insert customer ID cross-check here. ] -->\n";
680 } else {
681 # New! Improved! And now Loaded From The Database!!
682 if ((!$webvar{custid}) || ($webvar{custid} ne 'STAFF')) {
683 $webvar{custid} = $def_custids{$webvar{alloctype}};
684 }
685 }
686
687 # Check POP location
688 my $flag;
689 if ($webvar{alloctype} eq 'rm') {
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';
699##fixme: hook to force-set POP or city on certain alloctypes
700# if ($webvar{alloctype =~ /foo,bar,bz/ { $webvar{pop} = 'blah'; }
701 if ($webvar{pop} =~ /^-$/) {
702 $flag = 'to route the block from/through';
703 }
704 }
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
708 if ($flag ne 'n') {
709 $page->param(err => "Please choose a valid POP location $flag. Valid ".
710 "POP locations are currently:<br>\n".join (" - ", @poplist));
711 return;
712 }
713
714 return 'OK';
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
727##fixme: allow "SWIP" (publication to rWHOIS) of static IP data
728 if ($webvar{block} =~ /\/32$/) {
729 $sql = "select ip,custid,type,city,circuitid,description,notes,modifystamp,privdata from poolips where ip='$webvar{block}'";
730 } else {
731 $sql = "select cidr,custid,type,city,circuitid,description,notes,modifystamp,privdata,swip from allocations where cidr='$webvar{block}'"
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?
747# Also have areas where a routed block at a POP serves "many" cities/towns/named crossroads
748
749# @data: cidr,custid,type,city,circuitid,description,notes,modifystamp,privdata,swip
750
751 $page->param(block => $webvar{block});
752
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]);
758
759##fixme The check here should be built from the database
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
778## node hack
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}'");
781 $sth->execute;
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/) {
794 $sth = $ip_dbh->prepare("SELECT node_id, node_name FROM nodes ORDER BY node_type,node_id");
795 $sth->execute;
796 my @nodelist;
797 while (my ($nid,$nname) = $sth->fetchrow_array()) {
798 my %row = (
799 selme => ($nodeid == $nid),
800 nodeid => $nid,
801 nodename => $nname,
802 );
803 push (@nodelist, \%row);
804 }
805 $page->param(nodelist => \@nodelist);
806 }
807 }
808## end node hack
809
810 my ($lastmod,undef) = split /\s+/, $data[7];
811 $page->param(lastmod => $lastmod);
812
813 # not happy with the upside-down logic, but...
814 $page->param(swipable => $data[2] !~ /.i/);
815 $page->param(swip => $data[10] ne 'n');
816
817 # Check to see if we can display sensitive data
818 $page->param(nocling => $IPDBacl{$authuser} =~ /s/);
819 $page->param(privdata => $data[8]);
820
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/);
824
825} # edit()
826
827
828# Stuff new info about a block into the db
829# action=update
830sub update {
831 if ($IPDBacl{$authuser} !~ /c/) {
832 $aclerr = 'updateblock';
833 return;
834 }
835
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
842 # Make sure incoming data is in correct format - custID among other things.
843 return if !validateInput;
844
845 # SQL transaction wrapper
846 eval {
847 # Relatively simple SQL transaction here.
848 my $sql;
849 if (my $pooltype = ($webvar{alloctype} =~ /^(.)i$/) ) {
850 $sql = "UPDATE poolips SET custid='$webvar{custid}',".
851 "city=?,description=?,notes=?,".
852 "circuitid='$webvar{circid}',".
853 "$privdata where ip='$webvar{block}'";
854 } else {
855 $sql = "UPDATE allocations SET custid='$webvar{custid}',".
856 "city=?,description=?,notes=?,".
857 "circuitid='$webvar{circid}'$privdata,".
858 "type='$webvar{alloctype}',".
859 "swip='".($webvar{swip} eq 'on' ? 'y' : 'n')."' ".
860 "where cidr='$webvar{block}'";
861 }
862 # Log the details of the change.
863 syslog "debug", $sql;
864 $sth = $ip_dbh->prepare($sql);
865 $sth->execute($webvar{city}, $webvar{desc}, $webvar{notes});
866## node hack
867 if ($webvar{node}) {
868 # done with delete/insert so we don't have to worry about funkyness updating a node ref that isn't there
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
874 $ip_dbh->commit;
875 };
876 if ($@) {
877 my $msg = $@;
878 eval { $ip_dbh->rollback; };
879 syslog "err", "$authuser could not update block/IP '$webvar{block}': '$msg'";
880 $page->param(err => "Could not update block/IP $webvar{block}: $msg");
881 return;
882 }
883
884 # If we get here, the operation succeeded.
885 syslog "notice", "$authuser updated $webvar{block}";
886##fixme: need to wedge something in to allow "update:field" notifications
887## hmm. how to tell what changed? O_o
888mailNotify($ip_dbh, 's:swi', "SWIPed: $disp_alloctypes{$webvar{alloctype}} $webvar{block}",
889 "$webvar{block} had SWIP status changed to \"Yes\" by $authuser") if $webvar{swip} eq 'on';
890
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
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$/) ) {
904 $page->param(backpool => 1);
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;
915 $page->param(backblock => $cblock);
916
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/;
928
929} # update()
930
931
932# Delete an allocation.
933sub remove {
934 if ($IPDBacl{$authuser} !~ /d/) {
935 $aclerr = 'delblock';
936 return;
937 }
938
939 # Serves'em right for getting here...
940 if (!defined($webvar{block})) {
941 $page->param(err => "Can't delete a block that doesn't exist");
942 return;
943 }
944
945 my ($cidr, $custid, $type, $city, $circid, $desc, $notes, $alloctype, $privdata);
946
947 if ($webvar{alloctype} eq 'rm') {
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};
959 $circid = "N/A";
960 $desc = "N/A";
961 $notes = "N/A";
962 $privdata = "N/A";
963
964 } elsif ($webvar{alloctype} eq 'mm') {
965
966 $cidr = $webvar{block};
967 $city = "N/A";
968 $custid = "N/A";
969 $alloctype = $webvar{alloctype};
970 $circid = "N/A";
971 $desc = "N/A";
972 $notes = "N/A";
973 $privdata = "N/A";
974
975 } elsif ($webvar{alloctype} =~ /^.i$/) { # done with alloctype=[rm]m
976
977 # Unassigning a static IP
978 my $sth = $ip_dbh->prepare("select ip,custid,city,type,notes,circuitid,privdata".
979 " from poolips where ip='$webvar{block}'");
980 $sth->execute();
981# croak $sth->errstr() if($sth->errstr());
982
983 $sth->bind_columns(\$cidr, \$custid, \$city, \$alloctype, \$notes, \$circid,
984 \$privdata);
985 $sth->fetch() || croak $sth->errstr;
986
987 } else { # done with alloctype=~ /^.i$/
988
989 my $sth = $ip_dbh->prepare("select cidr,custid,type,city,circuitid,description,notes,privdata".
990 " from allocations where cidr='$webvar{block}'");
991 $sth->execute();
992# croak $sth->errstr() if($sth->errstr());
993
994 $sth->bind_columns(\$cidr, \$custid, \$alloctype, \$city, \$circid, \$desc,
995 \$notes, \$privdata);
996 $sth->fetch() || carp $sth->errstr;
997 } # end cases for different alloctypes
998
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]$/);
1010
1011} # end remove()
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 {
1019 if ($IPDBacl{$authuser} !~ /d/) {
1020 $aclerr = 'delblock';
1021 return;
1022 }
1023
1024 # need to retrieve block data before deleting so we can notify on that
1025 my $blockinfo = getBlockData($ip_dbh, $webvar{block});
1026
1027 my ($code,$msg) = deleteBlock($ip_dbh, $webvar{block}, $webvar{alloctype});
1028
1029 $page->param(block => $webvar{block});
1030 if ($code eq 'OK') {
1031 syslog "notice", "$authuser deallocated '$webvar{alloctype}'-type netblock $webvar{block} ".
1032 $blockinfo->{custid}.", ".$blockinfo->{city}.", desc='".$blockinfo->{description}."'";
1033 mailNotify($ip_dbh, 'da', "REMOVED: $disp_alloctypes{$webvar{alloctype}} $webvar{block}",
1034 "$disp_alloctypes{$webvar{alloctype}} $webvar{block} deallocated by $authuser\n".
1035 "CustID: ".$blockinfo->{custid}."\nCity: ".$blockinfo->{city}.
1036 "\nDescription: ".$blockinfo->{description}."\n");
1037 } else {
1038 $page->param(failmsg => $msg);
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'";
1043 $page->param(netblock => 1);
1044 }
1045 }
1046
1047} # finalDelete
Note: See TracBrowser for help on using the repository browser.