source: trunk/DNSDB.pm@ 273

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

/trunk

updateRec() should now handle all record update changes

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