source: trunk/dns-rpc.cgi@ 749

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

/trunk

Fix deprecated syntax

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