source: trunk/DNSDB.pm@ 674

Last change on this file since 674 was 674, checked in by Kris Deugau, 9 years ago

/trunk

Fill in _validate_65284 so that it doesn't just blindly accept gibberish.

Still need to fill in a segment for export of these AAAA+PTR template
records; can't expand them the way A+PTR template records get handled.

Add a little more checking in addRec() to make sure we have both a host

and value.

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