source: trunk/dns-rpc.cgi@ 717

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

/trunk

Rollup of refinements mainly for IPDB RPC calls

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