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

Last change on this file since 593 was 593, checked in by Kris Deugau, 9 years ago

/branches/stable

Merge /trunk r517 (merge /branches/htmlform)
Conflicts all resolved towards /trunk.
Fix a minor syntax error with "while (@data..." -> "while (my @data..."
(may cause merge conflicts later)

  • Property svn:keywords set to Date Rev Author
File size: 30.4 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-14 22:10:22 +0000 (Tue, 14 May 2013) $
6# SVN revision $Rev: 593 $
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 @masterblocks
26        %allocated %free %routed %bigfree %IPDBacl %aclmsg
27        &initIPDBGlobals &connectDB &finish &checkDBSanity &allocateBlock &addMaster
28        &deleteBlock &getBlockData &mailNotify
29        );
30
31@EXPORT         = (); # Export nothing by default.
32%EXPORT_TAGS    = ( ALL => [qw(
33                %disp_alloctypes %list_alloctypes %def_custids @citylist @poplist
34                @masterblocks %allocated %free %routed %bigfree %IPDBacl %aclmsg
35                &initIPDBGlobals &connectDB &finish &checkDBSanity &allocateBlock
36                &addMaster &deleteBlock &getBlockData &mailNotify
37                )]
38        );
39
40##
41## Global variables
42##
43our %disp_alloctypes;
44our %list_alloctypes;
45our %def_custids;
46our @citylist;
47our @poplist;
48our @masterblocks;
49our %allocated;
50our %free;
51our %routed;
52our %bigfree;
53our %IPDBacl;
54
55# mapping table for functional-area => error message
56our %aclmsg = (
57        addmaster       => 'add a master block',
58        addblock        => 'add an allocation',
59        updateblock     => 'update a block',
60        delblock        => 'delete an allocation',
61        );
62
63our $org_name = 'Example Corp';
64our $smtphost = 'smtp.example.com';
65our $domain = 'example.com';
66our $defcustid = '5554242';
67# mostly for rwhois
68##fixme:  leave these blank by default?
69our $rwhoisDataPath = '/usr/local/rwhoisd/etc/rwhoisd'; # to match ./configure defaults from rwhoisd-1.5.9.6
70our $org_street = '123 4th Street';
71our $org_city = 'Anytown';
72our $org_prov_state = 'ON';
73our $org_pocode = 'H0H 0H0';
74our $org_country = 'CA';
75our $org_phone = '000-555-1234';
76our $org_techhandle = 'ISP-ARIN-HANDLE';
77our $org_email = 'noc@example.com';
78our $hostmaster = 'dns@example.com';
79
80our $syslog_facility = 'local2';
81
82# Allow allocations to come from private IP ranges by default?
83# Set to 'y' or 'on' to enable.
84our $allowprivrange = '';
85
86# Let's initialize the globals.
87## IPDB::initIPDBGlobals()
88# Initialize all globals.  Takes a database handle, returns a success or error code
89sub initIPDBGlobals {
90  my $dbh = $_[0];
91  my $sth;
92
93  # Initialize alloctypes hashes
94  $sth = $dbh->prepare("select type,listname,dispname,listorder,def_custid from alloctypes order by listorder");
95  $sth->execute;
96  while (my @data = $sth->fetchrow_array) {
97    $disp_alloctypes{$data[0]} = $data[2];
98    $def_custids{$data[0]} = $data[4];
99    if ($data[3] < 900) {
100      $list_alloctypes{$data[0]} = $data[1];
101    }
102  }
103
104  # City and POP listings
105  $sth = $dbh->prepare("select city,routing from cities order by city");
106  $sth->execute;
107  return (undef,$sth->errstr) if $sth->err;
108  while (my @data = $sth->fetchrow_array) {
109    push @citylist, $data[0];
110    if ($data[1] eq 'y') {
111      push @poplist, $data[0];
112    }
113  }
114
115  # Master block list
116  $sth = $dbh->prepare("select cidr from masterblocks order by cidr");
117  $sth->execute;
118  return (undef,$sth->errstr) if $sth->err;
119  for (my $i=0; my @data = $sth->fetchrow_array(); $i++) {
120    $masterblocks[$i] = new NetAddr::IP $data[0];
121    $allocated{"$masterblocks[$i]"} = 0;
122    $free{"$masterblocks[$i]"} = 0;
123    $bigfree{"$masterblocks[$i]"} = 128; # Larger number means smaller block.
124                                        # Set to 128 to prepare for IPv6
125    $routed{"$masterblocks[$i]"} = 0;
126  }
127
128  # Load ACL data.  Specific username checks are done at a different level.
129  $sth = $dbh->prepare("select username,acl from users");
130  $sth->execute;
131  return (undef,$sth->errstr) if $sth->err;
132  while (my @data = $sth->fetchrow_array) {
133    $IPDBacl{$data[0]} = $data[1];
134  }
135
136##fixme:  initialize HTML::Template env var for template path
137# something like $self->path().'/templates' ?
138#  $ENV{HTML_TEMPLATE_ROOT} = 'foo/bar';
139
140  return (1,"OK");
141} # end initIPDBGlobals
142
143
144## IPDB::connectDB()
145# Creates connection to IPDB.
146# Requires the database name, username, and password.
147# Returns a handle to the db.
148# Set up for a PostgreSQL db;  could be any transactional DBMS with the
149# right changes.
150sub connectDB {
151  my $dbname = shift;
152  my $user = shift;
153  my $pass = shift;
154  my $dbhost = shift;
155
156  my $dbh;
157  my $DSN = "DBI:Pg:".($dbhost ? "host=$dbhost;" : '')."dbname=$dbname";
158
159# Note that we want to autocommit by default, and we will turn it off locally as necessary.
160# We may not want to print gobbledygook errors;  YMMV.  Have to ponder that further.
161  $dbh = DBI->connect($DSN, $user, $pass, {
162        AutoCommit => 1,
163        PrintError => 0
164        })
165    or return (undef, $DBI::errstr) if(!$dbh);
166
167# Return here if we can't select.  Note that this indicates a
168# problem executing the select.
169  my $sth = $dbh->prepare("select type from alloctypes");
170  $sth->execute();
171  return (undef,$DBI::errstr) if ($sth->err);
172
173# See if the select returned anything (or null data).  This should
174# succeed if the select executed, but...
175  $sth->fetchrow();
176  return (undef,$DBI::errstr)  if ($sth->err);
177
178# If we get here, we should be OK.
179  return ($dbh,"DB connection OK");
180} # end connectDB
181
182
183## IPDB::finish()
184# Cleans up after database handles and so on.
185# Requires a database handle
186sub finish {
187  my $dbh = $_[0];
188  $dbh->disconnect if $dbh;
189} # end finish
190
191
192## IPDB::checkDBSanity()
193# Quick check to see if the db is responding.  A full integrity
194# check will have to be a separate tool to walk the IP allocation trees.
195sub checkDBSanity {
196  my ($dbh) = $_[0];
197
198  if (!$dbh) {
199    print "No database handle, or connection has been closed.";
200    return -1;
201  } else {
202    # it connects, try a stmt.
203    my $sth = $dbh->prepare("select type from alloctypes");
204    my $err = $sth->execute();
205
206    if ($sth->fetchrow()) {
207      # all is well.
208      return 1;
209    } else {
210      print "Connected to the database, but could not execute test statement.  ".$sth->errstr();
211      return -1;
212    }
213  }
214  # Clean up after ourselves.
215#  $dbh->disconnect;
216} # end checkDBSanity
217
218
219## IPDB::addMaster()
220# Does all the magic necessary to sucessfully add a master block
221# Requires database handle, block to add
222# Returns failure code and error message or success code and "message"
223sub addMaster {
224  my $dbh = shift;
225  my $cidr = new NetAddr::IP shift;
226
227  # Allow transactions, and raise an exception on errors so we can catch it later.
228  # Use local to make sure these get "reset" properly on exiting this block
229  local $dbh->{AutoCommit} = 0;
230  local $dbh->{RaiseError} = 1;
231
232  # Wrap all the SQL in a transaction
233  eval {
234    my $sth = $dbh->prepare("select count(*) from masterblocks where cidr <<= '$cidr'");
235    $sth->execute;
236    my @data = $sth->fetchrow_array;
237
238    if ($data[0] eq 0) {
239      # First case - master is brand-spanking-new.
240##fixme: rwhois should be globally-flagable somewhere, much like a number of other things
241## maybe a db table called "config"?
242      $sth = $dbh->prepare("insert into masterblocks (cidr,rwhois) values ('$cidr','y')");
243      $sth->execute;
244
245# Unrouted blocks aren't associated with a city (yet).  We don't rely on this
246# elsewhere though;  legacy data may have traps and pitfalls in it to break this.
247# Thus the "routed" flag.
248
249      $sth = $dbh->prepare("insert into freeblocks (cidr,maskbits,city,routed)".
250        " values ('$cidr',".$cidr->masklen.",'<NULL>','n')");
251      $sth->execute;
252
253      # If we get here, everything is happy.  Commit changes.
254      $dbh->commit;
255
256    } # new master does not contain existing master(s)
257    else {
258
259      # collect the master(s) we're going to absorb, and snag the longest netmask while we're at it.
260      my $smallmask = $cidr->masklen;
261      $sth = $dbh->prepare("select cidr as mask from masterblocks where cidr <<= '$cidr'");
262      $sth->execute;
263      my @cmasters;
264      while (my @data = $sth->fetchrow_array) {
265        my $master = new NetAddr::IP $data[0];
266        push @cmasters, $master;
267        $smallmask = $master->masklen if $master->masklen > $smallmask;
268      }
269
270      # split the new master, and keep only those blocks not part of an existing master
271      my @blocklist;
272      foreach my $seg ($cidr->split($smallmask)) {
273        my $contained = 0;
274        foreach my $master (@cmasters) {
275          $contained = 1 if $master->contains($seg);
276        }
277        push @blocklist, $seg if !$contained;
278      }
279
280      # collect the unrouted free blocks within the new master
281      $sth = $dbh->prepare("select cidr from freeblocks where ".
282                "maskbits>=$smallmask and cidr <<= '$cidr' and routed='n'");
283      $sth->execute;
284      while (my @data = $sth->fetchrow_array) {
285        my $freeblock = new NetAddr::IP $data[0];
286        push @blocklist, $freeblock;
287      }
288
289      # combine the set of free blocks we should have now.
290      @blocklist = Compact(@blocklist);
291
292      # and now insert the new data.  Make sure to delete old masters too.
293
294      # freeblocks
295      $sth = $dbh->prepare("delete from freeblocks where cidr <<= ?");
296      my $sth2 = $dbh->prepare("insert into freeblocks (cidr,maskbits,city,routed) values (?,?,'<NULL>','n')");
297      foreach my $newblock (@blocklist) {
298        $sth->execute("$newblock");
299        $sth2->execute("$newblock", $newblock->masklen);
300      }
301
302      # master
303      $sth = $dbh->prepare("delete from masterblocks where cidr <<= '$cidr'");
304      $sth->execute;
305      $sth = $dbh->prepare("insert into masterblocks (cidr,rwhois) values ('$cidr','y')");
306      $sth->execute;
307
308      # *whew*  If we got here, we likely suceeded.
309      $dbh->commit;
310    } # new master contained existing master(s)
311  }; # end eval
312
313  if ($@) {
314    my $msg = $@;
315    eval { $dbh->rollback; };
316    return ('FAIL',$msg);
317  } else {
318    return ('OK','OK');
319  }
320} # end addMaster
321
322
323## IPDB::allocateBlock()
324# Does all of the magic of actually allocating a netblock
325# Requires database handle, block to allocate, custid, type, city,
326#       description, notes, circuit ID, block to allocate from, private data
327# Returns a success code and optional error message.
328sub allocateBlock {
329  my ($dbh,undef,undef,$custid,$type,$city,$desc,$notes,$circid,$privdata,$nodeid) = @_;
330  $privdata = '' if !defined($privdata);
331
332  my $cidr = new NetAddr::IP $_[1];
333  my $alloc_from = new NetAddr::IP $_[2];
334  my $sth;
335
336  $desc = '' if !$desc;
337  $notes = '' if !$notes;
338  $circid = '' if !$circid;
339  $privdata = '' if !$privdata;
340
341  # Snag the "type" of the freeblock (alloc_from) "just in case"
342  $sth = $dbh->prepare("select routed from freeblocks where cidr='$alloc_from'");
343  $sth->execute;
344  my ($alloc_from_type) = $sth->fetchrow_array;
345
346  # To contain the error message, if any.
347  my $msg = "Unknown error allocating $cidr as '$type'";
348
349  # Enable transactions and error handling
350  local $dbh->{AutoCommit} = 0; # These need to be local so we don't
351  local $dbh->{RaiseError} = 1; # step on our toes by accident.
352
353  if ($type =~ /^.i$/) {
354    $msg = "Unable to assign static IP $cidr to $custid";
355    eval {
356      # We have to do this in two parts because otherwise we lose
357      # the ability to return the IP assigned.  Should that change,
358      # the commented SQL statement below may become usable.
359# update poolips set custid='$custid',city='$city',available='n',
360#       description='$desc',notes='$notes',circuitid='$circid'
361#       where ip=(select ip from poolips where pool='$alloc_from'
362#       and available='y' order by ip limit 1);
363
364# If no specific IP was requested, pick the next available one from the pool.
365      if (!$cidr) {
366        $sth = $dbh->prepare("select ip from poolips where pool='$alloc_from'".
367          " and available='y' order by ip");
368        $sth->execute;
369
370        my @data = $sth->fetchrow_array;
371        $cidr = $data[0];  # $cidr is already declared when we get here!
372      }
373
374      $sth = $dbh->prepare("update poolips set custid=?,city=?,".
375        "available='n',description=?,notes=?,circuitid=?,privdata=?".
376        " where ip=?");
377      $sth->execute($custid, $city, $desc, $notes, $circid, $privdata, "$cidr");
378# node hack
379      if ($nodeid && $nodeid ne '') {
380        $sth = $dbh->prepare("INSERT INTO noderef (block,node_id) VALUES (?,?)");
381        $sth->execute("$cidr",$nodeid);
382      }
383# end node hack
384      $dbh->commit;
385    };
386    if ($@) {
387      $msg .= ": '".$sth->errstr."'";
388      eval { $dbh->rollback; };
389      return ('FAIL',$msg);
390    } else {
391      return ('OK',"$cidr");
392    }
393
394  } else { # end IP-from-pool allocation
395
396    my $errcode = 'OK';
397    if ($cidr == $alloc_from) {
398      # Easiest case- insert in one table, delete in the other, and go home.  More or less.
399      # insert into allocations values (cidr,custid,type,city,desc) and
400      # delete from freeblocks where cidr='cidr'
401      # For data safety on non-transaction DBs, we delete first.
402
403      eval {
404        $msg = "Unable to allocate $cidr as '$disp_alloctypes{$type}'";
405        if ($type eq 'rm') {
406          $sth = $dbh->prepare("update freeblocks set routed='y',city='$city'".
407            " where cidr='$cidr'");
408          $sth->execute;
409          $sth = $dbh->prepare("insert into routed (cidr,maskbits,city)".
410                " values ('$cidr',".$cidr->masklen.",'$city')");
411          $sth->execute;
412        } else {
413          # common stuff for end-use, dialup, dynDSL, pools, etc, etc.
414
415          # special case - block is a container/"reserve" block
416          if ($type =~ /^(.)c$/) {
417            $sth = $dbh->prepare("update freeblocks set routed='$1' where cidr='$cidr'");
418            $sth->execute;
419          } else {
420            # "normal" case
421            $sth = $dbh->prepare("delete from freeblocks where cidr='$cidr'");
422            $sth->execute;
423          }
424          $sth = $dbh->prepare("insert into allocations".
425                " (cidr,custid,type,city,description,notes,maskbits,circuitid,privdata)".
426                " values (?,?,?,?,?,?,?,?,?)");
427          $sth->execute("$cidr", $custid, $type, $city, $desc, $notes, $cidr->masklen, $circid, $privdata);
428
429          # And initialize the pool, if necessary
430          # PPPoE pools (currently dialup, DSL, and WiFi) get all IPs made available
431          # "DHCP" or "real-subnet" pools have the net, gw, and bcast IPs removed.
432          if ($type =~ /^.p$/) {
433            $msg = "Could not initialize IPs in new $disp_alloctypes{$type} $cidr";
434            my ($code,$rmsg) = initPool($dbh,$cidr,$type,$city,"all");
435            die $rmsg if $code eq 'FAIL';
436            $msg = $rmsg;
437            $errcode = $code;
438          } elsif ($type =~ /^.d$/) {
439            $msg = "Could not initialize IPs in new $disp_alloctypes{$type} $cidr";
440            my ($code,$rmsg) = initPool($dbh,$cidr,$type,$city,"normal");
441            die $rmsg if $code eq 'FAIL';
442            $msg = $rmsg;
443            $errcode = $code;
444          }
445
446        } # routing vs non-routing netblock
447
448# node hack
449      if ($nodeid && $nodeid ne '') {
450        $sth = $dbh->prepare("INSERT INTO noderef (block,node_id) VALUES (?,?)");
451        $sth->execute("$cidr",$nodeid);
452      }
453# end node hack
454        $dbh->commit;
455      }; # end of eval
456      if ($@) {
457        $msg .= ": ".$@;
458        eval { $dbh->rollback; };
459        return ('FAIL',$msg);
460      } else {
461        return ($errcode,($type =~ /^.[pd]$/ ? $msg : "OK"));
462      }
463
464    } else { # cidr != alloc_from
465
466      # Hard case.  Allocation is smaller than free block.
467      my $wantmaskbits = $cidr->masklen;
468      my $maskbits = $alloc_from->masklen;
469
470      my @newfreeblocks;        # Holds free blocks generated from splitting the source freeblock.
471
472      # This determines which blocks will be left "free" after allocation.  We take the
473      # block we're allocating from, and split it in half.  We see which half the wanted
474      # block is in, and repeat until the wanted block is equal to one of the halves.
475      my $i=0;
476      my $tmp_from = $alloc_from;       # So we don't munge $alloc_from
477      while ($maskbits++ < $wantmaskbits) {
478        my @subblocks = $tmp_from->split($maskbits);
479        $newfreeblocks[$i++] = (($cidr->within($subblocks[0])) ? $subblocks[1] : $subblocks[0]);
480        $tmp_from = ( ($cidr->within($subblocks[0])) ? $subblocks[0] : $subblocks[1] );
481      } # while
482
483      # Begin SQL transaction block
484      eval {
485        $msg = "Unable to allocate $cidr as '$disp_alloctypes{$type}'";
486
487        # Delete old freeblocks entry
488        $sth = $dbh->prepare("delete from freeblocks where cidr='$alloc_from'");
489        $sth->execute();
490
491        # now we have to do some magic for routing blocks
492        if ($type eq 'rm') {
493
494          # Insert the new freeblocks entries
495          # Note that non-routed blocks are assigned to <NULL>
496          # and use the default value for the routed column ('n')
497          $sth = $dbh->prepare("insert into freeblocks (cidr,maskbits,city)".
498                " values (?, ?, '<NULL>')");
499          foreach my $block (@newfreeblocks) {
500            $sth->execute("$block", $block->masklen);
501          }
502
503          # Insert the entry in the routed table
504          $sth = $dbh->prepare("insert into routed (cidr,maskbits,city)".
505                " values ('$cidr',".$cidr->masklen.",'$city')");
506          $sth->execute;
507          # Insert the (almost) same entry in the freeblocks table
508          $sth = $dbh->prepare("insert into freeblocks (cidr,maskbits,city,routed)".
509                " values ('$cidr',".$cidr->masklen.",'$city','y')");
510          $sth->execute;
511
512        } else { # done with alloctype == rm
513
514          # Insert the new freeblocks entries
515          # Along with some more HairyPerl(TM):
516          #   if $alloc_type_from is p
517          #   OR
518          #   $type matches /^(.)r$/
519          # inserted value for routed column should match.
520          # This solves the case of inserting an arbitrary block into a
521          # "Reserve-for-routed-DSL" block.  Which you really shouldn't
522          # do in the first place, but anyway...
523          $sth = $dbh->prepare("insert into freeblocks (cidr,maskbits,city,routed)".
524                " values (?, ?, (select city from routed where cidr >>= '$cidr'),'".
525                ( ( ($alloc_from_type =~ /^(p)$/) || ($type =~ /^(.)r$/) ) ? "$1" : 'y')."')");
526          foreach my $block (@newfreeblocks) {
527            $sth->execute("$block", $block->masklen);
528          }
529          # Special-case for reserve/"container" blocks - generate
530          # the "extra" freeblocks entry for the container
531          if ($type =~ /^(.)c$/) {
532            $sth = $dbh->prepare("insert into freeblocks (cidr,maskbits,city,routed)".
533                " values ('$cidr',".$cidr->masklen.",'$city','$1')");
534            $sth->execute;
535          }
536          # Insert the allocations entry
537          $sth = $dbh->prepare("insert into allocations (cidr,custid,type,city,".
538                "description,notes,maskbits,circuitid,privdata)".
539                " values (?,?,?,?,?,?,?,?,?)");
540          $sth->execute("$cidr", $custid, $type, $city, $desc, $notes, $cidr->masklen, $circid, $privdata);
541
542          # And initialize the pool, if necessary
543          # PPPoE pools (currently dialup, DSL, and WiFi) get all IPs made available
544          # "DHCP" or "real-subnet" pools have the net, gw, and bcast IPs removed.
545          if ($type =~ /^.p$/) {
546            $msg = "Could not initialize IPs in new $disp_alloctypes{$type} $cidr";
547            my ($code,$rmsg) = initPool($dbh,$cidr,$type,$city,"all");
548            die $rmsg if $code eq 'FAIL';
549          } elsif ($type =~ /^.d$/) {
550            $msg = "Could not initialize IPs in new $disp_alloctypes{$type} $cidr";
551            my ($code,$rmsg) = initPool($dbh,$cidr,$type,$city,"normal");
552            die $rmsg if $code eq 'FAIL';
553          }
554
555        } # done with netblock alloctype != rm
556
557# node hack
558      if ($nodeid && $nodeid ne '') {
559        $sth = $dbh->prepare("INSERT INTO noderef (block,node_id) VALUES (?,?)");
560        $sth->execute("$cidr",$nodeid);
561      }
562# end node hack
563        $dbh->commit;
564      }; # end eval
565      if ($@) {
566        $msg .= ": ".$@;
567        eval { $dbh->rollback; };
568        return ('FAIL',$msg);
569      } else {
570        return ($errcode,($type =~ /^.[pd]$/ ? $msg : "OK"));
571      }
572
573    } # end fullcidr != alloc_from
574
575  } # end static-IP vs netblock allocation
576
577} # end allocateBlock()
578
579
580## IPDB::initPool()
581# Initializes a pool
582# Requires a database handle, the pool CIDR, type, city, and a parameter
583# indicating whether the pool should allow allocation of literally every
584# IP, or if it should reserve network/gateway/broadcast IPs
585# Note that this is NOT done in a transaction, that's why it's a private
586# function and should ONLY EVER get called from allocateBlock()
587sub initPool {
588  my ($dbh,undef,$type,$city,$class) = @_;
589  my $pool = new NetAddr::IP $_[1];
590
591  return ('WARN','Refusing to melt server with IPv6 IP pool') if $pool->bits == 128;
592
593##fixme Need to just replace 2nd char of type with i rather than capturing 1st char of type
594  $type =~ s/[pd]$/i/;
595  my $sth;
596  my $msg;
597
598  # Trap errors so we can pass them back to the caller.  Even if the
599  # caller is only ever supposed to be local, and therefore already
600  # trapping errors.  >:(
601  local $dbh->{AutoCommit} = 0; # These need to be local so we don't
602  local $dbh->{RaiseError} = 1; # step on our toes by accident.
603
604  eval {
605    # have to insert all pool IPs into poolips table as "unallocated".
606    $sth = $dbh->prepare("insert into poolips (pool,ip,custid,city,type)".
607        " values ('$pool', ?, '$defcustid', ?, '$type')");
608    my @poolip_list = $pool->hostenum;
609    if ($class eq 'all') { # (DSL-ish block - *all* IPs available
610      if ($pool->addr !~ /\.0$/) {      # .0 causes weirdness.
611        $sth->execute($pool->addr, $city);
612      }
613      for (my $i=0; $i<=$#poolip_list; $i++) {
614        $sth->execute($poolip_list[$i]->addr, $city);
615      }
616      $pool--;
617      if ($pool->addr !~ /\.255$/) {    # .255 can cause weirdness.
618        $sth->execute($pool->addr, $city);
619      }
620    } else { # (real netblock)
621      for (my $i=1; $i<=$#poolip_list; $i++) {
622        $sth->execute($poolip_list[$i]->addr, $city);
623      }
624    }
625  };
626  if ($@) {
627    $msg = $@." '".$sth->errstr."'";
628    eval { $dbh->rollback; };
629    return ('FAIL',$msg);
630  } else {
631    return ('OK',"OK");
632  }
633} # end initPool()
634
635
636## IPDB::deleteBlock()
637# Removes an allocation from the database, including deleting IPs
638# from poolips and recombining entries in freeblocks if possible
639# Also handles "deleting" a static IP allocation, and removal of a master
640# Requires a database handle, the block to delete, and the type of block
641sub deleteBlock {
642  my ($dbh,undef,$type) = @_;
643  my $cidr = new NetAddr::IP $_[1];
644
645  my $sth;
646
647  # Magic variables used for odd allocation cases.
648  my $container;
649  my $con_type;
650
651  # To contain the error message, if any.
652  my $msg = "Unknown error deallocating $type $cidr";
653  # Enable transactions and exception-on-errors... but only for this sub
654  local $dbh->{AutoCommit} = 0;
655  local $dbh->{RaiseError} = 1;
656
657  # First case.  The "block" is a static IP
658  # Note that we still need some additional code in the odd case
659  # of a netblock-aligned contiguous group of static IPs
660  if ($type =~ /^.i$/) {
661
662    eval {
663      $msg = "Unable to deallocate $disp_alloctypes{$type} $cidr";
664      $sth = $dbh->prepare("update poolips set custid=?,available='y',".
665        "city=(select city from allocations where cidr >>= ?".
666        " order by masklen(cidr) desc limit 1),".
667        "description='',notes='',circuitid='' where ip=?");
668      $sth->execute($defcustid, "$cidr", "$cidr");
669      $dbh->commit;
670    };
671    if ($@) {
672      eval { $dbh->rollback; };
673      return ('FAIL',$msg);
674    } else {
675      return ('OK',"OK");
676    }
677
678  } elsif ($type eq 'mm') { # end alloctype =~ /.i/
679
680    $msg = "Unable to delete master block $cidr";
681    eval {
682      $sth = $dbh->prepare("delete from masterblocks where cidr='$cidr'");
683      $sth->execute;
684      $sth = $dbh->prepare("delete from freeblocks where cidr <<= '$cidr'");
685      $sth->execute;
686      $dbh->commit;
687    };
688    if ($@) {
689      eval { $dbh->rollback; };
690      return ('FAIL', $msg);
691    } else {
692      return ('OK',"OK");
693    }
694
695  } else { # end alloctype master block case
696
697    ## This is a big block; but it HAS to be done in a chunk.  Any removal
698    ## of a netblock allocation may result in a larger chunk of free
699    ## contiguous IP space - which may in turn be combined into a single
700    ## netblock rather than a number of smaller netblocks.
701
702    eval {
703
704      if ($type eq 'rm') {
705        $msg = "Unable to remove routing allocation $cidr";
706        $sth = $dbh->prepare("delete from routed where cidr='$cidr'");
707        $sth->execute;
708        # Make sure block getting deleted is properly accounted for.
709        $sth = $dbh->prepare("update freeblocks set routed='n',city='<NULL>'".
710                " where cidr='$cidr'");
711        $sth->execute;
712        # Set up query to start compacting free blocks.
713        $sth = $dbh->prepare("select cidr from freeblocks where ".
714                "maskbits<=".$cidr->masklen." and routed='n' order by maskbits desc");
715
716      } else { # end alloctype routing case
717
718        # Magic.  We need to get information about the containing block (if any)
719        # so as to make sure that the freeblocks we insert get the correct "type".
720        $sth = $dbh->prepare("select cidr,type from allocations where cidr >> '$cidr'");
721        $sth->execute;
722        ($container, $con_type) = $sth->fetchrow_array;
723
724        # Delete all allocations within the block being deleted.  This is
725        # deliberate and correct, and removes the need to special-case
726        # removal of "container" blocks.
727        $sth = $dbh->prepare("delete from allocations where cidr <<='$cidr'");
728        $sth->execute;
729
730        # Special case - delete pool IPs
731        if ($type =~ /^.[pd]$/) {
732          # We have to delete the IPs from the pool listing.
733          $sth = $dbh->prepare("delete from poolips where pool='$cidr'");
734          $sth->execute;
735        }
736
737        # Set up query for compacting free blocks.
738        if ($con_type && $con_type eq 'pc') {
739          # Clean up after "bad" allocations (blocks that are not formally
740          # contained which have nevertheless been allocated from a container block)
741          # We want to make certain that the freeblocks are properly "labelled"
742          $sth = $dbh->prepare("select cidr from freeblocks where cidr <<= '$container' order by maskbits desc");
743        } else {
744          # Standard deallocation.
745          $sth = $dbh->prepare("select cidr from freeblocks where cidr <<= ".
746                "(select cidr from routed where cidr >>= '$cidr') ".
747                " and maskbits<=".$cidr->masklen.
748                " and routed='".(($type =~ /^(.)r$/) ? "$1" : 'y').
749                "' order by maskbits desc");
750        }
751
752      } # end alloctype general case
753
754      ## Deallocate legacy blocks stashed in the middle of a static IP pool
755      ## This may be expandable to an even more general case of contained netblock, or other pool types.
756
757      # Find out if the block we're deallocating is within a DSL pool
758      my $sth2 = $dbh->prepare("SELECT cidr,city,type FROM allocations WHERE type LIKE '_p' AND cidr >>= ?");
759      $sth2->execute("$cidr");
760      my ($pool,$poolcity,$pooltype) = $sth2->fetchrow_array;
761
762      if ($pool || $sth2->rows) {
763        # We've already deleted the block, now we have to stuff its IPs into the pool.
764        $pooltype =~ s/p$/i/;   # change type to static IP
765        $sth2 = $dbh->prepare("INSERT INTO poolips (pool,ip,city,type,custid) values ".
766                "('$pool',?,'$poolcity','$pooltype','$defcustid')");
767##fixme:  need to not insert net, gateway, and bcast on "real netblock" pools (DHCPish)
768        # don't insert .0
769        $sth2->execute($cidr->addr) unless $cidr->addr =~ m|\.0$|;
770        foreach my $ip ($cidr->hostenum) {
771          $sth2->execute("$ip");
772        }
773        $cidr--;
774        # don't insert .255
775        $sth2->execute($cidr->addr) unless $cidr->addr =~ m|\.255$|;
776      } else {  # done returning IPs from a block to a static DSL pool
777
778        # Now we look for larger-or-equal-sized free blocks in the same master (routed)
779        # (super)block. If there aren't any, we can't combine blocks anyway.  If there
780        # are, we check to see if we can combine blocks.
781        # Execute the statement prepared in the if-else above.
782
783        $sth->execute;
784
785# NetAddr::IP->compact() attempts to produce the smallest inclusive block
786# from the caller and the passed terms.
787# EG:  if you call $cidr->compact($ip1,$ip2,$ip3) when $cidr, $ip1, $ip2,
788#       and $ip3 are consecutive /27's starting on .0 (.0-.31, .32-.63,
789#       .64-.95, and .96-.128), you will get an array containing a single
790#       /25 as element 0 (.0-.127).  Order is not important;  you could have
791#       $cidr=.32/27, $ip1=.96/27, $ip2=.0/27, and $ip3=.64/27.
792
793        my (@together, @combinelist);
794        my $i=0;
795        while (my @data = $sth->fetchrow_array) {
796          my $testIP = new NetAddr::IP $data[0];
797          @together = $testIP->compact($cidr);
798          my $num = @together;
799          if ($num == 1) {
800            $cidr = $together[0];
801            $combinelist[$i++] = $testIP;
802          }
803        }
804
805        # Clear old freeblocks entries - if any.  They should all be within
806        # the $cidr determined above.
807        $sth = $dbh->prepare("delete from freeblocks where cidr <<='$cidr'");
808        $sth->execute;
809
810        # insert "new" freeblocks entry
811        if ($type eq 'rm') {
812          $sth = $dbh->prepare("insert into freeblocks (cidr,maskbits,city)".
813                " values ('$cidr',".$cidr->masklen.",'<NULL>')");
814        } else {
815          # Magic hackery to insert "correct" data for deallocation of
816          # non-contained blocks allocated from within a container.
817          $type = 'pr' if $con_type && $con_type eq 'pc';
818
819          $sth = $dbh->prepare("insert into freeblocks (cidr,maskbits,city,routed)".
820                " values ('$cidr',".$cidr->masklen.
821                ",(select city from routed where cidr >>= '$cidr'),'".
822                (($type =~ /^(.)r$/) ? "$1" : 'y')."')");
823        }
824        $sth->execute;
825
826      } # done returning IPs to the appropriate place
827
828      # If we got here, we've succeeded.  Whew!
829      $dbh->commit;
830    }; # end eval
831    if ($@) {
832      $msg = $@;
833      eval { $dbh->rollback; };
834      return ('FAIL', $msg);
835    } else {
836      return ('OK',"OK");
837    }
838
839  } # end alloctype != netblock
840
841} # end deleteBlock()
842
843
844## IPDB::getBlockData()
845# Return custid, type, city, and description for a block
846sub getBlockData {
847  my $dbh = shift;
848  my $block = shift;
849
850  my $sth = $dbh->prepare("select cidr,custid,type,city,description from searchme".
851        " where cidr='$block'");
852  $sth->execute();
853  return $sth->fetchrow_array();
854} # end getBlockData()
855
856
857## IPDB::mailNotify()
858# Sends notification mail to recipients regarding an IPDB operation
859sub mailNotify {
860  my $dbh = shift;
861  my ($action,$subj,$message) = @_;
862
863  return if $smtphost eq 'smtp.example.com';   # do nothing if still using default SMTP host.
864
865##fixme: need to redesign the breakdown/processing for $action for proper handling of all cases
866
867# split action into parts for fiddlement.  nb: there are almost certainly better ways to do this.
868  my @actionbits = split //, $action;
869
870  # want to notify anyone who has specifically requested notify on *this* type ($action as passed),
871  # on "all static IP types" or "all pool types" (and other last-char-in-type groupings), on eg "all DSL types",
872  # and "all events with this action"
873  my @actionsets = ($action);
874##fixme: ick, eww.  really gotta find a better way to handle this...
875  push @actionsets, ($actionbits[0].'.'.$actionbits[2],
876        $actionbits[0].$actionbits[1].'.', $actionbits[0].'a') if $action =~ /^.{3}$/;
877
878  my $mailer = Net::SMTP->new($smtphost, Hello => "ipdb.$domain");
879
880  # get recip list from db
881  my $sth = $dbh->prepare("SELECT reciplist FROM notify WHERE action=?");
882
883  my %reciplist;
884  foreach (@actionsets) {
885    $sth->execute($_);
886##fixme - need to handle db errors
887    my ($recipsub) = $sth->fetchrow_array;
888    next if !$recipsub;
889    foreach (split(/,/, $recipsub)) {
890      $reciplist{$_}++;
891    }
892  }
893
894  return if !%reciplist;
895
896  foreach my $recip (keys %reciplist) {
897    $mailer->mail("ipdb\@$domain");
898    $mailer->to($recip);
899    $mailer->data("From: \"$org_name IP Database\" <ipdb\@$domain>\n",
900        "To: $recip\n",
901        "Date: ".strftime("%a, %d %b %Y %H:%M:%S %z",localtime)."\n",
902        "Subject: {IPDB} $subj\n",
903        "X-Mailer: IPDB Notify v".sprintf("%.1d",$IPDB::VERSION)."\n",
904        "Organization: $org_name\n",
905        "\n$message\n");
906  }
907  $mailer->quit;
908}
909
910# Indicates module loaded OK.  Required by Perl.
9111;
Note: See TracBrowser for help on using the repository browser.