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

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

/trunk

Clean up and move SQL for showmaster to IPDB.pm. See #34.
Tweak template to use odd for row colors

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