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

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

/trunk

Extend UI to browse into a VRF. See #54.
Also extend breadcrumb segment to show the VRF.

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