source: trunk/DNSDB.pm@ 242

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

/trunk

Fix buglet that snuck back into A/AAAA+PTR add - domain ID was
not added field list or bind-values array. See #26.
Log entry update: Accidentally committed cleanups on fill_recdata
and several parts of the record page:

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