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

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

/trunk

Promote VRFs to top-level entities. See #54.

1 of mumble; convert index page to list VRFs instead of master blocks.

  • Property svn:keywords set to Date Rev Author
File size: 125.6 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-07 23:05:24 +0000 (Mon, 07 Mar 2016) $
6# SVN revision $Rev: 806 $
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;
1394 my @result;
1395
1396 my $sth = $dbh-> prepare("SELECT cidr,type,id,parent_id FROM allocations WHERE id=?");
1397
1398 while ($parent != 0) {
1399 $sth->execute($parent);
1400 my ($cidr,$type,$id,$pid) = $sth->fetchrow_array;
1401 push @result, {cidr => $cidr, link => $id, ispool => ($type =~ /^.[dp]$/ ? 1 : 0)};
1402 $parent = $pid;
1403 }
1404
1405 return \@result;
1406} # end getBread()
1407
1408
1409## IPDB::getRoutedCity()
1410# Get the city for a routed block.
1411sub getRoutedCity {
1412 my $dbh = shift;
1413 my $block = shift;
1414
1415 my ($rcity) = $dbh->selectrow_array("SELECT city FROM routed WHERE cidr = ?", undef, ($block) );
1416 return $rcity;
1417} # end getRoutedCity()
1418
1419
1420## IPDB::allocateBlock()
1421# Does all of the magic of actually allocating a netblock
1422# Requires a database handle, and a hash containing the block to allocate, routing depth, custid,
1423# type, city, block to allocate from, and optionally a description, notes, circuit ID,
1424# and private data
1425# Returns a success code and optional error message.
1426sub allocateBlock {
1427 my $dbh = shift;
1428
1429 my %args = @_;
1430
1431 if ($args{cidr} eq 'Single static IP') {
1432 $args{cidr} = '';
1433 } else {
1434 $args{cidr} = new NetAddr::IP $args{cidr};
1435 }
1436
1437 $args{desc} = '' if !$args{desc};
1438 $args{notes} = '' if !$args{notes};
1439 $args{circid} = '' if !$args{circid};
1440 $args{privdata} = '' if !$args{privdata};
1441 $args{vrf} = '' if !$args{vrf};
1442 $args{vlan} = '' if !$args{vlan};
1443 $args{rdns} = '' if !$args{rdns};
1444
1445 # Could arguably allow this for eg /120 allocations, but end users who get a single v4 IP are
1446 # usually given a v6 /64, and most v6 addressing schemes need at least half that address space
1447 if ($args{cidr} && $args{cidr}->{isv6} && $args{rdns} =~ /\%/) {
1448 return ('FAIL','Reverse DNS template patterns are not supported for IPv6 allocations');
1449 }
1450
1451 my $sth;
1452
1453 # Snag the "type" of the freeblock and its CIDR
1454 my ($alloc_from_type, $alloc_from, $fbparent, $fcity, $fbmaster) =
1455 $dbh->selectrow_array("SELECT routed,cidr,parent_id,city,master_id FROM freeblocks WHERE id = ?",
1456 undef, $args{fbid});
1457 $alloc_from = new NetAddr::IP $alloc_from;
1458 return ('FAIL',"Failed to allocate $args{cidr}; intended free block was used by another allocation.")
1459 if ($args{type} !~ /.i/ && !$fbparent);
1460##fixme: fail here if !$alloc_from
1461# also consider "lock for allocation" due to multistep allocation process
1462
1463 # To contain the error message, if any.
1464 my $msg = "Unknown error allocating $args{cidr} as '$disp_alloctypes{$args{type}}'";
1465
1466 # Enable transactions and error handling
1467 local $dbh->{AutoCommit} = 0; # These need to be local so we don't
1468 local $dbh->{RaiseError} = 1; # step on our toes by accident.
1469
1470 if ($args{type} =~ /^.i$/) {
1471 $msg = "Unable to assign static IP $args{cidr} to $args{custid}";
1472 eval {
1473 if ($args{cidr}) { # IP specified
1474 my ($isavail) = $dbh->selectrow_array("SELECT available FROM poolips WHERE ip=?", undef, ($args{cidr}) );
1475 die "IP is not in an IP pool.\n"
1476 if !$isavail;
1477 die "IP already allocated. Deallocate and reallocate, or update the entry\n"
1478 if $isavail eq 'n';
1479 } else { # IP not specified, take first available
1480 ($args{cidr}) = $dbh->selectrow_array("SELECT ip FROM poolips WHERE parent_id=? AND available='y' ORDER BY ip",
1481 undef, ($args{parent}) );
1482 }
1483
1484 # backup
1485 my $backupid = 0;
1486 if ($args{backup}) {
1487 my $bksql = "INSERT INTO backuplist (";
1488 my @bkvals;
1489 my @bkfields;
1490 for my $bk (@backupfields) {
1491 if ($args{"bk$bk"}) {
1492 push @bkfields, "bk$bk";
1493 push @bkvals, $args{"bk$bk"};
1494 }
1495 }
1496 $bksql .= join(',',@bkfields).") VALUES (".join(',', map {'?'} @bkfields).")";
1497 $dbh->do($bksql, undef, @bkvals);
1498 ($backupid) = $dbh->selectrow_array("SELECT currval('backuplist_backup_id_seq')");
1499 }
1500
1501 # finally assign the IP
1502 $dbh->do("UPDATE poolips SET custid = ?, city = ?, available='n', description = ?, notes = ?, ".
1503 "circuitid = ?, privdata = ?, vrf = ?, rdns = ?, backup_id = ? ".
1504 "WHERE ip = ? AND parent_id = ?", undef,
1505 ($args{custid}, $args{city}, $args{desc}, $args{notes},
1506 $args{circid}, $args{privdata}, $args{vrf}, $args{rdns}, $backupid,
1507 $args{cidr}, $args{parent}) );
1508
1509# node hack
1510 if ($args{nodeid} && $args{nodeid} ne '') {
1511 $dbh->do("INSERT INTO noderef (block,node_id) VALUES (?,?)", undef, ($args{cidr}, $args{nodeid}) );
1512 }
1513# end node hack
1514
1515 $dbh->commit; # Allocate IP from pool
1516 };
1517 if ($@) {
1518 $msg .= ": $@";
1519 eval { $dbh->rollback; };
1520 return ('FAIL', $msg);
1521 } else {
1522 # Snag the pool info
1523 my $pinfo = getBlockData($dbh, $args{parent});
1524 # Only try to update rDNS when the pool is flagged as "rDNS available"
1525 if ($pinfo->{revavail} || $pinfo->{revpartial}) {
1526 _rpc('addOrUpdateRevRec', cidr => "$args{cidr}", name => $args{rdns}, rpcuser => $args{user});
1527 }
1528 return ('OK', $args{cidr});
1529 }
1530
1531 } else { # end IP-from-pool allocation
1532
1533 if ($args{cidr} == $alloc_from) {
1534 # Easiest case- insert in one table, delete in the other, and go home. More or less.
1535
1536 eval {
1537 $msg = "Unable to allocate $args{cidr} as '$disp_alloctypes{$args{type}}'";
1538
1539 # backup
1540 my $backupid = 0;
1541 if ($args{backup}) {
1542 if (!$args{bkip}) {
1543 # check for /32-ness. no point in skipping /32 "netblocks", because they already single IPs
1544 die "Backup data set on a netblock requires a backup IP\n" unless $args{cidr} =~ m{/32$};
1545 $args{bkip} = $args{cidr};
1546 }
1547 my $bksql = "INSERT INTO backuplist (";
1548 my @bkfields;
1549 my @bkvals;
1550 for my $bk (@backupfields) {
1551 if ($args{"bk$bk"}) {
1552 push @bkfields, "bk$bk";
1553 push @bkvals, $args{"bk$bk"};
1554 }
1555 }
1556 $bksql .= join(',',@bkfields).") VALUES (".join(',',map {'?'} @bkfields).")";
1557 $dbh->do($bksql, undef, @bkvals);
1558 ($backupid) = $dbh->selectrow_array("SELECT currval('backuplist_backup_id_seq')");
1559 } # $args{backup}
1560
1561 # Insert the allocations entry
1562 $dbh->do("INSERT INTO allocations ".
1563 "(cidr,parent_id,master_id,vrf,vlan,custid,type,city,description,notes,circuitid,privdata,rdns,backup_id)".
1564 " VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)", undef,
1565 ($args{cidr}, $fbparent, $fbmaster, $args{vrf}, $args{vlan}, $args{custid}, $args{type}, $args{city},
1566 $args{desc}, $args{notes}, $args{circid}, $args{privdata}, $args{rdns}, $backupid) );
1567 my ($bid) = $dbh->selectrow_array("SELECT currval('allocations_id_seq')");
1568
1569 # Munge freeblocks
1570 if ($args{type} =~ /^(.)[mc]$/) {
1571 # special case - block is a routed or container/"reserve" block
1572 my $rtype = $1;
1573 $dbh->do("UPDATE freeblocks SET routed = ?,city = ?,parent_id = ? WHERE id = ?",
1574 undef, ($rtype, $args{city}, $bid, $args{fbid}) );
1575 } else {
1576 # "normal" case
1577 $dbh->do("DELETE FROM freeblocks WHERE id = ?", undef, ($args{fbid}) );
1578 }
1579
1580 # And initialize the pool, if necessary
1581 # PPPoE pools (currently dialup, DSL, and WiFi) get all IPs made available
1582 # "DHCP" or "real-subnet" pools have the net, gw, and bcast IPs removed.
1583 if ($args{type} =~ /^.p$/) {
1584 $msg = "Could not initialize IPs in new $disp_alloctypes{$args{type}} $args{cidr}";
1585 my ($code,$rmsg) = initPool($dbh, $args{cidr}, $args{type}, $args{city}, "all", $bid);
1586 die $rmsg if $code eq 'FAIL';
1587 } elsif ($args{type} =~ /^.d$/) {
1588 $msg = "Could not initialize IPs in new $disp_alloctypes{$args{type}} $args{cidr}";
1589 my ($code,$rmsg) = initPool($dbh, $args{cidr}, $args{type}, $args{city}, "normal", $bid);
1590 die $rmsg if $code eq 'FAIL';
1591 }
1592
1593# node hack
1594 if ($args{nodeid} && $args{nodeid} ne '') {
1595 $dbh->do("INSERT INTO noderef (block,node_id) VALUES (?,?)", undef, ($args{cidr}, $args{nodeid}) );
1596 }
1597# end node hack
1598
1599 $dbh->commit; # Simple block allocation
1600 }; # end of eval
1601 if ($@) {
1602 $msg .= ": ".$@;
1603 eval { $dbh->rollback; };
1604 return ('FAIL',$msg);
1605 }
1606
1607 } else { # cidr != alloc_from
1608
1609 # Hard case. Allocation is smaller than free block.
1610
1611 # make sure new allocation is in fact within freeblock. *sigh*
1612 return ('FAIL',"Requested allocation $args{cidr} is not within $alloc_from")
1613 if !$alloc_from->contains($args{cidr});
1614 my $wantmaskbits = $args{cidr}->masklen;
1615 my $maskbits = $alloc_from->masklen;
1616
1617 my @newfreeblocks; # Holds free blocks generated from splitting the source freeblock.
1618
1619 # This determines which blocks will be left "free" after allocation. We take the
1620 # block we're allocating from, and split it in half. We see which half the wanted
1621 # block is in, and repeat until the wanted block is equal to one of the halves.
1622 my $i=0;
1623 my $tmp_from = $alloc_from; # So we don't munge $args{alloc_from}
1624 while ($maskbits++ < $wantmaskbits) {
1625 my @subblocks = $tmp_from->split($maskbits);
1626 $newfreeblocks[$i++] = (($args{cidr}->within($subblocks[0])) ? $subblocks[1] : $subblocks[0]);
1627 $tmp_from = ( ($args{cidr}->within($subblocks[0])) ? $subblocks[0] : $subblocks[1] );
1628 } # while
1629
1630 # Begin SQL transaction block
1631 eval {
1632 $msg = "Unable to allocate $args{cidr} as '$disp_alloctypes{$args{type}}'";
1633
1634 # Delete old freeblocks entry
1635 $dbh->do("DELETE FROM freeblocks WHERE id = ?", undef, ($args{fbid}) );
1636
1637 # Insert the allocations entry
1638 $dbh->do("INSERT INTO allocations ".
1639 "(cidr,parent_id,master_id,vrf,vlan,custid,type,city,description,notes,circuitid,privdata,rdns)".
1640 " VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)", undef,
1641 ($args{cidr}, $fbparent, $fbmaster, $args{vrf}, $args{vlan}, $args{custid}, $args{type}, $args{city},
1642 $args{desc}, $args{notes}, $args{circid}, $args{privdata}, $args{rdns}) );
1643 my ($bid) = $dbh->selectrow_array("SELECT currval('allocations_id_seq')");
1644
1645 # Insert new list of smaller free blocks left over. Flag the one that matches the
1646 # masklength of the new allocation, if a reserve block was requested.
1647 $sth = $dbh->prepare("INSERT INTO freeblocks (cidr,city,routed,vrf,parent_id,master_id,reserve_for) ".
1648 "VALUES (?,?,?,?,?,?,?)");
1649 foreach my $block (@newfreeblocks) {
1650 $sth->execute($block, $fcity, $alloc_from_type, $args{vrf}, $fbparent, $fbmaster,
1651 ($args{reserve} && $block->masklen == $wantmaskbits ? $bid : 0));
1652 }
1653
1654 # For routed/container types, add a freeblock within the allocated block so we can subdivide it further
1655 if ($args{type} =~ /(.)[mc]/) { # rm and .c types - containers
1656 my $rtype = $1;
1657 $sth->execute($args{cidr}, $args{city}, $rtype, $args{vrf}, $bid, $fbmaster, 0);
1658 }
1659
1660 # And initialize the pool, if necessary
1661 # PPPoE pools (currently dialup, DSL, and WiFi) get all IPs made available
1662 # "DHCP" or "real-subnet" pools have the net, gw, and bcast IPs removed.
1663 if ($args{type} =~ /^.p$/) {
1664 $msg = "Could not initialize IPs in new $disp_alloctypes{$args{type}} $args{cidr}";
1665 my ($code,$rmsg) = initPool($dbh, $args{cidr}, $args{type}, $args{city}, "all", $bid);
1666 die $rmsg if $code eq 'FAIL';
1667 } elsif ($args{type} =~ /^.d$/) {
1668 $msg = "Could not initialize IPs in new $disp_alloctypes{$args{type}} $args{cidr}";
1669 my ($code,$rmsg) = initPool($dbh, $args{cidr}, $args{type}, $args{city}, "normal", $bid);
1670 die $rmsg if $code eq 'FAIL';
1671 }
1672
1673# node hack
1674 if ($args{nodeid} && $args{nodeid} ne '') {
1675 $dbh->do("INSERT INTO noderef (block,node_id) VALUES (?,?)", undef, ($args{cidr}, $args{nodeid}) );
1676 }
1677# end node hack
1678
1679 $dbh->commit; # Complex block allocation
1680 }; # end eval
1681 if ($@) {
1682 $msg .= ": ".$@;
1683 eval { $dbh->rollback; };
1684 return ('FAIL',$msg);
1685 }
1686
1687 } # end fullcidr != alloc_from
1688
1689 # Snag the parent info
1690 my $pinfo = getBlockData($dbh, $fbparent);
1691 # Only try to update rDNS when the pool is flagged as "rDNS available"
1692 if ($pinfo->{revavail} || $pinfo->{revpartial}) {
1693 # now we do the DNS dance for netblocks, if we have an RPC server to do it with and a pattern to use.
1694 _rpc('addOrUpdateRevRec', cidr => "$args{cidr}", name => $args{rdns}, rpcuser => $args{user})
1695 if $args{rdns};
1696
1697 # and the per-IP set, if there is one.
1698 _rpc('updateRevSet', %{$args{iprev}}, rpcuser => $args{user});
1699 }
1700
1701 return ('OK', 'OK');
1702
1703 } # end static-IP vs netblock allocation
1704
1705} # end allocateBlock()
1706
1707
1708## IPDB::initPool()
1709# Initializes a pool
1710# Requires a database handle, the pool CIDR, type, city, and a parameter
1711# indicating whether the pool should allow allocation of literally every
1712# IP, or if it should reserve network/gateway/broadcast IPs
1713# Note that this is NOT done in a transaction, that's why it's a private
1714# function and should ONLY EVER get called from allocateBlock()
1715sub initPool {
1716 my ($dbh,undef,$type,$city,$class,$parent) = @_;
1717 my $pool = new NetAddr::IP $_[1];
1718
1719 # IPv6 does not lend itself to IP pools as supported
1720 return ('FAIL',"Refusing to create IPv6 static IP pool") if $pool->{isv6};
1721 # IPv4 pools don't make much sense beyond even /24. Allow up to 4096-host footshooting anyway.
1722 # NetAddr::IP won't allow more than a /16 (65k hosts).
1723 return ('FAIL',"Refusing to create oversized static IP pool") if $pool->masklen <= 20;
1724
1725 # Retrieve some odds and ends for defaults on the IPs
1726 my ($pcustid) = $dbh->selectrow_array("SELECT def_custid FROM alloctypes WHERE type=?", undef, ($type) );
1727 my ($vrf,$vlan,$master) = $dbh->selectrow_array("SELECT vrf,vlan,master_id FROM allocations WHERE id = ?",
1728 undef, ($parent) );
1729
1730 $type =~ s/[pd]$/i/;
1731 my $sth;
1732 my $msg;
1733
1734 eval {
1735 # have to insert all pool IPs into poolips table as "unallocated".
1736 $sth = $dbh->prepare("INSERT INTO poolips (ip,custid,city,type,parent_id,master_id) VALUES (?,?,?,?,?,?)");
1737
1738 # in case of pool extension by some means, we need to see what IPs were already inserted
1739 my $tmp1 = $dbh->selectall_arrayref("SELECT ip FROM poolips WHERE parent_id = ?", undef, $parent);
1740 my %foundips;
1741 foreach (@{$tmp1}) {
1742 $foundips{$_->[0]} = 1;
1743 }
1744
1745# Dodge an edge case - pool where IPs have been "stolen" and turned into a netblock assignment.
1746# We can't just "get all the current IPs, and add the missing ones", because some IPs are
1747# legitimately missing (for stretchy values of "legitimately").
1748
1749 my $pdata = getBlockData($dbh, $parent);
1750 my $pcidr = new NetAddr::IP $pdata->{block};
1751
1752 if ($pcidr != $pool) {
1753 # enumerate the IPs from the *old* pool, flag them as "found", so we can iterate the entire
1754 # requested pool and still make sure we skip the IPs in the old pool - even if they've been
1755 # "stolen" by legacy netblocks.
1756 my @oldips = $pcidr->hostenum;
1757 # decide whether to start excluding existing IPs at the "gateway" or "gateway+1"
1758 my $ostart = ($pdata->{type} =~ /^.d$/ ? 1 : 0);
1759 for (my $i = $ostart; $i<= $#oldips; $i++) {
1760 $foundips{$oldips[$i]} = 1;
1761 }
1762 }
1763
1764 # enumerate the hosts in the IP range - everything except the first (net) and last (bcast) IP
1765 my @poolip_list = $pool->hostenum;
1766
1767 # always check/add IPs from gw+1 through bcast-1:
1768 # (but the set won't be in oooorderrrrr! <pout>)
1769 for (my $i=1; $i<=$#poolip_list; $i++) {
1770 my $baseip = $poolip_list[$i]->addr;
1771 if ($baseip !~ /\.(?:0|255)$/ && !$foundips{$poolip_list[$i]}) {
1772 $sth->execute($baseip, $pcustid, $city, $type, $parent, $master);
1773 }
1774 }
1775
1776 # now do the special case - DSL/PPP blocks can use the "net", "gw", and "bcast" IPs.
1777 # we exclude .0 and .255 anyway, since while they'll mostly work, they *will* behave badly here and there.
1778 if ($class eq 'all') { # (DSL-ish block - *all* IPs available
1779 if ($pool->addr !~ /\.0$/) { # .0 causes weirdness.
1780 $sth->execute($pool->addr, $pcustid, $city, $type, $parent, $master) unless $foundips{$pool->addr."/32"};
1781 }
1782 $sth->execute($poolip_list[0]->addr, $pcustid, $city, $type, $parent, $master) unless $foundips{$poolip_list[0]};
1783 $pool--;
1784 if ($pool->addr !~ /\.255$/) { # .255 can cause weirdness.
1785 $sth->execute($pool->addr, $pcustid, $city, $type, $parent, $master) unless $foundips{$pool->addr."/32"};
1786 }
1787 }
1788# don't commit here! the caller may not be done.
1789# $dbh->commit;
1790 };
1791 if ($@) {
1792 $msg = $@;
1793# Don't roll back! It's up to the caller to handle this.
1794# eval { $dbh->rollback; };
1795 return ('FAIL',$msg);
1796 } else {
1797 return ('OK',"OK");
1798 }
1799} # end initPool()
1800
1801
1802## IPDB::updateBlock()
1803# Update an allocation
1804# Takes all allocation fields in a hash
1805sub updateBlock {
1806 my $dbh = shift;
1807 my %args = @_;
1808
1809 return ('FAIL', 'Missing block to update') if !$args{block};
1810
1811 # Spaces don't show up well in lots of places. Make sure they don't get into the DB.
1812 $args{custid} =~ s/^\s+//;
1813 $args{custid} =~ s/\s+$//;
1814
1815 # do it all in a transaction
1816 local $dbh->{AutoCommit} = 0;
1817 local $dbh->{RaiseError} = 1;
1818
1819 my @fieldlist;
1820 my @vallist;
1821 foreach ('custid', 'city', 'description', 'notes', 'circuitid', 'privdata', 'rdns', 'vrf', 'vlan') {
1822 if ($args{$_}) {
1823 push @fieldlist, $_;
1824 push @vallist, $args{$_};
1825 }
1826 }
1827
1828 my $binfo;
1829 my $updtable = 'allocations';
1830 my $keyfield = 'id';
1831 if ($args{type} =~ /^(.)i$/) {
1832 $updtable = 'poolips';
1833 $binfo = getBlockData($dbh, $args{block}, 'i');
1834 } else {
1835## fixme: there's got to be a better way...
1836 $binfo = getBlockData($dbh, $args{block});
1837 if ($args{swip}) {
1838 if ($args{swip} eq 'on' || $args{swip} eq '1' || $args{swip} eq 'y') {
1839 $args{swip} = 'y';
1840 } else {
1841 $args{swip} = 'n';
1842 }
1843 }
1844 foreach ('type', 'swip') {
1845 if ($args{$_}) {
1846 push @fieldlist, $_;
1847 push @vallist, $args{$_};
1848 }
1849 }
1850 }
1851
1852 return ('FAIL', 'No fields to update') if !@fieldlist;
1853
1854 my $sql = "UPDATE $updtable SET ";
1855 $sql .= join " = ?, ", @fieldlist;
1856
1857 # create these here so we can use the expanded CIDR in the rDNS update after the eval,
1858 # if we're expanding the block into a "reserved" freeblock
1859 my $cidr = NetAddr::IP->new($binfo->{block});
1860 my $newblock = NetAddr::IP->new($cidr->addr, $cidr->masklen - 1)->network;
1861
1862 eval {
1863 # check for block merge first...
1864 if ($args{fbmerge}) {
1865 # safety net? make sure mergeable block passed in is really one or both of
1866 # a) reserved for expansion of the block and
1867 # b) confirmed CIDR-combinable
1868 # "safety? SELECT foo FROM freeblocks WHERE cidr << ? AND masklen(cidr) = ?, $newblock, ".$cidr->masklen."\n";
1869 $dbh->do("DELETE FROM freeblocks WHERE id=?", undef, $args{fbmerge});
1870 # ... so we can append the change in the stored CIDR field to extend the allocation.
1871 $sql .= " = ?, cidr";
1872 push @vallist, $newblock;
1873 # if we have an IP pool, call initPool to fill in any missing entries in the pool
1874 if ($binfo->{type} =~ /^.p$/) {
1875 my ($code,$rmsg) = initPool($dbh, "$newblock", $binfo->{type}, $binfo->{city}, 'all', $args{block});
1876 die $rmsg if $code eq 'FAIL';
1877 } elsif ($binfo->{type} =~ /^.d$/) {
1878 my ($code,$rmsg) = initPool($dbh, "$newblock", $binfo->{type}, $binfo->{city}, 'normal', $args{block});
1879 die $rmsg if $code eq 'FAIL';
1880 }
1881 }
1882
1883 # backup
1884 if (!defined($args{ignorebk})) {
1885 # backup data considered "restricted"; caller should set this flag if user does not have 's' permission
1886
1887 my $backupid = $binfo->{hasbk};
1888 if (!$binfo->{hasbk}) {
1889 if ($args{backup}) {
1890 # failure mode: backup data on netblock with no IP set
1891 if (!$args{bkip}) {
1892 # check for /32-ness. no point in skipping /32 "netblocks", because they already single IPs
1893 die "Backup data set on a netblock requires a backup IP\n" unless $binfo->{block} =~ m{/32$};
1894 $args{bkip} = $binfo->{block};
1895 }
1896 # insert new backup record since we don't have one
1897 my $bksql = "INSERT INTO backuplist (";
1898 my @bkfields;
1899 my @bkvals;
1900 for my $bk (@backupfields) {
1901 if ($args{"bk$bk"}) {
1902 push @bkfields, "bk$bk";
1903 push @bkvals, $args{"bk$bk"};
1904 }
1905 }
1906 $bksql .= join(',',@bkfields).") VALUES (".join(',', map {'?'} @bkfields).")";
1907 $dbh->do($bksql, undef, @bkvals);
1908 ($backupid) = $dbh->selectrow_array("SELECT currval('backuplist_backup_id_seq')");
1909 # add the backup ID to the update
1910 push @vallist, $backupid;
1911 $sql .= " = ?, backup_id";
1912 }
1913
1914 } else { # !$binfo->{hasbk}
1915
1916 # allocation already has backup data
1917 if ($args{backup}) {
1918 if (!$args{bkip}) {
1919 # check for /32-ness. no point in skipping /32 "netblocks", because they are already single IPs
1920 die "Backup data set on a netblock requires a backup IP\n" unless $binfo->{block} =~ m{/32$};
1921 $args{bkip} = $binfo->{block};
1922 }
1923 my @bkfields;
1924 my @bkvals;
1925 for my $bk (@backupfields) {
1926 no warnings qw( uninitialized );
1927 if ($binfo->{"bk$bk"} ne $args{"bk$bk"}) {
1928 push @bkfields, "bk$bk = ?";
1929 push @bkvals, $args{"bk$bk"};
1930 }
1931 }
1932
1933 $dbh->do("UPDATE backuplist SET ".join(',', @bkfields)." WHERE backup_id = ?",
1934 undef, @bkvals, $binfo->{hasbk})
1935 if @bkfields;
1936##todo: keep historic changes for $timeperiod, by adding a backref ID field, and on updates adding a new backup
1937# record instead of updating the existing one. should probably check if new==old so we don't do needless updates
1938# in that case...
1939 } else {
1940 if ($binfo->{hasbk}) {
1941 # had backup data, no longer checked - delete backup entry
1942 $dbh->do("DELETE FROM backuplist WHERE backup_id = ?", undef, $binfo->{hasbk});
1943 $sql .= " = ?, backup_id";
1944 push @vallist, 0;
1945 }
1946 }
1947 } # $binfo->{hasbk} defined
1948 } # if !args{ignorebk}
1949
1950 # append another SQL fragment
1951 push @vallist, $args{block};
1952 $sql .= " = ? WHERE $keyfield = ?";
1953
1954 # do the update
1955 $dbh->do($sql, undef, @vallist);
1956
1957 if ($args{node}) {
1958 # done with delete/insert so we don't have to worry about funkyness updating a node ref that isn't there
1959 $dbh->do("DELETE FROM noderef WHERE block = ?", undef, ($binfo->{block}) );
1960 $dbh->do("INSERT INTO noderef (block,node_id) VALUES (?,?)", undef, ($binfo->{block}, $args{node}) )
1961 if $args{node} ne '--';
1962 }
1963
1964 $dbh->commit;
1965 };
1966 if ($@) {
1967 my $msg = $@;
1968 $dbh->rollback;
1969 return ('FAIL', $msg);
1970 }
1971
1972 # Do RPC rDNS call, if available.
1973 # Snag the parent info
1974 my $pinfo = getBlockData($dbh, $binfo->{parent_id});
1975 # Return early if rDNS flag(s) are not set
1976 return ('OK','OK') unless ($pinfo->{revavail} || $pinfo->{revpartial});
1977
1978 # In case of any container (mainly master block), only update freeblocks so we don't stomp subs
1979 # (which would be the wrong thing in pretty much any case except "DELETE ALL EVARYTHING!!1!oneone!")
1980 if ($binfo->{type} =~ '.[mc]') {
1981 # Not using listFree() as it doesn't return quite all of the blocks wanted.
1982 # Retrieve the immediate free blocks
1983 my $sth = $dbh->prepare(q(
1984 SELECT cidr FROM freeblocks WHERE parent_id = ?
1985 UNION
1986 SELECT cidr FROM freeblocks f WHERE
1987 cidr = (SELECT cidr FROM allocations a WHERE f.cidr = a.cidr)
1988 AND master_id = ?
1989 ) );
1990 $sth->execute($args{block}, $binfo->{master_id});
1991 my %fbset;
1992 while (my ($fb) = $sth->fetchrow_array) {
1993 $fbset{"host_$fb"} = $args{rdns};
1994 }
1995 # We use this RPC call instead of multiple addOrUpdateRevRec calls, since we don't
1996 # know how many records we'll be updating and more than 3-4 is far too slow. This
1997 # should be safe to call unconditionally.
1998 # Requires dnsadmin >= r678
1999 _rpc('updateRevSet', %fbset, rpcuser => $args{user});
2000
2001 } else {
2002 $binfo->{block} =~ s|/32$||;
2003 _rpc('addOrUpdateRevRec', cidr => $binfo->{block}, name => $args{rdns}, rpcuser => $args{user});
2004
2005 # and the per-IP set, if there is one.
2006 _rpc('updateRevSet', %{$args{iprev}}, rpcuser => $args{user}) if keys (%{$args{iprev}});
2007
2008 # and fix up the template's CIDR if required
2009 _rpc('resizeTemplate', oldcidr => "$binfo->{block}", newcidr => $newblock->network.'', rpcuser => $args{user})
2010 if $args{fbmerge};
2011 }
2012
2013##fixme: RPC failures?
2014 return ('OK','OK');
2015} # end updateBlock()
2016
2017
2018## IPDB::splitBlock()
2019# Splits an existing allocation into two or more smaller allocations based on a passed netmask
2020# Duplicates all other data
2021# Returns an arrayref to a list of hashrefs with ID and CIDR keys for the list of new allocations.
2022# Should probably commit DNS magic to realign DNS data
2023# Mostly works but may return Strange Things(TM) if used on a master block
2024sub splitBlock {
2025 my $dbh = shift;
2026 my %args = @_;
2027
2028##fixme: set errstr on errors so caller can suitably clue-by-four the user
2029 return if $args{basetype} ne 'b'; # only netblocks allowed!
2030
2031 my $binfo = getBlockData($dbh, $args{id});
2032 return if !$binfo;
2033
2034 return if $args{newmask} !~ /^\d+$/;
2035
2036 my @ret;
2037 my $block = new NetAddr::IP $binfo->{block};
2038 my $oldmask = $block->masklen;
2039
2040 # Fail if the block to split is "too small" - eg, can't split a v4 /32 at all
2041 # failure modes:
2042 # difference between $oldmask and $newmask is negative or 0
2043 if ($args{newmask} - $oldmask <= 0) {
2044 $errstr = "Can't split a /$oldmask allocation into /$args{newmask} pieces";
2045 return;
2046 }
2047# # difference between $oldmask and $newmask is > n, for arbitrary n?
2048# if ($newmask - $oldmask > 42) { # because 42
2049# }
2050 # $oldmask > n, for arbitrary n? At least check limits of data type.
2051 if ($block->{isv6}) {
2052 if ($args{newmask} - $oldmask > 128) {
2053 $errstr = "Impossible IPv6 mask length /$args{newmask} requested";
2054 return;
2055 }
2056 } else {
2057 if ($args{newmask} - $oldmask > 32) {
2058 $errstr = "Impossible IPv4 mask length /$args{newmask} requested";
2059 return;
2060 }
2061 }
2062
2063 my @newblocks = $block->split($args{newmask});
2064
2065 local $dbh->{AutoCommit} = 0;
2066 local $dbh->{RaiseError} = 1;
2067
2068 eval {
2069 # line up a list of fields and values. Be nice if there was a handy way to do,
2070 # direct in SQL, something like
2071 # "INSERT INTO foo (f1,f2,f3) VALUES (newf1,(SELECT oldf2,oldf3 FROM foo WHERE baz))"
2072 my @fieldlist = qw(type city description notes circuitid privdata custid swip vrf vlan rdns parent_id master_id);
2073 my $fields_sql = join(',', @fieldlist);
2074 my @vals;
2075 foreach (@fieldlist) {
2076 push @vals, $binfo->{$_};
2077 }
2078 # note the first block in the split for return
2079 push @ret, {nid => $args{id}, nblock => "$newblocks[0]"};
2080
2081 # prepare
2082 my $idsth = $dbh->prepare("SELECT currval('allocations_id_seq')");
2083 my $allocsth = $dbh->prepare("INSERT INTO allocations (cidr, $fields_sql)".
2084 " VALUES (?".',?'x(scalar(@fieldlist)).")");
2085 my $allocsth2 = $dbh->prepare(qq(
2086 INSERT INTO allocations (cidr, $fields_sql)
2087 SELECT ? AS cidr, $fields_sql
2088 FROM allocations
2089 WHERE id = ?
2090 ) );
2091 my $nbsth = $dbh->prepare("DELETE FROM poolips WHERE parent_id = ? AND ip = ?");
2092 my $upd_psth = $dbh->prepare("UPDATE allocations SET parent_id = ? WHERE parent_id = ? AND cidr <<= ?");
2093 my $upd_msth = $dbh->prepare("UPDATE allocations SET master_id = ? WHERE master_id = ? AND cidr <<= ?");
2094 my $fb_psth = $dbh->prepare("UPDATE freeblocks SET parent_id = ? WHERE parent_id = ? AND cidr <<= ?");
2095 my $fb_msth = $dbh->prepare("UPDATE freeblocks SET master_id = ? WHERE master_id = ? AND cidr <<= ?");
2096 my $pool_psth = $dbh->prepare("UPDATE poolips SET parent_id = ? WHERE parent_id = ? AND ip << ?");
2097 my $pool_msth = $dbh->prepare("UPDATE poolips SET master_id = ? WHERE master_id = ? AND ip <<= ?");
2098
2099 my @clist;
2100 _getChildren($dbh, $args{id}, $binfo->{master_id}, \@clist, $block);
2101
2102 my @processlist;
2103 push @processlist, { id => $args{id}, cidr => $block, mask => $block->masklen, type => $binfo->{type} };
2104 foreach (@clist) {
2105 $_->{cidr} = new NetAddr::IP $_->{cidr};
2106 if ($_->{cidr}->masklen < $args{newmask}) {
2107 $_->{mask} = $_->{cidr}->masklen;
2108 push @processlist, $_;
2109 }
2110 }
2111
2112 # Sort on masklen, crudely break ties by pushing container blocks down the stack. Multiple-nested containers
2113 # of the same size are virtually guaranteed to produce strange results, but should be rare enough to not matter
2114 @processlist = sort { $b->{cidr}->masklen <=> $a->{cidr}->masklen || $a->{type} =~ /^.m$/ } @processlist;
2115
2116 foreach my $pr (@processlist) {
2117 my @nbset = $pr->{cidr}->split($args{newmask});
2118
2119 # set up update of existing block
2120 $dbh->do("UPDATE allocations SET cidr = ? WHERE id = ?", undef, ("$nbset[0]", $pr->{id}) );
2121
2122 # axe the new bcast IP from the smaller pool at the "base" block, if it's a "normal" pool
2123 if ($pr->{type} =~ /.d/) {
2124 $nbset[0]--;
2125 $nbsth->execute($pr->{id}, $nbset[0]->addr);
2126 }
2127
2128 # Holder for freeblocks-to-delete. Should be impossible to have more than one...
2129 my %fbdel;
2130
2131 # Loop over the new blocks that are not the base block
2132 for (my $i = 1; $i <= $#nbset; $i++) {
2133 # add the new allocation
2134 $allocsth2->execute($nbset[$i], $pr->{id});
2135
2136 # fetch the ID of the entry we just added...
2137 $idsth->execute();
2138 my ($nid) = $idsth->fetchrow_array();
2139 # ... so we can pass back the list of blocks and IDs...
2140 push @ret, {nid => $nid, nblock => "$nbset[$i]"};
2141 # axe the net, gw, and bcast IPs as necessary when splitting a "normal" pool
2142 if ($pr->{type} =~ /.d/) {
2143 # net
2144 $nbsth->execute($pr->{id}, $nbset[$i]->addr);
2145 $nbset[$i]++;
2146 # gw
2147 $nbsth->execute($pr->{id}, $nbset[$i]->addr);
2148 $nbset[$i]--;
2149 $nbset[$i]--;
2150 # bcast
2151 $nbsth->execute($pr->{id}, $nbset[$i]->addr);
2152 $nbset[$i]++;
2153 } # $binfo->{type} =~ /.d/
2154
2155 # Check for free blocks larger than the new mask length, and split those as needed.
2156 if ($pr->{type} =~ /.[cm]/) {
2157 # get a "list" of freeblocks bigger than the allocation in the parent. there's only one, right?
2158 my $fblist = $dbh->selectall_arrayref("SELECT id FROM freeblocks WHERE cidr >> ? AND parent_id = ? ",
2159 {Slice=>{}}, $nbset[$i], $pr->{id});
2160 if (@$fblist) {
2161 # create a new freeblock for the new block we created earlier
2162 $dbh->do(q{
2163 INSERT INTO freeblocks (cidr, parent_id, master_id, city, routed,vrf)
2164 SELECT ? AS cidr, ? AS parent_id, master_id, city, routed, vrf FROM freeblocks
2165 WHERE id = ?
2166 }, undef, ($nbset[$i], $nid, $fblist->[0]->{id}) );
2167 $fbdel{$fblist->[0]->{id}}++;
2168 }
2169 } # $binfo->{type} =~ /.[cm]/
2170
2171 # Reparent allocations, freeblocks, and pool IPs.
2172 $upd_psth->execute($nid, $pr->{id}, $nbset[$i]);
2173 $fb_psth->execute($nid, $pr->{id}, $nbset[$i]);
2174 $pool_psth->execute($nid, $pr->{id}, $nbset[$i]);
2175
2176 # Update master if we've split a master block
2177 if ($pr->{type} eq 'mm') {
2178 $upd_msth->execute($nid, $pr->{id}, $nbset[$i]);
2179 $fb_msth->execute($nid, $pr->{id}, $nbset[$i]);
2180 $pool_msth->execute($nid, $pr->{id}, $nbset[$i]);
2181 }
2182
2183##fixme:
2184# 2015/09/09 not sure if the latest rewrite has covered this case complete or not
2185# Still missing one edge case - megasplitting a large block such that "many" children also need to be split.
2186# I'm going to call this "unsupported" because I really can't imagine a sane reason for doing this.
2187# Should probably check and error out at least
2188
2189 } # for (... @nbset)
2190
2191 if (%fbdel) {
2192 my $delfblist = $dbh->selectall_arrayref(q{
2193 SELECT cidr,parent_id,id FROM freeblocks
2194 WHERE id in (
2195 }.join(',', keys %fbdel).")", {Slice=>{}} );
2196 $dbh->do("DELETE FROM freeblocks WHERE id IN (".join(',', keys %fbdel).")") if %fbdel;
2197 }
2198
2199 } # foreach @processlist
2200
2201 $dbh->commit;
2202 };
2203 if ($@) {
2204 $errstr = "Error splitting $binfo->{block}: $@";
2205 $dbh->rollback;
2206 return;
2207 }
2208
2209 # Only try to update rDNS when the original block is flagged as "rDNS available"
2210 _rpc('splitTemplate', cidr => $binfo->{block}, newmask => $args{newmask}, rpcuser => $args{user})
2211 if ($binfo->{revavail} || $binfo->{revpartial});
2212
2213 return \@ret;
2214} # end splitBlock()
2215
2216
2217## IPDB::shrinkBlock()
2218# Shrink an allocation to the passed CIDR block
2219# Takes an allocation ID and a new CIDR
2220# Returns an arrayref to a list of hashrefs with the ID and CIDR of the freed block(s)
2221# Refuses to shrink "real netblock" pool types below /30
2222sub shrinkBlock {
2223 my $dbh = shift;
2224 my $id = shift;
2225
2226 # just take the new CIDR spec; this way we can shrink eg .16/28 to .20/30 without extra contortions
2227 my $newblock = new NetAddr::IP shift;
2228
2229 my $user = shift;
2230
2231 if (!$newblock) {
2232 $errstr = "Can't shrink something that's not a netblock";
2233 return;
2234 }
2235
2236 my $binfo = getBlockData($dbh, $id);
2237 my $pinfo = getBlockData($dbh, $binfo->{parent_id});
2238
2239 if ($binfo->{type} =~ /.d/ && $newblock->masklen > ($newblock->bits+2) ) {
2240 $errstr = "Can't shrink a non-PPP pool smaller than ".($newblock->{isv6} ? '/124' : '/30');
2241 return;
2242 }
2243
2244 my $oldblock = new NetAddr::IP $binfo->{block};
2245
2246 # Don't try to shrink the block outside of itself, Bad Things (probably) Happen.
2247 if (!$oldblock->contains($newblock)) {
2248 $errstr = "Can't shrink an allocation outside of itself";
2249 return;
2250 }
2251
2252 local $dbh->{AutoCommit} = 0;
2253 local $dbh->{RaiseError} = 1;
2254
2255 my $addfbsth = $dbh->prepare("INSERT INTO freeblocks (cidr,city,routed,vrf,parent_id,master_id) VALUES (?,?,?,?,?,?)");
2256 my $idsth = $dbh->prepare("SELECT currval('freeblocks_id_seq')");
2257 my $poolsth = $dbh->prepare("DELETE FROM poolips WHERE parent_id = ? AND ip << ?");
2258 my $netsth = $dbh->prepare("DELETE FROM poolips WHERE parent_id = ? AND ip = ?");
2259 my $allocsth = $dbh->prepare("DELETE FROM allocations WHERE parent_id = ? AND cidr <<= ?");
2260 my $delfbsth = $dbh->prepare("DELETE FROM freeblocks WHERE parent_id = ? AND cidr <<= ?");
2261
2262 my @ret;
2263 my @newfreelist;
2264 eval {
2265 $dbh->do("UPDATE allocations SET cidr = ? WHERE id = ?", undef, $newblock, $id);
2266
2267 # find the netblock(s) that are now free
2268 my @workingblocks = $oldblock->split($newblock->masklen);
2269 foreach my $newsub (@workingblocks) {
2270 next if $newsub == $newblock;
2271 push @newfreelist, $newsub;
2272 }
2273 @newfreelist = Compact(@newfreelist);
2274
2275 # set new freeblocks, and clean up any IP pool entries if needed.
2276 foreach my $newfree (@newfreelist) {
2277 my @clist;
2278 # the block we're munging
2279 push @clist, { id => $id, type => $binfo->{type}, cidr => $binfo->{block} };
2280 _getChildren($dbh, $id, $binfo->{master_id}, \@clist, $newfree);
2281
2282 foreach my $goner (@clist) {
2283 $poolsth->execute($goner->{id}, $newfree) if $goner->{type} =~ /.[dp]/;
2284 $allocsth->execute($goner->{id}, $newfree);
2285 $delfbsth->execute($goner->{id}, $newfree);
2286 }
2287
2288 # No pinfo means we're shrinking a master block, which means the free space is returned outside of IPDB.
2289 if ($pinfo) {
2290 $addfbsth->execute($newfree, $pinfo->{city}, 'm', $pinfo->{vrf}, $binfo->{parent_id}, $pinfo->{master_id});
2291 $idsth->execute;
2292 my ($nid) = $idsth->fetchrow_array();
2293 # add to return list
2294 push @ret, {fbid => $nid, newfree => "$newfree", fbparent => $binfo->{parent_id} };
2295 }
2296
2297 } # $newfree (@newfreelist)
2298
2299 # additional cleanup on net/gw/bcast IPs in pool
2300 if ($binfo->{type} =~ /.d/) {
2301 $netsth->execute($id, $newblock->addr);
2302 $newblock++;
2303 $netsth->execute($id, $newblock->addr);
2304 $newblock--;
2305 $newblock--;
2306 $netsth->execute($id, $newblock->addr);
2307 }
2308
2309 $dbh->commit;
2310 };
2311 if ($@) {
2312 $errstr = "Error splitting $binfo->{block}: $@";
2313 $dbh->rollback;
2314 return;
2315 }
2316
2317 # Only try to update rDNS when the original block is flagged as "rDNS available"
2318 _rpc('resizeTemplate', oldcidr => $binfo->{block}, newcidr => $newblock->network, rpcuser => $user)
2319 if ($binfo->{revavail} || $binfo->{revpartial});
2320
2321 return \@ret;
2322} # end shrinkBlock()
2323
2324
2325## IPDB::mergeBlocks()
2326# Merges two or more adjacent allocations, optionally including relevant
2327# free space, into one allocation.
2328# Takes a "base" block ID and a hash with a mask length and a scope argument to decide
2329# how much existing allocation data to delete.
2330# Returns a list starting with the new merged block, then the merged allocations with comment
2331## Merge scope:
2332# Merge to container
2333# keepall
2334# Move all mergeable allocations into the new block
2335# Move all mergeable free blocks into the new block
2336# mergepeer
2337# Move subs of mergeable containers into the updated primary.
2338# Reparent free blocks in mergeable containers to the updated primary.
2339# Convert assigned IPs from pools into subs.
2340# Convert unused IPs from pools into free blocks.
2341# Convert leaf allocations into free blocks.
2342# clearpeer
2343# Keep subs of the original (if it was a container).
2344# Convert assigned IPs from the original pool into subs (if it was a pool).
2345# Convert unused IPs from the original pool into free blocks (if it was a pool).
2346# Delete all peers and their subs aside from the original.
2347# clearall
2348# Delete all peers, subs and IPs.
2349# Add single free block for new container.
2350# Merge to pool
2351# keepall
2352# Convert all leaf allocations in the merge range to groups of used IPs
2353# mergepeer
2354# Effectively equal to keepall
2355# clearpeer
2356# Only convert IPs from the original allocation to used IPs
2357# clearall
2358# Delete any existing IPs, and reinitialize the new pool entirely
2359# Merge to leaf type
2360# Remove all subs
2361sub mergeBlocks {
2362 my $dbh = shift;
2363 my $prime = shift; # "base" block ID to use as a starting point
2364 if (!$prime) {
2365 $errstr = "Missing block ID to base merge on";
2366 return;
2367 }
2368
2369 my %args = @_;
2370
2371 # check key arguments.
2372 if (!$args{scope} || $args{scope} !~ /^(keepall|mergepeer|clearpeer|clearall)$/) {
2373 $errstr = "Bad or missing merge scope";
2374 return;
2375 }
2376 if (!$args{newmask} || $args{newmask} !~ /^\d+$/) {
2377 $errstr = "Bad or missing new netmask";
2378 return;
2379 }
2380
2381 # Retrieve info about the base allocation we're munging
2382 my $binfo = getBlockData($dbh, $prime);
2383 my $block = new NetAddr::IP $binfo->{block};
2384 my ($basetype) = ($binfo->{type} =~ /^.(.)$/);
2385 $binfo->{id} = $prime; # preserve for later, just in case
2386
2387 # proposed block
2388 my $newblock = new NetAddr::IP $block->addr."/$args{newmask}";
2389 $newblock = $newblock->network;
2390 $args{newtype} = $binfo->{type} if !$args{newtype};
2391 # if the "primary" block being changed is a master, it must remain one.
2392 # Also force the scope, since otherwise things get ugly.
2393 if ($binfo->{type} eq 'mm') {
2394 $args{newtype} = 'mm';
2395 # don't want to make a peer master a sub of the existing one; too many special cases go explodey,
2396 # but want to retain all other allocations
2397 $args{scope} = 'mergepeer';
2398 }
2399 my ($newcontainerclass) = ($args{newtype} =~ /^(.).$/);
2400
2401 # build an info hash for the "new" allocation we're creating
2402 my $pinfo = {
2403 id => $prime,
2404 block => "$newblock",
2405 type => $args{newtype},
2406 parent_id =>
2407 $binfo->{parent_id},
2408 city => $binfo->{city},
2409 vrf => $binfo->{vrf},
2410 master_id => $binfo->{master_id}
2411 };
2412
2413 my @retlist;
2414
2415 local $dbh->{AutoCommit} = 0;
2416 local $dbh->{RaiseError} = 1;
2417
2418 # Want to do all of the DB stuff in a transaction, to minimize data changing underfoot
2419 eval {
2420
2421 # We always update the "prime" block passed in...
2422 my $updsth = $dbh->prepare("UPDATE allocations SET cidr = ?, type = ? WHERE id = ?");
2423
2424##fixme: There's still an edge case in the return list where some branches accidentally include
2425# the original block as "additional". Probably due to the ordering of when the prepared update
2426# above gets executed.
2427
2428 # For leaf blocks, we may need to create a new parent as the "primary" instead
2429 # of updating the existing block
2430 my $newparent = $dbh->prepare(q{
2431 INSERT INTO allocations (
2432 cidr, type, city, description, notes, circuitid, createstamp, modifystamp,
2433 privdata, custid, swip, vrf, vlan, rdns, parent_id, master_id
2434 )
2435 SELECT
2436 ? AS cidr, ? AS type, city, description, notes, circuitid, createstamp, modifystamp,
2437 privdata, custid, swip, vrf, vlan, rdns, parent_id, master_id
2438 FROM allocations
2439 WHERE id = ?
2440 });
2441
2442 # Common actions
2443 my $peersth = $dbh->prepare("SELECT cidr,id,type,master_id FROM allocations WHERE parent_id = ? AND cidr <<= ?");
2444 $peersth->execute($binfo->{parent_id}, "$newblock");
2445 my $reparentsth = $dbh->prepare("UPDATE allocations SET parent_id = ?, master_id = ? WHERE id = ?");
2446 my $insfbsth = $dbh->prepare("INSERT INTO freeblocks (cidr,city,routed,vrf,parent_id,master_id) VALUES (?,?,?,?,?,?)");
2447 my $delsth = $dbh->prepare("DELETE FROM allocations WHERE id = ?");
2448
2449 my $fbreparentsth = $dbh->prepare(q{
2450 UPDATE freeblocks
2451 SET parent_id = ?, master_id = ?, city = ?, routed = ?, vrf = ?
2452 WHERE parent_id = ? AND cidr <<= ?
2453 });
2454
2455 if ($args{newtype} =~ /.[cm]/) {
2456 ## Container
2457
2458 # In case of merging a master block. Somewhat redundant with calls to $fbreparentsth,
2459 # but not *quite* entirely.
2460 my $mfbsth = $dbh->prepare("UPDATE freeblocks SET master_id = ? WHERE master_id = ?");
2461
2462 if ($args{scope} eq 'keepall') {
2463 # Create a new parent with the same info as the passed "primary".
2464 $newparent->execute($newblock, $args{newtype}, $prime);
2465 # and now retrieve the new parent ID
2466 ($prime) = $dbh->selectrow_array("SELECT currval('allocations_id_seq')");
2467 # snag the new parent info for the return list
2468 push @retlist, { block => "$newblock", type => $disp_alloctypes{$args{newtype}}, id => $prime };
2469 # Reparent the free blocks in the new block
2470 $fbreparentsth->execute($prime, $binfo->{master_id}, $binfo->{city}, $newcontainerclass, $binfo->{vrf},
2471 $binfo->{parent_id}, $newblock);
2472 # keep existing allocations (including the original primary), just push them down a level
2473 while (my ($peercidr, $peer_id, $peertype, $m_id) = $peersth->fetchrow_array) {
2474 $reparentsth->execute($prime, $binfo->{master_id}, $peer_id);
2475 # Fix up master_id on free blocks if we're merging a master block
2476 $mfbsth->execute($binfo->{master_id}, $m_id) if $peertype eq 'mm';
2477 # capture block for return
2478 push @retlist, { block => $peercidr, mdisp => $disp_alloctypes{$peertype}, mtype => $peertype };
2479 }
2480
2481 } elsif ($args{scope} =~ /^clear/) {
2482 # clearpeer and clearall share a starting point
2483 # snag the new parent info for the return list
2484 push @retlist, { block => "$newblock", type => $disp_alloctypes{$args{newtype}}, id => $prime };
2485 # update the primary allocation info
2486 $updsth->execute($newblock, $args{newtype}, $prime);
2487 # Reparent the free blocks in the new block
2488 $fbreparentsth->execute($prime, $binfo->{master_id}, $binfo->{city}, $newcontainerclass, $binfo->{vrf},
2489 $binfo->{parent_id}, $newblock);
2490 # Insert a free block if $prime is a leaf
2491 if ($binfo->{type} =~ /.[enr]/) {
2492 $insfbsth->execute($binfo->{block}, $binfo->{city}, $newcontainerclass, $binfo->{vrf}, $prime,
2493 $binfo->{master_id});
2494 }
2495 # delete the peers.
2496 while (my ($peercidr, $peer_id, $peertype, $m_id) = $peersth->fetchrow_array) {
2497 next if $peer_id == $prime;
2498 # push existing allocations down a level before deleting,
2499 # so that when they're deleted the parent info is correct
2500 $reparentsth->execute($prime, $binfo->{master_id}, $peer_id);
2501 _deleteCascade($dbh, $peer_id);
2502 # insert the freeblock _deleteCascade() (deliberately) didn't when deleting a master block.
2503 # aren't special cases fun?
2504 $dbh->do("INSERT INTO freeblocks (cidr,routed,parent_id,master_id) values (?,?,?,?)",
2505 undef, ($peercidr, 'm', $prime, $prime) ) if $binfo->{type} eq 'mm';
2506 # capture block for return
2507 push @retlist, { block => $peercidr, mdisp => $disp_alloctypes{$peertype}, mtype => $peertype };
2508 }
2509 if ($args{scope} eq 'clearall') {
2510 # delete any subs of $prime as well
2511 my $substh = $dbh->prepare("SELECT cidr,id FROM allocations WHERE parent_id = ?");
2512 $substh->execute($prime);
2513 while (my ($scidr, $s_id) = $substh->fetchrow_array) {
2514 _deleteCascade($dbh, $s_id);
2515 }
2516 } else {
2517 # clearpeer
2518 if ($basetype =~ /[dp]/) {
2519 # Convert active IP pool entries to allocations if the original was an IP pool
2520 _poolToAllocations($dbh, $binfo, $pinfo, newtype => $poolmap{$binfo->{type}});
2521 }
2522 } # clearall or clearpeer
2523
2524 } elsif ($args{scope} eq 'mergepeer') { # should this just be an else?
2525 # Default case. Merge "peer" blocks, but keep all suballocations
2526 # snag the new parent info for the return list
2527 push @retlist, {block => "$newblock", type => $disp_alloctypes{$args{newtype}}, id => $prime};
2528 my $substh = $dbh->prepare("UPDATE allocations SET parent_id = ? WHERE parent_id = ?");
2529 my $delsth = $dbh->prepare("DELETE FROM allocations WHERE id = ?");
2530 # Reparent freeblocks in parent
2531 $fbreparentsth->execute($prime, $binfo->{master_id}, $binfo->{city}, $newcontainerclass, $binfo->{vrf},
2532 $binfo->{parent_id}, $newblock);
2533 # Loop over "peer" allocations to be merged
2534 while (my ($peercidr, $peer_id, $peertype, $m_id) = $peersth->fetchrow_array) {
2535 # Snag existing peer data since we may need it
2536 my $peerfull = getBlockData($dbh, $peer_id);
2537 # Reparent free blocks from existing containers
2538 $fbreparentsth->execute($prime, $binfo->{master_id}, $binfo->{city}, $newcontainerclass,
2539 $binfo->{vrf}, $peer_id, $newblock);
2540 # Reparent any subblocks from existing containers
2541 $substh->execute($prime, $peer_id);
2542 # Delete the old container
2543 $delsth->execute($peer_id) unless $peer_id == $prime;
2544 # Add new freeblocks for merged leaf blocks
2545 $insfbsth->execute($peercidr, $binfo->{city}, $newcontainerclass, $binfo->{vrf}, $binfo->{id},
2546 $binfo->{master_id}) if $peertype =~ /.[enr]/;
2547 # Convert pool IPs into allocations or aggregated free blocks
2548 _poolToAllocations($dbh, $peerfull, $pinfo, newparent => $prime) if $peertype =~ /.[dp]/;
2549 # Fix up master_id on free blocks if we're merging a master block
2550 $mfbsth->execute($binfo->{master_id}, $m_id) if $peertype eq 'mm';
2551 # capture block for return
2552 push @retlist, { block => $peercidr, mdisp => $disp_alloctypes{$peertype}, mtype => $peertype };
2553 } # merge peers
2554 # update the primary allocation info. Do this last so we don't stomp extra data-retrieval in the loop above
2555 $updsth->execute($newblock, $args{newtype}, $prime);
2556
2557 } # scope
2558
2559 # Clean up free blocks
2560 _compactFree($dbh, $prime);
2561
2562 } elsif ($args{newtype} =~ /.[dp]/) {
2563 ## Pool
2564 # Snag the new parent info for the return list
2565 push @retlist, { block => "$newblock", type => $disp_alloctypes{$args{newtype}}, id => $prime };
2566
2567 if ($args{scope} eq 'keepall') {
2568 # Convert all mergeable allocations and subs to chunks of pool IP assignments
2569 push @retlist, @{ _toPool($dbh, $prime, $newblock, $args{newtype}, 1) };
2570
2571 } elsif ($args{scope} =~ /^clear/) {
2572 # Clear it all out for a fresh (mostly?) empty IP pool
2573 while (my ($peercidr, $peer_id, $peertype, $m_id) = $peersth->fetchrow_array) {
2574 next if $peer_id == $prime;
2575 # Push existing allocations down a level before deleting,
2576 # so that when they're deleted the parent info is correct
2577 $reparentsth->execute($prime, $binfo->{master_id}, $peer_id);
2578 _deleteCascade($dbh, $peer_id, 0);
2579 # Capture block for return
2580 push @retlist, { block => $peercidr, mdisp => $disp_alloctypes{$peertype}, mtype => $peertype };
2581 }
2582 if ($args{scope} eq 'clearall') {
2583 # Delete any subs of $prime as well
2584 my $substh = $dbh->prepare("SELECT cidr,id FROM allocations WHERE parent_id = ?");
2585 $substh->execute($prime);
2586 while (my ($scidr, $s_id) = $substh->fetchrow_array) {
2587 _deleteCascade($dbh, $s_id);
2588 }
2589 } else {
2590 # Convert (subs of) self if not a leaf.
2591 push @retlist, @{ _toPool($dbh, $prime, $newblock, $args{newtype}, 1) }
2592 unless $binfo->{type} =~ /.[enr]/;
2593 } # scope ne 'clearall'
2594
2595 } elsif ($args{scope} eq 'mergepeer') {
2596 # Try to match behaviour from (target type == container) by deleting immediate peer leaf allocations
2597 while (my ($peercidr, $peer_id, $peertype, $m_id) = $peersth->fetchrow_array) {
2598 next if $peer_id == $prime; # don't delete the block we're turning into the pool allocation
2599 # Capture block for return
2600 push @retlist, { block => $peercidr, mdisp => $disp_alloctypes{$peertype}, mtype => $peertype };
2601 next unless $peertype =~ /.[enr]/;
2602 # Don't need _deleteCascade(), since we'll just be deleting the freshly
2603 # added free block a little later anyway
2604 $delsth->execute($peer_id);
2605 }
2606 # Convert self if not a leaf, to match behaviour with a container type as target
2607 _toPool($dbh, $prime, $newblock, $args{newtype}) unless $binfo->{type} =~ /.[enr]/;
2608 }
2609 # Update the primary allocation info.
2610 $updsth->execute($newblock, $args{newtype}, $prime);
2611 # Delete any lingering free blocks
2612 $dbh->do("DELETE FROM freeblocks WHERE parent_id = ? AND cidr <<= ?", undef, $binfo->{parent_id}, $newblock);
2613 # Fix up the rest of the pool IPs
2614 my ($code,$msg) = initPool($dbh, $newblock, $args{newtype}, $binfo->{city},
2615 ($args{newtype} =~ /.p/ ? 'all' : 'normal'), $prime);
2616
2617 } elsif ($args{newtype} =~ /.[enr]/) {
2618 ## Leaf
2619 # Merging to a leaf type of any kind is, pretty much be definition, scope == 'clearall'.
2620 # keepall, mergepeer, and clearpeer all imply keeping suballocations, where leaf allocations
2621 # by definition do not have suballocations.
2622 # Update the old allocation
2623 $updsth->execute($newblock, $args{newtype}, $prime);
2624 # Snag the new parent info for the return list
2625 push @retlist, {block => "$newblock", type => $disp_alloctypes{$args{newtype}}, id => $prime};
2626 while (my ($peercidr, $peer_id, $peertype, $m_id) = $peersth->fetchrow_array) {
2627 next if $peer_id == $prime;
2628 # Push existing allocations down a level before deleting,
2629 # so that when they're deleted the parent info is correct
2630 $reparentsth->execute($prime, $binfo->{master_id}, $peer_id);
2631 _deleteCascade($dbh, $peer_id, 0);
2632 # Capture block for return
2633 push @retlist, { block => $peercidr, mdisp => $disp_alloctypes{$peertype}, mtype => $peertype };
2634 }
2635 # Delete any subs of $prime as well
2636 my $substh = $dbh->prepare("SELECT cidr,id FROM allocations WHERE parent_id = ?");
2637 $substh->execute($prime);
2638 while (my ($scidr, $s_id) = $substh->fetchrow_array) {
2639 _deleteCascade($dbh, $s_id);
2640 }
2641 # Clean up lingering free blocks and pool IPs
2642 $dbh->do("DELETE FROM freeblocks WHERE cidr <<= ? AND (parent_id = ? OR parent_id = ?)", undef,
2643 $newblock, $binfo->{parent_id}, $prime);
2644 $dbh->do("DELETE FROM poolips WHERE parent_id = ? AND ip <<= ? ", undef,
2645 $prime, $newblock);
2646
2647 } # $args{newtype} if()
2648
2649 $dbh->commit;
2650 };
2651 if ($@) {
2652 my $msg = $@;
2653 $errstr = $msg;
2654 $dbh->rollback;
2655 return ('FAIL',$msg);
2656 }
2657
2658# Make the assumption that any change crossing /24 or /16 boundaries will not come out right. Reverse DNS
2659# updates for this operation are already complex enough without handling those edge cases.
2660# ... er, how do we detect this?
2661
2662 # Return early if the block wasn't flagged as rDNS-able
2663 return \@retlist unless $binfo->{revavail} || $binfo->{revpartial};
2664
2665 if ($args{newtype} =~ /.[cm]/) {
2666
2667 if ($args{scope} eq 'keepall') {
2668 # Add new rDNS for new container
2669 _rpc('addOrUpdateRevRec', cidr => $binfo->{block}, name => $binfo->{rdns}, rpcuser => $args{user});
2670
2671 } else {
2672 # Resize rDNS template for $prime
2673 _rpc('resizeTemplate', oldcidr => "$binfo->{block}", newcidr => $newblock->network.'', rpcuser => $args{user});
2674
2675 # Assemble a list of blocks to delete...
2676 my $cidrlist;
2677 foreach my $mblock (@retlist) {
2678 $cidrlist .= $mblock->{block}."," unless $mblock->{block} =~ $newblock;
2679 }
2680
2681 # ... then make slight variant batch delete calls depending on the merge scope
2682 if ($args{scope} eq 'mergepeer') {
2683 # Delete separate rDNS for other peers
2684 $cidrlist =~ s/,$//;
2685 _rpc('delRevSet', cidrlist => $cidrlist, rpcuser => $args{user}, delforward => 'y', delsubs => 'n',
2686 parpatt => $pinfo->{rdns});
2687
2688 } elsif ($args{scope} eq 'clearpeer') {
2689 # Delete all rDNS within other peers
2690 $cidrlist =~ s/,$//;
2691 _rpc('delRevSet', cidrlist => $cidrlist, rpcuser => $args{user}, delforward => 'y', delsubs => 'y',
2692 parpatt => $pinfo->{rdns})
2693
2694 } elsif ($args{scope} eq 'clearall') {
2695 # Delete all other records within the new block
2696 $cidrlist .= $binfo->{block};
2697 _rpc('delRevSet', cidrlist => $cidrlist, rpcuser => $args{user}, delforward => 'y', delsubs => 'y',
2698 parpatt => $pinfo->{rdns});
2699
2700 } # scope, second level
2701 } # scope, !keepall
2702
2703 } elsif ($args{newtype} =~ /.[dp]/) {
2704 # Merge to pool
2705
2706 # Resize rDNS template for $prime
2707 _rpc('resizeTemplate', oldcidr => "$binfo->{block}", newcidr => $newblock->network.'', rpcuser => $args{user});
2708
2709 if ($args{scope} eq 'keepall' || $args{scope} eq 'mergepeer') {
2710 # Assemble a list of blocks to convert from template to individual records...
2711 my @convlist;
2712 my @dellist;
2713 foreach my $mblock (@retlist) {
2714 next if $mblock->{block} =~ $newblock;
2715 if ($mblock->{mtype} =~ /.[cmdp]/) {
2716 # Container and pool templates get deleted
2717 push @dellist, $mblock->{block};
2718 } else {
2719 # Not-containers get converted to per-IP reverse records
2720 push @convlist, $mblock->{block};
2721 }
2722 }
2723 # And do the calls.
2724 _rpc('delRevSet', cidrlist => join(',', @dellist), rpcuser => $args{user}, delforward => 'y', delsubs => 'n',
2725 parpatt => $pinfo->{rdns});
2726 _rpc('templatesToRecords', templates => \@convlist, rpcuser => $args{user});
2727
2728 } # scope eq 'keepall' || 'mergepeer'
2729 else {
2730
2731 # Assemble a list of blocks to convert from template to individual records...
2732 my @convlist;
2733 my @dellist;
2734 my @fulldellist;
2735# There may be an impossible edge case that can be optimized away in here...
2736 foreach my $mblock (@retlist) {
2737 my $checkcidr = new NetAddr::IP $mblock->{block};
2738 next if $mblock->{block} =~ $newblock;
2739 if (!$block->contains($checkcidr)) {
2740 # Blocks not within the original get deleted
2741 push @fulldellist, $mblock->{block};
2742 }
2743 elsif ($mblock->{mtype} =~ /.[cmdp]/) {
2744 # Containers and pools get deleted
2745 push @dellist, $mblock->{block};
2746 } else {
2747 # Whatever's left over gets converted
2748 push @convlist, $mblock->{block};
2749 }
2750 } # foreach @retlist
2751 # And do the calls.
2752 if ($args{scope} eq 'clearpeer') {
2753 # Not happy doing this many, but there isn't really a better way.
2754 # We delete ALL EVARYTHING in peer blocks...
2755 _rpc('delRevSet', cidrlist => join(',', @fulldellist), rpcuser => $args{user}, delforward => 'y',
2756 delsubs => 'y', parpatt => $pinfo->{rdns}) if @fulldellist;
2757 # ... and just the template for container or pool templates in $prime...
2758 _rpc('delRevSet', cidrlist => join(',', @dellist), rpcuser => $args{user}, delforward => 'y',
2759 delsubs => 'n', parpatt => $pinfo->{rdns}) if @dellist;
2760 # ... and convert a few to record groups
2761 _rpc('templatesToRecords', templates => \@convlist, rpcuser => $args{user}) if @convlist;
2762 }
2763 if ($args{scope} eq 'clearall') {
2764# consider just doing join(',',$newblock->split($newblock->masklen+1))?
2765 _rpc('delRevSet', cidrlist => join(',', @fulldellist, @dellist, @convlist, $binfo->{block}),
2766 rpcuser => $args{user}, delforward => 'y', delsubs => 'y', parpatt => $pinfo->{rdns});
2767 }
2768
2769 } # scope eq 'clearpeer' || 'clearall'
2770
2771 } elsif ($args{newtype} =~ /.[enr]/) {
2772 # Merge to leaf type
2773
2774 # Resize rDNS template for $prime
2775 _rpc('resizeTemplate', oldcidr => "$binfo->{block}", newcidr => $newblock->network.'', rpcuser => $args{user});
2776
2777 # Assemble a list of blocks to delete...
2778 my $cidrlist;
2779 foreach my $mblock (@retlist) {
2780 $cidrlist .= $mblock->{block}."," unless $mblock->{block} =~ $newblock;
2781 }
2782 # Delete all other records within the new block
2783 $cidrlist .= $binfo->{block};
2784 _rpc('delRevSet', cidrlist => $cidrlist, rpcuser => $args{user}, delforward => 'y', delsubs => 'y',
2785 parpatt => $pinfo->{rdns});
2786
2787 } # type grouping for rDNS calls
2788
2789 return \@retlist;
2790
2791} # end mergeBlocks()
2792
2793
2794## IPDB::deleteBlock()
2795# Removes an allocation from the database, including deleting IPs
2796# from poolips and recombining entries in freeblocks if possible
2797# Also handles "deleting" a static IP allocation, and removal of a master
2798# Requires a database handle, the block to delete, the routing depth (if applicable),
2799# the VRF ID, and a flag to indicate whether to delete associated forward DNS entries
2800# as well as the reverse entry
2801sub deleteBlock {
2802 my ($dbh,$id,$basetype,$delfwd,$user) = @_;
2803
2804 # Collect info about the block we're going to delete
2805 my $binfo = getBlockData($dbh, $id, $basetype);
2806 my $cidr = new NetAddr::IP $binfo->{block};
2807
2808# For possible auto-VRF-ignoring (since public IPs shouldn't usually be present in more than one VRF)
2809# is_rfc1918 requires NetAddr::IP >= 4.059
2810# rather than doing this over and over and over.....
2811 my $tmpnum = $cidr->numeric;
2812# 192.168.0.0/16 -> 192.168.255.255 => 3232235520 -> 3232301055
2813# 172.16.0.0/12 -> 172.31.255.255 => 2886729728 -> 2887778303
2814# 10.0.0.0/8 -> 10.255.255.255 => 167772160 -> 184549375
2815 my $isprivnet = (3232235520 <= $tmpnum && $tmpnum <= 3232301055) ||
2816 (2886729728 <= $tmpnum && $tmpnum <= 2887778303) ||
2817 (167772160 <= $tmpnum && $tmpnum <= 184549375);
2818
2819 my $sth;
2820
2821 # Magic variables used for odd allocation cases.
2822 my $container;
2823 my $con_type;
2824
2825
2826 # temporarily forced null, until a sane UI for VRF tracking can be found.
2827# $vrf = '';# if !$vrf; # as with SQL, the null value is not equal to ''. *sigh*
2828
2829 # To contain the error message, if any.
2830 my $msg = "Unknown error deallocating $binfo->{type} $cidr";
2831 my $goback; # to put the parent in so we can link back where the deallocate started
2832
2833 # Enable transactions and exception-on-errors... but only for this sub
2834 local $dbh->{AutoCommit} = 0;
2835 local $dbh->{RaiseError} = 1;
2836
2837 if ($binfo->{type} =~ /^.i$/) {
2838 # First case. The "block" is a static IP
2839 # Note that we still need some additional code in the odd case
2840 # of a netblock-aligned contiguous group of static IPs
2841 my $pinfo;
2842
2843 eval {
2844 $msg = "Unable to deallocate $disp_alloctypes{$binfo->{type}} $cidr";
2845 $pinfo = getBlockData($dbh, $binfo->{parent_id}, 'b');
2846 $dbh->do("UPDATE poolips SET custid = ?, available = 'y',".
2847 "city = (SELECT city FROM allocations WHERE id = ?),".
2848 "description = '', notes = '', circuitid = '', vrf = ?, backup_id = 0".
2849 " WHERE id = ?", undef,
2850 ($pinfo->{custid}, $binfo->{parent_id}, $pinfo->{vrf}, $id) );
2851 $dbh->do("DELETE FROM backuplist WHERE backup_id = ?", undef, $binfo->{hasbk})
2852 if $binfo->{hasbk};
2853 $dbh->commit;
2854 };
2855 if ($@) {
2856 $msg .= ": $@";
2857 eval { $dbh->rollback; };
2858 return ('FAIL',$msg);
2859 }
2860
2861##fixme: RPC return code?
2862 _rpc('delByCIDR', cidr => "$cidr", user => $user, delforward => $delfwd, rpcuser => $user)
2863 if ($pinfo->{revavail} || $pinfo->{revpartial});
2864
2865 return ('OK',"OK");
2866
2867 } elsif ($binfo->{type} eq 'mm') { # end alloctype =~ /.i/
2868 # Second case. The block is a full master block
2869
2870##fixme: VRF limit
2871 $msg = "Unable to delete master block $cidr";
2872 eval {
2873 $dbh->do("DELETE FROM allocations WHERE cidr <<= ? AND master_id = ?", undef, ($cidr, $binfo->{master_id}) );
2874 $dbh->do("DELETE FROM freeblocks WHERE cidr <<= ? AND master_id = ?", undef, ($cidr, $binfo->{master_id}) );
2875 $dbh->do("DELETE FROM backuplist WHERE backup_id = ?", undef, $binfo->{hasbk})
2876 if $binfo->{hasbk};
2877 $dbh->commit;
2878 };
2879 if ($@) {
2880 $msg .= ": $@";
2881 eval { $dbh->rollback; };
2882 return ('FAIL', $msg);
2883 }
2884
2885 # Have to handle potentially split reverse zones. Assume they *are* split,
2886 # since if we added them here, they would have been added split.
2887# allow splitting reverse zones to be disabled, maybe, someday
2888#if ($splitrevzones && !$cidr->{isv6}) {
2889 my @zonelist;
2890 if (1 && !$cidr->{isv6}) {
2891 my $splitpoint = ($cidr->masklen <= 16 ? 16 : 24); # hack pthui
2892 @zonelist = $cidr->split($splitpoint);
2893 } else {
2894 @zonelist = ($cidr);
2895 }
2896 my @fails;
2897 foreach my $subzone (@zonelist) {
2898 # We don't wrap this call tighter, since there isn't an inherent allocation to check for rDNS-ability.
2899 if ($rpc_url && !_rpc('delZone', zone => "$subzone", revrec => 'y', rpcuser => $user, delforward => $delfwd) ) {
2900 push @fails, ("$subzone" => $errstr);
2901 }
2902 }
2903 if (@fails) {
2904 return ('WARN',"Warning(s) deleting $cidr from reverse DNS:\n".join("\n", @fails));
2905 }
2906 return ('OK','OK');
2907
2908 } else { # end alloctype master block case
2909
2910 ## This is a big block; but it HAS to be done in a chunk. Any removal
2911 ## of a netblock allocation may result in a larger chunk of free
2912 ## contiguous IP space - which may in turn be combined into a single
2913 ## netblock rather than a number of smaller netblocks.
2914
2915 my $retcode = 'OK';
2916 my ($ptype,$pcity,$ppatt,$p_id);
2917
2918 eval {
2919
2920##fixme: add recursive flag to allow "YES DAMMIT DELETE ALL EVARYTHING!!1!!" without
2921# explicitly deleting any suballocations of the block to be deleted.
2922
2923 # get parent info of the block we're deleting
2924 my $pinfo = getBlockData($dbh, $binfo->{parent_id});
2925 $ptype = $pinfo->{type};
2926 $pcity = $pinfo->{city};
2927 $ppatt = $pinfo->{rdns};
2928 $p_id = $binfo->{parent_id};
2929
2930 # Delete the block
2931 $dbh->do("DELETE FROM allocations WHERE id = ?", undef, ($id) );
2932
2933 # munge the parent type a little
2934 $ptype = (split //, $ptype)[1];
2935
2936##fixme: you can't... CAN NOT.... assign the same public IP to multiple things.
2937# 'Net don't work like that, homey. Restrict VRF-uniqueness to private IPs?
2938# -> $isprivnet flag from start of sub
2939
2940 # check to see if any container allocations could be the "true" parent
2941 my ($tparent,$tpar_id,$trtype,$tcity);
2942 $tpar_id = 0;
2943
2944##fixme: this is far simpler in the strict VRF case; we "know" that any allocation
2945# contained by a container is a part of the same allocation tree when the VRF fields are equal.
2946
2947# logic:
2948# For each possible container of $cidr
2949# note the parent id
2950# walk the chain up the parents
2951# if we intersect $cidr's current parent, break
2952# if we've intersected $cidr's current parent
2953# set some variables to track that block
2954# break
2955
2956# Set up part of "is it in the middle of a pool?" check
2957 my $wuzpool = $dbh->selectrow_hashref("SELECT cidr,parent_id,type,city,custid,id FROM allocations ".
2958 "WHERE (type LIKE '_d' OR type LIKE '_p') AND cidr >> ? AND master_id = ?", { Slice => {} },
2959 ($cidr, $binfo->{master_id}) );
2960
2961##fixme?
2962# edge cases not handled, or handled badly:
2963# -> $cidr managed to get to be the entirety of an IP pool
2964
2965 if ($wuzpool && $wuzpool->{id} != $id) {
2966 # we have legacy goo to be purified
2967 # going to ignore nested pools; not possible to create them via API and no current legacy data includes any.
2968
2969 # for convenience
2970 my $poolid = $wuzpool->{id};
2971 my $pool = $wuzpool->{cidr};
2972 my $poolcity = $wuzpool->{city};
2973 my $pooltype = $wuzpool->{type};
2974 my $poolcustid = $wuzpool->{custid};
2975
2976 $retcode = 'WARNPOOL';
2977 $goback = "$poolid,$pool";
2978 # We've already deleted the block, now we have to stuff its IPs into the pool.
2979 $pooltype =~ s/[dp]$/i/; # change type to static IP
2980 my $sth2 = $dbh->prepare("INSERT INTO poolips (ip,city,type,custid,parent_id) VALUES ".
2981 "(?,'$poolcity','$pooltype','$poolcustid',$poolid)");
2982
2983##fixme: need to not insert net, gateway, and bcast on "real netblock" pools (DHCPish)
2984 # don't insert .0
2985 $sth2->execute($cidr->addr) unless $cidr->addr =~ m|\.0$|;
2986 $cidr++;
2987 my $bcast = $cidr->broadcast;
2988 while ($cidr != $bcast) {
2989 $sth2->execute($cidr->addr);
2990 $cidr++;
2991 }
2992 # don't insert .255
2993 $sth2->execute($cidr->addr) unless $cidr->addr =~ m|\.255$|;
2994
2995# Weirdness Happens. $cidr goes read-only somewhere (this is a thing?!?),
2996# causing ->split, ->hostenum, and related methods to explode. O_o
2997# foreach my $ip ($cidr->hostenum) {
2998# $sth2->execute($ip);
2999# }
3000
3001 }
3002
3003## important!
3004# ... or IS IT?
3005# we may have undef'ed $wuzpool above, if the allocation tree $cidr is in doesn't intersect the pool we found
3006#if (!$wuzpool) {
3007
3008 else {
3009
3010# Edge case: Block is the same size as more than one parent level. Should be rare.
3011# - mainly master + first routing. Sorting on parent_id hides the problem pretty well,
3012# but it's likely still possible to fail in particularly well-mangled databases.
3013# The ultimate fix for this may be to resurrect the "routing depth" atrocity. :/
3014 # Get all possible (and probably a number of impossible) containers for $cidr
3015 $sth = $dbh->prepare("SELECT cidr,parent_id,type,city,id FROM allocations ".
3016 "WHERE (type LIKE '_m' OR type LIKE '_c') AND cidr >>= ? AND master_id = ? ".
3017 "ORDER BY masklen(cidr) DESC,parent_id DESC");
3018 $sth->execute($cidr, $binfo->{master_id});
3019
3020 # Quickly get certain fields (simpler than getBlockData()
3021 my $sth2 = $dbh->prepare("SELECT cidr,parent_id,type,city FROM allocations ".
3022 "WHERE (type LIKE '_m' OR type LIKE '_c') AND id = ? AND master_id = ?");
3023
3024 # For each possible container of $cidr...
3025 while (my @data = $sth->fetchrow_array) {
3026 my $i = 0;
3027 # Save some state and set a start point - parent ID of container we're checking
3028 $tparent = $data[0];
3029 my $ppid = $data[1];
3030 $trtype = $data[2];
3031 $tcity = $data[3];
3032 $tpar_id = $data[4];
3033 last if $data[4] == $binfo->{parent_id}; # Preemptively break if we're already in the right place
3034 last if $ppid == $binfo->{parent_id}; # ... or if the parent of the container is the block's parent
3035 while (1) {
3036 # Retrieve bits on that parent ID
3037 $sth2->execute($ppid, $binfo->{master_id});
3038 my @container = $sth2->fetchrow_array;
3039 $ppid = $container[1];
3040 last if $container[1] == 0; # Break if we've hit a master block
3041 last if $ppid == $binfo->{parent_id}; # Break if we've reached the block $cidr is currently in
3042 }
3043 last if $ppid == $binfo->{parent_id};
3044 }
3045
3046 # found an alternate parent; reset some parent-info bits
3047 if ($tpar_id != $binfo->{parent_id}) {
3048 $ptype = (split //, $trtype)[1];
3049 $pcity = $tcity;
3050 $retcode = 'WARNMERGE'; # may be redundant
3051 $p_id = $tpar_id;
3052 }
3053
3054 $goback = "$p_id,$tparent"; # breadcrumb, currently only used in case of live-parent-is-not-true-parent
3055
3056 # Special case - delete pool IPs
3057 if ($binfo->{type} =~ /^.[pd]$/) {
3058 # We have to delete the IPs from the pool listing.
3059##fixme: rdepth? vrf?
3060 $dbh->do("DELETE FROM poolips WHERE parent_id = ?", undef, ($id) );
3061 }
3062
3063 $pinfo = getBlockData($dbh, $p_id);
3064
3065 # If the block wasn't legacy goo embedded in a static pool, we check the
3066 # freeblocks in the identified parent to see if we can combine any of them.
3067
3068 # if the block to be deleted is a container, move its freeblock(s) up a level, and reset their parenting info
3069 if ($binfo->{type} =~ /^.[mc]/) {
3070 # move the freeblocks into the parent
3071 # we don't insert a new freeblock because there could be a live reparented sub.
3072 $dbh->do("UPDATE freeblocks SET parent_id = ?, routed = ?, city = ? WHERE parent_id = ?", undef,
3073 ($p_id, $ptype, $pcity, $id) );
3074 } else {
3075 # ... otherwise, add the freeblock
3076 $dbh->do("INSERT INTO freeblocks (cidr, city, routed, parent_id, master_id) VALUES (?,?,?,?,?)", undef,
3077 ($cidr, $pcity, $ptype, $p_id, $binfo->{master_id}) );
3078 }
3079
3080 # Walk the free blocks in the parent and reduce them to the minimal set of CIDR ranges necessary
3081 _compactFree($dbh, $p_id);
3082
3083 } # done returning IPs to the appropriate place
3084
3085 # If we got here, we've succeeded. Whew!
3086 $dbh->commit;
3087 }; # end eval
3088 if ($@) {
3089 $msg .= ": $@";
3090 eval { $dbh->rollback; };
3091 return ('FAIL', $msg);
3092 }
3093
3094##fixme: RPC return code?
3095 _rpc('delByCIDR', cidr => "$cidr", rpcuser => $user, delforward => $delfwd, delsubs => 'y', parpatt => $ppatt)
3096 if ($binfo->{revavail} || $binfo->{revpartial});
3097
3098 return ($retcode, $goback);
3099
3100 } # end alloctype != netblock
3101
3102} # end deleteBlock()
3103
3104
3105## IPDB::getBlockData()
3106# Get CIDR or IP, custid, type, city, circuit ID, description, notes, modification time,
3107# private/restricted data, and backup fields, for a CIDR block or pool IP
3108# Also returns SWIP status flag for CIDR blocks or pool netblock for IPs
3109# Takes the block ID or IP to look up and an optional flag to indicate a pool IP lookup
3110# instead of a netblock.
3111# Returns a hashref to the block data
3112sub getBlockData {
3113 my $dbh = shift;
3114 my $id = shift;
3115 my $type = shift || 'b'; # default to netblock for lazy callers
3116
3117 # netblocks are in the allocations table; pool IPs are in the poolips table.
3118 # If we try to look up a CIDR in an integer field we should just get back nothing.
3119 my ($btype) = $dbh->selectrow_array("SELECT type FROM allocations WHERE id=?", undef, ($id) );
3120
3121 # Note city, vrf, parent_id and master_id removed due to JOIN uncertainty for block allocations
3122 my $commonfields = q(custid, type, circuitid, description, notes, modifystamp AS lastmod,
3123 privdata, vlan, rdns);
3124 my $bkfields = q(b.backup_id AS hasbk, b.bkbrand, b.bkmodel, b.bktype, b.bkport, b.bksrc,
3125 b.bkuser, b.bkvpass, b.bkepass, b.bkip);
3126
3127 if ($type eq 'i') {
3128 my $binfo = $dbh->selectrow_hashref(qq(
3129 SELECT p.id, p.ip AS block, p.city, p.vrf, p.parent_id, p.master_id, $commonfields,
3130 d.zone >> p.ip AS revavail,
3131 $bkfields
3132 FROM poolips p
3133 LEFT JOIN dnsavail d ON p.master_id = d.parent_alloc AND p.ip << d.zone
3134 LEFT JOIN backuplist b ON p.backup_id = b.backup_id
3135 WHERE id = ?
3136 ), undef, ($id) );
3137 return $binfo;
3138 } else {
3139 my $binfo = $dbh->selectrow_hashref(qq(
3140 SELECT a.id, a.cidr AS block, a.city, a.vrf, a.parent_id, a.master_id, swip, $commonfields,
3141 f.cidr AS reserve, f.id as reserve_id,
3142 d.zone >>= a.cidr AS revavail, d.zone << a.cidr AS revpartial,
3143 $bkfields
3144 FROM allocations a
3145 LEFT JOIN freeblocks f ON a.id=f.reserve_for
3146 LEFT JOIN dnsavail d ON a.master_id = d.parent_alloc AND (a.cidr <<= d.zone OR a.cidr >> d.zone)
3147 LEFT JOIN backuplist b ON a.backup_id = b.backup_id
3148 WHERE a.id = ?
3149 ), undef, ($id) );
3150
3151 return $binfo;
3152 }
3153} # end getBlockData()
3154
3155
3156## IPDB::getBlockRDNS()
3157# Gets reverse DNS pattern for a block or IP. Note that this will also
3158# retrieve any default pattern following the parent chain up, and check via
3159# RPC (if available) to see what the narrowest pattern for the requested block is
3160# Returns the current pattern for the block or IP.
3161sub getBlockRDNS {
3162 my $dbh = shift;
3163 my %args = @_;
3164
3165 $args{type} = 'b' if !$args{type};
3166 my $cached = 1;
3167
3168 # snag entry from database
3169 my ($rdns,$rfrom,$pid);
3170 if ($args{type} =~ /.i/) {
3171 ($rdns, $rfrom, $pid) = $dbh->selectrow_array("SELECT rdns,ip,parent_id FROM poolips WHERE id = ?",
3172 undef, ($args{id}) );
3173 } else {
3174 ($rdns, $rfrom, $pid) = $dbh->selectrow_array("SELECT rdns,cidr,parent_id FROM allocations WHERE id = ?",
3175 undef, ($args{id}) );
3176 }
3177
3178 # Can't see a way this could end up empty, for any case I care about. If the caller
3179 # doesn't know an allocation ID to request, then they don't know anything else anyway.
3180 my $selfblock = $rfrom;
3181
3182 my $type;
3183 while (!$rdns && $pid) {
3184 ($rdns, $rfrom, $pid, $type) = $dbh->selectrow_array(
3185 "SELECT rdns,cidr,parent_id,type FROM allocations WHERE id = ?",
3186 undef, ($pid) );
3187 last if $type eq 'mm'; # break loops in unfortunate legacy data
3188 }
3189
3190 # use the actual allocation to check against the DNS utility; we don't want
3191 # to always go chasing up the chain to the master... which may (usually won't)
3192 # be present directly in DNS anyway
3193 my $cidr = new NetAddr::IP $selfblock;
3194
3195 if ($rpc_url) {
3196 # Use the first /16 or /24, rather than dithering over which sub-/14 /16
3197 # or sub-/19 /24 to retrieve - it's the least-wrong way to do things.
3198
3199 my ($rpcblock) = ($cidr->masklen <= 24 ? $cidr->split( ($cidr->masklen <= 16 ? 16 : 24) ) : $cidr);
3200 my %rpcargs = (
3201 rpcuser => $args{user},
3202 group => $revgroup, # not sure how this could sanely be exposed, tbh...
3203 cidr => "$rpcblock",
3204 );
3205
3206 $errstr = '';
3207 my $remote_rdns = _rpc('getRevPattern', %rpcargs);
3208 if ($remote_rdns) {
3209 $rdns = $remote_rdns;
3210 $cached = 0;
3211 } else {
3212 if (!$errstr) {
3213 # no error, but no data
3214 $cached = 0;
3215 }
3216 }
3217 }
3218
3219 # hmm. do we care about where it actually came from?
3220 return $rdns, $cached;
3221} # end getBlockRDNS()
3222
3223
3224## IPDB::getRDNSbyIP()
3225# Get individual reverse entries for the IP or CIDR IP range passed. Sort of looking the
3226# opposite direction down the netblock tree compared to getBlockRDNS() above.
3227sub getRDNSbyIP {
3228 my $dbh = shift;
3229 my %args = @_; # We want to accept a variety of call types
3230
3231 # key arguments: allocation ID, type
3232 unless ($args{id} || $args{type}) {
3233 $errstr = 'Missing allocation ID or type';
3234 return;
3235 }
3236
3237 my @ret = ();
3238 # special case: single IP. Check if it's an allocation or in a pool, then do the RPC call for fresh data.
3239 if ($args{type} =~ /^.i$/) {
3240 my ($ip, $localrev) = $dbh->selectrow_array("SELECT ip, rdns FROM poolips WHERE id = ?", undef, ($args{id}) );
3241 push @ret, { 'r_ip' => $ip, 'iphost' => $localrev };
3242 } else {
3243 if ($rpc_url) {
3244 my %rpcargs = (
3245 rpcuser => $args{user},
3246 group => $revgroup, # not sure how this could sanely be exposed, tbh...
3247 cidr => $args{range},
3248 );
3249
3250 my $remote_rdns = _rpc('getRevSet', %rpcargs);
3251 return $remote_rdns;
3252# $rdns = $remote_rdns if $remote_rdns;
3253# $cached = 0;
3254 }
3255 }
3256 return \@ret;
3257} # end getRDNSbyIP()
3258
3259
3260## IPDB::getNodeList()
3261# Gets a list of node ID+name pairs as an arrayref to a list of hashrefs
3262sub getNodeList {
3263 my $dbh = shift;
3264
3265 my $ret = $dbh->selectall_arrayref("SELECT node_id, node_name FROM nodes ORDER BY node_type,node_id",
3266 { Slice => {} });
3267 return $ret;
3268} # end getNodeList()
3269
3270
3271## IPDB::getNodeName()
3272# Get node name from the ID
3273sub getNodeName {
3274 my $dbh = shift;
3275 my $nid = shift;
3276
3277 my ($nname) = $dbh->selectrow_array("SELECT node_name FROM nodes WHERE node_id = ?", undef, ($nid) );
3278 return $nname;
3279} # end getNodeName()
3280
3281
3282## IPDB::getNodeInfo()
3283# Get node name and ID associated with a block
3284sub getNodeInfo {
3285 my $dbh = shift;
3286 my $block = shift;
3287
3288 my ($nid, $nname) = $dbh->selectrow_array("SELECT nodes.node_id,node_name FROM nodes INNER JOIN noderef".
3289 " ON nodes.node_id=noderef.node_id WHERE noderef.block = ?", undef, ($block) );
3290 return ($nid, $nname);
3291} # end getNodeInfo()
3292
3293
3294## IPDB::mailNotify()
3295# Sends notification mail to recipients regarding an IPDB operation
3296sub mailNotify {
3297 my $dbh = shift;
3298 my ($action,$subj,$message) = @_;
3299
3300 return if $smtphost eq 'smtp.example.com'; # do nothing if still using default SMTP host.
3301
3302##fixme: need to redesign the breakdown/processing for $action for proper handling of all cases
3303
3304# split action into parts for fiddlement. nb: there are almost certainly better ways to do this.
3305 my @actionbits = split //, $action;
3306
3307 # want to notify anyone who has specifically requested notify on *this* type ($action as passed),
3308 # on "all static IP types" or "all pool types" (and other last-char-in-type groupings), on eg "all DSL types",
3309 # and "all events with this action"
3310 my @actionsets = ($action);
3311##fixme: ick, eww. really gotta find a better way to handle this...
3312 push @actionsets, ($actionbits[0].'.'.$actionbits[2],
3313 $actionbits[0].$actionbits[1].'.', $actionbits[0].'a') if $action =~ /^.{3}$/;
3314
3315 my $mailer = Net::SMTP->new($smtphost, Hello => "ipdb.$domain");
3316
3317 # get recip list from db
3318 my $sth = $dbh->prepare("SELECT reciplist FROM notify WHERE action=?");
3319
3320 my %reciplist;
3321 foreach (@actionsets) {
3322 $sth->execute($_);
3323##fixme - need to handle db errors
3324 my ($recipsub) = $sth->fetchrow_array;
3325 next if !$recipsub;
3326 foreach (split(/,/, $recipsub)) {
3327 $reciplist{$_}++;
3328 }
3329 }
3330
3331 return if !%reciplist;
3332
3333 foreach my $recip (keys %reciplist) {
3334 $mailer->mail($smtpsender);
3335 $mailer->to($recip);
3336 $mailer->data("From: \"$org_name IP Database\" <$smtpsender>\n",
3337 "To: $recip\n",
3338 "Date: ".strftime("%a, %d %b %Y %H:%M:%S %z",localtime)."\n",
3339 "Subject: {IPDB} $subj\n",
3340 "X-Mailer: IPDB Notify v".sprintf("%.1d",$IPDB::VERSION)."\n",
3341 "Organization: $org_name\n",
3342 "\n$message\n");
3343 }
3344 $mailer->quit;
3345}
3346
3347# Indicates module loaded OK. Required by Perl.
33481;
Note: See TracBrowser for help on using the repository browser.