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

Last change on this file since 660 was 660, checked in by Kris Deugau, 8 years ago

/trunk

Backmerge addition of RPC shim from /branches/stable r600

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