source: trunk/DNSDB.pm@ 392

Last change on this file since 392 was 391, checked in by Kris Deugau, 12 years ago

/trunk

Add support for new permissions to addUser()'s permission type check. See #10.

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