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

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

/trunk

Remove minor debugging warning that snuck through in r832

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