source: branches/stable/dns-rpc.cgi@ 712

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

/branches/stable

Merge bugfixes and enhancements needed for IPDB integration since 1.2.4
forward from /trunk

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