source: trunk/DNSDB.pm@ 494

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

/trunk

Tweak RPC to run as FastCGI, and add another config option to control
the number of requests to handle before respawning

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