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

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

/branches/stable

Hand-backport pieces of the allocate-from-routed-freeblock from /trunk
post-r553. Cherrypick merge not possible due to intermingled changes
relating to the database structure updates.
Includes a handful of harmless references to the new structure.
Will likely cause merge conflicts when the structure update is merged.

  • Property svn:keywords set to Date Rev Author
File size: 46.2 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 21:26:55 +0000 (Wed, 15 May 2013) $
6# SVN revision $Rev: 595 $
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 'n') {
507    # grouping 'n' - all netblock types.  These include routed blocks, containers (_c)
508    # and contained (_r) types, dynamic-allocation ranges (_e), static IP pools (_d and _p),
509    # and the "miscellaneous" cn, in, and en types.
510    $tlist = $dbh->selectall_arrayref("SELECT type,listname FROM alloctypes WHERE listorder <= 500 ".
511        "AND type NOT LIKE '_i' ORDER BY listorder", { Slice => {} });
512  } elsif ($tgroup eq 'p') {
513    # grouping 'p' - primary allocation types.  As with 'n' above but without the _r contained types.
514    $tlist = $dbh->selectall_arrayref("SELECT type,listname FROM alloctypes WHERE listorder <= 500 ".
515        "AND type NOT LIKE '_i' AND type NOT LIKE '_r' ORDER BY listorder", { Slice => {} });
516  } elsif ($tgroup eq 'c') {
517    # grouping 'c' - contained types.  These include all static IPs and all _r types.
518    $tlist = $dbh->selectall_arrayref("SELECT type,listname FROM alloctypes WHERE listorder <= 500 ".
519        " AND (type LIKE '_i' OR type LIKE '_r') ORDER BY listorder", { Slice => {} });
520  } elsif ($tgroup eq 'i') {
521    # grouping 'i' - static IP types.
522    $tlist = $dbh->selectall_arrayref("SELECT type,listname FROM alloctypes WHERE listorder <= 500 ".
523        " AND type LIKE '_i' ORDER BY listorder", { Slice => {} });
524  } else {
525    # grouping 'a' - all standard allocation types.  This includes everything
526    # but mm (present only as a formality).  Make this the default.
527    $tlist = $dbh->selectall_arrayref("SELECT type,listname FROM alloctypes WHERE listorder <= 500 ".
528        " ORDER BY listorder", { Slice => {} });
529  }
530  return $tlist;
531}
532
533
534## IPDB::getPoolSelect()
535# Get a list of pools matching the passed city and type that have 1 or more free IPs
536# Returns an arrayref to a list of hashrefs
537sub getPoolSelect {
538  my $dbh = shift;
539  my $iptype = shift;
540  my $pcity = shift;
541
542  my ($ptype) = ($iptype =~ /^(.)i$/);
543  return if !$ptype;
544  $ptype .= '_';
545
546  my $plist = $dbh->selectall_arrayref(
547        "SELECT (SELECT city FROM allocations WHERE cidr=poolips.pool) AS poolcit, ".
548        "poolips.pool AS poolblock, COUNT(*) AS poolfree FROM poolips,allocations ".
549        "WHERE poolips.available='y' AND poolips.pool=allocations.cidr ".
550        "AND allocations.city = ? AND poolips.type LIKE ? ".
551        "GROUP BY pool", { Slice => {} }, ($pcity, $ptype) );
552  return $plist;
553} # end getPoolSelect()
554
555
556## IPDB::findAllocateFrom()
557# Find free block to add a new allocation from.  (CIDR block version of pool select above, more or less)
558# Takes
559#  - mask length
560#  - allocation type
561#  - POP city "parent"
562#  - optional master-block restriction
563#  - optional flag to allow automatic pick-from-private-network-ranges
564# Returns a string with the first CIDR block matching the criteria, if any
565sub findAllocateFrom {
566  my $dbh = shift;
567  my $maskbits = shift;
568  my $type = shift;
569  my $city = shift;
570  my $pop = shift;
571  my %optargs = @_;
572
573  my $failmsg = "No suitable free block found\n";
574
575## Set up the SQL to find out what freeblock we can (probably) use for an allocation.
576## Very large systems will require development of a reserve system (possibly an extension
577## of the reserve-for-expansion concept in https://secure.deepnet.cx/trac/ipdb/ticket/24?)
578## Also populate a value list for the DBI call.
579
580  my @vallist = ($maskbits, ($type eq 'rm' ? 'n' : ($type =~ /^(.)r$/ ? "$1" : 'y')) );
581  my $sql = "SELECT cidr FROM freeblocks WHERE maskbits <= ? AND routed = ?";
582
583  # for PPP(oE) and container types, the POP city is the one attached to the pool.
584  # individual allocations get listed with the customer city site.
585  ##fixme:  chain cities to align roughly with a full layer-2 node graph
586  $city = $pop if $type !~ /^.[pc]$/;
587  if ($type ne 'rm' && $city) {
588    $sql .= " AND city = ?";
589    push @vallist, $city;
590  }
591  # Allow specifying an arbitrary full block, instead of a master
592  if ($optargs{gimme}) {
593    $sql .= " AND cidr >>= ?";
594    push @vallist, $optargs{gimme};
595  }
596  # if a specific master was requested, allow the requestor to self->shoot(foot)
597  if ($optargs{master} && $optargs{master} ne '-') {
598    $sql .= " AND cidr <<= ?" if $optargs{master} ne '-';
599    push @vallist, $optargs{master};
600  } else {
601    # if a specific master was NOT requested, filter out the RFC 1918 private networks
602    if (!$optargs{allowpriv}) {
603      $sql .= " AND NOT (cidr <<= '192.168.0.0/16' OR cidr <<= '10.0.0.0/8' OR cidr <<= '172.16.0.0/12')";
604    }
605  }
606  # Sorting and limiting, since we don't (currently) care to provide a selection of
607  # blocks to carve up.  This preserves something resembling optimal usage of the IP
608  # space by forcing contiguous allocations and free blocks as much as possible.
609  $sql .= " ORDER BY maskbits DESC,cidr LIMIT 1";
610
611  my ($fbfound) = $dbh->selectrow_array($sql, undef, @vallist);
612  return $fbfound;
613} # end findAllocateFrom()
614
615
616## IPDB::ipParent()
617# Get an IP's parent pool's details
618# Takes a database handle and IP
619# Returns a hashref to the parent pool block, if any
620sub ipParent {
621  my $dbh = shift;
622  my $block = shift;
623
624  my $pinfo = $dbh->selectrow_hashref("SELECT cidr,custid,type,city,description FROM allocations".
625        " WHERE cidr >>= ?", undef, ($block) );
626  return $pinfo;
627} # end ipParent()
628
629
630## IPDB::subParent()
631# Get a block's parent's details
632# Takes a database handle and CIDR block
633# Returns a hashref to the parent container block, if any
634sub subParent {
635  my $dbh = shift;
636  my $block = shift;
637
638  my $pinfo = $dbh->selectrow_hashref("SELECT cidr,custid,type,city,description FROM allocations".
639        " WHERE cidr >>= ?", undef, ($block) );
640  return $pinfo;
641} # end subParent()
642
643
644## IPDB::blockParent()
645# Get a block's parent's details
646# Takes a database handle and CIDR block
647# Returns a hashref to the parent container block, if any
648sub blockParent {
649  my $dbh = shift;
650  my $block = shift;
651
652  my $pinfo = $dbh->selectrow_hashref("SELECT cidr,city FROM routed".
653        " WHERE cidr >>= ?", undef, ($block) );
654  return $pinfo;
655} # end blockParent()
656
657
658## IPDB::getRoutedCity()
659# Get the city for a routed block.
660sub getRoutedCity {
661  my $dbh = shift;
662  my $block = shift;
663
664  my ($rcity) = $dbh->selectrow_array("SELECT city FROM routed WHERE cidr = ?", undef, ($block) );
665  return $rcity;
666} # end getRoutedCity()
667
668
669## IPDB::allocateBlock()
670# Does all of the magic of actually allocating a netblock
671# Requires database handle, block to allocate, custid, type, city,
672#       description, notes, circuit ID, block to allocate from, private data
673# Returns a success code and optional error message.
674sub allocateBlock {
675  my ($dbh,undef,undef,$custid,$type,$city,$desc,$notes,$circid,$privdata,$nodeid) = @_;
676  $privdata = '' if !defined($privdata);
677
678  my $cidr = new NetAddr::IP $_[1];
679  my $alloc_from = new NetAddr::IP $_[2];
680  my $sth;
681
682  $desc = '' if !$desc;
683  $notes = '' if !$notes;
684  $circid = '' if !$circid;
685  $privdata = '' if !$privdata;
686
687  # Snag the "type" of the freeblock (alloc_from) "just in case"
688  $sth = $dbh->prepare("select routed from freeblocks where cidr='$alloc_from'");
689  $sth->execute;
690  my ($alloc_from_type) = $sth->fetchrow_array;
691
692  # To contain the error message, if any.
693  my $msg = "Unknown error allocating $cidr as '$type'";
694
695  # Enable transactions and error handling
696  local $dbh->{AutoCommit} = 0; # These need to be local so we don't
697  local $dbh->{RaiseError} = 1; # step on our toes by accident.
698
699  if ($type =~ /^.i$/) {
700    $msg = "Unable to assign static IP $cidr to $custid";
701    eval {
702      # We have to do this in two parts because otherwise we lose
703      # the ability to return the IP assigned.  Should that change,
704      # the commented SQL statement below may become usable.
705# update poolips set custid='$custid',city='$city',available='n',
706#       description='$desc',notes='$notes',circuitid='$circid'
707#       where ip=(select ip from poolips where pool='$alloc_from'
708#       and available='y' order by ip limit 1);
709
710      if ($cidr) {
711        my ($isavail) = $dbh->selectrow_array("SELECT available FROM poolips WHERE ip=?", undef, ($cidr) );
712        if ($isavail eq 'n') {
713          die "IP already allocated.  Deallocate and reallocate, or update the entry\n";
714        }
715        if (!$isavail) {
716          die "IP is not in an IP pool.\n";
717        }
718      } else {
719        ($cidr) = $dbh->selectrow_array("SELECT ip FROM poolips WHERE pool=? AND available='y' ORDER BY ip",
720                undef, ($alloc_from) );
721      }
722      $dbh->do("UPDATE poolips SET custid=?,city=?,available='n',description=?,notes=?,circuitid=?,privdata=? ".
723        "WHERE ip=?", undef, ($custid, $city, $desc, $notes, $circid, $privdata, $cidr) );
724
725# node hack
726      if ($nodeid && $nodeid ne '') {
727        $sth = $dbh->prepare("INSERT INTO noderef (block,node_id) VALUES (?,?)");
728        $sth->execute("$cidr",$nodeid);
729      }
730# end node hack
731
732      $dbh->commit;
733    };
734    if ($@) {
735      $msg .= ": $@";
736      eval { $dbh->rollback; };
737      return ('FAIL',$msg);
738    } else {
739      return ('OK',"$cidr");
740    }
741
742  } else { # end IP-from-pool allocation
743
744    my $errcode = 'OK';
745    if ($cidr == $alloc_from) {
746      # Easiest case- insert in one table, delete in the other, and go home.  More or less.
747      # insert into allocations values (cidr,custid,type,city,desc) and
748      # delete from freeblocks where cidr='cidr'
749      # For data safety on non-transaction DBs, we delete first.
750
751      eval {
752        $msg = "Unable to allocate $cidr as '$disp_alloctypes{$type}'";
753        if ($type eq 'rm') {
754          $sth = $dbh->prepare("update freeblocks set routed='y',city='$city'".
755            " where cidr='$cidr'");
756          $sth->execute;
757          $sth = $dbh->prepare("insert into routed (cidr,maskbits,city)".
758                " values ('$cidr',".$cidr->masklen.",'$city')");
759          $sth->execute;
760        } else {
761          # common stuff for end-use, dialup, dynDSL, pools, etc, etc.
762
763          # special case - block is a container/"reserve" block
764          if ($type =~ /^(.)c$/) {
765            $sth = $dbh->prepare("update freeblocks set routed='$1' where cidr='$cidr'");
766            $sth->execute;
767          } else {
768            # "normal" case
769            $sth = $dbh->prepare("delete from freeblocks where cidr='$cidr'");
770            $sth->execute;
771          }
772          $sth = $dbh->prepare("insert into allocations".
773                " (cidr,custid,type,city,description,notes,maskbits,circuitid,privdata)".
774                " values (?,?,?,?,?,?,?,?,?)");
775          $sth->execute("$cidr", $custid, $type, $city, $desc, $notes, $cidr->masklen, $circid, $privdata);
776
777          # And initialize the pool, if necessary
778          # PPPoE pools (currently dialup, DSL, and WiFi) get all IPs made available
779          # "DHCP" or "real-subnet" pools have the net, gw, and bcast IPs removed.
780          if ($type =~ /^.p$/) {
781            $msg = "Could not initialize IPs in new $disp_alloctypes{$type} $cidr";
782            my ($code,$rmsg) = initPool($dbh,$cidr,$type,$city,"all");
783            die $rmsg if $code eq 'FAIL';
784            $msg = $rmsg;
785            $errcode = $code;
786          } elsif ($type =~ /^.d$/) {
787            $msg = "Could not initialize IPs in new $disp_alloctypes{$type} $cidr";
788            my ($code,$rmsg) = initPool($dbh,$cidr,$type,$city,"normal");
789            die $rmsg if $code eq 'FAIL';
790            $msg = $rmsg;
791            $errcode = $code;
792          }
793
794        } # routing vs non-routing netblock
795
796# node hack
797      if ($nodeid && $nodeid ne '') {
798        $sth = $dbh->prepare("INSERT INTO noderef (block,node_id) VALUES (?,?)");
799        $sth->execute("$cidr",$nodeid);
800      }
801# end node hack
802        $dbh->commit;
803      }; # end of eval
804      if ($@) {
805        $msg .= ": ".$@;
806        eval { $dbh->rollback; };
807        return ('FAIL',$msg);
808      } else {
809        return ($errcode,($type =~ /^.[pd]$/ ? $msg : "OK"));
810      }
811
812    } else { # cidr != alloc_from
813
814      # Hard case.  Allocation is smaller than free block.
815      my $wantmaskbits = $cidr->masklen;
816      my $maskbits = $alloc_from->masklen;
817
818      my @newfreeblocks;        # Holds free blocks generated from splitting the source freeblock.
819
820      # This determines which blocks will be left "free" after allocation.  We take the
821      # block we're allocating from, and split it in half.  We see which half the wanted
822      # block is in, and repeat until the wanted block is equal to one of the halves.
823      my $i=0;
824      my $tmp_from = $alloc_from;       # So we don't munge $alloc_from
825      while ($maskbits++ < $wantmaskbits) {
826        my @subblocks = $tmp_from->split($maskbits);
827        $newfreeblocks[$i++] = (($cidr->within($subblocks[0])) ? $subblocks[1] : $subblocks[0]);
828        $tmp_from = ( ($cidr->within($subblocks[0])) ? $subblocks[0] : $subblocks[1] );
829      } # while
830
831      # Begin SQL transaction block
832      eval {
833        $msg = "Unable to allocate $cidr as '$disp_alloctypes{$type}'";
834
835        # Delete old freeblocks entry
836        $sth = $dbh->prepare("delete from freeblocks where cidr='$alloc_from'");
837        $sth->execute();
838
839        # now we have to do some magic for routing blocks
840        if ($type eq 'rm') {
841
842          # Insert the new freeblocks entries
843          # Note that non-routed blocks are assigned to <NULL>
844          # and use the default value for the routed column ('n')
845          $sth = $dbh->prepare("insert into freeblocks (cidr,maskbits,city)".
846                " values (?, ?, '<NULL>')");
847          foreach my $block (@newfreeblocks) {
848            $sth->execute("$block", $block->masklen);
849          }
850
851          # Insert the entry in the routed table
852          $sth = $dbh->prepare("insert into routed (cidr,maskbits,city)".
853                " values ('$cidr',".$cidr->masklen.",'$city')");
854          $sth->execute;
855          # Insert the (almost) same entry in the freeblocks table
856          $sth = $dbh->prepare("insert into freeblocks (cidr,maskbits,city,routed)".
857                " values ('$cidr',".$cidr->masklen.",'$city','y')");
858          $sth->execute;
859
860        } else { # done with alloctype == rm
861
862          # Insert the new freeblocks entries
863          # Along with some more HairyPerl(TM):
864          #   if $alloc_type_from is p
865          #   OR
866          #   $type matches /^(.)r$/
867          # inserted value for routed column should match.
868          # This solves the case of inserting an arbitrary block into a
869          # "Reserve-for-routed-DSL" block.  Which you really shouldn't
870          # do in the first place, but anyway...
871          $sth = $dbh->prepare("insert into freeblocks (cidr,maskbits,city,routed)".
872                " values (?, ?, (select city from routed where cidr >>= '$cidr'),'".
873                ( ( ($alloc_from_type =~ /^(p)$/) || ($type =~ /^(.)r$/) ) ? "$1" : 'y')."')");
874          foreach my $block (@newfreeblocks) {
875            $sth->execute("$block", $block->masklen);
876          }
877          # Special-case for reserve/"container" blocks - generate
878          # the "extra" freeblocks entry for the container
879          if ($type =~ /^(.)c$/) {
880            $sth = $dbh->prepare("insert into freeblocks (cidr,maskbits,city,routed)".
881                " values ('$cidr',".$cidr->masklen.",'$city','$1')");
882            $sth->execute;
883          }
884          # Insert the allocations entry
885          $sth = $dbh->prepare("insert into allocations (cidr,custid,type,city,".
886                "description,notes,maskbits,circuitid,privdata)".
887                " values (?,?,?,?,?,?,?,?,?)");
888          $sth->execute("$cidr", $custid, $type, $city, $desc, $notes, $cidr->masklen, $circid, $privdata);
889
890          # And initialize the pool, if necessary
891          # PPPoE pools (currently dialup, DSL, and WiFi) get all IPs made available
892          # "DHCP" or "real-subnet" pools have the net, gw, and bcast IPs removed.
893          if ($type =~ /^.p$/) {
894            $msg = "Could not initialize IPs in new $disp_alloctypes{$type} $cidr";
895            my ($code,$rmsg) = initPool($dbh,$cidr,$type,$city,"all");
896            die $rmsg if $code eq 'FAIL';
897          } elsif ($type =~ /^.d$/) {
898            $msg = "Could not initialize IPs in new $disp_alloctypes{$type} $cidr";
899            my ($code,$rmsg) = initPool($dbh,$cidr,$type,$city,"normal");
900            die $rmsg if $code eq 'FAIL';
901          }
902
903        } # done with netblock alloctype != rm
904
905# node hack
906      if ($nodeid && $nodeid ne '') {
907        $sth = $dbh->prepare("INSERT INTO noderef (block,node_id) VALUES (?,?)");
908        $sth->execute("$cidr",$nodeid);
909      }
910# end node hack
911        $dbh->commit;
912      }; # end eval
913      if ($@) {
914        $msg .= ": ".$@;
915        eval { $dbh->rollback; };
916        return ('FAIL',$msg);
917      } else {
918        return ($errcode,($type =~ /^.[pd]$/ ? $msg : "OK"));
919      }
920
921    } # end fullcidr != alloc_from
922
923  } # end static-IP vs netblock allocation
924
925} # end allocateBlock()
926
927
928## IPDB::initPool()
929# Initializes a pool
930# Requires a database handle, the pool CIDR, type, city, and a parameter
931# indicating whether the pool should allow allocation of literally every
932# IP, or if it should reserve network/gateway/broadcast IPs
933# Note that this is NOT done in a transaction, that's why it's a private
934# function and should ONLY EVER get called from allocateBlock()
935sub initPool {
936  my ($dbh,undef,$type,$city,$class) = @_;
937  my $pool = new NetAddr::IP $_[1];
938
939  return ('WARN','Refusing to melt server with IPv6 IP pool') if $pool->bits == 128;
940
941##fixme Need to just replace 2nd char of type with i rather than capturing 1st char of type
942  $type =~ s/[pd]$/i/;
943  my $sth;
944  my $msg;
945
946  # Trap errors so we can pass them back to the caller.  Even if the
947  # caller is only ever supposed to be local, and therefore already
948  # trapping errors.  >:(
949  local $dbh->{AutoCommit} = 0; # These need to be local so we don't
950  local $dbh->{RaiseError} = 1; # step on our toes by accident.
951
952  eval {
953    # have to insert all pool IPs into poolips table as "unallocated".
954    $sth = $dbh->prepare("insert into poolips (pool,ip,custid,city,type)".
955        " values ('$pool', ?, '$defcustid', ?, '$type')");
956    my @poolip_list = $pool->hostenum;
957    if ($class eq 'all') { # (DSL-ish block - *all* IPs available
958      if ($pool->addr !~ /\.0$/) {      # .0 causes weirdness.
959        $sth->execute($pool->addr, $city);
960      }
961      for (my $i=0; $i<=$#poolip_list; $i++) {
962        $sth->execute($poolip_list[$i]->addr, $city);
963      }
964      $pool--;
965      if ($pool->addr !~ /\.255$/) {    # .255 can cause weirdness.
966        $sth->execute($pool->addr, $city);
967      }
968    } else { # (real netblock)
969      for (my $i=1; $i<=$#poolip_list; $i++) {
970        $sth->execute($poolip_list[$i]->addr, $city);
971      }
972    }
973  };
974  if ($@) {
975    $msg = $@." '".$sth->errstr."'";
976    eval { $dbh->rollback; };
977    return ('FAIL',$msg);
978  } else {
979    return ('OK',"OK");
980  }
981} # end initPool()
982
983
984## IPDB::updateBlock()
985# Update an allocation
986# Takes all allocation fields in a hash
987sub updateBlock {
988  my $dbh = shift;
989  my %args = @_;
990
991  return ('FAIL', 'Missing block to update') if !$args{block};
992
993  # do it all in a transaction
994  local $dbh->{AutoCommit} = 0;
995  local $dbh->{RaiseError} = 1;
996
997  my @fieldlist;
998  my @vallist;
999  foreach ('custid', 'city', 'description', 'notes', 'circuitid', 'privdata') {
1000    if ($args{$_}) {
1001      push @fieldlist, $_;
1002      push @vallist, $args{$_};
1003    }
1004  }
1005
1006  my $updtable = 'allocations';
1007  my $keyfield = 'cidr';
1008  if ($args{type} =~ /^(.)i$/) {
1009    $updtable = 'poolips';
1010    $keyfield = 'ip';
1011  } else {
1012## fixme:  there's got to be a better way...
1013    if ($args{swip}) {
1014      if ($args{swip} eq 'on' || $args{swip} eq '1' || $args{swip} eq 'y') {
1015        $args{swip} = 'y';
1016      } else {
1017        $args{swip} = 'n';
1018      }
1019    }
1020    foreach ('type', 'swip') {
1021      if ($args{$_}) {
1022        push @fieldlist, $_;
1023        push @vallist, $args{$_};
1024      }
1025    }
1026  }
1027
1028  return ('FAIL', 'No fields to update') if !@fieldlist;
1029
1030  push @vallist, $args{block};
1031  my $sql = "UPDATE $updtable SET ";
1032  $sql .= join " = ?, ", @fieldlist;
1033  $sql .= " = ? WHERE $keyfield = ?";
1034
1035  eval {
1036    # do the update
1037    $dbh->do($sql, undef, @vallist);
1038
1039    if ($args{node}) {
1040      # done with delete/insert so we don't have to worry about funkyness updating a node ref that isn't there
1041      $dbh->do("DELETE FROM noderef WHERE block = ?", undef, ($args{block}) );
1042      $dbh->do("INSERT INTO noderef (block,node_id) VALUES (?,?)", undef, ($args{block}, $args{node}) );
1043    }
1044
1045    $dbh->commit;
1046  };
1047  if ($@) {
1048    my $msg = $@;
1049    $dbh->rollback;
1050    return ('FAIL', $msg);
1051  }
1052  return 0;
1053} # end updateBlock()
1054
1055
1056## IPDB::deleteBlock()
1057# Removes an allocation from the database, including deleting IPs
1058# from poolips and recombining entries in freeblocks if possible
1059# Also handles "deleting" a static IP allocation, and removal of a master
1060# Requires a database handle, the block to delete, and the type of block
1061sub deleteBlock {
1062  my ($dbh,undef,$type) = @_;
1063  my $cidr = new NetAddr::IP $_[1];
1064
1065  my $sth;
1066
1067  # Magic variables used for odd allocation cases.
1068  my $container;
1069  my $con_type;
1070
1071  # To contain the error message, if any.
1072  my $msg = "Unknown error deallocating $type $cidr";
1073  # Enable transactions and exception-on-errors... but only for this sub
1074  local $dbh->{AutoCommit} = 0;
1075  local $dbh->{RaiseError} = 1;
1076
1077  # First case.  The "block" is a static IP
1078  # Note that we still need some additional code in the odd case
1079  # of a netblock-aligned contiguous group of static IPs
1080  if ($type =~ /^.i$/) {
1081
1082    eval {
1083      $msg = "Unable to deallocate $disp_alloctypes{$type} $cidr";
1084      $sth = $dbh->prepare("update poolips set custid=?,available='y',".
1085        "city=(select city from allocations where cidr >>= ?".
1086        " order by masklen(cidr) desc limit 1),".
1087        "description='',notes='',circuitid='' where ip=?");
1088      $sth->execute($defcustid, "$cidr", "$cidr");
1089      $dbh->commit;
1090    };
1091    if ($@) {
1092      eval { $dbh->rollback; };
1093      return ('FAIL',$msg);
1094    } else {
1095      return ('OK',"OK");
1096    }
1097
1098  } elsif ($type eq 'mm') { # end alloctype =~ /.i/
1099
1100    $msg = "Unable to delete master block $cidr";
1101    eval {
1102      $sth = $dbh->prepare("delete from masterblocks where cidr='$cidr'");
1103      $sth->execute;
1104      $sth = $dbh->prepare("delete from freeblocks where cidr <<= '$cidr'");
1105      $sth->execute;
1106      $dbh->commit;
1107    };
1108    if ($@) {
1109      eval { $dbh->rollback; };
1110      return ('FAIL', $msg);
1111    } else {
1112      return ('OK',"OK");
1113    }
1114
1115  } else { # end alloctype master block case
1116
1117    ## This is a big block; but it HAS to be done in a chunk.  Any removal
1118    ## of a netblock allocation may result in a larger chunk of free
1119    ## contiguous IP space - which may in turn be combined into a single
1120    ## netblock rather than a number of smaller netblocks.
1121
1122    eval {
1123
1124      if ($type eq 'rm') {
1125        $msg = "Unable to remove routing allocation $cidr";
1126        $sth = $dbh->prepare("delete from routed where cidr='$cidr'");
1127        $sth->execute;
1128        # Make sure block getting deleted is properly accounted for.
1129        $sth = $dbh->prepare("update freeblocks set routed='n',city='<NULL>'".
1130                " where cidr='$cidr'");
1131        $sth->execute;
1132        # Set up query to start compacting free blocks.
1133        $sth = $dbh->prepare("select cidr from freeblocks where ".
1134                "maskbits<=".$cidr->masklen." and routed='n' order by maskbits desc");
1135
1136      } else { # end alloctype routing case
1137
1138        # Magic.  We need to get information about the containing block (if any)
1139        # so as to make sure that the freeblocks we insert get the correct "type".
1140        $sth = $dbh->prepare("select cidr,type from allocations where cidr >> '$cidr'");
1141        $sth->execute;
1142        ($container, $con_type) = $sth->fetchrow_array;
1143
1144        # Delete all allocations within the block being deleted.  This is
1145        # deliberate and correct, and removes the need to special-case
1146        # removal of "container" blocks.
1147        $sth = $dbh->prepare("delete from allocations where cidr <<='$cidr'");
1148        $sth->execute;
1149
1150        # Special case - delete pool IPs
1151        if ($type =~ /^.[pd]$/) {
1152          # We have to delete the IPs from the pool listing.
1153          $sth = $dbh->prepare("delete from poolips where pool='$cidr'");
1154          $sth->execute;
1155        }
1156
1157        # Set up query for compacting free blocks.
1158        if ($con_type && $con_type eq 'pc') {
1159          # Clean up after "bad" allocations (blocks that are not formally
1160          # contained which have nevertheless been allocated from a container block)
1161          # We want to make certain that the freeblocks are properly "labelled"
1162          $sth = $dbh->prepare("select cidr from freeblocks where cidr <<= '$container' order by maskbits desc");
1163        } else {
1164          # Standard deallocation.
1165          $sth = $dbh->prepare("select cidr from freeblocks where cidr <<= ".
1166                "(select cidr from routed where cidr >>= '$cidr') ".
1167                " and maskbits<=".$cidr->masklen.
1168                " and routed='".(($type =~ /^(.)r$/) ? "$1" : 'y').
1169                "' order by maskbits desc");
1170        }
1171
1172      } # end alloctype general case
1173
1174      ## Deallocate legacy blocks stashed in the middle of a static IP pool
1175      ## This may be expandable to an even more general case of contained netblock, or other pool types.
1176
1177      # Find out if the block we're deallocating is within a DSL pool
1178      my $sth2 = $dbh->prepare("SELECT cidr,city,type FROM allocations WHERE type LIKE '_p' AND cidr >>= ?");
1179      $sth2->execute("$cidr");
1180      my ($pool,$poolcity,$pooltype) = $sth2->fetchrow_array;
1181
1182      if ($pool || $sth2->rows) {
1183        # We've already deleted the block, now we have to stuff its IPs into the pool.
1184        $pooltype =~ s/p$/i/;   # change type to static IP
1185        $sth2 = $dbh->prepare("INSERT INTO poolips (pool,ip,city,type,custid) values ".
1186                "('$pool',?,'$poolcity','$pooltype','$defcustid')");
1187##fixme:  need to not insert net, gateway, and bcast on "real netblock" pools (DHCPish)
1188        # don't insert .0
1189        $sth2->execute($cidr->addr) unless $cidr->addr =~ m|\.0$|;
1190        foreach my $ip ($cidr->hostenum) {
1191          $sth2->execute("$ip");
1192        }
1193        $cidr--;
1194        # don't insert .255
1195        $sth2->execute($cidr->addr) unless $cidr->addr =~ m|\.255$|;
1196      } else {  # done returning IPs from a block to a static DSL pool
1197
1198        # Now we look for larger-or-equal-sized free blocks in the same master (routed)
1199        # (super)block. If there aren't any, we can't combine blocks anyway.  If there
1200        # are, we check to see if we can combine blocks.
1201        # Execute the statement prepared in the if-else above.
1202
1203        $sth->execute;
1204
1205# NetAddr::IP->compact() attempts to produce the smallest inclusive block
1206# from the caller and the passed terms.
1207# EG:  if you call $cidr->compact($ip1,$ip2,$ip3) when $cidr, $ip1, $ip2,
1208#       and $ip3 are consecutive /27's starting on .0 (.0-.31, .32-.63,
1209#       .64-.95, and .96-.128), you will get an array containing a single
1210#       /25 as element 0 (.0-.127).  Order is not important;  you could have
1211#       $cidr=.32/27, $ip1=.96/27, $ip2=.0/27, and $ip3=.64/27.
1212
1213        my (@together, @combinelist);
1214        my $i=0;
1215        while (my @data = $sth->fetchrow_array) {
1216          my $testIP = new NetAddr::IP $data[0];
1217          @together = $testIP->compact($cidr);
1218          my $num = @together;
1219          if ($num == 1) {
1220            $cidr = $together[0];
1221            $combinelist[$i++] = $testIP;
1222          }
1223        }
1224
1225        # Clear old freeblocks entries - if any.  They should all be within
1226        # the $cidr determined above.
1227        $sth = $dbh->prepare("delete from freeblocks where cidr <<='$cidr'");
1228        $sth->execute;
1229
1230        # insert "new" freeblocks entry
1231        if ($type eq 'rm') {
1232          $sth = $dbh->prepare("insert into freeblocks (cidr,maskbits,city)".
1233                " values ('$cidr',".$cidr->masklen.",'<NULL>')");
1234        } else {
1235          # Magic hackery to insert "correct" data for deallocation of
1236          # non-contained blocks allocated from within a container.
1237          $type = 'pr' if $con_type && $con_type eq 'pc';
1238
1239          $sth = $dbh->prepare("insert into freeblocks (cidr,maskbits,city,routed)".
1240                " values ('$cidr',".$cidr->masklen.
1241                ",(select city from routed where cidr >>= '$cidr'),'".
1242                (($type =~ /^(.)r$/) ? "$1" : 'y')."')");
1243        }
1244        $sth->execute;
1245
1246      } # done returning IPs to the appropriate place
1247
1248      # If we got here, we've succeeded.  Whew!
1249      $dbh->commit;
1250    }; # end eval
1251    if ($@) {
1252      $msg = $@;
1253      eval { $dbh->rollback; };
1254      return ('FAIL', $msg);
1255    } else {
1256      return ('OK',"OK");
1257    }
1258
1259  } # end alloctype != netblock
1260
1261} # end deleteBlock()
1262
1263
1264## IPDB::getBlockData()
1265# Get CIDR or IP, custid, type, city, circuit ID, description, notes, modification time, private/restricted
1266# data, for a CIDR block or pool IP
1267# Also returns SWIP status flag for CIDR blocks
1268# Takes the block/IP to look up
1269# Returns an arrayref to a list of hashrefs
1270sub getBlockData {
1271  my $dbh = shift;
1272  my $block = shift;
1273
1274  my $cidr = new NetAddr::IP $block;
1275
1276  my $keycol = 'cidr';
1277  my $blocktable = 'allocations';
1278  my $poolip = 0;
1279
1280  # Pool IP and IPv6 check all in one!  Still needs to be tightened
1281  # up a little for the as-yet-unhandled case of IPv6 IP pools
1282  if ($cidr->bits == 32 && $cidr->masklen == 32) {
1283    $poolip = 1;
1284    $keycol = 'ip';
1285    $blocktable = 'poolips';
1286  }
1287  my $binfo = $dbh->selectrow_hashref("SELECT $keycol AS block, custid, type, city, circuitid, description,".
1288        " notes, modifystamp AS lastmod, privdata".($poolip ? '' : ', swip')." FROM $blocktable".
1289        " WHERE $keycol = ?", undef, ($block) );
1290  return $binfo;
1291} # end getBlockData()
1292
1293
1294## IPDB::getNodeList()
1295# Gets a list of node ID+name pairs as an arrayref to a list of hashrefs
1296sub getNodeList {
1297  my $dbh = shift;
1298 
1299  my $ret = $dbh->selectall_arrayref("SELECT node_id, node_name FROM nodes ORDER BY node_type,node_id",
1300        { Slice => {} });
1301  return $ret;
1302} # end getNodeList()
1303
1304
1305## IPDB::getNodeName()
1306# Get node name from the ID
1307sub getNodeName {
1308  my $dbh = shift;
1309  my $nid = shift;
1310
1311  my ($nname) = $dbh->selectrow_array("SELECT node_name FROM nodes WHERE node_id = ?", undef, ($nid) );
1312  return $nname;
1313} # end getNodeName()
1314
1315
1316## IPDB::getNodeInfo()
1317# Get node name and ID associated with a block
1318sub getNodeInfo {
1319  my $dbh = shift;
1320  my $block = shift;
1321
1322  my ($nid, $nname) = $dbh->selectrow_array("SELECT nodes.node_id,node_name FROM nodes INNER JOIN noderef".
1323        " ON nodes.node_id=noderef.node_id WHERE noderef.block = ?", undef, ($block) );
1324  return ($nid, $nname);
1325} # end getNodeInfo()
1326
1327
1328## IPDB::mailNotify()
1329# Sends notification mail to recipients regarding an IPDB operation
1330sub mailNotify {
1331  my $dbh = shift;
1332  my ($action,$subj,$message) = @_;
1333
1334  return if $smtphost eq 'smtp.example.com';   # do nothing if still using default SMTP host.
1335
1336##fixme: need to redesign the breakdown/processing for $action for proper handling of all cases
1337
1338# split action into parts for fiddlement.  nb: there are almost certainly better ways to do this.
1339  my @actionbits = split //, $action;
1340
1341  # want to notify anyone who has specifically requested notify on *this* type ($action as passed),
1342  # on "all static IP types" or "all pool types" (and other last-char-in-type groupings), on eg "all DSL types",
1343  # and "all events with this action"
1344  my @actionsets = ($action);
1345##fixme: ick, eww.  really gotta find a better way to handle this...
1346  push @actionsets, ($actionbits[0].'.'.$actionbits[2],
1347        $actionbits[0].$actionbits[1].'.', $actionbits[0].'a') if $action =~ /^.{3}$/;
1348
1349  my $mailer = Net::SMTP->new($smtphost, Hello => "ipdb.$domain");
1350
1351  # get recip list from db
1352  my $sth = $dbh->prepare("SELECT reciplist FROM notify WHERE action=?");
1353
1354  my %reciplist;
1355  foreach (@actionsets) {
1356    $sth->execute($_);
1357##fixme - need to handle db errors
1358    my ($recipsub) = $sth->fetchrow_array;
1359    next if !$recipsub;
1360    foreach (split(/,/, $recipsub)) {
1361      $reciplist{$_}++;
1362    }
1363  }
1364
1365  return if !%reciplist;
1366
1367  foreach my $recip (keys %reciplist) {
1368    $mailer->mail("ipdb\@$domain");
1369    $mailer->to($recip);
1370    $mailer->data("From: \"$org_name IP Database\" <ipdb\@$domain>\n",
1371        "To: $recip\n",
1372        "Date: ".strftime("%a, %d %b %Y %H:%M:%S %z",localtime)."\n",
1373        "Subject: {IPDB} $subj\n",
1374        "X-Mailer: IPDB Notify v".sprintf("%.1d",$IPDB::VERSION)."\n",
1375        "Organization: $org_name\n",
1376        "\n$message\n");
1377  }
1378  $mailer->quit;
1379}
1380
1381# Indicates module loaded OK.  Required by Perl.
13821;
Note: See TracBrowser for help on using the repository browser.