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

Last change on this file since 827 was 820, checked in by Kris Deugau, 9 years ago

/trunk

Add "delete VRF" confirmation and action pages. Refine link from showvrf
template since a VRF is a completely different type of entity than a
netblock. See #54.

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