source: trunk/DNSDB.pm@ 278

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

/trunk

Checkpoint, diversion to get userdata somewhere handy(er) for logging
Copy-paste base login processing from dns.cg to login() in DNSDB.pm.
See #35.

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