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

Last change on this file since 590 was 590, checked in by Kris Deugau, 11 years ago

/trunk

RPC integration for allocation-delete should be complete. See #1.
Requires dnsadmin:/trunk@r459 or newer.

  • Pass a couple more bits into deleteBlock()
  • Use the new values when making the RPC call
  • Rearrange the delete-confirm page a little to allow the new "delete forward DNS too?" checkbox to actually contribute
  • Tweak new-allocation RPC call a little; don't bother if no rDNS was passed in.
  • Property svn:keywords set to Date Rev Author
File size: 56.0 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-22 22:31:53 +0000 (Tue, 22 Jan 2013) $
6# SVN revision $Rev: 590 $
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 and a pattern to use.
1035 _rpc('addOrUpdateRevRec', cidr => "$args{cidr}", name => $args{rdns}, rpcuser => $args{user})
1036 if $args{rdns};
1037
1038 return ('OK', 'OK');
1039
1040 } # end static-IP vs netblock allocation
1041
1042} # end allocateBlock()
1043
1044
1045## IPDB::initPool()
1046# Initializes a pool
1047# Requires a database handle, the pool CIDR, type, city, and a parameter
1048# indicating whether the pool should allow allocation of literally every
1049# IP, or if it should reserve network/gateway/broadcast IPs
1050# Note that this is NOT done in a transaction, that's why it's a private
1051# function and should ONLY EVER get called from allocateBlock()
1052sub initPool {
1053 my ($dbh,undef,$type,$city,$class,$rdepth) = @_;
1054 my $pool = new NetAddr::IP $_[1];
1055
1056 # IPv6 does not lend itself to IP pools as supported
1057 return ('FAIL',"Refusing to create IPv6 static IP pool") if $pool->{isv6};
1058 # IPv4 pools don't make much sense beyond even /24. Allow up to 4096-host footshooting anyway.
1059 # NetAddr::IP won't allow more than a /16 (65k hosts).
1060 return ('FAIL',"Refusing to create oversized static IP pool") if $pool->masklen <= 20;
1061
1062##fixme Need to just replace 2nd char of type with i rather than capturing 1st char of type
1063 $type =~ s/[pd]$/i/;
1064 my $sth;
1065 my $msg;
1066
1067 # Trap errors so we can pass them back to the caller. Even if the
1068 # caller is only ever supposed to be local, and therefore already
1069 # trapping errors. >:(
1070 local $dbh->{AutoCommit} = 0; # These need to be local so we don't
1071 local $dbh->{RaiseError} = 1; # step on our toes by accident.
1072
1073 eval {
1074 # have to insert all pool IPs into poolips table as "unallocated".
1075 $sth = $dbh->prepare("INSERT INTO poolips (pool,ip,custid,city,type,rdepth)".
1076 " VALUES ('$pool', ?, '$defcustid', ?, '$type', $rdepth)");
1077 my @poolip_list = $pool->hostenum;
1078 if ($class eq 'all') { # (DSL-ish block - *all* IPs available
1079 if ($pool->addr !~ /\.0$/) { # .0 causes weirdness.
1080 $sth->execute($pool->addr, $city);
1081 }
1082 for (my $i=0; $i<=$#poolip_list; $i++) {
1083 $sth->execute($poolip_list[$i]->addr, $city);
1084 }
1085 $pool--;
1086 if ($pool->addr !~ /\.255$/) { # .255 can cause weirdness.
1087 $sth->execute($pool->addr, $city);
1088 }
1089 } else { # (real netblock)
1090 for (my $i=1; $i<=$#poolip_list; $i++) {
1091 $sth->execute($poolip_list[$i]->addr, $city);
1092 }
1093 }
1094 $dbh->commit;
1095 };
1096 if ($@) {
1097 $msg = $@;
1098 eval { $dbh->rollback; };
1099 return ('FAIL',$msg);
1100 } else {
1101 return ('OK',"OK");
1102 }
1103} # end initPool()
1104
1105
1106## IPDB::updateBlock()
1107# Update an allocation
1108# Takes all allocation fields in a hash
1109sub updateBlock {
1110 my $dbh = shift;
1111 my %args = @_;
1112
1113 return ('FAIL', 'Missing block to update') if !$args{block};
1114
1115 # do it all in a transaction
1116 local $dbh->{AutoCommit} = 0;
1117 local $dbh->{RaiseError} = 1;
1118
1119 my @fieldlist;
1120 my @vallist;
1121 foreach ('custid', 'city', 'description', 'notes', 'circuitid', 'privdata', 'rdns') {
1122 if ($args{$_}) {
1123 push @fieldlist, $_;
1124 push @vallist, $args{$_};
1125 }
1126 }
1127
1128 my $updtable = 'allocations';
1129 my $keyfield = 'cidr';
1130 if ($args{type} =~ /^(.)i$/) {
1131 $updtable = 'poolips';
1132 $keyfield = 'ip';
1133 } else {
1134## fixme: there's got to be a better way...
1135 if ($args{swip}) {
1136 if ($args{swip} eq 'on' || $args{swip} eq '1' || $args{swip} eq 'y') {
1137 $args{swip} = 'y';
1138 } else {
1139 $args{swip} = 'n';
1140 }
1141 }
1142 foreach ('type', 'swip') {
1143 if ($args{$_}) {
1144 push @fieldlist, $_;
1145 push @vallist, $args{$_};
1146 }
1147 }
1148 }
1149
1150 return ('FAIL', 'No fields to update') if !@fieldlist;
1151
1152# push @vallist, $args{block}, $args{rdepth}, $args{vrf};
1153 push @vallist, $args{block}, $args{rdepth};
1154 my $sql = "UPDATE $updtable SET ";
1155 $sql .= join " = ?, ", @fieldlist;
1156# $sql .= " = ? WHERE $keyfield = ? AND rdepth = ? AND vrf = ?";
1157 $sql .= " = ? WHERE $keyfield = ? AND rdepth = ? ";
1158
1159 eval {
1160 # do the update
1161 $dbh->do($sql, undef, @vallist);
1162
1163 if ($args{node}) {
1164 # done with delete/insert so we don't have to worry about funkyness updating a node ref that isn't there
1165 $dbh->do("DELETE FROM noderef WHERE block = ?", undef, ($args{block}) );
1166 $dbh->do("INSERT INTO noderef (block,node_id) VALUES (?,?)", undef, ($args{block}, $args{node}) );
1167 }
1168
1169 $dbh->commit;
1170 };
1171 if ($@) {
1172 my $msg = $@;
1173 $dbh->rollback;
1174 return ('FAIL', $msg);
1175 }
1176
1177 _rpc('addOrUpdateRevRec', cidr => $args{block}, name => $args{rdns}, rpcuser => $args{user});
1178 return ('OK','OK');
1179} # end updateBlock()
1180
1181
1182## IPDB::deleteBlock()
1183# Removes an allocation from the database, including deleting IPs
1184# from poolips and recombining entries in freeblocks if possible
1185# Also handles "deleting" a static IP allocation, and removal of a master
1186# Requires a database handle, the block to delete, the routing depth (if applicable),
1187# the VRF ID, and a flag to indicate whether to delete associated forward DNS entries
1188# as well as the reverse entry
1189sub deleteBlock {
1190 my ($dbh,undef,$rdepth,$vrf,$delfwd,$user) = @_;
1191 my $cidr = new NetAddr::IP $_[1];
1192
1193# For possible auto-VRF-ignoring (since public IPs shouldn't usually be present in more than one VRF)
1194# is_rfc1918 requires NetAddr::IP >= 4.059
1195# rather than doing this over and over and over.....
1196 my $tmpnum = $cidr->numeric;
1197# 192.168.0.0/16 -> 192.168.255.255 => 3232235520 -> 3232301055
1198# 172.16.0.0/12 -> 172.31.255.255 => 2886729728 -> 2887778303
1199# 10.0.0.0/8 -> 10.255.255.255 => 167772160 -> 184549375
1200 my $isprivnet = (3232235520 <= $tmpnum && $tmpnum <= 3232301055) ||
1201 (2886729728 <= $tmpnum && $tmpnum <= 2887778303) ||
1202 (167772160 <= $tmpnum && $tmpnum <= 184549375);
1203
1204 my $sth;
1205
1206 # Magic variables used for odd allocation cases.
1207 my $container;
1208 my $con_type;
1209
1210 # Collect info about the block we're going to delete
1211 my $binfo = getBlockData($dbh, $cidr, $rdepth, $vrf);
1212
1213 # temporarily forced null, until a sane UI for VRF tracking can be found.
1214 $vrf = '';# if !$vrf; # as with SQL, the null value is not equal to ''. *sigh*
1215
1216 # To contain the error message, if any.
1217 my $msg = "Unknown error deallocating $binfo->{type} $cidr";
1218 my $goback; # to put the parent in so we can link back where the deallocate started
1219
1220 # Enable transactions and exception-on-errors... but only for this sub
1221 local $dbh->{AutoCommit} = 0;
1222 local $dbh->{RaiseError} = 1;
1223
1224 # First case. The "block" is a static IP
1225 # Note that we still need some additional code in the odd case
1226 # of a netblock-aligned contiguous group of static IPs
1227 if ($binfo->{type} =~ /^.i$/) {
1228
1229 eval {
1230 $msg = "Unable to deallocate $disp_alloctypes{$binfo->{type}} $cidr";
1231 my ($pool,$pcust,$pvrf) = $dbh->selectrow_array("SELECT pool,custid,vrf FROM poolips WHERE ip=?", undef, ($cidr) );
1232##fixme: VRF and rdepth
1233 $dbh->do("UPDATE poolips SET custid=?,available='y',".
1234 "city=(SELECT city FROM allocations WHERE cidr=?),".
1235 "description='',notes='',circuitid='',vrf=? WHERE ip=?", undef, ($pcust, $pool, $pvrf, $cidr) );
1236 $goback = $pool;
1237 $dbh->commit;
1238 };
1239 if ($@) {
1240 $msg .= ": $@";
1241 eval { $dbh->rollback; };
1242 return ('FAIL',$msg);
1243 } else {
1244##fixme: RPC return code?
1245 _rpc('delByCIDR', cidr => "$cidr", user => $user, delforward => $delfwd);
1246 return ('OK',"OK");
1247 }
1248
1249 } elsif ($binfo->{type} eq 'mm') { # end alloctype =~ /.i/
1250
1251##fixme: VRF limit
1252 $msg = "Unable to delete master block $cidr";
1253 eval {
1254 $dbh->do("DELETE FROM masterblocks WHERE cidr = ?", undef, ($cidr) );
1255 $dbh->do("DELETE FROM allocations WHERE cidr <<= ?", undef, ($cidr) );
1256 $dbh->do("DELETE FROM freeblocks WHERE cidr <<= ?", undef, ($cidr) );
1257 $dbh->commit;
1258 };
1259 if ($@) {
1260 $msg .= ": $@";
1261 eval { $dbh->rollback; };
1262 return ('FAIL', $msg);
1263 } else {
1264##fixme: RPC return code?
1265 _rpc('delZone', zone => "$cidr", user => $user, revrec => 'y');
1266 return ('OK',"OK");
1267 }
1268
1269 } else { # end alloctype master block case
1270
1271 ## This is a big block; but it HAS to be done in a chunk. Any removal
1272 ## of a netblock allocation may result in a larger chunk of free
1273 ## contiguous IP space - which may in turn be combined into a single
1274 ## netblock rather than a number of smaller netblocks.
1275
1276 my $retcode = 'OK';
1277
1278 eval {
1279
1280##fixme: add recursive flag to allow "YES DAMMIT DELETE ALL EVARYTHING!!1!!" without
1281# explicitly deleting any suballocations of the block to be deleted.
1282
1283 # find the current parent of the block we're deleting
1284 my ($parent) = $dbh->selectrow_array("SELECT parent FROM allocations WHERE cidr=? AND rdepth=?",
1285 undef, ($cidr, $rdepth) );
1286
1287 # Delete the block
1288 $dbh->do("DELETE FROM allocations WHERE cidr=? AND rdepth=?", undef, ($cidr, $rdepth) );
1289
1290##fixme: we could maybe eliminate a special case if we put masterblocks in the allocations table...?
1291 my ($ptype,$pcity);
1292 if ($rdepth == 1) {
1293 # parent is a master block.
1294 $ptype = 'mm';
1295 $pcity = '<NULL>';
1296 } else {
1297 # get that parent's details
1298 ($ptype,$pcity) = $dbh->selectrow_array("SELECT type,city FROM allocations ".
1299 "WHERE cidr=? AND rdepth=?", undef, ($parent, $rdepth-1) );
1300 }
1301
1302 # munge the parent type a little
1303 $ptype = (split //, $ptype)[0];
1304
1305##fixme: you can't... CAN NOT.... assign the same public IP to multiple things.
1306# 'Net don't work like that, homey. Restrict VRF-uniqueness to private IPs?
1307# -> $isprivnet flag from start of sub
1308
1309 my $fbrdepth = $rdepth;
1310
1311 # check to see if any container allocations could be the "true" parent
1312 my ($tparent,$trdepth,$trtype,$tcity) = $dbh->selectrow_array("SELECT cidr,rdepth,type,city FROM allocations ".
1313 "WHERE (type='rm' OR type LIKE '_c') AND cidr >> ? ".
1314 "ORDER BY masklen(cidr) DESC", undef, ($cidr) );
1315
1316 my $fparent;
1317 if ($tparent && $tparent ne $parent) {
1318 # found an alternate parent; reset some parent-info bits
1319 $parent = $tparent;
1320 $ptype = (split //, $trtype)[0];
1321 $pcity = $tcity;
1322 ##fixme: hmm. collect $rdepth into $goback here before vanishing?
1323 $retcode = 'WARN'; # may be redundant
1324 $goback = $tparent;
1325 # munge freeblock rdepth and parent to match true parent
1326 $dbh->do("UPDATE freeblocks SET rdepth = ?, parent = ?, routed = ? WHERE cidr <<= ? AND rdepth = ?", undef,
1327 ($trdepth+1, $parent, $ptype, $cidr, $rdepth) );
1328 $rdepth = $trdepth;
1329 $fbrdepth = $trdepth+1;
1330 }
1331
1332 $parent = new NetAddr::IP $parent;
1333 $goback = "$parent,$fbrdepth"; # breadcrumb in case of live-parent-is-not-true-parent
1334
1335 # Special case - delete pool IPs
1336 if ($binfo->{type} =~ /^.[pd]$/) {
1337 # We have to delete the IPs from the pool listing.
1338##fixme: rdepth? vrf?
1339 $dbh->do("DELETE FROM poolips WHERE pool = ?", undef, ($cidr) );
1340 }
1341
1342 # Find out if the block we're deallocating is within a DSL pool (legacy goo)
1343 my ($pool,$poolcity,$pooltype,$pooldepth) = $dbh->selectrow_array(
1344 "SELECT cidr,city,type,rdepth FROM allocations WHERE type LIKE '_p' AND cidr >>= ?",
1345 undef, ($cidr) );
1346
1347 # If so, return the block's IPs to the pool, instead of to freeblocks
1348## NB: not possible to currently cause this even via admin tools, only legacy data.
1349 if ($pool) {
1350 ## Deallocate legacy blocks stashed in the middle of a static IP pool
1351 ## This may be expandable to an even more general case of contained netblock, or other pool types.
1352 $retcode = 'WARNPOOL';
1353 $goback = "$pool,$pooldepth";
1354 # We've already deleted the block, now we have to stuff its IPs into the pool.
1355 $pooltype =~ s/p$/i/; # change type to static IP
1356 my $sth2 = $dbh->prepare("INSERT INTO poolips (pool,ip,city,type,custid) VALUES ".
1357 "('$pool',?,'$poolcity','$pooltype','$defcustid')");
1358 # don't insert .0
1359##fixme: need to not insert net, gateway, and bcast on "real netblock" pools (DHCPish)
1360 $sth2->execute($cidr->addr) unless $cidr->addr =~ m|\.0$|;
1361 foreach my $ip ($cidr->hostenum) {
1362 $sth2->execute($ip);
1363 }
1364 $cidr--;
1365 # don't insert .255
1366 $sth2->execute($cidr->addr) unless $cidr->addr =~ m|\.255$|;
1367 } else { # done returning IPs from a block to a static DSL pool
1368
1369 # If the block wasn't legacy goo embedded in a static pool, we check the
1370 # freeblocks in the identified parent to see if we can combine any of them.
1371
1372 # if the block to be deleted is a container, move its freeblock(s) up a level, and reset their parenting info
1373 if ($binfo->{type} =~ /^.[mc]/) {
1374 # move the freeblocks into the parent
1375 # we don't insert a new freeblock because there could be a live reparented sub.
1376 $dbh->do("UPDATE freeblocks SET rdepth=rdepth-1,parent=?,routed=?,city=? ".
1377 "WHERE parent=? AND rdepth=?", undef,
1378 ($parent, $ptype, $pcity, $cidr, $rdepth+1) );
1379 } else {
1380 # ... otherwise, add the freeblock
1381 $dbh->do("INSERT INTO freeblocks (cidr, city, routed, parent, rdepth) VALUES (?,?,?,?,?)", undef,
1382 ($cidr, $pcity, $ptype, $parent, $rdepth) );
1383 }
1384
1385##fixme: vrf
1386 # set up the query to get the list of blocks to try to merge.
1387 $sth = $dbh->prepare("SELECT cidr FROM freeblocks ".
1388 "WHERE parent = ? AND routed = ? AND rdepth = ? ".
1389 "ORDER BY masklen(cidr) DESC");
1390
1391 $sth->execute($parent, $ptype, $fbrdepth);
1392
1393# NetAddr::IP->compact() attempts to produce the smallest inclusive block
1394# from the caller and the passed terms.
1395# EG: if you call $cidr->compact($ip1,$ip2,$ip3) when $cidr, $ip1, $ip2,
1396# and $ip3 are consecutive /27's starting on .0 (.0-.31, .32-.63,
1397# .64-.95, and .96-.128), you will get an array containing a single
1398# /25 as element 0 (.0-.127). Order is not important; you could have
1399# $cidr=.32/27, $ip1=.96/27, $ip2=.0/27, and $ip3=.64/27.
1400
1401 my (@rawfb, @combinelist);
1402 my $i=0;
1403 # for each free block under $parent, push a NetAddr::IP object into one list, and
1404 # continuously use NetAddr::IP->compact to automagically merge netblocks as possible.
1405 while (my @data = $sth->fetchrow_array) {
1406 my $testIP = new NetAddr::IP $data[0];
1407 push @rawfb, $testIP;
1408 @combinelist = $testIP->compact(@combinelist);
1409 }
1410
1411 # now that we have the full list of "compacted" freeblocks, go back over
1412 # the list of raw freeblocks, and delete the ones that got merged.
1413 $sth = $dbh->prepare("DELETE FROM freeblocks WHERE cidr=? AND parent=? AND rdepth=?");
1414 foreach my $rawfree (@rawfb) {
1415 next if grep { $rawfree == $_ } @combinelist; # skip if the raw block is in the compacted list
1416 $sth->execute($rawfree, $parent, $fbrdepth);
1417 }
1418
1419 # now we walk the new list of compacted blocks, and see which ones we need to insert
1420 $sth = $dbh->prepare("INSERT INTO freeblocks (cidr,city,routed,parent,rdepth) VALUES (?,?,?,?,?)");
1421 foreach my $cme (@combinelist) {
1422 next if grep { $cme == $_ } @rawfb; # skip if the combined block was in the raw list
1423 $sth->execute($cme, $pcity, $ptype, $parent, $fbrdepth);
1424 }
1425
1426 } # done returning IPs to the appropriate place
1427
1428 # If we got here, we've succeeded. Whew!
1429 $dbh->commit;
1430 }; # end eval
1431 if ($@) {
1432 $msg .= ": $@";
1433 eval { $dbh->rollback; };
1434 return ('FAIL', $msg);
1435 } else {
1436##fixme: RPC return code?
1437 _rpc('delByCIDR', cidr => "$cidr", user => $user, delforward => $delfwd, delsubs => 'y');
1438 return ($retcode, $goback);
1439 }
1440
1441 } # end alloctype != netblock
1442
1443} # end deleteBlock()
1444
1445
1446## IPDB::getBlockData()
1447# Get CIDR or IP, custid, type, city, circuit ID, description, notes, modification time,
1448# private/restricted data, for a CIDR block or pool IP
1449# Also returns SWIP status flag for CIDR blocks or pool netblock for IPs
1450# Takes the block/IP to look up, routing depth, and VRF identifier
1451# Returns a hashref to the block data
1452sub getBlockData {
1453 my $dbh = shift;
1454 my $block = shift;
1455 my $rdepth = shift;
1456 my $vrf = shift || '';
1457
1458 my $cidr = new NetAddr::IP $block;
1459
1460 # better way to find IP allocations vs /32 "netblocks"
1461 my $btype = $dbh->selectrow_array("SELECT type FROM searchme WHERE cidr=?", undef, ($block) );
1462
1463 if (defined($rdepth) && $rdepth == 0) {
1464 # Only master blocks exist at rdepth 0
1465 my $binfo = $dbh->selectrow_hashref("SELECT cidr AS block, 'mm' AS type, 0 AS parent, cidr,".
1466 " ctime, mtime, rwhois, vrf".
1467 " FROM masterblocks WHERE cidr = ?", undef, ($block) );
1468# " FROM masterblocks WHERE cidr = ? AND vrf = ?", undef, ($block, $vrf) );
1469 return $binfo;
1470 } elsif ($btype =~ /^.i$/) {
1471 my $binfo = $dbh->selectrow_hashref("SELECT ip AS block, custid, type, city, circuitid, description,".
1472 " notes, modifystamp AS lastmod, privdata, vrf, pool, rdepth, rdns".
1473 " FROM poolips WHERE ip = ?", undef, ($block) );
1474# " FROM poolips WHERE ip = ? AND vrf = ?", undef, ($block, $vrf) );
1475 return $binfo;
1476 } else {
1477 my $binfo = $dbh->selectrow_hashref("SELECT cidr AS block, parent, custid, type, city, circuitid, ".
1478 "description, notes, modifystamp AS lastmod, privdata, vrf, swip, rdepth, rdns".
1479 " FROM allocations WHERE cidr = ? AND rdepth = ?", undef, ($block, $rdepth) );
1480# " FROM allocations WHERE cidr = ? AND rdepth = ? AND vrf = ?", undef, ($block, $rdepth, $vrf) );
1481 return $binfo;
1482 }
1483} # end getBlockData()
1484
1485
1486## IPDB::getBlockRDNS()
1487# Gets reverse DNS pattern for a block or IP. Note that this will also
1488# retrieve any default pattern following the parent chain up, and check via
1489# RPC (if available) to see what the narrowest pattern for the requested block is
1490# Returns the current pattern for the block or IP.
1491sub getBlockRDNS {
1492 my $dbh = shift;
1493 my $block = shift;
1494 my $rdepth = shift; # do we really need this?
1495 my %args = @_;
1496
1497 $args{vrf} = '' if !$args{vrf};
1498
1499 my $cidr = new NetAddr::IP $block;
1500
1501 my ($rdns,$rfrom) = $dbh->selectrow_array("SELECT rdns,cidr FROM allocations WHERE cidr >>= ? UNION ".
1502 "SELECT rdns,cidr FROM masterblocks WHERE cidr >>= ? ORDER BY cidr", undef, ($cidr,$cidr) );
1503
1504 if ($rpc_url) {
1505 # Use the first /16 or /24, rather than dithering over which sub-/14 /16
1506 # or sub-/19 /24 to retrieve - it's the least-wrong way to do things.
1507
1508 my ($rpcblock) = ($cidr->masklen <= 24 ? $cidr->split( ($cidr->masklen <= 16 ? 16 : 24) ) : $cidr);
1509
1510 my %rpcargs = (
1511 rpcuser => $args{user},
1512 group => $revgroup, # not sure how this could sanely be exposed, tbh...
1513 cidr => "$rpcblock",
1514 );
1515
1516 $rdns = _rpc('getRevPattern', %rpcargs);
1517 }
1518
1519 # hmm. do we care about where it actually came from?
1520 return $rdns;
1521} # end getBlockRDNS()
1522
1523
1524## IPDB::getNodeList()
1525# Gets a list of node ID+name pairs as an arrayref to a list of hashrefs
1526sub getNodeList {
1527 my $dbh = shift;
1528
1529 my $ret = $dbh->selectall_arrayref("SELECT node_id, node_name FROM nodes ORDER BY node_type,node_id",
1530 { Slice => {} });
1531 return $ret;
1532} # end getNodeList()
1533
1534
1535## IPDB::getNodeName()
1536# Get node name from the ID
1537sub getNodeName {
1538 my $dbh = shift;
1539 my $nid = shift;
1540
1541 my ($nname) = $dbh->selectrow_array("SELECT node_name FROM nodes WHERE node_id = ?", undef, ($nid) );
1542 return $nname;
1543} # end getNodeName()
1544
1545
1546## IPDB::getNodeInfo()
1547# Get node name and ID associated with a block
1548sub getNodeInfo {
1549 my $dbh = shift;
1550 my $block = shift;
1551
1552 my ($nid, $nname) = $dbh->selectrow_array("SELECT nodes.node_id,node_name FROM nodes INNER JOIN noderef".
1553 " ON nodes.node_id=noderef.node_id WHERE noderef.block = ?", undef, ($block) );
1554 return ($nid, $nname);
1555} # end getNodeInfo()
1556
1557
1558## IPDB::mailNotify()
1559# Sends notification mail to recipients regarding an IPDB operation
1560sub mailNotify {
1561 my $dbh = shift;
1562 my ($action,$subj,$message) = @_;
1563
1564 return if $smtphost eq 'smtp.example.com'; # do nothing if still using default SMTP host.
1565
1566##fixme: need to redesign the breakdown/processing for $action for proper handling of all cases
1567
1568# split action into parts for fiddlement. nb: there are almost certainly better ways to do this.
1569 my @actionbits = split //, $action;
1570
1571 # want to notify anyone who has specifically requested notify on *this* type ($action as passed),
1572 # on "all static IP types" or "all pool types" (and other last-char-in-type groupings), on eg "all DSL types",
1573 # and "all events with this action"
1574 my @actionsets = ($action);
1575##fixme: ick, eww. really gotta find a better way to handle this...
1576 push @actionsets, ($actionbits[0].'.'.$actionbits[2],
1577 $actionbits[0].$actionbits[1].'.', $actionbits[0].'a') if $action =~ /^.{3}$/;
1578
1579 my $mailer = Net::SMTP->new($smtphost, Hello => "ipdb.$domain");
1580
1581 # get recip list from db
1582 my $sth = $dbh->prepare("SELECT reciplist FROM notify WHERE action=?");
1583
1584 my %reciplist;
1585 foreach (@actionsets) {
1586 $sth->execute($_);
1587##fixme - need to handle db errors
1588 my ($recipsub) = $sth->fetchrow_array;
1589 next if !$recipsub;
1590 foreach (split(/,/, $recipsub)) {
1591 $reciplist{$_}++;
1592 }
1593 }
1594
1595 return if !%reciplist;
1596
1597 foreach my $recip (keys %reciplist) {
1598 $mailer->mail("ipdb\@$domain");
1599 $mailer->to($recip);
1600 $mailer->data("From: \"$org_name IP Database\" <ipdb\@$domain>\n",
1601 "To: $recip\n",
1602 "Date: ".strftime("%a, %d %b %Y %H:%M:%S %z",localtime)."\n",
1603 "Subject: {IPDB} $subj\n",
1604 "X-Mailer: IPDB Notify v".sprintf("%.1d",$IPDB::VERSION)."\n",
1605 "Organization: $org_name\n",
1606 "\n$message\n");
1607 }
1608 $mailer->quit;
1609}
1610
1611# Indicates module loaded OK. Required by Perl.
16121;
Note: See TracBrowser for help on using the repository browser.