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

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

/trunk

Fill in VRF when generating poolips entries

  • Property svn:keywords set to Date Rev Author
File size: 128.0 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-04-08 19:35:32 +0000 (Fri, 08 Apr 2016) $
6# SVN revision $Rev: 831 $
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,vrf) 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, $vrf);
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, $vrf)
1859 unless $foundips{$pool->addr."/32"};
1860 }
1861 $sth->execute($poolip_list[0]->addr, $pcustid, $city, $type, $parent, $master, $vrf)
1862 unless $foundips{$poolip_list[0]};
1863 $pool--;
1864 if ($pool->addr !~ /\.255$/) { # .255 can cause weirdness.
1865 $sth->execute($pool->addr, $pcustid, $city, $type, $parent, $master, $vrf)
1866 unless $foundips{$pool->addr."/32"};
1867 }
1868 }
1869# don't commit here! the caller may not be done.
1870# $dbh->commit;
1871 };
1872 if ($@) {
1873 $msg = $@;
1874# Don't roll back! It's up to the caller to handle this.
1875# eval { $dbh->rollback; };
1876 return ('FAIL',$msg);
1877 } else {
1878 return ('OK',"OK");
1879 }
1880} # end initPool()
1881
1882
1883## IPDB::updateBlock()
1884# Update an allocation
1885# Takes all allocation fields in a hash
1886sub updateBlock {
1887 my $dbh = shift;
1888 my %args = @_;
1889
1890 return ('FAIL', 'Missing block to update') if !$args{block};
1891
1892 # Spaces don't show up well in lots of places. Make sure they don't get into the DB.
1893 $args{custid} =~ s/^\s+//;
1894 $args{custid} =~ s/\s+$//;
1895
1896 # do it all in a transaction
1897 local $dbh->{AutoCommit} = 0;
1898 local $dbh->{RaiseError} = 1;
1899
1900 my @fieldlist;
1901 my @vallist;
1902 foreach ('custid', 'city', 'description', 'notes', 'circuitid', 'privdata', 'rdns', 'vrf', 'vlan') {
1903 if ($args{$_}) {
1904 push @fieldlist, $_;
1905 push @vallist, $args{$_};
1906 }
1907 }
1908
1909 my $binfo;
1910 my $updtable = 'allocations';
1911 my $keyfield = 'id';
1912 if ($args{type} =~ /^(.)i$/) {
1913 $updtable = 'poolips';
1914 $binfo = getBlockData($dbh, $args{block}, 'i');
1915 } else {
1916## fixme: there's got to be a better way...
1917 $binfo = getBlockData($dbh, $args{block});
1918 if ($args{swip}) {
1919 if ($args{swip} eq 'on' || $args{swip} eq '1' || $args{swip} eq 'y') {
1920 $args{swip} = 'y';
1921 } else {
1922 $args{swip} = 'n';
1923 }
1924 }
1925 foreach ('type', 'swip') {
1926 if ($args{$_}) {
1927 push @fieldlist, $_;
1928 push @vallist, $args{$_};
1929 }
1930 }
1931 }
1932
1933 return ('FAIL', 'No fields to update') if !@fieldlist;
1934
1935 my $sql = "UPDATE $updtable SET ";
1936 $sql .= join " = ?, ", @fieldlist;
1937
1938 # create these here so we can use the expanded CIDR in the rDNS update after the eval,
1939 # if we're expanding the block into a "reserved" freeblock
1940 my $cidr = NetAddr::IP->new($binfo->{block});
1941 my $newblock = NetAddr::IP->new($cidr->addr, $cidr->masklen - 1)->network;
1942
1943 eval {
1944 # check for block merge first...
1945 if ($args{fbmerge}) {
1946 # safety net? make sure mergeable block passed in is really one or both of
1947 # a) reserved for expansion of the block and
1948 # b) confirmed CIDR-combinable
1949 # "safety? SELECT foo FROM freeblocks WHERE cidr << ? AND masklen(cidr) = ?, $newblock, ".$cidr->masklen."\n";
1950 $dbh->do("DELETE FROM freeblocks WHERE id=?", undef, $args{fbmerge});
1951 # ... so we can append the change in the stored CIDR field to extend the allocation.
1952 $sql .= " = ?, cidr";
1953 push @vallist, $newblock;
1954 # if we have an IP pool, call initPool to fill in any missing entries in the pool
1955 if ($binfo->{type} =~ /^.p$/) {
1956 my ($code,$rmsg) = initPool($dbh, "$newblock", $binfo->{type}, $binfo->{city}, 'all', $args{block});
1957 die $rmsg if $code eq 'FAIL';
1958 } elsif ($binfo->{type} =~ /^.d$/) {
1959 my ($code,$rmsg) = initPool($dbh, "$newblock", $binfo->{type}, $binfo->{city}, 'normal', $args{block});
1960 die $rmsg if $code eq 'FAIL';
1961 }
1962 }
1963
1964 # backup
1965 if (!defined($args{ignorebk})) {
1966 # backup data considered "restricted"; caller should set this flag if user does not have 's' permission
1967
1968 my $backupid = $binfo->{hasbk};
1969 if (!$binfo->{hasbk}) {
1970 if ($args{backup}) {
1971 # failure mode: backup data on netblock with no IP set
1972 if (!$args{bkip}) {
1973 # check for /32-ness. no point in skipping /32 "netblocks", because they already single IPs
1974 die "Backup data set on a netblock requires a backup IP\n" unless $binfo->{block} =~ m{/32$};
1975 $args{bkip} = $binfo->{block};
1976 }
1977 # insert new backup record since we don't have one
1978 my $bksql = "INSERT INTO backuplist (";
1979 my @bkfields;
1980 my @bkvals;
1981 for my $bk (@backupfields) {
1982 if ($args{"bk$bk"}) {
1983 push @bkfields, "bk$bk";
1984 push @bkvals, $args{"bk$bk"};
1985 }
1986 }
1987 $bksql .= join(',',@bkfields).") VALUES (".join(',', map {'?'} @bkfields).")";
1988 $dbh->do($bksql, undef, @bkvals);
1989 ($backupid) = $dbh->selectrow_array("SELECT currval('backuplist_backup_id_seq')");
1990 # add the backup ID to the update
1991 push @vallist, $backupid;
1992 $sql .= " = ?, backup_id";
1993 }
1994
1995 } else { # !$binfo->{hasbk}
1996
1997 # allocation already has backup data
1998 if ($args{backup}) {
1999 if (!$args{bkip}) {
2000 # check for /32-ness. no point in skipping /32 "netblocks", because they are already single IPs
2001 die "Backup data set on a netblock requires a backup IP\n" unless $binfo->{block} =~ m{/32$};
2002 $args{bkip} = $binfo->{block};
2003 }
2004 my @bkfields;
2005 my @bkvals;
2006 for my $bk (@backupfields) {
2007 no warnings qw( uninitialized );
2008 if ($binfo->{"bk$bk"} ne $args{"bk$bk"}) {
2009 push @bkfields, "bk$bk = ?";
2010 push @bkvals, $args{"bk$bk"};
2011 }
2012 }
2013
2014 $dbh->do("UPDATE backuplist SET ".join(',', @bkfields)." WHERE backup_id = ?",
2015 undef, @bkvals, $binfo->{hasbk})
2016 if @bkfields;
2017##todo: keep historic changes for $timeperiod, by adding a backref ID field, and on updates adding a new backup
2018# record instead of updating the existing one. should probably check if new==old so we don't do needless updates
2019# in that case...
2020 } else {
2021 if ($binfo->{hasbk}) {
2022 # had backup data, no longer checked - delete backup entry
2023 $dbh->do("DELETE FROM backuplist WHERE backup_id = ?", undef, $binfo->{hasbk});
2024 $sql .= " = ?, backup_id";
2025 push @vallist, 0;
2026 }
2027 }
2028 } # $binfo->{hasbk} defined
2029 } # if !args{ignorebk}
2030
2031 # append another SQL fragment
2032 push @vallist, $args{block};
2033 $sql .= " = ? WHERE $keyfield = ?";
2034
2035 # do the update
2036 $dbh->do($sql, undef, @vallist);
2037
2038 if ($args{node}) {
2039 # done with delete/insert so we don't have to worry about funkyness updating a node ref that isn't there
2040 $dbh->do("DELETE FROM noderef WHERE block = ?", undef, ($binfo->{block}) );
2041 $dbh->do("INSERT INTO noderef (block,node_id) VALUES (?,?)", undef, ($binfo->{block}, $args{node}) )
2042 if $args{node} ne '--';
2043 }
2044
2045 $dbh->commit;
2046 };
2047 if ($@) {
2048 my $msg = $@;
2049 $dbh->rollback;
2050 return ('FAIL', $msg);
2051 }
2052
2053 # Do RPC rDNS call, if available.
2054 # Snag the parent info
2055 my $pinfo = getBlockData($dbh, $binfo->{parent_id});
2056 # Return early if rDNS flag(s) are not set
2057 return ('OK','OK') unless ($pinfo->{revavail} || $pinfo->{revpartial});
2058
2059 # In case of any container (mainly master block), only update freeblocks so we don't stomp subs
2060 # (which would be the wrong thing in pretty much any case except "DELETE ALL EVARYTHING!!1!oneone!")
2061 if ($binfo->{type} =~ '.[mc]') {
2062 # Not using listFree() as it doesn't return quite all of the blocks wanted.
2063 # Retrieve the immediate free blocks
2064 my $sth = $dbh->prepare(q(
2065 SELECT cidr FROM freeblocks WHERE parent_id = ?
2066 UNION
2067 SELECT cidr FROM freeblocks f WHERE
2068 cidr = (SELECT cidr FROM allocations a WHERE f.cidr = a.cidr)
2069 AND master_id = ?
2070 ) );
2071 $sth->execute($args{block}, $binfo->{master_id});
2072 my %fbset;
2073 while (my ($fb) = $sth->fetchrow_array) {
2074 $fbset{"host_$fb"} = $args{rdns};
2075 }
2076 # We use this RPC call instead of multiple addOrUpdateRevRec calls, since we don't
2077 # know how many records we'll be updating and more than 3-4 is far too slow. This
2078 # should be safe to call unconditionally.
2079 # Requires dnsadmin >= r678
2080 _rpc('updateRevSet', %fbset, rpcuser => $args{user});
2081
2082 } else {
2083 $binfo->{block} =~ s|/32$||;
2084 _rpc('addOrUpdateRevRec', cidr => $binfo->{block}, name => $args{rdns}, rpcuser => $args{user});
2085
2086 # and the per-IP set, if there is one.
2087 _rpc('updateRevSet', %{$args{iprev}}, rpcuser => $args{user}) if keys (%{$args{iprev}});
2088
2089 # and fix up the template's CIDR if required
2090 _rpc('resizeTemplate', oldcidr => "$binfo->{block}", newcidr => $newblock->network.'', rpcuser => $args{user})
2091 if $args{fbmerge};
2092 }
2093
2094##fixme: RPC failures?
2095 return ('OK','OK');
2096} # end updateBlock()
2097
2098
2099## IPDB::splitBlock()
2100# Splits an existing allocation into two or more smaller allocations based on a passed netmask
2101# Duplicates all other data
2102# Returns an arrayref to a list of hashrefs with ID and CIDR keys for the list of new allocations.
2103# Should probably commit DNS magic to realign DNS data
2104# Mostly works but may return Strange Things(TM) if used on a master block
2105sub splitBlock {
2106 my $dbh = shift;
2107 my %args = @_;
2108
2109##fixme: set errstr on errors so caller can suitably clue-by-four the user
2110 return if $args{basetype} ne 'b'; # only netblocks allowed!
2111
2112 my $binfo = getBlockData($dbh, $args{id});
2113 return if !$binfo;
2114
2115 return if $args{newmask} !~ /^\d+$/;
2116
2117 my @ret;
2118 my $block = new NetAddr::IP $binfo->{block};
2119 my $oldmask = $block->masklen;
2120
2121 # Fail if the block to split is "too small" - eg, can't split a v4 /32 at all
2122 # failure modes:
2123 # difference between $oldmask and $newmask is negative or 0
2124 if ($args{newmask} - $oldmask <= 0) {
2125 $errstr = "Can't split a /$oldmask allocation into /$args{newmask} pieces";
2126 return;
2127 }
2128# # difference between $oldmask and $newmask is > n, for arbitrary n?
2129# if ($newmask - $oldmask > 42) { # because 42
2130# }
2131 # $oldmask > n, for arbitrary n? At least check limits of data type.
2132 if ($block->{isv6}) {
2133 if ($args{newmask} - $oldmask > 128) {
2134 $errstr = "Impossible IPv6 mask length /$args{newmask} requested";
2135 return;
2136 }
2137 } else {
2138 if ($args{newmask} - $oldmask > 32) {
2139 $errstr = "Impossible IPv4 mask length /$args{newmask} requested";
2140 return;
2141 }
2142 }
2143
2144 my @newblocks = $block->split($args{newmask});
2145
2146 local $dbh->{AutoCommit} = 0;
2147 local $dbh->{RaiseError} = 1;
2148
2149 eval {
2150 # line up a list of fields and values. Be nice if there was a handy way to do,
2151 # direct in SQL, something like
2152 # "INSERT INTO foo (f1,f2,f3) VALUES (newf1,(SELECT oldf2,oldf3 FROM foo WHERE baz))"
2153 my @fieldlist = qw(type city description notes circuitid privdata custid swip vrf vlan rdns parent_id master_id);
2154 my $fields_sql = join(',', @fieldlist);
2155 my @vals;
2156 foreach (@fieldlist) {
2157 push @vals, $binfo->{$_};
2158 }
2159 # note the first block in the split for return
2160 push @ret, {nid => $args{id}, nblock => "$newblocks[0]"};
2161
2162 # prepare
2163 my $idsth = $dbh->prepare("SELECT currval('allocations_id_seq')");
2164 my $allocsth = $dbh->prepare("INSERT INTO allocations (cidr, $fields_sql)".
2165 " VALUES (?".',?'x(scalar(@fieldlist)).")");
2166 my $allocsth2 = $dbh->prepare(qq(
2167 INSERT INTO allocations (cidr, $fields_sql)
2168 SELECT ? AS cidr, $fields_sql
2169 FROM allocations
2170 WHERE id = ?
2171 ) );
2172 my $nbsth = $dbh->prepare("DELETE FROM poolips WHERE parent_id = ? AND ip = ?");
2173 my $upd_psth = $dbh->prepare("UPDATE allocations SET parent_id = ? WHERE parent_id = ? AND cidr <<= ?");
2174 my $upd_msth = $dbh->prepare("UPDATE allocations SET master_id = ? WHERE master_id = ? AND cidr <<= ?");
2175 my $fb_psth = $dbh->prepare("UPDATE freeblocks SET parent_id = ? WHERE parent_id = ? AND cidr <<= ?");
2176 my $fb_msth = $dbh->prepare("UPDATE freeblocks SET master_id = ? WHERE master_id = ? AND cidr <<= ?");
2177 my $pool_psth = $dbh->prepare("UPDATE poolips SET parent_id = ? WHERE parent_id = ? AND ip << ?");
2178 my $pool_msth = $dbh->prepare("UPDATE poolips SET master_id = ? WHERE master_id = ? AND ip <<= ?");
2179
2180 my @clist;
2181 _getChildren($dbh, $args{id}, $binfo->{master_id}, \@clist, $block);
2182
2183 my @processlist;
2184 push @processlist, { id => $args{id}, cidr => $block, mask => $block->masklen, type => $binfo->{type} };
2185 foreach (@clist) {
2186 $_->{cidr} = new NetAddr::IP $_->{cidr};
2187 if ($_->{cidr}->masklen < $args{newmask}) {
2188 $_->{mask} = $_->{cidr}->masklen;
2189 push @processlist, $_;
2190 }
2191 }
2192
2193 # Sort on masklen, crudely break ties by pushing container blocks down the stack. Multiple-nested containers
2194 # of the same size are virtually guaranteed to produce strange results, but should be rare enough to not matter
2195 @processlist = sort { $b->{cidr}->masklen <=> $a->{cidr}->masklen || $a->{type} =~ /^.m$/ } @processlist;
2196
2197 foreach my $pr (@processlist) {
2198 my @nbset = $pr->{cidr}->split($args{newmask});
2199
2200 # set up update of existing block
2201 $dbh->do("UPDATE allocations SET cidr = ? WHERE id = ?", undef, ("$nbset[0]", $pr->{id}) );
2202
2203 # axe the new bcast IP from the smaller pool at the "base" block, if it's a "normal" pool
2204 if ($pr->{type} =~ /.d/) {
2205 $nbset[0]--;
2206 $nbsth->execute($pr->{id}, $nbset[0]->addr);
2207 }
2208
2209 # Holder for freeblocks-to-delete. Should be impossible to have more than one...
2210 my %fbdel;
2211
2212 # Loop over the new blocks that are not the base block
2213 for (my $i = 1; $i <= $#nbset; $i++) {
2214 # add the new allocation
2215 $allocsth2->execute($nbset[$i], $pr->{id});
2216
2217 # fetch the ID of the entry we just added...
2218 $idsth->execute();
2219 my ($nid) = $idsth->fetchrow_array();
2220 # ... so we can pass back the list of blocks and IDs...
2221 push @ret, {nid => $nid, nblock => "$nbset[$i]"};
2222 # axe the net, gw, and bcast IPs as necessary when splitting a "normal" pool
2223 if ($pr->{type} =~ /.d/) {
2224 # net
2225 $nbsth->execute($pr->{id}, $nbset[$i]->addr);
2226 $nbset[$i]++;
2227 # gw
2228 $nbsth->execute($pr->{id}, $nbset[$i]->addr);
2229 $nbset[$i]--;
2230 $nbset[$i]--;
2231 # bcast
2232 $nbsth->execute($pr->{id}, $nbset[$i]->addr);
2233 $nbset[$i]++;
2234 } # $binfo->{type} =~ /.d/
2235
2236 # Check for free blocks larger than the new mask length, and split those as needed.
2237 if ($pr->{type} =~ /.[cm]/) {
2238 # get a "list" of freeblocks bigger than the allocation in the parent. there's only one, right?
2239 my $fblist = $dbh->selectall_arrayref("SELECT id FROM freeblocks WHERE cidr >> ? AND parent_id = ? ",
2240 {Slice=>{}}, $nbset[$i], $pr->{id});
2241 if (@$fblist) {
2242 # create a new freeblock for the new block we created earlier
2243 $dbh->do(q{
2244 INSERT INTO freeblocks (cidr, parent_id, master_id, city, routed,vrf)
2245 SELECT ? AS cidr, ? AS parent_id, master_id, city, routed, vrf FROM freeblocks
2246 WHERE id = ?
2247 }, undef, ($nbset[$i], $nid, $fblist->[0]->{id}) );
2248 $fbdel{$fblist->[0]->{id}}++;
2249 }
2250 } # $binfo->{type} =~ /.[cm]/
2251
2252 # Reparent allocations, freeblocks, and pool IPs.
2253 $upd_psth->execute($nid, $pr->{id}, $nbset[$i]);
2254 $fb_psth->execute($nid, $pr->{id}, $nbset[$i]);
2255 $pool_psth->execute($nid, $pr->{id}, $nbset[$i]);
2256
2257 # Update master if we've split a master block
2258 if ($pr->{type} eq 'mm') {
2259 $upd_msth->execute($nid, $pr->{id}, $nbset[$i]);
2260 $fb_msth->execute($nid, $pr->{id}, $nbset[$i]);
2261 $pool_msth->execute($nid, $pr->{id}, $nbset[$i]);
2262 }
2263
2264##fixme:
2265# 2015/09/09 not sure if the latest rewrite has covered this case complete or not
2266# Still missing one edge case - megasplitting a large block such that "many" children also need to be split.
2267# I'm going to call this "unsupported" because I really can't imagine a sane reason for doing this.
2268# Should probably check and error out at least
2269
2270 } # for (... @nbset)
2271
2272 if (%fbdel) {
2273 my $delfblist = $dbh->selectall_arrayref(q{
2274 SELECT cidr,parent_id,id FROM freeblocks
2275 WHERE id in (
2276 }.join(',', keys %fbdel).")", {Slice=>{}} );
2277 $dbh->do("DELETE FROM freeblocks WHERE id IN (".join(',', keys %fbdel).")") if %fbdel;
2278 }
2279
2280 } # foreach @processlist
2281
2282 $dbh->commit;
2283 };
2284 if ($@) {
2285 $errstr = "Error splitting $binfo->{block}: $@";
2286 $dbh->rollback;
2287 return;
2288 }
2289
2290 # Only try to update rDNS when the original block is flagged as "rDNS available"
2291 _rpc('splitTemplate', cidr => $binfo->{block}, newmask => $args{newmask}, rpcuser => $args{user})
2292 if ($binfo->{revavail} || $binfo->{revpartial});
2293
2294 return \@ret;
2295} # end splitBlock()
2296
2297
2298## IPDB::shrinkBlock()
2299# Shrink an allocation to the passed CIDR block
2300# Takes an allocation ID and a new CIDR
2301# Returns an arrayref to a list of hashrefs with the ID and CIDR of the freed block(s)
2302# Refuses to shrink "real netblock" pool types below /30
2303sub shrinkBlock {
2304 my $dbh = shift;
2305 my $id = shift;
2306
2307 # just take the new CIDR spec; this way we can shrink eg .16/28 to .20/30 without extra contortions
2308 my $newblock = new NetAddr::IP shift;
2309
2310 my $user = shift;
2311
2312 if (!$newblock) {
2313 $errstr = "Can't shrink something that's not a netblock";
2314 return;
2315 }
2316
2317 my $binfo = getBlockData($dbh, $id);
2318 my $pinfo = getBlockData($dbh, $binfo->{parent_id});
2319
2320 if ($binfo->{type} =~ /.d/ && $newblock->masklen > ($newblock->bits+2) ) {
2321 $errstr = "Can't shrink a non-PPP pool smaller than ".($newblock->{isv6} ? '/124' : '/30');
2322 return;
2323 }
2324
2325 my $oldblock = new NetAddr::IP $binfo->{block};
2326
2327 # Don't try to shrink the block outside of itself, Bad Things (probably) Happen.
2328 if (!$oldblock->contains($newblock)) {
2329 $errstr = "Can't shrink an allocation outside of itself";
2330 return;
2331 }
2332
2333 local $dbh->{AutoCommit} = 0;
2334 local $dbh->{RaiseError} = 1;
2335
2336 my $addfbsth = $dbh->prepare("INSERT INTO freeblocks (cidr,city,routed,vrf,parent_id,master_id) VALUES (?,?,?,?,?,?)");
2337 my $idsth = $dbh->prepare("SELECT currval('freeblocks_id_seq')");
2338 my $poolsth = $dbh->prepare("DELETE FROM poolips WHERE parent_id = ? AND ip << ?");
2339 my $netsth = $dbh->prepare("DELETE FROM poolips WHERE parent_id = ? AND ip = ?");
2340 my $allocsth = $dbh->prepare("DELETE FROM allocations WHERE parent_id = ? AND cidr <<= ?");
2341 my $delfbsth = $dbh->prepare("DELETE FROM freeblocks WHERE parent_id = ? AND cidr <<= ?");
2342
2343 my @ret;
2344 my @newfreelist;
2345 eval {
2346 $dbh->do("UPDATE allocations SET cidr = ? WHERE id = ?", undef, $newblock, $id);
2347
2348 # find the netblock(s) that are now free
2349 my @workingblocks = $oldblock->split($newblock->masklen);
2350 foreach my $newsub (@workingblocks) {
2351 next if $newsub == $newblock;
2352 push @newfreelist, $newsub;
2353 }
2354 @newfreelist = Compact(@newfreelist);
2355
2356 # set new freeblocks, and clean up any IP pool entries if needed.
2357 foreach my $newfree (@newfreelist) {
2358 my @clist;
2359 # the block we're munging
2360 push @clist, { id => $id, type => $binfo->{type}, cidr => $binfo->{block} };
2361 _getChildren($dbh, $id, $binfo->{master_id}, \@clist, $newfree);
2362
2363 foreach my $goner (@clist) {
2364 $poolsth->execute($goner->{id}, $newfree) if $goner->{type} =~ /.[dp]/;
2365 $allocsth->execute($goner->{id}, $newfree);
2366 $delfbsth->execute($goner->{id}, $newfree);
2367 }
2368
2369 # No pinfo means we're shrinking a master block, which means the free space is returned outside of IPDB.
2370 if ($pinfo) {
2371 $addfbsth->execute($newfree, $pinfo->{city}, 'm', $pinfo->{vrf}, $binfo->{parent_id}, $pinfo->{master_id});
2372 $idsth->execute;
2373 my ($nid) = $idsth->fetchrow_array();
2374 # add to return list
2375 push @ret, {fbid => $nid, newfree => "$newfree", fbparent => $binfo->{parent_id} };
2376 }
2377
2378 } # $newfree (@newfreelist)
2379
2380 # additional cleanup on net/gw/bcast IPs in pool
2381 if ($binfo->{type} =~ /.d/) {
2382 $netsth->execute($id, $newblock->addr);
2383 $newblock++;
2384 $netsth->execute($id, $newblock->addr);
2385 $newblock--;
2386 $newblock--;
2387 $netsth->execute($id, $newblock->addr);
2388 }
2389
2390 $dbh->commit;
2391 };
2392 if ($@) {
2393 $errstr = "Error splitting $binfo->{block}: $@";
2394 $dbh->rollback;
2395 return;
2396 }
2397
2398 # Only try to update rDNS when the original block is flagged as "rDNS available"
2399 _rpc('resizeTemplate', oldcidr => $binfo->{block}, newcidr => $newblock->network, rpcuser => $user)
2400 if ($binfo->{revavail} || $binfo->{revpartial});
2401
2402 return \@ret;
2403} # end shrinkBlock()
2404
2405
2406## IPDB::mergeBlocks()
2407# Merges two or more adjacent allocations, optionally including relevant
2408# free space, into one allocation.
2409# Takes a "base" block ID and a hash with a mask length and a scope argument to decide
2410# how much existing allocation data to delete.
2411# Returns a list starting with the new merged block, then the merged allocations with comment
2412## Merge scope:
2413# Merge to container
2414# keepall
2415# Move all mergeable allocations into the new block
2416# Move all mergeable free blocks into the new block
2417# mergepeer
2418# Move subs of mergeable containers into the updated primary.
2419# Reparent free blocks in mergeable containers to the updated primary.
2420# Convert assigned IPs from pools into subs.
2421# Convert unused IPs from pools into free blocks.
2422# Convert leaf allocations into free blocks.
2423# clearpeer
2424# Keep subs of the original (if it was a container).
2425# Convert assigned IPs from the original pool into subs (if it was a pool).
2426# Convert unused IPs from the original pool into free blocks (if it was a pool).
2427# Delete all peers and their subs aside from the original.
2428# clearall
2429# Delete all peers, subs and IPs.
2430# Add single free block for new container.
2431# Merge to pool
2432# keepall
2433# Convert all leaf allocations in the merge range to groups of used IPs
2434# mergepeer
2435# Effectively equal to keepall
2436# clearpeer
2437# Only convert IPs from the original allocation to used IPs
2438# clearall
2439# Delete any existing IPs, and reinitialize the new pool entirely
2440# Merge to leaf type
2441# Remove all subs
2442sub mergeBlocks {
2443 my $dbh = shift;
2444 my $prime = shift; # "base" block ID to use as a starting point
2445 if (!$prime) {
2446 $errstr = "Missing block ID to base merge on";
2447 return;
2448 }
2449
2450 my %args = @_;
2451
2452 # check key arguments.
2453 if (!$args{scope} || $args{scope} !~ /^(keepall|mergepeer|clearpeer|clearall)$/) {
2454 $errstr = "Bad or missing merge scope";
2455 return;
2456 }
2457 if (!$args{newmask} || $args{newmask} !~ /^\d+$/) {
2458 $errstr = "Bad or missing new netmask";
2459 return;
2460 }
2461
2462 # Retrieve info about the base allocation we're munging
2463 my $binfo = getBlockData($dbh, $prime);
2464 my $block = new NetAddr::IP $binfo->{block};
2465 my ($basetype) = ($binfo->{type} =~ /^.(.)$/);
2466 $binfo->{id} = $prime; # preserve for later, just in case
2467
2468 # proposed block
2469 my $newblock = new NetAddr::IP $block->addr."/$args{newmask}";
2470 $newblock = $newblock->network;
2471 $args{newtype} = $binfo->{type} if !$args{newtype};
2472 # if the "primary" block being changed is a master, it must remain one.
2473 # Also force the scope, since otherwise things get ugly.
2474 if ($binfo->{type} eq 'mm') {
2475 $args{newtype} = 'mm';
2476 # don't want to make a peer master a sub of the existing one; too many special cases go explodey,
2477 # but want to retain all other allocations
2478 $args{scope} = 'mergepeer';
2479 }
2480 my ($newcontainerclass) = ($args{newtype} =~ /^(.).$/);
2481
2482 # build an info hash for the "new" allocation we're creating
2483 my $pinfo = {
2484 id => $prime,
2485 block => "$newblock",
2486 type => $args{newtype},
2487 parent_id =>
2488 $binfo->{parent_id},
2489 city => $binfo->{city},
2490 vrf => $binfo->{vrf},
2491 master_id => $binfo->{master_id}
2492 };
2493
2494 my @retlist;
2495
2496 local $dbh->{AutoCommit} = 0;
2497 local $dbh->{RaiseError} = 1;
2498
2499 # Want to do all of the DB stuff in a transaction, to minimize data changing underfoot
2500 eval {
2501
2502 # We always update the "prime" block passed in...
2503 my $updsth = $dbh->prepare("UPDATE allocations SET cidr = ?, type = ? WHERE id = ?");
2504
2505##fixme: There's still an edge case in the return list where some branches accidentally include
2506# the original block as "additional". Probably due to the ordering of when the prepared update
2507# above gets executed.
2508
2509 # For leaf blocks, we may need to create a new parent as the "primary" instead
2510 # of updating the existing block
2511 my $newparent = $dbh->prepare(q{
2512 INSERT INTO allocations (
2513 cidr, type, city, description, notes, circuitid, createstamp, modifystamp,
2514 privdata, custid, swip, vrf, vlan, rdns, parent_id, master_id
2515 )
2516 SELECT
2517 ? AS cidr, ? AS type, city, description, notes, circuitid, createstamp, modifystamp,
2518 privdata, custid, swip, vrf, vlan, rdns, parent_id, master_id
2519 FROM allocations
2520 WHERE id = ?
2521 });
2522
2523 # Common actions
2524 my $peersth = $dbh->prepare("SELECT cidr,id,type,master_id FROM allocations WHERE parent_id = ? AND cidr <<= ?");
2525 $peersth->execute($binfo->{parent_id}, "$newblock");
2526 my $reparentsth = $dbh->prepare("UPDATE allocations SET parent_id = ?, master_id = ? WHERE id = ?");
2527 my $insfbsth = $dbh->prepare("INSERT INTO freeblocks (cidr,city,routed,vrf,parent_id,master_id) VALUES (?,?,?,?,?,?)");
2528 my $delsth = $dbh->prepare("DELETE FROM allocations WHERE id = ?");
2529
2530 my $fbreparentsth = $dbh->prepare(q{
2531 UPDATE freeblocks
2532 SET parent_id = ?, master_id = ?, city = ?, routed = ?, vrf = ?
2533 WHERE parent_id = ? AND cidr <<= ?
2534 });
2535
2536 if ($args{newtype} =~ /.[cm]/) {
2537 ## Container
2538
2539 # In case of merging a master block. Somewhat redundant with calls to $fbreparentsth,
2540 # but not *quite* entirely.
2541 my $mfbsth = $dbh->prepare("UPDATE freeblocks SET master_id = ? WHERE master_id = ?");
2542
2543 if ($args{scope} eq 'keepall') {
2544 # Create a new parent with the same info as the passed "primary".
2545 $newparent->execute($newblock, $args{newtype}, $prime);
2546 # and now retrieve the new parent ID
2547 ($prime) = $dbh->selectrow_array("SELECT currval('allocations_id_seq')");
2548 # snag the new parent info for the return list
2549 push @retlist, { block => "$newblock", type => $disp_alloctypes{$args{newtype}}, id => $prime };
2550 # Reparent the free blocks in the new block
2551 $fbreparentsth->execute($prime, $binfo->{master_id}, $binfo->{city}, $newcontainerclass, $binfo->{vrf},
2552 $binfo->{parent_id}, $newblock);
2553 # keep existing allocations (including the original primary), just push them down a level
2554 while (my ($peercidr, $peer_id, $peertype, $m_id) = $peersth->fetchrow_array) {
2555 $reparentsth->execute($prime, $binfo->{master_id}, $peer_id);
2556 # Fix up master_id on free blocks if we're merging a master block
2557 $mfbsth->execute($binfo->{master_id}, $m_id) if $peertype eq 'mm';
2558 # capture block for return
2559 push @retlist, { block => $peercidr, mdisp => $disp_alloctypes{$peertype}, mtype => $peertype };
2560 }
2561
2562 } elsif ($args{scope} =~ /^clear/) {
2563 # clearpeer and clearall share a starting point
2564 # snag the new parent info for the return list
2565 push @retlist, { block => "$newblock", type => $disp_alloctypes{$args{newtype}}, id => $prime };
2566 # update the primary allocation info
2567 $updsth->execute($newblock, $args{newtype}, $prime);
2568 # Reparent the free blocks in the new block
2569 $fbreparentsth->execute($prime, $binfo->{master_id}, $binfo->{city}, $newcontainerclass, $binfo->{vrf},
2570 $binfo->{parent_id}, $newblock);
2571 # Insert a free block if $prime is a leaf
2572 if ($binfo->{type} =~ /.[enr]/) {
2573 $insfbsth->execute($binfo->{block}, $binfo->{city}, $newcontainerclass, $binfo->{vrf}, $prime,
2574 $binfo->{master_id});
2575 }
2576 # delete the peers.
2577 while (my ($peercidr, $peer_id, $peertype, $m_id) = $peersth->fetchrow_array) {
2578 next if $peer_id == $prime;
2579 # push existing allocations down a level before deleting,
2580 # so that when they're deleted the parent info is correct
2581 $reparentsth->execute($prime, $binfo->{master_id}, $peer_id);
2582 _deleteCascade($dbh, $peer_id);
2583 # insert the freeblock _deleteCascade() (deliberately) didn't when deleting a master block.
2584 # aren't special cases fun?
2585 $dbh->do("INSERT INTO freeblocks (cidr,routed,parent_id,master_id) values (?,?,?,?)",
2586 undef, ($peercidr, 'm', $prime, $prime) ) if $binfo->{type} eq 'mm';
2587 # capture block for return
2588 push @retlist, { block => $peercidr, mdisp => $disp_alloctypes{$peertype}, mtype => $peertype };
2589 }
2590 if ($args{scope} eq 'clearall') {
2591 # delete any subs of $prime as well
2592 my $substh = $dbh->prepare("SELECT cidr,id FROM allocations WHERE parent_id = ?");
2593 $substh->execute($prime);
2594 while (my ($scidr, $s_id) = $substh->fetchrow_array) {
2595 _deleteCascade($dbh, $s_id);
2596 }
2597 } else {
2598 # clearpeer
2599 if ($basetype =~ /[dp]/) {
2600 # Convert active IP pool entries to allocations if the original was an IP pool
2601 _poolToAllocations($dbh, $binfo, $pinfo, newtype => $poolmap{$binfo->{type}});
2602 }
2603 } # clearall or clearpeer
2604
2605 } elsif ($args{scope} eq 'mergepeer') { # should this just be an else?
2606 # Default case. Merge "peer" blocks, but keep all suballocations
2607 # snag the new parent info for the return list
2608 push @retlist, {block => "$newblock", type => $disp_alloctypes{$args{newtype}}, id => $prime};
2609 my $substh = $dbh->prepare("UPDATE allocations SET parent_id = ? WHERE parent_id = ?");
2610 my $delsth = $dbh->prepare("DELETE FROM allocations WHERE id = ?");
2611 # Reparent freeblocks in parent
2612 $fbreparentsth->execute($prime, $binfo->{master_id}, $binfo->{city}, $newcontainerclass, $binfo->{vrf},
2613 $binfo->{parent_id}, $newblock);
2614 # Loop over "peer" allocations to be merged
2615 while (my ($peercidr, $peer_id, $peertype, $m_id) = $peersth->fetchrow_array) {
2616 # Snag existing peer data since we may need it
2617 my $peerfull = getBlockData($dbh, $peer_id);
2618 # Reparent free blocks from existing containers
2619 $fbreparentsth->execute($prime, $binfo->{master_id}, $binfo->{city}, $newcontainerclass,
2620 $binfo->{vrf}, $peer_id, $newblock);
2621 # Reparent any subblocks from existing containers
2622 $substh->execute($prime, $peer_id);
2623 # Delete the old container
2624 $delsth->execute($peer_id) unless $peer_id == $prime;
2625 # Add new freeblocks for merged leaf blocks
2626 $insfbsth->execute($peercidr, $binfo->{city}, $newcontainerclass, $binfo->{vrf}, $binfo->{id},
2627 $binfo->{master_id}) if $peertype =~ /.[enr]/;
2628 # Convert pool IPs into allocations or aggregated free blocks
2629 _poolToAllocations($dbh, $peerfull, $pinfo, newparent => $prime) if $peertype =~ /.[dp]/;
2630 # Fix up master_id on free blocks if we're merging a master block
2631 $mfbsth->execute($binfo->{master_id}, $m_id) if $peertype eq 'mm';
2632 # capture block for return
2633 push @retlist, { block => $peercidr, mdisp => $disp_alloctypes{$peertype}, mtype => $peertype };
2634 } # merge peers
2635 # update the primary allocation info. Do this last so we don't stomp extra data-retrieval in the loop above
2636 $updsth->execute($newblock, $args{newtype}, $prime);
2637
2638 } # scope
2639
2640 # Clean up free blocks
2641 _compactFree($dbh, $prime);
2642
2643 } elsif ($args{newtype} =~ /.[dp]/) {
2644 ## Pool
2645 # Snag the new parent info for the return list
2646 push @retlist, { block => "$newblock", type => $disp_alloctypes{$args{newtype}}, id => $prime };
2647
2648 if ($args{scope} eq 'keepall') {
2649 # Convert all mergeable allocations and subs to chunks of pool IP assignments
2650 push @retlist, @{ _toPool($dbh, $prime, $newblock, $args{newtype}, 1) };
2651
2652 } elsif ($args{scope} =~ /^clear/) {
2653 # Clear it all out for a fresh (mostly?) empty IP pool
2654 while (my ($peercidr, $peer_id, $peertype, $m_id) = $peersth->fetchrow_array) {
2655 next if $peer_id == $prime;
2656 # Push existing allocations down a level before deleting,
2657 # so that when they're deleted the parent info is correct
2658 $reparentsth->execute($prime, $binfo->{master_id}, $peer_id);
2659 _deleteCascade($dbh, $peer_id, 0);
2660 # Capture block for return
2661 push @retlist, { block => $peercidr, mdisp => $disp_alloctypes{$peertype}, mtype => $peertype };
2662 }
2663 if ($args{scope} eq 'clearall') {
2664 # Delete any subs of $prime as well
2665 my $substh = $dbh->prepare("SELECT cidr,id FROM allocations WHERE parent_id = ?");
2666 $substh->execute($prime);
2667 while (my ($scidr, $s_id) = $substh->fetchrow_array) {
2668 _deleteCascade($dbh, $s_id);
2669 }
2670 } else {
2671 # Convert (subs of) self if not a leaf.
2672 push @retlist, @{ _toPool($dbh, $prime, $newblock, $args{newtype}, 1) }
2673 unless $binfo->{type} =~ /.[enr]/;
2674 } # scope ne 'clearall'
2675
2676 } elsif ($args{scope} eq 'mergepeer') {
2677 # Try to match behaviour from (target type == container) by deleting immediate peer leaf allocations
2678 while (my ($peercidr, $peer_id, $peertype, $m_id) = $peersth->fetchrow_array) {
2679 next if $peer_id == $prime; # don't delete the block we're turning into the pool allocation
2680 # Capture block for return
2681 push @retlist, { block => $peercidr, mdisp => $disp_alloctypes{$peertype}, mtype => $peertype };
2682 next unless $peertype =~ /.[enr]/;
2683 # Don't need _deleteCascade(), since we'll just be deleting the freshly
2684 # added free block a little later anyway
2685 $delsth->execute($peer_id);
2686 }
2687 # Convert self if not a leaf, to match behaviour with a container type as target
2688 _toPool($dbh, $prime, $newblock, $args{newtype}) unless $binfo->{type} =~ /.[enr]/;
2689 }
2690 # Update the primary allocation info.
2691 $updsth->execute($newblock, $args{newtype}, $prime);
2692 # Delete any lingering free blocks
2693 $dbh->do("DELETE FROM freeblocks WHERE parent_id = ? AND cidr <<= ?", undef, $binfo->{parent_id}, $newblock);
2694 # Fix up the rest of the pool IPs
2695 my ($code,$msg) = initPool($dbh, $newblock, $args{newtype}, $binfo->{city},
2696 ($args{newtype} =~ /.p/ ? 'all' : 'normal'), $prime);
2697
2698 } elsif ($args{newtype} =~ /.[enr]/) {
2699 ## Leaf
2700 # Merging to a leaf type of any kind is, pretty much be definition, scope == 'clearall'.
2701 # keepall, mergepeer, and clearpeer all imply keeping suballocations, where leaf allocations
2702 # by definition do not have suballocations.
2703 # Update the old allocation
2704 $updsth->execute($newblock, $args{newtype}, $prime);
2705 # Snag the new parent info for the return list
2706 push @retlist, {block => "$newblock", type => $disp_alloctypes{$args{newtype}}, id => $prime};
2707 while (my ($peercidr, $peer_id, $peertype, $m_id) = $peersth->fetchrow_array) {
2708 next if $peer_id == $prime;
2709 # Push existing allocations down a level before deleting,
2710 # so that when they're deleted the parent info is correct
2711 $reparentsth->execute($prime, $binfo->{master_id}, $peer_id);
2712 _deleteCascade($dbh, $peer_id, 0);
2713 # Capture block for return
2714 push @retlist, { block => $peercidr, mdisp => $disp_alloctypes{$peertype}, mtype => $peertype };
2715 }
2716 # Delete any subs of $prime as well
2717 my $substh = $dbh->prepare("SELECT cidr,id FROM allocations WHERE parent_id = ?");
2718 $substh->execute($prime);
2719 while (my ($scidr, $s_id) = $substh->fetchrow_array) {
2720 _deleteCascade($dbh, $s_id);
2721 }
2722 # Clean up lingering free blocks and pool IPs
2723 $dbh->do("DELETE FROM freeblocks WHERE cidr <<= ? AND (parent_id = ? OR parent_id = ?)", undef,
2724 $newblock, $binfo->{parent_id}, $prime);
2725 $dbh->do("DELETE FROM poolips WHERE parent_id = ? AND ip <<= ? ", undef,
2726 $prime, $newblock);
2727
2728 } # $args{newtype} if()
2729
2730 $dbh->commit;
2731 };
2732 if ($@) {
2733 my $msg = $@;
2734 $errstr = $msg;
2735 $dbh->rollback;
2736 return ('FAIL',$msg);
2737 }
2738
2739# Make the assumption that any change crossing /24 or /16 boundaries will not come out right. Reverse DNS
2740# updates for this operation are already complex enough without handling those edge cases.
2741# ... er, how do we detect this?
2742
2743 # Return early if the block wasn't flagged as rDNS-able
2744 return \@retlist unless $binfo->{revavail} || $binfo->{revpartial};
2745
2746 if ($args{newtype} =~ /.[cm]/) {
2747
2748 if ($args{scope} eq 'keepall') {
2749 # Add new rDNS for new container
2750 _rpc('addOrUpdateRevRec', cidr => $binfo->{block}, name => $binfo->{rdns}, rpcuser => $args{user});
2751
2752 } else {
2753 # Resize rDNS template for $prime
2754 _rpc('resizeTemplate', oldcidr => "$binfo->{block}", newcidr => $newblock->network.'', rpcuser => $args{user});
2755
2756 # Assemble a list of blocks to delete...
2757 my $cidrlist;
2758 foreach my $mblock (@retlist) {
2759 $cidrlist .= $mblock->{block}."," unless $mblock->{block} =~ $newblock;
2760 }
2761
2762 # ... then make slight variant batch delete calls depending on the merge scope
2763 if ($args{scope} eq 'mergepeer') {
2764 # Delete separate rDNS for other peers
2765 $cidrlist =~ s/,$//;
2766 _rpc('delRevSet', cidrlist => $cidrlist, rpcuser => $args{user}, delforward => 'y', delsubs => 'n',
2767 parpatt => $pinfo->{rdns});
2768
2769 } elsif ($args{scope} eq 'clearpeer') {
2770 # Delete all rDNS within other peers
2771 $cidrlist =~ s/,$//;
2772 _rpc('delRevSet', cidrlist => $cidrlist, rpcuser => $args{user}, delforward => 'y', delsubs => 'y',
2773 parpatt => $pinfo->{rdns})
2774
2775 } elsif ($args{scope} eq 'clearall') {
2776 # Delete all other records within the new block
2777 $cidrlist .= $binfo->{block};
2778 _rpc('delRevSet', cidrlist => $cidrlist, rpcuser => $args{user}, delforward => 'y', delsubs => 'y',
2779 parpatt => $pinfo->{rdns});
2780
2781 } # scope, second level
2782 } # scope, !keepall
2783
2784 } elsif ($args{newtype} =~ /.[dp]/) {
2785 # Merge to pool
2786
2787 # Resize rDNS template for $prime
2788 _rpc('resizeTemplate', oldcidr => "$binfo->{block}", newcidr => $newblock->network.'', rpcuser => $args{user});
2789
2790 if ($args{scope} eq 'keepall' || $args{scope} eq 'mergepeer') {
2791 # Assemble a list of blocks to convert from template to individual records...
2792 my @convlist;
2793 my @dellist;
2794 foreach my $mblock (@retlist) {
2795 next if $mblock->{block} =~ $newblock;
2796 if ($mblock->{mtype} =~ /.[cmdp]/) {
2797 # Container and pool templates get deleted
2798 push @dellist, $mblock->{block};
2799 } else {
2800 # Not-containers get converted to per-IP reverse records
2801 push @convlist, $mblock->{block};
2802 }
2803 }
2804 # And do the calls.
2805 _rpc('delRevSet', cidrlist => join(',', @dellist), rpcuser => $args{user}, delforward => 'y', delsubs => 'n',
2806 parpatt => $pinfo->{rdns});
2807 _rpc('templatesToRecords', templates => \@convlist, rpcuser => $args{user});
2808
2809 } # scope eq 'keepall' || 'mergepeer'
2810 else {
2811
2812 # Assemble a list of blocks to convert from template to individual records...
2813 my @convlist;
2814 my @dellist;
2815 my @fulldellist;
2816# There may be an impossible edge case that can be optimized away in here...
2817 foreach my $mblock (@retlist) {
2818 my $checkcidr = new NetAddr::IP $mblock->{block};
2819 next if $mblock->{block} =~ $newblock;
2820 if (!$block->contains($checkcidr)) {
2821 # Blocks not within the original get deleted
2822 push @fulldellist, $mblock->{block};
2823 }
2824 elsif ($mblock->{mtype} =~ /.[cmdp]/) {
2825 # Containers and pools get deleted
2826 push @dellist, $mblock->{block};
2827 } else {
2828 # Whatever's left over gets converted
2829 push @convlist, $mblock->{block};
2830 }
2831 } # foreach @retlist
2832 # And do the calls.
2833 if ($args{scope} eq 'clearpeer') {
2834 # Not happy doing this many, but there isn't really a better way.
2835 # We delete ALL EVARYTHING in peer blocks...
2836 _rpc('delRevSet', cidrlist => join(',', @fulldellist), rpcuser => $args{user}, delforward => 'y',
2837 delsubs => 'y', parpatt => $pinfo->{rdns}) if @fulldellist;
2838 # ... and just the template for container or pool templates in $prime...
2839 _rpc('delRevSet', cidrlist => join(',', @dellist), rpcuser => $args{user}, delforward => 'y',
2840 delsubs => 'n', parpatt => $pinfo->{rdns}) if @dellist;
2841 # ... and convert a few to record groups
2842 _rpc('templatesToRecords', templates => \@convlist, rpcuser => $args{user}) if @convlist;
2843 }
2844 if ($args{scope} eq 'clearall') {
2845# consider just doing join(',',$newblock->split($newblock->masklen+1))?
2846 _rpc('delRevSet', cidrlist => join(',', @fulldellist, @dellist, @convlist, $binfo->{block}),
2847 rpcuser => $args{user}, delforward => 'y', delsubs => 'y', parpatt => $pinfo->{rdns});
2848 }
2849
2850 } # scope eq 'clearpeer' || 'clearall'
2851
2852 } elsif ($args{newtype} =~ /.[enr]/) {
2853 # Merge to leaf type
2854
2855 # Resize rDNS template for $prime
2856 _rpc('resizeTemplate', oldcidr => "$binfo->{block}", newcidr => $newblock->network.'', rpcuser => $args{user});
2857
2858 # Assemble a list of blocks to delete...
2859 my $cidrlist;
2860 foreach my $mblock (@retlist) {
2861 $cidrlist .= $mblock->{block}."," unless $mblock->{block} =~ $newblock;
2862 }
2863 # Delete all other records within the new block
2864 $cidrlist .= $binfo->{block};
2865 _rpc('delRevSet', cidrlist => $cidrlist, rpcuser => $args{user}, delforward => 'y', delsubs => 'y',
2866 parpatt => $pinfo->{rdns});
2867
2868 } # type grouping for rDNS calls
2869
2870 return \@retlist;
2871
2872} # end mergeBlocks()
2873
2874
2875## IPDB::deleteBlock()
2876# Removes an allocation from the database, including deleting IPs
2877# from poolips and recombining entries in freeblocks if possible
2878# Also handles "deleting" a static IP allocation, and removal of a master
2879# Requires a database handle, the block to delete, the routing depth (if applicable),
2880# the VRF ID, and a flag to indicate whether to delete associated forward DNS entries
2881# as well as the reverse entry
2882sub deleteBlock {
2883 my ($dbh,$id,$basetype,$delfwd,$user) = @_;
2884
2885 # Collect info about the block we're going to delete
2886 my $binfo = getBlockData($dbh, $id, $basetype);
2887 my $cidr = new NetAddr::IP $binfo->{block};
2888
2889# For possible auto-VRF-ignoring (since public IPs shouldn't usually be present in more than one VRF)
2890# is_rfc1918 requires NetAddr::IP >= 4.059
2891# rather than doing this over and over and over.....
2892 my $tmpnum = $cidr->numeric;
2893# 192.168.0.0/16 -> 192.168.255.255 => 3232235520 -> 3232301055
2894# 172.16.0.0/12 -> 172.31.255.255 => 2886729728 -> 2887778303
2895# 10.0.0.0/8 -> 10.255.255.255 => 167772160 -> 184549375
2896 my $isprivnet = (3232235520 <= $tmpnum && $tmpnum <= 3232301055) ||
2897 (2886729728 <= $tmpnum && $tmpnum <= 2887778303) ||
2898 (167772160 <= $tmpnum && $tmpnum <= 184549375);
2899
2900 my $sth;
2901
2902 # Magic variables used for odd allocation cases.
2903 my $container;
2904 my $con_type;
2905
2906
2907 # temporarily forced null, until a sane UI for VRF tracking can be found.
2908# $vrf = '';# if !$vrf; # as with SQL, the null value is not equal to ''. *sigh*
2909
2910 # To contain the error message, if any.
2911 my $msg = "Unknown error deallocating $binfo->{type} $cidr";
2912 my $goback; # to put the parent in so we can link back where the deallocate started
2913
2914 # Enable transactions and exception-on-errors... but only for this sub
2915 local $dbh->{AutoCommit} = 0;
2916 local $dbh->{RaiseError} = 1;
2917
2918 if ($binfo->{type} =~ /^.i$/) {
2919 # First case. The "block" is a static IP
2920 # Note that we still need some additional code in the odd case
2921 # of a netblock-aligned contiguous group of static IPs
2922 my $pinfo;
2923
2924 eval {
2925 $msg = "Unable to deallocate $disp_alloctypes{$binfo->{type}} $cidr";
2926 $pinfo = getBlockData($dbh, $binfo->{parent_id}, 'b');
2927 $dbh->do("UPDATE poolips SET custid = ?, available = 'y',".
2928 "city = (SELECT city FROM allocations WHERE id = ?),".
2929 "description = '', notes = '', circuitid = '', vrf = ?, backup_id = 0".
2930 " WHERE id = ?", undef,
2931 ($pinfo->{custid}, $binfo->{parent_id}, $pinfo->{vrf}, $id) );
2932 $dbh->do("DELETE FROM backuplist WHERE backup_id = ?", undef, $binfo->{hasbk})
2933 if $binfo->{hasbk};
2934 $dbh->commit;
2935 };
2936 if ($@) {
2937 $msg .= ": $@";
2938 eval { $dbh->rollback; };
2939 return ('FAIL',$msg);
2940 }
2941
2942##fixme: RPC return code?
2943 _rpc('delByCIDR', cidr => "$cidr", user => $user, delforward => $delfwd, rpcuser => $user)
2944 if ($pinfo->{revavail} || $pinfo->{revpartial});
2945
2946 return ('OK',"OK");
2947
2948 } elsif ($binfo->{type} eq 'mm') { # end alloctype =~ /.i/
2949 # Second case. The block is a full master block
2950
2951##fixme: VRF limit
2952 $msg = "Unable to delete master block $cidr";
2953 eval {
2954 $dbh->do("DELETE FROM allocations WHERE cidr <<= ? AND master_id = ?", undef, ($cidr, $binfo->{master_id}) );
2955 $dbh->do("DELETE FROM freeblocks WHERE cidr <<= ? AND master_id = ?", undef, ($cidr, $binfo->{master_id}) );
2956 $dbh->do("DELETE FROM backuplist WHERE backup_id = ?", undef, $binfo->{hasbk})
2957 if $binfo->{hasbk};
2958 $dbh->commit;
2959 };
2960 if ($@) {
2961 $msg .= ": $@";
2962 eval { $dbh->rollback; };
2963 return ('FAIL', $msg);
2964 }
2965
2966 # Have to handle potentially split reverse zones. Assume they *are* split,
2967 # since if we added them here, they would have been added split.
2968# allow splitting reverse zones to be disabled, maybe, someday
2969#if ($splitrevzones && !$cidr->{isv6}) {
2970 my @zonelist;
2971 if (1 && !$cidr->{isv6}) {
2972 my $splitpoint = ($cidr->masklen <= 16 ? 16 : 24); # hack pthui
2973 @zonelist = $cidr->split($splitpoint);
2974 } else {
2975 @zonelist = ($cidr);
2976 }
2977 my @fails;
2978 foreach my $subzone (@zonelist) {
2979 # We don't wrap this call tighter, since there isn't an inherent allocation to check for rDNS-ability.
2980 if ($rpc_url && !_rpc('delZone', zone => "$subzone", revrec => 'y', rpcuser => $user, delforward => $delfwd) ) {
2981 push @fails, ("$subzone" => $errstr);
2982 }
2983 }
2984 if (@fails) {
2985 return ('WARN',"Warning(s) deleting $cidr from reverse DNS:\n".join("\n", @fails));
2986 }
2987 return ('OK','OK');
2988
2989 } else { # end alloctype master block case
2990
2991 ## This is a big block; but it HAS to be done in a chunk. Any removal
2992 ## of a netblock allocation may result in a larger chunk of free
2993 ## contiguous IP space - which may in turn be combined into a single
2994 ## netblock rather than a number of smaller netblocks.
2995
2996 my $retcode = 'OK';
2997 my ($ptype,$pcity,$ppatt,$p_id);
2998
2999 eval {
3000
3001##fixme: add recursive flag to allow "YES DAMMIT DELETE ALL EVARYTHING!!1!!" without
3002# explicitly deleting any suballocations of the block to be deleted.
3003
3004 # get parent info of the block we're deleting
3005 my $pinfo = getBlockData($dbh, $binfo->{parent_id});
3006 $ptype = $pinfo->{type};
3007 $pcity = $pinfo->{city};
3008 $ppatt = $pinfo->{rdns};
3009 $p_id = $binfo->{parent_id};
3010
3011 # Delete the block
3012 $dbh->do("DELETE FROM allocations WHERE id = ?", undef, ($id) );
3013
3014 # munge the parent type a little
3015 $ptype = (split //, $ptype)[1];
3016
3017##fixme: you can't... CAN NOT.... assign the same public IP to multiple things.
3018# 'Net don't work like that, homey. Restrict VRF-uniqueness to private IPs?
3019# -> $isprivnet flag from start of sub
3020
3021 # check to see if any container allocations could be the "true" parent
3022 my ($tparent,$tpar_id,$trtype,$tcity);
3023 $tpar_id = 0;
3024
3025##fixme: this is far simpler in the strict VRF case; we "know" that any allocation
3026# contained by a container is a part of the same allocation tree when the VRF fields are equal.
3027
3028# logic:
3029# For each possible container of $cidr
3030# note the parent id
3031# walk the chain up the parents
3032# if we intersect $cidr's current parent, break
3033# if we've intersected $cidr's current parent
3034# set some variables to track that block
3035# break
3036
3037# Set up part of "is it in the middle of a pool?" check
3038 my $wuzpool = $dbh->selectrow_hashref("SELECT cidr,parent_id,type,city,custid,id FROM allocations ".
3039 "WHERE (type LIKE '_d' OR type LIKE '_p') AND cidr >> ? AND master_id = ?", { Slice => {} },
3040 ($cidr, $binfo->{master_id}) );
3041
3042##fixme?
3043# edge cases not handled, or handled badly:
3044# -> $cidr managed to get to be the entirety of an IP pool
3045
3046 if ($wuzpool && $wuzpool->{id} != $id) {
3047 # we have legacy goo to be purified
3048 # going to ignore nested pools; not possible to create them via API and no current legacy data includes any.
3049
3050 # for convenience
3051 my $poolid = $wuzpool->{id};
3052 my $pool = $wuzpool->{cidr};
3053 my $poolcity = $wuzpool->{city};
3054 my $pooltype = $wuzpool->{type};
3055 my $poolcustid = $wuzpool->{custid};
3056
3057 $retcode = 'WARNPOOL';
3058 $goback = "$poolid,$pool";
3059 # We've already deleted the block, now we have to stuff its IPs into the pool.
3060 $pooltype =~ s/[dp]$/i/; # change type to static IP
3061 my $sth2 = $dbh->prepare("INSERT INTO poolips (ip,city,type,custid,parent_id) VALUES ".
3062 "(?,'$poolcity','$pooltype','$poolcustid',$poolid)");
3063
3064##fixme: need to not insert net, gateway, and bcast on "real netblock" pools (DHCPish)
3065 # don't insert .0
3066 $sth2->execute($cidr->addr) unless $cidr->addr =~ m|\.0$|;
3067 $cidr++;
3068 my $bcast = $cidr->broadcast;
3069 while ($cidr != $bcast) {
3070 $sth2->execute($cidr->addr);
3071 $cidr++;
3072 }
3073 # don't insert .255
3074 $sth2->execute($cidr->addr) unless $cidr->addr =~ m|\.255$|;
3075
3076# Weirdness Happens. $cidr goes read-only somewhere (this is a thing?!?),
3077# causing ->split, ->hostenum, and related methods to explode. O_o
3078# foreach my $ip ($cidr->hostenum) {
3079# $sth2->execute($ip);
3080# }
3081
3082 }
3083
3084## important!
3085# ... or IS IT?
3086# we may have undef'ed $wuzpool above, if the allocation tree $cidr is in doesn't intersect the pool we found
3087#if (!$wuzpool) {
3088
3089 else {
3090
3091# Edge case: Block is the same size as more than one parent level. Should be rare.
3092# - mainly master + first routing. Sorting on parent_id hides the problem pretty well,
3093# but it's likely still possible to fail in particularly well-mangled databases.
3094# The ultimate fix for this may be to resurrect the "routing depth" atrocity. :/
3095 # Get all possible (and probably a number of impossible) containers for $cidr
3096 $sth = $dbh->prepare("SELECT cidr,parent_id,type,city,id FROM allocations ".
3097 "WHERE (type LIKE '_m' OR type LIKE '_c') AND cidr >>= ? AND master_id = ? ".
3098 "ORDER BY masklen(cidr) DESC,parent_id DESC");
3099 $sth->execute($cidr, $binfo->{master_id});
3100
3101 # Quickly get certain fields (simpler than getBlockData()
3102 my $sth2 = $dbh->prepare("SELECT cidr,parent_id,type,city FROM allocations ".
3103 "WHERE (type LIKE '_m' OR type LIKE '_c') AND id = ? AND master_id = ?");
3104
3105 # For each possible container of $cidr...
3106 while (my @data = $sth->fetchrow_array) {
3107 my $i = 0;
3108 # Save some state and set a start point - parent ID of container we're checking
3109 $tparent = $data[0];
3110 my $ppid = $data[1];
3111 $trtype = $data[2];
3112 $tcity = $data[3];
3113 $tpar_id = $data[4];
3114 last if $data[4] == $binfo->{parent_id}; # Preemptively break if we're already in the right place
3115 last if $ppid == $binfo->{parent_id}; # ... or if the parent of the container is the block's parent
3116 while (1) {
3117 # Retrieve bits on that parent ID
3118 $sth2->execute($ppid, $binfo->{master_id});
3119 my @container = $sth2->fetchrow_array;
3120 $ppid = $container[1];
3121 last if $container[1] == 0; # Break if we've hit a master block
3122 last if $ppid == $binfo->{parent_id}; # Break if we've reached the block $cidr is currently in
3123 }
3124 last if $ppid == $binfo->{parent_id};
3125 }
3126
3127 # found an alternate parent; reset some parent-info bits
3128 if ($tpar_id != $binfo->{parent_id}) {
3129 $ptype = (split //, $trtype)[1];
3130 $pcity = $tcity;
3131 $retcode = 'WARNMERGE'; # may be redundant
3132 $p_id = $tpar_id;
3133 }
3134
3135 $goback = "$p_id,$tparent"; # breadcrumb, currently only used in case of live-parent-is-not-true-parent
3136
3137 # Special case - delete pool IPs
3138 if ($binfo->{type} =~ /^.[pd]$/) {
3139 # We have to delete the IPs from the pool listing.
3140##fixme: rdepth? vrf?
3141 $dbh->do("DELETE FROM poolips WHERE parent_id = ?", undef, ($id) );
3142 }
3143
3144 $pinfo = getBlockData($dbh, $p_id);
3145
3146 # If the block wasn't legacy goo embedded in a static pool, we check the
3147 # freeblocks in the identified parent to see if we can combine any of them.
3148
3149 # if the block to be deleted is a container, move its freeblock(s) up a level, and reset their parenting info
3150 if ($binfo->{type} =~ /^.[mc]/) {
3151 # move the freeblocks into the parent
3152 # we don't insert a new freeblock because there could be a live reparented sub.
3153 $dbh->do("UPDATE freeblocks SET parent_id = ?, routed = ?, city = ? WHERE parent_id = ?", undef,
3154 ($p_id, $ptype, $pcity, $id) );
3155 } else {
3156 # ... otherwise, add the freeblock
3157 $dbh->do("INSERT INTO freeblocks (cidr, city, routed, parent_id, master_id) VALUES (?,?,?,?,?)", undef,
3158 ($cidr, $pcity, $ptype, $p_id, $binfo->{master_id}) );
3159 }
3160
3161 # Walk the free blocks in the parent and reduce them to the minimal set of CIDR ranges necessary
3162 _compactFree($dbh, $p_id);
3163
3164 } # done returning IPs to the appropriate place
3165
3166 # If we got here, we've succeeded. Whew!
3167 $dbh->commit;
3168 }; # end eval
3169 if ($@) {
3170 $msg .= ": $@";
3171 eval { $dbh->rollback; };
3172 return ('FAIL', $msg);
3173 }
3174
3175##fixme: RPC return code?
3176 _rpc('delByCIDR', cidr => "$cidr", rpcuser => $user, delforward => $delfwd, delsubs => 'y', parpatt => $ppatt)
3177 if ($binfo->{revavail} || $binfo->{revpartial});
3178
3179 return ($retcode, $goback);
3180
3181 } # end alloctype != netblock
3182
3183} # end deleteBlock()
3184
3185
3186## IPDB::getBlockData()
3187# Get CIDR or IP, custid, type, city, circuit ID, description, notes, modification time,
3188# private/restricted data, and backup fields, for a CIDR block or pool IP
3189# Also returns SWIP status flag for CIDR blocks or pool netblock for IPs
3190# Takes the block ID or IP to look up and an optional flag to indicate a pool IP lookup
3191# instead of a netblock.
3192# Returns a hashref to the block data
3193sub getBlockData {
3194 my $dbh = shift;
3195 my $id = shift;
3196 my $type = shift || 'b'; # default to netblock for lazy callers
3197
3198 # netblocks are in the allocations table; pool IPs are in the poolips table.
3199 # If we try to look up a CIDR in an integer field we should just get back nothing.
3200 my ($btype) = $dbh->selectrow_array("SELECT type FROM allocations WHERE id=?", undef, ($id) );
3201
3202 # Note city, vrf, parent_id and master_id removed due to JOIN uncertainty for block allocations
3203 my $commonfields = q(a.custid, a.type, a.circuitid, a.description, a.notes, a.modifystamp AS lastmod,
3204 a.privdata, a.vlan, a.rdns);
3205 my $bkfields = q(b.backup_id AS hasbk, b.bkbrand, b.bkmodel, b.bktype, b.bkport, b.bksrc,
3206 b.bkuser, b.bkvpass, b.bkepass, b.bkip);
3207
3208 if ($type eq 'i') {
3209 my $binfo = $dbh->selectrow_hashref(qq(
3210 SELECT a.id, a.ip AS block, a.city, a.vrf, a.parent_id, a.master_id, $commonfields,
3211 d.zone >> a.ip AS revavail,
3212 $bkfields,
3213 v.location
3214 FROM poolips a
3215 LEFT JOIN dnsavail d ON a.master_id = d.parent_alloc AND a.ip << d.zone
3216 LEFT JOIN backuplist b ON a.backup_id = b.backup_id
3217 JOIN allocations m ON a.master_id = m.id JOIN vrfs v ON m.vrf = v.vrf
3218 WHERE a.id = ?
3219 ), undef, ($id) );
3220 return $binfo;
3221 } else {
3222 my $binfo = $dbh->selectrow_hashref(qq(
3223 SELECT a.id, a.cidr AS block, a.city, a.vrf, a.parent_id, a.master_id, a.swip, $commonfields,
3224 f.cidr AS reserve, f.id as reserve_id,
3225 d.zone >>= a.cidr AS revavail, d.zone << a.cidr AS revpartial,
3226 $bkfields,
3227 v.location
3228 FROM allocations a
3229 LEFT JOIN freeblocks f ON a.id=f.reserve_for
3230 LEFT JOIN dnsavail d ON a.master_id = d.parent_alloc AND (a.cidr <<= d.zone OR a.cidr >> d.zone)
3231 LEFT JOIN backuplist b ON a.backup_id = b.backup_id
3232 JOIN allocations m ON a.master_id = m.id JOIN vrfs v ON m.vrf = v.vrf
3233 WHERE a.id = ?
3234 ), undef, ($id) );
3235
3236 return $binfo;
3237 }
3238} # end getBlockData()
3239
3240
3241## IPDB::getBlockRDNS()
3242# Gets reverse DNS pattern for a block or IP. Note that this will also
3243# retrieve any default pattern following the parent chain up, and check via
3244# RPC (if available) to see what the narrowest pattern for the requested block is
3245# Returns the current pattern for the block or IP.
3246sub getBlockRDNS {
3247 my $dbh = shift;
3248 my %args = @_;
3249
3250 $args{type} = 'b' if !$args{type};
3251 my $cached = 1;
3252
3253 # snag entry from database
3254 my ($rdns,$rfrom,$pid);
3255 if ($args{type} =~ /.i/) {
3256 ($rdns, $rfrom, $pid) = $dbh->selectrow_array("SELECT rdns,ip,parent_id FROM poolips WHERE id = ?",
3257 undef, ($args{id}) );
3258 } else {
3259 ($rdns, $rfrom, $pid) = $dbh->selectrow_array("SELECT rdns,cidr,parent_id FROM allocations WHERE id = ?",
3260 undef, ($args{id}) );
3261 }
3262
3263 # Can't see a way this could end up empty, for any case I care about. If the caller
3264 # doesn't know an allocation ID to request, then they don't know anything else anyway.
3265 my $selfblock = $rfrom;
3266
3267 my $type;
3268 while (!$rdns && $pid) {
3269 ($rdns, $rfrom, $pid, $type) = $dbh->selectrow_array(
3270 "SELECT rdns,cidr,parent_id,type FROM allocations WHERE id = ?",
3271 undef, ($pid) );
3272 last if $type eq 'mm'; # break loops in unfortunate legacy data
3273 }
3274
3275 # use the actual allocation to check against the DNS utility; we don't want
3276 # to always go chasing up the chain to the master... which may (usually won't)
3277 # be present directly in DNS anyway
3278 my $cidr = new NetAddr::IP $selfblock;
3279
3280 if ($rpc_url) {
3281 # Use the first /16 or /24, rather than dithering over which sub-/14 /16
3282 # or sub-/19 /24 to retrieve - it's the least-wrong way to do things.
3283
3284 my ($rpcblock) = ($cidr->masklen <= 24 ? $cidr->split( ($cidr->masklen <= 16 ? 16 : 24) ) : $cidr);
3285 my %rpcargs = (
3286 rpcuser => $args{user},
3287 group => $revgroup, # not sure how this could sanely be exposed, tbh...
3288 cidr => "$rpcblock",
3289 );
3290
3291 $errstr = '';
3292 my $remote_rdns = _rpc('getRevPattern', %rpcargs);
3293 if ($remote_rdns) {
3294 $rdns = $remote_rdns;
3295 $cached = 0;
3296 } else {
3297 if (!$errstr) {
3298 # no error, but no data
3299 $cached = 0;
3300 }
3301 }
3302 }
3303
3304 # hmm. do we care about where it actually came from?
3305 return $rdns, $cached;
3306} # end getBlockRDNS()
3307
3308
3309## IPDB::getRDNSbyIP()
3310# Get individual reverse entries for the IP or CIDR IP range passed. Sort of looking the
3311# opposite direction down the netblock tree compared to getBlockRDNS() above.
3312sub getRDNSbyIP {
3313 my $dbh = shift;
3314 my %args = @_; # We want to accept a variety of call types
3315
3316 # key arguments: allocation ID, type
3317 unless ($args{id} || $args{type}) {
3318 $errstr = 'Missing allocation ID or type';
3319 return;
3320 }
3321
3322 my @ret = ();
3323 # special case: single IP. Check if it's an allocation or in a pool, then do the RPC call for fresh data.
3324 if ($args{type} =~ /^.i$/) {
3325 my ($ip, $localrev) = $dbh->selectrow_array("SELECT ip, rdns FROM poolips WHERE id = ?", undef, ($args{id}) );
3326 push @ret, { 'r_ip' => $ip, 'iphost' => $localrev };
3327 } else {
3328 if ($rpc_url) {
3329 my %rpcargs = (
3330 rpcuser => $args{user},
3331 group => $revgroup, # not sure how this could sanely be exposed, tbh...
3332 cidr => $args{range},
3333 );
3334
3335 my $remote_rdns = _rpc('getRevSet', %rpcargs);
3336 return $remote_rdns;
3337# $rdns = $remote_rdns if $remote_rdns;
3338# $cached = 0;
3339 }
3340 }
3341 return \@ret;
3342} # end getRDNSbyIP()
3343
3344
3345## IPDB::getNodeList()
3346# Gets a list of node ID+name pairs as an arrayref to a list of hashrefs
3347sub getNodeList {
3348 my $dbh = shift;
3349
3350 my $ret = $dbh->selectall_arrayref("SELECT node_id, node_name FROM nodes ORDER BY node_type,node_id",
3351 { Slice => {} });
3352 return $ret;
3353} # end getNodeList()
3354
3355
3356## IPDB::getNodeName()
3357# Get node name from the ID
3358sub getNodeName {
3359 my $dbh = shift;
3360 my $nid = shift;
3361
3362 my ($nname) = $dbh->selectrow_array("SELECT node_name FROM nodes WHERE node_id = ?", undef, ($nid) );
3363 return $nname;
3364} # end getNodeName()
3365
3366
3367## IPDB::getNodeInfo()
3368# Get node name and ID associated with a block
3369sub getNodeInfo {
3370 my $dbh = shift;
3371 my $block = shift;
3372
3373 my ($nid, $nname) = $dbh->selectrow_array("SELECT nodes.node_id,node_name FROM nodes INNER JOIN noderef".
3374 " ON nodes.node_id=noderef.node_id WHERE noderef.block = ?", undef, ($block) );
3375 return ($nid, $nname);
3376} # end getNodeInfo()
3377
3378
3379## IPDB::mailNotify()
3380# Sends notification mail to recipients regarding an IPDB operation
3381sub mailNotify {
3382 my $dbh = shift;
3383 my ($action,$subj,$message) = @_;
3384
3385 return if $smtphost eq 'smtp.example.com'; # do nothing if still using default SMTP host.
3386
3387##fixme: need to redesign the breakdown/processing for $action for proper handling of all cases
3388
3389# split action into parts for fiddlement. nb: there are almost certainly better ways to do this.
3390 my @actionbits = split //, $action;
3391
3392 # want to notify anyone who has specifically requested notify on *this* type ($action as passed),
3393 # on "all static IP types" or "all pool types" (and other last-char-in-type groupings), on eg "all DSL types",
3394 # and "all events with this action"
3395 my @actionsets = ($action);
3396##fixme: ick, eww. really gotta find a better way to handle this...
3397 push @actionsets, ($actionbits[0].'.'.$actionbits[2],
3398 $actionbits[0].$actionbits[1].'.', $actionbits[0].'a') if $action =~ /^.{3}$/;
3399
3400 my $mailer = Net::SMTP->new($smtphost, Hello => "ipdb.$domain");
3401
3402 # get recip list from db
3403 my $sth = $dbh->prepare("SELECT reciplist FROM notify WHERE action=?");
3404
3405 my %reciplist;
3406 foreach (@actionsets) {
3407 $sth->execute($_);
3408##fixme - need to handle db errors
3409 my ($recipsub) = $sth->fetchrow_array;
3410 next if !$recipsub;
3411 foreach (split(/,/, $recipsub)) {
3412 $reciplist{$_}++;
3413 }
3414 }
3415
3416 return if !%reciplist;
3417
3418 foreach my $recip (keys %reciplist) {
3419 $mailer->mail($smtpsender);
3420 $mailer->to($recip);
3421 $mailer->data("From: \"$org_name IP Database\" <$smtpsender>\n",
3422 "To: $recip\n",
3423 "Date: ".strftime("%a, %d %b %Y %H:%M:%S %z",localtime)."\n",
3424 "Subject: {IPDB} $subj\n",
3425 "X-Mailer: IPDB Notify v".sprintf("%.1d",$IPDB::VERSION)."\n",
3426 "Organization: $org_name\n",
3427 "\n$message\n");
3428 }
3429 $mailer->quit;
3430}
3431
3432# Indicates module loaded OK. Required by Perl.
34331;
Note: See TracBrowser for help on using the repository browser.