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

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

/trunk

Tweak allocateBlock() to usefully handle passing an IP as an
override on the automatic IP-chooser.
Convert allocation of a pool IP in admin.cgi to use updated
allocateBlock(). See #34.

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