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

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

/trunk

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

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