source: trunk/DNSDB.pm@ 277

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

/trunk

Checkpoint: Clean up SOA editing and extend for reverse zones.
Mostly complete; still need to finish shuffling arguments to
get logging moved into DNSDB.pm
See #26

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