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