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

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

/trunk

Cleanup while rechecking merge-to-container in UI:

  • Move descriptive strings for merge scopes into a hash in IPDB.pm, so we don't have to update them everywhere every time they might change... now that most of the changes are done, of course.
  • Refiddle listForMerge's freeblock branch to show only direct children, or all free blocks depending on another optional argument.
  • Render previous point pointless due to dropping freeblocks from the return list of merged blocks anyway, because Confusion.
  • Force scope as well as type when merging a master block. Merging any other type in a way that happens to intersect a master remains undefined.
  • Make sure to capture the blocks merged/deleted for return.
  • Fix up some variable names for consistency.
  • Fix stupid typo missed in r732.

See #8.

  • Property svn:keywords set to Date Rev Author
File size: 101.6 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-25 22:25:20 +0000 (Mon, 25 May 2015) $
6# SVN revision $Rev: 733 $
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 # Trap errors so we can pass them back to the caller. Even if the
1540 # caller is only ever supposed to be local, and therefore already
1541 # trapping errors. >:(
1542 local $dbh->{AutoCommit} = 0; # These need to be local so we don't
1543 local $dbh->{RaiseError} = 1; # step on our toes by accident.
1544
1545 eval {
1546 # have to insert all pool IPs into poolips table as "unallocated".
1547 $sth = $dbh->prepare("INSERT INTO poolips (ip,custid,city,type,parent_id,master_id) VALUES (?,?,?,?,?,?)");
1548
1549 # in case of pool extension by some means, we need to see what IPs were already inserted
1550 my $tmp1 = $dbh->selectall_arrayref("SELECT ip FROM poolips WHERE parent_id = ?", undef, $parent);
1551 my %foundips;
1552 foreach (@{$tmp1}) {
1553 $foundips{$_->[0]} = 1;
1554 }
1555
1556# Dodge an edge case - pool where IPs have been "stolen" and turned into a netblock assignment.
1557# We can't just "get all the current IPs, and add the missing ones", because some IPs are
1558# legitimately missing (for stretchy values of "legitimately").
1559
1560 my $pdata = getBlockData($dbh, $parent);
1561 my $pcidr = new NetAddr::IP $pdata->{block};
1562
1563 if ($pcidr != $pool) {
1564 # enumerate the IPs from the *old* pool, flag them as "found", so we can iterate the entire
1565 # requested pool and still make sure we skip the IPs in the old pool - even if they've been
1566 # "stolen" by legacy netblocks.
1567 my @oldips = $pcidr->hostenum;
1568 # decide whether to start excluding existing IPs at the "gateway" or "gateway+1"
1569 my $ostart = ($pdata->{type} =~ /^.d$/ ? 1 : 0);
1570 for (my $i = $ostart; $i<= $#oldips; $i++) {
1571 $foundips{$oldips[$i]} = 1;
1572 }
1573 }
1574
1575 # enumerate the hosts in the IP range - everything except the first (net) and last (bcast) IP
1576 my @poolip_list = $pool->hostenum;
1577
1578 # always check/add IPs from gw+1 through bcast-1:
1579 # (but the set won't be in oooorderrrrr! <pout>)
1580 for (my $i=1; $i<=$#poolip_list; $i++) {
1581 my $baseip = $poolip_list[$i]->addr;
1582 if ($baseip !~ /\.(?:0|255)$/ && !$foundips{$poolip_list[$i]}) {
1583 $sth->execute($baseip, $pcustid, $city, $type, $parent, $master);
1584 }
1585 }
1586
1587 # now do the special case - DSL/PPP blocks can use the "net", "gw", and "bcast" IPs.
1588 # we exclude .0 and .255 anyway, since while they'll mostly work, they *will* behave badly here and there.
1589 if ($class eq 'all') { # (DSL-ish block - *all* IPs available
1590 if ($pool->addr !~ /\.0$/) { # .0 causes weirdness.
1591 $sth->execute($pool->addr, $pcustid, $city, $type, $parent, $master) unless $foundips{$pool->addr};
1592 }
1593 $sth->execute($poolip_list[0]->addr, $pcustid, $city, $type, $parent, $master) unless $foundips{$poolip_list[0]};
1594 $pool--;
1595 if ($pool->addr !~ /\.255$/) { # .255 can cause weirdness.
1596 $sth->execute($pool->addr, $pcustid, $city, $type, $parent, $master) unless $foundips{$pool->addr};
1597 }
1598 }
1599# don't commit here! the caller may not be done.
1600# $dbh->commit;
1601 };
1602 if ($@) {
1603 $msg = $@;
1604# Don't roll back! It's up to the caller to handle this.
1605# eval { $dbh->rollback; };
1606 return ('FAIL',$msg);
1607 } else {
1608 return ('OK',"OK");
1609 }
1610} # end initPool()
1611
1612
1613## IPDB::updateBlock()
1614# Update an allocation
1615# Takes all allocation fields in a hash
1616sub updateBlock {
1617 my $dbh = shift;
1618 my %args = @_;
1619
1620 return ('FAIL', 'Missing block to update') if !$args{block};
1621
1622 # Spaces don't show up well in lots of places. Make sure they don't get into the DB.
1623 $args{custid} =~ s/^\s+//;
1624 $args{custid} =~ s/\s+$//;
1625
1626 # do it all in a transaction
1627 local $dbh->{AutoCommit} = 0;
1628 local $dbh->{RaiseError} = 1;
1629
1630 my @fieldlist;
1631 my @vallist;
1632 foreach ('custid', 'city', 'description', 'notes', 'circuitid', 'privdata', 'rdns', 'vrf', 'vlan') {
1633 if ($args{$_}) {
1634 push @fieldlist, $_;
1635 push @vallist, $args{$_};
1636 }
1637 }
1638
1639 my $binfo;
1640 my $updtable = 'allocations';
1641 my $keyfield = 'id';
1642 if ($args{type} =~ /^(.)i$/) {
1643 $updtable = 'poolips';
1644 $binfo = getBlockData($dbh, $args{block}, 'i');
1645 } else {
1646## fixme: there's got to be a better way...
1647 $binfo = getBlockData($dbh, $args{block});
1648 if ($args{swip}) {
1649 if ($args{swip} eq 'on' || $args{swip} eq '1' || $args{swip} eq 'y') {
1650 $args{swip} = 'y';
1651 } else {
1652 $args{swip} = 'n';
1653 }
1654 }
1655 foreach ('type', 'swip') {
1656 if ($args{$_}) {
1657 push @fieldlist, $_;
1658 push @vallist, $args{$_};
1659 }
1660 }
1661 }
1662
1663 return ('FAIL', 'No fields to update') if !@fieldlist;
1664
1665 my $sql = "UPDATE $updtable SET ";
1666 $sql .= join " = ?, ", @fieldlist;
1667
1668 eval {
1669 # check for block merge first...
1670 if ($args{fbmerge}) {
1671 my $cidr = NetAddr::IP->new($binfo->{block});
1672 my $newblock = NetAddr::IP->new($cidr->addr, $cidr->masklen - 1)->network;
1673 # safety net? make sure mergeable block passed in is really one or both of
1674 # a) reserved for expansion of the block and
1675 # b) confirmed CIDR-combinable
1676 # "safety? SELECT foo FROM freeblocks WHERE cidr << ? AND masklen(cidr) = ?, $newblock, ".$cidr->masklen."\n";
1677 $dbh->do("DELETE FROM freeblocks WHERE id=?", undef, $args{fbmerge});
1678 # ... so we can append the change in the stored CIDR field to extend the allocation.
1679 $sql .= " = ?, cidr";
1680 push @vallist, $newblock;
1681 # if we have an IP pool, call initPool to fill in any missing entries in the pool
1682 if ($binfo->{type} =~ /^.p$/) {
1683 my ($code,$rmsg) = initPool($dbh, "$newblock", $binfo->{type}, $binfo->{city}, 'all', $args{block});
1684 die $rmsg if $code eq 'FAIL';
1685 } elsif ($binfo->{type} =~ /^.d$/) {
1686 my ($code,$rmsg) = initPool($dbh, "$newblock", $binfo->{type}, $binfo->{city}, 'normal', $args{block});
1687 die $rmsg if $code eq 'FAIL';
1688 }
1689 }
1690
1691 # append another SQL fragment
1692 push @vallist, $args{block};
1693 $sql .= " = ? WHERE $keyfield = ?";
1694
1695 # do the update
1696 $dbh->do($sql, undef, @vallist);
1697
1698 if ($args{node}) {
1699 # done with delete/insert so we don't have to worry about funkyness updating a node ref that isn't there
1700 $dbh->do("DELETE FROM noderef WHERE block = ?", undef, ($binfo->{block}) );
1701 $dbh->do("INSERT INTO noderef (block,node_id) VALUES (?,?)", undef, ($binfo->{block}, $args{node}) )
1702 if $args{node} ne '--';
1703 }
1704
1705 $dbh->commit;
1706 };
1707 if ($@) {
1708 my $msg = $@;
1709 $dbh->rollback;
1710 return ('FAIL', $msg);
1711 }
1712
1713 # In case of any container (mainly master block), only update freeblocks so we don't stomp subs
1714 # (which would be the wrong thing in pretty much any case except "DELETE ALL EVARYTHING!!1!oneone!")
1715 if ($binfo->{type} =~ '.[mc]') {
1716 # Not using listFree() as it doesn't return quite all of the blocks wanted.
1717 # Retrieve the immediate free blocks
1718 my $sth = $dbh->prepare(q(
1719 SELECT cidr FROM freeblocks WHERE parent_id = ?
1720 UNION
1721 SELECT cidr FROM freeblocks f WHERE
1722 cidr = (SELECT cidr FROM allocations a WHERE f.cidr = a.cidr)
1723 AND master_id = ?
1724 ) );
1725 $sth->execute($args{block}, $binfo->{master_id});
1726 my %fbset;
1727 while (my ($fb) = $sth->fetchrow_array) {
1728 $fbset{"host_$fb"} = $args{rdns};
1729 }
1730 # We use this RPC call instead of multiple addOrUpdateRevRec calls, since we don't
1731 # know how many records we'll be updating and more than 3-4 is far too slow. This
1732 # should be safe to call unconditionally.
1733 # Requires dnsadmin >= r678
1734 _rpc('updateRevSet', %fbset, rpcuser => $args{user});
1735
1736 } else {
1737 $binfo->{block} =~ s|/32$||;
1738 _rpc('addOrUpdateRevRec', cidr => $binfo->{block}, name => $args{rdns}, rpcuser => $args{user});
1739
1740 # and the per-IP set, if there is one.
1741 _rpc('updateRevSet', %{$args{iprev}}, rpcuser => $args{user}) if keys (%{$args{iprev}});
1742 }
1743
1744 return ('OK','OK');
1745} # end updateBlock()
1746
1747
1748## IPDB::splitBlock()
1749# Splits an existing allocation into two or more smaller allocations based on a passed netmask
1750# Duplicates all other data
1751# Returns an arrayref to a list of hashrefs with ID and CIDR keys for the list of new allocations.
1752# Should probably commit DNS magic to realign DNS data
1753# Mostly works but may return Strange Things(TM) if used on a master block
1754sub splitBlock {
1755 my $dbh = shift;
1756 my %args = @_;
1757# my $id = shift;
1758# my $basetype = shift;
1759# my $newmask = shift;
1760
1761##fixme: set errstr on errors so caller can suitably clue-by-four the user
1762 return if $args{basetype} ne 'b'; # only netblocks allowed!
1763
1764 my $binfo = getBlockData($dbh, $args{id});
1765 return if !$binfo;
1766
1767 return if $args{newmask} !~ /^\d+$/;
1768
1769 my @ret;
1770 my $block = new NetAddr::IP $binfo->{block};
1771 my $oldmask = $block->masklen;
1772
1773 # Fail if the block to split is "too small" - eg, can't split a v4 /32 at all
1774 # failure modes:
1775 # difference between $oldmask and $newmask is negative or 0
1776 if ($args{newmask} - $oldmask <= 0) {
1777 $errstr = "Can't split a /$oldmask allocation into /$args{newmask} pieces";
1778 return;
1779 }
1780# # difference between $oldmask and $newmask is > n, for arbitrary n?
1781# if ($newmask - $oldmask > 42) { # because 42
1782# }
1783 # $oldmask > n, for arbitrary n? At least check limits of data type.
1784 if ($block->{isv6}) {
1785 if ($args{newmask} - $oldmask > 128) {
1786 $errstr = "Impossible IPv6 mask length /$args{newmask} requested";
1787 return;
1788 }
1789 } else {
1790 if ($args{newmask} - $oldmask > 32) {
1791 $errstr = "Impossible IPv4 mask length /$args{newmask} requested";
1792 return;
1793 }
1794 }
1795
1796 my @newblocks = $block->split($args{newmask});
1797
1798 local $dbh->{AutoCommit} = 0;
1799 local $dbh->{RaiseError} = 1;
1800
1801 eval {
1802 # line up a list of fields and values. Be nice if there was a handy way to do,
1803 # direct in SQL, something like
1804 # "INSERT INTO foo (f1,f2,f3) VALUES (newf1,(SELECT oldf2,oldf3 FROM foo WHERE baz))"
1805 my @fieldlist = qw(type city description notes circuitid privdata custid swip vrf vlan rdns parent_id master_id);
1806 my $fields_sql = join(',', @fieldlist);
1807 my @vals;
1808 foreach (@fieldlist) {
1809 push @vals, $binfo->{$_};
1810 }
1811 # note the first block in the split for return
1812 push @ret, {nid => $args{id}, nblock => "$newblocks[0]"};
1813
1814 # prepare
1815 my $idsth = $dbh->prepare("SELECT currval('allocations_id_seq')");
1816 my $allocsth = $dbh->prepare("INSERT INTO allocations (cidr, $fields_sql)".
1817 " VALUES (?".',?'x(scalar(@fieldlist)).")");
1818 my $nbsth = $dbh->prepare("DELETE FROM poolips WHERE parent_id = ? AND ip = ?");
1819 my $upd_psth = $dbh->prepare("UPDATE allocations SET parent_id = ? WHERE parent_id = ? AND cidr <<= ?");
1820 my $upd_msth = $dbh->prepare("UPDATE allocations SET master_id = ? WHERE master_id = ? AND cidr <<= ?");
1821 my $fb_psth = $dbh->prepare("UPDATE freeblocks SET parent_id = ? WHERE parent_id = ? AND cidr <<= ?");
1822 my $fb_msth = $dbh->prepare("UPDATE freeblocks SET master_id = ? WHERE master_id = ? AND cidr <<= ?");
1823 my $pool_psth = $dbh->prepare("UPDATE poolips SET parent_id = ? WHERE parent_id = ? AND ip << ?");
1824 my $pool_msth = $dbh->prepare("UPDATE poolips SET master_id = ? WHERE master_id = ? AND ip <<= ?");
1825
1826 # set up update of existing block
1827 $dbh->do("UPDATE allocations SET cidr = ? WHERE id = ?", undef, ("$newblocks[0]", $args{id}) );
1828
1829 # axe the new bcast IP from the smaller pool at the "base" block, if it's a "normal" pool
1830 if ($binfo->{type} =~ /.d/) {
1831 $newblocks[0]--;
1832 $nbsth->execute($args{id}, $newblocks[0]->addr);
1833 }
1834
1835 # Loop over the new blocks that are not the base block
1836 for (my $i = 1; $i <= $#newblocks; $i++) {
1837 # add the new allocation
1838 $allocsth->execute($newblocks[$i], @vals);
1839 # fetch the ID of the entry we just added...
1840 $idsth->execute();
1841 my ($nid) = $idsth->fetchrow_array();
1842 # ... so we can pass back the list of blocks and IDs...
1843 push @ret, {nid => $nid, nblock => "$newblocks[$i]"};
1844 # axe the net, gw, and bcast IPs as necessary when splitting a "normal" pool
1845 if ($binfo->{type} =~ /.d/) {
1846 # net
1847 $nbsth->execute($args{id}, $newblocks[$i]->addr);
1848 $newblocks[$i]++;
1849 # gw
1850 $nbsth->execute($args{id}, $newblocks[$i]->addr);
1851 $newblocks[$i]--;
1852 $newblocks[$i]--;
1853 # bcast
1854 $nbsth->execute($args{id}, $newblocks[$i]->addr);
1855 $newblocks[$i]++;
1856 }
1857
1858 # Reparent allocations, freeblocks, and pool IPs.
1859 $upd_psth->execute($nid, $args{id}, $newblocks[$i]);
1860 $fb_psth->execute($nid, $args{id}, $newblocks[$i]);
1861 $pool_psth->execute($nid, $args{id}, $newblocks[$i]);
1862
1863 # Update master if we've split a master block
1864 if ($binfo->{type} eq 'mm') {
1865 $upd_msth->execute($nid, $args{id}, $newblocks[$i]);
1866 $fb_msth->execute($nid, $args{id}, $newblocks[$i]);
1867 $pool_msth->execute($nid, $args{id}, $newblocks[$i]);
1868 }
1869
1870 } # for (... @newblocks)
1871
1872 $dbh->commit;
1873 };
1874 if ($@) {
1875 $errstr = "Error splitting $binfo->{block}: $@";
1876 $dbh->rollback;
1877 return;
1878 }
1879##fixme: RPC return code?
1880# particularly useful in this case as there may be arbitrary combinations of pass, warn, fail
1881# results from each of the update and add(s), which could get the user to prod dnsadmin to see what exploded
1882 my $foo = _rpc('splitTemplate', cidr => $binfo->{block}, newmask => $args{newmask}, rpcuser => $args{user});
1883
1884 return \@ret;
1885} # end splitBlock()
1886
1887
1888## IPDB::shrinkBlock()
1889# Shrink an allocation to the passed CIDR block
1890# Takes an allocation ID and a new CIDR
1891# Returns an arrayref to a list of hashrefs with the ID and CIDR of the freed block(s)
1892# Refuses to shrink "real netblock" pool types below /30
1893sub shrinkBlock {
1894 my $dbh = shift;
1895 my $id = shift;
1896
1897 # just take the new CIDR spec; this way we can shrink eg .16/28 to .20/30 without extra contortions
1898 my $newblock = new NetAddr::IP shift;
1899
1900 if (!$newblock) {
1901 $errstr = "Can't shrink something that's not a netblock";
1902 return;
1903 }
1904
1905 my $binfo = getBlockData($dbh, $id);
1906 my $pinfo = getBlockData($dbh, $binfo->{parent_id});
1907
1908 if ($binfo->{type} =~ /.d/ && $newblock->masklen > ($newblock->bits+2) ) {
1909 $errstr = "Can't shrink a non-PPP pool smaller than ".($newblock->{isv6} ? '/124' : '/30');
1910 return;
1911 }
1912
1913 my $oldblock = new NetAddr::IP $binfo->{block};
1914
1915 # Don't try to shrink the block outside of itself, Bad Things (probably) Happen.
1916 if (!$oldblock->contains($newblock)) {
1917 $errstr = "Can't shrink an allocation outside of itself";
1918 return;
1919 }
1920
1921 local $dbh->{AutoCommit} = 0;
1922 local $dbh->{RaiseError} = 1;
1923
1924 my $addfbsth = $dbh->prepare("INSERT INTO freeblocks (cidr,city,routed,vrf,parent_id,master_id) VALUES (?,?,?,?,?,?)");
1925 my $idsth = $dbh->prepare("SELECT currval('freeblocks_id_seq')");
1926 my $poolsth = $dbh->prepare("DELETE FROM poolips WHERE parent_id = ? AND ip << ?");
1927 my $netsth = $dbh->prepare("DELETE FROM poolips WHERE parent_id = ? AND ip = ?");
1928 my $allocsth = $dbh->prepare("DELETE FROM allocations WHERE parent_id = ? AND cidr <<= ?");
1929 my $delfbsth = $dbh->prepare("DELETE FROM freeblocks WHERE parent_id = ? AND cidr <<= ?");
1930
1931##fixme: turn this into a public/top-level sub?
1932 sub getchildren {
1933 my $dbh = shift;
1934 my $id = shift;
1935 my $master = shift;
1936 my $retlist = shift; # better than trying to return complex structures recursively. Ow.
1937 my $cidr = shift;
1938
1939 if (!$cidr) {
1940 my $bd = getBlockData($dbh, $id);
1941 $cidr = $bd->{cidr};
1942 }
1943
1944 my $sth = $dbh->prepare(q(
1945 SELECT id,cidr,type FROM allocations
1946 WHERE parent_id = ? AND master_id = ? AND cidr <<= ?
1947 ) );
1948 $sth->execute($id, $master, $cidr);
1949 while (my $row = $sth->fetchrow_hashref) {
1950 push @$retlist, $row;
1951 getchildren($dbh, $row->{id}, $master, $retlist, $cidr);
1952 }
1953 }
1954
1955 my @ret;
1956 eval {
1957 $dbh->do("UPDATE allocations SET cidr = ? WHERE id = ?", undef, $newblock, $id);
1958
1959 # find the netblock(s) that are now free
1960 my @workingblocks = $oldblock->split($newblock->masklen);
1961 my @wb2;
1962 foreach my $newsub (@workingblocks) {
1963 next if $newsub == $newblock;
1964 push @wb2, $newsub;
1965 }
1966 @wb2 = Compact(@wb2);
1967
1968 # set new freeblocks, and clean up any IP pool entries if needed.
1969 foreach my $newfree (@wb2) {
1970 my @clist;
1971 # the block we're munging
1972 push @clist, { id => $id, type => $binfo->{type}, cidr => $binfo->{block} };
1973 getchildren($dbh, $id, $binfo->{master_id}, \@clist, $newfree);
1974
1975 foreach my $goner (@clist) {
1976 $poolsth->execute($goner->{id}, $newfree) if $goner->{type} =~ /.[dp]/;
1977 $allocsth->execute($goner->{id}, $newfree);
1978 $delfbsth->execute($goner->{id}, $newfree);
1979 }
1980
1981 # No pinfo means we're shrinking a master block, which means the free space is returned outside of IPDB.
1982 if ($pinfo) {
1983 $addfbsth->execute($newfree, $pinfo->{city}, 'm', $pinfo->{vrf}, $binfo->{parent_id}, $pinfo->{master_id});
1984 $idsth->execute;
1985 my ($nid) = $idsth->fetchrow_array();
1986 # add to return list
1987 push @ret, {fbid => $nid, newfree => "$newfree", fbparent => $binfo->{parent_id} };
1988 }
1989
1990 } # $newfree (@wb2)
1991
1992 # additional cleanup on net/gw/bcast IPs in pool
1993 if ($binfo->{type} =~ /.d/) {
1994 $netsth->execute($id, $newblock->addr);
1995 $newblock++;
1996 $netsth->execute($id, $newblock->addr);
1997 $newblock--;
1998 $newblock--;
1999 $netsth->execute($id, $newblock->addr);
2000 }
2001
2002 $dbh->commit;
2003 };
2004 if ($@) {
2005 $errstr = "Error splitting $binfo->{block}: $@";
2006 $dbh->rollback;
2007 return;
2008 }
2009
2010 return \@ret;
2011} # end shrinkBlock()
2012
2013
2014## IPDB::mergeBlocks()
2015# Merges two or more adjacent allocations, optionally including relevant
2016# free space, into one allocation.
2017# Takes a "base" block ID and a hash with a mask length and a scope argument to decide
2018# how much existing allocation data to delete.
2019# Returns a list starting with the new merged block, then the merged allocations with comment
2020## Merge scope:
2021# Merge to container
2022# keepall
2023# Move all mergeable allocations into the new block
2024# Move all mergeable free blocks into the new block
2025# mergepeer
2026# Move subs of mergeable containers into the updated primary.
2027# Reparent free blocks in mergeable containers to the updated primary.
2028# Convert assigned IPs from pools into subs.
2029# Convert unused IPs from pools into free blocks.
2030# Convert leaf allocations into free blocks.
2031# clearpeer
2032# Keep subs of the original
2033# Convert assigned IPs from pools into subs.
2034# Convert unused IPs from pools into free blocks.
2035# Convert leaf allocations into free blocks.
2036# clearall
2037# Delete all peers, subs and IPs.
2038# Add single free block for new container.
2039# Merge to pool
2040# keepall
2041# Convert all leaf allocations in the merge range to groups of used IPs
2042# mergepeer
2043# Effectively equal to keepall
2044# clearpeer
2045# Only convert IPs from the original allocation to used IPs
2046# clearall
2047# Delete any existing IPs, and reinitialize the new pool entirely
2048# Merge to leaf type
2049# Remove all subs
2050sub mergeBlocks {
2051 my $dbh = shift;
2052 my $prime = shift; # "base" block ID to use as a starting point
2053 if (!$prime) {
2054 $errstr = "Missing block ID to base merge on";
2055 return;
2056 }
2057
2058 my %args = @_;
2059
2060 # check key arguments.
2061 if (!$args{scope} || $args{scope} !~ /^(keepall|mergepeer|clearpeer|clearall)$/) {
2062 $errstr = "Bad or missing merge scope";
2063 return;
2064 }
2065 if (!$args{newmask} || $args{newmask} !~ /^\d+$/) {
2066 $errstr = "Bad or missing new netmask";
2067 return;
2068 }
2069
2070 # Retrieve info about the base allocation we're munging
2071 my $binfo = getBlockData($dbh, $prime);
2072 my $block = new NetAddr::IP $binfo->{block};
2073 my ($basetype) = ($binfo->{type} =~ /^.(.)$/);
2074 $binfo->{id} = $prime; # preserve for later, just in case
2075
2076 # proposed block
2077 my $newblock = new NetAddr::IP $block->addr."/$args{newmask}";
2078 $newblock = $newblock->network;
2079 $args{newtype} = $binfo->{type} if !$args{newtype};
2080 # if the "primary" block being changed is a master, it must remain one.
2081 # Also force the scope, since otherwise things get ugly.
2082 if ($binfo->{type} eq 'mm') {
2083 $args{newtype} = 'mm';
2084 # don't want to make a peer master a sub of the existing one; too many special cases go explodey,
2085 # but want to retain all other allocations
2086 $args{scope} = 'mergepeer';
2087 }
2088 my ($newcontainerclass) = ($args{newtype} =~ /^(.).$/);
2089
2090 # build an info hash for the "new" allocation we're creating
2091 my $pinfo = {
2092 id => $prime,
2093 block => "$newblock",
2094 type => $args{newtype},
2095 parent_id =>
2096 $binfo->{parent_id},
2097 city => $binfo->{city},
2098 vrf => $binfo->{vrf},
2099 master_id => $binfo->{master_id}
2100 };
2101
2102 my @retlist;
2103
2104 local $dbh->{AutoCommit} = 0;
2105 local $dbh->{RaiseError} = 1;
2106
2107 # Want to do all of the DB stuff in a transaction, to minimize data changing underfoot
2108 eval {
2109
2110 # We always update the "prime" block passed in...
2111 $dbh->do("UPDATE allocations SET cidr = ?, type = ? WHERE id = ?", undef,
2112 ($newblock, $args{newtype}, $prime) )
2113 # ... but only on existing container or pool types. Leaf -> container conversions
2114 # may need a new parent inserted instead.
2115 if $basetype =~ /[cm]/;
2116
2117 # For leaf blocks, we may need to create a new parent as the "primary" instead
2118 # of updating the existing block
2119 my $newparent = $dbh->prepare(q{
2120 INSERT INTO allocations (
2121 cidr, type, city, description, notes, circuitid, createstamp, modifystamp,
2122 privdata, custid, swip, vrf, vlan, rdns, parent_id, master_id
2123 )
2124 SELECT
2125 ? AS cidr, ? AS type, city, description, notes, circuitid, createstamp, modifystamp,
2126 privdata, custid, swip, vrf, vlan, rdns, parent_id, master_id
2127 FROM allocations
2128 WHERE id = ?
2129 });
2130
2131 # Common actions
2132 my $peersth = $dbh->prepare("SELECT cidr,id,type,master_id FROM allocations WHERE parent_id = ? AND cidr <<= ?");
2133 $peersth->execute($binfo->{parent_id}, "$newblock");
2134 my $reparentsth = $dbh->prepare("UPDATE allocations SET parent_id = ?, master_id = ? WHERE id = ?");
2135 my $insfbsth = $dbh->prepare("INSERT INTO freeblocks (cidr,city,routed,vrf,parent_id,master_id) VALUES (?,?,?,?,?,?)");
2136
2137 my $fbreparentsth = $dbh->prepare(q{
2138 UPDATE freeblocks
2139 SET parent_id = ?, master_id = ?, city = ?, routed = ?, vrf = ?
2140 WHERE parent_id = ? AND cidr <<= ?
2141 });
2142
2143 if ($args{newtype} =~ /.[cm]/) {
2144 ## Container
2145
2146 # In case of merging a master block. Somewhat redundant with calls to $fbreparentsth,
2147 # but not *quite* entirely.
2148 my $mfbsth = $dbh->prepare("UPDATE freeblocks SET master_id = ? WHERE master_id = ?");
2149
2150 if ($args{scope} eq 'keepall') {
2151 # Create a new parent with the same info as the passed "primary".
2152 $newparent->execute($newblock, $args{newtype}, $prime);
2153 # and now retrieve the new parent ID
2154 ($prime) = $dbh->selectrow_array("SELECT currval('allocations_id_seq')");
2155 # snag the new parent info for the return list
2156 push @retlist, { block => "$newblock", type => $disp_alloctypes{$args{newtype}}, id => $prime };
2157 # Reparent the free blocks in the new block
2158 $fbreparentsth->execute($prime, $binfo->{master_id}, $binfo->{city}, $newcontainerclass, $binfo->{vrf},
2159 $binfo->{parent_id}, $newblock);
2160 # keep existing allocations (including the original primary), just push them down a level
2161 while (my ($peercidr, $peer_id, $peertype, $m_id) = $peersth->fetchrow_array) {
2162 $reparentsth->execute($prime, $binfo->{master_id}, $peer_id);
2163 # Fix up master_id on free blocks if we're merging a master block
2164 $mfbsth->execute($binfo->{master_id}, $m_id) if $peertype eq 'mm';
2165 # capture block for return
2166 push @retlist, { block => $peercidr, mtype => $disp_alloctypes{$peertype} };
2167 }
2168
2169 } elsif ($args{scope} =~ /^clear/) {
2170 # clearpeer and clearall share a starting point
2171 # snag the new parent info for the return list
2172 push @retlist, { block => "$newblock", type => $disp_alloctypes{$args{newtype}}, id => $prime };
2173 # update the primary allocation info
2174 $dbh->do("UPDATE allocations SET cidr = ?, type = ? WHERE id = ?", undef, ($newblock, $args{newtype}, $prime) );
2175 # Reparent the free blocks in the new block
2176 $fbreparentsth->execute($prime, $binfo->{master_id}, $binfo->{city}, $newcontainerclass, $binfo->{vrf},
2177 $binfo->{parent_id}, $newblock);
2178 # Insert a free block if $prime is a leaf
2179 if ($binfo->{type} =~ /.[enr]/) {
2180 $insfbsth->execute($binfo->{block}, $binfo->{city}, $newcontainerclass, $binfo->{vrf}, $prime,
2181 $binfo->{master_id});
2182 }
2183 # delete the peers.
2184 while (my ($peercidr, $peer_id, $peertype, $m_id) = $peersth->fetchrow_array) {
2185 next if $peer_id == $prime;
2186 # push existing allocations down a level before deleting,
2187 # so that when they're deleted the parent info is correct
2188 $reparentsth->execute($prime, $binfo->{master_id}, $peer_id);
2189 _deleteCascade($dbh, $peer_id);
2190 # insert the freeblock _deleteCascade() (deliberately) didn't when deleting a master block.
2191 # aren't special cases fun?
2192 $dbh->do("INSERT INTO freeblocks (cidr,routed,parent_id,master_id) values (?,?,?,?)",
2193 undef, ($peercidr, 'm', $prime, $prime) ) if $binfo->{type} eq 'mm';
2194 # capture block for return
2195 push @retlist, { block => $peercidr, mtype => $disp_alloctypes{$peertype} };
2196 }
2197 if ($args{scope} eq 'clearall') {
2198 # delete any subs of $prime as well
2199 my $substh = $dbh->prepare("SELECT cidr,id FROM allocations WHERE parent_id = ?");
2200 $substh->execute($prime);
2201 while (my ($scidr, $s_id) = $substh->fetchrow_array) {
2202 _deleteCascade($dbh, $s_id);
2203 }
2204 } else {
2205 # clearpeer
2206 if ($basetype =~ /[dp]/) {
2207 # Convert active IP pool entries to allocations if the original was an IP pool
2208 _poolToAllocations($dbh, $binfo, $pinfo, newtype => $poolmap{$binfo->{type}});
2209 }
2210 } # clearall or clearpeer
2211
2212 } elsif ($args{scope} eq 'mergepeer') { # should this just be an else?
2213 # Default case. Merge "peer" blocks, but keep all suballocations
2214 # snag the new parent info for the return list
2215 push @retlist, {block => "$newblock", type => $disp_alloctypes{$args{newtype}}, id => $prime};
2216 my $substh = $dbh->prepare("UPDATE allocations SET parent_id = ? WHERE parent_id = ?");
2217 my $delsth = $dbh->prepare("DELETE FROM allocations WHERE id = ?");
2218 # Reparent freeblocks in parent
2219 $fbreparentsth->execute($prime, $binfo->{master_id}, $binfo->{city}, $newcontainerclass, $binfo->{vrf},
2220 $binfo->{parent_id}, $newblock);
2221 # Loop over "peer" allocations to be merged
2222 while (my ($peercidr, $peer_id, $peertype, $m_id) = $peersth->fetchrow_array) {
2223 # Snag existing peer data since we may need it
2224 my $peerfull = getBlockData($dbh, $peer_id);
2225 # Reparent free blocks from existing containers
2226 $fbreparentsth->execute($prime, $binfo->{master_id}, $binfo->{city}, $newcontainerclass,
2227 $binfo->{vrf}, $peer_id, $newblock);
2228 # Reparent any subblocks from existing containers
2229 $substh->execute($prime, $peer_id);
2230 # Delete the old container
2231 $delsth->execute($peer_id) unless $peer_id == $prime;
2232 # Add new freeblocks for merged leaf blocks
2233 $insfbsth->execute($peercidr, $binfo->{city}, $newcontainerclass, $binfo->{vrf}, $binfo->{id},
2234 $binfo->{master_id}) if $peertype =~ /.[enr]/;
2235 # Convert pool IPs into allocations or aggregated free blocks
2236 _poolToAllocations($dbh, $peerfull, $pinfo, newparent => $prime) if $peertype =~ /.[dp]/;
2237 # Fix up master_id on free blocks if we're merging a master block
2238 $mfbsth->execute($binfo->{master_id}, $m_id) if $peertype eq 'mm';
2239 # capture block for return
2240 push @retlist, { block => $peercidr, mtype => $disp_alloctypes{$peertype} };
2241 } # merge peers
2242 # update the primary allocation info. Do this last so we don't stomp extra data-retrieval in the loop above
2243 $dbh->do("UPDATE allocations SET cidr = ?, type = ? WHERE id = ?", undef, ($newblock, $args{newtype}, $prime) );
2244
2245 } # scope
2246
2247 # Clean up free blocks
2248 _compactFree($dbh, $prime);
2249
2250 } elsif ($args{newtype} =~ /.[dp]/) {
2251 ## Pool
2252
2253 } elsif ($args{newtype} =~ /.[enr]/) {
2254 ## Leaf
2255
2256 } # new type if()
2257
2258 $dbh->commit;
2259 };
2260 if ($@) {
2261 my $msg = $@;
2262 $errstr = $msg;
2263 $dbh->rollback;
2264 return ('FAIL',$msg);
2265 }
2266
2267 return \@retlist;
2268
2269} # end mergeBlocks()
2270
2271
2272## IPDB::deleteBlock()
2273# Removes an allocation from the database, including deleting IPs
2274# from poolips and recombining entries in freeblocks if possible
2275# Also handles "deleting" a static IP allocation, and removal of a master
2276# Requires a database handle, the block to delete, the routing depth (if applicable),
2277# the VRF ID, and a flag to indicate whether to delete associated forward DNS entries
2278# as well as the reverse entry
2279sub deleteBlock {
2280 my ($dbh,$id,$basetype,$delfwd,$user) = @_;
2281
2282 # Collect info about the block we're going to delete
2283 my $binfo = getBlockData($dbh, $id, $basetype);
2284 my $cidr = new NetAddr::IP $binfo->{block};
2285
2286# For possible auto-VRF-ignoring (since public IPs shouldn't usually be present in more than one VRF)
2287# is_rfc1918 requires NetAddr::IP >= 4.059
2288# rather than doing this over and over and over.....
2289 my $tmpnum = $cidr->numeric;
2290# 192.168.0.0/16 -> 192.168.255.255 => 3232235520 -> 3232301055
2291# 172.16.0.0/12 -> 172.31.255.255 => 2886729728 -> 2887778303
2292# 10.0.0.0/8 -> 10.255.255.255 => 167772160 -> 184549375
2293 my $isprivnet = (3232235520 <= $tmpnum && $tmpnum <= 3232301055) ||
2294 (2886729728 <= $tmpnum && $tmpnum <= 2887778303) ||
2295 (167772160 <= $tmpnum && $tmpnum <= 184549375);
2296
2297 my $sth;
2298
2299 # Magic variables used for odd allocation cases.
2300 my $container;
2301 my $con_type;
2302
2303
2304 # temporarily forced null, until a sane UI for VRF tracking can be found.
2305# $vrf = '';# if !$vrf; # as with SQL, the null value is not equal to ''. *sigh*
2306
2307 # To contain the error message, if any.
2308 my $msg = "Unknown error deallocating $binfo->{type} $cidr";
2309 my $goback; # to put the parent in so we can link back where the deallocate started
2310
2311 # Enable transactions and exception-on-errors... but only for this sub
2312 local $dbh->{AutoCommit} = 0;
2313 local $dbh->{RaiseError} = 1;
2314
2315 if ($binfo->{type} =~ /^.i$/) {
2316 # First case. The "block" is a static IP
2317 # Note that we still need some additional code in the odd case
2318 # of a netblock-aligned contiguous group of static IPs
2319
2320 eval {
2321 $msg = "Unable to deallocate $disp_alloctypes{$binfo->{type}} $cidr";
2322 my $pinfo = getBlockData($dbh, $binfo->{parent_id}, 'b');
2323##fixme: VRF and rdepth
2324 $dbh->do("UPDATE poolips SET custid = ?, available = 'y',".
2325 "city = (SELECT city FROM allocations WHERE id = ?),".
2326 "description = '', notes = '', circuitid = '', vrf = ? WHERE id = ?", undef,
2327 ($pinfo->{custid}, $binfo->{parent_id}, $pinfo->{vrf}, $id) );
2328 $dbh->commit;
2329 };
2330 if ($@) {
2331 $msg .= ": $@";
2332 eval { $dbh->rollback; };
2333 return ('FAIL',$msg);
2334 } else {
2335##fixme: RPC return code?
2336 _rpc('delByCIDR', cidr => "$cidr", user => $user, delforward => $delfwd, rpcuser => $user);
2337 return ('OK',"OK");
2338 }
2339
2340 } elsif ($binfo->{type} eq 'mm') { # end alloctype =~ /.i/
2341 # Second case. The block is a full master block
2342
2343##fixme: VRF limit
2344 $msg = "Unable to delete master block $cidr";
2345 eval {
2346 $dbh->do("DELETE FROM allocations WHERE cidr <<= ? AND master_id = ?", undef, ($cidr, $binfo->{master_id}) );
2347 $dbh->do("DELETE FROM freeblocks WHERE cidr <<= ? AND master_id = ?", undef, ($cidr, $binfo->{master_id}) );
2348 $dbh->commit;
2349 };
2350 if ($@) {
2351 $msg .= ": $@";
2352 eval { $dbh->rollback; };
2353 return ('FAIL', $msg);
2354 }
2355
2356 # Have to handle potentially split reverse zones. Assume they *are* split,
2357 # since if we added them here, they would have been added split.
2358# allow splitting reverse zones to be disabled, maybe, someday
2359#if ($splitrevzones && !$cidr->{isv6}) {
2360 my @zonelist;
2361 if (1 && !$cidr->{isv6}) {
2362 my $splitpoint = ($cidr->masklen <= 16 ? 16 : 24); # hack pthui
2363 @zonelist = $cidr->split($splitpoint);
2364 } else {
2365 @zonelist = ($cidr);
2366 }
2367 my @fails;
2368 foreach my $subzone (@zonelist) {
2369 if ($rpc_url && !_rpc('delZone', zone => "$subzone", revrec => 'y', rpcuser => $user, delforward => $delfwd) ) {
2370 push @fails, ("$subzone" => $errstr);
2371 }
2372 }
2373 if (@fails) {
2374 return ('WARN',"Warning(s) deleting $cidr from reverse DNS:\n".join("\n", @fails));
2375 }
2376 return ('OK','OK');
2377
2378 } else { # end alloctype master block case
2379
2380 ## This is a big block; but it HAS to be done in a chunk. Any removal
2381 ## of a netblock allocation may result in a larger chunk of free
2382 ## contiguous IP space - which may in turn be combined into a single
2383 ## netblock rather than a number of smaller netblocks.
2384
2385 my $retcode = 'OK';
2386 my ($ptype,$pcity,$ppatt,$p_id);
2387
2388 eval {
2389
2390##fixme: add recursive flag to allow "YES DAMMIT DELETE ALL EVARYTHING!!1!!" without
2391# explicitly deleting any suballocations of the block to be deleted.
2392
2393 # get parent info of the block we're deleting
2394 my $pinfo = getBlockData($dbh, $binfo->{parent_id});
2395 $ptype = $pinfo->{type};
2396 $pcity = $pinfo->{city};
2397 $ppatt = $pinfo->{rdns};
2398 $p_id = $binfo->{parent_id};
2399
2400 # Delete the block
2401 $dbh->do("DELETE FROM allocations WHERE id = ?", undef, ($id) );
2402
2403 # munge the parent type a little
2404 $ptype = (split //, $ptype)[1];
2405
2406##fixme: you can't... CAN NOT.... assign the same public IP to multiple things.
2407# 'Net don't work like that, homey. Restrict VRF-uniqueness to private IPs?
2408# -> $isprivnet flag from start of sub
2409
2410 # check to see if any container allocations could be the "true" parent
2411 my ($tparent,$tpar_id,$trtype,$tcity);
2412 $tpar_id = 0;
2413
2414##fixme: this is far simpler in the strict VRF case; we "know" that any allocation
2415# contained by a container is a part of the same allocation tree when the VRF fields are equal.
2416
2417# logic:
2418# For each possible container of $cidr
2419# note the parent id
2420# walk the chain up the parents
2421# if we intersect $cidr's current parent, break
2422# if we've intersected $cidr's current parent
2423# set some variables to track that block
2424# break
2425
2426# Set up part of "is it in the middle of a pool?" check
2427 my $wuzpool = $dbh->selectrow_hashref("SELECT cidr,parent_id,type,city,custid,id FROM allocations ".
2428 "WHERE (type LIKE '_d' OR type LIKE '_p') AND cidr >> ? AND master_id = ?", { Slice => {} },
2429 ($cidr, $binfo->{master_id}) );
2430
2431##fixme?
2432# edge cases not handled, or handled badly:
2433# -> $cidr managed to get to be the entirety of an IP pool
2434
2435 if ($wuzpool && $wuzpool->{id} != $id) {
2436 # we have legacy goo to be purified
2437 # going to ignore nested pools; not possible to create them via API and no current legacy data includes any.
2438
2439 # for convenience
2440 my $poolid = $wuzpool->{id};
2441 my $pool = $wuzpool->{cidr};
2442 my $poolcity = $wuzpool->{city};
2443 my $pooltype = $wuzpool->{type};
2444 my $poolcustid = $wuzpool->{custid};
2445
2446 $retcode = 'WARNPOOL';
2447 $goback = "$poolid,$pool";
2448 # We've already deleted the block, now we have to stuff its IPs into the pool.
2449 $pooltype =~ s/[dp]$/i/; # change type to static IP
2450 my $sth2 = $dbh->prepare("INSERT INTO poolips (ip,city,type,custid,parent_id) VALUES ".
2451 "(?,'$poolcity','$pooltype','$poolcustid',$poolid)");
2452
2453##fixme: need to not insert net, gateway, and bcast on "real netblock" pools (DHCPish)
2454 # don't insert .0
2455 $sth2->execute($cidr->addr) unless $cidr->addr =~ m|\.0$|;
2456 $cidr++;
2457 my $bcast = $cidr->broadcast;
2458 while ($cidr != $bcast) {
2459 $sth2->execute($cidr->addr);
2460 $cidr++;
2461 }
2462 # don't insert .255
2463 $sth2->execute($cidr->addr) unless $cidr->addr =~ m|\.255$|;
2464
2465# Weirdness Happens. $cidr goes read-only somewhere (this is a thing?!?),
2466# causing ->split, ->hostenum, and related methods to explode. O_o
2467# foreach my $ip ($cidr->hostenum) {
2468# $sth2->execute($ip);
2469# }
2470
2471 }
2472
2473## important!
2474# ... or IS IT?
2475# we may have undef'ed $wuzpool above, if the allocation tree $cidr is in doesn't intersect the pool we found
2476#if (!$wuzpool) {
2477
2478 else {
2479
2480# Edge case: Block is the same size as more than one parent level. Should be rare.
2481# - mainly master + first routing. Sorting on parent_id hides the problem pretty well,
2482# but it's likely still possible to fail in particularly well-mangled databases.
2483# The ultimate fix for this may be to resurrect the "routing depth" atrocity. :/
2484 # Get all possible (and probably a number of impossible) containers for $cidr
2485 $sth = $dbh->prepare("SELECT cidr,parent_id,type,city,id FROM allocations ".
2486 "WHERE (type LIKE '_m' OR type LIKE '_c') AND cidr >>= ? AND master_id = ? ".
2487 "ORDER BY masklen(cidr) DESC,parent_id DESC");
2488 $sth->execute($cidr, $binfo->{master_id});
2489
2490 # Quickly get certain fields (simpler than getBlockData()
2491 my $sth2 = $dbh->prepare("SELECT cidr,parent_id,type,city FROM allocations ".
2492 "WHERE (type LIKE '_m' OR type LIKE '_c') AND id = ? AND master_id = ?");
2493
2494 # For each possible container of $cidr...
2495 while (my @data = $sth->fetchrow_array) {
2496 my $i = 0;
2497 # Save some state and set a start point - parent ID of container we're checking
2498 $tparent = $data[0];
2499 my $ppid = $data[1];
2500 $trtype = $data[2];
2501 $tcity = $data[3];
2502 $tpar_id = $data[4];
2503 last if $data[4] == $binfo->{parent_id}; # Preemptively break if we're already in the right place
2504 last if $ppid == $binfo->{parent_id}; # ... or if the parent of the container is the block's parent
2505 while (1) {
2506 # Retrieve bits on that parent ID
2507 $sth2->execute($ppid, $binfo->{master_id});
2508 my @container = $sth2->fetchrow_array;
2509 $ppid = $container[1];
2510 last if $container[1] == 0; # Break if we've hit a master block
2511 last if $ppid == $binfo->{parent_id}; # Break if we've reached the block $cidr is currently in
2512 }
2513 last if $ppid == $binfo->{parent_id};
2514 }
2515
2516 # found an alternate parent; reset some parent-info bits
2517 if ($tpar_id != $binfo->{parent_id}) {
2518 $ptype = (split //, $trtype)[1];
2519 $pcity = $tcity;
2520 $retcode = 'WARNMERGE'; # may be redundant
2521 $p_id = $tpar_id;
2522 }
2523
2524 $goback = "$p_id,$tparent"; # breadcrumb, currently only used in case of live-parent-is-not-true-parent
2525
2526 # Special case - delete pool IPs
2527 if ($binfo->{type} =~ /^.[pd]$/) {
2528 # We have to delete the IPs from the pool listing.
2529##fixme: rdepth? vrf?
2530 $dbh->do("DELETE FROM poolips WHERE parent_id = ?", undef, ($id) );
2531 }
2532
2533 $pinfo = getBlockData($dbh, $p_id);
2534
2535 # If the block wasn't legacy goo embedded in a static pool, we check the
2536 # freeblocks in the identified parent to see if we can combine any of them.
2537
2538 # if the block to be deleted is a container, move its freeblock(s) up a level, and reset their parenting info
2539 if ($binfo->{type} =~ /^.[mc]/) {
2540 # move the freeblocks into the parent
2541 # we don't insert a new freeblock because there could be a live reparented sub.
2542 $dbh->do("UPDATE freeblocks SET parent_id = ?, routed = ?, city = ? WHERE parent_id = ?", undef,
2543 ($p_id, $ptype, $pcity, $id) );
2544 } else {
2545 # ... otherwise, add the freeblock
2546 $dbh->do("INSERT INTO freeblocks (cidr, city, routed, parent_id, master_id) VALUES (?,?,?,?,?)", undef,
2547 ($cidr, $pcity, $ptype, $p_id, $binfo->{master_id}) );
2548 }
2549
2550 # Walk the free blocks in the parent and reduce them to the minimal set of CIDR ranges necessary
2551 _compactFree($dbh, $p_id);
2552
2553 } # done returning IPs to the appropriate place
2554
2555 # If we got here, we've succeeded. Whew!
2556 $dbh->commit;
2557 }; # end eval
2558 if ($@) {
2559 $msg .= ": $@";
2560 eval { $dbh->rollback; };
2561 return ('FAIL', $msg);
2562 } else {
2563##fixme: RPC return code?
2564 _rpc('delByCIDR', cidr => "$cidr", rpcuser => $user, delforward => $delfwd, delsubs => 'y', parpatt => $ppatt);
2565 return ($retcode, $goback);
2566 }
2567
2568 } # end alloctype != netblock
2569
2570} # end deleteBlock()
2571
2572
2573## IPDB::getBlockData()
2574# Get CIDR or IP, custid, type, city, circuit ID, description, notes, modification time,
2575# private/restricted data, for a CIDR block or pool IP
2576# Also returns SWIP status flag for CIDR blocks or pool netblock for IPs
2577# Takes the block ID or IP to look up and an optional flag to indicate a pool IP lookup
2578# instead of a netblock.
2579# Returns a hashref to the block data
2580sub getBlockData {
2581 my $dbh = shift;
2582 my $id = shift;
2583 my $type = shift || 'b'; # default to netblock for lazy callers
2584
2585 # netblocks are in the allocations table; pool IPs are in the poolips table.
2586 # If we try to look up a CIDR in an integer field we should just get back nothing.
2587 my ($btype) = $dbh->selectrow_array("SELECT type FROM allocations WHERE id=?", undef, ($id) );
2588
2589 # Note city, vrf, parent_id and master_id removed due to JOIN uncertainty for block allocations
2590 my $commonfields = q(custid, type, circuitid, description, notes, modifystamp AS lastmod,
2591 privdata, vlan, rdns);
2592
2593 if ($type eq 'i') {
2594 my $binfo = $dbh->selectrow_hashref(qq(
2595 SELECT id, ip AS block, city, vrf, parent_id, master_id, $commonfields
2596 FROM poolips WHERE id = ?
2597 ), undef, ($id) );
2598 return $binfo;
2599 } else {
2600 my $binfo = $dbh->selectrow_hashref(qq(
2601 SELECT a.id, a.cidr AS block, a.city, a.vrf, a.parent_id, a.master_id, swip, $commonfields,
2602 f.cidr AS reserve, f.id as reserve_id
2603 FROM allocations a LEFT JOIN freeblocks f ON a.id=f.reserve_for
2604 WHERE a.id = ?
2605 ), undef, ($id) );
2606 return $binfo;
2607 }
2608} # end getBlockData()
2609
2610
2611## IPDB::getBlockRDNS()
2612# Gets reverse DNS pattern for a block or IP. Note that this will also
2613# retrieve any default pattern following the parent chain up, and check via
2614# RPC (if available) to see what the narrowest pattern for the requested block is
2615# Returns the current pattern for the block or IP.
2616sub getBlockRDNS {
2617 my $dbh = shift;
2618 my %args = @_;
2619
2620 $args{type} = 'b' if !$args{type};
2621 my $cached = 1;
2622
2623 # snag entry from database
2624 my ($rdns,$rfrom,$pid);
2625 if ($args{type} =~ /.i/) {
2626 ($rdns, $rfrom, $pid) = $dbh->selectrow_array("SELECT rdns,ip,parent_id FROM poolips WHERE id = ?",
2627 undef, ($args{id}) );
2628 } else {
2629 ($rdns, $rfrom, $pid) = $dbh->selectrow_array("SELECT rdns,cidr,parent_id FROM allocations WHERE id = ?",
2630 undef, ($args{id}) );
2631 }
2632
2633 # Can't see a way this could end up empty, for any case I care about. If the caller
2634 # doesn't know an allocation ID to request, then they don't know anything else anyway.
2635 my $selfblock = $rfrom;
2636
2637 my $type;
2638 while (!$rdns && $pid) {
2639 ($rdns, $rfrom, $pid, $type) = $dbh->selectrow_array(
2640 "SELECT rdns,cidr,parent_id,type FROM allocations WHERE id = ?",
2641 undef, ($pid) );
2642 last if $type eq 'mm'; # break loops in unfortunate legacy data
2643 }
2644
2645 # use the actual allocation to check against the DNS utility; we don't want
2646 # to always go chasing up the chain to the master... which may (usually won't)
2647 # be present directly in DNS anyway
2648 my $cidr = new NetAddr::IP $selfblock;
2649
2650 if ($rpc_url) {
2651 # Use the first /16 or /24, rather than dithering over which sub-/14 /16
2652 # or sub-/19 /24 to retrieve - it's the least-wrong way to do things.
2653
2654 my ($rpcblock) = ($cidr->masklen <= 24 ? $cidr->split( ($cidr->masklen <= 16 ? 16 : 24) ) : $cidr);
2655 my %rpcargs = (
2656 rpcuser => $args{user},
2657 group => $revgroup, # not sure how this could sanely be exposed, tbh...
2658 cidr => "$rpcblock",
2659 );
2660
2661 my $remote_rdns = _rpc('getRevPattern', %rpcargs);
2662 $rdns = $remote_rdns if $remote_rdns;
2663 $cached = 0;
2664 }
2665
2666 # hmm. do we care about where it actually came from?
2667 return $rdns, $cached;
2668} # end getBlockRDNS()
2669
2670
2671## IPDB::getRDNSbyIP()
2672# Get individual reverse entries for the IP or CIDR IP range passed. Sort of looking the
2673# opposite direction down the netblock tree compared to getBlockRDNS() above.
2674sub getRDNSbyIP {
2675 my $dbh = shift;
2676 my %args = @_; # We want to accept a variety of call types
2677
2678 # key arguments: allocation ID, type
2679 unless ($args{id} || $args{type}) {
2680 $errstr = 'Missing allocation ID or type';
2681 return;
2682 }
2683
2684 my @ret = ();
2685 # special case: single IP. Check if it's an allocation or in a pool, then do the RPC call for fresh data.
2686 if ($args{type} =~ /^.i$/) {
2687 my ($ip, $localrev) = $dbh->selectrow_array("SELECT ip, rdns FROM poolips WHERE id = ?", undef, ($args{id}) );
2688 push @ret, { 'r_ip' => $ip, 'iphost' => $localrev };
2689 } else {
2690 if ($rpc_url) {
2691 my %rpcargs = (
2692 rpcuser => $args{user},
2693 group => $revgroup, # not sure how this could sanely be exposed, tbh...
2694 cidr => $args{range},
2695 );
2696
2697 my $remote_rdns = _rpc('getRevSet', %rpcargs);
2698 return $remote_rdns;
2699# $rdns = $remote_rdns if $remote_rdns;
2700# $cached = 0;
2701 }
2702 }
2703 return \@ret;
2704} # end getRDNSbyIP()
2705
2706
2707## IPDB::getNodeList()
2708# Gets a list of node ID+name pairs as an arrayref to a list of hashrefs
2709sub getNodeList {
2710 my $dbh = shift;
2711
2712 my $ret = $dbh->selectall_arrayref("SELECT node_id, node_name FROM nodes ORDER BY node_type,node_id",
2713 { Slice => {} });
2714 return $ret;
2715} # end getNodeList()
2716
2717
2718## IPDB::getNodeName()
2719# Get node name from the ID
2720sub getNodeName {
2721 my $dbh = shift;
2722 my $nid = shift;
2723
2724 my ($nname) = $dbh->selectrow_array("SELECT node_name FROM nodes WHERE node_id = ?", undef, ($nid) );
2725 return $nname;
2726} # end getNodeName()
2727
2728
2729## IPDB::getNodeInfo()
2730# Get node name and ID associated with a block
2731sub getNodeInfo {
2732 my $dbh = shift;
2733 my $block = shift;
2734
2735 my ($nid, $nname) = $dbh->selectrow_array("SELECT nodes.node_id,node_name FROM nodes INNER JOIN noderef".
2736 " ON nodes.node_id=noderef.node_id WHERE noderef.block = ?", undef, ($block) );
2737 return ($nid, $nname);
2738} # end getNodeInfo()
2739
2740
2741## IPDB::mailNotify()
2742# Sends notification mail to recipients regarding an IPDB operation
2743sub mailNotify {
2744 my $dbh = shift;
2745 my ($action,$subj,$message) = @_;
2746
2747 return if $smtphost eq 'smtp.example.com'; # do nothing if still using default SMTP host.
2748
2749##fixme: need to redesign the breakdown/processing for $action for proper handling of all cases
2750
2751# split action into parts for fiddlement. nb: there are almost certainly better ways to do this.
2752 my @actionbits = split //, $action;
2753
2754 # want to notify anyone who has specifically requested notify on *this* type ($action as passed),
2755 # on "all static IP types" or "all pool types" (and other last-char-in-type groupings), on eg "all DSL types",
2756 # and "all events with this action"
2757 my @actionsets = ($action);
2758##fixme: ick, eww. really gotta find a better way to handle this...
2759 push @actionsets, ($actionbits[0].'.'.$actionbits[2],
2760 $actionbits[0].$actionbits[1].'.', $actionbits[0].'a') if $action =~ /^.{3}$/;
2761
2762 my $mailer = Net::SMTP->new($smtphost, Hello => "ipdb.$domain");
2763
2764 # get recip list from db
2765 my $sth = $dbh->prepare("SELECT reciplist FROM notify WHERE action=?");
2766
2767 my %reciplist;
2768 foreach (@actionsets) {
2769 $sth->execute($_);
2770##fixme - need to handle db errors
2771 my ($recipsub) = $sth->fetchrow_array;
2772 next if !$recipsub;
2773 foreach (split(/,/, $recipsub)) {
2774 $reciplist{$_}++;
2775 }
2776 }
2777
2778 return if !%reciplist;
2779
2780 foreach my $recip (keys %reciplist) {
2781 $mailer->mail($smtpsender);
2782 $mailer->to($recip);
2783 $mailer->data("From: \"$org_name IP Database\" <$smtpsender>\n",
2784 "To: $recip\n",
2785 "Date: ".strftime("%a, %d %b %Y %H:%M:%S %z",localtime)."\n",
2786 "Subject: {IPDB} $subj\n",
2787 "X-Mailer: IPDB Notify v".sprintf("%.1d",$IPDB::VERSION)."\n",
2788 "Organization: $org_name\n",
2789 "\n$message\n");
2790 }
2791 $mailer->quit;
2792}
2793
2794# Indicates module loaded OK. Required by Perl.
27951;
Note: See TracBrowser for help on using the repository browser.