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

Last change on this file since 462 was 461, checked in by Kris Deugau, 14 years ago

/branches/htmlform

Checkpoint - confirm.html almost completely converted to template.
Still need to fix up allocfrom (see ##fixme at line 790 in main.cgi).
See #3.

  • Property svn:executable set to *
  • Property svn:keywords set to Date Rev Author
File size: 48.3 KB
RevLine 
[4]1#!/usr/bin/perl
2# ipdb/cgi-bin/main.cgi
[8]3###
4# SVN revision info
5# $Date: 2010-08-04 21:59:51 +0000 (Wed, 04 Aug 2010) $
6# SVN revision $Rev: 461 $
7# Last update by $Author: kdeugau $
8###
[417]9# Copyright (C) 2004-2010 - Kris Deugau
[4]10
11use strict;
12use warnings;
13use CGI::Carp qw(fatalsToBrowser);
[447]14use CGI::Simple;
[449]15use HTML::Template;
[4]16use DBI;
17use CommonWeb qw(:ALL);
[400]18use CustIDCK;
[4]19use POSIX qw(ceil);
20use NetAddr::IP;
21
22use Sys::Syslog;
23
[417]24# don't remove! required for GNU/FHS-ish install from tarball
25##uselib##
26
27use MyIPDB;
28
[431]29openlog "IPDB","pid","$IPDB::syslog_facility";
[4]30
[233]31# Collect the username from HTTP auth. If undefined, we're in
32# a test environment, or called without a username.
[4]33my $authuser;
34if (!defined($ENV{'REMOTE_USER'})) {
35 $authuser = '__temptest';
36} else {
37 $authuser = $ENV{'REMOTE_USER'};
38}
39
[402]40syslog "debug", "$authuser active, $ENV{'REMOTE_ADDR'}";
[4]41
[106]42# Why not a global DB handle? (And a global statement handle, as well...)
43# Use the connectDB function, otherwise we end up confusing ourselves
44my $ip_dbh;
45my $sth;
46my $errstr;
[142]47($ip_dbh,$errstr) = connectDB_My;
[106]48if (!$ip_dbh) {
[233]49 exitError("Database error: $errstr\n");
[106]50}
51initIPDBGlobals($ip_dbh);
[4]52
[449]53# Set up some globals
54##fixme - need to autofill this somehow
55$ENV{HTML_TEMPLATE_ROOT} = '/home/kdeugau/dev/ipdb/trunk/templates';
56
[451]57my $header = HTML::Template->new(filename => "header.tmpl");
58$header->param(version => $IPDB::VERSION);
59$header->param(addperm => $IPDBacl{$authuser} =~ /a/);
60print "Content-type: text/html\n\n", $header->output;
[233]61
[447]62# Set up the CGI object...
63my $q = new CGI::Simple;
64# ... and get query-string params as well as POST params if necessary
65$q->parse_query_string;
[4]66
[447]67# Convenience; saves changing all references to %webvar
68##fixme: tweak for handling <select multiple='y' size=3> (list with multiple selection)
69my %webvar = $q->Vars;
[4]70
[447]71
[4]72#main()
73
74if(!defined($webvar{action})) {
[450]75 $webvar{action} = "index"; #shuts up the warnings.
[4]76}
77
[450]78my $page = HTML::Template->new(filename => "$webvar{action}.tmpl");
79
[4]80if($webvar{action} eq 'index') {
81 showSummary();
[233]82} elsif ($webvar{action} eq 'addmaster') {
83 if ($IPDBacl{$authuser} !~ /a/) {
84 printError("You shouldn't have been able to get here. Access denied.");
85 } else {
86 open HTML, "<../addmaster.html";
87 print while <HTML>;
88 }
[4]89} elsif ($webvar{action} eq 'newmaster') {
90
[233]91 if ($IPDBacl{$authuser} !~ /a/) {
92 printError("You shouldn't have been able to get here. Access denied.");
93 } else {
[4]94
[233]95 my $cidr = new NetAddr::IP $webvar{cidr};
[4]96
[233]97 print "<div type=heading align=center>Adding $cidr as master block....</div>\n";
[4]98
[371]99 my ($code,$msg) = addMaster($ip_dbh, $webvar{cidr});
[4]100
[371]101 if ($code eq 'FAIL') {
[320]102 carp "Transaction aborted because $msg";
103 syslog "err", "Could not add master block '$webvar{cidr}' to database: '$msg'";
104 printError("Could not add master block $webvar{cidr} to database: $msg");
[233]105 } else {
106 print "<div type=heading align=center>Success!</div>\n";
107 syslog "info", "$authuser added master block $webvar{cidr}";
108 }
[4]109
[233]110 } # ACL check
111
[4]112} # end add new master
113
114elsif($webvar{action} eq 'showmaster') {
115 showMaster();
116}
117elsif($webvar{action} eq 'showrouted') {
118 showRBlock();
119}
120elsif($webvar{action} eq 'listpool') {
121 listPool();
122}
123
124# Not modified or added; just shuffled
125elsif($webvar{action} eq 'assign') {
126 assignBlock();
127}
128elsif($webvar{action} eq 'confirm') {
129 confirmAssign();
130}
131elsif($webvar{action} eq 'insert') {
132 insertAssign();
133}
134elsif($webvar{action} eq 'edit') {
135 edit();
136}
137elsif($webvar{action} eq 'update') {
138 update();
139}
140elsif($webvar{action} eq 'delete') {
141 remove();
142}
143elsif($webvar{action} eq 'finaldelete') {
144 finalDelete();
145}
[397]146elsif ($webvar{action} eq 'nodesearch') {
147 open HTML, "<../nodesearch.html";
148 my $html = join('',<HTML>);
149 close HTML;
[4]150
[397]151 $sth = $ip_dbh->prepare("SELECT node_id, node_name FROM nodes ORDER BY node_type,node_id");
152 $sth->execute() or print "DEBUG: failed retrieval from nodes: ".$sth->errstr,"<br>\n";
153 my $nodes = '';
154 while (my ($nid,$nname) = $sth->fetchrow_array()) {
155 $nodes .= "<option value='$nid'>$nname</option>\n";
156 }
157 $html =~ s/\$\$NODELIST\$\$/$nodes/;
158
159 print $html;
160}
161
[4]162# Default is an error. It shouldn't be possible to easily get here.
163# The only way I can think of offhand is to just call main.cgi bare-
164# which is not in any way guaranteed to provide anything useful.
165else {
166 my $rnd = rand 500;
167 my $boing = sprintf("%.2f", rand 500);
168 my @excuses = ("Aether cloudy. Ask again later.","The gods are unhappy with your sacrifice.",
169 "Because one of it's legs are both the same", "*wibble*",
170 "Hey! Stop pushing my buttons!", "I ain't done nuttin'", "9",
171 "8", "9", "10", "11", "12", "13", "14", "15", "16", "17");
172 printAndExit("Error $boing: ".$excuses[$rnd/30.0]);
173}
[111]174## Finally! Done with that NASTY "case" emulation!
[4]175
176
177
[106]178# Clean up IPDB globals, DB handle, etc.
[111]179finish($ip_dbh);
[199]180
[449]181#print qq(<div align=right style="position: absolute; right: 30px;">).
182# qq(<a href="/ip/cgi-bin/admin.cgi">Admin tools</a></div><br>\n)
183# if $IPDBacl{$authuser} =~ /A/;
[199]184
[450]185print $page->output;
186
[111]187# We print the footer here, so we don't have to do it elsewhere.
[449]188my $footer = HTML::Template->new(filename => "footer.tmpl");
189# include the admin tools link in the output?
190$footer->param(adminlink => ($IPDBacl{$authuser} =~ /A/));
191
192print $footer->output;
193
[106]194# Just in case something waaaayyy down isn't in place
195# properly... we exit explicitly.
196exit;
[4]197
198
[111]199
[4]200# args are: a reference to an array with the row to be printed and the
201# class(stylesheet) to use for formatting.
202# if ommitting the class - call the sub as &printRow(\@array)
203sub printRow {
204 my ($rowRef,$class) = @_;
205
206 if (!$class) {
207 print "<tr>\n";
208 } else {
209 print "<tr class=\"$class\">\n";
210 }
211
[135]212ELEMENT: foreach my $element (@$rowRef) {
213 if (!defined($element)) {
214 print "<td></td>\n";
215 next ELEMENT;
216 }
[4]217 $element =~ s|\n|</br>|g;
218 print "<td>$element</td>\n";
219 }
220 print "</tr>";
221} # printRow
222
223
224# Prints table headings. Accepts any number of arguments;
225# each argument is a table heading.
226sub startTable {
227 print qq(<center><table width="98%" cellspacing="0" class="center"><tr>);
228
229 foreach(@_) {
230 print qq(<td class="heading">$_</td>);
231 }
232 print "</tr>\n";
233} # startTable
234
235
236# Initial display: Show master blocks with total allocated subnets, total free subnets
[118]237sub showSummary {
[106]238 my %allocated;
239 my %free;
240 my %routed;
241 my %bigfree;
242
[118]243 # Count the allocations.
244 $sth = $ip_dbh->prepare("select count(*) from allocations where cidr <<= ?");
245 foreach my $master (@masterblocks) {
246 $sth->execute("$master");
247 $sth->bind_columns(\$allocated{"$master"});
248 $sth->fetch();
[4]249 }
250
[118]251 # Count routed blocks
252 $sth = $ip_dbh->prepare("select count(*) from routed where cidr <<= ?");
253 foreach my $master (@masterblocks) {
254 $sth->execute("$master");
255 $sth->bind_columns(\$routed{"$master"});
256 $sth->fetch();
[4]257 }
258
[118]259 # Count the free blocks.
[231]260 $sth = $ip_dbh->prepare("select count(*) from freeblocks where cidr <<= ? and ".
261 "(routed='y' or routed='n')");
[118]262 foreach my $master (@masterblocks) {
263 $sth->execute("$master");
264 $sth->bind_columns(\$free{"$master"});
265 $sth->fetch();
[4]266 }
267
[118]268 # Find the largest free block in each master
[231]269 $sth = $ip_dbh->prepare("select maskbits from freeblocks where cidr <<= ? and ".
270 "(routed='y' or routed='n') order by maskbits limit 1");
[118]271 foreach my $master (@masterblocks) {
272 $sth->execute("$master");
273 $sth->bind_columns(\$bigfree{"$master"});
274 $sth->fetch();
275 }
276
[450]277 # Assemble the data to stuff into the template.
278 my @masterlist;
279 my $rowclass=0;
[4]280 foreach my $master (@masterblocks) {
[450]281 my %row = (rowclass => "row$rowclass",
282 master => "$master",
283 routed => $routed{"$master"},
284 allocated => $allocated{"$master"},
285 free => $free{"$master"},
286 bigfree => ( ($bigfree{"$master"} eq '') ? ("&lt;NONE&gt;") : ("/".$bigfree{"$master"}) )
[4]287 );
[450]288 push (@masterlist, \%row);
289 $rowclass++; $rowclass = $rowclass % 2;
[4]290 }
[450]291 $page->param(masterlist => \@masterlist);
[4]292
[450]293 $page->param(addmaster => ($IPDBacl{$authuser} =~ /a/) );
294
[4]295} # showSummary
296
297
298# Display detail on master
299# Alrighty then! We're showing routed blocks within a single master this time.
300# We should be able to steal code from showSummary(), and if I'm really smart
301# I'll figger a way to munge the two together. (Once I've done that, everything
302# else should follow. YMMV.)
303sub showMaster {
304
305 print qq(<center><div class="heading">Summarizing routed blocks for ).
306 qq($webvar{block}:</div></center><br>\n);
307
[106]308 my %allocated;
309 my %free;
310 my %routed;
311 my %bigfree;
312
[4]313 my $master = new NetAddr::IP $webvar{block};
314 my @localmasters;
315
[118]316 # Fetch only the blocks relevant to this master
[157]317 $sth = $ip_dbh->prepare("select cidr,city from routed where cidr <<= '$master' order by cidr");
[4]318 $sth->execute();
319
320 my $i=0;
321 while (my @data = $sth->fetchrow_array()) {
322 my $cidr = new NetAddr::IP $data[0];
[118]323 $localmasters[$i++] = $cidr;
324 $free{"$cidr"} = 0;
325 $allocated{"$cidr"} = 0;
326 $bigfree{"$cidr"} = 128;
[4]327 # Retain the routing destination
[157]328 $routed{"$cidr"} = $data[1];
[4]329 }
330
[118]331 # Check if there were actually any blocks routed from this master
[4]332 if ($i > 0) {
333 startTable('Routed block','Routed to','Allocated blocks',
334 'Free blocks','Largest free block');
335
[118]336 # Count the allocations
337 $sth = $ip_dbh->prepare("select count(*) from allocations where cidr <<= ?");
338 foreach my $master (@localmasters) {
339 $sth->execute("$master");
340 $sth->bind_columns(\$allocated{"$master"});
341 $sth->fetch();
[4]342 }
343
[118]344 # Count the free blocks.
[231]345 $sth = $ip_dbh->prepare("select count(*) from freeblocks where cidr <<= ? and ".
346 "(routed='y' or routed='n')");
[118]347 foreach my $master (@localmasters) {
348 $sth->execute("$master");
349 $sth->bind_columns(\$free{"$master"});
350 $sth->fetch();
[4]351 }
352
[118]353 # Get the size of the largest free block
[231]354 $sth = $ip_dbh->prepare("select maskbits from freeblocks where cidr <<= ? and ".
355 "(routed='y' or routed='n') order by maskbits limit 1");
[118]356 foreach my $master (@localmasters) {
357 $sth->execute("$master");
358 $sth->bind_columns(\$bigfree{"$master"});
359 $sth->fetch();
[4]360 }
361
362 # Print the data.
363 my $count=0;
364 foreach my $master (@localmasters) {
365 my @row = ("<a href=\"/ip/cgi-bin/main.cgi?action=showrouted&block=$master\">$master</a>",
366 $routed{"$master"}, $allocated{"$master"},
367 $free{"$master"},
368 ( ($bigfree{"$master"} eq 128) ? ("&lt;NONE&gt;") : ("/".$bigfree{"$master"}) )
369 );
370 printRow(\@row, 'color1' ) if($count%2==0);
371 printRow(\@row, 'color2' ) if($count%2!=0);
372 $count++;
373 }
374 } else {
375 # If a master block has no routed blocks, then by definition it has no
376 # allocations, and can be deleted.
377 print qq(<hr width="60%"><center><div class="heading">No allocations in ).
378 qq($master.</div>\n).
[233]379 ($IPDBacl{$authuser} =~ /d/ ?
380 qq(<form action="/ip/cgi-bin/main.cgi" method=POST>\n).
381 qq(<input type=hidden name=action value="delete">\n).
382 qq(<input type=hidden name=block value="$master">\n).
383 qq(<input type=hidden name=alloctype value="mm">\n).
384 qq(<input type=submit value=" Remove this master ">\n).
385 qq(</form></center>\n) :
386 '');
[4]387
388 } # end check for existence of routed blocks in master
389
390 print qq(</table>\n<hr width="60%">\n).
391 qq(<center><div class="heading">Unrouted blocks in $master:</div></center><br>\n);
392
393 startTable('Netblock','Range');
394
395 # Snag the free blocks.
396 my $count = 0;
[118]397 $sth = $ip_dbh->prepare("select cidr from freeblocks where cidr <<='$master' and ".
398 "routed='n' order by cidr");
[4]399 $sth->execute();
400 while (my @data = $sth->fetchrow_array()) {
401 my $cidr = new NetAddr::IP $data[0];
[118]402 my @row = ("$cidr", $cidr->range);
403 printRow(\@row, 'color1' ) if($count%2==0);
404 printRow(\@row, 'color2' ) if($count%2!=0);
405 $count++;
[4]406 }
407
408 print "</table>\n";
409} # showMaster
410
411
412# Display details of a routed block
413# Alrighty then! We're showing allocations within a routed block this time.
414# We should be able to steal code from showSummary() and showMaster(), and if
415# I'm really smart I'll figger a way to munge all three together. (Once I've
416# done that, everything else should follow. YMMV.
417# This time, we check the database before spewing, because we may
418# not have anything useful to spew.
419sub showRBlock {
420
421 my $master = new NetAddr::IP $webvar{block};
422
[157]423 $sth = $ip_dbh->prepare("select city from routed where cidr='$master'");
[4]424 $sth->execute;
425 my @data = $sth->fetchrow_array;
426
427 print qq(<center><div class="heading">Summarizing allocated blocks for ).
[157]428 qq($master ($data[0]):</div></center><br>\n);
[4]429
[320]430 startTable('CIDR allocation','Customer Location','Type','CustID','SWIPed?','Description/Name');
[118]431
432 # Snag the allocations for this block
[320]433 $sth = $ip_dbh->prepare("select cidr,city,type,custid,swip,description".
[157]434 " from allocations where cidr <<= '$master' order by cidr");
[4]435 $sth->execute();
436
[380]437 # hack hack hack
438 # set up to flag swip=y records if they don't actually have supporting data in the customers table
439 my $custsth = $ip_dbh->prepare("select count(*) from customers where custid=?");
440
[4]441 my $count=0;
442 while (my @data = $sth->fetchrow_array()) {
[320]443 # cidr,city,type,custid,swip,description, as per the SELECT
[4]444 my $cidr = new NetAddr::IP $data[0];
445
446 # Clean up extra spaces that are borking things.
[157]447# $data[2] =~ s/\s+//g;
[4]448
[380]449 $custsth->execute($data[3]);
450 my ($ncust) = $custsth->fetchrow_array();
451
[187]452 # Prefix subblocks with "Sub "
453 my @row = ( (($data[2] =~ /^.r$/) ? 'Sub ' : '').
[186]454 qq(<a href="/ip/cgi-bin/main.cgi?action=edit&block=$data[0]">$data[0]</a>),
[320]455 $data[1], $disp_alloctypes{$data[2]}, $data[3],
[380]456 ($data[4] eq 'y' ? ($ncust == 0 ? 'Yes<small>*</small>' : 'Yes') : 'No'), $data[5]);
[4]457 # If the allocation is a pool, allow listing of the IPs in the pool.
[157]458 if ($data[2] =~ /^.[pd]$/) {
[4]459 $row[0] .= ' &nbsp; <a href="/ip/cgi-bin/main.cgi?action=listpool'.
460 "&pool=$data[0]\">List IPs</a>";
461 }
462
463 printRow(\@row, 'color1') if ($count%2 == 0);
464 printRow(\@row, 'color2') if ($count%2 != 0);
465 $count++;
466 }
467
468 print "</table>\n";
469
470 # If the routed block has no allocations, by definition it only has
471 # one free block, and therefore may be deleted.
472 if ($count == 0) {
473 print qq(<hr width="60%"><center><div class="heading">No allocations in ).
474 qq($master.</div></center>\n).
[233]475 ($IPDBacl{$authuser} =~ /d/ ?
476 qq(<form action="/ip/cgi-bin/main.cgi" method=POST>\n).
477 qq(<input type=hidden name=action value="delete">\n).
478 qq(<input type=hidden name=block value="$master">\n).
479 qq(<input type=hidden name=alloctype value="rm">\n).
480 qq(<input type=submit value=" Remove this block ">\n).
481 qq(</form>\n) :
482 '');
[4]483 }
484
485 print qq(<hr width="60%">\n<center><div class="heading">Free blocks within routed ).
486 qq(submaster $master</div></center>\n);
487
488 startTable('CIDR block','Range');
489
490 # Snag the free blocks. We don't really *need* to be pedantic about avoiding
491 # unrouted free blocks, but it's better to let the database do the work if we can.
492 $count = 0;
[186]493 $sth = $ip_dbh->prepare("select cidr,routed from freeblocks where cidr <<= '$master'".
494 " order by cidr");
[4]495 $sth->execute();
496 while (my @data = $sth->fetchrow_array()) {
[186]497 # cidr,routed
[4]498 my $cidr = new NetAddr::IP $data[0];
[187]499 # Include some HairyPerl(TM) to prefix subblocks with "Sub "
500 my @row = ((($data[1] ne 'y' && $data[1] ne 'n') ? 'Sub ' : '').
[233]501 ($IPDBacl{$authuser} =~ /a/ ? qq(<a href="/ip/cgi-bin/main.cgi?action=assign&block=$cidr&fbtype=$data[1]">$cidr</a>) : $cidr),
[21]502 $cidr->range);
[118]503 printRow(\@row, 'color1') if ($count%2 == 0);
504 printRow(\@row, 'color2') if ($count%2 != 0);
505 $count++;
[4]506 }
507
508 print "</table>\n";
509} # showRBlock
510
511
512# List the IPs used in a pool
513sub listPool {
514
515 my $cidr = new NetAddr::IP $webvar{pool};
516
[157]517 my ($pooltype,$poolcity);
518
[4]519 # Snag pool info for heading
[157]520 $sth = $ip_dbh->prepare("select type,city from allocations where cidr='$cidr'");
[4]521 $sth->execute;
[157]522 $sth->bind_columns(\$pooltype, \$poolcity);
523 $sth->fetch() || carp $sth->errstr;
[4]524
525 print qq(<center><div class="heading">Listing pool IPs for $cidr<br>\n).
[157]526 qq(($disp_alloctypes{$pooltype} in $poolcity)</div></center><br>\n);
527 # Only display net/gw/bcast if it's a "real" netblock and not a PPP(oE) lunacy
528 if ($pooltype =~ /^.d$/) {
529 print qq(<div class="indent"><b>Reserved IPs:</b><br>\n);
530 print qq(<div class="indent"><table><tr class=color1><td>Network IP:</td><td>).
[4]531 $cidr->addr."</td></tr>\n";
[157]532 $cidr++;
533 print "<tr class=color2><td>Gateway:</td><td>".$cidr->addr."</td></tr>\n";
534 $cidr--; $cidr--;
535 print "<tr class=color1><td>Broadcast:</td><td>".$cidr->addr."</td></tr>\n".
[4]536 "<tr><td>Netmask:</td><td>".$cidr->mask."</td></tr>\n".
537 "</table></div></div>\n";
[157]538 }
[4]539
540# probably have to add an "edit IP allocation" link here somewhere.
541
542 startTable('IP','Customer ID','Available?','Description','');
[157]543 $sth = $ip_dbh->prepare("select ip,custid,available,description,type".
544 " from poolips where pool='$webvar{pool}' order by ip");
[4]545 $sth->execute;
546 my $count = 0;
547 while (my @data = $sth->fetchrow_array) {
[74]548 # pool,ip,custid,city,ptype,available,notes,description,circuitid
[157]549 # ip,custid,available,description,type
550 # If desc is "null", make it not null. <g>
551 if ($data[3] eq '') {
552 $data[3] = '&nbsp;';
[4]553 }
554 # Some nice hairy Perl to decide whether to allow unassigning each IP
[157]555 # -> if $data[2] (aka poolips.available) == 'n' then we print the unassign link
[4]556 # else we print a blank space
[157]557 my @row = ( qq(<a href="/ip/cgi-bin/main.cgi?action=edit&block=$data[0]">$data[0]</a>),
558 $data[1],$data[2],$data[3],
[233]559 ( (($data[2] eq 'n') && ($IPDBacl{$authuser} =~ /d/)) ?
[157]560 ("<a href=\"/ip/cgi-bin/main.cgi?action=delete&block=$data[0]&".
561 "alloctype=$data[4]\">Unassign this IP</a>") :
[4]562 ("&nbsp;") )
563 );
564 printRow(\@row, 'color1') if($count%2==0);
565 printRow(\@row, 'color2') if($count%2!=0);
566 $count++;
567 }
568 print "</table>\n";
569
570} # end listPool
571
572
[106]573# Show "Add new allocation" page. Note that the actual page may
574# be one of two templates, and the lists come from the database.
[4]575sub assignBlock {
576
[233]577 if ($IPDBacl{$authuser} !~ /a/) {
578 printError("You shouldn't have been able to get here. Access denied.");
579 return;
580 }
581
[456]582 # hack pthbttt eww
583 $webvar{block} = '' if !$webvar{block};
[21]584
[456]585# hmm. TMPL_IF block and TMPL_ELSE block on these instead?
586 $page->param(rowa => 'row'.($webvar{block} eq '' ? 1 : 0));
587 $page->param(rowb => 'row'.($webvar{block} eq '' ? 0 : 1));
588 $page->param(block => $webvar{block}); # fb-assign flag, if block is set, we're in fb-assign
589 $page->param(iscontained => ($webvar{fbtype} && $webvar{fbtype} ne 'y'));
590
[21]591 # New special case- block to assign is specified
592 if ($webvar{block} ne '') {
593 my $block = new NetAddr::IP $webvar{block};
[187]594
[456]595 # Handle contained freeblock allocation.
[187]596 # This is a little dangerous, as it's *theoretically* possible to
597 # get fbtype='n' (aka a non-routed freeblock). However, should
598 # someone manage to get there, they get what they deserve.
599 if ($webvar{fbtype} ne 'y') {
[456]600 # Snag the type of the container block from the database.
[187]601 $sth = $ip_dbh->prepare("select type from allocations where cidr >>='$block'");
602 $sth->execute;
603 my @data = $sth->fetchrow_array;
604 $data[0] =~ s/c$/r/; # Munge the type into the correct form
[456]605 $page->param(fbdisptype => $list_alloctypes{$data[0]});
606 $page->param(type => $data[0]);
[187]607 } else {
608 $sth = $ip_dbh->prepare("select type,listname from alloctypes where listorder < 500 ".
[191]609 "and type not like '_i' and type not like '_r' order by listorder");
[187]610 $sth->execute;
611 my @data = $sth->fetchrow_array;
[456]612 my @typelist;
613 my $selflag = 0;
[187]614 while (my @data = $sth->fetchrow_array) {
[456]615 my %row = (tval => $data[0],
616 type => $data[1],
617 sel => ($selflag == 0 ? ' selected' : '')
618 );
619 push (@typelist, \%row);
620 $selflag++;
[187]621 }
[456]622 $page->param(typelist => \@typelist);
[106]623 }
[21]624 } else {
[456]625 my @masterlist;
[31]626 foreach my $master (@masterblocks) {
[456]627 my %row = (master => "$master");
628 push (@masterlist, \%row);
[31]629 }
[456]630 $page->param(masterlist => \@masterlist);
631
632 my @pops;
[92]633 foreach my $pop (@poplist) {
[456]634 my %row = (pop => $pop);
635 push (@pops, \%row);
[92]636 }
[456]637 $page->param(pops => \@pops);
638
639 # could arguably include routing (500) in the list, but ATM it doesn't
640 # make sense, and in any case that shouldn't be structurally possible here.
641 $sth = $ip_dbh->prepare("select type,listname from alloctypes where listorder < 500 order by listorder");
[106]642 $sth->execute;
[456]643 my @typelist;
644 my $selflag = 0;
[106]645 while (my @data = $sth->fetchrow_array) {
[456]646 my %row = (tval => $data[0],
647 type => $data[1],
648 sel => ($selflag == 0 ? ' selected' : '')
649 );
650 push (@typelist, \%row);
651 $selflag++;
[106]652 }
[456]653 $page->param(typelist => \@typelist);
[21]654 }
[456]655
656 my @cities;
[92]657 foreach my $city (@citylist) {
[456]658 my %row = (city => $city);
659 push (@cities, \%row);
[92]660 }
[456]661 $page->param(citylist => \@cities);
[4]662
[397]663## node hack
664 $sth = $ip_dbh->prepare("SELECT node_id, node_name FROM nodes ORDER BY node_type,node_id");
665 $sth->execute() or print "DEBUG: failed retrieval from nodes: ".$sth->errstr,"<br>\n";
[456]666 my @nodes;
[397]667 while (my ($nid,$nname) = $sth->fetchrow_array()) {
[456]668 my %row = (nid => $nid, nname => $nname);
669 push (@nodes, \%row);
[397]670 }
[456]671 $page->param(nodelist => \@nodes);
[397]672## end node hack
673
[456]674 $page->param(privdata => $IPDBacl{$authuser} =~ /s/);
[284]675
[4]676} # assignBlock
677
678
679# Take info on requested IP assignment and see what we can provide.
680sub confirmAssign {
[233]681 if ($IPDBacl{$authuser} !~ /a/) {
682 printError("You shouldn't have been able to get here. Access denied.");
683 return;
684 }
[4]685
686 my $cidr;
687 my $alloc_from;
688
689 # Going to manually validate some items.
690 # custid and city are automagic.
[111]691 return if !validateInput();
[4]692
693# Several different cases here.
694# Static IP vs netblock
695# + Different flavours of static IP
696# + Different flavours of netblock
697
[157]698 if ($webvar{alloctype} =~ /^.i$/) {
[4]699 my ($base,undef) = split //, $webvar{alloctype}; # split into individual chars
700
[214]701# Ewww. But it works.
702 $sth = $ip_dbh->prepare("SELECT (SELECT city FROM allocations WHERE cidr=poolips.pool), ".
703 "poolips.pool, COUNT(*) FROM poolips,allocations WHERE poolips.available='y' AND ".
[442]704 "poolips.pool=allocations.cidr AND allocations.city='$webvar{pop}' AND poolips.type LIKE '".$base."_' ".
[214]705 "GROUP BY pool");
[4]706 $sth->execute;
707 my $optionlist;
708 while (my @data = $sth->fetchrow_array) {
[214]709 # city,pool cidr,free IP count
710 if ($data[2] > 0) {
711 $optionlist .= "<option value='$data[1]'>$data[1] [$data[2] free IP(s)] in $data[0]</option>\n";
712 }
[4]713 }
714 $cidr = "Single static IP";
715 $alloc_from = "<select name=alloc_from>".$optionlist."</select>\n";
716
717 } else { # end show pool options
[21]718
719 if ($webvar{fbassign} eq 'y') {
720 $cidr = new NetAddr::IP $webvar{block};
721 $webvar{maskbits} = $cidr->masklen;
722 } else { # done with direct freeblocks assignment
723
724 if (!$webvar{maskbits}) {
[111]725 printError("Please specify a CIDR mask length.");
726 return;
[21]727 }
728 my $sql;
729 my $city;
730 my $failmsg;
[320]731 my $extracond = '';
732 if ($webvar{allocfrom} eq '-') {
733 $extracond = ($webvar{allowpriv} eq 'on' ? '' :
734 " and not (cidr <<= '192.168.0.0/16'".
735 " or cidr <<= '10.0.0.0/8'".
736 " or cidr <<= '172.16.0.0/12')");
737 }
738 my $sortorder;
[187]739 if ($webvar{alloctype} eq 'rm') {
[31]740 if ($webvar{allocfrom} ne '-') {
741 $sql = "select * from freeblocks where maskbits<=$webvar{maskbits} and routed='n'".
[320]742 " and cidr <<= '$webvar{allocfrom}'";
743 $sortorder = "maskbits desc";
[31]744 } else {
[320]745 $sql = "select * from freeblocks where maskbits<=$webvar{maskbits} and routed='n'";
746 $sortorder = "maskbits desc";
[31]747 }
[21]748 $failmsg = "No suitable free block found.<br>\nWe do not have a free".
749 " routeable block of that size.<br>\nYou will have to either route".
750 " a set of smaller netblocks or a single smaller netblock.";
[4]751 } else {
[118]752##fixme
753# This section needs serious Pondering.
[214]754 # Pools of most types get assigned to the POP they're "routed from"
[187]755 # This includes WAN blocks and other netblock "containers"
[214]756 # This does NOT include cable pools.
757 if ($webvar{alloctype} =~ /^.[pc]$/) {
[37]758 $city = $webvar{city};
[21]759 $failmsg = "No suitable free block found.<br>\nYou will have to route another".
[442]760 " superblock from one of the<br>\nmaster blocks or chose a smaller".
[21]761 " block size for the pool.";
762 } else {
763 $city = $webvar{pop};
764 $failmsg = "No suitable free block found.<br>\nYou will have to route another".
[442]765 " superblock to $webvar{pop}<br>\nfrom one of the master blocks or".
[21]766 " chose a smaller blocksize.";
767 }
[300]768 if (defined $webvar{allocfrom} && $webvar{allocfrom} ne '-') {
[157]769 $sql = "select cidr from freeblocks where city='$city' and maskbits<=$webvar{maskbits}".
[186]770 " and cidr <<= '$webvar{allocfrom}' and routed='".
[320]771 (($webvar{alloctype} =~ /^(.)r$/) ? "$1" : 'y')."'";
772 $sortorder = "maskbits desc,cidr";
[31]773 } else {
[157]774 $sql = "select cidr from freeblocks where city='$city' and maskbits<=$webvar{maskbits}".
[320]775 " and routed='".(($webvar{alloctype} =~ /^(.)r$/) ? "$1" : 'y')."'";
776 $sortorder = "maskbits desc,cidr";
[31]777 }
[4]778 }
[320]779 $sql = $sql.$extracond." order by ".$sortorder;
[21]780 $sth = $ip_dbh->prepare($sql);
781 $sth->execute;
782 my @data = $sth->fetchrow_array();
783 if ($data[0] eq "") {
[111]784 printError($failmsg);
785 return;
[21]786 }
787 $cidr = new NetAddr::IP $data[0];
788 } # check for freeblocks assignment or IPDB-controlled assignment
[4]789
[461]790##fixme: HTML must be removed from script!
[4]791 $alloc_from = qq($cidr<input type=hidden name=alloc_from value="$cidr">);
792
793 # If the block to be allocated is smaller than the one we found,
794 # figure out the "real" block to be allocated.
795 if ($cidr->masklen() ne $webvar{maskbits}) {
796 my $maskbits = $cidr->masklen();
797 my @subblocks;
798 while ($maskbits++ < $webvar{maskbits}) {
799 @subblocks = $cidr->split($maskbits);
800 }
801 $cidr = $subblocks[0];
802 }
[157]803 } # if ($webvar{alloctype} =~ /^.i$/)
[4]804
[397]805## node hack
806 if ($webvar{node} && $webvar{node} ne '-') {
807 $sth = $ip_dbh->prepare("SELECT node_name FROM nodes WHERE node_id=?");
808 $sth->execute($webvar{node});
809 my ($nodename) = $sth->fetchrow_array();
[461]810 $page->param(nodename => $nodename);
811 $page->param(nodeid => $webvar{node});
[397]812 }
813## end node hack
814
[4]815 # Stick in the allocation data
[461]816 $page->param(alloc_type => $webvar{alloctype});
817 $page->param(typefull => $q->escapeHTML($disp_alloctypes{$webvar{alloctype}}));
818 $page->param(alloc_from => $alloc_from);
819 $page->param(cidr => $cidr);
820 $page->param(city => $q->escapeHTML($webvar{city}));
821 $page->param(custid => $webvar{custid});
822 $page->param(circid => $q->escapeHTML($webvar{circid}));
823 $page->param(desc => $q->escapeHTML($webvar{desc}));
[4]824
[461]825##fixme: find a way to have the displayed copy have <br> substitutions
826# for newlines, and the <input> value have either encoded or bare newlines.
827# Also applies to privdata.
828 $page->param(notes => $q->escapeHTML($webvar{notes},'y'));
829
[284]830 # Check to see if user is allowed to do anything with sensitive data
831 my $privdata = '';
[461]832 $page->param(privdata => $q->escapeHTML($webvar{privdata},'y'))
833 if $IPDBacl{$authuser} =~ /s/;
834
835 # Yay! This now has it's very own little home.
836 $page->param(billinguser => $webvar{userid})
[299]837 if $webvar{userid};
[284]838
[461]839##fixme: this is only needed iff confirm.tmpl/confirm.html and
840# confirmRemove.html/confirmRemove.tmpl are merged (quite possible, just
841# a little tedious)
842 $page->param(action => "insert");
[284]843
[4]844} # end confirmAssign
845
846
847# Do the work of actually inserting a block in the database.
848sub insertAssign {
[233]849 if ($IPDBacl{$authuser} !~ /a/) {
850 printError("You shouldn't have been able to get here. Access denied.");
851 return;
852 }
[4]853 # Some things are done more than once.
[111]854 return if !validateInput();
[4]855
[284]856 if (!defined($webvar{privdata})) {
857 $webvar{privdata} = '';
858 }
[106]859 # $code is "success" vs "failure", $msg contains OK for a
860 # successful netblock allocation, the IP allocated for static
861 # IP, or the error message if an error occurred.
862 my ($code,$msg) = allocateBlock($ip_dbh, $webvar{fullcidr}, $webvar{alloc_from},
863 $webvar{custid}, $webvar{alloctype}, $webvar{city}, $webvar{desc}, $webvar{notes},
[397]864 $webvar{circid}, $webvar{privdata}, $webvar{node});
[4]865
[111]866 if ($code eq 'OK') {
[106]867 if ($webvar{alloctype} =~ /^.i$/) {
[300]868 $msg =~ s|/32||;
[297]869 print qq(<div class="center"><div class="heading">The IP $msg has been allocated to customer $webvar{custid}</div>).
[312]870 ( ($webvar{alloctype} eq 'di' && $webvar{billinguser}) ?
[380]871 qq(<div><a href="https://billing.example.com/radius.pl?).
[314]872 "action=new_radius_user&custid=$webvar{custid}&userid=$webvar{billinguser}".
[302]873 qq(&ipdb=1&ip=$msg">Add this IP to RADIUS user table</a></div>)
[297]874 : "</div>");
[416]875 mailNotify($ip_dbh, "a$webvar{alloctype}", "ADDED: $disp_alloctypes{$webvar{alloctype}} allocation",
876 "$disp_alloctypes{$webvar{alloctype}} $msg allocated to customer $webvar{custid}\n".
877 "Description: $webvar{desc}\n\nAllocated by: $authuser\n");
[106]878 } else {
[301]879 my $netblock = new NetAddr::IP $webvar{fullcidr};
[106]880 print qq(<div class="center"><div class="heading">The block $webvar{fullcidr} was ).
[301]881 "sucessfully added as: $disp_alloctypes{$webvar{alloctype}}</div>".
[313]882 ( ($webvar{alloctype} eq 'pr' && $webvar{billinguser}) ?
[380]883 qq(<div><a href="https://billing.example.com/radius.pl?).
[314]884 "action=new_radius_user&custid=$webvar{custid}&userid=$webvar{billinguser}".
[301]885 "&route_subnet=".$netblock->addr."&subnet_slash=".$netblock->masklen.
[302]886 "&include_routed_subnet=1&ipdb=1".
[301]887 qq(">Add this netblock to RADIUS user table</a></div>)
888 : "</div>");
[416]889 mailNotify($ip_dbh, "a$webvar{alloctype}", "ADDED: $disp_alloctypes{$webvar{alloctype}} allocation",
890 "$disp_alloctypes{$webvar{alloctype}} $webvar{fullcidr} allocated to customer $webvar{custid}\n".
891 "Description: $webvar{desc}\n\nAllocated by: $authuser\n");
[4]892 }
[106]893 syslog "notice", "$authuser allocated '$webvar{fullcidr}' to '$webvar{custid}' as ".
[256]894 "'$webvar{alloctype}' ($msg)";
[111]895 } else {
896 syslog "err", "Allocation of '$webvar{fullcidr}' to '$webvar{custid}' as ".
897 "'$webvar{alloctype}' by $authuser failed: '$msg'";
[189]898 printError("Allocation of $webvar{fullcidr} as '$disp_alloctypes{$webvar{alloctype}}'".
[157]899 " failed:<br>\n$msg\n");
[106]900 }
[4]901
902} # end insertAssign()
903
904
905# Does some basic checks on common input data to make sure nothing
906# *really* weird gets in to the database through this script.
907# Does NOT do complete input validation!!!
908sub validateInput {
909 if ($webvar{city} eq '-') {
[111]910 printError("Please choose a city.");
911 return;
[4]912 }
[138]913
914 # Alloctype check.
[4]915 chomp $webvar{alloctype};
[138]916 if (!grep /$webvar{alloctype}/, keys %disp_alloctypes) {
917 # Danger! Danger! alloctype should ALWAYS be set by a dropdown. Anyone
918 # managing to call things in such a way as to cause this deserves a cryptic error.
919 printError("Invalid alloctype");
920 return;
921 }
922
923 # CustID check
[4]924 # We have different handling for customer allocations and "internal" or "our" allocations
[214]925 if ($def_custids{$webvar{alloctype}} eq '') {
[4]926 if (!$webvar{custid}) {
[111]927 printError("Please enter a customer ID.");
928 return;
[4]929 }
[400]930 if ($webvar{custid} !~ /^(?:\d{10}|\d{7}|STAFF)(?:-\d\d?)?$/) {
931 # Force uppercase for now...
932 $webvar{custid} =~ tr/a-z/A-Z/;
933 # Crosscheck with billing.
934 my $status = CustIDCK->custid_exist($webvar{custid});
935 if ($CustIDCK::Error) {
936 printError("Error verifying customer ID: ".$CustIDCK::ErrMsg);
937 return;
938 }
939 if (!$status) {
940 printError("Customer ID not valid. Make sure the Customer ID ".
[420]941 "is correct.<br>\nUse STAFF for staff static IPs, and $IPDB::defcustid for any other ".
[400]942 "non-customer assignments.");
943 return;
944 }
[4]945 }
[400]946# print "<!-- [ In validateInput(). Insert customer ID cross-check here. ] -->\n";
[138]947 } else {
[167]948 # New! Improved! And now Loaded From The Database!!
[320]949 if ((!$webvar{custid}) || ($webvar{custid} ne 'STAFF')) {
950 $webvar{custid} = $def_custids{$webvar{alloctype}};
951 }
[4]952 }
[111]953
954 # Check POP location
955 my $flag;
[187]956 if ($webvar{alloctype} eq 'rm') {
[111]957 $flag = 'for a routed netblock';
958 foreach (@poplist) {
959 if (/^$webvar{city}$/) {
960 $flag = 'n';
961 last;
962 }
963 }
964 } else {
965 $flag = 'n';
[442]966##fixme: hook to force-set POP or city on certain alloctypes
967# if ($webvar{alloctype =~ /foo,bar,bz/ { $webvar{pop} = 'blah'; }
[400]968 if ($webvar{pop} =~ /^-$/) {
[111]969 $flag = 'to route the block from/through';
970 }
971 }
972 if ($flag ne 'n') {
973 printError("Please choose a valid POP location $flag. Valid ".
974 "POP locations are currently:<br>\n".join (" - ", @poplist));
975 return;
976 }
977
978 return 'OK';
[4]979} # end validateInput
980
981
982# Displays details of a specific allocation in a form
983# Allows update/delete
984# action=edit
985sub edit {
986
987 my $sql;
988
989 # Two cases: block is a netblock, or block is a static IP from a pool
990 # because I'm lazy, we'll try to make the SELECT's bring out identical)ish) data
991 if ($webvar{block} =~ /\/32$/) {
[320]992 $sql = "select ip,custid,type,city,circuitid,description,notes,modifystamp,privdata,oldcustid from poolips where ip='$webvar{block}'";
[4]993 } else {
[320]994 $sql = "select cidr,custid,type,city,circuitid,description,notes,modifystamp,privdata,oldcustid,swip from allocations where cidr='$webvar{block}'"
[4]995 }
996
997 # gotta snag block info from db
998 $sth = $ip_dbh->prepare($sql);
999 $sth->execute;
1000 my @data = $sth->fetchrow_array;
1001
1002 # Clean up extra whitespace on alloc type
1003 $data[2] =~ s/\s//;
1004
1005 open (HTML, "../editDisplay.html")
1006 or croak "Could not open editDisplay.html :$!";
1007 my $html = join('', <HTML>);
1008
1009 # We can't let the city be changed here; this block is a part of
1010 # a larger routed allocation and therefore by definition can't be moved.
1011 # block and city are static.
1012##fixme
1013# Needs thinking. Have to allow changes to city to correct errors, no?
1014 $html =~ s/\$\$BLOCK\$\$/$webvar{block}/g;
1015
[233]1016 if ($IPDBacl{$authuser} =~ /c/) {
1017 $html =~ s/\$\$CUSTID\$\$/<input type=text name=custid value="$data[1]" maxlength=15 class="regular">/;
1018
[4]1019# Screw it. Changing allocation types gets very ugly VERY quickly- especially
1020# with the much longer list of allocation types.
1021# We'll just show what type of block it is.
1022
[33]1023# this has now been Requested, so here goes.
[4]1024
[187]1025##fixme The check here should be built from the database
[233]1026 if ($data[2] =~ /^.[ne]$/) {
1027 # Block that can be changed
1028 my $blockoptions = "<select name=alloctype><option".
[187]1029 (($data[2] eq 'me') ? ' selected' : '') ." value='me'>Dialup netblock</option>\n<option".
[228]1030 (($data[2] eq 'de') ? ' selected' : '') ." value='de'>Dynamic DSL netblock</option>\n<option".
1031 (($data[2] eq 'ce') ? ' selected' : '') ." value='ce'>Dynamic cable netblock</option>\n<option".
1032 (($data[2] eq 'we') ? ' selected' : '') ." value='we'>Dynamic wireless netblock</option>\n<option".
[33]1033 (($data[2] eq 'cn') ? ' selected' : '') ." value='cn'>Customer netblock</option>\n<option".
[187]1034 (($data[2] eq 'en') ? ' selected' : '') ." value='en'>End-use netblock</option>\n<option".
[135]1035 (($data[2] eq 'in') ? ' selected' : '') ." value='in'>Internal netblock</option>\n".
[33]1036 "</select>\n";
[233]1037 $html =~ s/\$\$TYPESELECT\$\$/$blockoptions/g;
1038 } else {
1039 $html =~ s/\$\$TYPESELECT\$\$/$disp_alloctypes{$data[2]}<input type=hidden name=alloctype value="$data[2]">/g;
1040 }
[397]1041## node hack
1042 $sth = $ip_dbh->prepare("SELECT node_id FROM noderef WHERE block='$webvar{block}'");
1043 $sth->execute;
1044 my ($nodeid) = $sth->fetchrow_array();
1045 if ($nodeid) {
1046 $sth = $ip_dbh->prepare("SELECT node_id, node_name FROM nodes ORDER BY node_type,node_id");
1047 $sth->execute() or print "DEBUG: failed retrieval from nodes: ".$sth->errstr,"<br>\n";
1048 my $nodes = "<select name=node>\n";
1049 while (my ($nid,$nname) = $sth->fetchrow_array()) {
1050 $nodes .= "<option".($nodeid == $nid ? ' selected' : '')." value='$nid'>$nname</option>\n";
1051 }
1052 $nodes .= "</select>\n";
1053 $html =~ s/\$\$NODE\$\$/$nodes/;
1054 } else {
1055 if ($data[2] eq 'fr' || $data[2] eq 'bi') {
1056 $sth = $ip_dbh->prepare("SELECT node_id, node_name FROM nodes ORDER BY node_type,node_id");
1057 $sth->execute() or print "DEBUG: failed retrieval from nodes: ".$sth->errstr,"<br>\n";
1058 my $nodes = "<select name=node>\n<option value=>--</option>\n";
1059 while (my ($nid,$nname) = $sth->fetchrow_array()) {
1060 $nodes .= "<option value='$nid'>$nname</option>\n";
1061 }
1062 $nodes .= "</select>\n";
1063 $html =~ s/\$\$NODE\$\$/$nodes/;
1064 } else {
1065 $html =~ s|\$\$NODE\$\$|N/A|;
1066 }
1067 }
1068## end node hack
[320]1069 $html =~ s/\$\$OLDCUSTID\$\$/$data[9]/g;
[233]1070 $html =~ s/\$\$CITY\$\$/<input type=text name=city value="$data[3]">/g;
1071 $html =~ s/\$\$CIRCID\$\$/<input type="text" name="circid" value="$data[4]" maxlength=64 size=64 class="regular">/g;
1072 $html =~ s/\$\$DESC\$\$/<input type="text" name="desc" value="$data[5]" maxlength=64 size=64 class="regular">/g;
1073 $html =~ s|\$\$NOTES\$\$|<textarea rows="8" cols="64" name="notes" class="regular">$data[6]</textarea>|g;
[33]1074 } else {
[397]1075## node hack
1076 if ($data[2] eq 'fr' || $data[2] eq 'bi') {
1077 $sth = $ip_dbh->prepare("SELECT node_name FROM nodes INNER JOIN noderef".
1078 " ON nodes.node_id=noderef.node_id WHERE noderef.block='$webvar{block}'");
1079 $sth->execute() or print "DEBUG: failed retrieval from nodes: ".$sth->errstr,"<br>\n";
1080 my ($node) = $sth->fetchrow_array;
1081 $html =~ s/\$\$NODE\$\$/$node/;
1082 } else {
1083 $html =~ s|\$\$NODE\$\$|N/A|;
1084 }
1085## end node hack
[233]1086 $html =~ s/\$\$CUSTID\$\$/$data[1]/g;
[320]1087 $html =~ s/\$\$OLDCUSTID\$\$/$data[9]/g;
[233]1088 $html =~ s/\$\$TYPESELECT\$\$/$disp_alloctypes{$data[2]}/g;
1089 $html =~ s/\$\$CITY\$\$/$data[3]/g;
1090 $html =~ s/\$\$CIRCID\$\$/$data[4]/g;
1091 $html =~ s/\$\$DESC\$\$/$data[5]/g;
1092 $html =~ s/\$\$NOTES\$\$/$data[6]/g;
[33]1093 }
[255]1094 my ($lastmod,undef) = split /\s+/, $data[7];
1095 $html =~ s/\$\$LASTMOD\$\$/$lastmod/g;
[33]1096
[320]1097## Hack time! SWIP isn't going to stay, so I'm not going to integrate it with ACLs.
1098if ($data[2] =~ /.i/) {
1099 $html =~ s/\$\$SWIP\$\$/N\/A/;
[406]1100} else {
[320]1101 my $tmp = (($data[10] eq 'n') ? '<input type=checkbox name=swip>' :
1102 '<input type=checkbox name=swip checked=yes>');
1103 $html =~ s/\$\$SWIP\$\$/$tmp/;
1104}
1105
[255]1106 # Allows us to "correctly" colour backgrounds in table
1107 my $i=1;
1108
[284]1109 # Check to see if we can display sensitive data
1110 my $privdata = '';
1111 if ($IPDBacl{$authuser} =~ /s/) {
1112 $privdata = qq(<tr class="color).($i%2).qq("><td class=heading>Restricted data:</td>).
1113 qq(<td class=regular><textarea rows="3" cols="64" name="privdata" class="regular">).
1114 qq($data[8]</textarea></td></tr>\n);
1115 $i++;
1116 }
1117 $html =~ s/\$\$PRIVDATA\$\$/$privdata/g;
1118
[233]1119 # More ACL trickery - we can live with forms that don't submit,
1120 # but we can't leave the extra table rows there, and we *really*
1121 # can't leave the submit buttons there.
1122 my $updok = '';
1123 if ($IPDBacl{$authuser} =~ /c/) {
[284]1124 $updok = qq(<tr class="color).($i%2).qq("><td colspan=2><div class="center">).
[233]1125 qq(<input type="submit" value=" Update this block " class="regular">).
1126 "</div></td></tr></form>\n";
[255]1127 $i++;
[233]1128 }
1129 $html =~ s/\$\$UPDOK\$\$/$updok/g;
[4]1130
[233]1131 my $delok = '';
1132 if ($IPDBacl{$authuser} =~ /d/) {
1133 $delok = qq(<form method="POST" action="main.cgi">
[284]1134 <tr class="color).($i%2).qq("><td colspan=2 class="regular"><div class=center>
[233]1135 <input type="hidden" name="action" value="delete">
1136 <input type="hidden" name="block" value="$webvar{block}">
1137 <input type="hidden" name="alloctype" value="$data[2]">
1138 <input type=submit value=" Delete this block ">
1139 </div></td></tr>);
1140 }
1141 $html =~ s/\$\$DELOK\$\$/$delok/;
1142
[4]1143 print $html;
1144
1145} # edit()
1146
1147
1148# Stuff new info about a block into the db
1149# action=update
1150sub update {
[284]1151 if ($IPDBacl{$authuser} !~ /c/) {
1152 printError("You shouldn't have been able to get here. Access denied.");
1153 return;
1154 }
[4]1155
[284]1156 # Check to see if we can update restricted data
1157 my $privdata = '';
1158 if ($IPDBacl{$authuser} =~ /s/) {
1159 $privdata = ",privdata='$webvar{privdata}'";
1160 }
1161
[4]1162 # Make sure incoming data is in correct format - custID among other things.
[228]1163 return if !validateInput;
[4]1164
1165 # SQL transaction wrapper
1166 eval {
1167 # Relatively simple SQL transaction here.
1168 my $sql;
[157]1169 if (my $pooltype = ($webvar{alloctype} =~ /^(.)i$/) ) {
[74]1170 $sql = "update poolips set custid='$webvar{custid}',notes='$webvar{notes}',".
[284]1171 "circuitid='$webvar{circid}',description='$webvar{desc}',city='$webvar{city}'".
1172 "$privdata where ip='$webvar{block}'";
[4]1173 } else {
1174 $sql = "update allocations set custid='$webvar{custid}',".
[33]1175 "description='$webvar{desc}',notes='$webvar{notes}',city='$webvar{city}',".
[320]1176 "type='$webvar{alloctype}',circuitid='$webvar{circid}'$privdata,".
1177 "swip='".($webvar{swip} eq 'on' ? 'y' : 'n')."' ".
[284]1178 "where cidr='$webvar{block}'";
[4]1179 }
[157]1180 # Log the details of the change.
1181 syslog "debug", $sql;
[4]1182 $sth = $ip_dbh->prepare($sql);
1183 $sth->execute;
[397]1184## node hack
1185 if ($webvar{node}) {
1186 $ip_dbh->do("DELETE FROM noderef WHERE block='$webvar{block}'");
1187 $sth = $ip_dbh->prepare("INSERT INTO noderef (block,node_id) VALUES (?,?)");
1188 $sth->execute($webvar{block},$webvar{node});
1189 }
1190## end node hack
[4]1191 $ip_dbh->commit;
1192 };
1193 if ($@) {
[166]1194 my $msg = $@;
1195 carp "Transaction aborted because $msg";
[4]1196 eval { $ip_dbh->rollback; };
[166]1197 syslog "err", "$authuser could not update block/IP '$webvar{block}': '$msg'";
1198 printError("Could not update block/IP $webvar{block}: $msg");
[111]1199 return;
[4]1200 }
1201
1202 # If we get here, the operation succeeded.
1203 syslog "notice", "$authuser updated $webvar{block}";
[416]1204##fixme: need to wedge something in to allow "update:field" notifications
1205## hmm. how to tell what changed? O_o
[426]1206mailNotify($ip_dbh, 's:swi', "SWIPed: $disp_alloctypes{$webvar{alloctype}} $webvar{block}",
[416]1207 "$webvar{block} had SWIP status changed to \"Yes\" by $authuser") if $webvar{swip} eq 'on';
[4]1208 open (HTML, "../updated.html")
[111]1209 or croak "Could not open updated.html :$!";
[4]1210 my $html = join('', <HTML>);
1211
[380]1212 # Link back to browse-routed or list-pool page on "Update complete" page.
1213 my $backlink = "/ip/cgi-bin/main.cgi?action=";
1214 my $cblock; # to contain the CIDR of the container block we're retrieving.
1215 my $sql;
1216 if (my $pooltype = ($webvar{alloctype} =~ /^(.)i$/) ) {
1217 $sql = "select pool from poolips where ip='$webvar{block}'";
1218 $backlink .= "listpool&pool=";
1219 } else {
1220 $sql = "select cidr from routed where cidr >>= '$webvar{block}'";
1221 $backlink .= "showrouted&block=";
1222 }
1223 # I define there to be no errors on this operation... so we don't need to check for them.
1224 $sth = $ip_dbh->prepare($sql);
1225 $sth->execute;
1226 $sth->bind_columns(\$cblock);
1227 $sth->fetch();
1228 $sth->finish;
1229 $backlink .= $cblock;
1230
[320]1231my $swiptmp = ($webvar{swip} eq 'on' ? 'Yes' : 'No');
[4]1232 $html =~ s/\$\$BLOCK\$\$/$webvar{block}/g;
[448]1233 $webvar{city} = $q->escapeHTML($webvar{city});
[4]1234 $html =~ s/\$\$CITY\$\$/$webvar{city}/g;
1235 $html =~ s/\$\$ALLOCTYPE\$\$/$webvar{alloctype}/g;
[106]1236 $html =~ s/\$\$TYPEFULL\$\$/$disp_alloctypes{$webvar{alloctype}}/g;
[4]1237 $html =~ s/\$\$CUSTID\$\$/$webvar{custid}/g;
[320]1238 $html =~ s/\$\$SWIP\$\$/$swiptmp/g;
[448]1239 $webvar{circid} = $q->escapeHTML($webvar{circid});
[74]1240 $html =~ s/\$\$CIRCID\$\$/$webvar{circid}/g;
[448]1241 $webvar{desc} = $q->escapeHTML($webvar{desc});
[4]1242 $html =~ s/\$\$DESC\$\$/$webvar{desc}/g;
[448]1243 $webvar{notes} = $q->escapeHTML($webvar{notes});
[4]1244 $html =~ s/\$\$NOTES\$\$/$webvar{notes}/g;
[380]1245 $html =~ s/\$\$BACKLINK\$\$/$backlink/g;
1246 $html =~ s/\$\$BACKBLOCK\$\$/$cblock/g;
[4]1247
[284]1248 if ($IPDBacl{$authuser} =~ /s/) {
1249 $privdata = qq(<tr class="color2"><td valign="top">Restricted data:</td>).
[448]1250 qq(<td class="regular">).$q->escapeHTML($webvar{privdata}).qq(</td></tr>\n);
[284]1251 }
1252 $html =~ s/\$\$PRIVDATA\$\$/$privdata/g;
1253
[4]1254 print $html;
1255
1256} # update()
1257
1258
1259# Delete an allocation.
[106]1260sub remove {
[233]1261 if ($IPDBacl{$authuser} !~ /d/) {
1262 printError("You shouldn't have been able to get here. Access denied.");
1263 return;
1264 }
1265
[4]1266 #show confirm screen.
1267 open HTML, "../confirmRemove.html"
1268 or croak "Could not open confirmRemove.html :$!";
1269 my $html = join('', <HTML>);
1270 close HTML;
1271
1272 # Serves'em right for getting here...
1273 if (!defined($webvar{block})) {
[111]1274 printError("Error 332");
1275 return;
[4]1276 }
1277
[284]1278 my ($cidr, $custid, $type, $city, $circid, $desc, $notes, $alloctype, $privdata);
[4]1279
[187]1280 if ($webvar{alloctype} eq 'rm') {
[4]1281 $sth = $ip_dbh->prepare("select cidr,city from routed where cidr='$webvar{block}'");
1282 $sth->execute();
1283
1284# This feels... extreme.
1285 croak $sth->errstr() if($sth->errstr());
1286
1287 $sth->bind_columns(\$cidr,\$city);
1288 $sth->execute();
1289 $sth->fetch || croak $sth->errstr();
1290 $custid = "N/A";
1291 $alloctype = $webvar{alloctype};
[74]1292 $circid = "N/A";
[4]1293 $desc = "N/A";
1294 $notes = "N/A";
1295
1296 } elsif ($webvar{alloctype} eq 'mm') {
1297 $cidr = $webvar{block};
1298 $city = "N/A";
1299 $custid = "N/A";
1300 $alloctype = $webvar{alloctype};
[74]1301 $circid = "N/A";
[4]1302 $desc = "N/A";
1303 $notes = "N/A";
[189]1304 } elsif ($webvar{alloctype} =~ /^.i$/) { # done with alloctype=[rm]m
[4]1305
1306 # Unassigning a static IP
[284]1307 my $sth = $ip_dbh->prepare("select ip,custid,city,type,notes,circuitid,privdata".
1308 " from poolips where ip='$webvar{block}'");
[4]1309 $sth->execute();
1310# croak $sth->errstr() if($sth->errstr());
1311
[284]1312 $sth->bind_columns(\$cidr, \$custid, \$city, \$alloctype, \$notes, \$circid,
1313 \$privdata);
[4]1314 $sth->fetch() || croak $sth->errstr;
1315
[157]1316 } else { # done with alloctype=~ /^.i$/
[4]1317
[284]1318 my $sth = $ip_dbh->prepare("select cidr,custid,type,city,circuitid,description,notes,privdata".
1319 " from allocations where cidr='$webvar{block}'");
[4]1320 $sth->execute();
1321# croak $sth->errstr() if($sth->errstr());
1322
[284]1323 $sth->bind_columns(\$cidr, \$custid, \$alloctype, \$city, \$circid, \$desc,
1324 \$notes, \$privdata);
[74]1325 $sth->fetch() || carp $sth->errstr;
[4]1326 } # end cases for different alloctypes
1327
1328 # Munge everything into HTML
1329 $html =~ s|Please confirm|Please confirm <b>removal</b> of|;
1330 $html =~ s|\$\$BLOCK\$\$|$cidr|g;
[106]1331 $html =~ s|\$\$TYPEFULL\$\$|$disp_alloctypes{$alloctype}|g;
[4]1332 $html =~ s|\$\$ALLOCTYPE\$\$|$alloctype|g;
1333 $html =~ s|\$\$CITY\$\$|$city|g;
1334 $html =~ s|\$\$CUSTID\$\$|$custid|g;
[74]1335 $html =~ s|\$\$CIRCID\$\$|$circid|g;
[4]1336 $html =~ s|\$\$DESC\$\$|$desc|g;
1337 $html =~ s|\$\$NOTES\$\$|$notes|g;
1338
1339 $html =~ s|\$\$ACTION\$\$|finaldelete|g;
1340
1341 # Set the warning text.
[157]1342 if ($alloctype =~ /^.[pd]$/) {
[4]1343 $html =~ s|<!--warn-->|<tr bgcolor="black"><td colspan="2"><div class="red">Warning: clicking confirm will remove this record entirely.<br>Any IPs allocated from this pool will also be removed!</div></td></tr>|;
1344 } else {
1345 $html =~ s|<!--warn-->|<tr bgcolor="black"><td colspan="2"><div class="red">Warning: clicking confirm will remove this record entirely.</div></td></tr>|;
1346 }
1347
[284]1348 my $i = 1;
1349 # Check to see if user is allowed to do anything with sensitive data
1350 if ($IPDBacl{$authuser} =~ /s/) {
1351 $privdata = qq(<tr class="color).($i%2).qq("><td>Restricted data:</td>).
1352 qq(<td class=regular>$privdata</td></tr>\n);
1353 $i++;
1354 }
1355 $html =~ s/\$\$PRIVDATA\$\$/$privdata/g;
1356
1357 $i = ++$i % 2;
1358 $html =~ s/\$\$BUTTONROWCOLOUR\$\$/color$i/;
1359
[4]1360 print $html;
1361} # end edit()
1362
1363
1364# Delete an allocation. Return it to the freeblocks table; munge
1365# data as necessary to keep as few records as possible in freeblocks
1366# to prevent weirdness when allocating blocks later.
1367# Remove IPs from pool listing if necessary
1368sub finalDelete {
[233]1369 if ($IPDBacl{$authuser} !~ /d/) {
1370 printError("You shouldn't have been able to get here. Access denied.");
1371 return;
1372 }
[4]1373
[370]1374 # need to retrieve block data before deleting so we can notify on that
1375 my ($cidr,$custid,$type,$city,$description) = getBlockData($ip_dbh, $webvar{block});
1376
[106]1377 my ($code,$msg) = deleteBlock($ip_dbh, $webvar{block}, $webvar{alloctype});
[4]1378
[106]1379 if ($code eq 'OK') {
[4]1380 print "<div class=heading align=center>Success! $webvar{block} deallocated.</div>\n";
[370]1381 syslog "notice", "$authuser deallocated '$webvar{alloctype}'-type netblock $webvar{block}".
1382 " $custid, $city, desc='$description'";
[416]1383 mailNotify($ip_dbh, 'da', "REMOVED: $disp_alloctypes{$webvar{alloctype}} $webvar{block}",
1384 "$disp_alloctypes{$webvar{alloctype}} $webvar{block} deallocated by $authuser\n".
1385 "CustID: $custid\nCity: $city\nDescription: $description\n");
[106]1386 } else {
1387 if ($webvar{alloctype} =~ /^.i$/) {
1388 syslog "err", "$authuser could not deallocate static IP '$webvar{block}': '$msg'";
[111]1389 printError("Could not deallocate static IP $webvar{block}: $msg");
[106]1390 } else {
1391 syslog "err", "$authuser could not deallocate netblock '$webvar{block}': '$msg'";
[111]1392 printError("Could not deallocate netblock $webvar{block}: $msg");
[4]1393 }
[106]1394 }
[4]1395
1396} # finalDelete
1397
1398
[449]1399# going, going, gone... this sub to be removed Any Day Real Soon Now(TM)
[233]1400sub exitError {
1401 my $errStr = $_[0];
1402 printHeader('','');
1403 print qq(<center><p class="regular"> $errStr </p>
1404<input type="button" value="Back" onclick="history.go(-1)">
1405</center>
1406);
[449]1407
1408 # We print the footer here, so we don't have to do it elsewhere.
1409 my $footer = HTML::Template->new(filename => "footer.tmpl");
1410 # include the admin tools link in the output?
1411 $footer->param(adminlink => ($IPDBacl{$authuser} =~ /A/));
1412
1413 print $footer->output;
1414
[233]1415 exit;
1416} # errorExit
1417
1418
[4]1419# Just in case we manage to get here.
1420exit 0;
Note: See TracBrowser for help on using the repository browser.