source: branches/stable/DNSDB.pm@ 623

Last change on this file since 623 was 587, checked in by Kris Deugau, 11 years ago

/branches/stable

Merge forward bugfixes and option additions from /trunk r583 through r586.
Bump version patch number.

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