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