source: trunk/DNSDB.pm@ 618

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

/trunk

Update _validate_5() (CNAME) for any-record-in-any-zone. See #53.

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