source: trunk/cgi-bin/IPDB.pm@ 374

Last change on this file since 374 was 371, checked in by Kris Deugau, 17 years ago

/trunk

Merge bugfixes and enhancements from /branches/stable r360 through r369

  • Property svn:keywords set to Date Rev Author
File size: 25.8 KB
RevLine 
[8]1# ipdb/cgi-bin/IPDB.pm
[66]2# Contains functions for IPDB - database access, subnet mangling, block allocation, etc
[8]3###
4# SVN revision info
5# $Date: 2007-11-27 17:27:45 +0000 (Tue, 27 Nov 2007) $
6# SVN revision $Rev: 371 $
7# Last update by $Author: kdeugau $
8###
[320]9# Copyright (C) 2004-2006 - Kris Deugau
[8]10
[4]11package IPDB;
12
13use strict;
14use warnings;
15use Exporter;
[77]16use DBI;
[66]17use Net::SMTP;
[371]18use NetAddr::IP qw( Compact );
[68]19use POSIX;
[4]20use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
21
[77]22$VERSION = 2.0;
[4]23@ISA = qw(Exporter);
[106]24@EXPORT_OK = qw(
[167]25 %disp_alloctypes %list_alloctypes %def_custids @citylist @poplist @masterblocks
[233]26 %allocated %free %routed %bigfree %IPDBacl
[371]27 &initIPDBGlobals &connectDB &finish &checkDBSanity &allocateBlock &addMaster
28 &deleteBlock &getBlockData &mailNotify
[106]29 );
[4]30
31@EXPORT = (); # Export nothing by default.
[106]32%EXPORT_TAGS = ( ALL => [qw(
[167]33 %disp_alloctypes %list_alloctypes %def_custids @citylist @poplist
[233]34 @masterblocks %allocated %free %routed %bigfree %IPDBacl
[106]35 &initIPDBGlobals &connectDB &finish &checkDBSanity &allocateBlock
[371]36 &addMaster &deleteBlock &getBlockData &mailNotify
[106]37 )]
38 );
[4]39
[77]40##
41## Global variables
42##
43our %disp_alloctypes;
44our %list_alloctypes;
[167]45our %def_custids;
[96]46our @citylist;
47our @poplist;
[106]48our @masterblocks;
[118]49our %allocated;
50our %free;
51our %routed;
52our %bigfree;
[233]53our %IPDBacl;
[66]54
[77]55# Let's initialize the globals.
56## IPDB::initIPDBGlobals()
57# Initialize all globals. Takes a database handle, returns a success or error code
58sub initIPDBGlobals {
59 my $dbh = $_[0];
60 my $sth;
61
[106]62 # Initialize alloctypes hashes
[167]63 $sth = $dbh->prepare("select type,listname,dispname,listorder,def_custid from alloctypes order by listorder");
[77]64 $sth->execute;
65 while (my @data = $sth->fetchrow_array) {
[106]66 $disp_alloctypes{$data[0]} = $data[2];
[167]67 $def_custids{$data[0]} = $data[4];
[106]68 if ($data[3] < 900) {
69 $list_alloctypes{$data[0]} = $data[1];
70 }
[77]71 }
[96]72
73 # City and POP listings
[157]74 $sth = $dbh->prepare("select city,routing from cities order by city");
[96]75 $sth->execute;
76 return (undef,$sth->errstr) if $sth->err;
77 while (my @data = $sth->fetchrow_array) {
[106]78 push @citylist, $data[0];
[96]79 if ($data[1] eq 'y') {
[106]80 push @poplist, $data[0];
[96]81 }
82 }
83
[106]84 # Master block list
[157]85 $sth = $dbh->prepare("select cidr from masterblocks order by cidr");
[106]86 $sth->execute;
[233]87 return (undef,$sth->errstr) if $sth->err;
[106]88 for (my $i=0; my @data = $sth->fetchrow_array(); $i++) {
89 $masterblocks[$i] = new NetAddr::IP $data[0];
[118]90 $allocated{"$masterblocks[$i]"} = 0;
91 $free{"$masterblocks[$i]"} = 0;
92 $bigfree{"$masterblocks[$i]"} = 128; # Larger number means smaller block.
93 # Set to 128 to prepare for IPv6
94 $routed{"$masterblocks[$i]"} = 0;
[106]95 }
[233]96
97 # Load ACL data. Specific username checks are done at a different level.
98 $sth = $dbh->prepare("select username,acl from users");
99 $sth->execute;
[106]100 return (undef,$sth->errstr) if $sth->err;
[233]101 while (my @data = $sth->fetchrow_array) {
102 $IPDBacl{$data[0]} = $data[1];
103 }
[106]104
[77]105 return (1,"OK");
106} # end initIPDBGlobals
107
108
109## IPDB::connectDB()
[4]110# Creates connection to IPDB.
[77]111# Requires the database name, username, and password.
[4]112# Returns a handle to the db.
[77]113# Set up for a PostgreSQL db; could be any transactional DBMS with the
114# right changes.
115# This definition should be sub connectDB($$$) to be technically correct,
116# but this breaks. GRR.
[4]117sub connectDB {
[77]118 my ($dbname,$user,$pass) = @_;
[4]119 my $dbh;
[77]120 my $DSN = "DBI:Pg:dbname=$dbname";
121# my $user = 'ipdb';
122# my $pw = 'ipdbpwd';
[4]123
124# Note that we want to autocommit by default, and we will turn it off locally as necessary.
[77]125# We may not want to print gobbledygook errors; YMMV. Have to ponder that further.
126 $dbh = DBI->connect($DSN, $user, $pass, {
127 AutoCommit => 1,
128 PrintError => 0
129 })
130 or return (undef, $DBI::errstr) if(!$dbh);
[4]131
[77]132# Return here if we can't select. Note that this indicates a
133# problem executing the select.
[183]134 my $sth = $dbh->prepare("select type from alloctypes");
[77]135 $sth->execute();
136 return (undef,$DBI::errstr) if ($sth->err);
137
138# See if the select returned anything (or null data). This should
139# succeed if the select executed, but...
140 $sth->fetchrow();
141 return (undef,$DBI::errstr) if ($sth->err);
142
143# If we get here, we should be OK.
144 return ($dbh,"DB connection OK");
[4]145} # end connectDB
146
[77]147
148## IPDB::finish()
149# Cleans up after database handles and so on.
150# Requires a database handle
151sub finish {
152 my $dbh = $_[0];
153 $dbh->disconnect;
154} # end finish
155
156
[106]157## IPDB::checkDBSanity()
[4]158# Quick check to see if the db is responding. A full integrity
159# check will have to be a separate tool to walk the IP allocation trees.
160sub checkDBSanity {
[106]161 my ($dbh) = $_[0];
[4]162
163 if (!$dbh) {
[106]164 print "No database handle, or connection has been closed.";
165 return -1;
[4]166 } else {
167 # it connects, try a stmt.
[184]168 my $sth = $dbh->prepare("select type from alloctypes");
[4]169 my $err = $sth->execute();
170
171 if ($sth->fetchrow()) {
172 # all is well.
173 return 1;
174 } else {
[16]175 print "Connected to the database, but could not execute test statement. ".$sth->errstr();
[106]176 return -1;
[4]177 }
178 }
179 # Clean up after ourselves.
[106]180# $dbh->disconnect;
[4]181} # end checkDBSanity
182
[66]183
[371]184## IPDB::addMaster()
185# Does all the magic necessary to sucessfully add a master block
186# Requires database handle, block to add
187# Returns failure code and error message or success code and "message"
188sub addMaster {
189 my $dbh = shift;
190 my $cidr = new NetAddr::IP shift;
191
192 # Allow transactions, and raise an exception on errors so we can catch it later.
193 # Use local to make sure these get "reset" properly on exiting this block
194 local $dbh->{AutoCommit} = 0;
195 local $dbh->{RaiseError} = 1;
196
197 # Wrap all the SQL in a transaction
198 eval {
199 my $sth = $dbh->prepare("select count(*) from masterblocks where cidr <<= '$cidr'");
200 $sth->execute;
201 my @data = $sth->fetchrow_array;
202
203 if ($data[0] eq 0) {
204 # First case - master is brand-spanking-new.
205##fixme: rwhois should be globally-flagable somewhere, much like a number of other things
206## maybe a db table called "config"?
207 $sth = $dbh->prepare("insert into masterblocks (cidr,rwhois) values ('$cidr','y')");
208 $sth->execute;
209
210# Unrouted blocks aren't associated with a city (yet). We don't rely on this
211# elsewhere though; legacy data may have traps and pitfalls in it to break this.
212# Thus the "routed" flag.
213
214 $sth = $dbh->prepare("insert into freeblocks (cidr,maskbits,city,routed)".
215 " values ('$cidr',".$cidr->masklen.",'<NULL>','n')");
216 $sth->execute;
217
218 # If we get here, everything is happy. Commit changes.
219 $dbh->commit;
220
221 } # new master does not contain existing master(s)
222 else {
223
224 # collect the master(s) we're going to absorb, and snag the longest netmask while we're at it.
225 my $smallmask = $cidr->masklen;
226 $sth = $dbh->prepare("select cidr as mask from masterblocks where cidr <<= '$cidr'");
227 $sth->execute;
228 my @cmasters;
229 while (my @data = $sth->fetchrow_array) {
230 my $master = new NetAddr::IP $data[0];
231 push @cmasters, $master;
232 $smallmask = $master->masklen if $master->masklen > $smallmask;
233 }
234
235 # split the new master, and keep only those blocks not part of an existing master
236 my @blocklist;
237 foreach my $seg ($cidr->split($smallmask)) {
238 my $contained = 0;
239 foreach my $master (@cmasters) {
240 $contained = 1 if $master->contains($seg);
241 }
242 push @blocklist, $seg if !$contained;
243 }
244
245 # collect the unrouted free blocks within the new master
246 $sth = $dbh->prepare("select cidr from freeblocks where ".
247 "maskbits>=$smallmask and cidr <<= '$cidr' and routed='n'");
248 $sth->execute;
249 while (my @data = $sth->fetchrow_array) {
250 my $freeblock = new NetAddr::IP $data[0];
251 push @blocklist, $freeblock;
252 }
253
254 # combine the set of free blocks we should have now.
255 @blocklist = Compact(@blocklist);
256
257 # and now insert the new data. Make sure to delete old masters too.
258
259 # freeblocks
260 $sth = $dbh->prepare("delete from freeblocks where cidr <<= ?");
261 my $sth2 = $dbh->prepare("insert into freeblocks (cidr,maskbits,city,routed) values (?,?,'<NULL>','n')");
262 foreach my $newblock (@blocklist) {
263 $sth->execute("$newblock");
264 $sth2->execute("$newblock", $newblock->masklen);
265 }
266
267 # master
268 $sth = $dbh->prepare("delete from masterblocks where cidr <<= '$cidr'");
269 $sth->execute;
270 $sth = $dbh->prepare("insert into masterblocks (cidr,rwhois) values ('$cidr','y')");
271 $sth->execute;
272
273 # *whew* If we got here, we likely suceeded.
274 $dbh->commit;
275 } # new master contained existing master(s)
276 }; # end eval
277
278 if ($@) {
279 my $msg = $@;
280 eval { $dbh->rollback; };
281 return ('FAIL',$msg);
282 } else {
283 return ('OK','OK');
284 }
285} # end addMaster
286
287
[77]288## IPDB::allocateBlock()
[66]289# Does all of the magic of actually allocating a netblock
[77]290# Requires database handle, block to allocate, custid, type, city,
[284]291# description, notes, circuit ID, block to allocate from, private data
[77]292# Returns a success code and optional error message.
293sub allocateBlock {
[284]294 my ($dbh,undef,undef,$custid,$type,$city,$desc,$notes,$circid,$privdata) = @_;
295
[77]296 my $cidr = new NetAddr::IP $_[1];
297 my $alloc_from = new NetAddr::IP $_[2];
298 my $sth;
[66]299
[349]300 # Snag the "type" of the freeblock (alloc_from) "just in case"
301 $sth = $dbh->prepare("select routed from freeblocks where cidr='$alloc_from'");
302 $sth->execute;
303 my ($alloc_from_type) = $sth->fetchrow_array;
304
[79]305 # To contain the error message, if any.
306 my $msg = "Unknown error allocating $cidr as '$type'";
307
[77]308 # Enable transactions and error handling
309 local $dbh->{AutoCommit} = 0; # These need to be local so we don't
310 local $dbh->{RaiseError} = 1; # step on our toes by accident.
[66]311
[157]312 if ($type =~ /^.i$/) {
[79]313 $msg = "Unable to assign static IP $cidr to $custid";
[77]314 eval {
[157]315 # We have to do this in two parts because otherwise we lose
316 # the ability to return the IP assigned. Should that change,
317 # the commented SQL statement below may become usable.
[77]318# update poolips set custid='$custid',city='$city',available='n',
319# description='$desc',notes='$notes',circuitid='$circid'
320# where ip=(select ip from poolips where pool='$alloc_from'
321# and available='y' order by ip limit 1);
[157]322
323 $sth = $dbh->prepare("select ip from poolips where pool='$alloc_from'".
324 " and available='y' order by ip");
325 $sth->execute;
326
[77]327 my @data = $sth->fetchrow_array;
[157]328 $cidr = $data[0]; # $cidr is already declared when we get here!
[77]329
330 $sth = $dbh->prepare("update poolips set custid='$custid',".
[108]331 "city='$city',available='n',description='$desc',notes='$notes',".
[284]332 "circuitid='$circid',privdata='$privdata'".
[77]333 " where ip='$cidr'");
334 $sth->execute;
[79]335 $dbh->commit;
[77]336 };
337 if ($@) {
[107]338 $msg .= ": '".$sth->errstr."'";
[78]339 eval { $dbh->rollback; };
340 return ('FAIL',$msg);
[77]341 } else {
[106]342 return ('OK',"$cidr");
[77]343 }
344
345 } else { # end IP-from-pool allocation
346
347 if ($cidr == $alloc_from) {
348 # Easiest case- insert in one table, delete in the other, and go home. More or less.
349 # insert into allocations values (cidr,custid,type,city,desc) and
350 # delete from freeblocks where cidr='cidr'
351 # For data safety on non-transaction DBs, we delete first.
352
353 eval {
[79]354 $msg = "Unable to allocate $cidr as '$disp_alloctypes{$type}'";
[187]355 if ($type eq 'rm') {
[77]356 $sth = $dbh->prepare("update freeblocks set routed='y',city='$city'".
357 " where cidr='$cidr'");
358 $sth->execute;
[157]359 $sth = $dbh->prepare("insert into routed (cidr,maskbits,city)".
360 " values ('$cidr',".$cidr->masklen.",'$city')");
[77]361 $sth->execute;
362 } else {
363 # common stuff for end-use, dialup, dynDSL, pools, etc, etc.
364
[187]365 # special case - block is a container/"reserve" block
366 if ($type =~ /^(.)c$/) {
367 $sth = $dbh->prepare("update freeblocks set routed='$1' where cidr='$cidr'");
[186]368 $sth->execute;
369 } else {
370 # "normal" case
371 $sth = $dbh->prepare("delete from freeblocks where cidr='$cidr'");
372 $sth->execute;
373 }
[157]374 $sth = $dbh->prepare("insert into allocations".
[284]375 " (cidr,custid,type,city,description,notes,maskbits,circuitid,privdata)".
[157]376 " values ('$cidr','$custid','$type','$city','$desc','$notes',".
[284]377 $cidr->masklen.",'$circid','$privdata')");
[77]378 $sth->execute;
[78]379
380 # And initialize the pool, if necessary
[157]381 # PPPoE pools (currently dialup, DSL, and WiFi) get all IPs made available
382 # "DHCP" or "real-subnet" pools have the net, gw, and bcast IPs removed.
[78]383 if ($type =~ /^.p$/) {
[157]384 $msg = "Could not initialize IPs in new $disp_alloctypes{$type} $cidr";
385 my ($code,$rmsg) = initPool($dbh,$cidr,$type,$city,"all");
386 die $rmsg if $code eq 'FAIL';
387 } elsif ($type =~ /^.d$/) {
388 $msg = "Could not initialize IPs in new $disp_alloctypes{$type} $cidr";
389 my ($code,$rmsg) = initPool($dbh,$cidr,$type,$city,"normal");
390 die $rmsg if $code eq 'FAIL';
[79]391 }
392
[77]393 } # routing vs non-routing netblock
[79]394
[77]395 $dbh->commit;
[78]396 }; # end of eval
[77]397 if ($@) {
[157]398 $msg .= ": ".$@;
[77]399 eval { $dbh->rollback; };
[157]400 return ('FAIL',$msg);
[77]401 } else {
[78]402 return ('OK',"OK");
403 }
[77]404
405 } else { # cidr != alloc_from
406
407 # Hard case. Allocation is smaller than free block.
408 my $wantmaskbits = $cidr->masklen;
409 my $maskbits = $alloc_from->masklen;
410
411 my @newfreeblocks; # Holds free blocks generated from splitting the source freeblock.
412
413 # This determines which blocks will be left "free" after allocation. We take the
414 # block we're allocating from, and split it in half. We see which half the wanted
415 # block is in, and repeat until the wanted block is equal to one of the halves.
416 my $i=0;
417 my $tmp_from = $alloc_from; # So we don't munge $alloc_from
418 while ($maskbits++ < $wantmaskbits) {
419 my @subblocks = $tmp_from->split($maskbits);
420 $newfreeblocks[$i++] = (($cidr->within($subblocks[0])) ? $subblocks[1] : $subblocks[0]);
421 $tmp_from = ( ($cidr->within($subblocks[0])) ? $subblocks[0] : $subblocks[1] );
422 } # while
423
424 # Begin SQL transaction block
425 eval {
[79]426 $msg = "Unable to allocate $cidr as '$disp_alloctypes{$type}'";
427
[77]428 # Delete old freeblocks entry
429 $sth = $dbh->prepare("delete from freeblocks where cidr='$alloc_from'");
430 $sth->execute();
431
432 # now we have to do some magic for routing blocks
[187]433 if ($type eq 'rm') {
[79]434
[77]435 # Insert the new freeblocks entries
436 # Note that non-routed blocks are assigned to <NULL>
[157]437 # and use the default value for the routed column ('n')
438 $sth = $dbh->prepare("insert into freeblocks (cidr,maskbits,city)".
439 " values (?, ?, '<NULL>')");
[77]440 foreach my $block (@newfreeblocks) {
441 $sth->execute("$block", $block->masklen);
442 }
[79]443
[77]444 # Insert the entry in the routed table
[157]445 $sth = $dbh->prepare("insert into routed (cidr,maskbits,city)".
446 " values ('$cidr',".$cidr->masklen.",'$city')");
[77]447 $sth->execute;
448 # Insert the (almost) same entry in the freeblocks table
[157]449 $sth = $dbh->prepare("insert into freeblocks (cidr,maskbits,city,routed)".
450 " values ('$cidr',".$cidr->masklen.",'$city','y')");
[77]451 $sth->execute;
452
[189]453 } else { # done with alloctype == rm
[77]454
455 # Insert the new freeblocks entries
[349]456 # Along with some more HairyPerl(TM):
457 # if $alloc_type_from is p
458 # OR
459 # $type matches /^(.)r$/
460 # inserted value for routed column should match.
461 # This solves the case of inserting an arbitrary block into a
462 # "Reserve-for-routed-DSL" block. Which you really shouldn't
463 # do in the first place, but anyway...
[157]464 $sth = $dbh->prepare("insert into freeblocks (cidr,maskbits,city,routed)".
[186]465 " values (?, ?, (select city from routed where cidr >>= '$cidr'),'".
[349]466 ( ( ($alloc_from_type =~ /^(p)$/) || ($type =~ /^(.)r$/) ) ? "$1" : 'y')."')");
[77]467 foreach my $block (@newfreeblocks) {
468 $sth->execute("$block", $block->masklen);
469 }
[187]470 # Special-case for reserve/"container" blocks - generate
471 # the "extra" freeblocks entry for the container
472 if ($type =~ /^(.)c$/) {
[186]473 $sth = $dbh->prepare("insert into freeblocks (cidr,maskbits,city,routed)".
[187]474 " values ('$cidr',".$cidr->masklen.",'$city','$1')");
[186]475 $sth->execute;
476 }
[77]477 # Insert the allocations entry
[157]478 $sth = $dbh->prepare("insert into allocations (cidr,custid,type,city,".
[284]479 "description,notes,maskbits,circuitid,privdata)".
[157]480 " values ('$cidr','$custid','$type','$city','$desc','$notes',".
[284]481 $cidr->masklen.",'$circid','$privdata')");
[77]482 $sth->execute;
[78]483
484 # And initialize the pool, if necessary
[157]485 # PPPoE pools (currently dialup, DSL, and WiFi) get all IPs made available
486 # "DHCP" or "real-subnet" pools have the net, gw, and bcast IPs removed.
[78]487 if ($type =~ /^.p$/) {
[79]488 $msg = "Could not initialize IPs in new $disp_alloctypes{$type} $cidr";
[157]489 my ($code,$rmsg) = initPool($dbh,$cidr,$type,$city,"all");
490 die $rmsg if $code eq 'FAIL';
491 } elsif ($type =~ /^.d$/) {
492 $msg = "Could not initialize IPs in new $disp_alloctypes{$type} $cidr";
493 my ($code,$rmsg) = initPool($dbh,$cidr,$type,$city,"normal");
494 die $rmsg if $code eq 'FAIL';
[79]495 }
496
[189]497 } # done with netblock alloctype != rm
[79]498
[77]499 $dbh->commit;
500 }; # end eval
501 if ($@) {
[256]502 $msg .= ": ".$@;
[77]503 eval { $dbh->rollback; };
[78]504 return ('FAIL',$msg);
[77]505 } else {
[78]506 return ('OK',"OK");
[77]507 }
508
509 } # end fullcidr != alloc_from
510
511 } # end static-IP vs netblock allocation
512
513} # end allocateBlock()
514
515
516## IPDB::initPool()
517# Initializes a pool
518# Requires a database handle, the pool CIDR, type, city, and a parameter
519# indicating whether the pool should allow allocation of literally every
520# IP, or if it should reserve network/gateway/broadcast IPs
[78]521# Note that this is NOT done in a transaction, that's why it's a private
522# function and should ONLY EVER get called from allocateBlock()
[77]523sub initPool {
524 my ($dbh,undef,$type,$city,$class) = @_;
525 my $pool = new NetAddr::IP $_[1];
526
[157]527##fixme Need to just replace 2nd char of type with i rather than capturing 1st char of type
528 $type =~ s/[pd]$/i/;
[77]529 my $sth;
[157]530 my $msg;
[77]531
[157]532 # Trap errors so we can pass them back to the caller. Even if the
533 # caller is only ever supposed to be local, and therefore already
534 # trapping errors. >:(
535 local $dbh->{AutoCommit} = 0; # These need to be local so we don't
536 local $dbh->{RaiseError} = 1; # step on our toes by accident.
537
538 eval {
539 # have to insert all pool IPs into poolips table as "unallocated".
540 $sth = $dbh->prepare("insert into poolips (pool,ip,custid,city,type)".
541 " values ('$pool', ?, '6750400', '$city', '$type')");
542 my @poolip_list = $pool->hostenum;
543 if ($class eq 'all') { # (DSL-ish block - *all* IPs available
[246]544 if ($pool->addr !~ /\.0$/) { # .0 causes weirdness.
545 $sth->execute($pool->addr);
546 }
[157]547 for (my $i=0; $i<=$#poolip_list; $i++) {
548 $sth->execute($poolip_list[$i]->addr);
549 }
550 $pool--;
[246]551 if ($pool->addr !~ /\.255$/) { # .255 can cause weirdness.
552 $sth->execute($pool->addr);
553 }
[157]554 } else { # (real netblock)
555 for (my $i=1; $i<=$#poolip_list; $i++) {
556 $sth->execute($poolip_list[$i]->addr);
557 }
[77]558 }
[157]559 };
560 if ($@) {
561 $msg = "'".$sth->errstr."'";
562 eval { $dbh->rollback; };
563 return ('FAIL',$msg);
564 } else {
565 return ('OK',"OK");
[77]566 }
567} # end initPool()
568
569
[93]570## IPDB::deleteBlock()
571# Removes an allocation from the database, including deleting IPs
572# from poolips and recombining entries in freeblocks if possible
573# Also handles "deleting" a static IP allocation, and removal of a master
574# Requires a database handle, the block to delete, and the type of block
575sub deleteBlock {
576 my ($dbh,undef,$type) = @_;
577 my $cidr = new NetAddr::IP $_[1];
578
579 my $sth;
580
[349]581 # Magic variables used for odd allocation cases.
582 my $container;
583 my $con_type;
584
[93]585 # To contain the error message, if any.
586 my $msg = "Unknown error deallocating $type $cidr";
587 # Enable transactions and exception-on-errors... but only for this sub
588 local $dbh->{AutoCommit} = 0;
589 local $dbh->{RaiseError} = 1;
590
591 # First case. The "block" is a static IP
592 # Note that we still need some additional code in the odd case
593 # of a netblock-aligned contiguous group of static IPs
594 if ($type =~ /^.i$/) {
595
596 eval {
[157]597 $msg = "Unable to deallocate $disp_alloctypes{$type} $cidr";
[93]598 $sth = $dbh->prepare("update poolips set custid='6750400',available='y',".
[370]599 "city=(select city from allocations where cidr >>= '$cidr'".
600 " order by masklen(cidr) desc limit 1),".
[93]601 "description='',notes='',circuitid='' where ip='$cidr'");
602 $sth->execute;
603 $dbh->commit;
604 };
605 if ($@) {
606 eval { $dbh->rollback; };
607 return ('FAIL',$msg);
608 } else {
609 return ('OK',"OK");
610 }
611
612 } elsif ($type eq 'mm') { # end alloctype =~ /.i/
613
614 $msg = "Unable to delete master block $cidr";
615 eval {
616 $sth = $dbh->prepare("delete from masterblocks where cidr='$cidr'");
617 $sth->execute;
[371]618 $sth = $dbh->prepare("delete from freeblocks where cidr <<= '$cidr'");
[93]619 $sth->execute;
620 $dbh->commit;
621 };
622 if ($@) {
623 eval { $dbh->rollback; };
624 return ('FAIL', $msg);
625 } else {
626 return ('OK',"OK");
627 }
628
629 } else { # end alloctype master block case
630
631 ## This is a big block; but it HAS to be done in a chunk. Any removal
632 ## of a netblock allocation may result in a larger chunk of free
633 ## contiguous IP space - which may in turn be combined into a single
634 ## netblock rather than a number of smaller netblocks.
635
636 eval {
637
[187]638 if ($type eq 'rm') {
[93]639 $msg = "Unable to remove routing allocation $cidr";
640 $sth = $dbh->prepare("delete from routed where cidr='$cidr'");
641 $sth->execute;
642 # Make sure block getting deleted is properly accounted for.
643 $sth = $dbh->prepare("update freeblocks set routed='n',city='<NULL>'".
644 " where cidr='$cidr'");
645 $sth->execute;
646 # Set up query to start compacting free blocks.
[157]647 $sth = $dbh->prepare("select cidr from freeblocks where ".
[93]648 "maskbits<=".$cidr->masklen." and routed='n' order by maskbits desc");
649
650 } else { # end alloctype routing case
651
[349]652 # Magic. We need to get information about the containing block (if any)
653 # so as to make sure that the freeblocks we insert get the correct "type".
654 $sth = $dbh->prepare("select cidr,type from allocations where cidr >> '$cidr'");
655 $sth->execute;
656 ($container, $con_type) = $sth->fetchrow_array;
657
[186]658 # Delete all allocations within the block being deleted. This is
659 # deliberate and correct, and removes the need to special-case
660 # removal of "container" blocks.
661 $sth = $dbh->prepare("delete from allocations where cidr <<='$cidr'");
[93]662 $sth->execute;
[186]663
[93]664 # Special case - delete pool IPs
[157]665 if ($type =~ /^.[pd]$/) {
[93]666 # We have to delete the IPs from the pool listing.
667 $sth = $dbh->prepare("delete from poolips where pool='$cidr'");
668 $sth->execute;
669 }
670
671 # Set up query for compacting free blocks.
[349]672 if ($con_type && $con_type eq 'pc') {
673 # Clean up after "bad" allocations (blocks that are not formally
674 # contained which have nevertheless been allocated from a container block)
675 # We want to make certain that the freeblocks are properly "labelled"
[371]676 $sth = $dbh->prepare("select cidr from freeblocks where cidr <<= '$container' order by maskbits desc");
[349]677 } else {
678 # Standard deallocation.
679 $sth = $dbh->prepare("select cidr from freeblocks where cidr <<= ".
[120]680 "(select cidr from routed where cidr >>= '$cidr') ".
[186]681 " and maskbits<=".$cidr->masklen.
[350]682 " and routed='".(($type =~ /^(.)r$/) ? "$1" : 'y').
[186]683 "' order by maskbits desc");
[349]684 }
[93]685
686 } # end alloctype general case
687
688 # Now we look for larger-or-equal-sized free blocks in the same master (routed)
689 # (super)block. If there aren't any, we can't combine blocks anyway. If there
690 # are, we check to see if we can combine blocks.
691 # Execute the statement prepared in the if-else above.
692
693 $sth->execute;
694
695# NetAddr::IP->compact() attempts to produce the smallest inclusive block
696# from the caller and the passed terms.
697# EG: if you call $cidr->compact($ip1,$ip2,$ip3) when $cidr, $ip1, $ip2,
698# and $ip3 are consecutive /27's starting on .0 (.0-.31, .32-.63,
699# .64-.95, and .96-.128), you will get an array containing a single
700# /25 as element 0 (.0-.127). Order is not important; you could have
701# $cidr=.32/27, $ip1=.96/27, $ip2=.0/27, and $ip3=.64/27.
702
703 my (@together, @combinelist);
704 my $i=0;
705 while (my @data = $sth->fetchrow_array) {
706 my $testIP = new NetAddr::IP $data[0];
707 @together = $testIP->compact($cidr);
708 my $num = @together;
709 if ($num == 1) {
710 $cidr = $together[0];
711 $combinelist[$i++] = $testIP;
712 }
713 }
714
[186]715 # Clear old freeblocks entries - if any. They should all be within
716 # the $cidr determined above.
717 $sth = $dbh->prepare("delete from freeblocks where cidr <<='$cidr'");
718 $sth->execute;
[93]719
720 # insert "new" freeblocks entry
[187]721 if ($type eq 'rm') {
[157]722 $sth = $dbh->prepare("insert into freeblocks (cidr,maskbits,city)".
723 " values ('$cidr',".$cidr->masklen.",'<NULL>')");
[93]724 } else {
[349]725 # Magic hackery to insert "correct" data for deallocation of
726 # non-contained blocks allocated from within a container.
727 $type = 'pr' if $con_type && $con_type eq 'pc';
728
[157]729 $sth = $dbh->prepare("insert into freeblocks (cidr,maskbits,city,routed)".
730 " values ('$cidr',".$cidr->masklen.
[186]731 ",(select city from routed where cidr >>= '$cidr'),'".
[189]732 (($type =~ /^(.)r$/) ? "$1" : 'y')."')");
[93]733 }
734 $sth->execute;
735
736 # If we got here, we've succeeded. Whew!
737 $dbh->commit;
738 }; # end eval
739 if ($@) {
740 eval { $dbh->rollback; };
741 return ('FAIL', $msg);
742 } else {
743 return ('OK',"OK");
744 }
745
746 } # end alloctype != netblock
747
748} # end deleteBlock()
749
750
[370]751## IPDB::getBlockData()
752# Return custid, type, city, and description for a block
753sub getBlockData {
754 my $dbh = shift;
755 my $block = shift;
756
757 my $sth = $dbh->prepare("select cidr,custid,type,city,description from searchme".
758 " where cidr='$block'");
759 $sth->execute();
760 return $sth->fetchrow_array();
761} # end getBlockData()
762
763
[77]764## IPDB::mailNotify()
[66]765# Sends notification mail to recipients regarding an IPDB operation
766sub mailNotify ($$$) {
767 my ($recip,$subj,$message) = @_;
[69]768 my $mailer = Net::SMTP->new("smtp.example.com", Hello => "ipdb.example.com");
[66]769
770 $mailer->mail('ipdb@example.com');
771 $mailer->to($recip);
[69]772 $mailer->data("From: \"IP Database\" <ipdb\@example.com>\n",
[135]773 "To: $recip\n",
[69]774 "Date: ".strftime("%a, %d %b %Y %H:%M:%S %z",localtime)."\n",
775 "Subject: {IPDB} $subj\n",
776 "X-Mailer: IPDB Notify v".sprintf("%.1d",$IPDB::VERSION)."\n",
777 "Organization: Example Corp\n",
778 "\n$message\n");
[66]779 $mailer->quit;
780}
781
[4]782# Indicates module loaded OK. Required by Perl.
7831;
Note: See TracBrowser for help on using the repository browser.