source: trunk/DNSDB.pm@ 652

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

/trunk

Add options to skip export of .0 and .255 IPs in template records.
Required tweaking calls to _printrec_tiny() and some of its inner subs
to pass the DNSDB object down to where the option is actually used.

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