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

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

/trunk

Fix subtle bug in deleting IPv6 blocks; the text representation coming
out of the database is not the normal stringification from NetAddr::IP

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