source: trunk/DNSDB.pm@ 541

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

/trunk

Add a comment about a bit more info found on a ##fixme

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