source: trunk/DNSDB.pm@ 585

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

/trunk

Add .arpa detection to record update to match record add.

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