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

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

/trunk

"add VRF" action etc. See #54.

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