source: trunk/dns-rpc.cgi@ 710

Last change on this file since 710 was 710, checked in by Kris Deugau, 8 years ago

/trunk

Refine/fix behaviour of updateRevSet() and chained subs

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