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

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

/branches/htmlform

Remove printFooter from CommonWeb.pm
Add HTML::Template to main.cgi, admin.cgi, and search.cgi
Convert footer.inc to templates/footer.tmpl, and normalize
output for three scripts above
See #3.

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