source: branches/new-search-20050223/cgi-bin/main.cgi@ 171

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

/branches/new-search-20050223

First iteration:

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