source: trunk/DNSDB.pm@ 660

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

/trunk

Tweak some IP validation internals; accept a CIDR suffix to be nice to

callers.

Almost(?) always use inetlazy() function on sorts on the records table;

it looks bad to have reverse records properly sorted by IP, but domain
records only sorted by string value.

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