source: trunk/dns-rpc.cgi@ 686

Last change on this file since 686 was 686, checked in by Kris Deugau, 9 years ago

/trunk

  • Tweak call to DNSDB::_template4_expand() in templatesToRecords() for _template4_expand()'s changes
  • Note a couple of distant edge case buglets for future consideration
  • Property svn:executable set to *
  • Property svn:keywords set to Date Rev Author Id
File size: 33.6 KB
RevLine 
[216]1#!/usr/bin/perl -w -T
[262]2# XMLRPC interface to manipulate most DNS DB entities
3##
[200]4# $Id: dns-rpc.cgi 686 2015-07-27 21:39:44Z kdeugau $
[496]5# Copyright 2012,2013 Kris Deugau <kdeugau@deepnet.cx>
[262]6#
7# This program is free software: you can redistribute it and/or modify
8# it under the terms of the GNU General Public License as published by
9# the Free Software Foundation, either version 3 of the License, or
10# (at your option) any later version.
11#
12# This program is distributed in the hope that it will be useful,
13# but WITHOUT ANY WARRANTY; without even the implied warranty of
14# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15# GNU General Public License for more details.
16#
17# You should have received a copy of the GNU General Public License
18# along with this program. If not, see <http://www.gnu.org/licenses/>.
19##
[119]20
21use strict;
22use warnings;
[216]23
24# don't remove! required for GNU/FHS-ish install from tarball
25use lib '.'; ##uselib##
[490]26use DNSDB;
[216]27
[490]28use FCGI;
[119]29#use Frontier::RPC2;
30use Frontier::Responder;
31
32## We need to handle a couple of things globally, rather than pasting the same bit into *every* sub.
33## So, let's subclass Frontier::RPC2 + Frontier::Responder, so we can override the single sub in each
34## that needs kicking
35#### hmm. put this in a separate file?
36#package DNSDB::RPC;
37#our @ISA = ("Frontier::RPC2", "Frontier::Responder");
38#package main;
39
[468]40my $dnsdb = DNSDB->new();
[191]41
[119]42my $methods = {
[515]43#sub getPermissions {
44#sub changePermissions {
45#sub comparePermissions {
46#sub changeGroup {
[119]47 'dnsdb.addDomain' => \&addDomain,
[401]48 'dnsdb.delZone' => \&delZone,
[515]49#sub domainName {
50#sub revName {
[500]51 'dnsdb.domainID' => \&domainID,
[515]52#sub revID {
[405]53 'dnsdb.addRDNS' => \&addRDNS,
[515]54#sub getZoneCount {
55#sub getZoneList {
56#sub getZoneLocation {
[121]57 'dnsdb.addGroup' => \&addGroup,
58 'dnsdb.delGroup' => \&delGroup,
[515]59#sub getChildren {
60#sub groupName {
61#sub getGroupCount {
62#sub getGroupList {
63#sub groupID {
[121]64 'dnsdb.addUser' => \&addUser,
[515]65#sub getUserCount {
66#sub getUserList {
67#sub getUserDropdown {
[121]68 'dnsdb.updateUser' => \&updateUser,
69 'dnsdb.delUser' => \&delUser,
[515]70#sub userFullName {
71#sub userStatus {
72#sub getUserData {
73#sub addLoc {
74#sub updateLoc {
75#sub delLoc {
76#sub getLoc {
77#sub getLocCount {
78#sub getLocList {
[447]79 'dnsdb.getLocDropdown' => \&getLocDropdown,
[121]80 'dnsdb.getSOA' => \&getSOA,
[515]81#sub updateSOA {
[123]82 'dnsdb.getRecLine' => \&getRecLine,
[495]83 'dnsdb.getRecList' => \&getRecList,
[123]84 'dnsdb.getRecCount' => \&getRecCount,
[659]85 'dnsdb.addRec' => \&rpc_addRec,
[675]86 'dnsdb.updateRec' => \&rpc_updateRec,
[515]87#sub downconvert {
[453]88 'dnsdb.addOrUpdateRevRec' => \&addOrUpdateRevRec,
[676]89 'dnsdb.updateRevSet' => \&updateRevSet,
[680]90 'dnsdb.splitTemplate' => \&splitTemplate,
[681]91 'dnsdb.resizeTemplate' => \&resizeTemplate,
[682]92 'dnsdb.templatesToRecords' => \&templatesToRecords,
[123]93 'dnsdb.delRec' => \&delRec,
[459]94 'dnsdb.delByCIDR' => \&delByCIDR,
[684]95 'dnsdb.delRevSet' => \&delRevSet,
[452]96#sub getLogCount {}
97#sub getLogEntries {}
98 'dnsdb.getRevPattern' => \&getRevPattern,
[673]99 'dnsdb.getRevSet' => \&getRevSet,
[506]100 'dnsdb.getTypelist' => \&getTypelist,
[504]101 'dnsdb.getTypemap' => \&getTypemap,
102 'dnsdb.getReverse_typemap' => \&getReverse_typemap,
[515]103#sub parentID {
104#sub isParent {
[405]105 'dnsdb.zoneStatus' => \&zoneStatus,
[452]106 'dnsdb.getZonesByCIDR' => \&getZonesByCIDR,
[515]107#sub importAXFR {
108#sub importBIND {
109#sub import_tinydns {
110#sub export {
111#sub mailNotify {
[121]112
[119]113 'dnsdb.getMethods' => \&get_method_list
114};
115
[490]116my $reqcnt = 0;
117
118while (FCGI::accept >= 0) {
119 my $res = Frontier::Responder->new(
[119]120 methods => $methods
121 );
122
[490]123 # "Can't do that" errors
124 if (!$dnsdb) {
125 print "Content-type: text/xml\n\n".$res->{_decode}->encode_fault(5, $dnsdb->err);
126 } else {
127 print $res->answer;
128 }
129 last if $reqcnt++ > $dnsdb->{maxfcgi};
130} # while FCGI::accept
[119]131
132
133exit;
134
135##
136## Subs below here
137##
138
[490]139# Check RPC ACL
[401]140sub _aclcheck {
141 my $subsys = shift;
[486]142 return 1 if grep /$ENV{REMOTE_ADDR}/, @{$dnsdb->{rpcacl}{$subsys}};
[505]143 warn "$subsys/$ENV{REMOTE_ADDR} not in ACL\n"; # a bit of logging
[401]144 return 0;
145}
146
[405]147# Let's see if we can factor these out of the RPC method subs
148sub _commoncheck {
149 my $argref = shift;
150 my $needslog = shift;
151
152 die "Missing remote system name\n" if !$argref->{rpcsystem};
153 die "Access denied\n" if !_aclcheck($argref->{rpcsystem});
154 if ($needslog) {
155 die "Missing remote username\n" if !$argref->{rpcuser};
156 die "Couldn't set userdata for logging\n"
[486]157 unless $dnsdb->initRPC(username => $argref->{rpcuser}, rpcsys => $argref->{rpcsystem},
158 fullname => ($argref->{fullname} ? $argref->{fullname} : $argref->{rpcuser}) );
[405]159 }
160}
161
[511]162# check for defrec and revrec; only call on subs that deal with records
163sub _reccheck {
164 my $argref = shift;
165 die "Missing defrec and/or revrec flags\n" if !($argref->{defrec} || $argref->{revrec});
166}
167
[453]168# set location to the zone's default location if none is specified
169sub _loccheck {
170 my $argref = shift;
171 if (!$argref->{location} && $argref->{defrec} eq 'n') {
[477]172 $argref->{location} = $dnsdb->getZoneLocation($argref->{revrec}, $argref->{parent_id});
[453]173 }
174}
175
176# set ttl to zone defailt minttl if none is specified
177sub _ttlcheck {
178 my $argref = shift;
179 if (!$argref->{ttl}) {
[486]180 my $tmp = $dnsdb->getSOA($argref->{defrec}, $argref->{revrec}, $argref->{parent_id});
[453]181 $argref->{ttl} = $tmp->{minttl};
182 }
183}
184
[119]185#sub connectDB {
186#sub finish {
187#sub initGlobals {
188#sub initPermissions {
189#sub getPermissions {
190#sub changePermissions {
191#sub comparePermissions {
192#sub changeGroup {
193#sub _log {
194
195sub addDomain {
196 my %args = @_;
197
[405]198 _commoncheck(\%args, 'y');
[119]199
[516]200 my ($code, $msg) = $dnsdb->addDomain($args{domain}, $args{group}, $args{state}, $args{location});
[511]201 die "$msg\n" if $code eq 'FAIL';
[119]202 return $msg; # domain ID
203}
204
[401]205sub delZone {
[119]206 my %args = @_;
207
[405]208 _commoncheck(\%args, 'y');
209 die "Need forward/reverse zone flag\n" if !$args{revrec};
[119]210
[121]211 my ($code,$msg);
[405]212 # Let's be nice; delete based on zone id OR zone name. Saves an RPC call round-trip, maybe.
213 if ($args{zone} =~ /^\d+$/) {
[477]214 ($code,$msg) = $dnsdb->delZone($args{zone}, $args{revrec});
[119]215 } else {
[405]216 my $zoneid;
[477]217 $zoneid = $dnsdb->domainID($args{zone}) if $args{revrec} eq 'n';
218 $zoneid = $dnsdb->revID($args{zone}) if $args{revrec} eq 'y';
[671]219 die "Can't find zone: ".$dnsdb->errstr."\n" if !$zoneid;
[477]220 ($code,$msg) = $dnsdb->delZone($zoneid, $args{revrec});
[119]221 }
[511]222 die "$msg\n" if $code eq 'FAIL';
[405]223 return $msg;
[119]224}
225
[405]226#sub domainName {}
227#sub revName {}
[500]228
229sub domainID {
230 my %args = @_;
231
232 _commoncheck(\%args, 'y');
233
234 my $domid = $dnsdb->domainID($args{domain});
[671]235 die $dnsdb->errstr."\n" if !$domid;
[500]236 return $domid;
237}
238
[405]239#sub revID {}
[119]240
[405]241sub addRDNS {
242 my %args = @_;
243
244 _commoncheck(\%args, 'y');
245
[477]246 my ($code, $msg) = $dnsdb->addRDNS($args{revzone}, $args{revpatt}, $args{group}, $args{state}, $args{defloc});
[447]247 die "$msg\n" if $code eq 'FAIL';
[405]248 return $msg; # domain ID
249}
250
251#sub getZoneCount {}
252#sub getZoneList {}
253#sub getZoneLocation {}
254
[119]255sub addGroup {
256 my %args = @_;
257
[405]258 _commoncheck(\%args, 'y');
[407]259 die "Missing new group name\n" if !$args{groupname};
260 die "Missing parent group ID\n" if !$args{parent_id};
[119]261
[407]262# not sure how to usefully represent permissions via RPC. :/
[121]263# not to mention, permissions are checked at the UI layer, not the DB layer.
[119]264 my $perms = {domain_edit => 1, domain_create => 1, domain_delete => 1,
265 record_edit => 1, record_create => 1, record_delete => 1
266 };
267## optional $inhert arg?
[476]268 my ($code,$msg) = $dnsdb->addGroup($args{groupname}, $args{parent_id}, $perms);
[511]269 die "$msg\n" if $code eq 'FAIL';
[119]270 return $msg;
271}
272
273sub delGroup {
274 my %args = @_;
275
[405]276 _commoncheck(\%args, 'y');
[407]277 die "Missing group ID or name to remove\n" if !$args{group};
[119]278
[121]279 my ($code,$msg);
[119]280 # Let's be nice; delete based on groupid OR group name. Saves an RPC call round-trip, maybe.
281 if ($args{group} =~ /^\d+$/) {
[476]282 ($code,$msg) = $dnsdb->delGroup($args{group});
[119]283 } else {
[486]284 my $grpid = $dnsdb->groupID($args{group});
[407]285 die "Can't find group\n" if !$grpid;
[476]286 ($code,$msg) = $dnsdb->delGroup($grpid);
[119]287 }
[511]288 die "$msg\n" if $code eq 'FAIL';
[407]289 return $msg;
[119]290}
291
[405]292#sub getChildren {}
293#sub groupName {}
294#sub getGroupCount {}
295#sub getGroupList {}
296#sub groupID {}
[119]297
298sub addUser {
299 my %args = @_;
300
[405]301 _commoncheck(\%args, 'y');
[119]302
[409]303# not sure how to usefully represent permissions via RPC. :/
[121]304# not to mention, permissions are checked at the UI layer, not the DB layer.
[119]305 # bend and twist; get those arguments in in the right order!
306 $args{type} = 'u' if !$args{type};
307 $args{permstring} = 'i' if !defined($args{permstring});
308 my @userargs = ($args{username}, $args{group}, $args{pass}, $args{state}, $args{type}, $args{permstring});
309 for my $argname ('fname','lname','phone') {
310 last if !$args{$argname};
311 push @userargs, $args{$argname};
312 }
[479]313 my ($code,$msg) = $dnsdb->addUser(@userargs);
[511]314 die "$msg\n" if $code eq 'FAIL';
[119]315 return $msg;
316}
317
[405]318#sub getUserCount {}
319#sub getUserList {}
320#sub getUserDropdown {}
321#sub checkUser {}
[119]322
323sub updateUser {
324 my %args = @_;
325
[405]326 _commoncheck(\%args, 'y');
[119]327
[401]328 die "Missing UID\n" if !$args{uid};
[121]329
[119]330 # bend and twist; get those arguments in in the right order!
[411]331 $args{type} = 'u' if !$args{type};
[119]332 my @userargs = ($args{uid}, $args{username}, $args{group}, $args{pass}, $args{state}, $args{type});
333 for my $argname ('fname','lname','phone') {
334 last if !$args{$argname};
335 push @userargs, $args{$argname};
336 }
337##fixme: also underlying in DNSDB::updateUser(): no way to just update this or that attribute;
338# have to pass them all in to be overwritten
[479]339 my ($code,$msg) = $dnsdb->updateUser(@userargs);
[511]340 die "$msg\n" if $code eq 'FAIL';
[412]341 return $msg;
[119]342}
343
344sub delUser {
345 my %args = @_;
346
[405]347 _commoncheck(\%args, 'y');
[119]348
[401]349 die "Missing UID\n" if !$args{uid};
[479]350 my ($code,$msg) = $dnsdb->delUser($args{uid});
[511]351 die "$msg\n" if $code eq 'FAIL';
[412]352 return $msg;
[119]353}
354
[405]355#sub userFullName {}
356#sub userStatus {}
357#sub getUserData {}
[119]358
[405]359#sub addLoc {}
360#sub updateLoc {}
361#sub delLoc {}
362#sub getLoc {}
363#sub getLocCount {}
364#sub getLocList {}
365
[447]366sub getLocDropdown {
367 my %args = @_;
368
369 _commoncheck(\%args);
370 $args{defloc} = '' if !$args{defloc};
371
[480]372 my $ret = $dnsdb->getLocDropdown($args{group}, $args{defloc});
[447]373 return $ret;
374}
375
[119]376sub getSOA {
377 my %args = @_;
378
[405]379 _commoncheck(\%args);
[121]380
[511]381 _reccheck(\%args);
382
[481]383 my $ret = $dnsdb->getSOA($args{defrec}, $args{revrec}, $args{id});
[413]384 if (!$ret) {
385 if ($args{defrec} eq 'y') {
[401]386 die "No default SOA record in group\n";
[121]387 } else {
[413]388 die "No SOA record in zone\n";
[121]389 }
390 }
[413]391 return $ret;
[119]392}
393
[405]394#sub updateSOA {}
395
[119]396sub getRecLine {
397 my %args = @_;
398
[405]399 _commoncheck(\%args);
[123]400
[511]401 _reccheck(\%args);
402
[481]403 my $ret = $dnsdb->getRecLine($args{defrec}, $args{revrec}, $args{id});
[123]404
[671]405 die $dnsdb->errstr."\n" if !$ret;
[123]406
407 return $ret;
[119]408}
409
[495]410sub getRecList {
[119]411 my %args = @_;
412
[405]413 _commoncheck(\%args);
[123]414
[500]415 # deal gracefully with alternate calling convention for args{id}
416 $args{id} = $args{ID} if !$args{id} && $args{ID};
417 # ... and fail if we don't have one
418 die "Missing zone ID\n" if !$args{id};
419
[405]420 # set some optional args
[500]421 $args{offset} = 0 if !$args{offset};
[123]422## for order, need to map input to column names
423 $args{order} = 'host' if !$args{order};
424 $args{direction} = 'ASC' if !$args{direction};
[500]425 $args{defrec} = 'n' if !$args{defrec};
426 $args{revrec} = 'n' if !$args{revrec};
[123]427
[500]428 # convert zone name to zone ID, if needed
429 if ($args{defrec} eq 'n') {
430 if ($args{revrec} eq 'n') {
431 $args{id} = $dnsdb->domainID($args{id}) if $args{id} !~ /^\d+$/;
432 } else {
433 $args{id} = $dnsdb->revID($args{id}) if $args{id} !~ /^\d+$/
434 }
435 }
436
[502]437 # fail if we *still* don't have a valid zone ID
[671]438 die $dnsdb->errstr."\n" if !$args{id};
[502]439
[500]440 # and finally retrieve the records.
[495]441 my $ret = $dnsdb->getRecList(defrec => $args{defrec}, revrec => $args{revrec}, id => $args{id},
[500]442 offset => $args{offset}, nrecs => $args{nrecs}, sortby => $args{sortby},
443 sortorder => $args{sortorder}, filter => $args{filter});
[671]444 die $dnsdb->errstr."\n" if !$ret;
[123]445
446 return $ret;
[119]447}
448
[123]449sub getRecCount {
450 my %args = @_;
[119]451
[405]452 _commoncheck(\%args);
[123]453
[511]454 _reccheck(\%args);
455
[405]456 # set some optional args
457 $args{nrecs} = 'all' if !$args{nrecs};
458 $args{nstart} = 0 if !$args{nstart};
459## for order, need to map input to column names
460 $args{order} = 'host' if !$args{order};
461 $args{direction} = 'ASC' if !$args{direction};
462
[666]463 my $ret = $dnsdb->getRecCount(defrec => $args{defrec}, revrec => $args{revrec},
464 id => $args{id}, filter => $args{filter});
[405]465
[671]466 die $dnsdb->errstr."\n" if !$ret;
[405]467
468 return $ret;
[123]469}
470
[659]471sub rpc_addRec {
[119]472 my %args = @_;
473
[405]474 _commoncheck(\%args, 'y');
[123]475
[511]476 _reccheck(\%args);
[453]477 _loccheck(\%args);
478 _ttlcheck(\%args);
[123]479
[498]480 # allow passing text types rather than DNS integer IDs
[499]481 $args{type} = $DNSDB::reverse_typemap{$args{type}} if $args{type} !~ /^\d+$/;
[498]482
[481]483 my @recargs = ($args{defrec}, $args{revrec}, $args{parent_id},
[543]484 \$args{name}, \$args{type}, \$args{address}, $args{ttl}, $args{location},
485 $args{expires}, $args{stamp});
[426]486 if ($args{type} == $DNSDB::reverse_typemap{MX} or $args{type} == $DNSDB::reverse_typemap{SRV}) {
487 push @recargs, $args{distance};
488 if ($args{type} == $DNSDB::reverse_typemap{SRV}) {
489 push @recargs, $args{weight};
490 push @recargs, $args{port};
491 }
492 }
493
[481]494 my ($code, $msg) = $dnsdb->addRec(@recargs);
[426]495
[511]496 die "$msg\n" if $code eq 'FAIL';
[426]497 return $msg;
[659]498} # rpc_addRec
[119]499
[675]500sub rpc_updateRec {
[119]501 my %args = @_;
502
[405]503 _commoncheck(\%args, 'y');
[123]504
[511]505 _reccheck(\%args);
506
[543]507 # put some caller-friendly names in their rightful DB column places
[680]508 $args{val} = $args{address} if !$args{val};
509 $args{host} = $args{name} if !$args{host};
[543]510
[452]511 # get old line, so we can update only the bits that the caller passed to change
[481]512 my $oldrec = $dnsdb->getRecLine($args{defrec}, $args{revrec}, $args{id});
[543]513 foreach my $field (qw(host type val ttl location expires distance weight port)) {
[452]514 $args{$field} = $oldrec->{$field} if !$args{$field} && defined($oldrec->{$field});
515 }
[543]516 # stamp has special handling when blank or 0. "undefined" from the caller should mean "don't change"
[659]517 $args{stamp} = $oldrec->{stamp} if !defined($args{stamp}) && $oldrec->{stampactive};
[452]518
[498]519 # allow passing text types rather than DNS integer IDs
[499]520 $args{type} = $DNSDB::reverse_typemap{$args{type}} if $args{type} !~ /^\d+$/;
[498]521
[405]522 # note dist, weight, port are not required on all types; will be ignored if not needed.
[426]523 # parent_id is the "primary" zone we're updating; necessary for forward/reverse voodoo
[481]524 my ($code, $msg) = $dnsdb->updateRec($args{defrec}, $args{revrec}, $args{id}, $args{parent_id},
[543]525 \$args{host}, \$args{type}, \$args{val}, $args{ttl}, $args{location},
526 $args{expires}, $args{stamp},
[426]527 $args{distance}, $args{weight}, $args{port});
[123]528
[511]529 die "$msg\n" if $code eq 'FAIL';
[426]530 return $msg;
[680]531} # rpc_updateRec
[119]532
[453]533# Takes a passed CIDR block and DNS pattern; adds a new record or updates the record(s) affected
534sub addOrUpdateRevRec {
535 my %args = @_;
536
537 _commoncheck(\%args, 'y');
[459]538 my $cidr = new NetAddr::IP $args{cidr};
[453]539
[686]540##fixme: Minor edge case; if we receive calls one after the other to update
541# to the same thing, we bulk out the log with useless notices. Leaving this
542# for future development since this should be rare in practice.
543
[477]544 my $zonelist = $dnsdb->getZonesByCIDR(%args);
[453]545 if (scalar(@$zonelist) == 0) {
546 # enhh.... WTF?
547 } elsif (scalar(@$zonelist) == 1) {
548 # check if the single zone returned is bigger than the CIDR. if so, we can just add a record
549 my $zone = new NetAddr::IP $zonelist->[0]->{revnet};
[459]550 if ($zone->contains($cidr)) {
[454]551 # We need to strip the CIDR mask on IPv4 /32 assignments, or we just add a new record all the time.
[459]552 my $filt = ($cidr->{isv6} || $cidr->masklen != 32 ? "$cidr" : $cidr->addr);
[495]553 my $reclist = $dnsdb->getRecList(defrec => 'n', revrec => 'y',
[454]554 id => $zonelist->[0]->{rdns_id}, filter => $filt);
[671]555##fixme: Figure some new magic to automerge new incoming A(AAA)+PTR requests
556# with existing A records to prevent duplication of A(AAA) records
[453]557 if (scalar(@$reclist) == 0) {
558 # Aren't Magic Numbers Fun? See pseudotype list in dnsadmin.
[672]559 my $type = ($cidr->{isv6} ? ($cidr->masklen == 128 ? 65281 : 65284) : ($cidr->masklen == 32 ? 65280 : 65283) );
[659]560 rpc_addRec(defrec => 'n', revrec => 'y', parent_id => $zonelist->[0]->{rdns_id}, type => $type,
[459]561 address => "$cidr", %args);
[453]562 } else {
[459]563 my $flag = 0;
[453]564 foreach my $rec (@$reclist) {
[454]565 # pure PTR plus composite types
566 next unless $rec->{type} == 12 || $rec->{type} == 65280 || $rec->{type} == 65281
567 || $rec->{type} == 65282 || $rec->{type} == 65283 || $rec->{type} == 65284;
568 next unless $rec->{val} eq $filt; # make sure we really update the record we want to update.
[675]569 rpc_updateRec(defrec =>'n', revrec => 'y', id => $rec->{record_id},
[672]570 parent_id => $zonelist->[0]->{rdns_id}, address => "$cidr", %args);
[459]571 $flag = 1;
[453]572 last; # only do one record.
573 }
[459]574 unless ($flag) {
575 # Nothing was updated, so we didn't really have a match. Add as per @$reclist==0
576 # Aren't Magic Numbers Fun? See pseudotype list in dnsadmin.
577 my $type = ($cidr->{isv6} ? 65282 : ($cidr->masklen == 32 ? 65280 : 65283) );
[659]578 rpc_addRec(defrec => 'n', revrec => 'y', parent_id => $zonelist->[0]->{rdns_id}, type => $type,
[459]579 address => "$cidr", %args);
580 }
[453]581 }
582 } else {
583 # ebbeh? CIDR is only partly represented in DNS. This needs manual intervention.
584 } # done single-zone-contains-$cidr
585 } else {
586 # Overlapping reverse zones shouldn't be possible, so if we're here we've got a CIDR
587 # that spans multiple reverse zones (eg, /23 CIDR -> 2 /24 rzones)
588 foreach my $zdata (@$zonelist) {
[495]589 my $reclist = $dnsdb->getRecList(defrec => 'n', revrec => 'y',
[453]590 id => $zdata->{rdns_id}, filter => $zdata->{revnet});
591 if (scalar(@$reclist) == 0) {
592 my $type = ($args{cidr}->{isv6} ? 65282 : ($args{cidr}->masklen == 32 ? 65280 : 65283) );
[659]593 rpc_addRec(defrec => 'n', revrec => 'y', parent_id => $zdata->{rdns_id}, type => $type,
[453]594 address => "$args{cidr}", %args);
595 } else {
596 foreach my $rec (@$reclist) {
[454]597 # only the composite and/or template types; pure PTR or nontemplate composite
598 # types are nominally impossible here.
[453]599 next unless $rec->{type} == 65282 || $rec->{type} == 65283 || $rec->{type} == 65284;
[678]600 rpc_updateRec(defrec => 'n', revrec => 'y', id => $rec->{record_id},
[453]601 parent_id => $zdata->{rdns_id}, %args);
602 last; # only do one record.
603 }
604 }
605 } # iterate zones within $cidr
606 } # done $cidr-contains-zones
[676]607##fixme: what about errors? what about warnings?
608} # done addOrUpdateRevRec()
[453]609
[676]610# Update rDNS on a whole batch of IP addresses. Presented as a separate sub via RPC
611# since RPC calls can be s...l...o...w....
612sub updateRevSet {
613 my %args = @_;
614
615 _commoncheck(\%args, 'y');
616
617 my @ret;
618 # loop over passed IP/hostname pairs
619 foreach my $key (keys %args) {
[678]620 next unless $key =~ m{^host_((?:[\d.]+|[\da-f:]+)(?:/\d+)?)$};
[676]621 my $ip = $1;
622 push @ret, addOrUpdateRevRec(cidr => $ip, name => $args{$key}, %args);
623 }
624##fixme: what about errors? what about warnings?
625 return \@ret;
626} # done updateRevSet()
627
[680]628# Split a template record as per a passed CIDR.
629# Requires the CIDR and the new mask length
630sub splitTemplate {
631 my %args = @_;
632
633 _commoncheck(\%args, 'y');
634
635 my $cidr = new NetAddr::IP $args{cidr};
636
637 my $zonelist = $dnsdb->getZonesByCIDR(%args);
638
639 if (scalar(@$zonelist) == 0) {
640 # enhh.... WTF?
641
642 } elsif (scalar(@$zonelist) == 1) {
643 my $zone = new NetAddr::IP $zonelist->[0]->{revnet};
644 if ($zone->contains($cidr)) {
645 # Find the first record in the reverse zone that matches the CIDR we're splitting...
646 my $reclist = $dnsdb->getRecList(defrec => 'n', revrec => 'y',
647 id => $zonelist->[0]->{rdns_id}, filter => $cidr, sortby => 'val', sortorder => 'DESC');
648 my $oldrec;
649 foreach my $rec (@$reclist) {
650 my $reccidr = new NetAddr::IP $rec->{val};
651 next unless $cidr->contains($reccidr); # not sure this is needed here
652 # ... and is a reverse-template type.
653 # Could arguably trim the list below to just 65282, 65283, 65284
654 next unless $rec->{type} == 12 || $rec->{type} == 65280 || $rec->{type} == 65281 ||
655 $rec->{type} == 65282 || $rec->{type} == 65283 ||$rec->{type} == 65284;
656 # snag old record so we can copy its data
657 $oldrec = $dnsdb->getRecLine('n', 'y', $rec->{record_id});
658 last; # we've found one record that meets our criteria; Extras Are Irrelevant
659 }
660
661 my @newblocks = $cidr->split($args{newmask});
662 # Change the existing record with the new CIDR
663 my $up_res = rpc_updateRec(%args, val => $newblocks[0], id => $oldrec->{record_id}, defrec => 'n', revrec => 'y');
664 my @ret;
665 # the update is assumed to have succeeded if it didn't fail.
666##fixme: find a way to save and return "warning" states?
667 push @ret, {block => "$newblocks[0]", code => "OK", msg => $up_res};
668 # And now add new record(s) for each of the new CIDR entries, reusing the old data
669 for (my $i = 1; $i <= $#newblocks; $i++) {
670 my $newval = "$newblocks[$i]";
671 my @recargs = ('n', 'y', $oldrec->{rdns_id}, \$oldrec->{host}, \$oldrec->{type}, \$newval,
672 $oldrec->{ttl}, $oldrec->{location}, 0, '');
673 my ($code, $msg) = $dnsdb->addRec(@recargs);
674 # Note failures here are not fatal; this should typically only ever be called by IPDB
675 push @ret, {block => "$newblocks[$i]", code => $code, msg => $up_res};
676 }
677 # return an info hash in case of warnings doing the update or add(s)
678 return \@ret;
679
680 } else { # $cidr > $zone but we only have one zone
681 # ebbeh? CIDR is only partly represented in DNS. This needs manual intervention.
682 return "Warning: $args{cidr} is only partly represented in DNS. Check and update DNS records manually.";
683 } # done single-zone-contains-$cidr
684
685 } else {
686 # multiple zones nominally "contain" $cidr
687 } # done $cidr-contains-zones
688
689} # done splitTemplate()
690
[681]691# Resize a template according to an old/new CIDR pair
692# Takes the old cidr in $args{oldcidr} and the new in $args{newcidr}
693sub resizeTemplate {
694 my %args = @_;
695
696 _commoncheck(\%args, 'y');
697
698 my $oldcidr = new NetAddr::IP $args{oldcidr};
699 my $newcidr = new NetAddr::IP $args{newcidr};
700 die "$oldcidr and $newcidr do not overlap"
701 unless $oldcidr->contains($newcidr) || $newcidr->contains($oldcidr);
702 $args{cidr} = $args{oldcidr};
703
704 my $up_res;
705
706 my $zonelist = $dnsdb->getZonesByCIDR(%args);
707 if (scalar(@$zonelist) == 0) {
708 # enhh.... WTF?
709
710 } elsif (scalar(@$zonelist) == 1) {
711 my $zone = new NetAddr::IP $zonelist->[0]->{revnet};
712 if ($zone->contains($oldcidr)) {
713 # Find record(s) matching the old and new CIDR
714
715 my $sql = q(
716 SELECT record_id,host,val
717 FROM records
718 WHERE rdns_id = ?
719 AND type IN (12, 65280, 65281, 65282, 65283, 65284)
720 AND (val = ? OR val = ?)
721 ORDER BY masklen(inetlazy(val)) ASC
722 );
723 my $sth = $dnsdb->{dbh}->prepare($sql);
724 $sth->execute($zonelist->[0]->{rdns_id}, "$oldcidr", "$newcidr");
725 my $upd_id;
726 my $oldhost;
727 while (my ($recid, $host, $val) = $sth->fetchrow_array) {
728 my $tcidr = NetAddr::IP->new($val);
729 if ($tcidr == $newcidr) {
730 # Match found for new CIDR. Delete this record.
731 $up_res = $dnsdb->delRec('n', 'y', $recid);
732 } else {
733 # Update this record, then exit the loop
734 $up_res = rpc_updateRec(%args, val => $newcidr, id => $recid, defrec => 'n', revrec => 'y');
735 last;
736 }
737 # Your llama is on fire
738 }
739 $sth->finish;
740
741 return "Template record for $oldcidr changed to $newcidr.";
742
743 } else { # $cidr > $zone but we only have one zone
744 # ebbeh? CIDR is only partly represented in DNS. This needs manual intervention.
745 return "Warning: $args{cidr} is only partly represented in DNS. Check and update DNS records manually.";
746 } # done single-zone-contains-$cidr
747
748 } else {
749 # multiple zones nominally "contain" $cidr
750 }
751
752 return $up_res;
753} # done resizeTemplate()
754
[682]755# Convert one or more template records to a set of individual IP records. Expands the template.
756# Handle the case of nested templates, although the primary caller (IPDB) should not be
757# able to generate records that would trigger that case.
758# Accounts for existing PTR or A+PTR records same as on-export template expansion.
759# Takes a list of templates and a bounding CIDR?
760sub templatesToRecords {
761 my %args = @_;
762
763 _commoncheck(\%args, 'y');
764
765 my %iplist;
766 my @retlist;
767
768 my $zsth = $dnsdb->{dbh}->prepare("SELECT rdns_id,group_id FROM revzones WHERE revnet >>= ?");
769 # Going to assume template records with no expiry
770 # Also note IPv6 template records don't expand sanely the way v4 records do
771 my $recsth = $dnsdb->{dbh}->prepare(q(
772 SELECT record_id, domain_id, host, type, val, ttl, location
773 FROM records
774 WHERE rdns_id = ?
775 AND type IN (12, 65280, 65282, 65283)
776 AND inetlazy(val) <<= ?
777 ORDER BY masklen(inetlazy(val)) DESC
778 ));
779 my $insth = $dnsdb->{dbh}->prepare("INSERT INTO records (domain_id, rdns_id, host, type, val, ttl, location)".
780 " VALUES (?,?,?,?,?,?,?)");
781 my $delsth = $dnsdb->{dbh}->prepare("DELETE FROM records WHERE record_id = ?");
782 my %typedown = (12 => 12, 65280 => 65280, 65281 => 65281, 65282 => 12, 65283 => 65280, 65284 => 65281);
783
784 my @checkrange;
785
786 local $dnsdb->{dbh}->{AutoCommit} = 0;
787 local $dnsdb->{dbh}->{RaiseError} = 1;
788
789 eval {
790 foreach my $template (@{$args{templates}}) {
791 $zsth->execute($template);
792 my ($zid,$zgrp) = $zsth->fetchrow_array;
793 if (!$zid) {
794 push @retlist, {$template, "Zone not found"};
795 next;
796 }
797 $recsth->execute($zid, $template);
798 while (my ($recid, $domid, $host, $type, $val, $ttl, $loc) = $recsth->fetchrow_array) {
799 # Skip single IPs with PTR or A+PTR records
800 if ($type == 12 || $type == 65280) {
801 $iplist{"$val/32"}++;
802 next;
803 }
804 my @newips = NetAddr::IP->new($template)->split(32);
805 $type = $typedown{$type};
806 foreach my $ip (@newips) {
807 next if $iplist{$ip};
808 my $newhost = $host;
[686]809 $dnsdb->_template4_expand(\$newhost, $ip->addr);
[682]810 $insth->execute($domid, $zid, $newhost, $type, $ip->addr, $ttl, $loc);
811 $iplist{$ip}++;
812 }
813 $delsth->execute($recid);
814 $dnsdb->_log(group_id => $zgrp, domain_id => $domid, rdns_id => $zid,
815 entry => "$template converted to individual $typemap{$type} records");
816 push @retlist, "$template converted to individual records";
817 } # record fetch
818 } # foreach passed template CIDR
819
820 $dnsdb->{dbh}->commit;
821 };
822 if ($@) {
823 die "Error converting a template record to individual records: $@";
824 }
825
826 return \@retlist;
827
828} # done templatesToRecords()
829
[119]830sub delRec {
831 my %args = @_;
832
[405]833 _commoncheck(\%args, 'y');
[123]834
[511]835 _reccheck(\%args);
836
[481]837 my ($code, $msg) = $dnsdb->delRec($args{defrec}, $args{recrev}, $args{id});
[123]838
[511]839 die "$msg\n" if $code eq 'FAIL';
[426]840 return $msg;
[119]841}
842
[459]843sub delByCIDR {
844 my %args = @_;
845
846 _commoncheck(\%args, 'y');
847
[683]848 # Caller may pass 'n' in delsubs. Assume it should be false/undefined
849 # unless the caller explicitly requested 'yes'
850 $args{delsubs} = 0 if $args{delsubs} ne 'y';
851
[459]852 # much like addOrUpdateRevRec()
[477]853 my $zonelist = $dnsdb->getZonesByCIDR(%args);
[459]854 my $cidr = new NetAddr::IP $args{cidr};
855
856 if (scalar(@$zonelist) == 0) {
857 # enhh.... WTF?
858 } elsif (scalar(@$zonelist) == 1) {
859
860 # check if the single zone returned is bigger than the CIDR
861 my $zone = new NetAddr::IP $zonelist->[0]->{revnet};
862 if ($zone->contains($cidr)) {
863 if ($args{delsubs}) {
864 # Delete ALL EVARYTHING!!one11!! in $args{cidr}
[495]865 my $reclist = $dnsdb->getRecList(defrec => 'n', revrec => 'y', id => $zonelist->[0]->{rdns_id});
[459]866 foreach my $rec (@$reclist) {
867 my $reccidr = new NetAddr::IP $rec->{val};
868 next unless $cidr->contains($reccidr);
[460]869 next unless $rec->{type} == 12 || $rec->{type} == 65280 || $rec->{type} == 65281 ||
870 $rec->{type} == 65282 || $rec->{type} == 65283 ||$rec->{type} == 65284;
[459]871 ##fixme: multiple records, wanna wax'em all, how to report errors?
872 if ($args{delforward} ||
873 $rec->{type} == 12 || $rec->{type} == 65282 ||
874 $rec->{type} == 65283 || $rec->{type} == 65284) {
[481]875 my ($code,$msg) = $dnsdb->delRec('n', 'y', $rec->{record_id});
[459]876 } else {
[686]877##fixme: AAAA+PTR?
[481]878 my $ret = $dnsdb->downconvert($rec->{record_id}, $DNSDB::reverse_typemap{A});
[459]879 }
880 }
[460]881 if ($args{parpatt} && $zone == $cidr) {
882 # Edge case; we've just gone and axed all the records in the reverse zone.
883 # Re-add one to match the parent if we've been given a pattern to use.
[659]884 rpc_addRec(defrec => 'n', revrec => 'y', parent_id => $zonelist->[0]->{rdns_id},
[672]885 type => ($zone->{isv6} ? 65284 : 65283), address => "$cidr", name => $args{parpatt}, %args);
[460]886 }
[459]887
888 } else {
889 # Selectively delete only exact matches on $args{cidr}
890 # We need to strip the CIDR mask on IPv4 /32 assignments, or we can't find single-IP records
891 my $filt = ($cidr->{isv6} || $cidr->masklen != 32 ? "$cidr" : $cidr->addr);
[495]892 my $reclist = $dnsdb->getRecList(defrec => 'n', revrec => 'y',
[459]893 id => $zonelist->[0]->{rdns_id}, filter => $filt, sortby => 'val', sortorder => 'DESC');
894 foreach my $rec (@$reclist) {
895 my $reccidr = new NetAddr::IP $rec->{val};
896 next unless $cidr == $reccidr;
[460]897 next unless $rec->{type} == 12 || $rec->{type} == 65280 || $rec->{type} == 65281 ||
898 $rec->{type} == 65282 || $rec->{type} == 65283 ||$rec->{type} == 65284;
[459]899 if ($args{delforward} || $rec->{type} == 12) {
[481]900 my ($code,$msg) = $dnsdb->delRec('n', 'y', $rec->{record_id});
[511]901 die "$msg\n" if $code eq 'FAIL';
[459]902 return $msg;
903 } else {
[481]904 my $ret = $dnsdb->downconvert($rec->{record_id}, $DNSDB::reverse_typemap{A});
[671]905 die $dnsdb->errstr."\n" if !$ret;
[459]906 return "A+PTR for $args{cidr} split and PTR removed";
907 }
908 } # foreach @$reclist
909 }
910
911 } else { # $cidr > $zone but we only have one zone
912 # ebbeh? CIDR is only partly represented in DNS. This needs manual intervention.
913 return "Warning: $args{cidr} is only partly represented in DNS. Check and remove DNS records manually.";
914 } # done single-zone-contains-$cidr
915
916 } else { # multiple zones nominally "contain" $cidr
917 # Overlapping reverse zones shouldn't be possible, so if we're here we've got a CIDR
918 # that spans multiple reverse zones (eg, /23 CIDR -> 2 /24 rzones)
919 foreach my $zdata (@$zonelist) {
[495]920 my $reclist = $dnsdb->getRecList(defrec => 'n', revrec => 'y', id => $zdata->{rdns_id});
[459]921 if (scalar(@$reclist) == 0) {
[460]922# nothing to do? or do we (re)add a record based on the parent?
923# yes, yes we do, past the close of the else
924# my $type = ($args{cidr}->{isv6} ? 65282 : ($args{cidr}->masklen == 32 ? 65280 : 65283) );
[659]925# rpc_addRec(defrec => 'n', revrec => 'y', parent_id => $zdata->{rdns_id}, type => $type,
[460]926# address => "$args{cidr}", %args);
[459]927 } else {
928 foreach my $rec (@$reclist) {
[460]929 next unless $rec->{type} == 12 || $rec->{type} == 65280 || $rec->{type} == 65281 ||
930 $rec->{type} == 65282 || $rec->{type} == 65283 || $rec->{type} == 65284;
931 # Template types are only useful when attached to a reverse zone.
932##fixme ..... or ARE THEY?
933 if ($args{delforward} ||
934 $rec->{type} == 12 || $rec->{type} == 65282 ||
935 $rec->{type} == 65283 || $rec->{type} == 65284) {
[481]936 my ($code,$msg) = $dnsdb->delRec('n', 'y', $rec->{record_id});
[460]937 } else {
[481]938 my $ret = $dnsdb->downconvert($rec->{record_id}, $DNSDB::reverse_typemap{A});
[460]939 }
[459]940 } # foreach @$reclist
[460]941 } # nrecs != 0
942 if ($args{parpatt}) {
943 # We've just gone and axed all the records in the reverse zone.
944 # Re-add one to match the parent if we've been given a pattern to use.
[659]945 rpc_addRec(defrec => 'n', revrec => 'y', parent_id => $zdata->{rdns_id},
[460]946 type => ($cidr->{isv6} ? 65284 : 65283),
947 address => $zdata->{revnet}, name => $args{parpatt}, %args);
[459]948 }
949 } # iterate zones within $cidr
950 } # done $cidr-contains-zones
951
952} # end delByCIDR()
953
[684]954# Batch-delete a set of reverse entries similar to updateRevSet
955sub delRevSet {
956 my %args = @_;
957
958 _commoncheck(\%args, 'y');
959
960 my @ret;
961 # loop over passed CIDRs in args{cidrlist}
962 foreach my $cidr (split(',', $args{cidrlist})) {
963 push @ret, delByCIDR(cidr => $cidr, %args)
964 }
965
966 return \@ret;
967} # end delRevSet()
968
[405]969#sub getLogCount {}
970#sub getLogEntries {}
[452]971
972sub getRevPattern {
973 my %args = @_;
974
975 _commoncheck(\%args, 'y');
976
[483]977 return $dnsdb->getRevPattern($args{cidr}, $args{group});
[452]978}
979
[673]980sub getRevSet {
981 my %args = @_;
982
983 _commoncheck(\%args, 'y');
984
985 return $dnsdb->getRevSet($args{cidr}, $args{group});
986}
987
[506]988sub getTypelist {
989 my %args = @_;
990 _commoncheck(\%args, 'y');
[504]991
[506]992 $args{selected} = $reverse_typemap{A} if !$args{selected};
993
994 return $dnsdb->getTypelist($args{recgroup}, $args{selected});
995}
996
[504]997sub getTypemap {
998 my %args = @_;
999 _commoncheck(\%args, 'y');
1000 return \%typemap;
1001}
1002
1003sub getReverse_typemap {
1004 my %args = @_;
1005 _commoncheck(\%args, 'y');
1006 return \%reverse_typemap;
1007}
1008
[405]1009#sub parentID {}
1010#sub isParent {}
[123]1011
[405]1012sub zoneStatus {
[123]1013 my %args = @_;
1014
[405]1015 _commoncheck(\%args, 'y');
[123]1016
[477]1017 my @arglist = ($args{zoneid});
[123]1018 push @arglist, $args{status} if defined($args{status});
1019
[477]1020 my $status = $dnsdb->zoneStatus(@arglist);
[123]1021}
1022
[452]1023# Get a list of hashes referencing the reverse zone(s) for a passed CIDR block
1024sub getZonesByCIDR {
1025 my %args = @_;
1026
1027 _commoncheck(\%args, 'y');
1028
[477]1029 return $dnsdb->getZonesByCIDR(%args);
[452]1030}
1031
[405]1032#sub importAXFR {}
1033#sub importBIND {}
1034#sub import_tinydns {}
1035#sub export {}
1036#sub __export_tiny {}
1037#sub _printrec_tiny {}
1038#sub mailNotify {}
[119]1039
1040sub get_method_list {
1041 my @methods = keys %{$methods};
1042 return \@methods;
1043}
Note: See TracBrowser for help on using the repository browser.