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

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

/trunk

Fixes in deleteCascade() for edge cases along with some hefty docucomments

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