source: trunk/DNSDB.pm@ 274

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

/trunk

Flesh out most reverse zone deletion. See #26.

  • Convert delDomain() to delZone()
  • Add checks to coerce the shared-zone record types down to standard types on removal of the second parent, either way around. (IE, A+PTR will be converted to PTR if the parent domain is removed, or A if the parent revzone is removed)

Make sure to show result or error messages on the reverse zone
list page

  • Property svn:keywords set to Date Rev Author Id
File size: 106.7 KB
Line 
1# dns/trunk/DNSDB.pm
2# Abstraction functions for DNS administration
3##
4# $Id: DNSDB.pm 274 2012-03-14 22:01:42Z 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 &addRDNS
42 &getZoneCount &getZoneList
43 &addGroup &delGroup &getChildren &groupName
44 &addUser &updateUser &delUser &userFullName &userStatus &getUserData
45 &getSOA &getRecLine &getDomRecs &getRecCount
46 &addRec &updateRec &delRec
47 &getTypelist
48 &parentID
49 &isParent
50 &domStatus &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 &addRDNS
64 &getZoneCount &getZoneList
65 &addGroup &delGroup &getChildren &groupName
66 &addUser &updateUser &delUser &userFullName &userStatus &getUserData
67 &getSOA &getRecLine &getDomRecs &getRecCount
68 &addRec &updateRec &delRec
69 &getTypelist
70 &parentID
71 &isParent
72 &domStatus &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::addRDNS
1371# Adds a reverse DNS zone
1372# Takes a database handle, CIDR block, numeric group, boolean(ish) state (active/inactive),
1373# and user info hash (for logging).
1374# Returns a status code and message
1375sub addRDNS {
1376 my $dbh = shift;
1377 my $zone = NetAddr::IP->new(shift);
1378 return ('FAIL',"Zone name must be a valid CIDR netblock") unless ($zone && $zone->addr !~ /^0/);
1379 my $revpatt = shift; # construct a custom (A/AAAA+)? PTR template record
1380 my $group = shift;
1381 my $state = shift;
1382
1383 my %userinfo = @_; # remaining bits.
1384# user ID, username, user full name
1385
1386 $state = 1 if $state =~ /^active$/;
1387 $state = 1 if $state =~ /^on$/;
1388 $state = 0 if $state =~ /^inactive$/;
1389 $state = 0 if $state =~ /^off$/;
1390
1391 return ('FAIL',"Invalid zone status") if $state !~ /^\d+$/;
1392
1393# quick check to start to see if we've already got one
1394 my ($rdns_id) = $dbh->selectrow_array("SELECT rdns_id FROM revzones WHERE revzone=?", undef, ("$zone"));
1395
1396 return ('FAIL', "Zone already exists") if $rdns_id;
1397
1398 # Allow transactions, and raise an exception on errors so we can catch it later.
1399 # Use local to make sure these get "reset" properly on exiting this block
1400 local $dbh->{AutoCommit} = 0;
1401 local $dbh->{RaiseError} = 1;
1402
1403 my $warnstr = '';
1404 my $defttl = 3600; # 1 hour should be reasonable. And unless things have gone horribly
1405 # wrong, we should have a value to override this anyway.
1406
1407 # Wrap all the SQL in a transaction
1408 eval {
1409 # insert the domain...
1410 $dbh->do("INSERT INTO revzones (revnet,group_id,status) VALUES (?,?,?)", undef, ($zone, $group, $state));
1411
1412 # get the ID...
1413 ($rdns_id) = $dbh->selectrow_array("SELECT currval('revzones_rdns_id_seq')");
1414
1415 _log($dbh, (rdns_id => $rdns_id, user_id => $userinfo{id}, group_id => $group, username => $userinfo{name},
1416 entry => "Added ".($state ? 'active' : 'inactive')." reverse zone $zone"));
1417
1418 # ... and now we construct the standard records from the default set. NB: group should be variable.
1419 my $sth = $dbh->prepare("SELECT host,type,val,ttl FROM default_rev_records WHERE group_id=?");
1420 my $sth_in = $dbh->prepare("INSERT INTO records (rdns_id,domain_id,host,type,val,ttl)".
1421 " VALUES ($rdns_id,?,?,?,?,?)");
1422 $sth->execute($group);
1423 while (my ($host,$type,$val,$ttl) = $sth->fetchrow_array()) {
1424 # Silently skip v4/v6 mismatches. This is not an error, this is expected.
1425 if ($zone->{isv6}) {
1426 next if ($type == 65280 || $type == 65283);
1427 } else {
1428 next if ($type == 65281 || $type == 65284);
1429 }
1430
1431 $host =~ s/ADMINDOMAIN/$config{domain}/g;
1432
1433 # Check to make sure the IP stubs will fit in the zone. Under most usage failures here should be rare.
1434 # On failure, tack a note on to a warning string and continue without adding this record.
1435 # While we're at it, we substitute $zone for ZONE in the value.
1436 if ($val eq 'ZONE') {
1437 next if $revpatt; # If we've got a pattern, we skip the default record version.
1438##fixme? do we care if we have multiple whole-zone templates?
1439 $val = $zone->network;
1440 } elsif ($val =~ /ZONE/) {
1441 my $tmpval = $val;
1442 $tmpval =~ s/ZONE//;
1443 # Bend the rules and allow single-trailing-number PTR or PTR template records to be inserted
1444 # as either v4 or v6. May make this an off-by-default config flag
1445 # Note that the origin records that may trigger this **SHOULD** already have ZONE,\d
1446 if ($type == 12 || $type == 65282) {
1447 $tmpval =~ s/[,.]/::/ if ($tmpval =~ /^[,.]\d+$/ && $zone->{isv6});
1448 $tmpval =~ s/[,:]+/./ if ($tmpval =~ /^(?:,|::)\d+$/ && !$zone->{isv6});
1449 }
1450 my $addr;
1451 if (_ipparent($dbh, 'n', 'y', \$tmpval, $rdns_id, \$addr)) {
1452 $val = $addr->addr;
1453 } else {
1454 $warnstr .= "\nDefault record '$val $typemap{$type} $host' doesn't fit in $zone, skipping";
1455 next;
1456 }
1457 }
1458
1459 # Substitute $zone for ZONE in the hostname.
1460 $host = _ZONE($zone, $host);
1461
1462 # Fill in the forward domain ID if we can find it, otherwise:
1463 # Coerce type down to PTR or PTR template if we can't
1464 my $domid = 0;
1465 if ($type >= 65280) {
1466 if (!($domid = _hostparent($dbh, $host))) {
1467 $warnstr .= "\nRecord added as PTR instead of $typemap{$type}; domain not found for $host";
1468 $type = $reverse_typemap{PTR};
1469 $domid = 0; # just to be explicit.
1470 }
1471 }
1472
1473 $sth_in->execute($domid,$host,$type,$val,$ttl);
1474
1475 if ($typemap{$type} eq 'SOA') {
1476 my @tmp1 = split /:/, $host;
1477 my @tmp2 = split /:/, $val;
1478 _log($dbh, (rdns_id => $rdns_id, user_id => $userinfo{id}, group_id => $group,
1479 username => $userinfo{name}, entry =>
1480 "[new $zone] Added SOA record [contact $tmp1[0]] [master $tmp1[1]] ".
1481 "[refresh $tmp2[0]] [retry $tmp2[1]] [expire $tmp2[2]] [minttl $tmp2[3]], TTL $ttl"));
1482 $defttl = $tmp2[3];
1483 } else {
1484 my $logentry = "[new $zone] Added record '$host $typemap{$type}";
1485 _log($dbh, (rdns_id => $rdns_id, domain_id => $domid, user_id => $userinfo{id}, group_id => $group,
1486 username => $userinfo{name}, entry =>
1487 $logentry." $val', TTL $ttl"));
1488 }
1489 }
1490
1491 # Generate record based on provided pattern.
1492 if ($revpatt) {
1493 my $host;
1494 my $type = ($zone->{isv6} ? 65284 : 65283);
1495 my $val = $zone->network;
1496
1497 # Substitute $zone for ZONE in the hostname.
1498 $host = _ZONE($zone, $revpatt);
1499
1500 my $domid = 0;
1501 if (!($domid = _hostparent($dbh, $host))) {
1502 $warnstr .= "\nDefault pattern added as PTR template instead of $typemap{$type}; domain not found for $host";
1503 $type = 65282;
1504 $domid = 0; # just to be explicit.
1505 }
1506
1507 $sth_in->execute($domid,$host,$type,$val,$defttl);
1508 }
1509
1510 # If there are warnings (presumably about default records skipped for cause) log them
1511 _log($dbh, (rdns_id => $rdns_id, user_id => $userinfo{id}, group_id => $group,
1512 username => $userinfo{name}, entry => "Warning(s) adding $zone:$warnstr"))
1513 if $warnstr;
1514
1515 # once we get here, we should have suceeded.
1516 $dbh->commit;
1517 }; # end eval
1518
1519 if ($@) {
1520 my $msg = $@;
1521 eval { $dbh->rollback; };
1522 return ('FAIL',$msg);
1523 } else {
1524 return ('OK',$rdns_id);
1525 }
1526
1527} # end addRDNS()
1528
1529
1530## DNSDB::getZoneCount
1531# Get count of zones in group or groups
1532# Takes a database handle and hash containing:
1533# - the "current" group
1534# - an array of "acceptable" groups
1535# - a flag for forward/reverse zones
1536# - Optionally accept a "starts with" and/or "contains" filter argument
1537# Returns an integer count of the resulting zone list.
1538sub getZoneCount {
1539 my $dbh = shift;
1540
1541 my %args = @_;
1542
1543 my @filterargs;
1544 $args{startwith} = undef if $args{startwith} && $args{startwith} !~ /^(?:[a-z]|0-9)$/;
1545 push @filterargs, "^$args{startwith}" if $args{startwith};
1546 $args{filter} =~ s/\./\[\.\]/g if $args{filter}; # only match literal dots, usually in reverse zones
1547 push @filterargs, $args{filter} if $args{filter};
1548
1549 my $sql;
1550 # Not as compact, and fix-me-twice if the common bits get wrong, but much easier to read
1551 if ($args{revrec} eq 'n') {
1552 $sql = "SELECT count(*) FROM domains".
1553 " WHERE group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
1554 ($args{startwith} ? " AND domain ~* ?" : '').
1555 ($args{filter} ? " AND domain ~* ?" : '');
1556 } else {
1557 $sql = "SELECT count(*) FROM revzones".
1558 " WHERE group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
1559 ($args{startwith} ? " AND CAST(revnet AS VARCHAR) ~* ?" : '').
1560 ($args{filter} ? " AND CAST(revnet AS VARCHAR) ~* ?" : '');
1561 }
1562 my ($count) = $dbh->selectrow_array($sql, undef, @filterargs);
1563 return $count;
1564} # end getZoneCount()
1565
1566
1567## DNSDB::getZoneList()
1568# Get a list of zones in the specified group(s)
1569# Takes the same arguments as getZoneCount() above
1570# Returns a reference to an array of hashrefs suitable for feeding to HTML::Template
1571sub getZoneList {
1572 my $dbh = shift;
1573
1574 my %args = @_;
1575
1576 my @zonelist;
1577
1578 $args{sortorder} = 'ASC' if !grep $args{sortorder}, ('ASC','DESC');
1579 $args{offset} = 0 if !$args{offset} || $args{offset} !~ /^(?:all|\d+)$/;
1580
1581 my @filterargs;
1582 $args{startwith} = undef if $args{startwith} && $args{startwith} !~ /^(?:[a-z]|0-9)$/;
1583 push @filterargs, "^$args{startwith}" if $args{startwith};
1584 $args{filter} =~ s/\./\[\.\]/g if $args{filter}; # only match literal dots, usually in reverse zones
1585 push @filterargs, $args{filter} if $args{filter};
1586
1587 my $sql;
1588 # Not as compact, and fix-me-twice if the common bits get wrong, but much easier to read
1589 if ($args{revrec} eq 'n') {
1590 $args{sortby} = 'domain' if !grep $args{sortby}, ('revnet','group','status');
1591 $sql = "SELECT domain_id,domain,status,groups.group_name AS group FROM domains".
1592 " INNER JOIN groups ON domains.group_id=groups.group_id".
1593 " WHERE domains.group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
1594 ($args{startwith} ? " AND domain ~* ?" : '').
1595 ($args{filter} ? " AND domain ~* ?" : '');
1596 } else {
1597##fixme: arguably startwith here is irrelevant. depends on the UI though.
1598 $args{sortby} = 'revnet' if !grep $args{sortby}, ('domain','group','status');
1599 $sql = "SELECT rdns_id,revnet,status,groups.group_name AS group FROM revzones".
1600 " INNER JOIN groups ON revzones.group_id=groups.group_id".
1601 " WHERE revzones.group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
1602 ($args{startwith} ? " AND CAST(revnet AS VARCHAR) ~* ?" : '').
1603 ($args{filter} ? " AND CAST(revnet AS VARCHAR) ~* ?" : '');
1604 }
1605 # A common tail.
1606 $sql .= " ORDER BY ".($args{sortby} eq 'group' ? 'groups.group_name' : $args{sortby})." $args{sortorder} ".
1607 ($args{offset} eq 'all' ? '' : " LIMIT $config{perpage}".
1608 " OFFSET ".$args{offset}*$config{perpage});
1609 my $sth = $dbh->prepare($sql);
1610 $sth->execute(@filterargs);
1611 my $rownum = 0;
1612
1613 while (my @data = $sth->fetchrow_array) {
1614 my %row;
1615 $row{domainid} = $data[0];
1616 $row{domain} = $data[1];
1617 $row{status} = $data[2];
1618 $row{group} = $data[3];
1619 push @zonelist, \%row;
1620 }
1621
1622 return \@zonelist;
1623} # end getZoneList()
1624
1625
1626## DNSDB::addGroup()
1627# Add a group
1628# Takes a database handle, group name, parent group, hashref for permissions,
1629# and optional template-vs-cloneme flag
1630# Returns a status code and message
1631sub addGroup {
1632 $errstr = '';
1633 my $dbh = shift;
1634 my $groupname = shift;
1635 my $pargroup = shift;
1636 my $permissions = shift;
1637
1638 # 0 indicates "custom", hardcoded.
1639 # Any other value clones that group's default records, if it exists.
1640 my $inherit = shift || 0;
1641##fixme: need a flag to indicate clone records or <?> ?
1642
1643 # Allow transactions, and raise an exception on errors so we can catch it later.
1644 # Use local to make sure these get "reset" properly on exiting this block
1645 local $dbh->{AutoCommit} = 0;
1646 local $dbh->{RaiseError} = 1;
1647
1648 my $sth = $dbh->prepare("SELECT group_id FROM groups WHERE group_name=?");
1649 my $group_id;
1650
1651# quick check to start to see if we've already got one
1652 $sth->execute($groupname);
1653 ($group_id) = $sth->fetchrow_array;
1654
1655 return ('FAIL', "Group already exists") if $group_id;
1656
1657 # Wrap all the SQL in a transaction
1658 eval {
1659 $sth = $dbh->prepare("INSERT INTO groups (parent_group_id,group_name) VALUES (?,?)");
1660 $sth->execute($pargroup,$groupname);
1661
1662 my ($groupid) = $dbh->selectrow_array("SELECT group_id FROM groups WHERE group_name=?", undef, ($groupname));
1663
1664# Permissions
1665 if ($inherit) {
1666 } else {
1667 my @permvals;
1668 foreach (@permtypes) {
1669 if (!defined ($permissions->{$_})) {
1670 push @permvals, 0;
1671 } else {
1672 push @permvals, $permissions->{$_};
1673 }
1674 }
1675
1676 $sth = $dbh->prepare("INSERT INTO permissions (group_id,$permlist) values (?".',?'x($#permtypes+1).")");
1677 $sth->execute($groupid,@permvals);
1678
1679 $sth = $dbh->prepare("SELECT permission_id FROM permissions WHERE group_id=?");
1680 $sth->execute($groupid);
1681 my ($permid) = $sth->fetchrow_array();
1682
1683 $dbh->do("UPDATE groups SET permission_id=$permid WHERE group_id=$groupid");
1684 } # done permission fiddling
1685
1686# Default records
1687 my $sthf = $dbh->prepare("INSERT INTO default_records (group_id,host,type,val,distance,weight,port,ttl) ".
1688 "VALUES ($groupid,?,?,?,?,?,?,?)");
1689 my $sthr = $dbh->prepare("INSERT INTO default_rev_records (group_id,host,type,val,ttl) ".
1690 "VALUES ($groupid,?,?,?,?)");
1691 if ($inherit) {
1692 # Duplicate records from parent. Actually relying on inherited records feels
1693 # very fragile, and it would be problematic to roll over at a later time.
1694 my $sth2 = $dbh->prepare("SELECT host,type,val,distance,weight,port,ttl FROM default_records WHERE group_id=?");
1695 $sth2->execute($pargroup);
1696 while (my @clonedata = $sth2->fetchrow_array) {
1697 $sthf->execute(@clonedata);
1698 }
1699 # And now the reverse records
1700 $sth2 = $dbh->prepare("SELECT group_id,host,type,val,ttl FROM default_rev_records WHERE group_id=?");
1701 $sth2->execute($pargroup);
1702 while (my @clonedata = $sth2->fetchrow_array) {
1703 $sthr->execute(@clonedata);
1704 }
1705 } else {
1706##fixme: Hardcoding is Bad, mmmmkaaaay?
1707 # reasonable basic defaults for SOA, MX, NS, and minimal hosting
1708 # could load from a config file, but somewhere along the line we need hardcoded bits.
1709 $sthf->execute('ns1.example.com:hostmaster.example.com', 6, '10800:3600:604800:10800', 0, 0, 0, 86400);
1710 $sthf->execute('DOMAIN', 1, '192.168.4.2', 0, 0, 0, 7200);
1711 $sthf->execute('DOMAIN', 15, 'mx.example.com', 10, 0, 0, 7200);
1712 $sthf->execute('DOMAIN', 2, 'ns1.example.com', 0, 0, 0, 7200);
1713 $sthf->execute('DOMAIN', 2, 'ns2.example.com', 0, 0, 0, 7200);
1714 $sthf->execute('www.DOMAIN', 5, 'DOMAIN', 0, 0, 0, 7200);
1715 # reasonable basic defaults for generic reverse zone. Same as initial SQL tabledef.
1716 $sthr->execute('hostmaster.ADMINDOMAIN:ns1.ADMINDOMAIN', 6, '10800:3600:604800:10800', 86400);
1717 $sthr->execute('unused-%r.ADMINDOMAIN', 65283, 'ZONE', 3600);
1718 }
1719
1720 # once we get here, we should have suceeded.
1721 $dbh->commit;
1722 }; # end eval
1723
1724 if ($@) {
1725 my $msg = $@;
1726 eval { $dbh->rollback; };
1727 return ('FAIL',$msg);
1728 } else {
1729 return ('OK','OK');
1730 }
1731
1732} # end addGroup()
1733
1734
1735## DNSDB::delGroup()
1736# Delete a group.
1737# Takes a group ID
1738# Returns a status code and message
1739sub delGroup {
1740 my $dbh = shift;
1741 my $groupid = shift;
1742
1743 # Allow transactions, and raise an exception on errors so we can catch it later.
1744 # Use local to make sure these get "reset" properly on exiting this block
1745 local $dbh->{AutoCommit} = 0;
1746 local $dbh->{RaiseError} = 1;
1747
1748##fixme: locate "knowable" error conditions and deal with them before the eval
1749# ... or inside, whatever.
1750# -> domains still exist in group
1751# -> ...
1752 my $failmsg = '';
1753
1754 # Wrap all the SQL in a transaction
1755 eval {
1756 my $sth = $dbh->prepare("SELECT count(*) FROM domains WHERE group_id=?");
1757 $sth->execute($groupid);
1758 my ($domcnt) = $sth->fetchrow_array;
1759 $failmsg = "Can't remove group ".groupName($dbh,$groupid);
1760 die "$domcnt domains still in group\n" if $domcnt;
1761
1762 $sth = $dbh->prepare("delete from default_records where group_id=?");
1763 $failmsg = "Failed to delete default records for ".groupName($dbh,$groupid);
1764 $sth->execute($groupid);
1765 $sth = $dbh->prepare("delete from groups where group_id=?");
1766 $failmsg = "Failed to remove group ".groupName($dbh,$groupid);
1767 $sth->execute($groupid);
1768
1769 # once we get here, we should have suceeded.
1770 $dbh->commit;
1771 }; # end eval
1772
1773 if ($@) {
1774 my $msg = $@;
1775 eval { $dbh->rollback; };
1776 return ('FAIL',"$failmsg: $msg");
1777 } else {
1778 return ('OK','OK');
1779 }
1780} # end delGroup()
1781
1782
1783## DNSDB::getChildren()
1784# Get a list of all groups whose parent^n is group <n>
1785# Takes a database handle, group ID, reference to an array to put the group IDs in,
1786# and an optional flag to return only immediate children or all children-of-children
1787# default to returning all children
1788# Calls itself
1789sub getChildren {
1790 $errstr = '';
1791 my $dbh = shift;
1792 my $rootgroup = shift;
1793 my $groupdest = shift;
1794 my $immed = shift || 'all';
1795
1796 # special break for default group; otherwise we get stuck.
1797 if ($rootgroup == 1) {
1798 # by definition, group 1 is the Root Of All Groups
1799 my $sth = $dbh->prepare("SELECT group_id FROM groups WHERE NOT (group_id=1)".
1800 ($immed ne 'all' ? " AND parent_group_id=1" : ''));
1801 $sth->execute;
1802 while (my @this = $sth->fetchrow_array) {
1803 push @$groupdest, @this;
1804 }
1805 } else {
1806 my $sth = $dbh->prepare("SELECT group_id FROM groups WHERE parent_group_id=?");
1807 $sth->execute($rootgroup);
1808 return if $sth->rows == 0;
1809 my @grouplist;
1810 while (my ($group) = $sth->fetchrow_array) {
1811 push @$groupdest, $group;
1812 getChildren($dbh,$group,$groupdest) if $immed eq 'all';
1813 }
1814 }
1815} # end getChildren()
1816
1817
1818## DNSDB::groupName()
1819# Return the group name based on a group ID
1820# Takes a database handle and the group ID
1821# Returns the group name or undef on failure
1822sub groupName {
1823 $errstr = '';
1824 my $dbh = shift;
1825 my $groupid = shift;
1826 my $sth = $dbh->prepare("SELECT group_name FROM groups WHERE group_id=?");
1827 $sth->execute($groupid);
1828 my ($groupname) = $sth->fetchrow_array();
1829 $errstr = $DBI::errstr if !$groupname;
1830 return $groupname if $groupname;
1831} # end groupName
1832
1833
1834## DNSDB::groupID()
1835# Return the group ID based on the group name
1836# Takes a database handle and the group name
1837# Returns the group ID or undef on failure
1838sub groupID {
1839 $errstr = '';
1840 my $dbh = shift;
1841 my $group = shift;
1842 my ($grpid) = $dbh->selectrow_array("SELECT group_id FROM groups WHERE group=?", undef, ($group) );
1843 $errstr = $DBI::errstr if !$grpid;
1844 return $grpid if $grpid;
1845} # end groupID()
1846
1847
1848## DNSDB::addUser()
1849# Add a user.
1850# Takes a DB handle, username, group ID, password, state (active/inactive).
1851# Optionally accepts:
1852# user type (user/admin) - defaults to user
1853# permissions string - defaults to inherit from group
1854# three valid forms:
1855# i - Inherit permissions
1856# c:<user_id> - Clone permissions from <user_id>
1857# C:<permission list> - Set these specific permissions
1858# first name - defaults to username
1859# last name - defaults to blank
1860# phone - defaults to blank (could put other data within column def)
1861# Returns (OK,<uid>) on success, (FAIL,<message>) on failure
1862sub addUser {
1863 $errstr = '';
1864 my $dbh = shift;
1865 my $username = shift;
1866 my $group = shift;
1867 my $pass = shift;
1868 my $state = shift;
1869
1870 return ('FAIL', "Missing one or more required entries") if !defined($state);
1871 return ('FAIL', "Username must not be blank") if !$username;
1872
1873 my $type = shift || 'u'; # create limited users by default - fwiw, not sure yet how this will interact with ACLs
1874
1875 my $permstring = shift || 'i'; # default is to inhert permissions from group
1876
1877 my $fname = shift || $username;
1878 my $lname = shift || '';
1879 my $phone = shift || ''; # not going format-check
1880
1881 my $sth = $dbh->prepare("SELECT user_id FROM users WHERE username=?");
1882 my $user_id;
1883
1884# quick check to start to see if we've already got one
1885 $sth->execute($username);
1886 ($user_id) = $sth->fetchrow_array;
1887
1888 return ('FAIL', "User already exists") if $user_id;
1889
1890 # Allow transactions, and raise an exception on errors so we can catch it later.
1891 # Use local to make sure these get "reset" properly on exiting this block
1892 local $dbh->{AutoCommit} = 0;
1893 local $dbh->{RaiseError} = 1;
1894
1895 my $failmsg = '';
1896
1897 # Wrap all the SQL in a transaction
1898 eval {
1899 # insert the user... note we set inherited perms by default since
1900 # it's simple and cleans up some other bits of state
1901 my $sth = $dbh->prepare("INSERT INTO users ".
1902 "(group_id,username,password,firstname,lastname,phone,type,status,permission_id,inherit_perm) ".
1903 "VALUES (?,?,?,?,?,?,?,?,(SELECT permission_id FROM permissions WHERE group_id=?),'t')");
1904 $sth->execute($group,$username,unix_md5_crypt($pass),$fname,$lname,$phone,$type,$state,$group);
1905
1906 # get the ID...
1907 ($user_id) = $dbh->selectrow_array("SELECT currval('users_user_id_seq')");
1908
1909# Permissions! Gotta set'em all!
1910 die "Invalid permission string $permstring"
1911 if $permstring !~ /^(?:
1912 i # inherit
1913 |c:\d+ # clone
1914 # custom. no, the leading , is not a typo
1915 |C:(?:,(?:group|user|domain|record|self)_(?:edit|create|delete))*
1916 )$/x;
1917# bleh. I'd call another function to do my dirty work, but we're in the middle of a transaction already.
1918 if ($permstring ne 'i') {
1919 # for cloned or custom permissions, we have to create a new permissions entry.
1920 my $clonesrc = $group;
1921 if ($permstring =~ /^c:(\d+)/) { $clonesrc = $1; }
1922 $dbh->do("INSERT INTO permissions ($permlist,user_id) ".
1923 "SELECT $permlist,? FROM permissions WHERE permission_id=".
1924 "(SELECT permission_id FROM permissions WHERE ".($permstring =~ /^c:/ ? 'user' : 'group')."_id=?)",
1925 undef, ($user_id,$clonesrc) );
1926 $dbh->do("UPDATE users SET permission_id=".
1927 "(SELECT permission_id FROM permissions WHERE user_id=?) ".
1928 "WHERE user_id=?", undef, ($user_id, $user_id) );
1929 }
1930 if ($permstring =~ /^C:/) {
1931 # finally for custom permissions, we set the passed-in permissions (and unset
1932 # any that might have been brought in by the clone operation above)
1933 my ($permid) = $dbh->selectrow_array("SELECT permission_id FROM permissions WHERE user_id=?",
1934 undef, ($user_id) );
1935 foreach (@permtypes) {
1936 if ($permstring =~ /,$_/) {
1937 $dbh->do("UPDATE permissions SET $_='t' WHERE permission_id=?", undef, ($permid) );
1938 } else {
1939 $dbh->do("UPDATE permissions SET $_='f' WHERE permission_id=?", undef, ($permid) );
1940 }
1941 }
1942 }
1943
1944 $dbh->do("UPDATE users SET inherit_perm='n' WHERE user_id=?", undef, ($user_id) );
1945
1946##fixme: add another table to hold name/email for log table?
1947
1948 # once we get here, we should have suceeded.
1949 $dbh->commit;
1950 }; # end eval
1951
1952 if ($@) {
1953 my $msg = $@;
1954 eval { $dbh->rollback; };
1955 return ('FAIL',$msg." $failmsg");
1956 } else {
1957 return ('OK',$user_id);
1958 }
1959} # end addUser
1960
1961
1962## DNSDB::checkUser()
1963# Check user/pass combo on login
1964sub checkUser {
1965 my $dbh = shift;
1966 my $user = shift;
1967 my $inpass = shift;
1968
1969 my $sth = $dbh->prepare("SELECT user_id,group_id,password,firstname,lastname FROM users WHERE username=?");
1970 $sth->execute($user);
1971 my ($uid,$gid,$pass,$fname,$lname) = $sth->fetchrow_array;
1972 my $loginfailed = 1 if !defined($uid);
1973
1974 if ($pass =~ m|^\$1\$([A-Za-z0-9/.]+)\$|) {
1975 $loginfailed = 1 if $pass ne unix_md5_crypt($inpass,$1);
1976 } else {
1977 $loginfailed = 1 if $pass ne $inpass;
1978 }
1979
1980 # nnnngggg
1981 return ($uid, $gid);
1982} # end checkUser
1983
1984
1985## DNSDB:: updateUser()
1986# Update general data about user
1987sub updateUser {
1988 my $dbh = shift;
1989
1990##fixme: tweak calling convention so that we can update any given bit of data
1991 my $uid = shift;
1992 my $username = shift;
1993 my $group = shift;
1994 my $pass = shift;
1995 my $state = shift;
1996 my $type = shift || 'u';
1997 my $fname = shift || $username;
1998 my $lname = shift || '';
1999 my $phone = shift || ''; # not going format-check
2000
2001 my $failmsg = '';
2002
2003 # Allow transactions, and raise an exception on errors so we can catch it later.
2004 # Use local to make sure these get "reset" properly on exiting this block
2005 local $dbh->{AutoCommit} = 0;
2006 local $dbh->{RaiseError} = 1;
2007
2008 my $sth;
2009
2010 # Password can be left blank; if so we assume there's one on file.
2011 # Actual blank passwords are bad, mm'kay?
2012 if (!$pass) {
2013 $sth = $dbh->prepare("SELECT password FROM users WHERE user_id=?");
2014 $sth->execute($uid);
2015 ($pass) = $sth->fetchrow_array;
2016 } else {
2017 $pass = unix_md5_crypt($pass);
2018 }
2019
2020 eval {
2021 my $sth = $dbh->prepare(q(
2022 UPDATE users
2023 SET username=?, password=?, firstname=?, lastname=?, phone=?, type=?, status=?
2024 WHERE user_id=?
2025 )
2026 );
2027 $sth->execute($username, $pass, $fname, $lname, $phone, $type, $state, $uid);
2028 $dbh->commit;
2029 };
2030 if ($@) {
2031 my $msg = $@;
2032 eval { $dbh->rollback; };
2033 return ('FAIL',"$failmsg: $msg");
2034 } else {
2035 return ('OK','OK');
2036 }
2037} # end updateUser()
2038
2039
2040## DNSDB::delUser()
2041#
2042sub delUser {
2043 my $dbh = shift;
2044 return ('FAIL',"Need database handle") if !$dbh;
2045 my $userid = shift;
2046 return ('FAIL',"Missing userid") if !defined($userid);
2047
2048 my $sth = $dbh->prepare("delete from users where user_id=?");
2049 $sth->execute($userid);
2050
2051 return ('FAIL',"Couldn't remove user: ".$sth->errstr) if $sth->err;
2052
2053 return ('OK','OK');
2054
2055} # end delUser
2056
2057
2058## DNSDB::userFullName()
2059# Return a pretty string!
2060# Takes a user_id and optional printf-ish string to indicate which pieces where:
2061# %u for the username
2062# %f for the first name
2063# %l for the last name
2064# All other text in the passed string will be left as-is.
2065##fixme: need a "smart" option too, so that missing/null/blank first/last names don't give funky output
2066sub userFullName {
2067 $errstr = '';
2068 my $dbh = shift;
2069 my $userid = shift;
2070 my $fullformat = shift || '%f %l (%u)';
2071 my $sth = $dbh->prepare("select username,firstname,lastname from users where user_id=?");
2072 $sth->execute($userid);
2073 my ($uname,$fname,$lname) = $sth->fetchrow_array();
2074 $errstr = $DBI::errstr if !$uname;
2075
2076 $fullformat =~ s/\%u/$uname/g;
2077 $fullformat =~ s/\%f/$fname/g;
2078 $fullformat =~ s/\%l/$lname/g;
2079
2080 return $fullformat;
2081} # end userFullName
2082
2083
2084## DNSDB::userStatus()
2085# Sets and/or returns a user's status
2086# Takes a database handle, user ID and optionally a status argument
2087# Returns undef on errors.
2088sub userStatus {
2089 my $dbh = shift;
2090 my $id = shift;
2091 my $newstatus = shift;
2092
2093 return undef if $id !~ /^\d+$/;
2094
2095 my $sth;
2096
2097# ooo, fun! let's see what we were passed for status
2098 if ($newstatus) {
2099 $sth = $dbh->prepare("update users set status=? where user_id=?");
2100 # ass-u-me caller knows what's going on in full
2101 if ($newstatus =~ /^[01]$/) { # only two valid for now.
2102 $sth->execute($newstatus,$id);
2103 } elsif ($newstatus =~ /^usero(?:n|ff)$/) {
2104 $sth->execute(($newstatus eq 'useron' ? 1 : 0),$id);
2105 }
2106 }
2107
2108 $sth = $dbh->prepare("select status from users where user_id=?");
2109 $sth->execute($id);
2110 my ($status) = $sth->fetchrow_array;
2111 return $status;
2112} # end userStatus()
2113
2114
2115## DNSDB::getUserData()
2116# Get misc user data for display
2117sub getUserData {
2118 my $dbh = shift;
2119 my $uid = shift;
2120
2121 my $sth = $dbh->prepare("SELECT group_id,username,firstname,lastname,phone,type,status,inherit_perm ".
2122 "FROM users WHERE user_id=?");
2123 $sth->execute($uid);
2124 return $sth->fetchrow_hashref();
2125
2126} # end getUserData()
2127
2128
2129## DNSDB::getSOA()
2130# Return all suitable fields from an SOA record in separate elements of a hash
2131# Takes a database handle, default/live flag, domain/reverse flag, and parent ID
2132sub getSOA {
2133 $errstr = '';
2134 my $dbh = shift;
2135 my $def = shift;
2136 my $rev = shift;
2137 my $id = shift;
2138 my %ret;
2139
2140 # (ab)use distance and weight columns to store SOA data? can't for default_rev_records...
2141 # - should really attach serial to the zone parent somewhere
2142
2143 my $sql = "SELECT record_id,host,val,ttl from "._rectable($def,$rev).
2144 " WHERE "._recparent($def,$rev)." = ? AND type=$reverse_typemap{SOA}";
2145
2146 my $sth = $dbh->prepare($sql);
2147 $sth->execute($id);
2148##fixme: stick a flag somewhere if the record doesn't exist. by the API, this is an impossible case, but...
2149
2150 my ($recid,$host,$val,$ttl) = $sth->fetchrow_array() or return;
2151 my ($contact,$prins) = split /:/, $host;
2152 my ($refresh,$retry,$expire,$minttl) = split /:/, $val;
2153
2154 $ret{recid} = $recid;
2155 $ret{ttl} = $ttl;
2156# $ret{serial} = $serial; # ca't use distance for serial with default_rev_records
2157 $ret{prins} = $prins;
2158 $ret{contact} = $contact;
2159 $ret{refresh} = $refresh;
2160 $ret{retry} = $retry;
2161 $ret{expire} = $expire;
2162 $ret{minttl} = $minttl;
2163
2164 return %ret;
2165} # end getSOA()
2166
2167
2168## DNSDB::updateSOA()
2169# Update the specified SOA record
2170# Takes a database handle, default/live flag, forward/reverse flag, and SOA data hash
2171sub updateSOA {
2172 my $dbh = shift;
2173 my $defrec = shift;
2174 my $revrec = shift;
2175
2176 my %soa = @_;
2177
2178##fixme: data validation: make sure {recid} is really the SOA for {parent}
2179 my $sql = "UPDATE "._rectable($defrec, $revrec)." SET host=?, val=?, ttl=? WHERE record_id=? AND type=6";
2180 $dbh->do($sql, undef, ("$soa{contact}:$soa{prins}", "$soa{refresh}:$soa{retry}:$soa{expire}:$soa{minttl}",
2181 $soa{ttl}, $soa{recid}));
2182
2183} # end updateSOA()
2184
2185
2186## DNSDB::getRecLine()
2187# Return all data fields for a zone record in separate elements of a hash
2188# Takes a database handle, default/live flag, forward/reverse flag, and record ID
2189sub getRecLine {
2190 $errstr = '';
2191 my $dbh = shift;
2192 my $defrec = shift;
2193 my $revrec = shift;
2194 my $id = shift;
2195
2196 my $sql = "SELECT record_id,host,type,val,ttl".($revrec eq 'n' ? ',distance,weight,port' : '').
2197 (($defrec eq 'y') ? ',group_id FROM ' : ',domain_id,rdns_id FROM ').
2198 _rectable($defrec,$revrec)." WHERE record_id=?";
2199 my $ret = $dbh->selectrow_hashref($sql, undef, ($id) );
2200
2201 if ($dbh->err) {
2202 $errstr = $DBI::errstr;
2203 return undef;
2204 }
2205
2206 if (!$ret) {
2207 $errstr = "No such record";
2208 return undef;
2209 }
2210
2211 # explicitly set a parent id
2212 if ($defrec eq 'y') {
2213 $ret->{parid} = $ret->{group_id};
2214 } else {
2215 $ret->{parid} = (($revrec eq 'n') ? $ret->{domain_id} : $ret->{rdns_id});
2216 # and a secondary if we have a custom type that lives in both a forward and reverse zone
2217 $ret->{secid} = (($revrec eq 'y') ? $ret->{domain_id} : $ret->{rdns_id}) if $ret->{type} > 65279;
2218 }
2219
2220 return $ret;
2221}
2222
2223
2224##fixme: should use above (getRecLine()) to get lines for below?
2225## DNSDB::getDomRecs()
2226# Return records for a domain
2227# Takes a database handle, default/live flag, group/domain ID, start,
2228# number of records, sort field, and sort order
2229# Returns a reference to an array of hashes
2230sub getDomRecs {
2231 $errstr = '';
2232 my $dbh = shift;
2233 my $def = shift;
2234 my $rev = shift;
2235 my $id = shift;
2236 my $nrecs = shift || 'all';
2237 my $nstart = shift || 0;
2238
2239## for order, need to map input to column names
2240 my $order = shift || 'host';
2241 my $direction = shift || 'ASC';
2242
2243 my $filter = shift || '';
2244
2245 my $sql = "SELECT r.record_id,r.host,r.type,r.val,r.ttl";
2246 $sql .= ",r.distance,r.weight,r.port" if $rev eq 'n';
2247 $sql .= " FROM "._rectable($def,$rev)." r ";
2248 $sql .= "INNER JOIN rectypes t ON r.type=t.val "; # for sorting by type alphabetically
2249 $sql .= "WHERE "._recparent($def,$rev)." = ?";
2250 $sql .= " AND NOT r.type=$reverse_typemap{SOA}";
2251 $sql .= " AND host ~* ?" if $filter;
2252 # use alphaorder column for "correct" ordering of sort-by-type instead of DNS RR type number
2253 $sql .= " ORDER BY ".($order eq 'type' ? 't.alphaorder' : "r.$order")." $direction";
2254
2255 my @bindvars = ($id);
2256 push @bindvars, $filter if $filter;
2257
2258 # just to be ultraparanoid about SQL injection vectors
2259 if ($nstart ne 'all') {
2260 $sql .= " LIMIT ? OFFSET ?";
2261 push @bindvars, $nrecs;
2262 push @bindvars, ($nstart*$nrecs);
2263 }
2264 my $sth = $dbh->prepare($sql) or warn $dbh->errstr;
2265 $sth->execute(@bindvars) or warn "$sql: ".$sth->errstr;
2266
2267 my @retbase;
2268 while (my $ref = $sth->fetchrow_hashref()) {
2269 push @retbase, $ref;
2270 }
2271
2272 my $ret = \@retbase;
2273 return $ret;
2274} # end getDomRecs()
2275
2276
2277## DNSDB::getRecCount()
2278# Return count of non-SOA records in zone (or default records in a group)
2279# Takes a database handle, default/live flag, reverse/forward flag, group/domain ID,
2280# and optional filtering modifier
2281# Returns the count
2282sub getRecCount {
2283 my $dbh = shift;
2284 my $defrec = shift;
2285 my $revrec = shift;
2286 my $id = shift;
2287 my $filter = shift || '';
2288
2289 # keep the nasties down, since we can't ?-sub this bit. :/
2290 # note this is chars allowed in DNS hostnames
2291 $filter =~ s/[^a-zA-Z0-9_.:-]//g;
2292
2293 my @bindvars = ($id);
2294 push @bindvars, $filter if $filter;
2295 my $sql = "SELECT count(*) FROM ".
2296 _rectable($defrec,$revrec).
2297 " WHERE "._recparent($defrec,$revrec)."=? ".
2298 "AND NOT type=$reverse_typemap{SOA}".
2299 ($filter ? " AND host ~* ?" : '');
2300 my ($count) = $dbh->selectrow_array($sql, undef, (@bindvars) );
2301
2302 return $count;
2303
2304} # end getRecCount()
2305
2306
2307## DNSDB::addRec()
2308# Add a new record to a domain or a group's default records
2309# Takes a database handle, default/live flag, group/domain ID,
2310# host, type, value, and TTL
2311# Some types require additional detail: "distance" for MX and SRV,
2312# and weight/port for SRV
2313# Returns a status code and detail message in case of error
2314##fixme: pass a hash with the record data, not a series of separate values
2315sub addRec {
2316 $errstr = '';
2317 my $dbh = shift;
2318 my $defrec = shift;
2319 my $revrec = shift;
2320 my $id = shift; # parent (group_id for defrecs, rdns_id for reverse records,
2321 # domain_id for domain records)
2322
2323 my $host = shift;
2324 my $rectype = shift; # reference so we can coerce it if "+"-types can't find both zones
2325 my $val = shift;
2326 my $ttl = shift;
2327
2328 # prep for validation
2329 my $addr = NetAddr::IP->new($$val);
2330 $$host =~ s/\.+$//; # FQDNs ending in . are an internal detail, and really shouldn't be exposed in the UI.
2331
2332 my $domid = 0;
2333 my $revid = 0;
2334
2335 my $retcode = 'OK'; # assume everything will go OK
2336 my $retmsg = '';
2337
2338 # do simple validation first
2339 return ('FAIL', "TTL must be numeric") unless $ttl =~ /^\d+$/;
2340
2341 # Quick check on hostname parts. Note the regex is more forgiving than the error message;
2342 # domain names technically are case-insensitive, and we use printf-like % codes for a couple
2343 # of types. Other things may also be added to validate default records of several flavours.
2344 return ('FAIL', "Hostnames may not contain anything other than (0-9 a-z . _)")
2345 if $defrec eq 'n' && $$host !~ /^[0-9a-z_%.-]+$/i;
2346
2347 # Collect these even if we're only doing a simple A record so we can call *any* validation sub
2348 my $dist = shift;
2349 my $port = shift;
2350 my $weight = shift;
2351
2352 my $fields;
2353 my @vallist;
2354
2355 # Call the validation sub for the type requested.
2356 ($retcode,$retmsg) = $validators{$$rectype}($dbh, (defrec => $defrec, revrec => $revrec, id => $id,
2357 host => $host, rectype => $rectype, val => $val, addr => $addr,
2358 dist => \$dist, port => \$port, weight => \$weight,
2359 fields => \$fields, vallist => \@vallist) );
2360
2361 return ($retcode,$retmsg) if $retcode eq 'FAIL';
2362
2363 # Set up database fields and bind parameters
2364 $fields .= "host,type,val,ttl,"._recparent($defrec,$revrec);
2365 push @vallist, ($$host,$$rectype,$$val,$ttl,$id);
2366 my $vallen = '?'.(',?'x$#vallist);
2367
2368 # Allow transactions, and raise an exception on errors so we can catch it later.
2369 # Use local to make sure these get "reset" properly on exiting this block
2370 local $dbh->{AutoCommit} = 0;
2371 local $dbh->{RaiseError} = 1;
2372
2373 eval {
2374 $dbh->do("INSERT INTO "._rectable($defrec, $revrec)." ($fields) VALUES ($vallen)",
2375 undef, @vallist);
2376 $dbh->commit;
2377 };
2378 if ($@) {
2379 my $msg = $@;
2380 eval { $dbh->rollback; };
2381 return ('FAIL',$msg);
2382 }
2383
2384 return ($retcode, $retmsg);
2385
2386} # end addRec()
2387
2388
2389## DNSDB::updateRec()
2390# Update a record
2391# Takes a database handle, default and reverse flags, record ID, immediate parent ID, and new record data.
2392# Returns a status code and message
2393sub updateRec {
2394 $errstr = '';
2395
2396 my $dbh = shift;
2397 my $defrec = shift;
2398 my $revrec = shift;
2399 my $id = shift;
2400 my $parid = shift; # immediate parent entity that we're descending from to update the record
2401
2402 # all records have these
2403 my $host = shift;
2404 my $hostbk = $$host; # Keep a backup copy of the original, so we can WARN if the update mangles the domain
2405 my $rectype = shift;
2406 my $val = shift;
2407 my $ttl = shift;
2408
2409 # prep for validation
2410 my $addr = NetAddr::IP->new($$val);
2411 $$host =~ s/\.+$//; # FQDNs ending in . are an internal detail, and really shouldn't be exposed in the UI.
2412
2413 my $domid = 0;
2414 my $revid = 0;
2415
2416 my $retcode = 'OK'; # assume everything will go OK
2417 my $retmsg = '';
2418
2419 # do simple validation first
2420 return ('FAIL', "TTL must be numeric") unless $ttl =~ /^\d+$/;
2421
2422 # Quick check on hostname parts. Note the regex is more forgiving than the error message;
2423 # domain names technically are case-insensitive, and we use printf-like % codes for a couple
2424 # of types. Other things may also be added to validate default records of several flavours.
2425 return ('FAIL', "Hostnames may not contain anything other than (0-9 a-z - . _)")
2426 if $defrec eq 'n' && $$host !~ /^[0-9a-z_%.-]+$/i;
2427
2428 # only MX and SRV will use these
2429 my $dist = 0;
2430 my $weight = 0;
2431 my $port = 0;
2432
2433 my $fields;
2434 my @vallist;
2435
2436 # get old record data so we have the right parent ID
2437 # and for logging (eventually)
2438 my $oldrec = getRecLine($dbh, $defrec, $revrec, $id);
2439
2440 # Call the validation sub for the type requested.
2441 # Note the ID to pass here is the *parent*, not the record
2442 ($retcode,$retmsg) = $validators{$$rectype}($dbh, (defrec => $defrec, revrec => $revrec,
2443 id => ($defrec eq 'y' ? $oldrec->{group_id} : ($revrec eq 'n' ? $oldrec->{domain_id} : $oldrec->{rdns_id})),
2444 host => $host, rectype => $rectype, val => $val, addr => $addr,
2445 dist => \$dist, port => \$port, weight => \$weight,
2446 fields => \$fields, vallist => \@vallist,
2447 update => $id) );
2448
2449 return ($retcode,$retmsg) if $retcode eq 'FAIL';
2450
2451 # Set up database fields and bind parameters. Note only the optional fields
2452 # (distance, weight, port, secondary parent ID) are added in the validation call above
2453 $fields .= "host,type,val,ttl,"._recparent($defrec,$revrec);
2454 push @vallist, ($$host,$$rectype,$$val,$ttl,
2455 ($defrec eq 'y' ? $oldrec->{group_id} : ($revrec eq 'n' ? $oldrec->{domain_id} : $oldrec->{rdns_id})) );
2456
2457 # hack hack PTHUI
2458 # need to forcibly make sure we disassociate a record with a parent it's no longer related to.
2459 # eg, PTR records may not have a domain parent, or A/AAAA records may not have a revzone parent.
2460 # mainly needed for crossover types that got coerced down to "standard" types
2461 if ($defrec eq 'n') {
2462 if ($$rectype == $reverse_typemap{PTR}) {
2463 $fields .= ",domain_id";
2464 push @vallist, 0;
2465 }
2466 if ($$rectype == $reverse_typemap{A} || $$rectype == $reverse_typemap{AAAA}) {
2467 $fields .= ",rdns_id";
2468 push @vallist, 0;
2469 }
2470 }
2471
2472 # Fiddle the field list into something suitable for updates
2473 $fields =~ s/,/=?,/g;
2474 $fields .= "=?";
2475
2476 local $dbh->{AutoCommit} = 0;
2477 local $dbh->{RaiseError} = 1;
2478
2479 eval {
2480 $dbh->do("UPDATE "._rectable($defrec,$revrec)." SET $fields WHERE record_id=?", undef, (@vallist, $id) );
2481 $dbh->commit;
2482 };
2483 if ($@) {
2484 my $msg = $@;
2485 $dbh->rollback;
2486 return ('FAIL', $msg);
2487 }
2488
2489 return ($retcode, $retmsg);
2490} # end updateRec()
2491
2492
2493## DNSDB::delRec()
2494# Delete a record.
2495sub delRec {
2496 $errstr = '';
2497 my $dbh = shift;
2498 my $defrec = shift;
2499 my $revrec = shift;
2500 my $id = shift;
2501
2502 my $sth = $dbh->prepare("DELETE FROM "._rectable($defrec,$revrec)." WHERE record_id=?");
2503 $sth->execute($id);
2504
2505 return ('FAIL',"Couldn't remove record: ".$sth->errstr) if $sth->err;
2506
2507 return ('OK','OK');
2508} # end delRec()
2509
2510
2511 # Reference hashes.
2512my %par_tbl = (
2513 group => 'groups',
2514 user => 'users',
2515 defrec => 'default_records',
2516 defrevrec => 'default_rev_records',
2517 domain => 'domains',
2518 revzone => 'revzones',
2519 record => 'records'
2520 );
2521my %id_col = (
2522 group => 'group_id',
2523 user => 'user_id',
2524 defrec => 'record_id',
2525 defrevrec => 'record_id',
2526 domain => 'domain_id',
2527 revzone => 'rdns_id',
2528 record => 'record_id'
2529 );
2530my %par_col = (
2531 group => 'parent_group_id',
2532 user => 'group_id',
2533 defrec => 'group_id',
2534 defrevrec => 'group_id',
2535 domain => 'group_id',
2536 revzone => 'group_id',
2537 record => 'domain_id'
2538 );
2539my %par_type = (
2540 group => 'group',
2541 user => 'group',
2542 defrec => 'group',
2543 defrevrec => 'group',
2544 domain => 'group',
2545 revzone => 'group',
2546 record => 'domain'
2547 );
2548
2549
2550## DNSDB::getTypelist()
2551# Get a list of record types for various UI dropdowns
2552# Takes database handle, forward/reverse/lookup flag, and optional "tag as selected" indicator (defaults to A)
2553# Returns an arrayref to list of hashrefs perfect for HTML::Template
2554sub getTypelist {
2555 my $dbh = shift;
2556 my $recgroup = shift;
2557 my $type = shift || $reverse_typemap{A};
2558
2559 # also accepting $webvar{revrec}!
2560 $recgroup = 'f' if $recgroup eq 'n';
2561 $recgroup = 'r' if $recgroup eq 'y';
2562
2563 my $sql = "SELECT val,name FROM rectypes WHERE ";
2564 if ($recgroup eq 'r') {
2565 # reverse zone types
2566 $sql .= "stdflag=2 OR stdflag=3";
2567 } elsif ($recgroup eq 'l') {
2568 # DNS lookup types. Note we avoid our custom types >= 65280, since those are entirely internal.
2569 $sql .= "(stdflag=1 OR stdflag=2 OR stdflag=3) AND val < 65280";
2570 } else {
2571 # default; forward zone types. technically $type eq 'f' but not worth the error message.
2572 $sql .= "stdflag=1 OR stdflag=2";
2573 }
2574 $sql .= " ORDER BY listorder";
2575
2576 my $sth = $dbh->prepare($sql);
2577 $sth->execute;
2578 my @typelist;
2579 while (my ($rval,$rname) = $sth->fetchrow_array()) {
2580 my %row = ( recval => $rval, recname => $rname );
2581 $row{tselect} = 1 if $rval == $type;
2582 push @typelist, \%row;
2583 }
2584
2585 # Add SOA on lookups since it's not listed in other dropdowns.
2586 if ($recgroup eq 'l') {
2587 my %row = ( recval => $reverse_typemap{SOA}, recname => 'SOA' );
2588 $row{tselect} = 1 if $reverse_typemap{SOA} == $type;
2589 push @typelist, \%row;
2590 }
2591
2592 return \@typelist;
2593} # end getTypelist()
2594
2595
2596## DNSDB::parentID()
2597# Get ID of entity that is nearest parent to requested id
2598# Takes a database handle and a hash of entity ID, entity type, optional parent type flag
2599# (domain/reverse zone or group), and optional default/live and forward/reverse flags
2600# Returns the ID or undef on failure
2601sub parentID {
2602 my $dbh = shift;
2603
2604 my %args = @_;
2605
2606 # clean up the parent-type. Set it to group if not set; coerce revzone to domain for simpler logic
2607 $args{partype} = 'group' if !$args{partype};
2608 $args{partype} = 'domain' if $args{partype} eq 'revzone';
2609
2610 # clean up defrec and revrec. default to live record, forward zone
2611 $args{defrec} = 'n' if !$args{defrec};
2612 $args{revrec} = 'n' if !$args{revrec};
2613
2614 if ($par_type{$args{partype}} eq 'domain') {
2615 # only live records can have a domain/zone parent
2616 return unless ($args{type} eq 'record' && $args{defrec} eq 'n');
2617 my $result = $dbh->selectrow_hashref("SELECT ".($args{revrec} eq 'n' ? 'domain_id' : 'rdns_id').
2618 " FROM records WHERE record_id = ?",
2619 undef, ($args{id}) ) or return;
2620 return $result;
2621 } else {
2622 # snag some arguments that will either fall through or be overwritten to save some code duplication
2623 my $tmpid = $args{id};
2624 my $type = $args{type};
2625 if ($type eq 'record' && $args{defrec} eq 'n') {
2626 # Live records go through the records table first.
2627 ($tmpid) = $dbh->selectrow_array("SELECT ".($args{revrec} eq 'n' ? 'domain_id' : 'rdns_id').
2628 " FROM records WHERE record_id = ?",
2629 undef, ($args{id}) ) or return;
2630 $type = ($args{revrec} eq 'n' ? 'domain' : 'revzone');
2631 }
2632 my ($result) = $dbh->selectrow_array("SELECT $par_col{$type} FROM $par_tbl{$type} WHERE $id_col{$type} = ?",
2633 undef, ($tmpid) );
2634 return $result;
2635 }
2636# should be impossible to get here with even remotely sane arguments
2637 return;
2638} # end parentID()
2639
2640
2641## DNSDB::isParent()
2642# Returns true if $id1 is a parent of $id2, false otherwise
2643sub isParent {
2644 my $dbh = shift;
2645 my $id1 = shift;
2646 my $type1 = shift;
2647 my $id2 = shift;
2648 my $type2 = shift;
2649##todo: immediate, secondary, full (default)
2650
2651 # Return false on invalid types
2652 return 0 if !grep /^$type1$/, ('record','defrec','defrevrec','user','domain','revzone','group');
2653 return 0 if !grep /^$type2$/, ('record','defrec','defrevrec','user','domain','revzone','group');
2654
2655 # Return false on impossible relations
2656 return 0 if $type1 eq 'record'; # nothing may be a child of a record
2657 return 0 if $type1 eq 'defrec'; # nothing may be a child of a record
2658 return 0 if $type1 eq 'defrevrec'; # nothing may be a child of a record
2659 return 0 if $type1 eq 'user'; # nothing may be child of a user
2660 return 0 if $type1 eq 'domain' && $type2 ne 'record'; # domain may not be a parent of anything other than a record
2661 return 0 if $type1 eq 'revzone' && $type2 ne 'record';# reverse zone may not be a parent of anything other than a record
2662
2663 # ennnhhhh.... if we're passed an id of 0, it will never be found. usual
2664 # case would be the UI creating a new <thing>, and so we don't have an ID for
2665 # <thing> to look up yet. in that case the UI should check the parent as well.
2666 return 0 if $id1 == 0; # nothing can have a parent id of 0
2667 return 1 if $id2 == 0; # anything could have a child id of 0 (or "unknown")
2668
2669 # group 1 is the ultimate root parent
2670 return 1 if $type1 eq 'group' && $id1 == 1;
2671
2672 # groups are always (a) parent of themselves
2673 return 1 if $type1 eq 'group' && $type2 eq 'group' && $id1 == $id2;
2674
2675 my $id = $id2;
2676 my $type = $type2;
2677 my $foundparent = 0;
2678
2679 # Records are the only entity with two possible parents. We need to split the parent checks on
2680 # domain/rdns.
2681 if ($type eq 'record') {
2682 my ($dom,$rdns) = $dbh->selectrow_array("SELECT domain_id,rdns_id FROM records WHERE record_id=?",
2683 undef, ($id));
2684 # check immediate parent against request
2685 return 1 if $type1 eq 'domain' && $id1 == $dom;
2686 return 1 if $type1 eq 'revzone' && $id1 == $rdns;
2687 # if request is group, check *both* parents. Only check if the parent is nonzero though.
2688 return 1 if $dom && isParent($dbh, $id1, $type1, $dom, 'domain');
2689 return 1 if $rdns && isParent($dbh, $id1, $type1, $rdns, 'revzone');
2690 # exit here since we've executed the loop below by proxy in the above recursive calls.
2691 return 0;
2692 }
2693
2694# almost the same loop as getParents() above
2695 my $limiter = 0;
2696 while (1) {
2697 my $sql = "SELECT $par_col{$type} FROM $par_tbl{$type} WHERE $id_col{$type} = ?";
2698 my $result = $dbh->selectrow_hashref($sql,
2699 undef, ($id) );
2700 if (!$result) {
2701 $limiter++;
2702##fixme: how often will this happen on a live site? fail at max limiter <n>?
2703 warn "no results looking for $sql with id $id (depth $limiter)\n";
2704 last;
2705 }
2706 if ($result && $result->{$par_col{$type}} == $id1) {
2707 $foundparent = 1;
2708 last;
2709 } else {
2710##fixme: do we care about trying to return a "no such record/domain/user/group" error?
2711# should be impossible to create an inconsistent DB just with API calls.
2712 warn $dbh->errstr." $sql, $id" if $dbh->errstr;
2713 }
2714 # group 1 is its own parent. need this here more to break strange loops than for detecting a parent
2715 last if $result->{$par_col{$type}} == 1;
2716 $id = $result->{$par_col{$type}};
2717 $type = $par_type{$type};
2718 }
2719
2720 return $foundparent;
2721} # end isParent()
2722
2723
2724## DNSDB::domStatus()
2725# Sets and/or returns a domain's status
2726# Takes a database handle, domain ID and optionally a status argument
2727# Returns undef on errors.
2728sub domStatus {
2729 my $dbh = shift;
2730 my $id = shift;
2731 my $newstatus = shift;
2732
2733 return undef if $id !~ /^\d+$/;
2734
2735 my $sth;
2736
2737# ooo, fun! let's see what we were passed for status
2738 if ($newstatus) {
2739 $sth = $dbh->prepare("update domains set status=? where domain_id=?");
2740 # ass-u-me caller knows what's going on in full
2741 if ($newstatus =~ /^[01]$/) { # only two valid for now.
2742 $sth->execute($newstatus,$id);
2743 } elsif ($newstatus =~ /^domo(?:n|ff)$/) {
2744 $sth->execute(($newstatus eq 'domon' ? 1 : 0),$id);
2745 }
2746 }
2747
2748 $sth = $dbh->prepare("select status from domains where domain_id=?");
2749 $sth->execute($id);
2750 my ($status) = $sth->fetchrow_array;
2751 return $status;
2752} # end domStatus()
2753
2754
2755## DNSDB::importAXFR
2756# Import a domain via AXFR
2757# Takes AXFR host, domain to transfer, group to put the domain in,
2758# and optionally:
2759# - active/inactive state flag (defaults to active)
2760# - overwrite-SOA flag (defaults to off)
2761# - overwrite-NS flag (defaults to off, doesn't affect subdomain NS records)
2762# Returns a status code (OK, WARN, or FAIL) and message - message should be blank
2763# if status is OK, but WARN includes conditions that are not fatal but should
2764# really be reported.
2765sub importAXFR {
2766 my $dbh = shift;
2767 my $ifrom_in = shift;
2768 my $domain = shift;
2769 my $group = shift;
2770 my $status = shift || 1;
2771 my $rwsoa = shift || 0;
2772 my $rwns = shift || 0;
2773
2774##fixme: add mode to delete&replace, merge+overwrite, merge new?
2775
2776 my $nrecs = 0;
2777 my $soaflag = 0;
2778 my $nsflag = 0;
2779 my $warnmsg = '';
2780 my $ifrom;
2781
2782 # choke on possible bad setting in ifrom
2783 # IPv4 and v6, and valid hostnames!
2784 ($ifrom) = ($ifrom_in =~ /^([0-9a-f\:.]+|[0-9a-z_.-]+)$/i);
2785 return ('FAIL', "Bad AXFR source host $ifrom")
2786 unless ($ifrom) = ($ifrom_in =~ /^([0-9a-f\:.]+|[0-9a-z_.-]+)$/i);
2787
2788 # Allow transactions, and raise an exception on errors so we can catch it later.
2789 # Use local to make sure these get "reset" properly on exiting this block
2790 local $dbh->{AutoCommit} = 0;
2791 local $dbh->{RaiseError} = 1;
2792
2793 my $sth = $dbh->prepare("SELECT domain_id FROM domains WHERE domain=?");
2794 my $dom_id;
2795
2796# quick check to start to see if we've already got one
2797 $sth->execute($domain);
2798 ($dom_id) = $sth->fetchrow_array;
2799
2800 return ('FAIL', "Domain already exists") if $dom_id;
2801
2802 eval {
2803 # can't do this, can't nest transactions. sigh.
2804 #my ($dcode, $dmsg) = addDomain(dbh, domain, group, status);
2805
2806##fixme: serial
2807 my $sth = $dbh->prepare("INSERT INTO domains (domain,group_id,status) VALUES (?,?,?)");
2808 $sth->execute($domain,$group,$status);
2809
2810## bizarre DBI<->Net::DNS interaction bug:
2811## sometimes a zone will cause an immediate commit-and-exit (sort of) of the while()
2812## fixed, apparently I was doing *something* odd, but not certain what it was that
2813## caused a commit instead of barfing
2814
2815 # get domain id so we can do the records
2816 $sth = $dbh->prepare("SELECT domain_id FROM domains WHERE domain=?");
2817 $sth->execute($domain);
2818 ($dom_id) = $sth->fetchrow_array();
2819
2820 my $res = Net::DNS::Resolver->new;
2821 $res->nameservers($ifrom);
2822 $res->axfr_start($domain)
2823 or die "Couldn't begin AXFR\n";
2824
2825 while (my $rr = $res->axfr_next()) {
2826 my $type = $rr->type;
2827
2828 my $sql = "INSERT INTO records (domain_id,host,type,ttl,val";
2829 my $vallen = "?,?,?,?,?";
2830
2831 $soaflag = 1 if $type eq 'SOA';
2832 $nsflag = 1 if $type eq 'NS';
2833
2834 my @vallist = ($dom_id, $rr->name, $reverse_typemap{$type}, $rr->ttl);
2835
2836# "Primary" types:
2837# A, NS, CNAME, SOA, PTR(warn in forward), MX, TXT, AAAA, SRV, A6(ob), SPF
2838# maybe KEY
2839
2840# nasty big ugly case-like thing here, since we have to do *some* different
2841# processing depending on the record. le sigh.
2842
2843##fixme: what record types other than TXT can/will have >255-byte payloads?
2844
2845 if ($type eq 'A') {
2846 push @vallist, $rr->address;
2847 } elsif ($type eq 'NS') {
2848# hmm. should we warn here if subdomain NS'es are left alone?
2849 next if ($rwns && ($rr->name eq $domain));
2850 push @vallist, $rr->nsdname;
2851 $nsflag = 1;
2852 } elsif ($type eq 'CNAME') {
2853 push @vallist, $rr->cname;
2854 } elsif ($type eq 'SOA') {
2855 next if $rwsoa;
2856 $vallist[1] = $rr->mname.":".$rr->rname;
2857 push @vallist, ($rr->refresh.":".$rr->retry.":".$rr->expire.":".$rr->minimum);
2858 $soaflag = 1;
2859 } elsif ($type eq 'PTR') {
2860 push @vallist, $rr->ptrdname;
2861 # hmm. PTR records should not be in forward zones.
2862 } elsif ($type eq 'MX') {
2863 $sql .= ",distance";
2864 $vallen .= ",?";
2865 push @vallist, $rr->exchange;
2866 push @vallist, $rr->preference;
2867 } elsif ($type eq 'TXT') {
2868##fixme: Net::DNS docs say this should be deprecated for rdatastr() or char_str_list(),
2869## but don't really seem enthusiastic about it.
2870 my $rrdata = $rr->txtdata;
2871 push @vallist, $rrdata;
2872 } elsif ($type eq 'SPF') {
2873##fixme: and the same caveat here, since it is apparently a clone of ::TXT
2874 my $rrdata = $rr->txtdata;
2875 push @vallist, $rrdata;
2876 } elsif ($type eq 'AAAA') {
2877 push @vallist, $rr->address;
2878 } elsif ($type eq 'SRV') {
2879 $sql .= ",distance,weight,port" if $type eq 'SRV';
2880 $vallen .= ",?,?,?" if $type eq 'SRV';
2881 push @vallist, $rr->target;
2882 push @vallist, $rr->priority;
2883 push @vallist, $rr->weight;
2884 push @vallist, $rr->port;
2885 } elsif ($type eq 'KEY') {
2886 # we don't actually know what to do with these...
2887 push @vallist, ($rr->flags.":".$rr->protocol.":".$rr->algorithm.":".$rr->key.":".$rr->keytag.":".$rr->privatekeyname);
2888 } else {
2889 my $rrdata = $rr->rdatastr;
2890 push @vallist, $rrdata;
2891 # Finding a different record type is not fatal.... just problematic.
2892 # We may not be able to export it correctly.
2893 $warnmsg .= "Unusual record ".$rr->name." ($type) found\n";
2894 }
2895
2896# BIND supports:
2897# A CNAME HINFO MB(ex) MD(ob) MF(ob) MG(ex) MINFO(ex) MR(ex) MX NS NULL
2898# PTR SOA TXT WKS AFSDB(ex) ISDN(ex) RP(ex) RT(ex) X25(ex) PX
2899# ... if one can ever find the right magic to format them correctly
2900
2901# Net::DNS supports:
2902# RRSIG SIG NSAP NS NIMLOC NAPTR MX MR MINFO MG MB LOC ISDN IPSECKEY HINFO
2903# EID DNAME CNAME CERT APL AFSDB AAAA A DS NXT NSEC3PARAM NSEC3 NSEC KEY
2904# DNSKEY DLV X25 TXT TSIG TKEY SSHFP SRV SPF SOA RT RP PX PTR NULL APL::AplItem
2905
2906 $sth = $dbh->prepare($sql.") VALUES (".$vallen.")") or die "problem preparing record insert SQL\n";
2907 $sth->execute(@vallist) or die "failed to insert ".$rr->string.": ".$sth->errstr."\n";
2908
2909 $nrecs++;
2910
2911 } # while axfr_next
2912
2913 # Overwrite SOA record
2914 if ($rwsoa) {
2915 $soaflag = 1;
2916 my $sthgetsoa = $dbh->prepare("SELECT host,val,ttl FROM default_records WHERE group_id=? AND type=?");
2917 my $sthputsoa = $dbh->prepare("INSERT INTO records (domain_id,host,type,val,ttl) VALUES (?,?,?,?,?)");
2918 $sthgetsoa->execute($group,$reverse_typemap{SOA});
2919 while (my ($host,$val,$ttl) = $sthgetsoa->fetchrow_array()) {
2920 $host =~ s/DOMAIN/$domain/g;
2921 $val =~ s/DOMAIN/$domain/g;
2922 $sthputsoa->execute($dom_id,$host,$reverse_typemap{SOA},$val,$ttl);
2923 }
2924 }
2925
2926 # Overwrite NS records
2927 if ($rwns) {
2928 $nsflag = 1;
2929 my $sthgetns = $dbh->prepare("SELECT host,val,ttl FROM default_records WHERE group_id=? AND type=?");
2930 my $sthputns = $dbh->prepare("INSERT INTO records (domain_id,host,type,val,ttl) VALUES (?,?,?,?,?)");
2931 $sthgetns->execute($group,$reverse_typemap{NS});
2932 while (my ($host,$val,$ttl) = $sthgetns->fetchrow_array()) {
2933 $host =~ s/DOMAIN/$domain/g;
2934 $val =~ s/DOMAIN/$domain/g;
2935 $sthputns->execute($dom_id,$host,$reverse_typemap{NS},$val,$ttl);
2936 }
2937 }
2938
2939 die "No records found; either $ifrom is not authoritative or doesn't allow transfers\n" if !$nrecs;
2940 die "Bad zone: No SOA record!\n" if !$soaflag;
2941 die "Bad zone: No NS records!\n" if !$nsflag;
2942
2943 $dbh->commit;
2944
2945 };
2946
2947 if ($@) {
2948 my $msg = $@;
2949 eval { $dbh->rollback; };
2950 return ('FAIL',$msg." $warnmsg");
2951 } else {
2952 return ('WARN', $warnmsg) if $warnmsg;
2953 return ('OK',"Imported OK");
2954 }
2955
2956 # it should be impossible to get here.
2957 return ('WARN',"OOOK!");
2958} # end importAXFR()
2959
2960
2961## DNSDB::export()
2962# Export the DNS database, or a part of it
2963# Takes database handle, export type, optional arguments depending on type
2964# Writes zone data to targets as appropriate for type
2965sub export {
2966 my $dbh = shift;
2967 my $target = shift;
2968
2969 if ($target eq 'tiny') {
2970 __export_tiny($dbh,@_);
2971 }
2972# elsif ($target eq 'foo') {
2973# __export_foo($dbh,@_);
2974#}
2975# etc
2976
2977} # end export()
2978
2979
2980## DNSDB::__export_tiny
2981# Internal sub to implement tinyDNS (compatible) export
2982# Takes database handle, filehandle to write export to, optional argument(s)
2983# to determine which data gets exported
2984sub __export_tiny {
2985 my $dbh = shift;
2986 my $datafile = shift;
2987
2988##fixme: slurp up further options to specify particular zone(s) to export
2989
2990 ## Convert a bare number into an octal-coded pair of octets.
2991 # Take optional arg to indicate a decimal or hex input. Defaults to hex.
2992 sub octalize {
2993 my $tmp = shift;
2994 my $srctype = shift || 'h'; # default assumes hex string
2995 $tmp = sprintf "%0.4x", hex($tmp) if $srctype eq 'h'; # 0-pad hex to 4 digits
2996 $tmp = sprintf "%0.4x", $tmp if $srctype eq 'd'; # 0-pad decimal to 4 hex digits
2997 my @o = ($tmp =~ /^(..)(..)$/); # split into octets
2998 return sprintf "\\%0.3o\\%0.3o", hex($o[0]), hex($o[1]);;
2999 }
3000
3001##fixme: fail if $datafile isn't an open, writable file
3002
3003 # easy case - export all evarything
3004 # not-so-easy case - export item(s) specified
3005 # todo: figure out what kind of list we use to export items
3006
3007 my $domsth = $dbh->prepare("SELECT domain_id,domain,status FROM domains WHERE status=1");
3008 my $recsth = $dbh->prepare("SELECT host,type,val,distance,weight,port,ttl ".
3009 "FROM records WHERE domain_id=?");
3010 $domsth->execute();
3011 while (my ($domid,$dom,$domstat) = $domsth->fetchrow_array) {
3012 $recsth->execute($domid);
3013 while (my ($host,$type,$val,$dist,$weight,$port,$ttl) = $recsth->fetchrow_array) {
3014##fixme: need to store location in the db, and retrieve it here.
3015# temporarily hardcoded to empty so we can include it further down.
3016my $loc = '';
3017
3018##fixme: record validity timestamp. tinydns supports fiddling with timestamps.
3019# note $ttl must be set to 0 if we want to use tinydns's auto-expiring timestamps.
3020# timestamps are TAI64
3021# ~~ 2^62 + time()
3022my $stamp = '';
3023
3024# raw packet in unknown format: first byte indicates length
3025# of remaining data, allows up to 255 raw bytes
3026
3027##fixme? append . to all host/val hostnames
3028 if ($typemap{$type} eq 'SOA') {
3029
3030 # host contains pri-ns:responsible
3031 # val is abused to contain refresh:retry:expire:minttl
3032##fixme: "manual" serial vs tinydns-autoserial
3033 # let's be explicit about abusing $host and $val
3034 my ($email, $primary) = (split /:/, $host)[0,1];
3035 my ($refresh, $retry, $expire, $min_ttl) = (split /:/, $val)[0,1,2,3];
3036 print $datafile "Z$dom:$primary:$email"."::$refresh:$retry:$expire:$min_ttl:$ttl:$stamp:$loc\n";
3037
3038 } elsif ($typemap{$type} eq 'A') {
3039
3040 print $datafile "+$host:$val:$ttl:$stamp:$loc\n";
3041
3042 } elsif ($typemap{$type} eq 'NS') {
3043
3044 print $datafile "\&$host"."::$val:$ttl:$stamp:$loc\n";
3045
3046 } elsif ($typemap{$type} eq 'AAAA') {
3047
3048 print $datafile ":$host:28:";
3049 my $altgrp = 0;
3050 my @altconv;
3051 # Split in to up to 8 groups of hex digits (allows for IPv6 :: 0-collapsing)
3052 foreach (split /:/, $val) {
3053 if (/^$/) {
3054 # flag blank entry; this is a series of 0's of (currently) unknown length
3055 $altconv[$altgrp++] = 's';
3056 } else {
3057 # call sub to convert 1-4 hex digits to 2 string-rep octal bytes
3058 $altconv[$altgrp++] = octalize($_)
3059 }
3060 }
3061 foreach my $octet (@altconv) {
3062 # if not 's', output
3063 print $datafile $octet unless $octet =~ /^s$/;
3064 # if 's', output (9-array length)x literal '\000\000'
3065 print $datafile '\000\000'x(9-$altgrp) if $octet =~ /^s$/;
3066 }
3067 print $datafile ":$ttl:$stamp:$loc\n";
3068
3069 } elsif ($typemap{$type} eq 'MX') {
3070
3071 print $datafile "\@$host"."::$val:$dist:$ttl:$stamp:$loc\n";
3072
3073 } elsif ($typemap{$type} eq 'TXT') {
3074
3075##fixme: split v-e-r-y long TXT strings? will need to do so for BIND export, at least
3076 $val =~ s/:/\\072/g; # may need to replace other symbols
3077 print $datafile "'$host:$val:$ttl:$stamp:$loc\n";
3078
3079# by-hand TXT
3080#:deepnet.cx:16:2v\075spf1\040a\040a\072bacon.deepnet.cx\040a\072home.deepnet.cx\040-all:3600
3081#@ IN TXT "v=spf1 a a:bacon.deepnet.cx a:home.deepnet.cx -all"
3082#'deepnet.cx:v=spf1 a a\072bacon.deepnet.cx a\072home.deepnet.cx -all:3600
3083
3084#txttest IN TXT "v=foo bar:bob kn;ob' \" !@#$%^&*()-=_+[]{}<>?"
3085#: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
3086
3087# very long TXT record as brought in by axfr-get
3088# note tinydns does not support >512-byte RR data, need axfr-dns (for TCP support) for that
3089# also note, tinydns does not seem to support <512, >256-byte RRdata from axfr-get either. :/
3090#:longtxt.deepnet.cx:16:
3091#\170this is a very long txt record. it is really long. long. very long. really very long. this is a very long txt record.
3092#\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.
3093#\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.
3094#:3600
3095
3096 } elsif ($typemap{$type} eq 'CNAME') {
3097
3098 print $datafile "C$host:$val:$ttl:$stamp:$loc\n";
3099
3100 } elsif ($typemap{$type} eq 'SRV') {
3101
3102 # data is two-byte values for priority, weight, port, in that order,
3103 # followed by length/string data
3104
3105 print $datafile ":$host:33:".octalize($dist,'d').octalize($weight,'d').octalize($port,'d');
3106
3107 $val .= '.' if $val !~ /\.$/;
3108 foreach (split /\./, $val) {
3109 printf $datafile "\\%0.3o%s", length($_), $_;
3110 }
3111 print $datafile "\\000:$ttl:$stamp:$loc\n";
3112
3113 } elsif ($typemap{$type} eq 'RP') {
3114
3115 # RP consists of two mostly free-form strings.
3116 # The first is supposed to be an email address with @ replaced by . (as with the SOA contact)
3117 # The second is the "hostname" of a TXT record with more info.
3118 print $datafile ":$host:17:";
3119 my ($who,$what) = split /\s/, $val;
3120 foreach (split /\./, $who) {
3121 printf $datafile "\\%0.3o%s", length($_), $_;
3122 }
3123 print $datafile '\000';
3124 foreach (split /\./, $what) {
3125 printf $datafile "\\%0.3o%s", length($_), $_;
3126 }
3127 print $datafile "\\000:$ttl:$stamp:$loc\n";
3128
3129 } elsif ($typemap{$type} eq 'PTR') {
3130
3131 # must handle both IPv4 and IPv6
3132##work
3133 # data should already be in suitable reverse order.
3134 print $datafile "^$host:$val:$ttl:$stamp:$loc\n";
3135
3136 } else {
3137 # raw record. we don't know what's in here, so we ASS-U-ME the user has
3138 # put it in correctly, since either the user is messing directly with the
3139 # database, or the record was imported via AXFR
3140 # <split by char>
3141 # convert anything not a-zA-Z0-9.- to octal coding
3142
3143##fixme: add flag to export "unknown" record types - note we'll probably end up
3144# mangling them since they were written to the DB from Net::DNS::RR::<type>->rdatastr.
3145 #print $datafile ":$host:$type:$val:$ttl:$stamp:$loc\n";
3146
3147 } # record type if-else
3148
3149 } # while ($recsth)
3150 } # while ($domsth)
3151} # end __export_tiny()
3152
3153
3154## DNSDB::mailNotify()
3155# Sends notification mail to recipients regarding an IPDB operation
3156sub mailNotify {
3157 my $dbh = shift;
3158 my ($subj,$message) = @_;
3159
3160 return if $config{mailhost} eq 'smtp.example.com'; # do nothing if still using default SMTP host.
3161
3162 my $mailer = Net::SMTP->new($config{mailhost}, Hello => "dnsadmin.$config{domain}");
3163
3164 my $mailsender = ($config{mailsender} ? $config{mailsender} : $config{mailnotify});
3165
3166 $mailer->mail($mailsender);
3167 $mailer->to($config{mailnotify});
3168 $mailer->data("From: \"$config{mailname}\" <$mailsender>\n",
3169 "To: <$config{mailnotify}>\n",
3170 "Date: ".strftime("%a, %d %b %Y %H:%M:%S %z",localtime)."\n",
3171 "Subject: $subj\n",
3172 "X-Mailer: DNSAdmin Notify v".sprintf("%.1d",$DNSDB::VERSION)."\n",
3173 "Organization: $config{orgname}\n",
3174 "\n$message\n");
3175 $mailer->quit;
3176}
3177
3178# shut Perl up
31791;
Note: See TracBrowser for help on using the repository browser.