source: branches/stable/cgi-bin/IPDB.pm@ 592

Last change on this file since 592 was 592, checked in by Kris Deugau, 11 years ago

/branches/stable

Merge /trunk changes up to r516

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