source: trunk/DNSDB.pm@ 465

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

/trunk

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

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