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

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

/branches/htmlform

Convert initial DB connection error output to a sane page. Could arguably provide
space for this (and other) errors on all normal pages. (See #3).
This allows us to:

  • Remove editError sub in main.cgi
  • Remove printHeader sub in CommonWeb.pm (see #15, #26)

Removed duplicate "exit if we get this far"
Tweak IPDB::finish so it doesn't spit a fatal error when called with a null database handle

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