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

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

/trunk

Add getVRF() to retrieve default location for the add new master page. See #54.

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