source: branches/stable/cgi-bin/main.cgi@ 192

Last change on this file since 192 was 192, checked in by Kris Deugau, 19 years ago

/branches/stable

Merge updates and changes (and bugfixes to same) from /trunk
r186,187 and r189-191

  • Property svn:executable set to *
  • Property svn:keywords set to Date Rev Author
File size: 44.7 KB
Line 
1#!/usr/bin/perl
2# ipdb/cgi-bin/main.cgi
3# Started munging from noc.vianet's old IPDB 04/22/2004
4###
5# SVN revision info
6# $Date: 2005-03-10 19:15:19 +0000 (Thu, 10 Mar 2005) $
7# SVN revision $Rev: 192 $
8# Last update by $Author: kdeugau $
9###
10
11use strict;
12use warnings;
13use CGI::Carp qw(fatalsToBrowser);
14use DBI;
15use CommonWeb qw(:ALL);
16use MyIPDB;
17use CustIDCK;
18use POSIX qw(ceil);
19use NetAddr::IP;
20
21use Sys::Syslog;
22
23openlog "IPDB","pid","local2";
24
25# Collect the username from HTTP auth. If undefined, we're in a test environment.
26my $authuser;
27if (!defined($ENV{'REMOTE_USER'})) {
28 $authuser = '__temptest';
29} else {
30 $authuser = $ENV{'REMOTE_USER'};
31}
32
33syslog "debug", "$authuser active";
34
35# Why not a global DB handle? (And a global statement handle, as well...)
36# Use the connectDB function, otherwise we end up confusing ourselves
37my $ip_dbh;
38my $sth;
39my $errstr;
40($ip_dbh,$errstr) = connectDB_My;
41if (!$ip_dbh) {
42 printAndExit("Database error: $errstr\n");
43}
44initIPDBGlobals($ip_dbh);
45
46#prototypes
47sub viewBy($$); # feed it the category and query
48sub queryResults($$$); # args is the sql, the page# and the rowCount
49# Needs rewrite/rename
50sub countRows($); # returns first element of first row of passed SQL
51 # Only usage passes "select count(*) ..."
52
53# Global variables
54my $RESULTS_PER_PAGE = 50;
55my %webvar = parse_post();
56cleanInput(\%webvar);
57
58
59#main()
60
61if(!defined($webvar{action})) {
62 $webvar{action} = "<NULL>"; #shuts up the warnings.
63}
64
65if($webvar{action} eq 'index') {
66 showSummary();
67} elsif ($webvar{action} eq 'newmaster') {
68 printHeader('');
69
70 my $cidr = new NetAddr::IP $webvar{cidr};
71
72 print "<div type=heading align=center>Adding $cidr as master block....</div>\n";
73
74 # Allow transactions, and raise an exception on errors so we can catch it later.
75 # Use local to make sure these get "reset" properly on exiting this block
76 local $ip_dbh->{AutoCommit} = 0;
77 local $ip_dbh->{RaiseError} = 1;
78
79 # Wrap the SQL in a transaction
80 eval {
81 $sth = $ip_dbh->prepare("insert into masterblocks values ('$webvar{cidr}')");
82 $sth->execute;
83
84# Unrouted blocks aren't associated with a city (yet). We don't rely on this
85# elsewhere though; legacy data may have traps and pitfalls in it to break this.
86# Thus the "routed" flag.
87
88 $sth = $ip_dbh->prepare("insert into freeblocks (cidr,maskbits,city,routed)".
89 " values ('$webvar{cidr}',".$cidr->masklen.",'<NULL>','n')");
90 $sth->execute;
91
92 # If we get here, everything is happy. Commit changes.
93 $ip_dbh->commit;
94 }; # end eval
95
96 if ($@) {
97 carp "Transaction aborted because $@";
98 eval { $ip_dbh->rollback; };
99 syslog "err", "Could not add master block '$webvar{cidr}' to database: '$@'";
100 printError("Could not add master block $webvar{cidr} to database: $@");
101 } else {
102 print "<div type=heading align=center>Success!</div>\n";
103 syslog "info", "$authuser added master block $webvar{cidr}";
104 }
105
106} # end add new master
107
108elsif($webvar{action} eq 'showmaster') {
109 showMaster();
110}
111elsif($webvar{action} eq 'showrouted') {
112 showRBlock();
113}
114elsif($webvar{action} eq 'listpool') {
115 listPool();
116}
117elsif($webvar{action} eq 'search') {
118 printHeader('');
119 if (!$webvar{input}) {
120 # No search term. Display everything.
121 viewBy('all', '');
122 } else {
123 # Search term entered. Display matches.
124 # We should really sanitize $webvar{input}, no?
125 viewBy($webvar{searchfor}, $webvar{input});
126 }
127}
128
129# Not modified or added; just shuffled
130elsif($webvar{action} eq 'assign') {
131 assignBlock();
132}
133elsif($webvar{action} eq 'confirm') {
134 confirmAssign();
135}
136elsif($webvar{action} eq 'insert') {
137 insertAssign();
138}
139elsif($webvar{action} eq 'edit') {
140 edit();
141}
142elsif($webvar{action} eq 'update') {
143 update();
144}
145elsif($webvar{action} eq 'delete') {
146 remove();
147}
148elsif($webvar{action} eq 'finaldelete') {
149 finalDelete();
150}
151
152# Default is an error. It shouldn't be possible to easily get here.
153# The only way I can think of offhand is to just call main.cgi bare-
154# which is not in any way guaranteed to provide anything useful.
155else {
156 printHeader('');
157 my $rnd = rand 500;
158 my $boing = sprintf("%.2f", rand 500);
159 my @excuses = ("Aether cloudy. Ask again later.","The gods are unhappy with your sacrifice.",
160 "Because one of it's legs are both the same", "*wibble*",
161 "Hey! Stop pushing my buttons!", "I ain't done nuttin'", "9",
162 "8", "9", "10", "11", "12", "13", "14", "15", "16", "17");
163 printAndExit("Error $boing: ".$excuses[$rnd/30.0]);
164}
165## Finally! Done with that NASTY "case" emulation!
166
167
168
169# Clean up IPDB globals, DB handle, etc.
170finish($ip_dbh);
171# We print the footer here, so we don't have to do it elsewhere.
172printFooter;
173# Just in case something waaaayyy down isn't in place
174# properly... we exit explicitly.
175exit;
176
177
178
179sub viewBy($$) {
180 my ($category,$query) = @_;
181
182 # Local variables
183 my $sql;
184
185#print "<pre>\n";
186
187#print "start querysub: query '$query'\n";
188# this may happen with more than one subcategory. Unlikely, but possible.
189
190 # Calculate start point for LIMIT clause
191 my $offset = ($webvar{page}-1)*$RESULTS_PER_PAGE;
192
193# Possible cases:
194# 1) Partial IP/subnet. Treated as "first-three-octets-match" in old IPDB,
195# I should be able to handle it similarly here.
196# 2a) CIDR subnet. Treated more or less as such in old IPDB.
197# 2b) CIDR netmask. Not sure how it's treated.
198# 3) Customer ID. Not handled in old IPDB
199# 4) Description.
200# 5) Invalid data which might be interpretable as an IP or something, but
201# which probably shouldn't be for reasons of sanity.
202
203 if ($category eq 'all') {
204
205 print qq(<div class="heading">Showing all netblock and static-IP allocations</div><br>\n);
206
207 # Need to assemble SQL query in this order to avoid breaking things.
208 $sql = "select cidr,custid,type,city,description from searchme";
209 my $count = countRows("select count(*) from ($sql) foo");
210 $sql .= " order by cidr limit $RESULTS_PER_PAGE offset $offset";
211 queryResults($sql, $webvar{page}, $count);
212
213 } elsif ($category eq 'cust') {
214
215 print qq(<div class="heading">Searching for Customer IDs containing '$query'</div><br>\n);
216
217 # Query for a customer ID. Note that we can't restrict to "numeric-only"
218 # as we have non-numeric custIDs in the legacy data. :/
219 $sql = "select cidr,custid,type,city,description from searchme where custid ilike '%$query%'";
220 my $count = countRows("select count(*) from ($sql) foo");
221 $sql .= " order by cidr limit $RESULTS_PER_PAGE offset $offset";
222 queryResults($sql, $webvar{page}, $count);
223
224 } elsif ($category eq 'desc') {
225
226 print qq(<div class="heading">Searching for descriptions containing '$query'</div><br>\n);
227 # Query based on description (includes "name" from old DB).
228 $sql = "select cidr,custid,type,city,description from searchme where description ilike '%$query%'";
229 my $count = countRows("select count(*) from ($sql) foo");
230 $sql .= " order by cidr limit $RESULTS_PER_PAGE offset $offset";
231 queryResults($sql, $webvar{page}, $count);
232
233 } elsif ($category =~ /ipblock/) {
234
235 # Query is for a partial IP, a CIDR block in some form, or a flat IP.
236 print qq(<div class="heading">Searching for IP-based matches on '$query'</div><br>\n);
237
238 $query =~ s/\s+//g;
239 if ($query =~ /\//) {
240 # 209.91.179/26 should show all /26 subnets in 209.91.179
241 my ($net,$maskbits) = split /\//, $query;
242 if ($query =~ /^(\d{1,3}\.){3}\d{1,3}\/\d{2}$/) {
243 # /0->/9 are silly to worry about right now. I don't think
244 # we'll be getting a class A anytime soon. <g>
245 $sql = "select cidr,custid,type,city,description from searchme where cidr='$query'";
246 queryResults($sql, $webvar{page}, 1);
247 } else {
248 print "Finding all blocks with netmask /$maskbits, leading octet(s) $net<br>\n";
249 # Partial match; beginning of subnet and maskbits are provided
250 $sql = "select cidr,custid,type,city,description from searchme where ".
251 "text(cidr) like '$net%' and text(cidr) like '%$maskbits'";
252 my $count = countRows("select count(*) from ($sql) foo");
253 $sql .= " order by cidr limit $RESULTS_PER_PAGE offset $offset";
254 queryResults($sql, $webvar{page}, $count);
255 }
256 } elsif ($query =~ /^(\d{1,3}\.){3}\d{1,3}$/) {
257 # Specific IP address match
258 my $sfor = new NetAddr::IP $query;
259# We do this convoluted roundabout way of finding things in order
260# to bring up matches for single IPs that are within a static block;
261# we want to show both the "container" block and the static IP itself.
262 $sth = $ip_dbh->prepare("select cidr from searchme where cidr >>= '$sfor'");
263 $sth->execute;
264 while (my @data = $sth->fetchrow_array()) {
265 my $cidr = new NetAddr::IP $data[0];
266 queryResults("select cidr,custid,type,city,description from searchme where ".
267 "cidr='$cidr'", $webvar{page}, 1);
268 }
269 } elsif ($query =~ /^\d{1,3}\.\d{1,3}\.\d{1,3}\.?$/) {
270 print "Finding matches where the first three octets are $query<br>\n";
271 $sql = "select cidr,custid,type,city,description from searchme where ".
272 "text(cidr) like '$query%'";
273 my $count = countRows("select count(*) from ($sql) foo");
274 $sql .= " order by cidr limit $RESULTS_PER_PAGE offset $offset";
275 queryResults($sql, $webvar{page}, $count);
276 } else {
277 # This shouldn't happen, but if it does, whoever gets it deserves what they get...
278 printError("Invalid query.");
279 }
280 } else {
281 # This shouldn't happen, but if it does, whoever gets it deserves what they get...
282 printError("Invalid searchfor.");
283 }
284} # viewBy
285
286
287# args are: a reference to an array with the row to be printed and the
288# class(stylesheet) to use for formatting.
289# if ommitting the class - call the sub as &printRow(\@array)
290sub printRow {
291 my ($rowRef,$class) = @_;
292
293 if (!$class) {
294 print "<tr>\n";
295 } else {
296 print "<tr class=\"$class\">\n";
297 }
298
299ELEMENT: foreach my $element (@$rowRef) {
300 if (!defined($element)) {
301 print "<td></td>\n";
302 next ELEMENT;
303 }
304 $element =~ s|\n|</br>|g;
305 print "<td>$element</td>\n";
306 }
307 print "</tr>";
308} # printRow
309
310
311# Display certain types of search query. Note that this can't be
312# cleanly reused much of anywhere else as the data isn't neatly tabulated.
313# This is tied to the search sub tightly enough I may just gut it and provide
314# more appropriate tables directly as needed.
315sub queryResults($$$) {
316 my ($sql, $pageNo, $rowCount) = @_;
317 my $offset = 0;
318 $offset = $1 if($sql =~ m/.*limit\s+(.*),.*/);
319
320 my $sth = $ip_dbh->prepare($sql);
321 $sth->execute();
322
323 startTable('Allocation','CustID','Type','City','Description/Name');
324 my $count = 0;
325
326 while (my @data = $sth->fetchrow_array) {
327 # cidr,custid,type,city,description
328 # Prefix subblocks with "Sub "
329 my @row = ( (($data[2] =~ /^.r$/) ? 'Sub ' : '').
330 qq(<a href="/ip/cgi-bin/main.cgi?action=edit&block=$data[0]">$data[0]</a>),
331 $data[1], $disp_alloctypes{$data[2]}, $data[3], $data[4]);
332 # Allow listing of pool if desired/required.
333 if ($data[2] =~ /^.[pd]$/) {
334 $row[0] .= ' &nbsp; <a href="/ip/cgi-bin/main.cgi?action=listpool'.
335 "&pool=$data[0]\">List IPs</a>";
336 }
337 printRow(\@row, 'color1', 1) if ($count%2==0);
338 printRow(\@row, 'color2', 1) if ($count%2!=0);
339 $count++;
340 }
341
342 # Have to think on this call, it's primarily to clean up unfetched rows from a select.
343 # In this context it's probably a good idea.
344 $sth->finish();
345
346 my $upper = $offset+$count;
347 print "<tr><td colspan=10 bgcolor=white class=regular>Records found: $rowCount<br><i>Displaying: $offset - $upper</i></td></tr>\n";
348 print "</table></center>\n";
349
350 # print the page thing..
351 if ($rowCount > $RESULTS_PER_PAGE) {
352 my $pages = ceil($rowCount/$RESULTS_PER_PAGE);
353 print qq(<div class="center"> Page: );
354 for (my $i = 1; $i <= $pages; $i++) {
355 if ($i == $pageNo) {
356 print "<b>$i&nbsp;</b>\n";
357 } else {
358 print qq(<a href="/ip/cgi-bin/main.cgi?page=$i&input=$webvar{input}&action=search&searchfor=$webvar{searchfor}">$i</a>&nbsp;\n);
359 }
360 }
361 print "</div>";
362 }
363} # queryResults
364
365
366# Prints table headings. Accepts any number of arguments;
367# each argument is a table heading.
368sub startTable {
369 print qq(<center><table width="98%" cellspacing="0" class="center"><tr>);
370
371 foreach(@_) {
372 print qq(<td class="heading">$_</td>);
373 }
374 print "</tr>\n";
375} # startTable
376
377
378# Return first element of passed SQL query
379sub countRows($) {
380 my $sth = $ip_dbh->prepare($_[0]);
381 $sth->execute();
382 my @a = $sth->fetchrow_array();
383 $sth->finish();
384 return $a[0];
385}
386
387
388# Initial display: Show master blocks with total allocated subnets, total free subnets
389sub showSummary {
390 # this is horrible-ugly-bad and will Go Away real soon now(TM)
391 print "Content-type: text/html\n\n";
392
393 startTable('Master netblock', 'Routed netblocks', 'Allocated netblocks',
394 'Free netblocks', 'Largest free block');
395
396 my %allocated;
397 my %free;
398 my %routed;
399 my %bigfree;
400
401 # Count the allocations.
402 $sth = $ip_dbh->prepare("select count(*) from allocations where cidr <<= ?");
403 foreach my $master (@masterblocks) {
404 $sth->execute("$master");
405 $sth->bind_columns(\$allocated{"$master"});
406 $sth->fetch();
407 }
408
409 # Count routed blocks
410 $sth = $ip_dbh->prepare("select count(*) from routed where cidr <<= ?");
411 foreach my $master (@masterblocks) {
412 $sth->execute("$master");
413 $sth->bind_columns(\$routed{"$master"});
414 $sth->fetch();
415 }
416
417 # Count the free blocks.
418 $sth = $ip_dbh->prepare("select count(*) from freeblocks where cidr <<= ?");
419 foreach my $master (@masterblocks) {
420 $sth->execute("$master");
421 $sth->bind_columns(\$free{"$master"});
422 $sth->fetch();
423 }
424
425 # Find the largest free block in each master
426 $sth = $ip_dbh->prepare("select maskbits from freeblocks where cidr <<= ? order by maskbits limit 1");
427 foreach my $master (@masterblocks) {
428 $sth->execute("$master");
429 $sth->bind_columns(\$bigfree{"$master"});
430 $sth->fetch();
431 }
432
433 # Print the data.
434 my $count=0;
435 foreach my $master (@masterblocks) {
436 my @row = ("<a href=\"/ip/cgi-bin/main.cgi?action=showmaster&block=$master\">$master</a>",
437 $routed{"$master"}, $allocated{"$master"}, $free{"$master"},
438 ( ($bigfree{"$master"} eq '') ? ("&lt;NONE&gt;") : ("/".$bigfree{"$master"}) )
439 );
440
441 printRow(\@row, 'color1' ) if($count%2==0);
442 printRow(\@row, 'color2' ) if($count%2!=0);
443 $count++;
444 }
445 print "</table>\n";
446 print qq(<a href="/ip/addmaster.shtml">Add new master block</a><br><br>\n);
447 print "Note: Free blocks noted here include both routed and unrouted blocks.\n";
448
449} # showSummary
450
451
452# Display detail on master
453# Alrighty then! We're showing routed blocks within a single master this time.
454# We should be able to steal code from showSummary(), and if I'm really smart
455# I'll figger a way to munge the two together. (Once I've done that, everything
456# else should follow. YMMV.)
457sub showMaster {
458 printHeader('');
459
460 print qq(<center><div class="heading">Summarizing routed blocks for ).
461 qq($webvar{block}:</div></center><br>\n);
462
463 my %allocated;
464 my %free;
465 my %routed;
466 my %bigfree;
467
468 my $master = new NetAddr::IP $webvar{block};
469 my @localmasters;
470
471 # Fetch only the blocks relevant to this master
472 $sth = $ip_dbh->prepare("select cidr,city from routed where cidr <<= '$master' order by cidr");
473 $sth->execute();
474
475 my $i=0;
476 while (my @data = $sth->fetchrow_array()) {
477 my $cidr = new NetAddr::IP $data[0];
478 $localmasters[$i++] = $cidr;
479 $free{"$cidr"} = 0;
480 $allocated{"$cidr"} = 0;
481 $bigfree{"$cidr"} = 128;
482 # Retain the routing destination
483 $routed{"$cidr"} = $data[1];
484 }
485
486 # Check if there were actually any blocks routed from this master
487 if ($i > 0) {
488 startTable('Routed block','Routed to','Allocated blocks',
489 'Free blocks','Largest free block');
490
491 # Count the allocations
492 $sth = $ip_dbh->prepare("select count(*) from allocations where cidr <<= ?");
493 foreach my $master (@localmasters) {
494 $sth->execute("$master");
495 $sth->bind_columns(\$allocated{"$master"});
496 $sth->fetch();
497 }
498
499 # Count the free blocks.
500 $sth = $ip_dbh->prepare("select count(*) from freeblocks where cidr <<= ?");
501 foreach my $master (@localmasters) {
502 $sth->execute("$master");
503 $sth->bind_columns(\$free{"$master"});
504 $sth->fetch();
505 }
506
507 # Get the size of the largest free block
508 $sth = $ip_dbh->prepare("select maskbits from freeblocks where cidr <<= ? order by maskbits limit 1");
509 foreach my $master (@localmasters) {
510 $sth->execute("$master");
511 $sth->bind_columns(\$bigfree{"$master"});
512 $sth->fetch();
513 }
514
515 # Print the data.
516 my $count=0;
517 foreach my $master (@localmasters) {
518 my @row = ("<a href=\"/ip/cgi-bin/main.cgi?action=showrouted&block=$master\">$master</a>",
519 $routed{"$master"}, $allocated{"$master"},
520 $free{"$master"},
521 ( ($bigfree{"$master"} eq 128) ? ("&lt;NONE&gt;") : ("/".$bigfree{"$master"}) )
522 );
523 printRow(\@row, 'color1' ) if($count%2==0);
524 printRow(\@row, 'color2' ) if($count%2!=0);
525 $count++;
526 }
527 } else {
528 # If a master block has no routed blocks, then by definition it has no
529 # allocations, and can be deleted.
530 print qq(<hr width="60%"><center><div class="heading">No allocations in ).
531 qq($master.</div>\n).
532 qq(<form action="/ip/cgi-bin/main.cgi" method=POST>\n).
533 qq(<input type=hidden name=action value="delete">\n).
534 qq(<input type=hidden name=block value="$master">\n).
535 qq(<input type=hidden name=alloctype value="mm">\n).
536 qq(<input type=submit value=" Remove this master ">\n).
537 qq(</form></center>\n);
538
539 } # end check for existence of routed blocks in master
540
541 print qq(</table>\n<hr width="60%">\n).
542 qq(<center><div class="heading">Unrouted blocks in $master:</div></center><br>\n);
543
544 startTable('Netblock','Range');
545
546 # Snag the free blocks.
547 my $count = 0;
548 $sth = $ip_dbh->prepare("select cidr from freeblocks where cidr <<='$master' and ".
549 "routed='n' order by cidr");
550 $sth->execute();
551 while (my @data = $sth->fetchrow_array()) {
552 my $cidr = new NetAddr::IP $data[0];
553 my @row = ("$cidr", $cidr->range);
554 printRow(\@row, 'color1' ) if($count%2==0);
555 printRow(\@row, 'color2' ) if($count%2!=0);
556 $count++;
557 }
558
559 print "</table>\n";
560} # showMaster
561
562
563# Display details of a routed block
564# Alrighty then! We're showing allocations within a routed block this time.
565# We should be able to steal code from showSummary() and showMaster(), and if
566# I'm really smart I'll figger a way to munge all three together. (Once I've
567# done that, everything else should follow. YMMV.
568# This time, we check the database before spewing, because we may
569# not have anything useful to spew.
570sub showRBlock {
571 printHeader('');
572
573 my $master = new NetAddr::IP $webvar{block};
574
575 $sth = $ip_dbh->prepare("select city from routed where cidr='$master'");
576 $sth->execute;
577 my @data = $sth->fetchrow_array;
578
579 print qq(<center><div class="heading">Summarizing allocated blocks for ).
580 qq($master ($data[0]):</div></center><br>\n);
581
582 startTable('CIDR allocation','Customer Location','Type','CustID','Description/Name');
583
584 # Snag the allocations for this block
585 $sth = $ip_dbh->prepare("select cidr,city,type,custid,description".
586 " from allocations where cidr <<= '$master' order by cidr");
587 $sth->execute();
588
589 my $count=0;
590 while (my @data = $sth->fetchrow_array()) {
591 # cidr,city,type,custid,description, as per the SELECT
592 my $cidr = new NetAddr::IP $data[0];
593
594 # Clean up extra spaces that are borking things.
595# $data[2] =~ s/\s+//g;
596
597 # Prefix subblocks with "Sub "
598 my @row = ( (($data[2] =~ /^.r$/) ? 'Sub ' : '').
599 qq(<a href="/ip/cgi-bin/main.cgi?action=edit&block=$data[0]">$data[0]</a>),
600 $data[1], $disp_alloctypes{$data[2]}, $data[3], $data[4]);
601 # If the allocation is a pool, allow listing of the IPs in the pool.
602 if ($data[2] =~ /^.[pd]$/) {
603 $row[0] .= ' &nbsp; <a href="/ip/cgi-bin/main.cgi?action=listpool'.
604 "&pool=$data[0]\">List IPs</a>";
605 }
606
607 printRow(\@row, 'color1') if ($count%2 == 0);
608 printRow(\@row, 'color2') if ($count%2 != 0);
609 $count++;
610 }
611
612 print "</table>\n";
613
614 # If the routed block has no allocations, by definition it only has
615 # one free block, and therefore may be deleted.
616 if ($count == 0) {
617 print qq(<hr width="60%"><center><div class="heading">No allocations in ).
618 qq($master.</div></center>\n).
619 qq(<form action="/ip/cgi-bin/main.cgi" method=POST>\n).
620 qq(<input type=hidden name=action value="delete">\n).
621 qq(<input type=hidden name=block value="$master">\n).
622 qq(<input type=hidden name=alloctype value="rm">\n).
623 qq(<input type=submit value=" Remove this block ">\n).
624 qq(</form>\n);
625 }
626
627 print qq(<hr width="60%">\n<center><div class="heading">Free blocks within routed ).
628 qq(submaster $master</div></center>\n);
629
630 startTable('CIDR block','Range');
631
632 # Snag the free blocks. We don't really *need* to be pedantic about avoiding
633 # unrouted free blocks, but it's better to let the database do the work if we can.
634 $count = 0;
635 $sth = $ip_dbh->prepare("select cidr,routed from freeblocks where cidr <<= '$master'".
636 " order by cidr");
637 $sth->execute();
638 while (my @data = $sth->fetchrow_array()) {
639 # cidr,routed
640 my $cidr = new NetAddr::IP $data[0];
641 # Include some HairyPerl(TM) to prefix subblocks with "Sub "
642 my @row = ((($data[1] ne 'y' && $data[1] ne 'n') ? 'Sub ' : '').
643 qq(<a href="/ip/cgi-bin/main.cgi?action=assign&block=$cidr&fbtype=$data[1]">$cidr</a>),
644 $cidr->range);
645 printRow(\@row, 'color1') if ($count%2 == 0);
646 printRow(\@row, 'color2') if ($count%2 != 0);
647 $count++;
648 }
649
650 print "</table>\n";
651} # showRBlock
652
653
654# List the IPs used in a pool
655sub listPool {
656 printHeader('');
657
658 my $cidr = new NetAddr::IP $webvar{pool};
659
660 my ($pooltype,$poolcity);
661
662 # Snag pool info for heading
663 $sth = $ip_dbh->prepare("select type,city from allocations where cidr='$cidr'");
664 $sth->execute;
665 $sth->bind_columns(\$pooltype, \$poolcity);
666 $sth->fetch() || carp $sth->errstr;
667
668 print qq(<center><div class="heading">Listing pool IPs for $cidr<br>\n).
669 qq(($disp_alloctypes{$pooltype} in $poolcity)</div></center><br>\n);
670 # Only display net/gw/bcast if it's a "real" netblock and not a PPP(oE) lunacy
671 if ($pooltype =~ /^.d$/) {
672 print qq(<div class="indent"><b>Reserved IPs:</b><br>\n);
673 print qq(<div class="indent"><table><tr class=color1><td>Network IP:</td><td>).
674 $cidr->addr."</td></tr>\n";
675 $cidr++;
676 print "<tr class=color2><td>Gateway:</td><td>".$cidr->addr."</td></tr>\n";
677 $cidr--; $cidr--;
678 print "<tr class=color1><td>Broadcast:</td><td>".$cidr->addr."</td></tr>\n".
679 "<tr><td>Netmask:</td><td>".$cidr->mask."</td></tr>\n".
680 "</table></div></div>\n";
681 }
682
683# probably have to add an "edit IP allocation" link here somewhere.
684
685 startTable('IP','Customer ID','Available?','Description','');
686 $sth = $ip_dbh->prepare("select ip,custid,available,description,type".
687 " from poolips where pool='$webvar{pool}' order by ip");
688 $sth->execute;
689 my $count = 0;
690 while (my @data = $sth->fetchrow_array) {
691 # pool,ip,custid,city,ptype,available,notes,description,circuitid
692 # ip,custid,available,description,type
693 # If desc is "null", make it not null. <g>
694 if ($data[3] eq '') {
695 $data[3] = '&nbsp;';
696 }
697 # Some nice hairy Perl to decide whether to allow unassigning each IP
698 # -> if $data[2] (aka poolips.available) == 'n' then we print the unassign link
699 # else we print a blank space
700 my @row = ( qq(<a href="/ip/cgi-bin/main.cgi?action=edit&block=$data[0]">$data[0]</a>),
701 $data[1],$data[2],$data[3],
702 ( ($data[2] eq 'n') ?
703 ("<a href=\"/ip/cgi-bin/main.cgi?action=delete&block=$data[0]&".
704 "alloctype=$data[4]\">Unassign this IP</a>") :
705 ("&nbsp;") )
706 );
707 printRow(\@row, 'color1') if($count%2==0);
708 printRow(\@row, 'color2') if($count%2!=0);
709 $count++;
710 }
711 print "</table>\n";
712
713} # end listPool
714
715
716# Show "Add new allocation" page. Note that the actual page may
717# be one of two templates, and the lists come from the database.
718sub assignBlock {
719 printHeader('');
720
721 my $html;
722
723 # New special case- block to assign is specified
724 if ($webvar{block} ne '') {
725 open HTML, "../fb-assign.html"
726 or croak "Could not open fb-assign.html: $!";
727 $html = join('',<HTML>);
728 close HTML;
729 my $block = new NetAddr::IP $webvar{block};
730 $html =~ s|\$\$BLOCK\$\$|$block|g;
731 $html =~ s|\$\$MASKBITS\$\$|$block->masklen|;
732 my $typelist = '';
733
734 # This is a little dangerous, as it's *theoretically* possible to
735 # get fbtype='n' (aka a non-routed freeblock). However, should
736 # someone manage to get there, they get what they deserve.
737 if ($webvar{fbtype} ne 'y') {
738 # Snag the type of the block from the database. We have no
739 # convenient way to pass this in from the calling location. :/
740 $sth = $ip_dbh->prepare("select type from allocations where cidr >>='$block'");
741 $sth->execute;
742 my @data = $sth->fetchrow_array;
743 $data[0] =~ s/c$/r/; # Munge the type into the correct form
744 $typelist = "$list_alloctypes{$data[0]}<input type=hidden name=alloctype value=$data[0]>\n";
745 } else {
746 $typelist .= qq(<select name="alloctype">\n);
747 $sth = $ip_dbh->prepare("select type,listname from alloctypes where listorder < 500 ".
748 "and type not like '_i' and type not like '_r' order by listorder");
749 $sth->execute;
750 my @data = $sth->fetchrow_array;
751 $typelist .= "<option value='$data[0]' selected>$data[1]</option>\n";
752 while (my @data = $sth->fetchrow_array) {
753 $typelist .= "<option value='$data[0]'>$data[1]</option>\n";
754 }
755 $typelist .= "</select>\n";
756 }
757 $html =~ s|\$\$TYPELIST\$\$|$typelist|g;
758 } else {
759 open HTML, "../assign.html"
760 or croak "Could not open assign.html: $!";
761 $html = join('',<HTML>);
762 close HTML;
763 my $masterlist = "<select name=allocfrom><option selected>-</option>\n";
764 foreach my $master (@masterblocks) {
765 $masterlist .= "<option>$master</option>\n";
766 }
767 $masterlist .= "</select>\n";
768 $html =~ s|\$\$MASTERLIST\$\$|$masterlist|g;
769 my $pops = '';
770 foreach my $pop (@poplist) {
771 $pops .= "<option>$pop</option>\n";
772 }
773 $html =~ s|\$\$POPLIST\$\$|$pops|g;
774 my $typelist = '';
775 $sth = $ip_dbh->prepare("select type,listname from alloctypes where listorder < 900 order by listorder");
776 $sth->execute;
777 my @data = $sth->fetchrow_array;
778 $typelist .= "<option value='$data[0]' selected>$data[1]</option>\n";
779 while (my @data = $sth->fetchrow_array) {
780 $typelist .= "<option value='$data[0]'>$data[1]</option>\n";
781 }
782 $html =~ s|\$\$TYPELIST\$\$|$typelist|g;
783 }
784 my $cities = '';
785 foreach my $city (@citylist) {
786 $cities .= "<option>$city</option>\n";
787 }
788 $html =~ s|\$\$ALLCITIES\$\$|$cities|g;
789
790 print $html;
791
792} # assignBlock
793
794
795# Take info on requested IP assignment and see what we can provide.
796sub confirmAssign {
797 printHeader('');
798
799 my $cidr;
800 my $alloc_from;
801
802 # Going to manually validate some items.
803 # custid and city are automagic.
804 return if !validateInput();
805
806# Several different cases here.
807# Static IP vs netblock
808# + Different flavours of static IP
809# + Different flavours of netblock
810
811 if ($webvar{alloctype} =~ /^.i$/) {
812 my ($base,undef) = split //, $webvar{alloctype}; # split into individual chars
813 my $sql;
814 # Check for pools in Subury or North Bay if DSL or server pool. Anywhere else is
815 # invalid and shouldn't be in the db in the first place.
816 # ... aside from #^%#$%#@#^%^^!!!! legacy data. GRRR.
817 # Note that we want to retain the requested city to relate to customer info.
818##fixme This needs thought.
819##SELECT DISTINCT pool, Count(*) FROM poolips where available='y' GROUP BY pool;
820 if ($base =~ /^[ds]$/) {
821 $sql = "select * from poolips where available='y' and".
822 " type='$webvar{alloctype}' and (city='Sudbury' or city='North Bay')";
823 } else {
824 $sql = "select * from poolips where available='y' and".
825 " type='$webvar{alloctype}' and city='$webvar{pop}'";
826 }
827
828 # Now that we know where we're looking, we can list the pools with free IPs.
829 $sth = $ip_dbh->prepare($sql);
830 $sth->execute;
831 my %ipcount;
832 my $optionlist;
833 while (my @data = $sth->fetchrow_array) {
834 $ipcount{$data[0]}++;
835 }
836 $sth = $ip_dbh->prepare("select city from allocations where cidr=?");
837 foreach my $key (keys %ipcount) {
838 $sth->execute($key);
839 my @data = $sth->fetchrow_array;
840 $optionlist .= "<option value='$key'>$key [$ipcount{$key} free IP(s)] in $data[0]</option>\n";
841 }
842 $cidr = "Single static IP";
843 $alloc_from = "<select name=alloc_from>".$optionlist."</select>\n";
844
845 } else { # end show pool options
846
847 if ($webvar{fbassign} eq 'y') {
848 $cidr = new NetAddr::IP $webvar{block};
849 $webvar{maskbits} = $cidr->masklen;
850 } else { # done with direct freeblocks assignment
851
852 if (!$webvar{maskbits}) {
853 printError("Please specify a CIDR mask length.");
854 return;
855 }
856 my $sql;
857 my $city;
858 my $failmsg;
859 if ($webvar{alloctype} eq 'rm') {
860 if ($webvar{allocfrom} ne '-') {
861 $sql = "select * from freeblocks where maskbits<=$webvar{maskbits} and routed='n'".
862 " and cidr <<= '$webvar{allocfrom}' order by maskbits desc";
863 } else {
864 $sql = "select * from freeblocks where maskbits<=$webvar{maskbits} and routed='n'".
865 " order by maskbits desc";
866 }
867 $failmsg = "No suitable free block found.<br>\nWe do not have a free".
868 " routeable block of that size.<br>\nYou will have to either route".
869 " a set of smaller netblocks or a single smaller netblock.";
870 } else {
871##fixme
872# This section needs serious Pondering.
873 # Pools of all types get assigned to the POP they're "routed from"
874 # This includes WAN blocks and other netblock "containers"
875 if ($webvar{alloctype} =~ /^.[pdc]$/) {
876 if (($webvar{city} !~ /^(Sudbury|North Bay)$/) && ($webvar{alloctype} eq 'dp')) {
877 printError("You must chose Sudbury or North Bay for DSL pools.");
878 return;
879 }
880 $city = $webvar{city};
881 $failmsg = "No suitable free block found.<br>\nYou will have to route another".
882 " superblock from one of the<br>\nmaster blocks in Sudbury or chose a smaller".
883 " block size for the pool.";
884 } else {
885 $city = $webvar{pop};
886 $failmsg = "No suitable free block found.<br>\nYou will have to route another".
887 " superblock to $webvar{pop}<br>\nfrom one of the master blocks in Sudbury or".
888 " chose a smaller blocksize.";
889 }
890 if ($webvar{allocfrom} ne '-') {
891 $sql = "select cidr from freeblocks where city='$city' and maskbits<=$webvar{maskbits}".
892 " and cidr <<= '$webvar{allocfrom}' and routed='".
893 (($webvar{alloctype} =~ /^(.)r$/) ? "$1" : 'y')."' order by maskbits desc,cidr";
894 } else {
895 $sql = "select cidr from freeblocks where city='$city' and maskbits<=$webvar{maskbits}".
896 " and routed='".(($webvar{alloctype} =~ /^(.)r$/) ? "$1" : 'y').
897 "' order by maskbits desc,cidr";
898 }
899 }
900 $sth = $ip_dbh->prepare($sql);
901 $sth->execute;
902 my @data = $sth->fetchrow_array();
903 if ($data[0] eq "") {
904 printError($failmsg);
905 return;
906 }
907 $cidr = new NetAddr::IP $data[0];
908 } # check for freeblocks assignment or IPDB-controlled assignment
909
910 $alloc_from = qq($cidr<input type=hidden name=alloc_from value="$cidr">);
911
912 # If the block to be allocated is smaller than the one we found,
913 # figure out the "real" block to be allocated.
914 if ($cidr->masklen() ne $webvar{maskbits}) {
915 my $maskbits = $cidr->masklen();
916 my @subblocks;
917 while ($maskbits++ < $webvar{maskbits}) {
918 @subblocks = $cidr->split($maskbits);
919 }
920 $cidr = $subblocks[0];
921 }
922 } # if ($webvar{alloctype} =~ /^.i$/)
923
924 open HTML, "../confirm.html"
925 or croak "Could not open confirm.html: $!";
926 my $html = join '', <HTML>;
927 close HTML;
928
929### gotta fix this in final
930 # Stick in customer info as necessary - if it's blank, it just ends
931 # up as blank lines ignored in the rendering of the page
932 my $custbits;
933 $html =~ s|\$\$CUSTBITS\$\$|$custbits|g;
934###
935
936 # Stick in the allocation data
937 $html =~ s|\$\$ALLOC_TYPE\$\$|$webvar{alloctype}|g;
938 $html =~ s|\$\$TYPEFULL\$\$|$disp_alloctypes{$webvar{alloctype}}|g;
939 $html =~ s|\$\$ALLOC_FROM\$\$|$alloc_from|g;
940 $html =~ s|\$\$CIDR\$\$|$cidr|g;
941 $webvar{city} = desanitize($webvar{city});
942 $html =~ s|\$\$CITY\$\$|$webvar{city}|g;
943 $html =~ s|\$\$CUSTID\$\$|$webvar{custid}|g;
944 $webvar{circid} = desanitize($webvar{circid});
945 $html =~ s|\$\$CIRCID\$\$|$webvar{circid}|g;
946 $webvar{desc} = desanitize($webvar{desc});
947 $html =~ s|\$\$DESC\$\$|$webvar{desc}|g;
948 $webvar{notes} = desanitize($webvar{notes});
949 $html =~ s|\$\$NOTES\$\$|$webvar{notes}|g;
950 $html =~ s|\$\$ACTION\$\$|insert|g;
951
952 print $html;
953
954} # end confirmAssign
955
956
957# Do the work of actually inserting a block in the database.
958sub insertAssign {
959 # Some things are done more than once.
960 printHeader('');
961 return if !validateInput();
962
963 # $code is "success" vs "failure", $msg contains OK for a
964 # successful netblock allocation, the IP allocated for static
965 # IP, or the error message if an error occurred.
966 my ($code,$msg) = allocateBlock($ip_dbh, $webvar{fullcidr}, $webvar{alloc_from},
967 $webvar{custid}, $webvar{alloctype}, $webvar{city}, $webvar{desc}, $webvar{notes},
968 $webvar{circid});
969
970 if ($code eq 'OK') {
971 if ($webvar{alloctype} =~ /^.i$/) {
972 print qq(<div class="center"><div class="heading">The IP $msg has been allocated to customer $webvar{custid}</div></div>);
973 # Notify tech@example.com
974 mailNotify('tech@example.com',"$disp_alloctypes{$webvar{alloctype}} allocation",
975 "$disp_alloctypes{$webvar{alloctype}} $msg allocated to customer $webvar{custid}\n".
976 "Description: $webvar{desc}\n\nAllocated by: $authuser\n");
977 } else {
978 print qq(<div class="center"><div class="heading">The block $webvar{fullcidr} was ).
979 "sucessfully added as: $disp_alloctypes{$webvar{alloctype}}</div></div>";
980 }
981 syslog "notice", "$authuser allocated '$webvar{fullcidr}' to '$webvar{custid}' as ".
982 "'$webvar{alloctype}'";
983 } else {
984 syslog "err", "Allocation of '$webvar{fullcidr}' to '$webvar{custid}' as ".
985 "'$webvar{alloctype}' by $authuser failed: '$msg'";
986 printError("Allocation of $webvar{fullcidr} as '$disp_alloctypes{$webvar{alloctype}}'".
987 " failed:<br>\n$msg\n");
988 }
989
990} # end insertAssign()
991
992
993# Does some basic checks on common input data to make sure nothing
994# *really* weird gets in to the database through this script.
995# Does NOT do complete input validation!!!
996sub validateInput {
997 if ($webvar{city} eq '-') {
998 printError("Please choose a city.");
999 return;
1000 }
1001
1002 # Alloctype check.
1003 chomp $webvar{alloctype};
1004 if (!grep /$webvar{alloctype}/, keys %disp_alloctypes) {
1005 # Danger! Danger! alloctype should ALWAYS be set by a dropdown. Anyone
1006 # managing to call things in such a way as to cause this deserves a cryptic error.
1007 printError("Invalid alloctype");
1008 return;
1009 }
1010
1011 # CustID check
1012 # We have different handling for customer allocations and "internal" or "our" allocations
1013 if ($webvar{alloctype} =~ /^(cn|.i)$/) {
1014 if (!$webvar{custid}) {
1015 printError("Please enter a customer ID.");
1016 return;
1017 }
1018 if ($webvar{custid} !~ /^(?:\d{10}|\d{7}|STAFF)(?:-\d\d?)?$/) {
1019 # Force uppercase for now...
1020 $webvar{custid} =~ tr/a-z/A-Z/;
1021 # Crosscheck with ... er... something.
1022 my $status = CustIDCK->custid_exist($webvar{custid});
1023 if ($CustIDCK::Error) {
1024 printError("Error verifying customer ID: ".$CustIDCK::ErrMsg);
1025 return;
1026 }
1027 if (!$status) {
1028 printError("Customer ID not valid. Make sure the Customer ID ".
1029 "is correct.<br>\nUse STAFF for staff static IPs, and 6750400 for any other ".
1030 "non-customer assignments.");
1031 return;
1032 }
1033#"Please enter a valid customer ID- this must be a 7- or 10-digit number, or STAFF for
1034#static IPs for staff.");
1035 }
1036# print "<!-- [ In validateInput(). Insert customer ID cross-check here. ] -->\n";
1037 } else {
1038 # New! Improved! And now Loaded From The Database!!
1039 if ((!$webvar{custid}) || ($webvar{custid} ne 'STAFF')) {
1040 $webvar{custid} = $def_custids{$webvar{alloctype}};
1041 }
1042 }
1043
1044 # Check POP location
1045 my $flag;
1046 if ($webvar{alloctype} eq 'rm') {
1047 $flag = 'for a routed netblock';
1048 foreach (@poplist) {
1049 if (/^$webvar{city}$/) {
1050 $flag = 'n';
1051 last;
1052 }
1053 }
1054 } else {
1055 $flag = 'n';
1056 if ($webvar{pop} =~ /^-$/) {
1057 $flag = 'to route the block from/through';
1058 }
1059 }
1060 if ($flag ne 'n') {
1061 printError("Please choose a valid POP location $flag. Valid ".
1062 "POP locations are currently:<br>\n".join (" - ", @poplist));
1063 return;
1064 }
1065
1066 return 'OK';
1067} # end validateInput
1068
1069
1070# Displays details of a specific allocation in a form
1071# Allows update/delete
1072# action=edit
1073sub edit {
1074 printHeader('');
1075
1076 my $sql;
1077
1078 # Two cases: block is a netblock, or block is a static IP from a pool
1079 # because I'm lazy, we'll try to make the SELECT's bring out identical)ish) data
1080 if ($webvar{block} =~ /\/32$/) {
1081 $sql = "select ip,custid,type,city,circuitid,description,notes from poolips where ip='$webvar{block}'";
1082 } else {
1083 $sql = "select cidr,custid,type,city,circuitid,description,notes from allocations where cidr='$webvar{block}'"
1084 }
1085
1086 # gotta snag block info from db
1087 $sth = $ip_dbh->prepare($sql);
1088 $sth->execute;
1089 my @data = $sth->fetchrow_array;
1090
1091 # Clean up extra whitespace on alloc type
1092 $data[2] =~ s/\s//;
1093
1094##fixme LEGACY CODE
1095 # Postfix "i" on pool IP types
1096 if ($data[2] =~ /^[cdsmw]$/) {
1097 $data[2] .= "i";
1098 }
1099
1100 open (HTML, "../editDisplay.html")
1101 or croak "Could not open editDisplay.html :$!";
1102 my $html = join('', <HTML>);
1103
1104 # We can't let the city be changed here; this block is a part of
1105 # a larger routed allocation and therefore by definition can't be moved.
1106 # block and city are static.
1107##fixme
1108# Needs thinking. Have to allow changes to city to correct errors, no?
1109 $html =~ s/\$\$BLOCK\$\$/$webvar{block}/g;
1110 $html =~ s/\$\$CITY\$\$/$data[3]/g;
1111
1112# Screw it. Changing allocation types gets very ugly VERY quickly- especially
1113# with the much longer list of allocation types.
1114# We'll just show what type of block it is.
1115
1116# this has now been Requested, so here goes.
1117
1118##fixme The check here should be built from the database
1119 if ($data[2] =~ /^.[ne]$/) {
1120 # Block that can be changed
1121 my $blockoptions = "<select name=alloctype><option".
1122 (($data[2] eq 'me') ? ' selected' : '') ." value='me'>Dialup netblock</option>\n<option".
1123 (($data[2] eq 'de') ? ' selected' : '') ." value='de'>Dynamic DSL netblock</option>\n<option". (($data[2] eq 'dc') ? ' selected' : '') ." value='dc'>Dynamic cable netblock</option>\n<option".
1124 (($data[2] eq 'ce') ? ' selected' : '') ." value='ce'>Dynamic cable netblock</option>\n<option". (($data[2] eq 'dc') ? ' selected' : '') ." value='dc'>Dynamic cable netblock</option>\n<option".
1125 (($data[2] eq 'we') ? ' selected' : '') ." value='we'>Dynamic wireless netblock</option>\n<option". (($data[2] eq 'dc') ? ' selected' : '') ." value='dc'>Dynamic cable netblock</option>\n<option".
1126 (($data[2] eq 'cn') ? ' selected' : '') ." value='cn'>Customer netblock</option>\n<option".
1127 (($data[2] eq 'en') ? ' selected' : '') ." value='en'>End-use netblock</option>\n<option".
1128 (($data[2] eq 'in') ? ' selected' : '') ." value='in'>Internal netblock</option>\n".
1129 "</select>\n";
1130 $html =~ s/\$\$TYPESELECT\$\$/$blockoptions/g;
1131 } else {
1132 $html =~ s/\$\$TYPESELECT\$\$/$disp_alloctypes{$data[2]}<input type=hidden name=alloctype value="$data[2]">/g;
1133 }
1134
1135 # These can be modified, although CustID changes may get ignored.
1136 $html =~ s/\$\$CUSTID\$\$/$data[1]/g;
1137 $html =~ s/\$\$TYPE\$\$/$data[2]/g;
1138 $html =~ s/\$\$CIRCID\$\$/$data[4]/g;
1139 $html =~ s/\$\$DESC\$\$/$data[5]/g;
1140 $html =~ s/\$\$NOTES\$\$/$data[6]/g;
1141
1142 print $html;
1143
1144} # edit()
1145
1146
1147# Stuff new info about a block into the db
1148# action=update
1149sub update {
1150 printHeader('');
1151
1152 # Make sure incoming data is in correct format - custID among other things.
1153 validateInput;
1154
1155 # SQL transaction wrapper
1156 eval {
1157 # Relatively simple SQL transaction here.
1158 my $sql;
1159 if (my $pooltype = ($webvar{alloctype} =~ /^(.)i$/) ) {
1160 $sql = "update poolips set custid='$webvar{custid}',notes='$webvar{notes}',".
1161 "circuitid='$webvar{circid}',description='$webvar{desc}' ".
1162 "where ip='$webvar{block}'";
1163 } else {
1164 $sql = "update allocations set custid='$webvar{custid}',".
1165 "description='$webvar{desc}',notes='$webvar{notes}',city='$webvar{city}',".
1166 "type='$webvar{alloctype}',circuitid='$webvar{circid}' where cidr='$webvar{block}'";
1167 }
1168 # Log the details of the change.
1169 syslog "debug", $sql;
1170 $sth = $ip_dbh->prepare($sql);
1171 $sth->execute;
1172 $ip_dbh->commit;
1173 };
1174 if ($@) {
1175 my $msg = $@;
1176 carp "Transaction aborted because $msg";
1177 eval { $ip_dbh->rollback; };
1178 syslog "err", "$authuser could not update block/IP '$webvar{block}': '$msg'";
1179 printError("Could not update block/IP $webvar{block}: $msg");
1180 return;
1181 }
1182
1183 # If we get here, the operation succeeded.
1184 syslog "notice", "$authuser updated $webvar{block}";
1185 open (HTML, "../updated.html")
1186 or croak "Could not open updated.html :$!";
1187 my $html = join('', <HTML>);
1188
1189 $html =~ s/\$\$BLOCK\$\$/$webvar{block}/g;
1190 $webvar{city} = desanitize($webvar{city});
1191 $html =~ s/\$\$CITY\$\$/$webvar{city}/g;
1192 $html =~ s/\$\$ALLOCTYPE\$\$/$webvar{alloctype}/g;
1193 $html =~ s/\$\$TYPEFULL\$\$/$disp_alloctypes{$webvar{alloctype}}/g;
1194 $html =~ s/\$\$CUSTID\$\$/$webvar{custid}/g;
1195 $webvar{circid} = desanitize($webvar{circid});
1196 $html =~ s/\$\$CIRCID\$\$/$webvar{circid}/g;
1197 $webvar{desc} = desanitize($webvar{desc});
1198 $html =~ s/\$\$DESC\$\$/$webvar{desc}/g;
1199 $webvar{notes} = desanitize($webvar{notes});
1200 $html =~ s/\$\$NOTES\$\$/$webvar{notes}/g;
1201
1202 print $html;
1203
1204} # update()
1205
1206
1207# Delete an allocation.
1208sub remove {
1209 printHeader('');
1210 #show confirm screen.
1211 open HTML, "../confirmRemove.html"
1212 or croak "Could not open confirmRemove.html :$!";
1213 my $html = join('', <HTML>);
1214 close HTML;
1215
1216 # Serves'em right for getting here...
1217 if (!defined($webvar{block})) {
1218 printError("Error 332");
1219 return;
1220 }
1221
1222 my ($cidr, $custid, $type, $city, $circid, $desc, $notes, $alloctype);
1223
1224 if ($webvar{alloctype} eq 'rm') {
1225 $sth = $ip_dbh->prepare("select cidr,city from routed where cidr='$webvar{block}'");
1226 $sth->execute();
1227
1228# This feels... extreme.
1229 croak $sth->errstr() if($sth->errstr());
1230
1231 $sth->bind_columns(\$cidr,\$city);
1232 $sth->execute();
1233 $sth->fetch || croak $sth->errstr();
1234 $custid = "N/A";
1235 $alloctype = $webvar{alloctype};
1236 $circid = "N/A";
1237 $desc = "N/A";
1238 $notes = "N/A";
1239
1240 } elsif ($webvar{alloctype} eq 'mm') {
1241 $cidr = $webvar{block};
1242 $city = "N/A";
1243 $custid = "N/A";
1244 $alloctype = $webvar{alloctype};
1245 $circid = "N/A";
1246 $desc = "N/A";
1247 $notes = "N/A";
1248 } elsif ($webvar{alloctype} =~ /^.i$/) { # done with alloctype=[rm]m
1249
1250 # Unassigning a static IP
1251 my $sth = $ip_dbh->prepare("select ip,custid,city,type,notes,circuitid from poolips".
1252 " where ip='$webvar{block}'");
1253 $sth->execute();
1254# croak $sth->errstr() if($sth->errstr());
1255
1256 $sth->bind_columns(\$cidr, \$custid, \$city, \$alloctype, \$notes, \$circid);
1257 $sth->fetch() || croak $sth->errstr;
1258
1259 } else { # done with alloctype=~ /^.i$/
1260
1261 my $sth = $ip_dbh->prepare("select cidr,custid,type,city,circuitid,description,notes from ".
1262 "allocations where cidr='$webvar{block}'");
1263 $sth->execute();
1264# croak $sth->errstr() if($sth->errstr());
1265
1266 $sth->bind_columns(\$cidr, \$custid, \$alloctype, \$city, \$circid, \$desc, \$notes);
1267 $sth->fetch() || carp $sth->errstr;
1268 } # end cases for different alloctypes
1269
1270 # Munge everything into HTML
1271 $html =~ s|Please confirm|Please confirm <b>removal</b> of|;
1272 $html =~ s|\$\$BLOCK\$\$|$cidr|g;
1273 $html =~ s|\$\$TYPEFULL\$\$|$disp_alloctypes{$alloctype}|g;
1274 $html =~ s|\$\$ALLOCTYPE\$\$|$alloctype|g;
1275 $html =~ s|\$\$CITY\$\$|$city|g;
1276 $html =~ s|\$\$CUSTID\$\$|$custid|g;
1277 $html =~ s|\$\$CIRCID\$\$|$circid|g;
1278 $html =~ s|\$\$DESC\$\$|$desc|g;
1279 $html =~ s|\$\$NOTES\$\$|$notes|g;
1280
1281 $html =~ s|\$\$ACTION\$\$|finaldelete|g;
1282
1283 # Set the warning text.
1284 if ($alloctype =~ /^.[pd]$/) {
1285 $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>|;
1286 } else {
1287 $html =~ s|<!--warn-->|<tr bgcolor="black"><td colspan="2"><div class="red">Warning: clicking confirm will remove this record entirely.</div></td></tr>|;
1288 }
1289
1290 print $html;
1291} # end edit()
1292
1293
1294# Delete an allocation. Return it to the freeblocks table; munge
1295# data as necessary to keep as few records as possible in freeblocks
1296# to prevent weirdness when allocating blocks later.
1297# Remove IPs from pool listing if necessary
1298sub finalDelete {
1299 printHeader('');
1300
1301 my ($code,$msg) = deleteBlock($ip_dbh, $webvar{block}, $webvar{alloctype});
1302
1303 if ($code eq 'OK') {
1304 print "<div class=heading align=center>Success! $webvar{block} deallocated.</div>\n";
1305 syslog "notice", "$authuser deallocated '$webvar{alloctype}'-type netblock $webvar{block}";
1306 } else {
1307 if ($webvar{alloctype} =~ /^.i$/) {
1308 syslog "err", "$authuser could not deallocate static IP '$webvar{block}': '$msg'";
1309 printError("Could not deallocate static IP $webvar{block}: $msg");
1310 } else {
1311 syslog "err", "$authuser could not deallocate netblock '$webvar{block}': '$msg'";
1312 printError("Could not deallocate netblock $webvar{block}: $msg");
1313 }
1314 }
1315
1316} # finalDelete
1317
1318
1319# Just in case we manage to get here.
1320exit 0;
Note: See TracBrowser for help on using the repository browser.