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

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

/trunk

Fix minor bugs in _compactFree() that would only affect guided allocation

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