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

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

/trunk

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