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

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

/trunk

Extend listSubs() to include some details on container blocks when
appropriate. Not sure this format will work; it ends up looking very
busy and confused after importing a dataset from IPDB 2.8. Consider
splitting containers vs direct allocations (so that there would be
three main page sections, not two).

  • Property svn:keywords set to Date Rev Author
File size: 61.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-12-17 23:04:01 +0000 (Wed, 17 Dec 2014) $
6# SVN revision $Rev: 653 $
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 {
[652]436 $dbh->do("UPDATE allocations SET modifystamp=now() WHERE id = ?", undef, ($master));
[547]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
[653]502 # snag some more details
503 my $substh = $dbh->prepare("SELECT count(*) FROM allocations WHERE cidr <<= ? AND type='rm' AND master_id = ? AND NOT cidr = ? ");
504 my $alsth = $dbh->prepare("SELECT count(*) FROM allocations WHERE cidr <<= ? ".
505 "AND NOT type='rm' AND NOT type='mm' AND master_id = ?");
506 my $freesth = $dbh->prepare("SELECT count(*) FROM freeblocks WHERE cidr <<= ? AND master_id = ?");
507 my $lfreesth = $dbh->prepare("SELECT masklen(cidr) AS maskbits FROM freeblocks WHERE cidr <<= ?".
508 " AND master_id = ? ORDER BY masklen(cidr) LIMIT 1");
509
[561]510 my @blocklist;
[653]511 while (my ($cidr,$city,$type,$custid,$swip,$desc,$id,$mid) = $sth->fetchrow_array()) {
[561]512 $custsth->execute($custid);
513 my ($ncust) = $custsth->fetchrow_array();
[653]514 $substh->execute($cidr, $mid, $cidr);
515 my ($cont) = $substh->fetchrow_array();
516 $alsth->execute($cidr, $mid);
517 my ($alloc) = $alsth->fetchrow_array();
518 $freesth->execute($cidr, $mid);
519 my ($free) = $freesth->fetchrow_array();
520 $lfreesth->execute($cidr, $mid);
521 my ($lfree) = $lfreesth->fetchrow_array();
522 $lfree = "/$lfree" if $lfree;
523 $lfree = '<NONE>' if !$lfree;
[561]524 my %row = (
525 block => $cidr,
[653]526 subcontainers => $cont,
527 suballocs => $alloc,
528 subfree => $free,
529 lfree => $lfree,
[561]530 city => $city,
531 type => $disp_alloctypes{$type},
532 custid => $custid,
533 swip => ($swip eq 'y' ? 'Yes' : 'No'),
534 partswip => ($swip eq 'y' && $ncust == 0 ? 1 : 0),
535 desc => $desc,
536 hassubs => ($type eq 'rm' || $type =~ /.c/ ? 1 : 0),
[627]537 id => $id,
[561]538 );
539# $row{subblock} = ($type =~ /^.r$/); # hmf. wonder why these won't work in the hash declaration...
540 $row{listpool} = ($type =~ /^.[pd]$/);
541 push (@blocklist, \%row);
542 }
543 return \@blocklist;
544} # end listSubs()
545
546
[524]547## IPDB::listMaster()
548# Get list of routed blocks in the requested master
549# Returns an arrayref to a list of hashrefs containing the routed block, POP/city the block is routed to,
550# allocated count, free count, and largest free block masklength
551sub listMaster {
552 my $dbh = shift;
553 my $master = shift;
[523]554
[524]555 my $rlist = $dbh->selectall_arrayref("SELECT cidr AS block,city FROM routed WHERE cidr <<= ? ORDER BY cidr",
556 { Slice => {} }, ($master) );
[523]557
[524]558 foreach (@{$rlist}) {
559 my ($acnt) = $dbh->selectrow_array("SELECT count(*) FROM allocations WHERE cidr <<= ?", undef, ($$_{block}));
560 $$_{nsubs} = $acnt;
561 my ($fcnt) = $dbh->selectrow_array("SELECT count(*) FROM freeblocks WHERE cidr <<= ?".
562 " AND (routed='y' OR routed='n')", undef, ($$_{block}));
563 $$_{nfree} = $fcnt;
564 my ($bigfree) = $dbh->selectrow_array("SELECT maskbits FROM freeblocks WHERE cidr <<= ?".
565 " AND (routed='y' OR routed='n') ORDER BY maskbits LIMIT 1", undef, ($$_{block}));
566##fixme: should find a way to do this without having to HTMLize the <>
567 $bigfree = "/$bigfree" if $bigfree;
[525]568 $bigfree = '<NONE>' if !$bigfree;
[524]569 $$_{lfree} = $bigfree;
570 }
571 return $rlist;
572} # end listMaster()
573
574
[527]575## IPDB::listRBlock()
576# Gets a list of free blocks in the requested parent/master in both CIDR and range notation
577# Takes a parent/master and an optional flag to look at routed or unrouted blocks, depending
578# on whether the master is a direct master or a routed block
579# Returns an arrayref to a list of hashrefs containing the CIDR and range-notation blocks
580sub listRBlock {
581 my $dbh = shift;
582 my $routed = shift;
[524]583
[527]584 # Snag the allocations for this block
585 my $sth = $dbh->prepare("SELECT cidr,city,type,custid,swip,description".
586 " FROM allocations WHERE cidr <<= ? ORDER BY cidr");
587 $sth->execute($routed);
[524]588
[527]589 # hack hack hack
590 # set up to flag swip=y records if they don't actually have supporting data in the customers table
591 my $custsth = $dbh->prepare("SELECT count(*) FROM customers WHERE custid = ?");
592
593 my @blocklist;
594 while (my ($cidr,$city,$type,$custid,$swip,$desc) = $sth->fetchrow_array()) {
595 $custsth->execute($custid);
596 my ($ncust) = $custsth->fetchrow_array();
597 my %row = (
598 block => $cidr,
599 city => $city,
600 type => $disp_alloctypes{$type},
601 custid => $custid,
602 swip => ($swip eq 'y' ? 'Yes' : 'No'),
603 partswip => ($swip eq 'y' && $ncust == 0 ? 1 : 0),
604 desc => $desc
605 );
606 $row{subblock} = ($type =~ /^.r$/); # hmf. wonder why these won't work in the hash declaration...
607 $row{listpool} = ($type =~ /^.[pd]$/);
608 push (@blocklist, \%row);
609 }
610 return \@blocklist;
611} # end listRBlock()
612
613
[524]614## IPDB::listFree()
[562]615# Gets a list of free blocks in the requested parent/master and VRF instance in both CIDR and range notation
[630]616# Takes a parent/master ID and an optional VRF specifier that defaults to empty.
[524]617# Returns an arrayref to a list of hashrefs containing the CIDR and range-notation blocks
[527]618# Returns some extra flags in the hashrefs for routed blocks, since those can have several subtypes
[524]619sub listFree {
620 my $dbh = shift;
621
[562]622 my %args = @_;
623 # Just In Case
624 $args{vrf} = '' if !$args{vrf};
625
[630]626 my $sth = $dbh->prepare("SELECT cidr,id FROM freeblocks WHERE parent_id = ? ORDER BY cidr");
627# $sth->execute($args{parent}, $args{vrf});
628 $sth->execute($args{parent});
[524]629 my @flist;
[630]630 while (my ($cidr,$id) = $sth->fetchrow_array()) {
[524]631 $cidr = new NetAddr::IP $cidr;
[527]632 my %row = (
633 fblock => "$cidr",
634 frange => $cidr->range,
[630]635 fbid => $id,
636 fbparent => $args{parent},
[527]637 );
[524]638 push @flist, \%row;
639 }
640 return \@flist;
[527]641} # end listFree()
[524]642
643
[528]644## IPDB::listPool()
645#
646sub listPool {
647 my $dbh = shift;
648 my $pool = shift;
649
[630]650 my $sth = $dbh->prepare("SELECT ip,custid,available,description,type,id".
651 " FROM poolips WHERE parent_id = ? ORDER BY ip");
[528]652 $sth->execute($pool);
653 my @poolips;
[630]654 while (my ($ip,$custid,$available,$desc,$type,$id) = $sth->fetchrow_array) {
[528]655 my %row = (
656 ip => $ip,
657 custid => $custid,
658 available => $available,
659 desc => $desc,
[563]660 delme => $available eq 'n',
[630]661 parent => $pool,
662 id => $id,
[528]663 );
664 push @poolips, \%row;
665 }
666 return \@poolips;
667} # end listPool()
668
669
[541]670## IPDB::getMasterList()
671# Get a list of master blocks, optionally including last-modified timestamps
672# Takes an optional flag to indicate whether to include timestamps;
673# 'm' includes ctime, all others (suggest 'c') do not.
674# Returns an arrayref to a list of hashrefs
675sub getMasterList {
676 my $dbh = shift;
677 my $stampme = shift || 'm'; # optional but should be set by caller for clarity
678
[632]679 my $mlist = $dbh->selectall_arrayref("SELECT id,vrf,cidr AS master".($stampme eq 'm' ? ',modifystamp AS mtime' : '').
680 " FROM allocations WHERE type='mm' ORDER BY cidr", { Slice => {} });
[541]681 return $mlist;
682} # end getMasterList()
683
684
[529]685## IPDB::getTypeList()
686# Get an alloctype/description pair list suitable for dropdowns
687# Takes a flag to determine which general groups of types are returned
688# Returns an reference to an array of hashrefs
689sub getTypeList {
690 my $dbh = shift;
691 my $tgroup = shift || 'a'; # technically optional, like this, but should
692 # really be specified in the call for clarity
693 my $tlist;
[564]694 if ($tgroup eq 'n') {
695 # grouping 'p' - all netblock types. These include routed blocks, containers (_c)
696 # and contained (_r) types, dynamic-allocation ranges (_e), static IP pools (_d and _p),
697 # and the "miscellaneous" cn, in, and en types.
698 $tlist = $dbh->selectall_arrayref("SELECT type,listname FROM alloctypes WHERE listorder <= 500 ".
699 "AND type NOT LIKE '_i' ORDER BY listorder", { Slice => {} });
700 } elsif ($tgroup eq 'p') {
701 # grouping 'p' - primary allocation types. As with 'n' above but without the _r contained types.
702 $tlist = $dbh->selectall_arrayref("SELECT type,listname FROM alloctypes WHERE listorder <= 500 ".
[529]703 "AND type NOT LIKE '_i' AND type NOT LIKE '_r' ORDER BY listorder", { Slice => {} });
704 } elsif ($tgroup eq 'c') {
705 # grouping 'c' - contained types. These include all static IPs and all _r types.
706 $tlist = $dbh->selectall_arrayref("SELECT type,listname FROM alloctypes WHERE listorder <= 500 ".
707 " AND (type LIKE '_i' OR type LIKE '_r') ORDER BY listorder", { Slice => {} });
[632]708 } elsif ($tgroup eq 'i') {
709 # grouping 'i' - static IP types.
710 $tlist = $dbh->selectall_arrayref("SELECT type,listname FROM alloctypes WHERE listorder <= 500 ".
711 " AND type LIKE '_i' ORDER BY listorder", { Slice => {} });
[529]712 } else {
713 # grouping 'a' - all standard allocation types. This includes everything
714 # but mm (present only as a formality). Make this the default.
715 $tlist = $dbh->selectall_arrayref("SELECT type,listname FROM alloctypes WHERE listorder <= 500 ".
716 " ORDER BY listorder", { Slice => {} });
717 }
718 return $tlist;
719}
720
721
[532]722## IPDB::getPoolSelect()
723# Get a list of pools matching the passed city and type that have 1 or more free IPs
[533]724# Returns an arrayref to a list of hashrefs
[532]725sub getPoolSelect {
726 my $dbh = shift;
727 my $iptype = shift;
728 my $pcity = shift;
729
730 my ($ptype) = ($iptype =~ /^(.)i$/);
731 return if !$ptype;
732 $ptype .= '_';
733
734 my $plist = $dbh->selectall_arrayref(
[572]735 "SELECT count(*) AS poolfree,p.pool AS poolblock, a.city AS poolcit, a.rdepth AS poolrdepth ".
736 "FROM poolips p ".
737 "JOIN allocations a ON p.pool=a.cidr ".
738 "WHERE p.available='y' AND a.city = ? AND p.type LIKE ? ".
739 "GROUP BY p.pool,a.city,a.rdepth",
740 { Slice => {} }, ($pcity, $ptype) );
[532]741 return $plist;
742} # end getPoolSelect()
743
744
[533]745## IPDB::findAllocateFrom()
746# Find free block to add a new allocation from. (CIDR block version of pool select above, more or less)
747# Takes
748# - mask length
749# - allocation type
750# - POP city "parent"
751# - optional master-block restriction
752# - optional flag to allow automatic pick-from-private-network-ranges
753# Returns a string with the first CIDR block matching the criteria, if any
754sub findAllocateFrom {
755 my $dbh = shift;
756 my $maskbits = shift;
757 my $type = shift;
758 my $city = shift;
759 my $pop = shift;
760 my %optargs = @_;
761
762 my $failmsg = "No suitable free block found\n";
763
[633]764 my @vallist;
765 my $sql;
766
767 # Free pool IPs should be easy.
768 if ($type =~ /^.i$/) {
769 # User may get an IP from the wrong VRF. User should not be using admin tools to allocate static IPs.
770 $sql = "SELECT id, ip, parent_id FROM poolips WHERE ip = ?";
771 @vallist = ($optargs{gimme});
772 } else {
773
[533]774## Set up the SQL to find out what freeblock we can (probably) use for an allocation.
775## Very large systems will require development of a reserve system (possibly an extension
776## of the reserve-for-expansion concept in https://secure.deepnet.cx/trac/ipdb/ticket/24?)
777## Also populate a value list for the DBI call.
778
[633]779 @vallist = ($maskbits);
780 $sql = "SELECT id,cidr,parent_id FROM freeblocks WHERE masklen(cidr) <= ?";
[533]781
[572]782# cases, strict rules
783# .c -> container type
784# requires a routing container, fbtype r
785# .d -> DHCP/"normal-routing" static pool
786# requires a routing container, fbtype r
787# .e -> Dynamic-assignment connectivity
788# requires a routing container, fbtype r
789# .i -> error, can't allocate static IPs this way?
790# mm -> error, master block
791# rm -> routed block
792# requires master block, fbtype m
793# .n -> Miscellaneous usage
794# requires a routing container, fbtype r
795# .p -> PPP(oE) static pool
796# requires a routing container, fbtype r
797# .r -> contained type
798# requires a matching container, fbtype $1
799##fixme: strict-or-not flag
800
[633]801##fixme: config or UI flag for "Strict" mode
802# if ($strictmode) {
803if (0) {
[572]804 if ($type =~ /^(.)r$/) {
805 push @vallist, $1;
806 $sql .= " AND routed = ?";
807 } elsif ($type eq 'rm') {
808 $sql .= " AND routed = 'm'";
809 } else {
810 $sql .= " AND routed = 'r'";
811 }
[633]812}
[572]813
[633]814 # for PPP(oE) and container types, the POP city is the one attached to the pool.
815 # individual allocations get listed with the customer city site.
816 ##fixme: chain cities to align roughly with a full layer-2 node graph
817 $city = $pop if $type !~ /^.[pc]$/;
818 if ($type ne 'rm' && $city) {
819 $sql .= " AND city = ?";
820 push @vallist, $city;
[533]821 }
[633]822 # Allow specifying an arbitrary full block, instead of a master
823 if ($optargs{gimme}) {
824 $sql .= " AND cidr >>= ?";
825 push @vallist, $optargs{gimme};
826 }
827 # if a specific master was requested, allow the requestor to self->shoot(foot)
828 if ($optargs{master} && $optargs{master} ne '-') {
829 $sql .= " AND master_id = ?";
830# if $optargs{master} ne '-';
831 push @vallist, $optargs{master};
832 } else {
833 # if a specific master was NOT requested, filter out the RFC 1918 private networks
834 if (!$optargs{allowpriv}) {
835 $sql .= " AND NOT (cidr <<= '192.168.0.0/16' OR cidr <<= '10.0.0.0/8' OR cidr <<= '172.16.0.0/12')";
836 }
837 }
838 # Sorting and limiting, since we don't (currently) care to provide a selection of
839 # blocks to carve up. This preserves something resembling optimal usage of the IP
840 # space by forcing contiguous allocations and free blocks as much as possible.
841 $sql .= " ORDER BY masklen(cidr) DESC,cidr LIMIT 1";
842 } # done setting up SQL for free CIDR block
[533]843
[633]844 my ($fbid,$fbfound,$fbparent) = $dbh->selectrow_array($sql, undef, @vallist);
845 return $fbid,$fbfound,$fbparent;
[533]846} # end findAllocateFrom()
847
848
[536]849## IPDB::ipParent()
850# Get an IP's parent pool's details
851# Takes a database handle and IP
852# Returns a hashref to the parent pool block, if any
853sub ipParent {
854 my $dbh = shift;
855 my $block = shift;
856
857 my $pinfo = $dbh->selectrow_hashref("SELECT cidr,custid,type,city,description FROM allocations".
[565]858 " WHERE cidr >>= ? AND (type LIKE '_p' OR type LIKE '_d')", undef, ($block) );
[536]859 return $pinfo;
860} # end ipParent()
861
862
863## IPDB::subParent()
[529]864# Get a block's parent's details
865# Takes a database handle and CIDR block
[536]866# Returns a hashref to the parent container block, if any
867sub subParent {
[529]868 my $dbh = shift;
869 my $block = shift;
870
871 my $pinfo = $dbh->selectrow_hashref("SELECT cidr,custid,type,city,description FROM allocations".
872 " WHERE cidr >>= ?", undef, ($block) );
873 return $pinfo;
[536]874} # end subParent()
[529]875
876
[536]877## IPDB::blockParent()
878# Get a block's parent's details
879# Takes a database handle and CIDR block
880# Returns a hashref to the parent container block, if any
881sub blockParent {
882 my $dbh = shift;
883 my $block = shift;
884
885 my $pinfo = $dbh->selectrow_hashref("SELECT cidr,city FROM routed".
886 " WHERE cidr >>= ?", undef, ($block) );
887 return $pinfo;
888} # end blockParent()
889
890
[527]891## IPDB::getRoutedCity()
892# Get the city for a routed block.
893sub getRoutedCity {
894 my $dbh = shift;
895 my $block = shift;
896
897 my ($rcity) = $dbh->selectrow_array("SELECT city FROM routed WHERE cidr = ?", undef, ($block) );
898 return $rcity;
899} # end getRoutedCity()
900
901
[77]902## IPDB::allocateBlock()
[66]903# Does all of the magic of actually allocating a netblock
[554]904# Requires a database handle, and a hash containing the block to allocate, routing depth, custid,
905# type, city, block to allocate from, and optionally a description, notes, circuit ID,
906# and private data
[77]907# Returns a success code and optional error message.
908sub allocateBlock {
[554]909 my $dbh = shift;
[284]910
[554]911 my %args = @_;
912
913 $args{cidr} = new NetAddr::IP $args{cidr};
914
915 $args{desc} = '' if !$args{desc};
916 $args{notes} = '' if !$args{notes};
917 $args{circid} = '' if !$args{circid};
918 $args{privdata} = '' if !$args{privdata};
919 $args{vrf} = '' if !$args{vrf};
[585]920 $args{rdns} = '' if !$args{rdns};
[554]921
[77]922 my $sth;
[66]923
[633]924 # Snag the "type" of the freeblock and its CIDR
925 my ($alloc_from_type, $alloc_from, $fbparent, $fcity, $fbmaster) =
926 $dbh->selectrow_array("SELECT routed,cidr,parent_id,city,master_id FROM freeblocks WHERE id = ?",
927 undef, $args{fbid});
928 $alloc_from = new NetAddr::IP $alloc_from;
[349]929
[79]930 # To contain the error message, if any.
[554]931 my $msg = "Unknown error allocating $args{cidr} as '$disp_alloctypes{$args{type}}'";
[79]932
[77]933 # Enable transactions and error handling
934 local $dbh->{AutoCommit} = 0; # These need to be local so we don't
935 local $dbh->{RaiseError} = 1; # step on our toes by accident.
[66]936
[554]937 if ($args{type} =~ /^.i$/) {
938 $msg = "Unable to assign static IP $args{cidr} to $args{custid}";
[77]939 eval {
[554]940 if ($args{cidr}) { # IP specified
941 my ($isavail) = $dbh->selectrow_array("SELECT available FROM poolips WHERE ip=?", undef, ($args{cidr}) );
942 die "IP is not in an IP pool.\n"
943 if !$isavail;
944 die "IP already allocated. Deallocate and reallocate, or update the entry\n"
945 if $isavail eq 'n';
946 } else { # IP not specified, take first available
947 ($args{cidr}) = $dbh->selectrow_array("SELECT ip FROM poolips WHERE pool=? AND available='y' ORDER BY ip",
948 undef, ($args{alloc_from}) );
[545]949 }
[633]950 $dbh->do("UPDATE poolips SET custid = ?, city = ?,available='n', description = ?, notes = ?, ".
951 "circuitid = ?, privdata = ?, vrf = ?, rdns = ? ".
952 "WHERE ip = ? AND parent_id = ?", undef,
953 ($args{custid}, $args{city}, $args{desc}, $args{notes},
954 $args{circid}, $args{privdata}, $args{vrf}, $args{rdns},
955 $args{cidr}, $args{parent}) );
[157]956
[397]957# node hack
[554]958 if ($args{nodeid} && $args{nodeid} ne '') {
959 $dbh->do("INSERT INTO noderef (block,node_id) VALUES (?,?)", undef, ($args{cidr}, $args{nodeid}) );
[397]960 }
961# end node hack
[545]962
[79]963 $dbh->commit;
[77]964 };
965 if ($@) {
[545]966 $msg .= ": $@";
[78]967 eval { $dbh->rollback; };
[578]968 return ('FAIL', $msg);
[77]969 } else {
[585]970 _rpc('addOrUpdateRevRec', cidr => "$args{cidr}", name => $args{rdns}, rpcuser => $args{user});
[578]971 return ('OK', $args{cidr});
[77]972 }
973
974 } else { # end IP-from-pool allocation
975
[633]976 if ($args{cidr} == $alloc_from) {
[77]977 # Easiest case- insert in one table, delete in the other, and go home. More or less.
978 # insert into allocations values (cidr,custid,type,city,desc) and
979 # delete from freeblocks where cidr='cidr'
980 # For data safety on non-transaction DBs, we delete first.
981
982 eval {
[554]983 $msg = "Unable to allocate $args{cidr} as '$disp_alloctypes{$args{type}}'";
984
[633]985 # Insert the allocations entry
986 $dbh->do("INSERT INTO allocations ".
987 "(cidr,parent_id,master_id,vrf,custid,type,city,description,notes,circuitid,privdata,rdns)".
988 " VALUES (?,?,?,?,?,?,?,?,?,?,?,?)", undef,
989 ($args{cidr}, $fbparent, $fbmaster, $args{vrf}, $args{custid}, $args{type}, $args{city},
990 $args{desc}, $args{notes}, $args{circid}, $args{privdata}, $args{rdns}) );
991 my ($bid) = $dbh->selectrow_array("SELECT currval('allocations_id_seq')");
[555]992
[554]993 # Munge freeblocks
994 if ($args{type} =~ /^(.)[mc]$/) {
995 # special case - block is a routed or container/"reserve" block
996 my $rtype = $1;
[633]997 $dbh->do("UPDATE freeblocks SET routed = ?,city = ?,parent_id = ? WHERE id = ?",
998 undef, ($rtype, $args{city}, $bid, $args{fbid}) );
[77]999 } else {
[554]1000 # "normal" case
[633]1001 $dbh->do("DELETE FROM freeblocks WHERE id = ?", undef, ($args{fbid}) );
[554]1002 }
[77]1003
[554]1004 # And initialize the pool, if necessary
1005 # PPPoE pools (currently dialup, DSL, and WiFi) get all IPs made available
1006 # "DHCP" or "real-subnet" pools have the net, gw, and bcast IPs removed.
1007 if ($args{type} =~ /^.p$/) {
1008 $msg = "Could not initialize IPs in new $disp_alloctypes{$args{type}} $args{cidr}";
[633]1009 my ($code,$rmsg) = initPool($dbh, $args{cidr}, $args{type}, $args{city}, "all", $bid);
[554]1010 die $rmsg if $code eq 'FAIL';
1011 } elsif ($args{type} =~ /^.d$/) {
1012 $msg = "Could not initialize IPs in new $disp_alloctypes{$args{type}} $args{cidr}";
[633]1013 my ($code,$rmsg) = initPool($dbh, $args{cidr}, $args{type}, $args{city}, "normal", $bid);
[554]1014 die $rmsg if $code eq 'FAIL';
1015 }
[79]1016
[397]1017# node hack
[554]1018 if ($args{nodeid} && $args{nodeid} ne '') {
1019 $dbh->do("INSERT INTO noderef (block,node_id) VALUES (?,?)", undef, ($args{cidr}, $args{nodeid}) );
[397]1020 }
1021# end node hack
[574]1022
[77]1023 $dbh->commit;
[78]1024 }; # end of eval
[77]1025 if ($@) {
[157]1026 $msg .= ": ".$@;
[77]1027 eval { $dbh->rollback; };
[157]1028 return ('FAIL',$msg);
[78]1029 }
[77]1030
1031 } else { # cidr != alloc_from
1032
1033 # Hard case. Allocation is smaller than free block.
[633]1034
1035 # make sure new allocation is in fact within freeblock. *sigh*
1036 return ('FAIL',"Requested allocation $args{cidr} is not within $alloc_from")
1037 if !$alloc_from->contains($args{cidr});
[554]1038 my $wantmaskbits = $args{cidr}->masklen;
[633]1039 my $maskbits = $alloc_from->masklen;
[77]1040
1041 my @newfreeblocks; # Holds free blocks generated from splitting the source freeblock.
1042
1043 # This determines which blocks will be left "free" after allocation. We take the
1044 # block we're allocating from, and split it in half. We see which half the wanted
1045 # block is in, and repeat until the wanted block is equal to one of the halves.
1046 my $i=0;
[633]1047 my $tmp_from = $alloc_from; # So we don't munge $args{alloc_from}
[77]1048 while ($maskbits++ < $wantmaskbits) {
1049 my @subblocks = $tmp_from->split($maskbits);
[554]1050 $newfreeblocks[$i++] = (($args{cidr}->within($subblocks[0])) ? $subblocks[1] : $subblocks[0]);
1051 $tmp_from = ( ($args{cidr}->within($subblocks[0])) ? $subblocks[0] : $subblocks[1] );
[77]1052 } # while
1053
1054 # Begin SQL transaction block
1055 eval {
[554]1056 $msg = "Unable to allocate $args{cidr} as '$disp_alloctypes{$args{type}}'";
[79]1057
[77]1058 # Delete old freeblocks entry
[633]1059 $dbh->do("DELETE FROM freeblocks WHERE id = ?", undef, ($args{fbid}) );
[77]1060
[554]1061 # Insert new list of smaller free blocks left over
[633]1062 $sth = $dbh->prepare("INSERT INTO freeblocks (cidr,city,routed,vrf,parent_id,master_id) VALUES (?,?,?,?,?,?)");
[554]1063 foreach my $block (@newfreeblocks) {
[633]1064 $sth->execute($block, $fcity, $alloc_from_type, $args{vrf}, $fbparent, $fbmaster);
[554]1065 }
[79]1066
[633]1067 # Insert the allocations entry
1068 $dbh->do("INSERT INTO allocations ".
1069 "(cidr,parent_id,master_id,vrf,custid,type,city,description,notes,circuitid,privdata,rdns)".
1070 " VALUES (?,?,?,?,?,?,?,?,?,?,?,?)", undef,
1071 ($args{cidr}, $fbparent, $fbmaster, $args{vrf}, $args{custid}, $args{type}, $args{city},
1072 $args{desc}, $args{notes}, $args{circid}, $args{privdata}, $args{rdns}) );
1073 my ($bid) = $dbh->selectrow_array("SELECT currval('allocations_id_seq')");
1074
[554]1075 # For routed/container types, add a freeblock within the allocated block so we can subdivide it further
1076 if ($args{type} =~ /(.)[mc]/) { # rm and .c types - containers
1077 my $rtype = $1;
[633]1078 $sth->execute($args{cidr}, $args{city}, $rtype, $args{vrf}, $bid, $fbmaster);
[554]1079 }
[79]1080
[554]1081 # And initialize the pool, if necessary
1082 # PPPoE pools (currently dialup, DSL, and WiFi) get all IPs made available
1083 # "DHCP" or "real-subnet" pools have the net, gw, and bcast IPs removed.
1084 if ($args{type} =~ /^.p$/) {
1085 $msg = "Could not initialize IPs in new $disp_alloctypes{$args{type}} $args{cidr}";
[633]1086 my ($code,$rmsg) = initPool($dbh, $args{cidr}, $args{type}, $args{city}, "all", $bid);
[554]1087 die $rmsg if $code eq 'FAIL';
1088 } elsif ($args{type} =~ /^.d$/) {
1089 $msg = "Could not initialize IPs in new $disp_alloctypes{$args{type}} $args{cidr}";
[633]1090 my ($code,$rmsg) = initPool($dbh, $args{cidr}, $args{type}, $args{city}, "normal", $bid);
[554]1091 die $rmsg if $code eq 'FAIL';
1092 }
[77]1093
[397]1094# node hack
[554]1095 if ($args{nodeid} && $args{nodeid} ne '') {
1096 $dbh->do("INSERT INTO noderef (block,node_id) VALUES (?,?)", undef, ($args{cidr}, $args{nodeid}) );
[397]1097 }
1098# end node hack
[554]1099
[77]1100 $dbh->commit;
1101 }; # end eval
1102 if ($@) {
[256]1103 $msg .= ": ".$@;
[77]1104 eval { $dbh->rollback; };
[78]1105 return ('FAIL',$msg);
[77]1106 }
1107
1108 } # end fullcidr != alloc_from
1109
[590]1110 # now we do the DNS dance for netblocks, if we have an RPC server to do it with and a pattern to use.
1111 _rpc('addOrUpdateRevRec', cidr => "$args{cidr}", name => $args{rdns}, rpcuser => $args{user})
1112 if $args{rdns};
[585]1113
1114 return ('OK', 'OK');
1115
[77]1116 } # end static-IP vs netblock allocation
1117
1118} # end allocateBlock()
1119
1120
1121## IPDB::initPool()
1122# Initializes a pool
1123# Requires a database handle, the pool CIDR, type, city, and a parameter
1124# indicating whether the pool should allow allocation of literally every
1125# IP, or if it should reserve network/gateway/broadcast IPs
[78]1126# Note that this is NOT done in a transaction, that's why it's a private
1127# function and should ONLY EVER get called from allocateBlock()
[77]1128sub initPool {
[633]1129 my ($dbh,undef,$type,$city,$class,$parent) = @_;
[77]1130 my $pool = new NetAddr::IP $_[1];
1131
[574]1132 # IPv6 does not lend itself to IP pools as supported
1133 return ('FAIL',"Refusing to create IPv6 static IP pool") if $pool->{isv6};
1134 # IPv4 pools don't make much sense beyond even /24. Allow up to 4096-host footshooting anyway.
1135 # NetAddr::IP won't allow more than a /16 (65k hosts).
1136 return ('FAIL',"Refusing to create oversized static IP pool") if $pool->masklen <= 20;
1137
[633]1138 my ($pcustid) = $dbh->selectrow_array("SELECT def_custid FROM alloctypes WHERE type=?", undef, ($type) );
[157]1139 $type =~ s/[pd]$/i/;
[77]1140 my $sth;
[157]1141 my $msg;
[77]1142
[157]1143 # Trap errors so we can pass them back to the caller. Even if the
1144 # caller is only ever supposed to be local, and therefore already
1145 # trapping errors. >:(
1146 local $dbh->{AutoCommit} = 0; # These need to be local so we don't
1147 local $dbh->{RaiseError} = 1; # step on our toes by accident.
1148
1149 eval {
1150 # have to insert all pool IPs into poolips table as "unallocated".
[633]1151 $sth = $dbh->prepare("INSERT INTO poolips (ip,custid,city,type,parent_id) VALUES (?,?,?,?,?)");
[157]1152 my @poolip_list = $pool->hostenum;
1153 if ($class eq 'all') { # (DSL-ish block - *all* IPs available
[246]1154 if ($pool->addr !~ /\.0$/) { # .0 causes weirdness.
[633]1155 $sth->execute($pool->addr, $pcustid, $city, $type, $parent);
[246]1156 }
[157]1157 for (my $i=0; $i<=$#poolip_list; $i++) {
[633]1158 $sth->execute($poolip_list[$i]->addr, $pcustid, $city, $type, $parent);
[157]1159 }
1160 $pool--;
[246]1161 if ($pool->addr !~ /\.255$/) { # .255 can cause weirdness.
[633]1162 $sth->execute($pool->addr, $pcustid, $city, $type, $parent);
[246]1163 }
[157]1164 } else { # (real netblock)
1165 for (my $i=1; $i<=$#poolip_list; $i++) {
[633]1166 $sth->execute($poolip_list[$i]->addr, $pcustid, $city, $type, $parent);
[157]1167 }
[77]1168 }
[633]1169# don't commit here! the caller may not be done.
1170# $dbh->commit;
[157]1171 };
1172 if ($@) {
[574]1173 $msg = $@;
[633]1174# Don't roll back! It's up to the caller to handle this.
1175# eval { $dbh->rollback; };
[157]1176 return ('FAIL',$msg);
1177 } else {
1178 return ('OK',"OK");
[77]1179 }
1180} # end initPool()
1181
1182
[531]1183## IPDB::updateBlock()
1184# Update an allocation
1185# Takes all allocation fields in a hash
1186sub updateBlock {
1187 my $dbh = shift;
1188 my %args = @_;
1189
1190 return ('FAIL', 'Missing block to update') if !$args{block};
1191
[634]1192 # Spaces don't show up well in lots of places. Make sure they don't get into the DB.
1193 $args{custid} =~ s/^\s+//;
1194 $args{custid} =~ s/\s+$//;
1195
[531]1196 # do it all in a transaction
1197 local $dbh->{AutoCommit} = 0;
1198 local $dbh->{RaiseError} = 1;
1199
1200 my @fieldlist;
1201 my @vallist;
[588]1202 foreach ('custid', 'city', 'description', 'notes', 'circuitid', 'privdata', 'rdns') {
[531]1203 if ($args{$_}) {
1204 push @fieldlist, $_;
1205 push @vallist, $args{$_};
1206 }
1207 }
1208
[634]1209 my $binfo;
[531]1210 my $updtable = 'allocations';
[634]1211 my $keyfield = 'id';
[535]1212 if ($args{type} =~ /^(.)i$/) {
[531]1213 $updtable = 'poolips';
[634]1214 $binfo = getBlockData($dbh, $args{block}, 'i');
[531]1215 } else {
1216## fixme: there's got to be a better way...
[634]1217 $binfo = getBlockData($dbh, $args{block});
[531]1218 if ($args{swip}) {
1219 if ($args{swip} eq 'on' || $args{swip} eq '1' || $args{swip} eq 'y') {
1220 $args{swip} = 'y';
1221 } else {
1222 $args{swip} = 'n';
1223 }
1224 }
1225 foreach ('type', 'swip') {
1226 if ($args{$_}) {
1227 push @fieldlist, $_;
1228 push @vallist, $args{$_};
1229 }
1230 }
1231 }
1232
1233 return ('FAIL', 'No fields to update') if !@fieldlist;
1234
[634]1235 push @vallist, $args{block};
[531]1236 my $sql = "UPDATE $updtable SET ";
1237 $sql .= join " = ?, ", @fieldlist;
[634]1238 $sql .= " = ? WHERE $keyfield = ?";
[531]1239
1240 eval {
1241 # do the update
1242 $dbh->do($sql, undef, @vallist);
1243
1244 if ($args{node}) {
1245 # done with delete/insert so we don't have to worry about funkyness updating a node ref that isn't there
[634]1246 $dbh->do("DELETE FROM noderef WHERE block = ?", undef, ($binfo->{block}) );
1247 $dbh->do("INSERT INTO noderef (block,node_id) VALUES (?,?)", undef, ($binfo->{block}, $args{node}) )
1248 if $args{node} ne '--';
[531]1249 }
1250
1251 $dbh->commit;
1252 };
1253 if ($@) {
1254 my $msg = $@;
1255 $dbh->rollback;
1256 return ('FAIL', $msg);
1257 }
[588]1258
[634]1259 $binfo->{block} =~ s|/32$||;
1260 _rpc('addOrUpdateRevRec', cidr => $binfo->{block}, name => $args{rdns}, rpcuser => $args{user});
[588]1261 return ('OK','OK');
[531]1262} # end updateBlock()
1263
1264
[93]1265## IPDB::deleteBlock()
1266# Removes an allocation from the database, including deleting IPs
1267# from poolips and recombining entries in freeblocks if possible
1268# Also handles "deleting" a static IP allocation, and removal of a master
[558]1269# Requires a database handle, the block to delete, the routing depth (if applicable),
[590]1270# the VRF ID, and a flag to indicate whether to delete associated forward DNS entries
1271# as well as the reverse entry
[93]1272sub deleteBlock {
[638]1273 my ($dbh,$id,$basetype,$delfwd,$user) = @_;
[93]1274
[638]1275 # Collect info about the block we're going to delete
1276 my $binfo = getBlockData($dbh, $id, $basetype);
1277 my $cidr = new NetAddr::IP $binfo->{block};
1278
[558]1279# For possible auto-VRF-ignoring (since public IPs shouldn't usually be present in more than one VRF)
1280# is_rfc1918 requires NetAddr::IP >= 4.059
1281# rather than doing this over and over and over.....
1282 my $tmpnum = $cidr->numeric;
1283# 192.168.0.0/16 -> 192.168.255.255 => 3232235520 -> 3232301055
1284# 172.16.0.0/12 -> 172.31.255.255 => 2886729728 -> 2887778303
1285# 10.0.0.0/8 -> 10.255.255.255 => 167772160 -> 184549375
1286 my $isprivnet = (3232235520 <= $tmpnum && $tmpnum <= 3232301055) ||
1287 (2886729728 <= $tmpnum && $tmpnum <= 2887778303) ||
1288 (167772160 <= $tmpnum && $tmpnum <= 184549375);
1289
[93]1290 my $sth;
1291
[349]1292 # Magic variables used for odd allocation cases.
1293 my $container;
1294 my $con_type;
1295
[558]1296
1297 # temporarily forced null, until a sane UI for VRF tracking can be found.
[638]1298# $vrf = '';# if !$vrf; # as with SQL, the null value is not equal to ''. *sigh*
[558]1299
[93]1300 # To contain the error message, if any.
[558]1301 my $msg = "Unknown error deallocating $binfo->{type} $cidr";
1302 my $goback; # to put the parent in so we can link back where the deallocate started
1303
[93]1304 # Enable transactions and exception-on-errors... but only for this sub
1305 local $dbh->{AutoCommit} = 0;
1306 local $dbh->{RaiseError} = 1;
1307
[558]1308 if ($binfo->{type} =~ /^.i$/) {
[638]1309 # First case. The "block" is a static IP
1310 # Note that we still need some additional code in the odd case
1311 # of a netblock-aligned contiguous group of static IPs
[93]1312
1313 eval {
[558]1314 $msg = "Unable to deallocate $disp_alloctypes{$binfo->{type}} $cidr";
[638]1315 my $pinfo = getBlockData($dbh, $binfo->{parent_id}, 'b');
[558]1316##fixme: VRF and rdepth
[638]1317 $dbh->do("UPDATE poolips SET custid = ?, available = 'y',".
1318 "city = (SELECT city FROM allocations WHERE id = ?),".
1319 "description = '', notes = '', circuitid = '', vrf = ? WHERE id = ?", undef,
1320 ($pinfo->{custid}, $binfo->{parent_id}, $pinfo->{vrf}, $id) );
[93]1321 $dbh->commit;
1322 };
1323 if ($@) {
[558]1324 $msg .= ": $@";
[93]1325 eval { $dbh->rollback; };
1326 return ('FAIL',$msg);
1327 } else {
[590]1328##fixme: RPC return code?
[638]1329 _rpc('delByCIDR', cidr => "$cidr", user => $user, delforward => $delfwd, rpcuser => $user);
[93]1330 return ('OK',"OK");
1331 }
1332
[558]1333 } elsif ($binfo->{type} eq 'mm') { # end alloctype =~ /.i/
[638]1334 # Second case. The block is a full master block
[93]1335
[558]1336##fixme: VRF limit
[93]1337 $msg = "Unable to delete master block $cidr";
1338 eval {
[638]1339 $dbh->do("DELETE FROM allocations WHERE cidr <<= ? AND master_id = ?", undef, ($cidr, $binfo->{master_id}) );
1340 $dbh->do("DELETE FROM freeblocks WHERE cidr <<= ? AND master_id = ?", undef, ($cidr, $binfo->{master_id}) );
[93]1341 $dbh->commit;
1342 };
1343 if ($@) {
[558]1344 $msg .= ": $@";
[93]1345 eval { $dbh->rollback; };
1346 return ('FAIL', $msg);
[591]1347 }
1348
1349 # Have to handle potentially split reverse zones. Assume they *are* split,
1350 # since if we added them here, they would have been added split.
1351# allow splitting reverse zones to be disabled, maybe, someday
1352#if ($splitrevzones && !$cidr->{isv6}) {
1353 my @zonelist;
1354 if (1 && !$cidr->{isv6}) {
1355 my $splitpoint = ($cidr->masklen <= 16 ? 16 : 24); # hack pthui
1356 @zonelist = $cidr->split($splitpoint);
[93]1357 } else {
[591]1358 @zonelist = ($cidr);
[93]1359 }
[591]1360 my @fails;
1361 foreach my $subzone (@zonelist) {
[638]1362 if ($rpc_url && !_rpc('delZone', zone => "$subzone", revrec => 'y', rpcuser => $user, delforward => $delfwd) ) {
[591]1363 push @fails, ("$subzone" => $errstr);
1364 }
1365 }
1366 if (@fails) {
1367 return ('WARN',"Warning(s) deleting $cidr from reverse DNS:\n".join("\n", @fails));
1368 }
1369 return ('OK','OK');
[93]1370
1371 } else { # end alloctype master block case
1372
1373 ## This is a big block; but it HAS to be done in a chunk. Any removal
1374 ## of a netblock allocation may result in a larger chunk of free
1375 ## contiguous IP space - which may in turn be combined into a single
1376 ## netblock rather than a number of smaller netblocks.
1377
[558]1378 my $retcode = 'OK';
[638]1379 my ($ptype,$pcity,$ppatt,$p_id);
[558]1380
[93]1381 eval {
1382
[558]1383##fixme: add recursive flag to allow "YES DAMMIT DELETE ALL EVARYTHING!!1!!" without
1384# explicitly deleting any suballocations of the block to be deleted.
[93]1385
[638]1386 # get parent info of the block we're deleting
1387 my $pinfo = getBlockData($dbh, $binfo->{parent_id});
1388 $ptype = $pinfo->{type};
1389 $pcity = $pinfo->{city};
1390 $ppatt = $pinfo->{rdns};
1391 $p_id = $binfo->{parent_id};
[93]1392
[558]1393 # Delete the block
[638]1394 $dbh->do("DELETE FROM allocations WHERE id = ?", undef, ($id) );
[349]1395
[558]1396 # munge the parent type a little
[638]1397 $ptype = (split //, $ptype)[1];
[93]1398
[558]1399##fixme: you can't... CAN NOT.... assign the same public IP to multiple things.
1400# 'Net don't work like that, homey. Restrict VRF-uniqueness to private IPs?
1401# -> $isprivnet flag from start of sub
[93]1402
[558]1403 # check to see if any container allocations could be the "true" parent
[638]1404 my ($tparent,$tpar_id,$trtype,$tcity);
1405 $tpar_id = 0;
[404]1406
[638]1407##fixme: this is far simpler in the strict VRF case; we "know" that any allocation
1408# contained by a container is a part of the same allocation tree when the VRF fields are equal.
[558]1409
[638]1410# logic:
1411# For each possible container of $cidr
1412# note the parent id
1413# walk the chain up the parents
1414# if we intersect $cidr's current parent, break
1415# if we've intersected $cidr's current parent
1416# set some variables to track that block
1417# break
[558]1418
[638]1419# Set up part of "is it in the middle of a pool?" check
1420 my $wuzpool = $dbh->selectrow_hashref("SELECT cidr,parent_id,type,city,custid,id FROM allocations ".
1421 "WHERE (type LIKE '_d' OR type LIKE '_p') AND cidr >> ? AND master_id = ?", { Slice => {} },
1422 ($cidr, $binfo->{master_id}) );
[558]1423
[638]1424##fixme?
1425# edge cases not handled, or handled badly:
1426# -> $cidr managed to get to be the entirety of an IP pool
[558]1427
[638]1428 if ($wuzpool && $wuzpool->{id} != $id) {
1429 # we have legacy goo to be purified
1430 # going to ignore nested pools; not possible to create them via API and no current legacy data includes any.
1431
1432 # for convenience
1433 my $poolid = $wuzpool->{id};
1434 my $pool = $wuzpool->{cidr};
1435 my $poolcity = $wuzpool->{city};
1436 my $pooltype = $wuzpool->{type};
1437 my $poolcustid = $wuzpool->{custid};
1438
1439 $retcode = 'WARNPOOL';
1440 $goback = "$poolid,$pool";
1441 # We've already deleted the block, now we have to stuff its IPs into the pool.
1442 $pooltype =~ s/[dp]$/i/; # change type to static IP
1443 my $sth2 = $dbh->prepare("INSERT INTO poolips (ip,city,type,custid,parent_id) VALUES ".
1444 "(?,'$poolcity','$pooltype','$poolcustid',$poolid)");
[429]1445##fixme: need to not insert net, gateway, and bcast on "real netblock" pools (DHCPish)
[638]1446 # don't insert .0
1447 $sth2->execute($cidr->addr) unless $cidr->addr =~ m|\.0$|;
1448 foreach my $ip ($cidr->hostenum) {
1449 $sth2->execute($ip);
1450 }
1451 $cidr--;
1452 # don't insert .255
1453 $sth2->execute($cidr->addr) unless $cidr->addr =~ m|\.255$|;
1454 }
[93]1455
[638]1456## important!
1457# ... or IS IT?
1458# we may have undef'ed $wuzpool above, if the allocation tree $cidr is in doesn't intersect the pool we found
1459#if (!$wuzpool) {
1460
1461 else {
1462
1463 # Get all possible (and probably a number of impossible) containers for $cidr
1464 $sth = $dbh->prepare("SELECT cidr,parent_id,type,city,id FROM allocations ".
1465 "WHERE (type LIKE '_m' OR type LIKE '_c') AND cidr >>= ? AND master_id = ? ".
1466 "ORDER BY masklen(cidr) DESC");
1467 $sth->execute($cidr, $binfo->{master_id});
1468
1469 # Quickly get certain fields (simpler than getBlockData()
1470 my $sth2 = $dbh->prepare("SELECT cidr,parent_id,type,city FROM allocations ".
1471 "WHERE (type LIKE '_m' OR type LIKE '_c') AND id = ? AND master_id = ?");
1472
1473 # For each possible container of $cidr...
1474 while (my @data = $sth->fetchrow_array) {
1475 my $i = 0;
1476 # Save some state and set a start point - parent ID of container we're checking
1477 $tparent = $data[0];
1478 my $ppid = $data[1];
1479 $trtype = $data[2];
1480 $tcity = $data[3];
1481 $tpar_id = $data[4];
1482 last if $data[4] == $binfo->{parent_id}; # Preemptively break if we're already in the right place
1483 last if $ppid == $binfo->{parent_id}; # ... or if the parent of the container is the block's parent
1484 while (1) {
1485 # Retrieve bits on that parent ID
1486 $sth2->execute($ppid, $binfo->{master_id});
1487 my @container = $sth2->fetchrow_array;
1488 $ppid = $container[1];
1489 last if $container[1] == 0; # Break if we've hit a master block
1490 last if $ppid == $binfo->{parent_id}; # Break if we've reached the block $cidr is currently in
1491 }
1492 last if $ppid == $binfo->{parent_id};
1493 }
1494
1495 # found an alternate parent; reset some parent-info bits
1496 if ($tpar_id != $binfo->{parent_id}) {
1497 $ptype = (split //, $trtype)[1];
1498 $pcity = $tcity;
1499 $retcode = 'WARNMERGE'; # may be redundant
1500 $p_id = $tpar_id;
1501 }
1502
1503 $goback = "$p_id,$tparent"; # breadcrumb, currently only used in case of live-parent-is-not-true-parent
1504
1505 # Special case - delete pool IPs
1506 if ($binfo->{type} =~ /^.[pd]$/) {
1507 # We have to delete the IPs from the pool listing.
1508 $dbh->do("DELETE FROM poolips WHERE parent_id = ?", undef, ($id) );
1509 }
1510
1511 $pinfo = getBlockData($dbh, $p_id);
1512
[558]1513 # If the block wasn't legacy goo embedded in a static pool, we check the
1514 # freeblocks in the identified parent to see if we can combine any of them.
[93]1515
[559]1516 # if the block to be deleted is a container, move its freeblock(s) up a level, and reset their parenting info
1517 if ($binfo->{type} =~ /^.[mc]/) {
1518 # move the freeblocks into the parent
1519 # we don't insert a new freeblock because there could be a live reparented sub.
[638]1520 $dbh->do("UPDATE freeblocks SET parent_id = ?, routed = ?, city = ? WHERE parent_id = ?", undef,
1521 ($p_id, $ptype, $pcity, $id) );
[559]1522 } else {
1523 # ... otherwise, add the freeblock
[638]1524 $dbh->do("INSERT INTO freeblocks (cidr, city, routed, parent_id, master_id) VALUES (?,?,?,?,?)", undef,
1525 ($cidr, $pcity, $ptype, $p_id, $binfo->{master_id}) );
[559]1526 }
1527
[558]1528##fixme: vrf
[638]1529##fixme: simplify since all containers now represent different "layers"/"levels"?
[558]1530 # set up the query to get the list of blocks to try to merge.
[638]1531 $sth = $dbh->prepare("SELECT cidr,id FROM freeblocks ".
1532 "WHERE parent_id = ? ".
[558]1533 "ORDER BY masklen(cidr) DESC");
[428]1534
[638]1535 $sth->execute($p_id);
[558]1536
[93]1537# NetAddr::IP->compact() attempts to produce the smallest inclusive block
1538# from the caller and the passed terms.
1539# EG: if you call $cidr->compact($ip1,$ip2,$ip3) when $cidr, $ip1, $ip2,
1540# and $ip3 are consecutive /27's starting on .0 (.0-.31, .32-.63,
1541# .64-.95, and .96-.128), you will get an array containing a single
1542# /25 as element 0 (.0-.127). Order is not important; you could have
1543# $cidr=.32/27, $ip1=.96/27, $ip2=.0/27, and $ip3=.64/27.
1544
[638]1545 my (@rawfb, @combinelist, %rawid);
[428]1546 my $i=0;
[558]1547 # for each free block under $parent, push a NetAddr::IP object into one list, and
1548 # continuously use NetAddr::IP->compact to automagically merge netblocks as possible.
[428]1549 while (my @data = $sth->fetchrow_array) {
1550 my $testIP = new NetAddr::IP $data[0];
[558]1551 push @rawfb, $testIP;
[638]1552 $rawid{$data[0]} = $data[1];
[558]1553 @combinelist = $testIP->compact(@combinelist);
[93]1554 }
1555
[558]1556 # now that we have the full list of "compacted" freeblocks, go back over
1557 # the list of raw freeblocks, and delete the ones that got merged.
[638]1558 $sth = $dbh->prepare("DELETE FROM freeblocks WHERE id = ?");
[558]1559 foreach my $rawfree (@rawfb) {
1560 next if grep { $rawfree == $_ } @combinelist; # skip if the raw block is in the compacted list
[638]1561 $sth->execute($rawid{$rawfree});
[558]1562 }
[93]1563
[558]1564 # now we walk the new list of compacted blocks, and see which ones we need to insert
[638]1565 $sth = $dbh->prepare("INSERT INTO freeblocks (cidr,city,routed,parent_id,master_id) VALUES (?,?,?,?,?)");
[558]1566 foreach my $cme (@combinelist) {
1567 next if grep { $cme == $_ } @rawfb; # skip if the combined block was in the raw list
[638]1568 $sth->execute($cme, $pcity, $ptype, $p_id, $binfo->{master_id});
[428]1569 }
[93]1570
[428]1571 } # done returning IPs to the appropriate place
[404]1572
[93]1573 # If we got here, we've succeeded. Whew!
1574 $dbh->commit;
1575 }; # end eval
1576 if ($@) {
[558]1577 $msg .= ": $@";
[93]1578 eval { $dbh->rollback; };
1579 return ('FAIL', $msg);
1580 } else {
[590]1581##fixme: RPC return code?
[638]1582 _rpc('delByCIDR', cidr => "$cidr", rpcuser => $user, delforward => $delfwd, delsubs => 'y', parpatt => $ppatt);
[558]1583 return ($retcode, $goback);
[93]1584 }
1585
1586 } # end alloctype != netblock
1587
1588} # end deleteBlock()
1589
1590
[370]1591## IPDB::getBlockData()
[557]1592# Get CIDR or IP, custid, type, city, circuit ID, description, notes, modification time,
1593# private/restricted data, for a CIDR block or pool IP
1594# Also returns SWIP status flag for CIDR blocks or pool netblock for IPs
[636]1595# Takes the block ID or IP to look up and an optional flag to indicate a pool IP lookup
1596# instead of a netblock.
[557]1597# Returns a hashref to the block data
[370]1598sub getBlockData {
1599 my $dbh = shift;
[636]1600 my $id = shift;
1601 my $type = shift || 'b'; # default to netblock for lazy callers
[370]1602
[636]1603 # netblocks are in the allocations table; pool IPs are in the poolips table.
1604 # If we try to look up a CIDR in an integer field we should just get back nothing.
1605 my ($btype) = $dbh->selectrow_array("SELECT type FROM allocations WHERE id=?", undef, ($id) );
[534]1606
[636]1607 if ($type eq 'i') {
[557]1608 my $binfo = $dbh->selectrow_hashref("SELECT ip AS block, custid, type, city, circuitid, description,".
[636]1609 " notes, modifystamp AS lastmod, privdata, vrf, rdns, parent_id, master_id".
1610 " FROM poolips WHERE id = ?", undef, ($id) );
[557]1611 return $binfo;
1612 } else {
[636]1613 my $binfo = $dbh->selectrow_hashref("SELECT cidr AS block, custid, type, city, circuitid, ".
1614 "description, notes, modifystamp AS lastmod, privdata, vrf, swip, rdns, parent_id, master_id".
1615 " FROM allocations WHERE id = ?", undef, ($id) );
[557]1616 return $binfo;
[534]1617 }
[370]1618} # end getBlockData()
1619
1620
[585]1621## IPDB::getBlockRDNS()
1622# Gets reverse DNS pattern for a block or IP. Note that this will also
1623# retrieve any default pattern following the parent chain up, and check via
1624# RPC (if available) to see what the narrowest pattern for the requested block is
1625# Returns the current pattern for the block or IP.
1626sub getBlockRDNS {
1627 my $dbh = shift;
1628 my %args = @_;
1629
[637]1630 $args{type} = 'b' if !$args{type};
[585]1631
[637]1632 # snag entry from database
1633 my ($rdns,$rfrom,$pid);
1634 if ($args{type} =~ /.i/) {
1635 ($rdns, $rfrom, $pid) = $dbh->selectrow_array("SELECT rdns,ip,parent_id FROM poolips WHERE id = ?",
1636 undef, ($args{id}) );
1637 } else {
1638 ($rdns, $rfrom, $pid) = $dbh->selectrow_array("SELECT rdns,cidr,parent_id FROM allocations WHERE id = ?",
1639 undef, ($args{id}) );
1640 }
[585]1641
[637]1642 # Can't see a way this could end up empty, for any case I care about. If the caller
1643 # doesn't know an allocation ID to request, then they don't know anything else anyway.
1644 my $selfblock = $rfrom;
[585]1645
[637]1646 my $type;
1647 while (!$rdns && $pid) {
1648 ($rdns, $rfrom, $pid, $type) = $dbh->selectrow_array(
1649 "SELECT rdns,cidr,parent_id,type FROM allocations WHERE id = ?",
1650 undef, ($pid) );
1651 last if $type eq 'mm'; # break loops in unfortunate legacy data
1652 }
1653
1654 # use the actual allocation to check against the DNS utility; we don't want
1655 # to always go chasing up the chain to the master... which may (usually won't)
1656 # be present directly in DNS anyway
1657 my $cidr = new NetAddr::IP $selfblock;
1658
[585]1659 if ($rpc_url) {
1660 # Use the first /16 or /24, rather than dithering over which sub-/14 /16
1661 # or sub-/19 /24 to retrieve - it's the least-wrong way to do things.
1662
[586]1663 my ($rpcblock) = ($cidr->masklen <= 24 ? $cidr->split( ($cidr->masklen <= 16 ? 16 : 24) ) : $cidr);
[585]1664 my %rpcargs = (
1665 rpcuser => $args{user},
1666 group => $revgroup, # not sure how this could sanely be exposed, tbh...
1667 cidr => "$rpcblock",
1668 );
1669
[637]1670 my $remote_rdns = _rpc('getRevPattern', %rpcargs);
1671 $rdns = $remote_rdns if $remote_rdns;
[585]1672 }
1673
1674 # hmm. do we care about where it actually came from?
1675 return $rdns;
1676} # end getBlockRDNS()
1677
1678
[519]1679## IPDB::getNodeList()
1680# Gets a list of node ID+name pairs as an arrayref to a list of hashrefs
1681sub getNodeList {
1682 my $dbh = shift;
1683
1684 my $ret = $dbh->selectall_arrayref("SELECT node_id, node_name FROM nodes ORDER BY node_type,node_id",
1685 { Slice => {} });
1686 return $ret;
1687} # end getNodeList()
1688
1689
[530]1690## IPDB::getNodeName()
1691# Get node name from the ID
1692sub getNodeName {
1693 my $dbh = shift;
1694 my $nid = shift;
1695
1696 my ($nname) = $dbh->selectrow_array("SELECT node_name FROM nodes WHERE node_id = ?", undef, ($nid) );
1697 return $nname;
1698} # end getNodeName()
1699
1700
1701## IPDB::getNodeInfo()
1702# Get node name and ID associated with a block
1703sub getNodeInfo {
1704 my $dbh = shift;
1705 my $block = shift;
1706
1707 my ($nid, $nname) = $dbh->selectrow_array("SELECT nodes.node_id,node_name FROM nodes INNER JOIN noderef".
1708 " ON nodes.node_id=noderef.node_id WHERE noderef.block = ?", undef, ($block) );
1709 return ($nid, $nname);
1710} # end getNodeInfo()
1711
1712
[77]1713## IPDB::mailNotify()
[66]1714# Sends notification mail to recipients regarding an IPDB operation
[416]1715sub mailNotify {
1716 my $dbh = shift;
1717 my ($action,$subj,$message) = @_;
[66]1718
[462]1719 return if $smtphost eq 'smtp.example.com'; # do nothing if still using default SMTP host.
1720
[422]1721##fixme: need to redesign the breakdown/processing for $action for proper handling of all cases
1722
[416]1723# split action into parts for fiddlement. nb: there are almost certainly better ways to do this.
[422]1724 my @actionbits = split //, $action;
[416]1725
1726 # want to notify anyone who has specifically requested notify on *this* type ($action as passed),
1727 # on "all static IP types" or "all pool types" (and other last-char-in-type groupings), on eg "all DSL types",
1728 # and "all events with this action"
1729 my @actionsets = ($action);
1730##fixme: ick, eww. really gotta find a better way to handle this...
1731 push @actionsets, ($actionbits[0].'.'.$actionbits[2],
1732 $actionbits[0].$actionbits[1].'.', $actionbits[0].'a') if $action =~ /^.{3}$/;
1733
1734 my $mailer = Net::SMTP->new($smtphost, Hello => "ipdb.$domain");
1735
1736 # get recip list from db
1737 my $sth = $dbh->prepare("SELECT reciplist FROM notify WHERE action=?");
1738
[443]1739 my %reciplist;
[416]1740 foreach (@actionsets) {
[426]1741 $sth->execute($_);
[416]1742##fixme - need to handle db errors
1743 my ($recipsub) = $sth->fetchrow_array;
1744 next if !$recipsub;
1745 foreach (split(/,/, $recipsub)) {
[443]1746 $reciplist{$_}++;
[416]1747 }
1748 }
1749
[443]1750 return if !%reciplist;
[420]1751
[443]1752 foreach my $recip (keys %reciplist) {
[416]1753 $mailer->mail("ipdb\@$domain");
1754 $mailer->to($recip);
[422]1755 $mailer->data("From: \"$org_name IP Database\" <ipdb\@$domain>\n",
[135]1756 "To: $recip\n",
[69]1757 "Date: ".strftime("%a, %d %b %Y %H:%M:%S %z",localtime)."\n",
1758 "Subject: {IPDB} $subj\n",
1759 "X-Mailer: IPDB Notify v".sprintf("%.1d",$IPDB::VERSION)."\n",
[417]1760 "Organization: $org_name\n",
[69]1761 "\n$message\n");
[416]1762 }
[66]1763 $mailer->quit;
1764}
1765
[4]1766# Indicates module loaded OK. Required by Perl.
17671;
Note: See TracBrowser for help on using the repository browser.