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

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

/trunk

Add AWOL ACL message

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