source: trunk/DNSDB.pm@ 543

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

/trunk

Implement most of the UI and back end for handling scheduled changes
to records. See #40.

This turned out to be most of what I had vaguely imagined; only SOA
records can't sanely be set for scheduled changes yet (can't think of
a scenario where this would even be useful) and there's only a small
dusting of UI chrome left for another time.

Bumped up from projected 1.4 to 1.2 per request from Reid Sutherland.

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