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

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

/branches/stable

Add new sub to IPDB.pm: addMaster()
Sub is more complex than original stub in main.cgi; allows adding a
master that is a superset of an existing master
Minor bugfix on removing a master; make sure to delete all relevant freeblocks

  • Property svn:keywords set to Date Rev Author
File size: 26.4 KB
Line 
1# ipdb/cgi-bin/IPDB.pm
2# Contains functions for IPDB - database access, subnet mangling, block allocation, etc
3###
4# SVN revision info
5# $Date: 2007-10-09 17:06:45 +0000 (Tue, 09 Oct 2007) $
6# SVN revision $Rev: 365 $
7# Last update by $Author: kdeugau $
8###
9# Copyright (C) 2004-2006 - Kris Deugau
10
11package IPDB;
12
13use strict;
14use warnings;
15use Exporter;
16use DBI;
17use Net::SMTP;
18use NetAddr::IP qw( Compact );
19use POSIX;
20use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
21
22$VERSION = 2.0;
23@ISA = qw(Exporter);
24@EXPORT_OK = qw(
25 %disp_alloctypes %list_alloctypes %def_custids @citylist @poplist @masterblocks
26 %allocated %free %routed %bigfree %IPDBacl
27 &initIPDBGlobals &connectDB &finish &checkDBSanity &allocateBlock &addMaster
28 &deleteBlock &getBlockData &mailNotify
29 );
30
31@EXPORT = (); # Export nothing by default.
32%EXPORT_TAGS = ( ALL => [qw(
33 %disp_alloctypes %list_alloctypes %def_custids @citylist @poplist
34 @masterblocks %allocated %free %routed %bigfree %IPDBacl
35 &initIPDBGlobals &connectDB &finish &checkDBSanity &allocateBlock
36 &addMaster &deleteBlock &getBlockData &mailNotify
37 )]
38 );
39
40##
41## Global variables
42##
43our %disp_alloctypes;
44our %list_alloctypes;
45our %def_custids;
46our @citylist;
47our @poplist;
48our @masterblocks;
49our %allocated;
50our %free;
51our %routed;
52our %bigfree;
53our %IPDBacl;
54
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
62 # Initialize alloctypes hashes
63 $sth = $dbh->prepare("select type,listname,dispname,listorder,def_custid from alloctypes order by listorder");
64 $sth->execute;
65 while (my @data = $sth->fetchrow_array) {
66 $disp_alloctypes{$data[0]} = $data[2];
67 $def_custids{$data[0]} = $data[4];
68 if ($data[3] < 900) {
69 $list_alloctypes{$data[0]} = $data[1];
70 }
71 }
72
73 # City and POP listings
74 $sth = $dbh->prepare("select city,routing from cities order by city");
75 $sth->execute;
76 return (undef,$sth->errstr) if $sth->err;
77 while (my @data = $sth->fetchrow_array) {
78 push @citylist, $data[0];
79 if ($data[1] eq 'y') {
80 push @poplist, $data[0];
81 }
82 }
83
84 # Master block list
85 $sth = $dbh->prepare("select cidr from masterblocks order by cidr");
86 $sth->execute;
87 return (undef,$sth->errstr) if $sth->err;
88 for (my $i=0; my @data = $sth->fetchrow_array(); $i++) {
89 $masterblocks[$i] = new NetAddr::IP $data[0];
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;
95 }
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;
100 return (undef,$sth->errstr) if $sth->err;
101 while (my @data = $sth->fetchrow_array) {
102 $IPDBacl{$data[0]} = $data[1];
103 }
104
105 return (1,"OK");
106} # end initIPDBGlobals
107
108
109## IPDB::connectDB()
110# Creates connection to IPDB.
111# Requires the database name, username, and password.
112# Returns a handle to the db.
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.
117sub connectDB {
118 my ($dbname,$user,$pass) = @_;
119 my $dbh;
120 my $DSN = "DBI:Pg:dbname=$dbname";
121# my $user = 'ipdb';
122# my $pw = 'ipdbpwd';
123
124# Note that we want to autocommit by default, and we will turn it off locally as necessary.
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);
131
132# Return here if we can't select. Note that this indicates a
133# problem executing the select.
134 my $sth = $dbh->prepare("select type from alloctypes");
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");
145} # end connectDB
146
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
157## IPDB::checkDBSanity()
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 {
161 my ($dbh) = $_[0];
162
163 if (!$dbh) {
164 print "No database handle, or connection has been closed.";
165 return -1;
166 } else {
167 # it connects, try a stmt.
168 my $sth = $dbh->prepare("select type from alloctypes");
169 my $err = $sth->execute();
170
171 if ($sth->fetchrow()) {
172 # all is well.
173 return 1;
174 } else {
175 print "Connected to the database, but could not execute test statement. ".$sth->errstr();
176 return -1;
177 }
178 }
179 # Clean up after ourselves.
180# $dbh->disconnect;
181} # end checkDBSanity
182
183
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
288## IPDB::allocateBlock()
289# Does all of the magic of actually allocating a netblock
290# Requires database handle, block to allocate, custid, type, city,
291# description, notes, circuit ID, block to allocate from, private data
292# Returns a success code and optional error message.
293sub allocateBlock {
294 my ($dbh,undef,undef,$custid,$type,$city,$desc,$notes,$circid,$privdata) = @_;
295
296 my $cidr = new NetAddr::IP $_[1];
297 my $alloc_from = new NetAddr::IP $_[2];
298 my $sth;
299
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
305 # To contain the error message, if any.
306 my $msg = "Unknown error allocating $cidr as '$type'";
307
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.
311
312 if ($type =~ /^.i$/) {
313 $msg = "Unable to assign static IP $cidr to $custid";
314 eval {
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.
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);
322
323 $sth = $dbh->prepare("select ip from poolips where pool='$alloc_from'".
324 " and available='y' order by ip");
325 $sth->execute;
326
327 my @data = $sth->fetchrow_array;
328 $cidr = $data[0]; # $cidr is already declared when we get here!
329
330 $sth = $dbh->prepare("update poolips set custid='$custid',".
331 "city='$city',available='n',description='$desc',notes='$notes',".
332 "circuitid='$circid',privdata='$privdata'".
333 " where ip='$cidr'");
334 $sth->execute;
335 $dbh->commit;
336 };
337 if ($@) {
338 $msg .= ": '".$sth->errstr."'";
339 eval { $dbh->rollback; };
340 return ('FAIL',$msg);
341 } else {
342 return ('OK',"$cidr");
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 {
354 $msg = "Unable to allocate $cidr as '$disp_alloctypes{$type}'";
355 if ($type eq 'rm') {
356 $sth = $dbh->prepare("update freeblocks set routed='y',city='$city'".
357 " where cidr='$cidr'");
358 $sth->execute;
359 $sth = $dbh->prepare("insert into routed (cidr,maskbits,city)".
360 " values ('$cidr',".$cidr->masklen.",'$city')");
361 $sth->execute;
362 } else {
363 # common stuff for end-use, dialup, dynDSL, pools, etc, etc.
364
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'");
368 $sth->execute;
369 } else {
370 # "normal" case
371 $sth = $dbh->prepare("delete from freeblocks where cidr='$cidr'");
372 $sth->execute;
373 }
374 $sth = $dbh->prepare("insert into allocations".
375 " (cidr,custid,type,city,description,notes,maskbits,circuitid,privdata)".
376 " values ('$cidr','$custid','$type','$city','$desc','$notes',".
377 $cidr->masklen.",'$circid','$privdata')");
378 $sth->execute;
379
380 # And initialize the pool, if necessary
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.
383 if ($type =~ /^.p$/) {
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';
391 }
392
393 } # routing vs non-routing netblock
394
395 $dbh->commit;
396 }; # end of eval
397 if ($@) {
398 $msg .= ": ".$@;
399 eval { $dbh->rollback; };
400 return ('FAIL',$msg);
401 } else {
402 return ('OK',"OK");
403 }
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 {
426 $msg = "Unable to allocate $cidr as '$disp_alloctypes{$type}'";
427
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
433 if ($type eq 'rm') {
434
435 # Insert the new freeblocks entries
436 # Note that non-routed blocks are assigned to <NULL>
437 # and use the default value for the routed column ('n')
438 $sth = $dbh->prepare("insert into freeblocks (cidr,maskbits,city)".
439 " values (?, ?, '<NULL>')");
440 foreach my $block (@newfreeblocks) {
441 $sth->execute("$block", $block->masklen);
442 }
443
444 # Insert the entry in the routed table
445 $sth = $dbh->prepare("insert into routed (cidr,maskbits,city)".
446 " values ('$cidr',".$cidr->masklen.",'$city')");
447 $sth->execute;
448 # Insert the (almost) same entry in the freeblocks table
449 $sth = $dbh->prepare("insert into freeblocks (cidr,maskbits,city,routed)".
450 " values ('$cidr',".$cidr->masklen.",'$city','y')");
451 $sth->execute;
452
453 } else { # done with alloctype == rm
454
455 # Insert the new freeblocks entries
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...
464 $sth = $dbh->prepare("insert into freeblocks (cidr,maskbits,city,routed)".
465 " values (?, ?, (select city from routed where cidr >>= '$cidr'),'".
466 ( ( ($alloc_from_type =~ /^(p)$/) || ($type =~ /^(.)r$/) ) ? "$1" : 'y')."')");
467 foreach my $block (@newfreeblocks) {
468 $sth->execute("$block", $block->masklen);
469 }
470 # Special-case for reserve/"container" blocks - generate
471 # the "extra" freeblocks entry for the container
472 if ($type =~ /^(.)c$/) {
473 $sth = $dbh->prepare("insert into freeblocks (cidr,maskbits,city,routed)".
474 " values ('$cidr',".$cidr->masklen.",'$city','$1')");
475 $sth->execute;
476 }
477 # Insert the allocations entry
478 $sth = $dbh->prepare("insert into allocations (cidr,custid,type,city,".
479 "description,notes,maskbits,circuitid,privdata)".
480 " values ('$cidr','$custid','$type','$city','$desc','$notes',".
481 $cidr->masklen.",'$circid','$privdata')");
482 $sth->execute;
483
484 # And initialize the pool, if necessary
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.
487 if ($type =~ /^.p$/) {
488 $msg = "Could not initialize IPs in new $disp_alloctypes{$type} $cidr";
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';
495 }
496
497 } # done with netblock alloctype != rm
498
499 $dbh->commit;
500 }; # end eval
501 if ($@) {
502 $msg .= ": ".$@;
503 eval { $dbh->rollback; };
504 return ('FAIL',$msg);
505 } else {
506 return ('OK',"OK");
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
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()
523sub initPool {
524 my ($dbh,undef,$type,$city,$class) = @_;
525 my $pool = new NetAddr::IP $_[1];
526
527##fixme Need to just replace 2nd char of type with i rather than capturing 1st char of type
528 $type =~ s/[pd]$/i/;
529 my $sth;
530 my $msg;
531
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
544 if ($pool->addr !~ /\.0$/) { # .0 causes weirdness.
545 $sth->execute($pool->addr);
546 }
547 for (my $i=0; $i<=$#poolip_list; $i++) {
548 $sth->execute($poolip_list[$i]->addr);
549 }
550 $pool--;
551 if ($pool->addr !~ /\.255$/) { # .255 can cause weirdness.
552 $sth->execute($pool->addr);
553 }
554 } else { # (real netblock)
555 for (my $i=1; $i<=$#poolip_list; $i++) {
556 $sth->execute($poolip_list[$i]->addr);
557 }
558 }
559 };
560 if ($@) {
561 $msg = "'".$sth->errstr."'";
562 eval { $dbh->rollback; };
563 return ('FAIL',$msg);
564 } else {
565 return ('OK',"OK");
566 }
567} # end initPool()
568
569
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
581 # Magic variables used for odd allocation cases.
582 my $container;
583 my $con_type;
584
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 {
597 $msg = "Unable to deallocate $disp_alloctypes{$type} $cidr";
598 $sth = $dbh->prepare("update poolips set custid='6750400',available='y',".
599 "city=(select city from allocations where cidr >>= '$cidr'".
600 " order by masklen(cidr) desc limit 1),".
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;
618 $sth = $dbh->prepare("delete from freeblocks where cidr <<= '$cidr'");
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
638 if ($type eq 'rm') {
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.
647 $sth = $dbh->prepare("select cidr from freeblocks where ".
648 "maskbits<=".$cidr->masklen." and routed='n' order by maskbits desc");
649
650 } else { # end alloctype routing case
651
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
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'");
662 $sth->execute;
663
664 # Special case - delete pool IPs
665 if ($type =~ /^.[pd]$/) {
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.
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"
676 $sth = $dbh->prepare("select cidr from freeblocks where cidr <<= '$container' order by maskbits desc");
677 } else {
678 # Standard deallocation.
679 $sth = $dbh->prepare("select cidr from freeblocks where cidr <<= ".
680 "(select cidr from routed where cidr >>= '$cidr') ".
681 " and maskbits<=".$cidr->masklen.
682 " and routed='".(($type =~ /^(.)r$/) ? "$1" : 'y').
683 "' order by maskbits desc");
684 }
685
686 } # end alloctype general case
687
688##TEMP
689## Temporary wrapper to "properly" deallocate sIP PPPoE/DSL "netblocks" in 209.91.185.0/24
690## Note that we should really general-case this.
691my $staticpool = new NetAddr::IP "209.91.185.0/24";
692##TEMP
693if ($cidr->within($staticpool)) {
694##TEMP
695 # We've already deleted the block, now we have to stuff its IPs into the pool.
696 my $sth2 = $dbh->prepare("insert into poolips values ('209.91.185.0/24',?,'6750400','Sudbury','di','y','','','')");
697 $sth2->execute($cidr->addr);
698 foreach my $ip ($cidr->hostenum) {
699 $sth2->execute("$ip");
700 }
701 $cidr--;
702 $sth2->execute($cidr->addr);
703
704##TEMP
705} else {
706##TEMP
707
708 # Now we look for larger-or-equal-sized free blocks in the same master (routed)
709 # (super)block. If there aren't any, we can't combine blocks anyway. If there
710 # are, we check to see if we can combine blocks.
711 # Execute the statement prepared in the if-else above.
712
713 $sth->execute;
714
715# NetAddr::IP->compact() attempts to produce the smallest inclusive block
716# from the caller and the passed terms.
717# EG: if you call $cidr->compact($ip1,$ip2,$ip3) when $cidr, $ip1, $ip2,
718# and $ip3 are consecutive /27's starting on .0 (.0-.31, .32-.63,
719# .64-.95, and .96-.128), you will get an array containing a single
720# /25 as element 0 (.0-.127). Order is not important; you could have
721# $cidr=.32/27, $ip1=.96/27, $ip2=.0/27, and $ip3=.64/27.
722
723 my (@together, @combinelist);
724 my $i=0;
725 while (my @data = $sth->fetchrow_array) {
726 my $testIP = new NetAddr::IP $data[0];
727 @together = $testIP->compact($cidr);
728 my $num = @together;
729 if ($num == 1) {
730 $cidr = $together[0];
731 $combinelist[$i++] = $testIP;
732 }
733 }
734
735 # Clear old freeblocks entries - if any. They should all be within
736 # the $cidr determined above.
737 $sth = $dbh->prepare("delete from freeblocks where cidr <<='$cidr'");
738 $sth->execute;
739
740 # insert "new" freeblocks entry
741 if ($type eq 'rm') {
742 $sth = $dbh->prepare("insert into freeblocks (cidr,maskbits,city)".
743 " values ('$cidr',".$cidr->masklen.",'<NULL>')");
744 } else {
745 # Magic hackery to insert "correct" data for deallocation of
746 # non-contained blocks allocated from within a container.
747 $type = 'pr' if $con_type && $con_type eq 'pc';
748
749 $sth = $dbh->prepare("insert into freeblocks (cidr,maskbits,city,routed)".
750 " values ('$cidr',".$cidr->masklen.
751 ",(select city from routed where cidr >>= '$cidr'),'".
752 (($type =~ /^(.)r$/) ? "$1" : 'y')."')");
753 }
754 $sth->execute;
755
756##TEMP
757}
758##TEMP
759
760 # If we got here, we've succeeded. Whew!
761 $dbh->commit;
762 }; # end eval
763 if ($@) {
764 eval { $dbh->rollback; };
765 return ('FAIL', $msg);
766 } else {
767 return ('OK',"OK");
768 }
769
770 } # end alloctype != netblock
771
772} # end deleteBlock()
773
774
775## IPDB::getBlockData()
776# Return custid, type, city, and description for a block
777sub getBlockData {
778 my $dbh = shift;
779 my $block = shift;
780
781 my $sth = $dbh->prepare("select cidr,custid,type,city,description from searchme".
782 " where cidr='$block'");
783 $sth->execute();
784 return $sth->fetchrow_array();
785} # end getBlockData()
786
787
788## IPDB::mailNotify()
789# Sends notification mail to recipients regarding an IPDB operation
790sub mailNotify ($$$) {
791 my ($recip,$subj,$message) = @_;
792 my $mailer = Net::SMTP->new("smtp.example.com", Hello => "ipdb.example.com");
793
794 $mailer->mail('ipdb@example.com');
795 $mailer->to($recip);
796 $mailer->data("From: \"IP Database\" <ipdb\@example.com>\n",
797 "To: $recip\n",
798 "Date: ".strftime("%a, %d %b %Y %H:%M:%S %z",localtime)."\n",
799 "Subject: {IPDB} $subj\n",
800 "X-Mailer: IPDB Notify v".sprintf("%.1d",$IPDB::VERSION)."\n",
801 "Organization: Example Corp\n",
802 "\n$message\n");
803 $mailer->quit;
804}
805
806# Indicates module loaded OK. Required by Perl.
8071;
Note: See TracBrowser for help on using the repository browser.