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

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

/trunk

Update getBlockData() to retrieve backup data if present. See #52.

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