source: trunk/DNSDB.pm@ 473

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

/trunk

Object conversion of DNSDB.pm, 8 of <mumble>. See #11.

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