source: trunk/DNSDB.pm@ 523

Last change on this file since 523 was 523, checked in by Kris Deugau, 12 years ago

/trunk

Swap forward and reverse zone export order to better handle dangling =
records created by tiny-import.pl's -l option. Exporting all reverse-zone
pseudotype records first will let us ignore most of them while exporting
forward zones, without skipping the dangling ones not associated with a
reverse zone.

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