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

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

/branches/stable

Removed full_alloc_types hash definition
Cleaned up comments on globals

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