source: trunk/dns-rpc.cgi@ 686

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

/trunk

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