source: branches/stable/cgi-bin/IPDB.pm@ 134

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

/branches/stable

Bugfix for missing IP in static-IP allocation notifications.

-> Watch out for localizing variables that need to carry outside

of the local scope!

  • Property svn:keywords set to Date Rev Author
File size: 17.7 KB
RevLine 
[8]1# ipdb/cgi-bin/IPDB.pm
[71]2# Contains functions for IPDB - database access, subnet mangling, block allocation, etc
[8]3###
4# SVN revision info
5# $Date: 2005-01-21 17:31:49 +0000 (Fri, 21 Jan 2005) $
6# SVN revision $Rev: 132 $
7# Last update by $Author: kdeugau $
8###
[71]9# Copyright (C) 2004 - Kris Deugau
[8]10
[4]11package IPDB;
12
13use strict;
14use warnings;
15use Exporter;
[125]16use DBI;
[71]17use Net::SMTP;
18use POSIX;
[4]19use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
20
[125]21$VERSION = 2.0;
[4]22@ISA = qw(Exporter);
[125]23@EXPORT_OK = qw(
24 %disp_alloctypes %list_alloctypes @citylist @poplist @masterblocks
25 %allocated %free %routed %bigfree
26 &initIPDBGlobals &connectDB &finish &checkDBSanity &allocateBlock &deleteBlock
27 &mailNotify
28 );
[4]29
30@EXPORT = (); # Export nothing by default.
[125]31%EXPORT_TAGS = ( ALL => [qw(
32 %disp_alloctypes %list_alloctypes @citylist @poplist @masterblocks
33 %allocated %free %routed %bigfree
34 &initIPDBGlobals &connectDB &finish &checkDBSanity &allocateBlock
35 &deleteBlock &mailNotify
36 )]
37 );
[4]38
[125]39##
40## Global variables
41##
42our %disp_alloctypes;
43our %list_alloctypes;
44our @citylist;
45our @poplist;
46our @masterblocks;
47our %allocated;
48our %free;
49our %routed;
50our %bigfree;
[71]51
[125]52# Let's initialize the globals.
53## IPDB::initIPDBGlobals()
54# Initialize all globals. Takes a database handle, returns a success or error code
55sub initIPDBGlobals {
56 my $dbh = $_[0];
57 my $sth;
58
59 # Initialize alloctypes hashes
60 $sth = $dbh->prepare("select * from alloctypes order by listorder");
61 $sth->execute;
62 while (my @data = $sth->fetchrow_array) {
63 $disp_alloctypes{$data[0]} = $data[2];
64 if ($data[3] < 900) {
65 $list_alloctypes{$data[0]} = $data[1];
66 }
67 }
68
69 # City and POP listings
[129]70 $sth = $dbh->prepare("select * from cities order by city");
[125]71 $sth->execute;
72 return (undef,$sth->errstr) if $sth->err;
73 while (my @data = $sth->fetchrow_array) {
74 push @citylist, $data[0];
75 if ($data[1] eq 'y') {
76 push @poplist, $data[0];
77 }
78 }
79
80 # Master block list
81 $sth = $dbh->prepare("select * from masterblocks order by cidr");
82 $sth->execute;
83 for (my $i=0; my @data = $sth->fetchrow_array(); $i++) {
84 $masterblocks[$i] = new NetAddr::IP $data[0];
85 $allocated{"$masterblocks[$i]"} = 0;
86 $free{"$masterblocks[$i]"} = 0;
87 $bigfree{"$masterblocks[$i]"} = 128; # Larger number means smaller block.
88 # Set to 128 to prepare for IPv6
89 $routed{"$masterblocks[$i]"} = 0;
90 }
91 return (undef,$sth->errstr) if $sth->err;
92
93 return (1,"OK");
94} # end initIPDBGlobals
95
96
97## IPDB::connectDB()
[4]98# Creates connection to IPDB.
[125]99# Requires the database name, username, and password.
[4]100# Returns a handle to the db.
[125]101# Set up for a PostgreSQL db; could be any transactional DBMS with the
102# right changes.
103# This definition should be sub connectDB($$$) to be technically correct,
104# but this breaks. GRR.
[4]105sub connectDB {
[125]106 my ($dbname,$user,$pass) = @_;
[4]107 my $dbh;
[125]108 my $DSN = "DBI:Pg:dbname=$dbname";
109# my $user = 'ipdb';
110# my $pw = 'ipdbpwd';
[4]111
112# Note that we want to autocommit by default, and we will turn it off locally as necessary.
[125]113# We may not want to print gobbledygook errors; YMMV. Have to ponder that further.
114 $dbh = DBI->connect($DSN, $user, $pass, {
115 AutoCommit => 1,
116 PrintError => 0
117 })
118 or return (undef, $DBI::errstr) if(!$dbh);
[4]119
[125]120# Return here if we can't select. Note that this indicates a
121# problem executing the select.
122 my $sth = $dbh->prepare('select cidr from masterblocks');
123 $sth->execute();
124 return (undef,$DBI::errstr) if ($sth->err);
125
126# See if the select returned anything (or null data). This should
127# succeed if the select executed, but...
128 $sth->fetchrow();
129 return (undef,$DBI::errstr) if ($sth->err);
130
131# If we get here, we should be OK.
132 return ($dbh,"DB connection OK");
[4]133} # end connectDB
134
[125]135
136## IPDB::finish()
137# Cleans up after database handles and so on.
138# Requires a database handle
139sub finish {
140 my $dbh = $_[0];
141 $dbh->disconnect;
142} # end finish
143
144
145## IPDB::checkDBSanity()
[4]146# Quick check to see if the db is responding. A full integrity
147# check will have to be a separate tool to walk the IP allocation trees.
148sub checkDBSanity {
[125]149 my ($dbh) = $_[0];
[4]150
151 if (!$dbh) {
[125]152 print "No database handle, or connection has been closed.";
153 return -1;
[4]154 } else {
155 # it connects, try a stmt.
156 my $sth = $dbh->prepare('select cidr from masterblocks');
157 my $err = $sth->execute();
158
159 if ($sth->fetchrow()) {
160 # all is well.
161 return 1;
162 } else {
[16]163 print "Connected to the database, but could not execute test statement. ".$sth->errstr();
[125]164 return -1;
[4]165 }
166 }
167 # Clean up after ourselves.
[125]168# $dbh->disconnect;
[4]169} # end checkDBSanity
170
[71]171
[125]172## IPDB::allocateBlock()
[71]173# Does all of the magic of actually allocating a netblock
[125]174# Requires database handle, block to allocate, custid, type, city,
175# description, notes, circuit ID, block to allocate from,
176# Returns a success code and optional error message.
177sub allocateBlock {
178 my ($dbh,undef,undef,$custid,$type,$city,$desc,$notes,$circid) = @_;
179
180 my $cidr = new NetAddr::IP $_[1];
181 my $alloc_from = new NetAddr::IP $_[2];
182 my $sth;
[71]183
[125]184 # To contain the error message, if any.
185 my $msg = "Unknown error allocating $cidr as '$type'";
[71]186
[125]187 # Enable transactions and error handling
188 local $dbh->{AutoCommit} = 0; # These need to be local so we don't
189 local $dbh->{RaiseError} = 1; # step on our toes by accident.
190
191 if ($type =~ /^[cdsmw]i$/) {
192 $msg = "Unable to assign static IP $cidr to $custid";
193 eval {
194 # We'll just have to put up with the oddities caused by SQL (un)sort order
195 $sth = $dbh->prepare("select * from poolips where pool='$alloc_from'".
196 " and available='y' order by ip");
197 $sth->execute;
198
199# update poolips set custid='$custid',city='$city',available='n',
200# description='$desc',notes='$notes',circuitid='$circid'
201# where ip=(select ip from poolips where pool='$alloc_from'
202# and available='y' order by ip limit 1);
203##err Need better handling here; what if there's no free IPs when this sub gets called?
204 my @data = $sth->fetchrow_array;
[132]205 $cidr = $data[1]; # $cidr is already declared when we get here!
[125]206
207 $sth = $dbh->prepare("update poolips set custid='$custid',".
208 "city='$city',available='n',description='$desc',notes='$notes',".
209 "circuitid='$circid'".
210 " where ip='$cidr'");
211 $sth->execute;
212 $dbh->commit;
213 };
214 if ($@) {
215 $msg .= ": '".$sth->errstr."'";
216 eval { $dbh->rollback; };
217 return ('FAIL',$msg);
218 } else {
219 return ('OK',"$cidr");
220 }
221
222 } else { # end IP-from-pool allocation
223
224 if ($cidr == $alloc_from) {
225 # Easiest case- insert in one table, delete in the other, and go home. More or less.
226 # insert into allocations values (cidr,custid,type,city,desc) and
227 # delete from freeblocks where cidr='cidr'
228 # For data safety on non-transaction DBs, we delete first.
229
230 eval {
231 $msg = "Unable to allocate $cidr as '$disp_alloctypes{$type}'";
232 if ($type eq 'rr') {
233 $sth = $dbh->prepare("update freeblocks set routed='y',city='$city'".
234 " where cidr='$cidr'");
235 $sth->execute;
236 $sth = $dbh->prepare("insert into routed values ('$cidr',".
237 $cidr->masklen.",'$city')");
238 $sth->execute;
239 } else {
240 # common stuff for end-use, dialup, dynDSL, pools, etc, etc.
241 $sth = $dbh->prepare("delete from freeblocks where cidr='$cidr'");
242 $sth->execute;
243
244 $sth = $dbh->prepare("insert into allocations values ('$cidr',".
245 "'$custid','$type','$city','$desc','$notes',".
246 $cidr->masklen.",'$circid')");
247 $sth->execute;
248
249 # And initialize the pool, if necessary
250 if ($type =~ /^.p$/) {
251 $msg = "Could not initialize IPs in new $disp_alloctypes{$type} pool $cidr";
252 initPool($dbh,$cidr,$type,$city,($type eq 'dp' ? "all" : "normal"));
253 }
254
255 } # routing vs non-routing netblock
256
257 $dbh->commit;
258 }; # end of eval
259 if ($@) {
260 $msg = $@;
261 eval { $dbh->rollback; };
262 return ('FAIL',$@);
263 } else {
264 return ('OK',"OK");
265 }
266
267 } else { # cidr != alloc_from
268
269 # Hard case. Allocation is smaller than free block.
270 my $wantmaskbits = $cidr->masklen;
271 my $maskbits = $alloc_from->masklen;
272
273 my @newfreeblocks; # Holds free blocks generated from splitting the source freeblock.
274
275 # This determines which blocks will be left "free" after allocation. We take the
276 # block we're allocating from, and split it in half. We see which half the wanted
277 # block is in, and repeat until the wanted block is equal to one of the halves.
278 my $i=0;
279 my $tmp_from = $alloc_from; # So we don't munge $alloc_from
280 while ($maskbits++ < $wantmaskbits) {
281 my @subblocks = $tmp_from->split($maskbits);
282 $newfreeblocks[$i++] = (($cidr->within($subblocks[0])) ? $subblocks[1] : $subblocks[0]);
283 $tmp_from = ( ($cidr->within($subblocks[0])) ? $subblocks[0] : $subblocks[1] );
284 } # while
285
286 # Begin SQL transaction block
287 eval {
288 $msg = "Unable to allocate $cidr as '$disp_alloctypes{$type}'";
289
290 # Delete old freeblocks entry
291 $sth = $dbh->prepare("delete from freeblocks where cidr='$alloc_from'");
292 $sth->execute();
293
294 # now we have to do some magic for routing blocks
295 if ($type eq 'rr') {
296
297 # Insert the new freeblocks entries
298 # Note that non-routed blocks are assigned to <NULL>
299 $sth = $dbh->prepare("insert into freeblocks values (?, ?, '<NULL>','n')");
300 foreach my $block (@newfreeblocks) {
301 $sth->execute("$block", $block->masklen);
302 }
303
304 # Insert the entry in the routed table
305 $sth = $dbh->prepare("insert into routed values ('$cidr',".
306 $cidr->masklen.",'$city')");
307 $sth->execute;
308 # Insert the (almost) same entry in the freeblocks table
309 $sth = $dbh->prepare("insert into freeblocks values ('$cidr',".
310 $cidr->masklen.",'$city','y')");
311 $sth->execute;
312
313 } else { # done with alloctype == rr
314
315 # Insert the new freeblocks entries
316 $sth = $dbh->prepare("insert into freeblocks values (?, ?, ".
317 "(select city from routed where cidr >>= '$cidr'),'y')");
318 foreach my $block (@newfreeblocks) {
319 $sth->execute("$block", $block->masklen);
320 }
321
322 # Insert the allocations entry
323 $sth = $dbh->prepare("insert into allocations values ('$cidr',".
324 "'$custid','$type','$city','$desc','$notes',".$cidr->masklen.
325 ",'$circid')");
326 $sth->execute;
327
328 # And initialize the pool, if necessary
329 if ($type =~ /^.p$/) {
330 $msg = "Could not initialize IPs in new $disp_alloctypes{$type} $cidr";
331 initPool($dbh,$cidr,$type,$city,($type eq 'dp' ? "all" : "normal"));
332 }
333
334 } # done with netblock alloctype != rr
335
336 $dbh->commit;
337 }; # end eval
338 if ($@) {
339 eval { $dbh->rollback; };
340 return ('FAIL',$msg);
341 } else {
342 return ('OK',"OK");
343 }
344
345 } # end fullcidr != alloc_from
346
347 } # end static-IP vs netblock allocation
348
349} # end allocateBlock()
350
351
352## IPDB::initPool()
353# Initializes a pool
354# Requires a database handle, the pool CIDR, type, city, and a parameter
355# indicating whether the pool should allow allocation of literally every
356# IP, or if it should reserve network/gateway/broadcast IPs
357# Note that this is NOT done in a transaction, that's why it's a private
358# function and should ONLY EVER get called from allocateBlock()
359sub initPool {
360 my ($dbh,undef,$type,$city,$class) = @_;
361 my $pool = new NetAddr::IP $_[1];
362
363 my ($pooltype) = ($type =~ /^(.)p$/);
364 my $sth;
365
366 # have to insert all pool IPs into poolips table as "unallocated".
367 $sth = $dbh->prepare("insert into poolips values ('$pool',".
368 " ?, '6750400', '$city', '$pooltype', 'y', '', '', '')");
369 my @poolip_list = $pool->hostenum;
370 if ($class eq 'all') { # (DSL-ish block - *all* IPs available
371 $sth->execute($pool->addr);
372 for (my $i=0; $i<=$#poolip_list; $i++) {
373 $sth->execute($poolip_list[$i]->addr);
374 }
375 $pool--;
376 $sth->execute($pool->addr);
377 } else { # (real netblock)
378 for (my $i=1; $i<=$#poolip_list; $i++) {
379 $sth->execute($poolip_list[$i]->addr);
380 }
381 }
382} # end initPool()
383
384
385## IPDB::deleteBlock()
386# Removes an allocation from the database, including deleting IPs
387# from poolips and recombining entries in freeblocks if possible
388# Also handles "deleting" a static IP allocation, and removal of a master
389# Requires a database handle, the block to delete, and the type of block
390sub deleteBlock {
391 my ($dbh,undef,$type) = @_;
392 my $cidr = new NetAddr::IP $_[1];
393
394 my $sth;
395
396 # To contain the error message, if any.
397 my $msg = "Unknown error deallocating $type $cidr";
398 # Enable transactions and exception-on-errors... but only for this sub
399 local $dbh->{AutoCommit} = 0;
400 local $dbh->{RaiseError} = 1;
401
402 # First case. The "block" is a static IP
403 # Note that we still need some additional code in the odd case
404 # of a netblock-aligned contiguous group of static IPs
405 if ($type =~ /^.i$/) {
406
407 eval {
408 $msg = "Unable to deallocate $type $cidr";
409 $sth = $dbh->prepare("update poolips set custid='6750400',available='y',".
410 "city=(select city from allocations where cidr >>= '$cidr'),".
411 "description='',notes='',circuitid='' where ip='$cidr'");
412 $sth->execute;
413 $dbh->commit;
414 };
415 if ($@) {
416 eval { $dbh->rollback; };
417 return ('FAIL',$msg);
418 } else {
419 return ('OK',"OK");
420 }
421
422 } elsif ($type eq 'mm') { # end alloctype =~ /.i/
423
424 $msg = "Unable to delete master block $cidr";
425 eval {
426 $sth = $dbh->prepare("delete from masterblocks where cidr='$cidr'");
427 $sth->execute;
428 $sth = $dbh->prepare("delete from freeblocks where cidr='$cidr'");
429 $sth->execute;
430 $dbh->commit;
431 };
432 if ($@) {
433 eval { $dbh->rollback; };
434 return ('FAIL', $msg);
435 } else {
436 return ('OK',"OK");
437 }
438
439 } else { # end alloctype master block case
440
441 ## This is a big block; but it HAS to be done in a chunk. Any removal
442 ## of a netblock allocation may result in a larger chunk of free
443 ## contiguous IP space - which may in turn be combined into a single
444 ## netblock rather than a number of smaller netblocks.
445
446 eval {
447
448 if ($type eq 'rr') {
449 $msg = "Unable to remove routing allocation $cidr";
450 $sth = $dbh->prepare("delete from routed where cidr='$cidr'");
451 $sth->execute;
452 # Make sure block getting deleted is properly accounted for.
453 $sth = $dbh->prepare("update freeblocks set routed='n',city='<NULL>'".
454 " where cidr='$cidr'");
455 $sth->execute;
456 # Set up query to start compacting free blocks.
457 $sth = $dbh->prepare("select * from freeblocks where ".
458 "maskbits<=".$cidr->masklen." and routed='n' order by maskbits desc");
459
460 } else { # end alloctype routing case
461
462 $sth = $dbh->prepare("delete from allocations where cidr='$cidr'");
463 $sth->execute;
464 # Special case - delete pool IPs
465 if ($type =~ /^.p$/) {
466 # We have to delete the IPs from the pool listing.
467 $sth = $dbh->prepare("delete from poolips where pool='$cidr'");
468 $sth->execute;
469 }
470
471 # Set up query for compacting free blocks.
472 $sth = $dbh->prepare("select * from freeblocks where cidr <<= ".
473 "(select cidr from routed where cidr >>= '$cidr') ".
474 " and maskbits<=".$cidr->masklen." and routed='y' order by maskbits desc");
475
476 } # end alloctype general case
477
[126]478##TEMP
479## Temporary wrapper to "properly" deallocate sIP PPPoE/DSL "netblocks" in 209.91.185.0/24
480## Note that we should really general-case this.
481my $staticpool = new NetAddr::IP "209.91.185.0/24";
482##TEMP
483if ($cidr->within($staticpool)) {
484##TEMP
485 # We've already deleted the block, now we have to stuff its IPs into the pool.
[127]486 $sth = $dbh->prepare("insert into poolips values ('209.91.185.0/24',?,'6750400','Sudbury','d','y','','','')");
[126]487 $sth->execute($cidr->addr);
488 foreach my $ip ($cidr->hostenum) {
489 $sth->execute("$ip");
490 }
491 $cidr--;
492 $sth->execute($cidr->addr);
493
494##TEMP
495} else {
496##TEMP
497
[125]498 # Now we look for larger-or-equal-sized free blocks in the same master (routed)
499 # (super)block. If there aren't any, we can't combine blocks anyway. If there
500 # are, we check to see if we can combine blocks.
501 # Execute the statement prepared in the if-else above.
502
503 $sth->execute;
504
505# NetAddr::IP->compact() attempts to produce the smallest inclusive block
506# from the caller and the passed terms.
507# EG: if you call $cidr->compact($ip1,$ip2,$ip3) when $cidr, $ip1, $ip2,
508# and $ip3 are consecutive /27's starting on .0 (.0-.31, .32-.63,
509# .64-.95, and .96-.128), you will get an array containing a single
510# /25 as element 0 (.0-.127). Order is not important; you could have
511# $cidr=.32/27, $ip1=.96/27, $ip2=.0/27, and $ip3=.64/27.
512
513 my (@together, @combinelist);
514 my $i=0;
515 while (my @data = $sth->fetchrow_array) {
516 my $testIP = new NetAddr::IP $data[0];
517 @together = $testIP->compact($cidr);
518 my $num = @together;
519 if ($num == 1) {
520 $cidr = $together[0];
521 $combinelist[$i++] = $testIP;
522 }
523 }
524
525 # Clear old freeblocks entries - if any. $i==0 if not.
526 if ($i>0) {
527 $sth = $dbh->prepare("delete from freeblocks where cidr=?");
528 foreach my $block (@combinelist) {
529 $sth->execute("$block");
530 }
531 }
532
533 # insert "new" freeblocks entry
534 if ($type eq 'rr') {
535 $sth = $dbh->prepare("insert into freeblocks values ('$cidr',".$cidr->masklen.
536 ",'<NULL>','n')");
537 } else {
538 $sth = $dbh->prepare("insert into freeblocks values ('$cidr',".$cidr->masklen.
539 ",(select city from routed where cidr >>= '$cidr'),'y')");
540 }
541 $sth->execute;
542
[126]543##TEMP
544}
545##TEMP
546
[125]547 # If we got here, we've succeeded. Whew!
548 $dbh->commit;
549 }; # end eval
550 if ($@) {
551 eval { $dbh->rollback; };
552 return ('FAIL', $msg);
553 } else {
554 return ('OK',"OK");
555 }
556
557 } # end alloctype != netblock
558
559} # end deleteBlock()
560
561
562## IPDB::mailNotify()
[71]563# Sends notification mail to recipients regarding an IPDB operation
564sub mailNotify ($$$) {
565 my ($recip,$subj,$message) = @_;
566 my $mailer = Net::SMTP->new("smtp.example.com", Hello => "ipdb.example.com");
567
568 $mailer->mail('ipdb@example.com');
569 $mailer->to($recip);
570 $mailer->data("From: \"IP Database\" <ipdb\@example.com>\n",
[131]571 "To: $recip\n",
[71]572 "Date: ".strftime("%a, %d %b %Y %H:%M:%S %z",localtime)."\n",
573 "Subject: {IPDB} $subj\n",
574 "X-Mailer: IPDB Notify v".sprintf("%.1d",$IPDB::VERSION)."\n",
575 "Organization: Example Corp\n",
576 "\n$message\n");
577 $mailer->quit;
578}
579
[4]580# Indicates module loaded OK. Required by Perl.
5811;
Note: See TracBrowser for help on using the repository browser.