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

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

/trunk

Fix subtle bug in _toPool() that caused generated pool IPs to be inserted
without the correct master ID, which broke a surprising number of things.

  • Property svn:keywords set to Date Rev Author
File size: 133.9 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-05-13 17:36:59 +0000 (Fri, 13 May 2016) $
6# SVN revision $Rev: 875 $
7# Last update by $Author: kdeugau $
8###
9# Copyright (C) 2004-2010 - 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") 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") 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 # set up update of 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 my $delfblist = $dbh->selectall_arrayref(q{
2323 SELECT cidr,parent_id,id FROM freeblocks
2324 WHERE id in (
2325 }.join(',', keys %fbdel).")", {Slice=>{}} );
2326 $dbh->do("DELETE FROM freeblocks WHERE id IN (".join(',', keys %fbdel).")") if %fbdel;
2327 }
2328
2329 } # foreach @processlist
2330
2331 $dbh->commit;
2332 };
2333 if ($@) {
2334 $errstr = "Error splitting $binfo->{block}: $@";
2335 $dbh->rollback;
2336 return;
2337 }
2338
2339 # Only try to update rDNS when the original block is flagged as "rDNS available"
2340 _rpc('splitTemplate', cidr => $binfo->{block}, newmask => $args{newmask}, rpcuser => $args{user},
2341 location => $binfo->{location})
2342 if ($binfo->{revavail} || $binfo->{revpartial});
2343
2344 return \@ret;
2345} # end splitBlock()
2346
2347
2348## IPDB::shrinkBlock()
2349# Shrink an allocation to the passed CIDR block
2350# Takes an allocation ID and a new CIDR
2351# Returns an arrayref to a list of hashrefs with the ID and CIDR of the freed block(s)
2352# Refuses to shrink "real netblock" pool types below /30
2353sub shrinkBlock {
2354 my $dbh = shift;
2355 my $id = shift;
2356
2357 # just take the new CIDR spec; this way we can shrink eg .16/28 to .20/30 without extra contortions
2358 my $newblock = new NetAddr::IP shift;
2359
2360 my $user = shift;
2361
2362 if (!$newblock) {
2363 $errstr = "Can't shrink something that's not a netblock";
2364 return;
2365 }
2366
2367 my $binfo = getBlockData($dbh, $id);
2368 my $pinfo = getBlockData($dbh, $binfo->{parent_id});
2369
2370 if ($binfo->{type} =~ /.d/ && $newblock->masklen > ($newblock->bits+2) ) {
2371 $errstr = "Can't shrink a non-PPP pool smaller than ".($newblock->{isv6} ? '/124' : '/30');
2372 return;
2373 }
2374
2375 my $oldblock = new NetAddr::IP $binfo->{block};
2376
2377 # Don't try to shrink the block outside of itself, Bad Things (probably) Happen.
2378 if (!$oldblock->contains($newblock)) {
2379 $errstr = "Can't shrink an allocation outside of itself";
2380 return;
2381 }
2382
2383 local $dbh->{AutoCommit} = 0;
2384 local $dbh->{RaiseError} = 1;
2385
2386 my $addfbsth = $dbh->prepare("INSERT INTO freeblocks (cidr,city,routed,vrf,parent_id,master_id) VALUES (?,?,?,?,?,?)");
2387 my $idsth = $dbh->prepare("SELECT currval('freeblocks_id_seq')");
2388 my $poolsth = $dbh->prepare("DELETE FROM poolips WHERE parent_id = ? AND ip << ?");
2389 my $netsth = $dbh->prepare("DELETE FROM poolips WHERE parent_id = ? AND ip = ?");
2390 my $allocsth = $dbh->prepare("DELETE FROM allocations WHERE parent_id = ? AND cidr <<= ?");
2391 my $delfbsth = $dbh->prepare("DELETE FROM freeblocks WHERE parent_id = ? AND cidr <<= ?");
2392
2393 my @ret;
2394 my @newfreelist;
2395 eval {
2396 $dbh->do("UPDATE allocations SET cidr = ? WHERE id = ?", undef, $newblock, $id);
2397
2398 # find the netblock(s) that are now free
2399 my @workingblocks = $oldblock->split($newblock->masklen);
2400 foreach my $newsub (@workingblocks) {
2401 next if $newsub == $newblock;
2402 push @newfreelist, $newsub;
2403 }
2404 @newfreelist = Compact(@newfreelist);
2405
2406 # set new freeblocks, and clean up any IP pool entries if needed.
2407 foreach my $newfree (@newfreelist) {
2408 my @clist;
2409 # the block we're munging
2410 push @clist, { id => $id, type => $binfo->{type}, cidr => $binfo->{block} };
2411 _getChildren($dbh, $id, $binfo->{master_id}, \@clist, $newfree);
2412
2413 foreach my $goner (@clist) {
2414 $poolsth->execute($goner->{id}, $newfree) if $goner->{type} =~ /.[dp]/;
2415 $allocsth->execute($goner->{id}, $newfree);
2416 $delfbsth->execute($goner->{id}, $newfree);
2417 }
2418
2419 # No pinfo means we're shrinking a master block, which means the free space is returned outside of IPDB.
2420 if ($pinfo) {
2421 $addfbsth->execute($newfree, $pinfo->{city}, 'm', $pinfo->{vrf}, $binfo->{parent_id}, $pinfo->{master_id});
2422 $idsth->execute;
2423 my ($nid) = $idsth->fetchrow_array();
2424 # add to return list
2425 push @ret, {fbid => $nid, newfree => "$newfree", fbparent => $binfo->{parent_id} };
2426 }
2427
2428 } # $newfree (@newfreelist)
2429
2430 # additional cleanup on net/gw/bcast IPs in pool
2431 if ($binfo->{type} =~ /.d/) {
2432 $netsth->execute($id, $newblock->addr);
2433 $newblock++;
2434 $netsth->execute($id, $newblock->addr);
2435 $newblock--;
2436 $newblock--;
2437 $netsth->execute($id, $newblock->addr);
2438 }
2439
2440 $dbh->commit;
2441 };
2442 if ($@) {
2443 $errstr = "Error splitting $binfo->{block}: $@";
2444 $dbh->rollback;
2445 return;
2446 }
2447
2448 # Only try to update rDNS when the original block is flagged as "rDNS available"
2449 _rpc('resizeTemplate', oldcidr => $binfo->{block}, newcidr => $newblock->network, rpcuser => $user,
2450 location => $binfo->{location})
2451 if ($binfo->{revavail} || $binfo->{revpartial});
2452
2453 return \@ret;
2454} # end shrinkBlock()
2455
2456
2457## IPDB::mergeBlocks()
2458# Merges two or more adjacent allocations, optionally including relevant
2459# free space, into one allocation.
2460# Takes a "base" block ID and a hash with a mask length and a scope argument to decide
2461# how much existing allocation data to delete.
2462# Returns a list starting with the new merged block, then the merged allocations with comment
2463## Merge scope:
2464# Merge to container
2465# keepall
2466# Move all mergeable allocations into the new block
2467# Move all mergeable free blocks into the new block
2468# mergepeer
2469# Move subs of mergeable containers into the updated primary.
2470# Reparent free blocks in mergeable containers to the updated primary.
2471# Convert assigned IPs from pools into subs.
2472# Convert unused IPs from pools into free blocks.
2473# Convert leaf allocations into free blocks.
2474# clearpeer
2475# Keep subs of the original (if it was a container).
2476# Convert assigned IPs from the original pool into subs (if it was a pool).
2477# Convert unused IPs from the original pool into free blocks (if it was a pool).
2478# Delete all peers and their subs aside from the original.
2479# clearall
2480# Delete all peers, subs and IPs.
2481# Add single free block for new container.
2482# Merge to pool
2483# keepall
2484# Convert all leaf allocations in the merge range to groups of used IPs
2485# mergepeer
2486# Effectively equal to keepall
2487# clearpeer
2488# Only convert IPs from the original allocation to used IPs
2489# clearall
2490# Delete any existing IPs, and reinitialize the new pool entirely
2491# Merge to leaf type
2492# Remove all subs
2493sub mergeBlocks {
2494 my $dbh = shift;
2495 my $prime = shift; # "base" block ID to use as a starting point
2496 if (!$prime) {
2497 $errstr = "Missing block ID to base merge on";
2498 return;
2499 }
2500
2501 my %args = @_;
2502
2503 # check key arguments.
2504 if (!$args{scope} || $args{scope} !~ /^(keepall|mergepeer|clearpeer|clearall)$/) {
2505 $errstr = "Bad or missing merge scope";
2506 return;
2507 }
2508 if (!$args{newmask} || $args{newmask} !~ /^\d+$/) {
2509 $errstr = "Bad or missing new netmask";
2510 return;
2511 }
2512
2513 # Retrieve info about the base allocation we're munging
2514 my $binfo = getBlockData($dbh, $prime);
2515 my $block = new NetAddr::IP $binfo->{block};
2516 my ($basetype) = ($binfo->{type} =~ /^.(.)$/);
2517 $binfo->{id} = $prime; # preserve for later, just in case
2518
2519 # proposed block
2520 my $newblock = new NetAddr::IP $block->addr."/$args{newmask}";
2521 $newblock = $newblock->network;
2522 $args{newtype} = $binfo->{type} if !$args{newtype};
2523 # if the "primary" block being changed is a master, it must remain one.
2524 # Also force the scope, since otherwise things get ugly.
2525 if ($binfo->{type} eq 'mm') {
2526 $args{newtype} = 'mm';
2527 # don't want to make a peer master a sub of the existing one; too many special cases go explodey,
2528 # but want to retain all other allocations
2529 $args{scope} = 'mergepeer';
2530 }
2531 my ($newcontainerclass) = ($args{newtype} =~ /^(.).$/);
2532
2533 # build an info hash for the "new" allocation we're creating
2534 my $pinfo = {
2535 id => $prime,
2536 block => "$newblock",
2537 type => $args{newtype},
2538 parent_id =>
2539 $binfo->{parent_id},
2540 city => $binfo->{city},
2541 vrf => $binfo->{vrf},
2542 master_id => $binfo->{master_id}
2543 };
2544
2545 my @retlist;
2546
2547 local $dbh->{AutoCommit} = 0;
2548 local $dbh->{RaiseError} = 1;
2549
2550 # Want to do all of the DB stuff in a transaction, to minimize data changing underfoot
2551 eval {
2552
2553 # We always update the "prime" block passed in...
2554 my $updsth = $dbh->prepare("UPDATE allocations SET cidr = ?, type = ? WHERE id = ?");
2555
2556##fixme: There's still an edge case in the return list where some branches accidentally include
2557# the original block as "additional". Probably due to the ordering of when the prepared update
2558# above gets executed.
2559
2560 # For leaf blocks, we may need to create a new parent as the "primary" instead
2561 # of updating the existing block
2562 my $newparent = $dbh->prepare(q{
2563 INSERT INTO allocations (
2564 cidr, type, city, description, notes, circuitid, createstamp, modifystamp,
2565 privdata, custid, swip, vrf, vlan, rdns, parent_id, master_id
2566 )
2567 SELECT
2568 ? AS cidr, ? AS type, city, description, notes, circuitid, createstamp, modifystamp,
2569 privdata, custid, swip, vrf, vlan, rdns, parent_id, master_id
2570 FROM allocations
2571 WHERE id = ?
2572 });
2573
2574 # Common actions
2575 my $peersth = $dbh->prepare("SELECT cidr,id,type,master_id FROM allocations WHERE parent_id = ? AND cidr <<= ?");
2576 $peersth->execute($binfo->{parent_id}, "$newblock");
2577 my $reparentsth = $dbh->prepare("UPDATE allocations SET parent_id = ?, master_id = ? WHERE id = ?");
2578 my $insfbsth = $dbh->prepare("INSERT INTO freeblocks (cidr,city,routed,vrf,parent_id,master_id) VALUES (?,?,?,?,?,?)");
2579 my $delsth = $dbh->prepare("DELETE FROM allocations WHERE id = ?");
2580
2581 my $fbreparentsth = $dbh->prepare(q{
2582 UPDATE freeblocks
2583 SET parent_id = ?, master_id = ?, city = ?, routed = ?, vrf = ?
2584 WHERE parent_id = ? AND cidr <<= ?
2585 });
2586
2587 if ($args{newtype} =~ /.[cm]/) {
2588 ## Container
2589
2590 # In case of merging a master block. Somewhat redundant with calls to $fbreparentsth,
2591 # but not *quite* entirely.
2592 my $mfbsth = $dbh->prepare("UPDATE freeblocks SET master_id = ? WHERE master_id = ?");
2593
2594 if ($args{scope} eq 'keepall') {
2595 # Create a new parent with the same info as the passed "primary".
2596 $newparent->execute($newblock, $args{newtype}, $prime);
2597 # and now retrieve the new parent ID
2598 ($prime) = $dbh->selectrow_array("SELECT currval('allocations_id_seq')");
2599 # snag the new parent info for the return list
2600 push @retlist, { block => "$newblock", type => $disp_alloctypes{$args{newtype}}, id => $prime };
2601 # Reparent the free blocks in the new block
2602 $fbreparentsth->execute($prime, $binfo->{master_id}, $binfo->{city}, $newcontainerclass, $binfo->{vrf},
2603 $binfo->{parent_id}, $newblock);
2604 # keep existing allocations (including the original primary), just push them down a level
2605 while (my ($peercidr, $peer_id, $peertype, $m_id) = $peersth->fetchrow_array) {
2606 $reparentsth->execute($prime, $binfo->{master_id}, $peer_id);
2607 # Fix up master_id on free blocks if we're merging a master block
2608 $mfbsth->execute($binfo->{master_id}, $m_id) if $peertype eq 'mm';
2609 # capture block for return
2610 push @retlist, { block => $peercidr, mdisp => $disp_alloctypes{$peertype}, mtype => $peertype };
2611 }
2612
2613 } elsif ($args{scope} =~ /^clear/) {
2614 # clearpeer and clearall share a starting point
2615 # snag the new parent info for the return list
2616 push @retlist, { block => "$newblock", type => $disp_alloctypes{$args{newtype}}, id => $prime };
2617 # update the primary allocation info
2618 $updsth->execute($newblock, $args{newtype}, $prime);
2619 # Reparent the free blocks in the new block
2620 $fbreparentsth->execute($prime, $binfo->{master_id}, $binfo->{city}, $newcontainerclass, $binfo->{vrf},
2621 $binfo->{parent_id}, $newblock);
2622 # Insert a free block if $prime is a leaf
2623 if ($binfo->{type} =~ /.[enr]/) {
2624 $insfbsth->execute($binfo->{block}, $binfo->{city}, $newcontainerclass, $binfo->{vrf}, $prime,
2625 $binfo->{master_id});
2626 }
2627 # delete the peers.
2628 while (my ($peercidr, $peer_id, $peertype, $m_id) = $peersth->fetchrow_array) {
2629 next if $peer_id == $prime;
2630 # push existing allocations down a level before deleting,
2631 # so that when they're deleted the parent info is correct
2632 $reparentsth->execute($prime, $binfo->{master_id}, $peer_id);
2633 _deleteCascade($dbh, $peer_id);
2634 # insert the freeblock _deleteCascade() (deliberately) didn't when deleting a master block.
2635 # aren't special cases fun?
2636 $dbh->do("INSERT INTO freeblocks (cidr,routed,parent_id,master_id) values (?,?,?,?)",
2637 undef, ($peercidr, 'm', $prime, $prime) ) if $binfo->{type} eq 'mm';
2638 # capture block for return
2639 push @retlist, { block => $peercidr, mdisp => $disp_alloctypes{$peertype}, mtype => $peertype };
2640 }
2641 if ($args{scope} eq 'clearall') {
2642 # delete any subs of $prime as well
2643 my $substh = $dbh->prepare("SELECT cidr,id FROM allocations WHERE parent_id = ?");
2644 $substh->execute($prime);
2645 while (my ($scidr, $s_id) = $substh->fetchrow_array) {
2646 _deleteCascade($dbh, $s_id);
2647 }
2648 } else {
2649 # clearpeer
2650 if ($basetype =~ /[dp]/) {
2651 # Convert active IP pool entries to allocations if the original was an IP pool
2652 _poolToAllocations($dbh, $binfo, $pinfo, newtype => $poolmap{$binfo->{type}});
2653 }
2654 } # clearall or clearpeer
2655
2656 } elsif ($args{scope} eq 'mergepeer') { # should this just be an else?
2657 # Default case. Merge "peer" blocks, but keep all suballocations
2658 # snag the new parent info for the return list
2659 push @retlist, {block => "$newblock", type => $disp_alloctypes{$args{newtype}}, id => $prime};
2660 my $substh = $dbh->prepare("UPDATE allocations SET parent_id = ? WHERE parent_id = ?");
2661 my $delsth = $dbh->prepare("DELETE FROM allocations WHERE id = ?");
2662 # Reparent freeblocks in parent
2663 $fbreparentsth->execute($prime, $binfo->{master_id}, $binfo->{city}, $newcontainerclass, $binfo->{vrf},
2664 $binfo->{parent_id}, $newblock);
2665 # Loop over "peer" allocations to be merged
2666 while (my ($peercidr, $peer_id, $peertype, $m_id) = $peersth->fetchrow_array) {
2667 # Snag existing peer data since we may need it
2668 my $peerfull = getBlockData($dbh, $peer_id);
2669 # Reparent free blocks from existing containers
2670 $fbreparentsth->execute($prime, $binfo->{master_id}, $binfo->{city}, $newcontainerclass,
2671 $binfo->{vrf}, $peer_id, $newblock);
2672 # Reparent any subblocks from existing containers
2673 $substh->execute($prime, $peer_id);
2674 # Delete the old container
2675 $delsth->execute($peer_id) unless $peer_id == $prime;
2676 # Add new freeblocks for merged leaf blocks
2677 $insfbsth->execute($peercidr, $binfo->{city}, $newcontainerclass, $binfo->{vrf}, $binfo->{id},
2678 $binfo->{master_id}) if $peertype =~ /.[enr]/;
2679 # Convert pool IPs into allocations or aggregated free blocks
2680 _poolToAllocations($dbh, $peerfull, $pinfo, newparent => $prime) if $peertype =~ /.[dp]/;
2681 # Fix up master_id on free blocks if we're merging a master block
2682 $mfbsth->execute($binfo->{master_id}, $m_id) if $peertype eq 'mm';
2683 # capture block for return
2684 push @retlist, { block => $peercidr, mdisp => $disp_alloctypes{$peertype}, mtype => $peertype };
2685 } # merge peers
2686 # update the primary allocation info. Do this last so we don't stomp extra data-retrieval in the loop above
2687 $updsth->execute($newblock, $args{newtype}, $prime);
2688
2689 } # scope
2690
2691 # Clean up free blocks
2692 _compactFree($dbh, $prime);
2693
2694 } elsif ($args{newtype} =~ /.[dp]/) {
2695 ## Pool
2696 # Snag the new parent info for the return list
2697 push @retlist, { block => "$newblock", type => $disp_alloctypes{$args{newtype}}, id => $prime };
2698
2699 if ($args{scope} eq 'keepall') {
2700 # Convert all mergeable allocations and subs to chunks of pool IP assignments
2701 push @retlist, @{ _toPool($dbh, $prime, $newblock, $args{newtype}, 1) };
2702
2703 } elsif ($args{scope} =~ /^clear/) {
2704 # Clear it all out for a fresh (mostly?) empty IP pool
2705 while (my ($peercidr, $peer_id, $peertype, $m_id) = $peersth->fetchrow_array) {
2706 next if $peer_id == $prime;
2707 # Push existing allocations down a level before deleting,
2708 # so that when they're deleted the parent info is correct
2709 $reparentsth->execute($prime, $binfo->{master_id}, $peer_id);
2710 _deleteCascade($dbh, $peer_id, 0);
2711 # Capture block for return
2712 push @retlist, { block => $peercidr, mdisp => $disp_alloctypes{$peertype}, mtype => $peertype };
2713 }
2714 if ($args{scope} eq 'clearall') {
2715 # Delete any subs of $prime as well
2716 my $substh = $dbh->prepare("SELECT cidr,id FROM allocations WHERE parent_id = ?");
2717 $substh->execute($prime);
2718 while (my ($scidr, $s_id) = $substh->fetchrow_array) {
2719 _deleteCascade($dbh, $s_id);
2720 }
2721 } else {
2722 # Convert (subs of) self if not a leaf.
2723 push @retlist, @{ _toPool($dbh, $prime, $newblock, $args{newtype}, 1) }
2724 unless $binfo->{type} =~ /.[enr]/;
2725 } # scope ne 'clearall'
2726
2727 } elsif ($args{scope} eq 'mergepeer') {
2728 # Try to match behaviour from (target type == container) by deleting immediate peer leaf allocations
2729 while (my ($peercidr, $peer_id, $peertype, $m_id) = $peersth->fetchrow_array) {
2730 next if $peer_id == $prime; # don't delete the block we're turning into the pool allocation
2731 # Capture block for return
2732 push @retlist, { block => $peercidr, mdisp => $disp_alloctypes{$peertype}, mtype => $peertype };
2733 next unless $peertype =~ /.[enr]/;
2734 # Don't need _deleteCascade(), since we'll just be deleting the freshly
2735 # added free block a little later anyway
2736 $delsth->execute($peer_id);
2737 }
2738 # Convert self if not a leaf, to match behaviour with a container type as target
2739 _toPool($dbh, $prime, $newblock, $args{newtype}) unless $binfo->{type} =~ /.[enr]/;
2740 }
2741 # Update the primary allocation info.
2742 $updsth->execute($newblock, $args{newtype}, $prime);
2743 # Delete any lingering free blocks
2744 $dbh->do("DELETE FROM freeblocks WHERE parent_id = ? AND cidr <<= ?", undef, $binfo->{parent_id}, $newblock);
2745 # Fix up the rest of the pool IPs
2746 my ($code,$msg) = initPool($dbh, $newblock, $args{newtype}, $binfo->{city},
2747 ($args{newtype} =~ /.p/ ? 'all' : 'normal'), $prime);
2748
2749 } elsif ($args{newtype} =~ /.[enr]/) {
2750 ## Leaf
2751 # Merging to a leaf type of any kind is, pretty much be definition, scope == 'clearall'.
2752 # keepall, mergepeer, and clearpeer all imply keeping suballocations, where leaf allocations
2753 # by definition do not have suballocations.
2754 # Update the old allocation
2755 $updsth->execute($newblock, $args{newtype}, $prime);
2756 # Snag the new parent info for the return list
2757 push @retlist, {block => "$newblock", type => $disp_alloctypes{$args{newtype}}, id => $prime};
2758 while (my ($peercidr, $peer_id, $peertype, $m_id) = $peersth->fetchrow_array) {
2759 next if $peer_id == $prime;
2760 # Push existing allocations down a level before deleting,
2761 # so that when they're deleted the parent info is correct
2762 $reparentsth->execute($prime, $binfo->{master_id}, $peer_id);
2763 _deleteCascade($dbh, $peer_id, 0);
2764 # Capture block for return
2765 push @retlist, { block => $peercidr, mdisp => $disp_alloctypes{$peertype}, mtype => $peertype };
2766 }
2767 # Delete any subs of $prime as well
2768 my $substh = $dbh->prepare("SELECT cidr,id FROM allocations WHERE parent_id = ?");
2769 $substh->execute($prime);
2770 while (my ($scidr, $s_id) = $substh->fetchrow_array) {
2771 _deleteCascade($dbh, $s_id);
2772 }
2773 # Clean up lingering free blocks and pool IPs
2774 $dbh->do("DELETE FROM freeblocks WHERE cidr <<= ? AND (parent_id = ? OR parent_id = ?)", undef,
2775 $newblock, $binfo->{parent_id}, $prime);
2776 $dbh->do("DELETE FROM poolips WHERE parent_id = ? AND ip <<= ? ", undef,
2777 $prime, $newblock);
2778
2779 } # $args{newtype} if()
2780
2781 $dbh->commit;
2782 };
2783 if ($@) {
2784 my $msg = $@;
2785 $errstr = $msg;
2786 $dbh->rollback;
2787 return ('FAIL',$msg);
2788 }
2789
2790# Make the assumption that any change crossing /24 or /16 boundaries will not come out right. Reverse DNS
2791# updates for this operation are already complex enough without handling those edge cases.
2792# ... er, how do we detect this?
2793
2794 # Return early if the block wasn't flagged as rDNS-able
2795 return \@retlist unless $binfo->{revavail} || $binfo->{revpartial};
2796
2797 if ($args{newtype} =~ /.[cm]/) {
2798
2799 if ($args{scope} eq 'keepall') {
2800 # Add new rDNS for new container
2801 _rpc('addOrUpdateRevRec', cidr => $binfo->{block}, name => $binfo->{rdns}, rpcuser => $args{user},
2802 location => $binfo->{location});
2803
2804 } else {
2805 # Resize rDNS template for $prime
2806 _rpc('resizeTemplate', oldcidr => "$binfo->{block}", newcidr => $newblock->network.'',
2807 rpcuser => $args{user}, location => $binfo->{location});
2808
2809 # Assemble a list of blocks to delete...
2810 my $cidrlist;
2811 foreach my $mblock (@retlist) {
2812 $cidrlist .= $mblock->{block}."," unless $mblock->{block} =~ $newblock;
2813 }
2814
2815 # ... then make slight variant batch delete calls depending on the merge scope
2816 if ($args{scope} eq 'mergepeer') {
2817 # Delete separate rDNS for other peers
2818 $cidrlist =~ s/,$//;
2819 _rpc('delRevSet', cidrlist => $cidrlist, rpcuser => $args{user}, delforward => 'y', delsubs => 'n',
2820 parpatt => $pinfo->{rdns}, location => $binfo->{location});
2821
2822 } elsif ($args{scope} eq 'clearpeer') {
2823 # Delete all rDNS within other peers
2824 $cidrlist =~ s/,$//;
2825 _rpc('delRevSet', cidrlist => $cidrlist, rpcuser => $args{user}, delforward => 'y', delsubs => 'y',
2826 parpatt => $pinfo->{rdns}, location => $binfo->{location});
2827
2828 } elsif ($args{scope} eq 'clearall') {
2829 # Delete all other records within the new block
2830 $cidrlist .= $binfo->{block};
2831 _rpc('delRevSet', cidrlist => $cidrlist, rpcuser => $args{user}, delforward => 'y', delsubs => 'y',
2832 parpatt => $pinfo->{rdns}, location => $binfo->{location});
2833
2834 } # scope, second level
2835 } # scope, !keepall
2836
2837 } elsif ($args{newtype} =~ /.[dp]/) {
2838 # Merge to pool
2839
2840 # Resize rDNS template for $prime
2841 _rpc('resizeTemplate', oldcidr => "$binfo->{block}", newcidr => $newblock->network.'',
2842 rpcuser => $args{user}, location => $binfo->{location});
2843
2844 if ($args{scope} eq 'keepall' || $args{scope} eq 'mergepeer') {
2845 # Assemble a list of blocks to convert from template to individual records...
2846 my @convlist;
2847 my @dellist;
2848 foreach my $mblock (@retlist) {
2849 next if $mblock->{block} =~ $newblock;
2850 if ($mblock->{mtype} =~ /.[cmdp]/) {
2851 # Container and pool templates get deleted
2852 push @dellist, $mblock->{block};
2853 } else {
2854 # Not-containers get converted to per-IP reverse records
2855 push @convlist, $mblock->{block};
2856 }
2857 }
2858 # And do the calls.
2859 _rpc('delRevSet', cidrlist => join(',', @dellist), rpcuser => $args{user}, delforward => 'y', delsubs => 'n',
2860 parpatt => $pinfo->{rdns}, location => $binfo->{location});
2861 _rpc('templatesToRecords', templates => \@convlist, rpcuser => $args{user}, location => $binfo->{location});
2862
2863 } # scope eq 'keepall' || 'mergepeer'
2864 else {
2865
2866 # Assemble a list of blocks to convert from template to individual records...
2867 my @convlist;
2868 my @dellist;
2869 my @fulldellist;
2870# There may be an impossible edge case that can be optimized away in here...
2871 foreach my $mblock (@retlist) {
2872 my $checkcidr = new NetAddr::IP $mblock->{block};
2873 next if $mblock->{block} =~ $newblock;
2874 if (!$block->contains($checkcidr)) {
2875 # Blocks not within the original get deleted
2876 push @fulldellist, $mblock->{block};
2877 }
2878 elsif ($mblock->{mtype} =~ /.[cmdp]/) {
2879 # Containers and pools get deleted
2880 push @dellist, $mblock->{block};
2881 } else {
2882 # Whatever's left over gets converted
2883 push @convlist, $mblock->{block};
2884 }
2885 } # foreach @retlist
2886 # And do the calls.
2887 if ($args{scope} eq 'clearpeer') {
2888 # Not happy doing this many, but there isn't really a better way.
2889 # We delete ALL EVARYTHING in peer blocks...
2890 _rpc('delRevSet', cidrlist => join(',', @fulldellist), rpcuser => $args{user}, delforward => 'y',
2891 delsubs => 'y', parpatt => $pinfo->{rdns}, location => $binfo->{location})
2892 if @fulldellist;
2893 # ... and just the template for container or pool templates in $prime...
2894 _rpc('delRevSet', cidrlist => join(',', @dellist), rpcuser => $args{user}, delforward => 'y',
2895 delsubs => 'n', parpatt => $pinfo->{rdns}, location => $binfo->{location})
2896 if @dellist;
2897 # ... and convert a few to record groups
2898 _rpc('templatesToRecords', templates => \@convlist, rpcuser => $args{user},
2899 location => $binfo->{location})
2900 if @convlist;
2901 }
2902 if ($args{scope} eq 'clearall') {
2903# consider just doing join(',',$newblock->split($newblock->masklen+1))?
2904 _rpc('delRevSet', cidrlist => join(',', @fulldellist, @dellist, @convlist, $binfo->{block}),
2905 rpcuser => $args{user}, delforward => 'y', delsubs => 'y', parpatt => $pinfo->{rdns},
2906 location => $binfo->{location});
2907 }
2908
2909 } # scope eq 'clearpeer' || 'clearall'
2910
2911 } elsif ($args{newtype} =~ /.[enr]/) {
2912 # Merge to leaf type
2913
2914 # Resize rDNS template for $prime
2915 _rpc('resizeTemplate', oldcidr => "$binfo->{block}", newcidr => $newblock->network.'',
2916 rpcuser => $args{user}, location => $binfo->{location});
2917
2918 # Assemble a list of blocks to delete...
2919 my $cidrlist;
2920 foreach my $mblock (@retlist) {
2921 $cidrlist .= $mblock->{block}."," unless $mblock->{block} =~ $newblock;
2922 }
2923 # Delete all other records within the new block
2924 $cidrlist .= $binfo->{block};
2925 _rpc('delRevSet', cidrlist => $cidrlist, rpcuser => $args{user}, delforward => 'y', delsubs => 'y',
2926 parpatt => $pinfo->{rdns}, location => $binfo->{location});
2927
2928 } # type grouping for rDNS calls
2929
2930 return \@retlist;
2931
2932} # end mergeBlocks()
2933
2934
2935## IPDB::deleteBlock()
2936# Removes an allocation from the database, including deleting IPs
2937# from poolips and recombining entries in freeblocks if possible
2938# Also handles "deleting" a static IP allocation, and removal of a master
2939# Requires a database handle, the block to delete, the routing depth (if applicable),
2940# the VRF ID, and a flag to indicate whether to delete associated forward DNS entries
2941# as well as the reverse entry
2942sub deleteBlock {
2943 my ($dbh,$id,$basetype,$delfwd,$user) = @_;
2944
2945 # reset $basetype so caller can just pass the complete allocation type
2946 if ($basetype =~ /^.?i$/) {
2947 $basetype = 'i';
2948 } else {
2949 $basetype = 'b';
2950 }
2951
2952 # Collect info about the block we're going to delete
2953 my $binfo = getBlockData($dbh, $id, $basetype);
2954 my $cidr = new NetAddr::IP $binfo->{block};
2955
2956# For possible auto-VRF-ignoring (since public IPs shouldn't usually be present in more than one VRF)
2957# is_rfc1918 requires NetAddr::IP >= 4.059
2958# rather than doing this over and over and over.....
2959 my $tmpnum = $cidr->numeric;
2960# 192.168.0.0/16 -> 192.168.255.255 => 3232235520 -> 3232301055
2961# 172.16.0.0/12 -> 172.31.255.255 => 2886729728 -> 2887778303
2962# 10.0.0.0/8 -> 10.255.255.255 => 167772160 -> 184549375
2963 my $isprivnet = (3232235520 <= $tmpnum && $tmpnum <= 3232301055) ||
2964 (2886729728 <= $tmpnum && $tmpnum <= 2887778303) ||
2965 (167772160 <= $tmpnum && $tmpnum <= 184549375);
2966
2967 my $sth;
2968
2969 # Magic variables used for odd allocation cases.
2970 my $container;
2971 my $con_type;
2972
2973
2974 # temporarily forced null, until a sane UI for VRF tracking can be found.
2975# $vrf = '';# if !$vrf; # as with SQL, the null value is not equal to ''. *sigh*
2976
2977 # To contain the error message, if any.
2978 my $msg = "Unknown error deallocating $binfo->{type} $cidr";
2979 my $goback; # to put the parent in so we can link back where the deallocate started
2980
2981 # Enable transactions and exception-on-errors... but only for this sub
2982 local $dbh->{AutoCommit} = 0;
2983 local $dbh->{RaiseError} = 1;
2984
2985 if ($binfo->{type} =~ /^.i$/) {
2986 # First case. The "block" is a static IP
2987 # Note that we still need some additional code in the odd case
2988 # of a netblock-aligned contiguous group of static IPs
2989 my $pinfo;
2990
2991 eval {
2992 $msg = "Unable to deallocate $disp_alloctypes{$binfo->{type}} $cidr";
2993 $pinfo = getBlockData($dbh, $binfo->{parent_id}, 'b');
2994 $dbh->do("UPDATE poolips SET custid = ?, available = 'y',".
2995 "city = (SELECT city FROM allocations WHERE id = ?),".
2996 "description = '', notes = '', circuitid = '', vrf = ?, backup_id = 0".
2997 " WHERE id = ?", undef,
2998 ($pinfo->{custid}, $binfo->{parent_id}, $pinfo->{vrf}, $id) );
2999 $dbh->do("DELETE FROM backuplist WHERE backup_id = ?", undef, $binfo->{hasbk})
3000 if $binfo->{hasbk};
3001 $dbh->commit;
3002 };
3003 if ($@) {
3004 $msg .= ": $@";
3005 eval { $dbh->rollback; };
3006 return ('FAIL',$msg);
3007 }
3008
3009##fixme: RPC return code?
3010 _rpc('delByCIDR', cidr => "$cidr", user => $user, delforward => $delfwd, rpcuser => $user,
3011 location => $binfo->{location})
3012 if ($pinfo->{revavail} || $pinfo->{revpartial});
3013
3014 return ('OK',"OK");
3015
3016 } elsif ($binfo->{type} eq 'mm') { # end alloctype =~ /.i/
3017 # Second case. The block is a full master block
3018
3019##fixme: VRF limit
3020 $msg = "Unable to delete master block $cidr";
3021 eval {
3022 $dbh->do("DELETE FROM allocations WHERE cidr <<= ? AND master_id = ?", undef, ($cidr, $binfo->{master_id}) );
3023 $dbh->do("DELETE FROM freeblocks WHERE cidr <<= ? AND master_id = ?", undef, ($cidr, $binfo->{master_id}) );
3024 $dbh->do("DELETE FROM dnsavail WHERE location = ? AND parent_alloc = ?", undef,
3025 ($binfo->{location}, $binfo->{master_id}) );
3026 $dbh->do("DELETE FROM backuplist WHERE backup_id = ?", undef, $binfo->{hasbk})
3027 if $binfo->{hasbk};
3028 $dbh->commit;
3029 };
3030 if ($@) {
3031 $msg .= ": $@";
3032 eval { $dbh->rollback; };
3033 return ('FAIL', $msg);
3034 }
3035
3036 # Have to handle potentially split reverse zones. Assume they *are* split,
3037 # since if we added them here, they would have been added split.
3038# allow splitting reverse zones to be disabled, maybe, someday
3039#if ($splitrevzones && !$cidr->{isv6}) {
3040 my @zonelist;
3041 if (1 && !$cidr->{isv6}) {
3042 my $splitpoint = ($cidr->masklen <= 16 ? 16 : 24); # hack pthui
3043 @zonelist = $cidr->split($splitpoint);
3044 } else {
3045 @zonelist = ($cidr);
3046 }
3047 my @fails;
3048 foreach my $subzone (@zonelist) {
3049 # We don't wrap this call tighter, since there isn't an inherent allocation to check for rDNS-ability.
3050 if ($rpc_url && !_rpc('delZone', zone => "$subzone", revrec => 'y', rpcuser => $user, delforward => $delfwd) ) {
3051 push @fails, ("$subzone" => $errstr);
3052 }
3053 }
3054 if (@fails) {
3055 return ('WARN',"Warning(s) deleting $cidr from reverse DNS:\n".join("\n", @fails));
3056 }
3057 return ('OK','OK');
3058
3059 } else { # end alloctype master block case
3060
3061 ## This is a big block; but it HAS to be done in a chunk. Any removal
3062 ## of a netblock allocation may result in a larger chunk of free
3063 ## contiguous IP space - which may in turn be combined into a single
3064 ## netblock rather than a number of smaller netblocks.
3065
3066 my $retcode = 'OK';
3067 my ($ptype,$pcity,$ppatt,$p_id);
3068
3069 eval {
3070
3071##fixme: add recursive flag to allow "YES DAMMIT DELETE ALL EVARYTHING!!1!!" without
3072# explicitly deleting any suballocations of the block to be deleted.
3073
3074 # get parent info of the block we're deleting
3075 my $pinfo = getBlockData($dbh, $binfo->{parent_id});
3076 $ptype = $pinfo->{type};
3077 $pcity = $pinfo->{city};
3078 $ppatt = $pinfo->{rdns};
3079 $p_id = $binfo->{parent_id};
3080
3081 # Delete the block
3082 $dbh->do("DELETE FROM allocations WHERE id = ?", undef, ($id) );
3083
3084 # munge the parent type a little
3085 $ptype = (split //, $ptype)[1];
3086
3087##fixme: you can't... CAN NOT.... assign the same public IP to multiple things.
3088# 'Net don't work like that, homey. Restrict VRF-uniqueness to private IPs?
3089# -> $isprivnet flag from start of sub
3090
3091 # check to see if any container allocations could be the "true" parent
3092 my ($tparent,$tpar_id,$trtype,$tcity);
3093 $tpar_id = 0;
3094
3095##fixme: this is far simpler in the strict VRF case; we "know" that any allocation
3096# contained by a container is a part of the same allocation tree when the VRF fields are equal.
3097
3098# logic:
3099# For each possible container of $cidr
3100# note the parent id
3101# walk the chain up the parents
3102# if we intersect $cidr's current parent, break
3103# if we've intersected $cidr's current parent
3104# set some variables to track that block
3105# break
3106
3107# Set up part of "is it in the middle of a pool?" check
3108 my $wuzpool = $dbh->selectrow_hashref("SELECT cidr,parent_id,type,city,custid,id FROM allocations ".
3109 "WHERE (type LIKE '_d' OR type LIKE '_p') AND cidr >> ? AND master_id = ?", { Slice => {} },
3110 ($cidr, $binfo->{master_id}) );
3111
3112##fixme?
3113# edge cases not handled, or handled badly:
3114# -> $cidr managed to get to be the entirety of an IP pool
3115
3116 if ($wuzpool && $wuzpool->{id} != $id) {
3117 # we have legacy goo to be purified
3118 # going to ignore nested pools; not possible to create them via API and no current legacy data includes any.
3119
3120 # for convenience
3121 my $poolid = $wuzpool->{id};
3122 my $pool = $wuzpool->{cidr};
3123 my $poolcity = $wuzpool->{city};
3124 my $pooltype = $wuzpool->{type};
3125 my $poolcustid = $wuzpool->{custid};
3126
3127 $retcode = 'WARNPOOL';
3128 $goback = "$poolid,$pool";
3129 # We've already deleted the block, now we have to stuff its IPs into the pool.
3130 $pooltype =~ s/[dp]$/i/; # change type to static IP
3131 my $sth2 = $dbh->prepare("INSERT INTO poolips (ip,city,type,custid,parent_id) VALUES ".
3132 "(?,'$poolcity','$pooltype','$poolcustid',$poolid)");
3133
3134##fixme: need to not insert net, gateway, and bcast on "real netblock" pools (DHCPish)
3135 # don't insert .0
3136 $sth2->execute($cidr->addr) unless $cidr->addr =~ m|\.0$|;
3137 $cidr++;
3138 my $bcast = $cidr->broadcast;
3139 while ($cidr != $bcast) {
3140 $sth2->execute($cidr->addr);
3141 $cidr++;
3142 }
3143 # don't insert .255
3144 $sth2->execute($cidr->addr) unless $cidr->addr =~ m|\.255$|;
3145
3146# Weirdness Happens. $cidr goes read-only somewhere (this is a thing?!?),
3147# causing ->split, ->hostenum, and related methods to explode. O_o
3148# foreach my $ip ($cidr->hostenum) {
3149# $sth2->execute($ip);
3150# }
3151
3152 }
3153
3154## important!
3155# ... or IS IT?
3156# we may have undef'ed $wuzpool above, if the allocation tree $cidr is in doesn't intersect the pool we found
3157#if (!$wuzpool) {
3158
3159 else {
3160
3161# Edge case: Block is the same size as more than one parent level. Should be rare.
3162# - mainly master + first routing. Sorting on parent_id hides the problem pretty well,
3163# but it's likely still possible to fail in particularly well-mangled databases.
3164# The ultimate fix for this may be to resurrect the "routing depth" atrocity. :/
3165 # Get all possible (and probably a number of impossible) containers for $cidr
3166 $sth = $dbh->prepare("SELECT cidr,parent_id,type,city,id FROM allocations ".
3167 "WHERE (type LIKE '_m' OR type LIKE '_c') AND cidr >>= ? AND master_id = ? ".
3168 "ORDER BY masklen(cidr) DESC,parent_id DESC");
3169 $sth->execute($cidr, $binfo->{master_id});
3170
3171 # Quickly get certain fields (simpler than getBlockData()
3172 my $sth2 = $dbh->prepare("SELECT cidr,parent_id,type,city FROM allocations ".
3173 "WHERE (type LIKE '_m' OR type LIKE '_c') AND id = ? AND master_id = ?");
3174
3175 # For each possible container of $cidr...
3176 while (my @data = $sth->fetchrow_array) {
3177 my $i = 0;
3178 # Save some state and set a start point - parent ID of container we're checking
3179 $tparent = $data[0];
3180 my $ppid = $data[1];
3181 $trtype = $data[2];
3182 $tcity = $data[3];
3183 $tpar_id = $data[4];
3184 last if $data[4] == $binfo->{parent_id}; # Preemptively break if we're already in the right place
3185 last if $ppid == $binfo->{parent_id}; # ... or if the parent of the container is the block's parent
3186 while (1) {
3187 # Retrieve bits on that parent ID
3188 $sth2->execute($ppid, $binfo->{master_id});
3189 my @container = $sth2->fetchrow_array;
3190 $ppid = $container[1];
3191 last if $container[1] == 0; # Break if we've hit a master block
3192 last if $ppid == $binfo->{parent_id}; # Break if we've reached the block $cidr is currently in
3193 }
3194 last if $ppid == $binfo->{parent_id};
3195 }
3196
3197 # found an alternate parent; reset some parent-info bits
3198 if ($tpar_id != $binfo->{parent_id}) {
3199 $ptype = (split //, $trtype)[1];
3200 $pcity = $tcity;
3201 $retcode = 'WARNMERGE'; # may be redundant
3202 $p_id = $tpar_id;
3203 }
3204
3205 $goback = "$p_id,$tparent"; # breadcrumb, currently only used in case of live-parent-is-not-true-parent
3206
3207 # Special case - delete pool IPs
3208 if ($binfo->{type} =~ /^.[pd]$/) {
3209 # We have to delete the IPs from the pool listing.
3210##fixme: rdepth? vrf?
3211 $dbh->do("DELETE FROM poolips WHERE parent_id = ?", undef, ($id) );
3212 }
3213
3214 $pinfo = getBlockData($dbh, $p_id);
3215
3216 # If the block wasn't legacy goo embedded in a static pool, we check the
3217 # freeblocks in the identified parent to see if we can combine any of them.
3218
3219 # if the block to be deleted is a container, move its freeblock(s) up a level, and reset their parenting info
3220 if ($binfo->{type} =~ /^.[mc]/) {
3221 # move the freeblocks into the parent
3222 # we don't insert a new freeblock because there could be a live reparented sub.
3223 $dbh->do("UPDATE freeblocks SET parent_id = ?, routed = ?, city = ? WHERE parent_id = ?", undef,
3224 ($p_id, $ptype, $pcity, $id) );
3225 } else {
3226 # ... otherwise, add the freeblock
3227 $dbh->do("INSERT INTO freeblocks (cidr, city, routed, parent_id, master_id) VALUES (?,?,?,?,?)", undef,
3228 ($cidr, $pcity, $ptype, $p_id, $binfo->{master_id}) );
3229 }
3230
3231 # Walk the free blocks in the parent and reduce them to the minimal set of CIDR ranges necessary
3232 _compactFree($dbh, $p_id);
3233
3234 } # done returning IPs to the appropriate place
3235
3236 # If we got here, we've succeeded. Whew!
3237 $dbh->commit;
3238 }; # end eval
3239 if ($@) {
3240 $msg .= ": $@";
3241 eval { $dbh->rollback; };
3242 return ('FAIL', $msg);
3243 }
3244
3245##fixme: RPC return code?
3246 _rpc('delByCIDR', cidr => "$cidr", rpcuser => $user, delforward => $delfwd, delsubs => 'y',
3247 parpatt => $ppatt, location => $binfo->{location})
3248 if ($binfo->{revavail} || $binfo->{revpartial});
3249
3250 return ($retcode, $goback);
3251
3252 } # end alloctype != netblock
3253
3254} # end deleteBlock()
3255
3256
3257## IPDB::getBlockData()
3258# Get CIDR or IP, custid, type, city, circuit ID, description, notes, modification time,
3259# private/restricted data, and backup fields, for a CIDR block or pool IP
3260# Also returns SWIP status flag for CIDR blocks or pool netblock for IPs
3261# Takes the block ID or IP to look up and an optional flag to indicate a pool IP lookup
3262# instead of a netblock.
3263# Returns a hashref to the block data
3264sub getBlockData {
3265 my $dbh = shift;
3266 my $id = shift;
3267 my $type = shift || 'b'; # default to netblock for lazy callers
3268
3269 # reset $type so caller can just pass the complete allocation type
3270 if ($type =~ /^.?i$/) {
3271 $type = 'i';
3272 } else {
3273 $type = 'b';
3274 }
3275
3276# catch some errors, someday
3277# if (!$id || $id !~ /^\d+$/) {
3278# $errstr = "Allocation ID must be numeric
3279# }
3280
3281 # Note city, vrf, parent_id and master_id removed due to JOIN uncertainty for block allocations
3282 my $commonfields = q(a.custid, a.type, a.circuitid, a.description, a.notes, a.modifystamp AS lastmod,
3283 a.privdata, a.vlan, a.rdns);
3284 my $bkfields = q(b.backup_id AS hasbk, b.bkbrand, b.bkmodel, b.bktype, b.bkport, b.bksrc,
3285 b.bkuser, b.bkvpass, b.bkepass, b.bkip);
3286
3287 if ($type eq 'i') {
3288 my $binfo = $dbh->selectrow_hashref(qq(
3289 SELECT a.id, a.ip AS block, a.city, a.vrf, a.parent_id, a.master_id, $commonfields,
3290 d.zone >> a.ip AS revavail, d.location,
3291 $bkfields,
3292 v.location AS vrfloc
3293 FROM poolips a
3294 LEFT JOIN dnsavail d ON a.master_id = d.parent_alloc AND a.ip << d.zone
3295 LEFT JOIN backuplist b ON a.backup_id = b.backup_id
3296 JOIN allocations m ON a.master_id = m.id JOIN vrfs v ON m.vrf = v.vrf
3297 WHERE a.id = ?
3298 ), undef, ($id) );
3299 return $binfo;
3300 } else {
3301 my $binfo = $dbh->selectrow_hashref(qq(
3302 SELECT a.id, a.cidr AS block, a.city, a.vrf, a.parent_id, a.master_id, a.swip, $commonfields,
3303 f.cidr AS reserve, f.id as reserve_id,
3304 d.zone >>= a.cidr AS revavail, d.zone << a.cidr AS revpartial, d.location,
3305 $bkfields,
3306 v.location AS vrfloc
3307 FROM allocations a
3308 LEFT JOIN freeblocks f ON a.id=f.reserve_for
3309 LEFT JOIN dnsavail d ON a.master_id = d.parent_alloc AND (a.cidr <<= d.zone OR a.cidr >> d.zone)
3310 LEFT JOIN backuplist b ON a.backup_id = b.backup_id
3311 JOIN allocations m ON a.master_id = m.id JOIN vrfs v ON m.vrf = v.vrf
3312 WHERE a.id = ?
3313 ), undef, ($id) );
3314
3315 return $binfo;
3316 }
3317} # end getBlockData()
3318
3319
3320## IPDB::getBlockRDNS()
3321# Gets reverse DNS pattern for a block or IP. Note that this will also
3322# retrieve any default pattern following the parent chain up, and check via
3323# RPC (if available) to see what the narrowest pattern for the requested block is
3324# Returns the current pattern for the block or IP.
3325sub getBlockRDNS {
3326 my $dbh = shift;
3327 my %args = @_;
3328
3329 $args{type} = 'b' if !$args{type};
3330 my $cached = 1;
3331
3332 # snag entry from database
3333 my ($rdns,$rfrom,$pid,$mid);
3334 if ($args{type} =~ /.i/) {
3335 ($rdns, $rfrom, $pid, $mid) = $dbh->selectrow_array("SELECT rdns,ip,parent_id,master_id FROM poolips WHERE id = ?",
3336 undef, ($args{id}) );
3337 } else {
3338 ($rdns, $rfrom, $pid, $mid) = $dbh->selectrow_array("SELECT rdns,cidr,parent_id,master_id FROM allocations WHERE id = ?",
3339 undef, ($args{id}) );
3340 }
3341
3342 # Can't see a way this could end up empty, for any case I care about. If the caller
3343 # doesn't know an allocation ID to request, then they don't know anything else anyway.
3344 my $selfblock = $rfrom;
3345
3346 my $type;
3347 while (!$rdns && $pid) {
3348 ($rdns, $rfrom, $pid, $type) = $dbh->selectrow_array(
3349 "SELECT rdns,cidr,parent_id,type FROM allocations WHERE id = ?",
3350 undef, ($pid) );
3351 last if $type eq 'mm'; # break loops in unfortunate legacy data
3352 }
3353
3354 # use the actual allocation to check against the DNS utility; we don't want
3355 # to always go chasing up the chain to the master... which may (usually won't)
3356 # be present directly in DNS anyway
3357 my $cidr = new NetAddr::IP $selfblock;
3358
3359 if ($rpc_url) {
3360 # Use the first /16 or /24, rather than dithering over which sub-/14 /16
3361 # or sub-/19 /24 to retrieve - it's the least-wrong way to do things.
3362
3363 my ($rpcblock) = ($cidr->masklen <= 24 ? $cidr->split( ($cidr->masklen <= 16 ? 16 : 24) ) : $cidr);
3364 my %rpcargs = (
3365 rpcuser => $args{user},
3366 group => $revgroup, # not sure how this could sanely be exposed, tbh...
3367 cidr => "$rpcblock",
3368 );
3369
3370# # Retrieve the VRF's location by way of the master block
3371# ($rpcargs{location}) = $dbh->selectrow_array("SELECT v.location FROM vrfs v".
3372# " JOIN allocations a ON a.vrf = v.vrf".
3373# " WHERE a.id = ?", undef, $mid);
3374
3375## ... is there something more needed here?
3376# order by so that we get the narrowest entry
3377 ($rpcargs{location}) = $dbh->selectrow_array("SELECT d.location FROM dnsavail d".
3378 " WHERE d.parent_alloc = ? ORDER BY zone DESC", undef, $mid);
3379
3380 $errstr = '';
3381 my $remote_rdns = _rpc('getRevPattern', %rpcargs);
3382 if ($remote_rdns) {
3383 $rdns = $remote_rdns;
3384 $cached = 0;
3385 } else {
3386 if (!$errstr) {
3387 # no error, but no data
3388 $cached = 0;
3389 }
3390 }
3391 }
3392
3393 # hmm. do we care about where it actually came from?
3394 return $rdns, $cached;
3395} # end getBlockRDNS()
3396
3397
3398## IPDB::getRDNSbyIP()
3399# Get individual reverse entries for the IP or CIDR IP range passed. Sort of looking the
3400# opposite direction down the netblock tree compared to getBlockRDNS() above.
3401sub getRDNSbyIP {
3402 my $dbh = shift;
3403 my %args = @_; # We want to accept a variety of call types
3404
3405 # key arguments: allocation ID, type
3406 unless ($args{id} || $args{type}) {
3407 $errstr = 'Missing allocation ID or type';
3408 return;
3409 }
3410
3411 my $binfo = getBlockData($dbh, $args{id}, $args{type});
3412
3413 my @ret = ();
3414 # special case: single IP. Check if it's an allocation or in a pool, then do the RPC call for fresh data.
3415 if ($args{type} =~ /^.i$/) {
3416 my ($ip, $localrev) = $dbh->selectrow_array("SELECT ip, rdns FROM poolips WHERE id = ?", undef, ($args{id}) );
3417 push @ret, { 'r_ip' => $ip, 'iphost' => $localrev };
3418##fixme: rpc call?
3419 } else {
3420 if ($rpc_url) {
3421 my %rpcargs = (
3422 rpcuser => $args{user},
3423 group => $revgroup, # not sure how this could sanely be exposed, tbh...
3424 cidr => $args{range},
3425 );
3426
3427# # Retrieve the VRF's DNS location by way of the master block
3428# ($rpcargs{location}) = $dbh->selectrow_array("SELECT v.location FROM vrfs v".
3429# " JOIN allocations a ON a.vrf = v.vrf JOIN allocations b ON a.id = b.master_id".
3430# " WHERE b.id = ?", undef, $args{id});
3431
3432## ... is there something more needed here?
3433# order by so that we get the narrowest entry
3434 ($rpcargs{location}) = $dbh->selectrow_array("SELECT d.location FROM dnsavail d".
3435 " WHERE d.parent_alloc = ? ORDER BY zone DESC", undef, $binfo->{master_id});
3436
3437 my $remote_rdns = _rpc('getRevSet', %rpcargs);
3438 return $remote_rdns;
3439# $rdns = $remote_rdns if $remote_rdns;
3440# $cached = 0;
3441 }
3442 }
3443 return \@ret;
3444} # end getRDNSbyIP()
3445
3446
3447## IPDB::getRevID()
3448# Get the reverse zone ID(s) for an allocation
3449# Takes a hash with cidr, location and user elements
3450# Returns a hashref to a list of zones and zone IDs (in case of large
3451# allocations effectively split across multiple DNS zones)
3452##fixme: arguably should be integrated in some other related sub that
3453# does RPC to minimize the number of RPC calls somehow
3454sub getRevID {
3455 my $dbh = shift;
3456 my %args = @_;
3457
3458##fixme: build a local cache for mapping allocations to DNS zone IDs
3459# my ($revlocal) = $dbh->selectrow_array("SELECT revzones[0] AS zone,revzones[1] AS revid FROM dnsavail WHERE
3460#zone >>= ? AND location = ?", undef, $args{cidr}, $args{location});
3461#use Data::Dumper;
3462#print "rezone array?<pre>".Dumper($revlocal)."</pre>\n";
3463
3464 my $revzones = _rpc('getZonesByCIDR', rpcuser => $args{user},
3465 cidr => $args{cidr},
3466 return_location => 0,
3467 location => $args{location},
3468 );
3469 return $revzones;
3470} # end getRevID()
3471
3472
3473## IPDB::getNodeList()
3474# Gets a list of node ID+name pairs as an arrayref to a list of hashrefs
3475sub getNodeList {
3476 my $dbh = shift;
3477
3478 my $ret = $dbh->selectall_arrayref("SELECT node_id, node_name FROM nodes ORDER BY node_type,node_id",
3479 { Slice => {} });
3480 return $ret;
3481} # end getNodeList()
3482
3483
3484## IPDB::getNodeName()
3485# Get node name from the ID
3486sub getNodeName {
3487 my $dbh = shift;
3488 my $nid = shift;
3489
3490 my ($nname) = $dbh->selectrow_array("SELECT node_name FROM nodes WHERE node_id = ?", undef, ($nid) );
3491 return $nname;
3492} # end getNodeName()
3493
3494
3495## IPDB::getNodeInfo()
3496# Get node name and ID associated with a block
3497sub getNodeInfo {
3498 my $dbh = shift;
3499 my $block = shift;
3500
3501 my ($nid, $nname) = $dbh->selectrow_array("SELECT nodes.node_id,node_name FROM nodes INNER JOIN noderef".
3502 " ON nodes.node_id=noderef.node_id WHERE noderef.block = ?", undef, ($block) );
3503 return ($nid, $nname);
3504} # end getNodeInfo()
3505
3506
3507## IPDB::mailNotify()
3508# Sends notification mail to recipients regarding an IPDB operation
3509sub mailNotify {
3510 my $dbh = shift;
3511 my ($action,$subj,$message) = @_;
3512
3513 return if $smtphost eq 'smtp.example.com'; # do nothing if still using default SMTP host.
3514
3515##fixme: need to redesign the breakdown/processing for $action for proper handling of all cases
3516
3517# split action into parts for fiddlement. nb: there are almost certainly better ways to do this.
3518 my @actionbits = split //, $action;
3519
3520 # want to notify anyone who has specifically requested notify on *this* type ($action as passed),
3521 # on "all static IP types" or "all pool types" (and other last-char-in-type groupings), on eg "all DSL types",
3522 # and "all events with this action"
3523 my @actionsets = ($action);
3524##fixme: ick, eww. really gotta find a better way to handle this...
3525 push @actionsets, ($actionbits[0].'.'.$actionbits[2],
3526 $actionbits[0].$actionbits[1].'.', $actionbits[0].'a') if $action =~ /^.{3}$/;
3527
3528 my $mailer = Net::SMTP->new($smtphost, Hello => "ipdb.$domain");
3529
3530 # get recip list from db
3531 my $sth = $dbh->prepare("SELECT reciplist FROM notify WHERE action=?");
3532
3533 my %reciplist;
3534 foreach (@actionsets) {
3535 $sth->execute($_);
3536##fixme - need to handle db errors
3537 my ($recipsub) = $sth->fetchrow_array;
3538 next if !$recipsub;
3539 foreach (split(/,/, $recipsub)) {
3540 $reciplist{$_}++;
3541 }
3542 }
3543
3544 return if !%reciplist;
3545
3546 # dodge a bullet with module version "numbers"
3547 my ($ver) = ($IPDB::VERSION =~ /^([\d.]+)(?:^\d|$)/);
3548
3549 foreach my $recip (keys %reciplist) {
3550 $mailer->mail($smtpsender);
3551 $mailer->to($recip);
3552 $mailer->data("From: \"$org_name IP Database\" <$smtpsender>\n",
3553 "To: $recip\n",
3554 "Date: ".strftime("%a, %d %b %Y %H:%M:%S %z",localtime)."\n",
3555 "Subject: {IPDB} $subj\n",
3556 "X-Mailer: IPDB Notify v".sprintf("%.1d",$ver)."\n",
3557 "Organization: $org_name\n",
3558 "\n$message\n");
3559 }
3560 $mailer->quit;
3561}
3562
3563# Indicates module loaded OK. Required by Perl.
35641;
Note: See TracBrowser for help on using the repository browser.