source: trunk/DNSDB.pm@ 639

Last change on this file since 639 was 639, checked in by Kris Deugau, 11 years ago

/trunk

Add a little more checking to AXFR imports; warn but do not discard
on bare IP addresses (or things-that-look-like-IP-addresses) for NS,
CNAME, and SRV records.

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