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

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

/branches/stable

Temporary-hack bugfix for extra (extra (extra)) "Dynamic cable"
listings in edit-allocation screen. This should *really* be
generated from the database.

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