source: trunk/DNSDB.pm@ 269

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

/trunk

addRDNS() complete except for handling $revpatt.
See #26

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