source: trunk/DNSDB.pm@ 741

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

/trunk

Add another template expansion pattern; %x for the "n'th natural IP in
the range"

  • Property svn:keywords set to Date Rev Author Id
File size: 248.1 KB
Line 
1# dns/trunk/DNSDB.pm
2# Abstraction functions for DNS administration
3##
4# $Id: DNSDB.pm 741 2016-08-25 21:05:13Z kdeugau $
5# Copyright 2008-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
21package DNSDB;
22
23use strict;
24use warnings;
25use Exporter;
26use DBI;
27use Net::DNS;
28use Crypt::PasswdMD5;
29use Digest::MD5 qw(md5_hex);
30use Net::SMTP;
31use NetAddr::IP 4.027 qw(:lower);
32use POSIX;
33use Fcntl qw(:flock);
34use Time::TAI64 qw(:tai64);
35
36use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
37
38$VERSION = 1.3; ##VERSION##
39@ISA = qw(Exporter);
40@EXPORT_OK = qw(
41 &initGlobals &login &initActionLog
42 &getPermissions &changePermissions &comparePermissions
43 &changeGroup
44 &connectDB &finish
45 &addDomain &delZone &domainName &revName &domainID &revID &addRDNS
46 &getZoneCount &getZoneList &getZoneLocation
47 &addGroup &delGroup &getChildren &groupName
48 &getGroupCount &getGroupList
49 &addUser &updateUser &delUser &userFullName &userStatus &getUserData
50 &getUserCount &getUserList &getUserDropdown
51 &addLoc &updateLoc &delLoc &getLoc
52 &getLocCount &getLocList &getLocDropdown
53 &getSOA &updateSOA &getRecLine &getRecList &getRecCount
54 &addRec &updateRec &delRec
55 &getLogCount &getLogEntries
56 &getRevPattern
57 &getTypelist
58 &parentID
59 &isParent
60 &zoneStatus &getZonesByCIDR &importAXFR
61 &export
62 &mailNotify
63 %typemap %reverse_typemap
64 @permtypes $permlist %permchains
65 );
66
67@EXPORT = qw(%typemap %reverse_typemap @permtypes $permlist %permchains);
68%EXPORT_TAGS = ( ALL => [qw(
69 &initGlobals &login &initActionLog
70 &getPermissions &changePermissions &comparePermissions
71 &changeGroup
72 &connectDB &finish
73 &addDomain &delZone &domainName &revName &domainID &revID &addRDNS
74 &getZoneCount &getZoneList &getZoneLocation
75 &addGroup &delGroup &getChildren &groupName
76 &getGroupCount &getGroupList
77 &addUser &updateUser &delUser &userFullName &userStatus &getUserData
78 &getUserCount &getUserList &getUserDropdown
79 &addLoc &updateLoc &delLoc &getLoc
80 &getLocCount &getLocList &getLocDropdown
81 &getSOA &updateSOA &getRecLine &getRecList &getRecCount
82 &addRec &updateRec &delRec
83 &getLogCount &getLogEntries
84 &getRevPattern
85 &getTypelist
86 &parentID
87 &isParent
88 &zoneStatus &getZonesByCIDR &importAXFR
89 &export
90 &mailNotify
91 %typemap %reverse_typemap
92 @permtypes $permlist %permchains
93 )]
94 );
95
96our $errstr = '';
97our $resultstr = '';
98
99# Arguably defined wholly in the db, but little reason to change without supporting code changes
100# group_view, user_view permissions? separate rDNS permission(s)?
101our @permtypes = qw (
102 group_edit group_create group_delete
103 user_edit user_create user_delete
104 domain_edit domain_create domain_delete
105 record_edit record_create record_delete record_locchg
106 location_edit location_create location_delete location_view
107 self_edit admin
108);
109our $permlist = join(',',@permtypes);
110
111# Some permissions more or less require certain others.
112our %permchains = (
113 user_edit => 'self_edit',
114 location_edit => 'location_view',
115 location_create => 'location_view',
116 location_delete => 'location_view',
117 record_locchg => 'location_view',
118);
119
120# DNS record type map and reverse map.
121# loaded from the database, from http://www.iana.org/assignments/dns-parameters
122our %typemap;
123our %reverse_typemap;
124
125## (Semi)private variables
126
127# Hash of functions for validating record types. Filled in initGlobals() since
128# it relies on visibility flags from the rectypes table in the DB
129my %validators;
130
131# Entity-relationship reference hashes.
132my %par_tbl = (
133 group => 'groups',
134 user => 'users',
135 defrec => 'default_records',
136 defrevrec => 'default_rev_records',
137 domain => 'domains',
138 revzone => 'revzones',
139 record => 'records'
140 );
141my %id_col = (
142 group => 'group_id',
143 user => 'user_id',
144 defrec => 'record_id',
145 defrevrec => 'record_id',
146 domain => 'domain_id',
147 revzone => 'rdns_id',
148 record => 'record_id'
149 );
150my %par_col = (
151 group => 'parent_group_id',
152 user => 'group_id',
153 defrec => 'group_id',
154 defrevrec => 'group_id',
155 domain => 'group_id',
156 revzone => 'group_id',
157 record => 'domain_id'
158 );
159my %par_type = (
160 group => 'group',
161 user => 'group',
162 defrec => 'group',
163 defrevrec => 'group',
164 domain => 'group',
165 revzone => 'group',
166 record => 'domain'
167 );
168
169##
170## Constructor and destructor
171##
172
173sub new {
174 my $this = shift;
175 my $class = ref($this) || $this;
176 my %args = @_;
177
178 # Prepopulate a basic config. Note some of these *will* cause errors if left unset.
179 # note: add appropriate stanzas in __cfgload() to parse these
180 my %defconfig = (
181 # The only configuration options not loadable from a config file.
182 configfile => "/etc/dnsdb/dnsdb.conf", ##CFG_LEAF##
183
184 # Database connection info
185 dbname => 'dnsdb',
186 dbuser => 'dnsdb',
187 dbpass => 'secret',
188 dbhost => '',
189
190 # Email notice settings
191 mailhost => 'smtp.example.com',
192 mailnotify => 'dnsdb@example.com', # to
193 mailsender => 'dnsdb@example.com', # from
194 mailname => 'DNS Administration',
195 orgname => 'Example Corp',
196 domain => 'example.com',
197
198 # Template directory
199 templatedir => 'templates/',
200# fmeh. this is a real web path, not a logical internal one. hm..
201# cssdir => 'templates/',
202 sessiondir => 'session/',
203 exportcache => 'cache/',
204 usecache => 1, # do we bother using the cache above?
205
206 # Session params
207 timeout => '1h', # passed as-is to CGI::Session
208
209 # Other miscellanea
210 log_failures => 1, # log all evarthing by default
211 perpage => 15,
212 maxfcgi => 10, # reasonable default?
213 force_refresh => 1,
214 lowercase => 0, # mangle as little as possible by default
215 # show IPs and CIDR blocks as-is for reverse zones. valid values are
216 # 'none' (default, show natural IP or CIDR)
217 # 'zone' (zone name, wherever used)
218 # 'record' (IP or CIDR values in reverse record lists)
219 # 'all' (all IP values in any reverse zone view)
220 showrev_arpa => 'none',
221 # Two options for template record expansion:
222 template_skip_0 => 0, # publish .0 by default
223 template_skip_255 => 0, # publish .255 by default
224 # allow TXT records to be dealt with mostly automatically by DNS server?
225 autotxt => 1,
226 );
227
228 # Config file parse calls.
229 # If we are passed a blank argument for $args{configfile},
230 # we should NOT parse the default config file - we will
231 # rely on hardcoded defaults OR caller-specified values.
232 # If we are passed a non-blank argument, parse that file.
233 # If no config file is specified, parse the default one.
234 my %siteconfig;
235 if (defined($args{configfile})) {
236 if ($args{configfile}) {
237 return if !__cfgload($args{configfile}, \%siteconfig);
238 }
239 } else {
240 return if !__cfgload($defconfig{configfile}, \%siteconfig);
241 }
242
243 # Assemble the object. Apply configuration hashes in order of precedence.
244 my $self = {
245 # Hardcoded defaults
246 %defconfig,
247 # Default config file OR caller-specified one, loaded above
248 %siteconfig,
249 # Caller-specified arguments
250 %args
251 };
252 bless $self, $class;
253
254 # Several settings are booleans. Handle multiple possible ways of setting them.
255 for my $boolopt ('log_failures', 'force_refresh', 'lowercase', 'usecache',
256 'template_skip_0', 'template_skip_255', 'autotxt') {
257 if ($self->{$boolopt} ne '1' && $self->{$boolopt} ne '0') {
258 # true/false, on/off, yes/no all valid.
259 if ($self->{$boolopt} =~ /^(?:true|false|t|f|on|off|yes|no)$/) {
260 if ($self->{$boolopt} =~ /(?:true|t|on|yes)/) {
261 $self->{$boolopt} = 1;
262 } else {
263 $self->{$boolopt} = 0;
264 }
265 } else {
266 warn "Bad $boolopt setting $self->{$boolopt}, using default\n";
267 $self->{$boolopt} = $defconfig{$boolopt};
268 }
269 }
270 }
271
272 # Enum-ish option(s)
273 if (!grep /$self->{showrev_arpa}/, ('none','zone','record','all')) {
274 warn "Bad showrev_arpa setting $self->{showrev_arpa}, using default\n";
275 $self->{showrev_arpa} = 'none';
276 }
277
278 # Try to connect to the DB, and initialize a number of handy globals.
279 $self->{dbh} = connectDB($self->{dbname}, $self->{dbuser}, $self->{dbpass}, $self->{dbhost}) or return;
280 $self->initGlobals();
281
282 return $self;
283}
284
285sub DESTROY {
286 my $self = shift;
287 $self->{dbh}->disconnect if $self->{dbh};
288}
289
290sub errstr { $DNSDB::errstr; }
291
292##
293## utility functions
294##
295
296## DNSDB::_rectable()
297# Takes default+rdns flags, returns appropriate table name
298sub _rectable {
299 my $def = shift;
300 my $rev = shift;
301
302 return 'records' if $def ne 'y';
303 return 'default_records' if $rev ne 'y';
304 return 'default_rev_records';
305} # end _rectable()
306
307## DNSDB::_recparent()
308# Takes default+rdns flags, returns appropriate parent-id column name
309sub _recparent {
310 my $def = shift;
311 my $rev = shift;
312
313 return 'group_id' if $def eq 'y';
314 return 'rdns_id' if $rev eq 'y';
315 return 'domain_id';
316} # end _recparent()
317
318## DNSDB::_ipparent()
319# Check an IP to be added in a reverse zone to see if it's really in the requested parent.
320# Takes default and reverse flags, IP (fragment) to check, parent zone ID,
321# and a reference to a NetAddr::IP object (also used to pass back a fully-reconstructed IP for
322# database insertion)
323sub _ipparent {
324 my $self = shift;
325 my $dbh = $self->{dbh};
326 my $defrec = shift;
327 my $revrec = shift;
328 my $val = shift;
329 my $id = shift;
330 my $addr = shift;
331
332 return if $revrec ne 'y'; # this sub not useful in forward zones
333
334 $$addr = NetAddr::IP->new($$val); #necessary?
335
336 # subsub to split, reverse, and overlay an IP fragment on a netblock
337 sub __rev_overlay {
338 my $splitme = shift; # ':' or '.', m'lud?
339 my $parnet = shift;
340 my $val = shift;
341 my $addr = shift;
342
343 my $joinme = $splitme;
344 $splitme = '\.' if $splitme eq '.';
345 my @working = reverse(split($splitme, $parnet->addr));
346 my @parts = reverse(split($splitme, $$val));
347 for (my $i = 0; $i <= $#parts; $i++) {
348 $working[$i] = $parts[$i];
349 }
350 my $checkme = NetAddr::IP->new(join($joinme, reverse(@working))) or return 0;
351 return 0 unless $checkme->within($parnet);
352 $$addr = $checkme; # force "correct" IP to be recorded.
353 return 1;
354 }
355
356 my ($parstr) = $dbh->selectrow_array("SELECT revnet FROM revzones WHERE rdns_id = ?", undef, ($id));
357 my $parnet = NetAddr::IP->new($parstr);
358
359 # Fail early on v6-in-v4 or v4-in-v6. We're not accepting these ATM.
360 return 0 if $parnet->addr =~ /\./ && $$val =~ /:/;
361 return 0 if $parnet->addr =~ /:/ && $$val =~ /\./;
362
363 if ($$addr && ($$val =~ /^[\da-fA-F][\da-fA-F:]+[\da-fA-F]$/ || $$val =~ m|/\d+$|)) {
364 # the only case where NetAddr::IP's acceptance of legitimate IPs is "correct" is for a proper IPv6 address,
365 # or a netblock (only expected on templates)
366 # the rest we have to restructure before fiddling. *sigh*
367 return 1 if $$addr->within($parnet);
368 } else {
369 # We don't have a complete IP in $$val (yet)... unless we have a netblock
370 if ($parnet->addr =~ /:/) {
371 $$val =~ s/^:+//; # gotta strip'em all...
372 return __rev_overlay(':', $parnet, $val, $addr);
373 }
374 if ($parnet->addr =~ /\./) {
375 $$val =~ s/^\.+//;
376 return __rev_overlay('.', $parnet, $val, $addr);
377 }
378 # should be impossible to get here...
379 }
380 # ... and here.
381 # can't do nuttin' in forward zones
382} # end _ipparent()
383
384## DNSDB::_maybeip()
385# Wrapper for quick "does this look like an IP address?" regex, so we don't make dumb copy-paste mistakes
386sub _maybeip {
387 my $izzit = shift; # reference
388 return 1 if $$izzit =~ m,^(?:[\d\./]+|[0-9a-fA-F:/]+)$,;
389}
390
391## DNSDB::_inrev()
392# Check if a given "hostname" is within a given reverse zone
393# Takes a reference to the "hostname" and the reverse zone CIDR as a NetAddr::IP
394# Returns true/false. Sets $errstr on errors.
395sub _inrev {
396 my $self = shift;
397 my $dbh = $self->{dbh};
398 # References, since we might munge them
399 my $fq = shift;
400 my $zone = shift;
401
402 # set default error
403 $errstr = "$$fq not within $zone";
404
405 # Unlike forward zones, we will not coerce the data into the reverse zone - an A record
406 # in a reverse zone is already silly enough without appending a mess of 1.2.3.in-addr.arpa
407 # (or worse, 1.2.3.4.5.6.7.8.ip6.arpa) on the end of the nominal "hostname".
408 # We're also going to allow the "hostname" to be stored as .arpa or IP, because of
409 # non-IP FQDNs in .arpa
410 if ($$fq =~ /\.arpa$/) {
411 # "FQDN" could be any syntactically legitimate string, but it must be within the formal
412 # .arpa zone. Note we're not validating these for correct reverse-IP values.
413 # yes, we really need the v6 branch on the end here.
414 $zone = _ZONE($zone, 'ZONE', 'r', '.').($zone->{isv6} ? '.ip6.arpa' : '.in-addr.arpa');
415 return unless $$fq =~ /$zone$/;
416 } else {
417 # in most cases we should be getting a real IP as the "FQDN" to test
418 my $addr = new NetAddr::IP $$fq if _maybeip($fq);
419
420 # "FQDN" should be a valid IP address. Normalize formatting if so.
421 if (!$addr) {
422 $errstr = "$$fq is not a valid IP address";
423 return;
424 }
425 return if !$zone->contains($addr);
426 ($$fq = $addr) =~ s{/(?:32|128)$}{};
427 }
428 return 1;
429} # end _inrev()
430
431## DNSDB::_hostparent()
432# A little different than _ipparent above; this tries to *find* the parent zone of a hostname
433# Takes a hostname.
434# Returns the domain ID of the parent domain if one was found.
435sub _hostparent {
436 my $self = shift;
437 my $dbh = $self->{dbh};
438 my $hname = shift;
439
440 $hname =~ s/^\*\.//; # this should be impossible to find in the domains table.
441 my @hostbits = split /\./, $hname;
442 my $sth = $dbh->prepare("SELECT count(*),domain_id FROM domains WHERE lower(domain) = lower(?) GROUP BY domain_id");
443 foreach (@hostbits) {
444 $sth->execute($hname);
445 my ($found, $parid) = $sth->fetchrow_array;
446 if ($found) {
447 return $parid;
448 }
449 $hname =~ s/^$_\.//;
450 }
451} # end _hostparent()
452
453## DNSDB::_log()
454# Log an action
455# Takes a log entry hash containing at least:
456# group_id, log entry
457# and optionally one or more of:
458# domain_id, rdns_id
459# The %userdata hash provides the user ID, username, and fullname
460sub _log {
461 my $self = shift;
462 my $dbh = $self->{dbh};
463
464 my %args = @_;
465
466 $args{rdns_id} = 0 if !$args{rdns_id};
467 $args{domain_id} = 0 if !$args{domain_id};
468
469##fixme: farm out the actual logging to different subs for file, syslog, internal, etc based on config
470# if ($self->{log_channel} eq 'sql') {
471 $dbh->do("INSERT INTO log (domain_id,rdns_id,group_id,entry,user_id,email,name) VALUES (?,?,?,?,?,?,?)",
472 undef,
473 ($args{domain_id}, $args{rdns_id}, $args{group_id}, $args{entry},
474 $self->{loguserid}, $self->{logusername}, $self->{logfullname}) );
475# } elsif ($self->{log_channel} eq 'file') {
476# } elsif ($self->{log_channel} eq 'syslog') {
477# }
478} # end _log
479
480
481##
482## Record validation subs.
483##
484
485## All of these subs take substantially the same arguments:
486# a hash containing at least the following keys:
487# - defrec (default/live flag)
488# - revrec (forward/reverse flag)
489# - id (parent entity ID)
490# - host (hostname)
491# - rectype
492# - val (IP, hostname [CNAME/MX/SRV] or text)
493# - addr (NetAddr::IP object from val. May be undef.)
494# MX and SRV record validation also expect distance, and SRV records expect weight and port as well.
495# host, rectype, and addr should be references as these may be modified in validation
496
497# A record
498sub _validate_1 {
499 my $self = shift;
500 my $dbh = $self->{dbh};
501
502 my %args = @_;
503
504# only for strict type restrictions
505# return ('FAIL', 'Reverse zones cannot contain A records') if $args{revrec} eq 'y';
506
507 if ($args{revrec} eq 'y') {
508 # Get the revzone, so we can see if ${$args{val}} is in that zone
509 my $revzone = new NetAddr::IP $self->revName($args{id}, 'y');
510
511 return ('FAIL', $errstr) if !$self->_inrev($args{val}, $revzone);
512
513 # ${$args{val}} is either a valid IP or a string ending with the .arpa zone name;
514 # now check if it's a well-formed FQDN
515 return ('FAIL', $errstr) if ! _check_hostname_form(${$args{val}}, ${$args{rectype}}, $args{defrec}, $args{revrec}) &&
516 ${$args{val}} =~ /\.arpa$/;
517
518 # Check IP is well-formed, and that it's a v4 address
519 # Fail on "compact" IPv4 variants, because they are not consistent and predictable.
520 return ('FAIL',"A record must be a valid IPv4 address")
521 unless ${$args{host}} =~ m{^\d+\.\d+\.\d+\.\d+(/\d+)?$};
522 $args{addr} = new NetAddr::IP ${$args{host}};
523 return ('FAIL',"A record must be a valid IPv4 address")
524 unless $args{addr} && !$args{addr}->{isv6};
525 # coerce IP/value to normalized form for storage
526 ${$args{host}} = $args{addr}->addr;
527
528 # I'm just going to ignore the utterly barmy idea of an A record in the *default*
529 # records for a reverse zone; it's bad enough to find one in funky legacy data.
530
531 } else {
532 # revrec ne 'y'
533
534 # Coerce all hostnames to end in ".DOMAIN" for group/default records,
535 # or the intended parent domain for live records.
536 my $pname = ($args{defrec} eq 'y' ? 'DOMAIN' : $self->domainName($args{id}));
537 ${$args{host}} =~ s/\.*$/\.$pname/ if (${$args{host}} ne '@' && ${$args{host}} !~ /$pname$/i);
538
539 # Check if it's a proper formal .arpa name for an IP, and renormalize it to the IP
540 # value if so. Done mainly for symmetry with PTR/A+PTR, and saves a conversion on export.
541 if (${$args{val}} =~ /\.arpa$/) {
542 my ($code,$tmp) = _zone2cidr(${$args{val}});
543 if ($code ne 'FAIL') {
544 ${$args{val}} = $tmp->addr;
545 $args{addr} = $tmp;
546 }
547 }
548 # Check IP is well-formed, and that it's a v4 address
549 # Fail on "compact" IPv4 variants, because they are not consistent and predictable.
550 return ('FAIL',"A record must be a valid IPv4 address")
551 unless ${$args{val}} =~ /^\d+\.\d+\.\d+\.\d+$/;
552 $args{addr} = new NetAddr::IP ${$args{val}};
553 return ('FAIL',"A record must be a valid IPv4 address")
554 unless $args{addr} && !$args{addr}->{isv6};
555 # coerce IP/value to normalized form for storage
556 ${$args{val}} = $args{addr}->addr;
557 }
558
559 return ('OK','OK');
560} # done A record
561
562# NS record
563sub _validate_2 {
564 my $self = shift;
565 my $dbh = $self->{dbh};
566
567 my %args = @_;
568
569 # NS target check - IP addresses not allowed. Must be a more or less well-formed hostname.
570 if ($args{revrec} eq 'y') {
571 return ('FAIL', "NS records cannot point directly to an IP address")
572 if ${$args{host}} =~ /^(?:[\d.]+|[0-9a-fA-F:]+)$/;
573##enhance: Look up the passed value to see if it exists. Ooo, fancy.
574 return ('FAIL', $errstr) if ! _check_hostname_form(${$args{host}}, ${$args{rectype}}, $args{defrec}, $args{revrec});
575 } else {
576 return ('FAIL', "NS records cannot point directly to an IP address")
577 if ${$args{val}} =~ /^(?:[\d.]+|[0-9a-fA-F:]+)$/;
578##enhance: Look up the passed value to see if it exists. Ooo, fancy.
579 return ('FAIL', $errstr) if ! _check_hostname_form(${$args{val}}, ${$args{rectype}}, $args{defrec}, $args{revrec});
580 }
581
582 # Check that the target of the record is within the parent.
583 if ($args{defrec} eq 'n') {
584 # Check if IP/address/zone/"subzone" is within the parent
585 if ($args{revrec} eq 'y') {
586 # Get the revzone, so we can see if ${$args{val}} is in that zone
587 my $revzone = new NetAddr::IP $self->revName($args{id}, 'y');
588
589 # Note the NS record may or may not be for the zone itself, it may be a pointer for a subzone
590 return ('FAIL', $errstr) if !$self->_inrev($args{val}, $revzone);
591
592 # ${$args{val}} is either a valid IP or a string ending with the .arpa zone name;
593 # now check if it's a well-formed FQDN
594##enhance or ##fixme
595# convert well-formed .arpa names to IP addresses to match old "strict" validation design
596 return ('FAIL', $errstr) if ! _check_hostname_form(${$args{val}}, ${$args{rectype}}, $args{defrec}, $args{revrec}) &&
597 ${$args{val}} =~ /\.arpa$/;
598 } else {
599 # Forcibly append the domain name if the hostname being added does not end with the current domain name
600 my $pname = $self->domainName($args{id});
601 ${$args{host}} =~ s/\.*$/\.$pname/ if (${$args{host}} ne '@' && ${$args{host}} !~ /$pname$/i);
602 }
603 } else {
604 # Default reverse NS records should always refer to the implied parent.
605 if ($args{revrec} eq 'y') {
606 ${$args{val}} = 'ZONE';
607 } else {
608 ${$args{host}} = 'DOMAIN';
609 }
610 }
611
612 return ('OK','OK');
613} # done NS record
614
615# CNAME record
616sub _validate_5 {
617 my $self = shift;
618 my $dbh = $self->{dbh};
619
620 my %args = @_;
621
622 # CNAMEs in reverse zones shouldn't be handled manually, they should be generated on
623 # export by use of the "delegation" type. For the masochistic, and those importing
624 # legacy data from $deity-knows-where, we'll support them.
625
626 if ($args{revrec} eq 'y') {
627 # CNAME target check - IP addresses not allowed. Must be a more or less well-formed hostname.
628 return ('FAIL', "CNAME records cannot point directly to an IP address")
629 if ${$args{host}} =~ /^(?:[\d.]+|[0-9a-fA-F:]+)$/;
630
631 if ($args{defrec} eq 'n') {
632 # Get the revzone, so we can see if ${$args{val}} is in that zone
633 my $revzone = new NetAddr::IP $self->revName($args{id}, 'y');
634 return ('FAIL', $errstr) if !$self->_inrev($args{val}, $revzone);
635 # CNAMEs can not be used for parent nodes; just leaf nodes with no other record types
636 # note that this WILL probably miss some edge cases.
637 if (${$args{val}} =~ /^[\d.\/]+$/) {
638 # convert IP "hostname" to .arpa
639 my $tmphn = _ZONE(NetAddr::IP->new(${$args{val}}), 'ZONE', 'r', '.');
640 my $tmpz = _ZONE($revzone, 'ZONE', 'r', '.');
641 return ('FAIL', "The bare zone may not be a CNAME") if $tmphn eq $tmpz;
642##enhance: look up the target name and publish that instead on export
643 }
644 }
645
646##enhance or ##fixme
647# convert well-formed .arpa names to IP addresses to match old "strict" validation design
648 return ('FAIL', $errstr) if ! _check_hostname_form(${$args{val}}, ${$args{rectype}}, $args{defrec}, $args{revrec}) &&
649 ${$args{val}} =~ /\.arpa$/;
650
651##enhance: Look up the passed value to see if it exists. Ooo, fancy.
652 return ('FAIL', $errstr) if ! _check_hostname_form(${$args{host}}, ${$args{rectype}}, $args{defrec}, $args{revrec});
653 } else {
654 # CNAME target check - IP addresses not allowed. Must be a more or less well-formed hostname.
655 return ('FAIL', "CNAME records cannot point directly to an IP address")
656 if ${$args{val}} =~ /^(?:[\d.]+|[0-9a-fA-F:]+)$/;
657
658 # Make sure target is a well-formed hostname
659 return ('FAIL', $errstr) if ! _check_hostname_form(${$args{val}}, ${$args{rectype}}, $args{defrec}, $args{revrec});
660
661 # Forcibly append the domain name if the hostname being added does not end with the current domain name
662 my $pname = ($args{defrec} eq 'y' ? 'DOMAIN' : $self->domainName($args{id}));
663 ${$args{host}} =~ s/\.*$/\.$pname/ if ${$args{host}} !~ /$pname$/i;
664
665 # CNAMEs can not be used for parent nodes; just leaf nodes with no other record types
666 # Enforce this for the zone name
667 return ('FAIL', "The bare zone name may not be a CNAME") if ${$args{host}} eq $pname || ${$args{host}} =~ /^\@/;
668
669##enhance: Look up the passed value to see if it exists. Ooo, fancy.
670 return ('FAIL', $errstr) if ! _check_hostname_form(${$args{val}}, ${$args{rectype}}, $args{defrec}, $args{revrec});
671 }
672
673 return ('OK','OK');
674} # done CNAME record
675
676# SOA record
677sub _validate_6 {
678 # Smart monkeys won't stick their fingers in here; we have
679 # separate dedicated routines to deal with SOA records.
680 return ('OK','OK');
681} # done SOA record
682
683# PTR record
684sub _validate_12 {
685 my $self = shift;
686 my $dbh = $self->{dbh};
687
688 my %args = @_;
689 my $warnflag = '';
690
691 if ($args{defrec} eq 'y') {
692 if ($args{revrec} eq 'y') {
693 if (${$args{val}} =~ /^[\d.]+$/) {
694 # v4 or bare number
695 if (${$args{val}} =~ /^\d+\.\d+\.\d+\.\d+$/) {
696 # probable full IP. pointless but harmless. validate/normalize.
697 my $tmp = NetAddr::IP->new(${$args{val}})->addr
698 or return ('FAIL', "${$args{val}} is not a valid IP address");
699 ${$args{val}} = $tmp;
700 $warnflag = "${$args{val}} will only be added to a small number of zones\n";
701 } elsif (${$args{val}} =~ /^\d+$/) {
702 # bare number. This can be expanded to either a v4 or v6 zone
703 ${$args{val}} =~ s/^\.*/ZONE./ unless ${$args{val}} =~ /^ZONE/;
704 } else {
705 # $deity-only-knows what kind of gibberish we've been given. Only usable as a formal .arpa name.
706 # Append ARPAZONE to be replaced with the formal .arpa zone name when converted to a live record.
707 ${$args{val}} =~ s/\.*$/.ARPAZONE/ unless ${$args{val}} =~ /ARPAZONE$/;
708 }
709 } elsif (${$args{val}} =~ /^[a-fA-F0-9:]+$/) {
710 # v6 or fragment; pray it's not complete gibberish
711 ${$args{val}} =~ s/^:*/ZONE::/ unless ${$args{val}} =~ /^ZONE/;
712 } else {
713 # $deity-only-knows what kind of gibberish we've been given. Only usable as a formal .arpa name.
714 # Append ARPAZONE to be replaced with the formal .arpa zone name when converted to a live record.
715 ${$args{val}} .= ".ARPAZONE" unless ${$args{val}} =~ /ARPAZONE$/;
716 }
717 } else {
718 return ('FAIL', "PTR records are not supported in default record sets for forward zones (domains)");
719 }
720 } else {
721 if ($args{revrec} eq 'y') {
722 # Get the revzone, so we can see if ${$args{val}} is in that zone
723 my $revzone = new NetAddr::IP $self->revName($args{id}, 'y');
724
725 return ('FAIL', $errstr) if !$self->_inrev($args{val}, $revzone);
726
727 if (${$args{val}} =~ /\.arpa$/) {
728 # Check that it's well-formed
729 return ('FAIL', $errstr) if ! _check_hostname_form(${$args{val}}, ${$args{rectype}}, $args{defrec}, $args{revrec});
730
731 # Check if it's a proper formal .arpa name for an IP, and renormalize it to the IP
732 # value if so. I can't see why someone would voluntarily work with those instead of
733 # the natural IP values but what the hey.
734 my ($code,$tmp) = _zone2cidr(${$args{val}});
735 ${$args{val}} = $tmp->addr if $code ne 'FAIL';
736 } else {
737 # not a formal .arpa name, so it should be an IP value. Validate...
738 return ('FAIL', "${$args{val}} is not a valid IP value")
739 unless ${$args{val}} =~ /^(?:\d+\.\d+\.\d+\.\d+|[a-fA-F0-9:]+)$/;
740 $args{addr} = NetAddr::IP->new(${$args{val}})
741 or return ('FAIL', "IP/value looks like an IP address but isn't valid");
742 # ... and normalize.
743 ${$args{val}} = $args{addr}->addr;
744 }
745 # Validate PTR target for form.
746 # %blank% skips the IP when expanding a template record
747 return ('FAIL', $errstr)
748 unless _check_hostname_form(${$args{host}}, ${$args{rectype}}, $args{defrec}, $args{revrec}) ||
749 lc(${$args{host}}) eq '%blank%';
750 } else { # revrec ne 'y'
751 # Fetch the domain and append if the passed hostname isn't within it.
752 my $pname = ($args{defrec} eq 'y' ? 'DOMAIN' : $self->domainName($args{id}));
753 ${$args{host}} =~ s/\.*$/\.$pname/ if (${$args{host}} ne '@' && ${$args{host}} !~ /$pname$/i);
754 # Validate hostname and target for form
755 return ('FAIL', $errstr) if ! _check_hostname_form(${$args{host}}, ${$args{rectype}}, $args{defrec}, $args{revrec});
756 return ('FAIL', $errstr) if ! _check_hostname_form(${$args{val}}, ${$args{rectype}}, $args{defrec}, $args{revrec});
757 }
758 }
759
760# Multiple PTR records do NOT generally do what most people believe they do,
761# and tend to fail in the most awkward way possible. Check and warn.
762
763 my $chkbase = ${$args{val}};;
764 my $hostcol = 'val'; # Reverse zone hostnames are stored "backwards"
765 if ($args{revrec} eq 'n') { # PTRs in forward zones should be rare.
766 $chkbase = ${$args{host}};
767 $hostcol = 'host';
768 }
769 my @checkvals = ($chkbase);
770 if ($chkbase =~ /,/) {
771 # push . and :: variants into checkvals if $chkbase has ,
772 my $tmp;
773 ($tmp = $chkbase) =~ s/,/./;
774 push @checkvals, $tmp;
775 ($tmp = $chkbase) =~ s/,/::/;
776 push @checkvals, $tmp;
777 }
778
779 my $pcsth = $dbh->prepare("SELECT count(*) FROM "._rectable($args{defrec},$args{revrec})." WHERE $hostcol = ?");
780 foreach my $checkme (@checkvals) {
781 if ($args{update}) {
782 # $args{update} contains the ID of the record being updated. If the list of records that matches
783 # the new hostname specification doesn't include this, the change effectively adds a new PTR that's
784 # the same as one or more existing ones.
785 my @ptrs = @{ $dbh->selectcol_arrayref("SELECT record_id FROM "._rectable($args{defrec},$args{revrec}).
786 " WHERE val = ?", undef, ($checkme)) };
787 $warnflag .= "PTR record for $checkme already exists; adding another will probably not do what you want"
788 if @ptrs && (!grep /^$args{update}$/, @ptrs);
789 } else {
790 # New record. Always warn if a PTR exists
791 # Don't warn when a matching A record exists tho
792 my ($ptrcount) = $dbh->selectrow_array("SELECT count(*) FROM "._rectable($args{defrec},$args{revrec}).
793 " WHERE $hostcol = ? AND (type=12 OR type=65280 OR type=65281)", undef, ($checkme));
794 $warnflag .= "PTR record for $checkme already exists; adding another will probably not do what you want"
795 if $ptrcount;
796 }
797 }
798
799 return ('WARN',$warnflag) if $warnflag;
800
801 return ('OK','OK');
802} # done PTR record
803
804# MX record
805sub _validate_15 {
806 my $self = shift;
807 my $dbh = $self->{dbh};
808
809 my %args = @_;
810
811# only for strict type restrictions
812# return ('FAIL', 'Reverse zones cannot contain MX records') if $args{revrec} eq 'y';
813
814 return ('FAIL', "Distance is required for MX records") unless defined(${$args{dist}});
815 ${$args{dist}} =~ s/\s*//g;
816 return ('FAIL',"Distance is required, and must be numeric") unless ${$args{dist}} =~ /^\d+$/;
817
818 ${$args{fields}} = "distance,";
819 push @{$args{vallist}}, ${$args{dist}};
820
821 if ($args{revrec} eq 'n') {
822 # MX target check - IP addresses not allowed. Must be a more or less well-formed hostname.
823 return ('FAIL', "MX records cannot point directly to an IP address")
824 if ${$args{val}} =~ /^(?:[\d.]+|[0-9a-fA-F:]+)$/;
825
826 # Coerce all hostnames to end in ".DOMAIN" for group/default records,
827 # or the intended parent domain for live records.
828 my $pname = ($args{defrec} eq 'y' ? 'DOMAIN' : $self->domainName($args{id}));
829 ${$args{host}} =~ s/\.*$/\.$pname/ if (${$args{host}} ne '@' && ${$args{host}} !~ /$pname$/i);
830 return ('FAIL', $errstr) if ! _check_hostname_form(${$args{host}}, ${$args{rectype}}, $args{defrec}, $args{revrec});
831 } else {
832 # MX target check - IP addresses not allowed. Must be a more or less well-formed hostname.
833 return ('FAIL', "MX records cannot point directly to an IP address")
834 if ${$args{host}} =~ /^(?:[\d.]+|[0-9a-fA-F:]+)$/;
835
836 # MX records in reverse zones get stricter treatment. The UI bars adding them in
837 # reverse record sets, but we "need" to allow editing existing ones. And we'll allow
838 # editing them if some loon manually munges one into a default reverse record set.
839 if ($args{defrec} eq 'n') {
840 # Get the revzone, so we can see if ${$args{val}} is in that zone
841 my $revzone = new NetAddr::IP $self->revName($args{id}, 'y');
842 return ('FAIL', $errstr) if !$self->_inrev($args{val}, $revzone);
843 }
844
845##enhance or ##fixme
846# convert well-formed .arpa names to IP addresses to match old "strict" validation design
847 return ('FAIL', $errstr) if ! _check_hostname_form(${$args{val}}, ${$args{rectype}}, $args{defrec}, $args{revrec}) &&
848 ${$args{val}} =~ /\.arpa$/;
849
850##enhance: Look up the passed value to see if it exists. Ooo, fancy.
851 return ('FAIL', $errstr) if ! _check_hostname_form(${$args{host}}, ${$args{rectype}}, $args{defrec}, $args{revrec});
852
853 }
854
855 return ('OK','OK');
856} # done MX record
857
858# TXT record
859sub _validate_16 {
860 my $self = shift;
861
862 my %args = @_;
863
864 if ($args{revrec} eq 'n') {
865 # Coerce all hostnames to end in ".DOMAIN" for group/default records,
866 # or the intended parent domain for live records.
867 my $pname = ($args{defrec} eq 'y' ? 'DOMAIN' : $self->domainName($args{id}));
868 ${$args{host}} =~ s/\.*$/\.$pname/ if (${$args{host}} ne '@' && ${$args{host}} !~ /$pname$/i);
869 return ('FAIL', $errstr) if ! _check_hostname_form(${$args{host}}, ${$args{rectype}}, $args{defrec}, $args{revrec});
870 } else {
871 # We don't coerce reverse "hostnames" into the zone, mainly because we store most sane
872 # records as IP values, not .arpa names.
873 if ($args{defrec} eq 'n') {
874 # Get the revzone, so we can see if ${$args{val}} is in that zone
875 my $revzone = new NetAddr::IP $self->revName($args{id}, 'y');
876 return ('FAIL', $errstr) if !$self->_inrev($args{val}, $revzone);
877 }
878
879##enhance or ##fixme
880# convert well-formed .arpa names to IP addresses to match old "strict" validation design
881 return ('FAIL', $errstr) if ! _check_hostname_form(${$args{val}}, ${$args{rectype}}, $args{defrec}, $args{revrec}) &&
882 ${$args{val}} =~ /\.arpa$/;
883 }
884
885 # Could arguably put a WARN return here on very long (>512) records
886 return ('OK','OK');
887} # done TXT record
888
889# RP record
890sub _validate_17 {
891 # Probably have to validate these separately some day. Call _validate_16() above since
892 # they're otherwise very similar
893 return _validate_16(@_);
894} # done RP record
895
896# AAAA record
897# Almost but not quite an exact duplicate of A record
898sub _validate_28 {
899 my $self = shift;
900 my $dbh = $self->{dbh};
901
902 my %args = @_;
903
904# only for strict type restrictions
905# return ('FAIL', 'Reverse zones cannot contain AAAA records') if $args{revrec} eq 'y';
906
907 if ($args{revrec} eq 'y') {
908 # Get the revzone, so we can see if ${$args{val}} is in that zone
909 my $revzone = new NetAddr::IP $self->revName($args{id}, 'y');
910
911 return ('FAIL', $errstr) if !$self->_inrev($args{val}, $revzone);
912
913 # ${$args{val}} is either a valid IP or a string ending with the .arpa zone name;
914 # now check if it's a well-formed FQDN
915 return ('FAIL', $errstr) if ! _check_hostname_form(${$args{val}}, ${$args{rectype}}, $args{defrec}, $args{revrec}) &&
916 ${$args{val}} =~ /\.arpa$/;
917
918 # Check IP is well-formed, and that it's a v4 address
919 # Fail on "compact" IPv4 variants, because they are not consistent and predictable.
920 return ('FAIL',"AAAA record must be a valid IPv6 address")
921 unless ${$args{host}} =~ /^[a-fA-F0-9:]+$/;
922 $args{addr} = new NetAddr::IP ${$args{host}};
923 return ('FAIL',"AAAA record must be a valid IPv6 address")
924 unless $args{addr} && $args{addr}->{isv6};
925 # coerce IP/value to normalized form for storage
926 ${$args{host}} = $args{addr}->addr;
927
928 # I'm just going to ignore the utterly barmy idea of an AAAA record in the *default*
929 # records for a reverse zone; it's bad enough to find one in funky legacy data.
930
931 } else {
932 # revrec ne 'y'
933
934 # Coerce all hostnames to end in ".DOMAIN" for group/default records,
935 # or the intended parent domain for live records.
936 my $pname = ($args{defrec} eq 'y' ? 'DOMAIN' : $self->domainName($args{id}));
937 ${$args{host}} =~ s/\.*$/\.$pname/ if (${$args{host}} ne '@' && ${$args{host}} !~ /$pname$/i);
938
939 # Check if it's a proper formal .arpa name for an IP, and renormalize it to the IP
940 # value if so. Done mainly for symmetry with PTR/AAAA+PTR, and saves a conversion on export.
941 if (${$args{val}} =~ /\.arpa$/) {
942 my ($code,$tmp) = _zone2cidr(${$args{val}});
943 if ($code ne 'FAIL') {
944 ${$args{val}} = $tmp->addr;
945 $args{addr} = $tmp;
946 }
947 }
948 # Check IP is well-formed, and that it's a v6 address
949 return ('FAIL',"AAAA record must be a valid IPv6 address")
950 unless ${$args{val}} =~ /^[a-fA-F0-9:]+$/;
951 $args{addr} = new NetAddr::IP ${$args{val}};
952 return ('FAIL',"AAAA record must be a valid IPv6 address")
953 unless $args{addr} && $args{addr}->{isv6};
954 # coerce IP/value to normalized form for storage
955 ${$args{val}} = $args{addr}->addr;
956 }
957
958 return ('OK','OK');
959} # done AAAA record
960
961# SRV record
962sub _validate_33 {
963 my $self = shift;
964 my $dbh = $self->{dbh};
965
966 my %args = @_;
967
968# Not absolutely true but WTF use is an SRV record for a reverse zone?
969# return ('FAIL', 'Reverse zones cannot contain SRV records') if $args{revrec} eq 'y';
970
971 # Key additional record parts. Always required.
972 return ('FAIL',"Distance, port and weight are required for SRV records")
973 unless defined(${$args{weight}}) && defined(${$args{port}}) && defined(${$args{dist}});
974 ${$args{dist}} =~ s/\s*//g;
975 ${$args{weight}} =~ s/\s*//g;
976 ${$args{port}} =~ s/\s*//g;
977 return ('FAIL',"Distance, port and weight are required, and must be numeric")
978 unless ${$args{weight}} =~ /^\d+$/ && ${$args{port}} =~ /^\d+$/;
979
980 ${$args{fields}} = "distance,weight,port,";
981 push @{$args{vallist}}, (${$args{dist}}, ${$args{weight}}, ${$args{port}});
982
983 if ($args{revrec} eq 'n') {
984 # Coerce all hostnames to end in ".DOMAIN" for group/default records,
985 # or the intended parent domain for live records.
986 my $pname = ($args{defrec} eq 'y' ? 'DOMAIN' : $self->domainName($args{id}));
987 ${$args{host}} =~ s/\.*$/\.$pname/ if ${$args{host}} !~ /$pname$/i;
988
989##enhance: Rejig so that we can pass back a WARN red flag, instead of
990# hard-failing, since it seems that purely from the DNS record perspective,
991# SRV records without underscores are syntactically valid
992 # Not strictly true, but SRV records not following this convention won't be found.
993 return ('FAIL',"SRV records must begin with _service._protocol [${$args{host}}]")
994 unless ${$args{host}} =~ /^_[A-Za-z-]+\._[A-Za-z]+\.[a-zA-Z0-9-]+/;
995
996 # SRV target check - IP addresses not allowed. Must be a more or less well-formed hostname.
997 return ('FAIL', "SRV records cannot point directly to an IP address")
998 if ${$args{val}} =~ /^(?:[\d.]+|[0-9a-fA-F:]+)$/;
999 } else {
1000 # hm. we can't do anything sane with IP values here; part of the record data is in
1001 # fact encoded in the "hostname". enforce .arpa names? OTOH, SRV records in a reverse
1002 # zone are pretty silly.
1003
1004##enhance: Rejig so that we can pass back a WARN red flag, instead of
1005# hard-failing, since it seems that purely from the DNS record perspective,
1006# SRV records without underscores are syntactically valid
1007 # Not strictly true, but SRV records not following this convention won't be found.
1008 return ('FAIL',"SRV records must begin with _service._protocol [${$args{host}}]")
1009 unless ${$args{val}} =~ /^_[A-Za-z]+\._[A-Za-z]+\.[a-zA-Z0-9-]+/;
1010
1011 # SRV target check - IP addresses not allowed. Must be a more or less well-formed hostname.
1012 return ('FAIL', "SRV records cannot point directly to an IP address")
1013 if ${$args{host}} =~ /^(?:[\d.]+|[0-9a-fA-F:]+)$/;
1014
1015 # SRV records in reverse zones get stricter treatment. The UI bars adding them in
1016 # reverse record sets, but we "need" to allow editing existing ones. And we'll allow
1017 # editing them if some loon manually munges one into a default reverse record set.
1018 if ($args{defrec} eq 'n') {
1019 # Get the revzone, so we can see if ${$args{val}} is in that zone
1020 my $revzone = new NetAddr::IP $self->revName($args{id}, 'y');
1021 return ('FAIL', $errstr) if !$self->_inrev($args{val}, $revzone);
1022 }
1023
1024##enhance or ##fixme
1025# convert well-formed .arpa names to IP addresses to match old "strict" validation design
1026 return ('FAIL', $errstr) if ! _check_hostname_form(${$args{val}}, ${$args{rectype}}, $args{defrec}, $args{revrec}) &&
1027 ${$args{val}} =~ /\.arpa$/;
1028
1029##enhance: Look up the passed value to see if it exists. Ooo, fancy.
1030 return ('FAIL', $errstr) if ! _check_hostname_form(${$args{host}}, ${$args{rectype}}, $args{defrec}, $args{revrec});
1031
1032 }
1033
1034 return ('OK','OK');
1035} # done SRV record
1036
1037# Now the custom types
1038
1039# A+PTR record. With a very little bit of magic we can also use this sub to validate AAAA+PTR. Whee!
1040sub _validate_65280 {
1041 my $self = shift;
1042 my $dbh = $self->{dbh};
1043
1044 my %args = @_;
1045
1046 my $code = 'OK';
1047 my $msg = 'OK';
1048
1049 if ($args{defrec} eq 'n') {
1050 # live record; revrec determines whether we validate the PTR or A component first.
1051
1052 # Fail early on non-IP gibberish in ${$args{val}}. Arguably .arpa names might be acceptable
1053 # but that gets stupid in forward zones, since these records are shared.
1054 return ('FAIL', "$typemap{${$args{rectype}}} record must be a valid IPv4 address")
1055 if ${$args{rectype}} == 65280 && ${$args{val}} !~ m{^\d+\.\d+\.\d+\.\d+(?:/\d+)?$};
1056 return ('FAIL', "$typemap{${$args{rectype}}} record must be a valid IPv6 address")
1057 if ${$args{rectype}} == 65281 && ${$args{val}} !~ m{^[a-fA-F0-9:]+(?:/\d+)?$};
1058 # If things are not OK, this should prevent Stupid in the error log.
1059 $args{addr} = new NetAddr::IP ${$args{val}}
1060 or return ('FAIL', "$typemap{${$args{rectype}}} record must be a valid IPv".
1061 (${$args{rectype}} == 65280 ? '4' : '6')." address");
1062 ${$args{val}} = $args{addr}->addr;
1063
1064 if ($args{revrec} eq 'y') {
1065 ($code,$msg) = $self->_validate_12(%args);
1066 return ($code,$msg) if $code eq 'FAIL';
1067
1068 # check A+PTR is really v4
1069 return ('FAIL',"$typemap{${$args{rectype}}} record must be a valid IPv4 address")
1070 if ${$args{rectype}} == 65280 && $args{addr}->{isv6};
1071 # check AAAA+PTR is really v6
1072 return ('FAIL',"$typemap{${$args{rectype}}} record must be a valid IPv6 address")
1073 if ${$args{rectype}} == 65281 && !$args{addr}->{isv6};
1074
1075 # Check if the reqested domain exists. If not, coerce the type down to PTR and warn.
1076 if (!(${$args{domid}} = $self->_hostparent(${$args{host}}))) {
1077 my $addmsg = "Record ".($args{update} ? 'updated' : 'added').
1078 " as PTR instead of $typemap{${$args{rectype}}}; domain not found for ${$args{host}}";
1079 $msg .= "\n$addmsg" if $code eq 'WARN';
1080 $msg = $addmsg if $code eq 'OK';
1081 ${$args{rectype}} = $reverse_typemap{PTR};
1082 return ('WARN', $msg);
1083 }
1084
1085 # Add domain ID to field list and values
1086 ${$args{fields}} .= "domain_id,";
1087 push @{$args{vallist}}, ${$args{domid}};
1088
1089 } else {
1090 ($code,$msg) = $self->_validate_1(%args) if ${$args{rectype}} == 65280;
1091 ($code,$msg) = $self->_validate_28(%args) if ${$args{rectype}} == 65281;
1092 return ($code,$msg) if $code eq 'FAIL';
1093
1094 # Check if the requested reverse zone exists - note, an IP fragment won't
1095 # work here since we don't *know* which parent to put it in.
1096 # ${$args{val}} has been validated as a valid IP by now, in one of the above calls.
1097 my ($revid) = $dbh->selectrow_array("SELECT rdns_id FROM revzones WHERE revnet >> ?".
1098 " ORDER BY masklen(revnet) DESC", undef, (${$args{val}}));
1099 if (!$revid) {
1100 $msg = "Record ".($args{update} ? 'updated' : 'added')." as ".(${$args{rectype}} == 65280 ? 'A' : 'AAAA').
1101 " instead of $typemap{${$args{rectype}}}; reverse zone not found for ${$args{val}}";
1102 ${$args{rectype}} = (${$args{rectype}} == 65280 ? $reverse_typemap{A} : $reverse_typemap{AAAA});
1103 return ('WARN', $msg);
1104 }
1105
1106 # Check for duplicate PTRs. Note we don't have to play games with $code and $msg, because
1107 # by definition there can't be duplicate PTRs if the reverse zone isn't managed here.
1108 if ($args{update}) {
1109 # Record update. There should usually be an existing PTR (the record being updated)
1110 my @ptrs = @{ $dbh->selectcol_arrayref("SELECT record_id FROM "._rectable($args{defrec},$args{revrec}).
1111 " WHERE val = ?", undef, (${$args{val}})) };
1112 if (@ptrs && (!grep /^$args{update}$/, @ptrs)) {
1113 $msg = "PTR record for ${$args{val}} already exists; adding another will probably not do what you want";
1114 $code = 'WARN';
1115 }
1116 } else {
1117 # New record. Always warn if a PTR exists
1118 my ($ptrcount) = $dbh->selectrow_array("SELECT count(*) FROM "._rectable($args{defrec},$args{revrec}).
1119 " WHERE val = ?", undef, (${$args{val}}));
1120 $msg = "PTR record for ${$args{val}} already exists; adding another will probably not do what you want"
1121 if $ptrcount;
1122 $code = 'WARN' if $ptrcount;
1123 }
1124
1125 # Add the reverse zone ID to the fieldlist
1126 ${$args{fields}} .= "rdns_id,";
1127 push @{$args{vallist}}, $revid;
1128
1129 # Coerce the hostname back to the domain; this is so it displays and manipulates
1130 # sanely in the reverse zone.
1131 if (${$args{host}} eq '@') {
1132 ${$args{host}} = $self->domainName($args{id}); # errors? What errors?
1133 }
1134 } # revrec ne 'y'
1135
1136 } else { # defrec eq 'y'
1137
1138 if ($args{revrec} eq 'y') {
1139 ($code,$msg) = $self->_validate_12(%args);
1140 return ($code,$msg) if $code eq 'FAIL';
1141 if (${$args{rectype}} == 65280) {
1142 return ('FAIL',"A+PTR record must be a valid IPv4 address or fragment")
1143 if ${$args{val}} =~ /:/;
1144 ${$args{val}} =~ s/^ZONE,/ZONE./; # Clean up after uncertain IP-fragment-type from _validate_12
1145 } elsif (${$args{rectype}} == 65281) {
1146 return ('FAIL',"AAAA+PTR record must be a valid IPv6 address or fragment")
1147 if ${$args{val}} =~ /\./;
1148 ${$args{val}} =~ s/^ZONE,/ZONE::/; # Clean up after uncertain IP-fragment-type from _validate_12
1149 }
1150 } else {
1151 # This is easy. I also can't see a real use-case for A/AAAA+PTR in *all* forward
1152 # domains, since you wouldn't be able to substitute both domain and reverse zone
1153 # sanely, and you'd end up with guaranteed over-replicated PTR records that would
1154 # confuse the hell out of pretty much anything that uses them.
1155##fixme: make this a config flag?
1156 return ('FAIL', "$typemap{${$args{rectype}}} records not allowed in default domains");
1157 }
1158 }
1159
1160 return ($code, $msg);
1161} # done A+PTR record
1162
1163# AAAA+PTR record
1164# A+PTR above has been magicked to handle AAAA+PTR as well.
1165sub _validate_65281 {
1166 return _validate_65280(@_);
1167} # done AAAA+PTR record
1168
1169# PTR template record
1170sub _validate_65282 {
1171 my $self = shift;
1172 my $dbh = $self->{dbh};
1173
1174 my %args = @_;
1175
1176 # we're *this* >.< close to being able to just call _validate_12... unfortunately we can't, quite.
1177 if ($args{revrec} eq 'y') {
1178 if ($args{defrec} eq 'n') {
1179 return ('FAIL', "Template block ${$args{val}} is not within ".$self->revName($args{id}))
1180 unless $self->_ipparent($args{defrec}, $args{revrec}, $args{val}, $args{id}, \$args{addr});
1181##fixme: warn if $args{val} is not /31 or larger block?
1182 ${$args{val}} = "$args{addr}";
1183 } else {
1184 if (${$args{val}} =~ /\./) {
1185 # looks like a v4 or fragment
1186 if (${$args{val}} =~ m|^\d+\.\d+\.\d+\.\d+(?:/\d+)?$|) {
1187 # woo! a complete IP! validate it and normalize, or fail.
1188 $args{addr} = NetAddr::IP->new(${$args{val}})
1189 or return ('FAIL', "IP/value looks like IPv4 but isn't valid");
1190 ${$args{val}} = "$args{addr}";
1191 } else {
1192 ${$args{val}} =~ s/^\.*/ZONE./ unless ${$args{val}} =~ /^ZONE/;
1193 }
1194 } elsif (${$args{val}} =~ /[a-f:]/) {
1195 # looks like a v6 or fragment
1196 ${$args{val}} =~ s/^:*/ZONE::/ if !$args{addr} && ${$args{val}} !~ /^ZONE/;
1197 if ($args{addr}) {
1198 if ($args{addr}->addr =~ /^0/) {
1199 ${$args{val}} =~ s/^:*/ZONE::/ unless ${$args{val}} =~ /^ZONE/;
1200 } else {
1201 ${$args{val}} = "$args{addr}";
1202 }
1203 }
1204 } else {
1205 # bare number (probably). These could be v4 or v6, so we'll
1206 # expand on these on creation of a reverse zone.
1207 ${$args{val}} = "ZONE,${$args{val}}" unless ${$args{val}} =~ /^ZONE/;
1208 }
1209 }
1210##fixme: validate %-patterns?
1211
1212# Unlike single PTR records, there is absolutely no way to sanely support multiple
1213# PTR templates for the same block, since they expect to expand to all the individual
1214# IPs on export. Nested templates should be supported though.
1215
1216 my @checkvals = (${$args{val}});
1217 if (${$args{val}} =~ /,/) {
1218 # push . and :: variants into checkvals if val has ,
1219 my $tmp;
1220 ($tmp = ${$args{val}}) =~ s/,/./;
1221 push @checkvals, $tmp;
1222 ($tmp = ${$args{val}}) =~ s/,/::/;
1223 push @checkvals, $tmp;
1224 }
1225##fixme: this feels wrong still - need to restrict template pseudorecords to One Of Each
1226# Per Netblock such that they don't conflict on export
1227 my $typeck;
1228# type 65282 -> ptr template -> look for any of 65282, 65283, 65284
1229 $typeck = 'type=65283 OR type=65284' if ${$args{rectype}} == 65282;
1230# type 65283 -> a+ptr template -> v4 -> look for 65282 or 65283
1231 $typeck = 'type=65283' if ${$args{rectype}} == 65282;
1232# type 65284 -> aaaa+ptr template -> v6 -> look for 65282 or 65284
1233 $typeck = 'type=65284' if ${$args{rectype}} == 65282;
1234 my $pcsth = $dbh->prepare("SELECT count(*) FROM "._rectable($args{defrec},$args{revrec})." WHERE val = ? ".
1235 "AND (type=65282 OR $typeck)");
1236 foreach my $checkme (@checkvals) {
1237 $pcsth->execute($checkme);
1238 my ($rc) = $pcsth->fetchrow_array;
1239 return ('FAIL', "Only one template pseudorecord may exist for a given IP block") if $rc > 1;
1240 }
1241
1242 } else {
1243 return ('FAIL', "Forward zones cannot contain PTR records");
1244 }
1245
1246 return ('OK','OK');
1247} # done PTR template record
1248
1249# A+PTR template record
1250sub _validate_65283 {
1251 my $self = shift;
1252 my $dbh = $self->{dbh};
1253
1254 my %args = @_;
1255
1256 my ($code,$msg) = ('OK','OK');
1257
1258##fixme: need to fiddle things since A+PTR templates are acceptable in live
1259# forward zones but not default records
1260 if ($args{defrec} eq 'n') {
1261 if ($args{revrec} eq 'n') {
1262
1263 # Coerce all hostnames to end in ".DOMAIN" for group/default records,
1264 # or the intended parent domain for live records.
1265 my $pname = $self->domainName($args{id});
1266 ${$args{host}} =~ s/\.*$/\.$pname/ if ${$args{host}} !~ /$pname$/i;
1267
1268 # check for form; note this checks both normal and "other" hostnames.
1269 return ('FAIL', $errstr)
1270 if !_check_hostname_form(${$args{host}}, ${$args{rectype}}, $args{defrec}, $args{revrec});
1271
1272 # Check if the requested reverse zone exists - note, an IP fragment won't
1273 # work here since we don't *know* which parent to put it in.
1274 # ${$args{val}} has been validated as a valid IP by now, in one of the above calls.
1275 my ($revid) = $dbh->selectrow_array("SELECT rdns_id FROM revzones WHERE revnet >> ?".
1276 " ORDER BY masklen(revnet) DESC", undef, (${$args{val}}));
1277 # Fail if no match; we can't coerce a PTR-template type down to not include the PTR bit currently.
1278 if (!$revid) {
1279 $msg = "Can't ".($args{update} ? 'update' : 'add')." ${$args{host}}/${$args{val}} as ".
1280 "$typemap{${$args{rectype}}}: reverse zone not found for ${$args{val}}";
1281##fixme: add A template, AAAA template types?
1282# ${$args{rectype}} = (${$args{rectype}} == 65280 ? $reverse_typemap{A} : $reverse_typemap{AAAA});
1283 return ('FAIL', $msg);
1284 }
1285
1286 # Add reverse zone ID to field list and values
1287 ${$args{fields}} .= "rdns_id,";
1288 push @{$args{vallist}}, $revid;
1289
1290 } else {
1291 return ('FAIL', "IP or IP fragment ${$args{val}} is not within ".$self->revName($args{id}))
1292 unless $self->_ipparent($args{defrec}, $args{revrec}, $args{val}, $args{id}, \$args{addr});
1293 ${$args{val}} = "$args{addr}";
1294
1295 if (!(${$args{domid}} = $self->_hostparent(${$args{host}}))) {
1296 my $addmsg = "Record ".($args{update} ? 'updated' : 'added').
1297 " as PTR template instead of $typemap{${$args{rectype}}}; domain not found for ${$args{host}}";
1298 $msg .= "\n$addmsg" if $code eq 'WARN';
1299 $msg = $addmsg if $code eq 'OK';
1300 ${$args{rectype}} = 65282;
1301 return ('WARN', $msg);
1302 }
1303
1304 # Add domain ID to field list and values
1305 ${$args{fields}} .= "domain_id,";
1306 push @{$args{vallist}}, ${$args{domid}};
1307 }
1308
1309 } else {
1310 my ($code,$msg) = $self->_validate_65282(%args);
1311 return ($code, $msg) if $code eq 'FAIL';
1312 # get domain, check against ${$args{name}}
1313 }
1314
1315 return ('OK','OK');
1316} # done A+PTR template record
1317
1318# AAAA+PTR template record
1319# Not sure this can be handled sanely due to the size of IPv6 address space
1320# _validate_65283 above should handle v6 template records fine. It's on export we've got trouble.
1321sub _validate_65284 {
1322 my $self = shift;
1323 my %args = @_;
1324
1325 # do a quick check on the form of the hostname part; this is effectively a
1326 # "*.0.0.f.ip6.arpa" hostname, not an actual expandable IP template pattern
1327 # like with 65283.
1328 return ('FAIL', $errstr)
1329 if !_check_hostname_form(${$args{host}}, ${$args{rectype}}, $args{defrec}, $args{revrec});
1330 return $self->_validate_65283(%args);
1331} # done AAAA+PTR template record
1332
1333# Delegation record
1334# This is essentially a specialized clone of the NS record, primarily useful
1335# for delegating IPv4 sub-/24 reverse blocks
1336sub _validate_65285 {
1337 my $self = shift;
1338 my $dbh = $self->{dbh};
1339
1340 my %args = @_;
1341
1342# Almost, but not quite, identical to NS record validation.
1343
1344 # Check that the target of the record is within the parent.
1345 # Yes, host<->val are mixed up here; can't see a way to avoid it. :(
1346 if ($args{defrec} eq 'n') {
1347 # Check if IP/address/zone/"subzone" is within the parent
1348 if ($args{revrec} eq 'y') {
1349 my $tmpip = NetAddr::IP->new(${$args{val}});
1350 my $pname = $self->revName($args{id});
1351 return ('FAIL',"${$args{val}} not within $pname")
1352 unless $self->_ipparent($args{defrec}, $args{revrec}, $args{val}, $args{id}, \$tmpip);
1353 # Normalize
1354 ${$args{val}} = "$tmpip";
1355 } else {
1356 my $pname = $self->domainName($args{id});
1357 ${$args{host}} =~ s/\.*$/\.$pname/ if ${$args{host}} !~ /$pname$/i;
1358 }
1359 } else {
1360 return ('FAIL',"Delegation records are not permitted in default record sets");
1361 }
1362 return ('OK','OK');
1363}
1364
1365# Subs not specific to a particular record type
1366
1367# Convert $$host and/or $$val to lowercase as appropriate.
1368# Should only be called if $self->{lowercase} is true.
1369# $rectype is also a reference for caller convenience
1370sub _caseclean {
1371 my ($rectype, $host, $val, $defrec, $revrec) = @_;
1372
1373 # Can't case-squash default records, due to DOMAIN, ZONE, and ADMINDOMAIN templating
1374 return if $defrec eq 'y';
1375
1376 if ($typemap{$$rectype} eq 'TXT' || $typemap{$$rectype} eq 'SPF') {
1377 # TXT records should preserve user entry in the string.
1378 # SPF records are a duplicate of TXT with a new record type value (99)
1379 $$host = lc($$host) if $revrec eq 'n'; # only lowercase $$host on live forward TXT; preserve TXT content
1380 $$val = lc($$val) if $revrec eq 'y'; # only lowercase $$val on live reverse TXT; preserve TXT content
1381 } else {
1382 # Non-TXT, live records, are fully case-insensitive
1383 $$host = lc($$host);
1384 $$val = lc($$val);
1385 } # $typemap{$$rectype} else
1386
1387} # _caseclean()
1388
1389
1390##
1391## Record data substitution subs
1392##
1393
1394# Replace ZONE in hostname, or create (most of) the actual proper zone name
1395sub _ZONE {
1396 my $zone = shift;
1397 my $string = shift;
1398 my $fr = shift || 'f'; # flag for forward/reverse order? nb: ignored for IP
1399 my $sep = shift || '-'; # Separator character - unlikely we'll ever need more than . or -
1400
1401 my $prefix;
1402
1403 $string =~ s/,/./ if !$zone->{isv6};
1404 $string =~ s/,/::/ if $zone->{isv6};
1405
1406 # Subbing ZONE in the host. We need to properly ID the netblock range
1407 # The subbed text should have "network IP with trailing zeros stripped" for
1408 # blocks lined up on octet (for v4) or hex-quad (for v6) boundaries
1409 # For blocks that do NOT line up on these boundaries, we take the most
1410 # significant octet or 16-bit chunk of the "broadcast" IP and append it
1411 # after a double-dash
1412 # ie:
1413 # 8.0.0.0/6 -> 8.0.0.0 -> 11.255.255.255; sub should be 8--11
1414 # 10.0.0.0/12 -> 10.0.0.0 -> 10.0.0.0 -> 10.15.255.255; sub should be 10-0--15
1415 # 192.168.4.0/22 -> 192.168.4.0 -> 192.168.7.255; sub should be 192-168-4--7
1416 # 192.168.0.8/29 -> 192.168.0.8 -> 192.168.0.15; sub should be 192-168-0-8--15
1417 # Similar for v6
1418
1419 if (!$zone->{isv6}) { # IPv4
1420
1421 $prefix = $zone->network->addr; # Just In Case someone managed to slip in
1422 # a funky subnet that had host bits set.
1423 my $bc = $zone->broadcast->addr;
1424
1425 if ($zone->masklen > 24) {
1426 $bc =~ s/^\d+\.\d+\.\d+\.//;
1427 } elsif ($zone->masklen > 16) {
1428 $prefix =~ s/\.0$//;
1429 $bc =~ s/^\d+\.\d+\.//;
1430 } elsif ($zone->masklen > 8) {
1431 $bc =~ s/^\d+\.//;
1432 $prefix =~ s/\.0\.0$//;
1433 } else {
1434 $prefix =~ s/\.0\.0\.0$//;
1435 }
1436 if ($zone->masklen % 8) {
1437 $bc =~ s/(\.255)+$//;
1438 $prefix .= "--$bc"; #"--".zone->masklen; # use range or mask length?
1439 }
1440 if ($fr eq 'f') {
1441 $prefix =~ s/\.+/$sep/g;
1442 } else {
1443 $prefix = join($sep, reverse(split(/\./, $prefix)));
1444 }
1445
1446 } else { # IPv6
1447
1448 if ($fr eq 'f') {
1449
1450 $prefix = $zone->network->addr; # Just In Case someone managed to slip in
1451 # a funky subnet that had host bits set.
1452 my $bc = $zone->broadcast->addr;
1453 if (($zone->masklen % 16) != 0) {
1454 # Strip trailing :0 off $prefix, and :ffff off the broadcast IP
1455 for (my $i=0; $i<(7-int($zone->masklen / 16)); $i++) {
1456 $prefix =~ s/:0$//;
1457 $bc =~ s/:ffff$//;
1458 }
1459 # Strip the leading 16-bit chunks off the front of the broadcast IP
1460 $bc =~ s/^([a-f0-9]+:)+//;
1461 # Append the remaining 16-bit chunk to the prefix after "--"
1462 $prefix .= "--$bc";
1463 } else {
1464 # Strip off :0 from the end until we reach the netblock length.
1465 for (my $i=0; $i<(8-$zone->masklen / 16); $i++) {
1466 $prefix =~ s/:0$//;
1467 }
1468 }
1469 # Actually deal with the separator
1470 $prefix =~ s/:/$sep/g;
1471
1472 } else { # $fr eq 'f'
1473
1474 $prefix = $zone->network->full; # Just In Case someone managed to slip in
1475 # a funky subnet that had host bits set.
1476 my $bc = $zone->broadcast->full;
1477 $prefix =~ s/://g; # clean these out since they're not spaced right for this case
1478 $bc =~ s/://g;
1479 # Strip trailing 0 off $prefix, and f off the broadcast IP, to match the mask length
1480 for (my $i=0; $i<(31-int($zone->masklen / 4)); $i++) {
1481 $prefix =~ s/0$//;
1482 $bc =~ s/f$//;
1483 }
1484 # Split and reverse the order of the nibbles in the network/broadcast IPs
1485 # trim another 0 for nibble-aligned blocks first, but only if we really have a block, not an IP
1486 $prefix =~ s/0$// if $zone->masklen % 4 == 0 && $zone->masklen != 128;
1487 my @nbits = reverse split //, $prefix;
1488 my @bbits = reverse split //, $bc;
1489 # Handle the sub-nibble case. Eww. I feel dirty supporting this...
1490 $nbits[0] = "$nbits[0]-$bbits[0]" if ($zone->masklen % 4) != 0;
1491 # Glue it back together
1492 $prefix = join($sep, @nbits);
1493
1494 } # $fr ne 'f'
1495
1496 } # $zone->{isv6}
1497
1498 # Do the substitution, finally
1499 $string =~ s/ZONE/$prefix/;
1500 $string =~ s/--/-/ if $sep ne '-'; # - as separator needs extra help for sub-octet v4 netblocks
1501 return $string;
1502} # done _ZONE()
1503
1504# Not quite a substitution sub, but placed here as it's basically the inverse of above;
1505# given the .arpa zone name, return the CIDR netblock the zone is for.
1506# Supports v4 non-octet/non-classful netblocks as per the method outlined in the Grasshopper Book (2nd Ed p217-218)
1507# Does NOT support non-quad v6 netblocks via the same scheme; it shouldn't ever be necessary.
1508# Takes a nominal .arpa zone name, returns a success code and NetAddr::IP, or a fail code and message
1509sub _zone2cidr {
1510 my $zone = shift;
1511
1512 my $cidr;
1513 my $tmpcidr;
1514 my $warnmsg = '';
1515
1516 if ($zone =~ /\.in-addr\.arpa\.?$/) {
1517 # v4 revzone, formal zone name type
1518 my $tmpzone = $zone;
1519 return ('FAIL', "Non-numerics in apparent IPv4 reverse zone name [$tmpzone]")
1520 if $tmpzone !~ m{^(?:\d+[/-])?[\d\.]+\.in-addr\.arpa\.?$};
1521 $tmpzone =~ s/\.in-addr\.arpa\.?//;
1522
1523 # Snag the octet pieces
1524 my @octs = split /\./, $tmpzone;
1525
1526 # Map result of a range manipulation to a mask length change. Cheaper than finding the 2-root of $octets[0]+1.
1527 # Note we will not support /31 blocks, mostly due to issues telling "24-31" -> .24/29 apart from
1528 # "24-31" -> .24/31", with a litte bit of "/31 is icky".
1529 my %maskmap = ( 3 => 2, 7 => 3, 15 => 4, 31 => 5, 63 => 6, 127 => 7,
1530 30 => 2, 29 => 3, 28 => 4, 27 => 5, 26 => 6, 25 => 7
1531 );
1532
1533 # Handle "range" blocks, eg, 80-83.168.192.in-addr.arpa (192.168.80.0/22)
1534 # Need to take the size of the range to offset the basic octet-based mask length,
1535 # and make sure the first number in the range gets used as the network address for the block
1536 # Alternate form: The second number is actually the real netmask, not the end of the range.
1537 my $masklen = 0;
1538 if ($octs[0] =~ m{^((\d+)[/-](\d+))$}) { # take the range...
1539 if (24 < $3 && $3 < 31) {
1540 # we have a real netmask
1541 $masklen = -$maskmap{$3};
1542 } else {
1543 # we have a range. NB: only real CIDR ranges are supported
1544 $masklen -= $maskmap{-(eval $1)}; # find the mask base...
1545 }
1546 $octs[0] = $2; # set the base octet of the range...
1547 }
1548 @octs = reverse @octs; # We can reverse the octet pieces now that we've extracted and munged any ranges
1549
1550# arguably we should only allow sub-octet range/mask in-addr.arpa
1551# specifications in the least significant octet, but the code is
1552# simpler if we deal with sub-octet delegations at any level.
1553
1554 # Now we find the "true" mask with the aid of the "base" calculated above
1555 if ($#octs == 0) {
1556 $masklen += 8;
1557 $tmpcidr = "$octs[0].0.0.0/$masklen"; # really hope we don't see one of these very often.
1558 } elsif ($#octs == 1) {
1559 $masklen += 16;
1560 $tmpcidr = "$octs[0].$octs[1].0.0/$masklen";
1561 } elsif ($#octs == 2) {
1562 $masklen += 24;
1563 $tmpcidr = "$octs[0].$octs[1].$octs[2].0/$masklen";
1564 } else {
1565 $masklen += 32;
1566 $tmpcidr = "$octs[0].$octs[1].$octs[2].$octs[3]/$masklen";
1567 }
1568
1569 } elsif ($zone =~ /\.ip6\.arpa\.?$/) {
1570 # v6 revzone, formal zone name type
1571 my $tmpzone = $zone;
1572##fixme: if-n-when we decide we can support sub-nibble v6 zone names, we'll need to change this segment
1573 return ('FAIL', "Non-hexadecimals in apparent IPv6 reverse zone name [$tmpzone]")
1574 if $tmpzone !~ /^[a-fA-F\d\.]+\.ip6\.arpa\.?$/;
1575 $tmpzone =~ s/\.ip6\.arpa\.?//;
1576 my @quads = reverse(split(/\./, $tmpzone));
1577 $warnmsg .= "Apparent sub-/64 IPv6 reverse zone\n" if $#quads > 15;
1578 my $nc;
1579 foreach (@quads) {
1580 $tmpcidr .= $_;
1581 $tmpcidr .= ":" if ++$nc % 4 == 0 && $nc < $#quads;
1582 }
1583 my $nq = 1 if $nc % 4 != 0;
1584 my $mask = $nc * 4; # need to do this here because we probably increment it below
1585 while ($nc++ % 4 != 0) {
1586 $tmpcidr .= "0";
1587 }
1588 # polish it off with trailing ::/mask if this is a CIDR block instead of an IP
1589 $tmpcidr .= "::/$mask" if $mask != 128;
1590 }
1591
1592 # Just to be sure, use NetAddr::IP to validate. Saves a lot of nasty regex watching for valid octet values.
1593 return ('FAIL', "Invalid zone $zone (apparent netblock $tmpcidr)")
1594 unless $cidr = NetAddr::IP->new($tmpcidr);
1595
1596 if ($warnmsg) {
1597 $errstr = $warnmsg;
1598 return ('WARN', $cidr);
1599 }
1600 return ('OK', $cidr);
1601##fixme: use wantarray() to decide what to return?
1602} # done _zone2cidr()
1603
1604# Record template %-parameter expansion, IPv4. Note that IPv6 doesn't
1605# really have a sane way to handle this type of expansion at the moment
1606# due to the size of the address space.
1607# Takes a reference to a template string to be expanded, an IP to use in the replacement,
1608# an optional netblock for the %ngb (net, gw, bcast) expansion, and an optional index
1609# number for %c "n'th usable IP in block/range" patterns.
1610# Alters the template string referred.
1611sub _template4_expand {
1612 # ugh pthui
1613 my $self;
1614 $self = shift if ref($_[0]) eq 'DNSDB';
1615
1616 my $tmpl = shift;
1617 my $ip = shift;
1618 my $subnet = shift; # for %ngb and %c
1619 my $ipindex = shift; # for %c
1620
1621 # blank $tmpl on config template_skip_0 or template_skip_255, unless we have a %ngb
1622 if ($$tmpl !~ /\%-?n-?g-?b\%/) {
1623 if ( ($ip =~ /\.0$/ && $self->{template_skip_0}) ||
1624 ($ip =~ /\.255$/ && $self->{template_skip_255}) ) {
1625 $$tmpl = '';
1626 return;
1627 }
1628 }
1629
1630 my @ipparts = split /\./, $ip;
1631 my @iphex;
1632 my @ippad;
1633 for (@ipparts) {
1634 push @iphex, sprintf("%x", $_);
1635 push @ippad, sprintf("%0.3u", $_);
1636 }
1637
1638 # Two or three consecutive separator characters (_ or -) should be rare - users that use them
1639 # anywhere other than punycoded internationalized domains get to keep the pieces when it breaks.
1640 # We clean up the ones that we may inadvertently generate after replacing %c and %ngb%
1641 my ($thrsep) = ($$tmpl =~ /[_-]{3}/);
1642 my ($twosep) = ($$tmpl =~ /[_-]{2}/);
1643
1644 # Take the simplest path to pattern substitution; replace only exactly the %c or %ngb%
1645 # patterns as-is. Then check after to see if we've caused doubled separator characters (- or _)
1646 # and eliminate them, but only if the original template didn't have them already. Also
1647 # unconditionally drop separator characters immediately before a dot; these do not always
1648 # strictly make the label invalid but almost always, and any exceptions should never show up
1649 # in a template record that expands to "many" real records anyway.
1650
1651 # %ngb and %c require a netblock
1652 if ($subnet) {
1653 # extract the fragments
1654 my ($ngb,$n,$g,$b) = ($$tmpl =~ /(\%(-?n)(-?g)(-?b)\%)/);
1655 my ($c) = ($$tmpl =~ /(\%-?c)/); my $nld = ''; my $cld = '';
1656 $c = '' if !$c;
1657 my ($cn) = ($$tmpl =~ /(\%x)/);
1658 my $skipgw = ($c =~ /\%-c/ ? 0 : 1);
1659 my $ipkill = 0;
1660
1661 if ($cn) {
1662 # "natural n'th IP in the block" pattern
1663 $$tmpl =~ s/$cn/$ipindex+1/e;
1664 }
1665
1666##fixme: still have one edge case not handled well:
1667# %c%n-gb%
1668# do we drop the record as per -g, or publish the record with an index of 1 as per %c?
1669# arguably this is a "that's a STUPID question!" case
1670
1671 if ($c) {
1672 # "n'th usable IP in the block" pattern. We need the caller to provide an index
1673 # number otherwise we see exponential time growth because we have to iterate over
1674 # the whole block to map the IP back to an index. :/
1675 # NetAddr::IP does not have a method for asking "what index is IP <foo> at?"
1676
1677 # no index, or index == 0, (AKA network address), or IP == broadcast, blank the index fragment
1678 if (!$ipindex || ($$subnet->broadcast->addr eq $ip)) {
1679 $$tmpl =~ s/$c//;
1680 } else {
1681 # if we have %c, AKA "skip the gateway", and we're on the nominal gateway IP, blank the index fragment
1682 if ($skipgw && $$subnet->first->addr eq $ip) {
1683 $$tmpl =~ s/$c//;
1684 }
1685 # else replace the index fragment with the passed index minus $skipgw, so that we can start the
1686 # resulting index at 1 on net+2
1687 else {
1688 $$tmpl =~ s/$c/($ipindex-$skipgw)/e;
1689 }
1690 }
1691 } # if ($c)
1692
1693 if ($ngb) {
1694 # individually check the network, standard gateway (net+1) IP, and broadcast IP
1695 # blank $$tmpl if n, g, or b was prefixed with - (this allows "hiding" net/gw/bcast entries)
1696
1697 if ($$subnet->network->addr eq $ip) {
1698 if ($n eq '-n') {
1699 $$tmpl = '';
1700 } else {
1701 $$tmpl =~ s/$ngb/net/;
1702 $ipkill = 1;
1703 }
1704 } elsif ($$subnet->first->addr eq $ip) {
1705 if ($g eq '-g') {
1706 $$tmpl = '';
1707 } else {
1708 $$tmpl =~ s/$ngb/gw/;
1709 $ipkill = 1;
1710 }
1711 } elsif ($$subnet->broadcast->addr eq $ip) {
1712 if ($b eq '-b') {
1713 $$tmpl = '';
1714 } else {
1715 $$tmpl =~ s/$ngb/bcast/;
1716 $ipkill = 1;
1717 }
1718 } else {
1719 $$tmpl =~ s/$ngb//;
1720 }
1721 }
1722
1723 # We don't (usually) want to expand the IP-related patterns on the -net, -gw, or -bcast IPs.
1724 # Arguably this is another place for another config knob, or possibly further extension of
1725 # the template pattern to control it on a per-subnet basis.
1726 if ($ipkill) {
1727 # kill common IP patterns
1728 $$tmpl =~ s/\%[_.-]?[irdh]//;
1729 # kill IP octet patterns
1730 $$tmpl =~ s/\%[1234][dh0](?:[_.-]\%[1234][dh0]){0,3}//;
1731 }
1732
1733 # and now clean up to make sure we leave a valid DNS label... mostly. Should arguably
1734 # split on /\./ and process each label separately.
1735 $$tmpl =~ s/([_-]){3}/$1/ if !$thrsep;
1736 $$tmpl =~ s/([_-]){2}/$1/ if !$twosep;
1737 $$tmpl =~ s/[_-]\././;
1738
1739 } # if ($subnet)
1740
1741 # IP substitutions in template records:
1742 #major patterns:
1743 #dashed IP, forward and reverse
1744 #underscoreed IP, forward and reverse
1745 #dotted IP, forward and reverse (even if forward is... dumb)
1746 # -> %r for reverse, %i for forward, leading -, _, or . to indicate separator, defaults to -
1747 # %r or %-r => %4d-%3d-%2d-%1d
1748 # %_r => %4d_%3d_%2d_%1d
1749 # %.r => %4d.%3d.%2d.%1d
1750 # %i or %-i => %1d-%2d-%3d-%4d
1751 # %_i => %1d_%2d_%3d_%4d
1752 # %.i => %1d.%2d.%3d.%4d
1753 $$tmpl =~ s/\%r/\%4d-\%3d-\%2d-\%1d/g;
1754 $$tmpl =~ s/\%([-._])r/\%4d$1\%3d$1\%2d$1\%1d/g;
1755 $$tmpl =~ s/\%i/\%1d-\%2d-\%3d-\%4d/g;
1756 $$tmpl =~ s/\%([-._])i/\%1d$1\%2d$1\%3d$1\%4d/g;
1757
1758 #hex-coded IP
1759 # %h
1760 $$tmpl =~ s/\%h/$iphex[0]$iphex[1]$iphex[2]$iphex[3]/g;
1761
1762 #IP as decimal-coded 32-bit value
1763 # %d
1764 my $iptmp = $ipparts[0]*256*256*256 + $ipparts[1]*256*256 + $ipparts[2]*256 + $ipparts[3];
1765 $$tmpl =~ s/\%d/$iptmp/g;
1766
1767 #minor patterns (per-octet)
1768 # %[1234][dh0]
1769 #octet
1770 #hex-coded octet
1771 #0-padded octet
1772 $$tmpl =~ s/\%([1234])d/$ipparts[$1-1]/g;
1773 $$tmpl =~ s/\%([1234])h/$iphex[$1-1]/g;
1774 $$tmpl =~ s/\%([1234])0/$ippad[$1-1]/g;
1775
1776} # _template4_expand()
1777
1778# Broad syntactic check on the hostname. Checks for valid characters, correctly-expandable template patterns.
1779# Takes the hostname, type, and live/default and forward/reverse flags
1780# Returns true/false, sets errstr on failures
1781sub _check_hostname_form {
1782 my ($hname,$rectype,$defrec,$revrec) = @_;
1783
1784 if ($hname =~ /\%/ && ($rectype == 65282 || $rectype == 65283) ) {
1785 my $tmphost = $hname;
1786 # we don't actually need to test with the real IP passed; that saves a bit of fiddling.
1787 DNSDB::_template4_expand(\$tmphost, '10.10.10.10');
1788 if ($tmphost =~ /\%/ || lc($tmphost) !~ /^(?:\*\.)?(?:[0-9a-z_.-]+)$/) {
1789 $errstr = "Invalid template $hname";
1790 return;
1791 }
1792 } elsif ($rectype == $reverse_typemap{CNAME} && $revrec eq 'y') {
1793 # Allow / in reverse CNAME hostnames for sub-/24 delegation
1794 if (lc($hname) !~ m|^[0-9a-z_./-]+$|) {
1795 # error message is deliberately restrictive; special cases are SPECIAL and not for general use
1796 $errstr = "Hostnames may not contain anything other than (0-9 a-z . _)";
1797 return;
1798 }
1799 } elsif ($revrec eq 'y') {
1800 # Reverse zones don't support @ in hostnames
1801 if (lc($hname) !~ /^(?:\*\.)?[0-9a-z_.-]+$/) {
1802 # error message is deliberately restrictive; special cases are SPECIAL and not for general use
1803 $errstr = "Hostnames may not contain anything other than (0-9 a-z . _)";
1804 return;
1805 }
1806 } else {
1807 if (lc($hname) !~ /^(?:\*\.)?(?:[0-9a-z_.-]+|@)$/) {
1808 # Don't mention @, because it would be far too wordy to explain the nuance of @
1809 $errstr = "Hostnames may not contain anything other than (0-9 a-z . _)";
1810 return;
1811 }
1812 }
1813 return 1;
1814} # _check_hostname_form()
1815
1816
1817##
1818## Initialization and cleanup subs
1819##
1820
1821## DNSDB::__cfgload()
1822# Private sub to parse a config file and load it into %config
1823# Takes a filename and a hashref to put the parsed entries in
1824sub __cfgload {
1825 $errstr = '';
1826 my $cfgfile = shift;
1827 my $cfg = shift;
1828
1829 if (open CFG, "<$cfgfile") {
1830 while (<CFG>) {
1831 chomp;
1832 s/^\s*//;
1833 next if /^#/;
1834 next if /^$/;
1835# hmm. more complex bits in this file might require [heading] headers, maybe?
1836# $mode = $1 if /^\[(a-z)+]/;
1837 # DB connect info
1838 $cfg->{dbname} = $1 if /^dbname\s*=\s*([a-z0-9_.-]+)/i;
1839 $cfg->{dbuser} = $1 if /^dbuser\s*=\s*([a-z0-9_.-]+)/i;
1840 $cfg->{dbpass} = $1 if /^dbpass\s*=\s*([a-z0-9_.-]+)/i;
1841 $cfg->{dbhost} = $1 if /^dbhost\s*=\s*([a-z0-9_.-]+)/i;
1842 # Mail settings
1843 $cfg->{mailhost} = $1 if /^mailhost\s*=\s*([a-z0-9_.-]+)/i;
1844 $cfg->{mailnotify} = $1 if /^mailnotify\s*=\s*([a-z0-9_.\@-]+)/i;
1845 $cfg->{mailsender} = $1 if /^mailsender\s*=\s*([a-z0-9_.\@-]+)/i;
1846 $cfg->{mailname} = $1 if /^mailname\s*=\s*([a-z0-9\s_.-]+)/i;
1847 $cfg->{orgname} = $1 if /^orgname\s*=\s*([a-z0-9\s_.,'-]+)/i;
1848 $cfg->{domain} = $1 if /^domain\s*=\s*([a-z0-9_.-]+)/i;
1849 # session - note this is fed directly to CGI::Session
1850 $cfg->{timeout} = $1 if /^[tT][iI][mM][eE][oO][uU][tT]\s*=\s*(\d+[smhdwMy]?)/;
1851 $cfg->{sessiondir} = $1 if m{^sessiondir\s*=\s*([a-z0-9/_.-]+)}i;
1852 # misc
1853 $cfg->{log_failures} = $1 if /^log_failures\s*=\s*([a-z01]+)/i;
1854 $cfg->{perpage} = $1 if /^perpage\s*=\s*(\d+)/i;
1855 $cfg->{exportcache} = $1 if m{^exportcache\s*=\s*([a-z0-9/_.-]+)}i;
1856 $cfg->{usecache} = $1 if m{^usecache\s*=\s*([a-z01]+)}i;
1857 $cfg->{force_refresh} = $1 if /^force_refresh\s*=\s*([a-z01]+)/i;
1858 $cfg->{lowercase} = $1 if /^lowercase\s*=\s*([a-z01]+)/i;
1859 $cfg->{showrev_arpa} = $1 if /^showrev_arpa\s*=\s*([a-z]+)/i;
1860 $cfg->{template_skip_0} = $1 if /^template_skip_0\s*=\s*([a-z01]+)/i;
1861 $cfg->{template_skip_255} = $1 if /^template_skip_255\s*=\s*([a-z01]+)/i;
1862 $cfg->{autotxt} = $1 if /^autotxt\s*=\s*([a-z01]+)/i;
1863# not supported in dns.cgi yet
1864# $cfg->{templatedir} = $1 if m{^templatedir\s*=\s*([a-z0-9/_.-]+)}i;
1865# $cfg->{templateoverride} = $1 if m{^templateoverride\s*=\s*([a-z0-9/_.-]+)}i;
1866 # RPC options
1867 $cfg->{rpcmode} = $1 if /^rpc_mode\s*=\s*(socket|HTTP|XMLRPC)\s*$/i;
1868 $cfg->{maxfcgi} = $1 if /^max_fcgi_requests\s*=\s*(\d+)\s*$/i;
1869 if (my ($tmp) = /^rpc_iplist\s*=\s*(.+)/i) {
1870 my @ips = split /[,\s]+/, $tmp;
1871 my $rpcsys = shift @ips;
1872 push @{$cfg->{rpcacl}{$rpcsys}}, @ips;
1873 }
1874 }
1875 close CFG;
1876 } else {
1877 $errstr = "Couldn't load configuration file $cfgfile: $!";
1878 return;
1879 }
1880 return 1;
1881} # end __cfgload()
1882
1883
1884## DNSDB::connectDB()
1885# Creates connection to DNS database.
1886# Requires the database name, username, and password.
1887# Returns a handle to the db or undef on failure.
1888# Set up for a PostgreSQL db; could be any transactional DBMS with the
1889# right changes.
1890# Called by new(); not intended to be called publicly.
1891sub connectDB {
1892 $errstr = '';
1893 my $dbname = shift;
1894 my $user = shift;
1895 my $pass = shift;
1896 my $dbh;
1897 my $DSN = "DBI:Pg:dbname=$dbname";
1898
1899 my $host = shift;
1900 $DSN .= ";host=$host" if $host;
1901
1902# Note that we want to autocommit by default, and we will turn it off locally as necessary.
1903# We may not want to print gobbledygook errors; YMMV. Have to ponder that further.
1904 $dbh = DBI->connect($DSN, $user, $pass, {
1905 AutoCommit => 1,
1906 PrintError => 0
1907 });
1908 if (!$dbh) {
1909 $errstr = $DBI::errstr;
1910 return;
1911 }
1912#) if(!$dbh);
1913
1914 local $dbh->{RaiseError} = 1;
1915
1916 eval {
1917##fixme: initialize the DB if we can't find the table (since, by definition, there's
1918# nothing there if we can't select from it...)
1919 my $tblsth = $dbh->prepare("SELECT count(*) FROM pg_catalog.pg_class WHERE relkind='r' AND relname=?");
1920 my ($tblcount) = $dbh->selectrow_array($tblsth, undef, ('misc'));
1921# return (undef,$DBI::errstr) if $dbh->err;
1922
1923#if ($tblcount == 0) {
1924# # create tables one at a time, checking for each.
1925# return (undef, "check table misc missing");
1926#}
1927
1928# Return here if we can't select.
1929# This should retrieve the dbversion key.
1930 my $sth = $dbh->prepare("SELECT key,value FROM misc WHERE misc_id=1");
1931 $sth->execute();
1932# return (undef,$DBI::errstr) if ($sth->err);
1933
1934##fixme: do stuff to the DB on version mismatch
1935# x.y series should upgrade on $DNSDB::VERSION > misc(key=>version)
1936# DB should be downward-compatible; column defaults should give sane (if possibly
1937# useless-and-needs-help) values in columns an older software stack doesn't know about.
1938
1939# See if the select returned anything (or null data). This should
1940# succeed if the select executed, but...
1941 $sth->fetchrow();
1942# return (undef,$DBI::errstr) if ($sth->err);
1943
1944 $sth->finish;
1945
1946 }; # wrapped DB checks
1947 if ($@) {
1948 $errstr = $@;
1949 return;
1950 }
1951
1952# If we get here, we should be OK.
1953 return $dbh;
1954} # end connectDB
1955
1956
1957## DNSDB::finish()
1958# Cleans up after database handles and so on.
1959# Requires a database handle
1960sub finish {
1961 my $self = shift;
1962 $self->{dbh}->disconnect;
1963} # end finish
1964
1965
1966## DNSDB::initGlobals()
1967# Initialize global variables
1968# NB: this does NOT include web-specific session variables!
1969sub initGlobals {
1970 my $self = shift;
1971 my $dbh = $self->{dbh};
1972
1973# load record types from database
1974 my $sth = $dbh->prepare("SELECT val,name,stdflag FROM rectypes");
1975 $sth->execute;
1976 while (my ($recval,$recname,$stdflag) = $sth->fetchrow_array()) {
1977 $typemap{$recval} = $recname;
1978 $reverse_typemap{$recname} = $recval;
1979 # now we fill the record validation function hash
1980 if ($stdflag < 5) {
1981 my $fn = "_validate_$recval";
1982 $validators{$recval} = \&$fn;
1983 } else {
1984 my $fn = "sub { return ('FAIL','Type $recval ($recname) not supported'); }";
1985 $validators{$recval} = eval $fn;
1986 }
1987 }
1988} # end initGlobals
1989
1990
1991## DNSDB::initRPC()
1992# Takes a remote username and remote fullname.
1993# Sets up the RPC logging-pseudouser if needed.
1994# Sets the %userdata hash for logging.
1995# Returns undef on failure
1996sub initRPC {
1997 my $self = shift;
1998 my $dbh = $self->{dbh};
1999 my %args = @_;
2000
2001 return if !$args{username};
2002 return if !$args{fullname};
2003
2004 $args{username} = "$args{username}/$args{rpcsys}";
2005
2006 my $tmpuser = $dbh->selectrow_hashref("SELECT username,user_id AS userid,group_id,firstname,lastname,status".
2007 " FROM users WHERE username=?", undef, ($args{username}) );
2008 if (!$tmpuser) {
2009 $dbh->do("INSERT INTO users (username,password,firstname,type) VALUES (?,'RPC',?,'R')", undef,
2010 ($args{username}, $args{fullname}) );
2011 $tmpuser = $dbh->selectrow_hashref("SELECT username,user_id AS userid,group_id,firstname,lastname,status".
2012 " FROM users WHERE username=?", undef, ($args{username}) );
2013 }
2014 $tmpuser->{lastname} = '' if !$tmpuser->{lastname};
2015 $self->{loguserid} = $tmpuser->{userid};
2016 $self->{logusername} = $tmpuser->{username};
2017 $self->{logfullname} = "$tmpuser->{firstname} $tmpuser->{lastname} ($args{rpcsys})";
2018 return 1 if $tmpuser;
2019} # end initRPC()
2020
2021
2022## DNSDB::login()
2023# Takes a database handle, username and password
2024# Returns a userdata hash (UID, GID, username, fullname parts) if username exists,
2025# password matches the one on file, and account is not disabled
2026# Returns undef otherwise
2027sub login {
2028 my $self = shift;
2029 my $dbh = $self->{dbh};
2030 my $user = shift;
2031 my $pass = shift;
2032
2033 my $userinfo = $dbh->selectrow_hashref("SELECT user_id,group_id,password,firstname,lastname,status".
2034 " FROM users WHERE username=?",
2035 undef, ($user) );
2036 return if !$userinfo;
2037 return if !$userinfo->{status};
2038
2039 if ($userinfo->{password} =~ m|^\$1\$([A-Za-z0-9/.]+)\$|) {
2040 # native passwords (crypt-md5)
2041 return if $userinfo->{password} ne unix_md5_crypt($pass,$1);
2042 } elsif ($userinfo->{password} =~ /^[0-9a-f]{32}$/) {
2043 # VegaDNS import (hex-coded MD5)
2044 return if $userinfo->{password} ne md5_hex($pass);
2045 } else {
2046 # plaintext (convenient now and then)
2047 return if $userinfo->{password} ne $pass;
2048 }
2049
2050 return $userinfo;
2051} # end login()
2052
2053
2054## DNSDB::initActionLog()
2055# Set up action logging. Takes a database handle and user ID
2056# Sets some internal globals and Does The Right Thing to set up a logging channel.
2057# This sets up _log() to spew out log entries to the defined channel without worrying
2058# about having to open a file or a syslog channel
2059##fixme Need to call _initActionLog_blah() for various logging channels, configured
2060# via dnsdb.conf, in $self->{log_channel} or something
2061# See https://secure.deepnet.cx/trac/dnsadmin/ticket/21
2062sub initActionLog {
2063 my $self = shift;
2064 my $dbh = $self->{dbh};
2065 my $uid = shift;
2066
2067 return if !$uid;
2068
2069 # snag user info for logging. there's got to be a way to not have to pass this back
2070 # and forth from a caller, but web usage means no persistence we can rely on from
2071 # the server side.
2072 my ($username,$fullname) = $dbh->selectrow_array("SELECT username, firstname || ' ' || lastname".
2073 " FROM users WHERE user_id=?", undef, ($uid));
2074##fixme: errors are unpossible!
2075
2076 $self->{logusername} = $username;
2077 $self->{loguserid} = $uid;
2078 $self->{logfullname} = $fullname;
2079
2080 # convert to real check once we have other logging channels
2081 # if ($self->{log_channel} eq 'sql') {
2082 # Open Log, Sez Me!
2083 # }
2084
2085} # end initActionLog
2086
2087
2088## DNSDB::getPermissions()
2089# Get permissions from DB
2090# Requires DB handle, group or user flag, ID, and hashref.
2091sub getPermissions {
2092 my $self = shift;
2093 my $dbh = $self->{dbh};
2094
2095 my $type = shift;
2096 my $id = shift;
2097 my $hash = shift;
2098
2099 my $sql = qq(
2100 SELECT
2101 p.admin,p.self_edit,
2102 p.group_create,p.group_edit,p.group_delete,
2103 p.user_create,p.user_edit,p.user_delete,
2104 p.domain_create,p.domain_edit,p.domain_delete,
2105 p.record_create,p.record_edit,p.record_delete,p.record_locchg,
2106 p.location_create,p.location_edit,p.location_delete,p.location_view
2107 FROM permissions p
2108 );
2109 if ($type eq 'group') {
2110 $sql .= qq(
2111 JOIN groups g ON g.permission_id=p.permission_id
2112 WHERE g.group_id=?
2113 );
2114 } else {
2115 $sql .= qq(
2116 JOIN users u ON u.permission_id=p.permission_id
2117 WHERE u.user_id=?
2118 );
2119 }
2120
2121 my $sth = $dbh->prepare($sql);
2122
2123##fixme? we don't trap other plain SELECT errors
2124 $sth->execute($id);
2125
2126# my $permref = $sth->fetchrow_hashref;
2127# return $permref;
2128# $hash = $permref;
2129# Eww. Need to learn how to forcibly drop a hashref onto an existing hash.
2130 ($hash->{admin},$hash->{self_edit},
2131 $hash->{group_create},$hash->{group_edit},$hash->{group_delete},
2132 $hash->{user_create},$hash->{user_edit},$hash->{user_delete},
2133 $hash->{domain_create},$hash->{domain_edit},$hash->{domain_delete},
2134 $hash->{record_create},$hash->{record_edit},$hash->{record_delete},$hash->{record_locchg},
2135 $hash->{location_create},$hash->{location_edit},$hash->{location_delete},$hash->{location_view}
2136 ) = $sth->fetchrow_array;
2137
2138} # end getPermissions()
2139
2140
2141## DNSDB::changePermissions()
2142# Update an ACL entry
2143# Takes a db handle, type, owner-id, and hashref for the changed permissions.
2144sub changePermissions {
2145 my $self = shift;
2146 my $dbh = $self->{dbh};
2147 my $type = shift;
2148 my $id = shift;
2149 my $newperms = shift;
2150 my $inherit = shift || 0;
2151
2152 my $resultmsg = '';
2153
2154 # see if we're switching from inherited to custom. for bonus points,
2155 # snag the permid and parent permid anyway, since we'll need the permid
2156 # to set/alter custom perms, and both if we're switching from custom to
2157 # inherited.
2158 my $sth = $dbh->prepare("SELECT (u.permission_id=g.permission_id) AS was_inherited,u.permission_id,g.permission_id,".
2159 ($type eq 'user' ? 'u.group_id,u.username' : 'u.parent_group_id,u.group_name').
2160 " FROM ".($type eq 'user' ? 'users' : 'groups')." u ".
2161 " JOIN groups g ON u.".($type eq 'user' ? '' : 'parent_')."group_id=g.group_id ".
2162 " WHERE u.".($type eq 'user' ? 'user' : 'group')."_id=?");
2163 $sth->execute($id);
2164
2165 my ($wasinherited,$permid,$parpermid,$parid,$name) = $sth->fetchrow_array;
2166
2167# hack phtoui
2168# group id 1 is "special" in that it's it's own parent (err... possibly.)
2169# may make its parent id 0 which doesn't exist, and as a bonus is Perl-false.
2170 $wasinherited = 0 if ($type eq 'group' && $id == 1);
2171
2172 local $dbh->{AutoCommit} = 0;
2173 local $dbh->{RaiseError} = 1;
2174
2175 # Wrap all the SQL in a transaction
2176 eval {
2177 if ($inherit) {
2178
2179 $dbh->do("UPDATE ".($type eq 'user' ? 'users' : 'groups')." SET inherit_perm='t',permission_id=? ".
2180 "WHERE ".($type eq 'user' ? 'user' : 'group')."_id=?", undef, ($parpermid, $id) );
2181 $dbh->do("DELETE FROM permissions WHERE permission_id=?", undef, ($permid) );
2182
2183 } else {
2184
2185 if ($wasinherited) { # munge new permission entry in if we're switching from inherited perms
2186##fixme: need to add semirecursive bit to properly munge inherited permission ID on subgroups and users
2187# ... if'n'when we have groups with fully inherited permissions.
2188 # SQL is coo
2189 $dbh->do("INSERT INTO permissions ($permlist,".($type eq 'user' ? 'user' : 'group')."_id) ".
2190 "SELECT $permlist,? FROM permissions WHERE permission_id=?", undef, ($id,$permid) );
2191 ($permid) = $dbh->selectrow_array("SELECT permission_id FROM permissions ".
2192 "WHERE ".($type eq 'user' ? 'user' : 'group')."_id=?", undef, ($id) );
2193 $dbh->do("UPDATE ".($type eq 'user' ? 'users' : 'groups')." SET inherit_perm='f',permission_id=? ".
2194 "WHERE ".($type eq 'user' ? 'user' : 'group')."_id=?", undef, ($permid, $id) );
2195 }
2196
2197 # and now set the permissions we were passed
2198 foreach (@permtypes) {
2199 if (defined ($newperms->{$_})) {
2200 $dbh->do("UPDATE permissions SET $_=? WHERE permission_id=?", undef, ($newperms->{$_},$permid) );
2201 }
2202 }
2203
2204 } # (inherited->)? custom
2205
2206 if ($type eq 'user') {
2207 $resultmsg = "Updated permissions for user $name";
2208 } else {
2209 $resultmsg = "Updated default permissions for group $name";
2210 }
2211 $self->_log(group_id => ($type eq 'user' ? $parid : $id), entry => $resultmsg);
2212 $dbh->commit;
2213 }; # end eval
2214 if ($@) {
2215 my $msg = $@;
2216 eval { $dbh->rollback; };
2217 return ('FAIL',"Error changing permissions: $msg");
2218 }
2219
2220 return ('OK',$resultmsg);
2221} # end changePermissions()
2222
2223
2224## DNSDB::comparePermissions()
2225# Compare two permission hashes
2226# Returns '>', '<', '=', '!'
2227sub comparePermissions {
2228 my $self = shift;
2229 my $p1 = shift;
2230 my $p2 = shift;
2231
2232 my $retval = '='; # assume equality until proven otherwise
2233
2234 no warnings "uninitialized";
2235
2236 foreach (@permtypes) {
2237 next if $p1->{$_} == $p2->{$_}; # equal is good
2238 if ($p1->{$_} && !$p2->{$_}) {
2239 if ($retval eq '<') { # if we've already found an unequal pair where
2240 $retval = '!'; # $p2 has more access, and we now find a pair
2241 last; # where $p1 has more access, the overall access
2242 } # is neither greater or lesser, it's unequal.
2243 $retval = '>';
2244 }
2245 if (!$p1->{$_} && $p2->{$_}) {
2246 if ($retval eq '>') { # if we've already found an unequal pair where
2247 $retval = '!'; # $p1 has more access, and we now find a pair
2248 last; # where $p2 has more access, the overall access
2249 } # is neither greater or lesser, it's unequal.
2250 $retval = '<';
2251 }
2252 }
2253 return $retval;
2254} # end comparePermissions()
2255
2256
2257## DNSDB::changeGroup()
2258# Change group ID of an entity
2259# Takes a database handle, entity type, entity ID, and new group ID
2260sub changeGroup {
2261 my $self = shift;
2262 my $dbh = $self->{dbh};
2263 my $type = shift;
2264 my $id = shift;
2265 my $newgrp = shift;
2266
2267##fixme: fail on not enough args
2268 #return ('FAIL', "Missing
2269
2270 return ('FAIL', "Can't change the group of a $type")
2271 unless grep /^$type$/, ('domain','revzone','user','group'); # could be extended for defrecs?
2272
2273 # Collect some names for logging and messages
2274 my $entname;
2275 if ($type eq 'domain') {
2276 $entname = $self->domainName($id);
2277 } elsif ($type eq 'revzone') {
2278 $entname = $self->revName($id);
2279 } elsif ($type eq 'user') {
2280 $entname = $self->userFullName($id, '%u');
2281 } elsif ($type eq 'group') {
2282 $entname = $self->groupName($id);
2283 }
2284
2285 my ($oldgid) = $dbh->selectrow_array("SELECT group_id FROM $par_tbl{$type} WHERE $id_col{$type}=?",
2286 undef, ($id));
2287 my $oldgname = $self->groupName($oldgid);
2288 my $newgname = $self->groupName($newgrp);
2289
2290 return ('FAIL', "Can't move things into a group that doesn't exist") if !$newgname;
2291
2292 return ('WARN', "Nothing to do, new group is the same as the old group") if $oldgid == $newgrp;
2293
2294 # Allow transactions, and raise an exception on errors so we can catch it later.
2295 # Use local to make sure these get "reset" properly on exiting this block
2296 local $dbh->{AutoCommit} = 0;
2297 local $dbh->{RaiseError} = 1;
2298
2299 eval {
2300 $dbh->do("UPDATE $par_tbl{$type} SET group_id=? WHERE $id_col{$type}=?", undef, ($newgrp, $id));
2301 # Log the change in both the old and new groups
2302 $self->_log(group_id => $oldgid, entry => "Moved $type $entname from $oldgname to $newgname");
2303 $self->_log(group_id => $newgrp, entry => "Moved $type $entname from $oldgname to $newgname");
2304 $dbh->commit;
2305 };
2306 if ($@) {
2307 my $msg = $@;
2308 eval { $dbh->rollback; };
2309 if ($self->{log_failures}) {
2310 $self->_log(group_id => $oldgid, entry => "Error moving $type $entname to $newgname: $msg");
2311 $dbh->commit; # since we enabled transactions earlier
2312 }
2313 return ('FAIL',"Error moving $type $entname to $newgname: $msg");
2314 }
2315
2316 return ('OK',"Moved $type $entname from $oldgname to $newgname");
2317} # end changeGroup()
2318
2319
2320##
2321## Processing subs
2322##
2323
2324## DNSDB::addDomain()
2325# Add a domain
2326# Takes a database handle, domain name, numeric group, boolean(ish) state (active/inactive),
2327# and a default location indicator
2328# Returns a status code and message
2329sub addDomain {
2330 $errstr = '';
2331 my $self = shift;
2332 my $dbh = $self->{dbh};
2333 my $domain = shift;
2334 return ('FAIL',"Domain must not be blank\n") if !$domain;
2335 my $group = shift;
2336 return ('FAIL',"Group must be specified\n") if !defined($group);
2337 my $state = shift;
2338 return ('FAIL',"Domain status must be specified\n") if !defined($state);
2339 my $defloc = shift || '';
2340
2341 $state = 1 if $state =~ /^active$/;
2342 $state = 1 if $state =~ /^on$/;
2343 $state = 0 if $state =~ /^inactive$/;
2344 $state = 0 if $state =~ /^off$/;
2345
2346 return ('FAIL',"Invalid domain status") if $state !~ /^\d+$/;
2347
2348 $domain = lc($domain) if $self->{lowercase};
2349
2350 return ('FAIL', "Invalid characters in domain") if $domain !~ /^[a-zA-Z0-9_.-]+$/;
2351
2352 my $sth = $dbh->prepare("SELECT domain_id FROM domains WHERE lower(domain) = lower(?) AND default_location = ?");
2353 my $dom_id;
2354
2355# quick check to start to see if we've already got one
2356 $sth->execute($domain, $defloc);
2357 ($dom_id) = $sth->fetchrow_array;
2358
2359 return ('FAIL', "Domain already exists") if $dom_id;
2360
2361 # Allow transactions, and raise an exception on errors so we can catch it later.
2362 # Use local to make sure these get "reset" properly on exiting this block
2363 local $dbh->{AutoCommit} = 0;
2364 local $dbh->{RaiseError} = 1;
2365
2366 # Wrap all the SQL in a transaction
2367 eval {
2368 # insert the domain...
2369 $dbh->do("INSERT INTO domains (domain,group_id,status,default_location) VALUES (?,?,?,?)", undef,
2370 ($domain, $group, $state, $defloc));
2371
2372 # get the ID...
2373 ($dom_id) = $dbh->selectrow_array("SELECT domain_id FROM domains WHERE lower(domain) = lower(?) AND default_location = ?",
2374 undef, ($domain, $defloc));
2375
2376 $self->_log(domain_id => $dom_id, group_id => $group,
2377 entry => "Added ".($state ? 'active' : 'inactive')." domain $domain");
2378
2379 # ... and now we construct the standard records from the default set. NB: group should be variable.
2380 my $sth = $dbh->prepare("SELECT host,type,val,distance,weight,port,ttl FROM default_records WHERE group_id=?");
2381 my $sth_in = $dbh->prepare("INSERT INTO records (domain_id,host,type,val,distance,weight,port,ttl,location)".
2382 " VALUES ($dom_id,?,?,?,?,?,?,?,?)");
2383 $sth->execute($group);
2384 while (my ($host, $type, $val, $dist, $weight, $port, $ttl) = $sth->fetchrow_array()) {
2385 $host =~ s/DOMAIN/$domain/g;
2386 $val =~ s/DOMAIN/$domain/g;
2387 _caseclean(\$type, \$host, \$val, 'n', 'n') if $self->{lowercase};
2388 $sth_in->execute($host, $type, $val, $dist, $weight, $port, $ttl, $defloc);
2389 if ($typemap{$type} eq 'SOA') {
2390 my @tmp1 = split /:/, $host;
2391 my @tmp2 = split /:/, $val;
2392 $self->_log(domain_id => $dom_id, group_id => $group,
2393 entry => "[new $domain] Added SOA record [contact $tmp1[0]] [master $tmp1[1]] ".
2394 "[refresh $tmp2[0]] [retry $tmp2[1]] [expire $tmp2[2]] [minttl $tmp2[3]], TTL $ttl");
2395 } else {
2396 my $logentry = "[new $domain] Added record '$host $typemap{$type}";
2397 $logentry .= " [distance $dist]" if $typemap{$type} eq 'MX';
2398 $logentry .= " [priority $dist] [weight $weight] [port $port]" if $typemap{$type} eq 'SRV';
2399 $self->_log(domain_id => $dom_id, group_id => $group,
2400 entry => $logentry." $val', TTL $ttl");
2401 }
2402 }
2403
2404 # once we get here, we should have suceeded.
2405 $dbh->commit;
2406 }; # end eval
2407
2408 if ($@) {
2409 my $msg = $@;
2410 eval { $dbh->rollback; };
2411 $self->_log(group_id => $group, entry => "Failed adding domain $domain ($msg)")
2412 if $self->{log_failures};
2413 $dbh->commit; # since we enabled transactions earlier
2414 return ('FAIL',$msg);
2415 } else {
2416 return ('OK',$dom_id);
2417 }
2418} # end addDomain
2419
2420
2421## DNSDB::delZone()
2422# Delete a forward or reverse zone.
2423# Takes a database handle, zone ID, and forward/reverse flag.
2424# for now, just delete the records, then the domain.
2425# later we may want to archive it in some way instead (status code 2, for example?)
2426sub delZone {
2427 my $self = shift;
2428 my $dbh = $self->{dbh};
2429 my $zoneid = shift;
2430 my $revrec = shift;
2431
2432 # Allow transactions, and raise an exception on errors so we can catch it later.
2433 # Use local to make sure these get "reset" properly on exiting this block
2434 local $dbh->{AutoCommit} = 0;
2435 local $dbh->{RaiseError} = 1;
2436
2437 return ('FAIL', 'Need a zone identifier to look up') if !$zoneid;
2438
2439 my $msg = '';
2440 my $failmsg = '';
2441 my $zone = ($revrec eq 'n' ? $self->domainName($zoneid) : $self->revName($zoneid));
2442
2443 return ('FAIL', ($revrec eq 'n' ? 'Domain' : 'Reverse zone')." ID $zoneid doesn't exist") if !$zone;
2444
2445 # Set this up here since we may use if if $self->{log_failures} is enabled
2446 my %loghash;
2447 $loghash{domain_id} = $zoneid if $revrec eq 'n';
2448 $loghash{rdns_id} = $zoneid if $revrec eq 'y';
2449 $loghash{group_id} = $self->parentID(
2450 id => $zoneid, type => ($revrec eq 'n' ? 'domain' : 'revzone'), revrec => $revrec);
2451
2452 # Wrap all the SQL in a transaction
2453 eval {
2454 # Disentangle custom record types before removing the
2455 # ones that are only in the zone to be deleted
2456 if ($revrec eq 'n') {
2457 my $sth = $dbh->prepare("UPDATE records SET type=?,domain_id=0 WHERE domain_id=? AND type=?");
2458 $failmsg = "Failure converting multizone types to single-zone";
2459 $sth->execute($reverse_typemap{PTR}, $zoneid, 65280);
2460 $sth->execute($reverse_typemap{PTR}, $zoneid, 65281);
2461 $sth->execute(65282, $zoneid, 65283);
2462 $sth->execute(65282, $zoneid, 65284);
2463 $failmsg = "Failure removing domain records";
2464 $dbh->do("DELETE FROM records WHERE domain_id=?", undef, ($zoneid));
2465 $failmsg = "Failure removing domain";
2466 $dbh->do("DELETE FROM domains WHERE domain_id=?", undef, ($zoneid));
2467 } else {
2468 my $sth = $dbh->prepare("UPDATE records SET type=?,rdns_id=0 WHERE rdns_id=? AND type=?");
2469 $failmsg = "Failure converting multizone types to single-zone";
2470 $sth->execute($reverse_typemap{A}, $zoneid, 65280);
2471 $sth->execute($reverse_typemap{AAAA}, $zoneid, 65281);
2472# We don't have an "A template" or "AAAA template" type, although it might be useful for symmetry.
2473# $sth->execute(65286?, $zoneid, 65283);
2474# $sth->execute(65286?, $zoneid, 65284);
2475 $failmsg = "Failure removing reverse records";
2476 $dbh->do("DELETE FROM records WHERE rdns_id=?", undef, ($zoneid));
2477 $failmsg = "Failure removing reverse zone";
2478 $dbh->do("DELETE FROM revzones WHERE rdns_id=?", undef, ($zoneid));
2479 }
2480
2481 $msg = "Deleted ".($revrec eq 'n' ? 'domain' : 'reverse zone')." $zone";
2482 $loghash{entry} = $msg;
2483 $self->_log(%loghash);
2484
2485 # once we get here, we should have suceeded.
2486 $dbh->commit;
2487 }; # end eval
2488
2489 if ($@) {
2490 $msg = $@;
2491 eval { $dbh->rollback; };
2492 $loghash{entry} = "Error deleting $zone: $msg ($failmsg)";
2493 if ($self->{log_failures}) {
2494 $self->_log(%loghash);
2495 $dbh->commit; # since we enabled transactions earlier
2496 }
2497 return ('FAIL', $loghash{entry});
2498 } else {
2499 return ('OK', $msg);
2500 }
2501
2502} # end delZone()
2503
2504
2505## DNSDB::domainName()
2506# Return the domain name based on a domain ID
2507# Takes a database handle and the domain ID
2508# Returns the domain name or undef on failure
2509sub domainName {
2510 $errstr = '';
2511 my $self = shift;
2512 my $dbh = $self->{dbh};
2513 my $domid = shift;
2514 my ($domname) = $dbh->selectrow_array("SELECT domain FROM domains WHERE domain_id=?", undef, ($domid) );
2515 $errstr = $DBI::errstr if !$domname;
2516 return $domname if $domname;
2517} # end domainName()
2518
2519
2520## DNSDB::revName()
2521# Return the reverse zone name based on an rDNS ID
2522# Takes a database handle and the rDNS ID, and an optional flag to force return of the CIDR zone
2523# instead of the formal .arpa zone name
2524# Returns the reverse zone name or undef on failure
2525sub revName {
2526 $errstr = '';
2527 my $self = shift;
2528 my $dbh = $self->{dbh};
2529 my $revid = shift;
2530 my $cidrflag = shift || 'n';
2531 my ($revname) = $dbh->selectrow_array("SELECT revnet FROM revzones WHERE rdns_id=?", undef, ($revid) );
2532 $errstr = $DBI::errstr if !$revname;
2533 my $tmp = new NetAddr::IP $revname;
2534 $revname = _ZONE($tmp, 'ZONE', 'r', '.').($tmp->{isv6} ? '.ip6.arpa' : '.in-addr.arpa')
2535 if ($self->{showrev_arpa} eq 'zone' || $self->{showrev_arpa} eq 'all') && $cidrflag eq 'n';
2536 return $revname if $revname;
2537} # end revName()
2538
2539
2540## DNSDB::domainID()
2541# Takes a database handle and domain name
2542# Returns the domain ID number
2543sub domainID {
2544 $errstr = '';
2545 my $self = shift;
2546 my $dbh = $self->{dbh};
2547 my $domain = shift;
2548 my $location = shift;
2549
2550 # Note that location may be *empty*, but it may not be *undefined*
2551 if (!defined($location)) {
2552 $errstr = "Missing location";
2553 return;
2554 }
2555
2556 my ($domid) = $dbh->selectrow_array(
2557 "SELECT domain_id FROM domains WHERE lower(domain) = lower(?) AND default_location = ?",
2558 undef, ($domain, $location) );
2559 if (!$domid) {
2560 if ($dbh->err) {
2561 $errstr = $DBI::errstr;
2562 } else {
2563 $errstr = "Domain $domain not present";
2564 }
2565 }
2566 return $domid if $domid;
2567} # end domainID()
2568
2569
2570## DNSDB::revID()
2571# Takes a database handle and reverse zone name
2572# Returns the rDNS ID number
2573sub revID {
2574 $errstr = '';
2575 my $self = shift;
2576 my $dbh = $self->{dbh};
2577 my $revzone = shift;
2578 my $location = shift;
2579
2580 # Note that location may be *empty*, but it may not be *undefined*
2581 if (!defined($location)) {
2582 $errstr = "Missing location";
2583 return;
2584 }
2585
2586 my ($revid) = $dbh->selectrow_array(
2587 "SELECT rdns_id FROM revzones WHERE revnet = ? AND default_location = ?",
2588 undef, ($revzone, $location) );
2589 if (!$revid) {
2590 if ($dbh->err) {
2591 $errstr = $DBI::errstr;
2592 } else {
2593 $errstr = "Reverse zone $revzone not present";
2594 }
2595 }
2596 return $revid if $revid;
2597} # end revID()
2598
2599
2600## DNSDB::addRDNS
2601# Adds a reverse DNS zone
2602# Takes a database handle, CIDR block, reverse DNS pattern, numeric group,
2603# and boolean(ish) state (active/inactive)
2604# Returns a status code and message
2605sub addRDNS {
2606 my $self = shift;
2607 my $dbh = $self->{dbh};
2608 my $zone = shift;
2609
2610 # Autodetect formal .arpa zones
2611 if ($zone =~ /\.arpa\.?$/) {
2612 my $code;
2613 ($code,$zone) = _zone2cidr($zone);
2614 return ('FAIL', $zone) if $code eq 'FAIL';
2615 }
2616 $zone = NetAddr::IP->new($zone);
2617
2618 return ('FAIL',"Zone name must be a valid CIDR netblock") unless ($zone && $zone->addr !~ /^0/);
2619 my $revpatt = shift; # construct a custom (A/AAAA+)? PTR template record
2620 my $group = shift;
2621 my $state = shift;
2622 my $defloc = shift || '';
2623
2624 $state = 1 if $state =~ /^active$/;
2625 $state = 1 if $state =~ /^on$/;
2626 $state = 0 if $state =~ /^inactive$/;
2627 $state = 0 if $state =~ /^off$/;
2628
2629 return ('FAIL',"Invalid zone status") if $state !~ /^\d+$/;
2630
2631# quick check to start to see if we've already got one
2632 my ($rdns_id) = $dbh->selectrow_array("SELECT rdns_id FROM revzones WHERE revnet = ? AND default_location = ?",
2633 undef, ("$zone", $defloc));
2634
2635 return ('FAIL', "Zone already exists") if $rdns_id;
2636
2637 # Allow transactions, and raise an exception on errors so we can catch it later.
2638 # Use local to make sure these get "reset" properly on exiting this block
2639 local $dbh->{AutoCommit} = 0;
2640 local $dbh->{RaiseError} = 1;
2641
2642 my $warnstr = '';
2643 my $defttl = 3600; # 1 hour should be reasonable. And unless things have gone horribly
2644 # wrong, we should have a value to override this anyway.
2645
2646 # Wrap all the SQL in a transaction
2647 eval {
2648 # insert the zone...
2649 $dbh->do("INSERT INTO revzones (revnet,group_id,status,default_location) VALUES (?,?,?,?)", undef,
2650 ($zone, $group, $state, $defloc) );
2651
2652 # get the ID...
2653 ($rdns_id) = $dbh->selectrow_array("SELECT currval('revzones_rdns_id_seq')");
2654
2655 $self->_log(rdns_id => $rdns_id, group_id => $group,
2656 entry => "Added ".($state ? 'active' : 'inactive')." reverse zone $zone");
2657
2658 # ... and now we construct the standard records from the default set. NB: group should be variable.
2659 my $sth = $dbh->prepare("SELECT host,type,val,ttl FROM default_rev_records WHERE group_id=?");
2660 my $sth_in = $dbh->prepare("INSERT INTO records (rdns_id,domain_id,host,type,val,ttl,location)".
2661 " VALUES ($rdns_id,?,?,?,?,?,?)");
2662 $sth->execute($group);
2663 while (my ($host,$type,$val,$ttl) = $sth->fetchrow_array()) {
2664 # Silently skip v4/v6 mismatches. This is not an error, this is expected.
2665 if ($zone->{isv6}) {
2666 next if ($type == 65280 || $type == 65283);
2667 } else {
2668 next if ($type == 65281 || $type == 65284);
2669 }
2670
2671 $host =~ s/ADMINDOMAIN/$self->{domain}/g;
2672
2673 # Check to make sure the IP stubs will fit in the zone. Under most usage failures here should be rare.
2674 # On failure, tack a note on to a warning string and continue without adding this record.
2675 # While we're at it, we substitute $zone for ZONE in the value.
2676 if ($val eq 'ZONE') {
2677 # If we've got a pattern, we skip the default record version on (A+)PTR-template types
2678 next if $revpatt && ($type == 65282 || $type == 65283);
2679##fixme? do we care if we have multiple whole-zone templates?
2680 $val = $zone->network;
2681 } elsif ($val =~ /ZONE/) {
2682 my $tmpval = $val;
2683 $tmpval =~ s/ZONE//;
2684 # Bend the rules and allow single-trailing-number PTR or PTR template records to be inserted
2685 # as either v4 or v6. May make this an off-by-default config flag
2686 # Note that the origin records that may trigger this **SHOULD** already have ZONE,\d
2687 if ($type == 12 || $type == 65282) {
2688 $tmpval =~ s/[,.]/::/ if ($tmpval =~ /^[,.]\d+$/ && $zone->{isv6});
2689 $tmpval =~ s/[,:]+/./ if ($tmpval =~ /^(?:,|::)\d+$/ && !$zone->{isv6});
2690 }
2691 my $addr;
2692 if ($self->_ipparent('n', 'y', \$tmpval, $rdns_id, \$addr)) {
2693 $val = $addr->addr;
2694 } else {
2695 $warnstr .= "\nDefault record '$val $typemap{$type} $host' doesn't fit in $zone, skipping";
2696 next;
2697 }
2698 }
2699
2700 # Substitute $zone for ZONE in the hostname, but only for non-NS records.
2701 # NS records get this substitution on the value instead.
2702 $host = _ZONE($zone, $host) if $type != 2;
2703
2704 # Fill in the forward domain ID if we can find it, otherwise:
2705 # Coerce type down to PTR or PTR template if we can't
2706 my $domid = 0;
2707 if ($type >= 65280) {
2708 if (!($domid = $self->_hostparent($host))) {
2709 $warnstr .= "\nRecord added as PTR instead of $typemap{$type}; domain not found for $host";
2710 $type = $reverse_typemap{PTR};
2711 $domid = 0; # just to be explicit.
2712 }
2713 }
2714
2715 _caseclean(\$type, \$host, \$val, 'n', 'y') if $self->{lowercase};
2716
2717 $sth_in->execute($domid,$host,$type,$val,$ttl,$defloc);
2718
2719 if ($typemap{$type} eq 'SOA') {
2720 my @tmp1 = split /:/, $host;
2721 my @tmp2 = split /:/, $val;
2722 $self->_log(rdns_id => $rdns_id, group_id => $group,
2723 entry => "[new $zone] Added SOA record [contact $tmp1[0]] [master $tmp1[1]] ".
2724 "[refresh $tmp2[0]] [retry $tmp2[1]] [expire $tmp2[2]] [minttl $tmp2[3]], TTL $ttl");
2725 $defttl = $tmp2[3];
2726 } else {
2727 my $logentry = "[new $zone] Added record '$host $typemap{$type} $val', TTL $ttl";
2728 $logentry .= ", default location ".$self->getLoc($defloc)->{description} if $defloc;
2729 $self->_log(rdns_id => $rdns_id, domain_id => $domid, group_id => $group, entry => $logentry);
2730 }
2731 }
2732
2733 # Generate record based on provided pattern.
2734 if ($revpatt) {
2735 my $host;
2736 my $type = ($zone->{isv6} ? 65284 : 65283);
2737 my $val = $zone->network;
2738
2739 # Substitute $zone for ZONE in the hostname.
2740 $host = _ZONE($zone, $revpatt);
2741
2742 my $domid = 0;
2743 if (!($domid = $self->_hostparent($host))) {
2744 $warnstr .= "\nDefault pattern added as PTR template instead of $typemap{$type}; domain not found for $host";
2745 $type = 65282;
2746 $domid = 0; # just to be explicit.
2747 }
2748
2749 $sth_in->execute($domid,$host,$type,$val,$defttl,$defloc);
2750 my $logentry = "[new $zone] Added record '$host $typemap{$type}";
2751 $self->_log(rdns_id => $rdns_id, domain_id => $domid, group_id => $group,
2752 entry => $logentry." $val', TTL $defttl from pattern");
2753 }
2754
2755 # If there are warnings (presumably about default records skipped for cause) log them
2756 $self->_log(rdns_id => $rdns_id, group_id => $group, entry => "Warning(s) adding $zone:$warnstr")
2757 if $warnstr;
2758
2759 # once we get here, we should have suceeded.
2760 $dbh->commit;
2761 }; # end eval
2762
2763 if ($@) {
2764 my $msg = $@;
2765 eval { $dbh->rollback; };
2766 $self->_log(group_id => $group, entry => "Failed adding reverse zone $zone ($msg)")
2767 if $self->{log_failures};
2768 $dbh->commit; # since we enabled transactions earlier
2769 return ('FAIL',$msg);
2770 } else {
2771 my $retcode = 'OK';
2772 if ($warnstr) {
2773 $resultstr = $warnstr;
2774 $retcode = 'WARN';
2775 }
2776 return ($retcode, $rdns_id);
2777 }
2778
2779} # end addRDNS()
2780
2781
2782## DNSDB::getZoneCount
2783# Get count of zones in group or groups
2784# Takes a database handle and hash containing:
2785# - the "current" group
2786# - an array of "acceptable" groups
2787# - a flag for forward/reverse zones
2788# - Optionally accept a "starts with" and/or "contains" filter argument
2789# Returns an integer count of the resulting zone list.
2790sub getZoneCount {
2791 my $self = shift;
2792 my $dbh = $self->{dbh};
2793
2794 my %args = @_;
2795
2796 # Fail on bad curgroup argument. There's no sane fallback on this one.
2797 if (!$args{curgroup} || $args{curgroup} !~ /^\d+$/) {
2798 $errstr = "Bad or missing curgroup argument";
2799 return;
2800 }
2801 # Fail on bad childlist argument. This could be sanely ignored if bad, maybe.
2802 if ($args{childlist} && $args{childlist} !~ /^[\d,]+$/) {
2803 $errstr = "Bad childlist argument";
2804 return;
2805 }
2806
2807 my @filterargs;
2808 $args{startwith} = undef if $args{startwith} && $args{startwith} !~ /^(?:[a-z]|0-9)$/;
2809 push @filterargs, "^$args{startwith}" if $args{startwith};
2810 $args{filter} =~ s/\./\[\.\]/g if $args{filter}; # only match literal dots, usually in reverse zones
2811 push @filterargs, $args{filter} if $args{filter};
2812
2813 my $sql;
2814 # Not as compact, and fix-me-twice if the common bits get wrong, but much easier to read
2815 if ($args{revrec} eq 'n') {
2816 $sql = "SELECT count(*) FROM domains".
2817 " WHERE group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
2818 ($args{startwith} ? " AND domain ~* ?" : '').
2819 ($args{filter} ? " AND domain ~* ?" : '');
2820 } else {
2821 $sql = "SELECT count(*) FROM revzones".
2822 " WHERE group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
2823 ($args{startwith} ? " AND CAST(revnet AS VARCHAR) ~* ?" : '');
2824# if ($self->{showrev_arpa} eq 'zone' || $self->{showrev_arpa} eq 'all') {
2825 # Just In Case the UI is using formal .arpa notation, and someone enters something reversed,
2826 # we want to match both the formal and natural zone name
2827 $sql .= ($args{filter} ? " AND (CAST(revnet AS VARCHAR) ~* ? OR CAST(revnet AS VARCHAR) ~* ?)" : '');
2828 push @filterargs, join('[.]',reverse(split(/\[\.\]/,$args{filter}))) if $args{filter};
2829# } else {
2830# $sql .= ($args{filter} ? " AND CAST(revnet AS VARCHAR) ~* ?" : '');
2831# }
2832 }
2833 my ($count) = $dbh->selectrow_array($sql, undef, @filterargs);
2834 return $count;
2835} # end getZoneCount()
2836
2837
2838## DNSDB::getZoneList()
2839# Get a list of zones in the specified group(s)
2840# Takes the same arguments as getZoneCount() above
2841# Returns a reference to an array of hashrefs suitable for feeding to HTML::Template
2842sub getZoneList {
2843 my $self = shift;
2844 my $dbh = $self->{dbh};
2845
2846 my %args = @_;
2847
2848 my @zonelist;
2849
2850 $args{sortorder} = 'ASC' if !$args{sortorder} || !grep /^$args{sortorder}$/, ('ASC','DESC');
2851 $args{offset} = 0 if !$args{offset} || $args{offset} !~ /^(?:all|\d+)$/;
2852
2853 # Fail on bad curgroup argument. There's no sane fallback on this one.
2854 if (!$args{curgroup} || $args{curgroup} !~ /^\d+$/) {
2855 $errstr = "Bad or missing curgroup argument";
2856 return;
2857 }
2858 # Fail on bad childlist argument. This could be sanely ignored if bad, maybe.
2859 if ($args{childlist} && $args{childlist} !~ /^[\d,]+$/) {
2860 $errstr = "Bad childlist argument";
2861 return;
2862 }
2863
2864 my @filterargs;
2865 $args{startwith} = undef if $args{startwith} && $args{startwith} !~ /^(?:[a-z]|0-9)$/;
2866 push @filterargs, "^$args{startwith}" if $args{startwith};
2867 $args{filter} =~ s/\./\[\.\]/g if $args{filter}; # only match literal dots, usually in reverse zones
2868 push @filterargs, $args{filter} if $args{filter};
2869
2870 my $sql;
2871 # Not as compact, and fix-me-twice if the common bits get wrong, but much easier to read
2872 if ($args{revrec} eq 'n') {
2873 $args{sortby} = 'domain' if !$args{sortby} || !grep /^$args{sortby}$/, ('domain','group','status');
2874 $sql = q(SELECT
2875 domain_id AS zoneid,
2876 domain AS zone,
2877 status,
2878 groups.group_name AS group,
2879 l.description AS location
2880 FROM domains
2881 LEFT JOIN locations l ON domains.default_location=l.location
2882 INNER JOIN groups ON domains.group_id=groups.group_id ).
2883 "WHERE domains.group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
2884 ($args{startwith} ? " AND domain ~* ?" : '').
2885 ($args{filter} ? " AND domain ~* ?" : '');
2886 } else {
2887##fixme: arguably startwith here is irrelevant. depends on the UI though.
2888 $args{sortby} = 'revnet' if !$args{sortby} || !grep /^$args{sortby}$/, ('revnet','group','status');
2889 $sql = q(SELECT
2890 rdns_id AS zoneid,
2891 revnet AS zone,
2892 status,
2893 groups.group_name AS group,
2894 l.description AS location
2895 FROM revzones
2896 LEFT JOIN locations l ON revzones.default_location=l.location
2897 INNER JOIN groups ON revzones.group_id=groups.group_id ).
2898 " WHERE revzones.group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
2899 ($args{startwith} ? " AND CAST(revnet AS VARCHAR) ~* ?" : '');
2900# if ($self->{showrev_arpa} eq 'zone' || $self->{showrev_arpa} eq 'all') {
2901 # Just In Case the UI is using formal .arpa notation, and someone enters something reversed,
2902 # we want to match both the formal and natural zone name
2903 $sql .= ($args{filter} ? " AND (CAST(revnet AS VARCHAR) ~* ? OR CAST(revnet AS VARCHAR) ~* ?)" : '');
2904 push @filterargs, join('[.]',reverse(split(/\[\.\]/,$args{filter}))) if $args{filter};
2905# } else {
2906# $sql .= ($args{filter} ? " AND CAST(revnet AS VARCHAR) ~* ?" : '');
2907# }
2908 }
2909 # A common tail.
2910 $sql .= " ORDER BY ".($args{sortby} eq 'group' ? 'groups.group_name' : $args{sortby})." $args{sortorder} ".
2911 ($args{offset} eq 'all' ? '' : " LIMIT $self->{perpage}".
2912 " OFFSET ".$args{offset}*$self->{perpage});
2913
2914 my @working;
2915 my $zsth = $dbh->prepare($sql);
2916 $zsth->execute(@filterargs);
2917 while (my $zone = $zsth->fetchrow_hashref) {
2918 if ($args{revrec} eq 'y' && ($self->{showrev_arpa} eq 'zone' || $self->{showrev_arpa} eq 'all')) {
2919 my $tmp = new NetAddr::IP $zone->{zone};
2920 $zone->{zone} = DNSDB::_ZONE($tmp, 'ZONE', 'r', '.').($tmp->{isv6} ? '.ip6.arpa' : '.in-addr.arpa');
2921 }
2922 push @working, $zone;
2923 }
2924 return \@working;
2925} # end getZoneList()
2926
2927
2928## DNSDB::getZoneLocation()
2929# Retrieve the default location for a zone.
2930# Takes a database handle, forward/reverse flag, and zone ID
2931sub getZoneLocation {
2932 my $self = shift;
2933 my $dbh = $self->{dbh};
2934 my $revrec = shift;
2935 my $zoneid = shift;
2936
2937 my ($loc) = $dbh->selectrow_array("SELECT default_location FROM ".
2938 ($revrec eq 'n' ? 'domains WHERE domain_id = ?' : 'revzones WHERE rdns_id = ?'),
2939 undef, ($zoneid));
2940 return $loc;
2941} # end getZoneLocation()
2942
2943
2944## DNSDB::addGroup()
2945# Add a group
2946# Takes a database handle, group name, parent group, hashref for permissions,
2947# and optional template-vs-cloneme flag for the default records
2948# Returns a status code and message
2949sub addGroup {
2950 $errstr = '';
2951 my $self = shift;
2952 my $dbh = $self->{dbh};
2953 my $groupname = shift;
2954 my $pargroup = shift;
2955 my $permissions = shift;
2956
2957 # 0 indicates "custom", hardcoded.
2958 # Any other value clones that group's default records, if it exists.
2959 my $inherit = shift || 0;
2960##fixme: need a flag to indicate clone records or <?> ?
2961
2962 # Allow transactions, and raise an exception on errors so we can catch it later.
2963 # Use local to make sure these get "reset" properly on exiting this block
2964 local $dbh->{AutoCommit} = 0;
2965 local $dbh->{RaiseError} = 1;
2966
2967 my ($group_id) = $dbh->selectrow_array("SELECT group_id FROM groups WHERE group_name=?", undef, ($groupname));
2968
2969 return ('FAIL', "Group already exists") if $group_id;
2970
2971 # Wrap all the SQL in a transaction
2972 eval {
2973 $dbh->do("INSERT INTO groups (parent_group_id,group_name) VALUES (?,?)", undef, ($pargroup, $groupname) );
2974
2975 my ($groupid) = $dbh->selectrow_array("SELECT currval('groups_group_id_seq')");
2976
2977 # We work through the whole set of permissions instead of specifying them so
2978 # that when we add a new permission, we don't have to change the code anywhere
2979 # that doesn't explicitly deal with that specific permission.
2980 my @permvals;
2981 foreach (@permtypes) {
2982 if (!defined ($permissions->{$_})) {
2983 push @permvals, 0;
2984 } else {
2985 push @permvals, $permissions->{$_};
2986 }
2987 }
2988 $dbh->do("INSERT INTO permissions (group_id,$permlist) values (?".',?'x($#permtypes+1).")",
2989 undef, ($groupid, @permvals) );
2990 my ($permid) = $dbh->selectrow_array("SELECT currval('permissions_permission_id_seq')");
2991 $dbh->do("UPDATE groups SET permission_id=$permid WHERE group_id=$groupid");
2992
2993 # Default records
2994 my $sthf = $dbh->prepare("INSERT INTO default_records (group_id,host,type,val,distance,weight,port,ttl) ".
2995 "VALUES ($groupid,?,?,?,?,?,?,?)");
2996 my $sthr = $dbh->prepare("INSERT INTO default_rev_records (group_id,host,type,val,ttl) ".
2997 "VALUES ($groupid,?,?,?,?)");
2998 if ($inherit) {
2999 # Duplicate records from parent. Actually relying on inherited records feels
3000 # very fragile, and it would be problematic to roll over at a later time.
3001 my $sth2 = $dbh->prepare("SELECT host,type,val,distance,weight,port,ttl FROM default_records WHERE group_id=?");
3002 $sth2->execute($pargroup);
3003 while (my @clonedata = $sth2->fetchrow_array) {
3004 $sthf->execute(@clonedata);
3005 }
3006 # And now the reverse records
3007 $sth2 = $dbh->prepare("SELECT host,type,val,ttl FROM default_rev_records WHERE group_id=?");
3008 $sth2->execute($pargroup);
3009 while (my @clonedata = $sth2->fetchrow_array) {
3010 $sthr->execute(@clonedata);
3011 }
3012 } else {
3013##fixme: Hardcoding is Bad, mmmmkaaaay?
3014 # reasonable basic defaults for SOA, MX, NS, and minimal hosting
3015 # could load from a config file, but somewhere along the line we need hardcoded bits.
3016 $sthf->execute('ns1.example.com:hostmaster.example.com', 6, '10800:3600:604800:10800', 0, 0, 0, 86400);
3017 $sthf->execute('DOMAIN', 1, '192.168.4.2', 0, 0, 0, 7200);
3018 $sthf->execute('DOMAIN', 15, 'mx.example.com', 10, 0, 0, 7200);
3019 $sthf->execute('DOMAIN', 2, 'ns1.example.com', 0, 0, 0, 7200);
3020 $sthf->execute('DOMAIN', 2, 'ns2.example.com', 0, 0, 0, 7200);
3021 $sthf->execute('www.DOMAIN', 5, 'DOMAIN', 0, 0, 0, 7200);
3022 # reasonable basic defaults for generic reverse zone. Same as initial SQL tabledef.
3023 $sthr->execute('hostmaster.ADMINDOMAIN:ns1.ADMINDOMAIN', 6, '10800:3600:604800:10800', 86400);
3024 $sthr->execute('unused-%r.ADMINDOMAIN', 65283, 'ZONE', 3600);
3025 }
3026
3027 $self->_log(group_id => $pargroup, entry => "Added group $groupname");
3028
3029 # once we get here, we should have suceeded.
3030 $dbh->commit;
3031 }; # end eval
3032
3033 if ($@) {
3034 my $msg = $@;
3035 eval { $dbh->rollback; };
3036 if ($self->{log_failures}) {
3037 $self->_log(group_id => $pargroup, entry => "Failed to add group $groupname: $msg");
3038 $dbh->commit;
3039 }
3040 return ('FAIL',$msg);
3041 }
3042
3043 return ('OK','OK');
3044} # end addGroup()
3045
3046
3047## DNSDB::delGroup()
3048# Delete a group.
3049# Takes a group ID
3050# Returns a status code and message
3051sub delGroup {
3052 my $self = shift;
3053 my $dbh = $self->{dbh};
3054 my $groupid = shift;
3055
3056 # Allow transactions, and raise an exception on errors so we can catch it later.
3057 # Use local to make sure these get "reset" properly on exiting this block
3058 local $dbh->{AutoCommit} = 0;
3059 local $dbh->{RaiseError} = 1;
3060
3061##fixme: locate "knowable" error conditions and deal with them before the eval
3062# ... or inside, whatever.
3063# -> domains still exist in group
3064# -> ...
3065 my $failmsg = '';
3066 my $resultmsg = '';
3067
3068 # collect some pieces for logging and error messages
3069 my $groupname = $self->groupName($groupid);
3070 my $parid = $self->parentID(id => $groupid, type => 'group');
3071
3072 # Wrap all the SQL in a transaction
3073 eval {
3074 # Check for Things in the group
3075 $failmsg = "Can't remove group $groupname";
3076 my ($grpcnt) = $dbh->selectrow_array("SELECT count(*) FROM groups WHERE parent_group_id=?", undef, ($groupid));
3077 die "$grpcnt groups still in group\n" if $grpcnt;
3078 my ($domcnt) = $dbh->selectrow_array("SELECT count(*) FROM domains WHERE group_id=?", undef, ($groupid));
3079 die "$domcnt domains still in group\n" if $domcnt;
3080 my ($revcnt) = $dbh->selectrow_array("SELECT count(*) FROM revzones WHERE group_id=?", undef, ($groupid));
3081 die "$revcnt reverse zones still in group\n" if $revcnt;
3082 my ($usercnt) = $dbh->selectrow_array("SELECT count(*) FROM users WHERE group_id=?", undef, ($groupid));
3083 die "$usercnt users still in group\n" if $usercnt;
3084
3085 $failmsg = "Failed to delete default records for $groupname";
3086 $dbh->do("DELETE from default_records WHERE group_id=?", undef, ($groupid));
3087 $failmsg = "Failed to delete default reverse records for $groupname";
3088 $dbh->do("DELETE from default_rev_records WHERE group_id=?", undef, ($groupid));
3089 $failmsg = "Failed to remove group $groupname";
3090 $dbh->do("DELETE from groups WHERE group_id=?", undef, ($groupid));
3091
3092 $self->_log(group_id => $parid, entry => "Deleted group $groupname");
3093 $resultmsg = "Deleted group $groupname";
3094
3095 # once we get here, we should have suceeded.
3096 $dbh->commit;
3097 }; # end eval
3098
3099 if ($@) {
3100 my $msg = $@;
3101 eval { $dbh->rollback; };
3102 if ($self->{log_failures}) {
3103 $self->_log(group_id => $parid, entry => "$failmsg: $msg");
3104 $dbh->commit; # since we enabled transactions earlier
3105 }
3106 return ('FAIL',"$failmsg: $msg");
3107 }
3108
3109 return ('OK',$resultmsg);
3110} # end delGroup()
3111
3112
3113## DNSDB::getChildren()
3114# Get a list of all groups whose parent^n is group <n>
3115# Takes a database handle, group ID, reference to an array to put the group IDs in,
3116# and an optional flag to return only immediate children or all children-of-children
3117# default to returning all children
3118# Calls itself
3119sub getChildren {
3120 $errstr = '';
3121 my $self = shift;
3122 my $dbh = $self->{dbh};
3123 my $rootgroup = shift;
3124 my $groupdest = shift;
3125 my $immed = shift || 'all';
3126
3127 # special break for default group; otherwise we get stuck.
3128 if ($rootgroup == 1) {
3129 # by definition, group 1 is the Root Of All Groups
3130 my $sth = $dbh->prepare("SELECT group_id FROM groups WHERE NOT (group_id=1)".
3131 ($immed ne 'all' ? " AND parent_group_id=1" : '')." ORDER BY group_name");
3132 $sth->execute;
3133 while (my @this = $sth->fetchrow_array) {
3134 push @$groupdest, @this;
3135 }
3136 } else {
3137 my $sth = $dbh->prepare("SELECT group_id FROM groups WHERE parent_group_id=? ORDER BY group_name");
3138 $sth->execute($rootgroup);
3139 return if $sth->rows == 0;
3140 my @grouplist;
3141 while (my ($group) = $sth->fetchrow_array) {
3142 push @$groupdest, $group;
3143 $self->getChildren($group, $groupdest) if $immed eq 'all';
3144 }
3145 }
3146} # end getChildren()
3147
3148
3149## DNSDB::groupName()
3150# Return the group name based on a group ID
3151# Takes a database handle and the group ID
3152# Returns the group name or undef on failure
3153sub groupName {
3154 $errstr = '';
3155 my $self = shift;
3156 my $dbh = $self->{dbh};
3157 my $groupid = shift;
3158 my $sth = $dbh->prepare("SELECT group_name FROM groups WHERE group_id=?");
3159 $sth->execute($groupid);
3160 my ($groupname) = $sth->fetchrow_array();
3161 $errstr = $DBI::errstr if !$groupname;
3162 return $groupname if $groupname;
3163} # end groupName
3164
3165
3166## DNSDB::getGroupCount()
3167# Get count of subgroups in group or groups
3168# Takes a database handle and hash containing:
3169# - the "current" group
3170# - an array of "acceptable" groups
3171# - Optionally accept a "starts with" and/or "contains" filter argument
3172# Returns an integer count of the resulting group list.
3173sub getGroupCount {
3174 my $self = shift;
3175 my $dbh = $self->{dbh};
3176
3177 my %args = @_;
3178
3179 # Fail on bad curgroup argument. There's no sane fallback on this one.
3180 if (!$args{curgroup} || $args{curgroup} !~ /^\d+$/) {
3181 $errstr = "Bad or missing curgroup argument";
3182 return;
3183 }
3184 # Fail on bad childlist argument. This could be sanely ignored if bad, maybe.
3185 if ($args{childlist} && $args{childlist} !~ /^[\d,]+$/) {
3186 $errstr = "Bad childlist argument";
3187 return;
3188 }
3189
3190 my @filterargs;
3191 $args{startwith} = undef if $args{startwith} && $args{startwith} !~ /^(?:[a-z]|0-9)$/;
3192 push @filterargs, "^$args{startwith}" if $args{startwith};
3193 push @filterargs, $args{filter} if $args{filter};
3194
3195 my $sql = "SELECT count(*) FROM groups ".
3196 "WHERE parent_group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
3197 ($args{startwith} ? " AND group_name ~* ?" : '').
3198 ($args{filter} ? " AND group_name ~* ?" : '');
3199 my ($count) = $dbh->selectrow_array($sql, undef, (@filterargs) );
3200 $errstr = $dbh->errstr if !$count;
3201 return $count;
3202} # end getGroupCount
3203
3204
3205## DNSDB::getGroupList()
3206# Get a list of sub^n-groups in the specified group(s)
3207# Takes the same arguments as getGroupCount() above
3208# Returns an arrayref containing hashrefs suitable for feeding straight to HTML::Template
3209sub getGroupList {
3210 my $self = shift;
3211 my $dbh = $self->{dbh};
3212
3213 my %args = @_;
3214
3215 # Fail on bad curgroup argument. There's no sane fallback on this one.
3216 if (!$args{curgroup} || $args{curgroup} !~ /^\d+$/) {
3217 $errstr = "Bad or missing curgroup argument";
3218 return;
3219 }
3220 # Fail on bad childlist argument. This could be sanely ignored if bad, maybe.
3221 if ($args{childlist} && $args{childlist} !~ /^[\d,]+$/) {
3222 $errstr = "Bad childlist argument";
3223 return;
3224 }
3225
3226 my @filterargs;
3227 $args{startwith} = undef if $args{startwith} && $args{startwith} !~ /^(?:[a-z]|0-9)$/;
3228 push @filterargs, "^$args{startwith}" if $args{startwith};
3229 push @filterargs, $args{filter} if $args{filter};
3230
3231 # protection against bad or missing arguments
3232 $args{sortorder} = 'ASC' if !$args{sortorder} || !grep /^$args{sortorder}$/, ('ASC','DESC');
3233 $args{sortby} = 'group' if !$args{sortby} || $args{sortby} !~ /^[\w_.]+$/;
3234 $args{offset} = 0 if !$args{offset} || $args{offset} !~ /^(?:all|\d+)$/;
3235
3236 # munge sortby for columns in database
3237 $args{sortby} = 'g.group_name' if $args{sortby} eq 'group';
3238 $args{sortby} = 'g2.group_name' if $args{sortby} eq 'parent';
3239
3240 my $sql = q(SELECT g.group_id AS groupid, g.group_name AS groupname, g2.group_name AS pgroup
3241 FROM groups g
3242 INNER JOIN groups g2 ON g2.group_id=g.parent_group_id
3243 ).
3244 " WHERE g.parent_group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
3245 ($args{startwith} ? " AND g.group_name ~* ?" : '').
3246 ($args{filter} ? " AND g.group_name ~* ?" : '').
3247 " GROUP BY g.group_id, g.group_name, g2.group_name ".
3248 " ORDER BY $args{sortby} $args{sortorder} ".
3249 ($args{offset} eq 'all' ? '' : " LIMIT $self->{perpage} OFFSET ".$args{offset}*$self->{perpage});
3250 my $glist = $dbh->selectall_arrayref($sql, { Slice => {} }, (@filterargs) );
3251 $errstr = $dbh->errstr if !$glist;
3252
3253 # LEFT JOINs make the result set balloon beyond sanity just to include counts;
3254 # this means there's lots of crunching needed to trim the result set back down.
3255 # So instead we track the order of the groups, and push the counts into the
3256 # arrayref result separately.
3257##fixme: put this whole sub in a transaction? might be
3258# needed for accurate results on very busy systems.
3259##fixme: large group lists need prepared statements?
3260#my $ucsth = $dbh->prepare("SELECT count(*) FROM users WHERE group_id=?");
3261#my $dcsth = $dbh->prepare("SELECT count(*) FROM domains WHERE group_id=?");
3262#my $rcsth = $dbh->prepare("SELECT count(*) FROM revzones WHERE group_id=?");
3263 foreach (@{$glist}) {
3264 my ($ucnt) = $dbh->selectrow_array("SELECT count(*) FROM users WHERE group_id=?", undef, ($$_{groupid}));
3265 $$_{nusers} = $ucnt;
3266 my ($dcnt) = $dbh->selectrow_array("SELECT count(*) FROM domains WHERE group_id=?", undef, ($$_{groupid}));
3267 $$_{ndomains} = $dcnt;
3268 my ($rcnt) = $dbh->selectrow_array("SELECT count(*) FROM revzones WHERE group_id=?", undef, ($$_{groupid}));
3269 $$_{nrevzones} = $rcnt;
3270 }
3271
3272 return $glist;
3273} # end getGroupList
3274
3275
3276## DNSDB::groupID()
3277# Return the group ID based on the group name
3278# Takes a database handle and the group name
3279# Returns the group ID or undef on failure
3280sub groupID {
3281 $errstr = '';
3282 my $self = shift;
3283 my $dbh = $self->{dbh};
3284 my $group = shift;
3285 my ($grpid) = $dbh->selectrow_array("SELECT group_id FROM groups WHERE group_name=?", undef, ($group) );
3286 $errstr = $DBI::errstr if !$grpid;
3287 return $grpid if $grpid;
3288} # end groupID()
3289
3290
3291## DNSDB::addUser()
3292# Add a user.
3293# Takes a DB handle, username, group ID, password, state (active/inactive).
3294# Optionally accepts:
3295# user type (user/admin) - defaults to user
3296# permissions string - defaults to inherit from group
3297# three valid forms:
3298# i - Inherit permissions
3299# c:<user_id> - Clone permissions from <user_id>
3300# C:<permission list> - Set these specific permissions
3301# first name - defaults to username
3302# last name - defaults to blank
3303# phone - defaults to blank (could put other data within column def)
3304# Returns (OK,<uid>) on success, (FAIL,<message>) on failure
3305sub addUser {
3306 $errstr = '';
3307 my $self = shift;
3308 my $dbh = $self->{dbh};
3309 my $username = shift;
3310 my $group = shift;
3311 my $pass = shift;
3312 my $state = shift;
3313
3314 return ('FAIL', "Missing one or more required entries") if !defined($state);
3315 return ('FAIL', "Username must not be blank") if !$username;
3316
3317 # Munge in some alternate state values
3318 $state = 1 if $state =~ /^active$/;
3319 $state = 1 if $state =~ /^on$/;
3320 $state = 0 if $state =~ /^inactive$/;
3321 $state = 0 if $state =~ /^off$/;
3322
3323 my $type = shift || 'u'; # create limited users by default - fwiw, not sure yet how this will interact with ACLs
3324
3325 my $permstring = shift || 'i'; # default is to inhert permissions from group
3326
3327 my $fname = shift || $username;
3328 my $lname = shift || '';
3329 my $phone = shift || ''; # not going format-check
3330
3331 my $sth = $dbh->prepare("SELECT user_id FROM users WHERE username=?");
3332 my $user_id;
3333
3334# quick check to start to see if we've already got one
3335 $sth->execute($username);
3336 ($user_id) = $sth->fetchrow_array;
3337
3338 return ('FAIL', "User already exists") if $user_id;
3339
3340 # Allow transactions, and raise an exception on errors so we can catch it later.
3341 # Use local to make sure these get "reset" properly on exiting this block
3342 local $dbh->{AutoCommit} = 0;
3343 local $dbh->{RaiseError} = 1;
3344
3345 # Wrap all the SQL in a transaction
3346 eval {
3347 # insert the user... note we set inherited perms by default since
3348 # it's simple and cleans up some other bits of state
3349##fixme: need better handling of case of inherited or missing (!!) permissions entries
3350 my $sth = $dbh->prepare("INSERT INTO users ".
3351 "(group_id,username,password,firstname,lastname,phone,type,status,permission_id,inherit_perm) ".
3352 "VALUES (?,?,?,?,?,?,?,?,(SELECT permission_id FROM permissions WHERE group_id=?),'t')");
3353 $sth->execute($group,$username,unix_md5_crypt($pass),$fname,$lname,$phone,$type,$state,$group);
3354
3355 # get the ID...
3356 ($user_id) = $dbh->selectrow_array("SELECT currval('users_user_id_seq')");
3357
3358# Permissions! Gotta set'em all!
3359 die "Invalid permission string $permstring\n"
3360 if $permstring !~ /^(?:
3361 i # inherit
3362 |c:\d+ # clone
3363 # custom. no, the leading , is not a typo
3364 |C:(?:,(?:group|user|domain|record|location|self)_(?:edit|create|delete|locchg|view))*
3365 )$/x;
3366# bleh. I'd call another function to do my dirty work, but we're in the middle of a transaction already.
3367 if ($permstring ne 'i') {
3368 # for cloned or custom permissions, we have to create a new permissions entry.
3369 my $clonesrc = $group;
3370 if ($permstring =~ /^c:(\d+)/) { $clonesrc = $1; }
3371 $dbh->do("INSERT INTO permissions ($permlist,user_id) ".
3372 "SELECT $permlist,? FROM permissions WHERE permission_id=".
3373 "(SELECT permission_id FROM permissions WHERE ".($permstring =~ /^c:/ ? 'user' : 'group')."_id=?)",
3374 undef, ($user_id,$clonesrc) );
3375 $dbh->do("UPDATE users SET permission_id=".
3376 "(SELECT permission_id FROM permissions WHERE user_id=?) ".
3377 "WHERE user_id=?", undef, ($user_id, $user_id) );
3378 }
3379 if ($permstring =~ /^C:/) {
3380 # finally for custom permissions, we set the passed-in permissions (and unset
3381 # any that might have been brought in by the clone operation above)
3382 my ($permid) = $dbh->selectrow_array("SELECT permission_id FROM permissions WHERE user_id=?",
3383 undef, ($user_id) );
3384 foreach (@permtypes) {
3385 if ($permstring =~ /,$_/) {
3386 $dbh->do("UPDATE permissions SET $_='t' WHERE permission_id=?", undef, ($permid) );
3387 } else {
3388 $dbh->do("UPDATE permissions SET $_='f' WHERE permission_id=?", undef, ($permid) );
3389 }
3390 }
3391 }
3392
3393 $dbh->do("UPDATE users SET inherit_perm='n' WHERE user_id=?", undef, ($user_id) );
3394
3395##fixme: add another table to hold name/email for log table?
3396
3397 $self->_log(group_id => $group, entry => "Added user $username ($fname $lname)");
3398 # once we get here, we should have suceeded.
3399 $dbh->commit;
3400 }; # end eval
3401
3402 if ($@) {
3403 my $msg = $@;
3404 eval { $dbh->rollback; };
3405 if ($self->{log_failures}) {
3406 $self->_log(group_id => $group, entry => "Error adding user $username: $msg");
3407 $dbh->commit; # since we enabled transactions earlier
3408 }
3409 return ('FAIL',"Error adding user $username: $msg");
3410 }
3411
3412 return ('OK',"User $username ($fname $lname) added");
3413} # end addUser
3414
3415
3416## DNSDB::getUserCount()
3417# Get count of users in group
3418# Takes a database handle and hash containing at least the current group, and optionally:
3419# - a reference list of secondary groups
3420# - a filter string
3421# - a "Starts with" string
3422sub getUserCount {
3423 my $self = shift;
3424 my $dbh = $self->{dbh};
3425
3426 my %args = @_;
3427
3428 # Fail on bad curgroup argument. There's no sane fallback on this one.
3429 if (!$args{curgroup} || $args{curgroup} !~ /^\d+$/) {
3430 $errstr = "Bad or missing curgroup argument";
3431 return;
3432 }
3433 # Fail on bad childlist argument. This could be sanely ignored if bad, maybe.
3434 if ($args{childlist} && $args{childlist} !~ /^[\d,]+$/) {
3435 $errstr = "Bad childlist argument";
3436 return;
3437 }
3438
3439 my @filterargs;
3440 $args{startwith} = undef if $args{startwith} && $args{startwith} !~ /^(?:[a-z]|0-9)$/;
3441 push @filterargs, "^$args{startwith}" if $args{startwith};
3442 push @filterargs, $args{filter} if $args{filter};
3443
3444 my $sql = "SELECT count(*) FROM users ".
3445 "WHERE group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
3446 ($args{startwith} ? " AND username ~* ?" : '').
3447 ($args{filter} ? " AND username ~* ?" : '').
3448 " AND NOT type = 'R' ";
3449 my ($count) = $dbh->selectrow_array($sql, undef, (@filterargs) );
3450 $errstr = $dbh->errstr if !$count;
3451 return $count;
3452} # end getUserCount()
3453
3454
3455## DNSDB::getUserList()
3456# Get list of users
3457# Takes the same arguments as getUserCount() above, plus optional:
3458# - sort field
3459# - sort order
3460# - offset/return-all-everything flag (defaults to $perpage records)
3461sub getUserList {
3462 my $self = shift;
3463 my $dbh = $self->{dbh};
3464
3465 my %args = @_;
3466
3467 # Fail on bad curgroup argument. There's no sane fallback on this one.
3468 if (!$args{curgroup} || $args{curgroup} !~ /^\d+$/) {
3469 $errstr = "Bad or missing curgroup argument";
3470 return;
3471 }
3472 # Fail on bad childlist argument. This could be sanely ignored if bad, maybe.
3473 if ($args{childlist} && $args{childlist} !~ /^[\d,]+$/) {
3474 $errstr = "Bad childlist argument";
3475 return;
3476 }
3477
3478 my @filterargs;
3479 $args{startwith} = undef if $args{startwith} && $args{startwith} !~ /^(?:[a-z]|0-9)$/;
3480 push @filterargs, "^$args{startwith}" if $args{startwith};
3481 push @filterargs, $args{filter} if $args{filter};
3482
3483 # better to request sorts on "simple" names, but it means we need to map it to real columns
3484 my %sortmap = (user => 'u.username', type => 'u.type', group => 'g.group_name', status => 'u.status',
3485 fname => 'fname');
3486 $args{sortby} = $sortmap{$args{sortby}};
3487
3488 # protection against bad or missing arguments
3489 $args{sortorder} = 'ASC' if !$args{sortorder} || !grep /^$args{sortorder}$/, ('ASC','DESC');
3490 $args{sortby} = 'u.username' if !$args{sortby} || $args{sortby} !~ /^[\w_.]+$/;
3491 $args{offset} = 0 if !$args{offset} || $args{offset} !~ /^(?:all|\d+)$/;
3492
3493 my $sql = "SELECT u.user_id, u.username, u.firstname || ' ' || u.lastname AS fname, u.type, g.group_name, u.status ".
3494 "FROM users u ".
3495 "INNER JOIN groups g ON u.group_id=g.group_id ".
3496 "WHERE u.group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
3497 ($args{startwith} ? " AND u.username ~* ?" : '').
3498 ($args{filter} ? " AND u.username ~* ?" : '').
3499 " AND NOT u.type = 'R' ".
3500 " ORDER BY $args{sortby} $args{sortorder} ".
3501 ($args{offset} eq 'all' ? '' : " LIMIT $self->{perpage} OFFSET ".$args{offset}*$self->{perpage});
3502 my $ulist = $dbh->selectall_arrayref($sql, { Slice => {} }, (@filterargs) );
3503 $errstr = $dbh->errstr if !$ulist;
3504 return $ulist;
3505} # end getUserList()
3506
3507
3508## DNSDB::getUserDropdown()
3509# Get a list of usernames for use in a dropdown menu.
3510# Takes a database handle, current group, and optional "tag this as selected" flag.
3511# Returns a reference to a list of hashrefs suitable to feeding to HTML::Template
3512sub getUserDropdown {
3513 my $self = shift;
3514 my $dbh = $self->{dbh};
3515 my $grp = shift;
3516 my $sel = shift || 0;
3517
3518 my $sth = $dbh->prepare("SELECT username,user_id FROM users WHERE group_id=? AND password <> 'RPC'");
3519 $sth->execute($grp);
3520
3521 my @userlist;
3522 while (my ($username,$uid) = $sth->fetchrow_array) {
3523 my %row = (
3524 username => $username,
3525 uid => $uid,
3526 selected => ($sel == $uid ? 1 : 0)
3527 );
3528 push @userlist, \%row;
3529 }
3530 return \@userlist;
3531} # end getUserDropdown()
3532
3533
3534## DNSDB:: updateUser()
3535# Update general data about user
3536sub updateUser {
3537 my $self = shift;
3538 my $dbh = $self->{dbh};
3539
3540##fixme: tweak calling convention so that we can update any given bit of data
3541 my $uid = shift;
3542 my $username = shift;
3543 my $group = shift;
3544 my $pass = shift;
3545 my $state = shift;
3546 my $type = shift || 'u';
3547 my $fname = shift || $username;
3548 my $lname = shift || '';
3549 my $phone = shift || ''; # not going format-check
3550
3551 my $resultmsg = '';
3552
3553 # Munge in some alternate state values
3554 $state = 1 if $state =~ /^active$/;
3555 $state = 1 if $state =~ /^on$/;
3556 $state = 0 if $state =~ /^inactive$/;
3557 $state = 0 if $state =~ /^off$/;
3558
3559 # Allow transactions, and raise an exception on errors so we can catch it later.
3560 # Use local to make sure these get "reset" properly on exiting this block
3561 local $dbh->{AutoCommit} = 0;
3562 local $dbh->{RaiseError} = 1;
3563
3564 my $sth;
3565
3566 # Password can be left blank; if so we assume there's one on file.
3567 # Actual blank passwords are bad, mm'kay?
3568 if (!$pass) {
3569 ($pass) = $dbh->selectrow_array("SELECT password FROM users WHERE user_id=?", undef, ($uid));
3570 } else {
3571 $pass = unix_md5_crypt($pass);
3572 }
3573
3574 eval {
3575 $dbh->do("UPDATE users SET username=?, password=?, firstname=?, lastname=?, phone=?, type=?, status=?".
3576 " WHERE user_id=?", undef, ($username, $pass, $fname, $lname, $phone, $type, $state, $uid));
3577 $resultmsg = "Updated user info for $username ($fname $lname)";
3578 $self->_log(group_id => $group, entry => $resultmsg);
3579 $dbh->commit;
3580 };
3581 if ($@) {
3582 my $msg = $@;
3583 eval { $dbh->rollback; };
3584 if ($self->{log_failures}) {
3585 $self->_log(group_id => $group, entry => "Error updating user $username: $msg");
3586 $dbh->commit; # since we enabled transactions earlier
3587 }
3588 return ('FAIL',"Error updating user $username: $msg");
3589 }
3590
3591 return ('OK',$resultmsg);
3592} # end updateUser()
3593
3594
3595## DNSDB::delUser()
3596# Delete a user.
3597# Takes a database handle and user ID
3598# Returns a success/failure code and matching message
3599sub delUser {
3600 my $self = shift;
3601 my $dbh = $self->{dbh};
3602 my $userid = shift;
3603
3604 return ('FAIL',"Bad userid") if !defined($userid);
3605
3606 my $userdata = $self->getUserData($userid);
3607
3608 # Allow transactions, and raise an exception on errors so we can catch it later.
3609 # Use local to make sure these get "reset" properly on exiting this block
3610 local $dbh->{AutoCommit} = 0;
3611 local $dbh->{RaiseError} = 1;
3612
3613 eval {
3614 $dbh->do("DELETE FROM users WHERE user_id=?", undef, ($userid));
3615 $self->_log(group_id => $userdata->{group_id},
3616 entry => "Deleted user ID $userid/".$userdata->{username}.
3617 " (".$userdata->{firstname}." ".$userdata->{lastname}.")");
3618 $dbh->commit;
3619 };
3620 if ($@) {
3621 my $msg = $@;
3622 eval { $dbh->rollback; };
3623 if ($self->{log_failures}) {
3624 $self->_log(group_id => $userdata->{group_id}, entry => "Error deleting user ID ".
3625 "$userid/".$userdata->{username}.": $msg");
3626 $dbh->commit;
3627 }
3628 return ('FAIL',"Error deleting user $userid/".$userdata->{username}.": $msg");
3629 }
3630
3631 return ('OK',"Deleted user ".$userdata->{username}." (".$userdata->{firstname}." ".$userdata->{lastname}.")");
3632} # end delUser
3633
3634
3635## DNSDB::userFullName()
3636# Return a pretty string!
3637# Takes a user_id and optional printf-ish string to indicate which pieces where:
3638# %u for the username
3639# %f for the first name
3640# %l for the last name
3641# All other text in the passed string will be left as-is.
3642##fixme: need a "smart" option too, so that missing/null/blank first/last names don't give funky output
3643sub userFullName {
3644 $errstr = '';
3645 my $self = shift;
3646 my $dbh = $self->{dbh};
3647 my $userid = shift;
3648 my $fullformat = shift || '%f %l (%u)';
3649 my $sth = $dbh->prepare("select username,firstname,lastname from users where user_id=?");
3650 $sth->execute($userid);
3651 my ($uname,$fname,$lname) = $sth->fetchrow_array();
3652 $errstr = $DBI::errstr if !$uname;
3653
3654 no warnings qw (uninitialized);
3655 $fullformat =~ s/\%u/$uname/g;
3656 $fullformat =~ s/\%f/$fname/g;
3657 $fullformat =~ s/\%l/$lname/g;
3658
3659 return $fullformat;
3660} # end userFullName
3661
3662
3663## DNSDB::userStatus()
3664# Sets and/or returns a user's status
3665# Takes a database handle, user ID and optionally a status argument
3666# Returns undef on errors.
3667sub userStatus {
3668 my $self = shift;
3669 my $dbh = $self->{dbh};
3670 my $id = shift;
3671 my $newstatus = shift || 'mu';
3672
3673 return undef if $id !~ /^\d+$/;
3674
3675 my $userdata = $self->getUserData($id);
3676
3677 # Allow transactions, and raise an exception on errors so we can catch it later.
3678 # Use local to make sure these get "reset" properly on exiting this block
3679 local $dbh->{AutoCommit} = 0;
3680 local $dbh->{RaiseError} = 1;
3681
3682 if ($newstatus ne 'mu') {
3683 # ooo, fun! let's see what we were passed for status
3684 eval {
3685 $newstatus = 0 if $newstatus eq 'useroff';
3686 $newstatus = 1 if $newstatus eq 'useron';
3687 $dbh->do("UPDATE users SET status=? WHERE user_id=?", undef, ($newstatus, $id));
3688
3689 $resultstr = ($newstatus ? 'Enabled' : 'Disabled')." user ".$userdata->{username}.
3690 " (".$userdata->{firstname}." ".$userdata->{lastname}.")";
3691
3692 my %loghash;
3693 $loghash{group_id} = $self->parentID(id => $id, type => 'user');
3694 $loghash{entry} = $resultstr;
3695 $self->_log(%loghash);
3696
3697 $dbh->commit;
3698 };
3699 if ($@) {
3700 my $msg = $@;
3701 eval { $dbh->rollback; };
3702 $resultstr = '';
3703 $errstr = $msg;
3704##fixme: failure logging?
3705 return;
3706 }
3707 }
3708
3709 my ($status) = $dbh->selectrow_array("SELECT status FROM users WHERE user_id=?", undef, ($id));
3710 return $status;
3711} # end userStatus()
3712
3713
3714## DNSDB::getUserData()
3715# Get misc user data for display
3716sub getUserData {
3717 my $self = shift;
3718 my $dbh = $self->{dbh};
3719 my $uid = shift;
3720
3721 my $sth = $dbh->prepare("SELECT group_id,username,firstname,lastname,phone,type,status,inherit_perm ".
3722 "FROM users WHERE user_id=?");
3723 $sth->execute($uid);
3724 return $sth->fetchrow_hashref();
3725} # end getUserData()
3726
3727
3728## DNSDB::addLoc()
3729# Add a new location.
3730# Takes a database handle, group ID, short and long description, and a comma-separated
3731# list of IP addresses.
3732# Returns ('OK',<location>) on success, ('FAIL',<failmsg>) on failure
3733sub addLoc {
3734 my $self = shift;
3735 my $dbh = $self->{dbh};
3736 my %args = @_;
3737
3738 my $grp = $args{group};
3739 my $shdesc = $args{desc};
3740 my $comments = $args{comments};
3741 my $iplist = $args{iplist};
3742
3743 # $shdesc gets set to the generated location ID if possible, but these can be de-undefined here.
3744 $comments = '' if !$comments;
3745 $iplist = '' if !$iplist;
3746
3747 # allow requesting a specific location entry.
3748 my $loc = $args{loc};
3749
3750 # Generate a location ID. This is, by spec, a two-character widget. We'll use [a-z][a-z]
3751 # for now; 676 locations should satisfy all but the largest of the huge networks.
3752
3753 # just to be as clear as possible; as per http://cr.yp.to/djbdns/tinydns-data.html:
3754
3755#For versions 1.04 and above: You may include a client location on each line. The line is ignored for clients
3756#outside that location. Client locations are specified by % lines:
3757#
3758# %lo:ipprefix
3759#
3760#means that IP addresses starting with ipprefix are in location lo. lo is a sequence of one or two ASCII letters.
3761
3762 # this has been confirmed by experiment; locations "lo", "Lo", and "lO" are all distinct.
3763
3764# add just after "my $origloc = $loc;":
3765# # These expand the possible space from 26^2 to 52^2 [* note in testing only 2052 were achieved],
3766# # and wrap it around.
3767# # Yes, they skip a couple of possibles. No, I don't care.
3768# $loc = 'aA' if $loc eq 'zz';
3769# $loc = 'Aa' if $loc eq 'zZ';
3770# $loc = 'ZA' if $loc eq 'Zz';
3771# $loc = 'aa' if $loc eq 'ZZ';
3772
3773 # Allow transactions, and raise an exception on errors so we can catch it later.
3774 # Use local to make sure these get "reset" properly on exiting this block
3775 local $dbh->{AutoCommit} = 0;
3776 local $dbh->{RaiseError} = 1;
3777
3778##fixme: There is probably a far better way to do this. Sequential increments
3779# are marginally less stupid that pure random generation though, and the existence
3780# check makes sure we don't stomp on an imported one.
3781
3782 eval {
3783 # Get the "last" location. Note this is the only use for loc_id, because selecting on location Does Funky Things
3784 my ($newloc) = $dbh->selectrow_array("SELECT location FROM locations ORDER BY loc_id DESC LIMIT 1");
3785
3786 no warnings qw(uninitialized);
3787
3788 my $ecnt = $dbh->prepare("SELECT count(*) FROM locations WHERE location LIKE ?");
3789
3790 if ($loc) {
3791 $ecnt->execute($loc);
3792 if (($ecnt->fetchrow_array())[0]) {
3793 # too bad, so sad, requested location is unavailable.
3794##fixme: known failure case: caller requests a location ID that is not two characters.
3795 die "Requested location is already defined\n" if $args{reqonly};
3796 # fall back to autoincrement
3797 }
3798 $newloc = $loc;
3799 }
3800
3801 # Either the requested location ID is unavailable and the caller isn't too attached
3802 # to it, OR, the caller hasn't specified a location ID. (The second case should be
3803 # far more common.) Find the "next available" location identifier.
3804
3805 ($newloc) = ($newloc =~ /^(..)/) if $newloc;
3806 my $origloc = $newloc;
3807 $newloc = 'aa' if !$newloc;
3808 # Make a change...
3809 # ... and keep changing if it exists
3810 while ($dbh->selectrow_array("SELECT count(*) FROM locations WHERE location LIKE ?", undef, ($newloc.'%'))) {
3811 $newloc++;
3812 ($newloc) = ($newloc =~ /^(..)/);
3813 die "too many locations in use, can't add another one\n" if $newloc eq $origloc;
3814##fixme: really need to handle this case faster somehow
3815#if $loc eq $origloc die "<thwap> bad admin: all locations used, your network is too fragmented";
3816 }
3817 # And now we should have a unique location.
3818 $shdesc = $newloc if !$shdesc;
3819 $dbh->do("INSERT INTO locations (location, group_id, iplist, description, comments) VALUES (?,?,?,?,?)",
3820 undef, ($newloc, $grp, $iplist, $shdesc, $comments) );
3821 $self->_log(entry => "Added location ($shdesc, '$iplist')");
3822 $loc = $newloc;
3823 $dbh->commit;
3824 };
3825 if ($@) {
3826 my $msg = $@;
3827 eval { $dbh->rollback; };
3828 if ($self->{log_failures}) {
3829 $shdesc = $loc if !$shdesc;
3830 $self->_log(entry => "Failed adding location ($shdesc, '$iplist'): $msg");
3831 $dbh->commit;
3832 }
3833 return ('FAIL',$msg);
3834 }
3835
3836 return ('OK',$loc);
3837} # end addLoc()
3838
3839
3840## DNSDB::updateLoc()
3841# Update details of a location.
3842# Takes a database handle, location ID, group ID, short description,
3843# long comments/notes, and comma/space-separated IP list
3844# Returns a result code and message
3845sub updateLoc {
3846 my $self = shift;
3847 my $dbh = $self->{dbh};
3848 my $loc = shift;
3849 my $grp = shift;
3850 my $shdesc = shift;
3851 my $comments = shift;
3852 my $iplist = shift;
3853
3854 $shdesc = '' if !$shdesc;
3855 $comments = '' if !$comments;
3856 $iplist = '' if !$iplist;
3857
3858 # Allow transactions, and raise an exception on errors so we can catch it later.
3859 # Use local to make sure these get "reset" properly on exiting this block
3860 local $dbh->{AutoCommit} = 0;
3861 local $dbh->{RaiseError} = 1;
3862
3863 my $oldloc = $self->getLoc($loc);
3864 my $okmsg = "Updated location (".$oldloc->{description}.", '".$oldloc->{iplist}."') to ($shdesc, '$iplist')";
3865
3866 eval {
3867 $dbh->do("UPDATE locations SET group_id=?,iplist=?,description=?,comments=? WHERE location=?",
3868 undef, ($grp, $iplist, $shdesc, $comments, $loc) );
3869 $self->_log(entry => $okmsg);
3870 $dbh->commit;
3871 };
3872 if ($@) {
3873 my $msg = $@;
3874 eval { $dbh->rollback; };
3875 if ($self->{log_failures}) {
3876 $shdesc = $loc if !$shdesc;
3877 $self->_log(entry => "Failed updating location ($shdesc, '$iplist'): $msg");
3878 $dbh->commit;
3879 }
3880 return ('FAIL',$msg);
3881 }
3882
3883 return ('OK',$okmsg);
3884} # end updateLoc()
3885
3886
3887## DNSDB::delLoc()
3888sub delLoc {
3889 my $self = shift;
3890 my $dbh = $self->{dbh};
3891 my $loc = shift;
3892
3893 # Allow transactions, and raise an exception on errors so we can catch it later.
3894 # Use local to make sure these get "reset" properly on exiting this block
3895 local $dbh->{AutoCommit} = 0;
3896 local $dbh->{RaiseError} = 1;
3897
3898 my $oldloc = $self->getLoc($loc);
3899 my $olddesc = ($oldloc->{description} ? $oldloc->{description} : $loc);
3900 my $okmsg = "Deleted location ($olddesc, '".$oldloc->{iplist}."')";
3901
3902 eval {
3903 # Check for records with this location first. Deleting a location without deleting records
3904 # tagged for that location will render them unpublished without other warning.
3905 my ($r) = $dbh->selectrow_array("SELECT record_id FROM records WHERE location=? LIMIT 1", undef, ($loc) );
3906 die "Records still exist in location $olddesc\n" if $r;
3907 $dbh->do("DELETE FROM locations WHERE location=?", undef, ($loc) );
3908 $self->_log(entry => $okmsg);
3909 $dbh->commit;
3910 };
3911 if ($@) {
3912 my $msg = $@;
3913 eval { $dbh->rollback; };
3914 if ($self->{log_failures}) {
3915 $self->_log(entry => "Failed to delete location ($olddesc, '$oldloc->{iplist}'): $msg");
3916 $dbh->commit;
3917 }
3918 return ('FAIL', "Failed to delete location ($olddesc, '$oldloc->{iplist}'): $msg");
3919 }
3920
3921 return ('OK',$okmsg);
3922} # end delLoc()
3923
3924
3925## DNSDB::getLoc()
3926# Get details about a location/view
3927# Takes a database handle and location ID.
3928# Returns a reference to a hash containing the group ID, IP list, description, and comments/notes
3929sub getLoc {
3930 my $self = shift;
3931 my $dbh = $self->{dbh};
3932 my $loc = shift;
3933
3934 my $sth = $dbh->prepare("SELECT group_id,iplist,description,comments FROM locations WHERE location=?");
3935 $sth->execute($loc);
3936 return $sth->fetchrow_hashref();
3937} # end getLoc()
3938
3939
3940## DNSDB::getLocCount()
3941# Get count of locations/views
3942# Takes a database handle and hash containing at least the current group, and optionally:
3943# - a reference list of secondary groups
3944# - a filter string
3945# - a "Starts with" string
3946sub getLocCount {
3947 my $self = shift;
3948 my $dbh = $self->{dbh};
3949
3950 my %args = @_;
3951
3952 # Fail on bad curgroup argument. There's no sane fallback on this one.
3953 if (!$args{curgroup} || $args{curgroup} !~ /^\d+$/) {
3954 $errstr = "Bad or missing curgroup argument";
3955 return;
3956 }
3957 # Fail on bad childlist argument. This could be sanely ignored if bad, maybe.
3958 if ($args{childlist} && $args{childlist} !~ /^[\d,]+$/) {
3959 $errstr = "Bad childlist argument";
3960 return;
3961 }
3962
3963 my @filterargs;
3964 $args{startwith} = undef if $args{startwith} && $args{startwith} !~ /^(?:[a-z]|0-9)$/;
3965 push @filterargs, "^$args{startwith}" if $args{startwith};
3966 push @filterargs, $args{filter} if $args{filter};
3967
3968 my $sql = "SELECT count(*) FROM locations ".
3969 "WHERE group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
3970 ($args{startwith} ? " AND description ~* ?" : '').
3971 ($args{filter} ? " AND description ~* ?" : '');
3972 my ($count) = $dbh->selectrow_array($sql, undef, (@filterargs) );
3973 $errstr = $dbh->errstr if !$count;
3974 return $count;
3975} # end getLocCount()
3976
3977
3978## DNSDB::getLocList()
3979sub getLocList {
3980 my $self = shift;
3981 my $dbh = $self->{dbh};
3982
3983 my %args = @_;
3984
3985 # Fail on bad curgroup argument. There's no sane fallback on this one.
3986 if (!$args{curgroup} || $args{curgroup} !~ /^\d+$/) {
3987 $errstr = "Bad or missing curgroup argument";
3988 return;
3989 }
3990 # Fail on bad childlist argument. This could be sanely ignored if bad, maybe.
3991 if ($args{childlist} && $args{childlist} !~ /^[\d,]+$/) {
3992 $errstr = "Bad childlist argument";
3993 return;
3994 }
3995
3996 my @filterargs;
3997 $args{startwith} = undef if $args{startwith} && $args{startwith} !~ /^(?:[a-z]|0-9)$/;
3998 push @filterargs, "^$args{startwith}" if $args{startwith};
3999 push @filterargs, $args{filter} if $args{filter};
4000
4001 # better to request sorts on "simple" names, but it means we need to map it to real columns
4002# my %sortmap = (user => 'u.username', type => 'u.type', group => 'g.group_name', status => 'u.status',
4003# fname => 'fname');
4004# $args{sortby} = $sortmap{$args{sortby}};
4005
4006 # protection against bad or missing arguments
4007 $args{sortorder} = 'ASC' if !$args{sortorder} || !grep /^$args{sortorder}$/, ('ASC','DESC');
4008 $args{sortby} = 'l.description' if !$args{sortby} || $args{sortby} !~ /^[\w_.]+$/;
4009 $args{offset} = 0 if !$args{offset} || $args{offset} !~ /^(?:all|\d+)$/;
4010
4011 my $sql = "SELECT l.location, l.description, l.iplist, g.group_name ".
4012 "FROM locations l ".
4013 "INNER JOIN groups g ON l.group_id=g.group_id ".
4014 "WHERE l.group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
4015 ($args{startwith} ? " AND l.description ~* ?" : '').
4016 ($args{filter} ? " AND l.description ~* ?" : '').
4017 " ORDER BY $args{sortby} $args{sortorder} ".
4018 ($args{offset} eq 'all' ? '' : " LIMIT $self->{perpage} OFFSET ".$args{offset}*$self->{perpage});
4019 my $ulist = $dbh->selectall_arrayref($sql, { Slice => {} }, (@filterargs) );
4020 $errstr = $dbh->errstr if !$ulist;
4021 return $ulist;
4022} # end getLocList()
4023
4024
4025## DNSDB::getLocDropdown()
4026# Get a list of location names for use in a dropdown menu.
4027# Takes a database handle, current group, and optional "tag this as selected" flag.
4028# Returns a reference to a list of hashrefs suitable to feeding to HTML::Template
4029sub getLocDropdown {
4030 my $self = shift;
4031 my $dbh = $self->{dbh};
4032 my $grp = shift;
4033 my $sel = shift || '';
4034
4035 my $sth = $dbh->prepare(qq(
4036 SELECT description,location FROM locations
4037 WHERE group_id=?
4038 ORDER BY description
4039 ) );
4040 $sth->execute($grp);
4041
4042 my @loclist;
4043 push @loclist, { locname => "(Default/All)", loc => '', selected => ($sel ? 0 : ($sel eq '' ? 1 : 0)) };
4044 while (my ($locname, $loc) = $sth->fetchrow_array) {
4045 my %row = (
4046 locname => $locname,
4047 loc => $loc,
4048 selected => ($sel eq $loc ? 1 : 0)
4049 );
4050 push @loclist, \%row;
4051 }
4052 return \@loclist;
4053} # end getLocDropdown()
4054
4055
4056## DNSDB::getSOA()
4057# Return all suitable fields from an SOA record in separate elements of a hash
4058# Takes a database handle, default/live flag, domain/reverse flag, and parent ID
4059sub getSOA {
4060 $errstr = '';
4061 my $self = shift;
4062 my $dbh = $self->{dbh};
4063 my $def = shift;
4064 my $rev = shift;
4065 my $id = shift;
4066
4067 # (ab)use distance and weight columns to store SOA data? can't for default_rev_records...
4068 # - should really attach serial to the zone parent somewhere
4069
4070 my $sql = "SELECT record_id,host,val,ttl from "._rectable($def,$rev).
4071 " WHERE "._recparent($def,$rev)." = ? AND type=$reverse_typemap{SOA}";
4072 my $ret = $dbh->selectrow_hashref($sql, undef, ($id) );
4073 return if !$ret;
4074##fixme: stick a flag somewhere if the record doesn't exist. by the API, this is an impossible case, but...
4075
4076 ($ret->{contact},$ret->{prins}) = split /:/, $ret->{host};
4077 delete $ret->{host};
4078 ($ret->{refresh},$ret->{retry},$ret->{expire},$ret->{minttl}) = split /:/, $ret->{val};
4079 delete $ret->{val};
4080
4081 return $ret;
4082} # end getSOA()
4083
4084
4085## DNSDB::updateSOA()
4086# Update the specified SOA record
4087# Takes a database handle, default/live flag, forward/reverse flag, and SOA data hash
4088# Returns a two-element list with a result code and message
4089sub updateSOA {
4090 my $self = shift;
4091 my $dbh = $self->{dbh};
4092 my $defrec = shift;
4093 my $revrec = shift;
4094
4095 my %soa = @_;
4096
4097 my $oldsoa = $self->getSOA($defrec, $revrec, $soa{id});
4098
4099 my $msg;
4100 my %logdata;
4101 if ($defrec eq 'n') {
4102 $logdata{domain_id} = $soa{id} if $revrec eq 'n';
4103 $logdata{rdns_id} = $soa{id} if $revrec eq 'y';
4104 $logdata{group_id} = $self->parentID(id => $soa{id}, revrec => $revrec,
4105 type => ($revrec eq 'n' ? 'domain' : 'revzone') );
4106 } else {
4107 $logdata{group_id} = $soa{id};
4108 }
4109 my $parname = ($defrec eq 'y' ? $self->groupName($soa{id}) :
4110 ($revrec eq 'n' ? $self->domainName($soa{id}) : $self->revName($soa{id})) );
4111
4112 # Allow transactions, and raise an exception on errors so we can catch it later.
4113 # Use local to make sure these get "reset" properly on exiting this block
4114 local $dbh->{AutoCommit} = 0;
4115 local $dbh->{RaiseError} = 1;
4116
4117 eval {
4118 if (!$oldsoa) {
4119 # old SOA record is missing for some reason. create a new one.
4120 my $sql = "INSERT INTO "._rectable($defrec, $revrec)." ("._recparent($defrec, $revrec).
4121 ", host, type, val, ttl) VALUES (?,?,6,?,?)";
4122 $dbh->do($sql, undef, ($soa{id}, "$soa{contact}:$soa{prins}",
4123 "$soa{refresh}:$soa{retry}:$soa{expire}:$soa{minttl}", $soa{ttl}) );
4124 $msg = ($defrec eq 'y' ? ($revrec eq 'y' ? 'Default reverse ' : 'Default ') : '').
4125 "SOA missing for $parname; added (ns $soa{prins}, contact $soa{contact}, refresh $soa{refresh},".
4126 " retry $soa{retry}, expire $soa{expire}, minTTL $soa{minttl}, TTL $soa{ttl})";
4127 } else {
4128 my $sql = "UPDATE "._rectable($defrec, $revrec)." SET host=?, val=?, ttl=? WHERE record_id=? AND type=6";
4129 $dbh->do($sql, undef, ("$soa{contact}:$soa{prins}", "$soa{refresh}:$soa{retry}:$soa{expire}:$soa{minttl}",
4130 $soa{ttl}, $oldsoa->{record_id}) );
4131 $msg = "Updated ".($defrec eq 'y' ? ($revrec eq 'y' ? 'default reverse ' : 'default ') : '').
4132 "SOA for $parname: ".
4133 "(ns $oldsoa->{prins}, contact $oldsoa->{contact}, refresh $oldsoa->{refresh},".
4134 " retry $oldsoa->{retry}, expire $oldsoa->{expire}, minTTL $oldsoa->{minttl}, TTL $oldsoa->{ttl}) to ".
4135 "(ns $soa{prins}, contact $soa{contact}, refresh $soa{refresh},".
4136 " retry $soa{retry}, expire $soa{expire}, minTTL $soa{minttl}, TTL $soa{ttl})";
4137 }
4138 $logdata{entry} = $msg;
4139 $self->_log(%logdata);
4140
4141 $dbh->commit;
4142 };
4143 if ($@) {
4144 $msg = $@;
4145 eval { $dbh->rollback; };
4146 $logdata{entry} = "Error updating ".($defrec eq 'y' ? ($revrec eq 'y' ? 'default reverse zone ' : 'default ') : '').
4147 "SOA record for $parname: $msg";
4148 if ($self->{log_failures}) {
4149 $self->_log(%logdata);
4150 $dbh->commit;
4151 }
4152 return ('FAIL', $logdata{entry});
4153 } else {
4154 return ('OK', $msg);
4155 }
4156} # end updateSOA()
4157
4158
4159## DNSDB::getRecLine()
4160# Return all data fields for a zone record in separate elements of a hash
4161# Takes a database handle, default/live flag, forward/reverse flag, and record ID
4162sub getRecLine {
4163 $errstr = '';
4164 my $self = shift;
4165 my $dbh = $self->{dbh};
4166 my $defrec = shift;
4167 my $revrec = shift;
4168 my $id = shift;
4169
4170##fixme: do we need a knob to twist to switch between unix epoch and postgres time string?
4171 my $sql = "SELECT record_id,host,type,val,ttl".
4172 ($defrec eq 'n' ? ',location' : '').
4173 ($revrec eq 'n' ? ',distance,weight,port' : '').
4174 (($defrec eq 'y') ? ',group_id FROM ' : ',domain_id,rdns_id,stamp,stamp < now() AS ispast,expires,stampactive FROM ').
4175 _rectable($defrec,$revrec)." WHERE record_id=?";
4176 my $ret = $dbh->selectrow_hashref($sql, undef, ($id) );
4177
4178 if ($dbh->err) {
4179 $errstr = $DBI::errstr;
4180 return undef;
4181 }
4182
4183 if (!$ret) {
4184 $errstr = "No such record";
4185 return undef;
4186 }
4187
4188 # explicitly set a parent id
4189 if ($defrec eq 'y') {
4190 $ret->{parid} = $ret->{group_id};
4191 } else {
4192 $ret->{parid} = (($revrec eq 'n') ? $ret->{domain_id} : $ret->{rdns_id});
4193 # and a secondary if we have a custom type that lives in both a forward and reverse zone
4194 $ret->{secid} = (($revrec eq 'y') ? $ret->{domain_id} : $ret->{rdns_id}) if $ret->{type} > 65279;
4195 }
4196 $ret->{address} = $ret->{val}; # because.
4197
4198 return $ret;
4199}
4200
4201
4202##fixme: should use above (getRecLine()) to get lines for below?
4203## DNSDB::getRecList()
4204# Return records for a group or zone
4205# Takes a default/live flag, group or zone ID, start,
4206# number of records, sort field, and sort order
4207# Returns a reference to an array of hashes
4208sub getRecList {
4209 $errstr = '';
4210 my $self = shift;
4211 my $dbh = $self->{dbh};
4212
4213 my %args = @_;
4214
4215 $args{revrec} = 'n' if !$args{revrec};
4216 $args{defrec} = 'n' if !$args{defrec};
4217
4218 # RPC callers generally want the "true" IP. Flag argument for those to bypass showrev_arpa
4219##fixme: this will still blow up if some idiot has actually stored .arpa names in the DB.
4220# ... do we care?
4221 $args{rpc} = 0 if !$args{rpc};
4222
4223 # protection against bad or missing arguments
4224 $args{sortorder} = 'ASC' if !$args{sortorder} || !grep /^$args{sortorder}$/, ('ASC','DESC');
4225 my $defsort;
4226 $defsort = 'host' if $args{revrec} eq 'n'; # default sort by host on domain record list
4227 $defsort = 'val' if $args{revrec} eq 'y'; # default sort by IP on revzone record list
4228 $args{sortby} = '' if !$args{sortby};
4229 $args{sortby} = $defsort if !$args{revrec};
4230 $args{sortby} = $defsort if $args{sortby} !~ /^[\w_,.]+$/;
4231 $args{offset} = 0 if !$args{offset} || $args{offset} !~ /^(?:all|\d+)$/;
4232 my $perpage = ($args{nrecs} ? $args{nrecs} : $self->{perpage});
4233
4234##fixme: do we need a knob to twist to switch from unix epoch to postgres time string?
4235 my @bindvars;
4236 my $sql = "SELECT r.record_id,";
4237 # only include the parent info if we don't already know which parent we're in
4238 $sql .= "r.domain_id,r.rdns_id," unless $args{id};
4239 $sql .= "r.host,r.type,r.val,r.ttl";
4240 $sql .= ",l.description AS locname,stamp,r.stamp < now() AS ispast,r.expires,r.stampactive"
4241 if $args{defrec} eq 'n';
4242 $sql .= ",r.distance,r.weight,r.port" if $args{revrec} eq 'n';
4243 $sql .= " FROM "._rectable($args{defrec},$args{revrec})." r ";
4244 $sql .= "INNER JOIN rectypes t ON r.type=t.val "; # for sorting by type alphabetically
4245 $sql .= "LEFT JOIN locations l ON r.location=l.location " if $args{defrec} eq 'n';
4246 $sql .= "WHERE NOT r.type=$reverse_typemap{SOA}";
4247
4248 # "normal" record list
4249 if ($args{id}) {
4250 $sql .= " AND "._recparent($args{defrec},$args{revrec})." = ?";
4251 push @bindvars, $args{id};
4252 }
4253
4254 # Filtering on host/val (mainly normal record list)
4255 if ($args{filter}) {
4256 $sql .= " AND (r.host ~* ? OR r.val ~* ? OR r.host ~* ? OR r.val ~* ?)";
4257 my $tmp = join('.',reverse(split(/\./,$args{filter})));
4258 push @bindvars, ($args{filter},$args{filter});
4259 push @bindvars, ($tmp, $tmp);
4260 }
4261
4262 # Filtering on other fields
4263 foreach (qw(type distance weight port ttl description location)) {
4264 if ($args{$_}) {
4265 $sql .= " AND r.$_ ~* ?";
4266 push @bindvars, $args{$_};
4267 }
4268 }
4269
4270 # whee! multisort means just passing comma-separated fields in sortby!
4271 my $newsort = '';
4272 foreach my $sf (split /,/, $args{sortby}) {
4273 $sf = "r.$sf";
4274 # sort on IP, correctly
4275 $sf =~ s/r\.val/inetlazy(r.val)/;
4276# hmm. do we really need to limit this?
4277# if $args{revrec} eq 'y' && $args{defrec} eq 'n';
4278 $sf =~ s/r\.type/t.alphaorder/; # subtly different from sorting on rectypes.name
4279 $newsort .= ",$sf";
4280 }
4281 $newsort =~ s/^,//;
4282##enhance: pass in ascending/descending sort per-field
4283 $sql .= " ORDER BY $newsort $args{sortorder}";
4284 # ensure consistent ordering by sorting on record_id too
4285 $sql .= ", record_id $args{sortorder}";
4286
4287 # Offset/pagination
4288 $sql .= ($args{offset} eq 'all' ? '' : " LIMIT $perpage OFFSET ".$args{offset}*$perpage);
4289
4290 my @working;
4291 my $recsth = $dbh->prepare($sql);
4292 $recsth->execute(@bindvars);
4293 while (my $rec = $recsth->fetchrow_hashref) {
4294 if (!$args{rpc} && $args{revrec} eq 'y' && $args{defrec} eq 'n' &&
4295 ($self->{showrev_arpa} eq 'record' || $self->{showrev_arpa} eq 'all') &&
4296 $rec->{val} !~ /\.arpa$/ ) {
4297 # skip all reverse zone .arpa "hostnames" since they're already .arpa names.
4298##enhance: extend {showrev_arpa} eq 'record' to specify record types
4299 my $tmpip = new NetAddr::IP $rec->{val} if $rec->{val} =~ /^(?:[\d.\/]+|[a-fA-F0-9:\/]+)$/;
4300 $rec->{val} = DNSDB::_ZONE($tmpip, 'ZONE', 'r', '.').($tmpip->{isv6} ? '.ip6.arpa' : '.in-addr.arpa') if $tmpip;
4301 }
4302 push @working, $rec;
4303 }
4304 return \@working;
4305} # end getRecList()
4306
4307
4308## DNSDB::getRecCount()
4309# Return count of non-SOA records in zone (or default records in a group)
4310# Takes a database handle, default/live flag, reverse/forward flag, group/domain ID,
4311# and optional filtering modifier
4312# Returns the count
4313sub getRecCount {
4314 my $self = shift;
4315 my $dbh = $self->{dbh};
4316
4317 my %args = @_;
4318
4319 $args{defrec} = 'n' if !$args{defrec};
4320 $args{revrec} = 'n' if !$args{revrec};
4321
4322 my @bindvars;
4323 my $sql = "SELECT count(*) FROM ".
4324 _rectable($args{defrec},$args{revrec}).
4325 " r WHERE NOT type=$reverse_typemap{SOA}";
4326 if ($args{id}) {
4327 $sql .= " AND "._recparent($args{defrec},$args{revrec})." = ?";
4328 push @bindvars, $args{id};
4329 }
4330
4331 # Filtering on host/val (mainly normal record list)
4332 if ($args{filter}) {
4333 $sql .= " AND (r.host ~* ? OR r.val ~* ? OR r.host ~* ? OR r.val ~* ?)";
4334 my $tmp = join('.',reverse(split(/\./,$args{filter})));
4335 push @bindvars, ($args{filter},$args{filter});
4336 push @bindvars, ($tmp, $tmp);
4337 }
4338
4339 # Filtering on other fields
4340 foreach (qw(type distance weight port ttl description)) {
4341 if ($args{$_}) {
4342 $sql .= " AND $_ ~* ?";
4343 push @bindvars, $args{$_};
4344 }
4345 }
4346
4347 my ($count) = $dbh->selectrow_array($sql, undef, (@bindvars) );
4348
4349 return $count;
4350
4351} # end getRecCount()
4352
4353
4354## DNSDB::addRec()
4355# Add a new record to a domain or a group's default records
4356# Takes a database handle, default/live flag, group/domain ID,
4357# host, type, value, and TTL
4358# Some types require additional detail: "distance" for MX and SRV,
4359# and weight/port for SRV
4360# Returns a status code and detail message in case of error
4361##fixme: pass a hash with the record data, not a series of separate values
4362sub addRec {
4363 $errstr = '';
4364 my $self = shift;
4365 my $dbh = $self->{dbh};
4366 my $defrec = shift;
4367 my $revrec = shift;
4368 my $id = shift; # parent (group_id for defrecs, rdns_id for reverse records,
4369 # domain_id for domain records)
4370
4371 my $host = shift;
4372 my $rectype = shift; # reference so we can coerce it if "+"-types can't find both zones
4373 my $val = shift;
4374 my $ttl = shift;
4375 my $location = shift;
4376 $location = '' if !$location;
4377
4378 my $expires = shift || '';
4379 $expires = 1 if $expires eq 'until'; # Turn some special values into the appropriate booleans.
4380 $expires = 0 if $expires eq 'after';
4381 my $stamp = shift;
4382 $stamp = '' if !$stamp; # Timestamp should be a string at this point.
4383
4384 # extra safety net - apparently RPC can squeak this by. O_o
4385 return ('FAIL', "host must contain a value") if !$$host;
4386 return ('FAIL', "val must contain a value") if !$$val;
4387
4388 # Spaces are evil.
4389 $$host =~ s/^\s+//;
4390 $$host =~ s/\s+$//;
4391 if ($typemap{$$rectype} ne 'TXT') {
4392 # Leading or trailng spaces could be legit in TXT records.
4393 $$val =~ s/^\s+//;
4394 $$val =~ s/\s+$//;
4395 }
4396
4397 _caseclean($rectype, $host, $val, $defrec, $revrec) if $self->{lowercase};
4398
4399 # prep for validation
4400 my $addr = NetAddr::IP->new($$val) if _maybeip($val);
4401 $$host =~ s/\.+$//; # FQDNs ending in . are an internal detail, and really shouldn't be exposed in the UI.
4402
4403 my $domid = 0;
4404 my $revid = 0;
4405
4406 my $retcode = 'OK'; # assume everything will go OK
4407 my $retmsg = '';
4408
4409 # do simple validation first
4410 return ('FAIL', "TTL must be numeric") unless $ttl =~ /^-?\d+$/;
4411
4412 # Collect these even if we're only doing a simple A record so we can call *any* validation sub
4413 my $dist = shift;
4414 my $weight = shift;
4415 my $port = shift;
4416
4417 my $fields;
4418 my @vallist;
4419
4420 # Call the validation sub for the type requested.
4421 ($retcode,$retmsg) = $validators{$$rectype}($self, defrec => $defrec, revrec => $revrec, id => $id,
4422 host => $host, rectype => $rectype, val => $val, addr => $addr,
4423 dist => \$dist, port => \$port, weight => \$weight,
4424 fields => \$fields, vallist => \@vallist);
4425
4426 return ($retcode,$retmsg) if $retcode eq 'FAIL';
4427
4428 # Set up database fields and bind parameters
4429 $fields .= "host,type,val,ttl,"._recparent($defrec,$revrec);
4430 push @vallist, ($$host,$$rectype,$$val,$ttl,$id);
4431
4432 if ($defrec eq 'n') {
4433 # locations are not for default records, silly coder!
4434 $fields .= ",location";
4435 push @vallist, $location;
4436 # timestamps are rare.
4437 if ($stamp) {
4438 $fields .= ",stamp,expires,stampactive";
4439 push @vallist, $stamp, $expires, 'y';
4440 } else {
4441 $fields .= ",stampactive";
4442 push @vallist, 'n';
4443 }
4444 }
4445
4446 # a little magic to get the right number of ? placeholders based on how many values we're providing
4447 my $vallen = '?'.(',?'x$#vallist);
4448
4449 # Put together the success log entry. We have to use this horrible kludge
4450 # because domain_id and rdns_id may or may not be present, and if they are,
4451 # they're not at a guaranteed consistent index in the array. wheee!
4452 my %logdata;
4453 my @ftmp = split /,/, $fields;
4454 for (my $i=0; $i <= $#vallist; $i++) {
4455 $logdata{domain_id} = $vallist[$i] if $ftmp[$i] eq 'domain_id';
4456 $logdata{rdns_id} = $vallist[$i] if $ftmp[$i] eq 'rdns_id';
4457 }
4458 $logdata{group_id} = $id if $defrec eq 'y';
4459 $logdata{group_id} = $self->parentID(id => $id, type => ($revrec eq 'n' ? 'domain' : 'revzone'), revrec => $revrec)
4460 if $defrec eq 'n';
4461 $logdata{entry} = "Added ".($defrec eq 'y' ? 'default record' : 'record');
4462 # Log reverse records to match the formal .arpa tree
4463 if ($revrec eq 'y') {
4464 $logdata{entry} .= " '$$val $typemap{$$rectype} $$host";
4465 } else {
4466 $logdata{entry} .= " '$$host $typemap{$$rectype} $$val";
4467 }
4468
4469 $logdata{entry} .= " [distance $dist]" if $typemap{$$rectype} eq 'MX';
4470 $logdata{entry} .= " [priority $dist] [weight $weight] [port $port]"
4471 if $typemap{$$rectype} eq 'SRV';
4472 $logdata{entry} .= "', TTL $ttl";
4473 $logdata{entry} .= ", location ".$self->getLoc($location)->{description} if $location;
4474 $logdata{entry} .= ($expires ? ', expires at ' : ', valid after ').$stamp if $stamp;
4475
4476 # Allow transactions, and raise an exception on errors so we can catch it later.
4477 # Use local to make sure these get "reset" properly on exiting this block
4478 local $dbh->{AutoCommit} = 0;
4479 local $dbh->{RaiseError} = 1;
4480
4481 eval {
4482 $dbh->do("INSERT INTO "._rectable($defrec, $revrec)." ($fields) VALUES ($vallen)",
4483 undef, @vallist);
4484 $self->_log(%logdata);
4485 $dbh->commit;
4486 };
4487 if ($@) {
4488 my $msg = $@;
4489 eval { $dbh->rollback; };
4490 if ($self->{log_failures}) {
4491 $logdata{entry} = "Failed adding ".($defrec eq 'y' ? 'default ' : '').
4492 "record '$$host $typemap{$$rectype} $$val', TTL $ttl ($msg)";
4493 $self->_log(%logdata);
4494 $dbh->commit;
4495 }
4496 return ('FAIL',$msg);
4497 }
4498
4499 $resultstr = $logdata{entry};
4500 return ($retcode, $retmsg);
4501
4502} # end addRec()
4503
4504
4505## DNSDB::updateRec()
4506# Update a record
4507# Takes a database handle, default and reverse flags, record ID, immediate parent ID, and new record data.
4508# Returns a status code and message
4509sub updateRec {
4510 $errstr = '';
4511
4512 my $self = shift;
4513 my $dbh = $self->{dbh};
4514
4515 my $defrec = shift;
4516 my $revrec = shift;
4517 my $id = shift;
4518 my $parid = shift; # immediate parent entity that we're descending from to update the record
4519
4520 # all records have these
4521 my $host = shift;
4522 my $hostbk = $$host; # Keep a backup copy of the original, so we can WARN if the update mangles the domain
4523 my $rectype = shift;
4524 my $val = shift;
4525 my $ttl = shift;
4526 my $location = shift; # may be empty/null/undef depending on caller
4527 $location = '' if !$location;
4528
4529 my $expires = shift || '';
4530 $expires = 1 if $expires eq 'until'; # Turn some special values into the appropriate booleans.
4531 $expires = 0 if $expires eq 'after';
4532 my $stamp = shift;
4533 $stamp = '' if !$stamp; # Timestamp should be a string at this point.
4534
4535 # just set it to an empty string; failures will be caught later.
4536 $$host = '' if !$$host;
4537
4538 # Spaces are evil.
4539 $$host =~ s/^\s+//;
4540 $$host =~ s/\s+$//;
4541 if ($typemap{$$rectype} ne 'TXT') {
4542 # Leading or trailng spaces could be legit in TXT records.
4543 $$val =~ s/^\s+//;
4544 $$val =~ s/\s+$//;
4545 }
4546
4547 _caseclean($rectype, $host, $val, $defrec, $revrec) if $self->{lowercase};
4548
4549 # prep for validation
4550 my $addr = NetAddr::IP->new($$val) if _maybeip($val);
4551 $$host =~ s/\.+$//; # FQDNs ending in . are an internal detail, and really shouldn't be exposed in the UI.
4552
4553 my $domid = 0;
4554 my $revid = 0;
4555
4556 my $retcode = 'OK'; # assume everything will go OK
4557 my $retmsg = '';
4558
4559 # do simple validation first
4560 return ('FAIL', "TTL must be numeric") unless $ttl =~ /^-?\d+$/;
4561
4562 # only MX and SRV will use these
4563 my $dist = shift || 0;
4564 my $weight = shift || 0;
4565 my $port = shift || 0;
4566
4567 my $fields;
4568 my @vallist;
4569
4570 # get old record data so we have the right parent ID
4571 # and for logging (eventually)
4572 my $oldrec = $self->getRecLine($defrec, $revrec, $id);
4573
4574 # Call the validation sub for the type requested.
4575 # Note the ID to pass here is the *parent*, not the record
4576 ($retcode,$retmsg) = $validators{$$rectype}($self, defrec => $defrec, revrec => $revrec,
4577 id => ($defrec eq 'y' ? $oldrec->{group_id} : ($revrec eq 'n' ? $oldrec->{domain_id} : $oldrec->{rdns_id})),
4578 host => $host, rectype => $rectype, val => $val, addr => $addr,
4579 dist => \$dist, port => \$port, weight => \$weight,
4580 fields => \$fields, vallist => \@vallist,
4581 update => $id);
4582
4583 return ($retcode,$retmsg) if $retcode eq 'FAIL';
4584
4585 # Set up database fields and bind parameters. Note only the optional fields
4586 # (distance, weight, port, secondary parent ID) are added in the validation call above
4587 $fields .= "host,type,val,ttl,"._recparent($defrec,$revrec);
4588 push @vallist, ($$host,$$rectype,$$val,$ttl,
4589 ($defrec eq 'y' ? $oldrec->{group_id} : ($revrec eq 'n' ? $oldrec->{domain_id} : $oldrec->{rdns_id})) );
4590
4591 if ($defrec eq 'n') {
4592 # locations are not for default records, silly coder!
4593 $fields .= ",location";
4594 push @vallist, $location;
4595 # timestamps are rare.
4596 if ($stamp) {
4597 $fields .= ",stamp,expires,stampactive";
4598 push @vallist, $stamp, $expires, 'y';
4599 } else {
4600 $fields .= ",stampactive";
4601 push @vallist, 'n';
4602 }
4603 }
4604
4605 # hack hack PTHUI
4606 # need to forcibly make sure we disassociate a record with a parent it's no longer related to.
4607 # eg, PTR records may not have a domain parent, or A/AAAA records may not have a revzone parent.
4608 # needed for crossover types that got coerced down to "standard" types due to data changes
4609 # need to *avoid* funky records being updated like A/AAAA records in revzones, or PTRs in forward zones.
4610 if ($defrec eq 'n' && $oldrec->{type} > 65000) {
4611 if ($$rectype == $reverse_typemap{PTR}) {
4612 $fields .= ",domain_id";
4613 push @vallist, 0;
4614 }
4615 if ($$rectype == $reverse_typemap{A} || $$rectype == $reverse_typemap{AAAA}) {
4616 $fields .= ",rdns_id";
4617 push @vallist, 0;
4618 }
4619 }
4620 # fix fat-finger-originated record type changes
4621 if ($$rectype == 65285) { # delegation
4622 $fields .= ",rdns_id" if $revrec eq 'n';
4623 $fields .= ",domain_id" if $revrec eq 'y';
4624 push @vallist, 0;
4625 }
4626 # ... and now make sure we *do* associate a record with the "calling" parent
4627 if ($defrec eq 'n') {
4628 $domid = $parid if $revrec eq 'n';
4629 $revid = $parid if $revrec eq 'y';
4630 }
4631
4632 # Put together the success log entry. Horrible kludge from addRec() copied as-is since
4633 # we don't know whether the passed arguments or retrieved values for domain_id and rdns_id
4634 # will be maintained (due to "not-in-zone" validation changes)
4635 my %logdata;
4636 $logdata{domain_id} = $domid;
4637 $logdata{rdns_id} = $revid;
4638 my @ftmp = split /,/, $fields;
4639 for (my $i=0; $i <= $#vallist; $i++) {
4640 $logdata{domain_id} = $vallist[$i] if $ftmp[$i] eq 'domain_id';
4641 $logdata{rdns_id} = $vallist[$i] if $ftmp[$i] eq 'rdns_id';
4642 }
4643 $logdata{group_id} = $parid if $defrec eq 'y';
4644 $logdata{group_id} = $self->parentID(id => $parid, type => ($revrec eq 'n' ? 'domain' : 'revzone'), revrec => $revrec)
4645 if $defrec eq 'n';
4646 $logdata{entry} = "Updated ".($defrec eq 'y' ? 'default record' : 'record')." from\n";
4647 # Log reverse records "naturally", since they're stored, um, unnaturally.
4648 if ($revrec eq 'y') {
4649 $logdata{entry} .= " '$oldrec->{val} $typemap{$oldrec->{type}} $oldrec->{host}";
4650 } else {
4651 $logdata{entry} .= " '$oldrec->{host} $typemap{$oldrec->{type}} $oldrec->{val}";
4652 }
4653 $logdata{entry} .= " [distance $oldrec->{distance}]" if $typemap{$oldrec->{type}} eq 'MX';
4654 $logdata{entry} .= " [priority $oldrec->{distance}] [weight $oldrec->{weight}] [port $oldrec->{port}]"
4655 if $typemap{$oldrec->{type}} eq 'SRV';
4656 $logdata{entry} .= "', TTL $oldrec->{ttl}";
4657 $logdata{entry} .= ", location ".$self->getLoc($oldrec->{location})->{description} if $oldrec->{location};
4658 $logdata{entry} .= ($oldrec->{expires} ? ', expires at ' : ', valid after ').$oldrec->{stamp}
4659 if $oldrec->{stampactive};
4660 $logdata{entry} .= "\nto\n";
4661 # Log reverse records "naturally", since they're stored, um, unnaturally.
4662 if ($revrec eq 'y') {
4663 $logdata{entry} .= "'$$val $typemap{$$rectype} $$host";
4664 } else {
4665 $logdata{entry} .= "'$$host $typemap{$$rectype} $$val";
4666 }
4667 $logdata{entry} .= " [distance $dist]" if $typemap{$$rectype} eq 'MX';
4668 $logdata{entry} .= " [priority $dist] [weight $weight] [port $port]" if $typemap{$$rectype} eq 'SRV';
4669 $logdata{entry} .= "', TTL $ttl";
4670 $logdata{entry} .= ", location ".$self->getLoc($location)->{description} if $location;
4671 $logdata{entry} .= ($expires ? ', expires at ' : ', valid after ').$stamp if $stamp;
4672
4673 local $dbh->{AutoCommit} = 0;
4674 local $dbh->{RaiseError} = 1;
4675
4676 # Fiddle the field list into something suitable for updates
4677 $fields =~ s/,/=?,/g;
4678 $fields .= "=?";
4679
4680 eval {
4681 $dbh->do("UPDATE "._rectable($defrec,$revrec)." SET $fields WHERE record_id=?", undef, (@vallist, $id) );
4682 $self->_log(%logdata);
4683 $dbh->commit;
4684 };
4685 if ($@) {
4686 my $msg = $@;
4687 eval { $dbh->rollback; };
4688 if ($self->{log_failures}) {
4689 $logdata{entry} = "Failed updating ".($defrec eq 'y' ? 'default ' : '').
4690 "record '$oldrec->{host} $typemap{$oldrec->{type}} $oldrec->{val}', TTL $oldrec->{ttl} ($msg)";
4691 $self->_log(%logdata);
4692 $dbh->commit;
4693 }
4694 return ('FAIL', $msg);
4695 }
4696
4697 $resultstr = $logdata{entry};
4698 return ($retcode, $retmsg);
4699} # end updateRec()
4700
4701
4702## DNSDB::downconvert()
4703# A mostly internal (not exported) semiutilty sub to downconvert from pseudotype <x>
4704# to a compatible component type. Only a handful of operations are valid, anything
4705# else is a null-op.
4706# Takes the record ID and the new type. Returns boolean.
4707sub downconvert {
4708 my $self = shift;
4709 my $dbh = $self->{dbh};
4710 my $recid = shift;
4711 my $newtype = shift;
4712
4713 # also, only work on live records; little to no value trying to do this on default records.
4714 my $rec = $self->getRecLine('n', 'y', $recid);
4715
4716 # hm?
4717 #return 1 if !$rec;
4718
4719 return 1 if $rec->{type} < 65000; # Only the reverse-record pseudotypes can be downconverted
4720 return 1 if $rec->{type} == 65282; # Nowhere to go
4721
4722 my $delpar;
4723 my @sqlargs;
4724 if ($rec->{type} == 65280) {
4725 return 1 if $newtype != 1 && $newtype != 12;
4726 $delpar = ($newtype == 1 ? 'rdns_id' : 'domain_id');
4727 push @sqlargs, 0, $newtype, $recid;
4728 } elsif ($rec->{type} == 65281) {
4729 return 1 if $newtype != 28 && $newtype != 12;
4730 $delpar = ($newtype == 28 ? 'rdns_id' : 'domain_id');
4731 push @sqlargs, 0, $newtype, $recid;
4732 } elsif ($rec->{type} == 65283) {
4733 return 1 if $newtype != 65282;
4734 $delpar = 'rdns_id';
4735 } elsif ($rec->{type} == 65284) {
4736 return 1 if $newtype != 65282;
4737 $delpar = 'rdns_id';
4738 } else {
4739 # Your llama is on fire.
4740 }
4741
4742 local $dbh->{AutoCommit} = 0;
4743 local $dbh->{RaiseError} = 1;
4744
4745 eval {
4746 $dbh->do("UPDATE records SET $delpar = ?, type = ? WHERE record_id = ?", undef, @sqlargs);
4747 $self->_log(domain_id => $rec->{domain_id}, rdns_id => $rec->{rdns_id},
4748 group_id => $self->parentID(id => $rec->{rdns_id}, type => 'revzone', revrec => 'y'),
4749 entry => "'$rec->{host} $typemap{$rec->{type}} $rec->{val}' downconverted to ".
4750 "'$rec->{host} $typemap{$newtype} $rec->{val}'");
4751 $dbh->commit;
4752 };
4753 if ($@) {
4754 $errstr = $@;
4755 eval { $dbh->rollback; };
4756 return 0;
4757 }
4758 return 1;
4759} # end downconvert()
4760
4761
4762## DNSDB::delRec()
4763# Delete a record.
4764# Takes a default/live flag, forward/reverse flag, and the ID of the record to delete.
4765sub delRec {
4766 $errstr = '';
4767 my $self = shift;
4768 my $dbh = $self->{dbh};
4769 my $defrec = shift;
4770 my $revrec = shift;
4771 my $id = shift;
4772
4773 my $oldrec = $self->getRecLine($defrec, $revrec, $id);
4774
4775 # Allow transactions, and raise an exception on errors so we can catch it later.
4776 # Use local to make sure these get "reset" properly on exiting this block
4777 local $dbh->{AutoCommit} = 0;
4778 local $dbh->{RaiseError} = 1;
4779
4780 # Put together the log entry
4781 my %logdata;
4782 $logdata{domain_id} = $oldrec->{domain_id};
4783 $logdata{rdns_id} = $oldrec->{rdns_id};
4784 $logdata{group_id} = $oldrec->{group_id} if $defrec eq 'y';
4785 $logdata{group_id} = $self->parentID(id => ($revrec eq 'n' ? $oldrec->{domain_id} : $oldrec->{rdns_id}),
4786 type => 'domain', revrec => $revrec)
4787 if $defrec eq 'n';
4788 $logdata{entry} = "Deleted ".($defrec eq 'y' ? 'default record ' : 'record ').
4789 "'$oldrec->{host} $typemap{$oldrec->{type}} $oldrec->{val}";
4790 $logdata{entry} .= " [distance $oldrec->{distance}]" if $typemap{$oldrec->{type}} eq 'MX';
4791 $logdata{entry} .= " [priority $oldrec->{distance}] [weight $oldrec->{weight}] [port $oldrec->{port}]"
4792 if $typemap{$oldrec->{type}} eq 'SRV';
4793 $logdata{entry} .= "', TTL $oldrec->{ttl}";
4794 $logdata{entry} .= ", location ".$self->getLoc($oldrec->{location})->{description} if $oldrec->{location};
4795
4796 eval {
4797 my $sth = $dbh->do("DELETE FROM "._rectable($defrec,$revrec)." WHERE record_id=?", undef, ($id));
4798 $self->_log(%logdata);
4799 $dbh->commit;
4800 };
4801 if ($@) {
4802 my $msg = $@;
4803 eval { $dbh->rollback; };
4804 if ($self->{log_failures}) {
4805 $logdata{entry} = "Error deleting ".($defrec eq 'y' ? 'default record' : 'record').
4806 " '$oldrec->{host} $typemap{$oldrec->{type}} $oldrec->{val}', TTL $oldrec->{ttl} ($msg)";
4807 $self->_log(%logdata);
4808 $dbh->commit;
4809 }
4810 return ('FAIL', $msg);
4811 }
4812
4813 return ('OK',$logdata{entry});
4814} # end delRec()
4815
4816
4817## DNSDB::getLogCount()
4818# Get a count of log entries
4819# Takes a database handle and a hash containing at least:
4820# - Entity identifier and entity type as the primary log "slice"
4821sub getLogCount {
4822 my $self = shift;
4823 return $self->getLogEntries(@_, count => 1);
4824} # end getLogCount()
4825
4826
4827## DNSDB::getLogEntries()
4828# Get a list of log entries
4829# Takes arguments as with getLogCount() above, plus optional:
4830# - "count" flag
4831# OR
4832# - sort field
4833# - sort order
4834# - offset for pagination
4835sub getLogEntries {
4836 my $self = shift;
4837 my $dbh = $self->{dbh};
4838
4839 my %args = @_;
4840
4841 my @filterargs;
4842
4843 # fail if the prime id type is missing or invalid
4844 $errstr = "Missing primary log slice type";
4845 return if !$args{logtype};
4846 $args{logtype} = 'revzone' if $args{logtype} eq 'rdns'; # hack pthui
4847 $args{logtype} = 'domain' if $args{logtype} eq 'dom'; # hack pthui
4848 $errstr = "Invalid primary log slice type";
4849 return if !grep /^$args{logtype}$/, ('group', 'domain', 'revzone', 'user');
4850
4851 # fail if we don't have a prime ID to look for log entries for
4852 $errstr = "Missing ID for primary log slice";
4853 return if !($args{id} || $args{fname});
4854
4855 # Sorting defaults
4856 $args{sortorder} = 'DESC' if !$args{sortorder} || !grep /^$args{sortorder}$/, ('ASC','DESC');
4857 $args{sortby} = 'stamp' if !$args{sortby} || $args{sortby} !~ /^[\w_.]+$/;
4858 $args{offset} = 0 if !$args{offset} || $args{offset} !~ /^(?:all|\d+)$/;
4859
4860 my %sortmap = (fname => 'name', username => 'email', entry => 'entry', stamp => 'stamp',
4861 revzone => 'revnet', domain => 'domain');
4862 $args{sortby} = $sortmap{$args{sortby}};
4863
4864 push @filterargs, $args{filter} if $args{filter};
4865 my $sql;
4866 if ($args{count}) {
4867 $sql = "SELECT count(*) FROM log l ";
4868 } else {
4869 $sql = "SELECT l.user_id AS userid, l.name AS userfname, d.domain, l.domain_id, r.revnet AS revzone, ".
4870 "l.rdns_id, l.entry AS logentry, date_trunc('second',l.stamp) AS logtime ".
4871 "FROM log l ".
4872 "LEFT JOIN domains d ON l.domain_id = d.domain_id ".
4873 "LEFT JOIN revzones r ON l.rdns_id = r.rdns_id ";
4874 }
4875
4876 # decide which ID argument to use. Only use the "full name" if no normal ID is present
4877 my $idarg;
4878 if ($args{id}) {
4879 $sql .= "WHERE l.$id_col{$args{logtype}} = ? ";
4880 $idarg = $args{id};
4881 } else {
4882 $sql .= "WHERE l.name = ? ";
4883 $idarg = $args{fname};
4884 }
4885
4886 # add the entry filter, if any
4887 $sql .= ($args{filter} ? " AND entry ~* ?" : '');
4888
4889 # Limit scope based on group. Mainly useful for ltype==user, so subgroup
4890 # users can see what the deities in parent groups have done to their domains.
4891 if ($args{group} != 1) {
4892 my @grouplist;
4893 $self->getChildren($args{group}, \@grouplist);
4894 my $groupset = join(',', $args{group}, @grouplist);
4895 $sql .= " AND l.group_id IN ($groupset)";
4896 }
4897
4898 if ($args{count}) {
4899 my ($count) = $dbh->selectrow_array($sql, undef, ($idarg, @filterargs) );
4900 $errstr = $dbh->errstr if !$count;
4901 return $count;
4902 } else {
4903 $sql .= " ORDER BY $args{sortby} $args{sortorder}, log_id $args{sortorder}".
4904 ($args{offset} eq 'all' ? '' : " LIMIT $self->{perpage} OFFSET ".$args{offset}*$self->{perpage});
4905 my $loglist = $dbh->selectall_arrayref($sql, { Slice => {} }, ($idarg, @filterargs) );
4906 $errstr = $dbh->errstr if !$loglist;
4907 return $loglist;
4908 }
4909
4910 # Your llama is on fire
4911
4912} # end getLogEntries()
4913
4914
4915# a collection of joins for the record search
4916our $recsearchsqlbase = q(
4917FROM records r
4918LEFT JOIN domains d ON r.domain_id = d.domain_id
4919 LEFT JOIN groups g1 ON d.group_id = g1.group_id
4920LEFT JOIN revzones z ON r.rdns_id = z.rdns_id
4921 LEFT JOIN groups g2 on z.group_id = g2.group_id
4922JOIN rectypes t ON r.type = t.val
4923LEFT JOIN locations l ON r.location = l.location
4924WHERE r.type <> 6 AND (r.host ~* ? OR r.val ~* ?)
4925);
4926
4927
4928## DNSDB::recSearchCount()
4929# Get a total count for a global record search
4930# Takes a hash with the search string and the login group of the user
4931sub recSearchCount {
4932 my $self = shift;
4933 my $dbh = $self->{dbh};
4934 my %args = @_;
4935
4936 my $sql = "SELECT count(*)".$recsearchsqlbase;
4937
4938 # Limit scope based on group
4939 if ($args{group} != 1) {
4940 my @grouplist;
4941 $self->getChildren($args{group}, \@grouplist);
4942 my $groupset = join(',', $args{group}, @grouplist);
4943 # oh my aching HEAD. there has to be a better way to do conditions on joined tables...
4944 $sql .= "AND (
4945 (g1.group_id IN ($groupset) AND g2.group_id IN ($groupset)) OR
4946 (g1.group_id IN ($groupset) AND g2.group_id IS NULL) OR
4947 (g1.group_id IS NULL AND g2.group_id IN ($groupset))
4948 )
4949";
4950 }
4951
4952 my $count = $dbh->selectrow_array($sql, undef, $args{searchfor}, $args{searchfor});
4953 $errstr = $dbh->errstr if !$count;
4954 return $count;
4955
4956} # end recSearchCount()
4957
4958
4959## DNSDB::recSearch()
4960# Find records matching the search string
4961# Takes a hash with the search string, login group of the user, pagination offset, sort field,
4962# and sort direction
4963# Returns a reference to a list of hashrefs
4964sub recSearch {
4965 my $self = shift;
4966 my $dbh = $self->{dbh};
4967 my %args = @_;
4968
4969 my $sql = q(SELECT
4970 r.domain_id, d.domain, g1.group_name AS domgroup,
4971 r.rdns_id, z.revnet AS revzone, g2.group_name AS revgroup,
4972 r.host, t.name AS rectype, r.val, l.description AS location, r.record_id).
4973 $recsearchsqlbase;
4974
4975 # Limit scope based on group
4976 if ($args{group} != 1) {
4977 my @grouplist;
4978 $self->getChildren($args{group}, \@grouplist);
4979 my $groupset = join(',', $args{group}, @grouplist);
4980 # oh my aching HEAD. there has to be a better way to do conditions on joined tables...
4981 $sql .= "AND (
4982 (g1.group_id IN ($groupset) AND g2.group_id IN ($groupset)) OR
4983 (g1.group_id IN ($groupset) AND g2.group_id IS NULL) OR
4984 (g1.group_id IS NULL AND g2.group_id IN ($groupset))
4985 )
4986";
4987 }
4988
4989 # mixed tables means this isn't a simple prefix like the regular record list filter. :/
4990 my %sortmap = (
4991 domain => 'd.domain',
4992 revzone => 'z.revnet',
4993 host => 'r.host',
4994 type => 't.name',
4995 val => 'inetlazy(r.val)',
4996 location => 'r.location',
4997 );
4998
4999 # Sorting defaults
5000 $args{sortorder} = 'ASC' if !$args{sortorder} || !grep /^$args{sortorder}$/, ('ASC','DESC');
5001 $args{sortby} = 'r.host' if !$args{sortby} || $args{sortby} !~ /^[\w_.]+$/;
5002 $args{offset} = 0 if !$args{offset} || $args{offset} !~ /^(?:all|\d+)$/;
5003
5004 $args{sortby} = $sortmap{$args{sortby}} if $args{sortby} !~ /\./;
5005
5006 # Add sort and offset to SQL
5007 $sql .= "ORDER BY $args{sortby} $args{sortorder},record_id ASC\n";
5008 $sql .= ($args{offset} eq 'all' ? '' : "LIMIT $self->{perpage} OFFSET ".$args{offset}*$self->{perpage});
5009
5010##fixme: should probably sent the warning somewhere else
5011 return $dbh->selectall_arrayref($sql, { Slice => {} }, $args{searchfor}, $args{searchfor})
5012 or warn $dbh->errstr;
5013
5014} # end recSearch()
5015
5016
5017## DNSDB::getRevPattern()
5018# Get the narrowest template pattern applicable to a passed CIDR address (may be a netblock or an IP)
5019sub getRevPattern {
5020 my $self = shift;
5021 my $dbh = $self->{dbh};
5022 my $cidr = shift;
5023 my %args = @_;
5024 $args{group} = 1 if !$args{group}; # just in case
5025 $args{location} = '' if !$args{location};
5026
5027 # for speed! Casting and comparing even ~7K records takes ~2.5s, so narrow it down to one revzone first.
5028 my ($revid) = $dbh->selectrow_array("SELECT rdns_id FROM revzones WHERE revnet >>= ?",
5029 undef, ($cidr) );
5030
5031##fixme? may need to narrow things down more by octet-chopping and doing text comparisons before casting.
5032 my ($revpatt) = $dbh->selectrow_array("SELECT host FROM records ".
5033 "WHERE (type in (12,65280,65281,65282,65283,65284)) AND rdns_id = ? ".
5034 "AND location = ? AND inetlazy(val) >>= ? ".
5035 "ORDER BY inetlazy(val) DESC LIMIT 1",
5036 undef, ($revid, $args{location}, $cidr) );
5037
5038 return $revpatt;
5039} # end getRevPattern()
5040
5041
5042## DNSDB::getRevSet()
5043# Return the unique per-IP reverse hostnames, if any, for the passed
5044# CIDR address (may be a netblock or an IP)
5045sub getRevSet {
5046 my $self = shift;
5047 my $dbh = $self->{dbh};
5048 my $cidr = shift;
5049 my %args = @_;
5050 $args{group} = 1 if !$args{group}; # just in case
5051 $args{location} = '' if !$args{location};
5052
5053 # for speed! Casting and comparing even ~7K records takes ~2.5s, so narrow it down to one revzone first.
5054 my ($revid) = $dbh->selectrow_array("SELECT rdns_id FROM revzones WHERE revnet >>= ?",
5055 undef, ($cidr) );
5056
5057 $cidr = new NetAddr::IP $cidr;
5058 if ($cidr->num > 256) { # should also catch v6!
5059 # Even reverse entries for a v4 /24 of IPs is a bit much. I don't expect
5060 # there to be a sane reason to retrive more than a /27 at once, really.
5061 # v6 is going to be hairy no matter how you slice it.
5062 $errstr = "Reverse hostname detail range too large";
5063 return;
5064 }
5065
5066 my $sth = $dbh->prepare("SELECT val, host FROM records ".
5067 "WHERE (type in (12,65280,65281,65282,65283,65284)) AND rdns_id = ? AND location = ? AND inetlazy(val) = ?");
5068
5069 my @ret;
5070 foreach my $ip (@{$cidr->splitref()}) {
5071 $sth->execute($revid, $args{location}, $ip);
5072 my @data = $sth->fetchrow_array();
5073 my %row;
5074 if (@data) {
5075 $row{r_ip} = $data[0];
5076 $row{iphost} = $data[1];
5077 } else {
5078 $row{r_ip} = $ip->addr;
5079 $row{iphost} = '';
5080 }
5081 push @ret, \%row;
5082 }
5083
5084 return \@ret;
5085} # end getRevSet()
5086
5087
5088## DNSDB::getTypelist()
5089# Get a list of record types for various UI dropdowns
5090# Takes database handle, forward/reverse/lookup flag, and optional "tag as selected" indicator (defaults to A)
5091# Returns an arrayref to list of hashrefs perfect for HTML::Template
5092sub getTypelist {
5093 my $self = shift;
5094 my $dbh = $self->{dbh};
5095 my $recgroup = shift;
5096 my $type = shift || $reverse_typemap{A};
5097
5098 # also accepting $webvar{revrec}!
5099 $recgroup = 'f' if $recgroup eq 'n';
5100 $recgroup = 'r' if $recgroup eq 'y';
5101
5102 my $sql = "SELECT val,name FROM rectypes WHERE ";
5103 if ($recgroup eq 'r') {
5104 # reverse zone types
5105 $sql .= "stdflag=2 OR stdflag=3";
5106 } elsif ($recgroup eq 'l') {
5107 # DNS lookup types. Note we avoid our custom types >= 65280, since those are entirely internal.
5108 $sql .= "(stdflag=1 OR stdflag=2 OR stdflag=3) AND val < 65280";
5109 } else {
5110 # default; forward zone types. technically $type eq 'f' but not worth the error message.
5111 $sql .= "stdflag=1 OR stdflag=2";
5112 $sql .= " AND val < 65280" if $recgroup eq 'fo'; # An extra flag to trim off the pseudotypes as well.
5113 }
5114 $sql .= " ORDER BY listorder";
5115
5116 my $sth = $dbh->prepare($sql);
5117 $sth->execute;
5118 my @typelist;
5119 # track whether the passed type is in the list at all. allows you to edit a record
5120 # that wouldn't otherwise be generally available in that zone (typically, reverse zones)
5121 # without changing its type (accidentally or otherwise)
5122 my $selflag = 0;
5123 while (my ($rval,$rname) = $sth->fetchrow_array()) {
5124 my %row = ( recval => $rval, recname => $rname );
5125 if ($rval == $type) {
5126 $row{tselect} = 1;
5127 $selflag = 1;
5128 }
5129 push @typelist, \%row;
5130 }
5131
5132 # add the passed type if it wasn't in the list
5133 if (!$selflag) {
5134 my %row = ( recval => $type, recname => $typemap{$type}, tselect => 1 );
5135 push @typelist, \%row;
5136 }
5137
5138 # Add SOA on lookups since it's not listed in other dropdowns.
5139 if ($recgroup eq 'l') {
5140 my %row = ( recval => $reverse_typemap{SOA}, recname => 'SOA' );
5141 $row{tselect} = 1 if $reverse_typemap{SOA} == $type;
5142 push @typelist, \%row;
5143 }
5144
5145 return \@typelist;
5146} # end getTypelist()
5147
5148
5149## DNSDB::parentID()
5150# Get ID of entity that is nearest parent to requested id
5151# Takes a database handle and a hash of entity ID, entity type, optional parent type flag
5152# (domain/reverse zone or group), and optional default/live and forward/reverse flags
5153# Returns the ID or undef on failure
5154sub parentID {
5155 my $self = shift;
5156 my $dbh = $self->{dbh};
5157
5158 my %args = @_;
5159
5160 # clean up defrec and revrec. default to live record, forward zone
5161 $args{defrec} = 'n' if !$args{defrec};
5162 $args{revrec} = 'n' if !$args{revrec};
5163
5164 # clean up the parent-type. Set it to group if not set
5165 $args{partype} = 'group' if !$args{partype};
5166
5167 # allow callers to be lazy with type
5168 $args{type} = 'revzone' if $args{type} eq 'domain' && $args{revrec} eq 'y';
5169
5170 if ($par_type{$args{partype}} eq 'domain' || $par_type{$args{partype}} eq 'revzone') {
5171 # only live records can have a domain/zone parent
5172 return unless ($args{type} eq 'record' && $args{defrec} eq 'n');
5173 my $result = $dbh->selectrow_hashref("SELECT ".($args{revrec} eq 'n' ? 'domain_id' : 'rdns_id').
5174 " FROM records WHERE record_id = ?",
5175 undef, ($args{id}) ) or return;
5176 return $result;
5177 } else {
5178 # snag some arguments that will either fall through or be overwritten to save some code duplication
5179 my $tmpid = $args{id};
5180 my $type = $args{type};
5181 if ($type eq 'record' && $args{defrec} eq 'n') {
5182 # Live records go through the records table first.
5183 ($tmpid) = $dbh->selectrow_array("SELECT ".($args{revrec} eq 'n' ? 'domain_id' : 'rdns_id').
5184 " FROM records WHERE record_id = ?",
5185 undef, ($args{id}) ) or return;
5186 $type = ($args{revrec} eq 'n' ? 'domain' : 'revzone');
5187 }
5188 my ($result) = $dbh->selectrow_array("SELECT $par_col{$type} FROM $par_tbl{$type} WHERE $id_col{$type} = ?",
5189 undef, ($tmpid) );
5190 return $result;
5191 }
5192# should be impossible to get here with even remotely sane arguments
5193 return;
5194} # end parentID()
5195
5196
5197## DNSDB::isParent()
5198# Returns true if $id1 is a parent of $id2, false otherwise
5199sub isParent {
5200 my $self = shift;
5201 my $dbh = $self->{dbh};
5202 my $id1 = shift;
5203 my $type1 = shift;
5204 my $id2 = shift;
5205 my $type2 = shift;
5206##todo: immediate, secondary, full (default)
5207
5208 # Return false on invalid types
5209 return 0 if !grep /^$type1$/, ('record','defrec','defrevrec','user','domain','revzone','group');
5210 return 0 if !grep /^$type2$/, ('record','defrec','defrevrec','user','domain','revzone','group');
5211
5212 # Return false on impossible relations
5213 return 0 if $type1 eq 'record'; # nothing may be a child of a record
5214 return 0 if $type1 eq 'defrec'; # nothing may be a child of a record
5215 return 0 if $type1 eq 'defrevrec'; # nothing may be a child of a record
5216 return 0 if $type1 eq 'user'; # nothing may be child of a user
5217 return 0 if $type1 eq 'domain' && $type2 ne 'record'; # domain may not be a parent of anything other than a record
5218 return 0 if $type1 eq 'revzone' && $type2 ne 'record';# reverse zone may not be a parent of anything other than a record
5219
5220 # ennnhhhh.... if we're passed an id of 0, it will never be found. usual
5221 # case would be the UI creating a new <thing>, and so we don't have an ID for
5222 # <thing> to look up yet. in that case the UI should check the parent as well.
5223 return 0 if $id1 == 0; # nothing can have a parent id of 0
5224 return 1 if $id2 == 0; # anything could have a child id of 0 (or "unknown")
5225
5226 # group 1 is the ultimate root parent
5227 return 1 if $type1 eq 'group' && $id1 == 1;
5228
5229 # groups are always (a) parent of themselves
5230 return 1 if $type1 eq 'group' && $type2 eq 'group' && $id1 == $id2;
5231
5232 my $id = $id2;
5233 my $type = $type2;
5234 my $foundparent = 0;
5235
5236 # Records are the only entity with two possible parents. We need to split the parent checks on
5237 # domain/rdns.
5238 if ($type eq 'record') {
5239 my ($dom,$rdns) = $dbh->selectrow_array("SELECT domain_id,rdns_id FROM records WHERE record_id=?",
5240 undef, ($id));
5241 # check immediate parent against request
5242 return 1 if $type1 eq 'domain' && $id1 == $dom;
5243 return 1 if $type1 eq 'revzone' && $id1 == $rdns;
5244 # if request is group, check *both* parents. Only check if the parent is nonzero though.
5245 return 1 if $dom && $self->isParent($id1, $type1, $dom, 'domain');
5246 return 1 if $rdns && $self->isParent($id1, $type1, $rdns, 'revzone');
5247 # exit here since we've executed the loop below by proxy in the above recursive calls.
5248 return 0;
5249 }
5250
5251# almost the same loop as getParents() above
5252 my $limiter = 0;
5253 while (1) {
5254 my $sql = "SELECT $par_col{$type} FROM $par_tbl{$type} WHERE $id_col{$type} = ?";
5255 my $result = $dbh->selectrow_hashref($sql,
5256 undef, ($id) );
5257 if (!$result) {
5258 $limiter++;
5259##fixme: how often will this happen on a live site? fail at max limiter <n>?
5260# 2013/10/22 only seems to happen when you request an entity that doesn't exist.
5261 warn "no results looking for $sql with id $id (depth $limiter)\n";
5262 last;
5263 }
5264 if ($result && $result->{$par_col{$type}} == $id1) {
5265 $foundparent = 1;
5266 last;
5267 } else {
5268##fixme: do we care about trying to return a "no such record/domain/user/group" error?
5269# should be impossible to create an inconsistent DB just with API calls.
5270 warn $dbh->errstr." $sql, $id" if $dbh->errstr;
5271 }
5272 # group 1 is its own parent. need this here more to break strange loops than for detecting a parent
5273 last if $result->{$par_col{$type}} == 1;
5274 $id = $result->{$par_col{$type}};
5275 $type = $par_type{$type};
5276 }
5277
5278 return $foundparent;
5279} # end isParent()
5280
5281
5282## DNSDB::zoneStatus()
5283# Returns and optionally sets a zone's status
5284# Takes a database handle, domain/revzone ID, forward/reverse flag, and optionally a status argument
5285# Returns status, or undef on errors.
5286sub zoneStatus {
5287 my $self = shift;
5288 my $dbh = $self->{dbh};
5289 my $id = shift;
5290 my $revrec = shift;
5291 my $newstatus = shift || 'mu';
5292
5293 return undef if $id !~ /^\d+$/;
5294
5295 # Allow transactions, and raise an exception on errors so we can catch it later.
5296 # Use local to make sure these get "reset" properly on exiting this block
5297 local $dbh->{AutoCommit} = 0;
5298 local $dbh->{RaiseError} = 1;
5299
5300 if ($newstatus ne 'mu') {
5301 # ooo, fun! let's see what we were passed for status
5302 eval {
5303 $newstatus = 0 if $newstatus eq 'domoff';
5304 $newstatus = 1 if $newstatus eq 'domon';
5305 $dbh->do("UPDATE ".($revrec eq 'n' ? 'domains' : 'revzones')." SET status=? WHERE ".
5306 ($revrec eq 'n' ? 'domain_id' : 'rdns_id')."=?", undef, ($newstatus,$id) );
5307
5308##fixme switch to more consise "Enabled <domain"/"Disabled <domain>" as with users?
5309 $resultstr = "Changed ".($revrec eq 'n' ? $self->domainName($id) : $self->revName($id)).
5310 " state to ".($newstatus ? 'active' : 'inactive');
5311
5312 my %loghash;
5313 $loghash{domain_id} = $id if $revrec eq 'n';
5314 $loghash{rdns_id} = $id if $revrec eq 'y';
5315 $loghash{group_id} = $self->parentID(id => $id, type => ($revrec eq 'n' ? 'domain' : 'revzone'), revrec => $revrec);
5316 $loghash{entry} = $resultstr;
5317 $self->_log(%loghash);
5318
5319 $dbh->commit;
5320 };
5321 if ($@) {
5322 my $msg = $@;
5323 eval { $dbh->rollback; };
5324 $resultstr = '';
5325 $errstr = $msg;
5326 return;
5327 }
5328 }
5329
5330 my ($status) = $dbh->selectrow_array("SELECT status FROM ".
5331 ($revrec eq 'n' ? "domains WHERE domain_id=?" : "revzones WHERE rdns_id=?"),
5332 undef, ($id) );
5333 return $status;
5334} # end zoneStatus()
5335
5336
5337## DNSDB::getZonesByCIDR()
5338# Get a list of zone names and IDs that records for a passed CIDR block are within.
5339# Optionally restrict to a specific location/view
5340# Optionally leave off the default_location field
5341sub getZonesByCIDR {
5342 my $self = shift;
5343 my $dbh = $self->{dbh};
5344 my %args = @_;
5345 $args{return_location} = 1 if !defined($args{return_location});
5346
5347 my $sql = "SELECT rdns_id,revnet".($args{return_location} ? ',default_location' : '').
5348 " FROM revzones WHERE (revnet >>= ? OR revnet <<= ?)".
5349 (defined($args{location}) ? " AND default_location = ?" : '');
5350 my @svals = ($args{cidr}, $args{cidr});
5351 push @svals, $args{location} if defined $args{location};
5352
5353 my $result = $dbh->selectall_arrayref($sql, { Slice => {} }, @svals );
5354 return $result;
5355} # end getZonesByCIDR()
5356
5357
5358## DNSDB::importAXFR
5359# Import a domain via AXFR
5360# Takes AXFR host, domain to transfer, group to put the domain in,
5361# and an optional hash containing:
5362# status - active/inactive state flag (defaults to active)
5363# rwsoa - overwrite-SOA flag (defaults to off)
5364# rwns - overwrite-NS flag (defaults to off, doesn't affect subdomain NS records)
5365# merge - flag to automerge A or AAAA records with matching PTR records
5366# Returns a status code (OK, WARN, or FAIL) and message - message should be blank
5367# if status is OK, but WARN includes conditions that are not fatal but should
5368# really be reported.
5369sub importAXFR {
5370 my $self = shift;
5371 my $dbh = $self->{dbh};
5372 my $ifrom_in = shift;
5373 my $zone = shift;
5374 my $group = shift;
5375
5376 my %args = @_;
5377
5378##fixme: add mode to delete&replace, merge+overwrite, merge new?
5379
5380 $args{status} = (defined($args{status}) ? $args{status} : 0);
5381 $args{status} = 1 if $args{status} eq 'on';
5382
5383 my $nrecs = 0;
5384 my $soaflag = 0;
5385 my $nsflag = 0;
5386 my $warnmsg = '';
5387 my $ifrom;
5388
5389 my $rev = 'n';
5390 my $code = 'OK';
5391 my $msg = 'foobar?';
5392
5393 # choke on possible bad setting in ifrom
5394 # IPv4 and v6, and valid hostnames!
5395 ($ifrom) = ($ifrom_in =~ /^([0-9a-f\:.]+|[0-9a-z_.-]+)$/i);
5396 return ('FAIL', "Bad AXFR source host $ifrom")
5397 unless ($ifrom) = ($ifrom_in =~ /^([0-9a-f\:.]+|[0-9a-z_.-]+)$/i);
5398
5399 my $errmsg;
5400
5401 my $zone_id;
5402 my $domain_id = 0;
5403 my $rdns_id = 0;
5404 my $cidr;
5405
5406# magic happens! detect if we're importing a domain or a reverse zone
5407# while we're at it, figure out what the CIDR netblock is (if we got a .arpa)
5408# or what the formal .arpa zone is (if we got a CIDR netblock)
5409# Handles sub-octet v4 zones in the format specified in the Cricket Book, 2nd Ed, p217-218
5410
5411 if ($zone =~ m{(?:\.arpa\.?|/\d+|^[\d.]+|^[a-fA-F0-9:]+)$}) {
5412 # we seem to have a reverse zone
5413 $rev = 'y';
5414
5415 if ($zone =~ /\.arpa\.?$/) {
5416 # we have a formal reverse zone. call _zone2cidr and get the CIDR block.
5417 ($code,$msg) = _zone2cidr($zone);
5418 return ($code, $msg) if $code eq 'FAIL';
5419 $cidr = $msg;
5420 } elsif ($zone =~ m|^[\d.]+/\d+$|) {
5421 # v4 revzone, CIDR netblock
5422 $cidr = NetAddr::IP->new($zone) or return ('FAIL',"$zone is not a valid CIDR block");
5423 $zone = _ZONE($cidr, 'ZONE.in-addr.arpa', 'r', '.');
5424 } elsif ($zone =~ /^[\d.]+$/) {
5425 # v4 revzone, leading-octet format
5426 my $mask = 32;
5427 while ($zone !~ /^\d+\.\d+\.\d+\.\d+$/) {
5428 $zone .= '.0';
5429 $mask -= 8;
5430 }
5431 $zone .= "/$mask";
5432 $cidr = NetAddr::IP->new($zone) or return ('FAIL',"$zone is not a valid CIDR block");
5433 $zone = _ZONE($cidr, 'ZONE.in-addr.arpa', 'r', '.');
5434 } elsif ($zone =~ m|^[a-fA-F\d:]+/\d+$|) {
5435 # v6 revzone, CIDR netblock
5436 $cidr = NetAddr::IP->new($zone) or return ('FAIL',"$zone is not a valid CIDR block");
5437 return ('FAIL', "$zone is not a nibble-aligned block") if $cidr->masklen % 4 != 0;
5438 $zone = _ZONE($cidr, 'ZONE.ip6.arpa', 'r', '.');
5439 } elsif ($zone =~ /^[a-fA-F\d:]+$/) {
5440 # v6 revzone, leading-group format
5441 $zone =~ s/::$//;
5442 my $mask = 128;
5443 while ($zone !~ /^(?:[a-fA-F\d]{1,4}:){7}[a-fA-F\d]$/) {
5444 $zone .= ":0";
5445 $mask -= 16;
5446 }
5447 $zone .= "/$mask";
5448 $cidr = NetAddr::IP->new($zone) or return ('FAIL',"$zone is not a valid CIDR block");
5449 $zone = _ZONE($cidr, 'ZONE.ip6.arpa', 'r', '.');
5450 } else {
5451 # there is. no. else!
5452 return ('FAIL', "Unknown zone name format '$zone'");
5453 }
5454
5455 # several places this can be triggered from; better to do it once.
5456 $warnmsg .= "Apparent sub-/64 IPv6 reverse zone\n" if $cidr->masklen > 64;
5457
5458 # quick check to start to see if we've already got one
5459
5460 ($zone_id) = $dbh->selectrow_array("SELECT rdns_id FROM revzones WHERE revnet=?",
5461 undef, ("$cidr"));
5462 $rdns_id = $zone_id;
5463 } else {
5464 # default to domain
5465 ($zone_id) = $dbh->selectrow_array("SELECT domain_id FROM domains WHERE lower(domain) = lower(?)",
5466 undef, ($zone));
5467 $domain_id = $zone_id;
5468 }
5469
5470 return ('FAIL', ($rev eq 'n' ? 'Domain' : 'Reverse zone')." already exists") if $zone_id;
5471
5472 # little local utility sub to swap $val and $host for revzone records.
5473 sub _revswap {
5474 my $rechost = shift;
5475 my $recdata = shift;
5476
5477 if ($rechost =~ /\.in-addr\.arpa\.?$/) {
5478 $rechost =~ s/\.in-addr\.arpa\.?$//;
5479 $rechost = join '.', reverse split /\./, $rechost;
5480 } else {
5481 $rechost =~ s/\.ip6\.arpa\.?$//;
5482 my @nibs = reverse split /\./, $rechost;
5483 $rechost = '';
5484 my $nc;
5485 foreach (@nibs) {
5486# # fail on multicharacter nibbles; it's syntactically valid but no standard lookup
5487# # will ever reach it, because it doesn't directly represent a real IP address.
5488# return ('FAIL', "Invalid reverse v6 entry") if $_ !~ /^.$/;
5489 $rechost.= $_;
5490 $rechost .= ":" if ++$nc % 4 == 0 && $nc < 32;
5491 }
5492 $rechost .= ":" if $nc < 32 && $rechost !~ /\*$/; # close netblock records?
5493##fixme: there's a case that ends up with a partial entry here:
5494# ip:add:re:ss::
5495# can't reproduce after letting it sit overnight after discovery. :(
5496#print "$rechost\n";
5497 # canonicalize with NetAddr::IP
5498 $rechost = NetAddr::IP->new($rechost)->addr unless $rechost =~ /\*$/;
5499 }
5500 return ($recdata,$rechost)
5501 }
5502
5503
5504 # Allow transactions, and raise an exception on errors so we can catch it later.
5505 # Use local to make sure these get "reset" properly on exiting this block
5506 local $dbh->{AutoCommit} = 0;
5507 local $dbh->{RaiseError} = 1;
5508
5509 my $sth;
5510 eval {
5511
5512 if ($rev eq 'n') {
5513##fixme: serial
5514 $dbh->do("INSERT INTO domains (domain,group_id,status) VALUES (?,?,?)", undef,
5515 ($zone, $group, $args{status}) ) or die $dbh->errstr;
5516 # get domain id so we can do the records
5517 ($zone_id) = $dbh->selectrow_array("SELECT currval('domains_domain_id_seq')");
5518 $domain_id = $zone_id;
5519 $self->_log(group_id => $group, domain_id => $domain_id,
5520 entry => "[Added ".($args{status} ? 'active' : 'inactive')." domain $zone via AXFR]");
5521 } else {
5522##fixme: serial
5523 $dbh->do("INSERT INTO revzones (revnet,group_id,status) VALUES (?,?,?)", undef,
5524 ($cidr,$group,$args{status}) );
5525 # get revzone id so we can do the records
5526 ($zone_id) = $dbh->selectrow_array("SELECT currval('revzones_rdns_id_seq')");
5527 $rdns_id = $zone_id;
5528 $self->_log(group_id => $group, rdns_id => $rdns_id,
5529 entry => "[Added ".($args{status} ? 'active' : 'inactive')." reverse zone $cidr via AXFR]");
5530 }
5531
5532## bizarre DBI<->Net::DNS interaction bug:
5533## sometimes a zone will cause an immediate commit-and-exit (sort of) of the while()
5534## fixed, apparently I was doing *something* odd, but not certain what it was that
5535## caused a commit instead of barfing
5536
5537 my $res = Net::DNS::Resolver->new;
5538 $res->nameservers($ifrom);
5539 $res->axfr_start($zone)
5540 or die "Couldn't begin AXFR\n";
5541
5542 $sth = $dbh->prepare("INSERT INTO records (domain_id,rdns_id,host,type,val,distance,weight,port,ttl)".
5543 " VALUES (?,?,?,?,?,?,?,?,?)");
5544
5545 # Stash info about sub-octet v4 revzones here so we don't have
5546 # to store the CNAMEs used to delegate a suboctet zone
5547 # $suboct{zone}{ns}[] -> array of nameservers
5548 # $suboct{zone}{cname}[] -> array of extant CNAMEs (Just In Case someone did something bizarre)
5549## commented pending actual use of this data. for now, we'll just
5550## auto-(re)create the CNAMEs in revzones on export
5551# my %suboct;
5552
5553 while (my $rr = $res->axfr_next()) {
5554
5555 # Discard out-of-zone records. After trying for a while to replicate this with
5556 # *nix-based DNS servers, it appears that only MS DNS is prone to including these
5557 # in the AXFR data in the first place, and possibly only older versions at that...
5558 # so it can't be reasonably tested. Yay Microsoft.
5559 if ($rr->name !~ /$zone$/i) {
5560 $warnmsg .= "Discarding out-of-zone record ".$rr->string."\n";
5561 }
5562
5563 my $val;
5564 my $distance = 0;
5565 my $weight = 0;
5566 my $port = 0;
5567 my $logfrag = '';
5568
5569 # Collect some record parts
5570 my $type = $rr->type;
5571 my $host = $rr->name;
5572 my $ttl = ($args{newttl} ? $args{newttl} : $rr->ttl); # allow force-override TTLs
5573
5574 # Info flags for SOA and NS records
5575 $soaflag = 1 if $type eq 'SOA';
5576 $nsflag = 1 if $type eq 'NS';
5577
5578# "Primary" types:
5579# A, NS, CNAME, SOA, PTR(warn in forward), MX, TXT, AAAA, SRV, A6(ob), SPF
5580# maybe KEY
5581
5582# BIND supports:
5583# [standard]
5584# A AAAA CNAME MX NS PTR SOA TXT
5585# [variously experimental, obsolete, or obscure]
5586# HINFO MB(ex) MD(ob) MF(ob) MG(ex) MINFO(ex) MR(ex) NULL WKS AFSDB(ex) ISDN(ex) RP(ex) RT(ex) X25(ex) PX
5587# ... if one can ever find the right magic to format them correctly
5588
5589# Net::DNS supports:
5590# RRSIG SIG NSAP NS NIMLOC NAPTR MX MR MINFO MG MB LOC ISDN IPSECKEY HINFO
5591# EID DNAME CNAME CERT APL AFSDB AAAA A DS NXT NSEC3PARAM NSEC3 NSEC KEY
5592# DNSKEY DLV X25 TXT TSIG TKEY SSHFP SRV SPF SOA RT RP PX PTR NULL APL::AplItem
5593
5594# nasty big ugly case-like thing here, since we have to do *some* different
5595# processing depending on the record. le sigh.
5596
5597# do the initial processing as if the record was in a forward zone. If we're
5598# doing a revzone, we can flip $host and $val as needed, once, after this
5599# monster if-elsif-...-elsif-else. This actually simplifies things a lot.
5600
5601##fixme: what record types other than TXT can/will have >255-byte payloads?
5602
5603 if ($type eq 'A') {
5604 $val = $rr->address;
5605 } elsif ($type eq 'NS') {
5606# hmm. should we warn here if subdomain NS'es are left alone? OTOH, those should rarely be rewritten anyway.
5607 next if ($args{rwns} && ($host eq $zone));
5608 $val = $rr->nsdname;
5609 $warnmsg .= "Suspect record '".$rr->string."' may not be imported correctly: NS records may not be bare IP addresses\n"
5610 if $val =~ /^(?:(?:\d+\.){3}\d+|[a-fA-F0-9:]+)$/;
5611 $nsflag = 1;
5612 } elsif ($type eq 'CNAME') {
5613 $val = $rr->cname;
5614 $warnmsg .= "Suspect record '".$rr->string."' may not be imported correctly: CNAME records may not be bare IP addresses\n"
5615 if $val =~ /^(?:(?:\d+\.){3}\d+|[a-fA-F0-9:]+)$/;
5616 } elsif ($type eq 'SOA') {
5617 next if $args{rwsoa};
5618 $host = $rr->rname.":".$rr->mname;
5619 $val = $rr->refresh.":".$rr->retry.":".$rr->expire.":".$rr->minimum;
5620 $soaflag = 1;
5621 } elsif ($type eq 'PTR') {
5622 $val = $rr->ptrdname;
5623 } elsif ($type eq 'MX') {
5624 $val = $rr->exchange;
5625 $distance = $rr->preference;
5626 } elsif ($type eq 'TXT') {
5627##fixme: Net::DNS docs say this should be deprecated for rdatastr() or char_str_list(),
5628## but don't really seem enthusiastic about it.
5629#print "should use rdatastr:\n\t".$rr->rdatastr."\n or char_str_list:\n\t".join(' ',$rr->char_str_list())."\n";
5630# rdatastr returns a BIND-targetted logical string, including opening and closing quotes
5631# char_str_list returns a list of the individual string fragments in the record
5632# txtdata returns the more useful all-in-one form (since we want to push such protocol
5633# details as far down the stack as we can)
5634# NB: this may turn out to be more troublesome if we ever have need of >512-byte TXT records.
5635 $val = $rr->txtdata;
5636 } elsif ($type eq 'SPF') {
5637##fixme: and the same caveat here, since it is apparently a clone of ::TXT
5638 $val = $rr->txtdata;
5639 } elsif ($type eq 'AAAA') {
5640 $val = $rr->address;
5641 } elsif ($type eq 'SRV') {
5642 $val = $rr->target;
5643 $distance = $rr->priority;
5644 $weight = $rr->weight;
5645 $port = $rr->port;
5646 $warnmsg .= "Suspect record '".$rr->string."' may not be imported correctly: SRV records may not be bare IP addresses\n"
5647 if $val =~ /^(?:(?:\d+\.){3}\d+|[a-fA-F0-9:]+)$/;
5648 } elsif ($type eq 'KEY') {
5649 # we don't actually know what to do with these...
5650 $val = $rr->flags.":".$rr->protocol.":".$rr->algorithm.":".$rr->key.":".$rr->keytag.":".$rr->privatekeyname;
5651 } else {
5652 $val = $rr->rdatastr;
5653 # Finding a different record type is not fatal.... just problematic.
5654 # We may not be able to export it correctly.
5655 $warnmsg .= "Unusual record ".$rr->name." ($type) found\n";
5656 }
5657
5658 if ($rev eq 'y' && $type ne 'SOA') {
5659 # up to this point we haven't meddled with the record's hostname part or rdata part.
5660 # for reverse records, (except SOA) we must swap the two.
5661 $host = $val;
5662 $val = $rr->name;
5663 my ($tmpcode,$tmpmsg) = _zone2cidr($val);
5664 if ($tmpcode eq 'FAIL') {
5665 # $val did not have a valid IP value. It's syntactically valid but WTF?
5666 $warnmsg .= "Suspect record '".$rr->string."' may not be imported correctly: $tmpmsg\n";
5667 } else {
5668 # $val has a valid IP value. See if we can store it as that IP value.
5669 # Note we're enumerating do-nothing cases for clarity.
5670##enhance: this is where we will implement the more subtle variations on #53
5671 if ($type ne 'PTR' && $type ne 'NS' && $type ne 'CNAME' && $type ne 'TXT') {
5672 # case: the record is "weird" - ie, not a PTR, NS, CNAME, or TXT
5673 # $warnmsg .= "Discarding suspect record '".$rr->string."'\n" if $self->{strict} eq 'full';
5674 } elsif ($type eq 'PTR' && $tmpmsg->masklen != 32 && $tmpmsg->masklen != 128) {
5675 # case: PTR with netblock value, not IP value
5676 # eg, "@ PTR foo" in zone f.e.e.b.d.a.e.d.ip6.arpa should not be
5677 # stored/displayed as dead:beef::/32 PTR foo
5678
5679## hrm. WTF is this case for, anyway? Needs testing to check the logic.
5680# } elsif ( ($type eq 'PTR' || $type eq 'NS' || $type eq 'CNAME' || $type eq 'TXT') &&
5681# ($tmpmsg->masklen != $cidr->masklen)
5682# ) {
5683# # leave $val as-is if the record is "normal" (a PTR, NS, CNAME, or TXT),
5684# # and the mask does not match the zone
5685#$warnmsg .= "WTF case: $host $type $val\n";
5686# # $warnmsg .= "Discarding suspect record '".$rr->string."'\n" if $self->{strict} eq 'full';
5687
5688 } else {
5689 $val = $tmpmsg;
5690 $val =~ s/\/(?:32|128)$//; # automagically converts $val back to a string before s///
5691 #$val =~ s/:0$//g;
5692 }
5693 }
5694 # magic? convert * records to PTR template (not sure this actually makes sense)
5695 #if ($val =~ /^\*/) {
5696 # $val =~ s/\*\.//;
5697 # ($tmpcode,$tmpmsg) = _zone2cidr($val);
5698 # if ($tmpcode eq 'FAIL') {
5699 # $val = "*.$val";
5700 # $warnmsg .= "Suspect record '".$rr->string."' may not be converted to PTR template correctly: $tmpmsg\n";
5701 # } else {
5702 # $type = 'PTR template';
5703 # $val = $tmpmsg; if $tmp
5704 # $val =~ s/\/(?:32|128)$//; # automagically converts $val back to a string before s///
5705 # }
5706 #}
5707 } # non-SOA revrec $host/$val inversion and munging
5708
5709 my $logentry = "[AXFR ".($rev eq 'n' ? $zone : $cidr)."] ";
5710
5711 if ($args{merge}) {
5712 if ($rev eq 'n') {
5713 # importing a domain; we have A and AAAA records that could be merged with matching PTR records
5714 my $etype;
5715 my ($erdns,$erid,$ettl) = $dbh->selectrow_array("SELECT rdns_id,record_id,ttl FROM records ".
5716 "WHERE host=? AND val=? AND type=12",
5717 undef, ($host, $val) );
5718 if ($erid) {
5719 if ($type eq 'A') { # PTR -> A+PTR
5720 $etype = 65280;
5721 $logentry .= "Merged A record with existing PTR record '$host A+PTR $val', TTL $ettl";
5722 }
5723 if ($type eq 'AAAA') { # PTR -> AAAA+PTR
5724 $etype = 65281;
5725 $logentry .= "Merged AAAA record with existing PTR record '$host AAAA+PTR $val', TTL $ettl";
5726 }
5727 $ettl = ($ettl < $ttl ? $ettl : $ttl); # use lower TTL
5728 $dbh->do("UPDATE records SET domain_id=?,ttl=?,type=? WHERE record_id=?", undef,
5729 ($domain_id, $ettl, $etype, $erid));
5730 $nrecs++;
5731 $self->_log(group_id => $group, domain_id => $domain_id, rdns_id => $erdns, entry => $logentry);
5732 next; # while axfr_next
5733 }
5734 } # $rev eq 'n'
5735 else {
5736 # importing a revzone, we have PTR records that could be merged with matching A/AAAA records
5737 my ($domid,$erid,$ettl,$etype) = $dbh->selectrow_array("SELECT domain_id,record_id,ttl,type FROM records ".
5738 "WHERE host=? AND val=? AND (type=1 OR type=28)",
5739 undef, ($host, $val) );
5740 if ($erid) {
5741 if ($etype == 1) { # A -> A+PTR
5742 $etype = 65280;
5743 $logentry .= "Merged PTR record with existing matching A record '$host A+PTR $val', TTL $ettl";
5744 }
5745 if ($etype == 28) { # AAAA -> AAAA+PTR
5746 $etype = 65281;
5747 $logentry .= "Merged PTR record with existing matching AAAA record '$host AAAA+PTR $val', TTL $ettl";
5748 }
5749 $ettl = ($ettl < $ttl ? $ettl : $ttl); # use lower TTL
5750 $dbh->do("UPDATE records SET rdns_id=?,ttl=?,type=? WHERE record_id=?", undef,
5751 ($rdns_id, $ettl, $etype, $erid));
5752 $nrecs++;
5753 $self->_log(group_id => $group, domain_id => $domid, rdns_id => $rdns_id, entry => $logentry);
5754 next; # while axfr_next
5755 }
5756 } # $rev eq 'y'
5757 } # if $args{merge}
5758
5759 # Insert the new record
5760 $sth->execute($domain_id, $rdns_id, $host, $reverse_typemap{$type}, $val,
5761 $distance, $weight, $port, $ttl);
5762
5763 $nrecs++;
5764
5765 if ($type eq 'SOA') {
5766 # also !$args{rwsoa}, but if that's set, it should be impossible to get here.
5767 my @tmp1 = split /:/, $host;
5768 my @tmp2 = split /:/, $val;
5769 $logentry .= "Added SOA record [contact $tmp1[0]] [master $tmp1[1]] ".
5770 "[refresh $tmp2[0]] [retry $tmp2[1]] [expire $tmp2[2]] [minttl $tmp2[3]], TTL $ttl";
5771 } elsif ($logfrag) {
5772 # special case for log entries we need to meddle with a little.
5773 $logentry .= $logfrag;
5774 } else {
5775 $logentry .= "Added record '".($rev eq 'y' ? $val : $host)." $type";
5776 $logentry .= " [distance $distance]" if $type eq 'MX';
5777 $logentry .= " [priority $distance] [weight $weight] [port $port]" if $type eq 'SRV';
5778 $logentry .= " ".($rev eq 'y' ? $host : $val)."', TTL $ttl";
5779 }
5780 $self->_log(group_id => $group, domain_id => $domain_id, rdns_id => $rdns_id, entry => $logentry);
5781
5782 } # while axfr_next
5783
5784# Detect and handle delegated subzones
5785# Placeholder for when we decide what to actually do with this, see previous comments in NS and CNAME handling.
5786#foreach (keys %suboct) {
5787# print "found ".($suboct{$_}{ns} ? @{$suboct{$_}{ns}} : '0')." NS records and ".
5788# ($suboct{$_}{cname} ? @{$suboct{$_}{cname}} : '0')." CNAMEs for $_\n";
5789#}
5790
5791 # Overwrite SOA record
5792 if ($args{rwsoa}) {
5793 $soaflag = 1;
5794 my $sthgetsoa = $dbh->prepare("SELECT host,val,ttl FROM "._rectable('y', $rev)." WHERE group_id=? AND type=?");
5795 my $sthputsoa = $dbh->prepare("INSERT INTO records (".
5796 ($rev eq 'n' ? 'domain_id' : 'rdns_id').",host,type,val,ttl) VALUES (?,?,?,?,?)");
5797 $sthgetsoa->execute($group,$reverse_typemap{SOA});
5798 while (my ($host,$val,$ttl) = $sthgetsoa->fetchrow_array()) {
5799 if ($rev eq 'n') {
5800 $host =~ s/DOMAIN/$zone/g;
5801 $val =~ s/DOMAIN/$zone/g; # arguably useless
5802 } else {
5803 $host =~ s/ADMINDOMAIN/$self->{domain}/g;
5804 }
5805 $sthputsoa->execute($zone_id,$host,$reverse_typemap{SOA},$val,$ttl);
5806 }
5807 }
5808
5809 # Add standard NS records. The old one(s) should have been skipped by this point.
5810 if ($args{rwns}) {
5811 $nsflag = 1;
5812 my $sthgetns = $dbh->prepare("SELECT host,val,ttl FROM "._rectable('y',$rev)." WHERE group_id=? AND type=?");
5813 my $sthputns = $dbh->prepare("INSERT INTO records (".
5814 ($rev eq 'n' ? 'domain_id' : 'rdns_id').",host,type,val,ttl) VALUES (?,?,?,?,?)");
5815 $sthgetns->execute($group,$reverse_typemap{NS});
5816 while (my ($host,$val,$ttl) = $sthgetns->fetchrow_array()) {
5817 if ($rev eq 'n') {
5818 $host =~ s/DOMAIN/$zone/g;
5819 $val =~ s/DOMAIN/$zone/g; #hmm.
5820 } else {
5821 $host =~ s/ADMINDOMAIN/$self->{domain}/g; #hmm.
5822 $val =~ s/ZONE/$cidr/g;
5823 }
5824 $sthputns->execute($zone_id,$host,$reverse_typemap{NS},$val,$ttl);
5825 }
5826 }
5827
5828 die "No records found; either $ifrom is not authoritative or doesn't allow transfers\n" if !$nrecs;
5829 die "Bad zone: No SOA record!\n" if !$soaflag;
5830 die "Bad zone: No NS records!\n" if !$nsflag;
5831
5832 $dbh->commit;
5833
5834 };
5835
5836 if ($@) {
5837 my $msg = $@;
5838 eval { $dbh->rollback; };
5839 return ('FAIL',$msg." $warnmsg");
5840 } else {
5841 return ('WARN', $warnmsg) if $warnmsg;
5842 return ('OK',"Imported OK");
5843 }
5844
5845 # it should be impossible to get here.
5846 return ('WARN',"OOOK!");
5847} # end importAXFR()
5848
5849
5850## DNSDB::importBIND()
5851sub importBIND {
5852} # end importBIND()
5853
5854
5855## DNSDB::import_tinydns()
5856sub import_tinydns {
5857} # end import_tinydns()
5858
5859
5860## DNSDB::export()
5861# Export the DNS database, or a part of it
5862# Takes a string indicating the export type, plus optional arguments depending on type
5863# Writes zone data to targets as appropriate for type
5864sub export {
5865 my $self = shift;
5866 my $target = shift;
5867
5868 if ($target eq 'tiny') {
5869 eval {
5870 $self->__export_tiny(@_);
5871 };
5872 if ($@) {
5873 $errstr = $@;
5874 return undef;
5875 }
5876 }
5877# elsif ($target eq 'foo') {
5878# __export_foo(@_);
5879#}
5880# etc
5881
5882 return 1;
5883} # end export()
5884
5885
5886## DNSDB::__export_tiny
5887# Internal sub to implement tinyDNS (compatible) export
5888# Takes filehandle to write export to, optional argument(s)
5889# to determine which data gets exported
5890sub __export_tiny {
5891 my $self = shift;
5892 my $dbh = $self->{dbh};
5893 my $datafile = shift;
5894 my $zonefilehandle = $datafile; # makes cache/no-cache a little simpler
5895
5896##fixme: slurp up further options to specify particular zone(s) to export
5897
5898##fixme: fail if $datafile isn't an open, writable file
5899
5900 # Error check - does the cache dir exist, if we're using one?
5901 if ($self->{usecache}) {
5902 die "Cache directory does not exist\n" if !-e $self->{exportcache};
5903 die "$self->{exportcache} is not a directory\n" if !-d $self->{exportcache};
5904 die "$self->{exportcache} must be both readable and writable\n"
5905 if !-r $self->{exportcache} || !-w $self->{exportcache};
5906 }
5907
5908 # easy case - export all evarything
5909 # not-so-easy case - export item(s) specified
5910 # todo: figure out what kind of list we use to export items
5911
5912# raw packet in unknown format: first byte indicates length
5913# of remaining data, allows up to 255 raw bytes
5914
5915 # note: the only I/O failures we seem to be able to actually catch
5916 # here are "closed filehandle" errors. we're probably not writing
5917 # enough data at this point to properly trigger an "out of space"
5918 # error. :/
5919 eval {
5920 use warnings FATAL => ('io');
5921 # Locations/views - worth including in the caching setup?
5922 my $lochash = $dbh->selectall_hashref("SELECT location,iplist FROM locations", 'location');
5923 foreach my $location (keys %$lochash) {
5924 foreach my $ipprefix (split /[,\s]+/, $lochash->{$location}{iplist}) {
5925 $ipprefix =~ s/\s+//g;
5926 $ipprefix = new NetAddr::IP $ipprefix;
5927##fixme: how to handle IPv6?
5928next if $ipprefix->{isv6};
5929 # have to account for /nn CIDR entries. tinydns only speaks octet-sliced prefix.
5930 if ($ipprefix->masklen <= 8) {
5931 foreach ($ipprefix->split(8)) {
5932 my $tmp = $_->addr;
5933 $tmp =~ s/\.\d+\.\d+\.\d+$//;
5934 print $datafile "%$location:$tmp\n";
5935 }
5936 } elsif ($ipprefix->masklen <= 16) {
5937 foreach ($ipprefix->split(16)) {
5938 my $tmp = $_->addr;
5939 $tmp =~ s/\.\d+\.\d+$//;
5940 print $datafile "%$location:$tmp\n";
5941 }
5942 } elsif ($ipprefix->masklen <= 24) {
5943 foreach ($ipprefix->split(24)) {
5944 my $tmp = $_->addr;
5945 $tmp =~ s/\.\d+$//;
5946 print $datafile "%$location:$tmp\n";
5947 }
5948 } else {
5949 foreach ($ipprefix->split(32)) {
5950 print $datafile "%$location:".$_->addr."\n";
5951 }
5952 }
5953 }
5954 print $datafile "%$location\n" if !$lochash->{$location}{iplist};
5955 }
5956 };
5957 if ($@) {
5958 die "Error writing locations to master file: $@, $!\n";
5959 }
5960
5961 # tracking hash so we don't double-export A+PTR or AAAA+PTR records.
5962 my %recflags;
5963
5964# For reasons unknown, we can't sanely UNION these statements. Feh.
5965# Supposedly it should work though (note last 3 lines):
5966## PG manual
5967#UNION Clause
5968#
5969#The UNION clause has this general form:
5970#
5971# select_statement UNION [ ALL ] select_statement
5972#
5973#select_statement is any SELECT statement without an ORDER BY, LIMIT, FOR UPDATE, or FOR SHARE clause. (ORDER BY
5974#and LIMIT can be attached to a subexpression if it is enclosed in parentheses. Without parentheses, these
5975#clauses will be taken to apply to the result of the UNION, not to its right-hand input expression.)
5976 my $soasth = $dbh->prepare("SELECT host,type,val,distance,weight,port,ttl,record_id,location ".
5977 "FROM records WHERE rdns_id=? AND type=6");
5978 my $recsth = $dbh->prepare("SELECT host,type,val,distance,weight,port,ttl,record_id,location,extract(epoch from stamp),expires,stampactive ".
5979 "FROM records WHERE rdns_id=? AND NOT type=6 ".
5980 "ORDER BY masklen(inetlazy(val)) DESC, inetlazy(val)");
5981 my $revsth = $dbh->prepare("SELECT rdns_id,revnet,status,changed FROM revzones WHERE status=1 ".
5982 "ORDER BY masklen(revnet) DESC, rdns_id");
5983 my $zonesth = $dbh->prepare("UPDATE revzones SET changed='n' WHERE rdns_id=?");
5984 $revsth->execute();
5985 while (my ($revid,$revzone,$revstat,$changed) = $revsth->fetchrow_array) {
5986##fixme: need to find a way to block opening symlinked files without introducing a race.
5987# O_NOFOLLOW
5988# If pathname is a symbolic link, then the open fails. This is a FreeBSD extension, which was
5989# added to Linux in version 2.1.126. Symbolic links in earlier components of the pathname will
5990# still be followed.
5991# but that doesn't help other platforms. :/
5992 my $tmpzone = NetAddr::IP->new($revzone);
5993##fixme: locations/views? subnet mask? need to avoid possible collisions with zone/superzone
5994## (eg /20 vs /24, starting on .0.0)
5995 my $cz = $tmpzone->network->addr."-".$tmpzone->masklen;
5996 my $cachefile = "$self->{exportcache}/$cz";
5997 my $tmpcache = "$self->{exportcache}/tmp.$cz.$$";
5998 eval {
5999
6000 # write fresh records if:
6001 # - we are not using the cache
6002 # - force_refresh is set
6003 # - the zone has changed
6004 # - the cache file does not exist
6005 # - the cache file is empty
6006 if (!$self->{usecache} || $self->{force_refresh} || $changed || !-e $cachefile || -z $cachefile) {
6007 if ($self->{usecache}) {
6008 open ZONECACHE, ">$tmpcache" or die "Error creating temporary file $tmpcache: $!\n";
6009 $zonefilehandle = *ZONECACHE;
6010 }
6011
6012 # need to fetch this separately since the rest of the records all (should) have real IPs in val
6013 $soasth->execute($revid);
6014 my (@zsoa) = $soasth->fetchrow_array();
6015 $self->_printrec_tiny($zonefilehandle, $zsoa[7], 'y',\%recflags,$revzone,
6016 $zsoa[0],$zsoa[1],$zsoa[2],$zsoa[3],$zsoa[4],$zsoa[5],$zsoa[6],$zsoa[8],'');
6017
6018 $recsth->execute($revid);
6019 my $fullzone = _ZONE($tmpzone, 'ZONE', 'r', '.').($tmpzone->{isv6} ? '.ip6.arpa' : '.in-addr.arpa');
6020
6021 while (my ($host, $type, $val, $dist, $weight, $port, $ttl, $recid, $loc, $stamp, $expires, $stampactive)
6022 = $recsth->fetchrow_array) {
6023 next if $recflags{$recid};
6024
6025 # Check for out-of-zone data
6026 if ($val =~ /\.arpa$/) {
6027 # val is non-IP
6028 if ($val !~ /$fullzone$/) {
6029 warn "Not exporting out-of-zone record $val $typemap{$type} $host, $ttl (zone $tmpzone)\n";
6030 next;
6031 }
6032 } else {
6033 my $ipval = new NetAddr::IP $val;
6034 if (!$tmpzone->contains($ipval)) {
6035 warn "Not exporting out-of-zone record $val $typemap{$type} $host, $ttl (zone $tmpzone)\n";
6036 next;
6037 }
6038 } # is $val a raw .arpa name?
6039
6040 # Spaces are evil.
6041 $val =~ s/^\s+//;
6042 $val =~ s/\s+$//;
6043 if ($typemap{$type} ne 'TXT') {
6044 # Leading or trailng spaces could be legit in TXT records.
6045 $host =~ s/^\s+//;
6046 $host =~ s/\s+$//;
6047 }
6048
6049 $self->_printrec_tiny($zonefilehandle, $recid, 'y', \%recflags, $revzone,
6050 $host, $type, $val, $dist, $weight, $port, $ttl, $loc, $stamp, $expires, $stampactive);
6051
6052 $recflags{$recid} = 1;
6053
6054 } # while ($recsth)
6055
6056 if ($self->{usecache}) {
6057 close ZONECACHE; # force the file to be written
6058 # catch obvious write errors that leave an empty temp file
6059 if (-s $tmpcache) {
6060 rename $tmpcache, $cachefile
6061 or die "Error overwriting cache file $cachefile with temporary file: $!\n";
6062 }
6063 }
6064
6065 } # if $changed or cache filesize is 0
6066
6067 };
6068 if ($@) {
6069 die "error writing ".($self->{usecache} ? 'new data for ' : '')."$revzone: $@\n";
6070 # error! something borked, and we should be able to fall back on the old cache file
6071 # report the error, somehow.
6072 } else {
6073 # mark zone as unmodified. Only do this if no errors, that way
6074 # export failures should recover a little more automatically.
6075 $zonesth->execute($revid);
6076 }
6077
6078 if ($self->{usecache}) {
6079 # We've already made as sure as we can that a cached zone file is "good",
6080 # although possibly stale/obsolete due to errors creating a new one.
6081 eval {
6082 open CACHE, "<$cachefile" or die $!;
6083 print $datafile $_ or die "error copying cached $revzone to master file: $!" while <CACHE>;
6084 close CACHE;
6085 };
6086 die $@ if $@;
6087 }
6088
6089 } # while ($revsth)
6090
6091 $soasth = $dbh->prepare("SELECT host,type,val,distance,weight,port,ttl,record_id,location ".
6092 "FROM records WHERE domain_id=? AND type=6");
6093 $recsth = $dbh->prepare("SELECT host,type,val,distance,weight,port,ttl,record_id,location,extract(epoch from stamp),expires,stampactive ".
6094 "FROM records WHERE domain_id=? AND NOT type=6"); # Just exclude all types relating to rDNS
6095# "FROM records WHERE domain_id=? AND type < 65280"); # Just exclude all types relating to rDNS
6096 my $domsth = $dbh->prepare("SELECT domain_id,domain,status,changed FROM domains WHERE status=1 ORDER BY domain_id");
6097 $zonesth = $dbh->prepare("UPDATE domains SET changed='n' WHERE domain_id=?");
6098 $domsth->execute();
6099 while (my ($domid,$dom,$domstat,$changed) = $domsth->fetchrow_array) {
6100##fixme: need to find a way to block opening symlinked files without introducing a race.
6101# O_NOFOLLOW
6102# If pathname is a symbolic link, then the open fails. This is a FreeBSD extension, which was
6103# added to Linux in version 2.1.126. Symbolic links in earlier components of the pathname will
6104# still be followed.
6105# but that doesn't help other platforms. :/
6106 my $cachefile = "$self->{exportcache}/$dom";
6107 my $tmpcache = "$self->{exportcache}/tmp.$dom.$$";
6108 eval {
6109
6110 # write fresh records if:
6111 # - we are not using the cache
6112 # - force_refresh is set
6113 # - the zone has changed
6114 # - the cache file does not exist
6115 # - the cache file is empty
6116 if (!$self->{usecache} || $self->{force_refresh} || $changed || !-e $cachefile || -z $cachefile) {
6117 if ($self->{usecache}) {
6118 open ZONECACHE, ">$tmpcache" or die "Error creating temporary file $tmpcache: $!\n";
6119 $zonefilehandle = *ZONECACHE;
6120 }
6121
6122 # need to fetch this separately so the SOA comes first in the flatfile....
6123 # Just In Case we need/want to reimport from the flatfile later on.
6124 $soasth->execute($domid);
6125 my (@zsoa) = $soasth->fetchrow_array();
6126 $self->_printrec_tiny($zonefilehandle, $zsoa[7], 'n',\%recflags,$dom,
6127 $zsoa[0],$zsoa[1],$zsoa[2],$zsoa[3],$zsoa[4],$zsoa[5],$zsoa[6],$zsoa[8],'');
6128
6129 $recsth->execute($domid);
6130 while (my ($host,$type,$val,$dist,$weight,$port,$ttl,$recid,$loc,$stamp,$expires,$stampactive) = $recsth->fetchrow_array) {
6131 next if $recflags{$recid};
6132
6133 # Check for out-of-zone data
6134 $host = $dom if $host eq '@';
6135 if ($host !~ /$dom$/i) {
6136 warn "Not exporting out-of-zone record $host $type $val, $ttl (zone $dom)\n";
6137 next;
6138 }
6139
6140 # Spaces are evil.
6141 $host =~ s/^\s+//;
6142 $host =~ s/\s+$//;
6143 if ($typemap{$type} ne 'TXT') {
6144 # Leading or trailng spaces could be legit in TXT records.
6145 $val =~ s/^\s+//;
6146 $val =~ s/\s+$//;
6147 }
6148
6149 $self->_printrec_tiny($zonefilehandle, $recid, 'n', \%recflags,
6150 $dom, $host, $type, $val, $dist, $weight, $port, $ttl, $loc, $stamp, $expires, $stampactive);
6151
6152 $recflags{$recid} = 1;
6153
6154 } # while ($recsth)
6155
6156
6157 if ($self->{usecache}) {
6158 close ZONECACHE; # force the file to be written
6159 # catch obvious write errors that leave an empty temp file
6160 if (-s $tmpcache) {
6161 rename $tmpcache, $cachefile
6162 or die "Error overwriting cache file $cachefile with temporary file: $!\n";
6163 }
6164 }
6165
6166 } # if $changed or cache filesize is 0
6167
6168 };
6169 if ($@) {
6170 die "error writing ".($self->{usecache} ? 'new data for ' : '')."$dom: $@\n";
6171 # error! something borked, and we should be able to fall back on the old cache file
6172 # report the error, somehow.
6173 } else {
6174 # mark domain as unmodified. Only do this if no errors, that way
6175 # export failures should recover a little more automatically.
6176 $zonesth->execute($domid);
6177 }
6178
6179 if ($self->{usecache}) {
6180 # We've already made as sure as we can that a cached zone file is "good",
6181 # although possibly stale/obsolete due to errors creating a new one.
6182 eval {
6183 open CACHE, "<$cachefile" or die $!;
6184 print $datafile $_ or die "error copying cached $dom to master file: $!" while <CACHE>;
6185 close CACHE;
6186 };
6187 die $@ if $@;
6188 }
6189
6190 } # while ($domsth)
6191
6192 return 1;
6193} # end __export_tiny()
6194
6195
6196# Utility sub for __export_tiny above
6197sub _printrec_tiny {
6198 my $self = shift;
6199 my ($datafile, $recid, $revrec, $recflags, $zone, $host, $type, $val, $dist, $weight, $port, $ttl,
6200 $loc, $stamp, $expires, $stampactive) = @_;
6201
6202 $loc = '' if !$loc; # de-nullify - just in case
6203##fixme: handle case of record-with-location-that-doesn't-exist better.
6204# note this currently fails safe (tested) - records with a location that
6205# doesn't exist will not be sent to any client
6206# $loc = '' if !$lochash->{$loc};
6207
6208
6209## Records that are valid only before or after a set time
6210
6211# record due to expire sometime is the complex case. we don't want to just
6212# rely on tinydns' auto-adjusting TTLs, because the default TTL in that case
6213# is one day instead of the SOA minttl as BIND might do.
6214
6215# consider the case where a record is set to expire a week ahead, but the next
6216# day later you want to change it NOW (or as NOWish as you get with your DNS
6217# management practice). but now you're stuck, because someone, somewhere,
6218# has just done a lookup before your latest change was published, and they'll
6219# be caching that old, broken record for 1 day instead of your zone default
6220# TTL.
6221
6222# $stamp-$ttl is the *latest* we can publish the record with the defined TTL
6223# to still have the expiry happen as scheduled, but we need to find some
6224# *earlier* point. We can maybe guess, and 2x TTL is probably reasonable,
6225# but we need info on the export frequency.
6226
6227# export the normal, non-expiring record up until $stamp-<guesstimate>, then
6228# switch to exporting a record with the TAI64 stamp and a 0 TTL so tinydns
6229# takes over TTL management.
6230
6231 if ($stampactive) {
6232 if ($expires) {
6233 # record expires at $stamp; decide if we need to keep the TTL and ignore
6234 # the stamp for a time or if we need to change the TTL to 0 and convert
6235 # $stamp to TAI64 so tinydns can use $stamp to autoadjust the TTL on the fly.
6236# extra hack, optimally needs more knowledge of data export frequency
6237# smack the idiot customer who insists on 0 TTLs; they can suck up and
6238# deal with a 10-minute TTL. especially on scheduled changes. note this
6239# should be (export freq * 2), but we don't know the actual export frequency.
6240$ttl = 300 if $ttl == 0; #hack phtui
6241 my $ahead = (86400 < $ttl*2 ? 86400 : $ttl*2);
6242 if ((time() + $ahead) < $stamp) {
6243 # more than 2x TTL OR more than one day (whichever is less) from expiry time; publish normal record
6244 $stamp = '';
6245 } else {
6246 # less than 2x TTL from expiry time, let tinydns take over TTL management and publish the TAI64 stamp.
6247 $ttl = 0;
6248 $stamp = unixtai64($stamp);
6249 $stamp =~ s/\@//;
6250 }
6251 } else {
6252 # record is "active after"; convert epoch from database to TAI64, publish, and collect $200.
6253 $stamp = unixtai64($stamp);
6254 $stamp =~ s/\@//;
6255 }
6256 } else {
6257 # flag for active timestamp is false; don't actually put a timestamp in the output
6258 $stamp = '';
6259 }
6260
6261 # support tinydns' auto-TTL
6262 $ttl = '' if $ttl == -1;
6263# these are WAY FREAKING HIGH - higher even than most TLD registry TTLs!
6264# NS 259200 => 3d
6265# all others 86400 => 1d
6266
6267 if ($revrec eq 'y') {
6268 $val = $zone if $val eq '@';
6269 } else {
6270 $host = $zone if $host eq '@';
6271 }
6272
6273 ## Convert a bare number into an octal-coded pair of octets.
6274 # Take optional arg to indicate a decimal or hex input. Defaults to hex.
6275 sub octalize {
6276 my $tmp = shift;
6277 my $srctype = shift || 'h'; # default assumes hex string
6278 $tmp = sprintf "%0.4x", hex($tmp) if $srctype eq 'h'; # 0-pad hex to 4 digits
6279 $tmp = sprintf "%0.4x", $tmp if $srctype eq 'd'; # 0-pad decimal to 4 hex digits
6280 my @o = ($tmp =~ /^(..)(..)$/); # split into octets
6281 return sprintf "\\%0.3o\\%0.3o", hex($o[0]), hex($o[1]);
6282 }
6283
6284 # Utility sub-sub for reverse records; with "any-record-in-any-zone"
6285 # we may need to do extra processing on $val to make it publishable.
6286 sub __revswap {
6287 my $host = shift;
6288 my $val = shift;
6289 return ($val, $host) if $val =~ /\.arpa/;
6290 $val = new NetAddr::IP $val;
6291 my $newval = _ZONE($val, 'ZONE', 'r', '.').($val->{isv6} ? '.ip6.arpa' : '.in-addr.arpa');
6292 return ($newval, $host);
6293 }
6294
6295## WARNING: This works to export even the whole Internet's worth of IP space...
6296## if you have the disk/RAM to handle the dataset, and you call this sub based on /16-sized chunks
6297## A /16 took ~3 seconds with a handful of separate records; adding a /8 pushed export time out to ~13m:40s
6298## 0/0 is estimated to take ~54 hours and ~256G of disk
6299## RAM usage depends on how many non-template entries you have in the set.
6300## This should probably be done on record addition rather than export; large blocks may need to be done in a
6301## forked process
6302 sub __publish_subnet {
6303 my $self = shift; # *sigh* need to pass in the DNSDB object so we can read a couple of options
6304 my $sub = shift;
6305 my $recflags = shift;
6306 my $hpat = shift;
6307 my $fh = shift;
6308 my $ttl = shift;
6309 my $stamp = shift;
6310 my $loc = shift;
6311 my $zone = new NetAddr::IP shift;
6312 my $ptronly = shift || 0;
6313
6314 # do this conversion once, not (number-of-ips-in-subnet) times
6315 my $arpabase = _ZONE($zone, 'ZONE.in-addr.arpa', 'r', '.');
6316
6317 my $iplist = $sub->splitref(32);
6318 my $ipindex = -1;
6319 foreach (@$iplist) {
6320 my $ip = $_->addr;
6321 $ipindex++;
6322 # make as if we split the non-octet-aligned block into octet-aligned blocks as with SOA
6323 my $lastoct = (split /\./, $ip)[3];
6324 next if $$recflags{$ip}; # && $self->{skip_bcast_255}
6325 $$recflags{$ip}++;
6326 next if $hpat eq '%blank%'; # Allows blanking a subnet so no records are published.
6327 my $rec = $hpat; # start fresh with the template for each IP
6328##fixme: there really isn't a good way to handle sub-/24 zones here. This way at least
6329# seems less bad than some alternatives.
6330 $self->_template4_expand(\$rec, $ip, \$sub, $ipindex);
6331 # _template4_expand may blank $rec; if so, don't publish a record
6332 next if !$rec;
6333 if ($ptronly || $zone->masklen > 24) {
6334 print $fh "^$lastoct.$arpabase:$rec:$ttl:$stamp:$loc\n" or die $!;
6335 if (!$ptronly) {
6336 # print a separate A record. Arguably we could use an = record here instead.
6337 print $fh "+$rec:$ip:$ttl:$stamp:$loc\n" or die $!;
6338 }
6339 } else {
6340 print $fh "=$rec:$ip:$ttl:$stamp:$loc\n" or die $!;
6341 }
6342 }
6343 } # __publish_subnet
6344
6345## And now the meat.
6346
6347##fixme? append . to all host/val hostnames
6348#print "debug: rawdata: $host $typemap{$type} $val\n";
6349
6350 if ($typemap{$type} eq 'SOA') {
6351 # host contains pri-ns:responsible
6352 # val is abused to contain refresh:retry:expire:minttl
6353##fixme: "manual" serial vs tinydns-autoserial
6354 # let's be explicit about abusing $host and $val
6355 my ($email, $primary) = (split /:/, $host)[0,1];
6356 my ($refresh, $retry, $expire, $min_ttl) = (split /:/, $val)[0,1,2,3];
6357 if ($revrec eq 'y') {
6358##fixme: have to publish SOA records for each v4 /24 in sub-/16, and each /16 in sub-/8
6359# what about v6?
6360# -> only need SOA for local chunks offset from reverse delegation boundaries, so v6 is fine
6361# anyone who says they need sub-nibble v6 delegations, at this time, needs their head examined.
6362 $zone = NetAddr::IP->new($zone);
6363 # handle split-n-multiply SOA for off-octet (8 < mask < 16) or (16 < mask < 24) v4 zones
6364 if (!$zone->{isv6} && ($zone->masklen < 24) && ($zone->masklen % 8 != 0)) {
6365 foreach my $szone ($zone->split($zone->masklen + (8 - $zone->masklen % 8))) {
6366 $szone = _ZONE($szone, 'ZONE.in-addr.arpa', 'r', '.');
6367 print $datafile "Z$szone:$primary:$email"."::$refresh:$retry:$expire:$min_ttl:$ttl:$stamp:$loc\n"
6368 or die $!;
6369 }
6370 return; # skips "default" bits just below
6371 }
6372 $zone = _ZONE($zone, 'ZONE', 'r', '.').($zone->{isv6} ? '.ip6.arpa' : '.in-addr.arpa');
6373 }
6374 print $datafile "Z$zone:$primary:$email"."::$refresh:$retry:$expire:$min_ttl:$ttl:$stamp:$loc\n"
6375 or die $!;
6376
6377 } elsif ($typemap{$type} eq 'A') {
6378
6379 ($host,$val) = __revswap($host,$val) if $revrec eq 'y';
6380 print $datafile "+$host:$val:$ttl:$stamp:$loc\n" or die $!;
6381
6382 } elsif ($typemap{$type} eq 'NS') {
6383
6384 if ($revrec eq 'y') {
6385 $val = NetAddr::IP->new($val);
6386 # handle split-n-multiply SOA for off-octet (8 < mask < 16) or (16 < mask < 24) v4 zones
6387 if (!$val->{isv6} && ($val->masklen < 24) && ($val->masklen % 8 != 0)) {
6388 foreach my $szone ($val->split($val->masklen + (8 - $val->masklen % 8))) {
6389 my $szone2 = _ZONE($szone, 'ZONE.in-addr.arpa', 'r', '.');
6390 next if $$recflags{$szone2} && $$recflags{$szone2} > $val->masklen;
6391 print $datafile "\&$szone2"."::$host:$ttl:$stamp:$loc\n" or die $!;
6392 $$recflags{$szone2} = $val->masklen;
6393 }
6394 } elsif ($val->{isv6} && ($val->masklen < 64) && ($val->masklen % 4 !=0)) {
6395 foreach my $szone ($val->split($val->masklen + (4 - $val->masklen % 4))) {
6396 my $szone2 = _ZONE($szone, 'ZONE.ip6.arpa', 'r', '.');
6397 next if $$recflags{$szone2} && $$recflags{$szone2} > $val->masklen;
6398 print $datafile "\&$szone2"."::$host:$ttl:$stamp:$loc\n" or die $!;
6399 $$recflags{$szone2} = $val->masklen;
6400 }
6401 } else {
6402 my $val2 = _ZONE($val, 'ZONE', 'r', '.').($val->{isv6} ? '.ip6.arpa' : '.in-addr.arpa');
6403 print $datafile "\&$val2"."::$host:$ttl:$stamp:$loc\n" or die $!;
6404 $$recflags{$val2} = $val->masklen;
6405 }
6406 } else {
6407 print $datafile "\&$host"."::$val:$ttl:$stamp:$loc\n" or die $!;
6408 }
6409
6410 } elsif ($typemap{$type} eq 'AAAA') {
6411
6412 ($host,$val) = __revswap($host,$val) if $revrec eq 'y';
6413 my $altgrp = 0;
6414 my @altconv;
6415 # Split in to up to 8 groups of hex digits (allows for IPv6 :: 0-collapsing)
6416 foreach (split /:/, $val) {
6417 if (/^$/) {
6418 # flag blank entry; this is a series of 0's of (currently) unknown length
6419 $altconv[$altgrp++] = 's';
6420 } else {
6421 # call sub to convert 1-4 hex digits to 2 string-rep octal bytes
6422 $altconv[$altgrp++] = octalize($_)
6423 }
6424 }
6425 my $prefix = ":$host:28:";
6426 foreach my $octet (@altconv) {
6427 # if not 's', output
6428 $prefix .= $octet unless $octet =~ /^s$/;
6429 # if 's', output (9-array length)x literal '\000\000'
6430 $prefix .= '\000\000'x(9-$altgrp) if $octet =~ /^s$/;
6431 }
6432 print $datafile "$prefix:$ttl:$stamp:$loc\n" or die $!;
6433
6434 } elsif ($typemap{$type} eq 'MX') {
6435
6436 ($host,$val) = __revswap($host,$val) if $revrec eq 'y';
6437 print $datafile "\@$host"."::$val:$dist:$ttl:$stamp:$loc\n" or die $!;
6438
6439 } elsif ($typemap{$type} eq 'TXT') {
6440
6441 ($host,$val) = __revswap($host,$val) if $revrec eq 'y';
6442# le sigh. Some idiot DNS implementations don't seem to like tinydns autosplitting
6443# long TXT records at 127 characters instead of 255. Hand-crafting a record seems
6444# to paper over the remote stupid. We will NOT try to split on whitespace; the
6445# contents of a TXT record are opaque and clients who can't deal are even more broken
6446# than the ones that don't like them split at 127 characters... because BIND tries
6447# to "intelligently" split TXT data, and abso-by-damn-lutely generates chunks <255
6448# characters, and anything that can't interpret BIND's DNS responses has no business
6449# trying to interpret DNS data at all.
6450
6451 if ($self->{autotxt}) {
6452 # let tinydns deal with splitting the record. note tinydns autosplits at 127
6453 # characters, not 255. Because Reasons.
6454 $val =~ s/:/\\072/g; # may need to replace other symbols
6455 print $datafile "'$host:$val:$ttl:$stamp:$loc\n" or die $!;
6456 } else {
6457 print $datafile ":$host:16:";
6458 my @txtsegs = $val =~ /.{1,255}/g;
6459 foreach (@txtsegs) {
6460 my $len = length($_);
6461 s/:/\\072/g;
6462 printf $datafile "\\%0.3o%s", $len, $_;
6463 }
6464 print $datafile ":$ttl:$stamp:$loc\n";
6465 }
6466
6467# by-hand TXT
6468#:deepnet.cx:16:2v\075spf1\040a\040a\072bacon.deepnet.cx\040a\072home.deepnet.cx\040-all:3600
6469#@ IN TXT "v=spf1 a a:bacon.deepnet.cx a:home.deepnet.cx -all"
6470#'deepnet.cx:v=spf1 a a\072bacon.deepnet.cx a\072home.deepnet.cx -all:3600
6471
6472#txttest IN TXT "v=foo bar:bob kn;ob' \" !@#$%^&*()-=_+[]{}<>?"
6473#:txttest.deepnet.cx:16:\054v\075foo\040bar\072bob\040kn\073ob\047\040\042\040\041\100\043\044\045\136\046\052\050\051-\075\137\053\133\135\173\175\074\076\077:3600
6474
6475# very long TXT record as brought in by axfr-get
6476# note tinydns does not support >512-byte RR data, need axfr-dns (for TCP support) for that
6477# also note, tinydns does not seem to support <512, >256-byte RRdata from axfr-get either. :/
6478#:longtxt.deepnet.cx:16:
6479#\170this is a very long txt record. it is really long. long. very long. really very long. this is a very long txt record.
6480#\263 it is really long. long. very long. really very long. this is a very long txt record. it is really long. long. very long. really very long. this is a very long txt record.
6481#\351 it is really long. long. very long. really very long.this is a very long txt record. it is really long. long. very long. really very long. this is a very long txt record. it is really long. long. very long. really very long.
6482#:3600
6483
6484 } elsif ($typemap{$type} eq 'CNAME') {
6485
6486 ($host,$val) = __revswap($host,$val) if $revrec eq 'y';
6487 print $datafile "C$host:$val:$ttl:$stamp:$loc\n" or die $!;
6488
6489 } elsif ($typemap{$type} eq 'SRV') {
6490
6491 ($host,$val) = __revswap($host,$val) if $revrec eq 'y';
6492
6493 # data is two-byte values for priority, weight, port, in that order,
6494 # followed by length/string data
6495
6496 my $prefix = ":$host:33:".octalize($dist,'d').octalize($weight,'d').octalize($port,'d');
6497
6498 $val .= '.' if $val !~ /\.$/;
6499 foreach (split /\./, $val) {
6500 $prefix .= sprintf "\\%0.3o%s", length($_), $_ or die $!;
6501 }
6502 print $datafile "$prefix\\000:$ttl:$stamp:$loc\n" or die $!;
6503
6504 } elsif ($typemap{$type} eq 'RP') {
6505
6506 ($host,$val) = __revswap($host,$val) if $revrec eq 'y';
6507 # RP consists of two mostly free-form strings.
6508 # The first is supposed to be an email address with @ replaced by . (as with the SOA contact)
6509 # The second is the "hostname" of a TXT record with more info.
6510 my $prefix = ":$host:17:";
6511 my ($who,$what) = split /\s/, $val;
6512 foreach (split /\./, $who) {
6513 $prefix .= sprintf "\\%0.3o%s", length($_), $_;
6514 }
6515 $prefix .= '\000';
6516 foreach (split /\./, $what) {
6517 $prefix .= sprintf "\\%0.3o%s", length($_), $_;
6518 }
6519 print $datafile "$prefix\\000:$ttl:$stamp:$loc\n" or die $!;
6520
6521 } elsif ($typemap{$type} eq 'PTR') {
6522
6523 $$recflags{$val}++;
6524 if ($revrec eq 'y') {
6525
6526 if ($val =~ /\.arpa$/) {
6527 # someone put in the formal .arpa name. humor them.
6528 print $datafile "^$val:$host:$ttl:$stamp:$loc\n" or die $!;
6529 } else {
6530 $zone = NetAddr::IP->new($zone);
6531 if (!$zone->{isv6} && $zone->masklen > 24) {
6532 # sub-octet v4 zone
6533 ($val) = ($val =~ /\.(\d+)$/);
6534 print $datafile "^$val."._ZONE($zone, 'ZONE', 'r', '.').'.in-addr.arpa'.
6535 ":$host:$ttl:$stamp:$loc\n" or die $!;
6536 } else {
6537 # not going to care about strange results if $val is not an IP value and is resolveable in DNS
6538 $val = NetAddr::IP->new($val);
6539 print $datafile "^".
6540 _ZONE($val, 'ZONE', 'r', '.').($val->{isv6} ? '.ip6.arpa' : '.in-addr.arpa').
6541 ":$host:$ttl:$stamp:$loc\n" or die $!;
6542 }
6543 } # non-".arpa" $val
6544
6545 } else {
6546 # PTRs in forward zones are less bizarre and insane than some other record types
6547 # in reverse zones... OTOH we can't validate them any which way, so we cross our
6548 # fingers and close our eyes and make it Someone Else's Problem.
6549 print $datafile "^$host:$val:$ttl:$stamp:$loc\n" or die $!;
6550 }
6551
6552 } elsif ($type == 65280) { # A+PTR
6553
6554 $$recflags{$val}++;
6555 print $datafile "=$host:$val:$ttl:$stamp:$loc\n" or die $!;
6556
6557 } elsif ($type == 65281) { # AAAA+PTR
6558
6559 $$recflags{$val}++;
6560 # treat these as two separate records. since tinydns doesn't have
6561 # a native combined type, we have to create them separately anyway.
6562 # print both; a dangling record is harmless, and impossible via web
6563 # UI anyway
6564 $self->_printrec_tiny($datafile,$recid,'n',$recflags, $self->domainName($self->_hostparent($host)),
6565 $host, 28, $val, $dist, $weight, $port, $ttl, $loc, $stamp);
6566 $self->_printrec_tiny($datafile, $recid, 'y', $recflags, $zone,
6567 $host, 12, $val, $dist, $weight, $port, $ttl, $loc, $stamp);
6568
6569##fixme: add a config flag to indicate use of the patch from http://www.fefe.de/dns/
6570# type 6 is for AAAA+PTR, type 3 is for AAAA
6571
6572 } elsif ($type == 65282) { # PTR template
6573
6574 # only useful for v4 with standard DNS software, since this expands all
6575 # IPs in $zone (or possibly $val?) with autogenerated records
6576 $val = NetAddr::IP->new($val);
6577 return if $val->{isv6};
6578
6579 if ($val->masklen <= 16) {
6580 foreach my $sub ($val->split(16)) {
6581 $self->__publish_subnet($sub, $recflags, $host, $datafile, $ttl, $stamp, $loc, $zone, 1);
6582 }
6583 } else {
6584 $self->__publish_subnet($val, $recflags, $host, $datafile, $ttl, $stamp, $loc, $zone, 1);
6585 }
6586
6587 } elsif ($type == 65283) { # A+PTR template
6588
6589 $val = NetAddr::IP->new($val);
6590 # Just In Case. An A+PTR should be impossible to add to a v6 revzone via API.
6591 return if $val->{isv6};
6592
6593 if ($val->masklen < 16) {
6594 foreach my $sub ($val->split(16)) {
6595 $self->__publish_subnet($sub, $recflags, $host, $datafile, $ttl, $stamp, $loc, $zone, 0);
6596 }
6597 } else {
6598 $self->__publish_subnet($val, $recflags, $host, $datafile, $ttl, $stamp, $loc, $zone, 0);
6599 }
6600
6601 } elsif ($type == 65284) { # AAAA+PTR template
6602 # Stub for completeness. Could be exported to DNS software that supports
6603 # some degree of internal automagic in generic-record-creation
6604 # (eg http://search.cpan.org/dist/AllKnowingDNS/ )
6605
6606 } elsif ($type == 65285) { # Delegation
6607 # This is intended for reverse zones, but may prove useful in forward zones.
6608
6609 # All delegations need to create one or more NS records. The NS record handler knows what to do.
6610 $self->_printrec_tiny($datafile,$recid,$revrec,$recflags,$zone,$host,$reverse_typemap{'NS'},
6611 $val,$dist,$weight,$port,$ttl,$loc,$stamp);
6612 if ($revrec eq 'y') {
6613 # In the case of a sub-/24 v4 reverse delegation, we need to generate CNAMEs
6614 # to redirect all of the individual IP lookups as well.
6615 # OR
6616 # create NS records for each IP
6617 # Not sure how this would actually resolve if a /24 or larger was delegated
6618 # one way, and a sub-/24 in that >=/24 was delegated elsewhere...
6619 my $dblock = NetAddr::IP->new($val);
6620 if (!$dblock->{isv6} && $dblock->masklen > 24) {
6621 my @subs = $dblock->split;
6622 foreach (@subs) {
6623 next if $$recflags{"$_"};
6624 my ($oct) = ($_->addr =~ /(\d+)$/);
6625 print $datafile "C"._ZONE($_, 'ZONE.in-addr.arpa', 'r', '.').":$oct.".
6626 _ZONE($dblock, 'ZONE.in-addr.arpa', 'r', '.').":$ttl:$stamp:$loc\n" or die $!;
6627 $$recflags{"$_"}++;
6628 }
6629 }
6630 }
6631
6632##
6633## Uncommon types. These will need better UI support Any Day Sometime Maybe(TM).
6634##
6635
6636 } elsif ($type == 44) { # SSHFP
6637
6638 ($host,$val) = __revswap($host,$val) if $revrec eq 'y';
6639
6640 my ($algo,$fpt,$fp) = split /\s+/, $val;
6641
6642 my $rec = sprintf ":$host:44:\\%0.3o\\%0.3o", $algo, $fpt;
6643 while (my ($byte) = ($fp =~ /^(..)/) ) {
6644 $rec .= sprintf "\\%0.3o", hex($byte);
6645 $fp =~ s/^..//;
6646 }
6647 print $datafile "$rec:$ttl:$stamp:$loc\n" or die $!;
6648
6649 } else {
6650 # raw record. we don't know what's in here, so we ASS-U-ME the user has
6651 # put it in correctly, since either the user is messing directly with the
6652 # database, or the record was imported via AXFR
6653 # <split by char>
6654 # convert anything not a-zA-Z0-9.- to octal coding
6655
6656##fixme: add flag to export "unknown" record types - note we'll probably end up
6657# mangling them since they were written to the DB from Net::DNS::RR::<type>->rdatastr.
6658 #print $datafile ":$host:$type:$val:$ttl:$stamp:$loc\n";
6659
6660 } # record type if-else
6661
6662} # end _printrec_tiny()
6663
6664
6665## DNSDB::mailNotify()
6666# Sends notification mail to recipients regarding a DNSDB operation
6667sub mailNotify {
6668 my $self = shift;
6669 my $dbh = $self->{dbh};
6670 my ($subj,$message) = @_;
6671
6672 return if $self->{mailhost} eq 'smtp.example.com'; # do nothing if still using default SMTP host.
6673
6674 my $mailer = Net::SMTP->new($self->{mailhost}, Hello => "dnsadmin.$self->{domain}");
6675
6676 my $mailsender = ($self->{mailsender} ? $self->{mailsender} : $self->{mailnotify});
6677
6678 $mailer->mail($mailsender);
6679 $mailer->to($self->{mailnotify});
6680 $mailer->data("From: \"$self->{mailname}\" <$mailsender>\n",
6681 "To: <$self->{mailnotify}>\n",
6682 "Date: ".strftime("%a, %d %b %Y %H:%M:%S %z",localtime)."\n",
6683 "Subject: $subj\n",
6684 "X-Mailer: DNSAdmin v".$DNSDB::VERSION." Notify\n",
6685 "Organization: $self->{orgname}\n",
6686 "\n$message\n");
6687 $mailer->quit;
6688}
6689
6690# shut Perl up
66911;
Note: See TracBrowser for help on using the repository browser.