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

Last change on this file since 734 was 734, checked in by Kris Deugau, 9 years ago

/trunk

Fix subtle edge-case bug in initPool() where the check for preexisting
net and bcast IPs looked for the wrong thing, and tried to insert them
again.

  • Property svn:keywords set to Date Rev Author
File size: 101.3 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: 2015-05-27 18:26:30 +0000 (Wed, 27 May 2015) $
6# SVN revision $Rev: 734 $
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;
[573]18use NetAddr::IP qw(:lower Compact );
[582]19use Frontier::Client;
[68]20use POSIX;
[4]21use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
22
[417]23$VERSION = 2; ##VERSION##
[4]24@ISA = qw(Exporter);
[106]25@EXPORT_OK = qw(
[541]26 %disp_alloctypes %list_alloctypes %def_custids @citylist @poplist
[733]27 %IPDBacl %merge_display %aclmsg %rpcacl $maxfcgi
[660]28 $errstr
[523]29 &initIPDBGlobals &connectDB &finish &checkDBSanity
[547]30 &addMaster &touchMaster
[720]31 &listSummary &listSubs &listContainers &listAllocations &listForMerge &listFree &listPool
[541]32 &getMasterList &getTypeList &getPoolSelect &findAllocateFrom
[697]33 &ipParent &subParent &blockParent &getBreadCrumbs &getRoutedCity
[728]34 &allocateBlock &updateBlock &splitBlock &shrinkBlock &mergeBlocks &deleteBlock &getBlockData
[705]35 &getBlockRDNS &getRDNSbyIP
[530]36 &getNodeList &getNodeName &getNodeInfo
[519]37 &mailNotify
[106]38 );
[4]39
40@EXPORT = (); # Export nothing by default.
[106]41%EXPORT_TAGS = ( ALL => [qw(
[167]42 %disp_alloctypes %list_alloctypes %def_custids @citylist @poplist
[733]43 %IPDBacl %merge_display %aclmsg %rpcacl $maxfcgi
[660]44 $errstr
[523]45 &initIPDBGlobals &connectDB &finish &checkDBSanity
[547]46 &addMaster &touchMaster
[720]47 &listSummary &listSubs &listContainers &listAllocations &listForMerge &listFree &listPool
[541]48 &getMasterList &getTypeList &getPoolSelect &findAllocateFrom
[697]49 &ipParent &subParent &blockParent &getBreadCrumbs &getRoutedCity
[728]50 &allocateBlock &updateBlock &splitBlock &shrinkBlock &mergeBlocks &deleteBlock &getBlockData
[705]51 &getBlockRDNS &getRDNSbyIP
[530]52 &getNodeList &getNodeName &getNodeInfo
[519]53 &mailNotify
[106]54 )]
55 );
[4]56
[77]57##
58## Global variables
59##
60our %disp_alloctypes;
61our %list_alloctypes;
[167]62our %def_custids;
[96]63our @citylist;
64our @poplist;
[233]65our %IPDBacl;
[66]66
[725]67# Mapping hash for pooltype -> poolip-as-netblock conversions
68my %poolmap = (sd => 'en', cd => 'cn', dp => 'cn', mp => 'cn', wp => 'cn', ld => 'in', ad => 'in', bd => 'in');
69
[733]70# Friendly display strings for merge scopes
71our %merge_display = (
72 keepall => "Keep mergeable allocations as suballocations of new block",
73 mergepeer => "Keep suballocations of mergeable allocations",
74 clearpeer => "Keep only suballocations of the selected block",
75 clearall => "Clear all suballocations"
76 );
77
[517]78# mapping table for functional-area => error message
79our %aclmsg = (
80 addmaster => 'add a master block',
81 addblock => 'add an allocation',
82 updateblock => 'update a block',
83 delblock => 'delete an allocation',
84 );
85
[660]86our %rpcacl;
[661]87our $maxfcgi = 3;
[660]88
[585]89# error reporting
90our $errstr = '';
91
[417]92our $org_name = 'Example Corp';
[416]93our $smtphost = 'smtp.example.com';
94our $domain = 'example.com';
[417]95our $defcustid = '5554242';
[681]96our $smtpsender = 'ipdb@example.com';
[417]97# mostly for rwhois
98##fixme: leave these blank by default?
[420]99our $rwhoisDataPath = '/usr/local/rwhoisd/etc/rwhoisd'; # to match ./configure defaults from rwhoisd-1.5.9.6
[417]100our $org_street = '123 4th Street';
101our $org_city = 'Anytown';
102our $org_prov_state = 'ON';
103our $org_pocode = 'H0H 0H0';
104our $org_country = 'CA';
105our $org_phone = '000-555-1234';
106our $org_techhandle = 'ISP-ARIN-HANDLE';
[434]107our $org_email = 'noc@example.com';
[437]108our $hostmaster = 'dns@example.com';
[416]109
[417]110our $syslog_facility = 'local2';
111
[582]112our $rpc_url = '';
[585]113our $revgroup = 1; # should probably be configurable somewhere
114our $rpccount = 0;
[582]115
[674]116# Largest inverse CIDR mask length to show per-IP rDNS list
117# (eg, NetAddr::IP->bits - NetAddr::IP->masklen)
118our $maxrevlist = 5; # /27
119
[682]120# UI layout for subblocks/containers
121our $sublistlayout = 1;
122
[691]123# VLAN validation mode. Set to 0 to allow alphanumeric vlan names instead of using the vlan number.
124our $numeric_vlan = 1;
125
126
[585]127##
128## Internal utility functions
129##
130
131## IPDB::_rpc
132# Make an RPC call for DNS changes
133sub _rpc {
134 return if !$rpc_url; # Just In Case
135 my $rpcsub = shift;
136 my %args = @_;
137
138 # Make an object to represent the XML-RPC server.
139 my $server = Frontier::Client->new(url => $rpc_url, debug => 0);
140 my $result;
141
142 my %rpcargs = (
143 rpcsystem => 'ipdb',
[640]144# must be provided by caller's caller
145# rpcuser => $args{user},
146 %args,
[585]147 );
148
149 eval {
[640]150 $result = $server->call("dnsdb.$rpcsub", %rpcargs);
[585]151 };
152 if ($@) {
153 $errstr = $@;
[678]154 $errstr =~ s/\s*$//;
[585]155 $errstr =~ s/Fault returned from XML RPC Server, fault code 4: error executing RPC `dnsdb.$rpcsub'\.\s//;
156 }
157 $rpccount++;
158
159 return $result if $result;
160} # end _rpc()
161
162
[715]163## IPDB::_compactFree()
164# Utility sub to compact a set of free block entries down to the minimum possible set of CIDR entries
165# Not to be called outside of an eval{}!
166sub _compactFree {
167 my $dbh = shift;
168 my $parent = shift;
169
170 # Rather than having the caller provide all the details
171 my $pinfo = getBlockData($dbh, $parent);
[722]172 my $ftype = (split //, $pinfo->{type})[0];
[715]173
174# NetAddr::IP->compact() attempts to produce the smallest inclusive block
175# from the caller and the passed terms.
176# EG: if you call $cidr->compact($ip1,$ip2,$ip3) when $cidr, $ip1, $ip2,
177# and $ip3 are consecutive /27's starting on .0 (.0-.31, .32-.63,
178# .64-.95, and .96-.128), you will get an array containing a single
179# /25 as element 0 (.0-.127). Order is not important; you could have
180# $cidr=.32/27, $ip1=.96/27, $ip2=.0/27, and $ip3=.64/27.
181
182##fixme: vrf
183##fixme: simplify since all containers now represent different "layers"/"levels"?
184
185 # set up the query to get the list of blocks to try to merge.
186 my $sth = $dbh->prepare(q{
187 SELECT cidr,id FROM freeblocks
188 WHERE parent_id = ?
189 ORDER BY masklen(cidr) DESC
190 });
191 $sth->execute($parent);
192
193 my (@rawfb, @combinelist, %rawid);
194 my $i=0;
195 # for each free block under $parent, push a NetAddr::IP object into one list, and
196 # continuously use NetAddr::IP->compact to automagically merge netblocks as possible.
197 while (my ($fcidr, $fid) = $sth->fetchrow_array) {
198 my $testIP = new NetAddr::IP $fcidr;
199 push @rawfb, $testIP;
200 $rawid{"$testIP"} = $fid; # $data[0] vs "$testIP" *does* make a difference for v6
201 @combinelist = $testIP->compact(@combinelist);
202 }
203
204 # now that we have the full list of "compacted" freeblocks, go back over
205 # the list of raw freeblocks, and delete the ones that got merged.
206 $sth = $dbh->prepare("DELETE FROM freeblocks WHERE id = ?");
207 foreach my $rawfree (@rawfb) {
208 next if grep { $rawfree == $_ } @combinelist; # skip if the raw block is in the compacted list
209 $sth->execute($rawid{$rawfree});
210 }
211
212 # now we walk the new list of compacted blocks, and see which ones we need to insert
[723]213 $sth = $dbh->prepare("INSERT INTO freeblocks (cidr,city,routed,vrf,parent_id,master_id) VALUES (?,?,?,?,?,?)");
[715]214 foreach my $cme (@combinelist) {
215 next if grep { $cme == $_ } @rawfb; # skip if the combined block was in the raw list
[722]216 $sth->execute($cme, $pinfo->{city}, $ftype, $pinfo->{vrf}, $parent, $pinfo->{master_id});
[715]217 }
218
219} # end _compactFree()
220
221
[725]222## IPDB::_poolToAllocations
223# Convert pool IPs into allocations, and free IPs into free blocks
224# Takes a pool ID, original pool CIDR (in case the allocation has been updated before the call here)
225# and hashref to data for the new parent container for the IPs,
226# and an optional hash with the new parent ID and allocation type
227sub _poolToAllocations {
228 my $dbh = shift;
229 my $oldpool = shift;
230 my $parentinfo = shift;
231 my %args = @_;
232
233 # Default to converting the pool to a container
234 $args{newparent} = $oldpool->{id} if !$args{newparent};
235
236 my ($containerclass) = ($parentinfo->{type} =~ /(.)./);
237
238 # Default type mapping
239 $args{newtype} = $poolmap{$oldpool->{type}} if !$args{newtype};
240
241 # Convert a bunch of pool IP allocations into "normal" netblock allocations
242 my $pool2alloc = $dbh->prepare(q{
243 INSERT INTO allocations (
244 cidr,type,city, description, notes, circuitid, createstamp, modifystamp,
245 privdata, custid, vrf, vlan, rdns, parent_id, master_id
246 )
247 SELECT
248 ip, ? AS type, city, description, notes, circuitid, createstamp, modifystamp,
249 privdata, custid, vrf, vlan, rdns, ? AS parent_id, master_id
250 FROM poolips
251 WHERE parent_id = ? AND available = 'n'
252 });
253 $pool2alloc->execute($args{newtype}, $args{newparent}, $oldpool->{id});
254
255 # Snag the whole list of pool IPs
256 my @freeips = @{$dbh->selectall_arrayref("SELECT ip,available FROM poolips WHERE parent_id = ?",
257 undef, $oldpool->{id})};
258 my @iplist;
259 my %usedips;
260 # Filter out the ones that were used...
261 foreach my $ip (@freeips) {
262 $$ip[0] =~ s{/32$}{};
263 push @iplist, NetAddr::IP->new($$ip[0]) if $$ip[1] eq 'y';
264 $usedips{$$ip[0]}++ if $$ip[1] eq 'n';
265 }
266 # ... so that we can properly decide whether the net, gw, and bcast IPs need to be added to the free list.
267 my $tmpblock = new NetAddr::IP $oldpool->{block};
268 push @iplist, NetAddr::IP->new($tmpblock->network->addr)
269 if !$usedips{$tmpblock->network->addr} || $tmpblock->network->addr =~ /\.0$/;
270 push @iplist, NetAddr::IP->new($tmpblock->broadcast->addr)
271 if !$usedips{$tmpblock->broadcast->addr} || $tmpblock->broadcast->addr =~ /\.255$/;
272 # only "DHCP"-ish pools have a gw ip removed from the pool
273 if ($oldpool->{type} =~ /.d/) {
274 $tmpblock++;
275 push @iplist, NetAddr::IP->new($tmpblock->addr);
276 }
277
278 # take the list of /32 IPs, and see what CIDR ranges we get back as free, then insert them.
279 @iplist = Compact(@iplist);
280 my $insfbsth = $dbh->prepare("INSERT INTO freeblocks (cidr,city,routed,vrf,parent_id,master_id) VALUES (?,?,?,?,?,?)");
281 foreach (@iplist) {
282 $insfbsth->execute($_, $parentinfo->{city}, $containerclass, $parentinfo->{vrf},
283 $args{newparent}, $parentinfo->{master_id});
284 }
285
286 # and finally delete the poolips entries
287 $dbh->do("DELETE FROM poolips WHERE parent_id = ?", undef, $oldpool->{id});
288
289} # end _poolToAllocations()
290
291
[716]292## IPDB::_deleteCascade()
293# Internal sub. Deletes an allocation and all subcomponents
294sub _deleteCascade {
295 my $dbh = shift;
296 my $id = shift;
[724]297 my $createfb = shift; # may be null at this point
[716]298
299 my $binfo = getBlockData($dbh, $id);
300
[724]301 # Decide if we're going to add a free block.
302
303 # Caller is normal block delete -> add freeblock under $binfo->{parent_id} -> pass nothing
304 # Caller is delete for merge to leaf -> do not add freeblock -> pass 0
305 # Caller is normal master delete -> do not add freeblock -> pass nothing
306 # Caller is merge master -> add freeblock under alternate parent -> pass parent ID
307 if ($binfo->{type} ne 'mm') {
308 # Deleting a non-master block
309 if (!defined($createfb)) {
310 # No createfb flag passed; assuming normal block delete. Add the freeblock
311 # under the parent of the block we're deleting.
312 $createfb = $binfo->{parent_id};
313 #} else {
314 # Don't need to actually do anything here. The caller has given us an ID,
315 # which is either 0 (causing no free block) or (theoretically) a valid block
316 # ID to add the free block under.
317 }
318 #} else {
319 # Deleting a master block
320 # Don't need to actually do anything here. If the caller passed a parent ID,
321 # that parent will get the new free block. if the caller didn't pass anything,
322 # no free block will be added.
323 }
324
[716]325##fixme: special-case master blocks up here and quickly delete based on master_id,
326# instead of wasting time tracing parent relations
327
328 # grab all allocations in the master within the CIDR of the block to be deleted
329 my %parents;
330 my %cidrlist;
331##fixme: limit by VRF?
332 my $sth = $dbh->prepare("SELECT cidr,id,parent_id FROM allocations WHERE cidr <<= ? AND master_id = ?");
333 $sth->execute($binfo->{block}, $binfo->{master_id});
334 while (my ($cidr, $cid, $pid) = $sth->fetchrow_array) {
335 $parents{$cid} = $pid;
336 $cidrlist{$cid} = $cidr;
337 }
338
339 # Trace the parent relations up the tree until we either hit parent ID 0 (we've found a master block
340 # but not the parent we're looking for - arguably this is already an error) or the parent ID matches
341 # the passed ID. If the latter, push the whole set into a second flag hash, so we can terminate
342 # further tree-tracing early.
343 my %found;
344 foreach my $cid (keys %parents) {
345 my @tmp;
346 if ($cid == $id) {
347 # "child" is the ID we've been asked to cascade-delete.
348 $found{$cid}++;
349 } elsif ($found{$cid}) {
350 # ID already seen and the chain terminates in our parent.
351 } elsif ($parents{$cid} == $id) {
352 # Immediate parent is the target parent
353 $found{$cid}++;
354 } else {
355 # Immediate parent isn't the one we're looking for. Walk the chain up until we hit our parent,
356 # the nonexistent parent id 0, or undefined (ID is not a child of the target ID at all)
357 # There are probably better ways to structure this loop.
358 while (1) {
359 # cache the ID
360 push @tmp, $cid;
361 # some very particularly defined loop ending conditions
362 if (!defined($parents{$cid}) || $parents{$cid} == $id || $parents{$cid} == 0) {
363 last;
364 } else {
365 # if we haven't found either the desired parent or another limiting condition,
366 # reset the ID to the parent next up the tree
367 $cid = $parents{$cid};
368 }
369 }
370 # if the current chain of relations ended with our target parent, shuffle the cached IDs into a flag hash
371 if (defined($parents{$cid}) && $parents{$cid} == $id) {
372 foreach (@tmp) { $found{$_}++; }
373 }
374 } # else
375 } # foreach my $cid
376
377 # Use the keys in the flag hash to determine which allocations to actually delete.
378 # Delete matching freeblocks and pool IPs; their parents are going away so we want
379 # to make sure we don't leave orphaned records lying around loose.
380 my @dellist = keys %found;
381 push @dellist, $id; # Just In Case the target ID didn't make the list earlier.
382 my $b = '?'. (',?' x $#dellist);
383 $dbh->do("DELETE FROM allocations WHERE id IN ($b)", undef, (@dellist) );
384 $dbh->do("DELETE FROM freeblocks WHERE parent_id IN ($b)", undef, (@dellist) );
385 $dbh->do("DELETE FROM poolips WHERE parent_id IN ($b)", undef, (@dellist) );
386
[724]387 # Insert a new free block if needed
388 if ($createfb) {
389 my $pinfo = getBlockData($dbh, $createfb);
[716]390 my $pt = (split //, $pinfo->{type})[1];
391 $dbh->do("INSERT INTO freeblocks (cidr,city,routed,parent_id,vrf,master_id) VALUES (?,?,?,?,?,?)", undef,
[724]392 $binfo->{block}, $pinfo->{city}, $pt, $createfb, $pinfo->{vrf}, $binfo->{master_id});
[716]393 }
394
395##todo: and hey! bonus! we can return @dellist, or something (%cidrlist{@dellist})
[724]396
[716]397} # end _deleteCascade()
398
399
[715]400##
401## Public subs
402##
403
404
[77]405## IPDB::initIPDBGlobals()
406# Initialize all globals. Takes a database handle, returns a success or error code
407sub initIPDBGlobals {
408 my $dbh = $_[0];
409 my $sth;
410
[106]411 # Initialize alloctypes hashes
[167]412 $sth = $dbh->prepare("select type,listname,dispname,listorder,def_custid from alloctypes order by listorder");
[77]413 $sth->execute;
414 while (my @data = $sth->fetchrow_array) {
[106]415 $disp_alloctypes{$data[0]} = $data[2];
[167]416 $def_custids{$data[0]} = $data[4];
[106]417 if ($data[3] < 900) {
418 $list_alloctypes{$data[0]} = $data[1];
419 }
[77]420 }
[96]421
422 # City and POP listings
[157]423 $sth = $dbh->prepare("select city,routing from cities order by city");
[96]424 $sth->execute;
425 return (undef,$sth->errstr) if $sth->err;
426 while (my @data = $sth->fetchrow_array) {
[106]427 push @citylist, $data[0];
[96]428 if ($data[1] eq 'y') {
[106]429 push @poplist, $data[0];
[96]430 }
431 }
432
[233]433 # Load ACL data. Specific username checks are done at a different level.
434 $sth = $dbh->prepare("select username,acl from users");
435 $sth->execute;
[106]436 return (undef,$sth->errstr) if $sth->err;
[233]437 while (my @data = $sth->fetchrow_array) {
438 $IPDBacl{$data[0]} = $data[1];
439 }
[106]440
[517]441##fixme: initialize HTML::Template env var for template path
442# something like $self->path().'/templates' ?
443# $ENV{HTML_TEMPLATE_ROOT} = 'foo/bar';
444
[77]445 return (1,"OK");
446} # end initIPDBGlobals
447
448
449## IPDB::connectDB()
[4]450# Creates connection to IPDB.
[77]451# Requires the database name, username, and password.
[4]452# Returns a handle to the db.
[77]453# Set up for a PostgreSQL db; could be any transactional DBMS with the
454# right changes.
[4]455sub connectDB {
[432]456 my $dbname = shift;
457 my $user = shift;
458 my $pass = shift;
459 my $dbhost = shift;
460
[4]461 my $dbh;
[432]462 my $DSN = "DBI:Pg:".($dbhost ? "host=$dbhost;" : '')."dbname=$dbname";
[4]463
464# Note that we want to autocommit by default, and we will turn it off locally as necessary.
[77]465# We may not want to print gobbledygook errors; YMMV. Have to ponder that further.
466 $dbh = DBI->connect($DSN, $user, $pass, {
467 AutoCommit => 1,
468 PrintError => 0
469 })
470 or return (undef, $DBI::errstr) if(!$dbh);
[4]471
[77]472# Return here if we can't select. Note that this indicates a
473# problem executing the select.
[183]474 my $sth = $dbh->prepare("select type from alloctypes");
[77]475 $sth->execute();
476 return (undef,$DBI::errstr) if ($sth->err);
477
478# See if the select returned anything (or null data). This should
479# succeed if the select executed, but...
480 $sth->fetchrow();
481 return (undef,$DBI::errstr) if ($sth->err);
482
483# If we get here, we should be OK.
484 return ($dbh,"DB connection OK");
[4]485} # end connectDB
486
[77]487
488## IPDB::finish()
489# Cleans up after database handles and so on.
490# Requires a database handle
491sub finish {
492 my $dbh = $_[0];
[517]493 $dbh->disconnect if $dbh;
[77]494} # end finish
495
496
[106]497## IPDB::checkDBSanity()
[4]498# Quick check to see if the db is responding. A full integrity
499# check will have to be a separate tool to walk the IP allocation trees.
500sub checkDBSanity {
[106]501 my ($dbh) = $_[0];
[4]502
503 if (!$dbh) {
[106]504 print "No database handle, or connection has been closed.";
505 return -1;
[4]506 } else {
507 # it connects, try a stmt.
[184]508 my $sth = $dbh->prepare("select type from alloctypes");
[4]509 my $err = $sth->execute();
510
511 if ($sth->fetchrow()) {
512 # all is well.
513 return 1;
514 } else {
[16]515 print "Connected to the database, but could not execute test statement. ".$sth->errstr();
[106]516 return -1;
[4]517 }
518 }
519 # Clean up after ourselves.
[106]520# $dbh->disconnect;
[4]521} # end checkDBSanity
522
[66]523
[371]524## IPDB::addMaster()
525# Does all the magic necessary to sucessfully add a master block
526# Requires database handle, block to add
527# Returns failure code and error message or success code and "message"
528sub addMaster {
529 my $dbh = shift;
[591]530 # warning! during testing, this somehow generated a "Bad file descriptor" error. O_o
[371]531 my $cidr = new NetAddr::IP shift;
[582]532 my %args = @_;
[371]533
[582]534 $args{vrf} = '' if !$args{vrf};
535 $args{rdns} = '' if !$args{rdns};
536 $args{defloc} = '' if !$args{defloc};
537 $args{rwhois} = 'n' if !$args{rwhois}; # fail "safe", sort of.
538 $args{rwhois} = 'n' if $args{rwhois} ne 'n' and $args{rwhois} ne 'y';
539
[629]540 my $mid;
541
[371]542 # Allow transactions, and raise an exception on errors so we can catch it later.
543 # Use local to make sure these get "reset" properly on exiting this block
544 local $dbh->{AutoCommit} = 0;
545 local $dbh->{RaiseError} = 1;
546
547 # Wrap all the SQL in a transaction
548 eval {
[628]549 # First check - does the master exist? Ignore VRFs until we can see a sane UI
550 my ($mcontained) = $dbh->selectrow_array("SELECT cidr FROM allocations WHERE cidr >>= ? AND type = 'mm'",
551 undef, ($cidr) );
552 die "Master block $mcontained already exists and entirely contains $cidr\n"
553 if $mcontained;
[371]554
[628]555 # Second check - does the new master contain an existing one or ones?
556 my ($mexist) = $dbh->selectrow_array("SELECT cidr FROM allocations WHERE cidr <<= ? AND type = 'mm'",
557 undef, ($cidr) );
558
[518]559 if (!$mexist) {
[371]560 # First case - master is brand-spanking-new.
561##fixme: rwhois should be globally-flagable somewhere, much like a number of other things
562## maybe a db table called "config"?
[628]563 $dbh->do("INSERT INTO allocations (cidr,type,swip,vrf,rdns) VALUES (?,?,?,?,?)", undef,
564 ($cidr, 'mm', 'y', $args{vrf}, $args{rdns}) );
565 ($mid) = $dbh->selectrow_array("SELECT currval('allocations_id_seq')");
[371]566
567# Unrouted blocks aren't associated with a city (yet). We don't rely on this
568# elsewhere though; legacy data may have traps and pitfalls in it to break this.
569# Thus the "routed" flag.
[628]570 $dbh->do("INSERT INTO freeblocks (cidr,city,routed,parent_id,vrf,master_id) VALUES (?,?,?,?,?,?)", undef,
571 ($cidr, '<NULL>', 'm', $mid, $args{vrf}, $mid) );
[371]572
[628]573 # master should be its own master, so deletes directly at the master level work
574 $dbh->do("UPDATE allocations SET master_id = ? WHERE id = ?", undef, ($mid, $mid) );
575
[371]576 # If we get here, everything is happy. Commit changes.
577 $dbh->commit;
578
[518]579 } # done new master does not contain existing master(s)
[371]580 else {
581
582 # collect the master(s) we're going to absorb, and snag the longest netmask while we're at it.
583 my $smallmask = $cidr->masklen;
[628]584 my $sth = $dbh->prepare("SELECT cidr,id FROM allocations WHERE cidr <<= ? AND type='mm' AND parent_id=0");
[518]585 $sth->execute($cidr);
[371]586 my @cmasters;
[628]587 my @oldmids;
[371]588 while (my @data = $sth->fetchrow_array) {
589 my $master = new NetAddr::IP $data[0];
590 push @cmasters, $master;
[628]591 push @oldmids, $data[1];
[371]592 $smallmask = $master->masklen if $master->masklen > $smallmask;
593 }
594
595 # split the new master, and keep only those blocks not part of an existing master
596 my @blocklist;
597 foreach my $seg ($cidr->split($smallmask)) {
598 my $contained = 0;
599 foreach my $master (@cmasters) {
600 $contained = 1 if $master->contains($seg);
601 }
602 push @blocklist, $seg if !$contained;
603 }
604
[628]605##fixme: master_id
[371]606 # collect the unrouted free blocks within the new master
[556]607 $sth = $dbh->prepare("SELECT cidr FROM freeblocks WHERE masklen(cidr) <= ? AND cidr <<= ? AND routed = 'm'");
[518]608 $sth->execute($smallmask, $cidr);
[371]609 while (my @data = $sth->fetchrow_array) {
610 my $freeblock = new NetAddr::IP $data[0];
611 push @blocklist, $freeblock;
612 }
613
614 # combine the set of free blocks we should have now.
615 @blocklist = Compact(@blocklist);
616
[628]617 # master
618 $dbh->do("INSERT INTO allocations (cidr,type,swip,vrf,rdns) VALUES (?,?,?,?,?)", undef,
619 ($cidr, 'mm', 'y', $args{vrf}, $args{rdns}) );
620 ($mid) = $dbh->selectrow_array("SELECT currval('allocations_id_seq')");
621
622 # master should be its own master, so deletes directly at the master level work
623 $dbh->do("UPDATE allocations SET master_id = ? WHERE id = ?", undef, ($mid, $mid) );
624
[371]625 # and now insert the new data. Make sure to delete old masters too.
626
627 # freeblocks
[628]628 $sth = $dbh->prepare("DELETE FROM freeblocks WHERE cidr <<= ? AND parent_id IN (".join(',', @oldmids).")");
629 my $sth2 = $dbh->prepare("INSERT INTO freeblocks (cidr,city,routed,parent_id,vrf,master_id)".
630 " VALUES (?,'<NULL>','m',?,?,?)");
[371]631 foreach my $newblock (@blocklist) {
[518]632 $sth->execute($newblock);
[628]633 $sth2->execute($newblock, $mid, $args{vrf}, $mid);
[371]634 }
635
[628]636 # Update immediate allocations, and remove the old parents
637 $sth = $dbh->prepare("UPDATE allocations SET parent_id = ? WHERE parent_id = ?");
638 $sth2 = $dbh->prepare("DELETE FROM allocations WHERE id = ?");
639 foreach my $old (@oldmids) {
640 $sth->execute($mid, $old);
641 $sth2->execute($old);
642 }
[556]643
[371]644 # *whew* If we got here, we likely suceeded.
645 $dbh->commit;
[628]646
[371]647 } # new master contained existing master(s)
648 }; # end eval
649
650 if ($@) {
651 my $msg = $@;
652 eval { $dbh->rollback; };
653 return ('FAIL',$msg);
654 } else {
[582]655
656 # Only attempt rDNS if the IPDB side succeeded
657 if ($rpc_url) {
658
659# Note *not* splitting reverse zones negates any benefit from caching the exported data.
660# IPv6 address space is far too large to split usefully, and in any case (also due to
661# the large address space) doesn't support the iterated template records v4 zones do
662# that causes the bulk of the slowdown that needs the cache anyway.
663
664 my @zonelist;
665# allow splitting reverse zones to be disabled, maybe, someday
666#if ($splitrevzones && !$cidr->{isv6}) {
667 if (1 && !$cidr->{isv6}) {
668 my $splitpoint = ($cidr->masklen <= 16 ? 16 : 24); # hack pthui
669 @zonelist = $cidr->split($splitpoint);
670 } else {
671 @zonelist = ($cidr);
672 }
673 my @fails;
674 ##fixme: remove hardcoding where possible
675 foreach my $subzone (@zonelist) {
676 my %rpcargs = (
677 rpcuser => $args{user},
678 revzone => "$subzone",
679 revpatt => $args{rdns},
680 defloc => $args{defloc},
[585]681 group => $revgroup, # not sure how these two could sanely be exposed, tbh...
[582]682 state => 1, # could make them globally configurable maybe
683 );
[587]684 if ($rpc_url && !_rpc('addRDNS', %rpcargs)) {
[585]685 push @fails, ("$subzone" => $errstr);
[582]686 }
687 }
688 if (@fails) {
[628]689 $errstr = "Warning(s) adding $cidr to reverse DNS:\n".join("\n", @fails);
690 return ('WARN',$mid);
[582]691 }
692 }
[628]693 return ('OK',$mid);
[371]694 }
695} # end addMaster
696
697
[547]698## IPDB::touchMaster()
699# Update last-changed timestamp on a master block.
700sub touchMaster {
701 my $dbh = shift;
702 my $master = shift;
703
704 local $dbh->{AutoCommit} = 0;
705 local $dbh->{RaiseError} = 1;
706
707 eval {
[652]708 $dbh->do("UPDATE allocations SET modifystamp=now() WHERE id = ?", undef, ($master));
[547]709 $dbh->commit;
710 };
711
712 if ($@) {
713 my $msg = $@;
714 eval { $dbh->rollback; };
715 return ('FAIL',$msg);
716 }
717 return ('OK','OK');
718} # end touchMaster()
719
720
[523]721## IPDB::listSummary()
722# Get summary list of all master blocks
723# Returns an arrayref to a list of hashrefs containing the master block, routed count,
724# allocated count, free count, and largest free block masklength
725sub listSummary {
726 my $dbh = shift;
727
[625]728 my $mlist = $dbh->selectall_arrayref("SELECT cidr AS master,id,vrf FROM allocations ".
729 "WHERE type='mm' ORDER BY cidr",
730 { Slice => {} });
[523]731
732 foreach (@{$mlist}) {
[625]733 my ($rcnt) = $dbh->selectrow_array("SELECT count(*) FROM allocations WHERE cidr <<= ? AND type='rm' AND master_id = ?",
734 undef, ($$_{master}, $$_{id}));
[523]735 $$_{routed} = $rcnt;
[625]736 my ($acnt) = $dbh->selectrow_array("SELECT count(*) FROM allocations WHERE cidr <<= ? ".
737 "AND NOT type='rm' AND NOT type='mm' AND master_id = ?",
738 undef, ($$_{master}, $$_{id}));
[523]739 $$_{allocated} = $acnt;
[625]740 my ($fcnt) = $dbh->selectrow_array("SELECT count(*) FROM freeblocks WHERE cidr <<= ? AND master_id = ?",
741 undef, ($$_{master}, $$_{id}));
[523]742 $$_{free} = $fcnt;
[560]743 my ($bigfree) = $dbh->selectrow_array("SELECT masklen(cidr) AS maskbits FROM freeblocks WHERE cidr <<= ?".
[625]744 " AND master_id = ? ORDER BY masklen(cidr) LIMIT 1", undef, ($$_{master}, $$_{id}));
[523]745##fixme: should find a way to do this without having to HTMLize the <>
746 $bigfree = "/$bigfree" if $bigfree;
[525]747 $bigfree = '<NONE>' if !$bigfree;
[523]748 $$_{bigfree} = $bigfree;
749 }
750 return $mlist;
751} # end listSummary()
752
753
[561]754## IPDB::listSubs()
755# Get list of subnets within a specified CIDR block, on a specified VRF.
756# Returns an arrayref to a list of hashrefs containing the CIDR block, customer location or
757# city it's routed to, block type, SWIP status, and description
758sub listSubs {
759 my $dbh = shift;
760 my %args = @_;
761
762 # Just In Case
763 $args{vrf} = '' if !$args{vrf};
764
765 # Snag the allocations for this block
[691]766 my $sth = $dbh->prepare("SELECT cidr,city,type,custid,swip,description,vrf,id,master_id".
[627]767 " FROM allocations WHERE parent_id = ? ORDER BY cidr");
768 $sth->execute($args{parent});
[561]769
770 # hack hack hack
771 # set up to flag swip=y records if they don't actually have supporting data in the customers table
772 my $custsth = $dbh->prepare("SELECT count(*) FROM customers WHERE custid = ?");
773
[653]774 # snag some more details
[664]775 my $substh = $dbh->prepare("SELECT count(*) FROM allocations WHERE cidr <<= ? ".
[663]776 "AND type ~ '[mc]\$' AND master_id = ? AND NOT cidr = ? ");
[653]777 my $alsth = $dbh->prepare("SELECT count(*) FROM allocations WHERE cidr <<= ? ".
[712]778 "AND NOT type='rm' AND NOT type='mm' AND master_id = ? AND NOT id = ?");
[653]779 my $freesth = $dbh->prepare("SELECT count(*) FROM freeblocks WHERE cidr <<= ? AND master_id = ?");
780 my $lfreesth = $dbh->prepare("SELECT masklen(cidr) AS maskbits FROM freeblocks WHERE cidr <<= ?".
781 " AND master_id = ? ORDER BY masklen(cidr) LIMIT 1");
782
[561]783 my @blocklist;
[691]784 while (my ($cidr,$city,$type,$custid,$swip,$desc,$vrf,$id,$mid) = $sth->fetchrow_array()) {
785 $desc .= " - vrf:$vrf" if $desc && $vrf;
786 $desc = "vrf:$vrf" if !$desc && $vrf;
[561]787 $custsth->execute($custid);
788 my ($ncust) = $custsth->fetchrow_array();
[653]789 $substh->execute($cidr, $mid, $cidr);
790 my ($cont) = $substh->fetchrow_array();
[712]791 $alsth->execute($cidr, $mid, $id);
[653]792 my ($alloc) = $alsth->fetchrow_array();
793 $freesth->execute($cidr, $mid);
794 my ($free) = $freesth->fetchrow_array();
795 $lfreesth->execute($cidr, $mid);
796 my ($lfree) = $lfreesth->fetchrow_array();
797 $lfree = "/$lfree" if $lfree;
798 $lfree = '<NONE>' if !$lfree;
[561]799 my %row = (
800 block => $cidr,
[653]801 subcontainers => $cont,
802 suballocs => $alloc,
803 subfree => $free,
804 lfree => $lfree,
[561]805 city => $city,
806 type => $disp_alloctypes{$type},
807 custid => $custid,
808 swip => ($swip eq 'y' ? 'Yes' : 'No'),
809 partswip => ($swip eq 'y' && $ncust == 0 ? 1 : 0),
810 desc => $desc,
811 hassubs => ($type eq 'rm' || $type =~ /.c/ ? 1 : 0),
[627]812 id => $id,
[561]813 );
814# $row{subblock} = ($type =~ /^.r$/); # hmf. wonder why these won't work in the hash declaration...
815 $row{listpool} = ($type =~ /^.[pd]$/);
816 push (@blocklist, \%row);
817 }
818 return \@blocklist;
819} # end listSubs()
820
821
[663]822## IPDB::listContainers()
823# List all container-type allocations in a given parent
824# Takes a database handle and a hash:
825# - parent is the ID of the parent block
826# Returns an arrayref to a list of hashrefs with the CIDR block, location, type,
827# description, block ID, and counts for the nmber uf suballocations (all types),
828# free blocks, and the CIDR size of the largest free block
829sub listContainers {
830 my $dbh = shift;
831 my %args = @_;
832
833 # Just In Case
834 $args{vrf} = '' if !$args{vrf};
835
836 # Snag the allocations for this block
[691]837 my $sth = $dbh->prepare("SELECT cidr,city,type,custid,swip,description,vrf,id,master_id".
[663]838 " FROM allocations WHERE parent_id = ? AND type ~ '[mc]\$' ORDER BY cidr");
839 $sth->execute($args{parent});
840
841 my $alsth = $dbh->prepare("SELECT count(*) FROM allocations WHERE cidr <<= ? ".
[712]842 "AND NOT type='rm' AND NOT type='mm' AND master_id = ? AND NOT id = ?");
[663]843 my $freesth = $dbh->prepare("SELECT count(*) FROM freeblocks WHERE cidr <<= ? AND master_id = ?");
844 my $lfreesth = $dbh->prepare("SELECT masklen(cidr) AS maskbits FROM freeblocks WHERE cidr <<= ?".
845 " AND master_id = ? ORDER BY masklen(cidr) LIMIT 1");
846
847 my @blocklist;
[691]848 while (my ($cidr,$city,$type,$custid,$swip,$desc,$vrf,$id,$mid) = $sth->fetchrow_array()) {
849 $desc .= " - vrf:$vrf" if $desc && $vrf;
850 $desc = "vrf:$vrf" if !$desc && $vrf;
[712]851 $alsth->execute($cidr, $mid, $id);
[663]852 my ($alloc) = $alsth->fetchrow_array();
853 $freesth->execute($cidr, $mid);
854 my ($free) = $freesth->fetchrow_array();
855 $lfreesth->execute($cidr, $mid);
856 my ($lfree) = $lfreesth->fetchrow_array();
857 $lfree = "/$lfree" if $lfree;
858 $lfree = '<NONE>' if !$lfree;
859 my %row = (
860 block => $cidr,
861 suballocs => $alloc,
862 subfree => $free,
863 lfree => $lfree,
864 city => $city,
865 type => $disp_alloctypes{$type},
866 desc => $desc,
867 id => $id,
868 );
869 push (@blocklist, \%row);
870 }
871 return \@blocklist;
872} # end listContainers()
873
874
875## IPDB::listAllocations()
876# List all end-use allocations in a given parent
877# Takes a database handle and a hash:
878# - parent is the ID of the parent block
879# Returns an arrayref to a list of hashrefs with the CIDR block, location, type,
880# custID, SWIP flag, description, block ID, and master ID
881sub listAllocations {
882 my $dbh = shift;
883 my %args = @_;
884
885 # Snag the allocations for this block
[691]886 my $sth = $dbh->prepare("SELECT cidr,city,type,custid,swip,description,vrf,id,master_id".
[663]887 " FROM allocations WHERE parent_id = ? AND type !~ '[mc]\$' ORDER BY cidr");
888 $sth->execute($args{parent});
889
890 # hack hack hack
891 # set up to flag swip=y records if they don't actually have supporting data in the customers table
892 my $custsth = $dbh->prepare("SELECT count(*) FROM customers WHERE custid = ?");
893
894 my @blocklist;
[691]895 while (my ($cidr,$city,$type,$custid,$swip,$desc,$vrf,$id,$mid) = $sth->fetchrow_array()) {
896 $desc .= " - vrf:$vrf" if $desc && $vrf;
897 $desc = "vrf:$vrf" if !$desc && $vrf;
[663]898 $custsth->execute($custid);
899 my ($ncust) = $custsth->fetchrow_array();
900 my %row = (
901 block => $cidr,
902 city => $city,
903 type => $disp_alloctypes{$type},
904 custid => $custid,
905 swip => ($swip eq 'y' ? 'Yes' : 'No'),
906 partswip => ($swip eq 'y' && $ncust == 0 ? 1 : 0),
907 desc => $desc,
908 id => $id,
909 );
910# $row{subblock} = ($type =~ /^.r$/); # hmf. wonder why these won't work in the hash declaration...
911 $row{listpool} = ($type =~ /^.[pd]$/);
912 push (@blocklist, \%row);
913 }
914 return \@blocklist;
915} # end listAllocations()
916
917
[720]918## IPDB::listForMerge()
919# Get a list of blocks targetted in a proposed merge
920sub listForMerge {
921 my $dbh = shift;
922 my $parent = shift;
923 my $newblock = shift;
924 my $btype = shift || 'a';
925 $btype = 'a' if $btype !~/^[af]$/;
[733]926 my $incsub = shift;
927 $incsub = 1 if !defined($incsub);
[720]928
929 my $sql;
930 if ($btype eq 'a') {
931 my $ret = $dbh->selectall_arrayref(q(
932 SELECT a.cidr,a.id,t.dispname FROM allocations a
933 JOIN alloctypes t ON a.type=t.type
934 WHERE a.parent_id = ? AND a.cidr <<= ?
935 ORDER BY a.cidr
936 ),
937 { Slice => {} }, $parent, $newblock);
938 return $ret;
939 } else {
940##fixme: Not sure about the casting hackery in "SELECT ?::integer AS id", but it works as intended
[733]941 my @dbargs = ($parent, "$newblock");
942 push @dbargs, $parent, $newblock if $incsub;
943 my $ret = $dbh->selectall_arrayref(q{
944 SELECT cidr,id FROM freeblocks
945 WHERE parent_id IN (
946 }.($incsub ? "SELECT id FROM allocations WHERE parent_id = ? AND cidr <<= ? UNION " : '').q{
947 SELECT ?::integer AS id
948 ) AND cidr <<= ?
949 ORDER BY cidr
950 },
951 { Slice => {} }, @dbargs);
[720]952 return $ret;
953 }
[733]954 return;
[720]955} # end listForMerge()
956
957
[524]958## IPDB::listFree()
[562]959# Gets a list of free blocks in the requested parent/master and VRF instance in both CIDR and range notation
[630]960# Takes a parent/master ID and an optional VRF specifier that defaults to empty.
[524]961# Returns an arrayref to a list of hashrefs containing the CIDR and range-notation blocks
[527]962# Returns some extra flags in the hashrefs for routed blocks, since those can have several subtypes
[524]963sub listFree {
964 my $dbh = shift;
965
[562]966 my %args = @_;
967 # Just In Case
968 $args{vrf} = '' if !$args{vrf};
969
[692]970 my $sth = $dbh->prepare(q(
971 SELECT f.cidr,f.id,allocations.cidr
972 FROM freeblocks f
973 LEFT JOIN allocations ON f.reserve_for = allocations.id
974 WHERE f.parent_id = ?
975 ORDER BY f.cidr
976 ) );
[630]977# $sth->execute($args{parent}, $args{vrf});
978 $sth->execute($args{parent});
[524]979 my @flist;
[692]980 while (my ($cidr,$id,$resv) = $sth->fetchrow_array()) {
[524]981 $cidr = new NetAddr::IP $cidr;
[527]982 my %row = (
983 fblock => "$cidr",
984 frange => $cidr->range,
[630]985 fbid => $id,
986 fbparent => $args{parent},
[692]987 resv => $resv,
[527]988 );
[524]989 push @flist, \%row;
990 }
991 return \@flist;
[527]992} # end listFree()
[524]993
994
[528]995## IPDB::listPool()
996#
997sub listPool {
998 my $dbh = shift;
999 my $pool = shift;
1000
[630]1001 my $sth = $dbh->prepare("SELECT ip,custid,available,description,type,id".
1002 " FROM poolips WHERE parent_id = ? ORDER BY ip");
[528]1003 $sth->execute($pool);
1004 my @poolips;
[630]1005 while (my ($ip,$custid,$available,$desc,$type,$id) = $sth->fetchrow_array) {
[528]1006 my %row = (
1007 ip => $ip,
1008 custid => $custid,
1009 available => $available,
1010 desc => $desc,
[563]1011 delme => $available eq 'n',
[630]1012 parent => $pool,
1013 id => $id,
[528]1014 );
1015 push @poolips, \%row;
1016 }
1017 return \@poolips;
1018} # end listPool()
1019
1020
[541]1021## IPDB::getMasterList()
1022# Get a list of master blocks, optionally including last-modified timestamps
1023# Takes an optional flag to indicate whether to include timestamps;
1024# 'm' includes ctime, all others (suggest 'c') do not.
1025# Returns an arrayref to a list of hashrefs
1026sub getMasterList {
1027 my $dbh = shift;
1028 my $stampme = shift || 'm'; # optional but should be set by caller for clarity
1029
[632]1030 my $mlist = $dbh->selectall_arrayref("SELECT id,vrf,cidr AS master".($stampme eq 'm' ? ',modifystamp AS mtime' : '').
1031 " FROM allocations WHERE type='mm' ORDER BY cidr", { Slice => {} });
[541]1032 return $mlist;
1033} # end getMasterList()
1034
1035
[529]1036## IPDB::getTypeList()
1037# Get an alloctype/description pair list suitable for dropdowns
1038# Takes a flag to determine which general groups of types are returned
1039# Returns an reference to an array of hashrefs
1040sub getTypeList {
1041 my $dbh = shift;
1042 my $tgroup = shift || 'a'; # technically optional, like this, but should
1043 # really be specified in the call for clarity
[714]1044 my $seltype = shift || '';
1045
1046 my $sql = "SELECT type,listname,type=? AS sel FROM alloctypes WHERE listorder <= 500";
[564]1047 if ($tgroup eq 'n') {
1048 # grouping 'p' - all netblock types. These include routed blocks, containers (_c)
1049 # and contained (_r) types, dynamic-allocation ranges (_e), static IP pools (_d and _p),
1050 # and the "miscellaneous" cn, in, and en types.
[714]1051 $sql .= " AND type NOT LIKE '_i'";
[564]1052 } elsif ($tgroup eq 'p') {
1053 # grouping 'p' - primary allocation types. As with 'n' above but without the _r contained types.
[714]1054 $sql .= " AND type NOT LIKE '_i' AND type NOT LIKE '_r'";
[529]1055 } elsif ($tgroup eq 'c') {
1056 # grouping 'c' - contained types. These include all static IPs and all _r types.
[714]1057 $sql .= " AND (type LIKE '_i' OR type LIKE '_r')";
[632]1058 } elsif ($tgroup eq 'i') {
1059 # grouping 'i' - static IP types.
[714]1060 $sql .= " AND type LIKE '_i'";
[529]1061 } else {
1062 # grouping 'a' - all standard allocation types. This includes everything
1063 # but mm (present only as a formality). Make this the default.
[714]1064 # ... whee! no extra WHERE clauses
[529]1065 }
[714]1066 $sql .= " ORDER BY listorder";
1067 my $tlist = $dbh->selectall_arrayref($sql, { Slice => {} }, $seltype);
[529]1068 return $tlist;
1069}
1070
1071
[532]1072## IPDB::getPoolSelect()
1073# Get a list of pools matching the passed city and type that have 1 or more free IPs
[533]1074# Returns an arrayref to a list of hashrefs
[532]1075sub getPoolSelect {
1076 my $dbh = shift;
1077 my $iptype = shift;
1078 my $pcity = shift;
1079
1080 my ($ptype) = ($iptype =~ /^(.)i$/);
1081 return if !$ptype;
1082 $ptype .= '_';
1083
[663]1084 my $plist = $dbh->selectall_arrayref( q(
1085 SELECT count(*) AS poolfree,p.pool AS poolblock, a.city AS poolcit
1086 FROM poolips p
1087 JOIN allocations a ON p.parent_id=a.id
1088 WHERE p.available='y' AND a.city = ? AND p.type LIKE ?
1089 GROUP BY p.pool,a.city
1090 ),
[572]1091 { Slice => {} }, ($pcity, $ptype) );
[532]1092 return $plist;
1093} # end getPoolSelect()
1094
1095
[533]1096## IPDB::findAllocateFrom()
1097# Find free block to add a new allocation from. (CIDR block version of pool select above, more or less)
1098# Takes
1099# - mask length
1100# - allocation type
1101# - POP city "parent"
1102# - optional master-block restriction
1103# - optional flag to allow automatic pick-from-private-network-ranges
1104# Returns a string with the first CIDR block matching the criteria, if any
1105sub findAllocateFrom {
1106 my $dbh = shift;
1107 my $maskbits = shift;
1108 my $type = shift;
1109 my $city = shift;
1110 my $pop = shift;
1111 my %optargs = @_;
1112
1113 my $failmsg = "No suitable free block found\n";
1114
[633]1115 my @vallist;
1116 my $sql;
1117
1118 # Free pool IPs should be easy.
1119 if ($type =~ /^.i$/) {
1120 # User may get an IP from the wrong VRF. User should not be using admin tools to allocate static IPs.
1121 $sql = "SELECT id, ip, parent_id FROM poolips WHERE ip = ?";
1122 @vallist = ($optargs{gimme});
1123 } else {
1124
[533]1125## Set up the SQL to find out what freeblock we can (probably) use for an allocation.
1126## Very large systems will require development of a reserve system (possibly an extension
1127## of the reserve-for-expansion concept in https://secure.deepnet.cx/trac/ipdb/ticket/24?)
1128## Also populate a value list for the DBI call.
1129
[633]1130 @vallist = ($maskbits);
1131 $sql = "SELECT id,cidr,parent_id FROM freeblocks WHERE masklen(cidr) <= ?";
[533]1132
[572]1133# cases, strict rules
1134# .c -> container type
1135# requires a routing container, fbtype r
1136# .d -> DHCP/"normal-routing" static pool
1137# requires a routing container, fbtype r
1138# .e -> Dynamic-assignment connectivity
1139# requires a routing container, fbtype r
1140# .i -> error, can't allocate static IPs this way?
1141# mm -> error, master block
1142# rm -> routed block
1143# requires master block, fbtype m
1144# .n -> Miscellaneous usage
1145# requires a routing container, fbtype r
1146# .p -> PPP(oE) static pool
1147# requires a routing container, fbtype r
1148# .r -> contained type
1149# requires a matching container, fbtype $1
1150##fixme: strict-or-not flag
1151
[633]1152##fixme: config or UI flag for "Strict" mode
1153# if ($strictmode) {
1154if (0) {
[572]1155 if ($type =~ /^(.)r$/) {
1156 push @vallist, $1;
1157 $sql .= " AND routed = ?";
1158 } elsif ($type eq 'rm') {
1159 $sql .= " AND routed = 'm'";
1160 } else {
1161 $sql .= " AND routed = 'r'";
1162 }
[633]1163}
[572]1164
[633]1165 # for PPP(oE) and container types, the POP city is the one attached to the pool.
1166 # individual allocations get listed with the customer city site.
1167 ##fixme: chain cities to align roughly with a full layer-2 node graph
1168 $city = $pop if $type !~ /^.[pc]$/;
1169 if ($type ne 'rm' && $city) {
1170 $sql .= " AND city = ?";
1171 push @vallist, $city;
[533]1172 }
[633]1173 # Allow specifying an arbitrary full block, instead of a master
1174 if ($optargs{gimme}) {
1175 $sql .= " AND cidr >>= ?";
1176 push @vallist, $optargs{gimme};
1177 }
1178 # if a specific master was requested, allow the requestor to self->shoot(foot)
1179 if ($optargs{master} && $optargs{master} ne '-') {
1180 $sql .= " AND master_id = ?";
1181# if $optargs{master} ne '-';
1182 push @vallist, $optargs{master};
1183 } else {
1184 # if a specific master was NOT requested, filter out the RFC 1918 private networks
1185 if (!$optargs{allowpriv}) {
1186 $sql .= " AND NOT (cidr <<= '192.168.0.0/16' OR cidr <<= '10.0.0.0/8' OR cidr <<= '172.16.0.0/12')";
1187 }
1188 }
[693]1189 # Keep "reserved" blocks out of automatic assignment.
1190##fixme: needs a UI flag or a config knob
1191 $sql .= " AND reserve_for = 0";
[633]1192 # Sorting and limiting, since we don't (currently) care to provide a selection of
1193 # blocks to carve up. This preserves something resembling optimal usage of the IP
1194 # space by forcing contiguous allocations and free blocks as much as possible.
1195 $sql .= " ORDER BY masklen(cidr) DESC,cidr LIMIT 1";
1196 } # done setting up SQL for free CIDR block
[533]1197
[633]1198 my ($fbid,$fbfound,$fbparent) = $dbh->selectrow_array($sql, undef, @vallist);
1199 return $fbid,$fbfound,$fbparent;
[533]1200} # end findAllocateFrom()
1201
1202
[536]1203## IPDB::ipParent()
1204# Get an IP's parent pool's details
1205# Takes a database handle and IP
1206# Returns a hashref to the parent pool block, if any
1207sub ipParent {
1208 my $dbh = shift;
1209 my $block = shift;
1210
1211 my $pinfo = $dbh->selectrow_hashref("SELECT cidr,custid,type,city,description FROM allocations".
[565]1212 " WHERE cidr >>= ? AND (type LIKE '_p' OR type LIKE '_d')", undef, ($block) );
[536]1213 return $pinfo;
1214} # end ipParent()
1215
1216
1217## IPDB::subParent()
[529]1218# Get a block's parent's details
1219# Takes a database handle and CIDR block
[536]1220# Returns a hashref to the parent container block, if any
1221sub subParent {
[529]1222 my $dbh = shift;
1223 my $block = shift;
1224
1225 my $pinfo = $dbh->selectrow_hashref("SELECT cidr,custid,type,city,description FROM allocations".
1226 " WHERE cidr >>= ?", undef, ($block) );
1227 return $pinfo;
[536]1228} # end subParent()
[529]1229
1230
[536]1231## IPDB::blockParent()
1232# Get a block's parent's details
1233# Takes a database handle and CIDR block
1234# Returns a hashref to the parent container block, if any
1235sub blockParent {
1236 my $dbh = shift;
1237 my $block = shift;
1238
1239 my $pinfo = $dbh->selectrow_hashref("SELECT cidr,city FROM routed".
1240 " WHERE cidr >>= ?", undef, ($block) );
1241 return $pinfo;
1242} # end blockParent()
1243
1244
[697]1245## IPDB::getBreadCrumbs()
1246# Retrieve the ID and CIDR of a block's parent(s) up to the master block
1247# Returns an arrayref to a list of hashrefs with CIDR and block ID
1248sub getBreadCrumbs {
1249 my $dbh = shift;
1250 my $parent = shift;
1251 my @result;
1252
1253 my $sth = $dbh-> prepare("SELECT cidr,type,id,parent_id FROM allocations WHERE id=?");
1254
1255 while ($parent != 0) {
1256 $sth->execute($parent);
1257 my ($cidr,$type,$id,$pid) = $sth->fetchrow_array;
1258 push @result, {cidr => $cidr, link => $id, ispool => ($type =~ /^.[dp]$/ ? 1 : 0)};
1259 $parent = $pid;
1260 }
1261
1262 return \@result;
1263} # end getBread()
1264
1265
[527]1266## IPDB::getRoutedCity()
1267# Get the city for a routed block.
1268sub getRoutedCity {
1269 my $dbh = shift;
1270 my $block = shift;
1271
1272 my ($rcity) = $dbh->selectrow_array("SELECT city FROM routed WHERE cidr = ?", undef, ($block) );
1273 return $rcity;
1274} # end getRoutedCity()
1275
1276
[77]1277## IPDB::allocateBlock()
[66]1278# Does all of the magic of actually allocating a netblock
[554]1279# Requires a database handle, and a hash containing the block to allocate, routing depth, custid,
1280# type, city, block to allocate from, and optionally a description, notes, circuit ID,
1281# and private data
[77]1282# Returns a success code and optional error message.
1283sub allocateBlock {
[554]1284 my $dbh = shift;
[284]1285
[554]1286 my %args = @_;
1287
1288 $args{cidr} = new NetAddr::IP $args{cidr};
1289
1290 $args{desc} = '' if !$args{desc};
1291 $args{notes} = '' if !$args{notes};
1292 $args{circid} = '' if !$args{circid};
1293 $args{privdata} = '' if !$args{privdata};
1294 $args{vrf} = '' if !$args{vrf};
[691]1295 $args{vlan} = '' if !$args{vlan};
[585]1296 $args{rdns} = '' if !$args{rdns};
[554]1297
[690]1298 # Could arguably allow this for eg /120 allocations, but end users who get a single v4 IP are
1299 # usually given a v6 /64, and most v6 addressing schemes need at least half that address space
1300 if ($args{cidr}->{isv6} && $args{rdns} =~ /\%/) {
1301 return ('FAIL','Reverse DNS template patterns are not supported for IPv6 allocations');
1302 }
1303
[77]1304 my $sth;
[66]1305
[633]1306 # Snag the "type" of the freeblock and its CIDR
1307 my ($alloc_from_type, $alloc_from, $fbparent, $fcity, $fbmaster) =
1308 $dbh->selectrow_array("SELECT routed,cidr,parent_id,city,master_id FROM freeblocks WHERE id = ?",
1309 undef, $args{fbid});
1310 $alloc_from = new NetAddr::IP $alloc_from;
[692]1311 return ('FAIL',"Failed to allocate $args{cidr}; intended free block was used by another allocation.")
1312 if !$fbparent;
1313##fixme: fail here if !$alloc_from
1314# also consider "lock for allocation" due to multistep allocation process
[349]1315
[79]1316 # To contain the error message, if any.
[554]1317 my $msg = "Unknown error allocating $args{cidr} as '$disp_alloctypes{$args{type}}'";
[79]1318
[77]1319 # Enable transactions and error handling
1320 local $dbh->{AutoCommit} = 0; # These need to be local so we don't
1321 local $dbh->{RaiseError} = 1; # step on our toes by accident.
[66]1322
[554]1323 if ($args{type} =~ /^.i$/) {
1324 $msg = "Unable to assign static IP $args{cidr} to $args{custid}";
[77]1325 eval {
[554]1326 if ($args{cidr}) { # IP specified
1327 my ($isavail) = $dbh->selectrow_array("SELECT available FROM poolips WHERE ip=?", undef, ($args{cidr}) );
1328 die "IP is not in an IP pool.\n"
1329 if !$isavail;
1330 die "IP already allocated. Deallocate and reallocate, or update the entry\n"
1331 if $isavail eq 'n';
1332 } else { # IP not specified, take first available
1333 ($args{cidr}) = $dbh->selectrow_array("SELECT ip FROM poolips WHERE pool=? AND available='y' ORDER BY ip",
1334 undef, ($args{alloc_from}) );
[545]1335 }
[633]1336 $dbh->do("UPDATE poolips SET custid = ?, city = ?,available='n', description = ?, notes = ?, ".
1337 "circuitid = ?, privdata = ?, vrf = ?, rdns = ? ".
1338 "WHERE ip = ? AND parent_id = ?", undef,
1339 ($args{custid}, $args{city}, $args{desc}, $args{notes},
1340 $args{circid}, $args{privdata}, $args{vrf}, $args{rdns},
1341 $args{cidr}, $args{parent}) );
[157]1342
[397]1343# node hack
[554]1344 if ($args{nodeid} && $args{nodeid} ne '') {
1345 $dbh->do("INSERT INTO noderef (block,node_id) VALUES (?,?)", undef, ($args{cidr}, $args{nodeid}) );
[397]1346 }
1347# end node hack
[545]1348
[691]1349 $dbh->commit; # Allocate IP from pool
[77]1350 };
1351 if ($@) {
[545]1352 $msg .= ": $@";
[78]1353 eval { $dbh->rollback; };
[578]1354 return ('FAIL', $msg);
[77]1355 } else {
[585]1356 _rpc('addOrUpdateRevRec', cidr => "$args{cidr}", name => $args{rdns}, rpcuser => $args{user});
[578]1357 return ('OK', $args{cidr});
[77]1358 }
1359
1360 } else { # end IP-from-pool allocation
1361
[633]1362 if ($args{cidr} == $alloc_from) {
[77]1363 # Easiest case- insert in one table, delete in the other, and go home. More or less.
1364 # insert into allocations values (cidr,custid,type,city,desc) and
1365 # delete from freeblocks where cidr='cidr'
1366 # For data safety on non-transaction DBs, we delete first.
1367
1368 eval {
[554]1369 $msg = "Unable to allocate $args{cidr} as '$disp_alloctypes{$args{type}}'";
1370
[633]1371 # Insert the allocations entry
1372 $dbh->do("INSERT INTO allocations ".
[691]1373 "(cidr,parent_id,master_id,vrf,vlan,custid,type,city,description,notes,circuitid,privdata,rdns)".
1374 " VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)", undef,
1375 ($args{cidr}, $fbparent, $fbmaster, $args{vrf}, $args{vlan}, $args{custid}, $args{type}, $args{city},
[633]1376 $args{desc}, $args{notes}, $args{circid}, $args{privdata}, $args{rdns}) );
1377 my ($bid) = $dbh->selectrow_array("SELECT currval('allocations_id_seq')");
[555]1378
[554]1379 # Munge freeblocks
1380 if ($args{type} =~ /^(.)[mc]$/) {
1381 # special case - block is a routed or container/"reserve" block
1382 my $rtype = $1;
[633]1383 $dbh->do("UPDATE freeblocks SET routed = ?,city = ?,parent_id = ? WHERE id = ?",
1384 undef, ($rtype, $args{city}, $bid, $args{fbid}) );
[77]1385 } else {
[554]1386 # "normal" case
[633]1387 $dbh->do("DELETE FROM freeblocks WHERE id = ?", undef, ($args{fbid}) );
[554]1388 }
[77]1389
[554]1390 # And initialize the pool, if necessary
1391 # PPPoE pools (currently dialup, DSL, and WiFi) get all IPs made available
1392 # "DHCP" or "real-subnet" pools have the net, gw, and bcast IPs removed.
1393 if ($args{type} =~ /^.p$/) {
1394 $msg = "Could not initialize IPs in new $disp_alloctypes{$args{type}} $args{cidr}";
[633]1395 my ($code,$rmsg) = initPool($dbh, $args{cidr}, $args{type}, $args{city}, "all", $bid);
[554]1396 die $rmsg if $code eq 'FAIL';
1397 } elsif ($args{type} =~ /^.d$/) {
1398 $msg = "Could not initialize IPs in new $disp_alloctypes{$args{type}} $args{cidr}";
[633]1399 my ($code,$rmsg) = initPool($dbh, $args{cidr}, $args{type}, $args{city}, "normal", $bid);
[554]1400 die $rmsg if $code eq 'FAIL';
1401 }
[79]1402
[397]1403# node hack
[554]1404 if ($args{nodeid} && $args{nodeid} ne '') {
1405 $dbh->do("INSERT INTO noderef (block,node_id) VALUES (?,?)", undef, ($args{cidr}, $args{nodeid}) );
[397]1406 }
1407# end node hack
[574]1408
[691]1409 $dbh->commit; # Simple block allocation
[78]1410 }; # end of eval
[77]1411 if ($@) {
[157]1412 $msg .= ": ".$@;
[77]1413 eval { $dbh->rollback; };
[157]1414 return ('FAIL',$msg);
[78]1415 }
[77]1416
1417 } else { # cidr != alloc_from
1418
1419 # Hard case. Allocation is smaller than free block.
[633]1420
1421 # make sure new allocation is in fact within freeblock. *sigh*
1422 return ('FAIL',"Requested allocation $args{cidr} is not within $alloc_from")
1423 if !$alloc_from->contains($args{cidr});
[554]1424 my $wantmaskbits = $args{cidr}->masklen;
[633]1425 my $maskbits = $alloc_from->masklen;
[77]1426
1427 my @newfreeblocks; # Holds free blocks generated from splitting the source freeblock.
1428
1429 # This determines which blocks will be left "free" after allocation. We take the
1430 # block we're allocating from, and split it in half. We see which half the wanted
1431 # block is in, and repeat until the wanted block is equal to one of the halves.
1432 my $i=0;
[633]1433 my $tmp_from = $alloc_from; # So we don't munge $args{alloc_from}
[77]1434 while ($maskbits++ < $wantmaskbits) {
1435 my @subblocks = $tmp_from->split($maskbits);
[554]1436 $newfreeblocks[$i++] = (($args{cidr}->within($subblocks[0])) ? $subblocks[1] : $subblocks[0]);
1437 $tmp_from = ( ($args{cidr}->within($subblocks[0])) ? $subblocks[0] : $subblocks[1] );
[77]1438 } # while
1439
1440 # Begin SQL transaction block
1441 eval {
[554]1442 $msg = "Unable to allocate $args{cidr} as '$disp_alloctypes{$args{type}}'";
[79]1443
[77]1444 # Delete old freeblocks entry
[633]1445 $dbh->do("DELETE FROM freeblocks WHERE id = ?", undef, ($args{fbid}) );
[77]1446
[633]1447 # Insert the allocations entry
1448 $dbh->do("INSERT INTO allocations ".
[691]1449 "(cidr,parent_id,master_id,vrf,vlan,custid,type,city,description,notes,circuitid,privdata,rdns)".
1450 " VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)", undef,
1451 ($args{cidr}, $fbparent, $fbmaster, $args{vrf}, $args{vlan}, $args{custid}, $args{type}, $args{city},
[633]1452 $args{desc}, $args{notes}, $args{circid}, $args{privdata}, $args{rdns}) );
1453 my ($bid) = $dbh->selectrow_array("SELECT currval('allocations_id_seq')");
1454
[692]1455 # Insert new list of smaller free blocks left over. Flag the one that matches the
1456 # masklength of the new allocation, if a reserve block was requested.
1457 $sth = $dbh->prepare("INSERT INTO freeblocks (cidr,city,routed,vrf,parent_id,master_id,reserve_for) ".
1458 "VALUES (?,?,?,?,?,?,?)");
1459 foreach my $block (@newfreeblocks) {
1460 $sth->execute($block, $fcity, $alloc_from_type, $args{vrf}, $fbparent, $fbmaster,
[721]1461 ($args{reserve} && $block->masklen == $wantmaskbits ? $bid : 0));
[692]1462 }
1463
[554]1464 # For routed/container types, add a freeblock within the allocated block so we can subdivide it further
1465 if ($args{type} =~ /(.)[mc]/) { # rm and .c types - containers
1466 my $rtype = $1;
[698]1467 $sth->execute($args{cidr}, $args{city}, $rtype, $args{vrf}, $bid, $fbmaster, 0);
[554]1468 }
[79]1469
[554]1470 # And initialize the pool, if necessary
1471 # PPPoE pools (currently dialup, DSL, and WiFi) get all IPs made available
1472 # "DHCP" or "real-subnet" pools have the net, gw, and bcast IPs removed.
1473 if ($args{type} =~ /^.p$/) {
1474 $msg = "Could not initialize IPs in new $disp_alloctypes{$args{type}} $args{cidr}";
[633]1475 my ($code,$rmsg) = initPool($dbh, $args{cidr}, $args{type}, $args{city}, "all", $bid);
[554]1476 die $rmsg if $code eq 'FAIL';
1477 } elsif ($args{type} =~ /^.d$/) {
1478 $msg = "Could not initialize IPs in new $disp_alloctypes{$args{type}} $args{cidr}";
[633]1479 my ($code,$rmsg) = initPool($dbh, $args{cidr}, $args{type}, $args{city}, "normal", $bid);
[554]1480 die $rmsg if $code eq 'FAIL';
1481 }
[77]1482
[397]1483# node hack
[554]1484 if ($args{nodeid} && $args{nodeid} ne '') {
1485 $dbh->do("INSERT INTO noderef (block,node_id) VALUES (?,?)", undef, ($args{cidr}, $args{nodeid}) );
[397]1486 }
1487# end node hack
[554]1488
[691]1489 $dbh->commit; # Complex block allocation
[77]1490 }; # end eval
1491 if ($@) {
[256]1492 $msg .= ": ".$@;
[77]1493 eval { $dbh->rollback; };
[78]1494 return ('FAIL',$msg);
[77]1495 }
1496
1497 } # end fullcidr != alloc_from
1498
[590]1499 # now we do the DNS dance for netblocks, if we have an RPC server to do it with and a pattern to use.
1500 _rpc('addOrUpdateRevRec', cidr => "$args{cidr}", name => $args{rdns}, rpcuser => $args{user})
1501 if $args{rdns};
[585]1502
[677]1503 # and the per-IP set, if there is one.
1504 _rpc('updateRevSet', %{$args{iprev}}, rpcuser => $args{user});
1505
[585]1506 return ('OK', 'OK');
1507
[77]1508 } # end static-IP vs netblock allocation
1509
1510} # end allocateBlock()
1511
1512
1513## IPDB::initPool()
1514# Initializes a pool
1515# Requires a database handle, the pool CIDR, type, city, and a parameter
1516# indicating whether the pool should allow allocation of literally every
1517# IP, or if it should reserve network/gateway/broadcast IPs
[78]1518# Note that this is NOT done in a transaction, that's why it's a private
1519# function and should ONLY EVER get called from allocateBlock()
[77]1520sub initPool {
[633]1521 my ($dbh,undef,$type,$city,$class,$parent) = @_;
[77]1522 my $pool = new NetAddr::IP $_[1];
1523
[574]1524 # IPv6 does not lend itself to IP pools as supported
1525 return ('FAIL',"Refusing to create IPv6 static IP pool") if $pool->{isv6};
1526 # IPv4 pools don't make much sense beyond even /24. Allow up to 4096-host footshooting anyway.
1527 # NetAddr::IP won't allow more than a /16 (65k hosts).
1528 return ('FAIL',"Refusing to create oversized static IP pool") if $pool->masklen <= 20;
1529
[691]1530 # Retrieve some odds and ends for defaults on the IPs
[633]1531 my ($pcustid) = $dbh->selectrow_array("SELECT def_custid FROM alloctypes WHERE type=?", undef, ($type) );
[699]1532 my ($vrf,$vlan,$master) = $dbh->selectrow_array("SELECT vrf,vlan,master_id FROM allocations WHERE id = ?",
[691]1533 undef, ($parent) );
1534
[157]1535 $type =~ s/[pd]$/i/;
[77]1536 my $sth;
[157]1537 my $msg;
[77]1538
[157]1539 eval {
1540 # have to insert all pool IPs into poolips table as "unallocated".
[699]1541 $sth = $dbh->prepare("INSERT INTO poolips (ip,custid,city,type,parent_id,master_id) VALUES (?,?,?,?,?,?)");
[695]1542
1543 # in case of pool extension by some means, we need to see what IPs were already inserted
1544 my $tmp1 = $dbh->selectall_arrayref("SELECT ip FROM poolips WHERE parent_id = ?", undef, $parent);
1545 my %foundips;
1546 foreach (@{$tmp1}) {
1547 $foundips{$_->[0]} = 1;
1548 }
1549
[696]1550# Dodge an edge case - pool where IPs have been "stolen" and turned into a netblock assignment.
1551# We can't just "get all the current IPs, and add the missing ones", because some IPs are
1552# legitimately missing (for stretchy values of "legitimately").
1553
1554 my $pdata = getBlockData($dbh, $parent);
1555 my $pcidr = new NetAddr::IP $pdata->{block};
1556
1557 if ($pcidr != $pool) {
1558 # enumerate the IPs from the *old* pool, flag them as "found", so we can iterate the entire
1559 # requested pool and still make sure we skip the IPs in the old pool - even if they've been
1560 # "stolen" by legacy netblocks.
1561 my @oldips = $pcidr->hostenum;
1562 # decide whether to start excluding existing IPs at the "gateway" or "gateway+1"
1563 my $ostart = ($pdata->{type} =~ /^.d$/ ? 1 : 0);
1564 for (my $i = $ostart; $i<= $#oldips; $i++) {
1565 $foundips{$oldips[$i]} = 1;
1566 }
1567 }
1568
[695]1569 # enumerate the hosts in the IP range - everything except the first (net) and last (bcast) IP
[157]1570 my @poolip_list = $pool->hostenum;
[695]1571
1572 # always check/add IPs from gw+1 through bcast-1:
1573 # (but the set won't be in oooorderrrrr! <pout>)
1574 for (my $i=1; $i<=$#poolip_list; $i++) {
[696]1575 my $baseip = $poolip_list[$i]->addr;
1576 if ($baseip !~ /\.(?:0|255)$/ && !$foundips{$poolip_list[$i]}) {
[699]1577 $sth->execute($baseip, $pcustid, $city, $type, $parent, $master);
[696]1578 }
[695]1579 }
1580
1581 # now do the special case - DSL/PPP blocks can use the "net", "gw", and "bcast" IPs.
1582 # we exclude .0 and .255 anyway, since while they'll mostly work, they *will* behave badly here and there.
[157]1583 if ($class eq 'all') { # (DSL-ish block - *all* IPs available
[246]1584 if ($pool->addr !~ /\.0$/) { # .0 causes weirdness.
[734]1585 $sth->execute($pool->addr, $pcustid, $city, $type, $parent, $master) unless $foundips{$pool->addr."/32"};
[246]1586 }
[699]1587 $sth->execute($poolip_list[0]->addr, $pcustid, $city, $type, $parent, $master) unless $foundips{$poolip_list[0]};
[157]1588 $pool--;
[246]1589 if ($pool->addr !~ /\.255$/) { # .255 can cause weirdness.
[734]1590 $sth->execute($pool->addr, $pcustid, $city, $type, $parent, $master) unless $foundips{$pool->addr."/32"};
[246]1591 }
[77]1592 }
[633]1593# don't commit here! the caller may not be done.
1594# $dbh->commit;
[157]1595 };
1596 if ($@) {
[574]1597 $msg = $@;
[633]1598# Don't roll back! It's up to the caller to handle this.
1599# eval { $dbh->rollback; };
[157]1600 return ('FAIL',$msg);
1601 } else {
1602 return ('OK',"OK");
[77]1603 }
1604} # end initPool()
1605
1606
[531]1607## IPDB::updateBlock()
1608# Update an allocation
1609# Takes all allocation fields in a hash
1610sub updateBlock {
1611 my $dbh = shift;
1612 my %args = @_;
1613
1614 return ('FAIL', 'Missing block to update') if !$args{block};
1615
[634]1616 # Spaces don't show up well in lots of places. Make sure they don't get into the DB.
1617 $args{custid} =~ s/^\s+//;
1618 $args{custid} =~ s/\s+$//;
1619
[531]1620 # do it all in a transaction
1621 local $dbh->{AutoCommit} = 0;
1622 local $dbh->{RaiseError} = 1;
1623
1624 my @fieldlist;
1625 my @vallist;
[691]1626 foreach ('custid', 'city', 'description', 'notes', 'circuitid', 'privdata', 'rdns', 'vrf', 'vlan') {
[531]1627 if ($args{$_}) {
1628 push @fieldlist, $_;
1629 push @vallist, $args{$_};
1630 }
1631 }
1632
[634]1633 my $binfo;
[531]1634 my $updtable = 'allocations';
[634]1635 my $keyfield = 'id';
[535]1636 if ($args{type} =~ /^(.)i$/) {
[531]1637 $updtable = 'poolips';
[634]1638 $binfo = getBlockData($dbh, $args{block}, 'i');
[531]1639 } else {
1640## fixme: there's got to be a better way...
[634]1641 $binfo = getBlockData($dbh, $args{block});
[531]1642 if ($args{swip}) {
1643 if ($args{swip} eq 'on' || $args{swip} eq '1' || $args{swip} eq 'y') {
1644 $args{swip} = 'y';
1645 } else {
1646 $args{swip} = 'n';
1647 }
1648 }
1649 foreach ('type', 'swip') {
1650 if ($args{$_}) {
1651 push @fieldlist, $_;
1652 push @vallist, $args{$_};
1653 }
1654 }
1655 }
1656
1657 return ('FAIL', 'No fields to update') if !@fieldlist;
1658
1659 my $sql = "UPDATE $updtable SET ";
1660 $sql .= join " = ?, ", @fieldlist;
1661
1662 eval {
[695]1663 # check for block merge first...
1664 if ($args{fbmerge}) {
1665 my $cidr = NetAddr::IP->new($binfo->{block});
1666 my $newblock = NetAddr::IP->new($cidr->addr, $cidr->masklen - 1)->network;
1667 # safety net? make sure mergeable block passed in is really one or both of
1668 # a) reserved for expansion of the block and
1669 # b) confirmed CIDR-combinable
1670 # "safety? SELECT foo FROM freeblocks WHERE cidr << ? AND masklen(cidr) = ?, $newblock, ".$cidr->masklen."\n";
1671 $dbh->do("DELETE FROM freeblocks WHERE id=?", undef, $args{fbmerge});
1672 # ... so we can append the change in the stored CIDR field to extend the allocation.
1673 $sql .= " = ?, cidr";
1674 push @vallist, $newblock;
1675 # if we have an IP pool, call initPool to fill in any missing entries in the pool
1676 if ($binfo->{type} =~ /^.p$/) {
1677 my ($code,$rmsg) = initPool($dbh, "$newblock", $binfo->{type}, $binfo->{city}, 'all', $args{block});
1678 die $rmsg if $code eq 'FAIL';
1679 } elsif ($binfo->{type} =~ /^.d$/) {
1680 my ($code,$rmsg) = initPool($dbh, "$newblock", $binfo->{type}, $binfo->{city}, 'normal', $args{block});
1681 die $rmsg if $code eq 'FAIL';
1682 }
1683 }
1684
1685 # append another SQL fragment
1686 push @vallist, $args{block};
1687 $sql .= " = ? WHERE $keyfield = ?";
1688
[531]1689 # do the update
1690 $dbh->do($sql, undef, @vallist);
1691
1692 if ($args{node}) {
1693 # done with delete/insert so we don't have to worry about funkyness updating a node ref that isn't there
[634]1694 $dbh->do("DELETE FROM noderef WHERE block = ?", undef, ($binfo->{block}) );
1695 $dbh->do("INSERT INTO noderef (block,node_id) VALUES (?,?)", undef, ($binfo->{block}, $args{node}) )
1696 if $args{node} ne '--';
[531]1697 }
1698
1699 $dbh->commit;
1700 };
1701 if ($@) {
1702 my $msg = $@;
1703 $dbh->rollback;
1704 return ('FAIL', $msg);
1705 }
[588]1706
[686]1707 # In case of any container (mainly master block), only update freeblocks so we don't stomp subs
1708 # (which would be the wrong thing in pretty much any case except "DELETE ALL EVARYTHING!!1!oneone!")
1709 if ($binfo->{type} =~ '.[mc]') {
1710 # Not using listFree() as it doesn't return quite all of the blocks wanted.
1711 # Retrieve the immediate free blocks
1712 my $sth = $dbh->prepare(q(
1713 SELECT cidr FROM freeblocks WHERE parent_id = ?
1714 UNION
1715 SELECT cidr FROM freeblocks f WHERE
1716 cidr = (SELECT cidr FROM allocations a WHERE f.cidr = a.cidr)
1717 AND master_id = ?
1718 ) );
1719 $sth->execute($args{block}, $binfo->{master_id});
1720 my %fbset;
1721 while (my ($fb) = $sth->fetchrow_array) {
1722 $fbset{"host_$fb"} = $args{rdns};
1723 }
1724 # We use this RPC call instead of multiple addOrUpdateRevRec calls, since we don't
1725 # know how many records we'll be updating and more than 3-4 is far too slow. This
1726 # should be safe to call unconditionally.
1727 # Requires dnsadmin >= r678
1728 _rpc('updateRevSet', %fbset, rpcuser => $args{user});
[677]1729
[686]1730 } else {
1731 $binfo->{block} =~ s|/32$||;
1732 _rpc('addOrUpdateRevRec', cidr => $binfo->{block}, name => $args{rdns}, rpcuser => $args{user});
[677]1733
[686]1734 # and the per-IP set, if there is one.
1735 _rpc('updateRevSet', %{$args{iprev}}, rpcuser => $args{user}) if keys (%{$args{iprev}});
1736 }
1737
[588]1738 return ('OK','OK');
[531]1739} # end updateBlock()
1740
1741
[702]1742## IPDB::splitBlock()
1743# Splits an existing allocation into two or more smaller allocations based on a passed netmask
1744# Duplicates all other data
1745# Returns an arrayref to a list of hashrefs with ID and CIDR keys for the list of new allocations.
1746# Should probably commit DNS magic to realign DNS data
[713]1747# Mostly works but may return Strange Things(TM) if used on a master block
[702]1748sub splitBlock {
1749 my $dbh = shift;
[707]1750 my %args = @_;
1751# my $id = shift;
1752# my $basetype = shift;
1753# my $newmask = shift;
[702]1754
1755##fixme: set errstr on errors so caller can suitably clue-by-four the user
[707]1756 return if $args{basetype} ne 'b'; # only netblocks allowed!
[702]1757
[707]1758 my $binfo = getBlockData($dbh, $args{id});
[702]1759 return if !$binfo;
1760
[707]1761 return if $args{newmask} !~ /^\d+$/;
[702]1762
1763 my @ret;
1764 my $block = new NetAddr::IP $binfo->{block};
1765 my $oldmask = $block->masklen;
1766
1767 # Fail if the block to split is "too small" - eg, can't split a v4 /32 at all
1768 # failure modes:
1769 # difference between $oldmask and $newmask is negative or 0
[707]1770 if ($args{newmask} - $oldmask <= 0) {
1771 $errstr = "Can't split a /$oldmask allocation into /$args{newmask} pieces";
[702]1772 return;
1773 }
1774# # difference between $oldmask and $newmask is > n, for arbitrary n?
1775# if ($newmask - $oldmask > 42) { # because 42
1776# }
1777 # $oldmask > n, for arbitrary n? At least check limits of data type.
1778 if ($block->{isv6}) {
[707]1779 if ($args{newmask} - $oldmask > 128) {
1780 $errstr = "Impossible IPv6 mask length /$args{newmask} requested";
[702]1781 return;
1782 }
1783 } else {
[707]1784 if ($args{newmask} - $oldmask > 32) {
1785 $errstr = "Impossible IPv4 mask length /$args{newmask} requested";
[702]1786 return;
1787 }
1788 }
1789
[707]1790 my @newblocks = $block->split($args{newmask});
[702]1791
1792 local $dbh->{AutoCommit} = 0;
1793 local $dbh->{RaiseError} = 1;
1794
1795 eval {
1796 # line up a list of fields and values. Be nice if there was a handy way to do,
1797 # direct in SQL, something like
1798 # "INSERT INTO foo (f1,f2,f3) VALUES (newf1,(SELECT oldf2,oldf3 FROM foo WHERE baz))"
1799 my @fieldlist = qw(type city description notes circuitid privdata custid swip vrf vlan rdns parent_id master_id);
1800 my $fields_sql = join(',', @fieldlist);
1801 my @vals;
1802 foreach (@fieldlist) {
1803 push @vals, $binfo->{$_};
1804 }
1805 # note the first block in the split for return
[707]1806 push @ret, {nid => $args{id}, nblock => "$newblocks[0]"};
[702]1807
1808 # prepare
1809 my $idsth = $dbh->prepare("SELECT currval('allocations_id_seq')");
[713]1810 my $allocsth = $dbh->prepare("INSERT INTO allocations (cidr, $fields_sql)".
[702]1811 " VALUES (?".',?'x(scalar(@fieldlist)).")");
1812 my $nbsth = $dbh->prepare("DELETE FROM poolips WHERE parent_id = ? AND ip = ?");
[713]1813 my $upd_psth = $dbh->prepare("UPDATE allocations SET parent_id = ? WHERE parent_id = ? AND cidr <<= ?");
1814 my $upd_msth = $dbh->prepare("UPDATE allocations SET master_id = ? WHERE master_id = ? AND cidr <<= ?");
1815 my $fb_psth = $dbh->prepare("UPDATE freeblocks SET parent_id = ? WHERE parent_id = ? AND cidr <<= ?");
1816 my $fb_msth = $dbh->prepare("UPDATE freeblocks SET master_id = ? WHERE master_id = ? AND cidr <<= ?");
1817 my $pool_psth = $dbh->prepare("UPDATE poolips SET parent_id = ? WHERE parent_id = ? AND ip << ?");
1818 my $pool_msth = $dbh->prepare("UPDATE poolips SET master_id = ? WHERE master_id = ? AND ip <<= ?");
[702]1819
1820 # set up update of existing block
[707]1821 $dbh->do("UPDATE allocations SET cidr = ? WHERE id = ?", undef, ("$newblocks[0]", $args{id}) );
[702]1822
[713]1823 # axe the new bcast IP from the smaller pool at the "base" block, if it's a "normal" pool
[702]1824 if ($binfo->{type} =~ /.d/) {
1825 $newblocks[0]--;
[707]1826 $nbsth->execute($args{id}, $newblocks[0]->addr);
[702]1827 }
1828
1829 # Loop over the new blocks that are not the base block
1830 for (my $i = 1; $i <= $#newblocks; $i++) {
[713]1831 # add the new allocation
1832 $allocsth->execute($newblocks[$i], @vals);
[702]1833 # fetch the ID of the entry we just added...
1834 $idsth->execute();
1835 my ($nid) = $idsth->fetchrow_array();
1836 # ... so we can pass back the list of blocks and IDs...
1837 push @ret, {nid => $nid, nblock => "$newblocks[$i]"};
1838 # axe the net, gw, and bcast IPs as necessary when splitting a "normal" pool
1839 if ($binfo->{type} =~ /.d/) {
1840 # net
[707]1841 $nbsth->execute($args{id}, $newblocks[$i]->addr);
[702]1842 $newblocks[$i]++;
1843 # gw
[707]1844 $nbsth->execute($args{id}, $newblocks[$i]->addr);
[702]1845 $newblocks[$i]--;
1846 $newblocks[$i]--;
1847 # bcast
[707]1848 $nbsth->execute($args{id}, $newblocks[$i]->addr);
[702]1849 $newblocks[$i]++;
1850 }
1851
[713]1852 # Reparent allocations, freeblocks, and pool IPs.
1853 $upd_psth->execute($nid, $args{id}, $newblocks[$i]);
1854 $fb_psth->execute($nid, $args{id}, $newblocks[$i]);
1855 $pool_psth->execute($nid, $args{id}, $newblocks[$i]);
1856
1857 # Update master if we've split a master block
1858 if ($binfo->{type} eq 'mm') {
1859 $upd_msth->execute($nid, $args{id}, $newblocks[$i]);
1860 $fb_msth->execute($nid, $args{id}, $newblocks[$i]);
1861 $pool_msth->execute($nid, $args{id}, $newblocks[$i]);
1862 }
1863
1864 } # for (... @newblocks)
1865
[702]1866 $dbh->commit;
1867 };
1868 if ($@) {
1869 $errstr = "Error splitting $binfo->{block}: $@";
1870 $dbh->rollback;
1871 return;
1872 }
[707]1873##fixme: RPC return code?
1874# particularly useful in this case as there may be arbitrary combinations of pass, warn, fail
1875# results from each of the update and add(s), which could get the user to prod dnsadmin to see what exploded
1876 my $foo = _rpc('splitTemplate', cidr => $binfo->{block}, newmask => $args{newmask}, rpcuser => $args{user});
[702]1877
1878 return \@ret;
1879} # end splitBlock()
1880
1881
[705]1882## IPDB::shrinkBlock()
1883# Shrink an allocation to the passed CIDR block
1884# Takes an allocation ID and a new CIDR
1885# Returns an arrayref to a list of hashrefs with the ID and CIDR of the freed block(s)
1886# Refuses to shrink "real netblock" pool types below /30
1887sub shrinkBlock {
1888 my $dbh = shift;
1889 my $id = shift;
1890
1891 # just take the new CIDR spec; this way we can shrink eg .16/28 to .20/30 without extra contortions
1892 my $newblock = new NetAddr::IP shift;
1893
1894 if (!$newblock) {
1895 $errstr = "Can't shrink something that's not a netblock";
1896 return;
1897 }
1898
1899 my $binfo = getBlockData($dbh, $id);
1900 my $pinfo = getBlockData($dbh, $binfo->{parent_id});
1901
1902 if ($binfo->{type} =~ /.d/ && $newblock->masklen > ($newblock->bits+2) ) {
1903 $errstr = "Can't shrink a non-PPP pool smaller than ".($newblock->{isv6} ? '/124' : '/30');
1904 return;
1905 }
1906
1907 my $oldblock = new NetAddr::IP $binfo->{block};
1908
1909 # Don't try to shrink the block outside of itself, Bad Things (probably) Happen.
1910 if (!$oldblock->contains($newblock)) {
1911 $errstr = "Can't shrink an allocation outside of itself";
1912 return;
1913 }
1914
1915 local $dbh->{AutoCommit} = 0;
1916 local $dbh->{RaiseError} = 1;
1917
[713]1918 my $addfbsth = $dbh->prepare("INSERT INTO freeblocks (cidr,city,routed,vrf,parent_id,master_id) VALUES (?,?,?,?,?,?)");
[705]1919 my $idsth = $dbh->prepare("SELECT currval('freeblocks_id_seq')");
1920 my $poolsth = $dbh->prepare("DELETE FROM poolips WHERE parent_id = ? AND ip << ?");
1921 my $netsth = $dbh->prepare("DELETE FROM poolips WHERE parent_id = ? AND ip = ?");
[713]1922 my $allocsth = $dbh->prepare("DELETE FROM allocations WHERE parent_id = ? AND cidr <<= ?");
1923 my $delfbsth = $dbh->prepare("DELETE FROM freeblocks WHERE parent_id = ? AND cidr <<= ?");
[705]1924
[713]1925##fixme: turn this into a public/top-level sub?
1926 sub getchildren {
1927 my $dbh = shift;
1928 my $id = shift;
1929 my $master = shift;
1930 my $retlist = shift; # better than trying to return complex structures recursively. Ow.
1931 my $cidr = shift;
1932
1933 if (!$cidr) {
1934 my $bd = getBlockData($dbh, $id);
1935 $cidr = $bd->{cidr};
1936 }
1937
1938 my $sth = $dbh->prepare(q(
1939 SELECT id,cidr,type FROM allocations
1940 WHERE parent_id = ? AND master_id = ? AND cidr <<= ?
1941 ) );
1942 $sth->execute($id, $master, $cidr);
1943 while (my $row = $sth->fetchrow_hashref) {
1944 push @$retlist, $row;
1945 getchildren($dbh, $row->{id}, $master, $retlist, $cidr);
1946 }
1947 }
1948
[705]1949 my @ret;
1950 eval {
1951 $dbh->do("UPDATE allocations SET cidr = ? WHERE id = ?", undef, $newblock, $id);
1952
1953 # find the netblock(s) that are now free
1954 my @workingblocks = $oldblock->split($newblock->masklen);
1955 my @wb2;
1956 foreach my $newsub (@workingblocks) {
1957 next if $newsub == $newblock;
1958 push @wb2, $newsub;
1959 }
1960 @wb2 = Compact(@wb2);
1961
1962 # set new freeblocks, and clean up any IP pool entries if needed.
1963 foreach my $newfree (@wb2) {
[713]1964 my @clist;
1965 # the block we're munging
1966 push @clist, { id => $id, type => $binfo->{type}, cidr => $binfo->{block} };
1967 getchildren($dbh, $id, $binfo->{master_id}, \@clist, $newfree);
1968
1969 foreach my $goner (@clist) {
1970 $poolsth->execute($goner->{id}, $newfree) if $goner->{type} =~ /.[dp]/;
1971 $allocsth->execute($goner->{id}, $newfree);
1972 $delfbsth->execute($goner->{id}, $newfree);
[705]1973 }
1974
[713]1975 # No pinfo means we're shrinking a master block, which means the free space is returned outside of IPDB.
1976 if ($pinfo) {
1977 $addfbsth->execute($newfree, $pinfo->{city}, 'm', $pinfo->{vrf}, $binfo->{parent_id}, $pinfo->{master_id});
1978 $idsth->execute;
1979 my ($nid) = $idsth->fetchrow_array();
1980 # add to return list
1981 push @ret, {fbid => $nid, newfree => "$newfree", fbparent => $binfo->{parent_id} };
1982 }
1983
1984 } # $newfree (@wb2)
1985
[705]1986 # additional cleanup on net/gw/bcast IPs in pool
1987 if ($binfo->{type} =~ /.d/) {
1988 $netsth->execute($id, $newblock->addr);
1989 $newblock++;
1990 $netsth->execute($id, $newblock->addr);
1991 $newblock--;
1992 $newblock--;
1993 $netsth->execute($id, $newblock->addr);
1994 }
1995
1996 $dbh->commit;
1997 };
1998 if ($@) {
1999 $errstr = "Error splitting $binfo->{block}: $@";
2000 $dbh->rollback;
2001 return;
2002 }
2003
2004 return \@ret;
2005} # end shrinkBlock()
2006
2007
[728]2008## IPDB::mergeBlocks()
2009# Merges two or more adjacent allocations, optionally including relevant
2010# free space, into one allocation.
2011# Takes a "base" block ID and a hash with a mask length and a scope argument to decide
2012# how much existing allocation data to delete.
[733]2013# Returns a list starting with the new merged block, then the merged allocations with comment
[728]2014## Merge scope:
2015# Merge to container
2016# keepall
2017# Move all mergeable allocations into the new block
2018# Move all mergeable free blocks into the new block
2019# mergepeer
2020# Move subs of mergeable containers into the updated primary.
2021# Reparent free blocks in mergeable containers to the updated primary.
2022# Convert assigned IPs from pools into subs.
2023# Convert unused IPs from pools into free blocks.
2024# Convert leaf allocations into free blocks.
2025# clearpeer
2026# Keep subs of the original
2027# Convert assigned IPs from pools into subs.
2028# Convert unused IPs from pools into free blocks.
2029# Convert leaf allocations into free blocks.
2030# clearall
2031# Delete all peers, subs and IPs.
2032# Add single free block for new container.
2033# Merge to pool
2034# keepall
2035# Convert all leaf allocations in the merge range to groups of used IPs
2036# mergepeer
2037# Effectively equal to keepall
2038# clearpeer
2039# Only convert IPs from the original allocation to used IPs
2040# clearall
2041# Delete any existing IPs, and reinitialize the new pool entirely
2042# Merge to leaf type
2043# Remove all subs
2044sub mergeBlocks {
2045 my $dbh = shift;
2046 my $prime = shift; # "base" block ID to use as a starting point
2047 if (!$prime) {
2048 $errstr = "Missing block ID to base merge on";
2049 return;
2050 }
2051
2052 my %args = @_;
2053
2054 # check key arguments.
2055 if (!$args{scope} || $args{scope} !~ /^(keepall|mergepeer|clearpeer|clearall)$/) {
2056 $errstr = "Bad or missing merge scope";
2057 return;
2058 }
2059 if (!$args{newmask} || $args{newmask} !~ /^\d+$/) {
2060 $errstr = "Bad or missing new netmask";
2061 return;
2062 }
2063
2064 # Retrieve info about the base allocation we're munging
2065 my $binfo = getBlockData($dbh, $prime);
2066 my $block = new NetAddr::IP $binfo->{block};
2067 my ($basetype) = ($binfo->{type} =~ /^.(.)$/);
2068 $binfo->{id} = $prime; # preserve for later, just in case
2069
2070 # proposed block
2071 my $newblock = new NetAddr::IP $block->addr."/$args{newmask}";
2072 $newblock = $newblock->network;
2073 $args{newtype} = $binfo->{type} if !$args{newtype};
2074 # if the "primary" block being changed is a master, it must remain one.
[733]2075 # Also force the scope, since otherwise things get ugly.
2076 if ($binfo->{type} eq 'mm') {
2077 $args{newtype} = 'mm';
2078 # don't want to make a peer master a sub of the existing one; too many special cases go explodey,
2079 # but want to retain all other allocations
2080 $args{scope} = 'mergepeer';
2081 }
[728]2082 my ($newcontainerclass) = ($args{newtype} =~ /^(.).$/);
2083
2084 # build an info hash for the "new" allocation we're creating
2085 my $pinfo = {
2086 id => $prime,
2087 block => "$newblock",
2088 type => $args{newtype},
2089 parent_id =>
2090 $binfo->{parent_id},
2091 city => $binfo->{city},
2092 vrf => $binfo->{vrf},
2093 master_id => $binfo->{master_id}
2094 };
2095
2096 my @retlist;
2097
[729]2098 local $dbh->{AutoCommit} = 0;
2099 local $dbh->{RaiseError} = 1;
2100
[728]2101 # Want to do all of the DB stuff in a transaction, to minimize data changing underfoot
2102 eval {
2103
2104 # We always update the "prime" block passed in...
2105 $dbh->do("UPDATE allocations SET cidr = ?, type = ? WHERE id = ?", undef,
2106 ($newblock, $args{newtype}, $prime) )
2107 # ... but only on existing container or pool types. Leaf -> container conversions
2108 # may need a new parent inserted instead.
2109 if $basetype =~ /[cm]/;
2110
2111 # For leaf blocks, we may need to create a new parent as the "primary" instead
2112 # of updating the existing block
2113 my $newparent = $dbh->prepare(q{
2114 INSERT INTO allocations (
2115 cidr, type, city, description, notes, circuitid, createstamp, modifystamp,
2116 privdata, custid, swip, vrf, vlan, rdns, parent_id, master_id
2117 )
2118 SELECT
2119 ? AS cidr, ? AS type, city, description, notes, circuitid, createstamp, modifystamp,
2120 privdata, custid, swip, vrf, vlan, rdns, parent_id, master_id
2121 FROM allocations
2122 WHERE id = ?
2123 });
2124
2125 # Common actions
2126 my $peersth = $dbh->prepare("SELECT cidr,id,type,master_id FROM allocations WHERE parent_id = ? AND cidr <<= ?");
2127 $peersth->execute($binfo->{parent_id}, "$newblock");
2128 my $reparentsth = $dbh->prepare("UPDATE allocations SET parent_id = ?, master_id = ? WHERE id = ?");
2129 my $insfbsth = $dbh->prepare("INSERT INTO freeblocks (cidr,city,routed,vrf,parent_id,master_id) VALUES (?,?,?,?,?,?)");
2130
2131 my $fbreparentsth = $dbh->prepare(q{
2132 UPDATE freeblocks
2133 SET parent_id = ?, master_id = ?, city = ?, routed = ?, vrf = ?
2134 WHERE parent_id = ? AND cidr <<= ?
2135 });
2136
2137 if ($args{newtype} =~ /.[cm]/) {
2138 ## Container
2139
[733]2140 # In case of merging a master block. Somewhat redundant with calls to $fbreparentsth,
2141 # but not *quite* entirely.
[729]2142 my $mfbsth = $dbh->prepare("UPDATE freeblocks SET master_id = ? WHERE master_id = ?");
2143
2144 if ($args{scope} eq 'keepall') {
[730]2145 # Create a new parent with the same info as the passed "primary".
2146 $newparent->execute($newblock, $args{newtype}, $prime);
2147 # and now retrieve the new parent ID
2148 ($prime) = $dbh->selectrow_array("SELECT currval('allocations_id_seq')");
[733]2149 # snag the new parent info for the return list
2150 push @retlist, { block => "$newblock", type => $disp_alloctypes{$args{newtype}}, id => $prime };
[730]2151 # Reparent the free blocks in the new block
2152 $fbreparentsth->execute($prime, $binfo->{master_id}, $binfo->{city}, $newcontainerclass, $binfo->{vrf},
2153 $binfo->{parent_id}, $newblock);
2154 # keep existing allocations (including the original primary), just push them down a level
[733]2155 while (my ($peercidr, $peer_id, $peertype, $m_id) = $peersth->fetchrow_array) {
[730]2156 $reparentsth->execute($prime, $binfo->{master_id}, $peer_id);
2157 # Fix up master_id on free blocks if we're merging a master block
[733]2158 $mfbsth->execute($binfo->{master_id}, $m_id) if $peertype eq 'mm';
2159 # capture block for return
2160 push @retlist, { block => $peercidr, mtype => $disp_alloctypes{$peertype} };
[730]2161 }
2162
[729]2163 } elsif ($args{scope} =~ /^clear/) {
[731]2164 # clearpeer and clearall share a starting point
[733]2165 # snag the new parent info for the return list
2166 push @retlist, { block => "$newblock", type => $disp_alloctypes{$args{newtype}}, id => $prime };
[731]2167 # update the primary allocation info
2168 $dbh->do("UPDATE allocations SET cidr = ?, type = ? WHERE id = ?", undef, ($newblock, $args{newtype}, $prime) );
2169 # Reparent the free blocks in the new block
2170 $fbreparentsth->execute($prime, $binfo->{master_id}, $binfo->{city}, $newcontainerclass, $binfo->{vrf},
2171 $binfo->{parent_id}, $newblock);
2172 # Insert a free block if $prime is a leaf
2173 if ($binfo->{type} =~ /.[enr]/) {
2174 $insfbsth->execute($binfo->{block}, $binfo->{city}, $newcontainerclass, $binfo->{vrf}, $prime,
2175 $binfo->{master_id});
2176 }
[733]2177 # delete the peers.
2178 while (my ($peercidr, $peer_id, $peertype, $m_id) = $peersth->fetchrow_array) {
[731]2179 next if $peer_id == $prime;
2180 # push existing allocations down a level before deleting,
2181 # so that when they're deleted the parent info is correct
2182 $reparentsth->execute($prime, $binfo->{master_id}, $peer_id);
2183 _deleteCascade($dbh, $peer_id);
2184 # insert the freeblock _deleteCascade() (deliberately) didn't when deleting a master block.
2185 # aren't special cases fun?
2186 $dbh->do("INSERT INTO freeblocks (cidr,routed,parent_id,master_id) values (?,?,?,?)",
[733]2187 undef, ($peercidr, 'm', $prime, $prime) ) if $binfo->{type} eq 'mm';
2188 # capture block for return
2189 push @retlist, { block => $peercidr, mtype => $disp_alloctypes{$peertype} };
[731]2190 }
2191 if ($args{scope} eq 'clearall') {
2192 # delete any subs of $prime as well
2193 my $substh = $dbh->prepare("SELECT cidr,id FROM allocations WHERE parent_id = ?");
2194 $substh->execute($prime);
2195 while (my ($scidr, $s_id) = $substh->fetchrow_array) {
2196 _deleteCascade($dbh, $s_id);
2197 }
2198 } else {
2199 # clearpeer
2200 if ($basetype =~ /[dp]/) {
2201 # Convert active IP pool entries to allocations if the original was an IP pool
2202 _poolToAllocations($dbh, $binfo, $pinfo, newtype => $poolmap{$binfo->{type}});
2203 }
2204 } # clearall or clearpeer
2205
[729]2206 } elsif ($args{scope} eq 'mergepeer') { # should this just be an else?
[732]2207 # Default case. Merge "peer" blocks, but keep all suballocations
[733]2208 # snag the new parent info for the return list
2209 push @retlist, {block => "$newblock", type => $disp_alloctypes{$args{newtype}}, id => $prime};
[732]2210 my $substh = $dbh->prepare("UPDATE allocations SET parent_id = ? WHERE parent_id = ?");
2211 my $delsth = $dbh->prepare("DELETE FROM allocations WHERE id = ?");
2212 # Reparent freeblocks in parent
2213 $fbreparentsth->execute($prime, $binfo->{master_id}, $binfo->{city}, $newcontainerclass, $binfo->{vrf},
2214 $binfo->{parent_id}, $newblock);
2215 # Loop over "peer" allocations to be merged
2216 while (my ($peercidr, $peer_id, $peertype, $m_id) = $peersth->fetchrow_array) {
2217 # Snag existing peer data since we may need it
2218 my $peerfull = getBlockData($dbh, $peer_id);
2219 # Reparent free blocks from existing containers
2220 $fbreparentsth->execute($prime, $binfo->{master_id}, $binfo->{city}, $newcontainerclass,
2221 $binfo->{vrf}, $peer_id, $newblock);
2222 # Reparent any subblocks from existing containers
2223 $substh->execute($prime, $peer_id);
2224 # Delete the old container
2225 $delsth->execute($peer_id) unless $peer_id == $prime;
2226 # Add new freeblocks for merged leaf blocks
2227 $insfbsth->execute($peercidr, $binfo->{city}, $newcontainerclass, $binfo->{vrf}, $binfo->{id},
2228 $binfo->{master_id}) if $peertype =~ /.[enr]/;
2229 # Convert pool IPs into allocations or aggregated free blocks
[733]2230 _poolToAllocations($dbh, $peerfull, $pinfo, newparent => $prime) if $peertype =~ /.[dp]/;
[732]2231 # Fix up master_id on free blocks if we're merging a master block
2232 $mfbsth->execute($binfo->{master_id}, $m_id) if $peertype eq 'mm';
[733]2233 # capture block for return
2234 push @retlist, { block => $peercidr, mtype => $disp_alloctypes{$peertype} };
[732]2235 } # merge peers
2236 # update the primary allocation info. Do this last so we don't stomp extra data-retrieval in the loop above
2237 $dbh->do("UPDATE allocations SET cidr = ?, type = ? WHERE id = ?", undef, ($newblock, $args{newtype}, $prime) );
2238
[729]2239 } # scope
2240
2241 # Clean up free blocks
2242 _compactFree($dbh, $prime);
2243
[728]2244 } elsif ($args{newtype} =~ /.[dp]/) {
2245 ## Pool
2246
2247 } elsif ($args{newtype} =~ /.[enr]/) {
2248 ## Leaf
2249
2250 } # new type if()
2251
2252 $dbh->commit;
2253 };
2254 if ($@) {
2255 my $msg = $@;
2256 $errstr = $msg;
2257 $dbh->rollback;
2258 return ('FAIL',$msg);
2259 }
2260
2261 return \@retlist;
2262
2263} # end mergeBlocks()
2264
2265
[93]2266## IPDB::deleteBlock()
2267# Removes an allocation from the database, including deleting IPs
2268# from poolips and recombining entries in freeblocks if possible
2269# Also handles "deleting" a static IP allocation, and removal of a master
[558]2270# Requires a database handle, the block to delete, the routing depth (if applicable),
[590]2271# the VRF ID, and a flag to indicate whether to delete associated forward DNS entries
2272# as well as the reverse entry
[93]2273sub deleteBlock {
[638]2274 my ($dbh,$id,$basetype,$delfwd,$user) = @_;
[93]2275
[638]2276 # Collect info about the block we're going to delete
2277 my $binfo = getBlockData($dbh, $id, $basetype);
2278 my $cidr = new NetAddr::IP $binfo->{block};
2279
[558]2280# For possible auto-VRF-ignoring (since public IPs shouldn't usually be present in more than one VRF)
2281# is_rfc1918 requires NetAddr::IP >= 4.059
2282# rather than doing this over and over and over.....
2283 my $tmpnum = $cidr->numeric;
2284# 192.168.0.0/16 -> 192.168.255.255 => 3232235520 -> 3232301055
2285# 172.16.0.0/12 -> 172.31.255.255 => 2886729728 -> 2887778303
2286# 10.0.0.0/8 -> 10.255.255.255 => 167772160 -> 184549375
2287 my $isprivnet = (3232235520 <= $tmpnum && $tmpnum <= 3232301055) ||
2288 (2886729728 <= $tmpnum && $tmpnum <= 2887778303) ||
2289 (167772160 <= $tmpnum && $tmpnum <= 184549375);
2290
[93]2291 my $sth;
2292
[349]2293 # Magic variables used for odd allocation cases.
2294 my $container;
2295 my $con_type;
2296
[558]2297
2298 # temporarily forced null, until a sane UI for VRF tracking can be found.
[638]2299# $vrf = '';# if !$vrf; # as with SQL, the null value is not equal to ''. *sigh*
[558]2300
[93]2301 # To contain the error message, if any.
[558]2302 my $msg = "Unknown error deallocating $binfo->{type} $cidr";
2303 my $goback; # to put the parent in so we can link back where the deallocate started
2304
[93]2305 # Enable transactions and exception-on-errors... but only for this sub
2306 local $dbh->{AutoCommit} = 0;
2307 local $dbh->{RaiseError} = 1;
2308
[558]2309 if ($binfo->{type} =~ /^.i$/) {
[638]2310 # First case. The "block" is a static IP
2311 # Note that we still need some additional code in the odd case
2312 # of a netblock-aligned contiguous group of static IPs
[93]2313
2314 eval {
[558]2315 $msg = "Unable to deallocate $disp_alloctypes{$binfo->{type}} $cidr";
[638]2316 my $pinfo = getBlockData($dbh, $binfo->{parent_id}, 'b');
[558]2317##fixme: VRF and rdepth
[638]2318 $dbh->do("UPDATE poolips SET custid = ?, available = 'y',".
2319 "city = (SELECT city FROM allocations WHERE id = ?),".
2320 "description = '', notes = '', circuitid = '', vrf = ? WHERE id = ?", undef,
2321 ($pinfo->{custid}, $binfo->{parent_id}, $pinfo->{vrf}, $id) );
[93]2322 $dbh->commit;
2323 };
2324 if ($@) {
[558]2325 $msg .= ": $@";
[93]2326 eval { $dbh->rollback; };
2327 return ('FAIL',$msg);
2328 } else {
[590]2329##fixme: RPC return code?
[638]2330 _rpc('delByCIDR', cidr => "$cidr", user => $user, delforward => $delfwd, rpcuser => $user);
[93]2331 return ('OK',"OK");
2332 }
2333
[558]2334 } elsif ($binfo->{type} eq 'mm') { # end alloctype =~ /.i/
[638]2335 # Second case. The block is a full master block
[93]2336
[558]2337##fixme: VRF limit
[93]2338 $msg = "Unable to delete master block $cidr";
2339 eval {
[638]2340 $dbh->do("DELETE FROM allocations WHERE cidr <<= ? AND master_id = ?", undef, ($cidr, $binfo->{master_id}) );
2341 $dbh->do("DELETE FROM freeblocks WHERE cidr <<= ? AND master_id = ?", undef, ($cidr, $binfo->{master_id}) );
[93]2342 $dbh->commit;
2343 };
2344 if ($@) {
[558]2345 $msg .= ": $@";
[93]2346 eval { $dbh->rollback; };
2347 return ('FAIL', $msg);
[591]2348 }
2349
2350 # Have to handle potentially split reverse zones. Assume they *are* split,
2351 # since if we added them here, they would have been added split.
2352# allow splitting reverse zones to be disabled, maybe, someday
2353#if ($splitrevzones && !$cidr->{isv6}) {
2354 my @zonelist;
2355 if (1 && !$cidr->{isv6}) {
2356 my $splitpoint = ($cidr->masklen <= 16 ? 16 : 24); # hack pthui
2357 @zonelist = $cidr->split($splitpoint);
[93]2358 } else {
[591]2359 @zonelist = ($cidr);
[93]2360 }
[591]2361 my @fails;
2362 foreach my $subzone (@zonelist) {
[638]2363 if ($rpc_url && !_rpc('delZone', zone => "$subzone", revrec => 'y', rpcuser => $user, delforward => $delfwd) ) {
[591]2364 push @fails, ("$subzone" => $errstr);
2365 }
2366 }
2367 if (@fails) {
2368 return ('WARN',"Warning(s) deleting $cidr from reverse DNS:\n".join("\n", @fails));
2369 }
2370 return ('OK','OK');
[93]2371
2372 } else { # end alloctype master block case
2373
2374 ## This is a big block; but it HAS to be done in a chunk. Any removal
2375 ## of a netblock allocation may result in a larger chunk of free
2376 ## contiguous IP space - which may in turn be combined into a single
2377 ## netblock rather than a number of smaller netblocks.
2378
[558]2379 my $retcode = 'OK';
[638]2380 my ($ptype,$pcity,$ppatt,$p_id);
[558]2381
[93]2382 eval {
2383
[558]2384##fixme: add recursive flag to allow "YES DAMMIT DELETE ALL EVARYTHING!!1!!" without
2385# explicitly deleting any suballocations of the block to be deleted.
[93]2386
[638]2387 # get parent info of the block we're deleting
2388 my $pinfo = getBlockData($dbh, $binfo->{parent_id});
2389 $ptype = $pinfo->{type};
2390 $pcity = $pinfo->{city};
2391 $ppatt = $pinfo->{rdns};
2392 $p_id = $binfo->{parent_id};
[93]2393
[558]2394 # Delete the block
[638]2395 $dbh->do("DELETE FROM allocations WHERE id = ?", undef, ($id) );
[349]2396
[558]2397 # munge the parent type a little
[638]2398 $ptype = (split //, $ptype)[1];
[93]2399
[558]2400##fixme: you can't... CAN NOT.... assign the same public IP to multiple things.
2401# 'Net don't work like that, homey. Restrict VRF-uniqueness to private IPs?
2402# -> $isprivnet flag from start of sub
[93]2403
[558]2404 # check to see if any container allocations could be the "true" parent
[638]2405 my ($tparent,$tpar_id,$trtype,$tcity);
2406 $tpar_id = 0;
[404]2407
[638]2408##fixme: this is far simpler in the strict VRF case; we "know" that any allocation
2409# contained by a container is a part of the same allocation tree when the VRF fields are equal.
[558]2410
[638]2411# logic:
2412# For each possible container of $cidr
2413# note the parent id
2414# walk the chain up the parents
2415# if we intersect $cidr's current parent, break
2416# if we've intersected $cidr's current parent
2417# set some variables to track that block
2418# break
[558]2419
[638]2420# Set up part of "is it in the middle of a pool?" check
2421 my $wuzpool = $dbh->selectrow_hashref("SELECT cidr,parent_id,type,city,custid,id FROM allocations ".
2422 "WHERE (type LIKE '_d' OR type LIKE '_p') AND cidr >> ? AND master_id = ?", { Slice => {} },
2423 ($cidr, $binfo->{master_id}) );
[558]2424
[638]2425##fixme?
2426# edge cases not handled, or handled badly:
2427# -> $cidr managed to get to be the entirety of an IP pool
[558]2428
[638]2429 if ($wuzpool && $wuzpool->{id} != $id) {
2430 # we have legacy goo to be purified
2431 # going to ignore nested pools; not possible to create them via API and no current legacy data includes any.
2432
2433 # for convenience
2434 my $poolid = $wuzpool->{id};
2435 my $pool = $wuzpool->{cidr};
2436 my $poolcity = $wuzpool->{city};
2437 my $pooltype = $wuzpool->{type};
2438 my $poolcustid = $wuzpool->{custid};
2439
2440 $retcode = 'WARNPOOL';
2441 $goback = "$poolid,$pool";
2442 # We've already deleted the block, now we have to stuff its IPs into the pool.
2443 $pooltype =~ s/[dp]$/i/; # change type to static IP
2444 my $sth2 = $dbh->prepare("INSERT INTO poolips (ip,city,type,custid,parent_id) VALUES ".
2445 "(?,'$poolcity','$pooltype','$poolcustid',$poolid)");
[655]2446
[429]2447##fixme: need to not insert net, gateway, and bcast on "real netblock" pools (DHCPish)
[638]2448 # don't insert .0
2449 $sth2->execute($cidr->addr) unless $cidr->addr =~ m|\.0$|;
[655]2450 $cidr++;
2451 my $bcast = $cidr->broadcast;
2452 while ($cidr != $bcast) {
2453 $sth2->execute($cidr->addr);
2454 $cidr++;
[638]2455 }
2456 # don't insert .255
2457 $sth2->execute($cidr->addr) unless $cidr->addr =~ m|\.255$|;
[655]2458
2459# Weirdness Happens. $cidr goes read-only somewhere (this is a thing?!?),
2460# causing ->split, ->hostenum, and related methods to explode. O_o
2461# foreach my $ip ($cidr->hostenum) {
2462# $sth2->execute($ip);
2463# }
2464
[638]2465 }
[93]2466
[638]2467## important!
2468# ... or IS IT?
2469# we may have undef'ed $wuzpool above, if the allocation tree $cidr is in doesn't intersect the pool we found
2470#if (!$wuzpool) {
2471
2472 else {
2473
[655]2474# Edge case: Block is the same size as more than one parent level. Should be rare.
2475# - mainly master + first routing. Sorting on parent_id hides the problem pretty well,
2476# but it's likely still possible to fail in particularly well-mangled databases.
2477# The ultimate fix for this may be to resurrect the "routing depth" atrocity. :/
[638]2478 # Get all possible (and probably a number of impossible) containers for $cidr
2479 $sth = $dbh->prepare("SELECT cidr,parent_id,type,city,id FROM allocations ".
2480 "WHERE (type LIKE '_m' OR type LIKE '_c') AND cidr >>= ? AND master_id = ? ".
[655]2481 "ORDER BY masklen(cidr) DESC,parent_id DESC");
[638]2482 $sth->execute($cidr, $binfo->{master_id});
2483
2484 # Quickly get certain fields (simpler than getBlockData()
2485 my $sth2 = $dbh->prepare("SELECT cidr,parent_id,type,city FROM allocations ".
2486 "WHERE (type LIKE '_m' OR type LIKE '_c') AND id = ? AND master_id = ?");
2487
2488 # For each possible container of $cidr...
2489 while (my @data = $sth->fetchrow_array) {
2490 my $i = 0;
2491 # Save some state and set a start point - parent ID of container we're checking
2492 $tparent = $data[0];
2493 my $ppid = $data[1];
2494 $trtype = $data[2];
2495 $tcity = $data[3];
2496 $tpar_id = $data[4];
2497 last if $data[4] == $binfo->{parent_id}; # Preemptively break if we're already in the right place
2498 last if $ppid == $binfo->{parent_id}; # ... or if the parent of the container is the block's parent
2499 while (1) {
2500 # Retrieve bits on that parent ID
2501 $sth2->execute($ppid, $binfo->{master_id});
2502 my @container = $sth2->fetchrow_array;
2503 $ppid = $container[1];
2504 last if $container[1] == 0; # Break if we've hit a master block
2505 last if $ppid == $binfo->{parent_id}; # Break if we've reached the block $cidr is currently in
2506 }
2507 last if $ppid == $binfo->{parent_id};
2508 }
2509
2510 # found an alternate parent; reset some parent-info bits
2511 if ($tpar_id != $binfo->{parent_id}) {
2512 $ptype = (split //, $trtype)[1];
2513 $pcity = $tcity;
2514 $retcode = 'WARNMERGE'; # may be redundant
2515 $p_id = $tpar_id;
2516 }
2517
2518 $goback = "$p_id,$tparent"; # breadcrumb, currently only used in case of live-parent-is-not-true-parent
2519
2520 # Special case - delete pool IPs
2521 if ($binfo->{type} =~ /^.[pd]$/) {
[655]2522 # We have to delete the IPs from the pool listing.
2523##fixme: rdepth? vrf?
[638]2524 $dbh->do("DELETE FROM poolips WHERE parent_id = ?", undef, ($id) );
2525 }
2526
2527 $pinfo = getBlockData($dbh, $p_id);
2528
[558]2529 # If the block wasn't legacy goo embedded in a static pool, we check the
2530 # freeblocks in the identified parent to see if we can combine any of them.
[93]2531
[559]2532 # if the block to be deleted is a container, move its freeblock(s) up a level, and reset their parenting info
2533 if ($binfo->{type} =~ /^.[mc]/) {
2534 # move the freeblocks into the parent
2535 # we don't insert a new freeblock because there could be a live reparented sub.
[638]2536 $dbh->do("UPDATE freeblocks SET parent_id = ?, routed = ?, city = ? WHERE parent_id = ?", undef,
2537 ($p_id, $ptype, $pcity, $id) );
[559]2538 } else {
2539 # ... otherwise, add the freeblock
[638]2540 $dbh->do("INSERT INTO freeblocks (cidr, city, routed, parent_id, master_id) VALUES (?,?,?,?,?)", undef,
2541 ($cidr, $pcity, $ptype, $p_id, $binfo->{master_id}) );
[559]2542 }
2543
[715]2544 # Walk the free blocks in the parent and reduce them to the minimal set of CIDR ranges necessary
2545 _compactFree($dbh, $p_id);
[428]2546
2547 } # done returning IPs to the appropriate place
[404]2548
[93]2549 # If we got here, we've succeeded. Whew!
2550 $dbh->commit;
2551 }; # end eval
2552 if ($@) {
[558]2553 $msg .= ": $@";
[93]2554 eval { $dbh->rollback; };
2555 return ('FAIL', $msg);
2556 } else {
[590]2557##fixme: RPC return code?
[638]2558 _rpc('delByCIDR', cidr => "$cidr", rpcuser => $user, delforward => $delfwd, delsubs => 'y', parpatt => $ppatt);
[558]2559 return ($retcode, $goback);
[93]2560 }
2561
2562 } # end alloctype != netblock
2563
2564} # end deleteBlock()
2565
2566
[370]2567## IPDB::getBlockData()
[557]2568# Get CIDR or IP, custid, type, city, circuit ID, description, notes, modification time,
2569# private/restricted data, for a CIDR block or pool IP
2570# Also returns SWIP status flag for CIDR blocks or pool netblock for IPs
[636]2571# Takes the block ID or IP to look up and an optional flag to indicate a pool IP lookup
2572# instead of a netblock.
[557]2573# Returns a hashref to the block data
[370]2574sub getBlockData {
2575 my $dbh = shift;
[636]2576 my $id = shift;
2577 my $type = shift || 'b'; # default to netblock for lazy callers
[370]2578
[636]2579 # netblocks are in the allocations table; pool IPs are in the poolips table.
2580 # If we try to look up a CIDR in an integer field we should just get back nothing.
2581 my ($btype) = $dbh->selectrow_array("SELECT type FROM allocations WHERE id=?", undef, ($id) );
[534]2582
[692]2583 # Note city, vrf, parent_id and master_id removed due to JOIN uncertainty for block allocations
2584 my $commonfields = q(custid, type, circuitid, description, notes, modifystamp AS lastmod,
2585 privdata, vlan, rdns);
2586
[636]2587 if ($type eq 'i') {
[692]2588 my $binfo = $dbh->selectrow_hashref(qq(
[726]2589 SELECT id, ip AS block, city, vrf, parent_id, master_id, $commonfields
[692]2590 FROM poolips WHERE id = ?
2591 ), undef, ($id) );
[557]2592 return $binfo;
2593 } else {
[692]2594 my $binfo = $dbh->selectrow_hashref(qq(
[726]2595 SELECT a.id, a.cidr AS block, a.city, a.vrf, a.parent_id, a.master_id, swip, $commonfields,
[692]2596 f.cidr AS reserve, f.id as reserve_id
2597 FROM allocations a LEFT JOIN freeblocks f ON a.id=f.reserve_for
2598 WHERE a.id = ?
2599 ), undef, ($id) );
[557]2600 return $binfo;
[534]2601 }
[370]2602} # end getBlockData()
2603
2604
[585]2605## IPDB::getBlockRDNS()
2606# Gets reverse DNS pattern for a block or IP. Note that this will also
2607# retrieve any default pattern following the parent chain up, and check via
2608# RPC (if available) to see what the narrowest pattern for the requested block is
2609# Returns the current pattern for the block or IP.
2610sub getBlockRDNS {
2611 my $dbh = shift;
2612 my %args = @_;
2613
[637]2614 $args{type} = 'b' if !$args{type};
[675]2615 my $cached = 1;
[585]2616
[637]2617 # snag entry from database
2618 my ($rdns,$rfrom,$pid);
2619 if ($args{type} =~ /.i/) {
2620 ($rdns, $rfrom, $pid) = $dbh->selectrow_array("SELECT rdns,ip,parent_id FROM poolips WHERE id = ?",
2621 undef, ($args{id}) );
2622 } else {
2623 ($rdns, $rfrom, $pid) = $dbh->selectrow_array("SELECT rdns,cidr,parent_id FROM allocations WHERE id = ?",
2624 undef, ($args{id}) );
2625 }
[585]2626
[637]2627 # Can't see a way this could end up empty, for any case I care about. If the caller
2628 # doesn't know an allocation ID to request, then they don't know anything else anyway.
2629 my $selfblock = $rfrom;
[585]2630
[637]2631 my $type;
2632 while (!$rdns && $pid) {
2633 ($rdns, $rfrom, $pid, $type) = $dbh->selectrow_array(
2634 "SELECT rdns,cidr,parent_id,type FROM allocations WHERE id = ?",
2635 undef, ($pid) );
2636 last if $type eq 'mm'; # break loops in unfortunate legacy data
2637 }
2638
2639 # use the actual allocation to check against the DNS utility; we don't want
2640 # to always go chasing up the chain to the master... which may (usually won't)
2641 # be present directly in DNS anyway
2642 my $cidr = new NetAddr::IP $selfblock;
2643
[585]2644 if ($rpc_url) {
2645 # Use the first /16 or /24, rather than dithering over which sub-/14 /16
2646 # or sub-/19 /24 to retrieve - it's the least-wrong way to do things.
2647
[586]2648 my ($rpcblock) = ($cidr->masklen <= 24 ? $cidr->split( ($cidr->masklen <= 16 ? 16 : 24) ) : $cidr);
[585]2649 my %rpcargs = (
2650 rpcuser => $args{user},
2651 group => $revgroup, # not sure how this could sanely be exposed, tbh...
2652 cidr => "$rpcblock",
2653 );
2654
[637]2655 my $remote_rdns = _rpc('getRevPattern', %rpcargs);
2656 $rdns = $remote_rdns if $remote_rdns;
[675]2657 $cached = 0;
[585]2658 }
2659
2660 # hmm. do we care about where it actually came from?
[675]2661 return $rdns, $cached;
[585]2662} # end getBlockRDNS()
2663
2664
[675]2665## IPDB::getRDNSbyIP()
2666# Get individual reverse entries for the IP or CIDR IP range passed. Sort of looking the
2667# opposite direction down the netblock tree compared to getBlockRDNS() above.
2668sub getRDNSbyIP {
2669 my $dbh = shift;
2670 my %args = @_; # We want to accept a variety of call types
2671
2672 # key arguments: allocation ID, type
2673 unless ($args{id} || $args{type}) {
2674 $errstr = 'Missing allocation ID or type';
2675 return;
2676 }
2677
2678 my @ret = ();
2679 # special case: single IP. Check if it's an allocation or in a pool, then do the RPC call for fresh data.
2680 if ($args{type} =~ /^.i$/) {
2681 my ($ip, $localrev) = $dbh->selectrow_array("SELECT ip, rdns FROM poolips WHERE id = ?", undef, ($args{id}) );
2682 push @ret, { 'r_ip' => $ip, 'iphost' => $localrev };
2683 } else {
2684 if ($rpc_url) {
2685 my %rpcargs = (
2686 rpcuser => $args{user},
2687 group => $revgroup, # not sure how this could sanely be exposed, tbh...
2688 cidr => $args{range},
2689 );
2690
2691 my $remote_rdns = _rpc('getRevSet', %rpcargs);
2692 return $remote_rdns;
2693# $rdns = $remote_rdns if $remote_rdns;
2694# $cached = 0;
2695 }
2696 }
2697 return \@ret;
2698} # end getRDNSbyIP()
2699
2700
[519]2701## IPDB::getNodeList()
2702# Gets a list of node ID+name pairs as an arrayref to a list of hashrefs
2703sub getNodeList {
2704 my $dbh = shift;
2705
2706 my $ret = $dbh->selectall_arrayref("SELECT node_id, node_name FROM nodes ORDER BY node_type,node_id",
2707 { Slice => {} });
2708 return $ret;
2709} # end getNodeList()
2710
2711
[530]2712## IPDB::getNodeName()
2713# Get node name from the ID
2714sub getNodeName {
2715 my $dbh = shift;
2716 my $nid = shift;
2717
2718 my ($nname) = $dbh->selectrow_array("SELECT node_name FROM nodes WHERE node_id = ?", undef, ($nid) );
2719 return $nname;
2720} # end getNodeName()
2721
2722
2723## IPDB::getNodeInfo()
2724# Get node name and ID associated with a block
2725sub getNodeInfo {
2726 my $dbh = shift;
2727 my $block = shift;
2728
2729 my ($nid, $nname) = $dbh->selectrow_array("SELECT nodes.node_id,node_name FROM nodes INNER JOIN noderef".
2730 " ON nodes.node_id=noderef.node_id WHERE noderef.block = ?", undef, ($block) );
2731 return ($nid, $nname);
2732} # end getNodeInfo()
2733
2734
[77]2735## IPDB::mailNotify()
[66]2736# Sends notification mail to recipients regarding an IPDB operation
[416]2737sub mailNotify {
2738 my $dbh = shift;
2739 my ($action,$subj,$message) = @_;
[66]2740
[462]2741 return if $smtphost eq 'smtp.example.com'; # do nothing if still using default SMTP host.
2742
[422]2743##fixme: need to redesign the breakdown/processing for $action for proper handling of all cases
2744
[416]2745# split action into parts for fiddlement. nb: there are almost certainly better ways to do this.
[422]2746 my @actionbits = split //, $action;
[416]2747
2748 # want to notify anyone who has specifically requested notify on *this* type ($action as passed),
2749 # on "all static IP types" or "all pool types" (and other last-char-in-type groupings), on eg "all DSL types",
2750 # and "all events with this action"
2751 my @actionsets = ($action);
2752##fixme: ick, eww. really gotta find a better way to handle this...
2753 push @actionsets, ($actionbits[0].'.'.$actionbits[2],
2754 $actionbits[0].$actionbits[1].'.', $actionbits[0].'a') if $action =~ /^.{3}$/;
2755
2756 my $mailer = Net::SMTP->new($smtphost, Hello => "ipdb.$domain");
2757
2758 # get recip list from db
2759 my $sth = $dbh->prepare("SELECT reciplist FROM notify WHERE action=?");
2760
[443]2761 my %reciplist;
[416]2762 foreach (@actionsets) {
[426]2763 $sth->execute($_);
[416]2764##fixme - need to handle db errors
2765 my ($recipsub) = $sth->fetchrow_array;
2766 next if !$recipsub;
2767 foreach (split(/,/, $recipsub)) {
[443]2768 $reciplist{$_}++;
[416]2769 }
2770 }
2771
[443]2772 return if !%reciplist;
[420]2773
[443]2774 foreach my $recip (keys %reciplist) {
[681]2775 $mailer->mail($smtpsender);
[416]2776 $mailer->to($recip);
[681]2777 $mailer->data("From: \"$org_name IP Database\" <$smtpsender>\n",
[135]2778 "To: $recip\n",
[69]2779 "Date: ".strftime("%a, %d %b %Y %H:%M:%S %z",localtime)."\n",
2780 "Subject: {IPDB} $subj\n",
2781 "X-Mailer: IPDB Notify v".sprintf("%.1d",$IPDB::VERSION)."\n",
[417]2782 "Organization: $org_name\n",
[69]2783 "\n$message\n");
[416]2784 }
[66]2785 $mailer->quit;
2786}
2787
[4]2788# Indicates module loaded OK. Required by Perl.
27891;
Note: See TracBrowser for help on using the repository browser.