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

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

/trunk

Clean up and move SQL to IPDB.pm for pool-selector for static IPs
on allocation confirmation page. See #34.

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