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

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

/trunk

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