source: trunk/DNSDB.pm@ 276

Last change on this file since 276 was 276, checked in by Kris Deugau, 13 years ago

/trunk

Add revID sub to match domainID for consistency

  • Property svn:keywords set to Date Rev Author Id
File size: 107.1 KB
RevLine 
[2]1# dns/trunk/DNSDB.pm
2# Abstraction functions for DNS administration
[262]3##
4# $Id: DNSDB.pm 276 2012-03-15 20:44:53Z kdeugau $
5# Copyright 2008-2011 Kris Deugau <kdeugau@deepnet.cx>
6#
7# This program is free software: you can redistribute it and/or modify
8# it under the terms of the GNU General Public License as published by
9# the Free Software Foundation, either version 3 of the License, or
10# (at your option) any later version.
11#
12# This program is distributed in the hope that it will be useful,
13# but WITHOUT ANY WARRANTY; without even the implied warranty of
14# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15# GNU General Public License for more details.
16#
17# You should have received a copy of the GNU General Public License
18# along with this program. If not, see <http://www.gnu.org/licenses/>.
19##
[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;
[2]32use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
33
[200]34$VERSION = 0.1; ##VERSION##
[2]35@ISA = qw(Exporter);
36@EXPORT_OK = qw(
[67]37 &initGlobals
38 &initPermissions &getPermissions &changePermissions &comparePermissions
[112]39 &changeGroup
[128]40 &loadConfig &connectDB &finish
[276]41 &addDomain &delZone &domainName &revName &domainID &revID &addRDNS
[237]42 &getZoneCount &getZoneList
[22]43 &addGroup &delGroup &getChildren &groupName
[83]44 &addUser &updateUser &delUser &userFullName &userStatus &getUserData
[91]45 &getSOA &getRecLine &getDomRecs &getRecCount
[22]46 &addRec &updateRec &delRec
[225]47 &getTypelist
[254]48 &parentID
[117]49 &isParent
[275]50 &zoneStatus &importAXFR
[103]51 &export
[197]52 &mailNotify
[128]53 %typemap %reverse_typemap %config
[66]54 %permissions @permtypes $permlist
[2]55 );
56
57@EXPORT = (); # Export nothing by default.
58%EXPORT_TAGS = ( ALL => [qw(
[67]59 &initGlobals
60 &initPermissions &getPermissions &changePermissions &comparePermissions
[112]61 &changeGroup
[128]62 &loadConfig &connectDB &finish
[276]63 &addDomain &delZone &domainName &revName &domainID &revID &addRDNS
[237]64 &getZoneCount &getZoneList
[22]65 &addGroup &delGroup &getChildren &groupName
[83]66 &addUser &updateUser &delUser &userFullName &userStatus &getUserData
[91]67 &getSOA &getRecLine &getDomRecs &getRecCount
[22]68 &addRec &updateRec &delRec
[225]69 &getTypelist
[254]70 &parentID
[117]71 &isParent
[275]72 &zoneStatus &importAXFR
[103]73 &export
[197]74 &mailNotify
[128]75 %typemap %reverse_typemap %config
[66]76 %permissions @permtypes $permlist
[2]77 )]
78 );
79
80our $group = 1;
81our $errstr = '';
82
83# Halfway sane defaults for SOA, TTL, etc.
[101]84# serial defaults to 0 for convenience.
85# value will be either YYYYMMDDNN for BIND/etc, or auto-internal for tinydns
[2]86our %def = qw (
87 contact hostmaster.DOMAIN
88 prins ns1.myserver.com
[101]89 serial 0
[2]90 soattl 86400
91 refresh 10800
92 retry 3600
93 expire 604800
94 minttl 10800
95 ttl 10800
96);
97
[66]98# Arguably defined wholly in the db, but little reason to change without supporting code changes
99our @permtypes = qw (
100 group_edit group_create group_delete
101 user_edit user_create user_delete
102 domain_edit domain_create domain_delete
103 record_edit record_create record_delete
104 self_edit admin
105);
106our $permlist = join(',',@permtypes);
107
[2]108# DNS record type map and reverse map.
109# loaded from the database, from http://www.iana.org/assignments/dns-parameters
110our %typemap;
111our %reverse_typemap;
112
[65]113our %permissions;
[55]114
[128]115# Prepopulate a basic config. Note some of these *will* cause errors if left unset.
[195]116# note: add appropriate stanzas in loadConfig to parse these
[128]117our %config = (
118 # Database connection info
119 dbname => 'dnsdb',
120 dbuser => 'dnsdb',
121 dbpass => 'secret',
122 dbhost => '',
123
124 # Email notice settings
125 mailhost => 'smtp.example.com',
[195]126 mailnotify => 'dnsdb@example.com', # to
127 mailsender => 'dnsdb@example.com', # from
[128]128 mailname => 'DNS Administration',
[195]129 orgname => 'Example Corp',
130 domain => 'example.com',
[128]131
132 # Template directory
133 templatedir => 'templates/',
134# fmeh. this is a real web path, not a logical internal one. hm..
[163]135# cssdir => 'templates/',
[216]136 sessiondir => 'session/',
[163]137
138 # Session params
[195]139 timeout => '3600', # 1 hour default
140
141 # Other miscellanea
142 log_failures => 1, # log all evarthing by default
[201]143 perpage => 15,
[128]144 );
145
[228]146## (Semi)private variables
147# Hash of functions for validating record types. Filled in initGlobals() since
148# it relies on visibility flags from the rectypes table in the DB
149my %validators;
[128]150
[228]151
[2]152##
[225]153## utility functions
[224]154# _rectable()
155# Takes default+rdns flags, returns appropriate table name
156sub _rectable {
157 my $def = shift;
158 my $rev = shift;
159
160 return 'records' if $def ne 'y';
161 return 'default_records' if $rev ne 'y';
162 return 'default_rev_records';
163} # end _rectable()
164
165# _recparent()
166# Takes default+rdns flags, returns appropriate parent-id column name
167sub _recparent {
168 my $def = shift;
169 my $rev = shift;
170
171 return 'group_id' if $def eq 'y';
172 return 'rdns_id' if $rev eq 'y';
173 return 'domain_id';
174} # end _recparent()
175
[226]176# Check an IP to be added in a reverse zone to see if it's really in the requested parent.
177# Takes a database handle, default and reverse flags, IP (fragment) to check, parent zone ID,
178# and a reference to a NetAddr::IP object (also used to pass back a fully-reconstructed IP for
179# database insertion)
180sub _ipparent {
181 my $dbh = shift;
182 my $defrec = shift;
183 my $revrec = shift;
184 my $val = shift;
185 my $id = shift;
186 my $addr = shift;
[224]187
[232]188 return if $revrec ne 'y'; # this sub not useful in forward zones
189
190 $$addr = NetAddr::IP->new($$val); #necessary?
191
[226]192 # subsub to split, reverse, and overlay an IP fragment on a netblock
193 sub __rev_overlay {
194 my $splitme = shift; # ':' or '.', m'lud?
195 my $parnet = shift;
196 my $val = shift;
197 my $addr = shift;
198
199 my $joinme = $splitme;
200 $splitme = '\.' if $splitme eq '.';
[232]201 my @working = reverse(split($splitme, $parnet->addr));
202 my @parts = reverse(split($splitme, $$val));
[226]203 for (my $i = 0; $i <= $#parts; $i++) {
204 $working[$i] = $parts[$i];
205 }
[232]206 my $checkme = NetAddr::IP->new(join($joinme, reverse(@working))) or return 0;
207 return 0 unless $checkme->within($parnet);
[226]208 $$addr = $checkme; # force "correct" IP to be recorded.
209 return 1;
210 }
211
212 my ($parstr) = $dbh->selectrow_array("SELECT revnet FROM revzones WHERE rdns_id = ?", undef, ($id));
213 my $parnet = NetAddr::IP->new($parstr);
214
215 # Fail early on v6-in-v4 or v4-in-v6. We're not accepting these ATM.
[232]216 return 0 if $parnet->addr =~ /\./ && $$val =~ /:/;
217 return 0 if $parnet->addr =~ /:/ && $$val =~ /\./;
[226]218
[234]219 if ($$addr && $$val =~ /^[\da-fA-F][\da-fA-F:]+[\da-fA-F]$/) {
[232]220 # the only case where NetAddr::IP's acceptance of legitimate IPs is "correct" is for a proper IPv6 address.
221 # the rest we have to restructure before fiddling. *sigh*
222 return 1 if $$addr->within($parnet);
223 } else {
224 # We don't have a complete IP in $$val (yet)
225 if ($parnet->addr =~ /:/) {
226 $$val =~ s/^:+//; # gotta strip'em all...
[226]227 return __rev_overlay(':', $parnet, $val, $addr);
228 }
[232]229 if ($parnet->addr =~ /\./) {
230 $$val =~ s/^\.+//;
231 return __rev_overlay('.', $parnet, $val, $addr);
232 }
[226]233 # should be impossible to get here...
234 }
235 # ... and here.
236 # can't do nuttin' in forward zones
237} # end _ipparent()
238
[232]239# A little different than _ipparent above; this tries to *find* the parent zone of a hostname
240sub _hostparent {
241 my $dbh = shift;
242 my $hname = shift;
243
244 my @hostbits = split /\./, $hname;
245 my $sth = $dbh->prepare("SELECT count(*),domain_id FROM domains WHERE domain = ? GROUP BY domain_id");
246 foreach (@hostbits) {
247 $sth->execute($hname);
248 my ($found, $parid) = $sth->fetchrow_array;
249 if ($found) {
250 return $parid;
251 }
252 $hname =~ s/^$_\.//;
253 }
254} # end _hostparent()
[228]255
[224]256##
[228]257## Record validation subs.
258##
259
260# A record
261sub _validate_1 {
[229]262 my $dbh = shift;
263
[230]264 my %args = @_;
[229]265
[230]266 return ('FAIL', 'Reverse zones cannot contain A records') if $args{revrec} eq 'y';
[229]267
268 # Coerce all hostnames to end in ".DOMAIN" for group/default records,
269 # or the intended parent domain for live records.
[230]270 my $pname = ($args{defrec} eq 'y' ? 'DOMAIN' : domainName($dbh,$args{id}));
271 ${$args{host}} =~ s/\.*$/\.$pname/ if ${$args{host}} !~ /$pname$/;
[229]272
273 # Check IP is well-formed, and that it's a v4 address
[234]274 # Fail on "compact" IPv4 variants, because they are not consistent and predictable.
[232]275 return ('FAIL',"$typemap{${$args{rectype}}} record must be a valid IPv4 address")
[234]276 unless ${$args{val}} =~ /^\d+\.\d+\.\d+\.\d+$/;
277 return ('FAIL',"$typemap{${$args{rectype}}} record must be a valid IPv4 address")
[230]278 unless $args{addr} && !$args{addr}->{isv6};
[229]279 # coerce IP/value to normalized form for storage
[230]280 ${$args{val}} = $args{addr}->addr;
[229]281
[228]282 return ('OK','OK');
283} # done A record
284
285# NS record
286sub _validate_2 {
[230]287 my $dbh = shift;
288
289 my %args = @_;
290
291 # Coerce the hostname to "DOMAIN" for forward default records, "ZONE" for reverse default records,
292 # or the intended parent zone for live records.
293##fixme: allow for delegating <subdomain>.DOMAIN?
294 if ($args{revrec} eq 'y') {
295 my $pname = ($args{defrec} eq 'y' ? 'ZONE' : revName($dbh,$args{id}));
296 ${$args{host}} = $pname if ${$args{host}} ne $pname;
297 } else {
298 my $pname = ($args{defrec} eq 'y' ? 'DOMAIN' : domainName($dbh,$args{id}));
299 ${$args{host}} = $pname if ${$args{host}} ne $pname;
300 }
301
302# Let this lie for now. Needs more magic.
303# # Check IP is well-formed, and that it's a v4 address
304# return ('FAIL',"A record must be a valid IPv4 address")
305# unless $addr && !$addr->{isv6};
306# # coerce IP/value to normalized form for storage
307# $$val = $addr->addr;
308
[228]309 return ('OK','OK');
310} # done NS record
311
312# CNAME record
313sub _validate_5 {
[230]314 my $dbh = shift;
315
316 my %args = @_;
317
318# Not really true, but these are only useful for delegating smaller-than-/24 IP blocks.
319# This is fundamentally a messy operation and should really just be taken care of by the
320# export process, not manual maintenance of the necessary records.
321 return ('FAIL', 'Reverse zones cannot contain CNAME records') if $args{revrec} eq 'y';
322
323 # Coerce all hostnames to end in ".DOMAIN" for group/default records,
324 # or the intended parent domain for live records.
325 my $pname = ($args{defrec} eq 'y' ? 'DOMAIN' : domainName($dbh,$args{id}));
326 ${$args{host}} =~ s/\.*$/\.$pname/ if ${$args{host}} !~ /$pname$/;
327
[228]328 return ('OK','OK');
329} # done CNAME record
330
331# SOA record
332sub _validate_6 {
[230]333 # Smart monkeys won't stick their fingers in here; we have
334 # separate dedicated routines to deal with SOA records.
[228]335 return ('OK','OK');
336} # done SOA record
337
338# PTR record
339sub _validate_12 {
[232]340 my $dbh = shift;
341
342 my %args = @_;
343
344 if ($args{revrec} eq 'y') {
345 if ($args{defrec} eq 'n') {
346 return ('FAIL', "IP or IP fragment ${$args{val}} is not within ".revName($dbh, $args{id}))
347 unless _ipparent($dbh, $args{defrec}, $args{revrec}, $args{val}, $args{id}, \$args{addr});
348 ${$args{val}} = $args{addr}->addr;
349 } else {
[234]350 if (${$args{val}} =~ /\./) {
351 # looks like a v4 or fragment
352 if (${$args{val}} =~ /^\d+\.\d+\.\d+\.\d+$/) {
353 # woo! a complete IP! validate it and normalize, or fail.
354 $args{addr} = NetAddr::IP->new(${$args{val}})
355 or return ('FAIL', "IP/value looks like IPv4 but isn't valid");
356 ${$args{val}} = $args{addr}->addr;
357 } else {
[249]358 ${$args{val}} =~ s/^\.*/ZONE./ unless ${$args{val}} =~ /^ZONE/;
[234]359 }
360 } elsif (${$args{val}} =~ /[a-f:]/) {
361 # looks like a v6 or fragment
[251]362 ${$args{val}} =~ s/^:*/ZONE::/ if !$args{addr} && ${$args{val}} !~ /^ZONE/;
[234]363 if ($args{addr}) {
364 if ($args{addr}->addr =~ /^0/) {
[251]365 ${$args{val}} =~ s/^:*/ZONE::/ unless ${$args{val}} =~ /^ZONE/;
[234]366 } else {
367 ${$args{val}} = $args{addr}->addr;
368 }
369 }
370 } else {
371 # bare number (probably). These could be v4 or v6, so we'll
372 # expand on these on creation of a reverse zone.
[251]373 ${$args{val}} = "ZONE,${$args{val}}" unless ${$args{val}} =~ /^ZONE/;
[234]374 }
[249]375 ${$args{host}} =~ s/\.*$/\.$config{domain}/ if ${$args{host}} !~ /(?:$config{domain}|ADMINDOMAIN)$/;
[232]376 }
377
378# Multiple PTR records do NOT generally do what most people believe they do,
379# and tend to fail in the most awkward way possible. Check and warn.
380# We use $val instead of $addr->addr since we may be in a defrec, and may have eg "ZONE::42" or "ZONE.12"
[249]381
382 my @checkvals = (${$args{val}});
383 if (${$args{val}} =~ /,/) {
384 # push . and :: variants into checkvals if val has ,
385 my $tmp;
386 ($tmp = ${$args{val}}) =~ s/,/./;
387 push @checkvals, $tmp;
388 ($tmp = ${$args{val}}) =~ s/,/::/;
389 push @checkvals, $tmp;
390 }
391 my $pcsth = $dbh->prepare("SELECT count(*) FROM "._rectable($args{defrec},$args{revrec})." WHERE val = ?");
392 foreach my $checkme (@checkvals) {
[272]393 if ($args{update}) {
394 # Record update. There should usually be an existing PTR (the record being updated)
395 my @ptrs = @{ $dbh->selectcol_arrayref("SELECT record_id FROM "._rectable($args{defrec},$args{revrec}).
396 " WHERE val = ?", undef, ($checkme)) };
397 return ('WARN', "PTR record for $checkme already exists; adding another will probably not do what you want")
[273]398 if @ptrs && (!grep /^$args{update}$/, @ptrs);
[272]399 } else {
400 # New record. Always warn if a PTR exists
401 my ($ptrcount) = $dbh->selectrow_array("SELECT count(*) FROM "._rectable($args{defrec},$args{revrec}).
402 " WHERE val = ?", undef, ($checkme));
403 return ('WARN', "PTR record for $checkme already exists; adding another will probably not do what you want")
404 if $ptrcount;
405 }
[249]406 }
[272]407
[232]408 } else {
409 # Not absolutely true but only useful if you hack things up for sub-/24 v4 reverse delegations
410 # Simpler to just create the reverse zone and grant access for the customer to edit it, and create direct
411 # PTR records on export
412 return ('FAIL',"Forward zones cannot contain PTR records");
413 }
414
[228]415 return ('OK','OK');
416} # done PTR record
417
418# MX record
419sub _validate_15 {
[230]420 my $dbh = shift;
421
422 my %args = @_;
423
424# Not absolutely true but WTF use is an MX record for a reverse zone?
425 return ('FAIL', 'Reverse zones cannot contain MX records') if $args{revrec} eq 'y';
426
427 return ('FAIL', "Distance is required for MX records") unless defined(${$args{dist}});
428 ${$args{dist}} =~ s/\s*//g;
429 return ('FAIL',"Distance is required, and must be numeric") unless ${$args{dist}} =~ /^\d+$/;
430
431 ${$args{fields}} = "distance,";
432 push @{$args{vallist}}, ${$args{dist}};
433
434 # Coerce all hostnames to end in ".DOMAIN" for group/default records,
435 # or the intended parent domain for live records.
436 my $pname = ($args{defrec} eq 'y' ? 'DOMAIN' : domainName($dbh,$args{id}));
437 ${$args{host}} =~ s/\.*$/\.$pname/ if ${$args{host}} !~ /$pname$/;
438
[273]439# hmm.. this might work. except possibly for something pointing to "deadbeef.ca". <g>
440# if ($type == $reverse_typemap{NS} || $type == $reverse_typemap{MX} || $type == $reverse_typemap{SRV}) {
441# if ($val =~ /^\s*[\da-f:.]+\s*$/) {
442# return ('FAIL',"$val is not a valid IP address") if !$addr;
443# }
444# }
445
[228]446 return ('OK','OK');
447} # done MX record
448
449# TXT record
450sub _validate_16 {
[231]451 # Could arguably put a WARN return here on very long (>512) records
[228]452 return ('OK','OK');
453} # done TXT record
454
455# RP record
456sub _validate_17 {
[231]457 # Probably have to validate these some day
[228]458 return ('OK','OK');
459} # done RP record
460
461# AAAA record
462sub _validate_28 {
[229]463 my $dbh = shift;
464
[230]465 my %args = @_;
[229]466
[230]467 return ('FAIL', 'Reverse zones cannot contain AAAA records') if $args{revrec} eq 'y';
[229]468
469 # Coerce all hostnames to end in ".DOMAIN" for group/default records,
470 # or the intended parent domain for live records.
[230]471 my $pname = ($args{defrec} eq 'y' ? 'DOMAIN' : domainName($dbh,$args{id}));
472 ${$args{host}} =~ s/\.*$/\.$pname/ if ${$args{host}} !~ /$pname$/;
[229]473
474 # Check IP is well-formed, and that it's a v6 address
[232]475 return ('FAIL',"$typemap{${$args{rectype}}} record must be a valid IPv6 address")
[230]476 unless $args{addr} && $args{addr}->{isv6};
[229]477 # coerce IP/value to normalized form for storage
[230]478 ${$args{val}} = $args{addr}->addr;
[229]479
[228]480 return ('OK','OK');
481} # done AAAA record
482
483# SRV record
484sub _validate_33 {
[231]485 my $dbh = shift;
486
487 my %args = @_;
488
489# Not absolutely true but WTF use is an SRV record for a reverse zone?
490 return ('FAIL', 'Reverse zones cannot contain SRV records') if $args{revrec} eq 'y';
491
492 return ('FAIL', "Distance is required for SRV records") unless defined(${$args{dist}});
493 ${$args{dist}} =~ s/\s*//g;
494 return ('FAIL',"Distance is required, and must be numeric") unless ${$args{dist}} =~ /^\d+$/;
495
496 return ('FAIL',"SRV records must begin with _service._protocol [${$args{host}}]")
497 unless ${$args{host}} =~ /^_[A-Za-z]+\._[A-Za-z]+\.[a-zA-Z0-9-]+/;
498 return ('FAIL',"Port and weight are required for SRV records")
499 unless defined(${$args{weight}}) && defined(${$args{port}});
500 ${$args{weight}} =~ s/\s*//g;
501 ${$args{port}} =~ s/\s*//g;
502
503 return ('FAIL',"Port and weight are required, and must be numeric")
504 unless ${$args{weight}} =~ /^\d+$/ && ${$args{port}} =~ /^\d+$/;
505
506 ${$args{fields}} = "distance,weight,port,";
507 push @{$args{vallist}}, (${$args{dist}}, ${$args{weight}}, ${$args{port}});
508
509 # Coerce all hostnames to end in ".DOMAIN" for group/default records,
510 # or the intended parent domain for live records.
511 my $pname = ($args{defrec} eq 'y' ? 'DOMAIN' : domainName($dbh,$args{id}));
512 ${$args{host}} =~ s/\.*$/\.$pname/ if ${$args{host}} !~ /$pname$/;
513
[228]514 return ('OK','OK');
515} # done SRV record
516
517# Now the custom types
518
[232]519# A+PTR record. With a very little bit of magic we can also use this sub to validate AAAA+PTR. Whee!
[228]520sub _validate_65280 {
[232]521 my $dbh = shift;
522
523 my %args = @_;
524
525 my $code = 'OK';
526 my $msg = 'OK';
527
528 if ($args{defrec} eq 'n') {
529 # live record; revrec determines whether we validate the PTR or A component first.
[233]530
[232]531 if ($args{revrec} eq 'y') {
532 ($code,$msg) = _validate_12($dbh, %args);
533 return ($code,$msg) if $code eq 'FAIL';
534
535 # Check if the reqested domain exists. If not, coerce the type down to PTR and warn.
536 if (!(${$args{domid}} = _hostparent($dbh, ${$args{host}}))) {
[272]537 my $addmsg = "Record ".($args{update} ? 'updated' : 'added').
538 " as PTR instead of $typemap{${$args{rectype}}}; domain not found for ${$args{host}}";
[232]539 $msg .= "\n$addmsg" if $code eq 'WARN';
540 $msg = $addmsg if $code eq 'OK';
541 ${$args{rectype}} = $reverse_typemap{PTR};
542 return ('WARN', $msg);
543 }
544
[242]545 # Add domain ID to field list and values
546 ${$args{fields}} .= "domain_id,";
547 push @{$args{vallist}}, ${$args{domid}};
548
[232]549 } else {
550 ($code,$msg) = _validate_1($dbh, %args) if ${$args{rectype}} == 65280;
551 ($code,$msg) = _validate_28($dbh, %args) if ${$args{rectype}} == 65281;
552 return ($code,$msg) if $code eq 'FAIL';
553
554 # Check if the requested reverse zone exists - note, an IP fragment won't
555 # work here since we don't *know* which parent to put it in.
[233]556 # ${$args{val}} has been validated as a valid IP by now, in one of the above calls.
[232]557 my ($revid) = $dbh->selectrow_array("SELECT rdns_id FROM revzones WHERE revnet >> ?".
558 " ORDER BY masklen(revnet) DESC", undef, (${$args{val}}));
559 if (!$revid) {
[272]560 $msg = "Record ".($args{update} ? 'updated' : 'added')." as ".(${$args{rectype}} == 65280 ? 'A' : 'AAAA').
[232]561 " instead of $typemap{${$args{rectype}}}; reverse zone not found for ${$args{val}}";
562 ${$args{rectype}} = (${$args{rectype}} == 65280 ? $reverse_typemap{A} : $reverse_typemap{AAAA});
563 return ('WARN', $msg);
564 }
565
566 # Check for duplicate PTRs. Note we don't have to play games with $code and $msg, because
567 # by definition there can't be duplicate PTRs if the reverse zone isn't managed here.
[272]568 if ($args{update}) {
569 # Record update. There should usually be an existing PTR (the record being updated)
570 my @ptrs = @{ $dbh->selectcol_arrayref("SELECT record_id FROM "._rectable($args{defrec},$args{revrec}).
571 " WHERE val = ?", undef, (${$args{val}})) };
[273]572 if (@ptrs && (!grep /^$args{update}$/, @ptrs)) {
[272]573 $msg = "PTR record for ${$args{val}} already exists; adding another will probably not do what you want";
574 $code = 'WARN';
575 }
576 } else {
577 # New record. Always warn if a PTR exists
578 my ($ptrcount) = $dbh->selectrow_array("SELECT count(*) FROM "._rectable($args{defrec},$args{revrec}).
579 " WHERE val = ?", undef, (${$args{val}}));
580 $msg = "PTR record for ${$args{val}} already exists; adding another will probably not do what you want"
581 if $ptrcount;
582 $code = 'WARN' if $ptrcount;
[232]583 }
584
[272]585# my ($ptrcount) = $dbh->selectrow_array("SELECT count(*) FROM "._rectable($args{defrec},$args{revrec}).
586# " WHERE val = ?", undef, ${$args{val}});
587# if ($ptrcount) {
588# my $curid = $dbh->selectrow_array("SELECT record_id FROM "._rectable($args{defrec},$args{revrec}).
589# " WHERE val = ?
590# $msg = "PTR record for ${$args{val}} already exists; adding another will probably not do what you want";
591# $code = 'WARN';
592# }
593
[232]594 ${$args{fields}} .= "rdns_id,";
595 push @{$args{vallist}}, $revid;
596 }
597
[233]598 } else { # defrec eq 'y'
599 if ($args{revrec} eq 'y') {
600 ($code,$msg) = _validate_12($dbh, %args);
601 return ($code,$msg) if $code eq 'FAIL';
602 if (${$args{rectype}} == 65280) {
603 return ('FAIL',"A+PTR record must be a valid IPv4 address or fragment")
604 if ${$args{val}} =~ /:/;
[234]605 ${$args{val}} =~ s/^ZONE,/ZONE./; # Clean up after uncertain IP-fragment-type from _validate_12
[233]606 } elsif (${$args{rectype}} == 65281) {
607 return ('FAIL',"AAAA+PTR record must be a valid IPv6 address or fragment")
608 if ${$args{val}} =~ /\./;
[234]609 ${$args{val}} =~ s/^ZONE,/ZONE::/; # Clean up after uncertain IP-fragment-type from _validate_12
[233]610 }
611 } else {
612 # This is easy. I also can't see a real use-case for A/AAAA+PTR in *all* forward
613 # domains, since you wouldn't be able to substitute both domain and reverse zone
614 # sanely, and you'd end up with guaranteed over-replicated PTR records that would
615 # confuse the hell out of pretty much anything that uses them.
[234]616##fixme: make this a config flag?
[233]617 return ('FAIL', "$typemap{${$args{rectype}}} records not allowed in default domains");
618 }
[232]619 }
620
621 return ($code, $msg);
[228]622} # done A+PTR record
623
624# AAAA+PTR record
[232]625# A+PTR above has been magicked to handle AAAA+PTR as well.
[228]626sub _validate_65281 {
[232]627 return _validate_65280(@_);
[228]628} # done AAAA+PTR record
629
630# PTR template record
631sub _validate_65282 {
632 return ('OK','OK');
633} # done PTR template record
634
635# A+PTR template record
636sub _validate_65283 {
637 return ('OK','OK');
638} # done AAAA+PTR template record
639
640# AAAA+PTR template record
641sub _validate_65284 {
642 return ('OK','OK');
643} # done AAAA+PTR template record
644
645
[265]646##
647## Record data substitution subs
648##
[228]649
[265]650# Replace ZONE in hostname
651sub _ZONE {
652 my $zone = shift;
653 my $string = shift;
654 my $fr = shift || 'f'; # flag for forward/reverse order? nb: ignored for IP
655
656 my $prefix = $zone->network->addr; # Just In Case someone managed to slip in
657 # a funky subnet that had host bits set.
658
659 $string =~ s/,/./ if !$zone->{isv6};
660 $string =~ s/,/::/ if $zone->{isv6};
661
662# if ($zone->{isv6} && ($zone->masklen % 4) != 0) {
663# # grumpyfail, non-nibble zone. shouldn't happen
664# return;
665# }
666
667 # Subbing ZONE in the host. We need to properly ID the netblock range
668 # The subbed text should have "network IP with trailing zeros stripped" for
669 # blocks lined up on octet (for v4) or 16-bit (for v6) boundaries
670 # For blocks that do NOT line up on these boundaries, we tack on an extra "-0",
671 # then take the most significant octet or 16-bit chunk of the "broadcast" IP and
672 # append it after a double-dash
673 # ie:
674 # 8.0.0.0/6 -> 8.0.0.0 -> 11.255.255.255; sub should be 8--11
675 # 10.0.0.0/12 -> 10.0.0.0 -> 10.0.0.0 -> 10.15.255.255; sub should be 10-0--15
676 # 192.168.4.0/22 -> 192.168.4.0 -> 192.168.7.255; sub should be 192-168-4--7
677 # 192.168.0.8/29 -> 192.168.0.8 -> 192.168.0.15; sub should be 192-168-0-8--15
678 # Similar for v6
679 if (!$zone->{isv6}) {
680 my $bc = $zone->broadcast->addr;
681 if ($zone->masklen > 24) {
682 $bc =~ s/^\d+\.\d+\.\d+\.//;
683 } elsif ($zone->masklen > 16) {
684 $prefix =~ s/\.0$//;
685 $bc =~ s/^\d+\.\d+\.//;
686 } elsif ($zone->masklen > 8) {
687 $bc =~ s/^\d+\.//;
688 $prefix =~ s/\.0\.0$//;
689 } else {
690 $prefix =~ s/\.0\.0\.0$//;
691 }
692 if ($zone->masklen % 8) {
693 $bc =~ s/(\.255)+$//;
694 $prefix .= "--$bc"; #"--".zone->masklen; # use range or mask length?
695 }
696 } else {
697 if (($zone->masklen % 16) != 0) {
698 # Strip trailing :0 off $prefix, and :ffff off the broadcast IP
699 # Strip the leading 16-bit chunks off the front of the broadcast IP
700 # Append the remaining 16-bit chunk to the prefix after "--"
701 my $bc = $zone->broadcast->addr;
702 for (my $i=0; $i<(7-int($zone->masklen / 16)); $i++) {
703 $prefix =~ s/:0$//;
704 $bc =~ s/:ffff$//;
705 }
706 $bc =~ s/^([a-f0-9]+:)+//;
707 $prefix .= "--$bc";
708 } else {
709 # Strip off :0 from the end until we reach the netblock length.
710 for (my $i=0; $i<(8-$zone->masklen / 16); $i++) {
711 $prefix =~ s/:0$//;
712 }
713 }
714 }
715
716 # Replace . and : with -
717 # If flagged for reverse-order, split on . or :, reverse, and join with -
718 if ($fr eq 'f') {
719 $prefix =~ s/[:.]+/-/g;
720 } else {
721 $prefix = join('-', reverse(split(/[:.]/, $prefix)));
722 }
723 $string =~ s/ZONE/$prefix/;
724# }
725 return $string;
726} # done _ZONE
727
728
729
[228]730##
[2]731## Initialization and cleanup subs
732##
733
[55]734
[128]735## DNSDB::loadConfig()
736# Load the minimum required initial state (DB connect info) from a config file
737# Load misc other bits while we're at it.
738# Takes an optional basename and config path to look for
739# Populates the %config and %def hashes
740sub loadConfig {
741 my $basename = shift || ''; # this will work OK
[218]742##fixme $basename isn't doing what I think I thought I was trying to do.
[128]743
744 my $deferr = ''; # place to put error from default config file in case we can't find either one
745
[219]746 my $configroot = "/etc/dnsdb"; ##CFG_LEAF##
[128]747 $configroot = '' if $basename =~ m|^/|;
748 $basename .= ".conf" if $basename !~ /\.conf$/;
749 my $defconfig = "$configroot/dnsdb.conf";
750 my $siteconfig = "$configroot/$basename";
751
752 # System defaults
[131]753 __cfgload("$defconfig") or $deferr = $errstr;
[128]754
[131]755 # Per-site-ish settings.
756 if ($basename ne '.conf') {
757 unless (__cfgload("$siteconfig")) {
758 $errstr = ($deferr ? "Error opening default config file $defconfig: $deferr\n" : '').
[128]759 "Error opening site config file $siteconfig";
[131]760 return;
761 }
[128]762 }
763
[195]764 # Munge log_failures.
765 if ($config{log_failures} ne '1' && $config{log_failures} ne '0') {
766 # true/false, on/off, yes/no all valid.
767 if ($config{log_failures} =~ /^(?:true|false|on|off|yes|no)$/) {
768 if ($config{log_failures} =~ /(?:true|on|yes)/) {
769 $config{log_failures} = 1;
770 } else {
771 $config{log_failures} = 0;
772 }
773 } else {
774 $errstr = "Bad log_failures setting $config{log_failures}";
775 $config{log_failures} = 1;
776 # Bad setting shouldn't be fatal.
777 # return 2;
778 }
779 }
780
[128]781 # All good, clear the error and go home.
782 $errstr = '';
783 return 1;
784} # end loadConfig()
785
786
787## DNSDB::__cfgload()
788# Private sub to parse a config file and load it into %config
789# Takes a file handle on an open config file
790sub __cfgload {
791 $errstr = '';
792 my $cfgfile = shift;
[131]793
[128]794 if (open CFG, "<$cfgfile") {
795 while (<CFG>) {
796 chomp;
797 s/^\s*//;
798 next if /^#/;
799 next if /^$/;
800# hmm. more complex bits in this file might require [heading] headers, maybe?
801# $mode = $1 if /^\[(a-z)+]/;
802 # DB connect info
803 $config{dbname} = $1 if /^dbname\s*=\s*([a-z0-9_.-]+)/i;
804 $config{dbuser} = $1 if /^dbuser\s*=\s*([a-z0-9_.-]+)/i;
805 $config{dbpass} = $1 if /^dbpass\s*=\s*([a-z0-9_.-]+)/i;
806 $config{dbhost} = $1 if /^dbhost\s*=\s*([a-z0-9_.-]+)/i;
807 # SOA defaults
808 $def{contact} = $1 if /^contact\s*=\s*([a-z0-9_.-]+)/i;
809 $def{prins} = $1 if /^prins\s*=\s*([a-z0-9_.-]+)/i;
[201]810 $def{soattl} = $1 if /^soattl\s*=\s*(\d+)/i;
811 $def{refresh} = $1 if /^refresh\s*=\s*(\d+)/i;
812 $def{retry} = $1 if /^retry\s*=\s*(\d+)/i;
813 $def{expire} = $1 if /^expire\s*=\s*(\d+)/i;
814 $def{minttl} = $1 if /^minttl\s*=\s*(\d+)/i;
815 $def{ttl} = $1 if /^ttl\s*=\s*(\d+)/i;
[128]816 # Mail settings
817 $config{mailhost} = $1 if /^mailhost\s*=\s*([a-z0-9_.-]+)/i;
[198]818 $config{mailnotify} = $1 if /^mailnotify\s*=\s*([a-z0-9_.\@-]+)/i;
819 $config{mailsender} = $1 if /^mailsender\s*=\s*([a-z0-9_.\@-]+)/i;
[128]820 $config{mailname} = $1 if /^mailname\s*=\s*([a-z0-9\s_.-]+)/i;
[195]821 $config{orgname} = $1 if /^orgname\s*=\s*([a-z0-9\s_.,'-]+)/i;
822 $config{domain} = $1 if /^domain\s*=\s*([a-z0-9_.-]+)/i;
[163]823 # session - note this is fed directly to CGI::Session
[216]824 $config{timeout} = $1 if /^[tT][iI][mM][eE][oO][uU][tT]\s*=\s*(\d+[smhdwMy]?)/;
825 $config{sessiondir} = $1 if m{^sessiondir\s*=\s*([a-z0-9/_.-]+)}i;
[201]826 # misc
[195]827 $config{log_failures} = $1 if /^log_failures\s*=\s*([a-z01]+)/i;
[201]828 $config{perpage} = $1 if /^perpage\s*=\s*(\d+)/i;
[128]829 }
830 close CFG;
831 } else {
832 $errstr = $!;
833 return;
834 }
835 return 1;
836} # end __cfgload()
837
838
[2]839## DNSDB::connectDB()
840# Creates connection to DNS database.
841# Requires the database name, username, and password.
842# Returns a handle to the db.
843# Set up for a PostgreSQL db; could be any transactional DBMS with the
844# right changes.
845sub connectDB {
846 $errstr = '';
[15]847 my $dbname = shift;
848 my $user = shift;
849 my $pass = shift;
[2]850 my $dbh;
851 my $DSN = "DBI:Pg:dbname=$dbname";
852
853 my $host = shift;
854 $DSN .= ";host=$host" if $host;
855
856# Note that we want to autocommit by default, and we will turn it off locally as necessary.
857# We may not want to print gobbledygook errors; YMMV. Have to ponder that further.
858 $dbh = DBI->connect($DSN, $user, $pass, {
859 AutoCommit => 1,
860 PrintError => 0
861 })
862 or return (undef, $DBI::errstr) if(!$dbh);
863
[212]864##fixme: initialize the DB if we can't find the table (since, by definition, there's
865# nothing there if we can't select from it...)
866 my $tblsth = $dbh->prepare("SELECT count(*) FROM pg_catalog.pg_class WHERE relkind='r' AND relname=?");
867 my ($tblcount) = $dbh->selectrow_array($tblsth, undef, ('misc'));
868 return (undef,$DBI::errstr) if $dbh->err;
869
870#if ($tblcount == 0) {
871# # create tables one at a time, checking for each.
872# return (undef, "check table misc missing");
873#}
874
875
876# Return here if we can't select.
877# This should retrieve the dbversion key.
878 my $sth = $dbh->prepare("SELECT key,value FROM misc WHERE misc_id=1");
[2]879 $sth->execute();
880 return (undef,$DBI::errstr) if ($sth->err);
881
[212]882##fixme: do stuff to the DB on version mismatch
883# x.y series should upgrade on $DNSDB::VERSION > misc(key=>version)
884# DB should be downward-compatible; column defaults should give sane (if possibly
885# useless-and-needs-help) values in columns an older software stack doesn't know about.
886
[2]887# See if the select returned anything (or null data). This should
888# succeed if the select executed, but...
889 $sth->fetchrow();
890 return (undef,$DBI::errstr) if ($sth->err);
891
892 $sth->finish;
893
894# If we get here, we should be OK.
895 return ($dbh,"DB connection OK");
896} # end connectDB
897
898
899## DNSDB::finish()
900# Cleans up after database handles and so on.
901# Requires a database handle
902sub finish {
903 my $dbh = $_[0];
904 $dbh->disconnect;
905} # end finish
906
907
908## DNSDB::initGlobals()
909# Initialize global variables
910# NB: this does NOT include web-specific session variables!
911# Requires a database handle
912sub initGlobals {
913 my $dbh = shift;
914
[208]915# load record types from database
[228]916 my $sth = $dbh->prepare("SELECT val,name,stdflag FROM rectypes");
[2]917 $sth->execute;
[228]918 while (my ($recval,$recname,$stdflag) = $sth->fetchrow_array()) {
[2]919 $typemap{$recval} = $recname;
920 $reverse_typemap{$recname} = $recval;
[228]921 # now we fill the record validation function hash
922 if ($stdflag < 5) {
923 my $fn = "_validate_$recval";
924 $validators{$recval} = \&$fn;
925 } else {
926 my $fn = "sub { return ('FAIL','Type $recval ($recname) not supported'); }";
927 $validators{$recval} = eval $fn;
928 }
[2]929 }
930} # end initGlobals
931
932
[65]933## DNSDB::initPermissions()
934# Set up permissions global
935# Takes database handle and UID
936sub initPermissions {
937 my $dbh = shift;
938 my $uid = shift;
939
940# %permissions = $(getPermissions($dbh,'user',$uid));
941 getPermissions($dbh, 'user', $uid, \%permissions);
942
943} # end initPermissions()
944
945
946## DNSDB::getPermissions()
947# Get permissions from DB
948# Requires DB handle, group or user flag, ID, and hashref.
949sub getPermissions {
950 my $dbh = shift;
951 my $type = shift;
952 my $id = shift;
953 my $hash = shift;
954
955 my $sql = qq(
956 SELECT
957 p.admin,p.self_edit,
958 p.group_create,p.group_edit,p.group_delete,
959 p.user_create,p.user_edit,p.user_delete,
960 p.domain_create,p.domain_edit,p.domain_delete,
961 p.record_create,p.record_edit,p.record_delete
962 FROM permissions p
963 );
964 if ($type eq 'group') {
965 $sql .= qq(
966 JOIN groups g ON g.permission_id=p.permission_id
967 WHERE g.group_id=?
968 );
969 } else {
970 $sql .= qq(
971 JOIN users u ON u.permission_id=p.permission_id
972 WHERE u.user_id=?
973 );
974 }
975
976 my $sth = $dbh->prepare($sql);
977
978 $sth->execute($id) or die "argh: ".$sth->errstr;
979
980# my $permref = $sth->fetchrow_hashref;
981# return $permref;
982# $hash = $permref;
983# Eww. Need to learn how to forcibly drop a hashref onto an existing hash.
984 ($hash->{admin},$hash->{self_edit},
985 $hash->{group_create},$hash->{group_edit},$hash->{group_delete},
986 $hash->{user_create},$hash->{user_edit},$hash->{user_delete},
987 $hash->{domain_create},$hash->{domain_edit},$hash->{domain_delete},
988 $hash->{record_create},$hash->{record_edit},$hash->{record_delete})
989 = $sth->fetchrow_array;
990
991} # end getPermissions()
992
993
994## DNSDB::changePermissions()
995# Update an ACL entry
996# Takes a db handle, type, owner-id, and hashref for the changed permissions.
997sub changePermissions {
998 my $dbh = shift;
999 my $type = shift;
1000 my $id = shift;
1001 my $newperms = shift;
[87]1002 my $inherit = shift || 0;
[65]1003
[78]1004 my $failmsg = '';
[66]1005
[87]1006 # see if we're switching from inherited to custom. for bonus points,
1007 # snag the permid and parent permid anyway, since we'll need the permid
1008 # to set/alter custom perms, and both if we're switching from custom to
1009 # inherited.
1010 my $sth = $dbh->prepare("SELECT (u.permission_id=g.permission_id) AS was_inherited,u.permission_id,g.permission_id".
[65]1011 " FROM ".($type eq 'user' ? 'users' : 'groups')." u ".
[66]1012 " JOIN groups g ON u.".($type eq 'user' ? '' : 'parent_')."group_id=g.group_id ".
[65]1013 " WHERE u.".($type eq 'user' ? 'user' : 'group')."_id=?");
1014 $sth->execute($id);
1015
[87]1016 my ($wasinherited,$permid,$parpermid) = $sth->fetchrow_array;
[66]1017
[78]1018# hack phtoui
1019# group id 1 is "special" in that it's it's own parent (err... possibly.)
1020# may make its parent id 0 which doesn't exist, and as a bonus is Perl-false.
1021 $wasinherited = 0 if ($type eq 'group' && $id == 1);
1022
[66]1023 local $dbh->{AutoCommit} = 0;
1024 local $dbh->{RaiseError} = 1;
1025
1026 # Wrap all the SQL in a transaction
1027 eval {
[87]1028 if ($inherit) {
1029
1030 $dbh->do("UPDATE ".($type eq 'user' ? 'users' : 'groups')." SET inherit_perm='t',permission_id=? ".
1031 "WHERE ".($type eq 'user' ? 'user' : 'group')."_id=?", undef, ($parpermid, $id) );
1032 $dbh->do("DELETE FROM permissions WHERE permission_id=?", undef, ($permid) );
1033
1034 } else {
1035
1036 if ($wasinherited) { # munge new permission entry in if we're switching from inherited perms
[66]1037##fixme: need to add semirecursive bit to properly munge inherited permission ID on subgroups and users
[87]1038# ... if'n'when we have groups with fully inherited permissions.
1039 # SQL is coo
1040 $dbh->do("INSERT INTO permissions ($permlist,".($type eq 'user' ? 'user' : 'group')."_id) ".
1041 "SELECT $permlist,? FROM permissions WHERE permission_id=?", undef, ($id,$permid) );
1042 ($permid) = $dbh->selectrow_array("SELECT permission_id FROM permissions ".
1043 "WHERE ".($type eq 'user' ? 'user' : 'group')."_id=?", undef, ($id) );
1044 $dbh->do("UPDATE ".($type eq 'user' ? 'users' : 'groups')." SET inherit_perm='f',permission_id=? ".
1045 "WHERE ".($type eq 'user' ? 'user' : 'group')."_id=?", undef, ($permid, $id) );
[66]1046 }
[78]1047
[87]1048 # and now set the permissions we were passed
1049 foreach (@permtypes) {
1050 if (defined ($newperms->{$_})) {
1051 $dbh->do("UPDATE permissions SET $_=? WHERE permission_id=?", undef, ($newperms->{$_},$permid) );
1052 }
1053 }
1054
1055 } # (inherited->)? custom
1056
[66]1057 $dbh->commit;
1058 }; # end eval
1059 if ($@) {
1060 my $msg = $@;
1061 eval { $dbh->rollback; };
[87]1062 return ('FAIL',"$failmsg: $msg ($permid)");
[66]1063 } else {
1064 return ('OK',$permid);
1065 }
1066
[65]1067} # end changePermissions()
1068
1069
[67]1070## DNSDB::comparePermissions()
1071# Compare two permission hashes
1072# Returns '>', '<', '=', '!'
1073sub comparePermissions {
1074 my $p1 = shift;
1075 my $p2 = shift;
1076
1077 my $retval = '='; # assume equality until proven otherwise
1078
1079 no warnings "uninitialized";
1080
1081 foreach (@permtypes) {
1082 next if $p1->{$_} == $p2->{$_}; # equal is good
1083 if ($p1->{$_} && !$p2->{$_}) {
1084 if ($retval eq '<') { # if we've already found an unequal pair where
1085 $retval = '!'; # $p2 has more access, and we now find a pair
1086 last; # where $p1 has more access, the overall access
1087 } # is neither greater or lesser, it's unequal.
1088 $retval = '>';
1089 }
1090 if (!$p1->{$_} && $p2->{$_}) {
1091 if ($retval eq '>') { # if we've already found an unequal pair where
1092 $retval = '!'; # $p1 has more access, and we now find a pair
1093 last; # where $p2 has more access, the overall access
1094 } # is neither greater or lesser, it's unequal.
1095 $retval = '<';
1096 }
1097 }
1098 return $retval;
1099} # end comparePermissions()
1100
1101
[112]1102## DNSDB::changeGroup()
1103# Change group ID of an entity
1104# Takes a database handle, entity type, entity ID, and new group ID
1105sub changeGroup {
1106 my $dbh = shift;
1107 my $type = shift;
1108 my $id = shift;
1109 my $newgrp = shift;
1110
1111##fixme: fail on not enough args
1112 #return ('FAIL', "Missing
1113
1114 if ($type eq 'domain') {
1115 $dbh->do("UPDATE domains SET group_id=? WHERE domain_id=?", undef, ($newgrp, $id))
1116 or return ('FAIL','Group change failed: '.$dbh->errstr);
1117 } elsif ($type eq 'user') {
1118 $dbh->do("UPDATE users SET group_id=? WHERE user_id=?", undef, ($newgrp, $id))
1119 or return ('FAIL','Group change failed: '.$dbh->errstr);
1120 } elsif ($type eq 'group') {
1121 $dbh->do("UPDATE groups SET parent_group_id=? WHERE group_id=?", undef, ($newgrp, $id))
1122 or return ('FAIL','Group change failed: '.$dbh->errstr);
1123 }
1124 return ('OK','OK');
1125} # end changeGroup()
1126
1127
[55]1128## DNSDB::_log()
1129# Log an action
1130# Internal sub
[256]1131# Takes a database handle and log entry hash containing at least:
1132# user_id, group_id, log entry
1133# and optionally one or more of:
1134# username/email, user full name, domain_id, rdns_id
[193]1135##fixme: convert to trailing hash for user info
1136# User info must contain a (user ID OR username)+fullname
[55]1137sub _log {
[190]1138 my $dbh = shift;
1139
[256]1140 my %args = @_;
1141
1142 $args{rdns_id} = 0 if !$args{rdns_id};
1143 $args{domain_id} = 0 if !$args{domain_id};
1144
[193]1145##fixme: need better way(s?) to snag userinfo for log entries. don't want to have
1146# to pass around yet *another* constant (already passing $dbh, shouldn't need to)
[195]1147 my $fullname;
[256]1148 if (!$args{user_id}) {
1149 ($args{user_id}, $fullname) = $dbh->selectrow_array("SELECT user_id, firstname || ' ' || lastname FROM users".
1150 " WHERE username=?", undef, ($args{username}));
[259]1151 }
1152 if (!$args{username}) {
[256]1153 ($args{username}, $fullname) = $dbh->selectrow_array("SELECT username, firstname || ' ' || lastname FROM users".
1154 " WHERE user_id=?", undef, ($args{user_id}));
[259]1155 }
1156 if (!$args{fullname}) {
[195]1157 ($fullname) = $dbh->selectrow_array("SELECT firstname || ' ' || lastname FROM users".
[256]1158 " WHERE user_id=?", undef, ($args{user_id}));
[193]1159 }
1160
[256]1161 $args{name} = $fullname if !$args{name};
[193]1162
[190]1163##fixme: farm out the actual logging to different subs for file, syslog, internal, etc based on config
[256]1164 $dbh->do("INSERT INTO log (domain_id,rdns_id,user_id,group_id,email,name,entry) VALUES (?,?,?,?,?,?,?)",
1165 undef,
1166 ($args{domain_id},$args{rdns_id},$args{user_id},$args{group_id},$args{username},$args{name},$args{entry}));
1167
[55]1168} # end _log
1169
1170
[2]1171##
1172## Processing subs
1173##
1174
1175## DNSDB::addDomain()
1176# Add a domain
[190]1177# Takes a database handle, domain name, numeric group, boolean(ish) state (active/inactive),
1178# and user info hash (for logging).
[2]1179# Returns a status code and message
1180sub addDomain {
1181 $errstr = '';
1182 my $dbh = shift;
1183 return ('FAIL',"Need database handle") if !$dbh;
1184 my $domain = shift;
[91]1185 return ('FAIL',"Domain must not be blank") if !$domain;
[2]1186 my $group = shift;
1187 return ('FAIL',"Need group") if !defined($group);
1188 my $state = shift;
1189 return ('FAIL',"Need domain status") if !defined($state);
1190
[190]1191 my %userinfo = @_; # remaining bits.
1192# user ID, username, user full name
1193
[116]1194 $state = 1 if $state =~ /^active$/;
1195 $state = 1 if $state =~ /^on$/;
1196 $state = 0 if $state =~ /^inactive$/;
1197 $state = 0 if $state =~ /^off$/;
1198
1199 return ('FAIL',"Invalid domain status") if $state !~ /^\d+$/;
1200
[190]1201 return ('FAIL', "Invalid characters in domain") if $domain !~ /^[a-zA-Z0-9_.-]+$/;
1202
[38]1203 my $sth = $dbh->prepare("SELECT domain_id FROM domains WHERE domain=?");
[3]1204 my $dom_id;
1205
[38]1206# quick check to start to see if we've already got one
1207 $sth->execute($domain);
1208 ($dom_id) = $sth->fetchrow_array;
1209
1210 return ('FAIL', "Domain already exists") if $dom_id;
1211
[2]1212 # Allow transactions, and raise an exception on errors so we can catch it later.
1213 # Use local to make sure these get "reset" properly on exiting this block
1214 local $dbh->{AutoCommit} = 0;
1215 local $dbh->{RaiseError} = 1;
1216
1217 # Wrap all the SQL in a transaction
1218 eval {
1219 # insert the domain...
[190]1220 $dbh->do("INSERT INTO domains (domain,group_id,status) VALUES (?,?,?)", undef, ($domain, $group, $state));
[2]1221
1222 # get the ID...
[190]1223 ($dom_id) = $dbh->selectrow_array("SELECT domain_id FROM domains WHERE domain=?", undef, ($domain));
[2]1224
[259]1225 _log($dbh, (domain_id => $dom_id, user_id => $userinfo{id}, group_id => $group, username => $userinfo{username},
1226 entry => "Added ".($state ? 'active' : 'inactive')." domain $domain"));
[190]1227
[2]1228 # ... and now we construct the standard records from the default set. NB: group should be variable.
[190]1229 my $sth = $dbh->prepare("SELECT host,type,val,distance,weight,port,ttl FROM default_records WHERE group_id=?");
1230 my $sth_in = $dbh->prepare("INSERT INTO records (domain_id,host,type,val,distance,weight,port,ttl)".
1231 " VALUES ($dom_id,?,?,?,?,?,?,?)");
1232 $sth->execute($group);
[3]1233 while (my ($host,$type,$val,$dist,$weight,$port,$ttl) = $sth->fetchrow_array()) {
[2]1234 $host =~ s/DOMAIN/$domain/g;
[37]1235 $val =~ s/DOMAIN/$domain/g;
[3]1236 $sth_in->execute($host,$type,$val,$dist,$weight,$port,$ttl);
[190]1237 if ($typemap{$type} eq 'SOA') {
1238 my @tmp1 = split /:/, $host;
1239 my @tmp2 = split /:/, $val;
[258]1240 _log($dbh, (domain_id => $dom_id, user_id => $userinfo{id}, group_id => $group,
[259]1241 username => $userinfo{username}, entry =>
[190]1242 "[new $domain] Added SOA record [contact $tmp1[0]] [master $tmp1[1]] ".
[257]1243 "[refresh $tmp2[0]] [retry $tmp2[1]] [expire $tmp2[2]] [minttl $tmp2[3]], TTL $ttl"));
[190]1244 } else {
1245 my $logentry = "[new $domain] Added record '$host $typemap{$type}";
1246 $logentry .= " [distance $dist]" if $typemap{$type} eq 'MX';
1247 $logentry .= " [priority $dist] [weight $weight] [port $port]" if $typemap{$type} eq 'SRV';
[258]1248 _log($dbh, (domain_id => $dom_id, user_id => $userinfo{id}, group_id => $group,
[259]1249 username => $userinfo{username}, entry =>
[257]1250 $logentry." $val', TTL $ttl"));
[190]1251 }
[2]1252 }
1253
1254 # once we get here, we should have suceeded.
1255 $dbh->commit;
1256 }; # end eval
1257
1258 if ($@) {
1259 my $msg = $@;
1260 eval { $dbh->rollback; };
[193]1261 return ('FAIL',$msg);
[2]1262 } else {
[3]1263 return ('OK',$dom_id);
[2]1264 }
1265} # end addDomain
1266
1267
[274]1268## DNSDB::delZone()
1269# Delete a forward or reverse zone.
1270# Takes a database handle, zone ID, and forward/reverse flag.
[3]1271# for now, just delete the records, then the domain.
1272# later we may want to archive it in some way instead (status code 2, for example?)
[274]1273sub delZone {
[3]1274 my $dbh = shift;
[274]1275 my $zoneid = shift;
1276 my $revrec = shift;
[3]1277
1278 # Allow transactions, and raise an exception on errors so we can catch it later.
1279 # Use local to make sure these get "reset" properly on exiting this block
1280 local $dbh->{AutoCommit} = 0;
1281 local $dbh->{RaiseError} = 1;
1282
[23]1283 my $failmsg = '';
1284
[3]1285 # Wrap all the SQL in a transaction
1286 eval {
[274]1287 # Disentangle custom record types before removing the
1288 # ones that are only in the zone to be deleted
1289 if ($revrec eq 'n') {
1290 my $sth = $dbh->prepare("UPDATE records SET type=?,domain_id=0 WHERE domain_id=? AND type=?");
1291 $failmsg = "Failure converting multizone types to single-zone";
1292 $sth->execute($reverse_typemap{PTR}, $zoneid, 65280);
1293 $sth->execute($reverse_typemap{PTR}, $zoneid, 65281);
1294 $sth->execute(65282, $zoneid, 65283);
1295 $sth->execute(65282, $zoneid, 65284);
1296 $failmsg = "Failure removing domain records";
1297 $dbh->do("DELETE FROM records WHERE domain_id=?", undef, ($zoneid));
1298 $failmsg = "Failure removing domain";
1299 $dbh->do("DELETE FROM domains WHERE domain_id=?", undef, ($zoneid));
1300 } else {
1301 my $sth = $dbh->prepare("UPDATE records SET type=?,rdns_id=0 WHERE rdns_id=? AND type=?");
1302 $failmsg = "Failure converting multizone types to single-zone";
1303 $sth->execute($reverse_typemap{A}, $zoneid, 65280);
1304 $sth->execute($reverse_typemap{AAAA}, $zoneid, 65281);
1305# We don't have an "A template" or "AAAA template" type, although it might be useful for symmetry.
1306# $sth->execute(65285?, $zoneid, 65283);
1307# $sth->execute(65285?, $zoneid, 65284);
1308 $failmsg = "Failure removing reverse records";
1309 $dbh->do("DELETE FROM records WHERE rdns_id=?", undef, ($zoneid));
1310 $failmsg = "Failure removing reverse zone";
1311 $dbh->do("DELETE FROM revzones WHERE rdns_id=?", undef, ($zoneid));
1312 }
[3]1313
1314 # once we get here, we should have suceeded.
[23]1315 $dbh->commit;
[3]1316 }; # end eval
1317
1318 if ($@) {
1319 my $msg = $@;
1320 eval { $dbh->rollback; };
[23]1321 return ('FAIL',"$failmsg: $msg");
[3]1322 } else {
1323 return ('OK','OK');
1324 }
1325
[274]1326} # end delZone()
[3]1327
1328
[2]1329## DNSDB::domainName()
1330# Return the domain name based on a domain ID
1331# Takes a database handle and the domain ID
1332# Returns the domain name or undef on failure
1333sub domainName {
1334 $errstr = '';
1335 my $dbh = shift;
1336 my $domid = shift;
[91]1337 my ($domname) = $dbh->selectrow_array("SELECT domain FROM domains WHERE domain_id=?", undef, ($domid) );
[2]1338 $errstr = $DBI::errstr if !$domname;
1339 return $domname if $domname;
[91]1340} # end domainName()
[2]1341
1342
[224]1343## DNSDB::revName()
1344# Return the reverse zone name based on an rDNS ID
1345# Takes a database handle and the rDNS ID
1346# Returns the reverse zone name or undef on failure
1347sub revName {
1348 $errstr = '';
1349 my $dbh = shift;
1350 my $revid = shift;
1351 my ($revname) = $dbh->selectrow_array("SELECT revnet FROM revzones WHERE rdns_id=?", undef, ($revid) );
1352 $errstr = $DBI::errstr if !$revname;
1353 return $revname if $revname;
1354} # end revName()
1355
1356
[91]1357## DNSDB::domainID()
1358# Takes a database handle and domain name
1359# Returns the domain ID number
1360sub domainID {
1361 $errstr = '';
1362 my $dbh = shift;
1363 my $domain = shift;
1364 my ($domid) = $dbh->selectrow_array("SELECT domain_id FROM domains WHERE domain=?", undef, ($domain) );
1365 $errstr = $DBI::errstr if !$domid;
1366 return $domid if $domid;
1367} # end domainID()
1368
1369
[276]1370## DNSDB::revID()
1371# Takes a database handle and reverse zone name
1372# Returns the rDNS ID number
1373sub revID {
1374 $errstr = '';
1375 my $dbh = shift;
1376 my $revzone = shift;
1377 my ($revid) = $dbh->selectrow_array("SELECT rdns_id FROM revzones WHERE revnet=?", undef, ($revzone) );
1378 $errstr = $DBI::errstr if !$revid;
1379 return $revid if $revid;
1380} # end revID()
1381
1382
[260]1383## DNSDB::addRDNS
1384# Adds a reverse DNS zone
1385# Takes a database handle, CIDR block, numeric group, boolean(ish) state (active/inactive),
1386# and user info hash (for logging).
1387# Returns a status code and message
1388sub addRDNS {
1389 my $dbh = shift;
1390 my $zone = NetAddr::IP->new(shift);
1391 return ('FAIL',"Zone name must be a valid CIDR netblock") unless ($zone && $zone->addr !~ /^0/);
[270]1392 my $revpatt = shift; # construct a custom (A/AAAA+)? PTR template record
[260]1393 my $group = shift;
1394 my $state = shift;
1395
1396 my %userinfo = @_; # remaining bits.
1397# user ID, username, user full name
1398
1399 $state = 1 if $state =~ /^active$/;
1400 $state = 1 if $state =~ /^on$/;
1401 $state = 0 if $state =~ /^inactive$/;
1402 $state = 0 if $state =~ /^off$/;
1403
1404 return ('FAIL',"Invalid zone status") if $state !~ /^\d+$/;
1405
1406# quick check to start to see if we've already got one
1407 my ($rdns_id) = $dbh->selectrow_array("SELECT rdns_id FROM revzones WHERE revzone=?", undef, ("$zone"));
1408
1409 return ('FAIL', "Zone already exists") if $rdns_id;
1410
1411 # Allow transactions, and raise an exception on errors so we can catch it later.
1412 # Use local to make sure these get "reset" properly on exiting this block
1413 local $dbh->{AutoCommit} = 0;
1414 local $dbh->{RaiseError} = 1;
1415
[264]1416 my $warnstr = '';
[270]1417 my $defttl = 3600; # 1 hour should be reasonable. And unless things have gone horribly
1418 # wrong, we should have a value to override this anyway.
[264]1419
[260]1420 # Wrap all the SQL in a transaction
1421 eval {
1422 # insert the domain...
1423 $dbh->do("INSERT INTO revzones (revnet,group_id,status) VALUES (?,?,?)", undef, ($zone, $group, $state));
1424
1425 # get the ID...
1426 ($rdns_id) = $dbh->selectrow_array("SELECT currval('revzones_rdns_id_seq')");
1427
1428 _log($dbh, (rdns_id => $rdns_id, user_id => $userinfo{id}, group_id => $group, username => $userinfo{name},
1429 entry => "Added ".($state ? 'active' : 'inactive')." reverse zone $zone"));
1430
1431 # ... and now we construct the standard records from the default set. NB: group should be variable.
1432 my $sth = $dbh->prepare("SELECT host,type,val,ttl FROM default_rev_records WHERE group_id=?");
[269]1433 my $sth_in = $dbh->prepare("INSERT INTO records (rdns_id,domain_id,host,type,val,ttl)".
1434 " VALUES ($rdns_id,?,?,?,?,?)");
[260]1435 $sth->execute($group);
1436 while (my ($host,$type,$val,$ttl) = $sth->fetchrow_array()) {
[264]1437 # Silently skip v4/v6 mismatches. This is not an error, this is expected.
1438 if ($zone->{isv6}) {
1439 next if ($type == 65280 || $type == 65283);
1440 } else {
1441 next if ($type == 65281 || $type == 65284);
1442 }
[269]1443
[260]1444 $host =~ s/ADMINDOMAIN/$config{domain}/g;
[264]1445
[265]1446 # Check to make sure the IP stubs will fit in the zone. Under most usage failures here should be rare.
1447 # On failure, tack a note on to a warning string and continue without adding this record.
1448 # While we're at it, we substitute $zone for ZONE in the value.
1449 if ($val eq 'ZONE') {
[270]1450 next if $revpatt; # If we've got a pattern, we skip the default record version.
[269]1451##fixme? do we care if we have multiple whole-zone templates?
[265]1452 $val = $zone->network;
1453 } elsif ($val =~ /ZONE/) {
1454 my $tmpval = $val;
1455 $tmpval =~ s/ZONE//;
[269]1456 # Bend the rules and allow single-trailing-number PTR or PTR template records to be inserted
1457 # as either v4 or v6. May make this an off-by-default config flag
1458 # Note that the origin records that may trigger this **SHOULD** already have ZONE,\d
1459 if ($type == 12 || $type == 65282) {
1460 $tmpval =~ s/[,.]/::/ if ($tmpval =~ /^[,.]\d+$/ && $zone->{isv6});
1461 $tmpval =~ s/[,:]+/./ if ($tmpval =~ /^(?:,|::)\d+$/ && !$zone->{isv6});
1462 }
[265]1463 my $addr;
1464 if (_ipparent($dbh, 'n', 'y', \$tmpval, $rdns_id, \$addr)) {
1465 $val = $addr->addr;
1466 } else {
[269]1467 $warnstr .= "\nDefault record '$val $typemap{$type} $host' doesn't fit in $zone, skipping";
[264]1468 next;
1469 }
1470 }
1471
[265]1472 # Substitute $zone for ZONE in the hostname.
1473 $host = _ZONE($zone, $host);
1474
[269]1475 # Fill in the forward domain ID if we can find it, otherwise:
1476 # Coerce type down to PTR or PTR template if we can't
1477 my $domid = 0;
1478 if ($type >= 65280) {
1479 if (!($domid = _hostparent($dbh, $host))) {
1480 $warnstr .= "\nRecord added as PTR instead of $typemap{$type}; domain not found for $host";
1481 $type = $reverse_typemap{PTR};
1482 $domid = 0; # just to be explicit.
1483 }
1484 }
1485
1486 $sth_in->execute($domid,$host,$type,$val,$ttl);
1487
[260]1488 if ($typemap{$type} eq 'SOA') {
1489 my @tmp1 = split /:/, $host;
1490 my @tmp2 = split /:/, $val;
1491 _log($dbh, (rdns_id => $rdns_id, user_id => $userinfo{id}, group_id => $group,
1492 username => $userinfo{name}, entry =>
1493 "[new $zone] Added SOA record [contact $tmp1[0]] [master $tmp1[1]] ".
1494 "[refresh $tmp2[0]] [retry $tmp2[1]] [expire $tmp2[2]] [minttl $tmp2[3]], TTL $ttl"));
[270]1495 $defttl = $tmp2[3];
[260]1496 } else {
1497 my $logentry = "[new $zone] Added record '$host $typemap{$type}";
[269]1498 _log($dbh, (rdns_id => $rdns_id, domain_id => $domid, user_id => $userinfo{id}, group_id => $group,
[260]1499 username => $userinfo{name}, entry =>
1500 $logentry." $val', TTL $ttl"));
1501 }
1502 }
1503
[270]1504 # Generate record based on provided pattern.
1505 if ($revpatt) {
1506 my $host;
1507 my $type = ($zone->{isv6} ? 65284 : 65283);
1508 my $val = $zone->network;
[269]1509
[270]1510 # Substitute $zone for ZONE in the hostname.
1511 $host = _ZONE($zone, $revpatt);
1512
1513 my $domid = 0;
1514 if (!($domid = _hostparent($dbh, $host))) {
1515 $warnstr .= "\nDefault pattern added as PTR template instead of $typemap{$type}; domain not found for $host";
1516 $type = 65282;
1517 $domid = 0; # just to be explicit.
1518 }
1519
1520 $sth_in->execute($domid,$host,$type,$val,$defttl);
1521 }
1522
[264]1523 # If there are warnings (presumably about default records skipped for cause) log them
1524 _log($dbh, (rdns_id => $rdns_id, user_id => $userinfo{id}, group_id => $group,
[269]1525 username => $userinfo{name}, entry => "Warning(s) adding $zone:$warnstr"))
[264]1526 if $warnstr;
[269]1527
[260]1528 # once we get here, we should have suceeded.
1529 $dbh->commit;
1530 }; # end eval
1531
1532 if ($@) {
1533 my $msg = $@;
1534 eval { $dbh->rollback; };
1535 return ('FAIL',$msg);
1536 } else {
1537 return ('OK',$rdns_id);
1538 }
1539
1540} # end addRDNS()
1541
1542
[237]1543## DNSDB::getZoneCount
1544# Get count of zones in group or groups
1545# Takes a database handle and hash containing:
1546# - the "current" group
1547# - an array of "acceptable" groups
1548# - a flag for forward/reverse zones
1549# - Optionally accept a "starts with" and/or "contains" filter argument
1550# Returns an integer count of the resulting zone list.
1551sub getZoneCount {
1552 my $dbh = shift;
1553
1554 my %args = @_;
1555
1556 my @filterargs;
[239]1557 $args{startwith} = undef if $args{startwith} && $args{startwith} !~ /^(?:[a-z]|0-9)$/;
1558 push @filterargs, "^$args{startwith}" if $args{startwith};
1559 $args{filter} =~ s/\./\[\.\]/g if $args{filter}; # only match literal dots, usually in reverse zones
[237]1560 push @filterargs, $args{filter} if $args{filter};
1561
1562 my $sql;
1563 # Not as compact, and fix-me-twice if the common bits get wrong, but much easier to read
1564 if ($args{revrec} eq 'n') {
1565 $sql = "SELECT count(*) FROM domains".
1566 " WHERE group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
1567 ($args{startwith} ? " AND domain ~* ?" : '').
1568 ($args{filter} ? " AND domain ~* ?" : '');
1569 } else {
1570 $sql = "SELECT count(*) FROM revzones".
1571 " WHERE group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
1572 ($args{startwith} ? " AND CAST(revnet AS VARCHAR) ~* ?" : '').
1573 ($args{filter} ? " AND CAST(revnet AS VARCHAR) ~* ?" : '');
1574 }
1575 my ($count) = $dbh->selectrow_array($sql, undef, @filterargs);
1576 return $count;
1577} # end getZoneCount()
1578
1579
1580## DNSDB::getZoneList()
1581# Get a list of zones in the specified group(s)
1582# Takes the same arguments as getZoneCount() above
1583# Returns a reference to an array of hashrefs suitable for feeding to HTML::Template
1584sub getZoneList {
1585 my $dbh = shift;
1586
1587 my %args = @_;
1588
1589 my @zonelist;
1590
1591 $args{sortorder} = 'ASC' if !grep $args{sortorder}, ('ASC','DESC');
[239]1592 $args{offset} = 0 if !$args{offset} || $args{offset} !~ /^(?:all|\d+)$/;
[237]1593
1594 my @filterargs;
[239]1595 $args{startwith} = undef if $args{startwith} && $args{startwith} !~ /^(?:[a-z]|0-9)$/;
1596 push @filterargs, "^$args{startwith}" if $args{startwith};
1597 $args{filter} =~ s/\./\[\.\]/g if $args{filter}; # only match literal dots, usually in reverse zones
[237]1598 push @filterargs, $args{filter} if $args{filter};
1599
1600 my $sql;
1601 # Not as compact, and fix-me-twice if the common bits get wrong, but much easier to read
1602 if ($args{revrec} eq 'n') {
1603 $args{sortby} = 'domain' if !grep $args{sortby}, ('revnet','group','status');
1604 $sql = "SELECT domain_id,domain,status,groups.group_name AS group FROM domains".
1605 " INNER JOIN groups ON domains.group_id=groups.group_id".
1606 " WHERE domains.group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
1607 ($args{startwith} ? " AND domain ~* ?" : '').
1608 ($args{filter} ? " AND domain ~* ?" : '');
1609 } else {
[239]1610##fixme: arguably startwith here is irrelevant. depends on the UI though.
[237]1611 $args{sortby} = 'revnet' if !grep $args{sortby}, ('domain','group','status');
1612 $sql = "SELECT rdns_id,revnet,status,groups.group_name AS group FROM revzones".
1613 " INNER JOIN groups ON revzones.group_id=groups.group_id".
1614 " WHERE revzones.group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
1615 ($args{startwith} ? " AND CAST(revnet AS VARCHAR) ~* ?" : '').
1616 ($args{filter} ? " AND CAST(revnet AS VARCHAR) ~* ?" : '');
1617 }
1618 # A common tail.
[239]1619 $sql .= " ORDER BY ".($args{sortby} eq 'group' ? 'groups.group_name' : $args{sortby})." $args{sortorder} ".
1620 ($args{offset} eq 'all' ? '' : " LIMIT $config{perpage}".
[237]1621 " OFFSET ".$args{offset}*$config{perpage});
1622 my $sth = $dbh->prepare($sql);
1623 $sth->execute(@filterargs);
1624 my $rownum = 0;
1625
1626 while (my @data = $sth->fetchrow_array) {
1627 my %row;
1628 $row{domainid} = $data[0];
1629 $row{domain} = $data[1];
[239]1630 $row{status} = $data[2];
[237]1631 $row{group} = $data[3];
1632 push @zonelist, \%row;
1633 }
1634
1635 return \@zonelist;
1636} # end getZoneList()
1637
1638
[18]1639## DNSDB::addGroup()
1640# Add a group
[66]1641# Takes a database handle, group name, parent group, hashref for permissions,
1642# and optional template-vs-cloneme flag
[18]1643# Returns a status code and message
1644sub addGroup {
1645 $errstr = '';
1646 my $dbh = shift;
[20]1647 my $groupname = shift;
1648 my $pargroup = shift;
[66]1649 my $permissions = shift;
[18]1650
[66]1651 # 0 indicates "custom", hardcoded.
[18]1652 # Any other value clones that group's default records, if it exists.
[66]1653 my $inherit = shift || 0;
1654##fixme: need a flag to indicate clone records or <?> ?
[18]1655
1656 # Allow transactions, and raise an exception on errors so we can catch it later.
1657 # Use local to make sure these get "reset" properly on exiting this block
1658 local $dbh->{AutoCommit} = 0;
1659 local $dbh->{RaiseError} = 1;
1660
[38]1661 my $sth = $dbh->prepare("SELECT group_id FROM groups WHERE group_name=?");
1662 my $group_id;
1663
1664# quick check to start to see if we've already got one
1665 $sth->execute($groupname);
1666 ($group_id) = $sth->fetchrow_array;
1667
1668 return ('FAIL', "Group already exists") if $group_id;
1669
[18]1670 # Wrap all the SQL in a transaction
1671 eval {
[38]1672 $sth = $dbh->prepare("INSERT INTO groups (parent_group_id,group_name) VALUES (?,?)");
[20]1673 $sth->execute($pargroup,$groupname);
[18]1674
[255]1675 my ($groupid) = $dbh->selectrow_array("SELECT group_id FROM groups WHERE group_name=?", undef, ($groupname));
[18]1676
[66]1677# Permissions
1678 if ($inherit) {
1679 } else {
1680 my @permvals;
1681 foreach (@permtypes) {
1682 if (!defined ($permissions->{$_})) {
1683 push @permvals, 0;
1684 } else {
1685 push @permvals, $permissions->{$_};
1686 }
1687 }
1688
1689 $sth = $dbh->prepare("INSERT INTO permissions (group_id,$permlist) values (?".',?'x($#permtypes+1).")");
1690 $sth->execute($groupid,@permvals);
1691
1692 $sth = $dbh->prepare("SELECT permission_id FROM permissions WHERE group_id=?");
1693 $sth->execute($groupid);
1694 my ($permid) = $sth->fetchrow_array();
1695
1696 $dbh->do("UPDATE groups SET permission_id=$permid WHERE group_id=$groupid");
1697 } # done permission fiddling
1698
1699# Default records
[255]1700 my $sthf = $dbh->prepare("INSERT INTO default_records (group_id,host,type,val,distance,weight,port,ttl) ".
[20]1701 "VALUES ($groupid,?,?,?,?,?,?,?)");
[255]1702 my $sthr = $dbh->prepare("INSERT INTO default_rev_records (group_id,host,type,val,ttl) ".
1703 "VALUES ($groupid,?,?,?,?)");
[66]1704 if ($inherit) {
[87]1705 # Duplicate records from parent. Actually relying on inherited records feels
1706 # very fragile, and it would be problematic to roll over at a later time.
[18]1707 my $sth2 = $dbh->prepare("SELECT host,type,val,distance,weight,port,ttl FROM default_records WHERE group_id=?");
[87]1708 $sth2->execute($pargroup);
[18]1709 while (my @clonedata = $sth2->fetchrow_array) {
[255]1710 $sthf->execute(@clonedata);
[18]1711 }
[255]1712 # And now the reverse records
1713 $sth2 = $dbh->prepare("SELECT group_id,host,type,val,ttl FROM default_rev_records WHERE group_id=?");
1714 $sth2->execute($pargroup);
1715 while (my @clonedata = $sth2->fetchrow_array) {
1716 $sthr->execute(@clonedata);
1717 }
[18]1718 } else {
[66]1719##fixme: Hardcoding is Bad, mmmmkaaaay?
[18]1720 # reasonable basic defaults for SOA, MX, NS, and minimal hosting
1721 # could load from a config file, but somewhere along the line we need hardcoded bits.
[255]1722 $sthf->execute('ns1.example.com:hostmaster.example.com', 6, '10800:3600:604800:10800', 0, 0, 0, 86400);
1723 $sthf->execute('DOMAIN', 1, '192.168.4.2', 0, 0, 0, 7200);
1724 $sthf->execute('DOMAIN', 15, 'mx.example.com', 10, 0, 0, 7200);
1725 $sthf->execute('DOMAIN', 2, 'ns1.example.com', 0, 0, 0, 7200);
1726 $sthf->execute('DOMAIN', 2, 'ns2.example.com', 0, 0, 0, 7200);
1727 $sthf->execute('www.DOMAIN', 5, 'DOMAIN', 0, 0, 0, 7200);
1728 # reasonable basic defaults for generic reverse zone. Same as initial SQL tabledef.
1729 $sthr->execute('hostmaster.ADMINDOMAIN:ns1.ADMINDOMAIN', 6, '10800:3600:604800:10800', 86400);
1730 $sthr->execute('unused-%r.ADMINDOMAIN', 65283, 'ZONE', 3600);
[18]1731 }
1732
1733 # once we get here, we should have suceeded.
1734 $dbh->commit;
1735 }; # end eval
1736
1737 if ($@) {
1738 my $msg = $@;
1739 eval { $dbh->rollback; };
1740 return ('FAIL',$msg);
1741 } else {
1742 return ('OK','OK');
1743 }
1744
1745} # end addGroup()
1746
1747
[22]1748## DNSDB::delGroup()
1749# Delete a group.
1750# Takes a group ID
1751# Returns a status code and message
1752sub delGroup {
1753 my $dbh = shift;
1754 my $groupid = shift;
1755
1756 # Allow transactions, and raise an exception on errors so we can catch it later.
1757 # Use local to make sure these get "reset" properly on exiting this block
1758 local $dbh->{AutoCommit} = 0;
1759 local $dbh->{RaiseError} = 1;
1760
1761##fixme: locate "knowable" error conditions and deal with them before the eval
[23]1762# ... or inside, whatever.
[22]1763# -> domains still exist in group
1764# -> ...
[23]1765 my $failmsg = '';
[22]1766
1767 # Wrap all the SQL in a transaction
1768 eval {
[23]1769 my $sth = $dbh->prepare("SELECT count(*) FROM domains WHERE group_id=?");
[22]1770 $sth->execute($groupid);
[23]1771 my ($domcnt) = $sth->fetchrow_array;
1772 $failmsg = "Can't remove group ".groupName($dbh,$groupid);
1773 die "$domcnt domains still in group\n" if $domcnt;
1774
1775 $sth = $dbh->prepare("delete from default_records where group_id=?");
1776 $failmsg = "Failed to delete default records for ".groupName($dbh,$groupid);
1777 $sth->execute($groupid);
[22]1778 $sth = $dbh->prepare("delete from groups where group_id=?");
[23]1779 $failmsg = "Failed to remove group ".groupName($dbh,$groupid);
[22]1780 $sth->execute($groupid);
1781
1782 # once we get here, we should have suceeded.
1783 $dbh->commit;
1784 }; # end eval
1785
1786 if ($@) {
1787 my $msg = $@;
1788 eval { $dbh->rollback; };
[23]1789 return ('FAIL',"$failmsg: $msg");
[22]1790 } else {
1791 return ('OK','OK');
1792 }
1793} # end delGroup()
1794
1795
[19]1796## DNSDB::getChildren()
1797# Get a list of all groups whose parent^n is group <n>
[24]1798# Takes a database handle, group ID, reference to an array to put the group IDs in,
1799# and an optional flag to return only immediate children or all children-of-children
1800# default to returning all children
[19]1801# Calls itself
1802sub getChildren {
1803 $errstr = '';
1804 my $dbh = shift;
[20]1805 my $rootgroup = shift;
1806 my $groupdest = shift;
[24]1807 my $immed = shift || 'all';
[19]1808
1809 # special break for default group; otherwise we get stuck.
[20]1810 if ($rootgroup == 1) {
[19]1811 # by definition, group 1 is the Root Of All Groups
[24]1812 my $sth = $dbh->prepare("SELECT group_id FROM groups WHERE NOT (group_id=1)".
1813 ($immed ne 'all' ? " AND parent_group_id=1" : ''));
[19]1814 $sth->execute;
1815 while (my @this = $sth->fetchrow_array) {
[20]1816 push @$groupdest, @this;
[19]1817 }
1818 } else {
1819 my $sth = $dbh->prepare("SELECT group_id FROM groups WHERE parent_group_id=?");
[20]1820 $sth->execute($rootgroup);
[19]1821 return if $sth->rows == 0;
[20]1822 my @grouplist;
1823 while (my ($group) = $sth->fetchrow_array) {
1824 push @$groupdest, $group;
[24]1825 getChildren($dbh,$group,$groupdest) if $immed eq 'all';
[19]1826 }
1827 }
1828} # end getChildren()
1829
1830
[20]1831## DNSDB::groupName()
[17]1832# Return the group name based on a group ID
1833# Takes a database handle and the group ID
1834# Returns the group name or undef on failure
[20]1835sub groupName {
[13]1836 $errstr = '';
1837 my $dbh = shift;
[20]1838 my $groupid = shift;
1839 my $sth = $dbh->prepare("SELECT group_name FROM groups WHERE group_id=?");
1840 $sth->execute($groupid);
1841 my ($groupname) = $sth->fetchrow_array();
1842 $errstr = $DBI::errstr if !$groupname;
1843 return $groupname if $groupname;
1844} # end groupName
[13]1845
1846
[118]1847## DNSDB::groupID()
1848# Return the group ID based on the group name
1849# Takes a database handle and the group name
1850# Returns the group ID or undef on failure
1851sub groupID {
1852 $errstr = '';
1853 my $dbh = shift;
1854 my $group = shift;
1855 my ($grpid) = $dbh->selectrow_array("SELECT group_id FROM groups WHERE group=?", undef, ($group) );
1856 $errstr = $DBI::errstr if !$grpid;
1857 return $grpid if $grpid;
1858} # end groupID()
1859
1860
[24]1861## DNSDB::addUser()
[87]1862# Add a user.
1863# Takes a DB handle, username, group ID, password, state (active/inactive).
1864# Optionally accepts:
1865# user type (user/admin) - defaults to user
1866# permissions string - defaults to inherit from group
1867# three valid forms:
1868# i - Inherit permissions
1869# c:<user_id> - Clone permissions from <user_id>
1870# C:<permission list> - Set these specific permissions
1871# first name - defaults to username
1872# last name - defaults to blank
1873# phone - defaults to blank (could put other data within column def)
[90]1874# Returns (OK,<uid>) on success, (FAIL,<message>) on failure
[24]1875sub addUser {
1876 $errstr = '';
1877 my $dbh = shift;
1878 my $username = shift;
1879 my $group = shift;
1880 my $pass = shift;
1881 my $state = shift;
[25]1882
[90]1883 return ('FAIL', "Missing one or more required entries") if !defined($state);
1884 return ('FAIL', "Username must not be blank") if !$username;
[87]1885
[25]1886 my $type = shift || 'u'; # create limited users by default - fwiw, not sure yet how this will interact with ACLs
1887
[67]1888 my $permstring = shift || 'i'; # default is to inhert permissions from group
1889
[25]1890 my $fname = shift || $username;
[24]1891 my $lname = shift || '';
[25]1892 my $phone = shift || ''; # not going format-check
[24]1893
[38]1894 my $sth = $dbh->prepare("SELECT user_id FROM users WHERE username=?");
[24]1895 my $user_id;
1896
[38]1897# quick check to start to see if we've already got one
1898 $sth->execute($username);
1899 ($user_id) = $sth->fetchrow_array;
1900
1901 return ('FAIL', "User already exists") if $user_id;
1902
[24]1903 # Allow transactions, and raise an exception on errors so we can catch it later.
1904 # Use local to make sure these get "reset" properly on exiting this block
1905 local $dbh->{AutoCommit} = 0;
1906 local $dbh->{RaiseError} = 1;
1907
[94]1908 my $failmsg = '';
1909
[24]1910 # Wrap all the SQL in a transaction
1911 eval {
[87]1912 # insert the user... note we set inherited perms by default since
1913 # it's simple and cleans up some other bits of state
1914 my $sth = $dbh->prepare("INSERT INTO users ".
1915 "(group_id,username,password,firstname,lastname,phone,type,status,permission_id,inherit_perm) ".
1916 "VALUES (?,?,?,?,?,?,?,?,(SELECT permission_id FROM permissions WHERE group_id=?),'t')");
1917 $sth->execute($group,$username,unix_md5_crypt($pass),$fname,$lname,$phone,$type,$state,$group);
[24]1918
1919 # get the ID...
[94]1920 ($user_id) = $dbh->selectrow_array("SELECT currval('users_user_id_seq')");
[24]1921
[87]1922# Permissions! Gotta set'em all!
1923 die "Invalid permission string $permstring"
1924 if $permstring !~ /^(?:
1925 i # inherit
1926 |c:\d+ # clone
1927 # custom. no, the leading , is not a typo
[111]1928 |C:(?:,(?:group|user|domain|record|self)_(?:edit|create|delete))*
[87]1929 )$/x;
1930# bleh. I'd call another function to do my dirty work, but we're in the middle of a transaction already.
1931 if ($permstring ne 'i') {
1932 # for cloned or custom permissions, we have to create a new permissions entry.
1933 my $clonesrc = $group;
1934 if ($permstring =~ /^c:(\d+)/) { $clonesrc = $1; }
1935 $dbh->do("INSERT INTO permissions ($permlist,user_id) ".
1936 "SELECT $permlist,? FROM permissions WHERE permission_id=".
1937 "(SELECT permission_id FROM permissions WHERE ".($permstring =~ /^c:/ ? 'user' : 'group')."_id=?)",
1938 undef, ($user_id,$clonesrc) );
1939 $dbh->do("UPDATE users SET permission_id=".
1940 "(SELECT permission_id FROM permissions WHERE user_id=?) ".
1941 "WHERE user_id=?", undef, ($user_id, $user_id) );
1942 }
1943 if ($permstring =~ /^C:/) {
1944 # finally for custom permissions, we set the passed-in permissions (and unset
1945 # any that might have been brought in by the clone operation above)
1946 my ($permid) = $dbh->selectrow_array("SELECT permission_id FROM permissions WHERE user_id=?",
1947 undef, ($user_id) );
1948 foreach (@permtypes) {
1949 if ($permstring =~ /,$_/) {
1950 $dbh->do("UPDATE permissions SET $_='t' WHERE permission_id=?", undef, ($permid) );
1951 } else {
1952 $dbh->do("UPDATE permissions SET $_='f' WHERE permission_id=?", undef, ($permid) );
1953 }
1954 }
1955 }
1956
1957 $dbh->do("UPDATE users SET inherit_perm='n' WHERE user_id=?", undef, ($user_id) );
1958
[25]1959##fixme: add another table to hold name/email for log table?
1960
[24]1961 # once we get here, we should have suceeded.
1962 $dbh->commit;
1963 }; # end eval
1964
1965 if ($@) {
1966 my $msg = $@;
1967 eval { $dbh->rollback; };
[87]1968 return ('FAIL',$msg." $failmsg");
[24]1969 } else {
1970 return ('OK',$user_id);
1971 }
1972} # end addUser
1973
1974
[55]1975## DNSDB::checkUser()
1976# Check user/pass combo on login
1977sub checkUser {
1978 my $dbh = shift;
1979 my $user = shift;
[56]1980 my $inpass = shift;
[55]1981
1982 my $sth = $dbh->prepare("SELECT user_id,group_id,password,firstname,lastname FROM users WHERE username=?");
1983 $sth->execute($user);
1984 my ($uid,$gid,$pass,$fname,$lname) = $sth->fetchrow_array;
1985 my $loginfailed = 1 if !defined($uid);
1986
1987 if ($pass =~ m|^\$1\$([A-Za-z0-9/.]+)\$|) {
[56]1988 $loginfailed = 1 if $pass ne unix_md5_crypt($inpass,$1);
[55]1989 } else {
[56]1990 $loginfailed = 1 if $pass ne $inpass;
[55]1991 }
1992
1993 # nnnngggg
1994 return ($uid, $gid);
1995} # end checkUser
1996
1997
[83]1998## DNSDB:: updateUser()
[90]1999# Update general data about user
[83]2000sub updateUser {
2001 my $dbh = shift;
[118]2002
2003##fixme: tweak calling convention so that we can update any given bit of data
[83]2004 my $uid = shift;
2005 my $username = shift;
2006 my $group = shift;
2007 my $pass = shift;
2008 my $state = shift;
[87]2009 my $type = shift || 'u';
[83]2010 my $fname = shift || $username;
2011 my $lname = shift || '';
2012 my $phone = shift || ''; # not going format-check
2013
2014 my $failmsg = '';
2015
2016 # Allow transactions, and raise an exception on errors so we can catch it later.
2017 # Use local to make sure these get "reset" properly on exiting this block
2018 local $dbh->{AutoCommit} = 0;
2019 local $dbh->{RaiseError} = 1;
2020
2021 my $sth;
2022
2023 # Password can be left blank; if so we assume there's one on file.
2024 # Actual blank passwords are bad, mm'kay?
2025 if (!$pass) {
2026 $sth = $dbh->prepare("SELECT password FROM users WHERE user_id=?");
2027 $sth->execute($uid);
2028 ($pass) = $sth->fetchrow_array;
2029 } else {
2030 $pass = unix_md5_crypt($pass);
2031 }
2032
2033 eval {
2034 my $sth = $dbh->prepare(q(
2035 UPDATE users
2036 SET username=?, password=?, firstname=?, lastname=?, phone=?, type=?, status=?
2037 WHERE user_id=?
2038 )
2039 );
2040 $sth->execute($username, $pass, $fname, $lname, $phone, $type, $state, $uid);
2041 $dbh->commit;
2042 };
2043 if ($@) {
2044 my $msg = $@;
2045 eval { $dbh->rollback; };
2046 return ('FAIL',"$failmsg: $msg");
2047 } else {
2048 return ('OK','OK');
2049 }
2050} # end updateUser()
2051
2052
[24]2053## DNSDB::delUser()
2054#
2055sub delUser {
[25]2056 my $dbh = shift;
2057 return ('FAIL',"Need database handle") if !$dbh;
2058 my $userid = shift;
2059 return ('FAIL',"Missing userid") if !defined($userid);
2060
2061 my $sth = $dbh->prepare("delete from users where user_id=?");
2062 $sth->execute($userid);
2063
2064 return ('FAIL',"Couldn't remove user: ".$sth->errstr) if $sth->err;
2065
2066 return ('OK','OK');
2067
[24]2068} # end delUser
2069
2070
[25]2071## DNSDB::userFullName()
2072# Return a pretty string!
2073# Takes a user_id and optional printf-ish string to indicate which pieces where:
2074# %u for the username
2075# %f for the first name
2076# %l for the last name
2077# All other text in the passed string will be left as-is.
2078##fixme: need a "smart" option too, so that missing/null/blank first/last names don't give funky output
2079sub userFullName {
2080 $errstr = '';
2081 my $dbh = shift;
2082 my $userid = shift;
2083 my $fullformat = shift || '%f %l (%u)';
2084 my $sth = $dbh->prepare("select username,firstname,lastname from users where user_id=?");
2085 $sth->execute($userid);
2086 my ($uname,$fname,$lname) = $sth->fetchrow_array();
2087 $errstr = $DBI::errstr if !$uname;
2088
2089 $fullformat =~ s/\%u/$uname/g;
2090 $fullformat =~ s/\%f/$fname/g;
2091 $fullformat =~ s/\%l/$lname/g;
2092
2093 return $fullformat;
2094} # end userFullName
2095
2096
[51]2097## DNSDB::userStatus()
2098# Sets and/or returns a user's status
2099# Takes a database handle, user ID and optionally a status argument
2100# Returns undef on errors.
2101sub userStatus {
2102 my $dbh = shift;
2103 my $id = shift;
2104 my $newstatus = shift;
2105
2106 return undef if $id !~ /^\d+$/;
2107
2108 my $sth;
2109
2110# ooo, fun! let's see what we were passed for status
2111 if ($newstatus) {
2112 $sth = $dbh->prepare("update users set status=? where user_id=?");
2113 # ass-u-me caller knows what's going on in full
2114 if ($newstatus =~ /^[01]$/) { # only two valid for now.
2115 $sth->execute($newstatus,$id);
2116 } elsif ($newstatus =~ /^usero(?:n|ff)$/) {
2117 $sth->execute(($newstatus eq 'useron' ? 1 : 0),$id);
2118 }
2119 }
2120
2121 $sth = $dbh->prepare("select status from users where user_id=?");
2122 $sth->execute($id);
2123 my ($status) = $sth->fetchrow_array;
2124 return $status;
2125} # end userStatus()
2126
2127
[83]2128## DNSDB::getUserData()
2129# Get misc user data for display
2130sub getUserData {
2131 my $dbh = shift;
2132 my $uid = shift;
2133
2134 my $sth = $dbh->prepare("SELECT group_id,username,firstname,lastname,phone,type,status,inherit_perm ".
2135 "FROM users WHERE user_id=?");
2136 $sth->execute($uid);
2137 return $sth->fetchrow_hashref();
2138
2139} # end getUserData()
2140
2141
[2]2142## DNSDB::getSOA()
2143# Return all suitable fields from an SOA record in separate elements of a hash
[224]2144# Takes a database handle, default/live flag, domain/reverse flag, and parent ID
[2]2145sub getSOA {
2146 $errstr = '';
2147 my $dbh = shift;
2148 my $def = shift;
[224]2149 my $rev = shift;
[2]2150 my $id = shift;
2151 my %ret;
2152
[224]2153 # (ab)use distance and weight columns to store SOA data? can't for default_rev_records...
2154 # - should really attach serial to the zone parent somewhere
[101]2155
[224]2156 my $sql = "SELECT record_id,host,val,ttl from "._rectable($def,$rev).
2157 " WHERE "._recparent($def,$rev)." = ? AND type=$reverse_typemap{SOA}";
2158
[2]2159 my $sth = $dbh->prepare($sql);
[101]2160 $sth->execute($id);
[246]2161##fixme: stick a flag somewhere if the record doesn't exist. by the API, this is an impossible case, but...
[2]2162
[224]2163 my ($recid,$host,$val,$ttl) = $sth->fetchrow_array() or return;
[202]2164 my ($contact,$prins) = split /:/, $host;
[2]2165 my ($refresh,$retry,$expire,$minttl) = split /:/, $val;
2166
2167 $ret{recid} = $recid;
2168 $ret{ttl} = $ttl;
[224]2169# $ret{serial} = $serial; # ca't use distance for serial with default_rev_records
[2]2170 $ret{prins} = $prins;
2171 $ret{contact} = $contact;
2172 $ret{refresh} = $refresh;
2173 $ret{retry} = $retry;
2174 $ret{expire} = $expire;
2175 $ret{minttl} = $minttl;
2176
2177 return %ret;
2178} # end getSOA()
2179
2180
[246]2181## DNSDB::updateSOA()
2182# Update the specified SOA record
2183# Takes a database handle, default/live flag, forward/reverse flag, and SOA data hash
2184sub updateSOA {
2185 my $dbh = shift;
2186 my $defrec = shift;
[248]2187 my $revrec = shift;
[246]2188
2189 my %soa = @_;
2190
2191##fixme: data validation: make sure {recid} is really the SOA for {parent}
[248]2192 my $sql = "UPDATE "._rectable($defrec, $revrec)." SET host=?, val=?, ttl=? WHERE record_id=? AND type=6";
2193 $dbh->do($sql, undef, ("$soa{contact}:$soa{prins}", "$soa{refresh}:$soa{retry}:$soa{expire}:$soa{minttl}",
2194 $soa{ttl}, $soa{recid}));
[246]2195
2196} # end updateSOA()
2197
2198
[2]2199## DNSDB::getRecLine()
2200# Return all data fields for a zone record in separate elements of a hash
[243]2201# Takes a database handle, default/live flag, forward/reverse flag, and record ID
[2]2202sub getRecLine {
2203 $errstr = '';
2204 my $dbh = shift;
[243]2205 my $defrec = shift;
2206 my $revrec = shift;
[2]2207 my $id = shift;
2208
[243]2209 my $sql = "SELECT record_id,host,type,val,ttl".($revrec eq 'n' ? ',distance,weight,port' : '').
2210 (($defrec eq 'y') ? ',group_id FROM ' : ',domain_id,rdns_id FROM ').
2211 _rectable($defrec,$revrec)." WHERE record_id=?";
[123]2212 my $ret = $dbh->selectrow_hashref($sql, undef, ($id) );
[2]2213
[90]2214 if ($dbh->err) {
[2]2215 $errstr = $DBI::errstr;
2216 return undef;
2217 }
2218
[123]2219 if (!$ret) {
2220 $errstr = "No such record";
2221 return undef;
2222 }
2223
[243]2224 # explicitly set a parent id
2225 if ($defrec eq 'y') {
2226 $ret->{parid} = $ret->{group_id};
2227 } else {
2228 $ret->{parid} = (($revrec eq 'n') ? $ret->{domain_id} : $ret->{rdns_id});
2229 # and a secondary if we have a custom type that lives in both a forward and reverse zone
2230 $ret->{secid} = (($revrec eq 'y') ? $ret->{domain_id} : $ret->{rdns_id}) if $ret->{type} > 65279;
2231 }
[90]2232
2233 return $ret;
[2]2234}
2235
2236
2237##fixme: should use above (getRecLine()) to get lines for below?
2238## DNSDB::getDomRecs()
2239# Return records for a domain
2240# Takes a database handle, default/live flag, group/domain ID, start,
2241# number of records, sort field, and sort order
2242# Returns a reference to an array of hashes
2243sub getDomRecs {
2244 $errstr = '';
2245 my $dbh = shift;
[224]2246 my $def = shift;
2247 my $rev = shift;
[2]2248 my $id = shift;
[4]2249 my $nrecs = shift || 'all';
2250 my $nstart = shift || 0;
[2]2251
[4]2252## for order, need to map input to column names
2253 my $order = shift || 'host';
[72]2254 my $direction = shift || 'ASC';
[4]2255
[135]2256 my $filter = shift || '';
2257
[224]2258 my $sql = "SELECT r.record_id,r.host,r.type,r.val,r.ttl";
2259 $sql .= ",r.distance,r.weight,r.port" if $rev eq 'n';
2260 $sql .= " FROM "._rectable($def,$rev)." r ";
[104]2261 $sql .= "INNER JOIN rectypes t ON r.type=t.val "; # for sorting by type alphabetically
[224]2262 $sql .= "WHERE "._recparent($def,$rev)." = ?";
[104]2263 $sql .= " AND NOT r.type=$reverse_typemap{SOA}";
[160]2264 $sql .= " AND host ~* ?" if $filter;
[104]2265 # use alphaorder column for "correct" ordering of sort-by-type instead of DNS RR type number
2266 $sql .= " ORDER BY ".($order eq 'type' ? 't.alphaorder' : "r.$order")." $direction";
[4]2267
[222]2268 my @bindvars = ($id);
2269 push @bindvars, $filter if $filter;
[224]2270
2271 # just to be ultraparanoid about SQL injection vectors
2272 if ($nstart ne 'all') {
2273 $sql .= " LIMIT ? OFFSET ?";
2274 push @bindvars, $nrecs;
2275 push @bindvars, ($nstart*$nrecs);
2276 }
[90]2277 my $sth = $dbh->prepare($sql) or warn $dbh->errstr;
[222]2278 $sth->execute(@bindvars) or warn "$sql: ".$sth->errstr;
[2]2279
2280 my @retbase;
2281 while (my $ref = $sth->fetchrow_hashref()) {
2282 push @retbase, $ref;
2283 }
2284
2285 my $ret = \@retbase;
2286 return $ret;
2287} # end getDomRecs()
2288
2289
[91]2290## DNSDB::getRecCount()
[224]2291# Return count of non-SOA records in zone (or default records in a group)
2292# Takes a database handle, default/live flag, reverse/forward flag, group/domain ID,
2293# and optional filtering modifier
[91]2294# Returns the count
2295sub getRecCount {
2296 my $dbh = shift;
2297 my $defrec = shift;
[224]2298 my $revrec = shift;
[91]2299 my $id = shift;
[135]2300 my $filter = shift || '';
[91]2301
[135]2302 # keep the nasties down, since we can't ?-sub this bit. :/
2303 # note this is chars allowed in DNS hostnames
2304 $filter =~ s/[^a-zA-Z0-9_.:-]//g;
2305
[222]2306 my @bindvars = ($id);
2307 push @bindvars, $filter if $filter;
[224]2308 my $sql = "SELECT count(*) FROM ".
2309 _rectable($defrec,$revrec).
2310 " WHERE "._recparent($defrec,$revrec)."=? ".
2311 "AND NOT type=$reverse_typemap{SOA}".
2312 ($filter ? " AND host ~* ?" : '');
2313 my ($count) = $dbh->selectrow_array($sql, undef, (@bindvars) );
[91]2314
2315 return $count;
2316
2317} # end getRecCount()
2318
2319
[3]2320## DNSDB::addRec()
[2]2321# Add a new record to a domain or a group's default records
2322# Takes a database handle, default/live flag, group/domain ID,
2323# host, type, value, and TTL
2324# Some types require additional detail: "distance" for MX and SRV,
2325# and weight/port for SRV
2326# Returns a status code and detail message in case of error
[234]2327##fixme: pass a hash with the record data, not a series of separate values
[2]2328sub addRec {
2329 $errstr = '';
2330 my $dbh = shift;
2331 my $defrec = shift;
[226]2332 my $revrec = shift;
2333 my $id = shift; # parent (group_id for defrecs, rdns_id for reverse records,
2334 # domain_id for domain records)
[2]2335
2336 my $host = shift;
[234]2337 my $rectype = shift; # reference so we can coerce it if "+"-types can't find both zones
[2]2338 my $val = shift;
2339 my $ttl = shift;
2340
[226]2341 # prep for validation
[252]2342 my $addr = NetAddr::IP->new($$val);
2343 $$host =~ s/\.+$//; # FQDNs ending in . are an internal detail, and really shouldn't be exposed in the UI.
[226]2344
2345 my $domid = 0;
2346 my $revid = 0;
2347
2348 my $retcode = 'OK'; # assume everything will go OK
2349 my $retmsg = '';
2350
2351 # do simple validation first
2352 return ('FAIL', "TTL must be numeric") unless $ttl =~ /^\d+$/;
2353
[234]2354 # Quick check on hostname parts. Note the regex is more forgiving than the error message;
2355 # domain names technically are case-insensitive, and we use printf-like % codes for a couple
2356 # of types. Other things may also be added to validate default records of several flavours.
2357 return ('FAIL', "Hostnames may not contain anything other than (0-9 a-z . _)")
[272]2358 if $defrec eq 'n' && $$host !~ /^[0-9a-z_%.-]+$/i;
[226]2359
[234]2360 # Collect these even if we're only doing a simple A record so we can call *any* validation sub
2361 my $dist = shift;
2362 my $port = shift;
2363 my $weight = shift;
[226]2364
[234]2365 my $fields;
2366 my @vallist;
[226]2367
[234]2368 # Call the validation sub for the type requested.
2369 ($retcode,$retmsg) = $validators{$$rectype}($dbh, (defrec => $defrec, revrec => $revrec, id => $id,
[249]2370 host => $host, rectype => $rectype, val => $val, addr => $addr,
[234]2371 dist => \$dist, port => \$port, weight => \$weight,
2372 fields => \$fields, vallist => \@vallist) );
[129]2373
[234]2374 return ($retcode,$retmsg) if $retcode eq 'FAIL';
[209]2375
[234]2376 # Set up database fields and bind parameters
2377 $fields .= "host,type,val,ttl,"._recparent($defrec,$revrec);
[249]2378 push @vallist, ($$host,$$rectype,$$val,$ttl,$id);
[234]2379 my $vallen = '?'.(',?'x$#vallist);
[2]2380
[90]2381 # Allow transactions, and raise an exception on errors so we can catch it later.
2382 # Use local to make sure these get "reset" properly on exiting this block
2383 local $dbh->{AutoCommit} = 0;
2384 local $dbh->{RaiseError} = 1;
[2]2385
[90]2386 eval {
[236]2387 $dbh->do("INSERT INTO "._rectable($defrec, $revrec)." ($fields) VALUES ($vallen)",
[90]2388 undef, @vallist);
2389 $dbh->commit;
2390 };
2391 if ($@) {
2392 my $msg = $@;
2393 eval { $dbh->rollback; };
2394 return ('FAIL',$msg);
2395 }
[2]2396
[226]2397 return ($retcode, $retmsg);
[90]2398
[2]2399} # end addRec()
2400
2401
[16]2402## DNSDB::updateRec()
2403# Update a record
[273]2404# Takes a database handle, default and reverse flags, record ID, immediate parent ID, and new record data.
2405# Returns a status code and message
[16]2406sub updateRec {
2407 $errstr = '';
[17]2408
[16]2409 my $dbh = shift;
2410 my $defrec = shift;
[272]2411 my $revrec = shift;
[16]2412 my $id = shift;
[272]2413 my $parid = shift; # immediate parent entity that we're descending from to update the record
[16]2414
[273]2415 # all records have these
[16]2416 my $host = shift;
[272]2417 my $hostbk = $$host; # Keep a backup copy of the original, so we can WARN if the update mangles the domain
2418 my $rectype = shift;
[16]2419 my $val = shift;
2420 my $ttl = shift;
2421
[272]2422 # prep for validation
2423 my $addr = NetAddr::IP->new($$val);
2424 $$host =~ s/\.+$//; # FQDNs ending in . are an internal detail, and really shouldn't be exposed in the UI.
[16]2425
[272]2426 my $domid = 0;
2427 my $revid = 0;
2428
2429 my $retcode = 'OK'; # assume everything will go OK
2430 my $retmsg = '';
2431
[273]2432 # do simple validation first
[272]2433 return ('FAIL', "TTL must be numeric") unless $ttl =~ /^\d+$/;
2434
2435 # Quick check on hostname parts. Note the regex is more forgiving than the error message;
2436 # domain names technically are case-insensitive, and we use printf-like % codes for a couple
2437 # of types. Other things may also be added to validate default records of several flavours.
[273]2438 return ('FAIL', "Hostnames may not contain anything other than (0-9 a-z - . _)")
[272]2439 if $defrec eq 'n' && $$host !~ /^[0-9a-z_%.-]+$/i;
2440
[273]2441 # only MX and SRV will use these
[16]2442 my $dist = 0;
2443 my $weight = 0;
2444 my $port = 0;
2445
[272]2446 my $fields;
2447 my @vallist;
[16]2448
[273]2449 # get old record data so we have the right parent ID
2450 # and for logging (eventually)
2451 my $oldrec = getRecLine($dbh, $defrec, $revrec, $id);
[223]2452
[272]2453 # Call the validation sub for the type requested.
2454 # Note the ID to pass here is the *parent*, not the record
2455 ($retcode,$retmsg) = $validators{$$rectype}($dbh, (defrec => $defrec, revrec => $revrec,
2456 id => ($defrec eq 'y' ? $oldrec->{group_id} : ($revrec eq 'n' ? $oldrec->{domain_id} : $oldrec->{rdns_id})),
2457 host => $host, rectype => $rectype, val => $val, addr => $addr,
2458 dist => \$dist, port => \$port, weight => \$weight,
2459 fields => \$fields, vallist => \@vallist,
2460 update => $id) );
2461
2462 return ($retcode,$retmsg) if $retcode eq 'FAIL';
2463
[273]2464 # Set up database fields and bind parameters. Note only the optional fields
2465 # (distance, weight, port, secondary parent ID) are added in the validation call above
2466 $fields .= "host,type,val,ttl,"._recparent($defrec,$revrec);
2467 push @vallist, ($$host,$$rectype,$$val,$ttl,
2468 ($defrec eq 'y' ? $oldrec->{group_id} : ($revrec eq 'n' ? $oldrec->{domain_id} : $oldrec->{rdns_id})) );
[272]2469
[273]2470 # hack hack PTHUI
2471 # need to forcibly make sure we disassociate a record with a parent it's no longer related to.
2472 # eg, PTR records may not have a domain parent, or A/AAAA records may not have a revzone parent.
2473 # mainly needed for crossover types that got coerced down to "standard" types
2474 if ($defrec eq 'n') {
2475 if ($$rectype == $reverse_typemap{PTR}) {
2476 $fields .= ",domain_id";
2477 push @vallist, 0;
2478 }
2479 if ($$rectype == $reverse_typemap{A} || $$rectype == $reverse_typemap{AAAA}) {
2480 $fields .= ",rdns_id";
2481 push @vallist, 0;
2482 }
2483 }
[272]2484
[273]2485 # Fiddle the field list into something suitable for updates
2486 $fields =~ s/,/=?,/g;
2487 $fields .= "=?";
[272]2488
[90]2489 local $dbh->{AutoCommit} = 0;
2490 local $dbh->{RaiseError} = 1;
2491
2492 eval {
[273]2493 $dbh->do("UPDATE "._rectable($defrec,$revrec)." SET $fields WHERE record_id=?", undef, (@vallist, $id) );
[130]2494 $dbh->commit;
[90]2495 };
2496 if ($@) {
2497 my $msg = $@;
2498 $dbh->rollback;
2499 return ('FAIL', $msg);
2500 }
2501
[272]2502 return ($retcode, $retmsg);
[16]2503} # end updateRec()
2504
2505
[3]2506## DNSDB::delRec()
2507# Delete a record.
2508sub delRec {
2509 $errstr = '';
2510 my $dbh = shift;
2511 my $defrec = shift;
[243]2512 my $revrec = shift;
[3]2513 my $id = shift;
2514
[243]2515 my $sth = $dbh->prepare("DELETE FROM "._rectable($defrec,$revrec)." WHERE record_id=?");
[3]2516 $sth->execute($id);
2517
[23]2518 return ('FAIL',"Couldn't remove record: ".$sth->errstr) if $sth->err;
[3]2519
2520 return ('OK','OK');
2521} # end delRec()
2522
2523
[117]2524 # Reference hashes.
[244]2525my %par_tbl = (
[117]2526 group => 'groups',
2527 user => 'users',
2528 defrec => 'default_records',
[244]2529 defrevrec => 'default_rev_records',
[117]2530 domain => 'domains',
[244]2531 revzone => 'revzones',
[117]2532 record => 'records'
2533 );
[244]2534my %id_col = (
[117]2535 group => 'group_id',
2536 user => 'user_id',
2537 defrec => 'record_id',
[244]2538 defrevrec => 'record_id',
[117]2539 domain => 'domain_id',
[244]2540 revzone => 'rdns_id',
[117]2541 record => 'record_id'
2542 );
[244]2543my %par_col = (
[117]2544 group => 'parent_group_id',
2545 user => 'group_id',
2546 defrec => 'group_id',
[244]2547 defrevrec => 'group_id',
[117]2548 domain => 'group_id',
[244]2549 revzone => 'group_id',
[117]2550 record => 'domain_id'
2551 );
[244]2552my %par_type = (
[117]2553 group => 'group',
2554 user => 'group',
2555 defrec => 'group',
[244]2556 defrevrec => 'group',
[117]2557 domain => 'group',
[244]2558 revzone => 'group',
[117]2559 record => 'domain'
2560 );
2561
[225]2562
2563## DNSDB::getTypelist()
2564# Get a list of record types for various UI dropdowns
2565# Takes database handle, forward/reverse/lookup flag, and optional "tag as selected" indicator (defaults to A)
2566# Returns an arrayref to list of hashrefs perfect for HTML::Template
2567sub getTypelist {
2568 my $dbh = shift;
2569 my $recgroup = shift;
2570 my $type = shift || $reverse_typemap{A};
2571
2572 # also accepting $webvar{revrec}!
2573 $recgroup = 'f' if $recgroup eq 'n';
2574 $recgroup = 'r' if $recgroup eq 'y';
2575
2576 my $sql = "SELECT val,name FROM rectypes WHERE ";
2577 if ($recgroup eq 'r') {
2578 # reverse zone types
2579 $sql .= "stdflag=2 OR stdflag=3";
2580 } elsif ($recgroup eq 'l') {
2581 # DNS lookup types. Note we avoid our custom types >= 65280, since those are entirely internal.
2582 $sql .= "(stdflag=1 OR stdflag=2 OR stdflag=3) AND val < 65280";
2583 } else {
2584 # default; forward zone types. technically $type eq 'f' but not worth the error message.
2585 $sql .= "stdflag=1 OR stdflag=2";
2586 }
2587 $sql .= " ORDER BY listorder";
2588
2589 my $sth = $dbh->prepare($sql);
2590 $sth->execute;
2591 my @typelist;
2592 while (my ($rval,$rname) = $sth->fetchrow_array()) {
2593 my %row = ( recval => $rval, recname => $rname );
2594 $row{tselect} = 1 if $rval == $type;
2595 push @typelist, \%row;
2596 }
2597
2598 # Add SOA on lookups since it's not listed in other dropdowns.
2599 if ($recgroup eq 'l') {
2600 my %row = ( recval => $reverse_typemap{SOA}, recname => 'SOA' );
2601 $row{tselect} = 1 if $reverse_typemap{SOA} == $type;
2602 push @typelist, \%row;
2603 }
2604
2605 return \@typelist;
2606} # end getTypelist()
2607
2608
[254]2609## DNSDB::parentID()
2610# Get ID of entity that is nearest parent to requested id
2611# Takes a database handle and a hash of entity ID, entity type, optional parent type flag
2612# (domain/reverse zone or group), and optional default/live and forward/reverse flags
2613# Returns the ID or undef on failure
2614sub parentID {
[116]2615 my $dbh = shift;
2616
[254]2617 my %args = @_;
[116]2618
[254]2619 # clean up the parent-type. Set it to group if not set; coerce revzone to domain for simpler logic
2620 $args{partype} = 'group' if !$args{partype};
2621 $args{partype} = 'domain' if $args{partype} eq 'revzone';
[116]2622
[254]2623 # clean up defrec and revrec. default to live record, forward zone
2624 $args{defrec} = 'n' if !$args{defrec};
2625 $args{revrec} = 'n' if !$args{revrec};
[116]2626
[254]2627 if ($par_type{$args{partype}} eq 'domain') {
2628 # only live records can have a domain/zone parent
2629 return unless ($args{type} eq 'record' && $args{defrec} eq 'n');
2630 my $result = $dbh->selectrow_hashref("SELECT ".($args{revrec} eq 'n' ? 'domain_id' : 'rdns_id').
2631 " FROM records WHERE record_id = ?",
2632 undef, ($args{id}) ) or return;
2633 return $result;
2634 } else {
2635 # snag some arguments that will either fall through or be overwritten to save some code duplication
2636 my $tmpid = $args{id};
2637 my $type = $args{type};
2638 if ($type eq 'record' && $args{defrec} eq 'n') {
2639 # Live records go through the records table first.
2640 ($tmpid) = $dbh->selectrow_array("SELECT ".($args{revrec} eq 'n' ? 'domain_id' : 'rdns_id').
2641 " FROM records WHERE record_id = ?",
2642 undef, ($args{id}) ) or return;
2643 $type = ($args{revrec} eq 'n' ? 'domain' : 'revzone');
2644 }
2645 my ($result) = $dbh->selectrow_array("SELECT $par_col{$type} FROM $par_tbl{$type} WHERE $id_col{$type} = ?",
2646 undef, ($tmpid) );
2647 return $result;
2648 }
2649# should be impossible to get here with even remotely sane arguments
2650 return;
2651} # end parentID()
[116]2652
2653
[117]2654## DNSDB::isParent()
2655# Returns true if $id1 is a parent of $id2, false otherwise
2656sub isParent {
2657 my $dbh = shift;
2658 my $id1 = shift;
2659 my $type1 = shift;
2660 my $id2 = shift;
2661 my $type2 = shift;
2662##todo: immediate, secondary, full (default)
2663
[157]2664 # Return false on invalid types
[244]2665 return 0 if !grep /^$type1$/, ('record','defrec','defrevrec','user','domain','revzone','group');
2666 return 0 if !grep /^$type2$/, ('record','defrec','defrevrec','user','domain','revzone','group');
[157]2667
[117]2668 # Return false on impossible relations
2669 return 0 if $type1 eq 'record'; # nothing may be a child of a record
2670 return 0 if $type1 eq 'defrec'; # nothing may be a child of a record
[244]2671 return 0 if $type1 eq 'defrevrec'; # nothing may be a child of a record
[117]2672 return 0 if $type1 eq 'user'; # nothing may be child of a user
2673 return 0 if $type1 eq 'domain' && $type2 ne 'record'; # domain may not be a parent of anything other than a record
[244]2674 return 0 if $type1 eq 'revzone' && $type2 ne 'record';# reverse zone may not be a parent of anything other than a record
[117]2675
[186]2676 # ennnhhhh.... if we're passed an id of 0, it will never be found. usual
2677 # case would be the UI creating a new <thing>, and so we don't have an ID for
2678 # <thing> to look up yet. in that case the UI should check the parent as well.
2679 return 0 if $id1 == 0; # nothing can have a parent id of 0
2680 return 1 if $id2 == 0; # anything could have a child id of 0 (or "unknown")
2681
[117]2682 # group 1 is the ultimate root parent
2683 return 1 if $type1 eq 'group' && $id1 == 1;
2684
[155]2685 # groups are always (a) parent of themselves
2686 return 1 if $type1 eq 'group' && $type2 eq 'group' && $id1 == $id2;
2687
[117]2688 my $id = $id2;
2689 my $type = $type2;
2690 my $foundparent = 0;
[155]2691
[244]2692 # Records are the only entity with two possible parents. We need to split the parent checks on
2693 # domain/rdns.
2694 if ($type eq 'record') {
2695 my ($dom,$rdns) = $dbh->selectrow_array("SELECT domain_id,rdns_id FROM records WHERE record_id=?",
2696 undef, ($id));
2697 # check immediate parent against request
2698 return 1 if $type1 eq 'domain' && $id1 == $dom;
2699 return 1 if $type1 eq 'revzone' && $id1 == $rdns;
2700 # if request is group, check *both* parents. Only check if the parent is nonzero though.
2701 return 1 if $dom && isParent($dbh, $id1, $type1, $dom, 'domain');
2702 return 1 if $rdns && isParent($dbh, $id1, $type1, $rdns, 'revzone');
2703 # exit here since we've executed the loop below by proxy in the above recursive calls.
2704 return 0;
2705 }
2706
2707# almost the same loop as getParents() above
[186]2708 my $limiter = 0;
[117]2709 while (1) {
[155]2710 my $sql = "SELECT $par_col{$type} FROM $par_tbl{$type} WHERE $id_col{$type} = ?";
[117]2711 my $result = $dbh->selectrow_hashref($sql,
[157]2712 undef, ($id) );
[186]2713 if (!$result) {
2714 $limiter++;
[244]2715##fixme: how often will this happen on a live site? fail at max limiter <n>?
[186]2716 warn "no results looking for $sql with id $id (depth $limiter)\n";
2717 last;
2718 }
[157]2719 if ($result && $result->{$par_col{$type}} == $id1) {
[117]2720 $foundparent = 1;
2721 last;
[157]2722 } else {
2723##fixme: do we care about trying to return a "no such record/domain/user/group" error?
[244]2724# should be impossible to create an inconsistent DB just with API calls.
[157]2725 warn $dbh->errstr." $sql, $id" if $dbh->errstr;
[117]2726 }
2727 # group 1 is its own parent. need this here more to break strange loops than for detecting a parent
2728 last if $result->{$par_col{$type}} == 1;
[152]2729 $id = $result->{$par_col{$type}};
[117]2730 $type = $par_type{$type};
2731 }
2732
2733 return $foundparent;
2734} # end isParent()
2735
2736
[275]2737## DNSDB::zoneStatus()
2738# Returns and optionally sets a zone's status
2739# Takes a database handle, domain/revzone ID, forward/reverse flag, and optionally a status argument
2740# Returns status, or undef on errors.
2741sub zoneStatus {
[3]2742 my $dbh = shift;
2743 my $id = shift;
[275]2744 my $revrec = shift;
2745 my $newstatus = shift || 'mu';
[3]2746
2747 return undef if $id !~ /^\d+$/;
2748
2749# ooo, fun! let's see what we were passed for status
[275]2750 if ($newstatus ne 'mu') {
2751 $newstatus = 0 if $newstatus eq 'domoff';
2752 $newstatus = 1 if $newstatus eq 'domon';
2753 $dbh->do("UPDATE ".($revrec eq 'n' ? 'domains' : 'revzones')." SET status=? WHERE ".
2754 ($revrec eq 'n' ? 'domain_id' : 'rdns_id')."=?", undef, ($newstatus,$id) );
[3]2755 }
2756
[275]2757 my ($status) = $dbh->selectrow_array("SELECT status FROM ".
2758 ($revrec eq 'n' ? "domains WHERE domain_id=?" : "revzones WHERE rdns_id=?"),
2759 undef, ($id) );
[3]2760 return $status;
[275]2761} # end zoneStatus()
[3]2762
2763
[33]2764## DNSDB::importAXFR
2765# Import a domain via AXFR
[37]2766# Takes AXFR host, domain to transfer, group to put the domain in,
2767# and optionally:
2768# - active/inactive state flag (defaults to active)
2769# - overwrite-SOA flag (defaults to off)
2770# - overwrite-NS flag (defaults to off, doesn't affect subdomain NS records)
2771# Returns a status code (OK, WARN, or FAIL) and message - message should be blank
2772# if status is OK, but WARN includes conditions that are not fatal but should
2773# really be reported.
[33]2774sub importAXFR {
2775 my $dbh = shift;
[35]2776 my $ifrom_in = shift;
[33]2777 my $domain = shift;
2778 my $group = shift;
2779 my $status = shift || 1;
2780 my $rwsoa = shift || 0;
2781 my $rwns = shift || 0;
[37]2782
[33]2783##fixme: add mode to delete&replace, merge+overwrite, merge new?
2784
[37]2785 my $nrecs = 0;
2786 my $soaflag = 0;
2787 my $nsflag = 0;
2788 my $warnmsg = '';
2789 my $ifrom;
[33]2790
[35]2791 # choke on possible bad setting in ifrom
[37]2792 # IPv4 and v6, and valid hostnames!
[35]2793 ($ifrom) = ($ifrom_in =~ /^([0-9a-f\:.]+|[0-9a-z_.-]+)$/i);
2794 return ('FAIL', "Bad AXFR source host $ifrom")
2795 unless ($ifrom) = ($ifrom_in =~ /^([0-9a-f\:.]+|[0-9a-z_.-]+)$/i);
2796
[33]2797 # Allow transactions, and raise an exception on errors so we can catch it later.
2798 # Use local to make sure these get "reset" properly on exiting this block
2799 local $dbh->{AutoCommit} = 0;
2800 local $dbh->{RaiseError} = 1;
2801
[37]2802 my $sth = $dbh->prepare("SELECT domain_id FROM domains WHERE domain=?");
[34]2803 my $dom_id;
2804
[35]2805# quick check to start to see if we've already got one
[37]2806 $sth->execute($domain);
2807 ($dom_id) = $sth->fetchrow_array;
[35]2808
2809 return ('FAIL', "Domain already exists") if $dom_id;
2810
[33]2811 eval {
2812 # can't do this, can't nest transactions. sigh.
[35]2813 #my ($dcode, $dmsg) = addDomain(dbh, domain, group, status);
[33]2814
2815##fixme: serial
[37]2816 my $sth = $dbh->prepare("INSERT INTO domains (domain,group_id,status) VALUES (?,?,?)");
2817 $sth->execute($domain,$group,$status);
[33]2818
[35]2819## bizarre DBI<->Net::DNS interaction bug:
2820## sometimes a zone will cause an immediate commit-and-exit (sort of) of the while()
[37]2821## fixed, apparently I was doing *something* odd, but not certain what it was that
2822## caused a commit instead of barfing
[35]2823
[33]2824 # get domain id so we can do the records
[37]2825 $sth = $dbh->prepare("SELECT domain_id FROM domains WHERE domain=?");
2826 $sth->execute($domain);
2827 ($dom_id) = $sth->fetchrow_array();
[33]2828
[34]2829 my $res = Net::DNS::Resolver->new;
[35]2830 $res->nameservers($ifrom);
2831 $res->axfr_start($domain)
2832 or die "Couldn't begin AXFR\n";
[34]2833
[35]2834 while (my $rr = $res->axfr_next()) {
[33]2835 my $type = $rr->type;
[35]2836
[34]2837 my $sql = "INSERT INTO records (domain_id,host,type,ttl,val";
[33]2838 my $vallen = "?,?,?,?,?";
2839
[37]2840 $soaflag = 1 if $type eq 'SOA';
2841 $nsflag = 1 if $type eq 'NS';
[35]2842
2843 my @vallist = ($dom_id, $rr->name, $reverse_typemap{$type}, $rr->ttl);
[34]2844
2845# "Primary" types:
2846# A, NS, CNAME, SOA, PTR(warn in forward), MX, TXT, AAAA, SRV, A6(ob), SPF
2847# maybe KEY
2848
[35]2849# nasty big ugly case-like thing here, since we have to do *some* different
2850# processing depending on the record. le sigh.
2851
[105]2852##fixme: what record types other than TXT can/will have >255-byte payloads?
2853
[34]2854 if ($type eq 'A') {
2855 push @vallist, $rr->address;
2856 } elsif ($type eq 'NS') {
[37]2857# hmm. should we warn here if subdomain NS'es are left alone?
2858 next if ($rwns && ($rr->name eq $domain));
[34]2859 push @vallist, $rr->nsdname;
[35]2860 $nsflag = 1;
[34]2861 } elsif ($type eq 'CNAME') {
2862 push @vallist, $rr->cname;
2863 } elsif ($type eq 'SOA') {
[37]2864 next if $rwsoa;
[34]2865 $vallist[1] = $rr->mname.":".$rr->rname;
2866 push @vallist, ($rr->refresh.":".$rr->retry.":".$rr->expire.":".$rr->minimum);
[35]2867 $soaflag = 1;
[34]2868 } elsif ($type eq 'PTR') {
[105]2869 push @vallist, $rr->ptrdname;
[34]2870 # hmm. PTR records should not be in forward zones.
2871 } elsif ($type eq 'MX') {
[33]2872 $sql .= ",distance";
2873 $vallen .= ",?";
[34]2874 push @vallist, $rr->exchange;
2875 push @vallist, $rr->preference;
2876 } elsif ($type eq 'TXT') {
2877##fixme: Net::DNS docs say this should be deprecated for rdatastr() or char_str_list(),
2878## but don't really seem enthusiastic about it.
[105]2879 my $rrdata = $rr->txtdata;
[130]2880 push @vallist, $rrdata;
[34]2881 } elsif ($type eq 'SPF') {
2882##fixme: and the same caveat here, since it is apparently a clone of ::TXT
[105]2883 my $rrdata = $rr->txtdata;
[130]2884 push @vallist, $rrdata;
[34]2885 } elsif ($type eq 'AAAA') {
2886 push @vallist, $rr->address;
2887 } elsif ($type eq 'SRV') {
2888 $sql .= ",distance,weight,port" if $type eq 'SRV';
2889 $vallen .= ",?,?,?" if $type eq 'SRV';
[37]2890 push @vallist, $rr->target;
[34]2891 push @vallist, $rr->priority;
2892 push @vallist, $rr->weight;
2893 push @vallist, $rr->port;
2894 } elsif ($type eq 'KEY') {
[35]2895 # we don't actually know what to do with these...
[34]2896 push @vallist, ($rr->flags.":".$rr->protocol.":".$rr->algorithm.":".$rr->key.":".$rr->keytag.":".$rr->privatekeyname);
[35]2897 } else {
[105]2898 my $rrdata = $rr->rdatastr;
[130]2899 push @vallist, $rrdata;
[35]2900 # Finding a different record type is not fatal.... just problematic.
[37]2901 # We may not be able to export it correctly.
[35]2902 $warnmsg .= "Unusual record ".$rr->name." ($type) found\n";
[33]2903 }
2904
[34]2905# BIND supports:
2906# A CNAME HINFO MB(ex) MD(ob) MF(ob) MG(ex) MINFO(ex) MR(ex) MX NS NULL
2907# PTR SOA TXT WKS AFSDB(ex) ISDN(ex) RP(ex) RT(ex) X25(ex) PX
2908# ... if one can ever find the right magic to format them correctly
2909
2910# Net::DNS supports:
2911# RRSIG SIG NSAP NS NIMLOC NAPTR MX MR MINFO MG MB LOC ISDN IPSECKEY HINFO
2912# EID DNAME CNAME CERT APL AFSDB AAAA A DS NXT NSEC3PARAM NSEC3 NSEC KEY
2913# DNSKEY DLV X25 TXT TSIG TKEY SSHFP SRV SPF SOA RT RP PX PTR NULL APL::AplItem
2914
[37]2915 $sth = $dbh->prepare($sql.") VALUES (".$vallen.")") or die "problem preparing record insert SQL\n";
2916 $sth->execute(@vallist) or die "failed to insert ".$rr->string.": ".$sth->errstr."\n";
[34]2917
[37]2918 $nrecs++;
[34]2919
[37]2920 } # while axfr_next
2921
2922 # Overwrite SOA record
2923 if ($rwsoa) {
2924 $soaflag = 1;
2925 my $sthgetsoa = $dbh->prepare("SELECT host,val,ttl FROM default_records WHERE group_id=? AND type=?");
2926 my $sthputsoa = $dbh->prepare("INSERT INTO records (domain_id,host,type,val,ttl) VALUES (?,?,?,?,?)");
2927 $sthgetsoa->execute($group,$reverse_typemap{SOA});
2928 while (my ($host,$val,$ttl) = $sthgetsoa->fetchrow_array()) {
2929 $host =~ s/DOMAIN/$domain/g;
2930 $val =~ s/DOMAIN/$domain/g;
2931 $sthputsoa->execute($dom_id,$host,$reverse_typemap{SOA},$val,$ttl);
[34]2932 }
[37]2933 }
[34]2934
[37]2935 # Overwrite NS records
2936 if ($rwns) {
2937 $nsflag = 1;
2938 my $sthgetns = $dbh->prepare("SELECT host,val,ttl FROM default_records WHERE group_id=? AND type=?");
2939 my $sthputns = $dbh->prepare("INSERT INTO records (domain_id,host,type,val,ttl) VALUES (?,?,?,?,?)");
2940 $sthgetns->execute($group,$reverse_typemap{NS});
2941 while (my ($host,$val,$ttl) = $sthgetns->fetchrow_array()) {
2942 $host =~ s/DOMAIN/$domain/g;
2943 $val =~ s/DOMAIN/$domain/g;
2944 $sthputns->execute($dom_id,$host,$reverse_typemap{NS},$val,$ttl);
2945 }
2946 }
[34]2947
[35]2948 die "No records found; either $ifrom is not authoritative or doesn't allow transfers\n" if !$nrecs;
2949 die "Bad zone: No SOA record!\n" if !$soaflag;
2950 die "Bad zone: No NS records!\n" if !$nsflag;
2951
[37]2952 $dbh->commit;
[35]2953
[33]2954 };
2955
2956 if ($@) {
2957 my $msg = $@;
2958 eval { $dbh->rollback; };
[34]2959 return ('FAIL',$msg." $warnmsg");
[33]2960 } else {
[35]2961 return ('WARN', $warnmsg) if $warnmsg;
[91]2962 return ('OK',"Imported OK");
[33]2963 }
2964
[37]2965 # it should be impossible to get here.
[34]2966 return ('WARN',"OOOK!");
[33]2967} # end importAXFR()
2968
2969
[103]2970## DNSDB::export()
2971# Export the DNS database, or a part of it
2972# Takes database handle, export type, optional arguments depending on type
2973# Writes zone data to targets as appropriate for type
2974sub export {
2975 my $dbh = shift;
2976 my $target = shift;
2977
2978 if ($target eq 'tiny') {
2979 __export_tiny($dbh,@_);
2980 }
2981# elsif ($target eq 'foo') {
2982# __export_foo($dbh,@_);
2983#}
2984# etc
2985
2986} # end export()
2987
2988
2989## DNSDB::__export_tiny
2990# Internal sub to implement tinyDNS (compatible) export
2991# Takes database handle, filehandle to write export to, optional argument(s)
2992# to determine which data gets exported
2993sub __export_tiny {
2994 my $dbh = shift;
2995 my $datafile = shift;
2996
2997##fixme: slurp up further options to specify particular zone(s) to export
2998
2999 ## Convert a bare number into an octal-coded pair of octets.
3000 # Take optional arg to indicate a decimal or hex input. Defaults to hex.
3001 sub octalize {
3002 my $tmp = shift;
3003 my $srctype = shift || 'h'; # default assumes hex string
3004 $tmp = sprintf "%0.4x", hex($tmp) if $srctype eq 'h'; # 0-pad hex to 4 digits
3005 $tmp = sprintf "%0.4x", $tmp if $srctype eq 'd'; # 0-pad decimal to 4 hex digits
3006 my @o = ($tmp =~ /^(..)(..)$/); # split into octets
3007 return sprintf "\\%0.3o\\%0.3o", hex($o[0]), hex($o[1]);;
3008 }
3009
3010##fixme: fail if $datafile isn't an open, writable file
3011
3012 # easy case - export all evarything
3013 # not-so-easy case - export item(s) specified
3014 # todo: figure out what kind of list we use to export items
3015
3016 my $domsth = $dbh->prepare("SELECT domain_id,domain,status FROM domains WHERE status=1");
[130]3017 my $recsth = $dbh->prepare("SELECT host,type,val,distance,weight,port,ttl ".
3018 "FROM records WHERE domain_id=?");
[103]3019 $domsth->execute();
3020 while (my ($domid,$dom,$domstat) = $domsth->fetchrow_array) {
3021 $recsth->execute($domid);
[130]3022 while (my ($host,$type,$val,$dist,$weight,$port,$ttl) = $recsth->fetchrow_array) {
[108]3023##fixme: need to store location in the db, and retrieve it here.
3024# temporarily hardcoded to empty so we can include it further down.
3025my $loc = '';
3026
3027##fixme: record validity timestamp. tinydns supports fiddling with timestamps.
3028# note $ttl must be set to 0 if we want to use tinydns's auto-expiring timestamps.
3029# timestamps are TAI64
3030# ~~ 2^62 + time()
3031my $stamp = '';
3032
[103]3033# raw packet in unknown format: first byte indicates length
3034# of remaining data, allows up to 255 raw bytes
3035
3036##fixme? append . to all host/val hostnames
3037 if ($typemap{$type} eq 'SOA') {
3038
3039 # host contains pri-ns:responsible
3040 # val is abused to contain refresh:retry:expire:minttl
3041##fixme: "manual" serial vs tinydns-autoserial
[202]3042 # let's be explicit about abusing $host and $val
3043 my ($email, $primary) = (split /:/, $host)[0,1];
3044 my ($refresh, $retry, $expire, $min_ttl) = (split /:/, $val)[0,1,2,3];
3045 print $datafile "Z$dom:$primary:$email"."::$refresh:$retry:$expire:$min_ttl:$ttl:$stamp:$loc\n";
[103]3046
3047 } elsif ($typemap{$type} eq 'A') {
3048
[108]3049 print $datafile "+$host:$val:$ttl:$stamp:$loc\n";
[103]3050
3051 } elsif ($typemap{$type} eq 'NS') {
3052
[108]3053 print $datafile "\&$host"."::$val:$ttl:$stamp:$loc\n";
[103]3054
3055 } elsif ($typemap{$type} eq 'AAAA') {
3056
3057 print $datafile ":$host:28:";
3058 my $altgrp = 0;
3059 my @altconv;
[108]3060 # Split in to up to 8 groups of hex digits (allows for IPv6 :: 0-collapsing)
[103]3061 foreach (split /:/, $val) {
3062 if (/^$/) {
3063 # flag blank entry; this is a series of 0's of (currently) unknown length
3064 $altconv[$altgrp++] = 's';
3065 } else {
3066 # call sub to convert 1-4 hex digits to 2 string-rep octal bytes
3067 $altconv[$altgrp++] = octalize($_)
3068 }
3069 }
3070 foreach my $octet (@altconv) {
3071 # if not 's', output
3072 print $datafile $octet unless $octet =~ /^s$/;
3073 # if 's', output (9-array length)x literal '\000\000'
3074 print $datafile '\000\000'x(9-$altgrp) if $octet =~ /^s$/;
3075 }
[108]3076 print $datafile ":$ttl:$stamp:$loc\n";
[103]3077
3078 } elsif ($typemap{$type} eq 'MX') {
3079
[108]3080 print $datafile "\@$host"."::$val:$dist:$ttl:$stamp:$loc\n";
[103]3081
3082 } elsif ($typemap{$type} eq 'TXT') {
3083
3084##fixme: split v-e-r-y long TXT strings? will need to do so for BIND export, at least
3085 $val =~ s/:/\\072/g; # may need to replace other symbols
[108]3086 print $datafile "'$host:$val:$ttl:$stamp:$loc\n";
[103]3087
3088# by-hand TXT
3089#:deepnet.cx:16:2v\075spf1\040a\040a\072bacon.deepnet.cx\040a\072home.deepnet.cx\040-all:3600
3090#@ IN TXT "v=spf1 a a:bacon.deepnet.cx a:home.deepnet.cx -all"
3091#'deepnet.cx:v=spf1 a a\072bacon.deepnet.cx a\072home.deepnet.cx -all:3600
3092
3093#txttest IN TXT "v=foo bar:bob kn;ob' \" !@#$%^&*()-=_+[]{}<>?"
3094#: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
3095
3096# very long TXT record as brought in by axfr-get
3097# note tinydns does not support >512-byte RR data, need axfr-dns (for TCP support) for that
3098# also note, tinydns does not seem to support <512, >256-byte RRdata from axfr-get either. :/
3099#:longtxt.deepnet.cx:16:
3100#\170this is a very long txt record. it is really long. long. very long. really very long. this is a very long txt record.
3101#\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.
3102#\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.
3103#:3600
3104
3105 } elsif ($typemap{$type} eq 'CNAME') {
3106
[108]3107 print $datafile "C$host:$val:$ttl:$stamp:$loc\n";
[103]3108
3109 } elsif ($typemap{$type} eq 'SRV') {
3110
3111 # data is two-byte values for priority, weight, port, in that order,
3112 # followed by length/string data
3113
3114 print $datafile ":$host:33:".octalize($dist,'d').octalize($weight,'d').octalize($port,'d');
3115
3116 $val .= '.' if $val !~ /\.$/;
3117 foreach (split /\./, $val) {
3118 printf $datafile "\\%0.3o%s", length($_), $_;
3119 }
[108]3120 print $datafile "\\000:$ttl:$stamp:$loc\n";
[103]3121
3122 } elsif ($typemap{$type} eq 'RP') {
3123
3124 # RP consists of two mostly free-form strings.
3125 # The first is supposed to be an email address with @ replaced by . (as with the SOA contact)
3126 # The second is the "hostname" of a TXT record with more info.
3127 print $datafile ":$host:17:";
3128 my ($who,$what) = split /\s/, $val;
3129 foreach (split /\./, $who) {
3130 printf $datafile "\\%0.3o%s", length($_), $_;
3131 }
3132 print $datafile '\000';
3133 foreach (split /\./, $what) {
3134 printf $datafile "\\%0.3o%s", length($_), $_;
3135 }
[108]3136 print $datafile "\\000:$ttl:$stamp:$loc\n";
[103]3137
3138 } elsif ($typemap{$type} eq 'PTR') {
3139
3140 # must handle both IPv4 and IPv6
3141##work
[108]3142 # data should already be in suitable reverse order.
3143 print $datafile "^$host:$val:$ttl:$stamp:$loc\n";
[103]3144
[108]3145 } else {
3146 # raw record. we don't know what's in here, so we ASS-U-ME the user has
3147 # put it in correctly, since either the user is messing directly with the
3148 # database, or the record was imported via AXFR
3149 # <split by char>
3150 # convert anything not a-zA-Z0-9.- to octal coding
3151
3152##fixme: add flag to export "unknown" record types - note we'll probably end up
3153# mangling them since they were written to the DB from Net::DNS::RR::<type>->rdatastr.
3154 #print $datafile ":$host:$type:$val:$ttl:$stamp:$loc\n";
3155
[103]3156 } # record type if-else
3157
3158 } # while ($recsth)
3159 } # while ($domsth)
3160} # end __export_tiny()
3161
3162
[197]3163## DNSDB::mailNotify()
3164# Sends notification mail to recipients regarding an IPDB operation
3165sub mailNotify {
3166 my $dbh = shift;
3167 my ($subj,$message) = @_;
3168
3169 return if $config{mailhost} eq 'smtp.example.com'; # do nothing if still using default SMTP host.
3170
3171 my $mailer = Net::SMTP->new($config{mailhost}, Hello => "dnsadmin.$config{domain}");
3172
3173 my $mailsender = ($config{mailsender} ? $config{mailsender} : $config{mailnotify});
3174
3175 $mailer->mail($mailsender);
3176 $mailer->to($config{mailnotify});
[198]3177 $mailer->data("From: \"$config{mailname}\" <$mailsender>\n",
3178 "To: <$config{mailnotify}>\n",
[197]3179 "Date: ".strftime("%a, %d %b %Y %H:%M:%S %z",localtime)."\n",
3180 "Subject: $subj\n",
3181 "X-Mailer: DNSAdmin Notify v".sprintf("%.1d",$DNSDB::VERSION)."\n",
3182 "Organization: $config{orgname}\n",
3183 "\n$message\n");
3184 $mailer->quit;
3185}
3186
[2]3187# shut Perl up
31881;
Note: See TracBrowser for help on using the repository browser.