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

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

/trunk

Update mailNotify to use new table notify to decide who to spam
with notices on various events. See #2.

  • existing notification calls updated. Still need to move calls into IPDB.pm's subs
  • IPDB.pm and MyIPDB.pm updated with new semiglobal vars for org name, SMTP host, domain. Will add others as needed so MyIPDB.pm can be moved to /etc/ipdb/ (see #17).

Internal allocation types will need to be rearranged somewhat to
make full use of the flexibility possible. See #20.

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