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

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

/branches/stable

Backported bugfixes and changes from /trunk r60:63

  • Property svn:executable set to *
  • Property svn:keywords set to Date Rev Author
File size: 53.1 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: 2004-11-12 17:37:17 +0000 (Fri, 12 Nov 2004) $
7# SVN revision $Rev: 64 $
8# Last update by $Author: kdeugau $
9###
10
11use strict;
12use warnings;
13use CGI::Carp qw(fatalsToBrowser);
14use DBI;
15use CommonWeb qw(:ALL);
16use IPDB qw(:ALL);
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
35checkDBSanity();
36
37#prototypes
38sub viewBy($$); # feed it the category and query
39sub queryResults($$$); # args is the sql, the page# and the rowCount
40# Needs rewrite/rename
41sub countRows($); # returns first element of first row of passed SQL
42 # Only usage passes "select count(*) ..."
43
44my $RESULTS_PER_PAGE = 50;
45my %webvar = parse_post();
46cleanInput(\%webvar);
47
48my %full_alloc_types = (
49 "ci","Cable pool IP",
50 "di","DSL pool IP",
51 "si","Server pool IP",
52 "mi","Static dialup IP",
53 "wi","Static wireless IP",
54 "cp","Cable pool",
55 "dp","DSL pool",
56 "sp","Server pool",
57 "mp","Static dialup pool",
58 "wp","Static wireless pool",
59 "dn","Dialup netblock",
60 "dy","Dynamic DSL netblock",
61 "dc","Dynamic cable netblock",
62 "cn","Customer netblock",
63 "ee","End-use netblock",
64 "rr","Routed netblock",
65 "ii","Internal netblock",
66 "mm","Master block"
67);
68
69# Other global variables
70my @masterblocks;
71my %allocated; # Count for allocated blocks in a master block
72my %free; # Count for free blocks (routed and unrouted) in a master block
73my %bigfree; # Tracking largest free block in a master block
74my %routed; # Number of routed blocks in a master block
75
76# Why not a global DB handle? (And a global statement handle, as well...)
77# We already know the DB is happy, (checkDBSanity) otherwise we wouldn't be here.
78# Use the connectDB function, otherwise we end up confusing ourselves
79my $ip_dbh = connectDB;
80
81# Slurp up the master block list - we need this several places
82# While we're at it, initialize the related hashes.
83my $sth = $ip_dbh->prepare("select * from masterblocks order by cidr");
84$sth->execute;
85for (my $i=0; my @data = $sth->fetchrow_array(); $i++) {
86 $masterblocks[$i] = new NetAddr::IP $data[0];
87 $allocated{"$masterblocks[$i]"} = 0;
88 $free{"$masterblocks[$i]"} = 0;
89 $bigfree{"$masterblocks[$i]"} = 128; # Larger number means smaller block.
90 # Set to 128 to prepare for IPv6
91 $routed{"$masterblocks[$i]"} = 0;
92}
93
94
95
96
97#main()
98
99if(!defined($webvar{action})) {
100 $webvar{action} = "<NULL>"; #shuts up the warnings.
101}
102
103if($webvar{action} eq 'index') {
104 showSummary();
105} elsif ($webvar{action} eq 'newmaster') {
106 printHeader('');
107
108 my $cidr = new NetAddr::IP $webvar{cidr};
109
110 print "<div type=heading align=center>Adding $cidr as master block....\n";
111
112 # Allow transactions, and raise an exception on errors so we can catch it later.
113 # Use local to make sure these get "reset" properly on exiting this block
114 local $ip_dbh->{AutoCommit} = 0;
115 local $ip_dbh->{RaiseError} = 1;
116
117 # Wrap the SQL in a transaction
118 eval {
119 $sth = $ip_dbh->prepare("insert into masterblocks values ('$webvar{cidr}')");
120 $sth->execute;
121
122# Unrouted blocks aren't associated with a city (yet). We don't rely on this
123# elsewhere though; legacy data may have traps and pitfalls in it to break this.
124# Thus the "routed" flag.
125
126 $sth = $ip_dbh->prepare("insert into freeblocks values ('$webvar{cidr}',".
127 $cidr->masklen.",'<NULL>','n')");
128 $sth->execute;
129
130 # If we get here, everything is happy. Commit changes.
131 $ip_dbh->commit;
132 }; # end eval
133
134 if ($@) {
135 carp "Transaction aborted because $@";
136 eval { $ip_dbh->rollback; };
137 syslog "err", "Could not add master block '$webvar{cidr}' to database: '$@'";
138 printAndExit("Could not add master block $webvar{cidr} to database: $@");
139 }
140
141 print "Success!</div>\n";
142
143 printFooter;
144} # end add new master
145
146elsif($webvar{action} eq 'showmaster') {
147 showMaster();
148}
149elsif($webvar{action} eq 'showrouted') {
150 showRBlock();
151}
152elsif($webvar{action} eq 'listpool') {
153 listPool();
154}
155elsif($webvar{action} eq 'search') {
156 printHeader('');
157 if (!$webvar{input}) {
158 # No search term. Display everything.
159 viewBy('all', '');
160 } else {
161 # Search term entered. Display matches.
162 # We should really sanitize $webvar{input}, no?
163 viewBy($webvar{searchfor}, $webvar{input});
164 }
165 printFooter();
166}
167
168# Not modified or added; just shuffled
169elsif($webvar{action} eq 'assign') {
170 assignBlock();
171}
172elsif($webvar{action} eq 'confirm') {
173 confirmAssign();
174}
175elsif($webvar{action} eq 'insert') {
176 insertAssign();
177}
178elsif($webvar{action} eq 'edit') {
179 edit();
180}
181elsif($webvar{action} eq 'update') {
182 update();
183}
184elsif($webvar{action} eq 'delete') {
185 remove();
186}
187elsif($webvar{action} eq 'finaldelete') {
188 finalDelete();
189}
190
191# Default is an error. It shouldn't be possible to easily get here.
192# The only way I can think of offhand is to just call main.cgi bare-
193# which is not in any way guaranteed to provide anything useful.
194else {
195 printHeader('');
196 my $rnd = rand 500;
197 my $boing = sprintf("%.2f", rand 500);
198 my @excuses = ("Aether cloudy. Ask again later.","The gods are unhappy with your sacrifice.",
199 "Because one of it's legs are both the same", "*wibble*",
200 "Hey! Stop pushing my buttons!", "I ain't done nuttin'", "9",
201 "8", "9", "10", "11", "12", "13", "14", "15", "16", "17");
202 printAndExit("Error $boing: ".$excuses[$rnd/30.0]);
203}
204
205
206#end main()
207
208# Shut up error log warning about not disconnecting. Maybe.
209$ip_dbh->disconnect;
210# Just in case something waaaayyy down isn't in place properly...
211exit 0;
212
213
214sub viewBy($$) {
215 my ($category,$query) = @_;
216
217 # Local variables
218 my $sql;
219
220#print "<pre>\n";
221
222#print "start querysub: query '$query'\n";
223# this may happen with more than one subcategory. Unlikely, but possible.
224
225 # Calculate start point for LIMIT clause
226 my $offset = ($webvar{page}-1)*$RESULTS_PER_PAGE;
227
228# Possible cases:
229# 1) Partial IP/subnet. Treated as "first-three-octets-match" in old IPDB,
230# I should be able to handle it similarly here.
231# 2a) CIDR subnet. Treated more or less as such in old IPDB.
232# 2b) CIDR netmask. Not sure how it's treated.
233# 3) Customer ID. Not handled in old IPDB
234# 4) Description.
235# 5) Invalid data which might be interpretable as an IP or something, but
236# which probably shouldn't be for reasons of sanity.
237
238 if ($category eq 'all') {
239
240 print qq(<div class="heading">Showing all netblock and static-IP allocations</div><br>\n);
241 $sql = "select * from searchme";
242 my $count = countRows("select count(*) from ($sql) foo");
243 $sql .= " order by cidr limit $RESULTS_PER_PAGE offset $offset";
244 queryResults($sql, $webvar{page}, $count);
245
246 } elsif ($category eq 'cust') {
247
248 print qq(<div class="heading">Searching for Customer IDs containing '$query'</div><br>\n);
249
250 # Query for a customer ID. Note that we can't restrict to "numeric-only"
251 # as we have non-numeric custIDs in the legacy data. :/
252 $sql = "select * from searchme where custid ilike '%$query%'";
253 my $count = countRows("select count(*) from ($sql) foo");
254 $sql .= " order by cidr limit $RESULTS_PER_PAGE offset $offset";
255 queryResults($sql, $webvar{page}, $count);
256
257 } elsif ($category eq 'desc') {
258
259 print qq(<div class="heading">Searching for descriptions containing '$query'</div><br>\n);
260 # Query based on description (includes "name" from old DB).
261 $sql = "select * from searchme where description ilike '%$query%'";
262 my $count = countRows("select count(*) from ($sql) foo");
263 $sql .= " order by cidr limit $RESULTS_PER_PAGE offset $offset";
264 queryResults($sql, $webvar{page}, $count);
265
266 } elsif ($category =~ /ipblock/) {
267
268 # Query is for a partial IP, a CIDR block in some form, or a flat IP.
269 print qq(<div class="heading">Searching for IP-based matches on '$query'</div><br>\n);
270
271 $query =~ s/\s+//g;
272 if ($query =~ /\//) {
273 # 209.91.179/26 should show all /26 subnets in 209.91.179
274 my ($net,$maskbits) = split /\//, $query;
275 if ($query =~ /^(\d{1,3}\.){3}\d{1,3}\/\d{2}$/) {
276 # /0->/9 are silly to worry about right now. I don't think
277 # we'll be getting a class A anytime soon. <g>
278 $sql = "select * from searchme where cidr='$query'";
279 queryResults($sql, $webvar{page}, 1);
280 } else {
281 print "Finding all blocks with netmask /$maskbits, leading octet(s) $net<br>\n";
282 # Partial match; beginning of subnet and maskbits are provided
283 $sql = "select * from searchme where text(cidr) like '$net%' and ".
284 "text(cidr) like '%$maskbits'";
285 my $count = countRows("select count(*) from ($sql) foo");
286 $sql .= " order by cidr limit $RESULTS_PER_PAGE offset $offset";
287 queryResults($sql, $webvar{page}, $count);
288 }
289 } elsif ($query =~ /^(\d{1,3}\.){3}\d{1,3}$/) {
290 # Specific IP address match
291 print "4-octet pattern found; finding netblock containing IP $query<br>\n";
292 my ($net,$ip) = ($query =~ /(\d{1,3}\.\d{1,3}\.\d{1,3}\.)(\d{1,3})/);
293 my $sfor = new NetAddr::IP $query;
294 $sth = $ip_dbh->prepare("select * from searchme where text(cidr) like '$net%'");
295 $sth->execute;
296 while (my @data = $sth->fetchrow_array()) {
297 my $cidr = new NetAddr::IP $data[0];
298 if ($cidr->contains($sfor)) {
299 queryResults("select * from searchme where cidr='$cidr'", $webvar{page}, 1);
300 }
301 }
302 } elsif ($query =~ /^\d{1,3}\.\d{1,3}\.\d{1,3}\.?$/) {
303 print "Finding matches where the first three octets are $query<br>\n";
304 $sql = "select * from searchme where text(cidr) like '$query%'";
305 my $count = countRows("select count(*) from ($sql) foo");
306 $sql .= " order by cidr limit $RESULTS_PER_PAGE offset $offset";
307 queryResults($sql, $webvar{page}, $count);
308 } else {
309 # This shouldn't happen, but if it does, whoever gets it deserves what they get...
310 printAndExit("Invalid query.");
311 }
312 } else {
313 # This shouldn't happen, but if it does, whoever gets it deserves what they get...
314 printAndExit("Invalid searchfor.");
315 }
316} # viewBy
317
318
319# args are: a reference to an array with the row to be printed and the
320# class(stylesheet) to use for formatting.
321# if ommitting the class - call the sub as &printRow(\@array)
322sub printRow {
323 my ($rowRef,$class) = @_;
324
325 if (!$class) {
326 print "<tr>\n";
327 } else {
328 print "<tr class=\"$class\">\n";
329 }
330
331 foreach my $element (@$rowRef) {
332 print "<td></td>" if (!defined($element));
333 $element =~ s|\n|</br>|g;
334 print "<td>$element</td>\n";
335 }
336 print "</tr>";
337} # printRow
338
339
340# Display certain types of search query. Note that this can't be
341# cleanly reused much of anywhere else as the data isn't neatly tabulated.
342# This is tied to the search sub tightly enough I may just gut it and provide
343# more appropriate tables directly as needed.
344sub queryResults($$$) {
345 my ($sql, $pageNo, $rowCount) = @_;
346 my $offset = 0;
347 $offset = $1 if($sql =~ m/.*limit\s+(.*),.*/);
348
349 my $sth = $ip_dbh->prepare($sql);
350 $sth->execute();
351
352 startTable('Allocation','CustID','Type','City','Description/Name');
353 my $count = 0;
354
355 while (my @data = $sth->fetchrow_array) {
356 # cidr,custid,type,city,description,notes
357 # Fix up types from pools (which are single-char)
358 # Fixing the database would be... painful. :(
359 if ($data[2] =~ /^[sdcmw]$/) {
360 $data[2] .= 'i';
361 }
362 my @row = (qq(<a href="/ip/cgi-bin/main.cgi?action=edit&block=$data[0]">$data[0]</a>),
363 $data[1], $full_alloc_types{$data[2]}, $data[3], $data[4]);
364 # Allow listing of pool if desired/required.
365 if ($data[2] =~ /^[sdcmw]p$/) {
366 $row[0] .= ' &nbsp; <a href="/ip/cgi-bin/main.cgi?action=listpool'.
367 "&pool=$data[0]\">List IPs</a>";
368 }
369 printRow(\@row, 'color1', 1) if ($count%2==0);
370 printRow(\@row, 'color2', 1) if ($count%2!=0);
371 $count++;
372 }
373
374 # Have to think on this call, it's primarily to clean up unfetched rows from a select.
375 # In this context it's probably a good idea.
376 $sth->finish();
377
378 my $upper = $offset+$count;
379 print "<tr><td colspan=10 bgcolor=white class=regular>Records found: $rowCount<br><i>Displaying: $offset - $upper</i></td></tr>\n";
380 print "</table></center>\n";
381
382 # print the page thing..
383 if ($rowCount > $RESULTS_PER_PAGE) {
384 my $pages = ceil($rowCount/$RESULTS_PER_PAGE);
385 print qq(<div class="center"> Page: );
386 for (my $i = 1; $i <= $pages; $i++) {
387 if ($i == $pageNo) {
388 print "<b>$i&nbsp;</b>\n";
389 } else {
390 print qq(<a href="/ip/cgi-bin/main.cgi?page=$i&input=$webvar{input}&action=search&searchfor=$webvar{searchfor}">$i</a>&nbsp;\n);
391 }
392 }
393 print "</div>";
394 }
395} # queryResults
396
397
398# Prints table headings. Accepts any number of arguments;
399# each argument is a table heading.
400sub startTable {
401 print qq(<center><table width="98%" cellspacing="0" class="center"><tr>);
402
403 foreach(@_) {
404 print qq(<td class="heading">$_</td>);
405 }
406 print "</tr>\n";
407} # startTable
408
409
410# Return first element of passed SQL query
411sub countRows($) {
412 my $sth = $ip_dbh->prepare($_[0]);
413 $sth->execute();
414 my @a = $sth->fetchrow_array();
415 $sth->finish();
416 return $a[0];
417}
418
419
420# Initial display: Show master blocks with total allocated subnets, total free subnets
421sub showSummary
422{
423 print "Content-type: text/html\n\n";
424
425 startTable('Master netblock', 'Routed netblocks', 'Allocated netblocks',
426 'Free netblocks', 'Largest free block');
427
428# Snag the allocations.
429# I think it's too confusing to leave out internal allocations.
430 $sth = $ip_dbh->prepare("select * from allocations");
431 $sth->execute();
432 while (my @data = $sth->fetchrow_array()) {
433 # cidr,custid,type,city,description
434 # We only need the cidr
435 my $cidr = new NetAddr::IP $data[0];
436 foreach my $master (@masterblocks) {
437 if ($master->contains($cidr)) {
438 $allocated{"$master"}++;
439 }
440 }
441 }
442
443# Snag routed blocks
444 $sth = $ip_dbh->prepare("select * from routed");
445 $sth->execute();
446 while (my @data = $sth->fetchrow_array()) {
447 # cidr,maskbits,city
448 # We only need the cidr
449 my $cidr = new NetAddr::IP $data[0];
450 foreach my $master (@masterblocks) {
451 if ($master->contains($cidr)) {
452 $routed{"$master"}++;
453 }
454 }
455 }
456
457# Snag the free blocks.
458 $sth = $ip_dbh->prepare("select * from freeblocks");
459 $sth->execute();
460 while (my @data = $sth->fetchrow_array()) {
461 # cidr,maskbits,city
462 # We only need the cidr
463 my $cidr = new NetAddr::IP $data[0];
464 foreach my $master (@masterblocks) {
465 if ($master->contains($cidr)) {
466 $free{"$master"}++;
467 if ($cidr->masklen < $bigfree{"$master"}) { $bigfree{"$master"} = $cidr->masklen; }
468 }
469 }
470 }
471
472# Print the data.
473 my $count=0;
474 foreach my $master (@masterblocks) {
475 my @row = ("<a href=\"/ip/cgi-bin/main.cgi?action=showmaster&block=$master\">$master</a>",
476 $routed{"$master"}, $allocated{"$master"}, $free{"$master"},
477 ( ($bigfree{"$master"} eq 128) ? ("&lt;NONE&gt;") : ("/".$bigfree{"$master"}) )
478 );
479
480 printRow(\@row, 'color1' ) if($count%2==0);
481 printRow(\@row, 'color2' ) if($count%2!=0);
482 $count++;
483 }
484 print "</table>\n";
485 print qq(<a href="/ip/addmaster.shtml">Add new master block</a><br><br>\n);
486 print "Note: Free blocks noted here include both routed and unrouted blocks.\n";
487
488 # Because of the way this sub gets called, we don't need to print the footer here.
489 # (index.shtml makes an SSI #include call to cgi-bin/main.cgi?action=index)
490 # If we do, the footer comes in twice...
491 #printFooter;
492} # showSummary
493
494
495# Display detail on master
496# Alrighty then! We're showing routed blocks within a single master this time.
497# We should be able to steal code from showSummary(), and if I'm really smart
498# I'll figger a way to munge the two together. (Once I've done that, everything
499# else should follow. YMMV.)
500sub showMaster {
501 printHeader('');
502
503 print qq(<center><div class="heading">Summarizing routed blocks for ).
504 qq($webvar{block}:</div></center><br>\n);
505
506 my $master = new NetAddr::IP $webvar{block};
507 my @localmasters;
508
509 $sth = $ip_dbh->prepare("select * from routed order by cidr");
510 $sth->execute();
511
512 my $i=0;
513 while (my @data = $sth->fetchrow_array()) {
514 my $cidr = new NetAddr::IP $data[0];
515 if ($master->contains($cidr)) {
516 $localmasters[$i++] = $cidr;
517 $free{"$cidr"} = 0;
518 $allocated{"$cidr"} = 0;
519 # Retain the routing destination
520 $routed{"$cidr"} = $data[2];
521 }
522 }
523
524# Check if there were actually any blocks routed from this master
525 if ($i > 0) {
526 startTable('Routed block','Routed to','Allocated blocks',
527 'Free blocks','Largest free block');
528
529 # Count the allocations
530 $sth = $ip_dbh->prepare("select * from allocations");
531 $sth->execute();
532 while (my @data = $sth->fetchrow_array()) {
533 # cidr,custid,type,city,description
534 # We only need the cidr
535 my $cidr = new NetAddr::IP $data[0];
536 foreach my $master (@localmasters) {
537 if ($master->contains($cidr)) {
538 $allocated{"$master"}++;
539 }
540 }
541 }
542
543 # initialize bigfree base points
544 foreach my $lmaster (@localmasters) {
545 $bigfree{"$lmaster"} = 128;
546 }
547
548 # Snag the free blocks.
549 $sth = $ip_dbh->prepare("select * from freeblocks");
550 $sth->execute();
551 while (my @data = $sth->fetchrow_array()) {
552 # cidr,maskbits,city
553 # We only need the cidr
554 my $cidr = new NetAddr::IP $data[0];
555 foreach my $lmaster (@localmasters) {
556 if ($lmaster->contains($cidr)) {
557 $free{"$lmaster"}++;
558 if ($cidr->masklen < $bigfree{"$lmaster"}) {
559 $bigfree{"$lmaster"} = $cidr->masklen;
560 }
561 }
562 # check for largest free block
563 }
564 }
565
566 # Print the data.
567 my $count=0;
568 foreach my $master (@localmasters) {
569 my @row = ("<a href=\"/ip/cgi-bin/main.cgi?action=showrouted&block=$master\">$master</a>",
570 $routed{"$master"}, $allocated{"$master"},
571 $free{"$master"},
572 ( ($bigfree{"$master"} eq 128) ? ("&lt;NONE&gt;") : ("/".$bigfree{"$master"}) )
573 );
574 printRow(\@row, 'color1' ) if($count%2==0);
575 printRow(\@row, 'color2' ) if($count%2!=0);
576 $count++;
577 }
578 } else {
579 # If a master block has no routed blocks, then by definition it has no
580 # allocations, and can be deleted.
581 print qq(<hr width="60%"><center><div class="heading">No allocations in ).
582 qq($master.</div>\n).
583 qq(<form action="/ip/cgi-bin/main.cgi" method=POST>\n).
584 qq(<input type=hidden name=action value="delete">\n).
585 qq(<input type=hidden name=block value="$master">\n).
586 qq(<input type=hidden name=alloctype value="mm">\n).
587 qq(<input type=submit value=" Remove this master ">\n).
588 qq(</form></center>\n);
589
590 } # end check for existence of routed blocks in master
591
592 print qq(</table>\n<hr width="60%">\n).
593 qq(<center><div class="heading">Unrouted blocks in $master:</div></center><br>\n);
594
595 startTable('Netblock','Range');
596
597 # Snag the free blocks.
598 my $count = 0;
599 $sth = $ip_dbh->prepare("select * from freeblocks where routed='n' order by cidr");
600 $sth->execute();
601 while (my @data = $sth->fetchrow_array()) {
602 # cidr,maskbits,city
603 # We only need the cidr
604 my $cidr = new NetAddr::IP $data[0];
605 if ($master->contains($cidr)) {
606 my @row = ("$cidr", $cidr->range);
607 printRow(\@row, 'color1' ) if($count%2==0);
608 printRow(\@row, 'color2' ) if($count%2!=0);
609 $count++;
610 }
611 }
612
613 print "</table>\n";
614 printFooter;
615} # showMaster
616
617
618# Display details of a routed block
619# Alrighty then! We're showing allocations within a routed block this time.
620# We should be able to steal code from showSummary() and showMaster(), and if
621# I'm really smart I'll figger a way to munge all three together. (Once I've
622# done that, everything else should follow. YMMV.
623# This time, we check the database before spewing, because we may
624# not have anything useful to spew.
625sub showRBlock {
626 printHeader('');
627
628 my $master = new NetAddr::IP $webvar{block};
629
630 $sth = $ip_dbh->prepare("select * from routed where cidr='$master'");
631 $sth->execute;
632 my @data = $sth->fetchrow_array;
633
634 print qq(<center><div class="heading">Summarizing allocated blocks for ).
635 qq($master ($data[2]):</div></center><br>\n);
636
637 $sth = $ip_dbh->prepare("select * from allocations order by cidr");
638 $sth->execute();
639
640 startTable('CIDR allocation','Customer Location','Type','CustID','Description/Name');
641
642 my $count=0;
643 while (my @data = $sth->fetchrow_array()) {
644 # cidr,custid,type,city,description,notes,maskbits
645 my $cidr = new NetAddr::IP $data[0];
646 if (!$master->contains($cidr)) { next; }
647
648 # Clean up extra spaces that are borking things.
649 $data[2] =~ s/\s+//g;
650
651 my @row = ("<a href=\"/ip/cgi-bin/main.cgi?action=edit&block=$data[0]\">$data[0]</a>",
652 $data[3], $full_alloc_types{$data[2]}, $data[1], $data[4]);
653 # If the allocation is a pool, allow listing of the IPs in the pool.
654 if ($data[2] =~ /^[sdcmw]p$/) {
655 $row[0] .= ' &nbsp; <a href="/ip/cgi-bin/main.cgi?action=listpool'.
656 "&pool=$data[0]\">List IPs</a>";
657 }
658
659 printRow(\@row, 'color1') if ($count%2 == 0);
660 printRow(\@row, 'color2') if ($count%2 != 0);
661 $count++;
662 }
663
664 print "</table>\n";
665
666 # If the routed block has no allocations, by definition it only has
667 # one free block, and therefore may be deleted.
668 if ($count == 0) {
669 print qq(<hr width="60%"><center><div class="heading">No allocations in ).
670 qq($master.</div></center>\n).
671 qq(<form action="/ip/cgi-bin/main.cgi" method=POST>\n).
672 qq(<input type=hidden name=action value="delete">\n).
673 qq(<input type=hidden name=block value="$master">\n).
674 qq(<input type=hidden name=alloctype value="rr">\n).
675 qq(<input type=submit value=" Remove this block ">\n).
676 qq(</form>\n);
677 }
678
679 print qq(<hr width="60%">\n<center><div class="heading">Free blocks within routed ).
680 qq(submaster $master</div></center>\n);
681
682 startTable('CIDR block','Range');
683
684 # Snag the free blocks. We don't really *need* to be pedantic about avoiding
685 # unrouted free blocks, but it's better to let the database do the work if we can.
686 $count = 0;
687 $sth = $ip_dbh->prepare("select * from freeblocks where routed='y' order by cidr");
688 $sth->execute();
689 while (my @data = $sth->fetchrow_array()) {
690 # cidr,maskbits,city
691 my $cidr = new NetAddr::IP $data[0];
692 if ($master->contains($cidr)) {
693 my @row = ("<a href=\"/ip/cgi-bin/main.cgi?action=assign&block=$cidr\">$cidr</a>",
694 $cidr->range);
695 printRow(\@row, 'color1') if ($count%2 == 0);
696 printRow(\@row, 'color2') if ($count%2 != 0);
697 $count++;
698 }
699 }
700
701 print "</table>\n";
702 printFooter;
703} # showRBlock
704
705
706# List the IPs used in a pool
707sub listPool {
708 printHeader('');
709
710 my $cidr = new NetAddr::IP $webvar{pool};
711
712 # Snag pool info for heading
713 $sth = $ip_dbh->prepare("select * from allocations where cidr='$cidr'");
714 $sth->execute;
715 my @data = $sth->fetchrow_array;
716 my $type = $data[2]; # We'll need this later.
717
718 print qq(<center><div class="heading">Listing pool IPs for $cidr<br>\n).
719 qq(($full_alloc_types{$type} in $data[3])</div></center><br>\n);
720 print qq(<div class="indent"><b>Reserved IPs:</b><br>\n);
721 print qq(<div class="indent"><table><tr class=color1><td>Network IP:</td><td>).
722 $cidr->addr."</td></tr>\n";
723 $cidr++;
724 print "<tr class=color2><td>Gateway:</td><td>".$cidr->addr."</td></tr>\n";
725 $cidr--; $cidr--;
726 print "<tr class=color1><td>Broadcast:</td><td>".$cidr->addr."</td></tr>\n".
727 "<tr><td>Netmask:</td><td>".$cidr->mask."</td></tr>\n".
728 "</table></div></div>\n";
729
730# probably have to add an "edit IP allocation" link here somewhere.
731
732 startTable('IP','Customer ID','Available?','Description','');
733 $sth = $ip_dbh->prepare("select * from poolips where pool='$webvar{pool}' order by ip");
734 $sth->execute;
735 my $count = 0;
736 while (my @data = $sth->fetchrow_array) {
737 # pool,ip,custid,city,ptype,available,notes,description
738 # If desc is null, make it not null. <g>
739 if ($data[7] eq '') {
740 $data[7] = '&nbsp;';
741 }
742 # Some nice hairy Perl to decide whether to allow unassigning each IP
743 # -> if $data[5] (aka poolips.available) == 'n' then we print the unassign link
744 # else we print a blank space
745 my @row = ( qq(<a href="/ip/cgi-bin/main.cgi?action=edit&block=$data[1]">$data[1]</a>),
746 $data[2],$data[5],$data[7],
747 ( ($data[5] eq 'n') ?
748 ("<a href=\"/ip/cgi-bin/main.cgi?action=delete&block=$data[1]&".
749 "alloctype=$data[4]i\">Unassign this IP</a>") :
750 ("&nbsp;") )
751 );
752 printRow(\@row, 'color1') if($count%2==0);
753 printRow(\@row, 'color2') if($count%2!=0);
754 $count++;
755 }
756 print "</table>\n";
757
758 printFooter;
759} # end listPool
760
761
762# Should this maybe just be a full static page? It just spews out some predefined HTML.
763sub assignBlock {
764 printHeader('');
765
766 my $html;
767
768 # New special case- block to assign is specified
769 if ($webvar{block} ne '') {
770 open HTML, "../fb-assign.html"
771 or croak "Could not open fb-assign.html: $!";
772 $html = join('',<HTML>);
773 close HTML;
774 my $block = new NetAddr::IP $webvar{block};
775 $html =~ s|\$\$BLOCK\$\$|$block|g;
776 $html =~ s|\$\$MASKBITS\$\$|$block->masklen|;
777 } else {
778 open HTML, "../assign.html"
779 or croak "Could not open assign.html: $!";
780 $html = join('',<HTML>);
781 my $masterlist = "<select name=allocfrom><option selected>-</option>\n";
782 foreach my $master (@masterblocks) {
783 $masterlist .= "<option>$master</option>\n";
784 }
785 $masterlist .= "</select>\n";
786 $html =~ s|\$\$MASTERLIST\$\$|$masterlist|g;
787 close HTML;
788 }
789
790 print $html;
791
792 printFooter();
793} # assignBlock
794
795
796# Take info on requested IP assignment and see what we can provide.
797sub confirmAssign {
798 printHeader('');
799
800 my $cidr;
801 my $alloc_from;
802
803 # Going to manually validate some items.
804 # custid and city are automagic.
805 validateInput();
806
807# This isn't always useful.
808# if (!$webvar{maskbits}) {
809# printAndExit("Please enter a CIDR block length.");
810# }
811
812# Several different cases here.
813# Static IP vs netblock
814# + Different flavours of static IP
815# + Different flavours of netblock
816
817 if ($webvar{alloctype} =~ /^[scdmw]i$/) {
818 my ($base,undef) = split //, $webvar{alloctype}; # split into individual chars
819 my $sql;
820 # Check for pools in Subury or North Bay if DSL or server pool. Anywhere else is
821 # invalid and shouldn't be in the db in the first place.
822 # ... aside from #^%#$%#@#^%^^!!!! legacy data. GRRR.
823 # Note that we want to retain the requested city to relate to customer info.
824 if ($base =~ /^[ds]$/) {
825 $sql = "select * from poolips where available='y' and".
826 " ptype='$base' and (city='Sudbury' or city='North Bay')";
827 } else {
828## $city doesn't seem to get defined here.
829my $city; # Shut up Perl's "strict" scoping/usage check.
830 $sql = "select * from poolips where available='y' and".
831 " ptype='$base' and city='$webvar{city}'";
832 }
833
834 # Now that we know where we're looking, we can list the pools with free IPs.
835 $sth = $ip_dbh->prepare($sql);
836 $sth->execute;
837 my %ipcount;
838 my $optionlist;
839 while (my @data = $sth->fetchrow_array) {
840 $ipcount{$data[0]}++;
841 }
842 foreach my $key (keys %ipcount) {
843 $optionlist .= "<option value='$key'>$key [$ipcount{$key} free IP(s)]</option>\n";
844 }
845 $cidr = "Single static IP";
846 $alloc_from = "<select name=alloc_from>".$optionlist."</select>\n";
847
848 } else { # end show pool options
849
850 if ($webvar{fbassign} eq 'y') {
851 $cidr = new NetAddr::IP $webvar{block};
852 $webvar{maskbits} = $cidr->masklen;
853 } else { # done with direct freeblocks assignment
854
855 if (!$webvar{maskbits}) {
856 printAndExit("Please specify a CIDR mask length.");
857 }
858 my $sql;
859 my $city;
860 my $failmsg;
861 if ($webvar{alloctype} eq 'rr') {
862 if ($webvar{allocfrom} ne '-') {
863 $sql = "select * from freeblocks where maskbits<=$webvar{maskbits} and routed='n'".
864 " and cidr <<= '$webvar{allocfrom}' order by maskbits desc";
865 } else {
866 $sql = "select * from freeblocks where maskbits<=$webvar{maskbits} and routed='n'".
867 " order by maskbits desc";
868 }
869 $failmsg = "No suitable free block found.<br>\nWe do not have a free".
870 " routeable block of that size.<br>\nYou will have to either route".
871 " a set of smaller netblocks or a single smaller netblock.";
872 } else {
873 if ($webvar{alloctype} =~ /^[scdmw]p$/) {
874 if (($webvar{city} !~ /^(Sudbury|North Bay)$/) && ($webvar{alloctype} eq 'dp')) {
875 printAndExit("You must chose Sudbury or North Bay for DSL pools."); }
876 $city = $webvar{city};
877 $failmsg = "No suitable free block found.<br>\nYou will have to route another".
878 " superblock <br>\nfrom one of the master blocks in Sudbury or chose a smaller".
879 " block size for the pool.";
880 } else {
881 $city = $webvar{pop};
882 $failmsg = "No suitable free block found.<br>\nYou will have to route another".
883 " superblock to $webvar{city}<br>\nfrom one of the master blocks in Sudbury or".
884 " chose a smaller blocksize.";
885 }
886 if ($webvar{allocfrom} ne '-') {
887 $sql = "select * from freeblocks where city='$city' and maskbits<=$webvar{maskbits}".
888 " and cidr <<= '$webvar{allocfrom}' and routed='y' order by cidr,maskbits desc";
889 } else {
890 $sql = "select * from freeblocks where city='$city' and maskbits<=$webvar{maskbits}".
891 " and routed='y' order by cidr,maskbits desc";
892 }
893 }
894 $sth = $ip_dbh->prepare($sql);
895 $sth->execute;
896 my @data = $sth->fetchrow_array();
897 if ($data[0] eq "") {
898 printAndExit($failmsg);
899 }
900 $cidr = new NetAddr::IP $data[0];
901 } # check for freeblocks assignment or IPDB-controlled assignment
902
903 $alloc_from = qq($cidr<input type=hidden name=alloc_from value="$cidr">);
904
905 # If the block to be allocated is smaller than the one we found,
906 # figure out the "real" block to be allocated.
907 if ($cidr->masklen() ne $webvar{maskbits}) {
908 my $maskbits = $cidr->masklen();
909 my @subblocks;
910 while ($maskbits++ < $webvar{maskbits}) {
911 @subblocks = $cidr->split($maskbits);
912 }
913 $cidr = $subblocks[0];
914 }
915 } # if ($webvar{alloctype} =~ /^[cdsm]i$/) {
916
917 open HTML, "../confirm.html"
918 or croak "Could not open confirm.html: $!";
919 my $html = join '', <HTML>;
920 close HTML;
921
922### gotta fix this in final
923 # Stick in customer info as necessary - if it's blank, it just ends
924 # up as blank lines ignored in the rendering of the page
925 my $custbits;
926 $html =~ s|\$\$CUSTBITS\$\$|$custbits|g;
927###
928
929 # Stick in the allocation data
930 $html =~ s|\$\$ALLOC_TYPE\$\$|$webvar{alloctype}|g;
931 $html =~ s|\$\$TYPEFULL\$\$|$full_alloc_types{$webvar{alloctype}}|g;
932 $html =~ s|\$\$ALLOC_FROM\$\$|$alloc_from|g;
933 $html =~ s|\$\$CIDR\$\$|$cidr|g;
934 $html =~ s|\$\$CITY\$\$|$webvar{city}|g;
935 $html =~ s|\$\$CUSTID\$\$|$webvar{custid}|g;
936 $webvar{desc} = desanitize($webvar{desc});
937 $webvar{notes} = desanitize($webvar{notes});
938 $html =~ s|\$\$DESC\$\$|$webvar{desc}|g;
939 $html =~ s|\$\$NOTES\$\$|$webvar{notes}|g;
940 $html =~ s|\$\$ACTION\$\$|insert|g;
941
942 print $html;
943
944 printFooter;
945} # end confirmAssign
946
947
948# Do the work of actually inserting a block in the database.
949sub insertAssign {
950 # Some things are done more than once.
951 printHeader('');
952 validateInput();
953
954 # Set some things that may be needed
955 # Don't set $cidr here as it may not even be a valid IP address.
956 my $alloc_from = new NetAddr::IP $webvar{alloc_from};
957
958# dynDSL (dy), sIP DSL(dp), and server pools (sp) are nominally allocated to Sudbury
959# no matter what else happens.
960# if ($webvar{alloctype} =~ /^([sd]p|dy)$/) { $webvar{city} = "Sudbury"; }
961# OOPS. forgot about North Bay DSL.
962#### Gotta make this cleaner and more accurate
963# if ($webvar{alloctype} eq "sp") { $webvar{city} = "Sudbury"; }
964
965# Same ordering as confirmation page
966
967 if ($webvar{alloctype} =~ /^[cdsm]i$/) {
968 my ($base,$tmp) = split //, $webvar{alloctype}; # split into individual chars
969
970 # We'll just have to put up with the oddities caused by SQL (un)sort order
971 $sth = $ip_dbh->prepare("select * from poolips where pool='$webvar{alloc_from}'".
972 " and available='y' order by ip");
973 $sth->execute;
974
975 my @data = $sth->fetchrow_array;
976 my $cidr = $data[1];
977
978 $sth = $ip_dbh->prepare("update poolips set custid='$webvar{custid}',".
979 "city='$webvar{city}',available='n',description='$webvar{desc}'".
980 " where ip='$cidr'");
981 $sth->execute;
982 if ($sth->err) {
983 syslog "err", "Allocation of $cidr to $webvar{custid} by $authuser failed: ".
984 "'".$sth->errstr."'";
985 printAndExit("Allocation of $cidr to $webvar{custid} failed: '".$sth->errstr."'");
986 }
987 print qq(<div class="center"><div class="heading">The IP $cidr has been allocated to customer $webvar{custid}</div></div>);
988 syslog "notice", "$authuser allocated $cidr to $webvar{custid}";
989
990 } else { # end IP-from-pool allocation
991
992 # Set $cidr here as it may not be a valid IP address elsewhere.
993 my $cidr = new NetAddr::IP $webvar{fullcidr};
994
995# Allow transactions, and make errors much easier to catch.
996# Much as I would like to error-track specifically on each ->execute,
997# that's a LOT of code, and some SQL blocks MUST be atomic at a
998# multi-statement level. :/
999 local $ip_dbh->{AutoCommit} = 0; # These need to be local so we don't
1000 local $ip_dbh->{RaiseError} = 1; # step on our toes by accident.
1001
1002 if ($webvar{fullcidr} eq $webvar{alloc_from}) {
1003 # Easiest case- insert in one table, delete in the other, and go home. More or less.
1004 # insert into allocations values (cidr,custid,type,city,desc) and
1005 # delete from freeblocks where cidr='cidr'
1006 # For data safety on non-transaction DBs, we delete first.
1007
1008 eval {
1009 if ($webvar{alloctype} eq 'rr') {
1010 $sth = $ip_dbh->prepare("update freeblocks set routed='y',city='$webvar{city}'".
1011 " where cidr='$webvar{fullcidr}'");
1012 $sth->execute;
1013 $sth = $ip_dbh->prepare("insert into routed values ('$webvar{fullcidr}',".
1014 $cidr->masklen.",'$webvar{city}')");
1015 $sth->execute;
1016 } else {
1017 # common stuff for end-use, dialup, dynDSL, pools, etc, etc.
1018
1019 # city has to be reset for DSL/server pools; nominally to Sudbury.
1020 ## Gotta rethink this; DSL pools can be in North Bay as well. :/
1021 #if ($webvar{alloctype} =~ /^[sd]p$/) { $webvar{city} = 'Sudbury'; }
1022
1023 $sth = $ip_dbh->prepare("delete from freeblocks where cidr='$webvar{fullcidr}'");
1024 $sth->execute;
1025
1026 $sth = $ip_dbh->prepare("insert into allocations values ('$webvar{fullcidr}',".
1027 "'$webvar{custid}','$webvar{alloctype}','$webvar{city}','$webvar{desc}',".
1028 "'$webvar{notes}',".$cidr->masklen.")");
1029 $sth->execute;
1030 } # routing vs non-routing netblock
1031 $ip_dbh->commit;
1032 }; # end of eval
1033 if ($@) {
1034 carp "Transaction aborted because $@";
1035 eval { $ip_dbh->rollback; };
1036 syslog "err", "Allocation of '$webvar{fullcidr}' to '$webvar{custid}' as ".
1037 "'$webvar{alloctype}' by $authuser failed: '$@'";
1038 printAndExit("Allocation of $cidr as $full_alloc_types{$webvar{alloctype}} failed.\n");
1039 }
1040
1041 # If we get here, the DB transaction has succeeded.
1042 syslog "notice", "$authuser allocated '$webvar{fullcidr}' to '$webvar{custid}' as '$webvar{alloctype}'";
1043
1044# How to log SQL without munging too many error-checking wrappers in?
1045# syslog "info", "
1046# We don't. GRRR.
1047
1048 } else { # webvar{fullcidr} != webvar{alloc_from}
1049 # Hard case. Allocation is smaller than free block.
1050 my $wantmaskbits = $cidr->masklen;
1051 my $maskbits = $alloc_from->masklen;
1052
1053 my @newfreeblocks; # Holds free blocks generated from splitting the source freeblock.
1054
1055 my $i=0;
1056 while ($maskbits++ < $wantmaskbits) {
1057 my @subblocks = $alloc_from->split($maskbits);
1058 $newfreeblocks[$i++] = $subblocks[1];
1059 } # while
1060
1061 # Begin SQL transaction block
1062 eval {
1063 # Delete old freeblocks entry
1064 $sth = $ip_dbh->prepare("delete from freeblocks where cidr='$webvar{alloc_from}'");
1065 $sth->execute();
1066
1067 # now we have to do some magic for routing blocks
1068 if ($webvar{alloctype} eq 'rr') {
1069 # Insert the new freeblocks entries
1070 # Note that non-routed blocks are assigned to <NULL>
1071 $sth = $ip_dbh->prepare("insert into freeblocks values (?, ?, '<NULL>','n')");
1072 foreach my $block (@newfreeblocks) {
1073 $sth->execute("$block", $block->masklen);
1074 }
1075 # Insert the entry in the routed table
1076 $sth = $ip_dbh->prepare("insert into routed values ('$cidr',".
1077 $cidr->masklen.",'$webvar{city}')");
1078 $sth->execute;
1079 # Insert the (almost) same entry in the freeblocks table
1080 $sth = $ip_dbh->prepare("insert into freeblocks values ('$cidr',".
1081 $cidr->masklen.",'$webvar{city}','y')");
1082 $sth->execute;
1083
1084 } else { # done with alloctype == rr
1085
1086 # Insert the new freeblocks entries
1087 $sth = $ip_dbh->prepare("insert into freeblocks values (?, ?, ?,'y')");
1088 foreach my $block (@newfreeblocks) {
1089 $sth->execute("$block", $block->masklen, $webvar{city});
1090 }
1091 # Insert the allocations entry
1092 $sth = $ip_dbh->prepare("insert into allocations values ('$webvar{fullcidr}',".
1093 "'$webvar{custid}','$webvar{alloctype}','$webvar{city}',".
1094 "'$webvar{desc}','$webvar{notes}',".$cidr->masklen.")");
1095 $sth->execute;
1096 } # done with netblock alloctype != rr
1097 $ip_dbh->commit;
1098 }; # end eval
1099 if ($@) {
1100 carp "Transaction aborted because $@";
1101 eval { $ip_dbh->rollback; };
1102 syslog "err", "Allocation of '$webvar{fullcidr}' to '$webvar{custid}' as ".
1103 "'$webvar{alloctype}' by $authuser failed: '$@'";
1104 printAndExit("Allocation of $cidr as $full_alloc_types{$webvar{alloctype}} failed.\n");
1105 }
1106 syslog "notice", "$authuser allocated '$webvar{fullcidr}' to '$webvar{custid}' as '$webvar{alloctype}'";
1107
1108 } # end fullcidr != alloc_from
1109
1110 # Begin SQL transaction block
1111 eval {
1112 # special extra handling for pools.
1113 # Note that this must be done for ANY pool allocation!
1114 if ( my ($pooltype) = ($webvar{alloctype} =~ /^([cdsm])p$/) ) {
1115 # have to insert all pool IPs into poolips table as "unallocated".
1116 $sth = $ip_dbh->prepare("insert into poolips values ('$webvar{fullcidr}',".
1117 " ?, '6750400', '$webvar{city}', '$pooltype', 'y', '')");
1118 my @poolip_list = $cidr->hostenum;
1119 for (my $i=1; $i<=$#poolip_list; $i++) {
1120 $sth->execute($poolip_list[$i]->addr);
1121 }
1122 } # end pool special
1123 $ip_dbh->commit;
1124 }; # end eval
1125 if ($@) {
1126 carp "Transaction aborted because $@";
1127 eval { $ip_dbh->rollback; };
1128 syslog "err", "Initialization of pool '$webvar{fullcidr}' by $authuser failed: '$@'";
1129 printAndExit("$full_alloc_types{$webvar{alloctype}} $webvar{fullcidr} not completely initialized.");
1130 }
1131 syslog "notice", "$full_alloc_types{$webvar{alloctype}} '$webvar{fullcidr}' successfully initialized by $authuser";
1132
1133 print qq(<div class="center"><div class="heading">The block $webvar{fullcidr} was sucessfully added as type '$webvar{alloctype}' ($full_alloc_types{$webvar{alloctype}})</div></div>);
1134
1135 } # end static-IP vs netblock allocation
1136
1137 printFooter();
1138} # end insertAssign()
1139
1140
1141# Does some basic checks on common input data to make sure nothing
1142# *really* weird gets in to the database through this script.
1143# Does NOT do complete input validation!!!
1144sub validateInput {
1145 if ($webvar{city} eq '-') {
1146 printAndExit("Please choose a city.");
1147 }
1148 chomp $webvar{alloctype};
1149 # We have different handling for customer allocations and "internal" or "our" allocations
1150 if ($webvar{alloctype} =~ /^(ci|di|cn|mi)$/) {
1151 if (!$webvar{custid}) {
1152 printAndExit("Please enter a customer ID.");
1153 }
1154 if ($webvar{custid} !~ /^(?:\d{10}|\d{7}|STAFF)(?:-\d\d?)?$/) {
1155 # Force uppercase for now...
1156 $webvar{custid} =~ tr/a-z/A-Z/;
1157 # Crosscheck with ... er... something.
1158 my $status = CustIDCK->custid_exist($webvar{custid});
1159 printAndExit("Error verifying customer ID: ".$CustIDCK::ErrMsg)
1160 if $CustIDCK::Error;
1161 printAndExit("Customer ID not valid. Make sure the Customer ID ".
1162 "is correct.<br>\nUse STAFF for staff static IPs, and 6750400 for any other ".
1163 "non-customer assignments.")
1164 if !$status;
1165#"Please enter a valid customer ID- this must be a 7- or 10-digit number, or STAFF for
1166#static IPs for staff.");
1167 }
1168# print "<!-- [ In validateInput(). Insert customer ID cross-check here. ] -->\n";
1169 } elsif ($webvar{alloctype} =~ /^([sdcmw]p|si|dn|dy|dc|ee|rr|ii)$/){
1170 # All non-customer allocations MUST be entered with "our" customer ID.
1171 # I have Defined this as 6750400 for consistency.
1172 # STAFF is also acceptable.
1173 if ((!$webvar{custid}) || ($webvar{custid} ne 'STAFF')) {
1174 $webvar{custid} = "6750400";
1175 }
1176 if ($webvar{alloctype} eq 'rr') {
1177 if ($webvar{city} !~ /^(?:Huntsville|North Bay|Ottawa|Pembroke|Sault Ste. Marie|Sudbury|Timmins|Thunder Bay|Toronto)$/) {
1178 printAndExit("Please choose a valid POP location for a routed netblock. Valid ".
1179 "POP locations are currently:<br>\n Elliot Lake - Huntsville - North Bay -".
1180 " Ottawa -".
1181 " Pembroke - Sault Ste. Marie - Sudbury - Timmins - Thunder Bay - Toronto");
1182 }
1183 }
1184 } else {
1185 # Danger! Danger! alloctype should ALWAYS be set by a dropdown. Anyone
1186 # managing to call things in such a way as to cause this deserves a cryptic error.
1187 printAndExit("Invalid alloctype");
1188 }
1189 return 0;
1190} # end validateInput
1191
1192
1193# Displays details of a specific allocation in a form
1194# Allows update/delete
1195# action=edit
1196sub edit {
1197 printHeader('');
1198
1199 my $sql;
1200
1201 # Two cases: block is a netblock, or block is a static IP from a pool
1202 # because I'm lazy, we'll try to make the SELECT's bring out identical)ish) data
1203 if ($webvar{block} =~ /\/32$/) {
1204 $sql = "select ip,custid,ptype,city,description,notes from poolips where ip='$webvar{block}'";
1205 } else {
1206 $sql = "select cidr,custid,type,city,description,notes from allocations where cidr='$webvar{block}'"
1207 }
1208
1209 # gotta snag block info from db
1210 $sth = $ip_dbh->prepare($sql);
1211 $sth->execute;
1212 my @data = $sth->fetchrow_array;
1213
1214 # Clean up extra whitespace on alloc type
1215 $data[2] =~ s/\s//;
1216
1217 # Postfix "i" on pool IP types
1218 if ($data[2] =~ /^[cdsm]$/) {
1219 $data[2] .= "i";
1220 }
1221
1222 open (HTML, "../editDisplay.html")
1223 or croak "Could not open editDisplay.html :$!";
1224 my $html = join('', <HTML>);
1225
1226 # We can't let the city be changed here; this block is a part of
1227 # a larger routed allocation and therefore by definition can't be moved.
1228 # block and city are static.
1229##fixme
1230# Needs thinking. Have to allow changes to city to correct errors, no?
1231 $html =~ s/\$\$BLOCK\$\$/$webvar{block}/g;
1232 $html =~ s/\$\$CITY\$\$/$data[3]/g;
1233
1234# Screw it. Changing allocation types gets very ugly VERY quickly- especially
1235# with the much longer list of allocation types.
1236# We'll just show what type of block it is.
1237
1238# this has now been Requested, so here goes.
1239
1240 if ($data[2] =~ /^d[nyc]|cn|ee|ii$/) {
1241 # Block that can be changed
1242 my $blockoptions = "<select name=alloctype><option".
1243 (($data[2] eq 'dn') ? ' selected' : '') ." value='dn'>Dialup netblock</option>\n<option".
1244 (($data[2] eq 'dy') ? ' selected' : '') ." value='dy'>Dynamic DSL netblock</option>\n<option".
1245 (($data[2] eq 'dc') ? ' selected' : '') ." value='dc'>Dynamic cable netblock</option>\n<option".
1246 (($data[2] eq 'cn') ? ' selected' : '') ." value='cn'>Customer netblock</option>\n<option".
1247 (($data[2] eq 'ee') ? ' selected' : '') ." value='ee'>End-use netblock</option>\n<option".
1248 (($data[2] eq 'ii') ? ' selected' : '') ." value='ii'>Internal netblock</option>\n".
1249 "</select>\n";
1250 $html =~ s/\$\$TYPESELECT\$\$/$blockoptions/g;
1251 } else {
1252 $html =~ s/\$\$TYPESELECT\$\$/$full_alloc_types{$data[2]}<input type=hidden name=alloctype value="$data[2]">/g;
1253 }
1254
1255 # These can be modified, although CustID changes may get ignored.
1256 $html =~ s/\$\$CUSTID\$\$/$data[1]/g;
1257 $html =~ s/\$\$DESC\$\$/$data[4]/g;
1258 $html =~ s/\$\$NOTES\$\$/$data[5]/g;
1259
1260 print $html;
1261
1262 printFooter();
1263} # edit()
1264
1265
1266# Stuff new info about a block into the db
1267# action=update
1268sub update {
1269 printHeader('');
1270
1271 # Make sure incoming data is in correct format - custID among other things.
1272 validateInput;
1273
1274 # SQL transaction wrapper
1275 eval {
1276 # Relatively simple SQL transaction here.
1277 my $sql;
1278 if (my $pooltype = ($webvar{alloctype} =~ /^([cdms])i$/) ) {
1279 $sql = "update poolips set custid='$webvar{custid}',".
1280 "notes='$webvar{notes}',description='$webvar{desc}' ".
1281 "where ip='$webvar{block}'";
1282 } else {
1283 $sql = "update allocations set custid='$webvar{custid}',".
1284 "description='$webvar{desc}',notes='$webvar{notes}',city='$webvar{city}',".
1285 "type='$webvar{alloctype}' where cidr='$webvar{block}'";
1286 }
1287syslog "debug", $sql;
1288 $sth = $ip_dbh->prepare($sql);
1289 $sth->execute;
1290 $ip_dbh->commit;
1291 };
1292 if ($@) {
1293 carp "Transaction aborted because $@";
1294 eval { $ip_dbh->rollback; };
1295 syslog "err", "$authuser could not update block/IP '$webvar{block}': '$@'";
1296 printAndExit("Could not update block/IP $webvar{block}: $@");
1297 }
1298
1299 # If we get here, the operation succeeded.
1300 syslog "notice", "$authuser updated $webvar{block}";
1301 open (HTML, "../updated.html")
1302 or croak "Could not open updated.html :$!";
1303 my $html = join('', <HTML>);
1304
1305 $html =~ s/\$\$BLOCK\$\$/$webvar{block}/g;
1306 $html =~ s/\$\$CITY\$\$/$webvar{city}/g;
1307 $html =~ s/\$\$ALLOCTYPE\$\$/$webvar{alloctype}/g;
1308 $html =~ s/\$\$TYPEFULL\$\$/$full_alloc_types{$webvar{alloctype}}/g;
1309 $html =~ s/\$\$CUSTID\$\$/$webvar{custid}/g;
1310 $html =~ s/\$\$DESC\$\$/$webvar{desc}/g;
1311 $html =~ s/\$\$NOTES\$\$/$webvar{notes}/g;
1312
1313 print $html;
1314
1315 printFooter;
1316} # update()
1317
1318
1319# Delete an allocation.
1320sub remove
1321{
1322 printHeader('');
1323 #show confirm screen.
1324 open HTML, "../confirmRemove.html"
1325 or croak "Could not open confirmRemove.html :$!";
1326 my $html = join('', <HTML>);
1327 close HTML;
1328
1329 # Serves'em right for getting here...
1330 if (!defined($webvar{block})) {
1331 printAndExit("Error 332");
1332 }
1333
1334 my ($cidr, $custid, $type, $city, $desc, $notes, $alloctype);
1335
1336 if ($webvar{alloctype} eq 'rr') {
1337 $sth = $ip_dbh->prepare("select cidr,city from routed where cidr='$webvar{block}'");
1338 $sth->execute();
1339
1340# This feels... extreme.
1341 croak $sth->errstr() if($sth->errstr());
1342
1343 $sth->bind_columns(\$cidr,\$city);
1344 $sth->execute();
1345 $sth->fetch || croak $sth->errstr();
1346 $custid = "N/A";
1347 $alloctype = $webvar{alloctype};
1348 $desc = "N/A";
1349 $notes = "N/A";
1350
1351 } elsif ($webvar{alloctype} eq 'mm') {
1352 $cidr = $webvar{block};
1353 $city = "N/A";
1354 $custid = "N/A";
1355 $alloctype = $webvar{alloctype};
1356 $desc = "N/A";
1357 $notes = "N/A";
1358 } elsif ($webvar{alloctype} =~ /^[sdcmw]i$/) { # done with alloctype=rr
1359
1360 # Unassigning a static IP
1361 my $sth = $ip_dbh->prepare("select ip,custid,city,ptype,notes from poolips".
1362 " where ip='$webvar{block}'");
1363 $sth->execute();
1364# croak $sth->errstr() if($sth->errstr());
1365
1366 $sth->bind_columns(\$cidr, \$custid, \$city, \$alloctype, \$notes);
1367 $sth->fetch() || croak $sth->errstr;
1368
1369 $alloctype .="i";
1370
1371 } else { # done with alloctype=[sdcmw]i
1372
1373 my $sth = $ip_dbh->prepare("select cidr,custid,type,city,description,notes from ".
1374 "allocations where cidr='$webvar{block}'");
1375 $sth->execute();
1376# croak $sth->errstr() if($sth->errstr());
1377
1378 $sth->bind_columns(\$cidr, \$custid, \$alloctype, \$city, \$desc, \$notes);
1379 $sth->fetch() || croak $sth->errstr;
1380 } # end cases for different alloctypes
1381
1382 # Munge everything into HTML
1383 $html =~ s|Please confirm|Please confirm <b>removal</b> of|;
1384 $html =~ s|\$\$BLOCK\$\$|$cidr|g;
1385 $html =~ s|\$\$TYPEFULL\$\$|$full_alloc_types{$alloctype}|g;
1386 $html =~ s|\$\$ALLOCTYPE\$\$|$alloctype|g;
1387 $html =~ s|\$\$CITY\$\$|$city|g;
1388 $html =~ s|\$\$CUSTID\$\$|$custid|g;
1389 $html =~ s|\$\$DESC\$\$|$desc|g;
1390 $html =~ s|\$\$NOTES\$\$|$notes|g;
1391
1392 $html =~ s|\$\$ACTION\$\$|finaldelete|g;
1393
1394 # Set the warning text.
1395 if ($alloctype =~ /^[sdcmw]p$/) {
1396 $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>|;
1397 } else {
1398 $html =~ s|<!--warn-->|<tr bgcolor="black"><td colspan="2"><div class="red">Warning: clicking confirm will remove this record entirely.</div></td></tr>|;
1399 }
1400
1401 print $html;
1402 printFooter;
1403} # end edit()
1404
1405
1406# Delete an allocation. Return it to the freeblocks table; munge
1407# data as necessary to keep as few records as possible in freeblocks
1408# to prevent weirdness when allocating blocks later.
1409# Remove IPs from pool listing if necessary
1410sub finalDelete {
1411 printHeader('');
1412
1413 # Enable transactions and exception-on-errors... but only for this sub
1414 local $ip_dbh->{AutoCommit} = 0;
1415 local $ip_dbh->{RaiseError} = 1;
1416
1417 if ($webvar{alloctype} =~ /^[sdcmw]i$/) {
1418
1419 eval {
1420 $sth = $ip_dbh->prepare("select * from poolips where ip='$webvar{block}'");
1421 $sth->execute;
1422 my @data = $sth->fetchrow_array;
1423 $sth = $ip_dbh->prepare("select city from allocations where cidr='$data[0]'");
1424 $sth->execute;
1425 @data = $sth->fetchrow_array;
1426 $sth = $ip_dbh->prepare("update poolips set custid='6750400', available='y',".
1427 " city='$data[0]', description='' where ip='$webvar{block}'");
1428 $sth->execute;
1429 $ip_dbh->commit;
1430 };
1431 if ($@) {
1432 carp "Transaction aborted because $@";
1433 eval { $ip_dbh->rollback; };
1434 syslog "err", "$authuser could not deallocate static IP '$webvar{block}': '$@'";
1435 printAndExit("Could not deallocate static IP $webvar{block}: $@");
1436 }
1437 print "<div class=heading align=center>Success! $webvar{block} deallocated.</div>\n";
1438 syslog "notice", "$authuser deallocated static IP $webvar{block}";
1439
1440 } elsif ($webvar{alloctype} eq 'mm') { # end alloctype = [sdcmw]i
1441
1442 eval {
1443 $sth = $ip_dbh->prepare("delete from masterblocks where cidr='$webvar{block}'");
1444 $sth->execute;
1445 $sth = $ip_dbh->prepare("delete from freeblocks where cidr='$webvar{block}'");
1446 $sth->execute;
1447 $ip_dbh->commit;
1448 };
1449 if ($@) {
1450 carp "Transaction aborted because $@";
1451 eval { $ip_dbh->rollback; };
1452 syslog "err", "$authuser could not remove master block '$webvar{block}': '$@'";
1453 printAndExit("Could not remove master block $webvar{block}: $@");
1454 }
1455 print "<div class=heading align=center>Success! Master $webvar{block} removed.</div>\n";
1456 syslog "notice", "$authuser removed master block $webvar{block}";
1457
1458 } else { # end alloctype master block case
1459
1460 ## This is a big block; but it HAS to be done in a chunk. Any removal
1461 ## of a netblock allocation may result in a larger chunk of free
1462 ## contiguous IP space - which may in turn be combined into a single
1463 ## netblock rather than a number of smaller netblocks.
1464
1465 eval {
1466
1467 my $cidr = new NetAddr::IP $webvar{block};
1468 if ($webvar{alloctype} eq 'rr') {
1469
1470 $sth = $ip_dbh->prepare("delete from routed where cidr='$webvar{block}'");
1471 $sth->execute;
1472 # Make sure block getting deleted is properly accounted for.
1473 $sth = $ip_dbh->prepare("update freeblocks set routed='n',city='<NULL>'".
1474 " where cidr='$webvar{block}'");
1475 $sth->execute;
1476 # Set up query to start compacting free blocks.
1477 $sth = $ip_dbh->prepare("select * from freeblocks where ".
1478 "maskbits<=".$cidr->masklen." and routed='n' order by maskbits desc");
1479
1480 } else { # end alloctype routing case
1481
1482 $sth = $ip_dbh->prepare("delete from allocations where cidr='$webvar{block}'");
1483 $sth->execute;
1484 # Special case - delete pool IPs
1485 if ($webvar{alloctype} =~ /^[sdcmw]p$/) {
1486 # We have to delete the IPs from the pool listing.
1487 $sth = $ip_dbh->prepare("delete from poolips where pool='$webvar{block}'");
1488 $sth->execute;
1489 }
1490
1491 # Set up query for compacting free blocks.
1492 $sth = $ip_dbh->prepare("select * from freeblocks where cidr << ".
1493 "(select cidr from routed where cidr >> '$cidr') ".
1494 " and maskbits<=".$cidr->masklen." and routed='y' order by maskbits desc");
1495
1496 } # end alloctype general case
1497
1498 # Now we look for larger-or-equal-sized free blocks in the same master (routed)
1499 # (super)block. If there aren't any, we can't combine blocks anyway. If there
1500 # are, we check to see if we can combine blocks.
1501 # Execute the statement prepared in the if-else above.
1502
1503 $sth->execute;
1504
1505# NetAddr::IP->compact() attempts to produce the smallest inclusive block
1506# from the caller and the passed terms.
1507# EG: if you call $cidr->compact($ip1,$ip2,$ip3) when $cidr, $ip1, $ip2,
1508# and $ip3 are consecutive /27's starting on .0 (.0-.31, .32-.63,
1509# .64-.95, and .96-.128), you will get an array containing a single
1510# /25 as element 0 (.0-.127). Order is not important; you could have
1511# $cidr=.32/27, $ip1=.96/27, $ip2=.0/27, and $ip3=.64/27.
1512
1513 my (@together, @combinelist);
1514 my $i=0;
1515 while (my @data = $sth->fetchrow_array) {
1516 my $testIP = new NetAddr::IP $data[0];
1517 @together = $testIP->compact($cidr);
1518 my $num = @together;
1519 if ($num == 1) {
1520 $cidr = $together[0];
1521 $combinelist[$i++] = $testIP;
1522 }
1523 }
1524
1525 # Clear old freeblocks entries - if any. $i==0 if not.
1526 if ($i>0) {
1527 $sth = $ip_dbh->prepare("delete from freeblocks where cidr=?");
1528 foreach my $block (@combinelist) {
1529 $sth->execute("$block");
1530 }
1531 }
1532
1533 # insert "new" freeblocks entry
1534 if ($webvar{alloctype} eq 'rr') {
1535 $sth = $ip_dbh->prepare("insert into freeblocks values ('$cidr',".$cidr->masklen.
1536 ",'<NULL>','n')");
1537 } else {
1538 $sth = $ip_dbh->prepare("insert into freeblocks values ('$cidr',".$cidr->masklen.
1539 ",(select city from routed where cidr >>= '$cidr'),'y')");
1540 }
1541 $sth->execute;
1542
1543 # If we got here, we've succeeded. Whew!
1544 $ip_dbh->commit;
1545 }; # end eval
1546 if ($@) {
1547 carp "Transaction aborted because $@";
1548 eval { $ip_dbh->rollback; };
1549 syslog "err", "$authuser could not deallocate netblock '$webvar{block}': '$@'";
1550 printAndExit("Could not deallocate netblock $webvar{block}: $@");
1551 }
1552 print "<div class=heading align=center>Success! $webvar{block} deleted.</div>\n";
1553 syslog "notice", "$authuser deallocated '$webvar{alloctype}'-type netblock $webvar{block}";
1554
1555 } # end alloctype != netblock
1556
1557 printFooter;
1558} # finalDelete
1559
1560
1561# Just in case we manage to get here.
1562exit 0;
Note: See TracBrowser for help on using the repository browser.