source: trunk/DNSDB.pm@ 626

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

/trunk

Update _validate_28() (AAAA) for any-record-in-any-zone. See #53.

Also fix up a subtle potential bug in _validate_1(); don't use the passed-in
NetAddr::IP in $args{addr} as it may be something funky.

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