source: trunk/DNSDB.pm@ 764

Last change on this file since 764 was 764, checked in by Kris Deugau, 7 years ago

/trunk

Extract a key, complex, core bit of ALIAS processing (grabbing the chained
A records for the target and collapsing them into a blob for storage/export)
from two places, and put it in a sub for better maintenance.

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