source: trunk/DNSDB.pm@ 620

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

/trunk

Near-complete rewrite of _validate_12() (PTR) to support any-record-in-any-zone.
Introduce new default record template ARPAZONE for those times when you really
want something strange in all your reverse zones.

See #53.

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