source: trunk/DNSDB.pm@ 247

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

/trunk

Move SOA update SQL into DNSDB.pm while we update it for
handling reverse zones. See #26.

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