source: trunk/DNSDB.pm@ 653

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

/trunk

Fix up subtle bugs in handling of '@' as a hostname a la BIND. This
commit fixes add/update (validation).

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