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

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

/trunk

Clean up and move SQL for static IP pool list to IPDB.pm. See #34.

  • Rename listPool in main.cgi to showPool, so that we can:
  • Add listPool sub in IPDB.pm
  • Convert getBlockData to return a hashref instead of an array, and update the one extant call

Tweak template to use odd for row colors

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