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

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

/trunk

Move SQL for index/summary page into IPDB.pm. See #34.
Tweak initialization of page templates to set loop_context_vars so
we don't have to manually maintain the row0/row1 entries
Commentstub subs for master and routed list pages.

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