source: trunk/DNSDB.pm@ 629

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

/trunk

Fix the fix in r626; it tried to convert the wrong part of the record
to a NetAddr::IP.

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