source: trunk/DNSDB.pm@ 267

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

/trunk

Checkpoint, "add reverse zone" zone-info subsititution almost
complete
See #26

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