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

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

/branches/stable

Merge /trunk through r721; minor tweaks and updates required for RPC
from IPDB

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