source: trunk/DNSDB.pm@ 316

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

/trunk

Fix embarrasing bug in login process; account status was ignored
and disabled accounts could still log in.

  • Property svn:keywords set to Date Rev Author Id
File size: 138.1 KB
Line 
1# dns/trunk/DNSDB.pm
2# Abstraction functions for DNS administration
3##
4# $Id: DNSDB.pm 316 2012-04-25 21:07:22Z kdeugau $
5# Copyright 2008-2011 Kris Deugau <kdeugau@deepnet.cx>
6#
7# This program is free software: you can redistribute it and/or modify
8# it under the terms of the GNU General Public License as published by
9# the Free Software Foundation, either version 3 of the License, or
10# (at your option) any later version.
11#
12# This program is distributed in the hope that it will be useful,
13# but WITHOUT ANY WARRANTY; without even the implied warranty of
14# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15# GNU General Public License for more details.
16#
17# You should have received a copy of the GNU General Public License
18# along with this program. If not, see <http://www.gnu.org/licenses/>.
19##
20
21package DNSDB;
22
23use strict;
24use warnings;
25use Exporter;
26use DBI;
27use Net::DNS;
28use Crypt::PasswdMD5;
29use Net::SMTP;
30use NetAddr::IP qw(:lower);
31use POSIX;
32use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
33
34$VERSION = 0.1; ##VERSION##
35@ISA = qw(Exporter);
36@EXPORT_OK = qw(
37 &initGlobals &login &initActionLog
38 &initPermissions &getPermissions &changePermissions &comparePermissions
39 &changeGroup
40 &loadConfig &connectDB &finish
41 &addDomain &delZone &domainName &revName &domainID &revID &addRDNS
42 &getZoneCount &getZoneList
43 &addGroup &delGroup &getChildren &groupName
44 &getGroupCount &getGroupList
45 &addUser &updateUser &delUser &userFullName &userStatus &getUserData
46 &getSOA &updateSOA &getRecLine &getDomRecs &getRecCount
47 &addRec &updateRec &delRec
48 &getTypelist
49 &parentID
50 &isParent
51 &zoneStatus &importAXFR
52 &export
53 &mailNotify
54 %typemap %reverse_typemap %config
55 %permissions @permtypes $permlist
56 );
57
58@EXPORT = (); # Export nothing by default.
59%EXPORT_TAGS = ( ALL => [qw(
60 &initGlobals &login &initActionLog
61 &initPermissions &getPermissions &changePermissions &comparePermissions
62 &changeGroup
63 &loadConfig &connectDB &finish
64 &addDomain &delZone &domainName &revName &domainID &revID &addRDNS
65 &getZoneCount &getZoneList
66 &addGroup &delGroup &getChildren &groupName
67 &getGroupCount &getGroupList
68 &addUser &updateUser &delUser &userFullName &userStatus &getUserData
69 &getSOA &updateSOA &getRecLine &getDomRecs &getRecCount
70 &addRec &updateRec &delRec
71 &getTypelist
72 &parentID
73 &isParent
74 &zoneStatus &importAXFR
75 &export
76 &mailNotify
77 %typemap %reverse_typemap %config
78 %permissions @permtypes $permlist
79 )]
80 );
81
82our $group = 1;
83our $errstr = '';
84our $resultstr = '';
85
86# Halfway sane defaults for SOA, TTL, etc.
87# serial defaults to 0 for convenience.
88# value will be either YYYYMMDDNN for BIND/etc, or auto-internal for tinydns
89our %def = qw (
90 contact hostmaster.DOMAIN
91 prins ns1.myserver.com
92 serial 0
93 soattl 86400
94 refresh 10800
95 retry 3600
96 expire 604800
97 minttl 10800
98 ttl 10800
99);
100
101# Arguably defined wholly in the db, but little reason to change without supporting code changes
102our @permtypes = qw (
103 group_edit group_create group_delete
104 user_edit user_create user_delete
105 domain_edit domain_create domain_delete
106 record_edit record_create record_delete
107 self_edit admin
108);
109our $permlist = join(',',@permtypes);
110
111# DNS record type map and reverse map.
112# loaded from the database, from http://www.iana.org/assignments/dns-parameters
113our %typemap;
114our %reverse_typemap;
115
116our %permissions;
117
118# Prepopulate a basic config. Note some of these *will* cause errors if left unset.
119# note: add appropriate stanzas in loadConfig to parse these
120our %config = (
121 # Database connection info
122 dbname => 'dnsdb',
123 dbuser => 'dnsdb',
124 dbpass => 'secret',
125 dbhost => '',
126
127 # Email notice settings
128 mailhost => 'smtp.example.com',
129 mailnotify => 'dnsdb@example.com', # to
130 mailsender => 'dnsdb@example.com', # from
131 mailname => 'DNS Administration',
132 orgname => 'Example Corp',
133 domain => 'example.com',
134
135 # Template directory
136 templatedir => 'templates/',
137# fmeh. this is a real web path, not a logical internal one. hm..
138# cssdir => 'templates/',
139 sessiondir => 'session/',
140
141 # Session params
142 timeout => '3600', # 1 hour default
143
144 # Other miscellanea
145 log_failures => 1, # log all evarthing by default
146 perpage => 15,
147 );
148
149## (Semi)private variables
150
151# Hash of functions for validating record types. Filled in initGlobals() since
152# it relies on visibility flags from the rectypes table in the DB
153my %validators;
154
155# Username, full name, ID - mainly for logging
156my %userdata;
157
158# Entity-relationship reference hashes.
159my %par_tbl = (
160 group => 'groups',
161 user => 'users',
162 defrec => 'default_records',
163 defrevrec => 'default_rev_records',
164 domain => 'domains',
165 revzone => 'revzones',
166 record => 'records'
167 );
168my %id_col = (
169 group => 'group_id',
170 user => 'user_id',
171 defrec => 'record_id',
172 defrevrec => 'record_id',
173 domain => 'domain_id',
174 revzone => 'rdns_id',
175 record => 'record_id'
176 );
177my %par_col = (
178 group => 'parent_group_id',
179 user => 'group_id',
180 defrec => 'group_id',
181 defrevrec => 'group_id',
182 domain => 'group_id',
183 revzone => 'group_id',
184 record => 'domain_id'
185 );
186my %par_type = (
187 group => 'group',
188 user => 'group',
189 defrec => 'group',
190 defrevrec => 'group',
191 domain => 'group',
192 revzone => 'group',
193 record => 'domain'
194 );
195
196##
197## utility functions
198##
199
200## DNSDB::_rectable()
201# Takes default+rdns flags, returns appropriate table name
202sub _rectable {
203 my $def = shift;
204 my $rev = shift;
205
206 return 'records' if $def ne 'y';
207 return 'default_records' if $rev ne 'y';
208 return 'default_rev_records';
209} # end _rectable()
210
211## DNSDB::_recparent()
212# Takes default+rdns flags, returns appropriate parent-id column name
213sub _recparent {
214 my $def = shift;
215 my $rev = shift;
216
217 return 'group_id' if $def eq 'y';
218 return 'rdns_id' if $rev eq 'y';
219 return 'domain_id';
220} # end _recparent()
221
222## DNSDB::_ipparent()
223# Check an IP to be added in a reverse zone to see if it's really in the requested parent.
224# Takes a database handle, default and reverse flags, IP (fragment) to check, parent zone ID,
225# and a reference to a NetAddr::IP object (also used to pass back a fully-reconstructed IP for
226# database insertion)
227sub _ipparent {
228 my $dbh = shift;
229 my $defrec = shift;
230 my $revrec = shift;
231 my $val = shift;
232 my $id = shift;
233 my $addr = shift;
234
235 return if $revrec ne 'y'; # this sub not useful in forward zones
236
237 $$addr = NetAddr::IP->new($$val); #necessary?
238
239 # subsub to split, reverse, and overlay an IP fragment on a netblock
240 sub __rev_overlay {
241 my $splitme = shift; # ':' or '.', m'lud?
242 my $parnet = shift;
243 my $val = shift;
244 my $addr = shift;
245
246 my $joinme = $splitme;
247 $splitme = '\.' if $splitme eq '.';
248 my @working = reverse(split($splitme, $parnet->addr));
249 my @parts = reverse(split($splitme, $$val));
250 for (my $i = 0; $i <= $#parts; $i++) {
251 $working[$i] = $parts[$i];
252 }
253 my $checkme = NetAddr::IP->new(join($joinme, reverse(@working))) or return 0;
254 return 0 unless $checkme->within($parnet);
255 $$addr = $checkme; # force "correct" IP to be recorded.
256 return 1;
257 }
258
259 my ($parstr) = $dbh->selectrow_array("SELECT revnet FROM revzones WHERE rdns_id = ?", undef, ($id));
260 my $parnet = NetAddr::IP->new($parstr);
261
262 # Fail early on v6-in-v4 or v4-in-v6. We're not accepting these ATM.
263 return 0 if $parnet->addr =~ /\./ && $$val =~ /:/;
264 return 0 if $parnet->addr =~ /:/ && $$val =~ /\./;
265
266 if ($$addr && $$val =~ /^[\da-fA-F][\da-fA-F:]+[\da-fA-F]$/) {
267 # the only case where NetAddr::IP's acceptance of legitimate IPs is "correct" is for a proper IPv6 address.
268 # the rest we have to restructure before fiddling. *sigh*
269 return 1 if $$addr->within($parnet);
270 } else {
271 # We don't have a complete IP in $$val (yet)
272 if ($parnet->addr =~ /:/) {
273 $$val =~ s/^:+//; # gotta strip'em all...
274 return __rev_overlay(':', $parnet, $val, $addr);
275 }
276 if ($parnet->addr =~ /\./) {
277 $$val =~ s/^\.+//;
278 return __rev_overlay('.', $parnet, $val, $addr);
279 }
280 # should be impossible to get here...
281 }
282 # ... and here.
283 # can't do nuttin' in forward zones
284} # end _ipparent()
285
286## DNSDB::_hostparent()
287# A little different than _ipparent above; this tries to *find* the parent zone of a hostname
288# Takes a database handle and hostname.
289# Returns the domain ID of the parent domain if one was found.
290sub _hostparent {
291 my $dbh = shift;
292 my $hname = shift;
293
294 my @hostbits = split /\./, $hname;
295 my $sth = $dbh->prepare("SELECT count(*),domain_id FROM domains WHERE domain = ? GROUP BY domain_id");
296 foreach (@hostbits) {
297 $sth->execute($hname);
298 my ($found, $parid) = $sth->fetchrow_array;
299 if ($found) {
300 return $parid;
301 }
302 $hname =~ s/^$_\.//;
303 }
304} # end _hostparent()
305
306## DNSDB::_log()
307# Log an action
308# Takes a database handle and log entry hash containing at least:
309# group_id, log entry
310# and optionally one or more of:
311# domain_id, rdns_id
312# The %userdata hash provides the user ID, username, and fullname
313sub _log {
314 my $dbh = shift;
315
316 my %args = @_;
317
318 $args{rdns_id} = 0 if !$args{rdns_id};
319 $args{domain_id} = 0 if !$args{domain_id};
320
321##fixme: farm out the actual logging to different subs for file, syslog, internal, etc based on config
322# if ($config{log_channel} eq 'sql') {
323 $dbh->do("INSERT INTO log (domain_id,rdns_id,group_id,entry,user_id,email,name) VALUES (?,?,?,?,?,?,?)",
324 undef,
325 ($args{domain_id}, $args{rdns_id}, $args{group_id}, $args{entry},
326 $userdata{userid}, $userdata{username}, $userdata{fullname}) );
327# } elsif ($config{log_channel} eq 'file') {
328# } elsif ($config{log_channel} eq 'syslog') {
329# }
330} # end _log
331
332
333##
334## Record validation subs.
335##
336
337## All of these subs take substantially the same arguments:
338# a database handle
339# a hash containing at least the following keys:
340# - defrec (default/live flag)
341# - revrec (forward/reverse flag)
342# - id (parent entity ID)
343# - host (hostname)
344# - rectype
345# - val (IP, hostname [CNAME/MX/SRV] or text)
346# - addr (NetAddr::IP object from val. May be undef.)
347# MX and SRV record validation also expect distance, and SRV records expect weight and port as well.
348# host, rectype, and addr should be references as these may be modified in validation
349
350# A record
351sub _validate_1 {
352 my $dbh = shift;
353
354 my %args = @_;
355
356 return ('FAIL', 'Reverse zones cannot contain A records') if $args{revrec} eq 'y';
357
358 # Coerce all hostnames to end in ".DOMAIN" for group/default records,
359 # or the intended parent domain for live records.
360 my $pname = ($args{defrec} eq 'y' ? 'DOMAIN' : domainName($dbh,$args{id}));
361 ${$args{host}} =~ s/\.*$/\.$pname/ if ${$args{host}} !~ /$pname$/;
362
363 # Check IP is well-formed, and that it's a v4 address
364 # Fail on "compact" IPv4 variants, because they are not consistent and predictable.
365 return ('FAIL',"$typemap{${$args{rectype}}} record must be a valid IPv4 address")
366 unless ${$args{val}} =~ /^\d+\.\d+\.\d+\.\d+$/;
367 return ('FAIL',"$typemap{${$args{rectype}}} record must be a valid IPv4 address")
368 unless $args{addr} && !$args{addr}->{isv6};
369 # coerce IP/value to normalized form for storage
370 ${$args{val}} = $args{addr}->addr;
371
372 return ('OK','OK');
373} # done A record
374
375# NS record
376sub _validate_2 {
377 my $dbh = shift;
378
379 my %args = @_;
380
381 # Coerce the hostname to "DOMAIN" for forward default records, "ZONE" for reverse default records,
382 # or the intended parent zone for live records.
383##fixme: allow for delegating <subdomain>.DOMAIN?
384 if ($args{revrec} eq 'y') {
385 my $pname = ($args{defrec} eq 'y' ? 'ZONE' : revName($dbh,$args{id}));
386 ${$args{host}} = $pname if ${$args{host}} ne $pname;
387 } else {
388 my $pname = ($args{defrec} eq 'y' ? 'DOMAIN' : domainName($dbh,$args{id}));
389 ${$args{host}} = $pname if ${$args{host}} ne $pname;
390 }
391
392# Let this lie for now. Needs more magic.
393# # Check IP is well-formed, and that it's a v4 address
394# return ('FAIL',"A record must be a valid IPv4 address")
395# unless $addr && !$addr->{isv6};
396# # coerce IP/value to normalized form for storage
397# $$val = $addr->addr;
398
399 return ('OK','OK');
400} # done NS record
401
402# CNAME record
403sub _validate_5 {
404 my $dbh = shift;
405
406 my %args = @_;
407
408# Not really true, but these are only useful for delegating smaller-than-/24 IP blocks.
409# This is fundamentally a messy operation and should really just be taken care of by the
410# export process, not manual maintenance of the necessary records.
411 return ('FAIL', 'Reverse zones cannot contain CNAME records') if $args{revrec} eq 'y';
412
413 # Coerce all hostnames to end in ".DOMAIN" for group/default records,
414 # or the intended parent domain for live records.
415 my $pname = ($args{defrec} eq 'y' ? 'DOMAIN' : domainName($dbh,$args{id}));
416 ${$args{host}} =~ s/\.*$/\.$pname/ if ${$args{host}} !~ /$pname$/;
417
418 return ('OK','OK');
419} # done CNAME record
420
421# SOA record
422sub _validate_6 {
423 # Smart monkeys won't stick their fingers in here; we have
424 # separate dedicated routines to deal with SOA records.
425 return ('OK','OK');
426} # done SOA record
427
428# PTR record
429sub _validate_12 {
430 my $dbh = shift;
431
432 my %args = @_;
433
434 if ($args{revrec} eq 'y') {
435 if ($args{defrec} eq 'n') {
436 return ('FAIL', "IP or IP fragment ${$args{val}} is not within ".revName($dbh, $args{id}))
437 unless _ipparent($dbh, $args{defrec}, $args{revrec}, $args{val}, $args{id}, \$args{addr});
438 ${$args{val}} = $args{addr}->addr;
439 } else {
440 if (${$args{val}} =~ /\./) {
441 # looks like a v4 or fragment
442 if (${$args{val}} =~ /^\d+\.\d+\.\d+\.\d+$/) {
443 # woo! a complete IP! validate it and normalize, or fail.
444 $args{addr} = NetAddr::IP->new(${$args{val}})
445 or return ('FAIL', "IP/value looks like IPv4 but isn't valid");
446 ${$args{val}} = $args{addr}->addr;
447 } else {
448 ${$args{val}} =~ s/^\.*/ZONE./ unless ${$args{val}} =~ /^ZONE/;
449 }
450 } elsif (${$args{val}} =~ /[a-f:]/) {
451 # looks like a v6 or fragment
452 ${$args{val}} =~ s/^:*/ZONE::/ if !$args{addr} && ${$args{val}} !~ /^ZONE/;
453 if ($args{addr}) {
454 if ($args{addr}->addr =~ /^0/) {
455 ${$args{val}} =~ s/^:*/ZONE::/ unless ${$args{val}} =~ /^ZONE/;
456 } else {
457 ${$args{val}} = $args{addr}->addr;
458 }
459 }
460 } else {
461 # bare number (probably). These could be v4 or v6, so we'll
462 # expand on these on creation of a reverse zone.
463 ${$args{val}} = "ZONE,${$args{val}}" unless ${$args{val}} =~ /^ZONE/;
464 }
465 ${$args{host}} =~ s/\.*$/\.$config{domain}/ if ${$args{host}} !~ /(?:$config{domain}|ADMINDOMAIN)$/;
466 }
467
468# Multiple PTR records do NOT generally do what most people believe they do,
469# and tend to fail in the most awkward way possible. Check and warn.
470# We use $val instead of $addr->addr since we may be in a defrec, and may have eg "ZONE::42" or "ZONE.12"
471
472 my @checkvals = (${$args{val}});
473 if (${$args{val}} =~ /,/) {
474 # push . and :: variants into checkvals if val has ,
475 my $tmp;
476 ($tmp = ${$args{val}}) =~ s/,/./;
477 push @checkvals, $tmp;
478 ($tmp = ${$args{val}}) =~ s/,/::/;
479 push @checkvals, $tmp;
480 }
481 my $pcsth = $dbh->prepare("SELECT count(*) FROM "._rectable($args{defrec},$args{revrec})." WHERE val = ?");
482 foreach my $checkme (@checkvals) {
483 if ($args{update}) {
484 # Record update. There should usually be an existing PTR (the record being updated)
485 my @ptrs = @{ $dbh->selectcol_arrayref("SELECT record_id FROM "._rectable($args{defrec},$args{revrec}).
486 " WHERE val = ?", undef, ($checkme)) };
487 return ('WARN', "PTR record for $checkme already exists; adding another will probably not do what you want")
488 if @ptrs && (!grep /^$args{update}$/, @ptrs);
489 } else {
490 # New record. Always warn if a PTR exists
491 my ($ptrcount) = $dbh->selectrow_array("SELECT count(*) FROM "._rectable($args{defrec},$args{revrec}).
492 " WHERE val = ?", undef, ($checkme));
493 return ('WARN', "PTR record for $checkme already exists; adding another will probably not do what you want")
494 if $ptrcount;
495 }
496 }
497
498 } else {
499 # Not absolutely true but only useful if you hack things up for sub-/24 v4 reverse delegations
500 # Simpler to just create the reverse zone and grant access for the customer to edit it, and create direct
501 # PTR records on export
502 return ('FAIL',"Forward zones cannot contain PTR records");
503 }
504
505 return ('OK','OK');
506} # done PTR record
507
508# MX record
509sub _validate_15 {
510 my $dbh = shift;
511
512 my %args = @_;
513
514# Not absolutely true but WTF use is an MX record for a reverse zone?
515 return ('FAIL', 'Reverse zones cannot contain MX records') if $args{revrec} eq 'y';
516
517 return ('FAIL', "Distance is required for MX records") unless defined(${$args{dist}});
518 ${$args{dist}} =~ s/\s*//g;
519 return ('FAIL',"Distance is required, and must be numeric") unless ${$args{dist}} =~ /^\d+$/;
520
521 ${$args{fields}} = "distance,";
522 push @{$args{vallist}}, ${$args{dist}};
523
524 # Coerce all hostnames to end in ".DOMAIN" for group/default records,
525 # or the intended parent domain for live records.
526 my $pname = ($args{defrec} eq 'y' ? 'DOMAIN' : domainName($dbh,$args{id}));
527 ${$args{host}} =~ s/\.*$/\.$pname/ if ${$args{host}} !~ /$pname$/;
528
529# hmm.. this might work. except possibly for something pointing to "deadbeef.ca". <g>
530# if ($type == $reverse_typemap{NS} || $type == $reverse_typemap{MX} || $type == $reverse_typemap{SRV}) {
531# if ($val =~ /^\s*[\da-f:.]+\s*$/) {
532# return ('FAIL',"$val is not a valid IP address") if !$addr;
533# }
534# }
535
536 return ('OK','OK');
537} # done MX record
538
539# TXT record
540sub _validate_16 {
541 # Could arguably put a WARN return here on very long (>512) records
542 return ('OK','OK');
543} # done TXT record
544
545# RP record
546sub _validate_17 {
547 # Probably have to validate these some day
548 return ('OK','OK');
549} # done RP record
550
551# AAAA record
552sub _validate_28 {
553 my $dbh = shift;
554
555 my %args = @_;
556
557 return ('FAIL', 'Reverse zones cannot contain AAAA records') if $args{revrec} eq 'y';
558
559 # Coerce all hostnames to end in ".DOMAIN" for group/default records,
560 # or the intended parent domain for live records.
561 my $pname = ($args{defrec} eq 'y' ? 'DOMAIN' : domainName($dbh,$args{id}));
562 ${$args{host}} =~ s/\.*$/\.$pname/ if ${$args{host}} !~ /$pname$/;
563
564 # Check IP is well-formed, and that it's a v6 address
565 return ('FAIL',"$typemap{${$args{rectype}}} record must be a valid IPv6 address")
566 unless $args{addr} && $args{addr}->{isv6};
567 # coerce IP/value to normalized form for storage
568 ${$args{val}} = $args{addr}->addr;
569
570 return ('OK','OK');
571} # done AAAA record
572
573# SRV record
574sub _validate_33 {
575 my $dbh = shift;
576
577 my %args = @_;
578
579# Not absolutely true but WTF use is an SRV record for a reverse zone?
580 return ('FAIL', 'Reverse zones cannot contain SRV records') if $args{revrec} eq 'y';
581
582 return ('FAIL', "Distance is required for SRV records") unless defined(${$args{dist}});
583 ${$args{dist}} =~ s/\s*//g;
584 return ('FAIL',"Distance is required, and must be numeric") unless ${$args{dist}} =~ /^\d+$/;
585
586 return ('FAIL',"SRV records must begin with _service._protocol [${$args{host}}]")
587 unless ${$args{host}} =~ /^_[A-Za-z]+\._[A-Za-z]+\.[a-zA-Z0-9-]+/;
588 return ('FAIL',"Port and weight are required for SRV records")
589 unless defined(${$args{weight}}) && defined(${$args{port}});
590 ${$args{weight}} =~ s/\s*//g;
591 ${$args{port}} =~ s/\s*//g;
592
593 return ('FAIL',"Port and weight are required, and must be numeric")
594 unless ${$args{weight}} =~ /^\d+$/ && ${$args{port}} =~ /^\d+$/;
595
596 ${$args{fields}} = "distance,weight,port,";
597 push @{$args{vallist}}, (${$args{dist}}, ${$args{weight}}, ${$args{port}});
598
599 # Coerce all hostnames to end in ".DOMAIN" for group/default records,
600 # or the intended parent domain for live records.
601 my $pname = ($args{defrec} eq 'y' ? 'DOMAIN' : domainName($dbh,$args{id}));
602 ${$args{host}} =~ s/\.*$/\.$pname/ if ${$args{host}} !~ /$pname$/;
603
604 return ('OK','OK');
605} # done SRV record
606
607# Now the custom types
608
609# A+PTR record. With a very little bit of magic we can also use this sub to validate AAAA+PTR. Whee!
610sub _validate_65280 {
611 my $dbh = shift;
612
613 my %args = @_;
614
615 my $code = 'OK';
616 my $msg = 'OK';
617
618 if ($args{defrec} eq 'n') {
619 # live record; revrec determines whether we validate the PTR or A component first.
620
621 if ($args{revrec} eq 'y') {
622 ($code,$msg) = _validate_12($dbh, %args);
623 return ($code,$msg) if $code eq 'FAIL';
624
625 # Check if the reqested domain exists. If not, coerce the type down to PTR and warn.
626 if (!(${$args{domid}} = _hostparent($dbh, ${$args{host}}))) {
627 my $addmsg = "Record ".($args{update} ? 'updated' : 'added').
628 " as PTR instead of $typemap{${$args{rectype}}}; domain not found for ${$args{host}}";
629 $msg .= "\n$addmsg" if $code eq 'WARN';
630 $msg = $addmsg if $code eq 'OK';
631 ${$args{rectype}} = $reverse_typemap{PTR};
632 return ('WARN', $msg);
633 }
634
635 # Add domain ID to field list and values
636 ${$args{fields}} .= "domain_id,";
637 push @{$args{vallist}}, ${$args{domid}};
638
639 } else {
640 ($code,$msg) = _validate_1($dbh, %args) if ${$args{rectype}} == 65280;
641 ($code,$msg) = _validate_28($dbh, %args) if ${$args{rectype}} == 65281;
642 return ($code,$msg) if $code eq 'FAIL';
643
644 # Check if the requested reverse zone exists - note, an IP fragment won't
645 # work here since we don't *know* which parent to put it in.
646 # ${$args{val}} has been validated as a valid IP by now, in one of the above calls.
647 my ($revid) = $dbh->selectrow_array("SELECT rdns_id FROM revzones WHERE revnet >> ?".
648 " ORDER BY masklen(revnet) DESC", undef, (${$args{val}}));
649 if (!$revid) {
650 $msg = "Record ".($args{update} ? 'updated' : 'added')." as ".(${$args{rectype}} == 65280 ? 'A' : 'AAAA').
651 " instead of $typemap{${$args{rectype}}}; reverse zone not found for ${$args{val}}";
652 ${$args{rectype}} = (${$args{rectype}} == 65280 ? $reverse_typemap{A} : $reverse_typemap{AAAA});
653 return ('WARN', $msg);
654 }
655
656 # Check for duplicate PTRs. Note we don't have to play games with $code and $msg, because
657 # by definition there can't be duplicate PTRs if the reverse zone isn't managed here.
658 if ($args{update}) {
659 # Record update. There should usually be an existing PTR (the record being updated)
660 my @ptrs = @{ $dbh->selectcol_arrayref("SELECT record_id FROM "._rectable($args{defrec},$args{revrec}).
661 " WHERE val = ?", undef, (${$args{val}})) };
662 if (@ptrs && (!grep /^$args{update}$/, @ptrs)) {
663 $msg = "PTR record for ${$args{val}} already exists; adding another will probably not do what you want";
664 $code = 'WARN';
665 }
666 } else {
667 # New record. Always warn if a PTR exists
668 my ($ptrcount) = $dbh->selectrow_array("SELECT count(*) FROM "._rectable($args{defrec},$args{revrec}).
669 " WHERE val = ?", undef, (${$args{val}}));
670 $msg = "PTR record for ${$args{val}} already exists; adding another will probably not do what you want"
671 if $ptrcount;
672 $code = 'WARN' if $ptrcount;
673 }
674
675# my ($ptrcount) = $dbh->selectrow_array("SELECT count(*) FROM "._rectable($args{defrec},$args{revrec}).
676# " WHERE val = ?", undef, ${$args{val}});
677# if ($ptrcount) {
678# my $curid = $dbh->selectrow_array("SELECT record_id FROM "._rectable($args{defrec},$args{revrec}).
679# " WHERE val = ?
680# $msg = "PTR record for ${$args{val}} already exists; adding another will probably not do what you want";
681# $code = 'WARN';
682# }
683
684 ${$args{fields}} .= "rdns_id,";
685 push @{$args{vallist}}, $revid;
686 }
687
688 } else { # defrec eq 'y'
689 if ($args{revrec} eq 'y') {
690 ($code,$msg) = _validate_12($dbh, %args);
691 return ($code,$msg) if $code eq 'FAIL';
692 if (${$args{rectype}} == 65280) {
693 return ('FAIL',"A+PTR record must be a valid IPv4 address or fragment")
694 if ${$args{val}} =~ /:/;
695 ${$args{val}} =~ s/^ZONE,/ZONE./; # Clean up after uncertain IP-fragment-type from _validate_12
696 } elsif (${$args{rectype}} == 65281) {
697 return ('FAIL',"AAAA+PTR record must be a valid IPv6 address or fragment")
698 if ${$args{val}} =~ /\./;
699 ${$args{val}} =~ s/^ZONE,/ZONE::/; # Clean up after uncertain IP-fragment-type from _validate_12
700 }
701 } else {
702 # This is easy. I also can't see a real use-case for A/AAAA+PTR in *all* forward
703 # domains, since you wouldn't be able to substitute both domain and reverse zone
704 # sanely, and you'd end up with guaranteed over-replicated PTR records that would
705 # confuse the hell out of pretty much anything that uses them.
706##fixme: make this a config flag?
707 return ('FAIL', "$typemap{${$args{rectype}}} records not allowed in default domains");
708 }
709 }
710
711 return ($code, $msg);
712} # done A+PTR record
713
714# AAAA+PTR record
715# A+PTR above has been magicked to handle AAAA+PTR as well.
716sub _validate_65281 {
717 return _validate_65280(@_);
718} # done AAAA+PTR record
719
720# PTR template record
721sub _validate_65282 {
722 return ('OK','OK');
723} # done PTR template record
724
725# A+PTR template record
726sub _validate_65283 {
727 return ('OK','OK');
728} # done AAAA+PTR template record
729
730# AAAA+PTR template record
731sub _validate_65284 {
732 return ('OK','OK');
733} # done AAAA+PTR template record
734
735
736##
737## Record data substitution subs
738##
739
740# Replace ZONE in hostname, or create (most of) the actual proper zone name
741sub _ZONE {
742 my $zone = shift;
743 my $string = shift;
744 my $fr = shift || 'f'; # flag for forward/reverse order? nb: ignored for IP
745 my $sep = shift || '-'; # Separator character - unlikely we'll ever need more than . or -
746
747 my $prefix;
748
749 $string =~ s/,/./ if !$zone->{isv6};
750 $string =~ s/,/::/ if $zone->{isv6};
751
752 # Subbing ZONE in the host. We need to properly ID the netblock range
753 # The subbed text should have "network IP with trailing zeros stripped" for
754 # blocks lined up on octet (for v4) or hex-quad (for v6) boundaries
755 # For blocks that do NOT line up on these boundaries, we take the most
756 # significant octet or 16-bit chunk of the "broadcast" IP and append it
757 # after a double-dash
758 # ie:
759 # 8.0.0.0/6 -> 8.0.0.0 -> 11.255.255.255; sub should be 8--11
760 # 10.0.0.0/12 -> 10.0.0.0 -> 10.0.0.0 -> 10.15.255.255; sub should be 10-0--15
761 # 192.168.4.0/22 -> 192.168.4.0 -> 192.168.7.255; sub should be 192-168-4--7
762 # 192.168.0.8/29 -> 192.168.0.8 -> 192.168.0.15; sub should be 192-168-0-8--15
763 # Similar for v6
764
765 if (!$zone->{isv6}) { # IPv4
766
767 $prefix = $zone->network->addr; # Just In Case someone managed to slip in
768 # a funky subnet that had host bits set.
769 my $bc = $zone->broadcast->addr;
770
771 if ($zone->masklen > 24) {
772 $bc =~ s/^\d+\.\d+\.\d+\.//;
773 } elsif ($zone->masklen > 16) {
774 $prefix =~ s/\.0$//;
775 $bc =~ s/^\d+\.\d+\.//;
776 } elsif ($zone->masklen > 8) {
777 $bc =~ s/^\d+\.//;
778 $prefix =~ s/\.0\.0$//;
779 } else {
780 $prefix =~ s/\.0\.0\.0$//;
781 }
782 if ($zone->masklen % 8) {
783 $bc =~ s/(\.255)+$//;
784 $prefix .= "--$bc"; #"--".zone->masklen; # use range or mask length?
785 }
786 if ($fr eq 'f') {
787 $prefix =~ s/\.+/$sep/g;
788 } else {
789 $prefix = join($sep, reverse(split(/\./, $prefix)));
790 }
791
792 } else { # IPv6
793
794 if ($fr eq 'f') {
795
796 $prefix = $zone->network->addr; # Just In Case someone managed to slip in
797 # a funky subnet that had host bits set.
798 my $bc = $zone->broadcast->addr;
799 if (($zone->masklen % 16) != 0) {
800 # Strip trailing :0 off $prefix, and :ffff off the broadcast IP
801 for (my $i=0; $i<(7-int($zone->masklen / 16)); $i++) {
802 $prefix =~ s/:0$//;
803 $bc =~ s/:ffff$//;
804 }
805 # Strip the leading 16-bit chunks off the front of the broadcast IP
806 $bc =~ s/^([a-f0-9]+:)+//;
807 # Append the remaining 16-bit chunk to the prefix after "--"
808 $prefix .= "--$bc";
809 } else {
810 # Strip off :0 from the end until we reach the netblock length.
811 for (my $i=0; $i<(8-$zone->masklen / 16); $i++) {
812 $prefix =~ s/:0$//;
813 }
814 }
815 # Actually deal with the separator
816 $prefix =~ s/:/$sep/g;
817
818 } else { # $fr eq 'f'
819
820 $prefix = $zone->network->full; # Just In Case someone managed to slip in
821 # a funky subnet that had host bits set.
822 my $bc = $zone->broadcast->full;
823 $prefix =~ s/://g; # clean these out since they're not spaced right for this case
824 $bc =~ s/://g;
825 # Strip trailing 0 off $prefix, and f off the broadcast IP, to match the mask length
826 for (my $i=0; $i<(31-int($zone->masklen / 4)); $i++) {
827 $prefix =~ s/0$//;
828 $bc =~ s/f$//;
829 }
830 # Split and reverse the order of the nibbles in the network/broadcast IPs
831 $prefix =~ s/0$// if $zone->masklen % 4 == 0; # trim another 0 for nibble-aligned blocks first
832 my @nbits = reverse split //, $prefix;
833 my @bbits = reverse split //, $bc;
834 # Handle the sub-nibble case. Eww. I feel dirty supporting this...
835 $nbits[0] = "$nbits[0]-$bbits[0]" if ($zone->masklen % 4) != 0;
836 # Glue it back together
837 $prefix = join($sep, @nbits);
838
839 } # $fr ne 'f'
840
841 } # $zone->{isv6}
842
843 # Do the substitution, finally
844 $string =~ s/ZONE/$prefix/;
845 $string =~ s/--/-/ if $sep ne '-'; # - as separator needs extra help for sub-octet v4 netblocks
846 return $string;
847} # done _ZONE()
848
849# Not quite a substitution sub, but placed here as it's basically the inverse of above;
850# given the .arpa zone name, return the CIDR netblock the zone is for.
851# Supports v4 non-octet/non-classful netblocks as per the method outlined in the Grasshopper Book (2nd Ed p217-218)
852# Does NOT support non-quad v6 netblocks via the same scheme; it shouldn't ever be necessary.
853# Takes a nominal .arpa zone name, returns a success code and NetAddr::IP, or a fail code and message
854sub _zone2cidr {
855 my $zone = shift;
856
857 my $cidr;
858 my $tmpcidr;
859 my $warnmsg = '';
860
861 if ($zone =~ /\.in-addr\.arpa\.?$/) {
862 # v4 revzone, formal zone name type
863 my $tmpzone = $zone;
864 $tmpzone =~ s/\.in-addr\.arpa\.?//;
865 return ('FAIL', "Non-numerics in apparent IPv4 reverse zone name") if $tmpzone !~ /^(?:\d+-)?[\d\.]+$/;
866
867 # Snag the octet pieces
868 my @octs = split /\./, $tmpzone;
869
870 # Map result of a range manipulation to a mask length change. Cheaper than finding the 2-root of $octets[0]+1.
871 # Note we will not support /31 blocks, mostly due to issues telling "24-31" -> .24/29 apart from
872 # "24-31" -> .24/31", with a litte bit of "/31 is icky".
873 my %maskmap = ( 3 => 2, 7 => 3, 15 => 4, 31 => 5, 63 => 6, 127 => 7,
874 30 => 2, 29 => 3, 28 => 4, 27 => 5, 26 => 6, 25 => 7
875 );
876
877 # Handle "range" blocks, eg, 80-83.168.192.in-addr.arpa (192.168.80.0/22)
878 # Need to take the size of the range to offset the basic octet-based mask length,
879 # and make sure the first number in the range gets used as the network address for the block
880 # Alternate form: The second number is actually the real netmask, not the end of the range.
881 my $masklen = 0;
882 if ($octs[0] =~ /^((\d+)-(\d+))$/) { # take the range...
883 if (24 < $3 && $3 < 31) {
884 # we have a real netmask
885 $masklen = -$maskmap{$3};
886 } else {
887 # we have a range. NB: only real CIDR ranges are supported
888 $masklen -= $maskmap{-(eval $1)}; # find the mask base...
889 }
890 $octs[0] = $2; # set the base octet of the range...
891 }
892 @octs = reverse @octs; # We can reverse the octet pieces now that we've extracted and munged any ranges
893
894# arguably we should only allow sub-octet range/mask in-addr.arpa
895# specifications in the least significant octet, but the code is
896# simpler if we deal with sub-octet delegations at any level.
897
898 # Now we find the "true" mask with the aid of the "base" calculated above
899 if ($#octs == 0) {
900 $masklen += 8;
901 $tmpcidr = "$octs[0].0.0.0/$masklen"; # really hope we don't see one of these very often.
902 } elsif ($#octs == 1) {
903 $masklen += 16;
904 $tmpcidr = "$octs[0].$octs[1].0.0/$masklen";
905 } elsif ($#octs == 2) {
906 $masklen += 24;
907 $tmpcidr = "$octs[0].$octs[1].$octs[2].0/$masklen";
908 } else {
909 $masklen += 32;
910 $tmpcidr = "$octs[0].$octs[1].$octs[2].$octs[3]/$masklen";
911 }
912
913 } elsif ($zone =~ /\.ip6\.arpa$/) {
914 # v6 revzone, formal zone name type
915 my $tmpzone = $zone;
916 $tmpzone =~ s/\.ip6\.arpa\.?//;
917##fixme: if-n-when we decide we can support sub-nibble v6 zone names, we'll need to change this segment
918 return ('FAIL', "Non-hexadecimals in apparent IPv6 reverse zone name") if $tmpzone !~ /^[a-fA-F\d\.]+$/;
919 my @quads = reverse(split(/\./, $tmpzone));
920 $warnmsg .= "Apparent sub-/64 IPv6 reverse zone\n" if $#quads > 15;
921 my $nc;
922 foreach (@quads) {
923 $tmpcidr .= $_;
924 $tmpcidr .= ":" if ++$nc % 4 == 0;
925 }
926 my $nq = 1 if $nc % 4 != 0;
927 my $mask = $nc * 4; # need to do this here because we probably increment it below
928 while ($nc++ % 4 != 0) {
929 $tmpcidr .= "0";
930 }
931 $tmpcidr .= ($nq ? '::' : ':')."/$mask";
932 }
933
934 # Just to be sure, use NetAddr::IP to validate. Saves a lot of nasty regex watching for valid octet values.
935 return ('FAIL', "Invalid zone $zone (apparent netblock $tmpcidr)")
936 unless $cidr = NetAddr::IP->new($tmpcidr);
937
938 if ($warnmsg) {
939 $errstr = $warnmsg;
940 return ('WARN', $cidr);
941 }
942 return ('OK', $cidr);
943} # done _zone2cidr()
944
945
946##
947## Initialization and cleanup subs
948##
949
950
951## DNSDB::loadConfig()
952# Load the minimum required initial state (DB connect info) from a config file
953# Load misc other bits while we're at it.
954# Takes an optional basename and config path to look for
955# Populates the %config and %def hashes
956sub loadConfig {
957 my $basename = shift || ''; # this will work OK
958##fixme $basename isn't doing what I think I thought I was trying to do.
959
960 my $deferr = ''; # place to put error from default config file in case we can't find either one
961
962 my $configroot = "/etc/dnsdb"; ##CFG_LEAF##
963 $configroot = '' if $basename =~ m|^/|;
964 $basename .= ".conf" if $basename !~ /\.conf$/;
965 my $defconfig = "$configroot/dnsdb.conf";
966 my $siteconfig = "$configroot/$basename";
967
968 # System defaults
969 __cfgload("$defconfig") or $deferr = $errstr;
970
971 # Per-site-ish settings.
972 if ($basename ne '.conf') {
973 unless (__cfgload("$siteconfig")) {
974 $errstr = ($deferr ? "Error opening default config file $defconfig: $deferr\n" : '').
975 "Error opening site config file $siteconfig";
976 return;
977 }
978 }
979
980 # Munge log_failures.
981 if ($config{log_failures} ne '1' && $config{log_failures} ne '0') {
982 # true/false, on/off, yes/no all valid.
983 if ($config{log_failures} =~ /^(?:true|false|on|off|yes|no)$/) {
984 if ($config{log_failures} =~ /(?:true|on|yes)/) {
985 $config{log_failures} = 1;
986 } else {
987 $config{log_failures} = 0;
988 }
989 } else {
990 $errstr = "Bad log_failures setting $config{log_failures}";
991 $config{log_failures} = 1;
992 # Bad setting shouldn't be fatal.
993 # return 2;
994 }
995 }
996
997 # All good, clear the error and go home.
998 $errstr = '';
999 return 1;
1000} # end loadConfig()
1001
1002
1003## DNSDB::__cfgload()
1004# Private sub to parse a config file and load it into %config
1005# Takes a file handle on an open config file
1006sub __cfgload {
1007 $errstr = '';
1008 my $cfgfile = shift;
1009
1010 if (open CFG, "<$cfgfile") {
1011 while (<CFG>) {
1012 chomp;
1013 s/^\s*//;
1014 next if /^#/;
1015 next if /^$/;
1016# hmm. more complex bits in this file might require [heading] headers, maybe?
1017# $mode = $1 if /^\[(a-z)+]/;
1018 # DB connect info
1019 $config{dbname} = $1 if /^dbname\s*=\s*([a-z0-9_.-]+)/i;
1020 $config{dbuser} = $1 if /^dbuser\s*=\s*([a-z0-9_.-]+)/i;
1021 $config{dbpass} = $1 if /^dbpass\s*=\s*([a-z0-9_.-]+)/i;
1022 $config{dbhost} = $1 if /^dbhost\s*=\s*([a-z0-9_.-]+)/i;
1023 # SOA defaults
1024 $def{contact} = $1 if /^contact\s*=\s*([a-z0-9_.-]+)/i;
1025 $def{prins} = $1 if /^prins\s*=\s*([a-z0-9_.-]+)/i;
1026 $def{soattl} = $1 if /^soattl\s*=\s*(\d+)/i;
1027 $def{refresh} = $1 if /^refresh\s*=\s*(\d+)/i;
1028 $def{retry} = $1 if /^retry\s*=\s*(\d+)/i;
1029 $def{expire} = $1 if /^expire\s*=\s*(\d+)/i;
1030 $def{minttl} = $1 if /^minttl\s*=\s*(\d+)/i;
1031 $def{ttl} = $1 if /^ttl\s*=\s*(\d+)/i;
1032 # Mail settings
1033 $config{mailhost} = $1 if /^mailhost\s*=\s*([a-z0-9_.-]+)/i;
1034 $config{mailnotify} = $1 if /^mailnotify\s*=\s*([a-z0-9_.\@-]+)/i;
1035 $config{mailsender} = $1 if /^mailsender\s*=\s*([a-z0-9_.\@-]+)/i;
1036 $config{mailname} = $1 if /^mailname\s*=\s*([a-z0-9\s_.-]+)/i;
1037 $config{orgname} = $1 if /^orgname\s*=\s*([a-z0-9\s_.,'-]+)/i;
1038 $config{domain} = $1 if /^domain\s*=\s*([a-z0-9_.-]+)/i;
1039 # session - note this is fed directly to CGI::Session
1040 $config{timeout} = $1 if /^[tT][iI][mM][eE][oO][uU][tT]\s*=\s*(\d+[smhdwMy]?)/;
1041 $config{sessiondir} = $1 if m{^sessiondir\s*=\s*([a-z0-9/_.-]+)}i;
1042 # misc
1043 $config{log_failures} = $1 if /^log_failures\s*=\s*([a-z01]+)/i;
1044 $config{perpage} = $1 if /^perpage\s*=\s*(\d+)/i;
1045 }
1046 close CFG;
1047 } else {
1048 $errstr = $!;
1049 return;
1050 }
1051 return 1;
1052} # end __cfgload()
1053
1054
1055## DNSDB::connectDB()
1056# Creates connection to DNS database.
1057# Requires the database name, username, and password.
1058# Returns a handle to the db.
1059# Set up for a PostgreSQL db; could be any transactional DBMS with the
1060# right changes.
1061sub connectDB {
1062 $errstr = '';
1063 my $dbname = shift;
1064 my $user = shift;
1065 my $pass = shift;
1066 my $dbh;
1067 my $DSN = "DBI:Pg:dbname=$dbname";
1068
1069 my $host = shift;
1070 $DSN .= ";host=$host" if $host;
1071
1072# Note that we want to autocommit by default, and we will turn it off locally as necessary.
1073# We may not want to print gobbledygook errors; YMMV. Have to ponder that further.
1074 $dbh = DBI->connect($DSN, $user, $pass, {
1075 AutoCommit => 1,
1076 PrintError => 0
1077 })
1078 or return (undef, $DBI::errstr) if(!$dbh);
1079
1080##fixme: initialize the DB if we can't find the table (since, by definition, there's
1081# nothing there if we can't select from it...)
1082 my $tblsth = $dbh->prepare("SELECT count(*) FROM pg_catalog.pg_class WHERE relkind='r' AND relname=?");
1083 my ($tblcount) = $dbh->selectrow_array($tblsth, undef, ('misc'));
1084 return (undef,$DBI::errstr) if $dbh->err;
1085
1086#if ($tblcount == 0) {
1087# # create tables one at a time, checking for each.
1088# return (undef, "check table misc missing");
1089#}
1090
1091
1092# Return here if we can't select.
1093# This should retrieve the dbversion key.
1094 my $sth = $dbh->prepare("SELECT key,value FROM misc WHERE misc_id=1");
1095 $sth->execute();
1096 return (undef,$DBI::errstr) if ($sth->err);
1097
1098##fixme: do stuff to the DB on version mismatch
1099# x.y series should upgrade on $DNSDB::VERSION > misc(key=>version)
1100# DB should be downward-compatible; column defaults should give sane (if possibly
1101# useless-and-needs-help) values in columns an older software stack doesn't know about.
1102
1103# See if the select returned anything (or null data). This should
1104# succeed if the select executed, but...
1105 $sth->fetchrow();
1106 return (undef,$DBI::errstr) if ($sth->err);
1107
1108 $sth->finish;
1109
1110# If we get here, we should be OK.
1111 return ($dbh,"DB connection OK");
1112} # end connectDB
1113
1114
1115## DNSDB::finish()
1116# Cleans up after database handles and so on.
1117# Requires a database handle
1118sub finish {
1119 my $dbh = $_[0];
1120 $dbh->disconnect;
1121} # end finish
1122
1123
1124## DNSDB::initGlobals()
1125# Initialize global variables
1126# NB: this does NOT include web-specific session variables!
1127# Requires a database handle
1128sub initGlobals {
1129 my $dbh = shift;
1130
1131# load record types from database
1132 my $sth = $dbh->prepare("SELECT val,name,stdflag FROM rectypes");
1133 $sth->execute;
1134 while (my ($recval,$recname,$stdflag) = $sth->fetchrow_array()) {
1135 $typemap{$recval} = $recname;
1136 $reverse_typemap{$recname} = $recval;
1137 # now we fill the record validation function hash
1138 if ($stdflag < 5) {
1139 my $fn = "_validate_$recval";
1140 $validators{$recval} = \&$fn;
1141 } else {
1142 my $fn = "sub { return ('FAIL','Type $recval ($recname) not supported'); }";
1143 $validators{$recval} = eval $fn;
1144 }
1145 }
1146} # end initGlobals
1147
1148
1149## DNSDB::login()
1150# Takes a database handle, username and password
1151# Returns a userdata hash (UID, GID, username, fullname parts) if username exists,
1152# password matches the one on file, and account is not disabled
1153# Returns undef otherwise
1154sub login {
1155 my $dbh = shift;
1156 my $user = shift;
1157 my $pass = shift;
1158
1159 my $userinfo = $dbh->selectrow_hashref("SELECT user_id,group_id,password,firstname,lastname,status".
1160 " FROM users WHERE username=?",
1161 undef, ($user) );
1162 return if !$userinfo;
1163 return if !$userinfo->{status};
1164
1165 if ($userinfo->{password} =~ m|^\$1\$([A-Za-z0-9/.]+)\$|) {
1166 # native passwords (crypt-md5)
1167 return if $userinfo->{password} ne unix_md5_crypt($pass,$1);
1168 } elsif ($userinfo->{password} =~ /^[0-9a-f]{32}$/) {
1169 # VegaDNS import (hex-coded MD5)
1170 return if $userinfo->{password} ne md5_hex($pass);
1171 } else {
1172 # plaintext (convenient now and then)
1173 return if $userinfo->{password} ne $pass;
1174 }
1175
1176 return $userinfo;
1177} # end login()
1178
1179
1180## DNSDB::initActionLog()
1181# Set up action logging. Takes a database handle and user ID
1182# Sets some internal globals and Does The Right Thing to set up a logging channel.
1183# This sets up _log() to spew out log entries to the defined channel without worrying
1184# about having to open a file or a syslog channel
1185##fixme Need to call _initActionLog_blah() for various logging channels, configured
1186# via dnsdb.conf, in $config{log_channel} or something
1187# See https://secure.deepnet.cx/trac/dnsadmin/ticket/21
1188sub initActionLog {
1189 my $dbh = shift;
1190 my $uid = shift;
1191
1192 return if !$uid;
1193
1194 # snag user info for logging. there's got to be a way to not have to pass this back
1195 # and forth from a caller, but web usage means no persistence we can rely on from
1196 # the server side.
1197 my ($username,$fullname) = $dbh->selectrow_array("SELECT username, firstname || ' ' || lastname".
1198 " FROM users WHERE user_id=?", undef, ($uid));
1199##fixme: errors are unpossible!
1200
1201 $userdata{username} = $username;
1202 $userdata{userid} = $uid;
1203 $userdata{fullname} = $fullname;
1204
1205 # convert to real check once we have other logging channels
1206 # if ($config{log_channel} eq 'sql') {
1207 # Open Log, Sez Me!
1208 # }
1209
1210} # end initActionLog
1211
1212
1213## DNSDB::initPermissions()
1214# Set up permissions global
1215# Takes database handle and UID
1216sub initPermissions {
1217 my $dbh = shift;
1218 my $uid = shift;
1219
1220# %permissions = $(getPermissions($dbh,'user',$uid));
1221 getPermissions($dbh, 'user', $uid, \%permissions);
1222
1223} # end initPermissions()
1224
1225
1226## DNSDB::getPermissions()
1227# Get permissions from DB
1228# Requires DB handle, group or user flag, ID, and hashref.
1229sub getPermissions {
1230 my $dbh = shift;
1231 my $type = shift;
1232 my $id = shift;
1233 my $hash = shift;
1234
1235 my $sql = qq(
1236 SELECT
1237 p.admin,p.self_edit,
1238 p.group_create,p.group_edit,p.group_delete,
1239 p.user_create,p.user_edit,p.user_delete,
1240 p.domain_create,p.domain_edit,p.domain_delete,
1241 p.record_create,p.record_edit,p.record_delete
1242 FROM permissions p
1243 );
1244 if ($type eq 'group') {
1245 $sql .= qq(
1246 JOIN groups g ON g.permission_id=p.permission_id
1247 WHERE g.group_id=?
1248 );
1249 } else {
1250 $sql .= qq(
1251 JOIN users u ON u.permission_id=p.permission_id
1252 WHERE u.user_id=?
1253 );
1254 }
1255
1256 my $sth = $dbh->prepare($sql);
1257
1258 $sth->execute($id) or die "argh: ".$sth->errstr;
1259
1260# my $permref = $sth->fetchrow_hashref;
1261# return $permref;
1262# $hash = $permref;
1263# Eww. Need to learn how to forcibly drop a hashref onto an existing hash.
1264 ($hash->{admin},$hash->{self_edit},
1265 $hash->{group_create},$hash->{group_edit},$hash->{group_delete},
1266 $hash->{user_create},$hash->{user_edit},$hash->{user_delete},
1267 $hash->{domain_create},$hash->{domain_edit},$hash->{domain_delete},
1268 $hash->{record_create},$hash->{record_edit},$hash->{record_delete})
1269 = $sth->fetchrow_array;
1270
1271} # end getPermissions()
1272
1273
1274## DNSDB::changePermissions()
1275# Update an ACL entry
1276# Takes a db handle, type, owner-id, and hashref for the changed permissions.
1277sub changePermissions {
1278 my $dbh = shift;
1279 my $type = shift;
1280 my $id = shift;
1281 my $newperms = shift;
1282 my $inherit = shift || 0;
1283
1284 my $resultmsg = '';
1285
1286 # see if we're switching from inherited to custom. for bonus points,
1287 # snag the permid and parent permid anyway, since we'll need the permid
1288 # to set/alter custom perms, and both if we're switching from custom to
1289 # inherited.
1290 my $sth = $dbh->prepare("SELECT (u.permission_id=g.permission_id) AS was_inherited,u.permission_id,g.permission_id,".
1291 ($type eq 'user' ? 'u.group_id,u.username' : 'u.parent_group_id,u.group_name').
1292 " FROM ".($type eq 'user' ? 'users' : 'groups')." u ".
1293 " JOIN groups g ON u.".($type eq 'user' ? '' : 'parent_')."group_id=g.group_id ".
1294 " WHERE u.".($type eq 'user' ? 'user' : 'group')."_id=?");
1295 $sth->execute($id);
1296
1297 my ($wasinherited,$permid,$parpermid,$parid,$name) = $sth->fetchrow_array;
1298
1299# hack phtoui
1300# group id 1 is "special" in that it's it's own parent (err... possibly.)
1301# may make its parent id 0 which doesn't exist, and as a bonus is Perl-false.
1302 $wasinherited = 0 if ($type eq 'group' && $id == 1);
1303
1304 local $dbh->{AutoCommit} = 0;
1305 local $dbh->{RaiseError} = 1;
1306
1307 # Wrap all the SQL in a transaction
1308 eval {
1309 if ($inherit) {
1310
1311 $dbh->do("UPDATE ".($type eq 'user' ? 'users' : 'groups')." SET inherit_perm='t',permission_id=? ".
1312 "WHERE ".($type eq 'user' ? 'user' : 'group')."_id=?", undef, ($parpermid, $id) );
1313 $dbh->do("DELETE FROM permissions WHERE permission_id=?", undef, ($permid) );
1314
1315 } else {
1316
1317 if ($wasinherited) { # munge new permission entry in if we're switching from inherited perms
1318##fixme: need to add semirecursive bit to properly munge inherited permission ID on subgroups and users
1319# ... if'n'when we have groups with fully inherited permissions.
1320 # SQL is coo
1321 $dbh->do("INSERT INTO permissions ($permlist,".($type eq 'user' ? 'user' : 'group')."_id) ".
1322 "SELECT $permlist,? FROM permissions WHERE permission_id=?", undef, ($id,$permid) );
1323 ($permid) = $dbh->selectrow_array("SELECT permission_id FROM permissions ".
1324 "WHERE ".($type eq 'user' ? 'user' : 'group')."_id=?", undef, ($id) );
1325 $dbh->do("UPDATE ".($type eq 'user' ? 'users' : 'groups')." SET inherit_perm='f',permission_id=? ".
1326 "WHERE ".($type eq 'user' ? 'user' : 'group')."_id=?", undef, ($permid, $id) );
1327 }
1328
1329 # and now set the permissions we were passed
1330 foreach (@permtypes) {
1331 if (defined ($newperms->{$_})) {
1332 $dbh->do("UPDATE permissions SET $_=? WHERE permission_id=?", undef, ($newperms->{$_},$permid) );
1333 }
1334 }
1335
1336 } # (inherited->)? custom
1337
1338 if ($type eq 'user') {
1339 $resultmsg = "Updated permissions for user $name";
1340 } else {
1341 $resultmsg = "Updated default permissions for group $name";
1342 }
1343 _log($dbh, (group_id => ($type eq 'user' ? $parid : $id), entry => $resultmsg));
1344 $dbh->commit;
1345 }; # end eval
1346 if ($@) {
1347 my $msg = $@;
1348 eval { $dbh->rollback; };
1349 return ('FAIL',"Error changing permissions: $msg");
1350 }
1351
1352 return ('OK',$resultmsg);
1353} # end changePermissions()
1354
1355
1356## DNSDB::comparePermissions()
1357# Compare two permission hashes
1358# Returns '>', '<', '=', '!'
1359sub comparePermissions {
1360 my $p1 = shift;
1361 my $p2 = shift;
1362
1363 my $retval = '='; # assume equality until proven otherwise
1364
1365 no warnings "uninitialized";
1366
1367 foreach (@permtypes) {
1368 next if $p1->{$_} == $p2->{$_}; # equal is good
1369 if ($p1->{$_} && !$p2->{$_}) {
1370 if ($retval eq '<') { # if we've already found an unequal pair where
1371 $retval = '!'; # $p2 has more access, and we now find a pair
1372 last; # where $p1 has more access, the overall access
1373 } # is neither greater or lesser, it's unequal.
1374 $retval = '>';
1375 }
1376 if (!$p1->{$_} && $p2->{$_}) {
1377 if ($retval eq '>') { # if we've already found an unequal pair where
1378 $retval = '!'; # $p1 has more access, and we now find a pair
1379 last; # where $p2 has more access, the overall access
1380 } # is neither greater or lesser, it's unequal.
1381 $retval = '<';
1382 }
1383 }
1384 return $retval;
1385} # end comparePermissions()
1386
1387
1388## DNSDB::changeGroup()
1389# Change group ID of an entity
1390# Takes a database handle, entity type, entity ID, and new group ID
1391sub changeGroup {
1392 my $dbh = shift;
1393 my $type = shift;
1394 my $id = shift;
1395 my $newgrp = shift;
1396
1397##fixme: fail on not enough args
1398 #return ('FAIL', "Missing
1399
1400 return ('FAIL', "Can't change the group of a $type")
1401 unless grep /^$type$/, ('domain','revzone','user','group'); # could be extended for defrecs?
1402
1403 # Collect some names for logging and messages
1404 my $entname;
1405 if ($type eq 'domain') {
1406 $entname = domainName($dbh, $id);
1407 } elsif ($type eq 'revzone') {
1408 $entname = revName($dbh, $id);
1409 } elsif ($type eq 'user') {
1410 $entname = userFullName($dbh, $id, '%u');
1411 } elsif ($type eq 'group') {
1412 $entname = groupName($dbh, $id);
1413 }
1414
1415 my ($oldgid) = $dbh->selectrow_array("SELECT group_id FROM $par_tbl{$type} WHERE $id_col{$type}=?",
1416 undef, ($id));
1417 my $oldgname = groupName($dbh, $oldgid);
1418 my $newgname = groupName($dbh, $newgrp);
1419
1420 return ('FAIL', "Can't move things into a group that doesn't exist") if !$newgname;
1421
1422 return ('WARN', "Nothing to do, new group is the same as the old group") if $oldgid == $newgrp;
1423
1424 # Allow transactions, and raise an exception on errors so we can catch it later.
1425 # Use local to make sure these get "reset" properly on exiting this block
1426 local $dbh->{AutoCommit} = 0;
1427 local $dbh->{RaiseError} = 1;
1428
1429 eval {
1430 $dbh->do("UPDATE $par_tbl{$type} SET group_id=? WHERE $id_col{$type}=?", undef, ($newgrp, $id));
1431 # Log the change in both the old and new groups
1432 _log($dbh, (group_id => $oldgid, entry => "Moved $type $entname from $oldgname to $newgname"));
1433 _log($dbh, (group_id => $newgrp, entry => "Moved $type $entname from $oldgname to $newgname"));
1434 $dbh->commit;
1435 };
1436 if ($@) {
1437 my $msg = $@;
1438 eval { $dbh->rollback; };
1439 if ($config{log_failures}) {
1440 _log($dbh, (group_id => $oldgid, entry => "Error moving $type $entname to $newgname: $msg"));
1441 $dbh->commit; # since we enabled transactions earlier
1442 }
1443 return ('FAIL',"Error moving $type $entname to $newgname: $msg");
1444 }
1445
1446 return ('OK',"Moved $type $entname from $oldgname to $newgname");
1447} # end changeGroup()
1448
1449
1450##
1451## Processing subs
1452##
1453
1454## DNSDB::addDomain()
1455# Add a domain
1456# Takes a database handle, domain name, numeric group, boolean(ish) state (active/inactive),
1457# and user info hash (for logging).
1458# Returns a status code and message
1459sub addDomain {
1460 $errstr = '';
1461 my $dbh = shift;
1462 return ('FAIL',"Need database handle") if !$dbh;
1463 my $domain = shift;
1464 return ('FAIL',"Domain must not be blank") if !$domain;
1465 my $group = shift;
1466 return ('FAIL',"Need group") if !defined($group);
1467 my $state = shift;
1468 return ('FAIL',"Need domain status") if !defined($state);
1469
1470 $state = 1 if $state =~ /^active$/;
1471 $state = 1 if $state =~ /^on$/;
1472 $state = 0 if $state =~ /^inactive$/;
1473 $state = 0 if $state =~ /^off$/;
1474
1475 return ('FAIL',"Invalid domain status") if $state !~ /^\d+$/;
1476
1477 return ('FAIL', "Invalid characters in domain") if $domain !~ /^[a-zA-Z0-9_.-]+$/;
1478
1479 my $sth = $dbh->prepare("SELECT domain_id FROM domains WHERE domain=?");
1480 my $dom_id;
1481
1482# quick check to start to see if we've already got one
1483 $sth->execute($domain);
1484 ($dom_id) = $sth->fetchrow_array;
1485
1486 return ('FAIL', "Domain already exists") if $dom_id;
1487
1488 # Allow transactions, and raise an exception on errors so we can catch it later.
1489 # Use local to make sure these get "reset" properly on exiting this block
1490 local $dbh->{AutoCommit} = 0;
1491 local $dbh->{RaiseError} = 1;
1492
1493 # Wrap all the SQL in a transaction
1494 eval {
1495 # insert the domain...
1496 $dbh->do("INSERT INTO domains (domain,group_id,status) VALUES (?,?,?)", undef, ($domain, $group, $state));
1497
1498 # get the ID...
1499 ($dom_id) = $dbh->selectrow_array("SELECT domain_id FROM domains WHERE domain=?", undef, ($domain));
1500
1501 _log($dbh, (domain_id => $dom_id, group_id => $group,
1502 entry => "Added ".($state ? 'active' : 'inactive')." domain $domain"));
1503
1504 # ... and now we construct the standard records from the default set. NB: group should be variable.
1505 my $sth = $dbh->prepare("SELECT host,type,val,distance,weight,port,ttl FROM default_records WHERE group_id=?");
1506 my $sth_in = $dbh->prepare("INSERT INTO records (domain_id,host,type,val,distance,weight,port,ttl)".
1507 " VALUES ($dom_id,?,?,?,?,?,?,?)");
1508 $sth->execute($group);
1509 while (my ($host,$type,$val,$dist,$weight,$port,$ttl) = $sth->fetchrow_array()) {
1510 $host =~ s/DOMAIN/$domain/g;
1511 $val =~ s/DOMAIN/$domain/g;
1512 $sth_in->execute($host,$type,$val,$dist,$weight,$port,$ttl);
1513 if ($typemap{$type} eq 'SOA') {
1514 my @tmp1 = split /:/, $host;
1515 my @tmp2 = split /:/, $val;
1516 _log($dbh, (domain_id => $dom_id, group_id => $group,
1517 entry => "[new $domain] Added SOA record [contact $tmp1[0]] [master $tmp1[1]] ".
1518 "[refresh $tmp2[0]] [retry $tmp2[1]] [expire $tmp2[2]] [minttl $tmp2[3]], TTL $ttl"));
1519 } else {
1520 my $logentry = "[new $domain] Added record '$host $typemap{$type}";
1521 $logentry .= " [distance $dist]" if $typemap{$type} eq 'MX';
1522 $logentry .= " [priority $dist] [weight $weight] [port $port]" if $typemap{$type} eq 'SRV';
1523 _log($dbh, (domain_id => $dom_id, group_id => $group,
1524 entry => $logentry." $val', TTL $ttl"));
1525 }
1526 }
1527
1528 # once we get here, we should have suceeded.
1529 $dbh->commit;
1530 }; # end eval
1531
1532 if ($@) {
1533 my $msg = $@;
1534 eval { $dbh->rollback; };
1535 _log($dbh, (group_id => $group, entry => "Failed adding domain $domain ($msg)"))
1536 if $config{log_failures};
1537 $dbh->commit; # since we enabled transactions earlier
1538 return ('FAIL',$msg);
1539 } else {
1540 return ('OK',$dom_id);
1541 }
1542} # end addDomain
1543
1544
1545## DNSDB::delZone()
1546# Delete a forward or reverse zone.
1547# Takes a database handle, zone ID, and forward/reverse flag.
1548# for now, just delete the records, then the domain.
1549# later we may want to archive it in some way instead (status code 2, for example?)
1550sub delZone {
1551 my $dbh = shift;
1552 my $zoneid = shift;
1553 my $revrec = shift;
1554
1555 # Allow transactions, and raise an exception on errors so we can catch it later.
1556 # Use local to make sure these get "reset" properly on exiting this block
1557 local $dbh->{AutoCommit} = 0;
1558 local $dbh->{RaiseError} = 1;
1559
1560 my $msg = '';
1561 my $failmsg = '';
1562 my $zone = ($revrec eq 'n' ? domainName($dbh, $zoneid) : revName($dbh, $zoneid));
1563
1564 # Set this up here since we may use if if $config{log_failures} is enabled
1565 my %loghash;
1566 $loghash{domain_id} = $zoneid if $revrec eq 'n';
1567 $loghash{rdns_id} = $zoneid if $revrec eq 'y';
1568 $loghash{group_id} = parentID($dbh,
1569 (id => $zoneid, type => ($revrec eq 'n' ? 'domain' : 'revzone'), revrec => $revrec) );
1570
1571 # Wrap all the SQL in a transaction
1572 eval {
1573 # Disentangle custom record types before removing the
1574 # ones that are only in the zone to be deleted
1575 if ($revrec eq 'n') {
1576 my $sth = $dbh->prepare("UPDATE records SET type=?,domain_id=0 WHERE domain_id=? AND type=?");
1577 $failmsg = "Failure converting multizone types to single-zone";
1578 $sth->execute($reverse_typemap{PTR}, $zoneid, 65280);
1579 $sth->execute($reverse_typemap{PTR}, $zoneid, 65281);
1580 $sth->execute(65282, $zoneid, 65283);
1581 $sth->execute(65282, $zoneid, 65284);
1582 $failmsg = "Failure removing domain records";
1583 $dbh->do("DELETE FROM records WHERE domain_id=?", undef, ($zoneid));
1584 $failmsg = "Failure removing domain";
1585 $dbh->do("DELETE FROM domains WHERE domain_id=?", undef, ($zoneid));
1586 } else {
1587 my $sth = $dbh->prepare("UPDATE records SET type=?,rdns_id=0 WHERE rdns_id=? AND type=?");
1588 $failmsg = "Failure converting multizone types to single-zone";
1589 $sth->execute($reverse_typemap{A}, $zoneid, 65280);
1590 $sth->execute($reverse_typemap{AAAA}, $zoneid, 65281);
1591# We don't have an "A template" or "AAAA template" type, although it might be useful for symmetry.
1592# $sth->execute(65285?, $zoneid, 65283);
1593# $sth->execute(65285?, $zoneid, 65284);
1594 $failmsg = "Failure removing reverse records";
1595 $dbh->do("DELETE FROM records WHERE rdns_id=?", undef, ($zoneid));
1596 $failmsg = "Failure removing reverse zone";
1597 $dbh->do("DELETE FROM revzones WHERE rdns_id=?", undef, ($zoneid));
1598 }
1599
1600 $msg = "Deleted ".($revrec eq 'n' ? 'domain' : 'reverse zone')." $zone";
1601 $loghash{entry} = $msg;
1602 _log($dbh, %loghash);
1603
1604 # once we get here, we should have suceeded.
1605 $dbh->commit;
1606 }; # end eval
1607
1608 if ($@) {
1609 $msg = $@;
1610 eval { $dbh->rollback; };
1611 $loghash{entry} = "Error deleting $zone: $msg ($failmsg)";
1612 if ($config{log_failures}) {
1613 _log($dbh, %loghash);
1614 $dbh->commit; # since we enabled transactions earlier
1615 }
1616 return ('FAIL', $loghash{entry});
1617 } else {
1618 return ('OK', $msg);
1619 }
1620
1621} # end delZone()
1622
1623
1624## DNSDB::domainName()
1625# Return the domain name based on a domain ID
1626# Takes a database handle and the domain ID
1627# Returns the domain name or undef on failure
1628sub domainName {
1629 $errstr = '';
1630 my $dbh = shift;
1631 my $domid = shift;
1632 my ($domname) = $dbh->selectrow_array("SELECT domain FROM domains WHERE domain_id=?", undef, ($domid) );
1633 $errstr = $DBI::errstr if !$domname;
1634 return $domname if $domname;
1635} # end domainName()
1636
1637
1638## DNSDB::revName()
1639# Return the reverse zone name based on an rDNS ID
1640# Takes a database handle and the rDNS ID
1641# Returns the reverse zone name or undef on failure
1642sub revName {
1643 $errstr = '';
1644 my $dbh = shift;
1645 my $revid = shift;
1646 my ($revname) = $dbh->selectrow_array("SELECT revnet FROM revzones WHERE rdns_id=?", undef, ($revid) );
1647 $errstr = $DBI::errstr if !$revname;
1648 return $revname if $revname;
1649} # end revName()
1650
1651
1652## DNSDB::domainID()
1653# Takes a database handle and domain name
1654# Returns the domain ID number
1655sub domainID {
1656 $errstr = '';
1657 my $dbh = shift;
1658 my $domain = shift;
1659 my ($domid) = $dbh->selectrow_array("SELECT domain_id FROM domains WHERE domain=?", undef, ($domain) );
1660 $errstr = $DBI::errstr if !$domid;
1661 return $domid if $domid;
1662} # end domainID()
1663
1664
1665## DNSDB::revID()
1666# Takes a database handle and reverse zone name
1667# Returns the rDNS ID number
1668sub revID {
1669 $errstr = '';
1670 my $dbh = shift;
1671 my $revzone = shift;
1672 my ($revid) = $dbh->selectrow_array("SELECT rdns_id FROM revzones WHERE revnet=?", undef, ($revzone) );
1673 $errstr = $DBI::errstr if !$revid;
1674 return $revid if $revid;
1675} # end revID()
1676
1677
1678## DNSDB::addRDNS
1679# Adds a reverse DNS zone
1680# Takes a database handle, CIDR block, reverse DNS pattern, numeric group,
1681# and boolean(ish) state (active/inactive)
1682# Returns a status code and message
1683sub addRDNS {
1684 my $dbh = shift;
1685 my $zone = NetAddr::IP->new(shift);
1686 return ('FAIL',"Zone name must be a valid CIDR netblock") unless ($zone && $zone->addr !~ /^0/);
1687 my $revpatt = shift; # construct a custom (A/AAAA+)? PTR template record
1688 my $group = shift;
1689 my $state = shift;
1690
1691 $state = 1 if $state =~ /^active$/;
1692 $state = 1 if $state =~ /^on$/;
1693 $state = 0 if $state =~ /^inactive$/;
1694 $state = 0 if $state =~ /^off$/;
1695
1696 return ('FAIL',"Invalid zone status") if $state !~ /^\d+$/;
1697
1698# quick check to start to see if we've already got one
1699 my ($rdns_id) = $dbh->selectrow_array("SELECT rdns_id FROM revzones WHERE revnet=?", undef, ("$zone"));
1700
1701 return ('FAIL', "Zone already exists") if $rdns_id;
1702
1703 # Allow transactions, and raise an exception on errors so we can catch it later.
1704 # Use local to make sure these get "reset" properly on exiting this block
1705 local $dbh->{AutoCommit} = 0;
1706 local $dbh->{RaiseError} = 1;
1707
1708 my $warnstr = '';
1709 my $defttl = 3600; # 1 hour should be reasonable. And unless things have gone horribly
1710 # wrong, we should have a value to override this anyway.
1711
1712 # Wrap all the SQL in a transaction
1713 eval {
1714 # insert the domain...
1715 $dbh->do("INSERT INTO revzones (revnet,group_id,status) VALUES (?,?,?)", undef, ($zone, $group, $state));
1716
1717 # get the ID...
1718 ($rdns_id) = $dbh->selectrow_array("SELECT currval('revzones_rdns_id_seq')");
1719
1720 _log($dbh, (rdns_id => $rdns_id, group_id => $group,
1721 entry => "Added ".($state ? 'active' : 'inactive')." reverse zone $zone"));
1722
1723 # ... and now we construct the standard records from the default set. NB: group should be variable.
1724 my $sth = $dbh->prepare("SELECT host,type,val,ttl FROM default_rev_records WHERE group_id=?");
1725 my $sth_in = $dbh->prepare("INSERT INTO records (rdns_id,domain_id,host,type,val,ttl)".
1726 " VALUES ($rdns_id,?,?,?,?,?)");
1727 $sth->execute($group);
1728 while (my ($host,$type,$val,$ttl) = $sth->fetchrow_array()) {
1729 # Silently skip v4/v6 mismatches. This is not an error, this is expected.
1730 if ($zone->{isv6}) {
1731 next if ($type == 65280 || $type == 65283);
1732 } else {
1733 next if ($type == 65281 || $type == 65284);
1734 }
1735
1736 $host =~ s/ADMINDOMAIN/$config{domain}/g;
1737
1738 # Check to make sure the IP stubs will fit in the zone. Under most usage failures here should be rare.
1739 # On failure, tack a note on to a warning string and continue without adding this record.
1740 # While we're at it, we substitute $zone for ZONE in the value.
1741 if ($val eq 'ZONE') {
1742 next if $revpatt; # If we've got a pattern, we skip the default record version.
1743##fixme? do we care if we have multiple whole-zone templates?
1744 $val = $zone->network;
1745 } elsif ($val =~ /ZONE/) {
1746 my $tmpval = $val;
1747 $tmpval =~ s/ZONE//;
1748 # Bend the rules and allow single-trailing-number PTR or PTR template records to be inserted
1749 # as either v4 or v6. May make this an off-by-default config flag
1750 # Note that the origin records that may trigger this **SHOULD** already have ZONE,\d
1751 if ($type == 12 || $type == 65282) {
1752 $tmpval =~ s/[,.]/::/ if ($tmpval =~ /^[,.]\d+$/ && $zone->{isv6});
1753 $tmpval =~ s/[,:]+/./ if ($tmpval =~ /^(?:,|::)\d+$/ && !$zone->{isv6});
1754 }
1755 my $addr;
1756 if (_ipparent($dbh, 'n', 'y', \$tmpval, $rdns_id, \$addr)) {
1757 $val = $addr->addr;
1758 } else {
1759 $warnstr .= "\nDefault record '$val $typemap{$type} $host' doesn't fit in $zone, skipping";
1760 next;
1761 }
1762 }
1763
1764 # Substitute $zone for ZONE in the hostname.
1765 $host = _ZONE($zone, $host);
1766
1767 # Fill in the forward domain ID if we can find it, otherwise:
1768 # Coerce type down to PTR or PTR template if we can't
1769 my $domid = 0;
1770 if ($type >= 65280) {
1771 if (!($domid = _hostparent($dbh, $host))) {
1772 $warnstr .= "\nRecord added as PTR instead of $typemap{$type}; domain not found for $host";
1773 $type = $reverse_typemap{PTR};
1774 $domid = 0; # just to be explicit.
1775 }
1776 }
1777
1778 $sth_in->execute($domid,$host,$type,$val,$ttl);
1779
1780 if ($typemap{$type} eq 'SOA') {
1781 my @tmp1 = split /:/, $host;
1782 my @tmp2 = split /:/, $val;
1783 _log($dbh, (rdns_id => $rdns_id, group_id => $group,
1784 entry => "[new $zone] Added SOA record [contact $tmp1[0]] [master $tmp1[1]] ".
1785 "[refresh $tmp2[0]] [retry $tmp2[1]] [expire $tmp2[2]] [minttl $tmp2[3]], TTL $ttl"));
1786 $defttl = $tmp2[3];
1787 } else {
1788 my $logentry = "[new $zone] Added record '$host $typemap{$type}";
1789 _log($dbh, (rdns_id => $rdns_id, domain_id => $domid, group_id => $group,
1790 entry => $logentry." $val', TTL $ttl"));
1791 }
1792 }
1793
1794 # Generate record based on provided pattern.
1795 if ($revpatt) {
1796 my $host;
1797 my $type = ($zone->{isv6} ? 65284 : 65283);
1798 my $val = $zone->network;
1799
1800 # Substitute $zone for ZONE in the hostname.
1801 $host = _ZONE($zone, $revpatt);
1802
1803 my $domid = 0;
1804 if (!($domid = _hostparent($dbh, $host))) {
1805 $warnstr .= "\nDefault pattern added as PTR template instead of $typemap{$type}; domain not found for $host";
1806 $type = 65282;
1807 $domid = 0; # just to be explicit.
1808 }
1809
1810 $sth_in->execute($domid,$host,$type,$val,$defttl);
1811 my $logentry = "[new $zone] Added record '$host $typemap{$type}";
1812 _log($dbh, (rdns_id => $rdns_id, domain_id => $domid, group_id => $group,
1813 entry => $logentry." $val', TTL $defttl from pattern"));
1814 }
1815
1816 # If there are warnings (presumably about default records skipped for cause) log them
1817 _log($dbh, (rdns_id => $rdns_id, group_id => $group, entry => "Warning(s) adding $zone:$warnstr"))
1818 if $warnstr;
1819
1820 # once we get here, we should have suceeded.
1821 $dbh->commit;
1822 }; # end eval
1823
1824 if ($@) {
1825 my $msg = $@;
1826 eval { $dbh->rollback; };
1827 _log($dbh, (group_id => $group, entry => "Failed adding reverse zone $zone ($msg)"))
1828 if $config{log_failures};
1829 $dbh->commit; # since we enabled transactions earlier
1830 return ('FAIL',$msg);
1831 } else {
1832 my $retcode = 'OK';
1833 if ($warnstr) {
1834 $resultstr = $warnstr;
1835 $retcode = 'WARN';
1836 }
1837 return ($retcode, $rdns_id);
1838 }
1839
1840} # end addRDNS()
1841
1842
1843## DNSDB::getZoneCount
1844# Get count of zones in group or groups
1845# Takes a database handle and hash containing:
1846# - the "current" group
1847# - an array of "acceptable" groups
1848# - a flag for forward/reverse zones
1849# - Optionally accept a "starts with" and/or "contains" filter argument
1850# Returns an integer count of the resulting zone list.
1851sub getZoneCount {
1852 my $dbh = shift;
1853
1854 my %args = @_;
1855
1856 my @filterargs;
1857 $args{startwith} = undef if $args{startwith} && $args{startwith} !~ /^(?:[a-z]|0-9)$/;
1858 push @filterargs, "^$args{startwith}" if $args{startwith};
1859 $args{filter} =~ s/\./\[\.\]/g if $args{filter}; # only match literal dots, usually in reverse zones
1860 push @filterargs, $args{filter} if $args{filter};
1861
1862 my $sql;
1863 # Not as compact, and fix-me-twice if the common bits get wrong, but much easier to read
1864 if ($args{revrec} eq 'n') {
1865 $sql = "SELECT count(*) FROM domains".
1866 " WHERE group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
1867 ($args{startwith} ? " AND domain ~* ?" : '').
1868 ($args{filter} ? " AND domain ~* ?" : '');
1869 } else {
1870 $sql = "SELECT count(*) FROM revzones".
1871 " WHERE group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
1872 ($args{startwith} ? " AND CAST(revnet AS VARCHAR) ~* ?" : '').
1873 ($args{filter} ? " AND CAST(revnet AS VARCHAR) ~* ?" : '');
1874 }
1875 my ($count) = $dbh->selectrow_array($sql, undef, @filterargs);
1876 return $count;
1877} # end getZoneCount()
1878
1879
1880## DNSDB::getZoneList()
1881# Get a list of zones in the specified group(s)
1882# Takes the same arguments as getZoneCount() above
1883# Returns a reference to an array of hashrefs suitable for feeding to HTML::Template
1884sub getZoneList {
1885 my $dbh = shift;
1886
1887 my %args = @_;
1888
1889 my @zonelist;
1890
1891 $args{sortorder} = 'ASC' if !grep /^$args{sortorder}$/, ('ASC','DESC');
1892 $args{offset} = 0 if !$args{offset} || $args{offset} !~ /^(?:all|\d+)$/;
1893
1894 my @filterargs;
1895 $args{startwith} = undef if $args{startwith} && $args{startwith} !~ /^(?:[a-z]|0-9)$/;
1896 push @filterargs, "^$args{startwith}" if $args{startwith};
1897 $args{filter} =~ s/\./\[\.\]/g if $args{filter}; # only match literal dots, usually in reverse zones
1898 push @filterargs, $args{filter} if $args{filter};
1899
1900 my $sql;
1901 # Not as compact, and fix-me-twice if the common bits get wrong, but much easier to read
1902 if ($args{revrec} eq 'n') {
1903 $args{sortby} = 'domain' if !grep /^$args{sortby}$/, ('domain','group','status');
1904 $sql = "SELECT domain_id,domain,status,groups.group_name AS group FROM domains".
1905 " INNER JOIN groups ON domains.group_id=groups.group_id".
1906 " WHERE domains.group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
1907 ($args{startwith} ? " AND domain ~* ?" : '').
1908 ($args{filter} ? " AND domain ~* ?" : '');
1909 } else {
1910##fixme: arguably startwith here is irrelevant. depends on the UI though.
1911 $args{sortby} = 'revnet' if !grep /^$args{sortby}$/, ('revnet','group','status');
1912 $sql = "SELECT rdns_id,revnet,status,groups.group_name AS group FROM revzones".
1913 " INNER JOIN groups ON revzones.group_id=groups.group_id".
1914 " WHERE revzones.group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
1915 ($args{startwith} ? " AND CAST(revnet AS VARCHAR) ~* ?" : '').
1916 ($args{filter} ? " AND CAST(revnet AS VARCHAR) ~* ?" : '');
1917 }
1918 # A common tail.
1919 $sql .= " ORDER BY ".($args{sortby} eq 'group' ? 'groups.group_name' : $args{sortby})." $args{sortorder} ".
1920 ($args{offset} eq 'all' ? '' : " LIMIT $config{perpage}".
1921 " OFFSET ".$args{offset}*$config{perpage});
1922 my $sth = $dbh->prepare($sql);
1923 $sth->execute(@filterargs);
1924 my $rownum = 0;
1925
1926 while (my @data = $sth->fetchrow_array) {
1927 my %row;
1928 $row{domainid} = $data[0];
1929 $row{domain} = $data[1];
1930 $row{status} = $data[2];
1931 $row{group} = $data[3];
1932 push @zonelist, \%row;
1933 }
1934
1935 return \@zonelist;
1936} # end getZoneList()
1937
1938
1939## DNSDB::addGroup()
1940# Add a group
1941# Takes a database handle, group name, parent group, hashref for permissions,
1942# and optional template-vs-cloneme flag for the default records
1943# Returns a status code and message
1944sub addGroup {
1945 $errstr = '';
1946 my $dbh = shift;
1947 my $groupname = shift;
1948 my $pargroup = shift;
1949 my $permissions = shift;
1950
1951 # 0 indicates "custom", hardcoded.
1952 # Any other value clones that group's default records, if it exists.
1953 my $inherit = shift || 0;
1954##fixme: need a flag to indicate clone records or <?> ?
1955
1956 # Allow transactions, and raise an exception on errors so we can catch it later.
1957 # Use local to make sure these get "reset" properly on exiting this block
1958 local $dbh->{AutoCommit} = 0;
1959 local $dbh->{RaiseError} = 1;
1960
1961 my ($group_id) = $dbh->selectrow_array("SELECT group_id FROM groups WHERE group_name=?", undef, ($groupname));
1962
1963 return ('FAIL', "Group already exists") if $group_id;
1964
1965 # Wrap all the SQL in a transaction
1966 eval {
1967 $dbh->do("INSERT INTO groups (parent_group_id,group_name) VALUES (?,?)", undef, ($pargroup, $groupname) );
1968
1969 my ($groupid) = $dbh->selectrow_array("SELECT currval('groups_group_id_seq')");
1970
1971 # We work through the whole set of permissions instead of specifying them so
1972 # that when we add a new permission, we don't have to change the code anywhere
1973 # that doesn't explicitly deal with that specific permission.
1974 my @permvals;
1975 foreach (@permtypes) {
1976 if (!defined ($permissions->{$_})) {
1977 push @permvals, 0;
1978 } else {
1979 push @permvals, $permissions->{$_};
1980 }
1981 }
1982 $dbh->do("INSERT INTO permissions (group_id,$permlist) values (?".',?'x($#permtypes+1).")",
1983 undef, ($groupid, @permvals) );
1984 my ($permid) = $dbh->selectrow_array("SELECT currval('permissions_permission_id_seq')");
1985 $dbh->do("UPDATE groups SET permission_id=$permid WHERE group_id=$groupid");
1986
1987 # Default records
1988 my $sthf = $dbh->prepare("INSERT INTO default_records (group_id,host,type,val,distance,weight,port,ttl) ".
1989 "VALUES ($groupid,?,?,?,?,?,?,?)");
1990 my $sthr = $dbh->prepare("INSERT INTO default_rev_records (group_id,host,type,val,ttl) ".
1991 "VALUES ($groupid,?,?,?,?)");
1992 if ($inherit) {
1993 # Duplicate records from parent. Actually relying on inherited records feels
1994 # very fragile, and it would be problematic to roll over at a later time.
1995 my $sth2 = $dbh->prepare("SELECT host,type,val,distance,weight,port,ttl FROM default_records WHERE group_id=?");
1996 $sth2->execute($pargroup);
1997 while (my @clonedata = $sth2->fetchrow_array) {
1998 $sthf->execute(@clonedata);
1999 }
2000 # And now the reverse records
2001 $sth2 = $dbh->prepare("SELECT host,type,val,ttl FROM default_rev_records WHERE group_id=?");
2002 $sth2->execute($pargroup);
2003 while (my @clonedata = $sth2->fetchrow_array) {
2004 $sthr->execute(@clonedata);
2005 }
2006 } else {
2007##fixme: Hardcoding is Bad, mmmmkaaaay?
2008 # reasonable basic defaults for SOA, MX, NS, and minimal hosting
2009 # could load from a config file, but somewhere along the line we need hardcoded bits.
2010 $sthf->execute('ns1.example.com:hostmaster.example.com', 6, '10800:3600:604800:10800', 0, 0, 0, 86400);
2011 $sthf->execute('DOMAIN', 1, '192.168.4.2', 0, 0, 0, 7200);
2012 $sthf->execute('DOMAIN', 15, 'mx.example.com', 10, 0, 0, 7200);
2013 $sthf->execute('DOMAIN', 2, 'ns1.example.com', 0, 0, 0, 7200);
2014 $sthf->execute('DOMAIN', 2, 'ns2.example.com', 0, 0, 0, 7200);
2015 $sthf->execute('www.DOMAIN', 5, 'DOMAIN', 0, 0, 0, 7200);
2016 # reasonable basic defaults for generic reverse zone. Same as initial SQL tabledef.
2017 $sthr->execute('hostmaster.ADMINDOMAIN:ns1.ADMINDOMAIN', 6, '10800:3600:604800:10800', 86400);
2018 $sthr->execute('unused-%r.ADMINDOMAIN', 65283, 'ZONE', 3600);
2019 }
2020
2021 _log($dbh, (group_id => $pargroup, entry => "Added group $groupname") );
2022
2023 # once we get here, we should have suceeded.
2024 $dbh->commit;
2025 }; # end eval
2026
2027 if ($@) {
2028 my $msg = $@;
2029 eval { $dbh->rollback; };
2030 if ($config{log_failures}) {
2031 _log($dbh, (group_id => $pargroup, entry => "Failed to add group $groupname: $msg") );
2032 $dbh->commit;
2033 }
2034 return ('FAIL',$msg);
2035 }
2036
2037 return ('OK','OK');
2038} # end addGroup()
2039
2040
2041## DNSDB::delGroup()
2042# Delete a group.
2043# Takes a group ID
2044# Returns a status code and message
2045sub delGroup {
2046 my $dbh = shift;
2047 my $groupid = shift;
2048
2049 # Allow transactions, and raise an exception on errors so we can catch it later.
2050 # Use local to make sure these get "reset" properly on exiting this block
2051 local $dbh->{AutoCommit} = 0;
2052 local $dbh->{RaiseError} = 1;
2053
2054##fixme: locate "knowable" error conditions and deal with them before the eval
2055# ... or inside, whatever.
2056# -> domains still exist in group
2057# -> ...
2058 my $failmsg = '';
2059 my $resultmsg = '';
2060
2061 # collect some pieces for logging and error messages
2062 my $groupname = groupName($dbh,$groupid);
2063 my $parid = parentID($dbh, (id => $groupid, type => 'group'));
2064
2065 # Wrap all the SQL in a transaction
2066 eval {
2067 # Check for Things in the group
2068 $failmsg = "Can't remove group $groupname";
2069 my ($grpcnt) = $dbh->selectrow_array("SELECT count(*) FROM groups WHERE parent_group_id=?", undef, ($groupid));
2070 die "$grpcnt groups still in group\n" if $grpcnt;
2071 my ($domcnt) = $dbh->selectrow_array("SELECT count(*) FROM domains WHERE group_id=?", undef, ($groupid));
2072 die "$domcnt domains still in group\n" if $domcnt;
2073 my ($usercnt) = $dbh->selectrow_array("SELECT count(*) FROM users WHERE group_id=?", undef, ($groupid));
2074 die "$usercnt users still in group\n" if $usercnt;
2075
2076 $failmsg = "Failed to delete default records for $groupname";
2077 $dbh->do("DELETE from default_records WHERE group_id=?", undef, ($groupid));
2078 $failmsg = "Failed to delete default reverse records for $groupname";
2079 $dbh->do("DELETE from default_rev_records WHERE group_id=?", undef, ($groupid));
2080 $failmsg = "Failed to remove group $groupname";
2081 $dbh->do("DELETE from groups WHERE group_id=?", undef, ($groupid));
2082
2083 _log($dbh, (group_id => $parid, entry => "Deleted group $groupname"));
2084 $resultmsg = "Deleted group $groupname";
2085
2086 # once we get here, we should have suceeded.
2087 $dbh->commit;
2088 }; # end eval
2089
2090 if ($@) {
2091 my $msg = $@;
2092 eval { $dbh->rollback; };
2093 if ($config{log_failures}) {
2094 _log($dbh, (group_id => $parid, entry => "$failmsg: $msg"));
2095 $dbh->commit; # since we enabled transactions earlier
2096 }
2097 return ('FAIL',"$failmsg: $msg");
2098 }
2099
2100 return ('OK',$resultmsg);
2101} # end delGroup()
2102
2103
2104## DNSDB::getChildren()
2105# Get a list of all groups whose parent^n is group <n>
2106# Takes a database handle, group ID, reference to an array to put the group IDs in,
2107# and an optional flag to return only immediate children or all children-of-children
2108# default to returning all children
2109# Calls itself
2110sub getChildren {
2111 $errstr = '';
2112 my $dbh = shift;
2113 my $rootgroup = shift;
2114 my $groupdest = shift;
2115 my $immed = shift || 'all';
2116
2117 # special break for default group; otherwise we get stuck.
2118 if ($rootgroup == 1) {
2119 # by definition, group 1 is the Root Of All Groups
2120 my $sth = $dbh->prepare("SELECT group_id FROM groups WHERE NOT (group_id=1)".
2121 ($immed ne 'all' ? " AND parent_group_id=1" : ''));
2122 $sth->execute;
2123 while (my @this = $sth->fetchrow_array) {
2124 push @$groupdest, @this;
2125 }
2126 } else {
2127 my $sth = $dbh->prepare("SELECT group_id FROM groups WHERE parent_group_id=?");
2128 $sth->execute($rootgroup);
2129 return if $sth->rows == 0;
2130 my @grouplist;
2131 while (my ($group) = $sth->fetchrow_array) {
2132 push @$groupdest, $group;
2133 getChildren($dbh,$group,$groupdest) if $immed eq 'all';
2134 }
2135 }
2136} # end getChildren()
2137
2138
2139## DNSDB::groupName()
2140# Return the group name based on a group ID
2141# Takes a database handle and the group ID
2142# Returns the group name or undef on failure
2143sub groupName {
2144 $errstr = '';
2145 my $dbh = shift;
2146 my $groupid = shift;
2147 my $sth = $dbh->prepare("SELECT group_name FROM groups WHERE group_id=?");
2148 $sth->execute($groupid);
2149 my ($groupname) = $sth->fetchrow_array();
2150 $errstr = $DBI::errstr if !$groupname;
2151 return $groupname if $groupname;
2152} # end groupName
2153
2154
2155## DNSDB::getGroupCount()
2156# Get count of subgroups in group or groups
2157# Takes a database handle and hash containing:
2158# - the "current" group
2159# - an array of "acceptable" groups
2160# - Optionally accept a "starts with" and/or "contains" filter argument
2161# Returns an integer count of the resulting group list.
2162sub getGroupCount {
2163 my $dbh = shift;
2164
2165 my %args = @_;
2166
2167 my @filterargs;
2168
2169 $args{startwith} = undef if $args{startwith} && $args{startwith} !~ /^(?:[a-z]|0-9)$/;
2170 push @filterargs, "^$args{startwith}" if $args{startwith};
2171 push @filterargs, $args{filter} if $args{filter};
2172
2173 my $sql = "SELECT count(*) FROM groups ".
2174 "WHERE parent_group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
2175 ($args{startwith} ? " AND group_name ~* ?" : '').
2176 ($args{filter} ? " AND group_name ~* ?" : '');
2177 my ($count) = $dbh->selectrow_array($sql, undef, (@filterargs) );
2178 $errstr = $dbh->errstr if !$count;
2179 return $count;
2180} # end getGroupCount
2181
2182
2183## DNSDB::getGroupList()
2184# Get a list of sub^n-groups in the specified group(s)
2185# Takes the same arguments as getGroupCount() above
2186# Returns an arrayref containing hashrefs suitable for feeding straight to HTML::Template
2187sub getGroupList {
2188 my $dbh = shift;
2189
2190 my %args = @_;
2191
2192 my @filterargs;
2193
2194 $args{startwith} = undef if $args{startwith} && $args{startwith} !~ /^(?:[a-z]|0-9)$/;
2195 push @filterargs, "^$args{startwith}" if $args{startwith};
2196 push @filterargs, $args{filter} if $args{filter};
2197
2198 # protection against bad or missing arguments
2199 $args{sortorder} = 'ASC' if !$args{sortorder};
2200 $args{offset} = 0 if !$args{offset};
2201
2202 # munge sortby for columns in database
2203 $args{sortby} = 'g.group_name' if $args{sortby} eq 'group';
2204 $args{sortby} = 'g2.group_name' if $args{sortby} eq 'parent';
2205
2206 my $sql = q(SELECT g.group_id AS groupid, g.group_name AS groupname, g2.group_name AS pgroup,
2207 count(distinct(u.username)) AS nusers, count(distinct(d.domain)) AS ndomains,
2208 count(distinct(r.revnet)) AS nrevzones
2209 FROM groups g
2210 INNER JOIN groups g2 ON g2.group_id=g.parent_group_id
2211 LEFT OUTER JOIN users u ON u.group_id=g.group_id
2212 LEFT OUTER JOIN domains d ON d.group_id=g.group_id
2213 LEFT OUTER JOIN revzones r ON r.group_id=g.group_id
2214 ).
2215 "WHERE g.parent_group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
2216 ($args{startwith} ? " AND g.group_name ~* ?" : '').
2217 ($args{filter} ? " AND g.group_name ~* ?" : '').
2218 " GROUP BY g.group_id, g.group_name, g2.group_name ".
2219 " ORDER BY $args{sortby} $args{sortorder} ".
2220 ($args{offset} eq 'all' ? '' : " LIMIT $config{perpage} OFFSET ".$args{offset}*$config{perpage});
2221 my $glist = $dbh->selectall_arrayref($sql, { Slice => {} }, (@filterargs) );
2222 $errstr = $dbh->errstr if !$glist;
2223 return $glist;
2224} # end getGroupList
2225
2226
2227## DNSDB::groupID()
2228# Return the group ID based on the group name
2229# Takes a database handle and the group name
2230# Returns the group ID or undef on failure
2231sub groupID {
2232 $errstr = '';
2233 my $dbh = shift;
2234 my $group = shift;
2235 my ($grpid) = $dbh->selectrow_array("SELECT group_id FROM groups WHERE group=?", undef, ($group) );
2236 $errstr = $DBI::errstr if !$grpid;
2237 return $grpid if $grpid;
2238} # end groupID()
2239
2240
2241## DNSDB::addUser()
2242# Add a user.
2243# Takes a DB handle, username, group ID, password, state (active/inactive).
2244# Optionally accepts:
2245# user type (user/admin) - defaults to user
2246# permissions string - defaults to inherit from group
2247# three valid forms:
2248# i - Inherit permissions
2249# c:<user_id> - Clone permissions from <user_id>
2250# C:<permission list> - Set these specific permissions
2251# first name - defaults to username
2252# last name - defaults to blank
2253# phone - defaults to blank (could put other data within column def)
2254# Returns (OK,<uid>) on success, (FAIL,<message>) on failure
2255sub addUser {
2256 $errstr = '';
2257 my $dbh = shift;
2258 my $username = shift;
2259 my $group = shift;
2260 my $pass = shift;
2261 my $state = shift;
2262
2263 return ('FAIL', "Missing one or more required entries") if !defined($state);
2264 return ('FAIL', "Username must not be blank") if !$username;
2265
2266 my $type = shift || 'u'; # create limited users by default - fwiw, not sure yet how this will interact with ACLs
2267
2268 my $permstring = shift || 'i'; # default is to inhert permissions from group
2269
2270 my $fname = shift || $username;
2271 my $lname = shift || '';
2272 my $phone = shift || ''; # not going format-check
2273
2274 my $sth = $dbh->prepare("SELECT user_id FROM users WHERE username=?");
2275 my $user_id;
2276
2277# quick check to start to see if we've already got one
2278 $sth->execute($username);
2279 ($user_id) = $sth->fetchrow_array;
2280
2281 return ('FAIL', "User already exists") if $user_id;
2282
2283 # Allow transactions, and raise an exception on errors so we can catch it later.
2284 # Use local to make sure these get "reset" properly on exiting this block
2285 local $dbh->{AutoCommit} = 0;
2286 local $dbh->{RaiseError} = 1;
2287
2288 # Wrap all the SQL in a transaction
2289 eval {
2290 # insert the user... note we set inherited perms by default since
2291 # it's simple and cleans up some other bits of state
2292 my $sth = $dbh->prepare("INSERT INTO users ".
2293 "(group_id,username,password,firstname,lastname,phone,type,status,permission_id,inherit_perm) ".
2294 "VALUES (?,?,?,?,?,?,?,?,(SELECT permission_id FROM permissions WHERE group_id=?),'t')");
2295 $sth->execute($group,$username,unix_md5_crypt($pass),$fname,$lname,$phone,$type,$state,$group);
2296
2297 # get the ID...
2298 ($user_id) = $dbh->selectrow_array("SELECT currval('users_user_id_seq')");
2299
2300# Permissions! Gotta set'em all!
2301 die "Invalid permission string $permstring"
2302 if $permstring !~ /^(?:
2303 i # inherit
2304 |c:\d+ # clone
2305 # custom. no, the leading , is not a typo
2306 |C:(?:,(?:group|user|domain|record|self)_(?:edit|create|delete))*
2307 )$/x;
2308# bleh. I'd call another function to do my dirty work, but we're in the middle of a transaction already.
2309 if ($permstring ne 'i') {
2310 # for cloned or custom permissions, we have to create a new permissions entry.
2311 my $clonesrc = $group;
2312 if ($permstring =~ /^c:(\d+)/) { $clonesrc = $1; }
2313 $dbh->do("INSERT INTO permissions ($permlist,user_id) ".
2314 "SELECT $permlist,? FROM permissions WHERE permission_id=".
2315 "(SELECT permission_id FROM permissions WHERE ".($permstring =~ /^c:/ ? 'user' : 'group')."_id=?)",
2316 undef, ($user_id,$clonesrc) );
2317 $dbh->do("UPDATE users SET permission_id=".
2318 "(SELECT permission_id FROM permissions WHERE user_id=?) ".
2319 "WHERE user_id=?", undef, ($user_id, $user_id) );
2320 }
2321 if ($permstring =~ /^C:/) {
2322 # finally for custom permissions, we set the passed-in permissions (and unset
2323 # any that might have been brought in by the clone operation above)
2324 my ($permid) = $dbh->selectrow_array("SELECT permission_id FROM permissions WHERE user_id=?",
2325 undef, ($user_id) );
2326 foreach (@permtypes) {
2327 if ($permstring =~ /,$_/) {
2328 $dbh->do("UPDATE permissions SET $_='t' WHERE permission_id=?", undef, ($permid) );
2329 } else {
2330 $dbh->do("UPDATE permissions SET $_='f' WHERE permission_id=?", undef, ($permid) );
2331 }
2332 }
2333 }
2334
2335 $dbh->do("UPDATE users SET inherit_perm='n' WHERE user_id=?", undef, ($user_id) );
2336
2337##fixme: add another table to hold name/email for log table?
2338
2339 _log($dbh, (group_id => $group, entry => "Added user $username ($fname $lname)"));
2340 # once we get here, we should have suceeded.
2341 $dbh->commit;
2342 }; # end eval
2343
2344 if ($@) {
2345 my $msg = $@;
2346 eval { $dbh->rollback; };
2347 if ($config{log_failures}) {
2348 _log($dbh, (group_id => $group, entry => "Error adding user $username: $msg"));
2349 $dbh->commit; # since we enabled transactions earlier
2350 }
2351 return ('FAIL',"Error adding user $username: $msg");
2352 }
2353
2354 return ('OK',"User $username ($fname $lname) added");
2355} # end addUser
2356
2357
2358## DNSDB::checkUser()
2359# Check user/pass combo on login
2360sub checkUser {
2361 my $dbh = shift;
2362 my $user = shift;
2363 my $inpass = shift;
2364
2365 my $sth = $dbh->prepare("SELECT user_id,group_id,password,firstname,lastname FROM users WHERE username=?");
2366 $sth->execute($user);
2367 my ($uid,$gid,$pass,$fname,$lname) = $sth->fetchrow_array;
2368 my $loginfailed = 1 if !defined($uid);
2369
2370 if ($pass =~ m|^\$1\$([A-Za-z0-9/.]+)\$|) {
2371 $loginfailed = 1 if $pass ne unix_md5_crypt($inpass,$1);
2372 } else {
2373 $loginfailed = 1 if $pass ne $inpass;
2374 }
2375
2376 # nnnngggg
2377 return ($uid, $gid);
2378} # end checkUser
2379
2380
2381## DNSDB:: updateUser()
2382# Update general data about user
2383sub updateUser {
2384 my $dbh = shift;
2385
2386##fixme: tweak calling convention so that we can update any given bit of data
2387 my $uid = shift;
2388 my $username = shift;
2389 my $group = shift;
2390 my $pass = shift;
2391 my $state = shift;
2392 my $type = shift || 'u';
2393 my $fname = shift || $username;
2394 my $lname = shift || '';
2395 my $phone = shift || ''; # not going format-check
2396
2397 my $resultmsg = '';
2398
2399 # Allow transactions, and raise an exception on errors so we can catch it later.
2400 # Use local to make sure these get "reset" properly on exiting this block
2401 local $dbh->{AutoCommit} = 0;
2402 local $dbh->{RaiseError} = 1;
2403
2404 my $sth;
2405
2406 # Password can be left blank; if so we assume there's one on file.
2407 # Actual blank passwords are bad, mm'kay?
2408 if (!$pass) {
2409 ($pass) = $dbh->selectrow_array("SELECT password FROM users WHERE user_id=?", undef, ($uid));
2410 } else {
2411 $pass = unix_md5_crypt($pass);
2412 }
2413
2414 eval {
2415 $dbh->do("UPDATE users SET username=?, password=?, firstname=?, lastname=?, phone=?, type=?, status=?".
2416 " WHERE user_id=?", undef, ($username, $pass, $fname, $lname, $phone, $type, $state, $uid));
2417 $resultmsg = "Updated user info for $username ($fname $lname)";
2418 _log($dbh, group_id => $group, entry => $resultmsg);
2419 $dbh->commit;
2420 };
2421 if ($@) {
2422 my $msg = $@;
2423 eval { $dbh->rollback; };
2424 if ($config{log_failures}) {
2425 _log($dbh, (group_id => $group, entry => "Error updating user $username: $msg"));
2426 $dbh->commit; # since we enabled transactions earlier
2427 }
2428 return ('FAIL',"Error updating user $username: $msg");
2429 }
2430
2431 return ('OK',$resultmsg);
2432} # end updateUser()
2433
2434
2435## DNSDB::delUser()
2436# Delete a user.
2437# Takes a database handle and user ID
2438# Returns a success/failure code and matching message
2439sub delUser {
2440 my $dbh = shift;
2441 my $userid = shift;
2442
2443 return ('FAIL',"Bad userid") if !defined($userid);
2444
2445 my $userdata = getUserData($dbh, $userid);
2446
2447 # Allow transactions, and raise an exception on errors so we can catch it later.
2448 # Use local to make sure these get "reset" properly on exiting this block
2449 local $dbh->{AutoCommit} = 0;
2450 local $dbh->{RaiseError} = 1;
2451
2452 eval {
2453 $dbh->do("DELETE FROM users WHERE user_id=?", undef, ($userid));
2454 _log($dbh, (group_id => $userdata->{group_id},
2455 entry => "Deleted user ID $userid/".$userdata->{username}.
2456 " (".$userdata->{firstname}." ".$userdata->{lastname}.")") );
2457 $dbh->commit;
2458 };
2459 if ($@) {
2460 my $msg = $@;
2461 eval { $dbh->rollback; };
2462 if ($config{log_failures}) {
2463 _log($dbh, (group_id => $userdata->{group_id}, entry => "Error deleting user ID ".
2464 "$userid/".$userdata->{username}.": $msg") );
2465 $dbh->commit;
2466 }
2467 return ('FAIL',"Error deleting user $userid/".$userdata->{username}.": $msg");
2468 }
2469
2470 return ('OK',"Deleted user ".$userdata->{username}." (".$userdata->{firstname}." ".$userdata->{lastname}.")");
2471} # end delUser
2472
2473
2474## DNSDB::userFullName()
2475# Return a pretty string!
2476# Takes a user_id and optional printf-ish string to indicate which pieces where:
2477# %u for the username
2478# %f for the first name
2479# %l for the last name
2480# All other text in the passed string will be left as-is.
2481##fixme: need a "smart" option too, so that missing/null/blank first/last names don't give funky output
2482sub userFullName {
2483 $errstr = '';
2484 my $dbh = shift;
2485 my $userid = shift;
2486 my $fullformat = shift || '%f %l (%u)';
2487 my $sth = $dbh->prepare("select username,firstname,lastname from users where user_id=?");
2488 $sth->execute($userid);
2489 my ($uname,$fname,$lname) = $sth->fetchrow_array();
2490 $errstr = $DBI::errstr if !$uname;
2491
2492 $fullformat =~ s/\%u/$uname/g;
2493 $fullformat =~ s/\%f/$fname/g;
2494 $fullformat =~ s/\%l/$lname/g;
2495
2496 return $fullformat;
2497} # end userFullName
2498
2499
2500## DNSDB::userStatus()
2501# Sets and/or returns a user's status
2502# Takes a database handle, user ID and optionally a status argument
2503# Returns undef on errors.
2504sub userStatus {
2505 my $dbh = shift;
2506 my $id = shift;
2507 my $newstatus = shift || 'mu';
2508
2509 return undef if $id !~ /^\d+$/;
2510
2511 my $userdata = getUserData($dbh, $id);
2512
2513 # Allow transactions, and raise an exception on errors so we can catch it later.
2514 # Use local to make sure these get "reset" properly on exiting this block
2515 local $dbh->{AutoCommit} = 0;
2516 local $dbh->{RaiseError} = 1;
2517
2518 if ($newstatus ne 'mu') {
2519 # ooo, fun! let's see what we were passed for status
2520 eval {
2521 $newstatus = 0 if $newstatus eq 'useroff';
2522 $newstatus = 1 if $newstatus eq 'useron';
2523 $dbh->do("UPDATE users SET status=? WHERE user_id=?", undef, ($newstatus, $id));
2524
2525 $resultstr = ($newstatus ? 'Enabled' : 'Disabled')." user ".$userdata->{username}.
2526 " (".$userdata->{firstname}." ".$userdata->{lastname}.")";
2527
2528 my %loghash;
2529 $loghash{group_id} = parentID($dbh, (id => $id, type => 'user'));
2530 $loghash{entry} = $resultstr;
2531 _log($dbh, %loghash);
2532
2533 $dbh->commit;
2534 };
2535 if ($@) {
2536 my $msg = $@;
2537 eval { $dbh->rollback; };
2538 $resultstr = '';
2539 $errstr = $msg;
2540##fixme: failure logging?
2541 return;
2542 }
2543 }
2544
2545 my ($status) = $dbh->selectrow_array("SELECT status FROM users WHERE user_id=?", undef, ($id));
2546 return $status;
2547} # end userStatus()
2548
2549
2550## DNSDB::getUserData()
2551# Get misc user data for display
2552sub getUserData {
2553 my $dbh = shift;
2554 my $uid = shift;
2555
2556 my $sth = $dbh->prepare("SELECT group_id,username,firstname,lastname,phone,type,status,inherit_perm ".
2557 "FROM users WHERE user_id=?");
2558 $sth->execute($uid);
2559 return $sth->fetchrow_hashref();
2560
2561} # end getUserData()
2562
2563
2564## DNSDB::getSOA()
2565# Return all suitable fields from an SOA record in separate elements of a hash
2566# Takes a database handle, default/live flag, domain/reverse flag, and parent ID
2567sub getSOA {
2568 $errstr = '';
2569 my $dbh = shift;
2570 my $def = shift;
2571 my $rev = shift;
2572 my $id = shift;
2573
2574 # (ab)use distance and weight columns to store SOA data? can't for default_rev_records...
2575 # - should really attach serial to the zone parent somewhere
2576
2577 my $sql = "SELECT record_id,host,val,ttl from "._rectable($def,$rev).
2578 " WHERE "._recparent($def,$rev)." = ? AND type=$reverse_typemap{SOA}";
2579 my $ret = $dbh->selectrow_hashref($sql, undef, ($id) );
2580 return if !$ret;
2581##fixme: stick a flag somewhere if the record doesn't exist. by the API, this is an impossible case, but...
2582
2583 ($ret->{contact},$ret->{prins}) = split /:/, $ret->{host};
2584 delete $ret->{host};
2585 ($ret->{refresh},$ret->{retry},$ret->{expire},$ret->{minttl}) = split /:/, $ret->{val};
2586 delete $ret->{val};
2587
2588 return $ret;
2589} # end getSOA()
2590
2591
2592## DNSDB::updateSOA()
2593# Update the specified SOA record
2594# Takes a database handle, default/live flag, forward/reverse flag, and SOA data hash
2595# Returns a two-element list with a result code and message
2596sub updateSOA {
2597 my $dbh = shift;
2598 my $defrec = shift;
2599 my $revrec = shift;
2600
2601 my %soa = @_;
2602
2603 my $oldsoa = getSOA($dbh, $defrec, $revrec, $soa{id});
2604
2605 my $msg;
2606 my %logdata;
2607 if ($defrec eq 'n') {
2608 $logdata{domain_id} = $soa{id} if $revrec eq 'n';
2609 $logdata{rdns_id} = $soa{id} if $revrec eq 'y';
2610 $logdata{group_id} = parentID($dbh, (id => $soa{id}, revrec => $revrec,
2611 type => ($revrec eq 'n' ? 'domain' : 'revzone') ) );
2612 } else {
2613 $logdata{group_id} = $soa{id};
2614 }
2615 my $parname = ($defrec eq 'y' ? groupName($dbh, $soa{id}) :
2616 ($revrec eq 'n' ? domainName($dbh, $soa{id}) : revName($dbh, $soa{id})) );
2617
2618 # Allow transactions, and raise an exception on errors so we can catch it later.
2619 # Use local to make sure these get "reset" properly on exiting this block
2620 local $dbh->{AutoCommit} = 0;
2621 local $dbh->{RaiseError} = 1;
2622
2623 eval {
2624 my $sql = "UPDATE "._rectable($defrec, $revrec)." SET host=?, val=?, ttl=? WHERE record_id=? AND type=6";
2625 $dbh->do($sql, undef, ("$soa{contact}:$soa{prins}", "$soa{refresh}:$soa{retry}:$soa{expire}:$soa{minttl}",
2626 $soa{ttl}, $oldsoa->{record_id}) );
2627 $msg = "Updated ".($defrec eq 'y' ? ($revrec eq 'y' ? 'default reverse ' : 'default ') : '').
2628 "SOA for $parname: ".
2629 "(ns $oldsoa->{prins}, contact $oldsoa->{contact}, refresh $oldsoa->{refresh},".
2630 " retry $oldsoa->{retry}, expire $oldsoa->{expire}, minTTL $oldsoa->{minttl}, TTL $oldsoa->{ttl}) to ".
2631 "(ns $soa{prins}, contact $soa{contact}, refresh $soa{refresh},".
2632 " retry $soa{retry}, expire $soa{expire}, minTTL $soa{minttl}, TTL $soa{ttl})";
2633
2634 $logdata{entry} = $msg;
2635 _log($dbh, %logdata);
2636
2637 $dbh->commit;
2638 };
2639 if ($@) {
2640 $msg = $@;
2641 eval { $dbh->rollback; };
2642 $logdata{entry} = "Error updating ".($defrec eq 'y' ? ($revrec eq 'y' ? 'default reverse zone ' : 'default ') : '').
2643 "SOA record for $parname: $msg";
2644 if ($config{log_failures}) {
2645 _log($dbh, %logdata);
2646 $dbh->commit;
2647 }
2648 return ('FAIL', $logdata{entry});
2649 } else {
2650 return ('OK', $msg);
2651 }
2652} # end updateSOA()
2653
2654
2655## DNSDB::getRecLine()
2656# Return all data fields for a zone record in separate elements of a hash
2657# Takes a database handle, default/live flag, forward/reverse flag, and record ID
2658sub getRecLine {
2659 $errstr = '';
2660 my $dbh = shift;
2661 my $defrec = shift;
2662 my $revrec = shift;
2663 my $id = shift;
2664
2665 my $sql = "SELECT record_id,host,type,val,ttl".($revrec eq 'n' ? ',distance,weight,port' : '').
2666 (($defrec eq 'y') ? ',group_id FROM ' : ',domain_id,rdns_id FROM ').
2667 _rectable($defrec,$revrec)." WHERE record_id=?";
2668 my $ret = $dbh->selectrow_hashref($sql, undef, ($id) );
2669
2670 if ($dbh->err) {
2671 $errstr = $DBI::errstr;
2672 return undef;
2673 }
2674
2675 if (!$ret) {
2676 $errstr = "No such record";
2677 return undef;
2678 }
2679
2680 # explicitly set a parent id
2681 if ($defrec eq 'y') {
2682 $ret->{parid} = $ret->{group_id};
2683 } else {
2684 $ret->{parid} = (($revrec eq 'n') ? $ret->{domain_id} : $ret->{rdns_id});
2685 # and a secondary if we have a custom type that lives in both a forward and reverse zone
2686 $ret->{secid} = (($revrec eq 'y') ? $ret->{domain_id} : $ret->{rdns_id}) if $ret->{type} > 65279;
2687 }
2688
2689 return $ret;
2690}
2691
2692
2693##fixme: should use above (getRecLine()) to get lines for below?
2694## DNSDB::getDomRecs()
2695# Return records for a domain
2696# Takes a database handle, default/live flag, group/domain ID, start,
2697# number of records, sort field, and sort order
2698# Returns a reference to an array of hashes
2699sub getDomRecs {
2700 $errstr = '';
2701 my $dbh = shift;
2702 my $def = shift;
2703 my $rev = shift;
2704 my $id = shift;
2705 my $nrecs = shift || 'all';
2706 my $nstart = shift || 0;
2707
2708## for order, need to map input to column names
2709 my $order = shift || 'host';
2710 my $direction = shift || 'ASC';
2711
2712 my $filter = shift || '';
2713
2714 my $sql = "SELECT r.record_id,r.host,r.type,r.val,r.ttl";
2715 $sql .= ",r.distance,r.weight,r.port" if $rev eq 'n';
2716 $sql .= " FROM "._rectable($def,$rev)." r ";
2717 $sql .= "INNER JOIN rectypes t ON r.type=t.val "; # for sorting by type alphabetically
2718 $sql .= "WHERE "._recparent($def,$rev)." = ?";
2719 $sql .= " AND NOT r.type=$reverse_typemap{SOA}";
2720 $sql .= " AND host ~* ?" if $filter;
2721 # use alphaorder column for "correct" ordering of sort-by-type instead of DNS RR type number
2722 $sql .= " ORDER BY ".($order eq 'type' ? 't.alphaorder' : "r.$order")." $direction";
2723
2724 my @bindvars = ($id);
2725 push @bindvars, $filter if $filter;
2726
2727 # just to be ultraparanoid about SQL injection vectors
2728 if ($nstart ne 'all') {
2729 $sql .= " LIMIT ? OFFSET ?";
2730 push @bindvars, $nrecs;
2731 push @bindvars, ($nstart*$nrecs);
2732 }
2733 my $sth = $dbh->prepare($sql) or warn $dbh->errstr;
2734 $sth->execute(@bindvars) or warn "$sql: ".$sth->errstr;
2735
2736 my @retbase;
2737 while (my $ref = $sth->fetchrow_hashref()) {
2738 push @retbase, $ref;
2739 }
2740
2741 my $ret = \@retbase;
2742 return $ret;
2743} # end getDomRecs()
2744
2745
2746## DNSDB::getRecCount()
2747# Return count of non-SOA records in zone (or default records in a group)
2748# Takes a database handle, default/live flag, reverse/forward flag, group/domain ID,
2749# and optional filtering modifier
2750# Returns the count
2751sub getRecCount {
2752 my $dbh = shift;
2753 my $defrec = shift;
2754 my $revrec = shift;
2755 my $id = shift;
2756 my $filter = shift || '';
2757
2758 # keep the nasties down, since we can't ?-sub this bit. :/
2759 # note this is chars allowed in DNS hostnames
2760 $filter =~ s/[^a-zA-Z0-9_.:-]//g;
2761
2762 my @bindvars = ($id);
2763 push @bindvars, $filter if $filter;
2764 my $sql = "SELECT count(*) FROM ".
2765 _rectable($defrec,$revrec).
2766 " WHERE "._recparent($defrec,$revrec)."=? ".
2767 "AND NOT type=$reverse_typemap{SOA}".
2768 ($filter ? " AND host ~* ?" : '');
2769 my ($count) = $dbh->selectrow_array($sql, undef, (@bindvars) );
2770
2771 return $count;
2772
2773} # end getRecCount()
2774
2775
2776## DNSDB::addRec()
2777# Add a new record to a domain or a group's default records
2778# Takes a database handle, default/live flag, group/domain ID,
2779# host, type, value, and TTL
2780# Some types require additional detail: "distance" for MX and SRV,
2781# and weight/port for SRV
2782# Returns a status code and detail message in case of error
2783##fixme: pass a hash with the record data, not a series of separate values
2784sub addRec {
2785 $errstr = '';
2786 my $dbh = shift;
2787 my $defrec = shift;
2788 my $revrec = shift;
2789 my $id = shift; # parent (group_id for defrecs, rdns_id for reverse records,
2790 # domain_id for domain records)
2791
2792 my $host = shift;
2793 my $rectype = shift; # reference so we can coerce it if "+"-types can't find both zones
2794 my $val = shift;
2795 my $ttl = shift;
2796
2797 # prep for validation
2798 my $addr = NetAddr::IP->new($$val);
2799 $$host =~ s/\.+$//; # FQDNs ending in . are an internal detail, and really shouldn't be exposed in the UI.
2800
2801 my $domid = 0;
2802 my $revid = 0;
2803
2804 my $retcode = 'OK'; # assume everything will go OK
2805 my $retmsg = '';
2806
2807 # do simple validation first
2808 return ('FAIL', "TTL must be numeric") unless $ttl =~ /^\d+$/;
2809
2810 # Quick check on hostname parts. Note the regex is more forgiving than the error message;
2811 # domain names technically are case-insensitive, and we use printf-like % codes for a couple
2812 # of types. Other things may also be added to validate default records of several flavours.
2813 return ('FAIL', "Hostnames may not contain anything other than (0-9 a-z . _)")
2814 if $defrec eq 'n' && $$host !~ /^[0-9a-z_%.-]+$/i;
2815
2816 # Collect these even if we're only doing a simple A record so we can call *any* validation sub
2817 my $dist = shift;
2818 my $weight = shift;
2819 my $port = shift;
2820
2821 my $fields;
2822 my @vallist;
2823
2824 # Call the validation sub for the type requested.
2825 ($retcode,$retmsg) = $validators{$$rectype}($dbh, (defrec => $defrec, revrec => $revrec, id => $id,
2826 host => $host, rectype => $rectype, val => $val, addr => $addr,
2827 dist => \$dist, port => \$port, weight => \$weight,
2828 fields => \$fields, vallist => \@vallist) );
2829
2830 return ($retcode,$retmsg) if $retcode eq 'FAIL';
2831
2832 # Set up database fields and bind parameters
2833 $fields .= "host,type,val,ttl,"._recparent($defrec,$revrec);
2834 push @vallist, ($$host,$$rectype,$$val,$ttl,$id);
2835 my $vallen = '?'.(',?'x$#vallist);
2836
2837 # Put together the success log entry. We have to use this horrible kludge
2838 # because domain_id and rdns_id may or may not be present, and if they are,
2839 # they're not at a guaranteed consistent index in the array. wheee!
2840 my %logdata;
2841 my @ftmp = split /,/, $fields;
2842 for (my $i=0; $i <= $#vallist; $i++) {
2843 $logdata{domain_id} = $vallist[$i] if $ftmp[$i] eq 'domain_id';
2844 $logdata{rdns_id} = $vallist[$i] if $ftmp[$i] eq 'rdns_id';
2845 }
2846 $logdata{group_id} = $id if $defrec eq 'y';
2847 $logdata{group_id} = parentID($dbh,
2848 (id => $id, type => ($revrec eq 'n' ? 'domain' : 'revzone'), revrec => $revrec) )
2849 if $defrec eq 'n';
2850 $logdata{entry} = "Added ".($defrec eq 'y' ? 'default record' : 'record')." '$$host $typemap{$$rectype} $$val";
2851 $logdata{entry} .= " [distance $dist]" if $typemap{$$rectype} eq 'MX';
2852 $logdata{entry} .= " [priority $dist] [weight $weight] [port $port]"
2853 if $typemap{$$rectype} eq 'SRV';
2854 $logdata{entry} .= "', TTL $ttl";
2855
2856 # Allow transactions, and raise an exception on errors so we can catch it later.
2857 # Use local to make sure these get "reset" properly on exiting this block
2858 local $dbh->{AutoCommit} = 0;
2859 local $dbh->{RaiseError} = 1;
2860
2861 eval {
2862 $dbh->do("INSERT INTO "._rectable($defrec, $revrec)." ($fields) VALUES ($vallen)",
2863 undef, @vallist);
2864 _log($dbh, %logdata);
2865 $dbh->commit;
2866 };
2867 if ($@) {
2868 my $msg = $@;
2869 eval { $dbh->rollback; };
2870 if ($config{log_failures}) {
2871 $logdata{entry} = "Failed adding ".($defrec eq 'y' ? 'default ' : '').
2872 "record '$$host $typemap{$$rectype} $$val', TTL $ttl ($msg)";
2873 _log($dbh, %logdata);
2874 $dbh->commit;
2875 }
2876 return ('FAIL',$msg);
2877 }
2878
2879 $resultstr = $logdata{entry};
2880 return ($retcode, $retmsg);
2881
2882} # end addRec()
2883
2884
2885## DNSDB::updateRec()
2886# Update a record
2887# Takes a database handle, default and reverse flags, record ID, immediate parent ID, and new record data.
2888# Returns a status code and message
2889sub updateRec {
2890 $errstr = '';
2891
2892 my $dbh = shift;
2893 my $defrec = shift;
2894 my $revrec = shift;
2895 my $id = shift;
2896 my $parid = shift; # immediate parent entity that we're descending from to update the record
2897
2898 # all records have these
2899 my $host = shift;
2900 my $hostbk = $$host; # Keep a backup copy of the original, so we can WARN if the update mangles the domain
2901 my $rectype = shift;
2902 my $val = shift;
2903 my $ttl = shift;
2904
2905 # prep for validation
2906 my $addr = NetAddr::IP->new($$val);
2907 $$host =~ s/\.+$//; # FQDNs ending in . are an internal detail, and really shouldn't be exposed in the UI.
2908
2909 my $domid = 0;
2910 my $revid = 0;
2911
2912 my $retcode = 'OK'; # assume everything will go OK
2913 my $retmsg = '';
2914
2915 # do simple validation first
2916 return ('FAIL', "TTL must be numeric") unless $ttl =~ /^\d+$/;
2917
2918 # Quick check on hostname parts. Note the regex is more forgiving than the error message;
2919 # domain names technically are case-insensitive, and we use printf-like % codes for a couple
2920 # of types. Other things may also be added to validate default records of several flavours.
2921 return ('FAIL', "Hostnames may not contain anything other than (0-9 a-z - . _)")
2922 if $defrec eq 'n' && $$host !~ /^[0-9a-z_%.-]+$/i;
2923
2924 # only MX and SRV will use these
2925 my $dist = shift || 0;
2926 my $weight = shift || 0;
2927 my $port = shift || 0;
2928
2929 my $fields;
2930 my @vallist;
2931
2932 # get old record data so we have the right parent ID
2933 # and for logging (eventually)
2934 my $oldrec = getRecLine($dbh, $defrec, $revrec, $id);
2935
2936 # Call the validation sub for the type requested.
2937 # Note the ID to pass here is the *parent*, not the record
2938 ($retcode,$retmsg) = $validators{$$rectype}($dbh, (defrec => $defrec, revrec => $revrec,
2939 id => ($defrec eq 'y' ? $oldrec->{group_id} : ($revrec eq 'n' ? $oldrec->{domain_id} : $oldrec->{rdns_id})),
2940 host => $host, rectype => $rectype, val => $val, addr => $addr,
2941 dist => \$dist, port => \$port, weight => \$weight,
2942 fields => \$fields, vallist => \@vallist,
2943 update => $id) );
2944
2945 return ($retcode,$retmsg) if $retcode eq 'FAIL';
2946
2947 # Set up database fields and bind parameters. Note only the optional fields
2948 # (distance, weight, port, secondary parent ID) are added in the validation call above
2949 $fields .= "host,type,val,ttl,"._recparent($defrec,$revrec);
2950 push @vallist, ($$host,$$rectype,$$val,$ttl,
2951 ($defrec eq 'y' ? $oldrec->{group_id} : ($revrec eq 'n' ? $oldrec->{domain_id} : $oldrec->{rdns_id})) );
2952
2953 # hack hack PTHUI
2954 # need to forcibly make sure we disassociate a record with a parent it's no longer related to.
2955 # eg, PTR records may not have a domain parent, or A/AAAA records may not have a revzone parent.
2956 # mainly needed for crossover types that got coerced down to "standard" types
2957 if ($defrec eq 'n') {
2958 if ($$rectype == $reverse_typemap{PTR}) {
2959 $fields .= ",domain_id";
2960 push @vallist, 0;
2961 }
2962 if ($$rectype == $reverse_typemap{A} || $$rectype == $reverse_typemap{AAAA}) {
2963 $fields .= ",rdns_id";
2964 push @vallist, 0;
2965 }
2966 }
2967
2968 # Fiddle the field list into something suitable for updates
2969 $fields =~ s/,/=?,/g;
2970 $fields .= "=?";
2971
2972 # Put together the success log entry. Horrible kludge from addRec() copied as-is since
2973 # we don't know whether the passed arguments or retrieved values for domain_id and rdns_id
2974 # will be maintained (due to "not-in-zone" validation changes)
2975 my %logdata;
2976 my @ftmp = split /,/, $fields;
2977 for (my $i=0; $i <= $#vallist; $i++) {
2978 $logdata{domain_id} = $vallist[$i] if $ftmp[$i] eq 'domain_id';
2979 $logdata{rdns_id} = $vallist[$i] if $ftmp[$i] eq 'rdns_id';
2980 }
2981 $logdata{group_id} = $parid if $defrec eq 'y';
2982 $logdata{group_id} = parentID($dbh,
2983 (id => $parid, type => ($revrec eq 'n' ? 'domain' : 'revzone'), revrec => $revrec) )
2984 if $defrec eq 'n';
2985 $logdata{entry} = "Updated ".($defrec eq 'y' ? 'default record' : 'record')." from\n".
2986 "'$oldrec->{host} $typemap{$oldrec->{type}} $oldrec->{val}";
2987 $logdata{entry} .= " [distance $oldrec->{distance}]" if $typemap{$oldrec->{type}} eq 'MX';
2988 $logdata{entry} .= " [priority $oldrec->{distance}] [weight $oldrec->{weight}] [port $oldrec->{port}]"
2989 if $typemap{$oldrec->{type}} eq 'SRV';
2990 $logdata{entry} .= "', TTL $oldrec->{ttl}\nto\n'$$host $typemap{$$rectype} $$val";
2991 $logdata{entry} .= " [distance $dist]" if $typemap{$$rectype} eq 'MX';
2992 $logdata{entry} .= " [priority $dist] [weight $weight] [port $port]" if $typemap{$$rectype} eq 'SRV';
2993 $logdata{entry} .= "', TTL $ttl";
2994
2995 local $dbh->{AutoCommit} = 0;
2996 local $dbh->{RaiseError} = 1;
2997
2998 eval {
2999 $dbh->do("UPDATE "._rectable($defrec,$revrec)." SET $fields WHERE record_id=?", undef, (@vallist, $id) );
3000 _log($dbh, %logdata);
3001 $dbh->commit;
3002 };
3003 if ($@) {
3004 my $msg = $@;
3005 eval { $dbh->rollback; };
3006 if ($config{log_failures}) {
3007 $logdata{entry} = "Failed updating ".($defrec eq 'y' ? 'default ' : '').
3008 "record '$oldrec->{host} $typemap{$oldrec->{type}} $oldrec->{val}', TTL $oldrec->{ttl} ($msg)";
3009 _log($dbh, %logdata);
3010 $dbh->commit;
3011 }
3012 return ('FAIL', $msg);
3013 }
3014
3015 $resultstr = $logdata{entry};
3016 return ($retcode, $retmsg);
3017} # end updateRec()
3018
3019
3020## DNSDB::delRec()
3021# Delete a record.
3022sub delRec {
3023 $errstr = '';
3024 my $dbh = shift;
3025 my $defrec = shift;
3026 my $revrec = shift;
3027 my $id = shift;
3028
3029 my $oldrec = getRecLine($dbh, $defrec, $revrec, $id);
3030
3031 # Allow transactions, and raise an exception on errors so we can catch it later.
3032 # Use local to make sure these get "reset" properly on exiting this block
3033 local $dbh->{AutoCommit} = 0;
3034 local $dbh->{RaiseError} = 1;
3035
3036 # Put together the log entry
3037 my %logdata;
3038 $logdata{domain_id} = $oldrec->{domain_id};
3039 $logdata{rdns_id} = $oldrec->{rdns_id};
3040 $logdata{group_id} = $oldrec->{group_id} if $defrec eq 'y';
3041 $logdata{group_id} = parentID($dbh,
3042 (id => $oldrec->{domain_id}, type => ($revrec eq 'n' ? 'domain' : 'revzone'), revrec => $revrec) )
3043 if $defrec eq 'n';
3044 $logdata{entry} = "Deleted ".($defrec eq 'y' ? 'default record ' : 'record ').
3045 "'$oldrec->{host} $typemap{$oldrec->{type}} $oldrec->{val}";
3046 $logdata{entry} .= " [distance $oldrec->{distance}]" if $typemap{$oldrec->{type}} eq 'MX';
3047 $logdata{entry} .= " [priority $oldrec->{distance}] [weight $oldrec->{weight}] [port $oldrec->{port}]"
3048 if $typemap{$oldrec->{type}} eq 'SRV';
3049 $logdata{entry} .= "', TTL $oldrec->{ttl}\n";
3050
3051 eval {
3052 my $sth = $dbh->do("DELETE FROM "._rectable($defrec,$revrec)." WHERE record_id=?", undef, ($id));
3053 _log($dbh, %logdata);
3054 $dbh->commit;
3055 };
3056 if ($@) {
3057 my $msg = $@;
3058 eval { $dbh->rollback; };
3059 if ($config{log_failures}) {
3060 $logdata{entry} = "Error deleting ".($defrec eq 'y' ? 'default record' : 'record').
3061 " '$oldrec->{host} $typemap{$oldrec->{type}} $oldrec->{val}', TTL $oldrec->{ttl} ($msg)";
3062 _log($dbh, %logdata);
3063 $dbh->commit;
3064 }
3065 return ('FAIL', $msg);
3066 }
3067
3068 return ('OK',$logdata{entry});
3069} # end delRec()
3070
3071
3072## DNSDB::getTypelist()
3073# Get a list of record types for various UI dropdowns
3074# Takes database handle, forward/reverse/lookup flag, and optional "tag as selected" indicator (defaults to A)
3075# Returns an arrayref to list of hashrefs perfect for HTML::Template
3076sub getTypelist {
3077 my $dbh = shift;
3078 my $recgroup = shift;
3079 my $type = shift || $reverse_typemap{A};
3080
3081 # also accepting $webvar{revrec}!
3082 $recgroup = 'f' if $recgroup eq 'n';
3083 $recgroup = 'r' if $recgroup eq 'y';
3084
3085 my $sql = "SELECT val,name FROM rectypes WHERE ";
3086 if ($recgroup eq 'r') {
3087 # reverse zone types
3088 $sql .= "stdflag=2 OR stdflag=3";
3089 } elsif ($recgroup eq 'l') {
3090 # DNS lookup types. Note we avoid our custom types >= 65280, since those are entirely internal.
3091 $sql .= "(stdflag=1 OR stdflag=2 OR stdflag=3) AND val < 65280";
3092 } else {
3093 # default; forward zone types. technically $type eq 'f' but not worth the error message.
3094 $sql .= "stdflag=1 OR stdflag=2";
3095 }
3096 $sql .= " ORDER BY listorder";
3097
3098 my $sth = $dbh->prepare($sql);
3099 $sth->execute;
3100 my @typelist;
3101 while (my ($rval,$rname) = $sth->fetchrow_array()) {
3102 my %row = ( recval => $rval, recname => $rname );
3103 $row{tselect} = 1 if $rval == $type;
3104 push @typelist, \%row;
3105 }
3106
3107 # Add SOA on lookups since it's not listed in other dropdowns.
3108 if ($recgroup eq 'l') {
3109 my %row = ( recval => $reverse_typemap{SOA}, recname => 'SOA' );
3110 $row{tselect} = 1 if $reverse_typemap{SOA} == $type;
3111 push @typelist, \%row;
3112 }
3113
3114 return \@typelist;
3115} # end getTypelist()
3116
3117
3118## DNSDB::parentID()
3119# Get ID of entity that is nearest parent to requested id
3120# Takes a database handle and a hash of entity ID, entity type, optional parent type flag
3121# (domain/reverse zone or group), and optional default/live and forward/reverse flags
3122# Returns the ID or undef on failure
3123sub parentID {
3124 my $dbh = shift;
3125
3126 my %args = @_;
3127
3128 # clean up the parent-type. Set it to group if not set; coerce revzone to domain for simpler logic
3129 $args{partype} = 'group' if !$args{partype};
3130 $args{partype} = 'domain' if $args{partype} eq 'revzone';
3131
3132 # clean up defrec and revrec. default to live record, forward zone
3133 $args{defrec} = 'n' if !$args{defrec};
3134 $args{revrec} = 'n' if !$args{revrec};
3135
3136 if ($par_type{$args{partype}} eq 'domain') {
3137 # only live records can have a domain/zone parent
3138 return unless ($args{type} eq 'record' && $args{defrec} eq 'n');
3139 my $result = $dbh->selectrow_hashref("SELECT ".($args{revrec} eq 'n' ? 'domain_id' : 'rdns_id').
3140 " FROM records WHERE record_id = ?",
3141 undef, ($args{id}) ) or return;
3142 return $result;
3143 } else {
3144 # snag some arguments that will either fall through or be overwritten to save some code duplication
3145 my $tmpid = $args{id};
3146 my $type = $args{type};
3147 if ($type eq 'record' && $args{defrec} eq 'n') {
3148 # Live records go through the records table first.
3149 ($tmpid) = $dbh->selectrow_array("SELECT ".($args{revrec} eq 'n' ? 'domain_id' : 'rdns_id').
3150 " FROM records WHERE record_id = ?",
3151 undef, ($args{id}) ) or return;
3152 $type = ($args{revrec} eq 'n' ? 'domain' : 'revzone');
3153 }
3154 my ($result) = $dbh->selectrow_array("SELECT $par_col{$type} FROM $par_tbl{$type} WHERE $id_col{$type} = ?",
3155 undef, ($tmpid) );
3156 return $result;
3157 }
3158# should be impossible to get here with even remotely sane arguments
3159 return;
3160} # end parentID()
3161
3162
3163## DNSDB::isParent()
3164# Returns true if $id1 is a parent of $id2, false otherwise
3165sub isParent {
3166 my $dbh = shift;
3167 my $id1 = shift;
3168 my $type1 = shift;
3169 my $id2 = shift;
3170 my $type2 = shift;
3171##todo: immediate, secondary, full (default)
3172
3173 # Return false on invalid types
3174 return 0 if !grep /^$type1$/, ('record','defrec','defrevrec','user','domain','revzone','group');
3175 return 0 if !grep /^$type2$/, ('record','defrec','defrevrec','user','domain','revzone','group');
3176
3177 # Return false on impossible relations
3178 return 0 if $type1 eq 'record'; # nothing may be a child of a record
3179 return 0 if $type1 eq 'defrec'; # nothing may be a child of a record
3180 return 0 if $type1 eq 'defrevrec'; # nothing may be a child of a record
3181 return 0 if $type1 eq 'user'; # nothing may be child of a user
3182 return 0 if $type1 eq 'domain' && $type2 ne 'record'; # domain may not be a parent of anything other than a record
3183 return 0 if $type1 eq 'revzone' && $type2 ne 'record';# reverse zone may not be a parent of anything other than a record
3184
3185 # ennnhhhh.... if we're passed an id of 0, it will never be found. usual
3186 # case would be the UI creating a new <thing>, and so we don't have an ID for
3187 # <thing> to look up yet. in that case the UI should check the parent as well.
3188 return 0 if $id1 == 0; # nothing can have a parent id of 0
3189 return 1 if $id2 == 0; # anything could have a child id of 0 (or "unknown")
3190
3191 # group 1 is the ultimate root parent
3192 return 1 if $type1 eq 'group' && $id1 == 1;
3193
3194 # groups are always (a) parent of themselves
3195 return 1 if $type1 eq 'group' && $type2 eq 'group' && $id1 == $id2;
3196
3197 my $id = $id2;
3198 my $type = $type2;
3199 my $foundparent = 0;
3200
3201 # Records are the only entity with two possible parents. We need to split the parent checks on
3202 # domain/rdns.
3203 if ($type eq 'record') {
3204 my ($dom,$rdns) = $dbh->selectrow_array("SELECT domain_id,rdns_id FROM records WHERE record_id=?",
3205 undef, ($id));
3206 # check immediate parent against request
3207 return 1 if $type1 eq 'domain' && $id1 == $dom;
3208 return 1 if $type1 eq 'revzone' && $id1 == $rdns;
3209 # if request is group, check *both* parents. Only check if the parent is nonzero though.
3210 return 1 if $dom && isParent($dbh, $id1, $type1, $dom, 'domain');
3211 return 1 if $rdns && isParent($dbh, $id1, $type1, $rdns, 'revzone');
3212 # exit here since we've executed the loop below by proxy in the above recursive calls.
3213 return 0;
3214 }
3215
3216# almost the same loop as getParents() above
3217 my $limiter = 0;
3218 while (1) {
3219 my $sql = "SELECT $par_col{$type} FROM $par_tbl{$type} WHERE $id_col{$type} = ?";
3220 my $result = $dbh->selectrow_hashref($sql,
3221 undef, ($id) );
3222 if (!$result) {
3223 $limiter++;
3224##fixme: how often will this happen on a live site? fail at max limiter <n>?
3225 warn "no results looking for $sql with id $id (depth $limiter)\n";
3226 last;
3227 }
3228 if ($result && $result->{$par_col{$type}} == $id1) {
3229 $foundparent = 1;
3230 last;
3231 } else {
3232##fixme: do we care about trying to return a "no such record/domain/user/group" error?
3233# should be impossible to create an inconsistent DB just with API calls.
3234 warn $dbh->errstr." $sql, $id" if $dbh->errstr;
3235 }
3236 # group 1 is its own parent. need this here more to break strange loops than for detecting a parent
3237 last if $result->{$par_col{$type}} == 1;
3238 $id = $result->{$par_col{$type}};
3239 $type = $par_type{$type};
3240 }
3241
3242 return $foundparent;
3243} # end isParent()
3244
3245
3246## DNSDB::zoneStatus()
3247# Returns and optionally sets a zone's status
3248# Takes a database handle, domain/revzone ID, forward/reverse flag, and optionally a status argument
3249# Returns status, or undef on errors.
3250sub zoneStatus {
3251 my $dbh = shift;
3252 my $id = shift;
3253 my $revrec = shift;
3254 my $newstatus = shift || 'mu';
3255
3256 return undef if $id !~ /^\d+$/;
3257
3258 # Allow transactions, and raise an exception on errors so we can catch it later.
3259 # Use local to make sure these get "reset" properly on exiting this block
3260 local $dbh->{AutoCommit} = 0;
3261 local $dbh->{RaiseError} = 1;
3262
3263 if ($newstatus ne 'mu') {
3264 # ooo, fun! let's see what we were passed for status
3265 eval {
3266 $newstatus = 0 if $newstatus eq 'domoff';
3267 $newstatus = 1 if $newstatus eq 'domon';
3268 $dbh->do("UPDATE ".($revrec eq 'n' ? 'domains' : 'revzones')." SET status=? WHERE ".
3269 ($revrec eq 'n' ? 'domain_id' : 'rdns_id')."=?", undef, ($newstatus,$id) );
3270
3271##fixme switch to more consise "Enabled <domain"/"Disabled <domain>" as with users?
3272 $resultstr = "Changed ".($revrec eq 'n' ? domainName($dbh, $id) : revName($dbh, $id)).
3273 " state to ".($newstatus ? 'active' : 'inactive');
3274
3275 my %loghash;
3276 $loghash{domain_id} = $id if $revrec eq 'n';
3277 $loghash{rdns_id} = $id if $revrec eq 'y';
3278 $loghash{group_id} = parentID($dbh,
3279 (id => $id, type => ($revrec eq 'n' ? 'domain' : 'revzone'), revrec => $revrec) );
3280 $loghash{entry} = $resultstr;
3281 _log($dbh, %loghash);
3282
3283 $dbh->commit;
3284 };
3285 if ($@) {
3286 my $msg = $@;
3287 eval { $dbh->rollback; };
3288 $resultstr = '';
3289 $errstr = $msg;
3290 return;
3291 }
3292 }
3293
3294 my ($status) = $dbh->selectrow_array("SELECT status FROM ".
3295 ($revrec eq 'n' ? "domains WHERE domain_id=?" : "revzones WHERE rdns_id=?"),
3296 undef, ($id) );
3297 return $status;
3298} # end zoneStatus()
3299
3300
3301## DNSDB::importAXFR
3302# Import a domain via AXFR
3303# Takes AXFR host, domain to transfer, group to put the domain in,
3304# and optionally:
3305# - active/inactive state flag (defaults to active)
3306# - overwrite-SOA flag (defaults to off)
3307# - overwrite-NS flag (defaults to off, doesn't affect subdomain NS records)
3308# Returns a status code (OK, WARN, or FAIL) and message - message should be blank
3309# if status is OK, but WARN includes conditions that are not fatal but should
3310# really be reported.
3311sub importAXFR {
3312 my $dbh = shift;
3313 my $ifrom_in = shift;
3314 my $zone = shift;
3315 my $group = shift;
3316 my $status = shift || 1;
3317 my $rwsoa = shift || 0;
3318 my $rwns = shift || 0;
3319 my $merge = shift || 0; # do we attempt to merge A/AAAA and PTR records whenever possible?
3320 # do we overload this with the fixme below?
3321##fixme: add mode to delete&replace, merge+overwrite, merge new?
3322
3323 my $nrecs = 0;
3324 my $soaflag = 0;
3325 my $nsflag = 0;
3326 my $warnmsg = '';
3327 my $ifrom;
3328
3329 my $rev = 'n';
3330 my $code = 'OK';
3331 my $msg = 'foobar?';
3332
3333 # choke on possible bad setting in ifrom
3334 # IPv4 and v6, and valid hostnames!
3335 ($ifrom) = ($ifrom_in =~ /^([0-9a-f\:.]+|[0-9a-z_.-]+)$/i);
3336 return ('FAIL', "Bad AXFR source host $ifrom")
3337 unless ($ifrom) = ($ifrom_in =~ /^([0-9a-f\:.]+|[0-9a-z_.-]+)$/i);
3338
3339 my $errmsg;
3340
3341 my $zone_id;
3342 my $domain_id = 0;
3343 my $rdns_id = 0;
3344 my $cidr;
3345
3346# magic happens! detect if we're importing a domain or a reverse zone
3347# while we're at it, figure out what the CIDR netblock is (if we got a .arpa)
3348# or what the formal .arpa zone is (if we got a CIDR netblock)
3349# Handles sub-octet v4 zones in the format specified in the Cricket Book, 2nd Ed, p217-218
3350
3351 if ($zone =~ m{(?:\.arpa\.?|/\d+)$}) {
3352 # we seem to have a reverse zone
3353 $rev = 'y';
3354
3355 if ($zone =~ /\.arpa\.?$/) {
3356 # we have a formal reverse zone. call _zone2cidr and get the CIDR block.
3357 ($code,$msg) = _zone2cidr($zone);
3358 return ($code, $msg) if $code eq 'FAIL';
3359 $cidr = $msg;
3360 } elsif ($zone =~ m|^[\d.]+/\d+$|) {
3361 # v4 revzone, CIDR netblock
3362 $cidr = NetAddr::IP->new($zone) or return ('FAIL',"$zone is not a valid CIDR block");
3363 $zone = _ZONE($cidr, 'ZONE.in-addr.arpa', 'r', '.');
3364 } elsif ($zone =~ m|^[a-fA-F\d:]+/\d+$|) {
3365 # v6 revzone, CIDR netblock
3366 $cidr = NetAddr::IP->new($zone) or return ('FAIL',"$zone is not a valid CIDR block");
3367 return ('FAIL', "$zone is not a nibble-aligned block") if $cidr->masklen % 4 != 0;
3368 $zone = _ZONE($cidr, 'ZONE.ip6.arpa', 'r', '.');
3369 } else {
3370 # there is. no. else!
3371 return ('FAIL', "Unknown zone name format");
3372 }
3373
3374 # quick check to start to see if we've already got one
3375
3376 ($zone_id) = $dbh->selectrow_array("SELECT rdns_id FROM revzones WHERE revnet=?",
3377 undef, ("$cidr"));
3378 $rdns_id = $zone_id;
3379 } else {
3380 # default to domain
3381 ($zone_id) = $dbh->selectrow_array("SELECT domain_id FROM domains WHERE domain=?",
3382 undef, ($zone));
3383 $domain_id = $zone_id;
3384 }
3385
3386 return ('FAIL', ($rev eq 'n' ? 'Domain' : 'Reverse zone')." already exists") if $zone_id;
3387
3388 # little local utility sub to swap $val and $host for revzone records.
3389 sub _revswap {
3390 my $rechost = shift;
3391 my $recdata = shift;
3392
3393 if ($rechost =~ /\.in-addr\.arpa\.?$/) {
3394 $rechost =~ s/\.in-addr\.arpa\.?$//;
3395 $rechost = join '.', reverse split /\./, $rechost;
3396 } else {
3397 $rechost =~ s/\.ip6\.arpa\.?$//;
3398 my @nibs = reverse split /\./, $rechost;
3399 $rechost = '';
3400 my $nc;
3401 foreach (@nibs) {
3402 $rechost.= $_;
3403 $rechost .= ":" if ++$nc % 4 == 0 && $nc < 32;
3404 }
3405 $rechost .= ":" if $nc < 32 && $rechost !~ /\*$/; # close netblock records?
3406##fixme: there's a case that ends up with a partial entry here:
3407# ip:add:re:ss::
3408# can't reproduce after letting it sit overnight after discovery. :(
3409#print "$rechost\n";
3410 # canonicalize with NetAddr::IP
3411 $rechost = NetAddr::IP->new($rechost)->addr unless $rechost =~ /\*$/;
3412 }
3413 return ($recdata,$rechost)
3414 }
3415
3416
3417 # Allow transactions, and raise an exception on errors so we can catch it later.
3418 # Use local to make sure these get "reset" properly on exiting this block
3419 local $dbh->{AutoCommit} = 0;
3420 local $dbh->{RaiseError} = 1;
3421
3422 my $sth;
3423 eval {
3424
3425 if ($rev eq 'n') {
3426##fixme: serial
3427 $dbh->do("INSERT INTO domains (domain,group_id,status) VALUES (?,?,?)", undef, ($zone,$group,$status) );
3428 # get domain id so we can do the records
3429 ($zone_id) = $dbh->selectrow_array("SELECT currval('domains_domain_id_seq')");
3430 $domain_id = $zone_id;
3431 _log($dbh, (group_id => $group, domain_id => $domain_id,
3432 entry => "[Added ".($status ? 'active' : 'inactive')." domain $zone via AXFR]") );
3433 } else {
3434##fixme: serial
3435 $dbh->do("INSERT INTO revzones (revnet,group_id,status) VALUES (?,?,?)", undef, ($cidr,$group,$status) );
3436 # get revzone id so we can do the records
3437 ($zone_id) = $dbh->selectrow_array("SELECT currval('revzones_rdns_id_seq')");
3438 $rdns_id = $zone_id;
3439 _log($dbh, (group_id => $group, rdns_id => $rdns_id,
3440 entry => "[Added ".($status ? 'active' : 'inactive')." reverse zone $cidr via AXFR]") );
3441 }
3442
3443## bizarre DBI<->Net::DNS interaction bug:
3444## sometimes a zone will cause an immediate commit-and-exit (sort of) of the while()
3445## fixed, apparently I was doing *something* odd, but not certain what it was that
3446## caused a commit instead of barfing
3447
3448 my $res = Net::DNS::Resolver->new;
3449 $res->nameservers($ifrom);
3450 $res->axfr_start($zone)
3451 or die "Couldn't begin AXFR\n";
3452
3453 $sth = $dbh->prepare("INSERT INTO records (domain_id,rdns_id,host,type,val,distance,weight,port,ttl)".
3454 " VALUES (?,?,?,?,?,?,?,?,?)");
3455
3456 # Stash info about sub-octet v4 revzones here so we don't have
3457 # to store the CNAMEs used to delegate a suboctet zone
3458 # $suboct{zone}{ns}[] -> array of nameservers
3459 # $suboct{zone}{cname}[] -> array of extant CNAMEs (Just In Case someone did something bizarre)
3460## commented pending actual use of this data. for now, we'll just
3461## auto-(re)create the CNAMEs in revzones on export
3462# my %suboct;
3463
3464 while (my $rr = $res->axfr_next()) {
3465
3466 my $val;
3467 my $distance = 0;
3468 my $weight = 0;
3469 my $port = 0;
3470 my $logfrag = '';
3471
3472 my $type = $rr->type;
3473 my $host = $rr->name;
3474 my $ttl = $rr->ttl;
3475
3476 $soaflag = 1 if $type eq 'SOA';
3477 $nsflag = 1 if $type eq 'NS';
3478
3479# "Primary" types:
3480# A, NS, CNAME, SOA, PTR(warn in forward), MX, TXT, AAAA, SRV, A6(ob), SPF
3481# maybe KEY
3482
3483# BIND supports:
3484# [standard]
3485# A AAAA CNAME MX NS PTR SOA TXT
3486# [variously experimental, obsolete, or obscure]
3487# HINFO MB(ex) MD(ob) MF(ob) MG(ex) MINFO(ex) MR(ex) NULL WKS AFSDB(ex) ISDN(ex) RP(ex) RT(ex) X25(ex) PX
3488# ... if one can ever find the right magic to format them correctly
3489
3490# Net::DNS supports:
3491# RRSIG SIG NSAP NS NIMLOC NAPTR MX MR MINFO MG MB LOC ISDN IPSECKEY HINFO
3492# EID DNAME CNAME CERT APL AFSDB AAAA A DS NXT NSEC3PARAM NSEC3 NSEC KEY
3493# DNSKEY DLV X25 TXT TSIG TKEY SSHFP SRV SPF SOA RT RP PX PTR NULL APL::AplItem
3494
3495# nasty big ugly case-like thing here, since we have to do *some* different
3496# processing depending on the record. le sigh.
3497
3498##fixme: what record types other than TXT can/will have >255-byte payloads?
3499
3500 if ($type eq 'A') {
3501 $val = $rr->address;
3502 } elsif ($type eq 'NS') {
3503# hmm. should we warn here if subdomain NS'es are left alone?
3504 next if ($rwns && ($rr->name eq $zone));
3505 if ($rev eq 'y') {
3506 # revzones have records more or less reversed from forward zones.
3507 my ($tmpcode,$tmpmsg) = _zone2cidr($host);
3508 die "Error converting NS record: $tmpmsg" if $tmpcode eq 'FAIL'; # hmm. may not make sense...
3509 $val = "$tmpmsg";
3510 $host = $rr->nsdname;
3511 $logfrag = "Added record '$val $type $host', TTL $ttl";
3512# Tag and preserve. For now this is commented for a no-op, but we have Ideas for
3513# another custom storage type ("DELEGATE") that will use these subzone-delegation records
3514#if ($val ne "$cidr") {
3515# push @{$suboct{$val}{ns}}, $host;
3516#}
3517 } else {
3518 $val = $rr->nsdname;
3519 }
3520 $nsflag = 1;
3521 } elsif ($type eq 'CNAME') {
3522 if ($rev eq 'y') {
3523 # hmm. do we even want to bother with storing these at this level? Sub-octet delegation
3524 # by CNAME is essentially a record-publication hack, and we want to just represent the
3525 # "true" logical intentions as far down the stack as we can from the UI.
3526 ($host,$val) = _revswap($host,$rr->cname);
3527 $logfrag = "Added record '$val $type $host', TTL $ttl";
3528# Tag and preserve in case we want to commit them as-is later, but mostly we don't care.
3529# Commented pending actually doing something with possibly new type DELEGATE
3530#my $tmprev = $host;
3531#$tmprev =~ s/^\d+\.//;
3532#($code,$tmprev) = _zone2cidr($tmprev);
3533#push @{$suboct{"$tmprev"}{cname}}, $val;
3534 # Silently skip CNAMEs in revzones.
3535 next;
3536 } else {
3537 $val = $rr->cname;
3538 }
3539 } elsif ($type eq 'SOA') {
3540 next if $rwsoa;
3541 $host = $rr->rname.":".$rr->mname;
3542 $val = $rr->refresh.":".$rr->retry.":".$rr->expire.":".$rr->minimum;
3543 $soaflag = 1;
3544 } elsif ($type eq 'PTR') {
3545 ($host,$val) = _revswap($host,$rr->ptrdname);
3546 $logfrag = "Added record '$val $type $host', TTL $ttl";
3547 # hmm. PTR records should not be in forward zones.
3548 } elsif ($type eq 'MX') {
3549 $val = $rr->exchange;
3550 $distance = $rr->preference;
3551 } elsif ($type eq 'TXT') {
3552##fixme: Net::DNS docs say this should be deprecated for rdatastr() or char_str_list(),
3553## but don't really seem enthusiastic about it.
3554#print "should use rdatastr:\n\t".$rr->rdatastr."\n or char_str_list:\n\t".join(' ',$rr->char_str_list())."\n";
3555# rdatastr returns a BIND-targetted logical string, including opening and closing quotes
3556# char_str_list returns a list of the individual string fragments in the record
3557# txtdata returns the more useful all-in-one form (since we want to push such protocol
3558# details as far down the stack as we can)
3559# NB: this may turn out to be more troublesome if we ever have need of >512-byte TXT records.
3560 if ($rev eq 'y') {
3561 ($host,$val) = _revswap($host,$rr->txtdata);
3562 $logfrag = "Added record '$val $type $host', TTL $ttl";
3563 } else {
3564 $val = $rr->txtdata;
3565 }
3566 } elsif ($type eq 'SPF') {
3567##fixme: and the same caveat here, since it is apparently a clone of ::TXT
3568 $val = $rr->txtdata;
3569 } elsif ($type eq 'AAAA') {
3570 $val = $rr->address;
3571 } elsif ($type eq 'SRV') {
3572 $val = $rr->target;
3573 $distance = $rr->priority;
3574 $weight = $rr->weight;
3575 $port = $rr->port;
3576 } elsif ($type eq 'KEY') {
3577 # we don't actually know what to do with these...
3578 $val = $rr->flags.":".$rr->protocol.":".$rr->algorithm.":".$rr->key.":".$rr->keytag.":".$rr->privatekeyname;
3579 } else {
3580 $val = $rr->rdatastr;
3581 # Finding a different record type is not fatal.... just problematic.
3582 # We may not be able to export it correctly.
3583 $warnmsg .= "Unusual record ".$rr->name." ($type) found\n";
3584 }
3585
3586 my $logentry = "[AXFR ".($rev eq 'n' ? $zone : $cidr)."] ";
3587
3588 if ($merge) {
3589 if ($rev eq 'n') {
3590 # importing a domain; we have A and AAAA records that could be merged with matching PTR records
3591 my $etype;
3592 my ($erdns,$erid,$ettl) = $dbh->selectrow_array("SELECT rdns_id,record_id,ttl FROM records ".
3593 "WHERE host=? AND val=? AND type=12",
3594 undef, ($host, $val) );
3595 if ($erid) {
3596 if ($type eq 'A') { # PTR -> A+PTR
3597 $etype = 65280;
3598 $logentry .= "Merged A record with existing PTR record '$host A+PTR $val', TTL $ettl";
3599 }
3600 if ($type eq 'AAAA') { # PTR -> AAAA+PTR
3601 $etype = 65281;
3602 $logentry .= "Merged AAAA record with existing PTR record '$host AAAA+PTR $val', TTL $ettl";
3603 }
3604 $ettl = ($ettl < $ttl ? $ettl : $ttl); # use lower TTL
3605 $dbh->do("UPDATE records SET domain_id=?,ttl=?,type=? WHERE record_id=?", undef,
3606 ($domain_id, $ettl, $etype, $erid));
3607 $nrecs++;
3608 _log($dbh, (group_id => $group, domain_id => $domain_id, rdns_id => $erdns, entry => $logentry) );
3609 next; # while axfr_next
3610 }
3611 } # $rev eq 'n'
3612 else {
3613 # importing a revzone, we have PTR records that could be merged with matching A/AAAA records
3614 my ($domid,$erid,$ettl,$etype) = $dbh->selectrow_array("SELECT domain_id,record_id,ttl,type FROM records ".
3615 "WHERE host=? AND val=? AND (type=1 OR type=28)",
3616 undef, ($host, $val) );
3617 if ($erid) {
3618 if ($etype == 1) { # A -> A+PTR
3619 $etype = 65280;
3620 $logentry .= "Merged PTR record with existing matching A record '$host A+PTR $val', TTL $ettl";
3621 }
3622 if ($etype == 28) { # AAAA -> AAAA+PTR
3623 $etype = 65281;
3624 $logentry .= "Merged PTR record with existing matching AAAA record '$host AAAA+PTR $val', TTL $ettl";
3625 }
3626 $ettl = ($ettl < $ttl ? $ettl : $ttl); # use lower TTL
3627 $dbh->do("UPDATE records SET rdns_id=?,ttl=?,type=? WHERE record_id=?", undef,
3628 ($rdns_id, $ettl, $etype, $erid));
3629 $nrecs++;
3630 _log($dbh, (group_id => $group, domain_id => $domid, rdns_id => $rdns_id, entry => $logentry) );
3631 next; # while axfr_next
3632 }
3633 } # $rev eq 'y'
3634 } # if $merge
3635
3636 # Insert the new record
3637 $sth->execute($domain_id, $rdns_id, $host, $reverse_typemap{$type}, $val,
3638 $distance, $weight, $port, $ttl);
3639
3640 $nrecs++;
3641
3642 if ($type eq 'SOA') {
3643 # also !$rwsoa, but if that's set, it should be impossible to get here.
3644 my @tmp1 = split /:/, $host;
3645 my @tmp2 = split /:/, $val;
3646 $logentry .= "Added SOA record [contact $tmp1[0]] [master $tmp1[1]] ".
3647 "[refresh $tmp2[0]] [retry $tmp2[1]] [expire $tmp2[2]] [minttl $tmp2[3]], TTL $ttl";
3648 } elsif ($logfrag) {
3649 # special case for log entries we need to meddle with a little.
3650 $logentry .= $logfrag;
3651 } else {
3652 $logentry .= "Added record '$host $type";
3653 $logentry .= " [distance $distance]" if $type eq 'MX';
3654 $logentry .= " [priority $distance] [weight $weight] [port $port]" if $type eq 'SRV';
3655 $logentry .= " $val', TTL $ttl";
3656 }
3657 _log($dbh, (group_id => $group, domain_id => $domain_id, rdns_id => $rdns_id, entry => $logentry) );
3658
3659 } # while axfr_next
3660
3661# Detect and handle delegated subzones
3662# Placeholder for when we decide what to actually do with this, see previous comments in NS and CNAME handling.
3663#foreach (keys %suboct) {
3664# print "found ".($suboct{$_}{ns} ? @{$suboct{$_}{ns}} : '0')." NS records and ".
3665# ($suboct{$_}{cname} ? @{$suboct{$_}{cname}} : '0')." CNAMEs for $_\n";
3666#}
3667
3668 # Overwrite SOA record
3669 if ($rwsoa) {
3670 $soaflag = 1;
3671 my $sthgetsoa = $dbh->prepare("SELECT host,val,ttl FROM default_records WHERE group_id=? AND type=?");
3672 my $sthputsoa = $dbh->prepare("INSERT INTO records (domain_id,host,type,val,ttl) VALUES (?,?,?,?,?)");
3673 $sthgetsoa->execute($group,$reverse_typemap{SOA});
3674 while (my ($host,$val,$ttl) = $sthgetsoa->fetchrow_array()) {
3675 $host =~ s/DOMAIN/$zone/g;
3676 $val =~ s/DOMAIN/$zone/g;
3677 $sthputsoa->execute($zone_id,$host,$reverse_typemap{SOA},$val,$ttl);
3678 }
3679 }
3680
3681 # Overwrite NS records
3682 if ($rwns) {
3683 $nsflag = 1;
3684 my $sthgetns = $dbh->prepare("SELECT host,val,ttl FROM default_records WHERE group_id=? AND type=?");
3685 my $sthputns = $dbh->prepare("INSERT INTO records (domain_id,host,type,val,ttl) VALUES (?,?,?,?,?)");
3686 $sthgetns->execute($group,$reverse_typemap{NS});
3687 while (my ($host,$val,$ttl) = $sthgetns->fetchrow_array()) {
3688 $host =~ s/DOMAIN/$zone/g;
3689 $val =~ s/DOMAIN/$zone/g;
3690 $sthputns->execute($zone_id,$host,$reverse_typemap{NS},$val,$ttl);
3691 }
3692 }
3693
3694 die "No records found; either $ifrom is not authoritative or doesn't allow transfers\n" if !$nrecs;
3695 die "Bad zone: No SOA record!\n" if !$soaflag;
3696 die "Bad zone: No NS records!\n" if !$nsflag;
3697
3698 $dbh->commit;
3699
3700 };
3701
3702 if ($@) {
3703 my $msg = $@;
3704 eval { $dbh->rollback; };
3705 return ('FAIL',$msg." $warnmsg");
3706 } else {
3707 return ('WARN', $warnmsg) if $warnmsg;
3708 return ('OK',"Imported OK");
3709 }
3710
3711 # it should be impossible to get here.
3712 return ('WARN',"OOOK!");
3713} # end importAXFR()
3714
3715
3716## DNSDB::importBIND()
3717sub importBIND {
3718} # end importBIND()
3719
3720
3721## DNSDB::import_tinydns()
3722sub import_tinydns {
3723} # end import_tinydns()
3724
3725
3726## DNSDB::export()
3727# Export the DNS database, or a part of it
3728# Takes database handle, export type, optional arguments depending on type
3729# Writes zone data to targets as appropriate for type
3730sub export {
3731 my $dbh = shift;
3732 my $target = shift;
3733
3734 if ($target eq 'tiny') {
3735 __export_tiny($dbh,@_);
3736 }
3737# elsif ($target eq 'foo') {
3738# __export_foo($dbh,@_);
3739#}
3740# etc
3741
3742} # end export()
3743
3744
3745## DNSDB::__export_tiny
3746# Internal sub to implement tinyDNS (compatible) export
3747# Takes database handle, filehandle to write export to, optional argument(s)
3748# to determine which data gets exported
3749sub __export_tiny {
3750 my $dbh = shift;
3751 my $datafile = shift;
3752
3753##fixme: slurp up further options to specify particular zone(s) to export
3754
3755 ## Convert a bare number into an octal-coded pair of octets.
3756 # Take optional arg to indicate a decimal or hex input. Defaults to hex.
3757 sub octalize {
3758 my $tmp = shift;
3759 my $srctype = shift || 'h'; # default assumes hex string
3760 $tmp = sprintf "%0.4x", hex($tmp) if $srctype eq 'h'; # 0-pad hex to 4 digits
3761 $tmp = sprintf "%0.4x", $tmp if $srctype eq 'd'; # 0-pad decimal to 4 hex digits
3762 my @o = ($tmp =~ /^(..)(..)$/); # split into octets
3763 return sprintf "\\%0.3o\\%0.3o", hex($o[0]), hex($o[1]);;
3764 }
3765
3766##fixme: fail if $datafile isn't an open, writable file
3767
3768 # easy case - export all evarything
3769 # not-so-easy case - export item(s) specified
3770 # todo: figure out what kind of list we use to export items
3771
3772 my $domsth = $dbh->prepare("SELECT domain_id,domain,status FROM domains WHERE status=1");
3773 my $recsth = $dbh->prepare("SELECT host,type,val,distance,weight,port,ttl ".
3774 "FROM records WHERE domain_id=?");
3775 $domsth->execute();
3776 while (my ($domid,$dom,$domstat) = $domsth->fetchrow_array) {
3777 $recsth->execute($domid);
3778 while (my ($host,$type,$val,$dist,$weight,$port,$ttl) = $recsth->fetchrow_array) {
3779##fixme: need to store location in the db, and retrieve it here.
3780# temporarily hardcoded to empty so we can include it further down.
3781my $loc = '';
3782
3783##fixme: record validity timestamp. tinydns supports fiddling with timestamps.
3784# note $ttl must be set to 0 if we want to use tinydns's auto-expiring timestamps.
3785# timestamps are TAI64
3786# ~~ 2^62 + time()
3787my $stamp = '';
3788
3789# raw packet in unknown format: first byte indicates length
3790# of remaining data, allows up to 255 raw bytes
3791
3792##fixme? append . to all host/val hostnames
3793 if ($typemap{$type} eq 'SOA') {
3794
3795 # host contains pri-ns:responsible
3796 # val is abused to contain refresh:retry:expire:minttl
3797##fixme: "manual" serial vs tinydns-autoserial
3798 # let's be explicit about abusing $host and $val
3799 my ($email, $primary) = (split /:/, $host)[0,1];
3800 my ($refresh, $retry, $expire, $min_ttl) = (split /:/, $val)[0,1,2,3];
3801 print $datafile "Z$dom:$primary:$email"."::$refresh:$retry:$expire:$min_ttl:$ttl:$stamp:$loc\n";
3802
3803 } elsif ($typemap{$type} eq 'A') {
3804
3805 print $datafile "+$host:$val:$ttl:$stamp:$loc\n";
3806
3807 } elsif ($typemap{$type} eq 'NS') {
3808
3809 print $datafile "\&$host"."::$val:$ttl:$stamp:$loc\n";
3810
3811 } elsif ($typemap{$type} eq 'AAAA') {
3812
3813 print $datafile ":$host:28:";
3814 my $altgrp = 0;
3815 my @altconv;
3816 # Split in to up to 8 groups of hex digits (allows for IPv6 :: 0-collapsing)
3817 foreach (split /:/, $val) {
3818 if (/^$/) {
3819 # flag blank entry; this is a series of 0's of (currently) unknown length
3820 $altconv[$altgrp++] = 's';
3821 } else {
3822 # call sub to convert 1-4 hex digits to 2 string-rep octal bytes
3823 $altconv[$altgrp++] = octalize($_)
3824 }
3825 }
3826 foreach my $octet (@altconv) {
3827 # if not 's', output
3828 print $datafile $octet unless $octet =~ /^s$/;
3829 # if 's', output (9-array length)x literal '\000\000'
3830 print $datafile '\000\000'x(9-$altgrp) if $octet =~ /^s$/;
3831 }
3832 print $datafile ":$ttl:$stamp:$loc\n";
3833
3834 } elsif ($typemap{$type} eq 'MX') {
3835
3836 print $datafile "\@$host"."::$val:$dist:$ttl:$stamp:$loc\n";
3837
3838 } elsif ($typemap{$type} eq 'TXT') {
3839
3840##fixme: split v-e-r-y long TXT strings? will need to do so for BIND export, at least
3841 $val =~ s/:/\\072/g; # may need to replace other symbols
3842 print $datafile "'$host:$val:$ttl:$stamp:$loc\n";
3843
3844# by-hand TXT
3845#:deepnet.cx:16:2v\075spf1\040a\040a\072bacon.deepnet.cx\040a\072home.deepnet.cx\040-all:3600
3846#@ IN TXT "v=spf1 a a:bacon.deepnet.cx a:home.deepnet.cx -all"
3847#'deepnet.cx:v=spf1 a a\072bacon.deepnet.cx a\072home.deepnet.cx -all:3600
3848
3849#txttest IN TXT "v=foo bar:bob kn;ob' \" !@#$%^&*()-=_+[]{}<>?"
3850#: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
3851
3852# very long TXT record as brought in by axfr-get
3853# note tinydns does not support >512-byte RR data, need axfr-dns (for TCP support) for that
3854# also note, tinydns does not seem to support <512, >256-byte RRdata from axfr-get either. :/
3855#:longtxt.deepnet.cx:16:
3856#\170this is a very long txt record. it is really long. long. very long. really very long. this is a very long txt record.
3857#\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.
3858#\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.
3859#:3600
3860
3861 } elsif ($typemap{$type} eq 'CNAME') {
3862
3863 print $datafile "C$host:$val:$ttl:$stamp:$loc\n";
3864
3865 } elsif ($typemap{$type} eq 'SRV') {
3866
3867 # data is two-byte values for priority, weight, port, in that order,
3868 # followed by length/string data
3869
3870 print $datafile ":$host:33:".octalize($dist,'d').octalize($weight,'d').octalize($port,'d');
3871
3872 $val .= '.' if $val !~ /\.$/;
3873 foreach (split /\./, $val) {
3874 printf $datafile "\\%0.3o%s", length($_), $_;
3875 }
3876 print $datafile "\\000:$ttl:$stamp:$loc\n";
3877
3878 } elsif ($typemap{$type} eq 'RP') {
3879
3880 # RP consists of two mostly free-form strings.
3881 # The first is supposed to be an email address with @ replaced by . (as with the SOA contact)
3882 # The second is the "hostname" of a TXT record with more info.
3883 print $datafile ":$host:17:";
3884 my ($who,$what) = split /\s/, $val;
3885 foreach (split /\./, $who) {
3886 printf $datafile "\\%0.3o%s", length($_), $_;
3887 }
3888 print $datafile '\000';
3889 foreach (split /\./, $what) {
3890 printf $datafile "\\%0.3o%s", length($_), $_;
3891 }
3892 print $datafile "\\000:$ttl:$stamp:$loc\n";
3893
3894 } elsif ($typemap{$type} eq 'PTR') {
3895
3896 # must handle both IPv4 and IPv6
3897##work
3898 # data should already be in suitable reverse order.
3899 print $datafile "^$host:$val:$ttl:$stamp:$loc\n";
3900
3901 } else {
3902 # raw record. we don't know what's in here, so we ASS-U-ME the user has
3903 # put it in correctly, since either the user is messing directly with the
3904 # database, or the record was imported via AXFR
3905 # <split by char>
3906 # convert anything not a-zA-Z0-9.- to octal coding
3907
3908##fixme: add flag to export "unknown" record types - note we'll probably end up
3909# mangling them since they were written to the DB from Net::DNS::RR::<type>->rdatastr.
3910 #print $datafile ":$host:$type:$val:$ttl:$stamp:$loc\n";
3911
3912 } # record type if-else
3913
3914 } # while ($recsth)
3915 } # while ($domsth)
3916} # end __export_tiny()
3917
3918
3919## DNSDB::mailNotify()
3920# Sends notification mail to recipients regarding a DNSDB operation
3921sub mailNotify {
3922 my $dbh = shift;
3923 my ($subj,$message) = @_;
3924
3925 return if $config{mailhost} eq 'smtp.example.com'; # do nothing if still using default SMTP host.
3926
3927 my $mailer = Net::SMTP->new($config{mailhost}, Hello => "dnsadmin.$config{domain}");
3928
3929 my $mailsender = ($config{mailsender} ? $config{mailsender} : $config{mailnotify});
3930
3931 $mailer->mail($mailsender);
3932 $mailer->to($config{mailnotify});
3933 $mailer->data("From: \"$config{mailname}\" <$mailsender>\n",
3934 "To: <$config{mailnotify}>\n",
3935 "Date: ".strftime("%a, %d %b %Y %H:%M:%S %z",localtime)."\n",
3936 "Subject: $subj\n",
3937 "X-Mailer: DNSAdmin Notify v".sprintf("%.1d",$DNSDB::VERSION)."\n",
3938 "Organization: $config{orgname}\n",
3939 "\n$message\n");
3940 $mailer->quit;
3941}
3942
3943# shut Perl up
39441;
Note: See TracBrowser for help on using the repository browser.