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

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

/trunk

Fix subtle bug in splitBlock() - if there was a free block at the beginning
of a container block to be split, that itself would need to be split, it
would end up deleted instead. This affected eg a /24 with .128/25 assigned,
and .0/25 free split into /26 or smaller (the .0 free block would go
missing), or a /24 with two /25 containers with no further allocations split
into /26 or smaller (both the resulting .0 and .128 free blocks would go
missing).

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