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

Last change on this file since 435 was 434, checked in by Kris Deugau, 14 years ago

/trunk

Trim out another bit of hardcodery: "Updated-By" field in rWHOIS
exports is now $IPDB::org_email. See #17.

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