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

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

/trunk

Clean up and move SQL behind block assignment page to IPDB.pm. See #34.

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