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

Last change on this file since 676 was 676, checked in by Kris Deugau, 7 years ago

/trunk

Minor return cleanup on error in RPC wrapper sub

  • Property svn:keywords set to Date Rev Author
File size: 64.6 KB
Line 
1# ipdb/cgi-bin/IPDB.pm
2# Contains functions for IPDB - database access, subnet mangling, block allocation, etc
3###
4# SVN revision info
5# $Date: 2015-01-16 22:30:24 +0000 (Fri, 16 Jan 2015) $
6# SVN revision $Rev: 676 $
7# Last update by $Author: kdeugau $
8###
9# Copyright (C) 2004-2010 - Kris Deugau
10
11package IPDB;
12
13use strict;
14use warnings;
15use Exporter;
16use DBI;
17use Net::SMTP;
18use NetAddr::IP qw(:lower Compact );
19use Frontier::Client;
20use POSIX;
21use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
22
23$VERSION        = 2; ##VERSION##
24@ISA            = qw(Exporter);
25@EXPORT_OK    = qw(
26        %disp_alloctypes %list_alloctypes %def_custids @citylist @poplist
27        %IPDBacl %aclmsg %rpcacl $maxfcgi
28        $errstr
29        &initIPDBGlobals &connectDB &finish &checkDBSanity
30        &addMaster &touchMaster
31        &listSummary &listSubs &listContainers &listAllocations &listFree &listPool
32        &getMasterList &getTypeList &getPoolSelect &findAllocateFrom
33        &ipParent &subParent &blockParent &getRoutedCity
34        &allocateBlock &updateBlock &deleteBlock &getBlockData &getBlockRDNS &getRDNSbyIP
35        &getNodeList &getNodeName &getNodeInfo
36        &mailNotify
37        );
38
39@EXPORT         = (); # Export nothing by default.
40%EXPORT_TAGS    = ( ALL => [qw(
41                %disp_alloctypes %list_alloctypes %def_custids @citylist @poplist
42                %IPDBacl %aclmsg %rpcacl $maxfcgi
43                $errstr
44                &initIPDBGlobals &connectDB &finish &checkDBSanity
45                &addMaster &touchMaster
46                &listSummary &listSubs &listContainers &listAllocations &listFree &listPool
47                &getMasterList &getTypeList &getPoolSelect &findAllocateFrom
48                &ipParent &subParent &blockParent &getRoutedCity
49                &allocateBlock &updateBlock &deleteBlock &getBlockData &getBlockRDNS &getRDNSbyIP
50                &getNodeList &getNodeName &getNodeInfo
51                &mailNotify
52                )]
53        );
54
55##
56## Global variables
57##
58our %disp_alloctypes;
59our %list_alloctypes;
60our %def_custids;
61our @citylist;
62our @poplist;
63our %IPDBacl;
64
65# mapping table for functional-area => error message
66our %aclmsg = (
67        addmaster       => 'add a master block',
68        addblock        => 'add an allocation',
69        updateblock     => 'update a block',
70        delblock        => 'delete an allocation',
71        );
72
73our %rpcacl;
74our $maxfcgi = 3;
75
76# error reporting
77our $errstr = '';
78
79our $org_name = 'Example Corp';
80our $smtphost = 'smtp.example.com';
81our $domain = 'example.com';
82our $defcustid = '5554242';
83# mostly for rwhois
84##fixme:  leave these blank by default?
85our $rwhoisDataPath = '/usr/local/rwhoisd/etc/rwhoisd'; # to match ./configure defaults from rwhoisd-1.5.9.6
86our $org_street = '123 4th Street';
87our $org_city = 'Anytown';
88our $org_prov_state = 'ON';
89our $org_pocode = 'H0H 0H0';
90our $org_country = 'CA';
91our $org_phone = '000-555-1234';
92our $org_techhandle = 'ISP-ARIN-HANDLE';
93our $org_email = 'noc@example.com';
94our $hostmaster = 'dns@example.com';
95
96our $syslog_facility = 'local2';
97
98our $rpc_url = '';
99our $revgroup = 1;      # should probably be configurable somewhere
100our $rpccount = 0;
101
102# Largest inverse CIDR mask length to show per-IP rDNS list
103# (eg, NetAddr::IP->bits - NetAddr::IP->masklen)
104our $maxrevlist = 5;  # /27
105
106##
107## Internal utility functions
108##
109
110## IPDB::_rpc
111# Make an RPC call for DNS changes
112sub _rpc {
113  return if !$rpc_url;  # Just In Case
114  my $rpcsub = shift;
115  my %args = @_;
116
117  # Make an object to represent the XML-RPC server.
118  my $server = Frontier::Client->new(url => $rpc_url, debug => 0);
119  my $result;
120
121  my %rpcargs = (
122        rpcsystem => 'ipdb',
123# must be provided by caller's caller
124#       rpcuser => $args{user},
125        %args,
126        );
127
128  eval {
129    $result = $server->call("dnsdb.$rpcsub", %rpcargs);
130  };
131  if ($@) {
132    $errstr = $@;
133    $srrstr =~ s/\s*$//;
134    $errstr =~ s/Fault returned from XML RPC Server, fault code 4: error executing RPC `dnsdb.$rpcsub'\.\s//;
135  }
136  $rpccount++;
137
138  return $result if $result;
139} # end _rpc()
140
141
142# Let's initialize the globals.
143## IPDB::initIPDBGlobals()
144# Initialize all globals.  Takes a database handle, returns a success or error code
145sub initIPDBGlobals {
146  my $dbh = $_[0];
147  my $sth;
148
149  # Initialize alloctypes hashes
150  $sth = $dbh->prepare("select type,listname,dispname,listorder,def_custid from alloctypes order by listorder");
151  $sth->execute;
152  while (my @data = $sth->fetchrow_array) {
153    $disp_alloctypes{$data[0]} = $data[2];
154    $def_custids{$data[0]} = $data[4];
155    if ($data[3] < 900) {
156      $list_alloctypes{$data[0]} = $data[1];
157    }
158  }
159
160  # City and POP listings
161  $sth = $dbh->prepare("select city,routing from cities order by city");
162  $sth->execute;
163  return (undef,$sth->errstr) if $sth->err;
164  while (my @data = $sth->fetchrow_array) {
165    push @citylist, $data[0];
166    if ($data[1] eq 'y') {
167      push @poplist, $data[0];
168    }
169  }
170
171  # Load ACL data.  Specific username checks are done at a different level.
172  $sth = $dbh->prepare("select username,acl from users");
173  $sth->execute;
174  return (undef,$sth->errstr) if $sth->err;
175  while (my @data = $sth->fetchrow_array) {
176    $IPDBacl{$data[0]} = $data[1];
177  }
178
179##fixme:  initialize HTML::Template env var for template path
180# something like $self->path().'/templates' ?
181#  $ENV{HTML_TEMPLATE_ROOT} = 'foo/bar';
182
183  return (1,"OK");
184} # end initIPDBGlobals
185
186
187## IPDB::connectDB()
188# Creates connection to IPDB.
189# Requires the database name, username, and password.
190# Returns a handle to the db.
191# Set up for a PostgreSQL db;  could be any transactional DBMS with the
192# right changes.
193sub connectDB {
194  my $dbname = shift;
195  my $user = shift;
196  my $pass = shift;
197  my $dbhost = shift;
198
199  my $dbh;
200  my $DSN = "DBI:Pg:".($dbhost ? "host=$dbhost;" : '')."dbname=$dbname";
201
202# Note that we want to autocommit by default, and we will turn it off locally as necessary.
203# We may not want to print gobbledygook errors;  YMMV.  Have to ponder that further.
204  $dbh = DBI->connect($DSN, $user, $pass, {
205        AutoCommit => 1,
206        PrintError => 0
207        })
208    or return (undef, $DBI::errstr) if(!$dbh);
209
210# Return here if we can't select.  Note that this indicates a
211# problem executing the select.
212  my $sth = $dbh->prepare("select type from alloctypes");
213  $sth->execute();
214  return (undef,$DBI::errstr) if ($sth->err);
215
216# See if the select returned anything (or null data).  This should
217# succeed if the select executed, but...
218  $sth->fetchrow();
219  return (undef,$DBI::errstr)  if ($sth->err);
220
221# If we get here, we should be OK.
222  return ($dbh,"DB connection OK");
223} # end connectDB
224
225
226## IPDB::finish()
227# Cleans up after database handles and so on.
228# Requires a database handle
229sub finish {
230  my $dbh = $_[0];
231  $dbh->disconnect if $dbh;
232} # end finish
233
234
235## IPDB::checkDBSanity()
236# Quick check to see if the db is responding.  A full integrity
237# check will have to be a separate tool to walk the IP allocation trees.
238sub checkDBSanity {
239  my ($dbh) = $_[0];
240
241  if (!$dbh) {
242    print "No database handle, or connection has been closed.";
243    return -1;
244  } else {
245    # it connects, try a stmt.
246    my $sth = $dbh->prepare("select type from alloctypes");
247    my $err = $sth->execute();
248
249    if ($sth->fetchrow()) {
250      # all is well.
251      return 1;
252    } else {
253      print "Connected to the database, but could not execute test statement.  ".$sth->errstr();
254      return -1;
255    }
256  }
257  # Clean up after ourselves.
258#  $dbh->disconnect;
259} # end checkDBSanity
260
261
262## IPDB::addMaster()
263# Does all the magic necessary to sucessfully add a master block
264# Requires database handle, block to add
265# Returns failure code and error message or success code and "message"
266sub addMaster {
267  my $dbh = shift;
268        # warning!  during testing, this somehow generated a "Bad file descriptor" error.  O_o
269  my $cidr = new NetAddr::IP shift;
270  my %args = @_;
271
272  $args{vrf} = '' if !$args{vrf};
273  $args{rdns} = '' if !$args{rdns};
274  $args{defloc} = '' if !$args{defloc};
275  $args{rwhois} = 'n' if !$args{rwhois};        # fail "safe", sort of.
276  $args{rwhois} = 'n' if $args{rwhois} ne 'n' and $args{rwhois} ne 'y';
277
278  my $mid;
279
280  # Allow transactions, and raise an exception on errors so we can catch it later.
281  # Use local to make sure these get "reset" properly on exiting this block
282  local $dbh->{AutoCommit} = 0;
283  local $dbh->{RaiseError} = 1;
284
285  # Wrap all the SQL in a transaction
286  eval {
287    # First check - does the master exist?  Ignore VRFs until we can see a sane UI
288    my ($mcontained) = $dbh->selectrow_array("SELECT cidr FROM allocations WHERE cidr >>= ? AND type = 'mm'",
289        undef, ($cidr) );
290    die "Master block $mcontained already exists and entirely contains $cidr\n"
291        if $mcontained;
292
293    # Second check - does the new master contain an existing one or ones?
294    my ($mexist) = $dbh->selectrow_array("SELECT cidr FROM allocations WHERE cidr <<= ? AND type = 'mm'",
295        undef, ($cidr) );
296
297    if (!$mexist) {
298      # First case - master is brand-spanking-new.
299##fixme: rwhois should be globally-flagable somewhere, much like a number of other things
300## maybe a db table called "config"?
301      $dbh->do("INSERT INTO allocations (cidr,type,swip,vrf,rdns) VALUES (?,?,?,?,?)", undef,
302        ($cidr, 'mm', 'y', $args{vrf}, $args{rdns}) );
303      ($mid) = $dbh->selectrow_array("SELECT currval('allocations_id_seq')");
304
305# Unrouted blocks aren't associated with a city (yet).  We don't rely on this
306# elsewhere though;  legacy data may have traps and pitfalls in it to break this.
307# Thus the "routed" flag.
308      $dbh->do("INSERT INTO freeblocks (cidr,city,routed,parent_id,vrf,master_id) VALUES (?,?,?,?,?,?)", undef,
309        ($cidr, '<NULL>', 'm', $mid, $args{vrf}, $mid) );
310
311      # master should be its own master, so deletes directly at the master level work
312      $dbh->do("UPDATE allocations SET master_id = ? WHERE id = ?", undef, ($mid, $mid) );
313
314      # If we get here, everything is happy.  Commit changes.
315      $dbh->commit;
316
317    } # done new master does not contain existing master(s)
318    else {
319
320      # collect the master(s) we're going to absorb, and snag the longest netmask while we're at it.
321      my $smallmask = $cidr->masklen;
322      my $sth = $dbh->prepare("SELECT cidr,id FROM allocations WHERE cidr <<= ? AND type='mm' AND parent_id=0");
323      $sth->execute($cidr);
324      my @cmasters;
325      my @oldmids;
326      while (my @data = $sth->fetchrow_array) {
327        my $master = new NetAddr::IP $data[0];
328        push @cmasters, $master;
329        push @oldmids, $data[1];
330        $smallmask = $master->masklen if $master->masklen > $smallmask;
331      }
332
333      # split the new master, and keep only those blocks not part of an existing master
334      my @blocklist;
335      foreach my $seg ($cidr->split($smallmask)) {
336        my $contained = 0;
337        foreach my $master (@cmasters) {
338          $contained = 1 if $master->contains($seg);
339        }
340        push @blocklist, $seg if !$contained;
341      }
342
343##fixme:  master_id
344      # collect the unrouted free blocks within the new master
345      $sth = $dbh->prepare("SELECT cidr FROM freeblocks WHERE masklen(cidr) <= ? AND cidr <<= ? AND routed = 'm'");
346      $sth->execute($smallmask, $cidr);
347      while (my @data = $sth->fetchrow_array) {
348        my $freeblock = new NetAddr::IP $data[0];
349        push @blocklist, $freeblock;
350      }
351
352      # combine the set of free blocks we should have now.
353      @blocklist = Compact(@blocklist);
354
355      # master
356      $dbh->do("INSERT INTO allocations (cidr,type,swip,vrf,rdns) VALUES (?,?,?,?,?)", undef,
357        ($cidr, 'mm', 'y', $args{vrf}, $args{rdns}) );
358      ($mid) = $dbh->selectrow_array("SELECT currval('allocations_id_seq')");
359
360      # master should be its own master, so deletes directly at the master level work
361      $dbh->do("UPDATE allocations SET master_id = ? WHERE id = ?", undef, ($mid, $mid) );
362
363      # and now insert the new data.  Make sure to delete old masters too.
364
365      # freeblocks
366      $sth = $dbh->prepare("DELETE FROM freeblocks WHERE cidr <<= ? AND parent_id IN (".join(',', @oldmids).")");
367      my $sth2 = $dbh->prepare("INSERT INTO freeblocks (cidr,city,routed,parent_id,vrf,master_id)".
368        " VALUES (?,'<NULL>','m',?,?,?)");
369      foreach my $newblock (@blocklist) {
370        $sth->execute($newblock);
371        $sth2->execute($newblock, $mid, $args{vrf}, $mid);
372      }
373
374      # Update immediate allocations, and remove the old parents
375      $sth = $dbh->prepare("UPDATE allocations SET parent_id = ? WHERE parent_id = ?");
376      $sth2 = $dbh->prepare("DELETE FROM allocations WHERE id = ?");
377      foreach my $old (@oldmids) {
378        $sth->execute($mid, $old);
379        $sth2->execute($old);
380      }
381
382      # *whew*  If we got here, we likely suceeded.
383      $dbh->commit;
384
385    } # new master contained existing master(s)
386  }; # end eval
387
388  if ($@) {
389    my $msg = $@;
390    eval { $dbh->rollback; };
391    return ('FAIL',$msg);
392  } else {
393
394    # Only attempt rDNS if the IPDB side succeeded
395    if ($rpc_url) {
396
397# Note *not* splitting reverse zones negates any benefit from caching the exported data.
398# IPv6 address space is far too large to split usefully, and in any case (also due to
399# the large address space) doesn't support the iterated template records v4 zones do
400# that causes the bulk of the slowdown that needs the cache anyway.
401
402      my @zonelist;
403# allow splitting reverse zones to be disabled, maybe, someday
404#if ($splitrevzones && !$cidr->{isv6}) {
405      if (1 && !$cidr->{isv6}) {
406        my $splitpoint = ($cidr->masklen <= 16 ? 16 : 24);      # hack pthui
407        @zonelist = $cidr->split($splitpoint);
408      } else {
409        @zonelist = ($cidr);
410      }
411      my @fails;
412      ##fixme:  remove hardcoding where possible
413      foreach my $subzone (@zonelist) {
414        my %rpcargs = (
415          rpcuser => $args{user},
416          revzone => "$subzone",
417          revpatt => $args{rdns},
418          defloc => $args{defloc},
419          group => $revgroup,   # not sure how these two could sanely be exposed, tbh...
420          state => 1,   # could make them globally configurable maybe
421        );
422        if ($rpc_url && !_rpc('addRDNS', %rpcargs)) {
423          push @fails, ("$subzone" => $errstr);
424        }
425      }
426      if (@fails) {
427        $errstr = "Warning(s) adding $cidr to reverse DNS:\n".join("\n", @fails);
428        return ('WARN',$mid);
429      }
430    }
431    return ('OK',$mid);
432  }
433} # end addMaster
434
435
436## IPDB::touchMaster()
437# Update last-changed timestamp on a master block.
438sub touchMaster {
439  my $dbh = shift; 
440  my $master = shift;
441
442  local $dbh->{AutoCommit} = 0;
443  local $dbh->{RaiseError} = 1;
444
445  eval {
446    $dbh->do("UPDATE allocations SET modifystamp=now() WHERE id = ?", undef, ($master));
447    $dbh->commit;
448  };
449
450  if ($@) {
451    my $msg = $@;
452    eval { $dbh->rollback; };
453    return ('FAIL',$msg);
454  }
455  return ('OK','OK');
456} # end touchMaster()
457
458
459## IPDB::listSummary()
460# Get summary list of all master blocks
461# Returns an arrayref to a list of hashrefs containing the master block, routed count,
462# allocated count, free count, and largest free block masklength
463sub listSummary {
464  my $dbh = shift;
465
466  my $mlist = $dbh->selectall_arrayref("SELECT cidr AS master,id,vrf FROM allocations ".
467        "WHERE type='mm' ORDER BY cidr",
468        { Slice => {} });
469
470  foreach (@{$mlist}) {
471    my ($rcnt) = $dbh->selectrow_array("SELECT count(*) FROM allocations WHERE cidr <<= ? AND type='rm' AND master_id = ?",
472        undef, ($$_{master}, $$_{id}));
473    $$_{routed} = $rcnt;
474    my ($acnt) = $dbh->selectrow_array("SELECT count(*) FROM allocations WHERE cidr <<= ? ".
475        "AND NOT type='rm' AND NOT type='mm' AND master_id = ?",
476        undef, ($$_{master}, $$_{id}));
477    $$_{allocated} = $acnt;
478    my ($fcnt) = $dbh->selectrow_array("SELECT count(*) FROM freeblocks WHERE cidr <<= ? AND master_id = ?",
479        undef, ($$_{master}, $$_{id}));
480    $$_{free} = $fcnt;
481    my ($bigfree) = $dbh->selectrow_array("SELECT masklen(cidr) AS maskbits FROM freeblocks WHERE cidr <<= ?".
482        " AND master_id = ? ORDER BY masklen(cidr) LIMIT 1", undef, ($$_{master}, $$_{id}));
483##fixme:  should find a way to do this without having to HTMLize the <>
484    $bigfree = "/$bigfree" if $bigfree;
485    $bigfree = '<NONE>' if !$bigfree;
486    $$_{bigfree} = $bigfree;
487  }
488  return $mlist;
489} # end listSummary()
490
491
492## IPDB::listSubs()
493# Get list of subnets within a specified CIDR block, on a specified VRF.
494# Returns an arrayref to a list of hashrefs containing the CIDR block, customer location or
495# city it's routed to, block type, SWIP status, and description
496sub listSubs {
497  my $dbh = shift;
498  my %args = @_;
499
500  # Just In Case
501  $args{vrf} = '' if !$args{vrf};
502
503  # Snag the allocations for this block
504  my $sth = $dbh->prepare("SELECT cidr,city,type,custid,swip,description,id,master_id".
505        " FROM allocations WHERE parent_id = ? ORDER BY cidr");
506  $sth->execute($args{parent});
507
508  # hack hack hack
509  # set up to flag swip=y records if they don't actually have supporting data in the customers table
510  my $custsth = $dbh->prepare("SELECT count(*) FROM customers WHERE custid = ?");
511
512  # snag some more details
513  my $substh = $dbh->prepare("SELECT count(*) FROM allocations WHERE cidr <<= ? ".
514        "AND type ~ '[mc]\$' AND master_id = ? AND NOT cidr = ? ");
515  my $alsth = $dbh->prepare("SELECT count(*) FROM allocations WHERE cidr <<= ? ".
516        "AND NOT type='rm' AND NOT type='mm' AND master_id = ?");
517  my $freesth = $dbh->prepare("SELECT count(*) FROM freeblocks WHERE cidr <<= ? AND master_id = ?");
518  my $lfreesth = $dbh->prepare("SELECT masklen(cidr) AS maskbits FROM freeblocks WHERE cidr <<= ?".
519        " AND master_id = ? ORDER BY masklen(cidr) LIMIT 1");
520
521  my @blocklist;
522  while (my ($cidr,$city,$type,$custid,$swip,$desc,$id,$mid) = $sth->fetchrow_array()) {
523    $custsth->execute($custid);
524    my ($ncust) = $custsth->fetchrow_array();
525    $substh->execute($cidr, $mid, $cidr);
526    my ($cont) = $substh->fetchrow_array();
527    $alsth->execute($cidr, $mid);
528    my ($alloc) = $alsth->fetchrow_array();
529    $freesth->execute($cidr, $mid);
530    my ($free) = $freesth->fetchrow_array();
531    $lfreesth->execute($cidr, $mid);
532    my ($lfree) = $lfreesth->fetchrow_array();
533    $lfree = "/$lfree" if $lfree;
534    $lfree = '<NONE>' if !$lfree;
535    my %row = (
536        block => $cidr,
537        subcontainers => $cont,
538        suballocs => $alloc,
539        subfree => $free,
540        lfree => $lfree,
541        city => $city,
542        type => $disp_alloctypes{$type},
543        custid => $custid,
544        swip => ($swip eq 'y' ? 'Yes' : 'No'),
545        partswip => ($swip eq 'y' && $ncust == 0 ? 1 : 0),
546        desc => $desc,
547        hassubs => ($type eq 'rm' || $type =~ /.c/ ? 1 : 0),
548        id => $id,
549        );
550#    $row{subblock} = ($type =~ /^.r$/);         # hmf.  wonder why these won't work in the hash declaration...
551    $row{listpool} = ($type =~ /^.[pd]$/);
552    push (@blocklist, \%row);
553  }
554  return \@blocklist;
555} # end listSubs()
556
557
558## IPDB::listContainers()
559# List all container-type allocations in a given parent
560# Takes a database handle and a hash:
561#  - parent is the ID of the parent block
562# Returns an arrayref to a list of hashrefs with the CIDR block, location, type,
563# description, block ID, and counts for the nmber uf suballocations (all types),
564# free blocks, and the CIDR size of the largest free block
565sub listContainers {
566  my $dbh = shift;
567  my %args = @_;
568
569  # Just In Case
570  $args{vrf} = '' if !$args{vrf};
571
572  # Snag the allocations for this block
573  my $sth = $dbh->prepare("SELECT cidr,city,type,custid,swip,description,id,master_id".
574        " FROM allocations WHERE parent_id = ? AND type ~ '[mc]\$' ORDER BY cidr");
575  $sth->execute($args{parent});
576
577  my $alsth = $dbh->prepare("SELECT count(*) FROM allocations WHERE cidr <<= ? ".
578        "AND NOT type='rm' AND NOT type='mm' AND master_id = ?");
579  my $freesth = $dbh->prepare("SELECT count(*) FROM freeblocks WHERE cidr <<= ? AND master_id = ?");
580  my $lfreesth = $dbh->prepare("SELECT masklen(cidr) AS maskbits FROM freeblocks WHERE cidr <<= ?".
581        " AND master_id = ? ORDER BY masklen(cidr) LIMIT 1");
582
583  my @blocklist;
584  while (my ($cidr,$city,$type,$custid,$swip,$desc,$id,$mid) = $sth->fetchrow_array()) {
585    $alsth->execute($cidr, $mid);
586    my ($alloc) = $alsth->fetchrow_array();
587    $freesth->execute($cidr, $mid);
588    my ($free) = $freesth->fetchrow_array();
589    $lfreesth->execute($cidr, $mid);
590    my ($lfree) = $lfreesth->fetchrow_array();
591    $lfree = "/$lfree" if $lfree;
592    $lfree = '<NONE>' if !$lfree;
593    my %row = (
594        block => $cidr,
595        suballocs => $alloc,
596        subfree => $free,
597        lfree => $lfree,
598        city => $city,
599        type => $disp_alloctypes{$type},
600        desc => $desc,
601        id => $id,
602        );
603    push (@blocklist, \%row);
604  }
605  return \@blocklist;
606} # end listContainers()
607
608
609## IPDB::listAllocations()
610# List all end-use allocations in a given parent
611# Takes a database handle and a hash:
612#  - parent is the ID of the parent block
613# Returns an arrayref to a list of hashrefs with the CIDR block, location, type,
614# custID, SWIP flag, description, block ID, and master ID
615sub listAllocations {
616  my $dbh = shift;
617  my %args = @_;
618
619  # Snag the allocations for this block
620  my $sth = $dbh->prepare("SELECT cidr,city,type,custid,swip,description,id,master_id".
621        " FROM allocations WHERE parent_id = ? AND type !~ '[mc]\$' ORDER BY cidr");
622  $sth->execute($args{parent});
623
624  # hack hack hack
625  # set up to flag swip=y records if they don't actually have supporting data in the customers table
626  my $custsth = $dbh->prepare("SELECT count(*) FROM customers WHERE custid = ?");
627
628  my @blocklist;
629  while (my ($cidr,$city,$type,$custid,$swip,$desc,$id,$mid) = $sth->fetchrow_array()) {
630    $custsth->execute($custid);
631    my ($ncust) = $custsth->fetchrow_array();
632    my %row = (
633        block => $cidr,
634        city => $city,
635        type => $disp_alloctypes{$type},
636        custid => $custid,
637        swip => ($swip eq 'y' ? 'Yes' : 'No'),
638        partswip => ($swip eq 'y' && $ncust == 0 ? 1 : 0),
639        desc => $desc,
640        id => $id,
641        );
642#    $row{subblock} = ($type =~ /^.r$/);         # hmf.  wonder why these won't work in the hash declaration...
643    $row{listpool} = ($type =~ /^.[pd]$/);
644    push (@blocklist, \%row);
645  }
646  return \@blocklist;
647} # end listAllocations()
648
649
650## IPDB::listFree()
651# Gets a list of free blocks in the requested parent/master and VRF instance in both CIDR and range notation
652# Takes a parent/master ID and an optional VRF specifier that defaults to empty.
653# Returns an arrayref to a list of hashrefs containing the CIDR and range-notation blocks
654# Returns some extra flags in the hashrefs for routed blocks, since those can have several subtypes
655sub listFree {
656  my $dbh = shift;
657
658  my %args = @_;
659  # Just In Case
660  $args{vrf} = '' if !$args{vrf};
661
662  my $sth = $dbh->prepare("SELECT cidr,id FROM freeblocks WHERE parent_id = ? ORDER BY cidr");
663#  $sth->execute($args{parent}, $args{vrf});
664  $sth->execute($args{parent});
665  my @flist;
666  while (my ($cidr,$id) = $sth->fetchrow_array()) {
667    $cidr = new NetAddr::IP $cidr;
668    my %row = (
669        fblock => "$cidr",
670        frange => $cidr->range,
671        fbid => $id,
672        fbparent => $args{parent},
673        );
674    push @flist, \%row;
675  }
676  return \@flist;
677} # end listFree()
678
679
680## IPDB::listPool()
681#
682sub listPool {
683  my $dbh = shift;
684  my $pool = shift;
685
686  my $sth = $dbh->prepare("SELECT ip,custid,available,description,type,id".
687        " FROM poolips WHERE parent_id = ? ORDER BY ip");
688  $sth->execute($pool);
689  my @poolips;
690  while (my ($ip,$custid,$available,$desc,$type,$id) = $sth->fetchrow_array) {
691    my %row = (
692        ip => $ip,
693        custid => $custid,
694        available => $available,
695        desc => $desc,
696        delme => $available eq 'n',
697        parent => $pool,
698        id => $id,
699        );
700    push @poolips, \%row;
701  }
702  return \@poolips;
703} # end listPool()
704
705
706## IPDB::getMasterList()
707# Get a list of master blocks, optionally including last-modified timestamps
708# Takes an optional flag to indicate whether to include timestamps;
709#  'm' includes ctime, all others (suggest 'c') do not.
710# Returns an arrayref to a list of hashrefs
711sub getMasterList {
712  my $dbh = shift;
713  my $stampme = shift || 'm';   # optional but should be set by caller for clarity
714
715  my $mlist = $dbh->selectall_arrayref("SELECT id,vrf,cidr AS master".($stampme eq 'm' ? ',modifystamp AS mtime' : '').
716        " FROM allocations WHERE type='mm' ORDER BY cidr", { Slice => {} });
717  return $mlist;
718} # end getMasterList()
719
720
721## IPDB::getTypeList()
722# Get an alloctype/description pair list suitable for dropdowns
723# Takes a flag to determine which general groups of types are returned
724# Returns an reference to an array of hashrefs
725sub getTypeList {
726  my $dbh = shift;
727  my $tgroup = shift || 'a';    # technically optional, like this, but should
728                                # really be specified in the call for clarity
729  my $tlist;
730  if ($tgroup eq 'n') {
731    # grouping 'p' - all netblock types.  These include routed blocks, containers (_c)
732    # and contained (_r) types, dynamic-allocation ranges (_e), static IP pools (_d and _p),
733    # and the "miscellaneous" cn, in, and en types.
734    $tlist = $dbh->selectall_arrayref("SELECT type,listname FROM alloctypes WHERE listorder <= 500 ".
735        "AND type NOT LIKE '_i' ORDER BY listorder", { Slice => {} });
736  } elsif ($tgroup eq 'p') {
737    # grouping 'p' - primary allocation types.  As with 'n' above but without the _r contained types.
738    $tlist = $dbh->selectall_arrayref("SELECT type,listname FROM alloctypes WHERE listorder <= 500 ".
739        "AND type NOT LIKE '_i' AND type NOT LIKE '_r' ORDER BY listorder", { Slice => {} });
740  } elsif ($tgroup eq 'c') {
741    # grouping 'c' - contained types.  These include all static IPs and all _r types.
742    $tlist = $dbh->selectall_arrayref("SELECT type,listname FROM alloctypes WHERE listorder <= 500 ".
743        " AND (type LIKE '_i' OR type LIKE '_r') ORDER BY listorder", { Slice => {} });
744  } elsif ($tgroup eq 'i') {
745    # grouping 'i' - static IP types.
746    $tlist = $dbh->selectall_arrayref("SELECT type,listname FROM alloctypes WHERE listorder <= 500 ".
747        " AND type LIKE '_i' ORDER BY listorder", { Slice => {} });
748  } else {
749    # grouping 'a' - all standard allocation types.  This includes everything
750    # but mm (present only as a formality).  Make this the default.
751    $tlist = $dbh->selectall_arrayref("SELECT type,listname FROM alloctypes WHERE listorder <= 500 ".
752        " ORDER BY listorder", { Slice => {} });
753  }
754  return $tlist;
755}
756
757
758## IPDB::getPoolSelect()
759# Get a list of pools matching the passed city and type that have 1 or more free IPs
760# Returns an arrayref to a list of hashrefs
761sub getPoolSelect {
762  my $dbh = shift;
763  my $iptype = shift;
764  my $pcity = shift;
765
766  my ($ptype) = ($iptype =~ /^(.)i$/);
767  return if !$ptype;
768  $ptype .= '_';
769
770  my $plist = $dbh->selectall_arrayref( q(
771        SELECT count(*) AS poolfree,p.pool AS poolblock, a.city AS poolcit
772        FROM poolips p
773        JOIN allocations a ON p.parent_id=a.id
774        WHERE p.available='y' AND a.city = ? AND p.type LIKE ?
775        GROUP BY p.pool,a.city
776        ),
777        { Slice => {} }, ($pcity, $ptype) );
778  return $plist;
779} # end getPoolSelect()
780
781
782## IPDB::findAllocateFrom()
783# Find free block to add a new allocation from.  (CIDR block version of pool select above, more or less)
784# Takes
785#  - mask length
786#  - allocation type
787#  - POP city "parent"
788#  - optional master-block restriction
789#  - optional flag to allow automatic pick-from-private-network-ranges
790# Returns a string with the first CIDR block matching the criteria, if any
791sub findAllocateFrom {
792  my $dbh = shift;
793  my $maskbits = shift;
794  my $type = shift;
795  my $city = shift;
796  my $pop = shift;
797  my %optargs = @_;
798
799  my $failmsg = "No suitable free block found\n";
800
801  my @vallist;
802  my $sql;
803
804  # Free pool IPs should be easy.
805  if ($type =~ /^.i$/) {
806    # User may get an IP from the wrong VRF.  User should not be using admin tools to allocate static IPs.
807    $sql = "SELECT id, ip, parent_id FROM poolips WHERE ip = ?";
808    @vallist = ($optargs{gimme});
809  } else {
810
811## Set up the SQL to find out what freeblock we can (probably) use for an allocation.
812## Very large systems will require development of a reserve system (possibly an extension
813## of the reserve-for-expansion concept in https://secure.deepnet.cx/trac/ipdb/ticket/24?)
814## Also populate a value list for the DBI call.
815
816    @vallist = ($maskbits);
817    $sql = "SELECT id,cidr,parent_id FROM freeblocks WHERE masklen(cidr) <= ?";
818
819# cases, strict rules
820# .c  ->  container type
821#   requires a routing container, fbtype r
822# .d  ->  DHCP/"normal-routing" static pool
823#   requires a routing container, fbtype r
824# .e  ->  Dynamic-assignment connectivity
825#   requires a routing container, fbtype r
826# .i  ->  error, can't allocate static IPs this way?
827# mm  ->  error, master block
828# rm  ->  routed block
829#   requires master block, fbtype m
830# .n  ->  Miscellaneous usage
831#   requires a routing container, fbtype r
832# .p  ->  PPP(oE) static pool
833#   requires a routing container, fbtype r
834# .r  ->  contained type
835#   requires a matching container, fbtype $1
836##fixme:  strict-or-not flag
837
838##fixme:  config or UI flag for "Strict" mode
839# if ($strictmode) {
840if (0) {
841  if ($type =~ /^(.)r$/) {
842    push @vallist, $1;
843    $sql .= " AND routed = ?";
844  } elsif ($type eq 'rm') {
845    $sql .= " AND routed = 'm'";
846  } else {
847    $sql .= " AND routed = 'r'";
848  }
849}
850
851    # for PPP(oE) and container types, the POP city is the one attached to the pool.
852    # individual allocations get listed with the customer city site.
853    ##fixme:  chain cities to align roughly with a full layer-2 node graph
854    $city = $pop if $type !~ /^.[pc]$/;
855    if ($type ne 'rm' && $city) {
856      $sql .= " AND city = ?";
857      push @vallist, $city;
858    }
859    # Allow specifying an arbitrary full block, instead of a master
860    if ($optargs{gimme}) {
861      $sql .= " AND cidr >>= ?";
862      push @vallist, $optargs{gimme};
863    }
864    # if a specific master was requested, allow the requestor to self->shoot(foot)
865    if ($optargs{master} && $optargs{master} ne '-') {
866      $sql .= " AND master_id = ?";
867# if $optargs{master} ne '-';
868      push @vallist, $optargs{master};
869    } else {
870      # if a specific master was NOT requested, filter out the RFC 1918 private networks
871      if (!$optargs{allowpriv}) {
872        $sql .= " AND NOT (cidr <<= '192.168.0.0/16' OR cidr <<= '10.0.0.0/8' OR cidr <<= '172.16.0.0/12')";
873      }
874    }
875    # Sorting and limiting, since we don't (currently) care to provide a selection of
876    # blocks to carve up.  This preserves something resembling optimal usage of the IP
877    # space by forcing contiguous allocations and free blocks as much as possible.
878    $sql .= " ORDER BY masklen(cidr) DESC,cidr LIMIT 1";
879  } # done setting up SQL for free CIDR block
880
881  my ($fbid,$fbfound,$fbparent) = $dbh->selectrow_array($sql, undef, @vallist);
882  return $fbid,$fbfound,$fbparent;
883} # end findAllocateFrom()
884
885
886## IPDB::ipParent()
887# Get an IP's parent pool's details
888# Takes a database handle and IP
889# Returns a hashref to the parent pool block, if any
890sub ipParent {
891  my $dbh = shift;
892  my $block = shift;
893
894  my $pinfo = $dbh->selectrow_hashref("SELECT cidr,custid,type,city,description FROM allocations".
895        " WHERE cidr >>= ? AND (type LIKE '_p' OR type LIKE '_d')", undef, ($block) );
896  return $pinfo;
897} # end ipParent()
898
899
900## IPDB::subParent()
901# Get a block's parent's details
902# Takes a database handle and CIDR block
903# Returns a hashref to the parent container block, if any
904sub subParent {
905  my $dbh = shift;
906  my $block = shift;
907
908  my $pinfo = $dbh->selectrow_hashref("SELECT cidr,custid,type,city,description FROM allocations".
909        " WHERE cidr >>= ?", undef, ($block) );
910  return $pinfo;
911} # end subParent()
912
913
914## IPDB::blockParent()
915# Get a block's parent's details
916# Takes a database handle and CIDR block
917# Returns a hashref to the parent container block, if any
918sub blockParent {
919  my $dbh = shift;
920  my $block = shift;
921
922  my $pinfo = $dbh->selectrow_hashref("SELECT cidr,city FROM routed".
923        " WHERE cidr >>= ?", undef, ($block) );
924  return $pinfo;
925} # end blockParent()
926
927
928## IPDB::getRoutedCity()
929# Get the city for a routed block.
930sub getRoutedCity {
931  my $dbh = shift;
932  my $block = shift;
933
934  my ($rcity) = $dbh->selectrow_array("SELECT city FROM routed WHERE cidr = ?", undef, ($block) );
935  return $rcity;
936} # end getRoutedCity()
937
938
939## IPDB::allocateBlock()
940# Does all of the magic of actually allocating a netblock
941# Requires a database handle, and a hash containing the block to allocate, routing depth, custid,
942#   type, city, block to allocate from, and optionally a description, notes, circuit ID,
943#   and private data
944# Returns a success code and optional error message.
945sub allocateBlock {
946  my $dbh = shift;
947
948  my %args = @_;
949
950  $args{cidr} = new NetAddr::IP $args{cidr};
951
952  $args{desc} = '' if !$args{desc};
953  $args{notes} = '' if !$args{notes};
954  $args{circid} = '' if !$args{circid};
955  $args{privdata} = '' if !$args{privdata};
956  $args{vrf} = '' if !$args{vrf};
957  $args{rdns} = '' if !$args{rdns};
958
959  my $sth;
960
961  # Snag the "type" of the freeblock and its CIDR
962  my ($alloc_from_type, $alloc_from, $fbparent, $fcity, $fbmaster) =
963        $dbh->selectrow_array("SELECT routed,cidr,parent_id,city,master_id FROM freeblocks WHERE id = ?",
964        undef, $args{fbid});
965  $alloc_from = new NetAddr::IP $alloc_from;
966
967  # To contain the error message, if any.
968  my $msg = "Unknown error allocating $args{cidr} as '$disp_alloctypes{$args{type}}'";
969
970  # Enable transactions and error handling
971  local $dbh->{AutoCommit} = 0; # These need to be local so we don't
972  local $dbh->{RaiseError} = 1; # step on our toes by accident.
973
974  if ($args{type} =~ /^.i$/) {
975    $msg = "Unable to assign static IP $args{cidr} to $args{custid}";
976    eval {
977      if ($args{cidr}) {        # IP specified
978        my ($isavail) = $dbh->selectrow_array("SELECT available FROM poolips WHERE ip=?", undef, ($args{cidr}) );
979        die "IP is not in an IP pool.\n"
980          if !$isavail;
981        die "IP already allocated.  Deallocate and reallocate, or update the entry\n"
982          if $isavail eq 'n';
983      } else {  # IP not specified, take first available
984        ($args{cidr}) = $dbh->selectrow_array("SELECT ip FROM poolips WHERE pool=? AND available='y' ORDER BY ip",
985                undef, ($args{alloc_from}) );
986      }
987      $dbh->do("UPDATE poolips SET custid = ?, city = ?,available='n', description = ?, notes = ?, ".
988        "circuitid = ?, privdata = ?, vrf = ?, rdns = ? ".
989        "WHERE ip = ? AND parent_id = ?", undef,
990                ($args{custid}, $args{city}, $args{desc}, $args{notes},
991                $args{circid}, $args{privdata}, $args{vrf}, $args{rdns},
992                $args{cidr}, $args{parent}) );
993
994# node hack
995      if ($args{nodeid} && $args{nodeid} ne '') {
996        $dbh->do("INSERT INTO noderef (block,node_id) VALUES (?,?)", undef, ($args{cidr}, $args{nodeid}) );
997      }
998# end node hack
999
1000      $dbh->commit;
1001    };
1002    if ($@) {
1003      $msg .= ": $@";
1004      eval { $dbh->rollback; };
1005      return ('FAIL', $msg);
1006    } else {
1007      _rpc('addOrUpdateRevRec', cidr => "$args{cidr}", name => $args{rdns}, rpcuser => $args{user});
1008      return ('OK', $args{cidr});
1009    }
1010
1011  } else { # end IP-from-pool allocation
1012
1013    if ($args{cidr} == $alloc_from) {
1014      # Easiest case- insert in one table, delete in the other, and go home.  More or less.
1015      # insert into allocations values (cidr,custid,type,city,desc) and
1016      # delete from freeblocks where cidr='cidr'
1017      # For data safety on non-transaction DBs, we delete first.
1018
1019      eval {
1020        $msg = "Unable to allocate $args{cidr} as '$disp_alloctypes{$args{type}}'";
1021
1022        # Insert the allocations entry
1023        $dbh->do("INSERT INTO allocations ".
1024                "(cidr,parent_id,master_id,vrf,custid,type,city,description,notes,circuitid,privdata,rdns)".
1025                " VALUES (?,?,?,?,?,?,?,?,?,?,?,?)", undef,
1026                ($args{cidr}, $fbparent, $fbmaster, $args{vrf}, $args{custid}, $args{type}, $args{city},
1027                $args{desc}, $args{notes}, $args{circid}, $args{privdata}, $args{rdns}) );
1028        my ($bid) = $dbh->selectrow_array("SELECT currval('allocations_id_seq')");
1029
1030        # Munge freeblocks
1031        if ($args{type} =~ /^(.)[mc]$/) {
1032          # special case - block is a routed or container/"reserve" block
1033          my $rtype = $1;
1034          $dbh->do("UPDATE freeblocks SET routed = ?,city = ?,parent_id = ? WHERE id = ?",
1035                undef, ($rtype, $args{city}, $bid, $args{fbid}) );
1036        } else {
1037          # "normal" case
1038          $dbh->do("DELETE FROM freeblocks WHERE id = ?", undef, ($args{fbid}) );
1039        }
1040
1041        # And initialize the pool, if necessary
1042        # PPPoE pools (currently dialup, DSL, and WiFi) get all IPs made available
1043        # "DHCP" or "real-subnet" pools have the net, gw, and bcast IPs removed.
1044        if ($args{type} =~ /^.p$/) {
1045          $msg = "Could not initialize IPs in new $disp_alloctypes{$args{type}} $args{cidr}";
1046          my ($code,$rmsg) = initPool($dbh, $args{cidr}, $args{type}, $args{city}, "all", $bid);
1047          die $rmsg if $code eq 'FAIL';
1048        } elsif ($args{type} =~ /^.d$/) {
1049          $msg = "Could not initialize IPs in new $disp_alloctypes{$args{type}} $args{cidr}";
1050          my ($code,$rmsg) = initPool($dbh, $args{cidr}, $args{type}, $args{city}, "normal", $bid);
1051          die $rmsg if $code eq 'FAIL';
1052        }
1053
1054# node hack
1055      if ($args{nodeid} && $args{nodeid} ne '') {
1056        $dbh->do("INSERT INTO noderef (block,node_id) VALUES (?,?)", undef, ($args{cidr}, $args{nodeid}) );
1057      }
1058# end node hack
1059
1060        $dbh->commit;
1061      }; # end of eval
1062      if ($@) {
1063        $msg .= ": ".$@;
1064        eval { $dbh->rollback; };
1065        return ('FAIL',$msg);
1066      }
1067
1068    } else { # cidr != alloc_from
1069
1070      # Hard case.  Allocation is smaller than free block.
1071
1072      # make sure new allocation is in fact within freeblock.  *sigh*
1073      return ('FAIL',"Requested allocation $args{cidr} is not within $alloc_from")
1074        if !$alloc_from->contains($args{cidr});
1075      my $wantmaskbits = $args{cidr}->masklen;
1076      my $maskbits = $alloc_from->masklen;
1077
1078      my @newfreeblocks;        # Holds free blocks generated from splitting the source freeblock.
1079
1080      # This determines which blocks will be left "free" after allocation.  We take the
1081      # block we're allocating from, and split it in half.  We see which half the wanted
1082      # block is in, and repeat until the wanted block is equal to one of the halves.
1083      my $i=0;
1084      my $tmp_from = $alloc_from;       # So we don't munge $args{alloc_from}
1085      while ($maskbits++ < $wantmaskbits) {
1086        my @subblocks = $tmp_from->split($maskbits);
1087        $newfreeblocks[$i++] = (($args{cidr}->within($subblocks[0])) ? $subblocks[1] : $subblocks[0]);
1088        $tmp_from = ( ($args{cidr}->within($subblocks[0])) ? $subblocks[0] : $subblocks[1] );
1089      } # while
1090
1091      # Begin SQL transaction block
1092      eval {
1093        $msg = "Unable to allocate $args{cidr} as '$disp_alloctypes{$args{type}}'";
1094
1095        # Delete old freeblocks entry
1096        $dbh->do("DELETE FROM freeblocks WHERE id = ?", undef, ($args{fbid}) );
1097
1098        # Insert new list of smaller free blocks left over
1099        $sth = $dbh->prepare("INSERT INTO freeblocks (cidr,city,routed,vrf,parent_id,master_id) VALUES (?,?,?,?,?,?)");
1100        foreach my $block (@newfreeblocks) {
1101          $sth->execute($block, $fcity, $alloc_from_type, $args{vrf}, $fbparent, $fbmaster);
1102        }
1103
1104        # Insert the allocations entry
1105        $dbh->do("INSERT INTO allocations ".
1106                "(cidr,parent_id,master_id,vrf,custid,type,city,description,notes,circuitid,privdata,rdns)".
1107                " VALUES (?,?,?,?,?,?,?,?,?,?,?,?)", undef,
1108                ($args{cidr}, $fbparent, $fbmaster, $args{vrf}, $args{custid}, $args{type}, $args{city},
1109                $args{desc}, $args{notes}, $args{circid}, $args{privdata}, $args{rdns}) );
1110        my ($bid) = $dbh->selectrow_array("SELECT currval('allocations_id_seq')");
1111
1112        # For routed/container types, add a freeblock within the allocated block so we can subdivide it further
1113        if ($args{type} =~ /(.)[mc]/) { # rm and .c types - containers
1114          my $rtype = $1;
1115          $sth->execute($args{cidr}, $args{city}, $rtype, $args{vrf}, $bid, $fbmaster);
1116        }
1117
1118        # And initialize the pool, if necessary
1119        # PPPoE pools (currently dialup, DSL, and WiFi) get all IPs made available
1120        # "DHCP" or "real-subnet" pools have the net, gw, and bcast IPs removed.
1121        if ($args{type} =~ /^.p$/) {
1122          $msg = "Could not initialize IPs in new $disp_alloctypes{$args{type}} $args{cidr}";
1123          my ($code,$rmsg) = initPool($dbh, $args{cidr}, $args{type}, $args{city}, "all", $bid);
1124          die $rmsg if $code eq 'FAIL';
1125        } elsif ($args{type} =~ /^.d$/) {
1126          $msg = "Could not initialize IPs in new $disp_alloctypes{$args{type}} $args{cidr}";
1127          my ($code,$rmsg) = initPool($dbh, $args{cidr}, $args{type}, $args{city}, "normal", $bid);
1128          die $rmsg if $code eq 'FAIL';
1129        }
1130
1131# node hack
1132      if ($args{nodeid} && $args{nodeid} ne '') {
1133        $dbh->do("INSERT INTO noderef (block,node_id) VALUES (?,?)", undef, ($args{cidr}, $args{nodeid}) );
1134      }
1135# end node hack
1136
1137        $dbh->commit;
1138      }; # end eval
1139      if ($@) {
1140        $msg .= ": ".$@;
1141        eval { $dbh->rollback; };
1142        return ('FAIL',$msg);
1143      }
1144
1145    } # end fullcidr != alloc_from
1146
1147    # now we do the DNS dance for netblocks, if we have an RPC server to do it with and a pattern to use.
1148    _rpc('addOrUpdateRevRec', cidr => "$args{cidr}", name => $args{rdns}, rpcuser => $args{user})
1149      if $args{rdns};
1150
1151    return ('OK', 'OK');
1152
1153  } # end static-IP vs netblock allocation
1154
1155} # end allocateBlock()
1156
1157
1158## IPDB::initPool()
1159# Initializes a pool
1160# Requires a database handle, the pool CIDR, type, city, and a parameter
1161# indicating whether the pool should allow allocation of literally every
1162# IP, or if it should reserve network/gateway/broadcast IPs
1163# Note that this is NOT done in a transaction, that's why it's a private
1164# function and should ONLY EVER get called from allocateBlock()
1165sub initPool {
1166  my ($dbh,undef,$type,$city,$class,$parent) = @_;
1167  my $pool = new NetAddr::IP $_[1];
1168
1169  # IPv6 does not lend itself to IP pools as supported
1170  return ('FAIL',"Refusing to create IPv6 static IP pool") if $pool->{isv6};
1171  # IPv4 pools don't make much sense beyond even /24.  Allow up to 4096-host footshooting anyway.
1172  # NetAddr::IP won't allow more than a /16 (65k hosts).
1173  return ('FAIL',"Refusing to create oversized static IP pool") if $pool->masklen <= 20;
1174
1175  my ($pcustid) = $dbh->selectrow_array("SELECT def_custid FROM alloctypes WHERE type=?", undef, ($type) );
1176  $type =~ s/[pd]$/i/;
1177  my $sth;
1178  my $msg;
1179
1180  # Trap errors so we can pass them back to the caller.  Even if the
1181  # caller is only ever supposed to be local, and therefore already
1182  # trapping errors.  >:(
1183  local $dbh->{AutoCommit} = 0; # These need to be local so we don't
1184  local $dbh->{RaiseError} = 1; # step on our toes by accident.
1185
1186  eval {
1187    # have to insert all pool IPs into poolips table as "unallocated".
1188    $sth = $dbh->prepare("INSERT INTO poolips (ip,custid,city,type,parent_id) VALUES (?,?,?,?,?)");
1189    my @poolip_list = $pool->hostenum;
1190    if ($class eq 'all') { # (DSL-ish block - *all* IPs available
1191      if ($pool->addr !~ /\.0$/) {      # .0 causes weirdness.
1192        $sth->execute($pool->addr, $pcustid, $city, $type, $parent);
1193      }
1194      for (my $i=0; $i<=$#poolip_list; $i++) {
1195        $sth->execute($poolip_list[$i]->addr, $pcustid, $city, $type, $parent);
1196      }
1197      $pool--;
1198      if ($pool->addr !~ /\.255$/) {    # .255 can cause weirdness.
1199        $sth->execute($pool->addr, $pcustid, $city, $type, $parent);
1200      }
1201    } else { # (real netblock)
1202      for (my $i=1; $i<=$#poolip_list; $i++) {
1203        $sth->execute($poolip_list[$i]->addr, $pcustid, $city, $type, $parent);
1204      }
1205    }
1206# don't commit here!  the caller may not be done.
1207#    $dbh->commit;
1208  };
1209  if ($@) {
1210    $msg = $@;
1211# Don't roll back!  It's up to the caller to handle this.
1212#    eval { $dbh->rollback; };
1213    return ('FAIL',$msg);
1214  } else {
1215    return ('OK',"OK");
1216  }
1217} # end initPool()
1218
1219
1220## IPDB::updateBlock()
1221# Update an allocation
1222# Takes all allocation fields in a hash
1223sub updateBlock {
1224  my $dbh = shift;
1225  my %args = @_;
1226
1227  return ('FAIL', 'Missing block to update') if !$args{block};
1228
1229  # Spaces don't show up well in lots of places.  Make sure they don't get into the DB.
1230  $args{custid} =~ s/^\s+//;
1231  $args{custid} =~ s/\s+$//;
1232
1233  # do it all in a transaction
1234  local $dbh->{AutoCommit} = 0;
1235  local $dbh->{RaiseError} = 1;
1236
1237  my @fieldlist;
1238  my @vallist;
1239  foreach ('custid', 'city', 'description', 'notes', 'circuitid', 'privdata', 'rdns') {
1240    if ($args{$_}) {
1241      push @fieldlist, $_;
1242      push @vallist, $args{$_};
1243    }
1244  }
1245
1246  my $binfo;
1247  my $updtable = 'allocations';
1248  my $keyfield = 'id';
1249  if ($args{type} =~ /^(.)i$/) {
1250    $updtable = 'poolips';
1251    $binfo = getBlockData($dbh, $args{block}, 'i');
1252  } else {
1253## fixme:  there's got to be a better way...
1254    $binfo = getBlockData($dbh, $args{block});
1255    if ($args{swip}) {
1256      if ($args{swip} eq 'on' || $args{swip} eq '1' || $args{swip} eq 'y') {
1257        $args{swip} = 'y';
1258      } else {
1259        $args{swip} = 'n';
1260      }
1261    }
1262    foreach ('type', 'swip') {
1263      if ($args{$_}) {
1264        push @fieldlist, $_;
1265        push @vallist, $args{$_};
1266      }
1267    }
1268  }
1269
1270  return ('FAIL', 'No fields to update') if !@fieldlist;
1271
1272  push @vallist, $args{block};
1273  my $sql = "UPDATE $updtable SET ";
1274  $sql .= join " = ?, ", @fieldlist;
1275  $sql .= " = ? WHERE $keyfield = ?";
1276
1277  eval {
1278    # do the update
1279    $dbh->do($sql, undef, @vallist);
1280
1281    if ($args{node}) {
1282      # done with delete/insert so we don't have to worry about funkyness updating a node ref that isn't there
1283      $dbh->do("DELETE FROM noderef WHERE block = ?", undef, ($binfo->{block}) );
1284      $dbh->do("INSERT INTO noderef (block,node_id) VALUES (?,?)", undef, ($binfo->{block}, $args{node}) )
1285        if $args{node} ne '--';
1286    }
1287
1288    $dbh->commit;
1289  };
1290  if ($@) {
1291    my $msg = $@;
1292    $dbh->rollback;
1293    return ('FAIL', $msg);
1294  }
1295
1296  $binfo->{block} =~ s|/32$||;
1297  _rpc('addOrUpdateRevRec', cidr => $binfo->{block}, name => $args{rdns}, rpcuser => $args{user});
1298  return ('OK','OK');
1299} # end updateBlock()
1300
1301
1302## IPDB::deleteBlock()
1303# Removes an allocation from the database, including deleting IPs
1304# from poolips and recombining entries in freeblocks if possible
1305# Also handles "deleting" a static IP allocation, and removal of a master
1306# Requires a database handle, the block to delete, the routing depth (if applicable),
1307# the VRF ID, and a flag to indicate whether to delete associated forward DNS entries
1308# as well as the reverse entry
1309sub deleteBlock {
1310  my ($dbh,$id,$basetype,$delfwd,$user) = @_;
1311
1312  # Collect info about the block we're going to delete
1313  my $binfo = getBlockData($dbh, $id, $basetype);
1314  my $cidr = new NetAddr::IP $binfo->{block};
1315
1316# For possible auto-VRF-ignoring (since public IPs shouldn't usually be present in more than one VRF)
1317# is_rfc1918 requires NetAddr::IP >= 4.059
1318# rather than doing this over and over and over.....
1319  my $tmpnum = $cidr->numeric;
1320# 192.168.0.0/16 -> 192.168.255.255  =>  3232235520 -> 3232301055
1321# 172.16.0.0/12  -> 172.31.255.255   =>  2886729728 -> 2887778303
1322# 10.0.0.0/8     -> 10.255.255.255   =>  167772160  -> 184549375
1323  my $isprivnet = (3232235520 <= $tmpnum && $tmpnum <= 3232301055) ||
1324        (2886729728 <= $tmpnum && $tmpnum <= 2887778303) ||
1325        (167772160 <= $tmpnum && $tmpnum <= 184549375);
1326
1327  my $sth;
1328
1329  # Magic variables used for odd allocation cases.
1330  my $container;
1331  my $con_type;
1332
1333
1334  # temporarily forced null, until a sane UI for VRF tracking can be found.
1335#  $vrf = '';# if !$vrf;        # as with SQL, the null value is not equal to ''.  *sigh*
1336
1337  # To contain the error message, if any.
1338  my $msg = "Unknown error deallocating $binfo->{type} $cidr";
1339  my $goback;   # to put the parent in so we can link back where the deallocate started
1340
1341  # Enable transactions and exception-on-errors... but only for this sub
1342  local $dbh->{AutoCommit} = 0;
1343  local $dbh->{RaiseError} = 1;
1344
1345  if ($binfo->{type} =~ /^.i$/) {
1346    # First case.  The "block" is a static IP
1347    # Note that we still need some additional code in the odd case
1348    # of a netblock-aligned contiguous group of static IPs
1349
1350    eval {
1351      $msg = "Unable to deallocate $disp_alloctypes{$binfo->{type}} $cidr";
1352      my $pinfo = getBlockData($dbh, $binfo->{parent_id}, 'b');
1353##fixme: VRF and rdepth
1354      $dbh->do("UPDATE poolips SET custid = ?, available = 'y',".
1355        "city = (SELECT city FROM allocations WHERE id = ?),".
1356        "description = '', notes = '', circuitid = '', vrf = ? WHERE id = ?", undef,
1357        ($pinfo->{custid}, $binfo->{parent_id}, $pinfo->{vrf}, $id) );
1358      $dbh->commit;
1359    };
1360    if ($@) {
1361      $msg .= ": $@";
1362      eval { $dbh->rollback; };
1363      return ('FAIL',$msg);
1364    } else {
1365##fixme:  RPC return code?
1366      _rpc('delByCIDR', cidr => "$cidr", user => $user, delforward => $delfwd, rpcuser => $user);
1367      return ('OK',"OK");
1368    }
1369
1370  } elsif ($binfo->{type} eq 'mm') { # end alloctype =~ /.i/
1371    # Second case.  The block is a full master block
1372
1373##fixme: VRF limit
1374    $msg = "Unable to delete master block $cidr";
1375    eval {
1376      $dbh->do("DELETE FROM allocations WHERE cidr <<= ? AND master_id = ?", undef, ($cidr, $binfo->{master_id}) );
1377      $dbh->do("DELETE FROM freeblocks WHERE cidr <<= ? AND master_id = ?", undef, ($cidr, $binfo->{master_id}) );
1378      $dbh->commit;
1379    };
1380    if ($@) {
1381      $msg .= ": $@";
1382      eval { $dbh->rollback; };
1383      return ('FAIL', $msg);
1384    }
1385
1386    # Have to handle potentially split reverse zones.  Assume they *are* split,
1387    # since if we added them here, they would have been added split.
1388# allow splitting reverse zones to be disabled, maybe, someday
1389#if ($splitrevzones && !$cidr->{isv6}) {
1390    my @zonelist;
1391    if (1 && !$cidr->{isv6}) {
1392      my $splitpoint = ($cidr->masklen <= 16 ? 16 : 24);        # hack pthui
1393      @zonelist = $cidr->split($splitpoint);
1394    } else {
1395      @zonelist = ($cidr);
1396    }
1397    my @fails;
1398    foreach my $subzone (@zonelist) {
1399      if ($rpc_url && !_rpc('delZone', zone => "$subzone", revrec => 'y', rpcuser => $user, delforward => $delfwd) ) {
1400        push @fails, ("$subzone" => $errstr);
1401      }
1402    }
1403    if (@fails) {
1404      return ('WARN',"Warning(s) deleting $cidr from reverse DNS:\n".join("\n", @fails));
1405    }
1406    return ('OK','OK');
1407
1408  } else { # end alloctype master block case
1409
1410    ## This is a big block; but it HAS to be done in a chunk.  Any removal
1411    ## of a netblock allocation may result in a larger chunk of free
1412    ## contiguous IP space - which may in turn be combined into a single
1413    ## netblock rather than a number of smaller netblocks.
1414
1415    my $retcode = 'OK';
1416    my ($ptype,$pcity,$ppatt,$p_id);
1417
1418    eval {
1419
1420##fixme:  add recursive flag to allow "YES DAMMIT DELETE ALL EVARYTHING!!1!!" without
1421# explicitly deleting any suballocations of the block to be deleted.
1422
1423      # get parent info of the block we're deleting
1424      my $pinfo = getBlockData($dbh, $binfo->{parent_id});
1425      $ptype = $pinfo->{type};
1426      $pcity = $pinfo->{city};
1427      $ppatt = $pinfo->{rdns};
1428      $p_id = $binfo->{parent_id};
1429
1430      # Delete the block
1431      $dbh->do("DELETE FROM allocations WHERE id = ?", undef, ($id) );
1432
1433      # munge the parent type a little
1434      $ptype = (split //, $ptype)[1];
1435
1436##fixme:  you can't...  CAN NOT....  assign the same public IP to multiple things.
1437#  'Net don't work like that, homey.  Restrict VRF-uniqueness to private IPs?
1438# -> $isprivnet flag from start of sub
1439
1440      # check to see if any container allocations could be the "true" parent
1441      my ($tparent,$tpar_id,$trtype,$tcity);
1442      $tpar_id = 0;
1443
1444##fixme:  this is far simpler in the strict VRF case;  we "know" that any allocation
1445# contained by a container is a part of the same allocation tree when the VRF fields are equal.
1446
1447# logic:
1448# For each possible container of $cidr
1449#  note the parent id
1450#  walk the chain up the parents
1451#    if we intersect $cidr's current parent, break
1452#  if we've intersected $cidr's current parent
1453#    set some variables to track that block
1454#    break
1455
1456# Set up part of "is it in the middle of a pool?" check
1457      my $wuzpool = $dbh->selectrow_hashref("SELECT cidr,parent_id,type,city,custid,id FROM allocations ".
1458        "WHERE (type LIKE '_d' OR type LIKE '_p') AND cidr >> ? AND master_id = ?", { Slice => {} },
1459        ($cidr, $binfo->{master_id}) );
1460
1461##fixme?
1462# edge cases not handled, or handled badly:
1463# -> $cidr managed to get to be the entirety of an IP pool
1464
1465      if ($wuzpool && $wuzpool->{id} != $id) {
1466        # we have legacy goo to be purified
1467        # going to ignore nested pools;  not possible to create them via API and no current legacy data includes any.
1468
1469        # for convenience
1470        my $poolid = $wuzpool->{id};
1471        my $pool = $wuzpool->{cidr};
1472        my $poolcity = $wuzpool->{city};
1473        my $pooltype = $wuzpool->{type};
1474        my $poolcustid = $wuzpool->{custid};
1475
1476        $retcode = 'WARNPOOL';
1477        $goback = "$poolid,$pool";
1478        # We've already deleted the block, now we have to stuff its IPs into the pool.
1479        $pooltype =~ s/[dp]$/i/;        # change type to static IP
1480        my $sth2 = $dbh->prepare("INSERT INTO poolips (ip,city,type,custid,parent_id) VALUES ".
1481          "(?,'$poolcity','$pooltype','$poolcustid',$poolid)");
1482
1483##fixme:  need to not insert net, gateway, and bcast on "real netblock" pools (DHCPish)
1484        # don't insert .0
1485        $sth2->execute($cidr->addr) unless $cidr->addr =~ m|\.0$|;
1486        $cidr++;
1487        my $bcast = $cidr->broadcast;
1488        while ($cidr != $bcast) {
1489          $sth2->execute($cidr->addr);
1490          $cidr++;
1491        }
1492        # don't insert .255
1493        $sth2->execute($cidr->addr) unless $cidr->addr =~ m|\.255$|;
1494
1495# Weirdness Happens.  $cidr goes read-only somewhere (this is a thing?!?),
1496# causing ->split, ->hostenum, and related methods to explode.  O_o
1497#        foreach my $ip ($cidr->hostenum) {
1498#          $sth2->execute($ip);
1499#        }
1500
1501      }
1502
1503## important!
1504# ... or IS IT?
1505# we may have undef'ed $wuzpool above, if the allocation tree $cidr is in doesn't intersect the pool we found
1506#if (!$wuzpool) {
1507
1508      else {
1509
1510# Edge case:  Block is the same size as more than one parent level.  Should be rare.
1511# - mainly master + first routing.  Sorting on parent_id hides the problem pretty well,
1512# but it's likely still possible to fail in particularly well-mangled databases.
1513# The ultimate fix for this may be to resurrect the "routing depth" atrocity.  :/
1514        # Get all possible (and probably a number of impossible) containers for $cidr
1515        $sth = $dbh->prepare("SELECT cidr,parent_id,type,city,id FROM allocations ".
1516          "WHERE (type LIKE '_m' OR type LIKE '_c') AND cidr >>= ? AND master_id = ? ".
1517          "ORDER BY masklen(cidr) DESC,parent_id DESC");
1518        $sth->execute($cidr, $binfo->{master_id});
1519
1520        # Quickly get certain fields (simpler than getBlockData()
1521        my $sth2 = $dbh->prepare("SELECT cidr,parent_id,type,city FROM allocations ".
1522          "WHERE (type LIKE '_m' OR type LIKE '_c') AND id = ? AND master_id = ?");
1523
1524        # For each possible container of $cidr...
1525        while (my @data = $sth->fetchrow_array) {
1526          my $i = 0;
1527          # Save some state and set a start point - parent ID of container we're checking
1528          $tparent = $data[0];
1529          my $ppid = $data[1];
1530          $trtype = $data[2];
1531          $tcity = $data[3];
1532          $tpar_id = $data[4];
1533          last if $data[4] == $binfo->{parent_id};  # Preemptively break if we're already in the right place
1534          last if $ppid == $binfo->{parent_id};     # ... or if the parent of the container is the block's parent
1535          while (1) {
1536            # Retrieve bits on that parent ID
1537            $sth2->execute($ppid, $binfo->{master_id});
1538            my @container = $sth2->fetchrow_array;
1539            $ppid = $container[1];
1540            last if $container[1] == 0;   # Break if we've hit a master block
1541            last if $ppid == $binfo->{parent_id};   # Break if we've reached the block $cidr is currently in
1542          }
1543          last if $ppid == $binfo->{parent_id};
1544        }
1545
1546        # found an alternate parent;  reset some parent-info bits
1547        if ($tpar_id != $binfo->{parent_id}) {
1548          $ptype = (split //, $trtype)[1];
1549          $pcity = $tcity;
1550          $retcode = 'WARNMERGE';       # may be redundant
1551          $p_id = $tpar_id;
1552        }
1553
1554        $goback = "$p_id,$tparent";     # breadcrumb, currently only used in case of live-parent-is-not-true-parent
1555
1556        # Special case - delete pool IPs
1557        if ($binfo->{type} =~ /^.[pd]$/) {
1558          # We have to delete the IPs from the pool listing.
1559##fixme:  rdepth?  vrf?
1560          $dbh->do("DELETE FROM poolips WHERE parent_id = ?", undef, ($id) );
1561        }
1562
1563        $pinfo = getBlockData($dbh, $p_id);
1564
1565        # If the block wasn't legacy goo embedded in a static pool, we check the
1566        # freeblocks in the identified parent to see if we can combine any of them.
1567
1568        # if the block to be deleted is a container, move its freeblock(s) up a level, and reset their parenting info
1569        if ($binfo->{type} =~ /^.[mc]/) {
1570          # move the freeblocks into the parent
1571          # we don't insert a new freeblock because there could be a live reparented sub.
1572          $dbh->do("UPDATE freeblocks SET parent_id = ?, routed = ?, city = ? WHERE parent_id = ?", undef,
1573                ($p_id, $ptype, $pcity, $id) );
1574        } else {
1575          # ... otherwise, add the freeblock
1576          $dbh->do("INSERT INTO freeblocks (cidr, city, routed, parent_id, master_id) VALUES (?,?,?,?,?)", undef,
1577                ($cidr, $pcity, $ptype, $p_id, $binfo->{master_id}) );
1578        }
1579
1580##fixme: vrf
1581##fixme:  simplify since all containers now represent different "layers"/"levels"?
1582        # set up the query to get the list of blocks to try to merge.
1583        $sth = $dbh->prepare("SELECT cidr,id FROM freeblocks ".
1584                "WHERE parent_id = ? ".
1585                "ORDER BY masklen(cidr) DESC");
1586
1587        $sth->execute($p_id);
1588
1589# NetAddr::IP->compact() attempts to produce the smallest inclusive block
1590# from the caller and the passed terms.
1591# EG:  if you call $cidr->compact($ip1,$ip2,$ip3) when $cidr, $ip1, $ip2,
1592#       and $ip3 are consecutive /27's starting on .0 (.0-.31, .32-.63,
1593#       .64-.95, and .96-.128), you will get an array containing a single
1594#       /25 as element 0 (.0-.127).  Order is not important;  you could have
1595#       $cidr=.32/27, $ip1=.96/27, $ip2=.0/27, and $ip3=.64/27.
1596
1597        my (@rawfb, @combinelist, %rawid);
1598        my $i=0;
1599        # for each free block under $parent, push a NetAddr::IP object into one list, and
1600        # continuously use NetAddr::IP->compact to automagically merge netblocks as possible.
1601        while (my @data = $sth->fetchrow_array) {
1602          my $testIP = new NetAddr::IP $data[0];
1603          push @rawfb, $testIP;
1604          $rawid{"$testIP"} = $data[1];  # $data[0] vs "$testIP" *does* make a difference for v6
1605          @combinelist = $testIP->compact(@combinelist);
1606        }
1607
1608        # now that we have the full list of "compacted" freeblocks, go back over
1609        # the list of raw freeblocks, and delete the ones that got merged.
1610        $sth = $dbh->prepare("DELETE FROM freeblocks WHERE id = ?");
1611        foreach my $rawfree (@rawfb) {
1612          next if grep { $rawfree == $_ } @combinelist; # skip if the raw block is in the compacted list
1613          $sth->execute($rawid{$rawfree});
1614        }
1615
1616        # now we walk the new list of compacted blocks, and see which ones we need to insert
1617        $sth = $dbh->prepare("INSERT INTO freeblocks (cidr,city,routed,parent_id,master_id) VALUES (?,?,?,?,?)");
1618        foreach my $cme (@combinelist) {
1619          next if grep { $cme == $_ } @rawfb;   # skip if the combined block was in the raw list
1620          $sth->execute($cme, $pcity, $ptype, $p_id, $binfo->{master_id});
1621        }
1622
1623      } # done returning IPs to the appropriate place
1624
1625      # If we got here, we've succeeded.  Whew!
1626      $dbh->commit;
1627    }; # end eval
1628    if ($@) {
1629      $msg .= ": $@";
1630      eval { $dbh->rollback; };
1631      return ('FAIL', $msg);
1632    } else {
1633##fixme:  RPC return code?
1634      _rpc('delByCIDR', cidr => "$cidr", rpcuser => $user, delforward => $delfwd, delsubs => 'y', parpatt => $ppatt);
1635      return ($retcode, $goback);
1636    }
1637
1638  } # end alloctype != netblock
1639
1640} # end deleteBlock()
1641
1642
1643## IPDB::getBlockData()
1644# Get CIDR or IP, custid, type, city, circuit ID, description, notes, modification time,
1645# private/restricted data, for a CIDR block or pool IP
1646# Also returns SWIP status flag for CIDR blocks or pool netblock for IPs
1647# Takes the block ID or IP to look up and an optional flag to indicate a pool IP lookup
1648# instead of a netblock.
1649# Returns a hashref to the block data
1650sub getBlockData {
1651  my $dbh = shift;
1652  my $id = shift;
1653  my $type = shift || 'b';      # default to netblock for lazy callers
1654
1655  # netblocks are in the allocations table;  pool IPs are in the poolips table.
1656  # If we try to look up a CIDR in an integer field we should just get back nothing.
1657  my ($btype) = $dbh->selectrow_array("SELECT type FROM allocations WHERE id=?", undef, ($id) );
1658
1659  if ($type eq 'i') {
1660    my $binfo = $dbh->selectrow_hashref("SELECT ip AS block, custid, type, city, circuitid, description,".
1661        " notes, modifystamp AS lastmod, privdata, vrf, rdns, parent_id, master_id".
1662        " FROM poolips WHERE id = ?", undef, ($id) );
1663    return $binfo;
1664  } else {
1665    my $binfo = $dbh->selectrow_hashref("SELECT cidr AS block, custid, type, city, circuitid, ".
1666        "description, notes, modifystamp AS lastmod, privdata, vrf, swip, rdns, parent_id, master_id".
1667        " FROM allocations WHERE id = ?", undef, ($id) );
1668    return $binfo;
1669  }
1670} # end getBlockData()
1671
1672
1673## IPDB::getBlockRDNS()
1674# Gets reverse DNS pattern for a block or IP.  Note that this will also
1675# retrieve any default pattern following the parent chain up, and check via
1676# RPC (if available) to see what the narrowest pattern for the requested block is
1677# Returns the current pattern for the block or IP.
1678sub getBlockRDNS {
1679  my $dbh = shift;
1680  my %args = @_;
1681
1682  $args{type} = 'b' if !$args{type};
1683  my $cached = 1;
1684
1685  # snag entry from database
1686  my ($rdns,$rfrom,$pid);
1687  if ($args{type} =~ /.i/) {
1688    ($rdns, $rfrom, $pid) = $dbh->selectrow_array("SELECT rdns,ip,parent_id FROM poolips WHERE id = ?",
1689        undef, ($args{id}) );
1690  } else {
1691    ($rdns, $rfrom, $pid) = $dbh->selectrow_array("SELECT rdns,cidr,parent_id FROM allocations WHERE id = ?",
1692        undef, ($args{id}) );
1693  }
1694
1695  # Can't see a way this could end up empty, for any case I care about.  If the caller
1696  # doesn't know an allocation ID to request, then they don't know anything else anyway.
1697  my $selfblock = $rfrom;
1698
1699  my $type;
1700  while (!$rdns && $pid) {
1701    ($rdns, $rfrom, $pid, $type) = $dbh->selectrow_array(
1702        "SELECT rdns,cidr,parent_id,type FROM allocations WHERE id = ?",
1703        undef, ($pid) );
1704    last if $type eq 'mm';  # break loops in unfortunate legacy data
1705  }
1706
1707  # use the actual allocation to check against the DNS utility;  we don't want
1708  # to always go chasing up the chain to the master...  which may (usually won't)
1709  # be present directly in DNS anyway
1710  my $cidr = new NetAddr::IP $selfblock;
1711
1712  if ($rpc_url) {
1713    # Use the first /16 or /24, rather than dithering over which sub-/14 /16
1714    # or sub-/19 /24 to retrieve - it's the least-wrong way to do things.
1715
1716    my ($rpcblock) = ($cidr->masklen <= 24 ? $cidr->split( ($cidr->masklen <= 16 ? 16 : 24) ) : $cidr);
1717    my %rpcargs = (
1718        rpcuser => $args{user},
1719        group => $revgroup,     # not sure how this could sanely be exposed, tbh...
1720        cidr => "$rpcblock",
1721        );
1722
1723    my $remote_rdns = _rpc('getRevPattern', %rpcargs);
1724    $rdns = $remote_rdns if $remote_rdns;
1725    $cached = 0;
1726  }
1727
1728  # hmm.  do we care about where it actually came from?
1729  return $rdns, $cached;
1730} # end getBlockRDNS()
1731
1732
1733## IPDB::getRDNSbyIP()
1734# Get individual reverse entries for the IP or CIDR IP range passed.  Sort of looking the
1735# opposite direction down the netblock tree compared to getBlockRDNS() above.
1736sub getRDNSbyIP {
1737  my $dbh = shift;
1738  my %args = @_;  # We want to accept a variety of call types
1739
1740  # key arguments:  allocation ID, type
1741  unless ($args{id} || $args{type}) {
1742    $errstr = 'Missing allocation ID or type';
1743    return;
1744  }
1745
1746  my @ret = ();
1747  # special case:  single IP.  Check if it's an allocation or in a pool, then do the RPC call for fresh data.
1748  if ($args{type} =~ /^.i$/) {
1749    my ($ip, $localrev) = $dbh->selectrow_array("SELECT ip, rdns FROM poolips WHERE id = ?", undef, ($args{id}) );
1750    push @ret, { 'r_ip' => $ip, 'iphost' => $localrev };
1751  } else {
1752    if ($rpc_url) {
1753      my %rpcargs = (
1754        rpcuser => $args{user},
1755        group => $revgroup,     # not sure how this could sanely be exposed, tbh...
1756        cidr => $args{range},
1757        );
1758
1759      my $remote_rdns = _rpc('getRevSet', %rpcargs);
1760      return $remote_rdns;
1761#      $rdns = $remote_rdns if $remote_rdns;
1762#      $cached = 0;
1763    }
1764  }
1765  return \@ret;
1766} # end getRDNSbyIP()
1767
1768
1769## IPDB::getNodeList()
1770# Gets a list of node ID+name pairs as an arrayref to a list of hashrefs
1771sub getNodeList {
1772  my $dbh = shift;
1773 
1774  my $ret = $dbh->selectall_arrayref("SELECT node_id, node_name FROM nodes ORDER BY node_type,node_id",
1775        { Slice => {} });
1776  return $ret;
1777} # end getNodeList()
1778
1779
1780## IPDB::getNodeName()
1781# Get node name from the ID
1782sub getNodeName {
1783  my $dbh = shift;
1784  my $nid = shift;
1785
1786  my ($nname) = $dbh->selectrow_array("SELECT node_name FROM nodes WHERE node_id = ?", undef, ($nid) );
1787  return $nname;
1788} # end getNodeName()
1789
1790
1791## IPDB::getNodeInfo()
1792# Get node name and ID associated with a block
1793sub getNodeInfo {
1794  my $dbh = shift;
1795  my $block = shift;
1796
1797  my ($nid, $nname) = $dbh->selectrow_array("SELECT nodes.node_id,node_name FROM nodes INNER JOIN noderef".
1798        " ON nodes.node_id=noderef.node_id WHERE noderef.block = ?", undef, ($block) );
1799  return ($nid, $nname);
1800} # end getNodeInfo()
1801
1802
1803## IPDB::mailNotify()
1804# Sends notification mail to recipients regarding an IPDB operation
1805sub mailNotify {
1806  my $dbh = shift;
1807  my ($action,$subj,$message) = @_;
1808
1809  return if $smtphost eq 'smtp.example.com';   # do nothing if still using default SMTP host.
1810
1811##fixme: need to redesign the breakdown/processing for $action for proper handling of all cases
1812
1813# split action into parts for fiddlement.  nb: there are almost certainly better ways to do this.
1814  my @actionbits = split //, $action;
1815
1816  # want to notify anyone who has specifically requested notify on *this* type ($action as passed),
1817  # on "all static IP types" or "all pool types" (and other last-char-in-type groupings), on eg "all DSL types",
1818  # and "all events with this action"
1819  my @actionsets = ($action);
1820##fixme: ick, eww.  really gotta find a better way to handle this...
1821  push @actionsets, ($actionbits[0].'.'.$actionbits[2],
1822        $actionbits[0].$actionbits[1].'.', $actionbits[0].'a') if $action =~ /^.{3}$/;
1823
1824  my $mailer = Net::SMTP->new($smtphost, Hello => "ipdb.$domain");
1825
1826  # get recip list from db
1827  my $sth = $dbh->prepare("SELECT reciplist FROM notify WHERE action=?");
1828
1829  my %reciplist;
1830  foreach (@actionsets) {
1831    $sth->execute($_);
1832##fixme - need to handle db errors
1833    my ($recipsub) = $sth->fetchrow_array;
1834    next if !$recipsub;
1835    foreach (split(/,/, $recipsub)) {
1836      $reciplist{$_}++;
1837    }
1838  }
1839
1840  return if !%reciplist;
1841
1842  foreach my $recip (keys %reciplist) {
1843    $mailer->mail("ipdb\@$domain");
1844    $mailer->to($recip);
1845    $mailer->data("From: \"$org_name IP Database\" <ipdb\@$domain>\n",
1846        "To: $recip\n",
1847        "Date: ".strftime("%a, %d %b %Y %H:%M:%S %z",localtime)."\n",
1848        "Subject: {IPDB} $subj\n",
1849        "X-Mailer: IPDB Notify v".sprintf("%.1d",$IPDB::VERSION)."\n",
1850        "Organization: $org_name\n",
1851        "\n$message\n");
1852  }
1853  $mailer->quit;
1854}
1855
1856# Indicates module loaded OK.  Required by Perl.
18571;
Note: See TracBrowser for help on using the repository browser.