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

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

/branches/htmlform

Convert initial DB connection error output to a sane page. Could arguably provide
space for this (and other) errors on all normal pages. (See #3).
This allows us to:

  • Remove editError sub in main.cgi
  • Remove printHeader sub in CommonWeb.pm (see #15, #26)

Removed duplicate "exit if we get this far"
Tweak IPDB::finish so it doesn't spit a fatal error when called with a null database handle

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