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

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

/trunk

Clean up and move most SQL for allocation update into IPDB.pm. See #34.

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