source: trunk/DNSDB.pm@ 673

Last change on this file since 673 was 673, checked in by Kris Deugau, 9 years ago

/trunk

Add getRevSet() to retrieve a whole set of per-IP reverse names, and

expose via RPC

Fix module name in comment header for getRevPattern()

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