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

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

/trunk

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

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