source: trunk/DNSDB.pm@ 617

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

/trunk

Move case-folding in addRec() and updateRec() to its own sub. Add calls
in addDomain() and addRDNS() to case-fold records after all the other
mangling is done, just before inserting the new live record.

Extends/updates change in r542.

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