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

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

/trunk

Further tweak splitBlock() to handle a contained block the same size as
its container - may be a common case in legacy data. Still leaves more
deeply nested same-sized container trees hanging but those should be
rare enough than manual intervention can patch it up well enough. See #7.

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