source: trunk/dns-rpc.cgi@ 714

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

/trunk

Refine/fix behaviour of updateRevSet() and chained subs

  • properly represent add, update, and delete actions all in one set
  • do nothing on null "updates" to keep log noise down
  • properly target requests to a single location to avoid stomping unrelated records
  • Property svn:executable set to *
  • Property svn:keywords set to Date Rev Author Id
File size: 35.4 KB
Line 
1#!/usr/bin/perl -w -T
2# XMLRPC interface to manipulate most DNS DB entities
3##
4# $Id: dns-rpc.cgi 710 2016-03-17 19:06:32Z 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 assignments, or we just add a new record all the time.
583 my $filt = ($cidr->{isv6} || $cidr->masklen != 32 ? "$cidr" : $cidr->addr);
584 my $reclist = $dnsdb->getRecList(defrec => 'n', revrec => 'y',
585 id => $zonelist->[0]->{rdns_id}, filter => $filt);
586##fixme: Figure some new magic to automerge new incoming A(AAA)+PTR requests
587# with existing A records to prevent duplication of A(AAA) records
588 if (scalar(@$reclist) == 0) {
589 # Aren't Magic Numbers Fun? See pseudotype list in dnsadmin.
590 my $type = ($cidr->{isv6} ? ($cidr->masklen == 128 ? 65281 : 65284) : ($cidr->masklen == 32 ? 65280 : 65283) );
591 rpc_addRec(defrec => 'n', revrec => 'y', parent_id => $zonelist->[0]->{rdns_id}, type => $type,
592 address => "$cidr", %args);
593 } else {
594 my $flag = 0;
595 foreach my $rec (@$reclist) {
596 # pure PTR plus composite types
597 next unless $rec->{type} == 12 || $rec->{type} == 65280 || $rec->{type} == 65281
598 || $rec->{type} == 65282 || $rec->{type} == 65283 || $rec->{type} == 65284;
599 next unless $rec->{val} eq $filt; # make sure we really update the record we want to update.
600 my %newrec = (host => $args{name}, val => $args{cidr}, type => $args{type});
601 rpc_updateRec(defrec =>'n', revrec => 'y', id => $rec->{record_id},
602 parent_id => $zonelist->[0]->{rdns_id}, address => "$cidr", %args)
603 if _checkRecMod($rec, \%newrec); # and only do the update if there really is something to change
604 $flag = 1;
605 last; # only do one record.
606 }
607 unless ($flag) {
608 # Nothing was updated, so we didn't really have a match. Add as per @$reclist==0
609 # Aren't Magic Numbers Fun? See pseudotype list in dnsadmin.
610 my $type = ($cidr->{isv6} ? 65282 : ($cidr->masklen == 32 ? 65280 : 65283) );
611 rpc_addRec(defrec => 'n', revrec => 'y', parent_id => $zonelist->[0]->{rdns_id}, type => $type,
612 address => "$cidr", %args);
613 }
614 }
615 } else {
616 # ebbeh? CIDR is only partly represented in DNS. This needs manual intervention.
617 } # done single-zone-contains-$cidr
618 } else {
619 # Overlapping reverse zones shouldn't be possible, so if we're here we've got a CIDR
620 # that spans multiple reverse zones (eg, /23 CIDR -> 2 /24 rzones)
621 foreach my $zdata (@$zonelist) {
622 my $reclist = $dnsdb->getRecList(defrec => 'n', revrec => 'y',
623 id => $zdata->{rdns_id}, filter => $zdata->{revnet});
624 if (scalar(@$reclist) == 0) {
625 my $type = ($args{cidr}->{isv6} ? 65282 : ($args{cidr}->masklen == 32 ? 65280 : 65283) );
626 rpc_addRec(defrec => 'n', revrec => 'y', parent_id => $zdata->{rdns_id}, type => $type,
627 address => "$args{cidr}", %args);
628 } else {
629 foreach my $rec (@$reclist) {
630 # only the composite and/or template types; pure PTR or nontemplate composite
631 # types are nominally impossible here.
632 next unless $rec->{type} == 65282 || $rec->{type} == 65283 || $rec->{type} == 65284;
633 rpc_updateRec(defrec => 'n', revrec => 'y', id => $rec->{record_id},
634 parent_id => $zdata->{rdns_id}, %args);
635 last; # only do one record.
636 }
637 }
638 } # iterate zones within $cidr
639 } # done $cidr-contains-zones
640##fixme: what about errors? what about warnings?
641} # done addOrUpdateRevRec()
642
643# Update rDNS on a whole batch of IP addresses. Presented as a separate sub via RPC
644# since RPC calls can be s...l...o...w....
645sub updateRevSet {
646 my %args = @_;
647
648 _commoncheck(\%args, 'y');
649
650 my @ret;
651 # loop over passed IP/hostname pairs
652 foreach my $key (keys %args) {
653 next unless $key =~ m{^host_((?:[\d.]+|[\da-f:]+)(?:/\d+)?)$};
654 my $ip = $1;
655 push @ret, addOrUpdateRevRec(%args, cidr => $ip, name => $args{$key});
656 }
657
658 # now we check the parts of the block that didn't get passed to see if they should be deleted
659 my $block = new NetAddr::IP $args{cidr};
660 foreach my $ip (@{$block->splitref(32)}) {
661 my $bare = $ip->addr;
662 next if $args{"host_$bare"};
663 delByCIDR(delforward => 1, delsubs => 0, cidr => $bare, location => $args{location},
664 rpcuser => $args{rpcuser}, rpcsystem => $args{rpcsystem});
665 }
666
667##fixme: what about errors? what about warnings?
668 return \@ret;
669} # done updateRevSet()
670
671# Split a template record as per a passed CIDR.
672# Requires the CIDR and the new mask length
673sub splitTemplate {
674 my %args = @_;
675
676 _commoncheck(\%args, 'y');
677
678 my $cidr = new NetAddr::IP $args{cidr};
679
680 my $zonelist = $dnsdb->getZonesByCIDR(%args);
681
682 if (scalar(@$zonelist) == 0) {
683 # enhh.... WTF?
684
685 } elsif (scalar(@$zonelist) == 1) {
686 my $zone = new NetAddr::IP $zonelist->[0]->{revnet};
687 if ($zone->contains($cidr)) {
688 # Find the first record in the reverse zone that matches the CIDR we're splitting...
689 my $reclist = $dnsdb->getRecList(defrec => 'n', revrec => 'y',
690 id => $zonelist->[0]->{rdns_id}, filter => $cidr, sortby => 'val', sortorder => 'DESC');
691 my $oldrec;
692 foreach my $rec (@$reclist) {
693 my $reccidr = new NetAddr::IP $rec->{val};
694 next unless $cidr->contains($reccidr); # not sure this is needed here
695 # ... and is a reverse-template type.
696 # Could arguably trim the list below to just 65282, 65283, 65284
697 next unless $rec->{type} == 12 || $rec->{type} == 65280 || $rec->{type} == 65281 ||
698 $rec->{type} == 65282 || $rec->{type} == 65283 ||$rec->{type} == 65284;
699 # snag old record so we can copy its data
700 $oldrec = $dnsdb->getRecLine('n', 'y', $rec->{record_id});
701 last; # we've found one record that meets our criteria; Extras Are Irrelevant
702 }
703
704 my @newblocks = $cidr->split($args{newmask});
705 # Change the existing record with the new CIDR
706 my $up_res = rpc_updateRec(%args, val => $newblocks[0], id => $oldrec->{record_id}, defrec => 'n', revrec => 'y');
707 my @ret;
708 # the update is assumed to have succeeded if it didn't fail.
709##fixme: find a way to save and return "warning" states?
710 push @ret, {block => "$newblocks[0]", code => "OK", msg => $up_res};
711 # And now add new record(s) for each of the new CIDR entries, reusing the old data
712 for (my $i = 1; $i <= $#newblocks; $i++) {
713 my $newval = "$newblocks[$i]";
714 my @recargs = ('n', 'y', $oldrec->{rdns_id}, \$oldrec->{host}, \$oldrec->{type}, \$newval,
715 $oldrec->{ttl}, $oldrec->{location}, 0, '');
716 my ($code, $msg) = $dnsdb->addRec(@recargs);
717 # Note failures here are not fatal; this should typically only ever be called by IPDB
718 push @ret, {block => "$newblocks[$i]", code => $code, msg => $up_res};
719 }
720 # return an info hash in case of warnings doing the update or add(s)
721 return \@ret;
722
723 } else { # $cidr > $zone but we only have one zone
724 # ebbeh? CIDR is only partly represented in DNS. This needs manual intervention.
725 return "Warning: $args{cidr} is only partly represented in DNS. Check and update DNS records manually.";
726 } # done single-zone-contains-$cidr
727
728 } else {
729 # multiple zones nominally "contain" $cidr
730 } # done $cidr-contains-zones
731
732} # done splitTemplate()
733
734# Resize a template according to an old/new CIDR pair
735# Takes the old cidr in $args{oldcidr} and the new in $args{newcidr}
736sub resizeTemplate {
737 my %args = @_;
738
739 _commoncheck(\%args, 'y');
740
741 my $oldcidr = new NetAddr::IP $args{oldcidr};
742 my $newcidr = new NetAddr::IP $args{newcidr};
743 die "$oldcidr and $newcidr do not overlap"
744 unless $oldcidr->contains($newcidr) || $newcidr->contains($oldcidr);
745 $args{cidr} = $args{oldcidr};
746
747 my $up_res;
748
749 my $zonelist = $dnsdb->getZonesByCIDR(%args);
750 if (scalar(@$zonelist) == 0) {
751 # enhh.... WTF?
752
753 } elsif (scalar(@$zonelist) == 1) {
754 my $zone = new NetAddr::IP $zonelist->[0]->{revnet};
755 if ($zone->contains($oldcidr)) {
756 # Find record(s) matching the old and new CIDR
757
758 my $sql = q(
759 SELECT record_id,host,val
760 FROM records
761 WHERE rdns_id = ?
762 AND type IN (12, 65280, 65281, 65282, 65283, 65284)
763 AND (val = ? OR val = ?)
764 ORDER BY masklen(inetlazy(val)) ASC
765 );
766 my $sth = $dnsdb->{dbh}->prepare($sql);
767 $sth->execute($zonelist->[0]->{rdns_id}, "$oldcidr", "$newcidr");
768 my $upd_id;
769 my $oldhost;
770 while (my ($recid, $host, $val) = $sth->fetchrow_array) {
771 my $tcidr = NetAddr::IP->new($val);
772 if ($tcidr == $newcidr) {
773 # Match found for new CIDR. Delete this record.
774 $up_res = $dnsdb->delRec('n', 'y', $recid);
775 } else {
776 # Update this record, then exit the loop
777 $up_res = rpc_updateRec(%args, val => $newcidr, id => $recid, defrec => 'n', revrec => 'y');
778 last;
779 }
780 # Your llama is on fire
781 }
782 $sth->finish;
783
784 return "Template record for $oldcidr changed to $newcidr.";
785
786 } else { # $cidr > $zone but we only have one zone
787 # ebbeh? CIDR is only partly represented in DNS. This needs manual intervention.
788 return "Warning: $args{cidr} is only partly represented in DNS. Check and update DNS records manually.";
789 } # done single-zone-contains-$cidr
790
791 } else {
792 # multiple zones nominally "contain" $cidr
793 }
794
795 return $up_res;
796} # done resizeTemplate()
797
798# Convert one or more template records to a set of individual IP records. Expands the template.
799# Handle the case of nested templates, although the primary caller (IPDB) should not be
800# able to generate records that would trigger that case.
801# Accounts for existing PTR or A+PTR records same as on-export template expansion.
802# Takes a list of templates and a bounding CIDR?
803sub templatesToRecords {
804 my %args = @_;
805
806 _commoncheck(\%args, 'y');
807
808 my %iplist;
809 my @retlist;
810
811 my $zsth = $dnsdb->{dbh}->prepare("SELECT rdns_id,group_id FROM revzones WHERE revnet >>= ?");
812 # Going to assume template records with no expiry
813 # Also note IPv6 template records don't expand sanely the way v4 records do
814 my $recsth = $dnsdb->{dbh}->prepare(q(
815 SELECT record_id, domain_id, host, type, val, ttl, location
816 FROM records
817 WHERE rdns_id = ?
818 AND type IN (12, 65280, 65282, 65283)
819 AND inetlazy(val) <<= ?
820 ORDER BY masklen(inetlazy(val)) DESC
821 ));
822 my $insth = $dnsdb->{dbh}->prepare("INSERT INTO records (domain_id, rdns_id, host, type, val, ttl, location)".
823 " VALUES (?,?,?,?,?,?,?)");
824 my $delsth = $dnsdb->{dbh}->prepare("DELETE FROM records WHERE record_id = ?");
825 my %typedown = (12 => 12, 65280 => 65280, 65281 => 65281, 65282 => 12, 65283 => 65280, 65284 => 65281);
826
827 my @checkrange;
828
829 local $dnsdb->{dbh}->{AutoCommit} = 0;
830 local $dnsdb->{dbh}->{RaiseError} = 1;
831
832 eval {
833 foreach my $template (@{$args{templates}}) {
834 $zsth->execute($template);
835 my ($zid,$zgrp) = $zsth->fetchrow_array;
836 if (!$zid) {
837 push @retlist, {$template, "Zone not found"};
838 next;
839 }
840 $recsth->execute($zid, $template);
841 while (my ($recid, $domid, $host, $type, $val, $ttl, $loc) = $recsth->fetchrow_array) {
842 # Skip single IPs with PTR or A+PTR records
843 if ($type == 12 || $type == 65280) {
844 $iplist{"$val/32"}++;
845 next;
846 }
847 my @newips = NetAddr::IP->new($template)->split(32);
848 $type = $typedown{$type};
849 foreach my $ip (@newips) {
850 next if $iplist{$ip};
851 my $newhost = $host;
852 $dnsdb->_template4_expand(\$newhost, $ip->addr);
853 $insth->execute($domid, $zid, $newhost, $type, $ip->addr, $ttl, $loc);
854 $iplist{$ip}++;
855 }
856 $delsth->execute($recid);
857 $dnsdb->_log(group_id => $zgrp, domain_id => $domid, rdns_id => $zid,
858 entry => "$template converted to individual $typemap{$type} records");
859 push @retlist, "$template converted to individual records";
860 } # record fetch
861 } # foreach passed template CIDR
862
863 $dnsdb->{dbh}->commit;
864 };
865 if ($@) {
866 die "Error converting a template record to individual records: $@";
867 }
868
869 return \@retlist;
870
871} # done templatesToRecords()
872
873sub delRec {
874 my %args = @_;
875
876 _commoncheck(\%args, 'y');
877
878 _reccheck(\%args);
879
880 my ($code, $msg) = $dnsdb->delRec($args{defrec}, $args{revrec}, $args{id});
881
882 die "$msg\n" if $code eq 'FAIL';
883 return $msg;
884}
885
886sub delByCIDR {
887 my %args = @_;
888
889 _commoncheck(\%args, 'y');
890
891 # Caller may pass 'n' in delsubs. Assume it should be false/undefined
892 # unless the caller explicitly requested 'yes'
893 $args{delsubs} = 0 if $args{delsubs} ne 'y';
894
895 # Don't delete the A component of an A+PTR by default
896 $args{delforward} = 0 if !$args{delforward};
897
898 # much like addOrUpdateRevRec()
899 my $zonelist = $dnsdb->getZonesByCIDR(%args);
900 my $cidr = new NetAddr::IP $args{cidr};
901
902 if (scalar(@$zonelist) == 0) {
903 # enhh.... WTF?
904 } elsif (scalar(@$zonelist) == 1) {
905
906 # check if the single zone returned is bigger than the CIDR
907 my $zone = new NetAddr::IP $zonelist->[0]->{revnet};
908 if ($zone->contains($cidr)) {
909 if ($args{delsubs}) {
910 # Delete ALL EVARYTHING!!one11!! in $args{cidr}
911 my $reclist = $dnsdb->getRecList(defrec => 'n', revrec => 'y', id => $zonelist->[0]->{rdns_id});
912 foreach my $rec (@$reclist) {
913 my $reccidr = new NetAddr::IP $rec->{val};
914 next unless $cidr->contains($reccidr);
915 next unless $rec->{type} == 12 || $rec->{type} == 65280 || $rec->{type} == 65281 ||
916 $rec->{type} == 65282 || $rec->{type} == 65283 ||$rec->{type} == 65284;
917 ##fixme: multiple records, wanna wax'em all, how to report errors?
918 if ($args{delforward} ||
919 $rec->{type} == 12 || $rec->{type} == 65282 ||
920 $rec->{type} == 65283 || $rec->{type} == 65284) {
921 my ($code,$msg) = $dnsdb->delRec('n', 'y', $rec->{record_id});
922 } else {
923##fixme: AAAA+PTR?
924 my $ret = $dnsdb->downconvert($rec->{record_id}, $DNSDB::reverse_typemap{A});
925 }
926 }
927 if ($args{parpatt} && $zone == $cidr) {
928 # Edge case; we've just gone and axed all the records in the reverse zone.
929 # Re-add one to match the parent if we've been given a pattern to use.
930 rpc_addRec(defrec => 'n', revrec => 'y', parent_id => $zonelist->[0]->{rdns_id},
931 type => ($zone->{isv6} ? 65284 : 65283), address => "$cidr", name => $args{parpatt}, %args);
932 }
933
934 } else {
935 # Selectively delete only exact matches on $args{cidr}
936 # We need to strip the CIDR mask on IPv4 /32 assignments, or we can't find single-IP records
937 my $filt = ($cidr->{isv6} || $cidr->masklen != 32 ? "$cidr" : $cidr->addr);
938 my $reclist = $dnsdb->getRecList(defrec => 'n', revrec => 'y',
939 id => $zonelist->[0]->{rdns_id}, filter => $filt, sortby => 'val', sortorder => 'DESC');
940 foreach my $rec (@$reclist) {
941 my $reccidr = new NetAddr::IP $rec->{val};
942 next unless $cidr == $reccidr;
943 # restrict to the right location
944 next unless ( defined($rec->{locname}) && defined($args{location}) &&
945 $rec->{locname} eq $args{location} );
946 next unless $rec->{type} == 12 || $rec->{type} == 65280 || $rec->{type} == 65281 ||
947 $rec->{type} == 65282 || $rec->{type} == 65283 ||$rec->{type} == 65284;
948 if ($args{delforward} || $rec->{type} == 12) {
949 my ($code,$msg) = $dnsdb->delRec('n', 'y', $rec->{record_id});
950 die "$msg\n" if $code eq 'FAIL';
951 return $msg;
952 } else {
953 my $ret = $dnsdb->downconvert($rec->{record_id}, $DNSDB::reverse_typemap{A});
954 die $dnsdb->errstr."\n" if !$ret;
955 return "A+PTR for $args{cidr} split and PTR removed";
956 }
957 } # foreach @$reclist
958 }
959
960 } else { # $cidr > $zone but we only have one zone
961 # ebbeh? CIDR is only partly represented in DNS. This needs manual intervention.
962 return "Warning: $args{cidr} is only partly represented in DNS. Check and remove DNS records manually.";
963 } # done single-zone-contains-$cidr
964
965 } else { # multiple zones nominally "contain" $cidr
966 # Overlapping reverse zones shouldn't be possible, so if we're here we've got a CIDR
967 # that spans multiple reverse zones (eg, /23 CIDR -> 2 /24 rzones)
968 foreach my $zdata (@$zonelist) {
969 my $reclist = $dnsdb->getRecList(defrec => 'n', revrec => 'y', id => $zdata->{rdns_id});
970 if (scalar(@$reclist) == 0) {
971# nothing to do? or do we (re)add a record based on the parent?
972# yes, yes we do, past the close of the else
973# my $type = ($args{cidr}->{isv6} ? 65282 : ($args{cidr}->masklen == 32 ? 65280 : 65283) );
974# rpc_addRec(defrec => 'n', revrec => 'y', parent_id => $zdata->{rdns_id}, type => $type,
975# address => "$args{cidr}", %args);
976 } else {
977 foreach my $rec (@$reclist) {
978 next unless $rec->{type} == 12 || $rec->{type} == 65280 || $rec->{type} == 65281 ||
979 $rec->{type} == 65282 || $rec->{type} == 65283 || $rec->{type} == 65284;
980 # Template types are only useful when attached to a reverse zone.
981##fixme ..... or ARE THEY?
982 if ($args{delforward} ||
983 $rec->{type} == 12 || $rec->{type} == 65282 ||
984 $rec->{type} == 65283 || $rec->{type} == 65284) {
985 my ($code,$msg) = $dnsdb->delRec('n', 'y', $rec->{record_id});
986 } else {
987 my $ret = $dnsdb->downconvert($rec->{record_id}, $DNSDB::reverse_typemap{A});
988 }
989 } # foreach @$reclist
990 } # nrecs != 0
991 if ($args{parpatt}) {
992 # We've just gone and axed all the records in the reverse zone.
993 # Re-add one to match the parent if we've been given a pattern to use.
994 rpc_addRec(defrec => 'n', revrec => 'y', parent_id => $zdata->{rdns_id},
995 type => ($cidr->{isv6} ? 65284 : 65283),
996 address => $zdata->{revnet}, name => $args{parpatt}, %args);
997 }
998 } # iterate zones within $cidr
999 } # done $cidr-contains-zones
1000
1001} # end delByCIDR()
1002
1003# Batch-delete a set of reverse entries similar to updateRevSet
1004sub delRevSet {
1005 my %args = @_;
1006
1007 _commoncheck(\%args, 'y');
1008
1009 my @ret;
1010 # loop over passed CIDRs in args{cidrlist}
1011 foreach my $cidr (split(',', $args{cidrlist})) {
1012 push @ret, delByCIDR(cidr => $cidr, %args)
1013 }
1014
1015 return \@ret;
1016} # end delRevSet()
1017
1018#sub getLogCount {}
1019#sub getLogEntries {}
1020
1021sub getRevPattern {
1022 my %args = @_;
1023
1024 _commoncheck(\%args, 'y');
1025
1026 return $dnsdb->getRevPattern($args{cidr}, location => $args{location}, group => $args{group});
1027}
1028
1029sub getRevSet {
1030 my %args = @_;
1031
1032 _commoncheck(\%args, 'y');
1033
1034 return $dnsdb->getRevSet($args{cidr}, location => $args{location}, group => $args{group});
1035}
1036
1037sub getTypelist {
1038 my %args = @_;
1039 _commoncheck(\%args, 'y');
1040
1041 $args{selected} = $reverse_typemap{A} if !$args{selected};
1042
1043 return $dnsdb->getTypelist($args{recgroup}, $args{selected});
1044}
1045
1046sub getTypemap {
1047 my %args = @_;
1048 _commoncheck(\%args, 'y');
1049 return \%typemap;
1050}
1051
1052sub getReverse_typemap {
1053 my %args = @_;
1054 _commoncheck(\%args, 'y');
1055 return \%reverse_typemap;
1056}
1057
1058#sub parentID {}
1059#sub isParent {}
1060
1061sub zoneStatus {
1062 my %args = @_;
1063
1064 _commoncheck(\%args, 'y');
1065
1066 $args{reverse} = 'n' if !$args{reverse} || $args{reverse} ne 'y';
1067 my @arglist = ($args{zoneid}, $args{reverse});
1068 push @arglist, $args{status} if defined($args{status});
1069
1070 my $status = $dnsdb->zoneStatus(@arglist);
1071}
1072
1073# Get a list of hashes referencing the reverse zone(s) for a passed CIDR block
1074sub getZonesByCIDR {
1075 my %args = @_;
1076
1077 _commoncheck(\%args, 'y');
1078
1079 return $dnsdb->getZonesByCIDR(%args);
1080}
1081
1082#sub importAXFR {}
1083#sub importBIND {}
1084#sub import_tinydns {}
1085#sub export {}
1086#sub __export_tiny {}
1087#sub _printrec_tiny {}
1088#sub mailNotify {}
1089
1090sub get_method_list {
1091 my @methods = keys %{$methods};
1092 return \@methods;
1093}
Note: See TracBrowser for help on using the repository browser.