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

Last change on this file since 518 was 518, checked in by Kris Deugau, 12 years ago

/trunk

Update addMaster() to use ?-substitution in SQL. See #34.

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