source: trunk/DNSDB.pm@ 542

Last change on this file since 542 was 542, checked in by Kris Deugau, 10 years ago

/trunk

Add config knob and supporting code to forcibly case-fold domain names
and hostnames. Defaults to off.

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