source: branches/stable/DNSDB.pm@ 547

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

/branches/stable

Merge reverse DNS work and object conversion from /trunk, 4 of mumble

Includes changes through r492 with a few minor conflicts.

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