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