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

Last change on this file since 923 was 923, checked in by kdeugau, 6 months ago

/trunk

Refine selection handling in static IP section of allocateBlock().

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