source: branches/stable/DNSDB.pm@ 544

Last change on this file since 544 was 544, checked in by Kris Deugau, 10 years ago

/branches/stable

Merge reverse DNS work; 1 of mumble

  • from branch creation through r261

Minor conflicts in dns.cgi and DNSDB.pm

  • Property svn:keywords set to Date Rev Author Id
File size: 98.3 KB
Line 
1# dns/trunk/DNSDB.pm
2# Abstraction functions for DNS administration
3##
4# $Id: DNSDB.pm 544 2013-12-10 22:15:56Z 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 = "1.0.5"; ##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#$dbh->selectrow_array("SELECT currval('users_user_id_seq')");
1263 # Wrap all the SQL in a transaction
1264 eval {
1265 # insert the domain...
1266 $dbh->do("INSERT INTO revzones (revnet,group_id,status) VALUES (?,?,?)", undef, ($zone, $group, $state));
1267
1268 # get the ID...
1269 ($rdns_id) = $dbh->selectrow_array("SELECT currval('revzones_rdns_id_seq')");
1270
1271 _log($dbh, (rdns_id => $rdns_id, user_id => $userinfo{id}, group_id => $group, username => $userinfo{name},
1272 entry => "Added ".($state ? 'active' : 'inactive')." reverse zone $zone"));
1273
1274 # ... and now we construct the standard records from the default set. NB: group should be variable.
1275 my $sth = $dbh->prepare("SELECT host,type,val,ttl FROM default_rev_records WHERE group_id=?");
1276 my $sth_in = $dbh->prepare("INSERT INTO records (rdns_id,host,type,val,ttl)".
1277 " VALUES ($rdns_id,?,?,?,?)");
1278 $sth->execute($group);
1279 while (my ($host,$type,$val,$ttl) = $sth->fetchrow_array()) {
1280 $host =~ s/ADMINDOMAIN/$config{domain}/g;
1281##work
1282# - replace ZONE in $val
1283# - skip records not appropriate for the zone (skip A+PTR on v6 zones, and AAAA+PTR on v4 zones)
1284# $val =~ s/DOMAIN/$domain/g;
1285 $sth_in->execute($host,$type,$val,$ttl);
1286 if ($typemap{$type} eq 'SOA') {
1287 my @tmp1 = split /:/, $host;
1288 my @tmp2 = split /:/, $val;
1289 _log($dbh, (rdns_id => $rdns_id, user_id => $userinfo{id}, group_id => $group,
1290 username => $userinfo{name}, entry =>
1291 "[new $zone] Added SOA record [contact $tmp1[0]] [master $tmp1[1]] ".
1292 "[refresh $tmp2[0]] [retry $tmp2[1]] [expire $tmp2[2]] [minttl $tmp2[3]], TTL $ttl"));
1293 } else {
1294 my $logentry = "[new $zone] Added record '$host $typemap{$type}";
1295# $logentry .= " [distance $dist]" if $typemap{$type} eq 'MX';
1296# $logentry .= " [priority $dist] [weight $weight] [port $port]" if $typemap{$type} eq 'SRV';
1297 _log($dbh, (rdns_id => $rdns_id, user_id => $userinfo{id}, group_id => $group,
1298 username => $userinfo{name}, entry =>
1299 $logentry." $val', TTL $ttl"));
1300 }
1301 }
1302
1303 # once we get here, we should have suceeded.
1304 $dbh->commit;
1305 }; # end eval
1306
1307 if ($@) {
1308 my $msg = $@;
1309 eval { $dbh->rollback; };
1310 return ('FAIL',$msg);
1311 } else {
1312 return ('OK',$rdns_id);
1313 }
1314
1315} # end addRDNS()
1316
1317
1318## DNSDB::getZoneCount
1319# Get count of zones in group or groups
1320# Takes a database handle and hash containing:
1321# - the "current" group
1322# - an array of "acceptable" groups
1323# - a flag for forward/reverse zones
1324# - Optionally accept a "starts with" and/or "contains" filter argument
1325# Returns an integer count of the resulting zone list.
1326sub getZoneCount {
1327 my $dbh = shift;
1328
1329 my %args = @_;
1330
1331 my @filterargs;
1332 $args{startwith} = undef if $args{startwith} && $args{startwith} !~ /^(?:[a-z]|0-9)$/;
1333 push @filterargs, "^$args{startwith}" if $args{startwith};
1334 $args{filter} =~ s/\./\[\.\]/g if $args{filter}; # only match literal dots, usually in reverse zones
1335 push @filterargs, $args{filter} if $args{filter};
1336
1337 my $sql;
1338 # Not as compact, and fix-me-twice if the common bits get wrong, but much easier to read
1339 if ($args{revrec} eq 'n') {
1340 $sql = "SELECT count(*) FROM domains".
1341 " WHERE group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
1342 ($args{startwith} ? " AND domain ~* ?" : '').
1343 ($args{filter} ? " AND domain ~* ?" : '');
1344 } else {
1345 $sql = "SELECT count(*) FROM revzones".
1346 " WHERE group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
1347 ($args{startwith} ? " AND CAST(revnet AS VARCHAR) ~* ?" : '').
1348 ($args{filter} ? " AND CAST(revnet AS VARCHAR) ~* ?" : '');
1349 }
1350 my ($count) = $dbh->selectrow_array($sql, undef, @filterargs);
1351 return $count;
1352} # end getZoneCount()
1353
1354
1355## DNSDB::getZoneList()
1356# Get a list of zones in the specified group(s)
1357# Takes the same arguments as getZoneCount() above
1358# Returns a reference to an array of hashrefs suitable for feeding to HTML::Template
1359sub getZoneList {
1360 my $dbh = shift;
1361
1362 my %args = @_;
1363
1364 my @zonelist;
1365
1366 $args{sortorder} = 'ASC' if !grep $args{sortorder}, ('ASC','DESC');
1367 $args{offset} = 0 if !$args{offset} || $args{offset} !~ /^(?:all|\d+)$/;
1368
1369 my @filterargs;
1370 $args{startwith} = undef if $args{startwith} && $args{startwith} !~ /^(?:[a-z]|0-9)$/;
1371 push @filterargs, "^$args{startwith}" if $args{startwith};
1372 $args{filter} =~ s/\./\[\.\]/g if $args{filter}; # only match literal dots, usually in reverse zones
1373 push @filterargs, $args{filter} if $args{filter};
1374
1375 my $sql;
1376 # Not as compact, and fix-me-twice if the common bits get wrong, but much easier to read
1377 if ($args{revrec} eq 'n') {
1378 $args{sortby} = 'domain' if !grep $args{sortby}, ('revnet','group','status');
1379 $sql = "SELECT domain_id,domain,status,groups.group_name AS group FROM domains".
1380 " INNER JOIN groups ON domains.group_id=groups.group_id".
1381 " WHERE domains.group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
1382 ($args{startwith} ? " AND domain ~* ?" : '').
1383 ($args{filter} ? " AND domain ~* ?" : '');
1384 } else {
1385##fixme: arguably startwith here is irrelevant. depends on the UI though.
1386 $args{sortby} = 'revnet' if !grep $args{sortby}, ('domain','group','status');
1387 $sql = "SELECT rdns_id,revnet,status,groups.group_name AS group FROM revzones".
1388 " INNER JOIN groups ON revzones.group_id=groups.group_id".
1389 " WHERE revzones.group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
1390 ($args{startwith} ? " AND CAST(revnet AS VARCHAR) ~* ?" : '').
1391 ($args{filter} ? " AND CAST(revnet AS VARCHAR) ~* ?" : '');
1392 }
1393 # A common tail.
1394 $sql .= " ORDER BY ".($args{sortby} eq 'group' ? 'groups.group_name' : $args{sortby})." $args{sortorder} ".
1395 ($args{offset} eq 'all' ? '' : " LIMIT $config{perpage}".
1396 " OFFSET ".$args{offset}*$config{perpage});
1397 my $sth = $dbh->prepare($sql);
1398 $sth->execute(@filterargs);
1399 my $rownum = 0;
1400
1401 while (my @data = $sth->fetchrow_array) {
1402 my %row;
1403 $row{domainid} = $data[0];
1404 $row{domain} = $data[1];
1405 $row{status} = $data[2];
1406 $row{group} = $data[3];
1407 push @zonelist, \%row;
1408 }
1409
1410 return \@zonelist;
1411} # end getZoneList()
1412
1413
1414## DNSDB::addGroup()
1415# Add a group
1416# Takes a database handle, group name, parent group, hashref for permissions,
1417# and optional template-vs-cloneme flag
1418# Returns a status code and message
1419sub addGroup {
1420 $errstr = '';
1421 my $dbh = shift;
1422 my $groupname = shift;
1423 my $pargroup = shift;
1424 my $permissions = shift;
1425
1426 # 0 indicates "custom", hardcoded.
1427 # Any other value clones that group's default records, if it exists.
1428 my $inherit = shift || 0;
1429##fixme: need a flag to indicate clone records or <?> ?
1430
1431 # Allow transactions, and raise an exception on errors so we can catch it later.
1432 # Use local to make sure these get "reset" properly on exiting this block
1433 local $dbh->{AutoCommit} = 0;
1434 local $dbh->{RaiseError} = 1;
1435
1436 my $sth = $dbh->prepare("SELECT group_id FROM groups WHERE group_name=?");
1437 my $group_id;
1438
1439# quick check to start to see if we've already got one
1440 $sth->execute($groupname);
1441 ($group_id) = $sth->fetchrow_array;
1442
1443 return ('FAIL', "Group already exists") if $group_id;
1444
1445 # Wrap all the SQL in a transaction
1446 eval {
1447 $sth = $dbh->prepare("INSERT INTO groups (parent_group_id,group_name) VALUES (?,?)");
1448 $sth->execute($pargroup,$groupname);
1449
1450 my ($groupid) = $dbh->selectrow_array("SELECT group_id FROM groups WHERE group_name=?", undef, ($groupname));
1451
1452# Permissions
1453 if ($inherit) {
1454 } else {
1455 my @permvals;
1456 foreach (@permtypes) {
1457 if (!defined ($permissions->{$_})) {
1458 push @permvals, 0;
1459 } else {
1460 push @permvals, $permissions->{$_};
1461 }
1462 }
1463
1464 $sth = $dbh->prepare("INSERT INTO permissions (group_id,$permlist) values (?".',?'x($#permtypes+1).")");
1465 $sth->execute($groupid,@permvals);
1466
1467 $sth = $dbh->prepare("SELECT permission_id FROM permissions WHERE group_id=?");
1468 $sth->execute($groupid);
1469 my ($permid) = $sth->fetchrow_array();
1470
1471 $dbh->do("UPDATE groups SET permission_id=$permid WHERE group_id=$groupid");
1472 } # done permission fiddling
1473
1474# Default records
1475 my $sthf = $dbh->prepare("INSERT INTO default_records (group_id,host,type,val,distance,weight,port,ttl) ".
1476 "VALUES ($groupid,?,?,?,?,?,?,?)");
1477 my $sthr = $dbh->prepare("INSERT INTO default_rev_records (group_id,host,type,val,ttl) ".
1478 "VALUES ($groupid,?,?,?,?)");
1479 if ($inherit) {
1480 # Duplicate records from parent. Actually relying on inherited records feels
1481 # very fragile, and it would be problematic to roll over at a later time.
1482 my $sth2 = $dbh->prepare("SELECT host,type,val,distance,weight,port,ttl FROM default_records WHERE group_id=?");
1483 $sth2->execute($pargroup);
1484 while (my @clonedata = $sth2->fetchrow_array) {
1485 $sthf->execute(@clonedata);
1486 }
1487 # And now the reverse records
1488 $sth2 = $dbh->prepare("SELECT group_id,host,type,val,ttl FROM default_rev_records WHERE group_id=?");
1489 $sth2->execute($pargroup);
1490 while (my @clonedata = $sth2->fetchrow_array) {
1491 $sthr->execute(@clonedata);
1492 }
1493 } else {
1494##fixme: Hardcoding is Bad, mmmmkaaaay?
1495 # reasonable basic defaults for SOA, MX, NS, and minimal hosting
1496 # could load from a config file, but somewhere along the line we need hardcoded bits.
1497 $sthf->execute('ns1.example.com:hostmaster.example.com', 6, '10800:3600:604800:10800', 0, 0, 0, 86400);
1498 $sthf->execute('DOMAIN', 1, '192.168.4.2', 0, 0, 0, 7200);
1499 $sthf->execute('DOMAIN', 15, 'mx.example.com', 10, 0, 0, 7200);
1500 $sthf->execute('DOMAIN', 2, 'ns1.example.com', 0, 0, 0, 7200);
1501 $sthf->execute('DOMAIN', 2, 'ns2.example.com', 0, 0, 0, 7200);
1502 $sthf->execute('www.DOMAIN', 5, 'DOMAIN', 0, 0, 0, 7200);
1503 # reasonable basic defaults for generic reverse zone. Same as initial SQL tabledef.
1504 $sthr->execute('hostmaster.ADMINDOMAIN:ns1.ADMINDOMAIN', 6, '10800:3600:604800:10800', 86400);
1505 $sthr->execute('unused-%r.ADMINDOMAIN', 65283, 'ZONE', 3600);
1506 }
1507
1508 # once we get here, we should have suceeded.
1509 $dbh->commit;
1510 }; # end eval
1511
1512 if ($@) {
1513 my $msg = $@;
1514 eval { $dbh->rollback; };
1515 return ('FAIL',$msg);
1516 } else {
1517 return ('OK','OK');
1518 }
1519
1520} # end addGroup()
1521
1522
1523## DNSDB::delGroup()
1524# Delete a group.
1525# Takes a group ID
1526# Returns a status code and message
1527sub delGroup {
1528 my $dbh = shift;
1529 my $groupid = shift;
1530
1531 # Allow transactions, and raise an exception on errors so we can catch it later.
1532 # Use local to make sure these get "reset" properly on exiting this block
1533 local $dbh->{AutoCommit} = 0;
1534 local $dbh->{RaiseError} = 1;
1535
1536##fixme: locate "knowable" error conditions and deal with them before the eval
1537# ... or inside, whatever.
1538# -> domains still exist in group
1539# -> ...
1540 my $failmsg = '';
1541
1542 # Wrap all the SQL in a transaction
1543 eval {
1544 my $sth = $dbh->prepare("SELECT count(*) FROM domains WHERE group_id=?");
1545 $sth->execute($groupid);
1546 my ($domcnt) = $sth->fetchrow_array;
1547 $failmsg = "Can't remove group ".groupName($dbh,$groupid);
1548 die "$domcnt domains still in group\n" if $domcnt;
1549
1550 $sth = $dbh->prepare("delete from default_records where group_id=?");
1551 $failmsg = "Failed to delete default records for ".groupName($dbh,$groupid);
1552 $sth->execute($groupid);
1553 $sth = $dbh->prepare("delete from groups where group_id=?");
1554 $failmsg = "Failed to remove group ".groupName($dbh,$groupid);
1555 $sth->execute($groupid);
1556
1557 # once we get here, we should have suceeded.
1558 $dbh->commit;
1559 }; # end eval
1560
1561 if ($@) {
1562 my $msg = $@;
1563 eval { $dbh->rollback; };
1564 return ('FAIL',"$failmsg: $msg");
1565 } else {
1566 return ('OK','OK');
1567 }
1568} # end delGroup()
1569
1570
1571## DNSDB::getChildren()
1572# Get a list of all groups whose parent^n is group <n>
1573# Takes a database handle, group ID, reference to an array to put the group IDs in,
1574# and an optional flag to return only immediate children or all children-of-children
1575# default to returning all children
1576# Calls itself
1577sub getChildren {
1578 $errstr = '';
1579 my $dbh = shift;
1580 my $rootgroup = shift;
1581 my $groupdest = shift;
1582 my $immed = shift || 'all';
1583
1584 # special break for default group; otherwise we get stuck.
1585 if ($rootgroup == 1) {
1586 # by definition, group 1 is the Root Of All Groups
1587 my $sth = $dbh->prepare("SELECT group_id FROM groups WHERE NOT (group_id=1)".
1588 ($immed ne 'all' ? " AND parent_group_id=1" : ''));
1589 $sth->execute;
1590 while (my @this = $sth->fetchrow_array) {
1591 push @$groupdest, @this;
1592 }
1593 } else {
1594 my $sth = $dbh->prepare("SELECT group_id FROM groups WHERE parent_group_id=?");
1595 $sth->execute($rootgroup);
1596 return if $sth->rows == 0;
1597 my @grouplist;
1598 while (my ($group) = $sth->fetchrow_array) {
1599 push @$groupdest, $group;
1600 getChildren($dbh,$group,$groupdest) if $immed eq 'all';
1601 }
1602 }
1603} # end getChildren()
1604
1605
1606## DNSDB::groupName()
1607# Return the group name based on a group ID
1608# Takes a database handle and the group ID
1609# Returns the group name or undef on failure
1610sub groupName {
1611 $errstr = '';
1612 my $dbh = shift;
1613 my $groupid = shift;
1614 my $sth = $dbh->prepare("SELECT group_name FROM groups WHERE group_id=?");
1615 $sth->execute($groupid);
1616 my ($groupname) = $sth->fetchrow_array();
1617 $errstr = $DBI::errstr if !$groupname;
1618 return $groupname if $groupname;
1619} # end groupName
1620
1621
1622## DNSDB::groupID()
1623# Return the group ID based on the group name
1624# Takes a database handle and the group name
1625# Returns the group ID or undef on failure
1626sub groupID {
1627 $errstr = '';
1628 my $dbh = shift;
1629 my $group = shift;
1630 my ($grpid) = $dbh->selectrow_array("SELECT group_id FROM groups WHERE group=?", undef, ($group) );
1631 $errstr = $DBI::errstr if !$grpid;
1632 return $grpid if $grpid;
1633} # end groupID()
1634
1635
1636## DNSDB::addUser()
1637# Add a user.
1638# Takes a DB handle, username, group ID, password, state (active/inactive).
1639# Optionally accepts:
1640# user type (user/admin) - defaults to user
1641# permissions string - defaults to inherit from group
1642# three valid forms:
1643# i - Inherit permissions
1644# c:<user_id> - Clone permissions from <user_id>
1645# C:<permission list> - Set these specific permissions
1646# first name - defaults to username
1647# last name - defaults to blank
1648# phone - defaults to blank (could put other data within column def)
1649# Returns (OK,<uid>) on success, (FAIL,<message>) on failure
1650sub addUser {
1651 $errstr = '';
1652 my $dbh = shift;
1653 my $username = shift;
1654 my $group = shift;
1655 my $pass = shift;
1656 my $state = shift;
1657
1658 return ('FAIL', "Missing one or more required entries") if !defined($state);
1659 return ('FAIL', "Username must not be blank") if !$username;
1660
1661 my $type = shift || 'u'; # create limited users by default - fwiw, not sure yet how this will interact with ACLs
1662
1663 my $permstring = shift || 'i'; # default is to inhert permissions from group
1664
1665 my $fname = shift || $username;
1666 my $lname = shift || '';
1667 my $phone = shift || ''; # not going format-check
1668
1669 my $sth = $dbh->prepare("SELECT user_id FROM users WHERE username=?");
1670 my $user_id;
1671
1672# quick check to start to see if we've already got one
1673 $sth->execute($username);
1674 ($user_id) = $sth->fetchrow_array;
1675
1676 return ('FAIL', "User already exists") if $user_id;
1677
1678 # Allow transactions, and raise an exception on errors so we can catch it later.
1679 # Use local to make sure these get "reset" properly on exiting this block
1680 local $dbh->{AutoCommit} = 0;
1681 local $dbh->{RaiseError} = 1;
1682
1683 my $failmsg = '';
1684
1685 # Wrap all the SQL in a transaction
1686 eval {
1687 # insert the user... note we set inherited perms by default since
1688 # it's simple and cleans up some other bits of state
1689 my $sth = $dbh->prepare("INSERT INTO users ".
1690 "(group_id,username,password,firstname,lastname,phone,type,status,permission_id,inherit_perm) ".
1691 "VALUES (?,?,?,?,?,?,?,?,(SELECT permission_id FROM permissions WHERE group_id=?),'t')");
1692 $sth->execute($group,$username,unix_md5_crypt($pass),$fname,$lname,$phone,$type,$state,$group);
1693
1694 # get the ID...
1695 ($user_id) = $dbh->selectrow_array("SELECT currval('users_user_id_seq')");
1696
1697# Permissions! Gotta set'em all!
1698 die "Invalid permission string $permstring"
1699 if $permstring !~ /^(?:
1700 i # inherit
1701 |c:\d+ # clone
1702 # custom. no, the leading , is not a typo
1703 |C:(?:,(?:group|user|domain|record|self)_(?:edit|create|delete))*
1704 )$/x;
1705# bleh. I'd call another function to do my dirty work, but we're in the middle of a transaction already.
1706 if ($permstring ne 'i') {
1707 # for cloned or custom permissions, we have to create a new permissions entry.
1708 my $clonesrc = $group;
1709 if ($permstring =~ /^c:(\d+)/) { $clonesrc = $1; }
1710 $dbh->do("INSERT INTO permissions ($permlist,user_id) ".
1711 "SELECT $permlist,? FROM permissions WHERE permission_id=".
1712 "(SELECT permission_id FROM permissions WHERE ".($permstring =~ /^c:/ ? 'user' : 'group')."_id=?)",
1713 undef, ($user_id,$clonesrc) );
1714 $dbh->do("UPDATE users SET permission_id=".
1715 "(SELECT permission_id FROM permissions WHERE user_id=?) ".
1716 "WHERE user_id=?", undef, ($user_id, $user_id) );
1717 }
1718 if ($permstring =~ /^C:/) {
1719 # finally for custom permissions, we set the passed-in permissions (and unset
1720 # any that might have been brought in by the clone operation above)
1721 my ($permid) = $dbh->selectrow_array("SELECT permission_id FROM permissions WHERE user_id=?",
1722 undef, ($user_id) );
1723 foreach (@permtypes) {
1724 if ($permstring =~ /,$_/) {
1725 $dbh->do("UPDATE permissions SET $_='t' WHERE permission_id=?", undef, ($permid) );
1726 } else {
1727 $dbh->do("UPDATE permissions SET $_='f' WHERE permission_id=?", undef, ($permid) );
1728 }
1729 }
1730 }
1731
1732 $dbh->do("UPDATE users SET inherit_perm='n' WHERE user_id=?", undef, ($user_id) );
1733
1734##fixme: add another table to hold name/email for log table?
1735
1736 # once we get here, we should have suceeded.
1737 $dbh->commit;
1738 }; # end eval
1739
1740 if ($@) {
1741 my $msg = $@;
1742 eval { $dbh->rollback; };
1743 return ('FAIL',$msg." $failmsg");
1744 } else {
1745 return ('OK',$user_id);
1746 }
1747} # end addUser
1748
1749
1750## DNSDB::checkUser()
1751# Check user/pass combo on login
1752sub checkUser {
1753 my $dbh = shift;
1754 my $user = shift;
1755 my $inpass = shift;
1756
1757 my $sth = $dbh->prepare("SELECT user_id,group_id,password,firstname,lastname FROM users WHERE username=?");
1758 $sth->execute($user);
1759 my ($uid,$gid,$pass,$fname,$lname) = $sth->fetchrow_array;
1760 my $loginfailed = 1 if !defined($uid);
1761
1762 if ($pass =~ m|^\$1\$([A-Za-z0-9/.]+)\$|) {
1763 $loginfailed = 1 if $pass ne unix_md5_crypt($inpass,$1);
1764 } else {
1765 $loginfailed = 1 if $pass ne $inpass;
1766 }
1767
1768 # nnnngggg
1769 return ($uid, $gid);
1770} # end checkUser
1771
1772
1773## DNSDB:: updateUser()
1774# Update general data about user
1775sub updateUser {
1776 my $dbh = shift;
1777
1778##fixme: tweak calling convention so that we can update any given bit of data
1779 my $uid = shift;
1780 my $username = shift;
1781 my $group = shift;
1782 my $pass = shift;
1783 my $state = shift;
1784 my $type = shift || 'u';
1785 my $fname = shift || $username;
1786 my $lname = shift || '';
1787 my $phone = shift || ''; # not going format-check
1788
1789 my $failmsg = '';
1790
1791 # Allow transactions, and raise an exception on errors so we can catch it later.
1792 # Use local to make sure these get "reset" properly on exiting this block
1793 local $dbh->{AutoCommit} = 0;
1794 local $dbh->{RaiseError} = 1;
1795
1796 my $sth;
1797
1798 # Password can be left blank; if so we assume there's one on file.
1799 # Actual blank passwords are bad, mm'kay?
1800 if (!$pass) {
1801 $sth = $dbh->prepare("SELECT password FROM users WHERE user_id=?");
1802 $sth->execute($uid);
1803 ($pass) = $sth->fetchrow_array;
1804 } else {
1805 $pass = unix_md5_crypt($pass);
1806 }
1807
1808 eval {
1809 my $sth = $dbh->prepare(q(
1810 UPDATE users
1811 SET username=?, password=?, firstname=?, lastname=?, phone=?, type=?, status=?
1812 WHERE user_id=?
1813 )
1814 );
1815 $sth->execute($username, $pass, $fname, $lname, $phone, $type, $state, $uid);
1816 $dbh->commit;
1817 };
1818 if ($@) {
1819 my $msg = $@;
1820 eval { $dbh->rollback; };
1821 return ('FAIL',"$failmsg: $msg");
1822 } else {
1823 return ('OK','OK');
1824 }
1825} # end updateUser()
1826
1827
1828## DNSDB::delUser()
1829#
1830sub delUser {
1831 my $dbh = shift;
1832 return ('FAIL',"Need database handle") if !$dbh;
1833 my $userid = shift;
1834 return ('FAIL',"Missing userid") if !defined($userid);
1835
1836 my $sth = $dbh->prepare("delete from users where user_id=?");
1837 $sth->execute($userid);
1838
1839 return ('FAIL',"Couldn't remove user: ".$sth->errstr) if $sth->err;
1840
1841 return ('OK','OK');
1842
1843} # end delUser
1844
1845
1846## DNSDB::userFullName()
1847# Return a pretty string!
1848# Takes a user_id and optional printf-ish string to indicate which pieces where:
1849# %u for the username
1850# %f for the first name
1851# %l for the last name
1852# All other text in the passed string will be left as-is.
1853##fixme: need a "smart" option too, so that missing/null/blank first/last names don't give funky output
1854sub userFullName {
1855 $errstr = '';
1856 my $dbh = shift;
1857 my $userid = shift;
1858 my $fullformat = shift || '%f %l (%u)';
1859 my $sth = $dbh->prepare("select username,firstname,lastname from users where user_id=?");
1860 $sth->execute($userid);
1861 my ($uname,$fname,$lname) = $sth->fetchrow_array();
1862 $errstr = $DBI::errstr if !$uname;
1863
1864 $fullformat =~ s/\%u/$uname/g;
1865 $fullformat =~ s/\%f/$fname/g;
1866 $fullformat =~ s/\%l/$lname/g;
1867
1868 return $fullformat;
1869} # end userFullName
1870
1871
1872## DNSDB::userStatus()
1873# Sets and/or returns a user's status
1874# Takes a database handle, user ID and optionally a status argument
1875# Returns undef on errors.
1876sub userStatus {
1877 my $dbh = shift;
1878 my $id = shift;
1879 my $newstatus = shift;
1880
1881 return undef if $id !~ /^\d+$/;
1882
1883 my $sth;
1884
1885# ooo, fun! let's see what we were passed for status
1886 if ($newstatus) {
1887 $sth = $dbh->prepare("update users set status=? where user_id=?");
1888 # ass-u-me caller knows what's going on in full
1889 if ($newstatus =~ /^[01]$/) { # only two valid for now.
1890 $sth->execute($newstatus,$id);
1891 } elsif ($newstatus =~ /^usero(?:n|ff)$/) {
1892 $sth->execute(($newstatus eq 'useron' ? 1 : 0),$id);
1893 }
1894 }
1895
1896 $sth = $dbh->prepare("select status from users where user_id=?");
1897 $sth->execute($id);
1898 my ($status) = $sth->fetchrow_array;
1899 return $status;
1900} # end userStatus()
1901
1902
1903## DNSDB::getUserData()
1904# Get misc user data for display
1905sub getUserData {
1906 my $dbh = shift;
1907 my $uid = shift;
1908
1909 my $sth = $dbh->prepare("SELECT group_id,username,firstname,lastname,phone,type,status,inherit_perm ".
1910 "FROM users WHERE user_id=?");
1911 $sth->execute($uid);
1912 return $sth->fetchrow_hashref();
1913
1914} # end getUserData()
1915
1916
1917## DNSDB::getSOA()
1918# Return all suitable fields from an SOA record in separate elements of a hash
1919# Takes a database handle, default/live flag, domain/reverse flag, and parent ID
1920sub getSOA {
1921 $errstr = '';
1922 my $dbh = shift;
1923 my $def = shift;
1924 my $rev = shift;
1925 my $id = shift;
1926 my %ret;
1927
1928 # (ab)use distance and weight columns to store SOA data? can't for default_rev_records...
1929 # - should really attach serial to the zone parent somewhere
1930
1931 my $sql = "SELECT record_id,host,val,ttl from "._rectable($def,$rev).
1932 " WHERE "._recparent($def,$rev)." = ? AND type=$reverse_typemap{SOA}";
1933
1934 my $sth = $dbh->prepare($sql);
1935 $sth->execute($id);
1936##fixme: stick a flag somewhere if the record doesn't exist. by the API, this is an impossible case, but...
1937
1938 my ($recid,$host,$val,$ttl) = $sth->fetchrow_array() or return;
1939 my ($contact,$prins) = split /:/, $host;
1940 my ($refresh,$retry,$expire,$minttl) = split /:/, $val;
1941
1942 $ret{recid} = $recid;
1943 $ret{ttl} = $ttl;
1944# $ret{serial} = $serial; # ca't use distance for serial with default_rev_records
1945 $ret{prins} = $prins;
1946 $ret{contact} = $contact;
1947 $ret{refresh} = $refresh;
1948 $ret{retry} = $retry;
1949 $ret{expire} = $expire;
1950 $ret{minttl} = $minttl;
1951
1952 return %ret;
1953} # end getSOA()
1954
1955
1956## DNSDB::updateSOA()
1957# Update the specified SOA record
1958# Takes a database handle, default/live flag, forward/reverse flag, and SOA data hash
1959sub updateSOA {
1960 my $dbh = shift;
1961 my $defrec = shift;
1962 my $revrec = shift;
1963
1964 my %soa = @_;
1965
1966##fixme: data validation: make sure {recid} is really the SOA for {parent}
1967 my $sql = "UPDATE "._rectable($defrec, $revrec)." SET host=?, val=?, ttl=? WHERE record_id=? AND type=6";
1968 $dbh->do($sql, undef, ("$soa{contact}:$soa{prins}", "$soa{refresh}:$soa{retry}:$soa{expire}:$soa{minttl}",
1969 $soa{ttl}, $soa{recid}));
1970
1971} # end updateSOA()
1972
1973
1974## DNSDB::getRecLine()
1975# Return all data fields for a zone record in separate elements of a hash
1976# Takes a database handle, default/live flag, forward/reverse flag, and record ID
1977sub getRecLine {
1978 $errstr = '';
1979 my $dbh = shift;
1980 my $defrec = shift;
1981 my $revrec = shift;
1982 my $id = shift;
1983
1984 my $sql = "SELECT record_id,host,type,val,ttl".($revrec eq 'n' ? ',distance,weight,port' : '').
1985 (($defrec eq 'y') ? ',group_id FROM ' : ',domain_id,rdns_id FROM ').
1986 _rectable($defrec,$revrec)." WHERE record_id=?";
1987 my $ret = $dbh->selectrow_hashref($sql, undef, ($id) );
1988
1989 if ($dbh->err) {
1990 $errstr = $DBI::errstr;
1991 return undef;
1992 }
1993
1994 if (!$ret) {
1995 $errstr = "No such record";
1996 return undef;
1997 }
1998
1999 # explicitly set a parent id
2000 if ($defrec eq 'y') {
2001 $ret->{parid} = $ret->{group_id};
2002 } else {
2003 $ret->{parid} = (($revrec eq 'n') ? $ret->{domain_id} : $ret->{rdns_id});
2004 # and a secondary if we have a custom type that lives in both a forward and reverse zone
2005 $ret->{secid} = (($revrec eq 'y') ? $ret->{domain_id} : $ret->{rdns_id}) if $ret->{type} > 65279;
2006 }
2007
2008 return $ret;
2009}
2010
2011
2012##fixme: should use above (getRecLine()) to get lines for below?
2013## DNSDB::getDomRecs()
2014# Return records for a domain
2015# Takes a database handle, default/live flag, group/domain ID, start,
2016# number of records, sort field, and sort order
2017# Returns a reference to an array of hashes
2018sub getDomRecs {
2019 $errstr = '';
2020 my $dbh = shift;
2021 my $def = shift;
2022 my $rev = shift;
2023 my $id = shift;
2024 my $nrecs = shift || 'all';
2025 my $nstart = shift || 0;
2026
2027## for order, need to map input to column names
2028 my $order = shift || 'host';
2029 my $direction = shift || 'ASC';
2030
2031 my $filter = shift || '';
2032
2033 my $sql = "SELECT r.record_id,r.host,r.type,r.val,r.ttl";
2034 $sql .= ",r.distance,r.weight,r.port" if $rev eq 'n';
2035 $sql .= " FROM "._rectable($def,$rev)." r ";
2036
2037 # whee! multisort means just passing comma-separated fields in sortby!
2038 my $newsort = '';
2039 foreach my $sf (split /,/, $order) {
2040 $sf = "r.$sf";
2041 $sf =~ s/r\.type/t.alphaorder/;
2042 $newsort .= ",$sf";
2043 }
2044 $newsort =~ s/^,//;
2045
2046 $sql .= "INNER JOIN rectypes t ON r.type=t.val "; # for sorting by type alphabetically
2047 $sql .= "WHERE "._recparent($def,$rev)." = ?";
2048 $sql .= " AND NOT r.type=$reverse_typemap{SOA}";
2049 $sql .= " AND host ~* ?" if $filter;
2050 # use alphaorder column for "correct" ordering of sort-by-type instead of DNS RR type number
2051 $sql .= " ORDER BY $newsort $direction";
2052
2053 my @bindvars = ($id);
2054 push @bindvars, $filter if $filter;
2055
2056 # just to be ultraparanoid about SQL injection vectors
2057 if ($nstart ne 'all') {
2058 $sql .= " LIMIT ? OFFSET ?";
2059 push @bindvars, $nrecs;
2060 push @bindvars, ($nstart*$nrecs);
2061 }
2062 my $sth = $dbh->prepare($sql) or warn $dbh->errstr;
2063 $sth->execute(@bindvars) or warn "$sql: ".$sth->errstr;
2064
2065 my @retbase;
2066 while (my $ref = $sth->fetchrow_hashref()) {
2067 push @retbase, $ref;
2068 }
2069
2070 my $ret = \@retbase;
2071 return $ret;
2072} # end getDomRecs()
2073
2074
2075## DNSDB::getRecCount()
2076# Return count of non-SOA records in zone (or default records in a group)
2077# Takes a database handle, default/live flag, reverse/forward flag, group/domain ID,
2078# and optional filtering modifier
2079# Returns the count
2080sub getRecCount {
2081 my $dbh = shift;
2082 my $defrec = shift;
2083 my $revrec = shift;
2084 my $id = shift;
2085 my $filter = shift || '';
2086
2087 # keep the nasties down, since we can't ?-sub this bit. :/
2088 # note this is chars allowed in DNS hostnames
2089 $filter =~ s/[^a-zA-Z0-9_.:-]//g;
2090
2091 my @bindvars = ($id);
2092 push @bindvars, $filter if $filter;
2093 my $sql = "SELECT count(*) FROM ".
2094 _rectable($defrec,$revrec).
2095 " WHERE "._recparent($defrec,$revrec)."=? ".
2096 "AND NOT type=$reverse_typemap{SOA}".
2097 ($filter ? " AND host ~* ?" : '');
2098 my ($count) = $dbh->selectrow_array($sql, undef, (@bindvars) );
2099
2100 return $count;
2101
2102} # end getRecCount()
2103
2104
2105## DNSDB::addRec()
2106# Add a new record to a domain or a group's default records
2107# Takes a database handle, default/live flag, group/domain ID,
2108# host, type, value, and TTL
2109# Some types require additional detail: "distance" for MX and SRV,
2110# and weight/port for SRV
2111# Returns a status code and detail message in case of error
2112##fixme: pass a hash with the record data, not a series of separate values
2113sub addRec {
2114 $errstr = '';
2115 my $dbh = shift;
2116 my $defrec = shift;
2117 my $revrec = shift;
2118 my $id = shift; # parent (group_id for defrecs, rdns_id for reverse records,
2119 # domain_id for domain records)
2120
2121 my $host = shift;
2122 my $rectype = shift; # reference so we can coerce it if "+"-types can't find both zones
2123 my $val = shift;
2124 my $ttl = shift;
2125
2126 # Spaces are evil.
2127 $host =~ s/^\s+//;
2128 $host =~ s/\s+$//;
2129 if ($typemap{$rectype} ne 'TXT') {
2130 # Leading or trailng spaces could be legit in TXT records.
2131 $val =~ s/^\s+//;
2132 $val =~ s/\s+$//;
2133 }
2134
2135 # Validation
2136 my $addr = NetAddr::IP->new($val);
2137 if ($rectype == $reverse_typemap{A}) {
2138 return ('FAIL',$typemap{$rectype}." record must be a valid IPv4 address")
2139 unless $addr && !$addr->{isv6};
2140 }
2141 if ($rectype == $reverse_typemap{AAAA}) {
2142 return ('FAIL',$typemap{$rectype}." record must be a valid IPv6 address")
2143 unless $addr && $addr->{isv6};
2144 }
2145
2146 my $domid = 0;
2147 my $revid = 0;
2148
2149 my $retcode = 'OK'; # assume everything will go OK
2150 my $retmsg = '';
2151
2152 # do simple validation first
2153 return ('FAIL', "TTL must be numeric") unless $ttl =~ /^\d+$/;
2154
2155 # Quick check on hostname parts. Note the regex is more forgiving than the error message;
2156 # domain names technically are case-insensitive, and we use printf-like % codes for a couple
2157 # of types. Other things may also be added to validate default records of several flavours.
2158 return ('FAIL', "Hostnames may not contain anything other than (0-9 a-z . _)")
2159 if $defrec eq 'n' && $$host !~ /^[0-9a-z_%.]+$/i;
2160
2161 # Collect these even if we're only doing a simple A record so we can call *any* validation sub
2162 my $dist = shift;
2163 my $port = shift;
2164 my $weight = shift;
2165
2166 my $fields;
2167 my @vallist;
2168
2169 # Call the validation sub for the type requested.
2170 ($retcode,$retmsg) = $validators{$$rectype}($dbh, (defrec => $defrec, revrec => $revrec, id => $id,
2171 host => $host, rectype => $rectype, val => $val, addr => $addr,
2172 dist => \$dist, port => \$port, weight => \$weight,
2173 fields => \$fields, vallist => \@vallist) );
2174
2175 return ($retcode,$retmsg) if $retcode eq 'FAIL';
2176
2177 # Set up database fields and bind parameters
2178 $fields .= "host,type,val,ttl,"._recparent($defrec,$revrec);
2179 push @vallist, ($$host,$$rectype,$$val,$ttl,$id);
2180 my $vallen = '?'.(',?'x$#vallist);
2181
2182 # Allow transactions, and raise an exception on errors so we can catch it later.
2183 # Use local to make sure these get "reset" properly on exiting this block
2184 local $dbh->{AutoCommit} = 0;
2185 local $dbh->{RaiseError} = 1;
2186
2187 eval {
2188 $dbh->do("INSERT INTO "._rectable($defrec, $revrec)." ($fields) VALUES ($vallen)",
2189 undef, @vallist);
2190 $dbh->commit;
2191 };
2192 if ($@) {
2193 my $msg = $@;
2194 eval { $dbh->rollback; };
2195 return ('FAIL',$msg);
2196 }
2197
2198 return ($retcode, $retmsg);
2199
2200} # end addRec()
2201
2202
2203## DNSDB::updateRec()
2204# Update a record
2205sub updateRec {
2206 $errstr = '';
2207
2208 my $dbh = shift;
2209 my $defrec = shift;
2210 my $id = shift;
2211
2212# all records have these
2213 my $host = shift;
2214 my $type = shift;
2215 my $val = shift;
2216 my $ttl = shift;
2217
2218 return('FAIL',"Missing standard argument(s)") if !defined($ttl);
2219
2220 # Spaces are evil.
2221 $host =~ s/^\s+//;
2222 $host =~ s/\s+$//;
2223 if ($typemap{$type} ne 'TXT') {
2224 # Leading or trailng spaces could be legit in TXT records.
2225 $val =~ s/^\s+//;
2226 $val =~ s/\s+$//;
2227 }
2228
2229# only MX and SRV will use these
2230 my $dist = 0;
2231 my $weight = 0;
2232 my $port = 0;
2233
2234 if ($type == $reverse_typemap{MX} || $type == $reverse_typemap{SRV}) {
2235 $dist = shift;
2236 $dist =~ s/\s+//g;
2237 return ('FAIL',"MX or SRV requires distance") if !defined($dist);
2238 return ('FAIL', "Distance must be numeric") unless $dist =~ /^\d+$/;
2239 if ($type == $reverse_typemap{SRV}) {
2240 $weight = shift;
2241 $weight =~ s/\s+//g;
2242 return ('FAIL',"SRV requires weight") if !defined($weight);
2243 return ('FAIL',"Weight must be numeric") unless $weight =~ /^\d+$/;
2244 $port = shift;
2245 $port =~ s/\s+//g;
2246 return ('FAIL',"SRV requires port") if !defined($port);
2247 return ('FAIL',"Port must be numeric") unless $port =~ /^\d+$/;
2248 }
2249 }
2250
2251# Enforce IP addresses on A and AAAA types
2252 my $addr = NetAddr::IP->new($val);
2253 if ($type == $reverse_typemap{A}) {
2254 return ('FAIL',$typemap{$type}." record must be a valid IPv4 address")
2255 unless $addr && !$addr->{isv6};
2256 }
2257 if ($type == $reverse_typemap{AAAA}) {
2258 return ('FAIL',$typemap{$type}." record must be a valid IPv6 address")
2259 unless $addr && $addr->{isv6};
2260 }
2261
2262# hmm.. this might work. except possibly for something pointing to "deadbeef.ca". <g>
2263# if ($type == $reverse_typemap{NS} || $type == $reverse_typemap{MX} || $type == $reverse_typemap{SRV}) {
2264# if ($val =~ /^\s*[\da-f:.]+\s*$/) {
2265# return ('FAIL',"$val is not a valid IP address") if !$addr;
2266# }
2267# }
2268
2269 local $dbh->{AutoCommit} = 0;
2270 local $dbh->{RaiseError} = 1;
2271
2272 eval {
2273 $dbh->do("UPDATE ".($defrec eq 'y' ? 'default_' : '')."records ".
2274 "SET host=?,val=?,type=?,ttl=?,distance=?,weight=?,port=? ".
2275 "WHERE record_id=?", undef, ($host, $val, $type, $ttl, $dist, $weight, $port, $id) );
2276 $dbh->commit;
2277 };
2278 if ($@) {
2279 my $msg = $@;
2280 $dbh->rollback;
2281 return ('FAIL', $msg);
2282 }
2283
2284 return ('OK','OK');
2285} # end updateRec()
2286
2287
2288## DNSDB::delRec()
2289# Delete a record.
2290sub delRec {
2291 $errstr = '';
2292 my $dbh = shift;
2293 my $defrec = shift;
2294 my $revrec = shift;
2295 my $id = shift;
2296
2297 my $sth = $dbh->prepare("DELETE FROM "._rectable($defrec,$revrec)." WHERE record_id=?");
2298 $sth->execute($id);
2299
2300 return ('FAIL',"Couldn't remove record: ".$sth->errstr) if $sth->err;
2301
2302 return ('OK','OK');
2303} # end delRec()
2304
2305
2306 # Reference hashes.
2307my %par_tbl = (
2308 group => 'groups',
2309 user => 'users',
2310 defrec => 'default_records',
2311 defrevrec => 'default_rev_records',
2312 domain => 'domains',
2313 revzone => 'revzones',
2314 record => 'records'
2315 );
2316my %id_col = (
2317 group => 'group_id',
2318 user => 'user_id',
2319 defrec => 'record_id',
2320 defrevrec => 'record_id',
2321 domain => 'domain_id',
2322 revzone => 'rdns_id',
2323 record => 'record_id'
2324 );
2325my %par_col = (
2326 group => 'parent_group_id',
2327 user => 'group_id',
2328 defrec => 'group_id',
2329 defrevrec => 'group_id',
2330 domain => 'group_id',
2331 revzone => 'group_id',
2332 record => 'domain_id'
2333 );
2334my %par_type = (
2335 group => 'group',
2336 user => 'group',
2337 defrec => 'group',
2338 defrevrec => 'group',
2339 domain => 'group',
2340 revzone => 'group',
2341 record => 'domain'
2342 );
2343
2344
2345## DNSDB::getTypelist()
2346# Get a list of record types for various UI dropdowns
2347# Takes database handle, forward/reverse/lookup flag, and optional "tag as selected" indicator (defaults to A)
2348# Returns an arrayref to list of hashrefs perfect for HTML::Template
2349sub getTypelist {
2350 my $dbh = shift;
2351 my $recgroup = shift;
2352 my $type = shift || $reverse_typemap{A};
2353
2354 # also accepting $webvar{revrec}!
2355 $recgroup = 'f' if $recgroup eq 'n';
2356 $recgroup = 'r' if $recgroup eq 'y';
2357
2358 my $sql = "SELECT val,name FROM rectypes WHERE ";
2359 if ($recgroup eq 'r') {
2360 # reverse zone types
2361 $sql .= "stdflag=2 OR stdflag=3";
2362 } elsif ($recgroup eq 'l') {
2363 # DNS lookup types. Note we avoid our custom types >= 65280, since those are entirely internal.
2364 $sql .= "(stdflag=1 OR stdflag=2 OR stdflag=3) AND val < 65280";
2365 } else {
2366 # default; forward zone types. technically $type eq 'f' but not worth the error message.
2367 $sql .= "stdflag=1 OR stdflag=2";
2368 }
2369 $sql .= " ORDER BY listorder";
2370
2371 my $sth = $dbh->prepare($sql);
2372 $sth->execute;
2373 my @typelist;
2374 while (my ($rval,$rname) = $sth->fetchrow_array()) {
2375 my %row = ( recval => $rval, recname => $rname );
2376 $row{tselect} = 1 if $rval == $type;
2377 push @typelist, \%row;
2378 }
2379
2380 # Add SOA on lookups since it's not listed in other dropdowns.
2381 if ($recgroup eq 'l') {
2382 my %row = ( recval => $reverse_typemap{SOA}, recname => 'SOA' );
2383 $row{tselect} = 1 if $reverse_typemap{SOA} == $type;
2384 push @typelist, \%row;
2385 }
2386
2387 return \@typelist;
2388} # end getTypelist()
2389
2390
2391## DNSDB::parentID()
2392# Get ID of entity that is nearest parent to requested id
2393# Takes a database handle and a hash of entity ID, entity type, optional parent type flag
2394# (domain/reverse zone or group), and optional default/live and forward/reverse flags
2395# Returns the ID or undef on failure
2396sub parentID {
2397 my $dbh = shift;
2398
2399 my %args = @_;
2400
2401 # clean up the parent-type. Set it to group if not set; coerce revzone to domain for simpler logic
2402 $args{partype} = 'group' if !$args{partype};
2403 $args{partype} = 'domain' if $args{partype} eq 'revzone';
2404
2405 # clean up defrec and revrec. default to live record, forward zone
2406 $args{defrec} = 'n' if !$args{defrec};
2407 $args{revrec} = 'n' if !$args{revrec};
2408
2409 if ($par_type{$args{partype}} eq 'domain') {
2410 # only live records can have a domain/zone parent
2411 return unless ($args{type} eq 'record' && $args{defrec} eq 'n');
2412 my $result = $dbh->selectrow_hashref("SELECT ".($args{revrec} eq 'n' ? 'domain_id' : 'rdns_id').
2413 " FROM records WHERE record_id = ?",
2414 undef, ($args{id}) ) or return;
2415 return $result;
2416 } else {
2417 # snag some arguments that will either fall through or be overwritten to save some code duplication
2418 my $tmpid = $args{id};
2419 my $type = $args{type};
2420 if ($type eq 'record' && $args{defrec} eq 'n') {
2421 # Live records go through the records table first.
2422 ($tmpid) = $dbh->selectrow_array("SELECT ".($args{revrec} eq 'n' ? 'domain_id' : 'rdns_id').
2423 " FROM records WHERE record_id = ?",
2424 undef, ($args{id}) ) or return;
2425 $type = ($args{revrec} eq 'n' ? 'domain' : 'revzone');
2426 }
2427 my ($result) = $dbh->selectrow_array("SELECT $par_col{$type} FROM $par_tbl{$type} WHERE $id_col{$type} = ?",
2428 undef, ($tmpid) );
2429 return $result;
2430 }
2431# should be impossible to get here with even remotely sane arguments
2432 return;
2433} # end parentID()
2434
2435
2436## DNSDB::isParent()
2437# Returns true if $id1 is a parent of $id2, false otherwise
2438sub isParent {
2439 my $dbh = shift;
2440 my $id1 = shift;
2441 my $type1 = shift;
2442 my $id2 = shift;
2443 my $type2 = shift;
2444##todo: immediate, secondary, full (default)
2445
2446 # Return false on invalid types
2447 return 0 if !grep /^$type1$/, ('record','defrec','defrevrec','user','domain','revzone','group');
2448 return 0 if !grep /^$type2$/, ('record','defrec','defrevrec','user','domain','revzone','group');
2449
2450 # Return false on impossible relations
2451 return 0 if $type1 eq 'record'; # nothing may be a child of a record
2452 return 0 if $type1 eq 'defrec'; # nothing may be a child of a record
2453 return 0 if $type1 eq 'defrevrec'; # nothing may be a child of a record
2454 return 0 if $type1 eq 'user'; # nothing may be child of a user
2455 return 0 if $type1 eq 'domain' && $type2 ne 'record'; # domain may not be a parent of anything other than a record
2456 return 0 if $type1 eq 'revzone' && $type2 ne 'record';# reverse zone may not be a parent of anything other than a record
2457
2458 # ennnhhhh.... if we're passed an id of 0, it will never be found. usual
2459 # case would be the UI creating a new <thing>, and so we don't have an ID for
2460 # <thing> to look up yet. in that case the UI should check the parent as well.
2461 return 0 if $id1 == 0; # nothing can have a parent id of 0
2462 return 1 if $id2 == 0; # anything could have a child id of 0 (or "unknown")
2463
2464 # group 1 is the ultimate root parent
2465 return 1 if $type1 eq 'group' && $id1 == 1;
2466
2467 # groups are always (a) parent of themselves
2468 return 1 if $type1 eq 'group' && $type2 eq 'group' && $id1 == $id2;
2469
2470 my $id = $id2;
2471 my $type = $type2;
2472 my $foundparent = 0;
2473
2474 # Records are the only entity with two possible parents. We need to split the parent checks on
2475 # domain/rdns.
2476 if ($type eq 'record') {
2477 my ($dom,$rdns) = $dbh->selectrow_array("SELECT domain_id,rdns_id FROM records WHERE record_id=?",
2478 undef, ($id));
2479 # check immediate parent against request
2480 return 1 if $type1 eq 'domain' && $id1 == $dom;
2481 return 1 if $type1 eq 'revzone' && $id1 == $rdns;
2482 # if request is group, check *both* parents. Only check if the parent is nonzero though.
2483 return 1 if $dom && isParent($dbh, $id1, $type1, $dom, 'domain');
2484 return 1 if $rdns && isParent($dbh, $id1, $type1, $rdns, 'revzone');
2485 # exit here since we've executed the loop below by proxy in the above recursive calls.
2486 return 0;
2487 }
2488
2489# almost the same loop as getParents() above
2490 my $limiter = 0;
2491 while (1) {
2492 my $sql = "SELECT $par_col{$type} FROM $par_tbl{$type} WHERE $id_col{$type} = ?";
2493 my $result = $dbh->selectrow_hashref($sql,
2494 undef, ($id) );
2495 if (!$result) {
2496 $limiter++;
2497##fixme: how often will this happen on a live site? fail at max limiter <n>?
2498 warn "no results looking for $sql with id $id (depth $limiter)\n";
2499 last;
2500 }
2501 if ($result && $result->{$par_col{$type}} == $id1) {
2502 $foundparent = 1;
2503 last;
2504 } else {
2505##fixme: do we care about trying to return a "no such record/domain/user/group" error?
2506# should be impossible to create an inconsistent DB just with API calls.
2507 warn $dbh->errstr." $sql, $id" if $dbh->errstr;
2508 }
2509 # group 1 is its own parent. need this here more to break strange loops than for detecting a parent
2510 last if $result->{$par_col{$type}} == 1;
2511 $id = $result->{$par_col{$type}};
2512 $type = $par_type{$type};
2513 }
2514
2515 return $foundparent;
2516} # end isParent()
2517
2518
2519## DNSDB::domStatus()
2520# Sets and/or returns a domain's status
2521# Takes a database handle, domain ID and optionally a status argument
2522# Returns undef on errors.
2523sub domStatus {
2524 my $dbh = shift;
2525 my $id = shift;
2526 my $newstatus = shift;
2527
2528 return undef if $id !~ /^\d+$/;
2529
2530 my $sth;
2531
2532# ooo, fun! let's see what we were passed for status
2533 if ($newstatus) {
2534 $sth = $dbh->prepare("update domains set status=? where domain_id=?");
2535 # ass-u-me caller knows what's going on in full
2536 if ($newstatus =~ /^[01]$/) { # only two valid for now.
2537 $sth->execute($newstatus,$id);
2538 } elsif ($newstatus =~ /^domo(?:n|ff)$/) {
2539 $sth->execute(($newstatus eq 'domon' ? 1 : 0),$id);
2540 }
2541 }
2542
2543 $sth = $dbh->prepare("select status from domains where domain_id=?");
2544 $sth->execute($id);
2545 my ($status) = $sth->fetchrow_array;
2546 return $status;
2547} # end domStatus()
2548
2549
2550## DNSDB::importAXFR
2551# Import a domain via AXFR
2552# Takes AXFR host, domain to transfer, group to put the domain in,
2553# and optionally:
2554# - active/inactive state flag (defaults to active)
2555# - overwrite-SOA flag (defaults to off)
2556# - overwrite-NS flag (defaults to off, doesn't affect subdomain NS records)
2557# Returns a status code (OK, WARN, or FAIL) and message - message should be blank
2558# if status is OK, but WARN includes conditions that are not fatal but should
2559# really be reported.
2560sub importAXFR {
2561 my $dbh = shift;
2562 my $ifrom_in = shift;
2563 my $domain = shift;
2564 my $group = shift;
2565 my $status = shift;
2566 $status = (defined($status) ? $status : 0); # force sane semantics, and allow passing "null" (inactive) status
2567 my $rwsoa = shift || 0;
2568 my $rwns = shift || 0;
2569 my $newttl = shift;
2570
2571##fixme: add mode to delete&replace, merge+overwrite, merge new?
2572
2573 my $nrecs = 0;
2574 my $soaflag = 0;
2575 my $nsflag = 0;
2576 my $warnmsg = '';
2577 my $ifrom;
2578
2579 # choke on possible bad setting in ifrom
2580 # IPv4 and v6, and valid hostnames!
2581 ($ifrom) = ($ifrom_in =~ /^([0-9a-f\:.]+|[0-9a-z_.-]+)$/i);
2582 return ('FAIL', "Bad AXFR source host $ifrom")
2583 unless ($ifrom) = ($ifrom_in =~ /^([0-9a-f\:.]+|[0-9a-z_.-]+)$/i);
2584
2585 # Allow transactions, and raise an exception on errors so we can catch it later.
2586 # Use local to make sure these get "reset" properly on exiting this block
2587 local $dbh->{AutoCommit} = 0;
2588 local $dbh->{RaiseError} = 1;
2589
2590 my $sth = $dbh->prepare("SELECT domain_id FROM domains WHERE domain=?");
2591 my $dom_id;
2592
2593# quick check to start to see if we've already got one
2594 $sth->execute($domain);
2595 ($dom_id) = $sth->fetchrow_array;
2596
2597 return ('FAIL', "Domain already exists") if $dom_id;
2598
2599 eval {
2600 # can't do this, can't nest transactions. sigh.
2601 #my ($dcode, $dmsg) = addDomain(dbh, domain, group, status);
2602
2603##fixme: serial
2604 my $sth = $dbh->prepare("INSERT INTO domains (domain,group_id,status) VALUES (?,?,?)");
2605 $sth->execute($domain,$group,$status);
2606
2607## bizarre DBI<->Net::DNS interaction bug:
2608## sometimes a zone will cause an immediate commit-and-exit (sort of) of the while()
2609## fixed, apparently I was doing *something* odd, but not certain what it was that
2610## caused a commit instead of barfing
2611
2612 # get domain id so we can do the records
2613 $sth = $dbh->prepare("SELECT domain_id FROM domains WHERE domain=?");
2614 $sth->execute($domain);
2615 ($dom_id) = $sth->fetchrow_array();
2616
2617 my $res = Net::DNS::Resolver->new;
2618 $res->nameservers($ifrom);
2619 $res->axfr_start($domain)
2620 or die "Couldn't begin AXFR\n";
2621
2622 while (my $rr = $res->axfr_next()) {
2623 my $type = $rr->type;
2624 my $ttl = ($newttl ? $newttl : $rr->ttl); # allow force-override TTLs
2625
2626 my $sql = "INSERT INTO records (domain_id,host,type,ttl,val";
2627 my $vallen = "?,?,?,?,?";
2628
2629 $soaflag = 1 if $type eq 'SOA';
2630 $nsflag = 1 if $type eq 'NS';
2631
2632 my @vallist = ($dom_id, $rr->name, $reverse_typemap{$type}, $ttl);
2633
2634# "Primary" types:
2635# A, NS, CNAME, SOA, PTR(warn in forward), MX, TXT, AAAA, SRV, A6(ob), SPF
2636# maybe KEY
2637
2638# nasty big ugly case-like thing here, since we have to do *some* different
2639# processing depending on the record. le sigh.
2640
2641##fixme: what record types other than TXT can/will have >255-byte payloads?
2642
2643 if ($type eq 'A') {
2644 push @vallist, $rr->address;
2645 } elsif ($type eq 'NS') {
2646# hmm. should we warn here if subdomain NS'es are left alone?
2647 next if ($rwns && ($rr->name eq $domain));
2648 push @vallist, $rr->nsdname;
2649 $nsflag = 1;
2650 } elsif ($type eq 'CNAME') {
2651 push @vallist, $rr->cname;
2652 } elsif ($type eq 'SOA') {
2653 next if $rwsoa;
2654 $vallist[1] = $rr->mname.":".$rr->rname;
2655 push @vallist, ($rr->refresh.":".$rr->retry.":".$rr->expire.":".$rr->minimum);
2656 $soaflag = 1;
2657 } elsif ($type eq 'PTR') {
2658 push @vallist, $rr->ptrdname;
2659 # hmm. PTR records should not be in forward zones.
2660 } elsif ($type eq 'MX') {
2661 $sql .= ",distance";
2662 $vallen .= ",?";
2663 push @vallist, $rr->exchange;
2664 push @vallist, $rr->preference;
2665 } elsif ($type eq 'TXT') {
2666##fixme: Net::DNS docs say this should be deprecated for rdatastr() or char_str_list(),
2667## but don't really seem enthusiastic about it.
2668 my $rrdata = $rr->txtdata;
2669 push @vallist, $rrdata;
2670 } elsif ($type eq 'SPF') {
2671##fixme: and the same caveat here, since it is apparently a clone of ::TXT
2672 my $rrdata = $rr->txtdata;
2673 push @vallist, $rrdata;
2674 } elsif ($type eq 'AAAA') {
2675 push @vallist, $rr->address;
2676 } elsif ($type eq 'SRV') {
2677 $sql .= ",distance,weight,port" if $type eq 'SRV';
2678 $vallen .= ",?,?,?" if $type eq 'SRV';
2679 push @vallist, $rr->target;
2680 push @vallist, $rr->priority;
2681 push @vallist, $rr->weight;
2682 push @vallist, $rr->port;
2683 } elsif ($type eq 'KEY') {
2684 # we don't actually know what to do with these...
2685 push @vallist, ($rr->flags.":".$rr->protocol.":".$rr->algorithm.":".$rr->key.":".$rr->keytag.":".$rr->privatekeyname);
2686 } else {
2687 my $rrdata = $rr->rdatastr;
2688 push @vallist, $rrdata;
2689 # Finding a different record type is not fatal.... just problematic.
2690 # We may not be able to export it correctly.
2691 $warnmsg .= "Unusual record ".$rr->name." ($type) found\n";
2692 }
2693
2694# BIND supports:
2695# A CNAME HINFO MB(ex) MD(ob) MF(ob) MG(ex) MINFO(ex) MR(ex) MX NS NULL
2696# PTR SOA TXT WKS AFSDB(ex) ISDN(ex) RP(ex) RT(ex) X25(ex) PX
2697# ... if one can ever find the right magic to format them correctly
2698
2699# Net::DNS supports:
2700# RRSIG SIG NSAP NS NIMLOC NAPTR MX MR MINFO MG MB LOC ISDN IPSECKEY HINFO
2701# EID DNAME CNAME CERT APL AFSDB AAAA A DS NXT NSEC3PARAM NSEC3 NSEC KEY
2702# DNSKEY DLV X25 TXT TSIG TKEY SSHFP SRV SPF SOA RT RP PX PTR NULL APL::AplItem
2703
2704 $sth = $dbh->prepare($sql.") VALUES (".$vallen.")") or die "problem preparing record insert SQL\n";
2705 $sth->execute(@vallist) or die "failed to insert ".$rr->string.": ".$sth->errstr."\n";
2706
2707 $nrecs++;
2708
2709 } # while axfr_next
2710
2711 # Overwrite SOA record
2712 if ($rwsoa) {
2713 $soaflag = 1;
2714 my $sthgetsoa = $dbh->prepare("SELECT host,val,ttl FROM default_records WHERE group_id=? AND type=?");
2715 my $sthputsoa = $dbh->prepare("INSERT INTO records (domain_id,host,type,val,ttl) VALUES (?,?,?,?,?)");
2716 $sthgetsoa->execute($group,$reverse_typemap{SOA});
2717 while (my ($host,$val,$ttl) = $sthgetsoa->fetchrow_array()) {
2718 $host =~ s/DOMAIN/$domain/g;
2719 $val =~ s/DOMAIN/$domain/g;
2720 $sthputsoa->execute($dom_id,$host,$reverse_typemap{SOA},$val,$ttl);
2721 }
2722 }
2723
2724 # Overwrite NS records
2725 if ($rwns) {
2726 $nsflag = 1;
2727 my $sthgetns = $dbh->prepare("SELECT host,val,ttl FROM default_records WHERE group_id=? AND type=?");
2728 my $sthputns = $dbh->prepare("INSERT INTO records (domain_id,host,type,val,ttl) VALUES (?,?,?,?,?)");
2729 $sthgetns->execute($group,$reverse_typemap{NS});
2730 while (my ($host,$val,$ttl) = $sthgetns->fetchrow_array()) {
2731 $host =~ s/DOMAIN/$domain/g;
2732 $val =~ s/DOMAIN/$domain/g;
2733 $sthputns->execute($dom_id,$host,$reverse_typemap{NS},$val,$ttl);
2734 }
2735 }
2736
2737 die "No records found; either $ifrom is not authoritative or doesn't allow transfers\n" if !$nrecs;
2738 die "Bad zone: No SOA record!\n" if !$soaflag;
2739 die "Bad zone: No NS records!\n" if !$nsflag;
2740
2741 $dbh->commit;
2742
2743 };
2744
2745 if ($@) {
2746 my $msg = $@;
2747 eval { $dbh->rollback; };
2748 return ('FAIL',$msg." $warnmsg");
2749 } else {
2750 return ('WARN', $warnmsg) if $warnmsg;
2751 return ('OK',"Imported OK");
2752 }
2753
2754 # it should be impossible to get here.
2755 return ('WARN',"OOOK!");
2756} # end importAXFR()
2757
2758
2759## DNSDB::export()
2760# Export the DNS database, or a part of it
2761# Takes database handle, export type, optional arguments depending on type
2762# Writes zone data to targets as appropriate for type
2763sub export {
2764 my $dbh = shift;
2765 my $target = shift;
2766
2767 if ($target eq 'tiny') {
2768 __export_tiny($dbh,@_);
2769 }
2770# elsif ($target eq 'foo') {
2771# __export_foo($dbh,@_);
2772#}
2773# etc
2774
2775} # end export()
2776
2777
2778## DNSDB::__export_tiny
2779# Internal sub to implement tinyDNS (compatible) export
2780# Takes database handle, filehandle to write export to, optional argument(s)
2781# to determine which data gets exported
2782sub __export_tiny {
2783 my $dbh = shift;
2784 my $datafile = shift;
2785
2786##fixme: slurp up further options to specify particular zone(s) to export
2787
2788 ## Convert a bare number into an octal-coded pair of octets.
2789 # Take optional arg to indicate a decimal or hex input. Defaults to hex.
2790 sub octalize {
2791 my $tmp = shift;
2792 my $srctype = shift || 'h'; # default assumes hex string
2793 $tmp = sprintf "%0.4x", hex($tmp) if $srctype eq 'h'; # 0-pad hex to 4 digits
2794 $tmp = sprintf "%0.4x", $tmp if $srctype eq 'd'; # 0-pad decimal to 4 hex digits
2795 my @o = ($tmp =~ /^(..)(..)$/); # split into octets
2796 return sprintf "\\%0.3o\\%0.3o", hex($o[0]), hex($o[1]);;
2797 }
2798
2799##fixme: fail if $datafile isn't an open, writable file
2800
2801 # easy case - export all evarything
2802 # not-so-easy case - export item(s) specified
2803 # todo: figure out what kind of list we use to export items
2804
2805 my $domsth = $dbh->prepare("SELECT domain_id,domain,status FROM domains WHERE status=1");
2806 my $recsth = $dbh->prepare("SELECT host,type,val,distance,weight,port,ttl ".
2807 "FROM records WHERE domain_id=?");
2808 $domsth->execute();
2809 while (my ($domid,$dom,$domstat) = $domsth->fetchrow_array) {
2810 $recsth->execute($domid);
2811 while (my ($host,$type,$val,$dist,$weight,$port,$ttl) = $recsth->fetchrow_array) {
2812##fixme: need to store location in the db, and retrieve it here.
2813# temporarily hardcoded to empty so we can include it further down.
2814my $loc = '';
2815
2816##fixme: record validity timestamp. tinydns supports fiddling with timestamps.
2817# note $ttl must be set to 0 if we want to use tinydns's auto-expiring timestamps.
2818# timestamps are TAI64
2819# ~~ 2^62 + time()
2820my $stamp = '';
2821
2822# raw packet in unknown format: first byte indicates length
2823# of remaining data, allows up to 255 raw bytes
2824
2825 # Spaces are evil.
2826 $host =~ s/^\s+//;
2827 $host =~ s/\s+$//;
2828 if ($typemap{$type} ne 'TXT') {
2829 # Leading or trailng spaces could be legit in TXT records.
2830 $val =~ s/^\s+//;
2831 $val =~ s/\s+$//;
2832 }
2833
2834##fixme? append . to all host/val hostnames
2835 if ($typemap{$type} eq 'SOA') {
2836
2837 # host contains pri-ns:responsible
2838 # val is abused to contain refresh:retry:expire:minttl
2839##fixme: "manual" serial vs tinydns-autoserial
2840 # let's be explicit about abusing $host and $val
2841 my ($email, $primary) = (split /:/, $host)[0,1];
2842 my ($refresh, $retry, $expire, $min_ttl) = (split /:/, $val)[0,1,2,3];
2843 print $datafile "Z$dom:$primary:$email"."::$refresh:$retry:$expire:$min_ttl:$ttl:$stamp:$loc\n";
2844
2845 } elsif ($typemap{$type} eq 'A') {
2846
2847 print $datafile "+$host:$val:$ttl:$stamp:$loc\n";
2848
2849 } elsif ($typemap{$type} eq 'NS') {
2850
2851 print $datafile "\&$host"."::$val:$ttl:$stamp:$loc\n";
2852
2853 } elsif ($typemap{$type} eq 'AAAA') {
2854
2855 print $datafile ":$host:28:";
2856 my $altgrp = 0;
2857 my @altconv;
2858 # Split in to up to 8 groups of hex digits (allows for IPv6 :: 0-collapsing)
2859 foreach (split /:/, $val) {
2860 if (/^$/) {
2861 # flag blank entry; this is a series of 0's of (currently) unknown length
2862 $altconv[$altgrp++] = 's';
2863 } else {
2864 # call sub to convert 1-4 hex digits to 2 string-rep octal bytes
2865 $altconv[$altgrp++] = octalize($_)
2866 }
2867 }
2868 foreach my $octet (@altconv) {
2869 # if not 's', output
2870 print $datafile $octet unless $octet =~ /^s$/;
2871 # if 's', output (9-array length)x literal '\000\000'
2872 print $datafile '\000\000'x(9-$altgrp) if $octet =~ /^s$/;
2873 }
2874 print $datafile ":$ttl:$stamp:$loc\n";
2875
2876 } elsif ($typemap{$type} eq 'MX') {
2877
2878 print $datafile "\@$host"."::$val:$dist:$ttl:$stamp:$loc\n";
2879
2880 } elsif ($typemap{$type} eq 'TXT') {
2881
2882##fixme: split v-e-r-y long TXT strings? will need to do so for BIND export, at least
2883 $val =~ s/:/\\072/g; # may need to replace other symbols
2884 print $datafile "'$host:$val:$ttl:$stamp:$loc\n";
2885
2886# by-hand TXT
2887#:deepnet.cx:16:2v\075spf1\040a\040a\072bacon.deepnet.cx\040a\072home.deepnet.cx\040-all:3600
2888#@ IN TXT "v=spf1 a a:bacon.deepnet.cx a:home.deepnet.cx -all"
2889#'deepnet.cx:v=spf1 a a\072bacon.deepnet.cx a\072home.deepnet.cx -all:3600
2890
2891#txttest IN TXT "v=foo bar:bob kn;ob' \" !@#$%^&*()-=_+[]{}<>?"
2892#: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
2893
2894# very long TXT record as brought in by axfr-get
2895# note tinydns does not support >512-byte RR data, need axfr-dns (for TCP support) for that
2896# also note, tinydns does not seem to support <512, >256-byte RRdata from axfr-get either. :/
2897#:longtxt.deepnet.cx:16:
2898#\170this is a very long txt record. it is really long. long. very long. really very long. this is a very long txt record.
2899#\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.
2900#\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.
2901#:3600
2902
2903 } elsif ($typemap{$type} eq 'CNAME') {
2904
2905 print $datafile "C$host:$val:$ttl:$stamp:$loc\n";
2906
2907 } elsif ($typemap{$type} eq 'SRV') {
2908
2909 # data is two-byte values for priority, weight, port, in that order,
2910 # followed by length/string data
2911
2912 print $datafile ":$host:33:".octalize($dist,'d').octalize($weight,'d').octalize($port,'d');
2913
2914 $val .= '.' if $val !~ /\.$/;
2915 foreach (split /\./, $val) {
2916 printf $datafile "\\%0.3o%s", length($_), $_;
2917 }
2918 print $datafile "\\000:$ttl:$stamp:$loc\n";
2919
2920 } elsif ($typemap{$type} eq 'RP') {
2921
2922 # RP consists of two mostly free-form strings.
2923 # The first is supposed to be an email address with @ replaced by . (as with the SOA contact)
2924 # The second is the "hostname" of a TXT record with more info.
2925 print $datafile ":$host:17:";
2926 my ($who,$what) = split /\s/, $val;
2927 foreach (split /\./, $who) {
2928 printf $datafile "\\%0.3o%s", length($_), $_;
2929 }
2930 print $datafile '\000';
2931 foreach (split /\./, $what) {
2932 printf $datafile "\\%0.3o%s", length($_), $_;
2933 }
2934 print $datafile "\\000:$ttl:$stamp:$loc\n";
2935
2936 } elsif ($typemap{$type} eq 'PTR') {
2937
2938 # must handle both IPv4 and IPv6
2939##work
2940 # data should already be in suitable reverse order.
2941 print $datafile "^$host:$val:$ttl:$stamp:$loc\n";
2942
2943 } else {
2944 # raw record. we don't know what's in here, so we ASS-U-ME the user has
2945 # put it in correctly, since either the user is messing directly with the
2946 # database, or the record was imported via AXFR
2947 # <split by char>
2948 # convert anything not a-zA-Z0-9.- to octal coding
2949
2950##fixme: add flag to export "unknown" record types - note we'll probably end up
2951# mangling them since they were written to the DB from Net::DNS::RR::<type>->rdatastr.
2952 #print $datafile ":$host:$type:$val:$ttl:$stamp:$loc\n";
2953
2954 } # record type if-else
2955
2956 } # while ($recsth)
2957 } # while ($domsth)
2958} # end __export_tiny()
2959
2960
2961## DNSDB::mailNotify()
2962# Sends notification mail to recipients regarding an IPDB operation
2963sub mailNotify {
2964 my $dbh = shift;
2965 my ($subj,$message) = @_;
2966
2967 return if $config{mailhost} eq 'smtp.example.com'; # do nothing if still using default SMTP host.
2968
2969 my $mailer = Net::SMTP->new($config{mailhost}, Hello => "dnsadmin.$config{domain}");
2970
2971 my $mailsender = ($config{mailsender} ? $config{mailsender} : $config{mailnotify});
2972
2973 $mailer->mail($mailsender);
2974 $mailer->to($config{mailnotify});
2975 $mailer->data("From: \"$config{mailname}\" <$mailsender>\n",
2976 "To: <$config{mailnotify}>\n",
2977 "Date: ".strftime("%a, %d %b %Y %H:%M:%S %z",localtime)."\n",
2978 "Subject: $subj\n",
2979 "X-Mailer: DNSAdmin Notify v".sprintf("%.1d",$DNSDB::VERSION)."\n",
2980 "Organization: $config{orgname}\n",
2981 "\n$message\n");
2982 $mailer->quit;
2983}
2984
2985# shut Perl up
29861;
Note: See TracBrowser for help on using the repository browser.