source: branches/htmlform/cgi-bin/IPDB.pm@ 517

Last change on this file since 517 was 503, checked in by Kris Deugau, 13 years ago

/branches/htmlform

Checkpoint, clearing out references to printError()
All ACL checks that generate error pages should now be converted
to use the new aclerror template. See #15.
Fix a minor bug in CustIDCK.pm - calls to custid_check are being
treated as an object call for some reason.

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