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

Last change on this file since 895 was 893, checked in by Kris Deugau, 8 years ago

/trunk

Finally review and refresh copyright years again

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