source: trunk/DNSDB.pm@ 256

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

/trunk

Update internal _log() sub to handle rdns_id
Update existing calls to _log() in addDomain()
See #26

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