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

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

/trunk

Backmerge addition of RPC shim from /branches/stable r600

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