source: trunk/DNSDB.pm@ 244

Last change on this file since 244 was 244, checked in by Kris Deugau, 13 years ago

/trunk

Scope check cleanup for rdns, should be complete. Some checks
seem to have been wrong (eg default record delete) and may be
candidates for backporting to a stable release. See #26.

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