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

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

/trunk

Commit 4/mumble for work done intermittently over the past ~year.
See #5, comment 25:

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