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

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

/trunk

Allocation update should be complete for DNS changes. See #1.

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