source: branches/htmlform/cgi-bin/IPDB.pm@ 503

Last change on this file since 503 was 503, checked in by Kris Deugau, 13 years ago

/branches/htmlform

Checkpoint, clearing out references to printError()
All ACL checks that generate error pages should now be converted
to use the new aclerror template. See #15.
Fix a minor bug in CustIDCK.pm - calls to custid_check are being
treated as an object call for some reason.

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