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

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

/trunk

Commit lingering fix in allocateBlock() for incorrect failure allocating
a pool IP

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