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

Last change on this file since 133 was 118, checked in by Kris Deugau, 20 years ago

/trunk

SQL cleanup:

  • Made liberal use of "<<=" operator and "where" for DBMS-layer CIDR comparisons
  • Made liberal use of "select count(*) from ... where ..." in place of much more cumbersome "select * from ..." constructs

General code cleanup:

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