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

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

/trunk

Update listSummary() to slice by VRF. See #54.

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