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

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

/branches/stable

Backported SQL cleanup from /trunk r173

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