source: trunk/DNSDB.pm@ 622

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

/trunk

Commit update to MX record validation for any-record-in-any-zone.
See #53.

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