source: trunk/DNSDB.pm@ 528

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

/trunk

Fix AAAA+PTR record export; somewhere long the way this broke (or never
worked and wasn't noticed as broken)

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