source: trunk/DNSDB.pm@ 248

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

/trunk

Quick pass over log linking and display for reverse zones. See #26.
Also add a ##fixme in logaction() for pagination, filtering, and
other log data massaging.

Fix a couple of typos introduced by hand-applying unrelated fixes
in a separate working copy

  • Property svn:keywords set to Date Rev Author Id
File size: 90.7 KB
Line 
1# dns/trunk/DNSDB.pm
2# Abstraction functions for DNS administration
3###
4# SVN revision info
5# $Date: 2012-02-28 22:11:56 +0000 (Tue, 28 Feb 2012) $
6# SVN revision $Rev: 248 $
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##fixme: stick a flag somewhere if the record doesn't exist. by the API, this is an impossible case, but...
1804
1805 my ($recid,$host,$val,$ttl) = $sth->fetchrow_array() or return;
1806 my ($contact,$prins) = split /:/, $host;
1807 my ($refresh,$retry,$expire,$minttl) = split /:/, $val;
1808
1809 $ret{recid} = $recid;
1810 $ret{ttl} = $ttl;
1811# $ret{serial} = $serial; # ca't use distance for serial with default_rev_records
1812 $ret{prins} = $prins;
1813 $ret{contact} = $contact;
1814 $ret{refresh} = $refresh;
1815 $ret{retry} = $retry;
1816 $ret{expire} = $expire;
1817 $ret{minttl} = $minttl;
1818
1819 return %ret;
1820} # end getSOA()
1821
1822
1823## DNSDB::updateSOA()
1824# Update the specified SOA record
1825# Takes a database handle, default/live flag, forward/reverse flag, and SOA data hash
1826sub updateSOA {
1827 my $dbh = shift;
1828 my $defrec = shift;
1829 my $revrec = shift;
1830
1831 my %soa = @_;
1832
1833##fixme: data validation: make sure {recid} is really the SOA for {parent}
1834 my $sql = "UPDATE "._rectable($defrec, $revrec)." SET host=?, val=?, ttl=? WHERE record_id=? AND type=6";
1835 $dbh->do($sql, undef, ("$soa{contact}:$soa{prins}", "$soa{refresh}:$soa{retry}:$soa{expire}:$soa{minttl}",
1836 $soa{ttl}, $soa{recid}));
1837
1838} # end updateSOA()
1839
1840
1841## DNSDB::getRecLine()
1842# Return all data fields for a zone record in separate elements of a hash
1843# Takes a database handle, default/live flag, forward/reverse flag, and record ID
1844sub getRecLine {
1845 $errstr = '';
1846 my $dbh = shift;
1847 my $defrec = shift;
1848 my $revrec = shift;
1849 my $id = shift;
1850
1851 my $sql = "SELECT record_id,host,type,val,ttl".($revrec eq 'n' ? ',distance,weight,port' : '').
1852 (($defrec eq 'y') ? ',group_id FROM ' : ',domain_id,rdns_id FROM ').
1853 _rectable($defrec,$revrec)." WHERE record_id=?";
1854 my $ret = $dbh->selectrow_hashref($sql, undef, ($id) );
1855
1856 if ($dbh->err) {
1857 $errstr = $DBI::errstr;
1858 return undef;
1859 }
1860
1861 if (!$ret) {
1862 $errstr = "No such record";
1863 return undef;
1864 }
1865
1866 # explicitly set a parent id
1867 if ($defrec eq 'y') {
1868 $ret->{parid} = $ret->{group_id};
1869 } else {
1870 $ret->{parid} = (($revrec eq 'n') ? $ret->{domain_id} : $ret->{rdns_id});
1871 # and a secondary if we have a custom type that lives in both a forward and reverse zone
1872 $ret->{secid} = (($revrec eq 'y') ? $ret->{domain_id} : $ret->{rdns_id}) if $ret->{type} > 65279;
1873 }
1874
1875 return $ret;
1876}
1877
1878
1879##fixme: should use above (getRecLine()) to get lines for below?
1880## DNSDB::getDomRecs()
1881# Return records for a domain
1882# Takes a database handle, default/live flag, group/domain ID, start,
1883# number of records, sort field, and sort order
1884# Returns a reference to an array of hashes
1885sub getDomRecs {
1886 $errstr = '';
1887 my $dbh = shift;
1888 my $def = shift;
1889 my $rev = shift;
1890 my $id = shift;
1891 my $nrecs = shift || 'all';
1892 my $nstart = shift || 0;
1893
1894## for order, need to map input to column names
1895 my $order = shift || 'host';
1896 my $direction = shift || 'ASC';
1897
1898 my $filter = shift || '';
1899
1900 my $sql = "SELECT r.record_id,r.host,r.type,r.val,r.ttl";
1901 $sql .= ",r.distance,r.weight,r.port" if $rev eq 'n';
1902 $sql .= " FROM "._rectable($def,$rev)." r ";
1903 $sql .= "INNER JOIN rectypes t ON r.type=t.val "; # for sorting by type alphabetically
1904 $sql .= "WHERE "._recparent($def,$rev)." = ?";
1905 $sql .= " AND NOT r.type=$reverse_typemap{SOA}";
1906 $sql .= " AND host ~* ?" if $filter;
1907 # use alphaorder column for "correct" ordering of sort-by-type instead of DNS RR type number
1908 $sql .= " ORDER BY ".($order eq 'type' ? 't.alphaorder' : "r.$order")." $direction";
1909
1910 my @bindvars = ($id);
1911 push @bindvars, $filter if $filter;
1912
1913 # just to be ultraparanoid about SQL injection vectors
1914 if ($nstart ne 'all') {
1915 $sql .= " LIMIT ? OFFSET ?";
1916 push @bindvars, $nrecs;
1917 push @bindvars, ($nstart*$nrecs);
1918 }
1919 my $sth = $dbh->prepare($sql) or warn $dbh->errstr;
1920 $sth->execute(@bindvars) or warn "$sql: ".$sth->errstr;
1921
1922 my @retbase;
1923 while (my $ref = $sth->fetchrow_hashref()) {
1924 push @retbase, $ref;
1925 }
1926
1927 my $ret = \@retbase;
1928 return $ret;
1929} # end getDomRecs()
1930
1931
1932## DNSDB::getRecCount()
1933# Return count of non-SOA records in zone (or default records in a group)
1934# Takes a database handle, default/live flag, reverse/forward flag, group/domain ID,
1935# and optional filtering modifier
1936# Returns the count
1937sub getRecCount {
1938 my $dbh = shift;
1939 my $defrec = shift;
1940 my $revrec = shift;
1941 my $id = shift;
1942 my $filter = shift || '';
1943
1944 # keep the nasties down, since we can't ?-sub this bit. :/
1945 # note this is chars allowed in DNS hostnames
1946 $filter =~ s/[^a-zA-Z0-9_.:-]//g;
1947
1948 my @bindvars = ($id);
1949 push @bindvars, $filter if $filter;
1950 my $sql = "SELECT count(*) FROM ".
1951 _rectable($defrec,$revrec).
1952 " WHERE "._recparent($defrec,$revrec)."=? ".
1953 "AND NOT type=$reverse_typemap{SOA}".
1954 ($filter ? " AND host ~* ?" : '');
1955 my ($count) = $dbh->selectrow_array($sql, undef, (@bindvars) );
1956
1957 return $count;
1958
1959} # end getRecCount()
1960
1961
1962## DNSDB::addRec()
1963# Add a new record to a domain or a group's default records
1964# Takes a database handle, default/live flag, group/domain ID,
1965# host, type, value, and TTL
1966# Some types require additional detail: "distance" for MX and SRV,
1967# and weight/port for SRV
1968# Returns a status code and detail message in case of error
1969##fixme: pass a hash with the record data, not a series of separate values
1970sub addRec {
1971 $errstr = '';
1972 my $dbh = shift;
1973 my $defrec = shift;
1974 my $revrec = shift;
1975 my $id = shift; # parent (group_id for defrecs, rdns_id for reverse records,
1976 # domain_id for domain records)
1977
1978 my $host = shift;
1979 my $rectype = shift; # reference so we can coerce it if "+"-types can't find both zones
1980 my $val = shift;
1981 my $ttl = shift;
1982
1983 # prep for validation
1984 my $addr = NetAddr::IP->new($val);
1985 $host =~ s/\.+$//; # FQDNs ending in . are an internal detail, and really shouldn't be exposed in the UI.
1986
1987 my $domid = 0;
1988 my $revid = 0;
1989
1990 my $retcode = 'OK'; # assume everything will go OK
1991 my $retmsg = '';
1992
1993 # do simple validation first
1994 return ('FAIL', "TTL must be numeric") unless $ttl =~ /^\d+$/;
1995
1996 # Quick check on hostname parts. Note the regex is more forgiving than the error message;
1997 # domain names technically are case-insensitive, and we use printf-like % codes for a couple
1998 # of types. Other things may also be added to validate default records of several flavours.
1999 return ('FAIL', "Hostnames may not contain anything other than (0-9 a-z . _)")
2000 if $defrec eq 'n' && $host !~ /^[0-9a-z_%.]+$/i;
2001
2002 # Collect these even if we're only doing a simple A record so we can call *any* validation sub
2003 my $dist = shift;
2004 my $port = shift;
2005 my $weight = shift;
2006
2007 my $fields;
2008 my @vallist;
2009
2010 # Call the validation sub for the type requested.
2011 ($retcode,$retmsg) = $validators{$$rectype}($dbh, (defrec => $defrec, revrec => $revrec, id => $id,
2012 host => \$host, rectype => $rectype, val => \$val, addr => $addr,
2013 dist => \$dist, port => \$port, weight => \$weight,
2014 fields => \$fields, vallist => \@vallist) );
2015
2016 return ($retcode,$retmsg) if $retcode eq 'FAIL';
2017
2018 # Set up database fields and bind parameters
2019 $fields .= "host,type,val,ttl,"._recparent($defrec,$revrec);
2020 push @vallist, ($host,$$rectype,$val,$ttl,$id);
2021 my $vallen = '?'.(',?'x$#vallist);
2022
2023 # Allow transactions, and raise an exception on errors so we can catch it later.
2024 # Use local to make sure these get "reset" properly on exiting this block
2025 local $dbh->{AutoCommit} = 0;
2026 local $dbh->{RaiseError} = 1;
2027
2028 eval {
2029 $dbh->do("INSERT INTO "._rectable($defrec, $revrec)." ($fields) VALUES ($vallen)",
2030 undef, @vallist);
2031 $dbh->commit;
2032 };
2033 if ($@) {
2034 my $msg = $@;
2035 eval { $dbh->rollback; };
2036 return ('FAIL',$msg);
2037 }
2038
2039 return ($retcode, $retmsg);
2040
2041} # end addRec()
2042
2043
2044## DNSDB::updateRec()
2045# Update a record
2046sub updateRec {
2047 $errstr = '';
2048
2049 my $dbh = shift;
2050 my $defrec = shift;
2051 my $id = shift;
2052
2053# all records have these
2054 my $host = shift;
2055 my $type = shift;
2056 my $val = shift;
2057 my $ttl = shift;
2058
2059 return('FAIL',"Missing standard argument(s)") if !defined($ttl);
2060
2061# only MX and SRV will use these
2062 my $dist = 0;
2063 my $weight = 0;
2064 my $port = 0;
2065
2066 if ($type == $reverse_typemap{MX} || $type == $reverse_typemap{SRV}) {
2067 $dist = shift;
2068 $dist =~ s/\s+//g;
2069 return ('FAIL',"MX or SRV requires distance") if !defined($dist);
2070 return ('FAIL', "Distance must be numeric") unless $dist =~ /^\d+$/;
2071 if ($type == $reverse_typemap{SRV}) {
2072 $weight = shift;
2073 $weight =~ s/\s+//g;
2074 return ('FAIL',"SRV requires weight") if !defined($weight);
2075 return ('FAIL',"Weight must be numeric") unless $weight =~ /^\d+$/;
2076 $port = shift;
2077 $port =~ s/\s+//g;
2078 return ('FAIL',"SRV requires port") if !defined($port);
2079 return ('FAIL',"Port must be numeric") unless $port =~ /^\d+$/;
2080 }
2081 }
2082
2083# Enforce IP addresses on A and AAAA types
2084 my $addr = NetAddr::IP->new($val);
2085 if ($type == $reverse_typemap{A}) {
2086 return ('FAIL',$typemap{$type}." record must be a valid IPv4 address")
2087 unless $addr && !$addr->{isv6};
2088 }
2089 if ($type == $reverse_typemap{AAAA}) {
2090 return ('FAIL',$typemap{$type}." record must be a valid IPv6 address")
2091 unless $addr && $addr->{isv6};
2092 }
2093
2094# hmm.. this might work. except possibly for something pointing to "deadbeef.ca". <g>
2095# if ($type == $reverse_typemap{NS} || $type == $reverse_typemap{MX} || $type == $reverse_typemap{SRV}) {
2096# if ($val =~ /^\s*[\da-f:.]+\s*$/) {
2097# return ('FAIL',"$val is not a valid IP address") if !$addr;
2098# }
2099# }
2100
2101 local $dbh->{AutoCommit} = 0;
2102 local $dbh->{RaiseError} = 1;
2103
2104 eval {
2105 $dbh->do("UPDATE ".($defrec eq 'y' ? 'default_' : '')."records ".
2106 "SET host=?,val=?,type=?,ttl=?,distance=?,weight=?,port=? ".
2107 "WHERE record_id=?", undef, ($host, $val, $type, $ttl, $dist, $weight, $port, $id) );
2108 $dbh->commit;
2109 };
2110 if ($@) {
2111 my $msg = $@;
2112 $dbh->rollback;
2113 return ('FAIL', $msg);
2114 }
2115
2116 return ('OK','OK');
2117} # end updateRec()
2118
2119
2120## DNSDB::delRec()
2121# Delete a record.
2122sub delRec {
2123 $errstr = '';
2124 my $dbh = shift;
2125 my $defrec = shift;
2126 my $revrec = shift;
2127 my $id = shift;
2128
2129 my $sth = $dbh->prepare("DELETE FROM "._rectable($defrec,$revrec)." WHERE record_id=?");
2130 $sth->execute($id);
2131
2132 return ('FAIL',"Couldn't remove record: ".$sth->errstr) if $sth->err;
2133
2134 return ('OK','OK');
2135} # end delRec()
2136
2137
2138 # Reference hashes.
2139my %par_tbl = (
2140 group => 'groups',
2141 user => 'users',
2142 defrec => 'default_records',
2143 defrevrec => 'default_rev_records',
2144 domain => 'domains',
2145 revzone => 'revzones',
2146 record => 'records'
2147 );
2148my %id_col = (
2149 group => 'group_id',
2150 user => 'user_id',
2151 defrec => 'record_id',
2152 defrevrec => 'record_id',
2153 domain => 'domain_id',
2154 revzone => 'rdns_id',
2155 record => 'record_id'
2156 );
2157my %par_col = (
2158 group => 'parent_group_id',
2159 user => 'group_id',
2160 defrec => 'group_id',
2161 defrevrec => 'group_id',
2162 domain => 'group_id',
2163 revzone => 'group_id',
2164 record => 'domain_id'
2165 );
2166my %par_type = (
2167 group => 'group',
2168 user => 'group',
2169 defrec => 'group',
2170 defrevrec => 'group',
2171 domain => 'group',
2172 revzone => 'group',
2173 record => 'domain'
2174 );
2175
2176
2177## DNSDB::getTypelist()
2178# Get a list of record types for various UI dropdowns
2179# Takes database handle, forward/reverse/lookup flag, and optional "tag as selected" indicator (defaults to A)
2180# Returns an arrayref to list of hashrefs perfect for HTML::Template
2181sub getTypelist {
2182 my $dbh = shift;
2183 my $recgroup = shift;
2184 my $type = shift || $reverse_typemap{A};
2185
2186 # also accepting $webvar{revrec}!
2187 $recgroup = 'f' if $recgroup eq 'n';
2188 $recgroup = 'r' if $recgroup eq 'y';
2189
2190 my $sql = "SELECT val,name FROM rectypes WHERE ";
2191 if ($recgroup eq 'r') {
2192 # reverse zone types
2193 $sql .= "stdflag=2 OR stdflag=3";
2194 } elsif ($recgroup eq 'l') {
2195 # DNS lookup types. Note we avoid our custom types >= 65280, since those are entirely internal.
2196 $sql .= "(stdflag=1 OR stdflag=2 OR stdflag=3) AND val < 65280";
2197 } else {
2198 # default; forward zone types. technically $type eq 'f' but not worth the error message.
2199 $sql .= "stdflag=1 OR stdflag=2";
2200 }
2201 $sql .= " ORDER BY listorder";
2202
2203 my $sth = $dbh->prepare($sql);
2204 $sth->execute;
2205 my @typelist;
2206 while (my ($rval,$rname) = $sth->fetchrow_array()) {
2207 my %row = ( recval => $rval, recname => $rname );
2208 $row{tselect} = 1 if $rval == $type;
2209 push @typelist, \%row;
2210 }
2211
2212 # Add SOA on lookups since it's not listed in other dropdowns.
2213 if ($recgroup eq 'l') {
2214 my %row = ( recval => $reverse_typemap{SOA}, recname => 'SOA' );
2215 $row{tselect} = 1 if $reverse_typemap{SOA} == $type;
2216 push @typelist, \%row;
2217 }
2218
2219 return \@typelist;
2220} # end getTypelist()
2221
2222
2223## DNSDB::getParents()
2224# Find out which entities are parent to the requested id
2225# Returns arrayref containing hash pairs of id/type
2226sub getParents {
2227 my $dbh = shift;
2228 my $id = shift;
2229 my $type = shift;
2230 my $depth = shift || 'all'; # valid values: 'all', 'immed', <int> (stop at this group ID)
2231
2232 my @parlist;
2233
2234 while (1) {
2235 my $result = $dbh->selectrow_hashref("SELECT $par_col{$type} FROM $par_tbl{$type} WHERE $id_col{$type} = ?",
2236 undef, ($id) );
2237 my %tmp = ($result->{$par_col{$type}} => $par_type{$type});
2238 unshift @parlist, \%tmp;
2239 last if $result->{$par_col{$type}} == 1; # group 1 is its own parent
2240 $id = $result->{$par_col{$type}};
2241 $type = $par_type{$type};
2242 }
2243
2244 return \@parlist;
2245
2246} # end getParents()
2247
2248
2249## DNSDB::isParent()
2250# Returns true if $id1 is a parent of $id2, false otherwise
2251sub isParent {
2252 my $dbh = shift;
2253 my $id1 = shift;
2254 my $type1 = shift;
2255 my $id2 = shift;
2256 my $type2 = shift;
2257##todo: immediate, secondary, full (default)
2258
2259 # Return false on invalid types
2260 return 0 if !grep /^$type1$/, ('record','defrec','defrevrec','user','domain','revzone','group');
2261 return 0 if !grep /^$type2$/, ('record','defrec','defrevrec','user','domain','revzone','group');
2262
2263 # Return false on impossible relations
2264 return 0 if $type1 eq 'record'; # nothing may be a child of a record
2265 return 0 if $type1 eq 'defrec'; # nothing may be a child of a record
2266 return 0 if $type1 eq 'defrevrec'; # nothing may be a child of a record
2267 return 0 if $type1 eq 'user'; # nothing may be child of a user
2268 return 0 if $type1 eq 'domain' && $type2 ne 'record'; # domain may not be a parent of anything other than a record
2269 return 0 if $type1 eq 'revzone' && $type2 ne 'record';# reverse zone may not be a parent of anything other than a record
2270
2271 # ennnhhhh.... if we're passed an id of 0, it will never be found. usual
2272 # case would be the UI creating a new <thing>, and so we don't have an ID for
2273 # <thing> to look up yet. in that case the UI should check the parent as well.
2274 return 0 if $id1 == 0; # nothing can have a parent id of 0
2275 return 1 if $id2 == 0; # anything could have a child id of 0 (or "unknown")
2276
2277 # group 1 is the ultimate root parent
2278 return 1 if $type1 eq 'group' && $id1 == 1;
2279
2280 # groups are always (a) parent of themselves
2281 return 1 if $type1 eq 'group' && $type2 eq 'group' && $id1 == $id2;
2282
2283 my $id = $id2;
2284 my $type = $type2;
2285 my $foundparent = 0;
2286
2287 # Records are the only entity with two possible parents. We need to split the parent checks on
2288 # domain/rdns.
2289 if ($type eq 'record') {
2290 my ($dom,$rdns) = $dbh->selectrow_array("SELECT domain_id,rdns_id FROM records WHERE record_id=?",
2291 undef, ($id));
2292 # check immediate parent against request
2293 return 1 if $type1 eq 'domain' && $id1 == $dom;
2294 return 1 if $type1 eq 'revzone' && $id1 == $rdns;
2295 # if request is group, check *both* parents. Only check if the parent is nonzero though.
2296 return 1 if $dom && isParent($dbh, $id1, $type1, $dom, 'domain');
2297 return 1 if $rdns && isParent($dbh, $id1, $type1, $rdns, 'revzone');
2298 # exit here since we've executed the loop below by proxy in the above recursive calls.
2299 return 0;
2300 }
2301
2302# almost the same loop as getParents() above
2303 my $limiter = 0;
2304 while (1) {
2305 my $sql = "SELECT $par_col{$type} FROM $par_tbl{$type} WHERE $id_col{$type} = ?";
2306 my $result = $dbh->selectrow_hashref($sql,
2307 undef, ($id) );
2308 if (!$result) {
2309 $limiter++;
2310##fixme: how often will this happen on a live site? fail at max limiter <n>?
2311 warn "no results looking for $sql with id $id (depth $limiter)\n";
2312 last;
2313 }
2314 if ($result && $result->{$par_col{$type}} == $id1) {
2315 $foundparent = 1;
2316 last;
2317 } else {
2318##fixme: do we care about trying to return a "no such record/domain/user/group" error?
2319# should be impossible to create an inconsistent DB just with API calls.
2320 warn $dbh->errstr." $sql, $id" if $dbh->errstr;
2321 }
2322 # group 1 is its own parent. need this here more to break strange loops than for detecting a parent
2323 last if $result->{$par_col{$type}} == 1;
2324 $id = $result->{$par_col{$type}};
2325 $type = $par_type{$type};
2326 }
2327
2328 return $foundparent;
2329} # end isParent()
2330
2331
2332## DNSDB::domStatus()
2333# Sets and/or returns a domain's status
2334# Takes a database handle, domain ID and optionally a status argument
2335# Returns undef on errors.
2336sub domStatus {
2337 my $dbh = shift;
2338 my $id = shift;
2339 my $newstatus = shift;
2340
2341 return undef if $id !~ /^\d+$/;
2342
2343 my $sth;
2344
2345# ooo, fun! let's see what we were passed for status
2346 if ($newstatus) {
2347 $sth = $dbh->prepare("update domains set status=? where domain_id=?");
2348 # ass-u-me caller knows what's going on in full
2349 if ($newstatus =~ /^[01]$/) { # only two valid for now.
2350 $sth->execute($newstatus,$id);
2351 } elsif ($newstatus =~ /^domo(?:n|ff)$/) {
2352 $sth->execute(($newstatus eq 'domon' ? 1 : 0),$id);
2353 }
2354 }
2355
2356 $sth = $dbh->prepare("select status from domains where domain_id=?");
2357 $sth->execute($id);
2358 my ($status) = $sth->fetchrow_array;
2359 return $status;
2360} # end domStatus()
2361
2362
2363## DNSDB::importAXFR
2364# Import a domain via AXFR
2365# Takes AXFR host, domain to transfer, group to put the domain in,
2366# and optionally:
2367# - active/inactive state flag (defaults to active)
2368# - overwrite-SOA flag (defaults to off)
2369# - overwrite-NS flag (defaults to off, doesn't affect subdomain NS records)
2370# Returns a status code (OK, WARN, or FAIL) and message - message should be blank
2371# if status is OK, but WARN includes conditions that are not fatal but should
2372# really be reported.
2373sub importAXFR {
2374 my $dbh = shift;
2375 my $ifrom_in = shift;
2376 my $domain = shift;
2377 my $group = shift;
2378 my $status = shift || 1;
2379 my $rwsoa = shift || 0;
2380 my $rwns = shift || 0;
2381
2382##fixme: add mode to delete&replace, merge+overwrite, merge new?
2383
2384 my $nrecs = 0;
2385 my $soaflag = 0;
2386 my $nsflag = 0;
2387 my $warnmsg = '';
2388 my $ifrom;
2389
2390 # choke on possible bad setting in ifrom
2391 # IPv4 and v6, and valid hostnames!
2392 ($ifrom) = ($ifrom_in =~ /^([0-9a-f\:.]+|[0-9a-z_.-]+)$/i);
2393 return ('FAIL', "Bad AXFR source host $ifrom")
2394 unless ($ifrom) = ($ifrom_in =~ /^([0-9a-f\:.]+|[0-9a-z_.-]+)$/i);
2395
2396 # Allow transactions, and raise an exception on errors so we can catch it later.
2397 # Use local to make sure these get "reset" properly on exiting this block
2398 local $dbh->{AutoCommit} = 0;
2399 local $dbh->{RaiseError} = 1;
2400
2401 my $sth = $dbh->prepare("SELECT domain_id FROM domains WHERE domain=?");
2402 my $dom_id;
2403
2404# quick check to start to see if we've already got one
2405 $sth->execute($domain);
2406 ($dom_id) = $sth->fetchrow_array;
2407
2408 return ('FAIL', "Domain already exists") if $dom_id;
2409
2410 eval {
2411 # can't do this, can't nest transactions. sigh.
2412 #my ($dcode, $dmsg) = addDomain(dbh, domain, group, status);
2413
2414##fixme: serial
2415 my $sth = $dbh->prepare("INSERT INTO domains (domain,group_id,status) VALUES (?,?,?)");
2416 $sth->execute($domain,$group,$status);
2417
2418## bizarre DBI<->Net::DNS interaction bug:
2419## sometimes a zone will cause an immediate commit-and-exit (sort of) of the while()
2420## fixed, apparently I was doing *something* odd, but not certain what it was that
2421## caused a commit instead of barfing
2422
2423 # get domain id so we can do the records
2424 $sth = $dbh->prepare("SELECT domain_id FROM domains WHERE domain=?");
2425 $sth->execute($domain);
2426 ($dom_id) = $sth->fetchrow_array();
2427
2428 my $res = Net::DNS::Resolver->new;
2429 $res->nameservers($ifrom);
2430 $res->axfr_start($domain)
2431 or die "Couldn't begin AXFR\n";
2432
2433 while (my $rr = $res->axfr_next()) {
2434 my $type = $rr->type;
2435
2436 my $sql = "INSERT INTO records (domain_id,host,type,ttl,val";
2437 my $vallen = "?,?,?,?,?";
2438
2439 $soaflag = 1 if $type eq 'SOA';
2440 $nsflag = 1 if $type eq 'NS';
2441
2442 my @vallist = ($dom_id, $rr->name, $reverse_typemap{$type}, $rr->ttl);
2443
2444# "Primary" types:
2445# A, NS, CNAME, SOA, PTR(warn in forward), MX, TXT, AAAA, SRV, A6(ob), SPF
2446# maybe KEY
2447
2448# nasty big ugly case-like thing here, since we have to do *some* different
2449# processing depending on the record. le sigh.
2450
2451##fixme: what record types other than TXT can/will have >255-byte payloads?
2452
2453 if ($type eq 'A') {
2454 push @vallist, $rr->address;
2455 } elsif ($type eq 'NS') {
2456# hmm. should we warn here if subdomain NS'es are left alone?
2457 next if ($rwns && ($rr->name eq $domain));
2458 push @vallist, $rr->nsdname;
2459 $nsflag = 1;
2460 } elsif ($type eq 'CNAME') {
2461 push @vallist, $rr->cname;
2462 } elsif ($type eq 'SOA') {
2463 next if $rwsoa;
2464 $vallist[1] = $rr->mname.":".$rr->rname;
2465 push @vallist, ($rr->refresh.":".$rr->retry.":".$rr->expire.":".$rr->minimum);
2466 $soaflag = 1;
2467 } elsif ($type eq 'PTR') {
2468 push @vallist, $rr->ptrdname;
2469 # hmm. PTR records should not be in forward zones.
2470 } elsif ($type eq 'MX') {
2471 $sql .= ",distance";
2472 $vallen .= ",?";
2473 push @vallist, $rr->exchange;
2474 push @vallist, $rr->preference;
2475 } elsif ($type eq 'TXT') {
2476##fixme: Net::DNS docs say this should be deprecated for rdatastr() or char_str_list(),
2477## but don't really seem enthusiastic about it.
2478 my $rrdata = $rr->txtdata;
2479 push @vallist, $rrdata;
2480 } elsif ($type eq 'SPF') {
2481##fixme: and the same caveat here, since it is apparently a clone of ::TXT
2482 my $rrdata = $rr->txtdata;
2483 push @vallist, $rrdata;
2484 } elsif ($type eq 'AAAA') {
2485 push @vallist, $rr->address;
2486 } elsif ($type eq 'SRV') {
2487 $sql .= ",distance,weight,port" if $type eq 'SRV';
2488 $vallen .= ",?,?,?" if $type eq 'SRV';
2489 push @vallist, $rr->target;
2490 push @vallist, $rr->priority;
2491 push @vallist, $rr->weight;
2492 push @vallist, $rr->port;
2493 } elsif ($type eq 'KEY') {
2494 # we don't actually know what to do with these...
2495 push @vallist, ($rr->flags.":".$rr->protocol.":".$rr->algorithm.":".$rr->key.":".$rr->keytag.":".$rr->privatekeyname);
2496 } else {
2497 my $rrdata = $rr->rdatastr;
2498 push @vallist, $rrdata;
2499 # Finding a different record type is not fatal.... just problematic.
2500 # We may not be able to export it correctly.
2501 $warnmsg .= "Unusual record ".$rr->name." ($type) found\n";
2502 }
2503
2504# BIND supports:
2505# A CNAME HINFO MB(ex) MD(ob) MF(ob) MG(ex) MINFO(ex) MR(ex) MX NS NULL
2506# PTR SOA TXT WKS AFSDB(ex) ISDN(ex) RP(ex) RT(ex) X25(ex) PX
2507# ... if one can ever find the right magic to format them correctly
2508
2509# Net::DNS supports:
2510# RRSIG SIG NSAP NS NIMLOC NAPTR MX MR MINFO MG MB LOC ISDN IPSECKEY HINFO
2511# EID DNAME CNAME CERT APL AFSDB AAAA A DS NXT NSEC3PARAM NSEC3 NSEC KEY
2512# DNSKEY DLV X25 TXT TSIG TKEY SSHFP SRV SPF SOA RT RP PX PTR NULL APL::AplItem
2513
2514 $sth = $dbh->prepare($sql.") VALUES (".$vallen.")") or die "problem preparing record insert SQL\n";
2515 $sth->execute(@vallist) or die "failed to insert ".$rr->string.": ".$sth->errstr."\n";
2516
2517 $nrecs++;
2518
2519 } # while axfr_next
2520
2521 # Overwrite SOA record
2522 if ($rwsoa) {
2523 $soaflag = 1;
2524 my $sthgetsoa = $dbh->prepare("SELECT host,val,ttl FROM default_records WHERE group_id=? AND type=?");
2525 my $sthputsoa = $dbh->prepare("INSERT INTO records (domain_id,host,type,val,ttl) VALUES (?,?,?,?,?)");
2526 $sthgetsoa->execute($group,$reverse_typemap{SOA});
2527 while (my ($host,$val,$ttl) = $sthgetsoa->fetchrow_array()) {
2528 $host =~ s/DOMAIN/$domain/g;
2529 $val =~ s/DOMAIN/$domain/g;
2530 $sthputsoa->execute($dom_id,$host,$reverse_typemap{SOA},$val,$ttl);
2531 }
2532 }
2533
2534 # Overwrite NS records
2535 if ($rwns) {
2536 $nsflag = 1;
2537 my $sthgetns = $dbh->prepare("SELECT host,val,ttl FROM default_records WHERE group_id=? AND type=?");
2538 my $sthputns = $dbh->prepare("INSERT INTO records (domain_id,host,type,val,ttl) VALUES (?,?,?,?,?)");
2539 $sthgetns->execute($group,$reverse_typemap{NS});
2540 while (my ($host,$val,$ttl) = $sthgetns->fetchrow_array()) {
2541 $host =~ s/DOMAIN/$domain/g;
2542 $val =~ s/DOMAIN/$domain/g;
2543 $sthputns->execute($dom_id,$host,$reverse_typemap{NS},$val,$ttl);
2544 }
2545 }
2546
2547 die "No records found; either $ifrom is not authoritative or doesn't allow transfers\n" if !$nrecs;
2548 die "Bad zone: No SOA record!\n" if !$soaflag;
2549 die "Bad zone: No NS records!\n" if !$nsflag;
2550
2551 $dbh->commit;
2552
2553 };
2554
2555 if ($@) {
2556 my $msg = $@;
2557 eval { $dbh->rollback; };
2558 return ('FAIL',$msg." $warnmsg");
2559 } else {
2560 return ('WARN', $warnmsg) if $warnmsg;
2561 return ('OK',"Imported OK");
2562 }
2563
2564 # it should be impossible to get here.
2565 return ('WARN',"OOOK!");
2566} # end importAXFR()
2567
2568
2569## DNSDB::export()
2570# Export the DNS database, or a part of it
2571# Takes database handle, export type, optional arguments depending on type
2572# Writes zone data to targets as appropriate for type
2573sub export {
2574 my $dbh = shift;
2575 my $target = shift;
2576
2577 if ($target eq 'tiny') {
2578 __export_tiny($dbh,@_);
2579 }
2580# elsif ($target eq 'foo') {
2581# __export_foo($dbh,@_);
2582#}
2583# etc
2584
2585} # end export()
2586
2587
2588## DNSDB::__export_tiny
2589# Internal sub to implement tinyDNS (compatible) export
2590# Takes database handle, filehandle to write export to, optional argument(s)
2591# to determine which data gets exported
2592sub __export_tiny {
2593 my $dbh = shift;
2594 my $datafile = shift;
2595
2596##fixme: slurp up further options to specify particular zone(s) to export
2597
2598 ## Convert a bare number into an octal-coded pair of octets.
2599 # Take optional arg to indicate a decimal or hex input. Defaults to hex.
2600 sub octalize {
2601 my $tmp = shift;
2602 my $srctype = shift || 'h'; # default assumes hex string
2603 $tmp = sprintf "%0.4x", hex($tmp) if $srctype eq 'h'; # 0-pad hex to 4 digits
2604 $tmp = sprintf "%0.4x", $tmp if $srctype eq 'd'; # 0-pad decimal to 4 hex digits
2605 my @o = ($tmp =~ /^(..)(..)$/); # split into octets
2606 return sprintf "\\%0.3o\\%0.3o", hex($o[0]), hex($o[1]);;
2607 }
2608
2609##fixme: fail if $datafile isn't an open, writable file
2610
2611 # easy case - export all evarything
2612 # not-so-easy case - export item(s) specified
2613 # todo: figure out what kind of list we use to export items
2614
2615 my $domsth = $dbh->prepare("SELECT domain_id,domain,status FROM domains WHERE status=1");
2616 my $recsth = $dbh->prepare("SELECT host,type,val,distance,weight,port,ttl ".
2617 "FROM records WHERE domain_id=?");
2618 $domsth->execute();
2619 while (my ($domid,$dom,$domstat) = $domsth->fetchrow_array) {
2620 $recsth->execute($domid);
2621 while (my ($host,$type,$val,$dist,$weight,$port,$ttl) = $recsth->fetchrow_array) {
2622##fixme: need to store location in the db, and retrieve it here.
2623# temporarily hardcoded to empty so we can include it further down.
2624my $loc = '';
2625
2626##fixme: record validity timestamp. tinydns supports fiddling with timestamps.
2627# note $ttl must be set to 0 if we want to use tinydns's auto-expiring timestamps.
2628# timestamps are TAI64
2629# ~~ 2^62 + time()
2630my $stamp = '';
2631
2632# raw packet in unknown format: first byte indicates length
2633# of remaining data, allows up to 255 raw bytes
2634
2635##fixme? append . to all host/val hostnames
2636 if ($typemap{$type} eq 'SOA') {
2637
2638 # host contains pri-ns:responsible
2639 # val is abused to contain refresh:retry:expire:minttl
2640##fixme: "manual" serial vs tinydns-autoserial
2641 # let's be explicit about abusing $host and $val
2642 my ($email, $primary) = (split /:/, $host)[0,1];
2643 my ($refresh, $retry, $expire, $min_ttl) = (split /:/, $val)[0,1,2,3];
2644 print $datafile "Z$dom:$primary:$email"."::$refresh:$retry:$expire:$min_ttl:$ttl:$stamp:$loc\n";
2645
2646 } elsif ($typemap{$type} eq 'A') {
2647
2648 print $datafile "+$host:$val:$ttl:$stamp:$loc\n";
2649
2650 } elsif ($typemap{$type} eq 'NS') {
2651
2652 print $datafile "\&$host"."::$val:$ttl:$stamp:$loc\n";
2653
2654 } elsif ($typemap{$type} eq 'AAAA') {
2655
2656 print $datafile ":$host:28:";
2657 my $altgrp = 0;
2658 my @altconv;
2659 # Split in to up to 8 groups of hex digits (allows for IPv6 :: 0-collapsing)
2660 foreach (split /:/, $val) {
2661 if (/^$/) {
2662 # flag blank entry; this is a series of 0's of (currently) unknown length
2663 $altconv[$altgrp++] = 's';
2664 } else {
2665 # call sub to convert 1-4 hex digits to 2 string-rep octal bytes
2666 $altconv[$altgrp++] = octalize($_)
2667 }
2668 }
2669 foreach my $octet (@altconv) {
2670 # if not 's', output
2671 print $datafile $octet unless $octet =~ /^s$/;
2672 # if 's', output (9-array length)x literal '\000\000'
2673 print $datafile '\000\000'x(9-$altgrp) if $octet =~ /^s$/;
2674 }
2675 print $datafile ":$ttl:$stamp:$loc\n";
2676
2677 } elsif ($typemap{$type} eq 'MX') {
2678
2679 print $datafile "\@$host"."::$val:$dist:$ttl:$stamp:$loc\n";
2680
2681 } elsif ($typemap{$type} eq 'TXT') {
2682
2683##fixme: split v-e-r-y long TXT strings? will need to do so for BIND export, at least
2684 $val =~ s/:/\\072/g; # may need to replace other symbols
2685 print $datafile "'$host:$val:$ttl:$stamp:$loc\n";
2686
2687# by-hand TXT
2688#:deepnet.cx:16:2v\075spf1\040a\040a\072bacon.deepnet.cx\040a\072home.deepnet.cx\040-all:3600
2689#@ IN TXT "v=spf1 a a:bacon.deepnet.cx a:home.deepnet.cx -all"
2690#'deepnet.cx:v=spf1 a a\072bacon.deepnet.cx a\072home.deepnet.cx -all:3600
2691
2692#txttest IN TXT "v=foo bar:bob kn;ob' \" !@#$%^&*()-=_+[]{}<>?"
2693#: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
2694
2695# very long TXT record as brought in by axfr-get
2696# note tinydns does not support >512-byte RR data, need axfr-dns (for TCP support) for that
2697# also note, tinydns does not seem to support <512, >256-byte RRdata from axfr-get either. :/
2698#:longtxt.deepnet.cx:16:
2699#\170this is a very long txt record. it is really long. long. very long. really very long. this is a very long txt record.
2700#\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.
2701#\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.
2702#:3600
2703
2704 } elsif ($typemap{$type} eq 'CNAME') {
2705
2706 print $datafile "C$host:$val:$ttl:$stamp:$loc\n";
2707
2708 } elsif ($typemap{$type} eq 'SRV') {
2709
2710 # data is two-byte values for priority, weight, port, in that order,
2711 # followed by length/string data
2712
2713 print $datafile ":$host:33:".octalize($dist,'d').octalize($weight,'d').octalize($port,'d');
2714
2715 $val .= '.' if $val !~ /\.$/;
2716 foreach (split /\./, $val) {
2717 printf $datafile "\\%0.3o%s", length($_), $_;
2718 }
2719 print $datafile "\\000:$ttl:$stamp:$loc\n";
2720
2721 } elsif ($typemap{$type} eq 'RP') {
2722
2723 # RP consists of two mostly free-form strings.
2724 # The first is supposed to be an email address with @ replaced by . (as with the SOA contact)
2725 # The second is the "hostname" of a TXT record with more info.
2726 print $datafile ":$host:17:";
2727 my ($who,$what) = split /\s/, $val;
2728 foreach (split /\./, $who) {
2729 printf $datafile "\\%0.3o%s", length($_), $_;
2730 }
2731 print $datafile '\000';
2732 foreach (split /\./, $what) {
2733 printf $datafile "\\%0.3o%s", length($_), $_;
2734 }
2735 print $datafile "\\000:$ttl:$stamp:$loc\n";
2736
2737 } elsif ($typemap{$type} eq 'PTR') {
2738
2739 # must handle both IPv4 and IPv6
2740##work
2741 # data should already be in suitable reverse order.
2742 print $datafile "^$host:$val:$ttl:$stamp:$loc\n";
2743
2744 } else {
2745 # raw record. we don't know what's in here, so we ASS-U-ME the user has
2746 # put it in correctly, since either the user is messing directly with the
2747 # database, or the record was imported via AXFR
2748 # <split by char>
2749 # convert anything not a-zA-Z0-9.- to octal coding
2750
2751##fixme: add flag to export "unknown" record types - note we'll probably end up
2752# mangling them since they were written to the DB from Net::DNS::RR::<type>->rdatastr.
2753 #print $datafile ":$host:$type:$val:$ttl:$stamp:$loc\n";
2754
2755 } # record type if-else
2756
2757 } # while ($recsth)
2758 } # while ($domsth)
2759} # end __export_tiny()
2760
2761
2762## DNSDB::mailNotify()
2763# Sends notification mail to recipients regarding an IPDB operation
2764sub mailNotify {
2765 my $dbh = shift;
2766 my ($subj,$message) = @_;
2767
2768 return if $config{mailhost} eq 'smtp.example.com'; # do nothing if still using default SMTP host.
2769
2770 my $mailer = Net::SMTP->new($config{mailhost}, Hello => "dnsadmin.$config{domain}");
2771
2772 my $mailsender = ($config{mailsender} ? $config{mailsender} : $config{mailnotify});
2773
2774 $mailer->mail($mailsender);
2775 $mailer->to($config{mailnotify});
2776 $mailer->data("From: \"$config{mailname}\" <$mailsender>\n",
2777 "To: <$config{mailnotify}>\n",
2778 "Date: ".strftime("%a, %d %b %Y %H:%M:%S %z",localtime)."\n",
2779 "Subject: $subj\n",
2780 "X-Mailer: DNSAdmin Notify v".sprintf("%.1d",$DNSDB::VERSION)."\n",
2781 "Organization: $config{orgname}\n",
2782 "\n$message\n");
2783 $mailer->quit;
2784}
2785
2786# shut Perl up
27871;
Note: See TracBrowser for help on using the repository browser.