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

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

/trunk

Move SQL for index/summary page into IPDB.pm. See #34.
Tweak initialization of page templates to set loop_context_vars so
we don't have to manually maintain the row0/row1 entries
Commentstub subs for master and routed list pages.

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