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

Last change on this file since 934 was 933, checked in by Kris Deugau, 2 years ago

/trunk

Merge inexplicably unmerged get-pool-IPs-as-CSV feature from production
Fix long-missing VLAN display snafu on allocation update "done OK" page
Update @INC-munger in main.cgi
Update copyright block and style

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