source: branches/stable/cgi-bin/IPDB.pm @ 594

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

/branches/stable

Merge SQL changes and other miscellaneous fixes from /trunk through r553.

  • Property svn:keywords set to Date Rev Author
File size: 45.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: 2013-05-15 20:17:00 +0000 (Wed, 15 May 2013) $
6# SVN revision $Rev: 594 $
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( Compact );
19use POSIX;
20use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
21
22$VERSION        = 2; ##VERSION##
23@ISA            = qw(Exporter);
24@EXPORT_OK    = qw(
25        %disp_alloctypes %list_alloctypes %def_custids @citylist @poplist
26        %IPDBacl %aclmsg
27        &initIPDBGlobals &connectDB &finish &checkDBSanity
28        &addMaster &touchMaster
29        &listSummary &listMaster &listRBlock &listFree &listPool
30        &getMasterList &getTypeList &getPoolSelect &findAllocateFrom
31        &ipParent &subParent &blockParent &getRoutedCity
32        &allocateBlock &updateBlock &deleteBlock &getBlockData
33        &getNodeList &getNodeName &getNodeInfo
34        &mailNotify
35        );
36
37@EXPORT         = (); # Export nothing by default.
38%EXPORT_TAGS    = ( ALL => [qw(
39                %disp_alloctypes %list_alloctypes %def_custids @citylist @poplist
40                %IPDBacl %aclmsg
41                &initIPDBGlobals &connectDB &finish &checkDBSanity
42                &addMaster &touchMaster
43                &listSummary &listMaster &listRBlock &listFree &listPool
44                &getMasterList &getTypeList &getPoolSelect &findAllocateFrom
45                &ipParent &subParent &blockParent &getRoutedCity
46                &allocateBlock &updateBlock &deleteBlock &getBlockData
47                &getNodeList &getNodeName &getNodeInfo
48                &mailNotify
49                )]
50        );
51
52##
53## Global variables
54##
55our %disp_alloctypes;
56our %list_alloctypes;
57our %def_custids;
58our @citylist;
59our @poplist;
60our %IPDBacl;
61
62# mapping table for functional-area => error message
63our %aclmsg = (
64        addmaster       => 'add a master block',
65        addblock        => 'add an allocation',
66        updateblock     => 'update a block',
67        delblock        => 'delete an allocation',
68        );
69
70our $org_name = 'Example Corp';
71our $smtphost = 'smtp.example.com';
72our $domain = 'example.com';
73our $defcustid = '5554242';
74# mostly for rwhois
75##fixme:  leave these blank by default?
76our $rwhoisDataPath = '/usr/local/rwhoisd/etc/rwhoisd'; # to match ./configure defaults from rwhoisd-1.5.9.6
77our $org_street = '123 4th Street';
78our $org_city = 'Anytown';
79our $org_prov_state = 'ON';
80our $org_pocode = 'H0H 0H0';
81our $org_country = 'CA';
82our $org_phone = '000-555-1234';
83our $org_techhandle = 'ISP-ARIN-HANDLE';
84our $org_email = 'noc@example.com';
85our $hostmaster = 'dns@example.com';
86
87our $syslog_facility = 'local2';
88
89# Allow allocations to come from private IP ranges by default?
90# Set to 'y' or 'on' to enable.
91our $allowprivrange = '';
92
93# Let's initialize the globals.
94## IPDB::initIPDBGlobals()
95# Initialize all globals.  Takes a database handle, returns a success or error code
96sub initIPDBGlobals {
97  my $dbh = $_[0];
98  my $sth;
99
100  # Initialize alloctypes hashes
101  $sth = $dbh->prepare("select type,listname,dispname,listorder,def_custid from alloctypes order by listorder");
102  $sth->execute;
103  while (my @data = $sth->fetchrow_array) {
104    $disp_alloctypes{$data[0]} = $data[2];
105    $def_custids{$data[0]} = $data[4];
106    if ($data[3] < 900) {
107      $list_alloctypes{$data[0]} = $data[1];
108    }
109  }
110
111  # City and POP listings
112  $sth = $dbh->prepare("select city,routing from cities order by city");
113  $sth->execute;
114  return (undef,$sth->errstr) if $sth->err;
115  while (my @data = $sth->fetchrow_array) {
116    push @citylist, $data[0];
117    if ($data[1] eq 'y') {
118      push @poplist, $data[0];
119    }
120  }
121
122  # Load ACL data.  Specific username checks are done at a different level.
123  $sth = $dbh->prepare("select username,acl from users");
124  $sth->execute;
125  return (undef,$sth->errstr) if $sth->err;
126  while (my @data = $sth->fetchrow_array) {
127    $IPDBacl{$data[0]} = $data[1];
128  }
129
130##fixme:  initialize HTML::Template env var for template path
131# something like $self->path().'/templates' ?
132#  $ENV{HTML_TEMPLATE_ROOT} = 'foo/bar';
133
134  return (1,"OK");
135} # end initIPDBGlobals
136
137
138## IPDB::connectDB()
139# Creates connection to IPDB.
140# Requires the database name, username, and password.
141# Returns a handle to the db.
142# Set up for a PostgreSQL db;  could be any transactional DBMS with the
143# right changes.
144sub connectDB {
145  my $dbname = shift;
146  my $user = shift;
147  my $pass = shift;
148  my $dbhost = shift;
149
150  my $dbh;
151  my $DSN = "DBI:Pg:".($dbhost ? "host=$dbhost;" : '')."dbname=$dbname";
152
153# Note that we want to autocommit by default, and we will turn it off locally as necessary.
154# We may not want to print gobbledygook errors;  YMMV.  Have to ponder that further.
155  $dbh = DBI->connect($DSN, $user, $pass, {
156        AutoCommit => 1,
157        PrintError => 0
158        })
159    or return (undef, $DBI::errstr) if(!$dbh);
160
161# Return here if we can't select.  Note that this indicates a
162# problem executing the select.
163  my $sth = $dbh->prepare("select type from alloctypes");
164  $sth->execute();
165  return (undef,$DBI::errstr) if ($sth->err);
166
167# See if the select returned anything (or null data).  This should
168# succeed if the select executed, but...
169  $sth->fetchrow();
170  return (undef,$DBI::errstr)  if ($sth->err);
171
172# If we get here, we should be OK.
173  return ($dbh,"DB connection OK");
174} # end connectDB
175
176
177## IPDB::finish()
178# Cleans up after database handles and so on.
179# Requires a database handle
180sub finish {
181  my $dbh = $_[0];
182  $dbh->disconnect if $dbh;
183} # end finish
184
185
186## IPDB::checkDBSanity()
187# Quick check to see if the db is responding.  A full integrity
188# check will have to be a separate tool to walk the IP allocation trees.
189sub checkDBSanity {
190  my ($dbh) = $_[0];
191
192  if (!$dbh) {
193    print "No database handle, or connection has been closed.";
194    return -1;
195  } else {
196    # it connects, try a stmt.
197    my $sth = $dbh->prepare("select type from alloctypes");
198    my $err = $sth->execute();
199
200    if ($sth->fetchrow()) {
201      # all is well.
202      return 1;
203    } else {
204      print "Connected to the database, but could not execute test statement.  ".$sth->errstr();
205      return -1;
206    }
207  }
208  # Clean up after ourselves.
209#  $dbh->disconnect;
210} # end checkDBSanity
211
212
213## IPDB::addMaster()
214# Does all the magic necessary to sucessfully add a master block
215# Requires database handle, block to add
216# Returns failure code and error message or success code and "message"
217sub addMaster {
218  my $dbh = shift;
219  my $cidr = new NetAddr::IP shift;
220
221  # Allow transactions, and raise an exception on errors so we can catch it later.
222  # Use local to make sure these get "reset" properly on exiting this block
223  local $dbh->{AutoCommit} = 0;
224  local $dbh->{RaiseError} = 1;
225
226  # Wrap all the SQL in a transaction
227  eval {
228    my ($mexist) = $dbh->selectrow_array("SELECT cidr FROM masterblocks WHERE cidr <<= ?", undef, ($cidr) );
229
230    if (!$mexist) {
231      # First case - master is brand-spanking-new.
232##fixme: rwhois should be globally-flagable somewhere, much like a number of other things
233## maybe a db table called "config"?
234      $dbh->do("INSERT INTO masterblocks (cidr,rwhois) VALUES (?,?)", undef, ($cidr,'y') );
235
236# Unrouted blocks aren't associated with a city (yet).  We don't rely on this
237# elsewhere though;  legacy data may have traps and pitfalls in it to break this.
238# Thus the "routed" flag.
239      $dbh->do("INSERT INTO freeblocks (cidr,maskbits,city,routed) VALUES (?,?,?,?)", undef,
240        ($cidr, $cidr->masklen, '<NULL>', 'n') );
241
242      # If we get here, everything is happy.  Commit changes.
243      $dbh->commit;
244
245    } # done new master does not contain existing master(s)
246    else {
247
248      # collect the master(s) we're going to absorb, and snag the longest netmask while we're at it.
249      my $smallmask = $cidr->masklen;
250      my $sth = $dbh->prepare("SELECT cidr FROM masterblocks WHERE cidr <<= ?");
251      $sth->execute($cidr);
252      my @cmasters;
253      while (my @data = $sth->fetchrow_array) {
254        my $master = new NetAddr::IP $data[0];
255        push @cmasters, $master;
256        $smallmask = $master->masklen if $master->masklen > $smallmask;
257      }
258
259      # split the new master, and keep only those blocks not part of an existing master
260      my @blocklist;
261      foreach my $seg ($cidr->split($smallmask)) {
262        my $contained = 0;
263        foreach my $master (@cmasters) {
264          $contained = 1 if $master->contains($seg);
265        }
266        push @blocklist, $seg if !$contained;
267      }
268
269      # collect the unrouted free blocks within the new master
270      $sth = $dbh->prepare("SELECT cidr FROM freeblocks WHERE maskbits <= ? AND cidr <<= ? AND routed = 'n'");
271      $sth->execute($smallmask, $cidr);
272      while (my @data = $sth->fetchrow_array) {
273        my $freeblock = new NetAddr::IP $data[0];
274        push @blocklist, $freeblock;
275      }
276
277      # combine the set of free blocks we should have now.
278      @blocklist = Compact(@blocklist);
279
280      # and now insert the new data.  Make sure to delete old masters too.
281
282      # freeblocks
283      $sth = $dbh->prepare("DELETE FROM freeblocks WHERE cidr <<= ?");
284      my $sth2 = $dbh->prepare("INSERT INTO freeblocks (cidr,maskbits,city,routed) VALUES (?,?,'<NULL>','n')");
285      foreach my $newblock (@blocklist) {
286        $sth->execute($newblock);
287        $sth2->execute($newblock, $newblock->masklen);
288      }
289
290      # master
291      $dbh->do("DELETE FROM masterblocks WHERE cidr <<= ?", undef, ($cidr) );
292      $dbh->do("INSERT INTO masterblocks (cidr,rwhois) VALUES (?,?)", undef, ($cidr, 'y') );
293
294      # *whew*  If we got here, we likely suceeded.
295      $dbh->commit;
296    } # new master contained existing master(s)
297  }; # end eval
298
299  if ($@) {
300    my $msg = $@;
301    eval { $dbh->rollback; };
302    return ('FAIL',$msg);
303  } else {
304    return ('OK','OK');
305  }
306} # end addMaster
307
308
309## IPDB::touchMaster()
310# Update last-changed timestamp on a master block.
311sub touchMaster {
312  my $dbh = shift; 
313  my $master = shift;
314
315  local $dbh->{AutoCommit} = 0;
316  local $dbh->{RaiseError} = 1;
317
318  eval {
319    $dbh->do("UPDATE masterblocks SET mtime=now() WHERE cidr = ?", undef, ($master));
320    $dbh->commit;
321  };
322
323  if ($@) {
324    my $msg = $@;
325    eval { $dbh->rollback; };
326    return ('FAIL',$msg);
327  }
328  return ('OK','OK');
329} # end touchMaster()
330
331
332## IPDB::listSummary()
333# Get summary list of all master blocks
334# Returns an arrayref to a list of hashrefs containing the master block, routed count,
335# allocated count, free count, and largest free block masklength
336sub listSummary {
337  my $dbh = shift;
338
339  my $mlist = $dbh->selectall_arrayref("SELECT cidr AS master FROM masterblocks ORDER BY cidr", { Slice => {} });
340
341  foreach (@{$mlist}) {
342    my ($rcnt) = $dbh->selectrow_array("SELECT count(*) FROM routed WHERE cidr <<= ?", undef, ($$_{master}));
343    $$_{routed} = $rcnt;
344    my ($acnt) = $dbh->selectrow_array("SELECT count(*) FROM allocations WHERE cidr <<= ?", undef, ($$_{master}));
345    $$_{allocated} = $acnt;
346    my ($fcnt) = $dbh->selectrow_array("SELECT count(*) FROM freeblocks WHERE cidr <<= ?".
347        " AND (routed='y' OR routed='n')", undef, ($$_{master}));
348    $$_{free} = $fcnt;
349    my ($bigfree) = $dbh->selectrow_array("SELECT maskbits FROM freeblocks WHERE cidr <<= ?".
350        " AND (routed='y' OR routed='n') ORDER BY maskbits LIMIT 1", undef, ($$_{master}));
351##fixme:  should find a way to do this without having to HTMLize the <>
352    $bigfree = "/$bigfree" if $bigfree;
353    $bigfree = '<NONE>' if !$bigfree;
354    $$_{bigfree} = $bigfree;
355  }
356  return $mlist;
357} # end listSummary()
358
359
360## IPDB::listMaster()
361# Get list of routed blocks in the requested master
362# Returns an arrayref to a list of hashrefs containing the routed block, POP/city the block is routed to,
363# allocated count, free count, and largest free block masklength
364sub listMaster {
365  my $dbh = shift;
366  my $master = shift;
367
368  my $rlist = $dbh->selectall_arrayref("SELECT cidr AS block,city FROM routed WHERE cidr <<= ? ORDER BY cidr",
369        { Slice => {} }, ($master) );
370
371  foreach (@{$rlist}) {
372    my ($acnt) = $dbh->selectrow_array("SELECT count(*) FROM allocations WHERE cidr <<= ?", undef, ($$_{block}));
373    $$_{nsubs} = $acnt;
374    my ($fcnt) = $dbh->selectrow_array("SELECT count(*) FROM freeblocks WHERE cidr <<= ?".
375        " AND (routed='y' OR routed='n')", undef, ($$_{block}));
376    $$_{nfree} = $fcnt;
377    my ($bigfree) = $dbh->selectrow_array("SELECT maskbits FROM freeblocks WHERE cidr <<= ?".
378        " AND (routed='y' OR routed='n') ORDER BY maskbits LIMIT 1", undef, ($$_{block}));
379##fixme:  should find a way to do this without having to HTMLize the <>
380    $bigfree = "/$bigfree" if $bigfree;
381    $bigfree = '<NONE>' if !$bigfree;
382    $$_{lfree} = $bigfree;
383  }
384  return $rlist;
385} # end listMaster()
386
387
388## IPDB::listRBlock()
389# Gets a list of free blocks in the requested parent/master in both CIDR and range notation
390# Takes a parent/master and an optional flag to look at routed or unrouted blocks, depending
391# on whether the master is a direct master or a routed block
392# Returns an arrayref to a list of hashrefs containing the CIDR and range-notation blocks
393sub listRBlock {
394  my $dbh = shift;
395  my $routed = shift;
396
397  # Snag the allocations for this block
398  my $sth = $dbh->prepare("SELECT cidr,city,type,custid,swip,description".
399        " FROM allocations WHERE cidr <<= ? ORDER BY cidr");
400  $sth->execute($routed);
401
402  # hack hack hack
403  # set up to flag swip=y records if they don't actually have supporting data in the customers table
404  my $custsth = $dbh->prepare("SELECT count(*) FROM customers WHERE custid = ?");
405
406  my @blocklist;
407  while (my ($cidr,$city,$type,$custid,$swip,$desc) = $sth->fetchrow_array()) {
408    $custsth->execute($custid);
409    my ($ncust) = $custsth->fetchrow_array();
410    my %row = (
411        block => $cidr,
412        city => $city,
413        type => $disp_alloctypes{$type},
414        custid => $custid,
415        swip => ($swip eq 'y' ? 'Yes' : 'No'),
416        partswip => ($swip eq 'y' && $ncust == 0 ? 1 : 0),
417        desc => $desc
418        );
419    $row{subblock} = ($type =~ /^.r$/);         # hmf.  wonder why these won't work in the hash declaration...
420    $row{listpool} = ($type =~ /^.[pd]$/);
421    push (@blocklist, \%row);
422  }
423  return \@blocklist;
424} # end listRBlock()
425
426
427## IPDB::listFree()
428# Gets a list of free blocks in the requested parent/master in both CIDR and range notation
429# Takes a parent/master and an optional "routed or unrouted" flag that defaults to unrouted.
430# Returns an arrayref to a list of hashrefs containing the CIDR and range-notation blocks
431# Returns some extra flags in the hashrefs for routed blocks, since those can have several subtypes
432sub listFree {
433  my $dbh = shift;
434  my $master = shift;
435  my $routed = shift || 'n';
436
437  # do it this way so we can waste a little less time iterating
438  my $sth = $dbh->prepare("SELECT cidr,routed FROM freeblocks WHERE cidr <<= ? AND ".
439        ($routed eq 'n' ? '' : 'NOT')." routed = 'n' ORDER BY cidr");
440  $sth->execute($master);
441  my @flist;
442  while (my ($cidr,$rtype) = $sth->fetchrow_array()) {
443    $cidr = new NetAddr::IP $cidr;
444    my %row = (
445        fblock => "$cidr",
446        frange => $cidr->range,
447        );
448    if ($routed eq 'y') {
449      $row{subblock} = ($rtype ne 'y' && $rtype ne 'n');
450      $row{fbtype} = $rtype;
451    }
452    push @flist, \%row;
453  }
454  return \@flist;
455} # end listFree()
456
457
458## IPDB::listPool()
459#
460sub listPool {
461  my $dbh = shift;
462  my $pool = shift;
463
464  my $sth = $dbh->prepare("SELECT ip,custid,available,description,type".
465        " FROM poolips WHERE pool = ? ORDER BY ip");
466  $sth->execute($pool);
467  my @poolips;
468  while (my ($ip,$custid,$available,$desc,$type) = $sth->fetchrow_array) {
469    my %row = (
470        ip => $ip,
471        custid => $custid,
472        available => $available,
473        desc => $desc,
474        delme => $available eq 'n'
475        );
476    push @poolips, \%row;
477  }
478  return \@poolips;
479} # end listPool()
480
481
482## IPDB::getMasterList()
483# Get a list of master blocks, optionally including last-modified timestamps
484# Takes an optional flag to indicate whether to include timestamps;
485#  'm' includes ctime, all others (suggest 'c') do not.
486# Returns an arrayref to a list of hashrefs
487sub getMasterList {
488  my $dbh = shift;
489  my $stampme = shift || 'm';   # optional but should be set by caller for clarity
490
491  my $mlist = $dbh->selectall_arrayref("SELECT cidr AS master".($stampme eq 'm' ? ',mtime' : '').
492        " FROM masterblocks ORDER BY cidr", { Slice => {} });
493  return $mlist;
494} # end getMasterList()
495
496
497## IPDB::getTypeList()
498# Get an alloctype/description pair list suitable for dropdowns
499# Takes a flag to determine which general groups of types are returned
500# Returns an reference to an array of hashrefs
501sub getTypeList {
502  my $dbh = shift;
503  my $tgroup = shift || 'a';    # technically optional, like this, but should
504                                # really be specified in the call for clarity
505  my $tlist;
506  if ($tgroup eq 'p') {
507    # grouping 'p' - primary allocation types.  These include static IP pools (_d and _p),
508    # dynamic-allocation ranges (_e), containers (_c), and the "miscellaneous" cn, in, and en types.
509    $tlist = $dbh->selectall_arrayref("SELECT type,listname FROM alloctypes WHERE listorder < 500 ".
510        "AND type NOT LIKE '_i' AND type NOT LIKE '_r' ORDER BY listorder", { Slice => {} });
511  } elsif ($tgroup eq 'c') {
512    # grouping 'c' - contained types.  These include all static IPs and all _r types.
513    $tlist = $dbh->selectall_arrayref("SELECT type,listname FROM alloctypes WHERE listorder <= 500 ".
514        " AND (type LIKE '_i' OR type LIKE '_r') ORDER BY listorder", { Slice => {} });
515  } else {
516    # grouping 'a' - all standard allocation types.  This includes everything
517    # but mm (present only as a formality).  Make this the default.
518    $tlist = $dbh->selectall_arrayref("SELECT type,listname FROM alloctypes WHERE listorder <= 500 ".
519        " ORDER BY listorder", { Slice => {} });
520  }
521  return $tlist;
522}
523
524
525## IPDB::getPoolSelect()
526# Get a list of pools matching the passed city and type that have 1 or more free IPs
527# Returns an arrayref to a list of hashrefs
528sub getPoolSelect {
529  my $dbh = shift;
530  my $iptype = shift;
531  my $pcity = shift;
532
533  my ($ptype) = ($iptype =~ /^(.)i$/);
534  return if !$ptype;
535  $ptype .= '_';
536
537  my $plist = $dbh->selectall_arrayref(
538        "SELECT (SELECT city FROM allocations WHERE cidr=poolips.pool) AS poolcit, ".
539        "poolips.pool AS poolblock, COUNT(*) AS poolfree FROM poolips,allocations ".
540        "WHERE poolips.available='y' AND poolips.pool=allocations.cidr ".
541        "AND allocations.city = ? AND poolips.type LIKE ? ".
542        "GROUP BY pool", { Slice => {} }, ($pcity, $ptype) );
543  return $plist;
544} # end getPoolSelect()
545
546
547## IPDB::findAllocateFrom()
548# Find free block to add a new allocation from.  (CIDR block version of pool select above, more or less)
549# Takes
550#  - mask length
551#  - allocation type
552#  - POP city "parent"
553#  - optional master-block restriction
554#  - optional flag to allow automatic pick-from-private-network-ranges
555# Returns a string with the first CIDR block matching the criteria, if any
556sub findAllocateFrom {
557  my $dbh = shift;
558  my $maskbits = shift;
559  my $type = shift;
560  my $city = shift;
561  my $pop = shift;
562  my %optargs = @_;
563
564  my $failmsg = "No suitable free block found\n";
565
566## Set up the SQL to find out what freeblock we can (probably) use for an allocation.
567## Very large systems will require development of a reserve system (possibly an extension
568## of the reserve-for-expansion concept in https://secure.deepnet.cx/trac/ipdb/ticket/24?)
569## Also populate a value list for the DBI call.
570
571  my @vallist = ($maskbits, ($type eq 'rm' ? 'n' : ($type =~ /^(.)r$/ ? "$1" : 'y')) );
572  my $sql = "SELECT cidr FROM freeblocks WHERE maskbits <= ? AND routed = ?";
573
574  # for PPP(oE) and container types, the POP city is the one attached to the pool.
575  # individual allocations get listed with the customer city site.
576  ##fixme:  chain cities to align roughly with a full layer-2 node graph
577  $city = $pop if $type !~ /^.[pc]$/;
578  if ($type ne 'rm' && $city) {
579    $sql .= " AND city = ?";
580    push @vallist, $city;
581  }
582  # Allow specifying an arbitrary full block, instead of a master
583  if ($optargs{gimme}) {
584    $sql .= " AND cidr >>= ?";
585    push @vallist, $optargs{gimme};
586  }
587  # if a specific master was requested, allow the requestor to self->shoot(foot)
588  if ($optargs{master} && $optargs{master} ne '-') {
589    $sql .= " AND cidr <<= ?" if $optargs{master} ne '-';
590    push @vallist, $optargs{master};
591  } else {
592    # if a specific master was NOT requested, filter out the RFC 1918 private networks
593    if (!$optargs{allowpriv}) {
594      $sql .= " AND NOT (cidr <<= '192.168.0.0/16' OR cidr <<= '10.0.0.0/8' OR cidr <<= '172.16.0.0/12')";
595    }
596  }
597  # Sorting and limiting, since we don't (currently) care to provide a selection of
598  # blocks to carve up.  This preserves something resembling optimal usage of the IP
599  # space by forcing contiguous allocations and free blocks as much as possible.
600  $sql .= " ORDER BY maskbits DESC,cidr LIMIT 1";
601
602  my ($fbfound) = $dbh->selectrow_array($sql, undef, @vallist);
603  return $fbfound;
604} # end findAllocateFrom()
605
606
607## IPDB::ipParent()
608# Get an IP's parent pool's details
609# Takes a database handle and IP
610# Returns a hashref to the parent pool block, if any
611sub ipParent {
612  my $dbh = shift;
613  my $block = shift;
614
615  my $pinfo = $dbh->selectrow_hashref("SELECT cidr,custid,type,city,description FROM allocations".
616        " WHERE cidr >>= ?", undef, ($block) );
617  return $pinfo;
618} # end ipParent()
619
620
621## IPDB::subParent()
622# Get a block's parent's details
623# Takes a database handle and CIDR block
624# Returns a hashref to the parent container block, if any
625sub subParent {
626  my $dbh = shift;
627  my $block = shift;
628
629  my $pinfo = $dbh->selectrow_hashref("SELECT cidr,custid,type,city,description FROM allocations".
630        " WHERE cidr >>= ?", undef, ($block) );
631  return $pinfo;
632} # end subParent()
633
634
635## IPDB::blockParent()
636# Get a block's parent's details
637# Takes a database handle and CIDR block
638# Returns a hashref to the parent container block, if any
639sub blockParent {
640  my $dbh = shift;
641  my $block = shift;
642
643  my $pinfo = $dbh->selectrow_hashref("SELECT cidr,city FROM routed".
644        " WHERE cidr >>= ?", undef, ($block) );
645  return $pinfo;
646} # end blockParent()
647
648
649## IPDB::getRoutedCity()
650# Get the city for a routed block.
651sub getRoutedCity {
652  my $dbh = shift;
653  my $block = shift;
654
655  my ($rcity) = $dbh->selectrow_array("SELECT city FROM routed WHERE cidr = ?", undef, ($block) );
656  return $rcity;
657} # end getRoutedCity()
658
659
660## IPDB::allocateBlock()
661# Does all of the magic of actually allocating a netblock
662# Requires database handle, block to allocate, custid, type, city,
663#       description, notes, circuit ID, block to allocate from, private data
664# Returns a success code and optional error message.
665sub allocateBlock {
666  my ($dbh,undef,undef,$custid,$type,$city,$desc,$notes,$circid,$privdata,$nodeid) = @_;
667  $privdata = '' if !defined($privdata);
668
669  my $cidr = new NetAddr::IP $_[1];
670  my $alloc_from = new NetAddr::IP $_[2];
671  my $sth;
672
673  $desc = '' if !$desc;
674  $notes = '' if !$notes;
675  $circid = '' if !$circid;
676  $privdata = '' if !$privdata;
677
678  # Snag the "type" of the freeblock (alloc_from) "just in case"
679  $sth = $dbh->prepare("select routed from freeblocks where cidr='$alloc_from'");
680  $sth->execute;
681  my ($alloc_from_type) = $sth->fetchrow_array;
682
683  # To contain the error message, if any.
684  my $msg = "Unknown error allocating $cidr as '$type'";
685
686  # Enable transactions and error handling
687  local $dbh->{AutoCommit} = 0; # These need to be local so we don't
688  local $dbh->{RaiseError} = 1; # step on our toes by accident.
689
690  if ($type =~ /^.i$/) {
691    $msg = "Unable to assign static IP $cidr to $custid";
692    eval {
693      # We have to do this in two parts because otherwise we lose
694      # the ability to return the IP assigned.  Should that change,
695      # the commented SQL statement below may become usable.
696# update poolips set custid='$custid',city='$city',available='n',
697#       description='$desc',notes='$notes',circuitid='$circid'
698#       where ip=(select ip from poolips where pool='$alloc_from'
699#       and available='y' order by ip limit 1);
700
701      if ($cidr) {
702        my ($isavail) = $dbh->selectrow_array("SELECT available FROM poolips WHERE ip=?", undef, ($cidr) );
703        if ($isavail eq 'n') {
704          die "IP already allocated.  Deallocate and reallocate, or update the entry\n";
705        }
706        if (!$isavail) {
707          die "IP is not in an IP pool.\n";
708        }
709      } else {
710        ($cidr) = $dbh->selectrow_array("SELECT ip FROM poolips WHERE pool=? AND available='y' ORDER BY ip",
711                undef, ($alloc_from) );
712      }
713      $dbh->do("UPDATE poolips SET custid=?,city=?,available='n',description=?,notes=?,circuitid=?,privdata=? ".
714        "WHERE ip=?", undef, ($custid, $city, $desc, $notes, $circid, $privdata, $cidr) );
715
716# node hack
717      if ($nodeid && $nodeid ne '') {
718        $sth = $dbh->prepare("INSERT INTO noderef (block,node_id) VALUES (?,?)");
719        $sth->execute("$cidr",$nodeid);
720      }
721# end node hack
722
723      $dbh->commit;
724    };
725    if ($@) {
726      $msg .= ": $@";
727      eval { $dbh->rollback; };
728      return ('FAIL',$msg);
729    } else {
730      return ('OK',"$cidr");
731    }
732
733  } else { # end IP-from-pool allocation
734
735    my $errcode = 'OK';
736    if ($cidr == $alloc_from) {
737      # Easiest case- insert in one table, delete in the other, and go home.  More or less.
738      # insert into allocations values (cidr,custid,type,city,desc) and
739      # delete from freeblocks where cidr='cidr'
740      # For data safety on non-transaction DBs, we delete first.
741
742      eval {
743        $msg = "Unable to allocate $cidr as '$disp_alloctypes{$type}'";
744        if ($type eq 'rm') {
745          $sth = $dbh->prepare("update freeblocks set routed='y',city='$city'".
746            " where cidr='$cidr'");
747          $sth->execute;
748          $sth = $dbh->prepare("insert into routed (cidr,maskbits,city)".
749                " values ('$cidr',".$cidr->masklen.",'$city')");
750          $sth->execute;
751        } else {
752          # common stuff for end-use, dialup, dynDSL, pools, etc, etc.
753
754          # special case - block is a container/"reserve" block
755          if ($type =~ /^(.)c$/) {
756            $sth = $dbh->prepare("update freeblocks set routed='$1' where cidr='$cidr'");
757            $sth->execute;
758          } else {
759            # "normal" case
760            $sth = $dbh->prepare("delete from freeblocks where cidr='$cidr'");
761            $sth->execute;
762          }
763          $sth = $dbh->prepare("insert into allocations".
764                " (cidr,custid,type,city,description,notes,maskbits,circuitid,privdata)".
765                " values (?,?,?,?,?,?,?,?,?)");
766          $sth->execute("$cidr", $custid, $type, $city, $desc, $notes, $cidr->masklen, $circid, $privdata);
767
768          # And initialize the pool, if necessary
769          # PPPoE pools (currently dialup, DSL, and WiFi) get all IPs made available
770          # "DHCP" or "real-subnet" pools have the net, gw, and bcast IPs removed.
771          if ($type =~ /^.p$/) {
772            $msg = "Could not initialize IPs in new $disp_alloctypes{$type} $cidr";
773            my ($code,$rmsg) = initPool($dbh,$cidr,$type,$city,"all");
774            die $rmsg if $code eq 'FAIL';
775            $msg = $rmsg;
776            $errcode = $code;
777          } elsif ($type =~ /^.d$/) {
778            $msg = "Could not initialize IPs in new $disp_alloctypes{$type} $cidr";
779            my ($code,$rmsg) = initPool($dbh,$cidr,$type,$city,"normal");
780            die $rmsg if $code eq 'FAIL';
781            $msg = $rmsg;
782            $errcode = $code;
783          }
784
785        } # routing vs non-routing netblock
786
787# node hack
788      if ($nodeid && $nodeid ne '') {
789        $sth = $dbh->prepare("INSERT INTO noderef (block,node_id) VALUES (?,?)");
790        $sth->execute("$cidr",$nodeid);
791      }
792# end node hack
793        $dbh->commit;
794      }; # end of eval
795      if ($@) {
796        $msg .= ": ".$@;
797        eval { $dbh->rollback; };
798        return ('FAIL',$msg);
799      } else {
800        return ($errcode,($type =~ /^.[pd]$/ ? $msg : "OK"));
801      }
802
803    } else { # cidr != alloc_from
804
805      # Hard case.  Allocation is smaller than free block.
806      my $wantmaskbits = $cidr->masklen;
807      my $maskbits = $alloc_from->masklen;
808
809      my @newfreeblocks;        # Holds free blocks generated from splitting the source freeblock.
810
811      # This determines which blocks will be left "free" after allocation.  We take the
812      # block we're allocating from, and split it in half.  We see which half the wanted
813      # block is in, and repeat until the wanted block is equal to one of the halves.
814      my $i=0;
815      my $tmp_from = $alloc_from;       # So we don't munge $alloc_from
816      while ($maskbits++ < $wantmaskbits) {
817        my @subblocks = $tmp_from->split($maskbits);
818        $newfreeblocks[$i++] = (($cidr->within($subblocks[0])) ? $subblocks[1] : $subblocks[0]);
819        $tmp_from = ( ($cidr->within($subblocks[0])) ? $subblocks[0] : $subblocks[1] );
820      } # while
821
822      # Begin SQL transaction block
823      eval {
824        $msg = "Unable to allocate $cidr as '$disp_alloctypes{$type}'";
825
826        # Delete old freeblocks entry
827        $sth = $dbh->prepare("delete from freeblocks where cidr='$alloc_from'");
828        $sth->execute();
829
830        # now we have to do some magic for routing blocks
831        if ($type eq 'rm') {
832
833          # Insert the new freeblocks entries
834          # Note that non-routed blocks are assigned to <NULL>
835          # and use the default value for the routed column ('n')
836          $sth = $dbh->prepare("insert into freeblocks (cidr,maskbits,city)".
837                " values (?, ?, '<NULL>')");
838          foreach my $block (@newfreeblocks) {
839            $sth->execute("$block", $block->masklen);
840          }
841
842          # Insert the entry in the routed table
843          $sth = $dbh->prepare("insert into routed (cidr,maskbits,city)".
844                " values ('$cidr',".$cidr->masklen.",'$city')");
845          $sth->execute;
846          # Insert the (almost) same entry in the freeblocks table
847          $sth = $dbh->prepare("insert into freeblocks (cidr,maskbits,city,routed)".
848                " values ('$cidr',".$cidr->masklen.",'$city','y')");
849          $sth->execute;
850
851        } else { # done with alloctype == rm
852
853          # Insert the new freeblocks entries
854          # Along with some more HairyPerl(TM):
855          #   if $alloc_type_from is p
856          #   OR
857          #   $type matches /^(.)r$/
858          # inserted value for routed column should match.
859          # This solves the case of inserting an arbitrary block into a
860          # "Reserve-for-routed-DSL" block.  Which you really shouldn't
861          # do in the first place, but anyway...
862          $sth = $dbh->prepare("insert into freeblocks (cidr,maskbits,city,routed)".
863                " values (?, ?, (select city from routed where cidr >>= '$cidr'),'".
864                ( ( ($alloc_from_type =~ /^(p)$/) || ($type =~ /^(.)r$/) ) ? "$1" : 'y')."')");
865          foreach my $block (@newfreeblocks) {
866            $sth->execute("$block", $block->masklen);
867          }
868          # Special-case for reserve/"container" blocks - generate
869          # the "extra" freeblocks entry for the container
870          if ($type =~ /^(.)c$/) {
871            $sth = $dbh->prepare("insert into freeblocks (cidr,maskbits,city,routed)".
872                " values ('$cidr',".$cidr->masklen.",'$city','$1')");
873            $sth->execute;
874          }
875          # Insert the allocations entry
876          $sth = $dbh->prepare("insert into allocations (cidr,custid,type,city,".
877                "description,notes,maskbits,circuitid,privdata)".
878                " values (?,?,?,?,?,?,?,?,?)");
879          $sth->execute("$cidr", $custid, $type, $city, $desc, $notes, $cidr->masklen, $circid, $privdata);
880
881          # And initialize the pool, if necessary
882          # PPPoE pools (currently dialup, DSL, and WiFi) get all IPs made available
883          # "DHCP" or "real-subnet" pools have the net, gw, and bcast IPs removed.
884          if ($type =~ /^.p$/) {
885            $msg = "Could not initialize IPs in new $disp_alloctypes{$type} $cidr";
886            my ($code,$rmsg) = initPool($dbh,$cidr,$type,$city,"all");
887            die $rmsg if $code eq 'FAIL';
888          } elsif ($type =~ /^.d$/) {
889            $msg = "Could not initialize IPs in new $disp_alloctypes{$type} $cidr";
890            my ($code,$rmsg) = initPool($dbh,$cidr,$type,$city,"normal");
891            die $rmsg if $code eq 'FAIL';
892          }
893
894        } # done with netblock alloctype != rm
895
896# node hack
897      if ($nodeid && $nodeid ne '') {
898        $sth = $dbh->prepare("INSERT INTO noderef (block,node_id) VALUES (?,?)");
899        $sth->execute("$cidr",$nodeid);
900      }
901# end node hack
902        $dbh->commit;
903      }; # end eval
904      if ($@) {
905        $msg .= ": ".$@;
906        eval { $dbh->rollback; };
907        return ('FAIL',$msg);
908      } else {
909        return ($errcode,($type =~ /^.[pd]$/ ? $msg : "OK"));
910      }
911
912    } # end fullcidr != alloc_from
913
914  } # end static-IP vs netblock allocation
915
916} # end allocateBlock()
917
918
919## IPDB::initPool()
920# Initializes a pool
921# Requires a database handle, the pool CIDR, type, city, and a parameter
922# indicating whether the pool should allow allocation of literally every
923# IP, or if it should reserve network/gateway/broadcast IPs
924# Note that this is NOT done in a transaction, that's why it's a private
925# function and should ONLY EVER get called from allocateBlock()
926sub initPool {
927  my ($dbh,undef,$type,$city,$class) = @_;
928  my $pool = new NetAddr::IP $_[1];
929
930  return ('WARN','Refusing to melt server with IPv6 IP pool') if $pool->bits == 128;
931
932##fixme Need to just replace 2nd char of type with i rather than capturing 1st char of type
933  $type =~ s/[pd]$/i/;
934  my $sth;
935  my $msg;
936
937  # Trap errors so we can pass them back to the caller.  Even if the
938  # caller is only ever supposed to be local, and therefore already
939  # trapping errors.  >:(
940  local $dbh->{AutoCommit} = 0; # These need to be local so we don't
941  local $dbh->{RaiseError} = 1; # step on our toes by accident.
942
943  eval {
944    # have to insert all pool IPs into poolips table as "unallocated".
945    $sth = $dbh->prepare("insert into poolips (pool,ip,custid,city,type)".
946        " values ('$pool', ?, '$defcustid', ?, '$type')");
947    my @poolip_list = $pool->hostenum;
948    if ($class eq 'all') { # (DSL-ish block - *all* IPs available
949      if ($pool->addr !~ /\.0$/) {      # .0 causes weirdness.
950        $sth->execute($pool->addr, $city);
951      }
952      for (my $i=0; $i<=$#poolip_list; $i++) {
953        $sth->execute($poolip_list[$i]->addr, $city);
954      }
955      $pool--;
956      if ($pool->addr !~ /\.255$/) {    # .255 can cause weirdness.
957        $sth->execute($pool->addr, $city);
958      }
959    } else { # (real netblock)
960      for (my $i=1; $i<=$#poolip_list; $i++) {
961        $sth->execute($poolip_list[$i]->addr, $city);
962      }
963    }
964  };
965  if ($@) {
966    $msg = $@." '".$sth->errstr."'";
967    eval { $dbh->rollback; };
968    return ('FAIL',$msg);
969  } else {
970    return ('OK',"OK");
971  }
972} # end initPool()
973
974
975## IPDB::updateBlock()
976# Update an allocation
977# Takes all allocation fields in a hash
978sub updateBlock {
979  my $dbh = shift;
980  my %args = @_;
981
982  return ('FAIL', 'Missing block to update') if !$args{block};
983
984  # do it all in a transaction
985  local $dbh->{AutoCommit} = 0;
986  local $dbh->{RaiseError} = 1;
987
988  my @fieldlist;
989  my @vallist;
990  foreach ('custid', 'city', 'description', 'notes', 'circuitid', 'privdata') {
991    if ($args{$_}) {
992      push @fieldlist, $_;
993      push @vallist, $args{$_};
994    }
995  }
996
997  my $updtable = 'allocations';
998  my $keyfield = 'cidr';
999  if ($args{type} =~ /^(.)i$/) {
1000    $updtable = 'poolips';
1001    $keyfield = 'ip';
1002  } else {
1003## fixme:  there's got to be a better way...
1004    if ($args{swip}) {
1005      if ($args{swip} eq 'on' || $args{swip} eq '1' || $args{swip} eq 'y') {
1006        $args{swip} = 'y';
1007      } else {
1008        $args{swip} = 'n';
1009      }
1010    }
1011    foreach ('type', 'swip') {
1012      if ($args{$_}) {
1013        push @fieldlist, $_;
1014        push @vallist, $args{$_};
1015      }
1016    }
1017  }
1018
1019  return ('FAIL', 'No fields to update') if !@fieldlist;
1020
1021  push @vallist, $args{block};
1022  my $sql = "UPDATE $updtable SET ";
1023  $sql .= join " = ?, ", @fieldlist;
1024  $sql .= " = ? WHERE $keyfield = ?";
1025
1026  eval {
1027    # do the update
1028    $dbh->do($sql, undef, @vallist);
1029
1030    if ($args{node}) {
1031      # done with delete/insert so we don't have to worry about funkyness updating a node ref that isn't there
1032      $dbh->do("DELETE FROM noderef WHERE block = ?", undef, ($args{block}) );
1033      $dbh->do("INSERT INTO noderef (block,node_id) VALUES (?,?)", undef, ($args{block}, $args{node}) );
1034    }
1035
1036    $dbh->commit;
1037  };
1038  if ($@) {
1039    my $msg = $@;
1040    $dbh->rollback;
1041    return ('FAIL', $msg);
1042  }
1043  return 0;
1044} # end updateBlock()
1045
1046
1047## IPDB::deleteBlock()
1048# Removes an allocation from the database, including deleting IPs
1049# from poolips and recombining entries in freeblocks if possible
1050# Also handles "deleting" a static IP allocation, and removal of a master
1051# Requires a database handle, the block to delete, and the type of block
1052sub deleteBlock {
1053  my ($dbh,undef,$type) = @_;
1054  my $cidr = new NetAddr::IP $_[1];
1055
1056  my $sth;
1057
1058  # Magic variables used for odd allocation cases.
1059  my $container;
1060  my $con_type;
1061
1062  # To contain the error message, if any.
1063  my $msg = "Unknown error deallocating $type $cidr";
1064  # Enable transactions and exception-on-errors... but only for this sub
1065  local $dbh->{AutoCommit} = 0;
1066  local $dbh->{RaiseError} = 1;
1067
1068  # First case.  The "block" is a static IP
1069  # Note that we still need some additional code in the odd case
1070  # of a netblock-aligned contiguous group of static IPs
1071  if ($type =~ /^.i$/) {
1072
1073    eval {
1074      $msg = "Unable to deallocate $disp_alloctypes{$type} $cidr";
1075      $sth = $dbh->prepare("update poolips set custid=?,available='y',".
1076        "city=(select city from allocations where cidr >>= ?".
1077        " order by masklen(cidr) desc limit 1),".
1078        "description='',notes='',circuitid='' where ip=?");
1079      $sth->execute($defcustid, "$cidr", "$cidr");
1080      $dbh->commit;
1081    };
1082    if ($@) {
1083      eval { $dbh->rollback; };
1084      return ('FAIL',$msg);
1085    } else {
1086      return ('OK',"OK");
1087    }
1088
1089  } elsif ($type eq 'mm') { # end alloctype =~ /.i/
1090
1091    $msg = "Unable to delete master block $cidr";
1092    eval {
1093      $sth = $dbh->prepare("delete from masterblocks where cidr='$cidr'");
1094      $sth->execute;
1095      $sth = $dbh->prepare("delete from freeblocks where cidr <<= '$cidr'");
1096      $sth->execute;
1097      $dbh->commit;
1098    };
1099    if ($@) {
1100      eval { $dbh->rollback; };
1101      return ('FAIL', $msg);
1102    } else {
1103      return ('OK',"OK");
1104    }
1105
1106  } else { # end alloctype master block case
1107
1108    ## This is a big block; but it HAS to be done in a chunk.  Any removal
1109    ## of a netblock allocation may result in a larger chunk of free
1110    ## contiguous IP space - which may in turn be combined into a single
1111    ## netblock rather than a number of smaller netblocks.
1112
1113    eval {
1114
1115      if ($type eq 'rm') {
1116        $msg = "Unable to remove routing allocation $cidr";
1117        $sth = $dbh->prepare("delete from routed where cidr='$cidr'");
1118        $sth->execute;
1119        # Make sure block getting deleted is properly accounted for.
1120        $sth = $dbh->prepare("update freeblocks set routed='n',city='<NULL>'".
1121                " where cidr='$cidr'");
1122        $sth->execute;
1123        # Set up query to start compacting free blocks.
1124        $sth = $dbh->prepare("select cidr from freeblocks where ".
1125                "maskbits<=".$cidr->masklen." and routed='n' order by maskbits desc");
1126
1127      } else { # end alloctype routing case
1128
1129        # Magic.  We need to get information about the containing block (if any)
1130        # so as to make sure that the freeblocks we insert get the correct "type".
1131        $sth = $dbh->prepare("select cidr,type from allocations where cidr >> '$cidr'");
1132        $sth->execute;
1133        ($container, $con_type) = $sth->fetchrow_array;
1134
1135        # Delete all allocations within the block being deleted.  This is
1136        # deliberate and correct, and removes the need to special-case
1137        # removal of "container" blocks.
1138        $sth = $dbh->prepare("delete from allocations where cidr <<='$cidr'");
1139        $sth->execute;
1140
1141        # Special case - delete pool IPs
1142        if ($type =~ /^.[pd]$/) {
1143          # We have to delete the IPs from the pool listing.
1144          $sth = $dbh->prepare("delete from poolips where pool='$cidr'");
1145          $sth->execute;
1146        }
1147
1148        # Set up query for compacting free blocks.
1149        if ($con_type && $con_type eq 'pc') {
1150          # Clean up after "bad" allocations (blocks that are not formally
1151          # contained which have nevertheless been allocated from a container block)
1152          # We want to make certain that the freeblocks are properly "labelled"
1153          $sth = $dbh->prepare("select cidr from freeblocks where cidr <<= '$container' order by maskbits desc");
1154        } else {
1155          # Standard deallocation.
1156          $sth = $dbh->prepare("select cidr from freeblocks where cidr <<= ".
1157                "(select cidr from routed where cidr >>= '$cidr') ".
1158                " and maskbits<=".$cidr->masklen.
1159                " and routed='".(($type =~ /^(.)r$/) ? "$1" : 'y').
1160                "' order by maskbits desc");
1161        }
1162
1163      } # end alloctype general case
1164
1165      ## Deallocate legacy blocks stashed in the middle of a static IP pool
1166      ## This may be expandable to an even more general case of contained netblock, or other pool types.
1167
1168      # Find out if the block we're deallocating is within a DSL pool
1169      my $sth2 = $dbh->prepare("SELECT cidr,city,type FROM allocations WHERE type LIKE '_p' AND cidr >>= ?");
1170      $sth2->execute("$cidr");
1171      my ($pool,$poolcity,$pooltype) = $sth2->fetchrow_array;
1172
1173      if ($pool || $sth2->rows) {
1174        # We've already deleted the block, now we have to stuff its IPs into the pool.
1175        $pooltype =~ s/p$/i/;   # change type to static IP
1176        $sth2 = $dbh->prepare("INSERT INTO poolips (pool,ip,city,type,custid) values ".
1177                "('$pool',?,'$poolcity','$pooltype','$defcustid')");
1178##fixme:  need to not insert net, gateway, and bcast on "real netblock" pools (DHCPish)
1179        # don't insert .0
1180        $sth2->execute($cidr->addr) unless $cidr->addr =~ m|\.0$|;
1181        foreach my $ip ($cidr->hostenum) {
1182          $sth2->execute("$ip");
1183        }
1184        $cidr--;
1185        # don't insert .255
1186        $sth2->execute($cidr->addr) unless $cidr->addr =~ m|\.255$|;
1187      } else {  # done returning IPs from a block to a static DSL pool
1188
1189        # Now we look for larger-or-equal-sized free blocks in the same master (routed)
1190        # (super)block. If there aren't any, we can't combine blocks anyway.  If there
1191        # are, we check to see if we can combine blocks.
1192        # Execute the statement prepared in the if-else above.
1193
1194        $sth->execute;
1195
1196# NetAddr::IP->compact() attempts to produce the smallest inclusive block
1197# from the caller and the passed terms.
1198# EG:  if you call $cidr->compact($ip1,$ip2,$ip3) when $cidr, $ip1, $ip2,
1199#       and $ip3 are consecutive /27's starting on .0 (.0-.31, .32-.63,
1200#       .64-.95, and .96-.128), you will get an array containing a single
1201#       /25 as element 0 (.0-.127).  Order is not important;  you could have
1202#       $cidr=.32/27, $ip1=.96/27, $ip2=.0/27, and $ip3=.64/27.
1203
1204        my (@together, @combinelist);
1205        my $i=0;
1206        while (my @data = $sth->fetchrow_array) {
1207          my $testIP = new NetAddr::IP $data[0];
1208          @together = $testIP->compact($cidr);
1209          my $num = @together;
1210          if ($num == 1) {
1211            $cidr = $together[0];
1212            $combinelist[$i++] = $testIP;
1213          }
1214        }
1215
1216        # Clear old freeblocks entries - if any.  They should all be within
1217        # the $cidr determined above.
1218        $sth = $dbh->prepare("delete from freeblocks where cidr <<='$cidr'");
1219        $sth->execute;
1220
1221        # insert "new" freeblocks entry
1222        if ($type eq 'rm') {
1223          $sth = $dbh->prepare("insert into freeblocks (cidr,maskbits,city)".
1224                " values ('$cidr',".$cidr->masklen.",'<NULL>')");
1225        } else {
1226          # Magic hackery to insert "correct" data for deallocation of
1227          # non-contained blocks allocated from within a container.
1228          $type = 'pr' if $con_type && $con_type eq 'pc';
1229
1230          $sth = $dbh->prepare("insert into freeblocks (cidr,maskbits,city,routed)".
1231                " values ('$cidr',".$cidr->masklen.
1232                ",(select city from routed where cidr >>= '$cidr'),'".
1233                (($type =~ /^(.)r$/) ? "$1" : 'y')."')");
1234        }
1235        $sth->execute;
1236
1237      } # done returning IPs to the appropriate place
1238
1239      # If we got here, we've succeeded.  Whew!
1240      $dbh->commit;
1241    }; # end eval
1242    if ($@) {
1243      $msg = $@;
1244      eval { $dbh->rollback; };
1245      return ('FAIL', $msg);
1246    } else {
1247      return ('OK',"OK");
1248    }
1249
1250  } # end alloctype != netblock
1251
1252} # end deleteBlock()
1253
1254
1255## IPDB::getBlockData()
1256# Get CIDR or IP, custid, type, city, circuit ID, description, notes, modification time, private/restricted
1257# data, for a CIDR block or pool IP
1258# Also returns SWIP status flag for CIDR blocks
1259# Takes the block/IP to look up
1260# Returns an arrayref to a list of hashrefs
1261sub getBlockData {
1262  my $dbh = shift;
1263  my $block = shift;
1264
1265  my $cidr = new NetAddr::IP $block;
1266
1267  my $keycol = 'cidr';
1268  my $blocktable = 'allocations';
1269  my $poolip = 0;
1270
1271  # Pool IP and IPv6 check all in one!  Still needs to be tightened
1272  # up a little for the as-yet-unhandled case of IPv6 IP pools
1273  if ($cidr->bits == 32 && $cidr->masklen == 32) {
1274    $poolip = 1;
1275    $keycol = 'ip';
1276    $blocktable = 'poolips';
1277  }
1278  my $binfo = $dbh->selectrow_hashref("SELECT $keycol AS block, custid, type, city, circuitid, description,".
1279        " notes, modifystamp AS lastmod, privdata".($poolip ? '' : ', swip')." FROM $blocktable".
1280        " WHERE $keycol = ?", undef, ($block) );
1281  return $binfo;
1282} # end getBlockData()
1283
1284
1285## IPDB::getNodeList()
1286# Gets a list of node ID+name pairs as an arrayref to a list of hashrefs
1287sub getNodeList {
1288  my $dbh = shift;
1289 
1290  my $ret = $dbh->selectall_arrayref("SELECT node_id, node_name FROM nodes ORDER BY node_type,node_id",
1291        { Slice => {} });
1292  return $ret;
1293} # end getNodeList()
1294
1295
1296## IPDB::getNodeName()
1297# Get node name from the ID
1298sub getNodeName {
1299  my $dbh = shift;
1300  my $nid = shift;
1301
1302  my ($nname) = $dbh->selectrow_array("SELECT node_name FROM nodes WHERE node_id = ?", undef, ($nid) );
1303  return $nname;
1304} # end getNodeName()
1305
1306
1307## IPDB::getNodeInfo()
1308# Get node name and ID associated with a block
1309sub getNodeInfo {
1310  my $dbh = shift;
1311  my $block = shift;
1312
1313  my ($nid, $nname) = $dbh->selectrow_array("SELECT nodes.node_id,node_name FROM nodes INNER JOIN noderef".
1314        " ON nodes.node_id=noderef.node_id WHERE noderef.block = ?", undef, ($block) );
1315  return ($nid, $nname);
1316} # end getNodeInfo()
1317
1318
1319## IPDB::mailNotify()
1320# Sends notification mail to recipients regarding an IPDB operation
1321sub mailNotify {
1322  my $dbh = shift;
1323  my ($action,$subj,$message) = @_;
1324
1325  return if $smtphost eq 'smtp.example.com';   # do nothing if still using default SMTP host.
1326
1327##fixme: need to redesign the breakdown/processing for $action for proper handling of all cases
1328
1329# split action into parts for fiddlement.  nb: there are almost certainly better ways to do this.
1330  my @actionbits = split //, $action;
1331
1332  # want to notify anyone who has specifically requested notify on *this* type ($action as passed),
1333  # on "all static IP types" or "all pool types" (and other last-char-in-type groupings), on eg "all DSL types",
1334  # and "all events with this action"
1335  my @actionsets = ($action);
1336##fixme: ick, eww.  really gotta find a better way to handle this...
1337  push @actionsets, ($actionbits[0].'.'.$actionbits[2],
1338        $actionbits[0].$actionbits[1].'.', $actionbits[0].'a') if $action =~ /^.{3}$/;
1339
1340  my $mailer = Net::SMTP->new($smtphost, Hello => "ipdb.$domain");
1341
1342  # get recip list from db
1343  my $sth = $dbh->prepare("SELECT reciplist FROM notify WHERE action=?");
1344
1345  my %reciplist;
1346  foreach (@actionsets) {
1347    $sth->execute($_);
1348##fixme - need to handle db errors
1349    my ($recipsub) = $sth->fetchrow_array;
1350    next if !$recipsub;
1351    foreach (split(/,/, $recipsub)) {
1352      $reciplist{$_}++;
1353    }
1354  }
1355
1356  return if !%reciplist;
1357
1358  foreach my $recip (keys %reciplist) {
1359    $mailer->mail("ipdb\@$domain");
1360    $mailer->to($recip);
1361    $mailer->data("From: \"$org_name IP Database\" <ipdb\@$domain>\n",
1362        "To: $recip\n",
1363        "Date: ".strftime("%a, %d %b %Y %H:%M:%S %z",localtime)."\n",
1364        "Subject: {IPDB} $subj\n",
1365        "X-Mailer: IPDB Notify v".sprintf("%.1d",$IPDB::VERSION)."\n",
1366        "Organization: $org_name\n",
1367        "\n$message\n");
1368  }
1369  $mailer->quit;
1370}
1371
1372# Indicates module loaded OK.  Required by Perl.
13731;
Note: See TracBrowser for help on using the repository browser.