source: trunk/DNSDB.pm@ 489

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

/trunk

Object conversion of DNSDB.pm, part 21. See #11.

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