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

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

/trunk

Clean up and move most SQL for allocation update into IPDB.pm. See #34.

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