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

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

/trunk

Clean up and move SQL for showmaster to IPDB.pm. See #34.
Tweak template to use odd for row colors

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