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

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

/trunk

Rearrangements and tweaks toward releaseability:

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