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

Last change on this file since 645 was 640, checked in by Kris Deugau, 10 years ago

/trunk

Commit 12/mumble for work done intermittently over the past ~year.

  • Subtle tweak in internal DNS-RPC caller sub
  • Property svn:keywords set to Date Rev Author
File size: 60.9 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: 2014-10-17 20:37:37 +0000 (Fri, 17 Oct 2014) $
6# SVN revision $Rev: 640 $
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;
[573]18use NetAddr::IP qw(:lower Compact );
[582]19use Frontier::Client;
[68]20use POSIX;
[4]21use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
22
[417]23$VERSION = 2; ##VERSION##
[4]24@ISA = qw(Exporter);
[106]25@EXPORT_OK = qw(
[541]26 %disp_alloctypes %list_alloctypes %def_custids @citylist @poplist
[585]27 %IPDBacl %aclmsg $errstr
[523]28 &initIPDBGlobals &connectDB &finish &checkDBSanity
[547]29 &addMaster &touchMaster
[561]30 &listSummary &listSubs &listFree &listPool
[541]31 &getMasterList &getTypeList &getPoolSelect &findAllocateFrom
[536]32 &ipParent &subParent &blockParent &getRoutedCity
[585]33 &allocateBlock &updateBlock &deleteBlock &getBlockData &getBlockRDNS
[530]34 &getNodeList &getNodeName &getNodeInfo
[519]35 &mailNotify
[106]36 );
[4]37
38@EXPORT = (); # Export nothing by default.
[106]39%EXPORT_TAGS = ( ALL => [qw(
[167]40 %disp_alloctypes %list_alloctypes %def_custids @citylist @poplist
[585]41 %IPDBacl %aclmsg $errstr
[523]42 &initIPDBGlobals &connectDB &finish &checkDBSanity
[547]43 &addMaster &touchMaster
[561]44 &listSummary &listSubs &listFree &listPool
[541]45 &getMasterList &getTypeList &getPoolSelect &findAllocateFrom
[536]46 &ipParent &subParent &blockParent &getRoutedCity
[585]47 &allocateBlock &updateBlock &deleteBlock &getBlockData &getBlockRDNS
[530]48 &getNodeList &getNodeName &getNodeInfo
[519]49 &mailNotify
[106]50 )]
51 );
[4]52
[77]53##
54## Global variables
55##
56our %disp_alloctypes;
57our %list_alloctypes;
[167]58our %def_custids;
[96]59our @citylist;
60our @poplist;
[233]61our %IPDBacl;
[66]62
[517]63# mapping table for functional-area => error message
64our %aclmsg = (
65 addmaster => 'add a master block',
66 addblock => 'add an allocation',
67 updateblock => 'update a block',
68 delblock => 'delete an allocation',
69 );
70
[585]71# error reporting
72our $errstr = '';
73
[417]74our $org_name = 'Example Corp';
[416]75our $smtphost = 'smtp.example.com';
76our $domain = 'example.com';
[417]77our $defcustid = '5554242';
78# mostly for rwhois
79##fixme: leave these blank by default?
[420]80our $rwhoisDataPath = '/usr/local/rwhoisd/etc/rwhoisd'; # to match ./configure defaults from rwhoisd-1.5.9.6
[417]81our $org_street = '123 4th Street';
82our $org_city = 'Anytown';
83our $org_prov_state = 'ON';
84our $org_pocode = 'H0H 0H0';
85our $org_country = 'CA';
86our $org_phone = '000-555-1234';
87our $org_techhandle = 'ISP-ARIN-HANDLE';
[434]88our $org_email = 'noc@example.com';
[437]89our $hostmaster = 'dns@example.com';
[416]90
[417]91our $syslog_facility = 'local2';
92
[582]93our $rpc_url = '';
[585]94our $revgroup = 1; # should probably be configurable somewhere
95our $rpccount = 0;
[582]96
[585]97##
98## Internal utility functions
99##
100
101## IPDB::_rpc
102# Make an RPC call for DNS changes
103sub _rpc {
104 return if !$rpc_url; # Just In Case
105 my $rpcsub = shift;
106 my %args = @_;
107
108 # Make an object to represent the XML-RPC server.
109 my $server = Frontier::Client->new(url => $rpc_url, debug => 0);
110 my $result;
111
112 my %rpcargs = (
113 rpcsystem => 'ipdb',
[640]114# must be provided by caller's caller
115# rpcuser => $args{user},
116 %args,
[585]117 );
118
119 eval {
[640]120 $result = $server->call("dnsdb.$rpcsub", %rpcargs);
[585]121 };
122 if ($@) {
123 $errstr = $@;
124 $errstr =~ s/Fault returned from XML RPC Server, fault code 4: error executing RPC `dnsdb.$rpcsub'\.\s//;
125 }
126 $rpccount++;
127
128 return $result if $result;
129} # end _rpc()
130
131
[77]132# Let's initialize the globals.
133## IPDB::initIPDBGlobals()
134# Initialize all globals. Takes a database handle, returns a success or error code
135sub initIPDBGlobals {
136 my $dbh = $_[0];
137 my $sth;
138
[106]139 # Initialize alloctypes hashes
[167]140 $sth = $dbh->prepare("select type,listname,dispname,listorder,def_custid from alloctypes order by listorder");
[77]141 $sth->execute;
142 while (my @data = $sth->fetchrow_array) {
[106]143 $disp_alloctypes{$data[0]} = $data[2];
[167]144 $def_custids{$data[0]} = $data[4];
[106]145 if ($data[3] < 900) {
146 $list_alloctypes{$data[0]} = $data[1];
147 }
[77]148 }
[96]149
150 # City and POP listings
[157]151 $sth = $dbh->prepare("select city,routing from cities order by city");
[96]152 $sth->execute;
153 return (undef,$sth->errstr) if $sth->err;
154 while (my @data = $sth->fetchrow_array) {
[106]155 push @citylist, $data[0];
[96]156 if ($data[1] eq 'y') {
[106]157 push @poplist, $data[0];
[96]158 }
159 }
160
[233]161 # Load ACL data. Specific username checks are done at a different level.
162 $sth = $dbh->prepare("select username,acl from users");
163 $sth->execute;
[106]164 return (undef,$sth->errstr) if $sth->err;
[233]165 while (my @data = $sth->fetchrow_array) {
166 $IPDBacl{$data[0]} = $data[1];
167 }
[106]168
[517]169##fixme: initialize HTML::Template env var for template path
170# something like $self->path().'/templates' ?
171# $ENV{HTML_TEMPLATE_ROOT} = 'foo/bar';
172
[77]173 return (1,"OK");
174} # end initIPDBGlobals
175
176
177## IPDB::connectDB()
[4]178# Creates connection to IPDB.
[77]179# Requires the database name, username, and password.
[4]180# Returns a handle to the db.
[77]181# Set up for a PostgreSQL db; could be any transactional DBMS with the
182# right changes.
[4]183sub connectDB {
[432]184 my $dbname = shift;
185 my $user = shift;
186 my $pass = shift;
187 my $dbhost = shift;
188
[4]189 my $dbh;
[432]190 my $DSN = "DBI:Pg:".($dbhost ? "host=$dbhost;" : '')."dbname=$dbname";
[4]191
192# Note that we want to autocommit by default, and we will turn it off locally as necessary.
[77]193# We may not want to print gobbledygook errors; YMMV. Have to ponder that further.
194 $dbh = DBI->connect($DSN, $user, $pass, {
195 AutoCommit => 1,
196 PrintError => 0
197 })
198 or return (undef, $DBI::errstr) if(!$dbh);
[4]199
[77]200# Return here if we can't select. Note that this indicates a
201# problem executing the select.
[183]202 my $sth = $dbh->prepare("select type from alloctypes");
[77]203 $sth->execute();
204 return (undef,$DBI::errstr) if ($sth->err);
205
206# See if the select returned anything (or null data). This should
207# succeed if the select executed, but...
208 $sth->fetchrow();
209 return (undef,$DBI::errstr) if ($sth->err);
210
211# If we get here, we should be OK.
212 return ($dbh,"DB connection OK");
[4]213} # end connectDB
214
[77]215
216## IPDB::finish()
217# Cleans up after database handles and so on.
218# Requires a database handle
219sub finish {
220 my $dbh = $_[0];
[517]221 $dbh->disconnect if $dbh;
[77]222} # end finish
223
224
[106]225## IPDB::checkDBSanity()
[4]226# Quick check to see if the db is responding. A full integrity
227# check will have to be a separate tool to walk the IP allocation trees.
228sub checkDBSanity {
[106]229 my ($dbh) = $_[0];
[4]230
231 if (!$dbh) {
[106]232 print "No database handle, or connection has been closed.";
233 return -1;
[4]234 } else {
235 # it connects, try a stmt.
[184]236 my $sth = $dbh->prepare("select type from alloctypes");
[4]237 my $err = $sth->execute();
238
239 if ($sth->fetchrow()) {
240 # all is well.
241 return 1;
242 } else {
[16]243 print "Connected to the database, but could not execute test statement. ".$sth->errstr();
[106]244 return -1;
[4]245 }
246 }
247 # Clean up after ourselves.
[106]248# $dbh->disconnect;
[4]249} # end checkDBSanity
250
[66]251
[371]252## IPDB::addMaster()
253# Does all the magic necessary to sucessfully add a master block
254# Requires database handle, block to add
255# Returns failure code and error message or success code and "message"
256sub addMaster {
257 my $dbh = shift;
[591]258 # warning! during testing, this somehow generated a "Bad file descriptor" error. O_o
[371]259 my $cidr = new NetAddr::IP shift;
[582]260 my %args = @_;
[371]261
[582]262 $args{vrf} = '' if !$args{vrf};
263 $args{rdns} = '' if !$args{rdns};
264 $args{defloc} = '' if !$args{defloc};
265 $args{rwhois} = 'n' if !$args{rwhois}; # fail "safe", sort of.
266 $args{rwhois} = 'n' if $args{rwhois} ne 'n' and $args{rwhois} ne 'y';
267
[629]268 my $mid;
269
[371]270 # Allow transactions, and raise an exception on errors so we can catch it later.
271 # Use local to make sure these get "reset" properly on exiting this block
272 local $dbh->{AutoCommit} = 0;
273 local $dbh->{RaiseError} = 1;
274
275 # Wrap all the SQL in a transaction
276 eval {
[628]277 # First check - does the master exist? Ignore VRFs until we can see a sane UI
278 my ($mcontained) = $dbh->selectrow_array("SELECT cidr FROM allocations WHERE cidr >>= ? AND type = 'mm'",
279 undef, ($cidr) );
280 die "Master block $mcontained already exists and entirely contains $cidr\n"
281 if $mcontained;
[371]282
[628]283 # Second check - does the new master contain an existing one or ones?
284 my ($mexist) = $dbh->selectrow_array("SELECT cidr FROM allocations WHERE cidr <<= ? AND type = 'mm'",
285 undef, ($cidr) );
286
[518]287 if (!$mexist) {
[371]288 # First case - master is brand-spanking-new.
289##fixme: rwhois should be globally-flagable somewhere, much like a number of other things
290## maybe a db table called "config"?
[628]291 $dbh->do("INSERT INTO allocations (cidr,type,swip,vrf,rdns) VALUES (?,?,?,?,?)", undef,
292 ($cidr, 'mm', 'y', $args{vrf}, $args{rdns}) );
293 ($mid) = $dbh->selectrow_array("SELECT currval('allocations_id_seq')");
[371]294
295# Unrouted blocks aren't associated with a city (yet). We don't rely on this
296# elsewhere though; legacy data may have traps and pitfalls in it to break this.
297# Thus the "routed" flag.
[628]298 $dbh->do("INSERT INTO freeblocks (cidr,city,routed,parent_id,vrf,master_id) VALUES (?,?,?,?,?,?)", undef,
299 ($cidr, '<NULL>', 'm', $mid, $args{vrf}, $mid) );
[371]300
[628]301 # master should be its own master, so deletes directly at the master level work
302 $dbh->do("UPDATE allocations SET master_id = ? WHERE id = ?", undef, ($mid, $mid) );
303
[371]304 # If we get here, everything is happy. Commit changes.
305 $dbh->commit;
306
[518]307 } # done new master does not contain existing master(s)
[371]308 else {
309
310 # collect the master(s) we're going to absorb, and snag the longest netmask while we're at it.
311 my $smallmask = $cidr->masklen;
[628]312 my $sth = $dbh->prepare("SELECT cidr,id FROM allocations WHERE cidr <<= ? AND type='mm' AND parent_id=0");
[518]313 $sth->execute($cidr);
[371]314 my @cmasters;
[628]315 my @oldmids;
[371]316 while (my @data = $sth->fetchrow_array) {
317 my $master = new NetAddr::IP $data[0];
318 push @cmasters, $master;
[628]319 push @oldmids, $data[1];
[371]320 $smallmask = $master->masklen if $master->masklen > $smallmask;
321 }
322
323 # split the new master, and keep only those blocks not part of an existing master
324 my @blocklist;
325 foreach my $seg ($cidr->split($smallmask)) {
326 my $contained = 0;
327 foreach my $master (@cmasters) {
328 $contained = 1 if $master->contains($seg);
329 }
330 push @blocklist, $seg if !$contained;
331 }
332
[628]333##fixme: master_id
[371]334 # collect the unrouted free blocks within the new master
[556]335 $sth = $dbh->prepare("SELECT cidr FROM freeblocks WHERE masklen(cidr) <= ? AND cidr <<= ? AND routed = 'm'");
[518]336 $sth->execute($smallmask, $cidr);
[371]337 while (my @data = $sth->fetchrow_array) {
338 my $freeblock = new NetAddr::IP $data[0];
339 push @blocklist, $freeblock;
340 }
341
342 # combine the set of free blocks we should have now.
343 @blocklist = Compact(@blocklist);
344
[628]345 # master
346 $dbh->do("INSERT INTO allocations (cidr,type,swip,vrf,rdns) VALUES (?,?,?,?,?)", undef,
347 ($cidr, 'mm', 'y', $args{vrf}, $args{rdns}) );
348 ($mid) = $dbh->selectrow_array("SELECT currval('allocations_id_seq')");
349
350 # master should be its own master, so deletes directly at the master level work
351 $dbh->do("UPDATE allocations SET master_id = ? WHERE id = ?", undef, ($mid, $mid) );
352
[371]353 # and now insert the new data. Make sure to delete old masters too.
354
355 # freeblocks
[628]356 $sth = $dbh->prepare("DELETE FROM freeblocks WHERE cidr <<= ? AND parent_id IN (".join(',', @oldmids).")");
357 my $sth2 = $dbh->prepare("INSERT INTO freeblocks (cidr,city,routed,parent_id,vrf,master_id)".
358 " VALUES (?,'<NULL>','m',?,?,?)");
[371]359 foreach my $newblock (@blocklist) {
[518]360 $sth->execute($newblock);
[628]361 $sth2->execute($newblock, $mid, $args{vrf}, $mid);
[371]362 }
363
[628]364 # Update immediate allocations, and remove the old parents
365 $sth = $dbh->prepare("UPDATE allocations SET parent_id = ? WHERE parent_id = ?");
366 $sth2 = $dbh->prepare("DELETE FROM allocations WHERE id = ?");
367 foreach my $old (@oldmids) {
368 $sth->execute($mid, $old);
369 $sth2->execute($old);
370 }
[556]371
[371]372 # *whew* If we got here, we likely suceeded.
373 $dbh->commit;
[628]374
[371]375 } # new master contained existing master(s)
376 }; # end eval
377
378 if ($@) {
379 my $msg = $@;
380 eval { $dbh->rollback; };
381 return ('FAIL',$msg);
382 } else {
[582]383
384 # Only attempt rDNS if the IPDB side succeeded
385 if ($rpc_url) {
386
387# Note *not* splitting reverse zones negates any benefit from caching the exported data.
388# IPv6 address space is far too large to split usefully, and in any case (also due to
389# the large address space) doesn't support the iterated template records v4 zones do
390# that causes the bulk of the slowdown that needs the cache anyway.
391
392 my @zonelist;
393# allow splitting reverse zones to be disabled, maybe, someday
394#if ($splitrevzones && !$cidr->{isv6}) {
395 if (1 && !$cidr->{isv6}) {
396 my $splitpoint = ($cidr->masklen <= 16 ? 16 : 24); # hack pthui
397 @zonelist = $cidr->split($splitpoint);
398 } else {
399 @zonelist = ($cidr);
400 }
401 my @fails;
402 ##fixme: remove hardcoding where possible
403 foreach my $subzone (@zonelist) {
404 my %rpcargs = (
405 rpcuser => $args{user},
406 revzone => "$subzone",
407 revpatt => $args{rdns},
408 defloc => $args{defloc},
[585]409 group => $revgroup, # not sure how these two could sanely be exposed, tbh...
[582]410 state => 1, # could make them globally configurable maybe
411 );
[587]412 if ($rpc_url && !_rpc('addRDNS', %rpcargs)) {
[585]413 push @fails, ("$subzone" => $errstr);
[582]414 }
415 }
416 if (@fails) {
[628]417 $errstr = "Warning(s) adding $cidr to reverse DNS:\n".join("\n", @fails);
418 return ('WARN',$mid);
[582]419 }
420 }
[628]421 return ('OK',$mid);
[371]422 }
423} # end addMaster
424
425
[547]426## IPDB::touchMaster()
427# Update last-changed timestamp on a master block.
428sub touchMaster {
429 my $dbh = shift;
430 my $master = shift;
431
432 local $dbh->{AutoCommit} = 0;
433 local $dbh->{RaiseError} = 1;
434
435 eval {
436 $dbh->do("UPDATE masterblocks SET mtime=now() WHERE cidr = ?", undef, ($master));
437 $dbh->commit;
438 };
439
440 if ($@) {
441 my $msg = $@;
442 eval { $dbh->rollback; };
443 return ('FAIL',$msg);
444 }
445 return ('OK','OK');
446} # end touchMaster()
447
448
[523]449## IPDB::listSummary()
450# Get summary list of all master blocks
451# Returns an arrayref to a list of hashrefs containing the master block, routed count,
452# allocated count, free count, and largest free block masklength
453sub listSummary {
454 my $dbh = shift;
455
[625]456 my $mlist = $dbh->selectall_arrayref("SELECT cidr AS master,id,vrf FROM allocations ".
457 "WHERE type='mm' ORDER BY cidr",
458 { Slice => {} });
[523]459
460 foreach (@{$mlist}) {
[625]461 my ($rcnt) = $dbh->selectrow_array("SELECT count(*) FROM allocations WHERE cidr <<= ? AND type='rm' AND master_id = ?",
462 undef, ($$_{master}, $$_{id}));
[523]463 $$_{routed} = $rcnt;
[625]464 my ($acnt) = $dbh->selectrow_array("SELECT count(*) FROM allocations WHERE cidr <<= ? ".
465 "AND NOT type='rm' AND NOT type='mm' AND master_id = ?",
466 undef, ($$_{master}, $$_{id}));
[523]467 $$_{allocated} = $acnt;
[625]468 my ($fcnt) = $dbh->selectrow_array("SELECT count(*) FROM freeblocks WHERE cidr <<= ? AND master_id = ?",
469 undef, ($$_{master}, $$_{id}));
[523]470 $$_{free} = $fcnt;
[560]471 my ($bigfree) = $dbh->selectrow_array("SELECT masklen(cidr) AS maskbits FROM freeblocks WHERE cidr <<= ?".
[625]472 " AND master_id = ? ORDER BY masklen(cidr) LIMIT 1", undef, ($$_{master}, $$_{id}));
[523]473##fixme: should find a way to do this without having to HTMLize the <>
474 $bigfree = "/$bigfree" if $bigfree;
[525]475 $bigfree = '<NONE>' if !$bigfree;
[523]476 $$_{bigfree} = $bigfree;
477 }
478 return $mlist;
479} # end listSummary()
480
481
[561]482## IPDB::listSubs()
483# Get list of subnets within a specified CIDR block, on a specified VRF.
484# Returns an arrayref to a list of hashrefs containing the CIDR block, customer location or
485# city it's routed to, block type, SWIP status, and description
486sub listSubs {
487 my $dbh = shift;
488 my %args = @_;
489
490 # Just In Case
491 $args{vrf} = '' if !$args{vrf};
492
493 # Snag the allocations for this block
[627]494 my $sth = $dbh->prepare("SELECT cidr,city,type,custid,swip,description,id,master_id".
495 " FROM allocations WHERE parent_id = ? ORDER BY cidr");
496 $sth->execute($args{parent});
[561]497
498 # hack hack hack
499 # set up to flag swip=y records if they don't actually have supporting data in the customers table
500 my $custsth = $dbh->prepare("SELECT count(*) FROM customers WHERE custid = ?");
501
502 my @blocklist;
[627]503 while (my ($cidr,$city,$type,$custid,$swip,$desc,$id) = $sth->fetchrow_array()) {
[561]504 $custsth->execute($custid);
505 my ($ncust) = $custsth->fetchrow_array();
506 my %row = (
507 block => $cidr,
508 city => $city,
509 type => $disp_alloctypes{$type},
510 custid => $custid,
511 swip => ($swip eq 'y' ? 'Yes' : 'No'),
512 partswip => ($swip eq 'y' && $ncust == 0 ? 1 : 0),
513 desc => $desc,
514 hassubs => ($type eq 'rm' || $type =~ /.c/ ? 1 : 0),
[627]515 id => $id,
[561]516 );
517# $row{subblock} = ($type =~ /^.r$/); # hmf. wonder why these won't work in the hash declaration...
518 $row{listpool} = ($type =~ /^.[pd]$/);
519 push (@blocklist, \%row);
520 }
521 return \@blocklist;
522} # end listSubs()
523
524
[524]525## IPDB::listMaster()
526# Get list of routed blocks in the requested master
527# Returns an arrayref to a list of hashrefs containing the routed block, POP/city the block is routed to,
528# allocated count, free count, and largest free block masklength
529sub listMaster {
530 my $dbh = shift;
531 my $master = shift;
[523]532
[524]533 my $rlist = $dbh->selectall_arrayref("SELECT cidr AS block,city FROM routed WHERE cidr <<= ? ORDER BY cidr",
534 { Slice => {} }, ($master) );
[523]535
[524]536 foreach (@{$rlist}) {
537 my ($acnt) = $dbh->selectrow_array("SELECT count(*) FROM allocations WHERE cidr <<= ?", undef, ($$_{block}));
538 $$_{nsubs} = $acnt;
539 my ($fcnt) = $dbh->selectrow_array("SELECT count(*) FROM freeblocks WHERE cidr <<= ?".
540 " AND (routed='y' OR routed='n')", undef, ($$_{block}));
541 $$_{nfree} = $fcnt;
542 my ($bigfree) = $dbh->selectrow_array("SELECT maskbits FROM freeblocks WHERE cidr <<= ?".
543 " AND (routed='y' OR routed='n') ORDER BY maskbits LIMIT 1", undef, ($$_{block}));
544##fixme: should find a way to do this without having to HTMLize the <>
545 $bigfree = "/$bigfree" if $bigfree;
[525]546 $bigfree = '<NONE>' if !$bigfree;
[524]547 $$_{lfree} = $bigfree;
548 }
549 return $rlist;
550} # end listMaster()
551
552
[527]553## IPDB::listRBlock()
554# Gets a list of free blocks in the requested parent/master in both CIDR and range notation
555# Takes a parent/master and an optional flag to look at routed or unrouted blocks, depending
556# on whether the master is a direct master or a routed block
557# Returns an arrayref to a list of hashrefs containing the CIDR and range-notation blocks
558sub listRBlock {
559 my $dbh = shift;
560 my $routed = shift;
[524]561
[527]562 # Snag the allocations for this block
563 my $sth = $dbh->prepare("SELECT cidr,city,type,custid,swip,description".
564 " FROM allocations WHERE cidr <<= ? ORDER BY cidr");
565 $sth->execute($routed);
[524]566
[527]567 # hack hack hack
568 # set up to flag swip=y records if they don't actually have supporting data in the customers table
569 my $custsth = $dbh->prepare("SELECT count(*) FROM customers WHERE custid = ?");
570
571 my @blocklist;
572 while (my ($cidr,$city,$type,$custid,$swip,$desc) = $sth->fetchrow_array()) {
573 $custsth->execute($custid);
574 my ($ncust) = $custsth->fetchrow_array();
575 my %row = (
576 block => $cidr,
577 city => $city,
578 type => $disp_alloctypes{$type},
579 custid => $custid,
580 swip => ($swip eq 'y' ? 'Yes' : 'No'),
581 partswip => ($swip eq 'y' && $ncust == 0 ? 1 : 0),
582 desc => $desc
583 );
584 $row{subblock} = ($type =~ /^.r$/); # hmf. wonder why these won't work in the hash declaration...
585 $row{listpool} = ($type =~ /^.[pd]$/);
586 push (@blocklist, \%row);
587 }
588 return \@blocklist;
589} # end listRBlock()
590
591
[524]592## IPDB::listFree()
[562]593# Gets a list of free blocks in the requested parent/master and VRF instance in both CIDR and range notation
[630]594# Takes a parent/master ID and an optional VRF specifier that defaults to empty.
[524]595# Returns an arrayref to a list of hashrefs containing the CIDR and range-notation blocks
[527]596# Returns some extra flags in the hashrefs for routed blocks, since those can have several subtypes
[524]597sub listFree {
598 my $dbh = shift;
599
[562]600 my %args = @_;
601 # Just In Case
602 $args{vrf} = '' if !$args{vrf};
603
[630]604 my $sth = $dbh->prepare("SELECT cidr,id FROM freeblocks WHERE parent_id = ? ORDER BY cidr");
605# $sth->execute($args{parent}, $args{vrf});
606 $sth->execute($args{parent});
[524]607 my @flist;
[630]608 while (my ($cidr,$id) = $sth->fetchrow_array()) {
[524]609 $cidr = new NetAddr::IP $cidr;
[527]610 my %row = (
611 fblock => "$cidr",
612 frange => $cidr->range,
[630]613 fbid => $id,
614 fbparent => $args{parent},
[527]615 );
[524]616 push @flist, \%row;
617 }
618 return \@flist;
[527]619} # end listFree()
[524]620
621
[528]622## IPDB::listPool()
623#
624sub listPool {
625 my $dbh = shift;
626 my $pool = shift;
627
[630]628 my $sth = $dbh->prepare("SELECT ip,custid,available,description,type,id".
629 " FROM poolips WHERE parent_id = ? ORDER BY ip");
[528]630 $sth->execute($pool);
631 my @poolips;
[630]632 while (my ($ip,$custid,$available,$desc,$type,$id) = $sth->fetchrow_array) {
[528]633 my %row = (
634 ip => $ip,
635 custid => $custid,
636 available => $available,
637 desc => $desc,
[563]638 delme => $available eq 'n',
[630]639 parent => $pool,
640 id => $id,
[528]641 );
642 push @poolips, \%row;
643 }
644 return \@poolips;
645} # end listPool()
646
647
[541]648## IPDB::getMasterList()
649# Get a list of master blocks, optionally including last-modified timestamps
650# Takes an optional flag to indicate whether to include timestamps;
651# 'm' includes ctime, all others (suggest 'c') do not.
652# Returns an arrayref to a list of hashrefs
653sub getMasterList {
654 my $dbh = shift;
655 my $stampme = shift || 'm'; # optional but should be set by caller for clarity
656
[632]657 my $mlist = $dbh->selectall_arrayref("SELECT id,vrf,cidr AS master".($stampme eq 'm' ? ',modifystamp AS mtime' : '').
658 " FROM allocations WHERE type='mm' ORDER BY cidr", { Slice => {} });
[541]659 return $mlist;
660} # end getMasterList()
661
662
[529]663## IPDB::getTypeList()
664# Get an alloctype/description pair list suitable for dropdowns
665# Takes a flag to determine which general groups of types are returned
666# Returns an reference to an array of hashrefs
667sub getTypeList {
668 my $dbh = shift;
669 my $tgroup = shift || 'a'; # technically optional, like this, but should
670 # really be specified in the call for clarity
671 my $tlist;
[564]672 if ($tgroup eq 'n') {
673 # grouping 'p' - all netblock types. These include routed blocks, containers (_c)
674 # and contained (_r) types, dynamic-allocation ranges (_e), static IP pools (_d and _p),
675 # and the "miscellaneous" cn, in, and en types.
676 $tlist = $dbh->selectall_arrayref("SELECT type,listname FROM alloctypes WHERE listorder <= 500 ".
677 "AND type NOT LIKE '_i' ORDER BY listorder", { Slice => {} });
678 } elsif ($tgroup eq 'p') {
679 # grouping 'p' - primary allocation types. As with 'n' above but without the _r contained types.
680 $tlist = $dbh->selectall_arrayref("SELECT type,listname FROM alloctypes WHERE listorder <= 500 ".
[529]681 "AND type NOT LIKE '_i' AND type NOT LIKE '_r' ORDER BY listorder", { Slice => {} });
682 } elsif ($tgroup eq 'c') {
683 # grouping 'c' - contained types. These include all static IPs and all _r types.
684 $tlist = $dbh->selectall_arrayref("SELECT type,listname FROM alloctypes WHERE listorder <= 500 ".
685 " AND (type LIKE '_i' OR type LIKE '_r') ORDER BY listorder", { Slice => {} });
[632]686 } elsif ($tgroup eq 'i') {
687 # grouping 'i' - static IP types.
688 $tlist = $dbh->selectall_arrayref("SELECT type,listname FROM alloctypes WHERE listorder <= 500 ".
689 " AND type LIKE '_i' ORDER BY listorder", { Slice => {} });
[529]690 } else {
691 # grouping 'a' - all standard allocation types. This includes everything
692 # but mm (present only as a formality). Make this the default.
693 $tlist = $dbh->selectall_arrayref("SELECT type,listname FROM alloctypes WHERE listorder <= 500 ".
694 " ORDER BY listorder", { Slice => {} });
695 }
696 return $tlist;
697}
698
699
[532]700## IPDB::getPoolSelect()
701# Get a list of pools matching the passed city and type that have 1 or more free IPs
[533]702# Returns an arrayref to a list of hashrefs
[532]703sub getPoolSelect {
704 my $dbh = shift;
705 my $iptype = shift;
706 my $pcity = shift;
707
708 my ($ptype) = ($iptype =~ /^(.)i$/);
709 return if !$ptype;
710 $ptype .= '_';
711
712 my $plist = $dbh->selectall_arrayref(
[572]713 "SELECT count(*) AS poolfree,p.pool AS poolblock, a.city AS poolcit, a.rdepth AS poolrdepth ".
714 "FROM poolips p ".
715 "JOIN allocations a ON p.pool=a.cidr ".
716 "WHERE p.available='y' AND a.city = ? AND p.type LIKE ? ".
717 "GROUP BY p.pool,a.city,a.rdepth",
718 { Slice => {} }, ($pcity, $ptype) );
[532]719 return $plist;
720} # end getPoolSelect()
721
722
[533]723## IPDB::findAllocateFrom()
724# Find free block to add a new allocation from. (CIDR block version of pool select above, more or less)
725# Takes
726# - mask length
727# - allocation type
728# - POP city "parent"
729# - optional master-block restriction
730# - optional flag to allow automatic pick-from-private-network-ranges
731# Returns a string with the first CIDR block matching the criteria, if any
732sub findAllocateFrom {
733 my $dbh = shift;
734 my $maskbits = shift;
735 my $type = shift;
736 my $city = shift;
737 my $pop = shift;
738 my %optargs = @_;
739
740 my $failmsg = "No suitable free block found\n";
741
[633]742 my @vallist;
743 my $sql;
744
745 # Free pool IPs should be easy.
746 if ($type =~ /^.i$/) {
747 # User may get an IP from the wrong VRF. User should not be using admin tools to allocate static IPs.
748 $sql = "SELECT id, ip, parent_id FROM poolips WHERE ip = ?";
749 @vallist = ($optargs{gimme});
750 } else {
751
[533]752## Set up the SQL to find out what freeblock we can (probably) use for an allocation.
753## Very large systems will require development of a reserve system (possibly an extension
754## of the reserve-for-expansion concept in https://secure.deepnet.cx/trac/ipdb/ticket/24?)
755## Also populate a value list for the DBI call.
756
[633]757 @vallist = ($maskbits);
758 $sql = "SELECT id,cidr,parent_id FROM freeblocks WHERE masklen(cidr) <= ?";
[533]759
[572]760# cases, strict rules
761# .c -> container type
762# requires a routing container, fbtype r
763# .d -> DHCP/"normal-routing" static pool
764# requires a routing container, fbtype r
765# .e -> Dynamic-assignment connectivity
766# requires a routing container, fbtype r
767# .i -> error, can't allocate static IPs this way?
768# mm -> error, master block
769# rm -> routed block
770# requires master block, fbtype m
771# .n -> Miscellaneous usage
772# requires a routing container, fbtype r
773# .p -> PPP(oE) static pool
774# requires a routing container, fbtype r
775# .r -> contained type
776# requires a matching container, fbtype $1
777##fixme: strict-or-not flag
778
[633]779##fixme: config or UI flag for "Strict" mode
780# if ($strictmode) {
781if (0) {
[572]782 if ($type =~ /^(.)r$/) {
783 push @vallist, $1;
784 $sql .= " AND routed = ?";
785 } elsif ($type eq 'rm') {
786 $sql .= " AND routed = 'm'";
787 } else {
788 $sql .= " AND routed = 'r'";
789 }
[633]790}
[572]791
[633]792 # for PPP(oE) and container types, the POP city is the one attached to the pool.
793 # individual allocations get listed with the customer city site.
794 ##fixme: chain cities to align roughly with a full layer-2 node graph
795 $city = $pop if $type !~ /^.[pc]$/;
796 if ($type ne 'rm' && $city) {
797 $sql .= " AND city = ?";
798 push @vallist, $city;
[533]799 }
[633]800 # Allow specifying an arbitrary full block, instead of a master
801 if ($optargs{gimme}) {
802 $sql .= " AND cidr >>= ?";
803 push @vallist, $optargs{gimme};
804 }
805 # if a specific master was requested, allow the requestor to self->shoot(foot)
806 if ($optargs{master} && $optargs{master} ne '-') {
807 $sql .= " AND master_id = ?";
808# if $optargs{master} ne '-';
809 push @vallist, $optargs{master};
810 } else {
811 # if a specific master was NOT requested, filter out the RFC 1918 private networks
812 if (!$optargs{allowpriv}) {
813 $sql .= " AND NOT (cidr <<= '192.168.0.0/16' OR cidr <<= '10.0.0.0/8' OR cidr <<= '172.16.0.0/12')";
814 }
815 }
816 # Sorting and limiting, since we don't (currently) care to provide a selection of
817 # blocks to carve up. This preserves something resembling optimal usage of the IP
818 # space by forcing contiguous allocations and free blocks as much as possible.
819 $sql .= " ORDER BY masklen(cidr) DESC,cidr LIMIT 1";
820 } # done setting up SQL for free CIDR block
[533]821
[633]822 my ($fbid,$fbfound,$fbparent) = $dbh->selectrow_array($sql, undef, @vallist);
823 return $fbid,$fbfound,$fbparent;
[533]824} # end findAllocateFrom()
825
826
[536]827## IPDB::ipParent()
828# Get an IP's parent pool's details
829# Takes a database handle and IP
830# Returns a hashref to the parent pool block, if any
831sub ipParent {
832 my $dbh = shift;
833 my $block = shift;
834
835 my $pinfo = $dbh->selectrow_hashref("SELECT cidr,custid,type,city,description FROM allocations".
[565]836 " WHERE cidr >>= ? AND (type LIKE '_p' OR type LIKE '_d')", undef, ($block) );
[536]837 return $pinfo;
838} # end ipParent()
839
840
841## IPDB::subParent()
[529]842# Get a block's parent's details
843# Takes a database handle and CIDR block
[536]844# Returns a hashref to the parent container block, if any
845sub subParent {
[529]846 my $dbh = shift;
847 my $block = shift;
848
849 my $pinfo = $dbh->selectrow_hashref("SELECT cidr,custid,type,city,description FROM allocations".
850 " WHERE cidr >>= ?", undef, ($block) );
851 return $pinfo;
[536]852} # end subParent()
[529]853
854
[536]855## IPDB::blockParent()
856# Get a block's parent's details
857# Takes a database handle and CIDR block
858# Returns a hashref to the parent container block, if any
859sub blockParent {
860 my $dbh = shift;
861 my $block = shift;
862
863 my $pinfo = $dbh->selectrow_hashref("SELECT cidr,city FROM routed".
864 " WHERE cidr >>= ?", undef, ($block) );
865 return $pinfo;
866} # end blockParent()
867
868
[527]869## IPDB::getRoutedCity()
870# Get the city for a routed block.
871sub getRoutedCity {
872 my $dbh = shift;
873 my $block = shift;
874
875 my ($rcity) = $dbh->selectrow_array("SELECT city FROM routed WHERE cidr = ?", undef, ($block) );
876 return $rcity;
877} # end getRoutedCity()
878
879
[77]880## IPDB::allocateBlock()
[66]881# Does all of the magic of actually allocating a netblock
[554]882# Requires a database handle, and a hash containing the block to allocate, routing depth, custid,
883# type, city, block to allocate from, and optionally a description, notes, circuit ID,
884# and private data
[77]885# Returns a success code and optional error message.
886sub allocateBlock {
[554]887 my $dbh = shift;
[284]888
[554]889 my %args = @_;
890
891 $args{cidr} = new NetAddr::IP $args{cidr};
892
893 $args{desc} = '' if !$args{desc};
894 $args{notes} = '' if !$args{notes};
895 $args{circid} = '' if !$args{circid};
896 $args{privdata} = '' if !$args{privdata};
897 $args{vrf} = '' if !$args{vrf};
[585]898 $args{rdns} = '' if !$args{rdns};
[554]899
[77]900 my $sth;
[66]901
[633]902 # Snag the "type" of the freeblock and its CIDR
903 my ($alloc_from_type, $alloc_from, $fbparent, $fcity, $fbmaster) =
904 $dbh->selectrow_array("SELECT routed,cidr,parent_id,city,master_id FROM freeblocks WHERE id = ?",
905 undef, $args{fbid});
906 $alloc_from = new NetAddr::IP $alloc_from;
[349]907
[79]908 # To contain the error message, if any.
[554]909 my $msg = "Unknown error allocating $args{cidr} as '$disp_alloctypes{$args{type}}'";
[79]910
[77]911 # Enable transactions and error handling
912 local $dbh->{AutoCommit} = 0; # These need to be local so we don't
913 local $dbh->{RaiseError} = 1; # step on our toes by accident.
[66]914
[554]915 if ($args{type} =~ /^.i$/) {
916 $msg = "Unable to assign static IP $args{cidr} to $args{custid}";
[77]917 eval {
[554]918 if ($args{cidr}) { # IP specified
919 my ($isavail) = $dbh->selectrow_array("SELECT available FROM poolips WHERE ip=?", undef, ($args{cidr}) );
920 die "IP is not in an IP pool.\n"
921 if !$isavail;
922 die "IP already allocated. Deallocate and reallocate, or update the entry\n"
923 if $isavail eq 'n';
924 } else { # IP not specified, take first available
925 ($args{cidr}) = $dbh->selectrow_array("SELECT ip FROM poolips WHERE pool=? AND available='y' ORDER BY ip",
926 undef, ($args{alloc_from}) );
[545]927 }
[633]928 $dbh->do("UPDATE poolips SET custid = ?, city = ?,available='n', description = ?, notes = ?, ".
929 "circuitid = ?, privdata = ?, vrf = ?, rdns = ? ".
930 "WHERE ip = ? AND parent_id = ?", undef,
931 ($args{custid}, $args{city}, $args{desc}, $args{notes},
932 $args{circid}, $args{privdata}, $args{vrf}, $args{rdns},
933 $args{cidr}, $args{parent}) );
[157]934
[397]935# node hack
[554]936 if ($args{nodeid} && $args{nodeid} ne '') {
937 $dbh->do("INSERT INTO noderef (block,node_id) VALUES (?,?)", undef, ($args{cidr}, $args{nodeid}) );
[397]938 }
939# end node hack
[545]940
[79]941 $dbh->commit;
[77]942 };
943 if ($@) {
[545]944 $msg .= ": $@";
[78]945 eval { $dbh->rollback; };
[578]946 return ('FAIL', $msg);
[77]947 } else {
[585]948 _rpc('addOrUpdateRevRec', cidr => "$args{cidr}", name => $args{rdns}, rpcuser => $args{user});
[578]949 return ('OK', $args{cidr});
[77]950 }
951
952 } else { # end IP-from-pool allocation
953
[633]954 if ($args{cidr} == $alloc_from) {
[77]955 # Easiest case- insert in one table, delete in the other, and go home. More or less.
956 # insert into allocations values (cidr,custid,type,city,desc) and
957 # delete from freeblocks where cidr='cidr'
958 # For data safety on non-transaction DBs, we delete first.
959
960 eval {
[554]961 $msg = "Unable to allocate $args{cidr} as '$disp_alloctypes{$args{type}}'";
962
[633]963 # Insert the allocations entry
964 $dbh->do("INSERT INTO allocations ".
965 "(cidr,parent_id,master_id,vrf,custid,type,city,description,notes,circuitid,privdata,rdns)".
966 " VALUES (?,?,?,?,?,?,?,?,?,?,?,?)", undef,
967 ($args{cidr}, $fbparent, $fbmaster, $args{vrf}, $args{custid}, $args{type}, $args{city},
968 $args{desc}, $args{notes}, $args{circid}, $args{privdata}, $args{rdns}) );
969 my ($bid) = $dbh->selectrow_array("SELECT currval('allocations_id_seq')");
[555]970
[554]971 # Munge freeblocks
972 if ($args{type} =~ /^(.)[mc]$/) {
973 # special case - block is a routed or container/"reserve" block
974 my $rtype = $1;
[633]975 $dbh->do("UPDATE freeblocks SET routed = ?,city = ?,parent_id = ? WHERE id = ?",
976 undef, ($rtype, $args{city}, $bid, $args{fbid}) );
[77]977 } else {
[554]978 # "normal" case
[633]979 $dbh->do("DELETE FROM freeblocks WHERE id = ?", undef, ($args{fbid}) );
[554]980 }
[77]981
[554]982 # And initialize the pool, if necessary
983 # PPPoE pools (currently dialup, DSL, and WiFi) get all IPs made available
984 # "DHCP" or "real-subnet" pools have the net, gw, and bcast IPs removed.
985 if ($args{type} =~ /^.p$/) {
986 $msg = "Could not initialize IPs in new $disp_alloctypes{$args{type}} $args{cidr}";
[633]987 my ($code,$rmsg) = initPool($dbh, $args{cidr}, $args{type}, $args{city}, "all", $bid);
[554]988 die $rmsg if $code eq 'FAIL';
989 } elsif ($args{type} =~ /^.d$/) {
990 $msg = "Could not initialize IPs in new $disp_alloctypes{$args{type}} $args{cidr}";
[633]991 my ($code,$rmsg) = initPool($dbh, $args{cidr}, $args{type}, $args{city}, "normal", $bid);
[554]992 die $rmsg if $code eq 'FAIL';
993 }
[79]994
[397]995# node hack
[554]996 if ($args{nodeid} && $args{nodeid} ne '') {
997 $dbh->do("INSERT INTO noderef (block,node_id) VALUES (?,?)", undef, ($args{cidr}, $args{nodeid}) );
[397]998 }
999# end node hack
[574]1000
[77]1001 $dbh->commit;
[78]1002 }; # end of eval
[77]1003 if ($@) {
[157]1004 $msg .= ": ".$@;
[77]1005 eval { $dbh->rollback; };
[157]1006 return ('FAIL',$msg);
[78]1007 }
[77]1008
1009 } else { # cidr != alloc_from
1010
1011 # Hard case. Allocation is smaller than free block.
[633]1012
1013 # make sure new allocation is in fact within freeblock. *sigh*
1014 return ('FAIL',"Requested allocation $args{cidr} is not within $alloc_from")
1015 if !$alloc_from->contains($args{cidr});
[554]1016 my $wantmaskbits = $args{cidr}->masklen;
[633]1017 my $maskbits = $alloc_from->masklen;
[77]1018
1019 my @newfreeblocks; # Holds free blocks generated from splitting the source freeblock.
1020
1021 # This determines which blocks will be left "free" after allocation. We take the
1022 # block we're allocating from, and split it in half. We see which half the wanted
1023 # block is in, and repeat until the wanted block is equal to one of the halves.
1024 my $i=0;
[633]1025 my $tmp_from = $alloc_from; # So we don't munge $args{alloc_from}
[77]1026 while ($maskbits++ < $wantmaskbits) {
1027 my @subblocks = $tmp_from->split($maskbits);
[554]1028 $newfreeblocks[$i++] = (($args{cidr}->within($subblocks[0])) ? $subblocks[1] : $subblocks[0]);
1029 $tmp_from = ( ($args{cidr}->within($subblocks[0])) ? $subblocks[0] : $subblocks[1] );
[77]1030 } # while
1031
1032 # Begin SQL transaction block
1033 eval {
[554]1034 $msg = "Unable to allocate $args{cidr} as '$disp_alloctypes{$args{type}}'";
[79]1035
[77]1036 # Delete old freeblocks entry
[633]1037 $dbh->do("DELETE FROM freeblocks WHERE id = ?", undef, ($args{fbid}) );
[77]1038
[554]1039 # Insert new list of smaller free blocks left over
[633]1040 $sth = $dbh->prepare("INSERT INTO freeblocks (cidr,city,routed,vrf,parent_id,master_id) VALUES (?,?,?,?,?,?)");
[554]1041 foreach my $block (@newfreeblocks) {
[633]1042 $sth->execute($block, $fcity, $alloc_from_type, $args{vrf}, $fbparent, $fbmaster);
[554]1043 }
[79]1044
[633]1045 # Insert the allocations entry
1046 $dbh->do("INSERT INTO allocations ".
1047 "(cidr,parent_id,master_id,vrf,custid,type,city,description,notes,circuitid,privdata,rdns)".
1048 " VALUES (?,?,?,?,?,?,?,?,?,?,?,?)", undef,
1049 ($args{cidr}, $fbparent, $fbmaster, $args{vrf}, $args{custid}, $args{type}, $args{city},
1050 $args{desc}, $args{notes}, $args{circid}, $args{privdata}, $args{rdns}) );
1051 my ($bid) = $dbh->selectrow_array("SELECT currval('allocations_id_seq')");
1052
[554]1053 # For routed/container types, add a freeblock within the allocated block so we can subdivide it further
1054 if ($args{type} =~ /(.)[mc]/) { # rm and .c types - containers
1055 my $rtype = $1;
[633]1056 $sth->execute($args{cidr}, $args{city}, $rtype, $args{vrf}, $bid, $fbmaster);
[554]1057 }
[79]1058
[554]1059 # And initialize the pool, if necessary
1060 # PPPoE pools (currently dialup, DSL, and WiFi) get all IPs made available
1061 # "DHCP" or "real-subnet" pools have the net, gw, and bcast IPs removed.
1062 if ($args{type} =~ /^.p$/) {
1063 $msg = "Could not initialize IPs in new $disp_alloctypes{$args{type}} $args{cidr}";
[633]1064 my ($code,$rmsg) = initPool($dbh, $args{cidr}, $args{type}, $args{city}, "all", $bid);
[554]1065 die $rmsg if $code eq 'FAIL';
1066 } elsif ($args{type} =~ /^.d$/) {
1067 $msg = "Could not initialize IPs in new $disp_alloctypes{$args{type}} $args{cidr}";
[633]1068 my ($code,$rmsg) = initPool($dbh, $args{cidr}, $args{type}, $args{city}, "normal", $bid);
[554]1069 die $rmsg if $code eq 'FAIL';
1070 }
[77]1071
[397]1072# node hack
[554]1073 if ($args{nodeid} && $args{nodeid} ne '') {
1074 $dbh->do("INSERT INTO noderef (block,node_id) VALUES (?,?)", undef, ($args{cidr}, $args{nodeid}) );
[397]1075 }
1076# end node hack
[554]1077
[77]1078 $dbh->commit;
1079 }; # end eval
1080 if ($@) {
[256]1081 $msg .= ": ".$@;
[77]1082 eval { $dbh->rollback; };
[78]1083 return ('FAIL',$msg);
[77]1084 }
1085
1086 } # end fullcidr != alloc_from
1087
[590]1088 # now we do the DNS dance for netblocks, if we have an RPC server to do it with and a pattern to use.
1089 _rpc('addOrUpdateRevRec', cidr => "$args{cidr}", name => $args{rdns}, rpcuser => $args{user})
1090 if $args{rdns};
[585]1091
1092 return ('OK', 'OK');
1093
[77]1094 } # end static-IP vs netblock allocation
1095
1096} # end allocateBlock()
1097
1098
1099## IPDB::initPool()
1100# Initializes a pool
1101# Requires a database handle, the pool CIDR, type, city, and a parameter
1102# indicating whether the pool should allow allocation of literally every
1103# IP, or if it should reserve network/gateway/broadcast IPs
[78]1104# Note that this is NOT done in a transaction, that's why it's a private
1105# function and should ONLY EVER get called from allocateBlock()
[77]1106sub initPool {
[633]1107 my ($dbh,undef,$type,$city,$class,$parent) = @_;
[77]1108 my $pool = new NetAddr::IP $_[1];
1109
[574]1110 # IPv6 does not lend itself to IP pools as supported
1111 return ('FAIL',"Refusing to create IPv6 static IP pool") if $pool->{isv6};
1112 # IPv4 pools don't make much sense beyond even /24. Allow up to 4096-host footshooting anyway.
1113 # NetAddr::IP won't allow more than a /16 (65k hosts).
1114 return ('FAIL',"Refusing to create oversized static IP pool") if $pool->masklen <= 20;
1115
[633]1116 my ($pcustid) = $dbh->selectrow_array("SELECT def_custid FROM alloctypes WHERE type=?", undef, ($type) );
[157]1117 $type =~ s/[pd]$/i/;
[77]1118 my $sth;
[157]1119 my $msg;
[77]1120
[157]1121 # Trap errors so we can pass them back to the caller. Even if the
1122 # caller is only ever supposed to be local, and therefore already
1123 # trapping errors. >:(
1124 local $dbh->{AutoCommit} = 0; # These need to be local so we don't
1125 local $dbh->{RaiseError} = 1; # step on our toes by accident.
1126
1127 eval {
1128 # have to insert all pool IPs into poolips table as "unallocated".
[633]1129 $sth = $dbh->prepare("INSERT INTO poolips (ip,custid,city,type,parent_id) VALUES (?,?,?,?,?)");
[157]1130 my @poolip_list = $pool->hostenum;
1131 if ($class eq 'all') { # (DSL-ish block - *all* IPs available
[246]1132 if ($pool->addr !~ /\.0$/) { # .0 causes weirdness.
[633]1133 $sth->execute($pool->addr, $pcustid, $city, $type, $parent);
[246]1134 }
[157]1135 for (my $i=0; $i<=$#poolip_list; $i++) {
[633]1136 $sth->execute($poolip_list[$i]->addr, $pcustid, $city, $type, $parent);
[157]1137 }
1138 $pool--;
[246]1139 if ($pool->addr !~ /\.255$/) { # .255 can cause weirdness.
[633]1140 $sth->execute($pool->addr, $pcustid, $city, $type, $parent);
[246]1141 }
[157]1142 } else { # (real netblock)
1143 for (my $i=1; $i<=$#poolip_list; $i++) {
[633]1144 $sth->execute($poolip_list[$i]->addr, $pcustid, $city, $type, $parent);
[157]1145 }
[77]1146 }
[633]1147# don't commit here! the caller may not be done.
1148# $dbh->commit;
[157]1149 };
1150 if ($@) {
[574]1151 $msg = $@;
[633]1152# Don't roll back! It's up to the caller to handle this.
1153# eval { $dbh->rollback; };
[157]1154 return ('FAIL',$msg);
1155 } else {
1156 return ('OK',"OK");
[77]1157 }
1158} # end initPool()
1159
1160
[531]1161## IPDB::updateBlock()
1162# Update an allocation
1163# Takes all allocation fields in a hash
1164sub updateBlock {
1165 my $dbh = shift;
1166 my %args = @_;
1167
1168 return ('FAIL', 'Missing block to update') if !$args{block};
1169
[634]1170 # Spaces don't show up well in lots of places. Make sure they don't get into the DB.
1171 $args{custid} =~ s/^\s+//;
1172 $args{custid} =~ s/\s+$//;
1173
[531]1174 # do it all in a transaction
1175 local $dbh->{AutoCommit} = 0;
1176 local $dbh->{RaiseError} = 1;
1177
1178 my @fieldlist;
1179 my @vallist;
[588]1180 foreach ('custid', 'city', 'description', 'notes', 'circuitid', 'privdata', 'rdns') {
[531]1181 if ($args{$_}) {
1182 push @fieldlist, $_;
1183 push @vallist, $args{$_};
1184 }
1185 }
1186
[634]1187 my $binfo;
[531]1188 my $updtable = 'allocations';
[634]1189 my $keyfield = 'id';
[535]1190 if ($args{type} =~ /^(.)i$/) {
[531]1191 $updtable = 'poolips';
[634]1192 $binfo = getBlockData($dbh, $args{block}, 'i');
[531]1193 } else {
1194## fixme: there's got to be a better way...
[634]1195 $binfo = getBlockData($dbh, $args{block});
[531]1196 if ($args{swip}) {
1197 if ($args{swip} eq 'on' || $args{swip} eq '1' || $args{swip} eq 'y') {
1198 $args{swip} = 'y';
1199 } else {
1200 $args{swip} = 'n';
1201 }
1202 }
1203 foreach ('type', 'swip') {
1204 if ($args{$_}) {
1205 push @fieldlist, $_;
1206 push @vallist, $args{$_};
1207 }
1208 }
1209 }
1210
1211 return ('FAIL', 'No fields to update') if !@fieldlist;
1212
[634]1213 push @vallist, $args{block};
[531]1214 my $sql = "UPDATE $updtable SET ";
1215 $sql .= join " = ?, ", @fieldlist;
[634]1216 $sql .= " = ? WHERE $keyfield = ?";
[531]1217
1218 eval {
1219 # do the update
1220 $dbh->do($sql, undef, @vallist);
1221
1222 if ($args{node}) {
1223 # done with delete/insert so we don't have to worry about funkyness updating a node ref that isn't there
[634]1224 $dbh->do("DELETE FROM noderef WHERE block = ?", undef, ($binfo->{block}) );
1225 $dbh->do("INSERT INTO noderef (block,node_id) VALUES (?,?)", undef, ($binfo->{block}, $args{node}) )
1226 if $args{node} ne '--';
[531]1227 }
1228
1229 $dbh->commit;
1230 };
1231 if ($@) {
1232 my $msg = $@;
1233 $dbh->rollback;
1234 return ('FAIL', $msg);
1235 }
[588]1236
[634]1237 $binfo->{block} =~ s|/32$||;
1238 _rpc('addOrUpdateRevRec', cidr => $binfo->{block}, name => $args{rdns}, rpcuser => $args{user});
[588]1239 return ('OK','OK');
[531]1240} # end updateBlock()
1241
1242
[93]1243## IPDB::deleteBlock()
1244# Removes an allocation from the database, including deleting IPs
1245# from poolips and recombining entries in freeblocks if possible
1246# Also handles "deleting" a static IP allocation, and removal of a master
[558]1247# Requires a database handle, the block to delete, the routing depth (if applicable),
[590]1248# the VRF ID, and a flag to indicate whether to delete associated forward DNS entries
1249# as well as the reverse entry
[93]1250sub deleteBlock {
[638]1251 my ($dbh,$id,$basetype,$delfwd,$user) = @_;
[93]1252
[638]1253 # Collect info about the block we're going to delete
1254 my $binfo = getBlockData($dbh, $id, $basetype);
1255 my $cidr = new NetAddr::IP $binfo->{block};
1256
[558]1257# For possible auto-VRF-ignoring (since public IPs shouldn't usually be present in more than one VRF)
1258# is_rfc1918 requires NetAddr::IP >= 4.059
1259# rather than doing this over and over and over.....
1260 my $tmpnum = $cidr->numeric;
1261# 192.168.0.0/16 -> 192.168.255.255 => 3232235520 -> 3232301055
1262# 172.16.0.0/12 -> 172.31.255.255 => 2886729728 -> 2887778303
1263# 10.0.0.0/8 -> 10.255.255.255 => 167772160 -> 184549375
1264 my $isprivnet = (3232235520 <= $tmpnum && $tmpnum <= 3232301055) ||
1265 (2886729728 <= $tmpnum && $tmpnum <= 2887778303) ||
1266 (167772160 <= $tmpnum && $tmpnum <= 184549375);
1267
[93]1268 my $sth;
1269
[349]1270 # Magic variables used for odd allocation cases.
1271 my $container;
1272 my $con_type;
1273
[558]1274
1275 # temporarily forced null, until a sane UI for VRF tracking can be found.
[638]1276# $vrf = '';# if !$vrf; # as with SQL, the null value is not equal to ''. *sigh*
[558]1277
[93]1278 # To contain the error message, if any.
[558]1279 my $msg = "Unknown error deallocating $binfo->{type} $cidr";
1280 my $goback; # to put the parent in so we can link back where the deallocate started
1281
[93]1282 # Enable transactions and exception-on-errors... but only for this sub
1283 local $dbh->{AutoCommit} = 0;
1284 local $dbh->{RaiseError} = 1;
1285
[558]1286 if ($binfo->{type} =~ /^.i$/) {
[638]1287 # First case. The "block" is a static IP
1288 # Note that we still need some additional code in the odd case
1289 # of a netblock-aligned contiguous group of static IPs
[93]1290
1291 eval {
[558]1292 $msg = "Unable to deallocate $disp_alloctypes{$binfo->{type}} $cidr";
[638]1293 my $pinfo = getBlockData($dbh, $binfo->{parent_id}, 'b');
[558]1294##fixme: VRF and rdepth
[638]1295 $dbh->do("UPDATE poolips SET custid = ?, available = 'y',".
1296 "city = (SELECT city FROM allocations WHERE id = ?),".
1297 "description = '', notes = '', circuitid = '', vrf = ? WHERE id = ?", undef,
1298 ($pinfo->{custid}, $binfo->{parent_id}, $pinfo->{vrf}, $id) );
[93]1299 $dbh->commit;
1300 };
1301 if ($@) {
[558]1302 $msg .= ": $@";
[93]1303 eval { $dbh->rollback; };
1304 return ('FAIL',$msg);
1305 } else {
[590]1306##fixme: RPC return code?
[638]1307 _rpc('delByCIDR', cidr => "$cidr", user => $user, delforward => $delfwd, rpcuser => $user);
[93]1308 return ('OK',"OK");
1309 }
1310
[558]1311 } elsif ($binfo->{type} eq 'mm') { # end alloctype =~ /.i/
[638]1312 # Second case. The block is a full master block
[93]1313
[558]1314##fixme: VRF limit
[93]1315 $msg = "Unable to delete master block $cidr";
1316 eval {
[638]1317 $dbh->do("DELETE FROM allocations WHERE cidr <<= ? AND master_id = ?", undef, ($cidr, $binfo->{master_id}) );
1318 $dbh->do("DELETE FROM freeblocks WHERE cidr <<= ? AND master_id = ?", undef, ($cidr, $binfo->{master_id}) );
[93]1319 $dbh->commit;
1320 };
1321 if ($@) {
[558]1322 $msg .= ": $@";
[93]1323 eval { $dbh->rollback; };
1324 return ('FAIL', $msg);
[591]1325 }
1326
1327 # Have to handle potentially split reverse zones. Assume they *are* split,
1328 # since if we added them here, they would have been added split.
1329# allow splitting reverse zones to be disabled, maybe, someday
1330#if ($splitrevzones && !$cidr->{isv6}) {
1331 my @zonelist;
1332 if (1 && !$cidr->{isv6}) {
1333 my $splitpoint = ($cidr->masklen <= 16 ? 16 : 24); # hack pthui
1334 @zonelist = $cidr->split($splitpoint);
[93]1335 } else {
[591]1336 @zonelist = ($cidr);
[93]1337 }
[591]1338 my @fails;
1339 foreach my $subzone (@zonelist) {
[638]1340 if ($rpc_url && !_rpc('delZone', zone => "$subzone", revrec => 'y', rpcuser => $user, delforward => $delfwd) ) {
[591]1341 push @fails, ("$subzone" => $errstr);
1342 }
1343 }
1344 if (@fails) {
1345 return ('WARN',"Warning(s) deleting $cidr from reverse DNS:\n".join("\n", @fails));
1346 }
1347 return ('OK','OK');
[93]1348
1349 } else { # end alloctype master block case
1350
1351 ## This is a big block; but it HAS to be done in a chunk. Any removal
1352 ## of a netblock allocation may result in a larger chunk of free
1353 ## contiguous IP space - which may in turn be combined into a single
1354 ## netblock rather than a number of smaller netblocks.
1355
[558]1356 my $retcode = 'OK';
[638]1357 my ($ptype,$pcity,$ppatt,$p_id);
[558]1358
[93]1359 eval {
1360
[558]1361##fixme: add recursive flag to allow "YES DAMMIT DELETE ALL EVARYTHING!!1!!" without
1362# explicitly deleting any suballocations of the block to be deleted.
[93]1363
[638]1364 # get parent info of the block we're deleting
1365 my $pinfo = getBlockData($dbh, $binfo->{parent_id});
1366 $ptype = $pinfo->{type};
1367 $pcity = $pinfo->{city};
1368 $ppatt = $pinfo->{rdns};
1369 $p_id = $binfo->{parent_id};
[93]1370
[558]1371 # Delete the block
[638]1372 $dbh->do("DELETE FROM allocations WHERE id = ?", undef, ($id) );
[349]1373
[558]1374 # munge the parent type a little
[638]1375 $ptype = (split //, $ptype)[1];
[93]1376
[558]1377##fixme: you can't... CAN NOT.... assign the same public IP to multiple things.
1378# 'Net don't work like that, homey. Restrict VRF-uniqueness to private IPs?
1379# -> $isprivnet flag from start of sub
[93]1380
[558]1381 # check to see if any container allocations could be the "true" parent
[638]1382 my ($tparent,$tpar_id,$trtype,$tcity);
1383 $tpar_id = 0;
[404]1384
[638]1385##fixme: this is far simpler in the strict VRF case; we "know" that any allocation
1386# contained by a container is a part of the same allocation tree when the VRF fields are equal.
[558]1387
[638]1388# logic:
1389# For each possible container of $cidr
1390# note the parent id
1391# walk the chain up the parents
1392# if we intersect $cidr's current parent, break
1393# if we've intersected $cidr's current parent
1394# set some variables to track that block
1395# break
[558]1396
[638]1397# Set up part of "is it in the middle of a pool?" check
1398 my $wuzpool = $dbh->selectrow_hashref("SELECT cidr,parent_id,type,city,custid,id FROM allocations ".
1399 "WHERE (type LIKE '_d' OR type LIKE '_p') AND cidr >> ? AND master_id = ?", { Slice => {} },
1400 ($cidr, $binfo->{master_id}) );
[558]1401
[638]1402##fixme?
1403# edge cases not handled, or handled badly:
1404# -> $cidr managed to get to be the entirety of an IP pool
[558]1405
[638]1406 if ($wuzpool && $wuzpool->{id} != $id) {
1407 # we have legacy goo to be purified
1408 # going to ignore nested pools; not possible to create them via API and no current legacy data includes any.
1409
1410 # for convenience
1411 my $poolid = $wuzpool->{id};
1412 my $pool = $wuzpool->{cidr};
1413 my $poolcity = $wuzpool->{city};
1414 my $pooltype = $wuzpool->{type};
1415 my $poolcustid = $wuzpool->{custid};
1416
1417 $retcode = 'WARNPOOL';
1418 $goback = "$poolid,$pool";
1419 # We've already deleted the block, now we have to stuff its IPs into the pool.
1420 $pooltype =~ s/[dp]$/i/; # change type to static IP
1421 my $sth2 = $dbh->prepare("INSERT INTO poolips (ip,city,type,custid,parent_id) VALUES ".
1422 "(?,'$poolcity','$pooltype','$poolcustid',$poolid)");
[429]1423##fixme: need to not insert net, gateway, and bcast on "real netblock" pools (DHCPish)
[638]1424 # don't insert .0
1425 $sth2->execute($cidr->addr) unless $cidr->addr =~ m|\.0$|;
1426 foreach my $ip ($cidr->hostenum) {
1427 $sth2->execute($ip);
1428 }
1429 $cidr--;
1430 # don't insert .255
1431 $sth2->execute($cidr->addr) unless $cidr->addr =~ m|\.255$|;
1432 }
[93]1433
[638]1434## important!
1435# ... or IS IT?
1436# we may have undef'ed $wuzpool above, if the allocation tree $cidr is in doesn't intersect the pool we found
1437#if (!$wuzpool) {
1438
1439 else {
1440
1441 # Get all possible (and probably a number of impossible) containers for $cidr
1442 $sth = $dbh->prepare("SELECT cidr,parent_id,type,city,id FROM allocations ".
1443 "WHERE (type LIKE '_m' OR type LIKE '_c') AND cidr >>= ? AND master_id = ? ".
1444 "ORDER BY masklen(cidr) DESC");
1445 $sth->execute($cidr, $binfo->{master_id});
1446
1447 # Quickly get certain fields (simpler than getBlockData()
1448 my $sth2 = $dbh->prepare("SELECT cidr,parent_id,type,city FROM allocations ".
1449 "WHERE (type LIKE '_m' OR type LIKE '_c') AND id = ? AND master_id = ?");
1450
1451 # For each possible container of $cidr...
1452 while (my @data = $sth->fetchrow_array) {
1453 my $i = 0;
1454 # Save some state and set a start point - parent ID of container we're checking
1455 $tparent = $data[0];
1456 my $ppid = $data[1];
1457 $trtype = $data[2];
1458 $tcity = $data[3];
1459 $tpar_id = $data[4];
1460 last if $data[4] == $binfo->{parent_id}; # Preemptively break if we're already in the right place
1461 last if $ppid == $binfo->{parent_id}; # ... or if the parent of the container is the block's parent
1462 while (1) {
1463 # Retrieve bits on that parent ID
1464 $sth2->execute($ppid, $binfo->{master_id});
1465 my @container = $sth2->fetchrow_array;
1466 $ppid = $container[1];
1467 last if $container[1] == 0; # Break if we've hit a master block
1468 last if $ppid == $binfo->{parent_id}; # Break if we've reached the block $cidr is currently in
1469 }
1470 last if $ppid == $binfo->{parent_id};
1471 }
1472
1473 # found an alternate parent; reset some parent-info bits
1474 if ($tpar_id != $binfo->{parent_id}) {
1475 $ptype = (split //, $trtype)[1];
1476 $pcity = $tcity;
1477 $retcode = 'WARNMERGE'; # may be redundant
1478 $p_id = $tpar_id;
1479 }
1480
1481 $goback = "$p_id,$tparent"; # breadcrumb, currently only used in case of live-parent-is-not-true-parent
1482
1483 # Special case - delete pool IPs
1484 if ($binfo->{type} =~ /^.[pd]$/) {
1485 # We have to delete the IPs from the pool listing.
1486 $dbh->do("DELETE FROM poolips WHERE parent_id = ?", undef, ($id) );
1487 }
1488
1489 $pinfo = getBlockData($dbh, $p_id);
1490
[558]1491 # If the block wasn't legacy goo embedded in a static pool, we check the
1492 # freeblocks in the identified parent to see if we can combine any of them.
[93]1493
[559]1494 # if the block to be deleted is a container, move its freeblock(s) up a level, and reset their parenting info
1495 if ($binfo->{type} =~ /^.[mc]/) {
1496 # move the freeblocks into the parent
1497 # we don't insert a new freeblock because there could be a live reparented sub.
[638]1498 $dbh->do("UPDATE freeblocks SET parent_id = ?, routed = ?, city = ? WHERE parent_id = ?", undef,
1499 ($p_id, $ptype, $pcity, $id) );
[559]1500 } else {
1501 # ... otherwise, add the freeblock
[638]1502 $dbh->do("INSERT INTO freeblocks (cidr, city, routed, parent_id, master_id) VALUES (?,?,?,?,?)", undef,
1503 ($cidr, $pcity, $ptype, $p_id, $binfo->{master_id}) );
[559]1504 }
1505
[558]1506##fixme: vrf
[638]1507##fixme: simplify since all containers now represent different "layers"/"levels"?
[558]1508 # set up the query to get the list of blocks to try to merge.
[638]1509 $sth = $dbh->prepare("SELECT cidr,id FROM freeblocks ".
1510 "WHERE parent_id = ? ".
[558]1511 "ORDER BY masklen(cidr) DESC");
[428]1512
[638]1513 $sth->execute($p_id);
[558]1514
[93]1515# NetAddr::IP->compact() attempts to produce the smallest inclusive block
1516# from the caller and the passed terms.
1517# EG: if you call $cidr->compact($ip1,$ip2,$ip3) when $cidr, $ip1, $ip2,
1518# and $ip3 are consecutive /27's starting on .0 (.0-.31, .32-.63,
1519# .64-.95, and .96-.128), you will get an array containing a single
1520# /25 as element 0 (.0-.127). Order is not important; you could have
1521# $cidr=.32/27, $ip1=.96/27, $ip2=.0/27, and $ip3=.64/27.
1522
[638]1523 my (@rawfb, @combinelist, %rawid);
[428]1524 my $i=0;
[558]1525 # for each free block under $parent, push a NetAddr::IP object into one list, and
1526 # continuously use NetAddr::IP->compact to automagically merge netblocks as possible.
[428]1527 while (my @data = $sth->fetchrow_array) {
1528 my $testIP = new NetAddr::IP $data[0];
[558]1529 push @rawfb, $testIP;
[638]1530 $rawid{$data[0]} = $data[1];
[558]1531 @combinelist = $testIP->compact(@combinelist);
[93]1532 }
1533
[558]1534 # now that we have the full list of "compacted" freeblocks, go back over
1535 # the list of raw freeblocks, and delete the ones that got merged.
[638]1536 $sth = $dbh->prepare("DELETE FROM freeblocks WHERE id = ?");
[558]1537 foreach my $rawfree (@rawfb) {
1538 next if grep { $rawfree == $_ } @combinelist; # skip if the raw block is in the compacted list
[638]1539 $sth->execute($rawid{$rawfree});
[558]1540 }
[93]1541
[558]1542 # now we walk the new list of compacted blocks, and see which ones we need to insert
[638]1543 $sth = $dbh->prepare("INSERT INTO freeblocks (cidr,city,routed,parent_id,master_id) VALUES (?,?,?,?,?)");
[558]1544 foreach my $cme (@combinelist) {
1545 next if grep { $cme == $_ } @rawfb; # skip if the combined block was in the raw list
[638]1546 $sth->execute($cme, $pcity, $ptype, $p_id, $binfo->{master_id});
[428]1547 }
[93]1548
[428]1549 } # done returning IPs to the appropriate place
[404]1550
[93]1551 # If we got here, we've succeeded. Whew!
1552 $dbh->commit;
1553 }; # end eval
1554 if ($@) {
[558]1555 $msg .= ": $@";
[93]1556 eval { $dbh->rollback; };
1557 return ('FAIL', $msg);
1558 } else {
[590]1559##fixme: RPC return code?
[638]1560 _rpc('delByCIDR', cidr => "$cidr", rpcuser => $user, delforward => $delfwd, delsubs => 'y', parpatt => $ppatt);
[558]1561 return ($retcode, $goback);
[93]1562 }
1563
1564 } # end alloctype != netblock
1565
1566} # end deleteBlock()
1567
1568
[370]1569## IPDB::getBlockData()
[557]1570# Get CIDR or IP, custid, type, city, circuit ID, description, notes, modification time,
1571# private/restricted data, for a CIDR block or pool IP
1572# Also returns SWIP status flag for CIDR blocks or pool netblock for IPs
[636]1573# Takes the block ID or IP to look up and an optional flag to indicate a pool IP lookup
1574# instead of a netblock.
[557]1575# Returns a hashref to the block data
[370]1576sub getBlockData {
1577 my $dbh = shift;
[636]1578 my $id = shift;
1579 my $type = shift || 'b'; # default to netblock for lazy callers
[370]1580
[636]1581 # netblocks are in the allocations table; pool IPs are in the poolips table.
1582 # If we try to look up a CIDR in an integer field we should just get back nothing.
1583 my ($btype) = $dbh->selectrow_array("SELECT type FROM allocations WHERE id=?", undef, ($id) );
[534]1584
[636]1585 if ($type eq 'i') {
[557]1586 my $binfo = $dbh->selectrow_hashref("SELECT ip AS block, custid, type, city, circuitid, description,".
[636]1587 " notes, modifystamp AS lastmod, privdata, vrf, rdns, parent_id, master_id".
1588 " FROM poolips WHERE id = ?", undef, ($id) );
[557]1589 return $binfo;
1590 } else {
[636]1591 my $binfo = $dbh->selectrow_hashref("SELECT cidr AS block, custid, type, city, circuitid, ".
1592 "description, notes, modifystamp AS lastmod, privdata, vrf, swip, rdns, parent_id, master_id".
1593 " FROM allocations WHERE id = ?", undef, ($id) );
[557]1594 return $binfo;
[534]1595 }
[370]1596} # end getBlockData()
1597
1598
[585]1599## IPDB::getBlockRDNS()
1600# Gets reverse DNS pattern for a block or IP. Note that this will also
1601# retrieve any default pattern following the parent chain up, and check via
1602# RPC (if available) to see what the narrowest pattern for the requested block is
1603# Returns the current pattern for the block or IP.
1604sub getBlockRDNS {
1605 my $dbh = shift;
1606 my %args = @_;
1607
[637]1608 $args{type} = 'b' if !$args{type};
[585]1609
[637]1610 # snag entry from database
1611 my ($rdns,$rfrom,$pid);
1612 if ($args{type} =~ /.i/) {
1613 ($rdns, $rfrom, $pid) = $dbh->selectrow_array("SELECT rdns,ip,parent_id FROM poolips WHERE id = ?",
1614 undef, ($args{id}) );
1615 } else {
1616 ($rdns, $rfrom, $pid) = $dbh->selectrow_array("SELECT rdns,cidr,parent_id FROM allocations WHERE id = ?",
1617 undef, ($args{id}) );
1618 }
[585]1619
[637]1620 # Can't see a way this could end up empty, for any case I care about. If the caller
1621 # doesn't know an allocation ID to request, then they don't know anything else anyway.
1622 my $selfblock = $rfrom;
[585]1623
[637]1624 my $type;
1625 while (!$rdns && $pid) {
1626 ($rdns, $rfrom, $pid, $type) = $dbh->selectrow_array(
1627 "SELECT rdns,cidr,parent_id,type FROM allocations WHERE id = ?",
1628 undef, ($pid) );
1629 last if $type eq 'mm'; # break loops in unfortunate legacy data
1630 }
1631
1632 # use the actual allocation to check against the DNS utility; we don't want
1633 # to always go chasing up the chain to the master... which may (usually won't)
1634 # be present directly in DNS anyway
1635 my $cidr = new NetAddr::IP $selfblock;
1636
[585]1637 if ($rpc_url) {
1638 # Use the first /16 or /24, rather than dithering over which sub-/14 /16
1639 # or sub-/19 /24 to retrieve - it's the least-wrong way to do things.
1640
[586]1641 my ($rpcblock) = ($cidr->masklen <= 24 ? $cidr->split( ($cidr->masklen <= 16 ? 16 : 24) ) : $cidr);
[585]1642 my %rpcargs = (
1643 rpcuser => $args{user},
1644 group => $revgroup, # not sure how this could sanely be exposed, tbh...
1645 cidr => "$rpcblock",
1646 );
1647
[637]1648 my $remote_rdns = _rpc('getRevPattern', %rpcargs);
1649 $rdns = $remote_rdns if $remote_rdns;
[585]1650 }
1651
1652 # hmm. do we care about where it actually came from?
1653 return $rdns;
1654} # end getBlockRDNS()
1655
1656
[519]1657## IPDB::getNodeList()
1658# Gets a list of node ID+name pairs as an arrayref to a list of hashrefs
1659sub getNodeList {
1660 my $dbh = shift;
1661
1662 my $ret = $dbh->selectall_arrayref("SELECT node_id, node_name FROM nodes ORDER BY node_type,node_id",
1663 { Slice => {} });
1664 return $ret;
1665} # end getNodeList()
1666
1667
[530]1668## IPDB::getNodeName()
1669# Get node name from the ID
1670sub getNodeName {
1671 my $dbh = shift;
1672 my $nid = shift;
1673
1674 my ($nname) = $dbh->selectrow_array("SELECT node_name FROM nodes WHERE node_id = ?", undef, ($nid) );
1675 return $nname;
1676} # end getNodeName()
1677
1678
1679## IPDB::getNodeInfo()
1680# Get node name and ID associated with a block
1681sub getNodeInfo {
1682 my $dbh = shift;
1683 my $block = shift;
1684
1685 my ($nid, $nname) = $dbh->selectrow_array("SELECT nodes.node_id,node_name FROM nodes INNER JOIN noderef".
1686 " ON nodes.node_id=noderef.node_id WHERE noderef.block = ?", undef, ($block) );
1687 return ($nid, $nname);
1688} # end getNodeInfo()
1689
1690
[77]1691## IPDB::mailNotify()
[66]1692# Sends notification mail to recipients regarding an IPDB operation
[416]1693sub mailNotify {
1694 my $dbh = shift;
1695 my ($action,$subj,$message) = @_;
[66]1696
[462]1697 return if $smtphost eq 'smtp.example.com'; # do nothing if still using default SMTP host.
1698
[422]1699##fixme: need to redesign the breakdown/processing for $action for proper handling of all cases
1700
[416]1701# split action into parts for fiddlement. nb: there are almost certainly better ways to do this.
[422]1702 my @actionbits = split //, $action;
[416]1703
1704 # want to notify anyone who has specifically requested notify on *this* type ($action as passed),
1705 # on "all static IP types" or "all pool types" (and other last-char-in-type groupings), on eg "all DSL types",
1706 # and "all events with this action"
1707 my @actionsets = ($action);
1708##fixme: ick, eww. really gotta find a better way to handle this...
1709 push @actionsets, ($actionbits[0].'.'.$actionbits[2],
1710 $actionbits[0].$actionbits[1].'.', $actionbits[0].'a') if $action =~ /^.{3}$/;
1711
1712 my $mailer = Net::SMTP->new($smtphost, Hello => "ipdb.$domain");
1713
1714 # get recip list from db
1715 my $sth = $dbh->prepare("SELECT reciplist FROM notify WHERE action=?");
1716
[443]1717 my %reciplist;
[416]1718 foreach (@actionsets) {
[426]1719 $sth->execute($_);
[416]1720##fixme - need to handle db errors
1721 my ($recipsub) = $sth->fetchrow_array;
1722 next if !$recipsub;
1723 foreach (split(/,/, $recipsub)) {
[443]1724 $reciplist{$_}++;
[416]1725 }
1726 }
1727
[443]1728 return if !%reciplist;
[420]1729
[443]1730 foreach my $recip (keys %reciplist) {
[416]1731 $mailer->mail("ipdb\@$domain");
1732 $mailer->to($recip);
[422]1733 $mailer->data("From: \"$org_name IP Database\" <ipdb\@$domain>\n",
[135]1734 "To: $recip\n",
[69]1735 "Date: ".strftime("%a, %d %b %Y %H:%M:%S %z",localtime)."\n",
1736 "Subject: {IPDB} $subj\n",
1737 "X-Mailer: IPDB Notify v".sprintf("%.1d",$IPDB::VERSION)."\n",
[417]1738 "Organization: $org_name\n",
[69]1739 "\n$message\n");
[416]1740 }
[66]1741 $mailer->quit;
1742}
1743
[4]1744# Indicates module loaded OK. Required by Perl.
17451;
Note: See TracBrowser for help on using the repository browser.