source: branches/new-custids/cgi-bin/main.cgi@ 270

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

/trunk

Fixed buglet that would have incorrectly allowed allocation
of a specific free routed block as a 'contained' type

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