source: trunk/DNSDB.pm@ 624

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

/trunk

Fix the closing comment/flag on _validate_65283() (A+PTR template); it

was indicating 'AAAA+PTR template'.

Add a header note/reminder to AAAA+PTR template.

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