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

Last change on this file since 527 was 527, checked in by Kris Deugau, 12 years ago

/trunk

Clean up and move SQL for showRBlock to IPDB.pm
Tweak listFree() since the segments in showMaster and showRBlock it
replaced weren't quite as identical as I thought
Convert template to use odd and squeeze a bit more HTML out of
main.cgi and IPDB.pm

See #34.

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