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

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

/trunk

Fix subtle edge-case bug in initPool() where the check for preexisting
net and bcast IPs looked for the wrong thing, and tried to insert them
again.

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