source: trunk/dns-rpc.cgi@ 685

Last change on this file since 685 was 684, checked in by Kris Deugau, 10 years ago

/trunk

Add delRevSet() to RPC handler

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