source: trunk/DNSDB.pm@ 631

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

/trunk

Get an ##enhance comment in about validating SRV records: Consider a
config flag to allow "nonstandard" SRV records that don't match
_service._proto.

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