source: trunk/DNSDB.pm@ 240

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

/trunk

Whoops, forgot to export revName() somehow. See #26

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