source: trunk/DNSDB.pm@ 609

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

/trunk

Remove checks in addRec() and updateRec() that blocked reverse records
with a "value" that wasn't a formally correct IP address or rDNS .arpa
name for an IP.

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