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

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

/trunk

Clean up and move SQL for showRBlock to IPDB.pm
Tweak listFree() since the segments in showMaster and showRBlock it
replaced weren't quite as identical as I thought
Convert template to use odd and squeeze a bit more HTML out of
main.cgi and IPDB.pm

See #34.

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