source: branches/htmlform/cgi-bin/main.cgi@ 497

Last change on this file since 497 was 497, checked in by Kris Deugau, 13 years ago

/branches/htmlform

Fix up main.cgi

  • it got contaiminated with the template location for admin.cgi
  • tweak a fixme comment

See #3.

  • Property svn:executable set to *
  • Property svn:keywords set to Date Rev Author
File size: 39.7 KB
Line 
1#!/usr/bin/perl
2# ipdb/cgi-bin/main.cgi
3###
4# SVN revision info
5# $Date: 2011-09-23 16:51:27 +0000 (Fri, 23 Sep 2011) $
6# SVN revision $Rev: 497 $
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 CommonWeb qw(:ALL);
18use CustIDCK;
19use POSIX qw(ceil);
20use NetAddr::IP;
21
22use Sys::Syslog;
23
24# don't remove! required for GNU/FHS-ish install from tarball
25##uselib##
26
27use MyIPDB;
28
29openlog "IPDB","pid","$IPDB::syslog_facility";
30
31## Environment. Collect some things, process some things, set some things...
32
33# Collect the username from HTTP auth. If undefined, we're in
34# a test environment, or called without a username.
35my $authuser;
36if (!defined($ENV{'REMOTE_USER'})) {
37 $authuser = '__temptest';
38} else {
39 $authuser = $ENV{'REMOTE_USER'};
40}
41
42# anyone got a better name? :P
43my $thingroot = $ENV{SCRIPT_FILENAME};
44$thingroot =~ s|cgi-bin/main.cgi||;
45
46syslog "debug", "$authuser active, $ENV{'REMOTE_ADDR'}";
47
48##fixme there *must* be a better order to do things in so this can go back where it was
49# CGI fiddling done here so we can declare %webvar so we can alter $webvar{action}
50# to show the right page on DB errors.
51# Set up the CGI object...
52my $q = new CGI::Simple;
53# ... and get query-string params as well as POST params if necessary
54$q->parse_query_string;
55
56# Convenience; saves changing all references to %webvar
57##fixme: tweak for handling <select multiple='y' size=3> (list with multiple selection)
58my %webvar = $q->Vars;
59
60# Why not a global DB handle? (And a global statement handle, as well...)
61# Use the connectDB function, otherwise we end up confusing ourselves
62my $ip_dbh;
63my $sth;
64my $errstr;
65($ip_dbh,$errstr) = connectDB_My;
66if (!$ip_dbh) {
67 $webvar{action} = "dberr";
68} else {
69 initIPDBGlobals($ip_dbh);
70}
71
72# Set up some globals
73$ENV{HTML_TEMPLATE_ROOT} = $thingroot."templates";
74
75my $header = HTML::Template->new(filename => "header.tmpl");
76my $footer = HTML::Template->new(filename => "footer.tmpl");
77
78$header->param(version => $IPDB::VERSION);
79$header->param(addperm => $IPDBacl{$authuser} =~ /a/);
80print "Content-type: text/html\n\n", $header->output;
81
82
83#main()
84
85if(!defined($webvar{action})) {
86 $webvar{action} = "index"; #shuts up the warnings.
87}
88
89my $page;
90if (-e "$ENV{HTML_TEMPLATE_ROOT}/$webvar{action}.tmpl") {
91 $page = HTML::Template->new(filename => "$webvar{action}.tmpl");
92} else {
93 $page = HTML::Template->new(filename => "dunno.tmpl");
94}
95
96if($webvar{action} eq 'index') {
97 showSummary();
98} elsif ($webvar{action} eq 'addmaster') {
99 if ($IPDBacl{$authuser} !~ /a/) {
100 printError("You shouldn't have been able to get here. Access denied.");
101 }
102} elsif ($webvar{action} eq 'newmaster') {
103
104 if ($IPDBacl{$authuser} !~ /a/) {
105 printError("You shouldn't have been able to get here. Access denied.");
106 } else {
107 my $cidr = new NetAddr::IP $webvar{cidr};
108 $page->param(cidr => "$cidr");
109
110 my ($code,$msg) = addMaster($ip_dbh, $webvar{cidr});
111
112 if ($code eq 'FAIL') {
113 syslog "err", "Could not add master block '$webvar{cidr}' to database: '$msg'";
114 $page->param(err => $msg);
115 } else {
116 syslog "info", "$authuser added master block $webvar{cidr}";
117 }
118
119 } # ACL check
120
121} # end add new master
122
123elsif($webvar{action} eq 'showmaster') {
124 showMaster();
125}
126elsif($webvar{action} eq 'showrouted') {
127 showRBlock();
128}
129elsif($webvar{action} eq 'listpool') {
130 listPool();
131}
132
133# Not modified or added; just shuffled
134elsif($webvar{action} eq 'assign') {
135 assignBlock();
136}
137elsif($webvar{action} eq 'confirm') {
138 confirmAssign();
139}
140elsif($webvar{action} eq 'insert') {
141 insertAssign();
142}
143elsif($webvar{action} eq 'edit') {
144 edit();
145}
146elsif($webvar{action} eq 'update') {
147 update();
148}
149elsif($webvar{action} eq 'delete') {
150 remove();
151}
152elsif($webvar{action} eq 'finaldelete') {
153 finalDelete();
154}
155elsif ($webvar{action} eq 'nodesearch') {
156 $sth = $ip_dbh->prepare("SELECT node_id, node_name FROM nodes ORDER BY node_type,node_id");
157 $sth->execute() or $page->param(errmsg => $sth->errstr);
158 my @nodelist;
159 while (my ($nid,$nname) = $sth->fetchrow_array()) {
160 my %row = (nodeid => $nid, nodename => $nname);
161 push @nodelist, \%row;
162 }
163 $page->param(nodelist => \@nodelist);
164}
165
166# DB failure. Can't do much here, really.
167elsif ($webvar{action} eq 'dberr') {
168 $page->param(errmsg => $errstr);
169}
170
171# Default is an error. It shouldn't be possible to get here unless you're
172# randomly feeding in values for webvar{action}.
173else {
174 my $rnd = rand 500;
175 my $boing = sprintf("%.2f", rand 500);
176 my @excuses = (
177 "Aether cloudy. Ask again later about $webvar{action}.",
178 "The gods are unhappy with your sacrificial $webvar{action}.",
179 "Because one of $webvar{action}'s legs are both the same",
180 "<b>wibble</b><br>Can't $webvar{action}, the grue will get me!<br>Can't $webvar{action}, the grue will get me!",
181 "Hey, man, you've had your free $webvar{action}. Next one's gonna... <i>cost</i>....",
182 "I ain't done $webvar{action}",
183 "Oooo, look! A flying $webvar{action}!",
184 "$webvar{action} too evil, avoiding.",
185 "Rocks fall, $webvar{action} dies.",
186 "Bit bucket must be emptied before I can $webvar{action}..."
187 );
188 $page->param(dunno => $excuses[$rnd/50.0]);
189}
190## Finally! Done with that NASTY "case" emulation!
191
192
193
194# Clean up IPDB globals, DB handle, etc.
195finish($ip_dbh);
196
197## Do all our printing here so we can generate errors and stick them into the slots in the templates.
198
199# can't do this yet, too many blowups
200#print "Content-type: text/html\n\n", $header->output;
201
202print $page->output;
203
204# include the admin tools link in the output?
205$footer->param(adminlink => ($IPDBacl{$authuser} =~ /A/));
206
207print $footer->output;
208
209# Just in case something waaaayyy down isn't in place
210# properly... we exit explicitly.
211exit 0;
212
213
214# Initial display: Show master blocks with total allocated subnets, total free subnets
215sub showSummary {
216 my %allocated;
217 my %free;
218 my %routed;
219 my %bigfree;
220
221 # Count the allocations.
222 $sth = $ip_dbh->prepare("select count(*) from allocations where cidr <<= ?");
223 foreach my $master (@masterblocks) {
224 $sth->execute("$master");
225 $sth->bind_columns(\$allocated{"$master"});
226 $sth->fetch();
227 }
228
229 # Count routed blocks
230 $sth = $ip_dbh->prepare("select count(*) from routed where cidr <<= ?");
231 foreach my $master (@masterblocks) {
232 $sth->execute("$master");
233 $sth->bind_columns(\$routed{"$master"});
234 $sth->fetch();
235 }
236
237 # Count the free blocks.
238 $sth = $ip_dbh->prepare("select count(*) from freeblocks where cidr <<= ? and ".
239 "(routed='y' or routed='n')");
240 foreach my $master (@masterblocks) {
241 $sth->execute("$master");
242 $sth->bind_columns(\$free{"$master"});
243 $sth->fetch();
244 }
245
246 # Find the largest free block in each master
247 $sth = $ip_dbh->prepare("select maskbits from freeblocks where cidr <<= ? and ".
248 "(routed='y' or routed='n') order by maskbits limit 1");
249 foreach my $master (@masterblocks) {
250 $sth->execute("$master");
251 $sth->bind_columns(\$bigfree{"$master"});
252 $sth->fetch();
253 }
254
255 # Assemble the data to stuff into the template.
256 my @masterlist;
257 my $rowclass=0;
258 foreach my $master (@masterblocks) {
259 my %row = (
260 rowclass => $rowclass++ % 2,
261 master => "$master",
262 routed => $routed{"$master"},
263 allocated => $allocated{"$master"},
264 free => $free{"$master"},
265 bigfree => ( ($bigfree{"$master"} eq '') ? ("&lt;NONE&gt;") : ("/".$bigfree{"$master"}) )
266 );
267 push (@masterlist, \%row);
268 }
269 $page->param(masterlist => \@masterlist);
270
271 $page->param(addmaster => ($IPDBacl{$authuser} =~ /a/) );
272
273} # showSummary
274
275
276# Display detail on master
277# Alrighty then! We're showing routed blocks within a single master this time.
278# We should be able to steal code from showSummary(), and if I'm really smart
279# I'll figger a way to munge the two together. (Once I've done that, everything
280# else should follow. YMMV.)
281sub showMaster {
282
283 $page->param(master => $webvar{block});
284
285 my %allocated;
286 my %free;
287 my %cities;
288 my %bigfree;
289
290 my $master = new NetAddr::IP $webvar{block};
291 my @localmasters;
292
293 # Fetch only the blocks relevant to this master
294 $sth = $ip_dbh->prepare("select cidr,city from routed where cidr <<= '$master' order by cidr");
295 $sth->execute();
296
297 my $i=0;
298 while (my @data = $sth->fetchrow_array()) {
299 my $cidr = new NetAddr::IP $data[0];
300 $localmasters[$i++] = $cidr;
301 $free{"$cidr"} = 0;
302 $allocated{"$cidr"} = 0;
303 $bigfree{"$cidr"} = 128;
304 # Retain the routing destination
305 $cities{"$cidr"} = $data[1];
306 }
307
308 # Check if there were actually any blocks routed from this master
309 if ($i > 0) {
310
311 # Count the allocations
312 $sth = $ip_dbh->prepare("select count(*) from allocations where cidr <<= ?");
313 foreach my $master (@localmasters) {
314 $sth->execute("$master");
315 $sth->bind_columns(\$allocated{"$master"});
316 $sth->fetch();
317 }
318
319 # Count the free blocks.
320 $sth = $ip_dbh->prepare("select count(*) from freeblocks where cidr <<= ? and ".
321 "(routed='y' or routed='n')");
322 foreach my $master (@localmasters) {
323 $sth->execute("$master");
324 $sth->bind_columns(\$free{"$master"});
325 $sth->fetch();
326 }
327
328 # Get the size of the largest free block
329 $sth = $ip_dbh->prepare("select maskbits from freeblocks where cidr <<= ? and ".
330 "(routed='y' or routed='n') order by maskbits limit 1");
331 foreach my $master (@localmasters) {
332 $sth->execute("$master");
333 $sth->bind_columns(\$bigfree{"$master"});
334 $sth->fetch();
335 }
336
337 my @routed;
338 my $rowclass = 0;
339 foreach my $master (@localmasters) {
340 my %row = (
341 rowclass => $rowclass++ % 2,
342 block => "$master",
343 city => $cities{"$master"},
344 nsubs => $allocated{"$master"},
345 nfree => $free{"$master"},
346 lfree => ( ($bigfree{"$master"} eq 128) ? ("&lt;NONE&gt;") : ("/".$bigfree{"$master"}) )
347 );
348 push @routed, \%row;
349 }
350 $page->param(routedlist => \@routed);
351
352 } # end check for existence of routed blocks in master
353
354 $page->param(delmaster => ($IPDBacl{$authuser} =~ /d/));
355
356 # Snag the free blocks.
357 my $count = 0;
358 $sth = $ip_dbh->prepare("select cidr from freeblocks where cidr <<='$master' and ".
359 "routed='n' order by cidr");
360 $sth->execute();
361 my @unrouted;
362 my $rowclass = 0;
363 while (my @data = $sth->fetchrow_array()) {
364 my $cidr = new NetAddr::IP $data[0];
365 my %row = (
366 rowclass => $rowclass++ % 2,
367 fblock => "$cidr",
368 frange => $cidr->range
369 );
370 push @unrouted, \%row;
371 }
372 $page->param(unrouted => \@unrouted);
373
374} # showMaster
375
376
377# Display details of a routed block
378# Alrighty then! We're showing allocations within a routed block this time.
379# We should be able to steal code from showSummary() and showMaster(), and if
380# I'm really smart I'll figger a way to munge all three together. (Once I've
381# done that, everything else should follow. YMMV.
382# This time, we check the database before spewing, because we may
383# not have anything useful to spew.
384sub showRBlock {
385
386 my $master = new NetAddr::IP $webvar{block};
387
388 $sth = $ip_dbh->prepare("select city from routed where cidr='$master'");
389 $sth->execute;
390 my ($rcity) = $sth->fetchrow_array;
391
392 $page->param(master => "$master");
393 $page->param(rcity => $rcity);
394
395 # Snag the allocations for this block
396 $sth = $ip_dbh->prepare("select cidr,city,type,custid,swip,description".
397 " from allocations where cidr <<= '$master' order by cidr");
398 $sth->execute();
399
400 # hack hack hack
401 # set up to flag swip=y records if they don't actually have supporting data in the customers table
402 my $custsth = $ip_dbh->prepare("select count(*) from customers where custid=?");
403
404 my $rowclass = 0;
405 my @blocklist;
406 while (my ($cidr,$city,$type,$custid,$swip,$desc) = $sth->fetchrow_array()) {
407 $custsth->execute($custid);
408 my ($ncust) = $custsth->fetchrow_array();
409
410 my %row = (
411 rowclass => $rowclass++ % 2,
412 block => $cidr,
413 city => $city,
414 type => $disp_alloctypes{$type},
415 custid => $custid,
416 swip => ($swip eq 'y' ? ($ncust == 0 ? 'Yes<small>*</small>' : 'Yes') : 'No'),
417 desc => $desc
418 );
419 $row{subblock} = ($type =~ /^.r$/); # hmf. wonder why these won't work in the hash declaration...
420 $row{listpool} = ($type =~ /^.[pd]$/);
421 push (@blocklist, \%row);
422 }
423 $page->param(blocklist => \@blocklist);
424
425 $page->param(delrouted => $IPDBacl{$authuser} =~ /d/);
426
427 # Snag the free blocks. We don't really *need* to be pedantic about avoiding
428 # unrouted free blocks, but it's better to let the database do the work if we can.
429 $rowclass = 0;
430 my @unassigned;
431 $sth = $ip_dbh->prepare("select cidr,routed from freeblocks where cidr <<= '$master'".
432 " order by cidr");
433 $sth->execute();
434 while (my ($cidr_db,$routed) = $sth->fetchrow_array()) {
435 my $cidr = new NetAddr::IP $cidr_db;
436
437 my %row = (
438 rowclass => $rowclass++ % 2,
439 subblock => ($routed ne 'y' && $routed ne 'n'),
440 fblock => $cidr_db,
441 fbtype => $routed,
442 frange => $cidr->range,
443 );
444 push @unassigned, \%row;
445 }
446 $page->param(unassigned => \@unassigned);
447
448} # showRBlock
449
450
451# List the IPs used in a pool
452sub listPool {
453
454 my $cidr = new NetAddr::IP $webvar{pool};
455
456 $page->param(block => $webvar{pool});
457 $page->param(netip => $cidr->addr);
458 $cidr++;
459 $page->param(gate => $cidr->addr);
460 $cidr--; $cidr--;
461 $page->param(bcast => $cidr->addr);
462 $page->param(mask => $cidr->mask);
463
464 # Snag pool info for heading
465 $sth = $ip_dbh->prepare("select type,city from allocations where cidr=?");
466 $sth->execute($webvar{pool});
467 my ($pooltype, $poolcity) = $sth->fetchrow_array;
468
469 $page->param(disptype => $disp_alloctypes{$pooltype});
470 $page->param(city => $poolcity);
471
472 # Only display net/gw/bcast if it's a "real" netblock and not a PPP(oE) lunacy
473 $page->param(realblock => $pooltype =~ /^.d$/);
474
475# probably have to add an "edit IP allocation" link here somewhere.
476
477 $sth = $ip_dbh->prepare("select ip,custid,available,description,type".
478 " from poolips where pool='$webvar{pool}' order by ip");
479 $sth->execute;
480 my @poolips;
481 my $rowclass = 0;
482 while (my ($ip,$custid,$available,$desc,$type) = $sth->fetchrow_array) {
483 my %row = (
484 rowclass => $rowclass++ % 2,
485 ip => $ip,
486 custid => $custid,
487 available => $available,
488 desc => $desc,
489 maydel => $IPDBacl{$authuser} =~ /d/,
490 delme => $available eq 'n'
491 );
492 push @poolips, \%row;
493 }
494 $page->param(poolips => \@poolips);
495
496} # end listPool
497
498
499# Show "Add new allocation" page. Note that the actual page may
500# be one of two templates, and the lists come from the database.
501sub assignBlock {
502
503 if ($IPDBacl{$authuser} !~ /a/) {
504 printError("You shouldn't have been able to get here. Access denied.");
505 return;
506 }
507
508 # hack pthbttt eww
509 $webvar{block} = '' if !$webvar{block};
510
511# hmm. TMPL_IF block and TMPL_ELSE block on these instead?
512 $page->param(rowa => 'row'.($webvar{block} eq '' ? 1 : 0));
513 $page->param(rowb => 'row'.($webvar{block} eq '' ? 0 : 1));
514 $page->param(block => $webvar{block}); # fb-assign flag, if block is set, we're in fb-assign
515 $page->param(iscontained => ($webvar{fbtype} && $webvar{fbtype} ne 'y'));
516
517 # New special case- block to assign is specified
518 if ($webvar{block} ne '') {
519 my $block = new NetAddr::IP $webvar{block};
520
521 # Handle contained freeblock allocation.
522 # This is a little dangerous, as it's *theoretically* possible to
523 # get fbtype='n' (aka a non-routed freeblock). However, should
524 # someone manage to get there, they get what they deserve.
525 if ($webvar{fbtype} ne 'y') {
526 # Snag the type of the container block from the database.
527 $sth = $ip_dbh->prepare("select type from allocations where cidr >>='$block'");
528 $sth->execute;
529 my @data = $sth->fetchrow_array;
530 $data[0] =~ s/c$/r/; # Munge the type into the correct form
531 $page->param(fbdisptype => $list_alloctypes{$data[0]});
532 $page->param(type => $data[0]);
533 } else {
534 $sth = $ip_dbh->prepare("select type,listname from alloctypes where listorder < 500 ".
535 "and type not like '_i' and type not like '_r' order by listorder");
536 $sth->execute;
537 my @typelist;
538 my $selflag = 0;
539 while (my @data = $sth->fetchrow_array) {
540 my %row = (tval => $data[0],
541 type => $data[1],
542 sel => ($selflag == 0 ? ' selected' : '')
543 );
544 push (@typelist, \%row);
545 $selflag++;
546 }
547 $page->param(typelist => \@typelist);
548 }
549 } else {
550 my @masterlist;
551 foreach my $master (@masterblocks) {
552 my %row = (master => "$master");
553 push (@masterlist, \%row);
554 }
555 $page->param(masterlist => \@masterlist);
556
557 my @pops;
558 foreach my $pop (@poplist) {
559 my %row = (pop => $pop);
560 push (@pops, \%row);
561 }
562 $page->param(pops => \@pops);
563
564 # could arguably include routing (500) in the list, but ATM it doesn't
565 # make sense, and in any case that shouldn't be structurally possible here.
566 $sth = $ip_dbh->prepare("select type,listname from alloctypes where listorder <= 500 order by listorder");
567 $sth->execute;
568 my @typelist;
569 my $selflag = 0;
570 while (my @data = $sth->fetchrow_array) {
571 my %row = (tval => $data[0],
572 type => $data[1],
573 sel => ($selflag == 0 ? ' selected' : '')
574 );
575 push (@typelist, \%row);
576 $selflag++;
577 }
578 $page->param(typelist => \@typelist);
579 }
580
581 my @cities;
582 foreach my $city (@citylist) {
583 my %row = (city => $city);
584 push (@cities, \%row);
585 }
586 $page->param(citylist => \@cities);
587
588## node hack
589 $sth = $ip_dbh->prepare("SELECT node_id, node_name FROM nodes ORDER BY node_type,node_id");
590 $sth->execute() or print "DEBUG: failed retrieval from nodes: ".$sth->errstr,"<br>\n";
591 my @nodes;
592 while (my ($nid,$nname) = $sth->fetchrow_array()) {
593 my %row = (nid => $nid, nname => $nname);
594 push (@nodes, \%row);
595 }
596 $page->param(nodelist => \@nodes);
597## end node hack
598
599 $page->param(privdata => $IPDBacl{$authuser} =~ /s/);
600
601} # assignBlock
602
603
604# Take info on requested IP assignment and see what we can provide.
605sub confirmAssign {
606 if ($IPDBacl{$authuser} !~ /a/) {
607 printError("You shouldn't have been able to get here. Access denied.");
608 return;
609 }
610
611 my $cidr;
612 my $alloc_from;
613
614 # Going to manually validate some items.
615 # custid and city are automagic.
616 return if !validateInput();
617
618# Several different cases here.
619# Static IP vs netblock
620# + Different flavours of static IP
621# + Different flavours of netblock
622
623 if ($webvar{alloctype} =~ /^.i$/) {
624 my ($base,undef) = split //, $webvar{alloctype}; # split into individual chars
625
626# Ewww. But it works.
627 $sth = $ip_dbh->prepare("SELECT (SELECT city FROM allocations WHERE cidr=poolips.pool), ".
628 "poolips.pool, COUNT(*) FROM poolips,allocations WHERE poolips.available='y' AND ".
629 "poolips.pool=allocations.cidr AND allocations.city='$webvar{pop}' AND poolips.type LIKE '".$base."_' ".
630 "GROUP BY pool");
631 $sth->execute;
632 my $optionlist;
633
634 my @poollist;
635 while (my ($poolcit,$poolblock,$poolfree) = $sth->fetchrow_array) {
636 # city,pool cidr,free IP count
637 if ($poolfree > 0) {
638 my %row = (poolcit => $poolcit, poolblock => $poolblock, poolfree => $poolfree);
639 push (@poollist, \%row);
640 }
641 }
642 $page->param(staticip => 1);
643 $page->param(poollist => \@poollist);
644 $cidr = "Single static IP";
645##fixme: need to handle "no available pools"
646
647 } else { # end show pool options
648
649 if ($webvar{fbassign} eq 'y') {
650 $cidr = new NetAddr::IP $webvar{block};
651 $webvar{maskbits} = $cidr->masklen;
652 } else { # done with direct freeblocks assignment
653
654 if (!$webvar{maskbits}) {
655 $page->param(err => "Please specify a CIDR mask length.");
656 return;
657 }
658 my $sql;
659 my $city;
660 my $failmsg;
661 my $extracond = '';
662 if ($webvar{allocfrom} eq '-') {
663 $extracond = ($webvar{allowpriv} eq 'on' ? '' :
664 " and not (cidr <<= '192.168.0.0/16'".
665 " or cidr <<= '10.0.0.0/8'".
666 " or cidr <<= '172.16.0.0/12')");
667 }
668 my $sortorder;
669 if ($webvar{alloctype} eq 'rm') {
670 if ($webvar{allocfrom} ne '-') {
671 $sql = "select * from freeblocks where maskbits<=$webvar{maskbits} and routed='n'".
672 " and cidr <<= '$webvar{allocfrom}'";
673 $sortorder = "maskbits desc";
674 } else {
675 $sql = "select * from freeblocks where maskbits<=$webvar{maskbits} and routed='n'";
676 $sortorder = "maskbits desc";
677 }
678 $failmsg = "No suitable free block found.<br>\nWe do not have a free".
679 " routeable block of that size.<br>\nYou will have to either route".
680 " a set of smaller netblocks or a single smaller netblock.";
681 } else {
682##fixme
683# This section needs serious Pondering.
684 # Pools of most types get assigned to the POP they're "routed from"
685 # This includes WAN blocks and other netblock "containers"
686 # This does NOT include cable pools.
687 if ($webvar{alloctype} =~ /^.[pc]$/) {
688 $city = $webvar{city};
689 $failmsg = "No suitable free block found.<br>\nYou will have to route another".
690 " superblock from one of the<br>\nmaster blocks or chose a smaller".
691 " block size for the pool.";
692 } else {
693 $city = $webvar{pop};
694 $failmsg = "No suitable free block found.<br>\nYou will have to route another".
695 " superblock to $webvar{pop}<br>\nfrom one of the master blocks or".
696 " chose a smaller blocksize.";
697 }
698 if (defined $webvar{allocfrom} && $webvar{allocfrom} ne '-') {
699 $sql = "select cidr from freeblocks where city='$city' and maskbits<=$webvar{maskbits}".
700 " and cidr <<= '$webvar{allocfrom}' and routed='".
701 (($webvar{alloctype} =~ /^(.)r$/) ? "$1" : 'y')."'";
702 $sortorder = "maskbits desc,cidr";
703 } else {
704 $sql = "select cidr from freeblocks where city='$city' and maskbits<=$webvar{maskbits}".
705 " and routed='".(($webvar{alloctype} =~ /^(.)r$/) ? "$1" : 'y')."'";
706 $sortorder = "maskbits desc,cidr";
707 }
708 }
709 $sql = $sql.$extracond." order by ".$sortorder;
710 $sth = $ip_dbh->prepare($sql);
711 $sth->execute;
712 my @data = $sth->fetchrow_array();
713 if ($data[0] eq "") {
714 $page->param(err => $failmsg);
715 return;
716 }
717 $cidr = new NetAddr::IP $data[0];
718 } # check for freeblocks assignment or IPDB-controlled assignment
719
720 $alloc_from = "$cidr";
721
722 # If the block to be allocated is smaller than the one we found,
723 # figure out the "real" block to be allocated.
724 if ($cidr->masklen() ne $webvar{maskbits}) {
725 my $maskbits = $cidr->masklen();
726 my @subblocks;
727 while ($maskbits++ < $webvar{maskbits}) {
728 @subblocks = $cidr->split($maskbits);
729 }
730 $cidr = $subblocks[0];
731 }
732 } # if ($webvar{alloctype} =~ /^.i$/)
733
734## node hack
735 if ($webvar{node} && $webvar{node} ne '-') {
736 $sth = $ip_dbh->prepare("SELECT node_name FROM nodes WHERE node_id=?");
737 $sth->execute($webvar{node});
738 my ($nodename) = $sth->fetchrow_array();
739 $page->param(nodename => $nodename);
740 $page->param(nodeid => $webvar{node});
741 }
742## end node hack
743
744 # Stick in the allocation data
745 $page->param(alloc_type => $webvar{alloctype});
746 $page->param(typefull => $q->escapeHTML($disp_alloctypes{$webvar{alloctype}}));
747 $page->param(alloc_from => $alloc_from);
748 $page->param(cidr => $cidr);
749 $page->param(city => $q->escapeHTML($webvar{city}));
750 $page->param(custid => $webvar{custid});
751 $page->param(circid => $q->escapeHTML($webvar{circid}));
752 $page->param(desc => $q->escapeHTML($webvar{desc}));
753
754##fixme: find a way to have the displayed copy have <br> substitutions
755# for newlines, and the <input> value have either encoded or bare newlines.
756# Also applies to privdata.
757 $page->param(notes => $q->escapeHTML($webvar{notes},'y'));
758
759 # Check to see if user is allowed to do anything with sensitive data
760 my $privdata = '';
761 $page->param(privdata => $q->escapeHTML($webvar{privdata},'y'))
762 if $IPDBacl{$authuser} =~ /s/;
763
764 # Yay! This now has it's very own little home.
765 $page->param(billinguser => $webvar{userid})
766 if $webvar{userid};
767
768##fixme: this is only needed iff confirm.tmpl and
769# confirmRemove.tmpl are merged (quite possible, just
770# a little tedious)
771 $page->param(action => "insert");
772
773} # end confirmAssign
774
775
776# Do the work of actually inserting a block in the database.
777sub insertAssign {
778 if ($IPDBacl{$authuser} !~ /a/) {
779 printError("You shouldn't have been able to get here. Access denied.");
780 return;
781 }
782 # Some things are done more than once.
783 return if !validateInput();
784
785 if (!defined($webvar{privdata})) {
786 $webvar{privdata} = '';
787 }
788 # $code is "success" vs "failure", $msg contains OK for a
789 # successful netblock allocation, the IP allocated for static
790 # IP, or the error message if an error occurred.
791
792 my ($code,$msg) = allocateBlock($ip_dbh, $webvar{fullcidr}, $webvar{alloc_from},
793 $webvar{custid}, $webvar{alloctype}, $webvar{city}, $webvar{desc}, $webvar{notes},
794 $webvar{circid}, $webvar{privdata}, $webvar{node});
795
796 if ($code eq 'OK') {
797 if ($webvar{alloctype} =~ /^.i$/) {
798 $msg =~ s|/32||;
799 $page->param(staticip => $msg);
800 $page->param(custid => $webvar{custid});
801 $page->param(billinguser => $webvar{billinguser});
802 mailNotify($ip_dbh, "a$webvar{alloctype}", "ADDED: $disp_alloctypes{$webvar{alloctype}} allocation",
803 "$disp_alloctypes{$webvar{alloctype}} $msg allocated to customer $webvar{custid}\n".
804 "Description: $webvar{desc}\n\nAllocated by: $authuser\n");
805 } else {
806 my $netblock = new NetAddr::IP $webvar{fullcidr};
807 $page->param(fullcidr => $webvar{fullcidr});
808 $page->param(alloctype => $disp_alloctypes{$webvar{alloctype}});
809 $page->param(custid => $webvar{custid});
810 if ($webvar{alloctype} eq 'pr' && $webvar{billinguser}) {
811 $page->param(billinguser => $webvar{billinguser});
812 $page->param(custid => $webvar{custid});
813 $page->param(netaddr => $netblock->addr);
814 $page->param(masklen => $netblock->masklen);
815 }
816 mailNotify($ip_dbh, "a$webvar{alloctype}", "ADDED: $disp_alloctypes{$webvar{alloctype}} allocation",
817 "$disp_alloctypes{$webvar{alloctype}} $webvar{fullcidr} allocated to customer $webvar{custid}\n".
818 "Description: $webvar{desc}\n\nAllocated by: $authuser\n");
819 }
820 syslog "notice", "$authuser allocated '$webvar{fullcidr}' to '$webvar{custid}' as ".
821 "'$webvar{alloctype}' ($msg)";
822 } else {
823 syslog "err", "Allocation of '$webvar{fullcidr}' to '$webvar{custid}' as ".
824 "'$webvar{alloctype}' by $authuser failed: '$msg'";
825 $page->param(err => "Allocation of $webvar{fullcidr} as '$disp_alloctypes{$webvar{alloctype}}'".
826 " failed:<br>\n$msg\n");
827 }
828
829} # end insertAssign()
830
831
832# Does some basic checks on common input data to make sure nothing
833# *really* weird gets in to the database through this script.
834# Does NOT do complete input validation!!!
835sub validateInput {
836 if ($webvar{city} eq '-') {
837 printError("Please choose a city.");
838 return;
839 }
840
841 # Alloctype check.
842 chomp $webvar{alloctype};
843 if (!grep /$webvar{alloctype}/, keys %disp_alloctypes) {
844 # Danger! Danger! alloctype should ALWAYS be set by a dropdown. Anyone
845 # managing to call things in such a way as to cause this deserves a cryptic error.
846 printError("Invalid alloctype");
847 return;
848 }
849
850 # CustID check
851 # We have different handling for customer allocations and "internal" or "our" allocations
852 if ($def_custids{$webvar{alloctype}} eq '') {
853 if (!$webvar{custid}) {
854 printError("Please enter a customer ID.");
855 return;
856 }
857 if ($webvar{custid} !~ /^(?:\d{10}|\d{7}|STAFF)(?:-\d\d?)?$/) {
858 # Force uppercase for now...
859 $webvar{custid} =~ tr/a-z/A-Z/;
860 # Crosscheck with billing.
861 my $status = CustIDCK->custid_exist($webvar{custid});
862 if ($CustIDCK::Error) {
863 printError("Error verifying customer ID: ".$CustIDCK::ErrMsg);
864 return;
865 }
866 if (!$status) {
867 printError("Customer ID not valid. Make sure the Customer ID ".
868 "is correct.<br>\nUse STAFF for staff static IPs, and $IPDB::defcustid for any other ".
869 "non-customer assignments.");
870 return;
871 }
872 }
873# print "<!-- [ In validateInput(). Insert customer ID cross-check here. ] -->\n";
874 } else {
875 # New! Improved! And now Loaded From The Database!!
876 if ((!$webvar{custid}) || ($webvar{custid} ne 'STAFF')) {
877 $webvar{custid} = $def_custids{$webvar{alloctype}};
878 }
879 }
880
881 # Check POP location
882 my $flag;
883 if ($webvar{alloctype} eq 'rm') {
884 $flag = 'for a routed netblock';
885 foreach (@poplist) {
886 if (/^$webvar{city}$/) {
887 $flag = 'n';
888 last;
889 }
890 }
891 } else {
892 $flag = 'n';
893##fixme: hook to force-set POP or city on certain alloctypes
894# if ($webvar{alloctype =~ /foo,bar,bz/ { $webvar{pop} = 'blah'; }
895 if ($webvar{pop} =~ /^-$/) {
896 $flag = 'to route the block from/through';
897 }
898 }
899 if ($flag ne 'n') {
900 printError("Please choose a valid POP location $flag. Valid ".
901 "POP locations are currently:<br>\n".join (" - ", @poplist));
902 return;
903 }
904
905 return 'OK';
906} # end validateInput
907
908
909# Displays details of a specific allocation in a form
910# Allows update/delete
911# action=edit
912sub edit {
913
914 my $sql;
915
916 # Two cases: block is a netblock, or block is a static IP from a pool
917 # because I'm lazy, we'll try to make the SELECT's bring out identical)ish) data
918##fixme: allow "SWIP" (publication to rWHOIS) of static IP data
919 if ($webvar{block} =~ /\/32$/) {
920 $sql = "select ip,custid,type,city,circuitid,description,notes,modifystamp,privdata from poolips where ip='$webvar{block}'";
921 } else {
922 $sql = "select cidr,custid,type,city,circuitid,description,notes,modifystamp,privdata,swip from allocations where cidr='$webvar{block}'"
923 }
924
925 # gotta snag block info from db
926 $sth = $ip_dbh->prepare($sql);
927 $sth->execute;
928 my @data = $sth->fetchrow_array;
929
930 # Clean up extra whitespace on alloc type
931 $data[2] =~ s/\s//;
932
933 # We can't let the city be changed here; this block is a part of
934 # a larger routed allocation and therefore by definition can't be moved.
935 # block and city are static.
936##fixme
937# Needs thinking. Have to allow changes to city to correct errors, no?
938# Also have areas where a routed block at a POP serves "many" cities/towns/named crossroads
939
940# @data: cidr,custid,type,city,circuitid,description,notes,modifystamp,privdata,swip
941
942 $page->param(block => $webvar{block});
943
944 $page->param(custid => $data[1]);
945 $page->param(city => $data[3]);
946 $page->param(circid => $data[4]);
947 $page->param(desc => $data[5]);
948 $page->param(notes => $data[6]);
949
950##fixme The check here should be built from the database
951# Need to expand to support pool types too
952 if ($data[2] =~ /^.[ne]$/ && $IPDBacl{$authuser} =~ /c/) {
953 $page->param(changetype => 1);
954 $page->param(alloctype => [
955 { selme => ($data[2] eq 'me'), type => "me", disptype => "Dialup netblock" },
956 { selme => ($data[2] eq 'de'), type => "de", disptype => "Dynamic DSL netblock" },
957 { selme => ($data[2] eq 'ce'), type => "ce", disptype => "Dynamic cable netblock" },
958 { selme => ($data[2] eq 'we'), type => "we", disptype => "Dynamic wireless netblock" },
959 { selme => ($data[2] eq 'cn'), type => "cn", disptype => "Customer netblock" },
960 { selme => ($data[2] eq 'en'), type => "en", disptype => "End-use netblock" },
961 { selme => ($data[2] eq 'in'), type => "in", disptype => "Internal netblock" },
962 ]
963 );
964 } else {
965 $page->param(disptype => $disp_alloctypes{$data[2]});
966 $page->param(type => $data[2]);
967 }
968
969## node hack
970 $sth = $ip_dbh->prepare("SELECT nodes.node_id,node_name FROM nodes INNER JOIN noderef".
971 " ON nodes.node_id=noderef.node_id WHERE noderef.block='$webvar{block}'");
972 $sth->execute;
973 my ($nodeid,$nodename) = $sth->fetchrow_array();
974 $page->param(havenodeid => $nodeid);
975
976 if ($data[2] eq 'fr' || $data[2] eq 'bi') {
977 $page->param(typesupportsnodes => 1);
978 $page->param(nodename => $nodename);
979
980##fixme: this whole hack needs cleanup and generalization for all alloctypes
981##fixme: arguably a bug that presence of a nodeid implies it can be changed..
982# but except for manual database changes, only the two types fr and bi can
983# (currently) have a nodeid set in the first place.
984 if ($IPDBacl{$authuser} =~ /c/) {
985 $sth = $ip_dbh->prepare("SELECT node_id, node_name FROM nodes ORDER BY node_type,node_id");
986 $sth->execute;
987 my @nodelist;
988 while (my ($nid,$nname) = $sth->fetchrow_array()) {
989 my %row = (
990 selme => ($nodeid == $nid),
991 nodeid => $nid,
992 nodename => $nname,
993 );
994 push (@nodelist, \%row);
995 }
996 $page->param(nodelist => \@nodelist);
997 }
998 }
999## end node hack
1000
1001 my ($lastmod,undef) = split /\s+/, $data[7];
1002 $page->param(lastmod => $lastmod);
1003
1004 # not happy with the upside-down logic, but...
1005 $page->param(swipable => $data[2] !~ /.i/);
1006 $page->param(swip => $data[10] ne 'n');
1007
1008 # Check to see if we can display sensitive data
1009 $page->param(nocling => $IPDBacl{$authuser} =~ /s/);
1010 $page->param(privdata => $data[8]);
1011
1012 # ACL trickery - these two template booleans control the presence of all form/input tags
1013 $page->param(maychange => $IPDBacl{$authuser} =~ /c/);
1014 $page->param(maydel => $IPDBacl{$authuser} =~ /d/);
1015
1016} # edit()
1017
1018
1019# Stuff new info about a block into the db
1020# action=update
1021sub update {
1022 if ($IPDBacl{$authuser} !~ /c/) {
1023 printError("You shouldn't have been able to get here. Access denied.");
1024 return;
1025 }
1026
1027 # Check to see if we can update restricted data
1028 my $privdata = '';
1029 if ($IPDBacl{$authuser} =~ /s/) {
1030 $privdata = ",privdata='$webvar{privdata}'";
1031 }
1032
1033 # Make sure incoming data is in correct format - custID among other things.
1034 return if !validateInput;
1035
1036 # SQL transaction wrapper
1037 eval {
1038 # Relatively simple SQL transaction here.
1039 my $sql;
1040 if (my $pooltype = ($webvar{alloctype} =~ /^(.)i$/) ) {
1041 $sql = "UPDATE poolips SET custid='$webvar{custid}',".
1042 "city=?,description=?,notes=?,".
1043 "circuitid='$webvar{circid}',".
1044 "$privdata where ip='$webvar{block}'";
1045 } else {
1046 $sql = "UPDATE allocations SET custid='$webvar{custid}',".
1047 "city=?,description=?,notes=?,".
1048 "circuitid='$webvar{circid}'$privdata,".
1049 "type='$webvar{alloctype}',".
1050 "swip='".($webvar{swip} eq 'on' ? 'y' : 'n')."' ".
1051 "where cidr='$webvar{block}'";
1052 }
1053 # Log the details of the change.
1054 syslog "debug", $sql;
1055 $sth = $ip_dbh->prepare($sql);
1056 $sth->execute($webvar{city}, $webvar{desc}, $webvar{notes});
1057## node hack
1058 if ($webvar{node}) {
1059 # done with delete/insert so we don't have to worry about funkyness updating a node ref that isn't there
1060 $ip_dbh->do("DELETE FROM noderef WHERE block='$webvar{block}'");
1061 $sth = $ip_dbh->prepare("INSERT INTO noderef (block,node_id) VALUES (?,?)");
1062 $sth->execute($webvar{block},$webvar{node});
1063 }
1064## end node hack
1065 $ip_dbh->commit;
1066 };
1067 if ($@) {
1068 my $msg = $@;
1069 carp "Transaction aborted because $msg";
1070 eval { $ip_dbh->rollback; };
1071 syslog "err", "$authuser could not update block/IP '$webvar{block}': '$msg'";
1072 printError("Could not update block/IP $webvar{block}: $msg");
1073 return;
1074 }
1075
1076 # If we get here, the operation succeeded.
1077 syslog "notice", "$authuser updated $webvar{block}";
1078##fixme: need to wedge something in to allow "update:field" notifications
1079## hmm. how to tell what changed? O_o
1080mailNotify($ip_dbh, 's:swi', "SWIPed: $disp_alloctypes{$webvar{alloctype}} $webvar{block}",
1081 "$webvar{block} had SWIP status changed to \"Yes\" by $authuser") if $webvar{swip} eq 'on';
1082
1083## node hack
1084 if ($webvar{node} && $webvar{node} ne '-') {
1085 $sth = $ip_dbh->prepare("SELECT node_name FROM nodes WHERE node_id=?");
1086 $sth->execute($webvar{node});
1087 my ($nodename) = $sth->fetchrow_array();
1088 $page->param(nodename => $nodename);
1089 }
1090## end node hack
1091
1092 # Link back to browse-routed or list-pool page on "Update complete" page.
1093 my $cblock; # to contain the CIDR of the container block we're retrieving.
1094 my $sql;
1095 if (my $pooltype = ($webvar{alloctype} =~ /^(.)i$/) ) {
1096 $page->param(backpool => 1);
1097 $sql = "select pool from poolips where ip='$webvar{block}'";
1098 } else {
1099 $sql = "select cidr from routed where cidr >>= '$webvar{block}'";
1100 }
1101 # I define there to be no errors on this operation... so we don't need to check for them.
1102 $sth = $ip_dbh->prepare($sql);
1103 $sth->execute;
1104 $sth->bind_columns(\$cblock);
1105 $sth->fetch();
1106 $sth->finish;
1107 $page->param(backblock => $cblock);
1108
1109 $page->param(cidr => $webvar{block});
1110 $page->param(city => $webvar{city});
1111 $page->param(disptype => $disp_alloctypes{$webvar{alloctype}});
1112 $page->param(custid => $webvar{custid});
1113 $page->param(swip => $webvar{swip} eq 'on' ? 'Yes' : 'No');
1114 $page->param(circid => $q->escapeHTML($webvar{circid}));
1115 $page->param(desc => $q->escapeHTML($webvar{desc}));
1116 $page->param(notes => $q->escapeHTML($webvar{notes}));
1117 $webvar{privdata} = ($webvar{privdata} ? $q->escapeHTML($webvar{privdata}) : "&nbsp;");
1118 $page->param(privdata => $webvar{privdata})
1119 if $IPDBacl{$authuser} =~ /s/;
1120
1121} # update()
1122
1123
1124# Delete an allocation.
1125sub remove {
1126 if ($IPDBacl{$authuser} !~ /d/) {
1127 printError("You shouldn't have been able to get here. Access denied.");
1128 return;
1129 }
1130
1131 # Serves'em right for getting here...
1132 if (!defined($webvar{block})) {
1133 printError("Error 332");
1134 return;
1135 }
1136
1137 my ($cidr, $custid, $type, $city, $circid, $desc, $notes, $alloctype, $privdata);
1138
1139 if ($webvar{alloctype} eq 'rm') {
1140 $sth = $ip_dbh->prepare("select cidr,city from routed where cidr='$webvar{block}'");
1141 $sth->execute();
1142
1143# This feels... extreme.
1144 croak $sth->errstr() if($sth->errstr());
1145
1146 $sth->bind_columns(\$cidr,\$city);
1147 $sth->execute();
1148 $sth->fetch || croak $sth->errstr();
1149 $custid = "N/A";
1150 $alloctype = $webvar{alloctype};
1151 $circid = "N/A";
1152 $desc = "N/A";
1153 $notes = "N/A";
1154 $privdata = "N/A";
1155
1156 } elsif ($webvar{alloctype} eq 'mm') {
1157
1158 $cidr = $webvar{block};
1159 $city = "N/A";
1160 $custid = "N/A";
1161 $alloctype = $webvar{alloctype};
1162 $circid = "N/A";
1163 $desc = "N/A";
1164 $notes = "N/A";
1165 $privdata = "N/A";
1166
1167 } elsif ($webvar{alloctype} =~ /^.i$/) { # done with alloctype=[rm]m
1168
1169 # Unassigning a static IP
1170 my $sth = $ip_dbh->prepare("select ip,custid,city,type,notes,circuitid,privdata".
1171 " from poolips where ip='$webvar{block}'");
1172 $sth->execute();
1173# croak $sth->errstr() if($sth->errstr());
1174
1175 $sth->bind_columns(\$cidr, \$custid, \$city, \$alloctype, \$notes, \$circid,
1176 \$privdata);
1177 $sth->fetch() || croak $sth->errstr;
1178
1179 } else { # done with alloctype=~ /^.i$/
1180
1181 my $sth = $ip_dbh->prepare("select cidr,custid,type,city,circuitid,description,notes,privdata".
1182 " from allocations where cidr='$webvar{block}'");
1183 $sth->execute();
1184# croak $sth->errstr() if($sth->errstr());
1185
1186 $sth->bind_columns(\$cidr, \$custid, \$alloctype, \$city, \$circid, \$desc,
1187 \$notes, \$privdata);
1188 $sth->fetch() || carp $sth->errstr;
1189 } # end cases for different alloctypes
1190
1191 $page->param(block => $cidr);
1192 $page->param(disptype => $disp_alloctypes{$alloctype});
1193 $page->param(type => $alloctype);
1194 $page->param(city => $city);
1195 $page->param(custid => $custid);
1196 $page->param(circid => $circid);
1197 $page->param(desc => $desc);
1198 $page->param(notes => $notes);
1199 $privdata = '&nbsp;' if $privdata eq '';
1200 $page->param(privdata => $privdata) if $IPDBacl{$authuser} =~ /s/;
1201 $page->param(delpool => $alloctype =~ /^.[pd]$/);
1202
1203} # end remove()
1204
1205
1206# Delete an allocation. Return it to the freeblocks table; munge
1207# data as necessary to keep as few records as possible in freeblocks
1208# to prevent weirdness when allocating blocks later.
1209# Remove IPs from pool listing if necessary
1210sub finalDelete {
1211 if ($IPDBacl{$authuser} !~ /d/) {
1212 $page->param(aclerr => 1);
1213 return;
1214 }
1215
1216 # need to retrieve block data before deleting so we can notify on that
1217 my ($cidr,$custid,$type,$city,$description) = getBlockData($ip_dbh, $webvar{block});
1218
1219 my ($code,$msg) = deleteBlock($ip_dbh, $webvar{block}, $webvar{alloctype});
1220
1221 $page->param(block => $webvar{block});
1222 if ($code eq 'OK') {
1223 syslog "notice", "$authuser deallocated '$webvar{alloctype}'-type netblock $webvar{block}".
1224 " $custid, $city, desc='$description'";
1225 mailNotify($ip_dbh, 'da', "REMOVED: $disp_alloctypes{$webvar{alloctype}} $webvar{block}",
1226 "$disp_alloctypes{$webvar{alloctype}} $webvar{block} deallocated by $authuser\n".
1227 "CustID: $custid\nCity: $city\nDescription: $description\n");
1228 } else {
1229 $page->param(failmsg => $msg);
1230 if ($webvar{alloctype} =~ /^.i$/) {
1231 syslog "err", "$authuser could not deallocate static IP '$webvar{block}': '$msg'";
1232 } else {
1233 syslog "err", "$authuser could not deallocate netblock '$webvar{block}': '$msg'";
1234 $page->param(netblock => 1);
1235 }
1236 }
1237
1238} # finalDelete
Note: See TracBrowser for help on using the repository browser.