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

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

/trunk

Work in progress, see #5:
Fix subtle ordering bug in deleteBlock() handling legacy netblocks
allocated from a static IP pool; the whole point of the special
handling is to NOT make the IPs in it available for general
allocation.

  • Property svn:keywords set to Date Rev Author
File size: 47.9 KB
RevLine 
[8]1# ipdb/cgi-bin/IPDB.pm
[66]2# Contains functions for IPDB - database access, subnet mangling, block allocation, etc
[8]3###
4# SVN revision info
5# $Date: 2012-12-19 20:27:02 +0000 (Wed, 19 Dec 2012) $
6# SVN revision $Rev: 559 $
7# Last update by $Author: kdeugau $
8###
[417]9# Copyright (C) 2004-2010 - Kris Deugau
[8]10
[4]11package IPDB;
12
13use strict;
14use warnings;
15use Exporter;
[77]16use DBI;
[66]17use Net::SMTP;
[371]18use NetAddr::IP qw( Compact );
[68]19use POSIX;
[4]20use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
21
[417]22$VERSION = 2; ##VERSION##
[4]23@ISA = qw(Exporter);
[106]24@EXPORT_OK = qw(
[541]25 %disp_alloctypes %list_alloctypes %def_custids @citylist @poplist
26 %IPDBacl %aclmsg
[523]27 &initIPDBGlobals &connectDB &finish &checkDBSanity
[547]28 &addMaster &touchMaster
[528]29 &listSummary &listMaster &listRBlock &listFree &listPool
[541]30 &getMasterList &getTypeList &getPoolSelect &findAllocateFrom
[536]31 &ipParent &subParent &blockParent &getRoutedCity
[531]32 &allocateBlock &updateBlock &deleteBlock &getBlockData
[530]33 &getNodeList &getNodeName &getNodeInfo
[519]34 &mailNotify
[106]35 );
[4]36
37@EXPORT = (); # Export nothing by default.
[106]38%EXPORT_TAGS = ( ALL => [qw(
[167]39 %disp_alloctypes %list_alloctypes %def_custids @citylist @poplist
[541]40 %IPDBacl %aclmsg
[523]41 &initIPDBGlobals &connectDB &finish &checkDBSanity
[547]42 &addMaster &touchMaster
[528]43 &listSummary &listMaster &listRBlock &listFree &listPool
[541]44 &getMasterList &getTypeList &getPoolSelect &findAllocateFrom
[536]45 &ipParent &subParent &blockParent &getRoutedCity
[531]46 &allocateBlock &updateBlock &deleteBlock &getBlockData
[530]47 &getNodeList &getNodeName &getNodeInfo
[519]48 &mailNotify
[106]49 )]
50 );
[4]51
[77]52##
53## Global variables
54##
55our %disp_alloctypes;
56our %list_alloctypes;
[167]57our %def_custids;
[96]58our @citylist;
59our @poplist;
[233]60our %IPDBacl;
[66]61
[517]62# mapping table for functional-area => error message
63our %aclmsg = (
64 addmaster => 'add a master block',
65 addblock => 'add an allocation',
66 updateblock => 'update a block',
67 delblock => 'delete an allocation',
68 );
69
[417]70our $org_name = 'Example Corp';
[416]71our $smtphost = 'smtp.example.com';
72our $domain = 'example.com';
[417]73our $defcustid = '5554242';
74# mostly for rwhois
75##fixme: leave these blank by default?
[420]76our $rwhoisDataPath = '/usr/local/rwhoisd/etc/rwhoisd'; # to match ./configure defaults from rwhoisd-1.5.9.6
[417]77our $org_street = '123 4th Street';
78our $org_city = 'Anytown';
79our $org_prov_state = 'ON';
80our $org_pocode = 'H0H 0H0';
81our $org_country = 'CA';
82our $org_phone = '000-555-1234';
83our $org_techhandle = 'ISP-ARIN-HANDLE';
[434]84our $org_email = 'noc@example.com';
[437]85our $hostmaster = 'dns@example.com';
[416]86
[417]87our $syslog_facility = 'local2';
88
[77]89# Let's initialize the globals.
90## IPDB::initIPDBGlobals()
91# Initialize all globals. Takes a database handle, returns a success or error code
92sub initIPDBGlobals {
93 my $dbh = $_[0];
94 my $sth;
95
[106]96 # Initialize alloctypes hashes
[167]97 $sth = $dbh->prepare("select type,listname,dispname,listorder,def_custid from alloctypes order by listorder");
[77]98 $sth->execute;
99 while (my @data = $sth->fetchrow_array) {
[106]100 $disp_alloctypes{$data[0]} = $data[2];
[167]101 $def_custids{$data[0]} = $data[4];
[106]102 if ($data[3] < 900) {
103 $list_alloctypes{$data[0]} = $data[1];
104 }
[77]105 }
[96]106
107 # City and POP listings
[157]108 $sth = $dbh->prepare("select city,routing from cities order by city");
[96]109 $sth->execute;
110 return (undef,$sth->errstr) if $sth->err;
111 while (my @data = $sth->fetchrow_array) {
[106]112 push @citylist, $data[0];
[96]113 if ($data[1] eq 'y') {
[106]114 push @poplist, $data[0];
[96]115 }
116 }
117
[233]118 # Load ACL data. Specific username checks are done at a different level.
119 $sth = $dbh->prepare("select username,acl from users");
120 $sth->execute;
[106]121 return (undef,$sth->errstr) if $sth->err;
[233]122 while (my @data = $sth->fetchrow_array) {
123 $IPDBacl{$data[0]} = $data[1];
124 }
[106]125
[517]126##fixme: initialize HTML::Template env var for template path
127# something like $self->path().'/templates' ?
128# $ENV{HTML_TEMPLATE_ROOT} = 'foo/bar';
129
[77]130 return (1,"OK");
131} # end initIPDBGlobals
132
133
134## IPDB::connectDB()
[4]135# Creates connection to IPDB.
[77]136# Requires the database name, username, and password.
[4]137# Returns a handle to the db.
[77]138# Set up for a PostgreSQL db; could be any transactional DBMS with the
139# right changes.
[4]140sub connectDB {
[432]141 my $dbname = shift;
142 my $user = shift;
143 my $pass = shift;
144 my $dbhost = shift;
145
[4]146 my $dbh;
[432]147 my $DSN = "DBI:Pg:".($dbhost ? "host=$dbhost;" : '')."dbname=$dbname";
[4]148
149# Note that we want to autocommit by default, and we will turn it off locally as necessary.
[77]150# We may not want to print gobbledygook errors; YMMV. Have to ponder that further.
151 $dbh = DBI->connect($DSN, $user, $pass, {
152 AutoCommit => 1,
153 PrintError => 0
154 })
155 or return (undef, $DBI::errstr) if(!$dbh);
[4]156
[77]157# Return here if we can't select. Note that this indicates a
158# problem executing the select.
[183]159 my $sth = $dbh->prepare("select type from alloctypes");
[77]160 $sth->execute();
161 return (undef,$DBI::errstr) if ($sth->err);
162
163# See if the select returned anything (or null data). This should
164# succeed if the select executed, but...
165 $sth->fetchrow();
166 return (undef,$DBI::errstr) if ($sth->err);
167
168# If we get here, we should be OK.
169 return ($dbh,"DB connection OK");
[4]170} # end connectDB
171
[77]172
173## IPDB::finish()
174# Cleans up after database handles and so on.
175# Requires a database handle
176sub finish {
177 my $dbh = $_[0];
[517]178 $dbh->disconnect if $dbh;
[77]179} # end finish
180
181
[106]182## IPDB::checkDBSanity()
[4]183# Quick check to see if the db is responding. A full integrity
184# check will have to be a separate tool to walk the IP allocation trees.
185sub checkDBSanity {
[106]186 my ($dbh) = $_[0];
[4]187
188 if (!$dbh) {
[106]189 print "No database handle, or connection has been closed.";
190 return -1;
[4]191 } else {
192 # it connects, try a stmt.
[184]193 my $sth = $dbh->prepare("select type from alloctypes");
[4]194 my $err = $sth->execute();
195
196 if ($sth->fetchrow()) {
197 # all is well.
198 return 1;
199 } else {
[16]200 print "Connected to the database, but could not execute test statement. ".$sth->errstr();
[106]201 return -1;
[4]202 }
203 }
204 # Clean up after ourselves.
[106]205# $dbh->disconnect;
[4]206} # end checkDBSanity
207
[66]208
[371]209## IPDB::addMaster()
210# Does all the magic necessary to sucessfully add a master block
211# Requires database handle, block to add
212# Returns failure code and error message or success code and "message"
213sub addMaster {
214 my $dbh = shift;
215 my $cidr = new NetAddr::IP shift;
216
217 # Allow transactions, and raise an exception on errors so we can catch it later.
218 # Use local to make sure these get "reset" properly on exiting this block
219 local $dbh->{AutoCommit} = 0;
220 local $dbh->{RaiseError} = 1;
221
222 # Wrap all the SQL in a transaction
223 eval {
[518]224 my ($mexist) = $dbh->selectrow_array("SELECT cidr FROM masterblocks WHERE cidr <<= ?", undef, ($cidr) );
[371]225
[518]226 if (!$mexist) {
[371]227 # First case - master is brand-spanking-new.
228##fixme: rwhois should be globally-flagable somewhere, much like a number of other things
229## maybe a db table called "config"?
[518]230 $dbh->do("INSERT INTO masterblocks (cidr,rwhois) VALUES (?,?)", undef, ($cidr,'y') );
[371]231
232# Unrouted blocks aren't associated with a city (yet). We don't rely on this
233# elsewhere though; legacy data may have traps and pitfalls in it to break this.
234# Thus the "routed" flag.
[556]235 $dbh->do("INSERT INTO freeblocks (cidr,maskbits,city,routed,parent,rdepth) VALUES (?,?,?,?,?,?)", undef,
236 ($cidr, $cidr->masklen, '<NULL>', 'm', $cidr, 1) );
[371]237
238 # If we get here, everything is happy. Commit changes.
239 $dbh->commit;
240
[518]241 } # done new master does not contain existing master(s)
[371]242 else {
243
244 # collect the master(s) we're going to absorb, and snag the longest netmask while we're at it.
245 my $smallmask = $cidr->masklen;
[518]246 my $sth = $dbh->prepare("SELECT cidr FROM masterblocks WHERE cidr <<= ?");
247 $sth->execute($cidr);
[371]248 my @cmasters;
249 while (my @data = $sth->fetchrow_array) {
250 my $master = new NetAddr::IP $data[0];
251 push @cmasters, $master;
252 $smallmask = $master->masklen if $master->masklen > $smallmask;
253 }
254
255 # split the new master, and keep only those blocks not part of an existing master
256 my @blocklist;
257 foreach my $seg ($cidr->split($smallmask)) {
258 my $contained = 0;
259 foreach my $master (@cmasters) {
260 $contained = 1 if $master->contains($seg);
261 }
262 push @blocklist, $seg if !$contained;
263 }
264
265 # collect the unrouted free blocks within the new master
[556]266 $sth = $dbh->prepare("SELECT cidr FROM freeblocks WHERE masklen(cidr) <= ? AND cidr <<= ? AND routed = 'm'");
[518]267 $sth->execute($smallmask, $cidr);
[371]268 while (my @data = $sth->fetchrow_array) {
269 my $freeblock = new NetAddr::IP $data[0];
270 push @blocklist, $freeblock;
271 }
272
273 # combine the set of free blocks we should have now.
274 @blocklist = Compact(@blocklist);
275
276 # and now insert the new data. Make sure to delete old masters too.
277
278 # freeblocks
[518]279 $sth = $dbh->prepare("DELETE FROM freeblocks WHERE cidr <<= ?");
[556]280 my $sth2 = $dbh->prepare("INSERT INTO freeblocks (cidr,maskbits,city,routed,parent,rdepth)".
281 " VALUES (?,?,'<NULL>','m',?,1)");
[371]282 foreach my $newblock (@blocklist) {
[518]283 $sth->execute($newblock);
[556]284 $sth2->execute($newblock, $newblock->masklen, $cidr);
[371]285 }
286
[556]287 # update parent relations at rdepth=1
288 $dbh->do("UPDATE allocations SET parent = ? WHERE parent << ? AND rdepth=1", undef, ($cidr, $cidr) );
289 $dbh->do("UPDATE freeblocks SET parent = ? WHERE parent << ? AND rdepth=1", undef, ($cidr, $cidr) );
290
[371]291 # master
[518]292 $dbh->do("DELETE FROM masterblocks WHERE cidr <<= ?", undef, ($cidr) );
293 $dbh->do("INSERT INTO masterblocks (cidr,rwhois) VALUES (?,?)", undef, ($cidr, 'y') );
[371]294
295 # *whew* If we got here, we likely suceeded.
296 $dbh->commit;
297 } # new master contained existing master(s)
298 }; # end eval
299
300 if ($@) {
301 my $msg = $@;
302 eval { $dbh->rollback; };
303 return ('FAIL',$msg);
304 } else {
305 return ('OK','OK');
306 }
307} # end addMaster
308
309
[547]310## IPDB::touchMaster()
311# Update last-changed timestamp on a master block.
312sub touchMaster {
313 my $dbh = shift;
314 my $master = shift;
315
316 local $dbh->{AutoCommit} = 0;
317 local $dbh->{RaiseError} = 1;
318
319 eval {
320 $dbh->do("UPDATE masterblocks SET mtime=now() WHERE cidr = ?", undef, ($master));
321 $dbh->commit;
322 };
323
324 if ($@) {
325 my $msg = $@;
326 eval { $dbh->rollback; };
327 return ('FAIL',$msg);
328 }
329 return ('OK','OK');
330} # end touchMaster()
331
332
[523]333## IPDB::listSummary()
334# Get summary list of all master blocks
335# Returns an arrayref to a list of hashrefs containing the master block, routed count,
336# allocated count, free count, and largest free block masklength
337sub listSummary {
338 my $dbh = shift;
339
340 my $mlist = $dbh->selectall_arrayref("SELECT cidr AS master FROM masterblocks ORDER BY cidr", { Slice => {} });
341
342 foreach (@{$mlist}) {
343 my ($rcnt) = $dbh->selectrow_array("SELECT count(*) FROM routed WHERE cidr <<= ?", undef, ($$_{master}));
344 $$_{routed} = $rcnt;
345 my ($acnt) = $dbh->selectrow_array("SELECT count(*) FROM allocations WHERE cidr <<= ?", undef, ($$_{master}));
346 $$_{allocated} = $acnt;
347 my ($fcnt) = $dbh->selectrow_array("SELECT count(*) FROM freeblocks WHERE cidr <<= ?".
348 " AND (routed='y' OR routed='n')", undef, ($$_{master}));
349 $$_{free} = $fcnt;
350 my ($bigfree) = $dbh->selectrow_array("SELECT maskbits FROM freeblocks WHERE cidr <<= ?".
351 " AND (routed='y' OR routed='n') ORDER BY maskbits LIMIT 1", undef, ($$_{master}));
352##fixme: should find a way to do this without having to HTMLize the <>
353 $bigfree = "/$bigfree" if $bigfree;
[525]354 $bigfree = '<NONE>' if !$bigfree;
[523]355 $$_{bigfree} = $bigfree;
356 }
357 return $mlist;
358} # end listSummary()
359
360
[524]361## IPDB::listMaster()
362# Get list of routed blocks in the requested master
363# Returns an arrayref to a list of hashrefs containing the routed block, POP/city the block is routed to,
364# allocated count, free count, and largest free block masklength
365sub listMaster {
366 my $dbh = shift;
367 my $master = shift;
[523]368
[524]369 my $rlist = $dbh->selectall_arrayref("SELECT cidr AS block,city FROM routed WHERE cidr <<= ? ORDER BY cidr",
370 { Slice => {} }, ($master) );
[523]371
[524]372 foreach (@{$rlist}) {
373 my ($acnt) = $dbh->selectrow_array("SELECT count(*) FROM allocations WHERE cidr <<= ?", undef, ($$_{block}));
374 $$_{nsubs} = $acnt;
375 my ($fcnt) = $dbh->selectrow_array("SELECT count(*) FROM freeblocks WHERE cidr <<= ?".
376 " AND (routed='y' OR routed='n')", undef, ($$_{block}));
377 $$_{nfree} = $fcnt;
378 my ($bigfree) = $dbh->selectrow_array("SELECT maskbits FROM freeblocks WHERE cidr <<= ?".
379 " AND (routed='y' OR routed='n') ORDER BY maskbits LIMIT 1", undef, ($$_{block}));
380##fixme: should find a way to do this without having to HTMLize the <>
381 $bigfree = "/$bigfree" if $bigfree;
[525]382 $bigfree = '<NONE>' if !$bigfree;
[524]383 $$_{lfree} = $bigfree;
384 }
385 return $rlist;
386} # end listMaster()
387
388
[527]389## IPDB::listRBlock()
390# Gets a list of free blocks in the requested parent/master in both CIDR and range notation
391# Takes a parent/master and an optional flag to look at routed or unrouted blocks, depending
392# on whether the master is a direct master or a routed block
393# Returns an arrayref to a list of hashrefs containing the CIDR and range-notation blocks
394sub listRBlock {
395 my $dbh = shift;
396 my $routed = shift;
[524]397
[527]398 # Snag the allocations for this block
399 my $sth = $dbh->prepare("SELECT cidr,city,type,custid,swip,description".
400 " FROM allocations WHERE cidr <<= ? ORDER BY cidr");
401 $sth->execute($routed);
[524]402
[527]403 # hack hack hack
404 # set up to flag swip=y records if they don't actually have supporting data in the customers table
405 my $custsth = $dbh->prepare("SELECT count(*) FROM customers WHERE custid = ?");
406
407 my @blocklist;
408 while (my ($cidr,$city,$type,$custid,$swip,$desc) = $sth->fetchrow_array()) {
409 $custsth->execute($custid);
410 my ($ncust) = $custsth->fetchrow_array();
411 my %row = (
412 block => $cidr,
413 city => $city,
414 type => $disp_alloctypes{$type},
415 custid => $custid,
416 swip => ($swip eq 'y' ? 'Yes' : 'No'),
417 partswip => ($swip eq 'y' && $ncust == 0 ? 1 : 0),
418 desc => $desc
419 );
420 $row{subblock} = ($type =~ /^.r$/); # hmf. wonder why these won't work in the hash declaration...
421 $row{listpool} = ($type =~ /^.[pd]$/);
422 push (@blocklist, \%row);
423 }
424 return \@blocklist;
425} # end listRBlock()
426
427
[524]428## IPDB::listFree()
429# Gets a list of free blocks in the requested parent/master in both CIDR and range notation
[527]430# Takes a parent/master and an optional "routed or unrouted" flag that defaults to unrouted.
[524]431# Returns an arrayref to a list of hashrefs containing the CIDR and range-notation blocks
[527]432# Returns some extra flags in the hashrefs for routed blocks, since those can have several subtypes
[524]433sub listFree {
434 my $dbh = shift;
435 my $master = shift;
[527]436 my $routed = shift || 'n';
[524]437
438 # do it this way so we can waste a little less time iterating
[527]439 my $sth = $dbh->prepare("SELECT cidr,routed FROM freeblocks WHERE cidr <<= ? AND ".
440 ($routed eq 'n' ? '' : 'NOT')." routed = 'n' ORDER BY cidr");
441 $sth->execute($master);
[524]442 my @flist;
[527]443 while (my ($cidr,$rtype) = $sth->fetchrow_array()) {
[524]444 $cidr = new NetAddr::IP $cidr;
[527]445 my %row = (
446 fblock => "$cidr",
447 frange => $cidr->range,
448 );
449 if ($routed eq 'y') {
450 $row{subblock} = ($rtype ne 'y' && $rtype ne 'n');
451 $row{fbtype} = $rtype;
452 }
[524]453 push @flist, \%row;
454 }
455 return \@flist;
[527]456} # end listFree()
[524]457
458
[528]459## IPDB::listPool()
460#
461sub listPool {
462 my $dbh = shift;
463 my $pool = shift;
464
465 my $sth = $dbh->prepare("SELECT ip,custid,available,description,type".
466 " FROM poolips WHERE pool = ? ORDER BY ip");
467 $sth->execute($pool);
468 my @poolips;
469 while (my ($ip,$custid,$available,$desc,$type) = $sth->fetchrow_array) {
470 my %row = (
471 ip => $ip,
472 custid => $custid,
473 available => $available,
474 desc => $desc,
475 delme => $available eq 'n'
476 );
477 push @poolips, \%row;
478 }
479 return \@poolips;
480} # end listPool()
481
482
[541]483## IPDB::getMasterList()
484# Get a list of master blocks, optionally including last-modified timestamps
485# Takes an optional flag to indicate whether to include timestamps;
486# 'm' includes ctime, all others (suggest 'c') do not.
487# Returns an arrayref to a list of hashrefs
488sub getMasterList {
489 my $dbh = shift;
490 my $stampme = shift || 'm'; # optional but should be set by caller for clarity
491
492 my $mlist = $dbh->selectall_arrayref("SELECT cidr AS master".($stampme eq 'm' ? ',mtime' : '').
493 " FROM masterblocks ORDER BY cidr", { Slice => {} });
494 return $mlist;
495} # end getMasterList()
496
497
[529]498## IPDB::getTypeList()
499# Get an alloctype/description pair list suitable for dropdowns
500# Takes a flag to determine which general groups of types are returned
501# Returns an reference to an array of hashrefs
502sub getTypeList {
503 my $dbh = shift;
504 my $tgroup = shift || 'a'; # technically optional, like this, but should
505 # really be specified in the call for clarity
506 my $tlist;
507 if ($tgroup eq 'p') {
508 # grouping 'p' - primary allocation types. These include static IP pools (_d and _p),
509 # dynamic-allocation ranges (_e), containers (_c), and the "miscellaneous" cn, in, and en types.
510 $tlist = $dbh->selectall_arrayref("SELECT type,listname FROM alloctypes WHERE listorder < 500 ".
511 "AND type NOT LIKE '_i' AND type NOT LIKE '_r' ORDER BY listorder", { Slice => {} });
512 } elsif ($tgroup eq 'c') {
513 # grouping 'c' - contained types. These include all static IPs and all _r types.
514 $tlist = $dbh->selectall_arrayref("SELECT type,listname FROM alloctypes WHERE listorder <= 500 ".
515 " AND (type LIKE '_i' OR type LIKE '_r') ORDER BY listorder", { Slice => {} });
516 } else {
517 # grouping 'a' - all standard allocation types. This includes everything
518 # but mm (present only as a formality). Make this the default.
519 $tlist = $dbh->selectall_arrayref("SELECT type,listname FROM alloctypes WHERE listorder <= 500 ".
520 " ORDER BY listorder", { Slice => {} });
521 }
522 return $tlist;
523}
524
525
[532]526## IPDB::getPoolSelect()
527# Get a list of pools matching the passed city and type that have 1 or more free IPs
[533]528# Returns an arrayref to a list of hashrefs
[532]529sub getPoolSelect {
530 my $dbh = shift;
531 my $iptype = shift;
532 my $pcity = shift;
533
534 my ($ptype) = ($iptype =~ /^(.)i$/);
535 return if !$ptype;
536 $ptype .= '_';
537
538 my $plist = $dbh->selectall_arrayref(
539 "SELECT (SELECT city FROM allocations WHERE cidr=poolips.pool) AS poolcit, ".
540 "poolips.pool AS poolblock, COUNT(*) AS poolfree FROM poolips,allocations ".
541 "WHERE poolips.available='y' AND poolips.pool=allocations.cidr ".
542 "AND allocations.city = ? AND poolips.type LIKE ? ".
543 "GROUP BY pool", { Slice => {} }, ($pcity, $ptype) );
544 return $plist;
545} # end getPoolSelect()
546
547
[533]548## IPDB::findAllocateFrom()
549# Find free block to add a new allocation from. (CIDR block version of pool select above, more or less)
550# Takes
551# - mask length
552# - allocation type
553# - POP city "parent"
554# - optional master-block restriction
555# - optional flag to allow automatic pick-from-private-network-ranges
556# Returns a string with the first CIDR block matching the criteria, if any
557sub findAllocateFrom {
558 my $dbh = shift;
559 my $maskbits = shift;
560 my $type = shift;
561 my $city = shift;
562 my $pop = shift;
563 my %optargs = @_;
564
565 my $failmsg = "No suitable free block found\n";
566
567## Set up the SQL to find out what freeblock we can (probably) use for an allocation.
568## Very large systems will require development of a reserve system (possibly an extension
569## of the reserve-for-expansion concept in https://secure.deepnet.cx/trac/ipdb/ticket/24?)
570## Also populate a value list for the DBI call.
571
572 my @vallist = ($maskbits, ($type eq 'rm' ? 'n' : ($type =~ /^(.)r$/ ? "$1" : 'y')) );
573 my $sql = "SELECT cidr FROM freeblocks WHERE maskbits <= ? AND routed = ?";
574
575 # for PPP(oE) and container types, the POP city is the one attached to the pool.
576 # individual allocations get listed with the customer city site.
577 ##fixme: chain cities to align roughly with a full layer-2 node graph
578 $city = $pop if $type !~ /^.[pc]$/;
[544]579 if ($type ne 'rm' && $city) {
[533]580 $sql .= " AND city = ?";
581 push @vallist, $city;
582 }
[544]583 # Allow specifying an arbitrary full block, instead of a master
584 if ($optargs{gimme}) {
585 $sql .= " AND cidr >>= ?";
586 push @vallist, $optargs{gimme};
587 }
[533]588 # if a specific master was requested, allow the requestor to self->shoot(foot)
589 if ($optargs{master} && $optargs{master} ne '-') {
590 $sql .= " AND cidr <<= ?" if $optargs{master} ne '-';
591 push @vallist, $optargs{master};
592 } else {
593 # if a specific master was NOT requested, filter out the RFC 1918 private networks
594 if (!$optargs{allowpriv}) {
595 $sql .= " AND NOT (cidr <<= '192.168.0.0/16' OR cidr <<= '10.0.0.0/8' OR cidr <<= '172.16.0.0/12')";
596 }
597 }
598 # Sorting and limiting, since we don't (currently) care to provide a selection of
599 # blocks to carve up. This preserves something resembling optimal usage of the IP
600 # space by forcing contiguous allocations and free blocks as much as possible.
601 $sql .= " ORDER BY maskbits DESC,cidr LIMIT 1";
602
603 my ($fbfound) = $dbh->selectrow_array($sql, undef, @vallist);
604 return $fbfound;
605} # end findAllocateFrom()
606
607
[536]608## IPDB::ipParent()
609# Get an IP's parent pool's details
610# Takes a database handle and IP
611# Returns a hashref to the parent pool block, if any
612sub ipParent {
613 my $dbh = shift;
614 my $block = shift;
615
616 my $pinfo = $dbh->selectrow_hashref("SELECT cidr,custid,type,city,description FROM allocations".
617 " WHERE cidr >>= ?", undef, ($block) );
618 return $pinfo;
619} # end ipParent()
620
621
622## IPDB::subParent()
[529]623# Get a block's parent's details
624# Takes a database handle and CIDR block
[536]625# Returns a hashref to the parent container block, if any
626sub subParent {
[529]627 my $dbh = shift;
628 my $block = shift;
629
630 my $pinfo = $dbh->selectrow_hashref("SELECT cidr,custid,type,city,description FROM allocations".
631 " WHERE cidr >>= ?", undef, ($block) );
632 return $pinfo;
[536]633} # end subParent()
[529]634
635
[536]636## IPDB::blockParent()
637# Get a block's parent's details
638# Takes a database handle and CIDR block
639# Returns a hashref to the parent container block, if any
640sub blockParent {
641 my $dbh = shift;
642 my $block = shift;
643
644 my $pinfo = $dbh->selectrow_hashref("SELECT cidr,city FROM routed".
645 " WHERE cidr >>= ?", undef, ($block) );
646 return $pinfo;
647} # end blockParent()
648
649
[527]650## IPDB::getRoutedCity()
651# Get the city for a routed block.
652sub getRoutedCity {
653 my $dbh = shift;
654 my $block = shift;
655
656 my ($rcity) = $dbh->selectrow_array("SELECT city FROM routed WHERE cidr = ?", undef, ($block) );
657 return $rcity;
658} # end getRoutedCity()
659
660
[77]661## IPDB::allocateBlock()
[66]662# Does all of the magic of actually allocating a netblock
[554]663# Requires a database handle, and a hash containing the block to allocate, routing depth, custid,
664# type, city, block to allocate from, and optionally a description, notes, circuit ID,
665# and private data
[77]666# Returns a success code and optional error message.
667sub allocateBlock {
[554]668 my $dbh = shift;
[284]669
[554]670 my %args = @_;
671
672 $args{cidr} = new NetAddr::IP $args{cidr};
673 $args{alloc_from} = new NetAddr::IP $args{alloc_from};
674
675 $args{desc} = '' if !$args{desc};
676 $args{notes} = '' if !$args{notes};
677 $args{circid} = '' if !$args{circid};
678 $args{privdata} = '' if !$args{privdata};
679 $args{vrf} = '' if !$args{vrf};
680
[77]681 my $sth;
[66]682
[349]683 # Snag the "type" of the freeblock (alloc_from) "just in case"
[554]684 $sth = $dbh->prepare("select routed from freeblocks where cidr='$args{alloc_from}'");
[349]685 $sth->execute;
686 my ($alloc_from_type) = $sth->fetchrow_array;
687
[79]688 # To contain the error message, if any.
[554]689 my $msg = "Unknown error allocating $args{cidr} as '$disp_alloctypes{$args{type}}'";
[79]690
[77]691 # Enable transactions and error handling
692 local $dbh->{AutoCommit} = 0; # These need to be local so we don't
693 local $dbh->{RaiseError} = 1; # step on our toes by accident.
[66]694
[554]695 if ($args{type} =~ /^.i$/) {
696 $msg = "Unable to assign static IP $args{cidr} to $args{custid}";
[77]697 eval {
[554]698 if ($args{cidr}) { # IP specified
699 my ($isavail) = $dbh->selectrow_array("SELECT available FROM poolips WHERE ip=?", undef, ($args{cidr}) );
700 die "IP is not in an IP pool.\n"
701 if !$isavail;
702 die "IP already allocated. Deallocate and reallocate, or update the entry\n"
703 if $isavail eq 'n';
704 } else { # IP not specified, take first available
705 ($args{cidr}) = $dbh->selectrow_array("SELECT ip FROM poolips WHERE pool=? AND available='y' ORDER BY ip",
706 undef, ($args{alloc_from}) );
[545]707 }
[554]708 $dbh->do("UPDATE poolips SET custid=?,city=?,available='n',description=?,notes=?,circuitid=?,privdata=?,vrf=? ".
709 "WHERE ip=?", undef, ($args{custid}, $args{city}, $args{desc}, $args{notes}, $args{circid},
710 $args{privdata}, $args{vrf}, $args{cidr}) );
[157]711
[397]712# node hack
[554]713 if ($args{nodeid} && $args{nodeid} ne '') {
714 $dbh->do("INSERT INTO noderef (block,node_id) VALUES (?,?)", undef, ($args{cidr}, $args{nodeid}) );
[397]715 }
716# end node hack
[545]717
[79]718 $dbh->commit;
[77]719 };
720 if ($@) {
[545]721 $msg .= ": $@";
[78]722 eval { $dbh->rollback; };
723 return ('FAIL',$msg);
[77]724 } else {
[554]725 return ('OK',"$args{cidr}");
[77]726 }
727
728 } else { # end IP-from-pool allocation
729
[554]730 if ($args{cidr} == $args{alloc_from}) {
[77]731 # Easiest case- insert in one table, delete in the other, and go home. More or less.
732 # insert into allocations values (cidr,custid,type,city,desc) and
733 # delete from freeblocks where cidr='cidr'
734 # For data safety on non-transaction DBs, we delete first.
735
736 eval {
[554]737 $msg = "Unable to allocate $args{cidr} as '$disp_alloctypes{$args{type}}'";
738
[555]739 # Get old freeblocks parent/depth/routed for new entries... before we delete it.
740 my ($fparent) = $dbh->selectrow_array("SELECT parent FROM freeblocks WHERE cidr=? AND rdepth=?",
741 undef, ($args{alloc_from}, $args{rdepth}) );
742
[554]743 # Munge freeblocks
744 if ($args{type} =~ /^(.)[mc]$/) {
745 # special case - block is a routed or container/"reserve" block
746 my $rtype = $1;
747 $dbh->do("UPDATE freeblocks SET routed=?,rdepth=rdepth+1,city=?,parent=? WHERE cidr=? AND rdepth=?",
748 undef, ($rtype, $args{city}, $args{cidr}, $args{cidr}, $args{rdepth}));
[77]749 } else {
[554]750 # "normal" case
751 $dbh->do("DELETE FROM freeblocks WHERE cidr=? AND rdepth=?", undef, ($args{cidr}, $args{rdepth}));
752 }
[77]753
[554]754 # Insert the allocations entry
755 $dbh->do("INSERT INTO allocations ".
756 "(cidr,parent,vrf,rdepth,custid,type,city,description,notes,circuitid,privdata)".
757 " VALUES (?,?,?,?,?,?,?,?,?,?,?)", undef,
758 ($args{cidr}, $fparent, $args{vrf}, $args{rdepth}, $args{custid}, $args{type}, $args{city},
759 $args{desc}, $args{notes}, $args{circid}, $args{privdata}) );
[79]760
[554]761 # And initialize the pool, if necessary
762 # PPPoE pools (currently dialup, DSL, and WiFi) get all IPs made available
763 # "DHCP" or "real-subnet" pools have the net, gw, and bcast IPs removed.
764 if ($args{type} =~ /^.p$/) {
765 $msg = "Could not initialize IPs in new $disp_alloctypes{$args{type}} $args{cidr}";
766 my ($code,$rmsg) = initPool($dbh, $args{cidr}, $args{type}, $args{city}, "all");
767 die $rmsg if $code eq 'FAIL';
768 } elsif ($args{type} =~ /^.d$/) {
769 $msg = "Could not initialize IPs in new $disp_alloctypes{$args{type}} $args{cidr}";
770 my ($code,$rmsg) = initPool($dbh, $args{cidr}, $args{type}, $args{city}, "normal");
771 die $rmsg if $code eq 'FAIL';
772 }
[79]773
[397]774# node hack
[554]775 if ($args{nodeid} && $args{nodeid} ne '') {
776 $dbh->do("INSERT INTO noderef (block,node_id) VALUES (?,?)", undef, ($args{cidr}, $args{nodeid}) );
[397]777 }
778# end node hack
[77]779 $dbh->commit;
[78]780 }; # end of eval
[77]781 if ($@) {
[157]782 $msg .= ": ".$@;
[77]783 eval { $dbh->rollback; };
[157]784 return ('FAIL',$msg);
[77]785 } else {
[78]786 return ('OK',"OK");
787 }
[77]788
789 } else { # cidr != alloc_from
790
791 # Hard case. Allocation is smaller than free block.
[554]792 my $wantmaskbits = $args{cidr}->masklen;
793 my $maskbits = $args{alloc_from}->masklen;
[77]794
795 my @newfreeblocks; # Holds free blocks generated from splitting the source freeblock.
796
797 # This determines which blocks will be left "free" after allocation. We take the
798 # block we're allocating from, and split it in half. We see which half the wanted
799 # block is in, and repeat until the wanted block is equal to one of the halves.
800 my $i=0;
[554]801 my $tmp_from = $args{alloc_from}; # So we don't munge $args{alloc_from}
[77]802 while ($maskbits++ < $wantmaskbits) {
803 my @subblocks = $tmp_from->split($maskbits);
[554]804 $newfreeblocks[$i++] = (($args{cidr}->within($subblocks[0])) ? $subblocks[1] : $subblocks[0]);
805 $tmp_from = ( ($args{cidr}->within($subblocks[0])) ? $subblocks[0] : $subblocks[1] );
[77]806 } # while
807
808 # Begin SQL transaction block
809 eval {
[554]810 $msg = "Unable to allocate $args{cidr} as '$disp_alloctypes{$args{type}}'";
[79]811
[554]812 # Get old freeblocks parent/depth/routed for new entries
813 my ($fparent,$fcity,$wasrouted) = $dbh->selectrow_array("SELECT parent,city,routed FROM freeblocks".
814 " WHERE cidr=? AND rdepth=?", undef, ($args{alloc_from}, $args{rdepth}) );
815
[77]816 # Delete old freeblocks entry
[554]817 $dbh->do("DELETE FROM freeblocks WHERE cidr=? AND rdepth=?", undef, ($args{alloc_from}, $args{rdepth}) );
[77]818
[554]819 # Insert new list of smaller free blocks left over
820 $sth = $dbh->prepare("INSERT INTO freeblocks (cidr,city,routed,vrf,parent,rdepth) VALUES (?,?,?,?,?,?)");
821 foreach my $block (@newfreeblocks) {
822 $sth->execute($block, $fcity, $wasrouted, $args{vrf}, $fparent, $args{rdepth});
823 }
[79]824
[554]825 # For routed/container types, add a freeblock within the allocated block so we can subdivide it further
826 if ($args{type} =~ /(.)[mc]/) { # rm and .c types - containers
827 my $rtype = $1;
828 $sth->execute($args{cidr}, $args{city}, $rtype, $args{vrf}, $args{cidr}, $args{rdepth}+1);
829 }
[79]830
[554]831 # Insert the allocations entry
832 $dbh->do("INSERT INTO allocations ".
833 "(cidr,parent,vrf,rdepth,custid,type,city,description,notes,circuitid,privdata)".
834 " VALUES (?,?,?,?,?,?,?,?,?,?,?)", undef,
835 ($args{cidr}, $fparent, $args{vrf}, $args{rdepth}, $args{custid}, $args{type}, $args{city},
836 $args{desc}, $args{notes}, $args{circid}, $args{privdata}) );
[77]837
[554]838 # And initialize the pool, if necessary
839 # PPPoE pools (currently dialup, DSL, and WiFi) get all IPs made available
840 # "DHCP" or "real-subnet" pools have the net, gw, and bcast IPs removed.
841 if ($args{type} =~ /^.p$/) {
842 $msg = "Could not initialize IPs in new $disp_alloctypes{$args{type}} $args{cidr}";
843 my ($code,$rmsg) = initPool($dbh, $args{cidr}, $args{type}, $args{city}, "all");
844 die $rmsg if $code eq 'FAIL';
845 } elsif ($args{type} =~ /^.d$/) {
846 $msg = "Could not initialize IPs in new $disp_alloctypes{$args{type}} $args{cidr}";
847 my ($code,$rmsg) = initPool($dbh, $args{cidr}, $args{type}, $args{city}, "normal");
848 die $rmsg if $code eq 'FAIL';
849 }
[77]850
[397]851# node hack
[554]852 if ($args{nodeid} && $args{nodeid} ne '') {
853 $dbh->do("INSERT INTO noderef (block,node_id) VALUES (?,?)", undef, ($args{cidr}, $args{nodeid}) );
[397]854 }
855# end node hack
[554]856
[77]857 $dbh->commit;
858 }; # end eval
859 if ($@) {
[256]860 $msg .= ": ".$@;
[77]861 eval { $dbh->rollback; };
[78]862 return ('FAIL',$msg);
[77]863 } else {
[78]864 return ('OK',"OK");
[77]865 }
866
867 } # end fullcidr != alloc_from
868
869 } # end static-IP vs netblock allocation
870
871} # end allocateBlock()
872
873
874## IPDB::initPool()
875# Initializes a pool
876# Requires a database handle, the pool CIDR, type, city, and a parameter
877# indicating whether the pool should allow allocation of literally every
878# IP, or if it should reserve network/gateway/broadcast IPs
[78]879# Note that this is NOT done in a transaction, that's why it's a private
880# function and should ONLY EVER get called from allocateBlock()
[77]881sub initPool {
882 my ($dbh,undef,$type,$city,$class) = @_;
883 my $pool = new NetAddr::IP $_[1];
884
[157]885##fixme Need to just replace 2nd char of type with i rather than capturing 1st char of type
886 $type =~ s/[pd]$/i/;
[77]887 my $sth;
[157]888 my $msg;
[77]889
[157]890 # Trap errors so we can pass them back to the caller. Even if the
891 # caller is only ever supposed to be local, and therefore already
892 # trapping errors. >:(
893 local $dbh->{AutoCommit} = 0; # These need to be local so we don't
894 local $dbh->{RaiseError} = 1; # step on our toes by accident.
895
896 eval {
897 # have to insert all pool IPs into poolips table as "unallocated".
898 $sth = $dbh->prepare("insert into poolips (pool,ip,custid,city,type)".
[485]899 " values ('$pool', ?, '$defcustid', ?, '$type')");
[157]900 my @poolip_list = $pool->hostenum;
901 if ($class eq 'all') { # (DSL-ish block - *all* IPs available
[246]902 if ($pool->addr !~ /\.0$/) { # .0 causes weirdness.
[485]903 $sth->execute($pool->addr, $city);
[246]904 }
[157]905 for (my $i=0; $i<=$#poolip_list; $i++) {
[485]906 $sth->execute($poolip_list[$i]->addr, $city);
[157]907 }
908 $pool--;
[246]909 if ($pool->addr !~ /\.255$/) { # .255 can cause weirdness.
[485]910 $sth->execute($pool->addr, $city);
[246]911 }
[157]912 } else { # (real netblock)
913 for (my $i=1; $i<=$#poolip_list; $i++) {
[485]914 $sth->execute($poolip_list[$i]->addr, $city);
[157]915 }
[77]916 }
[157]917 };
918 if ($@) {
[485]919 $msg = $@." '".$sth->errstr."'";
[157]920 eval { $dbh->rollback; };
921 return ('FAIL',$msg);
922 } else {
923 return ('OK',"OK");
[77]924 }
925} # end initPool()
926
927
[531]928## IPDB::updateBlock()
929# Update an allocation
930# Takes all allocation fields in a hash
931sub updateBlock {
932 my $dbh = shift;
933 my %args = @_;
934
935 return ('FAIL', 'Missing block to update') if !$args{block};
936
937 # do it all in a transaction
938 local $dbh->{AutoCommit} = 0;
939 local $dbh->{RaiseError} = 1;
940
941 my @fieldlist;
942 my @vallist;
943 foreach ('custid', 'city', 'description', 'notes', 'circuitid', 'privdata') {
944 if ($args{$_}) {
945 push @fieldlist, $_;
946 push @vallist, $args{$_};
947 }
948 }
949
950 my $updtable = 'allocations';
951 my $keyfield = 'cidr';
[535]952 if ($args{type} =~ /^(.)i$/) {
[531]953 $updtable = 'poolips';
954 $keyfield = 'ip';
955 } else {
956## fixme: there's got to be a better way...
957 if ($args{swip}) {
958 if ($args{swip} eq 'on' || $args{swip} eq '1' || $args{swip} eq 'y') {
959 $args{swip} = 'y';
960 } else {
961 $args{swip} = 'n';
962 }
963 }
964 foreach ('type', 'swip') {
965 if ($args{$_}) {
966 push @fieldlist, $_;
967 push @vallist, $args{$_};
968 }
969 }
970 }
971
972 return ('FAIL', 'No fields to update') if !@fieldlist;
973
974 push @vallist, $args{block};
975 my $sql = "UPDATE $updtable SET ";
976 $sql .= join " = ?, ", @fieldlist;
977 $sql .= " = ? WHERE $keyfield = ?";
978
979 eval {
980 # do the update
981 $dbh->do($sql, undef, @vallist);
982
983 if ($args{node}) {
984 # done with delete/insert so we don't have to worry about funkyness updating a node ref that isn't there
985 $dbh->do("DELETE FROM noderef WHERE block = ?", undef, ($args{block}) );
986 $dbh->do("INSERT INTO noderef (block,node_id) VALUES (?,?)", undef, ($args{block}, $args{node}) );
987 }
988
989 $dbh->commit;
990 };
991 if ($@) {
992 my $msg = $@;
993 $dbh->rollback;
994 return ('FAIL', $msg);
995 }
996 return 0;
997} # end updateBlock()
998
999
[93]1000## IPDB::deleteBlock()
1001# Removes an allocation from the database, including deleting IPs
1002# from poolips and recombining entries in freeblocks if possible
1003# Also handles "deleting" a static IP allocation, and removal of a master
[558]1004# Requires a database handle, the block to delete, the routing depth (if applicable),
1005# and the VRF ID
[93]1006sub deleteBlock {
[558]1007 my ($dbh,undef,$rdepth,$vrf) = @_;
[93]1008 my $cidr = new NetAddr::IP $_[1];
1009
[558]1010# For possible auto-VRF-ignoring (since public IPs shouldn't usually be present in more than one VRF)
1011# is_rfc1918 requires NetAddr::IP >= 4.059
1012# rather than doing this over and over and over.....
1013 my $tmpnum = $cidr->numeric;
1014# 192.168.0.0/16 -> 192.168.255.255 => 3232235520 -> 3232301055
1015# 172.16.0.0/12 -> 172.31.255.255 => 2886729728 -> 2887778303
1016# 10.0.0.0/8 -> 10.255.255.255 => 167772160 -> 184549375
1017 my $isprivnet = (3232235520 <= $tmpnum && $tmpnum <= 3232301055) ||
1018 (2886729728 <= $tmpnum && $tmpnum <= 2887778303) ||
1019 (167772160 <= $tmpnum && $tmpnum <= 184549375);
1020
[93]1021 my $sth;
1022
[349]1023 # Magic variables used for odd allocation cases.
1024 my $container;
1025 my $con_type;
1026
[558]1027 # Collect info about the block we're going to delete
1028 my $binfo = getBlockData($dbh, $cidr, $rdepth, $vrf);
1029
1030 # temporarily forced null, until a sane UI for VRF tracking can be found.
1031 $vrf = '';# if !$vrf; # as with SQL, the null value is not equal to ''. *sigh*
1032
[93]1033 # To contain the error message, if any.
[558]1034 my $msg = "Unknown error deallocating $binfo->{type} $cidr";
1035 my $goback; # to put the parent in so we can link back where the deallocate started
1036
[93]1037 # Enable transactions and exception-on-errors... but only for this sub
1038 local $dbh->{AutoCommit} = 0;
1039 local $dbh->{RaiseError} = 1;
1040
1041 # First case. The "block" is a static IP
1042 # Note that we still need some additional code in the odd case
1043 # of a netblock-aligned contiguous group of static IPs
[558]1044 if ($binfo->{type} =~ /^.i$/) {
[93]1045
1046 eval {
[558]1047 $msg = "Unable to deallocate $disp_alloctypes{$binfo->{type}} $cidr";
1048 my ($pool,$pcust,$pvrf) = $dbh->selectrow_array("SELECT pool,custid,vrf FROM poolips WHERE ip=?", undef, ($cidr) );
1049##fixme: VRF and rdepth
1050 $dbh->do("UPDATE poolips SET custid=?,available='y',".
1051 "city=(SELECT city FROM allocations WHERE cidr=?),".
1052 "description='',notes='',circuitid='',vrf=? WHERE ip=?", undef, ($pcust, $pool, $pvrf, $cidr) );
1053 $goback = $pool;
[93]1054 $dbh->commit;
1055 };
1056 if ($@) {
[558]1057 $msg .= ": $@";
[93]1058 eval { $dbh->rollback; };
1059 return ('FAIL',$msg);
1060 } else {
1061 return ('OK',"OK");
1062 }
1063
[558]1064 } elsif ($binfo->{type} eq 'mm') { # end alloctype =~ /.i/
[93]1065
[558]1066##fixme: VRF limit
[93]1067 $msg = "Unable to delete master block $cidr";
1068 eval {
[558]1069 $dbh->do("DELETE FROM masterblocks WHERE cidr = ?", undef, ($cidr) );
1070 $dbh->do("DELETE FROM allocations WHERE cidr <<= ?", undef, ($cidr) );
1071 $dbh->do("DELETE FROM freeblocks WHERE cidr <<= ?", undef, ($cidr) );
[93]1072 $dbh->commit;
1073 };
1074 if ($@) {
[558]1075 $msg .= ": $@";
[93]1076 eval { $dbh->rollback; };
1077 return ('FAIL', $msg);
1078 } else {
1079 return ('OK',"OK");
1080 }
1081
1082 } else { # end alloctype master block case
1083
1084 ## This is a big block; but it HAS to be done in a chunk. Any removal
1085 ## of a netblock allocation may result in a larger chunk of free
1086 ## contiguous IP space - which may in turn be combined into a single
1087 ## netblock rather than a number of smaller netblocks.
1088
[558]1089 my $retcode = 'OK';
1090
[93]1091 eval {
1092
[558]1093##fixme: add recursive flag to allow "YES DAMMIT DELETE ALL EVARYTHING!!1!!" without
1094# explicitly deleting any suballocations of the block to be deleted.
[93]1095
[558]1096 # find the current parent of the block we're deleting
1097 my ($parent) = $dbh->selectrow_array("SELECT parent FROM allocations WHERE cidr=? AND rdepth=?",
1098 undef, ($cidr, $rdepth) );
[93]1099
[558]1100 # Delete the block
1101 $dbh->do("DELETE FROM allocations WHERE cidr=? AND rdepth=?", undef, ($cidr, $rdepth) );
[349]1102
[558]1103##fixme: we could maybe eliminate a special case if we put masterblocks in the allocations table...?
1104 my ($ptype,$pcity);
1105 if ($rdepth == 1) {
1106 # parent is a master block.
1107 $ptype = 'mm';
1108 $pcity = '<NULL>';
1109 } else {
1110 # get that parent's details
1111 ($ptype,$pcity) = $dbh->selectrow_array("SELECT type,city FROM allocations ".
1112 "WHERE cidr=? AND rdepth=?", undef, ($parent, $rdepth-1) );
1113 }
[186]1114
[558]1115 # munge the parent type a little
1116 $ptype = (split //, $ptype)[0];
[93]1117
[558]1118##fixme: you can't... CAN NOT.... assign the same public IP to multiple things.
1119# 'Net don't work like that, homey. Restrict VRF-uniqueness to private IPs?
1120# -> $isprivnet flag from start of sub
[93]1121
[558]1122 my $fbrdepth = $rdepth;
[404]1123
[558]1124 # check to see if any container allocations could be the "true" parent
1125 my ($tparent,$trdepth,$trtype,$tcity) = $dbh->selectrow_array("SELECT cidr,rdepth,type,city FROM allocations ".
1126 "WHERE (type='rm' OR type LIKE '_c') AND cidr >> ? ".
1127 "ORDER BY masklen(cidr) DESC", undef, ($cidr) );
[404]1128
[558]1129 my $fparent;
1130 if ($tparent && $tparent ne $parent) {
1131 # found an alternate parent; reset some parent-info bits
1132 $parent = $tparent;
1133 $ptype = (split //, $trtype)[0];
1134 $pcity = $tcity;
1135 ##fixme: hmm. collect $rdepth into $goback here before vanishing?
1136 $retcode = 'WARN'; # may be redundant
1137 $goback = $tparent;
1138 # munge freeblock rdepth and parent to match true parent
1139 $dbh->do("UPDATE freeblocks SET rdepth = ?, parent = ?, routed = ? WHERE cidr <<= ? AND rdepth = ?", undef,
1140 ($trdepth+1, $parent, $ptype, $cidr, $rdepth) );
1141 $rdepth = $trdepth;
1142 $fbrdepth = $trdepth+1;
1143 }
1144
1145 $parent = new NetAddr::IP $parent;
1146 $goback = "$parent,$fbrdepth"; # breadcrumb in case of live-parent-is-not-true-parent
1147
1148 # Special case - delete pool IPs
1149 if ($binfo->{type} =~ /^.[pd]$/) {
1150 # We have to delete the IPs from the pool listing.
1151##fixme: rdepth? vrf?
1152 $dbh->do("DELETE FROM poolips WHERE pool = ?", undef, ($cidr) );
1153 }
1154
1155 # Find out if the block we're deallocating is within a DSL pool (legacy goo)
1156 my ($pool,$poolcity,$pooltype,$pooldepth) = $dbh->selectrow_array(
1157 "SELECT cidr,city,type,rdepth FROM allocations WHERE type LIKE '_p' AND cidr >>= ?",
1158 undef, ($cidr) );
1159
1160 # If so, return the block's IPs to the pool, instead of to freeblocks
1161## NB: not possible to currently cause this even via admin tools, only legacy data.
1162 if ($pool) {
1163 ## Deallocate legacy blocks stashed in the middle of a static IP pool
1164 ## This may be expandable to an even more general case of contained netblock, or other pool types.
1165 $retcode = 'WARNPOOL';
1166 $goback = "$pool,$pooldepth";
[428]1167 # We've already deleted the block, now we have to stuff its IPs into the pool.
1168 $pooltype =~ s/p$/i/; # change type to static IP
[558]1169 my $sth2 = $dbh->prepare("INSERT INTO poolips (pool,ip,city,type,custid) VALUES ".
[428]1170 "('$pool',?,'$poolcity','$pooltype','$defcustid')");
[558]1171 # don't insert .0
[429]1172##fixme: need to not insert net, gateway, and bcast on "real netblock" pools (DHCPish)
[428]1173 $sth2->execute($cidr->addr) unless $cidr->addr =~ m|\.0$|;
1174 foreach my $ip ($cidr->hostenum) {
[558]1175 $sth2->execute($ip);
[428]1176 }
1177 $cidr--;
1178 # don't insert .255
1179 $sth2->execute($cidr->addr) unless $cidr->addr =~ m|\.255$|;
1180 } else { # done returning IPs from a block to a static DSL pool
[93]1181
[558]1182 # If the block wasn't legacy goo embedded in a static pool, we check the
1183 # freeblocks in the identified parent to see if we can combine any of them.
[93]1184
[559]1185 # if the block to be deleted is a container, move its freeblock(s) up a level, and reset their parenting info
1186 if ($binfo->{type} =~ /^.[mc]/) {
1187 # move the freeblocks into the parent
1188 # we don't insert a new freeblock because there could be a live reparented sub.
1189 $dbh->do("UPDATE freeblocks SET rdepth=rdepth-1,parent=?,routed=?,city=? ".
1190 "WHERE parent=? AND rdepth=?", undef,
1191 ($parent, $ptype, $pcity, $cidr, $rdepth+1) );
1192 } else {
1193 # ... otherwise, add the freeblock
1194 $dbh->do("INSERT INTO freeblocks (cidr, city, routed, parent, rdepth) VALUES (?,?,?,?,?)", undef,
1195 ($cidr, $pcity, $ptype, $parent, $rdepth) );
1196 }
1197
[558]1198##fixme: vrf
1199 # set up the query to get the list of blocks to try to merge.
1200 $sth = $dbh->prepare("SELECT cidr FROM freeblocks ".
1201 "WHERE parent = ? AND routed = ? AND rdepth = ? ".
1202 "ORDER BY masklen(cidr) DESC");
[428]1203
[558]1204 $sth->execute($parent, $ptype, $fbrdepth);
1205
[93]1206# NetAddr::IP->compact() attempts to produce the smallest inclusive block
1207# from the caller and the passed terms.
1208# EG: if you call $cidr->compact($ip1,$ip2,$ip3) when $cidr, $ip1, $ip2,
1209# and $ip3 are consecutive /27's starting on .0 (.0-.31, .32-.63,
1210# .64-.95, and .96-.128), you will get an array containing a single
1211# /25 as element 0 (.0-.127). Order is not important; you could have
1212# $cidr=.32/27, $ip1=.96/27, $ip2=.0/27, and $ip3=.64/27.
1213
[558]1214 my (@rawfb, @combinelist);
[428]1215 my $i=0;
[558]1216 # for each free block under $parent, push a NetAddr::IP object into one list, and
1217 # continuously use NetAddr::IP->compact to automagically merge netblocks as possible.
[428]1218 while (my @data = $sth->fetchrow_array) {
1219 my $testIP = new NetAddr::IP $data[0];
[558]1220 push @rawfb, $testIP;
1221 @combinelist = $testIP->compact(@combinelist);
[93]1222 }
1223
[558]1224 # now that we have the full list of "compacted" freeblocks, go back over
1225 # the list of raw freeblocks, and delete the ones that got merged.
1226 $sth = $dbh->prepare("DELETE FROM freeblocks WHERE cidr=? AND parent=? AND rdepth=?");
1227 foreach my $rawfree (@rawfb) {
1228 next if grep { $rawfree == $_ } @combinelist; # skip if the raw block is in the compacted list
1229 $sth->execute($rawfree, $parent, $fbrdepth);
1230 }
[93]1231
[558]1232 # now we walk the new list of compacted blocks, and see which ones we need to insert
1233 $sth = $dbh->prepare("INSERT INTO freeblocks (cidr,city,routed,parent,rdepth) VALUES (?,?,?,?,?)");
1234 foreach my $cme (@combinelist) {
1235 next if grep { $cme == $_ } @rawfb; # skip if the combined block was in the raw list
1236 $sth->execute($cme, $pcity, $ptype, $parent, $fbrdepth);
[428]1237 }
[93]1238
[428]1239 } # done returning IPs to the appropriate place
[404]1240
[93]1241 # If we got here, we've succeeded. Whew!
1242 $dbh->commit;
1243 }; # end eval
1244 if ($@) {
[558]1245 $msg .= ": $@";
[93]1246 eval { $dbh->rollback; };
1247 return ('FAIL', $msg);
1248 } else {
[558]1249 return ($retcode, $goback);
[93]1250 }
1251
1252 } # end alloctype != netblock
1253
1254} # end deleteBlock()
1255
1256
[370]1257## IPDB::getBlockData()
[557]1258# Get CIDR or IP, custid, type, city, circuit ID, description, notes, modification time,
1259# private/restricted data, for a CIDR block or pool IP
1260# Also returns SWIP status flag for CIDR blocks or pool netblock for IPs
1261# Takes the block/IP to look up, routing depth, and VRF identifier
1262# Returns a hashref to the block data
[370]1263sub getBlockData {
1264 my $dbh = shift;
1265 my $block = shift;
[557]1266 my $rdepth = shift;
1267 my $vrf = shift || '';
[370]1268
[534]1269 my $cidr = new NetAddr::IP $block;
1270
[557]1271 # better way to find IP allocations vs /32 "netblocks"
1272 my $btype = $dbh->selectrow_array("SELECT type FROM searchme WHERE cidr=?", undef, ($block) );
[534]1273
[557]1274 if (defined($rdepth) && $rdepth == 0) {
1275 # Only master blocks exist at rdepth 0
1276 my $binfo = $dbh->selectrow_hashref("SELECT cidr AS block, 'mm' AS type, 0 AS parent, cidr,".
1277 " ctime, mtime, rwhois, vrf".
1278 " FROM masterblocks WHERE cidr = ? AND vrf = ?", undef, ($block, $vrf) );
1279 return $binfo;
1280 } elsif ($btype =~ /^.i$/) {
1281 my $binfo = $dbh->selectrow_hashref("SELECT ip AS block, custid, type, city, circuitid, description,".
1282 " notes, modifystamp AS lastmod, privdata, vrf, pool, rdepth".
1283 " FROM poolips WHERE ip = ? AND vrf = ?", undef, ($block, $vrf) );
1284 return $binfo;
1285 } else {
1286 my $binfo = $dbh->selectrow_hashref("SELECT cidr AS block, parent, custid, type, city, circuitid, ".
1287 "description, notes, modifystamp AS lastmod, privdata, vrf, swip, rdepth".
1288 " FROM allocations WHERE cidr = ? AND rdepth = ?", undef, ($block, $rdepth) );
1289# " FROM allocations WHERE cidr = ? AND rdepth = ? AND vrf = ?", undef, ($block, $rdepth, $vrf) );
1290 return $binfo;
[534]1291 }
[370]1292} # end getBlockData()
1293
1294
[519]1295## IPDB::getNodeList()
1296# Gets a list of node ID+name pairs as an arrayref to a list of hashrefs
1297sub getNodeList {
1298 my $dbh = shift;
1299
1300 my $ret = $dbh->selectall_arrayref("SELECT node_id, node_name FROM nodes ORDER BY node_type,node_id",
1301 { Slice => {} });
1302 return $ret;
1303} # end getNodeList()
1304
1305
[530]1306## IPDB::getNodeName()
1307# Get node name from the ID
1308sub getNodeName {
1309 my $dbh = shift;
1310 my $nid = shift;
1311
1312 my ($nname) = $dbh->selectrow_array("SELECT node_name FROM nodes WHERE node_id = ?", undef, ($nid) );
1313 return $nname;
1314} # end getNodeName()
1315
1316
1317## IPDB::getNodeInfo()
1318# Get node name and ID associated with a block
1319sub getNodeInfo {
1320 my $dbh = shift;
1321 my $block = shift;
1322
1323 my ($nid, $nname) = $dbh->selectrow_array("SELECT nodes.node_id,node_name FROM nodes INNER JOIN noderef".
1324 " ON nodes.node_id=noderef.node_id WHERE noderef.block = ?", undef, ($block) );
1325 return ($nid, $nname);
1326} # end getNodeInfo()
1327
1328
[77]1329## IPDB::mailNotify()
[66]1330# Sends notification mail to recipients regarding an IPDB operation
[416]1331sub mailNotify {
1332 my $dbh = shift;
1333 my ($action,$subj,$message) = @_;
[66]1334
[462]1335 return if $smtphost eq 'smtp.example.com'; # do nothing if still using default SMTP host.
1336
[422]1337##fixme: need to redesign the breakdown/processing for $action for proper handling of all cases
1338
[416]1339# split action into parts for fiddlement. nb: there are almost certainly better ways to do this.
[422]1340 my @actionbits = split //, $action;
[416]1341
1342 # want to notify anyone who has specifically requested notify on *this* type ($action as passed),
1343 # on "all static IP types" or "all pool types" (and other last-char-in-type groupings), on eg "all DSL types",
1344 # and "all events with this action"
1345 my @actionsets = ($action);
1346##fixme: ick, eww. really gotta find a better way to handle this...
1347 push @actionsets, ($actionbits[0].'.'.$actionbits[2],
1348 $actionbits[0].$actionbits[1].'.', $actionbits[0].'a') if $action =~ /^.{3}$/;
1349
1350 my $mailer = Net::SMTP->new($smtphost, Hello => "ipdb.$domain");
1351
1352 # get recip list from db
1353 my $sth = $dbh->prepare("SELECT reciplist FROM notify WHERE action=?");
1354
[443]1355 my %reciplist;
[416]1356 foreach (@actionsets) {
[426]1357 $sth->execute($_);
[416]1358##fixme - need to handle db errors
1359 my ($recipsub) = $sth->fetchrow_array;
1360 next if !$recipsub;
1361 foreach (split(/,/, $recipsub)) {
[443]1362 $reciplist{$_}++;
[416]1363 }
1364 }
1365
[443]1366 return if !%reciplist;
[420]1367
[443]1368 foreach my $recip (keys %reciplist) {
[416]1369 $mailer->mail("ipdb\@$domain");
1370 $mailer->to($recip);
[422]1371 $mailer->data("From: \"$org_name IP Database\" <ipdb\@$domain>\n",
[135]1372 "To: $recip\n",
[69]1373 "Date: ".strftime("%a, %d %b %Y %H:%M:%S %z",localtime)."\n",
1374 "Subject: {IPDB} $subj\n",
1375 "X-Mailer: IPDB Notify v".sprintf("%.1d",$IPDB::VERSION)."\n",
[417]1376 "Organization: $org_name\n",
[69]1377 "\n$message\n");
[416]1378 }
[66]1379 $mailer->quit;
1380}
1381
[4]1382# Indicates module loaded OK. Required by Perl.
13831;
Note: See TracBrowser for help on using the repository browser.