source: trunk/DNSDB.pm@ 264

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

/trunk

Checkpoint; reverse records that don't match the zone (v4/v6) are skipped
Reverse records that can't fit in the zone are also skipped (... sort of,
still needs work)
Replacing ZONE in value/IP mostly done
See #26

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