source: trunk/DNSDB.pm@ 575

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

/trunk

Squash the missing-SOA-on-AXFR bug; SOA and NS records would not be
copied correctly when the "Rewrite SOA" or "Rewrite NS" options were
checked.

Pass the record ID into _printrec_tiny(), mainly as a debugging aid.

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