source: trunk/DNSDB.pm@ 314

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

/trunk

Move SQL for "Manage groups" to DNSDB.pm. See #1
Extend new group list sub to return a revzone count. See #26

  • Property svn:keywords set to Date Rev Author Id
File size: 138.0 KB
Line 
1# dns/trunk/DNSDB.pm
2# Abstraction functions for DNS administration
3##
4# $Id: DNSDB.pm 314 2012-04-24 20:43:39Z kdeugau $
5# Copyright 2008-2011 Kris Deugau <kdeugau@deepnet.cx>
6#
7# This program is free software: you can redistribute it and/or modify
8# it under the terms of the GNU General Public License as published by
9# the Free Software Foundation, either version 3 of the License, or
10# (at your option) any later version.
11#
12# This program is distributed in the hope that it will be useful,
13# but WITHOUT ANY WARRANTY; without even the implied warranty of
14# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15# GNU General Public License for more details.
16#
17# You should have received a copy of the GNU General Public License
18# along with this program. If not, see <http://www.gnu.org/licenses/>.
19##
20
21package DNSDB;
22
23use strict;
24use warnings;
25use Exporter;
26use DBI;
27use Net::DNS;
28use Crypt::PasswdMD5;
29use Net::SMTP;
30use NetAddr::IP qw(:lower);
31use POSIX;
32use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
33
34$VERSION = 0.1; ##VERSION##
35@ISA = qw(Exporter);
36@EXPORT_OK = qw(
37 &initGlobals &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# and password matches the one on file
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 FROM users WHERE username=?",
1160 undef, ($user) );
1161 return if !$userinfo;
1162
1163 if ($userinfo->{password} =~ m|^\$1\$([A-Za-z0-9/.]+)\$|) {
1164 # native passwords (crypt-md5)
1165 return if $userinfo->{password} ne unix_md5_crypt($pass,$1);
1166 } elsif ($userinfo->{password} =~ /^[0-9a-f]{32}$/) {
1167 # VegaDNS import (hex-coded MD5)
1168 return if $userinfo->{password} ne md5_hex($pass);
1169 } else {
1170 # plaintext (convenient now and then)
1171 return if $userinfo->{password} ne $pass;
1172 }
1173
1174 return $userinfo;
1175} # end login()
1176
1177
1178## DNSDB::initActionLog()
1179# Set up action logging. Takes a database handle and user ID
1180# Sets some internal globals and Does The Right Thing to set up a logging channel.
1181# This sets up _log() to spew out log entries to the defined channel without worrying
1182# about having to open a file or a syslog channel
1183##fixme Need to call _initActionLog_blah() for various logging channels, configured
1184# via dnsdb.conf, in $config{log_channel} or something
1185# See https://secure.deepnet.cx/trac/dnsadmin/ticket/21
1186sub initActionLog {
1187 my $dbh = shift;
1188 my $uid = shift;
1189
1190 return if !$uid;
1191
1192 # snag user info for logging. there's got to be a way to not have to pass this back
1193 # and forth from a caller, but web usage means no persistence we can rely on from
1194 # the server side.
1195 my ($username,$fullname) = $dbh->selectrow_array("SELECT username, firstname || ' ' || lastname".
1196 " FROM users WHERE user_id=?", undef, ($uid));
1197##fixme: errors are unpossible!
1198
1199 $userdata{username} = $username;
1200 $userdata{userid} = $uid;
1201 $userdata{fullname} = $fullname;
1202
1203 # convert to real check once we have other logging channels
1204 # if ($config{log_channel} eq 'sql') {
1205 # Open Log, Sez Me!
1206 # }
1207
1208} # end initActionLog
1209
1210
1211## DNSDB::initPermissions()
1212# Set up permissions global
1213# Takes database handle and UID
1214sub initPermissions {
1215 my $dbh = shift;
1216 my $uid = shift;
1217
1218# %permissions = $(getPermissions($dbh,'user',$uid));
1219 getPermissions($dbh, 'user', $uid, \%permissions);
1220
1221} # end initPermissions()
1222
1223
1224## DNSDB::getPermissions()
1225# Get permissions from DB
1226# Requires DB handle, group or user flag, ID, and hashref.
1227sub getPermissions {
1228 my $dbh = shift;
1229 my $type = shift;
1230 my $id = shift;
1231 my $hash = shift;
1232
1233 my $sql = qq(
1234 SELECT
1235 p.admin,p.self_edit,
1236 p.group_create,p.group_edit,p.group_delete,
1237 p.user_create,p.user_edit,p.user_delete,
1238 p.domain_create,p.domain_edit,p.domain_delete,
1239 p.record_create,p.record_edit,p.record_delete
1240 FROM permissions p
1241 );
1242 if ($type eq 'group') {
1243 $sql .= qq(
1244 JOIN groups g ON g.permission_id=p.permission_id
1245 WHERE g.group_id=?
1246 );
1247 } else {
1248 $sql .= qq(
1249 JOIN users u ON u.permission_id=p.permission_id
1250 WHERE u.user_id=?
1251 );
1252 }
1253
1254 my $sth = $dbh->prepare($sql);
1255
1256 $sth->execute($id) or die "argh: ".$sth->errstr;
1257
1258# my $permref = $sth->fetchrow_hashref;
1259# return $permref;
1260# $hash = $permref;
1261# Eww. Need to learn how to forcibly drop a hashref onto an existing hash.
1262 ($hash->{admin},$hash->{self_edit},
1263 $hash->{group_create},$hash->{group_edit},$hash->{group_delete},
1264 $hash->{user_create},$hash->{user_edit},$hash->{user_delete},
1265 $hash->{domain_create},$hash->{domain_edit},$hash->{domain_delete},
1266 $hash->{record_create},$hash->{record_edit},$hash->{record_delete})
1267 = $sth->fetchrow_array;
1268
1269} # end getPermissions()
1270
1271
1272## DNSDB::changePermissions()
1273# Update an ACL entry
1274# Takes a db handle, type, owner-id, and hashref for the changed permissions.
1275sub changePermissions {
1276 my $dbh = shift;
1277 my $type = shift;
1278 my $id = shift;
1279 my $newperms = shift;
1280 my $inherit = shift || 0;
1281
1282 my $resultmsg = '';
1283
1284 # see if we're switching from inherited to custom. for bonus points,
1285 # snag the permid and parent permid anyway, since we'll need the permid
1286 # to set/alter custom perms, and both if we're switching from custom to
1287 # inherited.
1288 my $sth = $dbh->prepare("SELECT (u.permission_id=g.permission_id) AS was_inherited,u.permission_id,g.permission_id,".
1289 ($type eq 'user' ? 'u.group_id,u.username' : 'u.parent_group_id,u.group_name').
1290 " FROM ".($type eq 'user' ? 'users' : 'groups')." u ".
1291 " JOIN groups g ON u.".($type eq 'user' ? '' : 'parent_')."group_id=g.group_id ".
1292 " WHERE u.".($type eq 'user' ? 'user' : 'group')."_id=?");
1293 $sth->execute($id);
1294
1295 my ($wasinherited,$permid,$parpermid,$parid,$name) = $sth->fetchrow_array;
1296
1297# hack phtoui
1298# group id 1 is "special" in that it's it's own parent (err... possibly.)
1299# may make its parent id 0 which doesn't exist, and as a bonus is Perl-false.
1300 $wasinherited = 0 if ($type eq 'group' && $id == 1);
1301
1302 local $dbh->{AutoCommit} = 0;
1303 local $dbh->{RaiseError} = 1;
1304
1305 # Wrap all the SQL in a transaction
1306 eval {
1307 if ($inherit) {
1308
1309 $dbh->do("UPDATE ".($type eq 'user' ? 'users' : 'groups')." SET inherit_perm='t',permission_id=? ".
1310 "WHERE ".($type eq 'user' ? 'user' : 'group')."_id=?", undef, ($parpermid, $id) );
1311 $dbh->do("DELETE FROM permissions WHERE permission_id=?", undef, ($permid) );
1312
1313 } else {
1314
1315 if ($wasinherited) { # munge new permission entry in if we're switching from inherited perms
1316##fixme: need to add semirecursive bit to properly munge inherited permission ID on subgroups and users
1317# ... if'n'when we have groups with fully inherited permissions.
1318 # SQL is coo
1319 $dbh->do("INSERT INTO permissions ($permlist,".($type eq 'user' ? 'user' : 'group')."_id) ".
1320 "SELECT $permlist,? FROM permissions WHERE permission_id=?", undef, ($id,$permid) );
1321 ($permid) = $dbh->selectrow_array("SELECT permission_id FROM permissions ".
1322 "WHERE ".($type eq 'user' ? 'user' : 'group')."_id=?", undef, ($id) );
1323 $dbh->do("UPDATE ".($type eq 'user' ? 'users' : 'groups')." SET inherit_perm='f',permission_id=? ".
1324 "WHERE ".($type eq 'user' ? 'user' : 'group')."_id=?", undef, ($permid, $id) );
1325 }
1326
1327 # and now set the permissions we were passed
1328 foreach (@permtypes) {
1329 if (defined ($newperms->{$_})) {
1330 $dbh->do("UPDATE permissions SET $_=? WHERE permission_id=?", undef, ($newperms->{$_},$permid) );
1331 }
1332 }
1333
1334 } # (inherited->)? custom
1335
1336 if ($type eq 'user') {
1337 $resultmsg = "Updated permissions for user $name";
1338 } else {
1339 $resultmsg = "Updated default permissions for group $name";
1340 }
1341 _log($dbh, (group_id => ($type eq 'user' ? $parid : $id), entry => $resultmsg));
1342 $dbh->commit;
1343 }; # end eval
1344 if ($@) {
1345 my $msg = $@;
1346 eval { $dbh->rollback; };
1347 return ('FAIL',"Error changing permissions: $msg");
1348 }
1349
1350 return ('OK',$resultmsg);
1351} # end changePermissions()
1352
1353
1354## DNSDB::comparePermissions()
1355# Compare two permission hashes
1356# Returns '>', '<', '=', '!'
1357sub comparePermissions {
1358 my $p1 = shift;
1359 my $p2 = shift;
1360
1361 my $retval = '='; # assume equality until proven otherwise
1362
1363 no warnings "uninitialized";
1364
1365 foreach (@permtypes) {
1366 next if $p1->{$_} == $p2->{$_}; # equal is good
1367 if ($p1->{$_} && !$p2->{$_}) {
1368 if ($retval eq '<') { # if we've already found an unequal pair where
1369 $retval = '!'; # $p2 has more access, and we now find a pair
1370 last; # where $p1 has more access, the overall access
1371 } # is neither greater or lesser, it's unequal.
1372 $retval = '>';
1373 }
1374 if (!$p1->{$_} && $p2->{$_}) {
1375 if ($retval eq '>') { # if we've already found an unequal pair where
1376 $retval = '!'; # $p1 has more access, and we now find a pair
1377 last; # where $p2 has more access, the overall access
1378 } # is neither greater or lesser, it's unequal.
1379 $retval = '<';
1380 }
1381 }
1382 return $retval;
1383} # end comparePermissions()
1384
1385
1386## DNSDB::changeGroup()
1387# Change group ID of an entity
1388# Takes a database handle, entity type, entity ID, and new group ID
1389sub changeGroup {
1390 my $dbh = shift;
1391 my $type = shift;
1392 my $id = shift;
1393 my $newgrp = shift;
1394
1395##fixme: fail on not enough args
1396 #return ('FAIL', "Missing
1397
1398 return ('FAIL', "Can't change the group of a $type")
1399 unless grep /^$type$/, ('domain','revzone','user','group'); # could be extended for defrecs?
1400
1401 # Collect some names for logging and messages
1402 my $entname;
1403 if ($type eq 'domain') {
1404 $entname = domainName($dbh, $id);
1405 } elsif ($type eq 'revzone') {
1406 $entname = revName($dbh, $id);
1407 } elsif ($type eq 'user') {
1408 $entname = userFullName($dbh, $id, '%u');
1409 } elsif ($type eq 'group') {
1410 $entname = groupName($dbh, $id);
1411 }
1412
1413 my ($oldgid) = $dbh->selectrow_array("SELECT group_id FROM $par_tbl{$type} WHERE $id_col{$type}=?",
1414 undef, ($id));
1415 my $oldgname = groupName($dbh, $oldgid);
1416 my $newgname = groupName($dbh, $newgrp);
1417
1418 return ('FAIL', "Can't move things into a group that doesn't exist") if !$newgname;
1419
1420 return ('WARN', "Nothing to do, new group is the same as the old group") if $oldgid == $newgrp;
1421
1422 # Allow transactions, and raise an exception on errors so we can catch it later.
1423 # Use local to make sure these get "reset" properly on exiting this block
1424 local $dbh->{AutoCommit} = 0;
1425 local $dbh->{RaiseError} = 1;
1426
1427 eval {
1428 $dbh->do("UPDATE $par_tbl{$type} SET group_id=? WHERE $id_col{$type}=?", undef, ($newgrp, $id));
1429 # Log the change in both the old and new groups
1430 _log($dbh, (group_id => $oldgid, entry => "Moved $type $entname from $oldgname to $newgname"));
1431 _log($dbh, (group_id => $newgrp, entry => "Moved $type $entname from $oldgname to $newgname"));
1432 $dbh->commit;
1433 };
1434 if ($@) {
1435 my $msg = $@;
1436 eval { $dbh->rollback; };
1437 if ($config{log_failures}) {
1438 _log($dbh, (group_id => $oldgid, entry => "Error moving $type $entname to $newgname: $msg"));
1439 $dbh->commit; # since we enabled transactions earlier
1440 }
1441 return ('FAIL',"Error moving $type $entname to $newgname: $msg");
1442 }
1443
1444 return ('OK',"Moved $type $entname from $oldgname to $newgname");
1445} # end changeGroup()
1446
1447
1448##
1449## Processing subs
1450##
1451
1452## DNSDB::addDomain()
1453# Add a domain
1454# Takes a database handle, domain name, numeric group, boolean(ish) state (active/inactive),
1455# and user info hash (for logging).
1456# Returns a status code and message
1457sub addDomain {
1458 $errstr = '';
1459 my $dbh = shift;
1460 return ('FAIL',"Need database handle") if !$dbh;
1461 my $domain = shift;
1462 return ('FAIL',"Domain must not be blank") if !$domain;
1463 my $group = shift;
1464 return ('FAIL',"Need group") if !defined($group);
1465 my $state = shift;
1466 return ('FAIL',"Need domain status") if !defined($state);
1467
1468 $state = 1 if $state =~ /^active$/;
1469 $state = 1 if $state =~ /^on$/;
1470 $state = 0 if $state =~ /^inactive$/;
1471 $state = 0 if $state =~ /^off$/;
1472
1473 return ('FAIL',"Invalid domain status") if $state !~ /^\d+$/;
1474
1475 return ('FAIL', "Invalid characters in domain") if $domain !~ /^[a-zA-Z0-9_.-]+$/;
1476
1477 my $sth = $dbh->prepare("SELECT domain_id FROM domains WHERE domain=?");
1478 my $dom_id;
1479
1480# quick check to start to see if we've already got one
1481 $sth->execute($domain);
1482 ($dom_id) = $sth->fetchrow_array;
1483
1484 return ('FAIL', "Domain already exists") if $dom_id;
1485
1486 # Allow transactions, and raise an exception on errors so we can catch it later.
1487 # Use local to make sure these get "reset" properly on exiting this block
1488 local $dbh->{AutoCommit} = 0;
1489 local $dbh->{RaiseError} = 1;
1490
1491 # Wrap all the SQL in a transaction
1492 eval {
1493 # insert the domain...
1494 $dbh->do("INSERT INTO domains (domain,group_id,status) VALUES (?,?,?)", undef, ($domain, $group, $state));
1495
1496 # get the ID...
1497 ($dom_id) = $dbh->selectrow_array("SELECT domain_id FROM domains WHERE domain=?", undef, ($domain));
1498
1499 _log($dbh, (domain_id => $dom_id, group_id => $group,
1500 entry => "Added ".($state ? 'active' : 'inactive')." domain $domain"));
1501
1502 # ... and now we construct the standard records from the default set. NB: group should be variable.
1503 my $sth = $dbh->prepare("SELECT host,type,val,distance,weight,port,ttl FROM default_records WHERE group_id=?");
1504 my $sth_in = $dbh->prepare("INSERT INTO records (domain_id,host,type,val,distance,weight,port,ttl)".
1505 " VALUES ($dom_id,?,?,?,?,?,?,?)");
1506 $sth->execute($group);
1507 while (my ($host,$type,$val,$dist,$weight,$port,$ttl) = $sth->fetchrow_array()) {
1508 $host =~ s/DOMAIN/$domain/g;
1509 $val =~ s/DOMAIN/$domain/g;
1510 $sth_in->execute($host,$type,$val,$dist,$weight,$port,$ttl);
1511 if ($typemap{$type} eq 'SOA') {
1512 my @tmp1 = split /:/, $host;
1513 my @tmp2 = split /:/, $val;
1514 _log($dbh, (domain_id => $dom_id, group_id => $group,
1515 entry => "[new $domain] Added SOA record [contact $tmp1[0]] [master $tmp1[1]] ".
1516 "[refresh $tmp2[0]] [retry $tmp2[1]] [expire $tmp2[2]] [minttl $tmp2[3]], TTL $ttl"));
1517 } else {
1518 my $logentry = "[new $domain] Added record '$host $typemap{$type}";
1519 $logentry .= " [distance $dist]" if $typemap{$type} eq 'MX';
1520 $logentry .= " [priority $dist] [weight $weight] [port $port]" if $typemap{$type} eq 'SRV';
1521 _log($dbh, (domain_id => $dom_id, group_id => $group,
1522 entry => $logentry." $val', TTL $ttl"));
1523 }
1524 }
1525
1526 # once we get here, we should have suceeded.
1527 $dbh->commit;
1528 }; # end eval
1529
1530 if ($@) {
1531 my $msg = $@;
1532 eval { $dbh->rollback; };
1533 _log($dbh, (group_id => $group, entry => "Failed adding domain $domain ($msg)"))
1534 if $config{log_failures};
1535 $dbh->commit; # since we enabled transactions earlier
1536 return ('FAIL',$msg);
1537 } else {
1538 return ('OK',$dom_id);
1539 }
1540} # end addDomain
1541
1542
1543## DNSDB::delZone()
1544# Delete a forward or reverse zone.
1545# Takes a database handle, zone ID, and forward/reverse flag.
1546# for now, just delete the records, then the domain.
1547# later we may want to archive it in some way instead (status code 2, for example?)
1548sub delZone {
1549 my $dbh = shift;
1550 my $zoneid = shift;
1551 my $revrec = shift;
1552
1553 # Allow transactions, and raise an exception on errors so we can catch it later.
1554 # Use local to make sure these get "reset" properly on exiting this block
1555 local $dbh->{AutoCommit} = 0;
1556 local $dbh->{RaiseError} = 1;
1557
1558 my $msg = '';
1559 my $failmsg = '';
1560 my $zone = ($revrec eq 'n' ? domainName($dbh, $zoneid) : revName($dbh, $zoneid));
1561
1562 # Set this up here since we may use if if $config{log_failures} is enabled
1563 my %loghash;
1564 $loghash{domain_id} = $zoneid if $revrec eq 'n';
1565 $loghash{rdns_id} = $zoneid if $revrec eq 'y';
1566 $loghash{group_id} = parentID($dbh,
1567 (id => $zoneid, type => ($revrec eq 'n' ? 'domain' : 'revzone'), revrec => $revrec) );
1568
1569 # Wrap all the SQL in a transaction
1570 eval {
1571 # Disentangle custom record types before removing the
1572 # ones that are only in the zone to be deleted
1573 if ($revrec eq 'n') {
1574 my $sth = $dbh->prepare("UPDATE records SET type=?,domain_id=0 WHERE domain_id=? AND type=?");
1575 $failmsg = "Failure converting multizone types to single-zone";
1576 $sth->execute($reverse_typemap{PTR}, $zoneid, 65280);
1577 $sth->execute($reverse_typemap{PTR}, $zoneid, 65281);
1578 $sth->execute(65282, $zoneid, 65283);
1579 $sth->execute(65282, $zoneid, 65284);
1580 $failmsg = "Failure removing domain records";
1581 $dbh->do("DELETE FROM records WHERE domain_id=?", undef, ($zoneid));
1582 $failmsg = "Failure removing domain";
1583 $dbh->do("DELETE FROM domains WHERE domain_id=?", undef, ($zoneid));
1584 } else {
1585 my $sth = $dbh->prepare("UPDATE records SET type=?,rdns_id=0 WHERE rdns_id=? AND type=?");
1586 $failmsg = "Failure converting multizone types to single-zone";
1587 $sth->execute($reverse_typemap{A}, $zoneid, 65280);
1588 $sth->execute($reverse_typemap{AAAA}, $zoneid, 65281);
1589# We don't have an "A template" or "AAAA template" type, although it might be useful for symmetry.
1590# $sth->execute(65285?, $zoneid, 65283);
1591# $sth->execute(65285?, $zoneid, 65284);
1592 $failmsg = "Failure removing reverse records";
1593 $dbh->do("DELETE FROM records WHERE rdns_id=?", undef, ($zoneid));
1594 $failmsg = "Failure removing reverse zone";
1595 $dbh->do("DELETE FROM revzones WHERE rdns_id=?", undef, ($zoneid));
1596 }
1597
1598 $msg = "Deleted ".($revrec eq 'n' ? 'domain' : 'reverse zone')." $zone";
1599 $loghash{entry} = $msg;
1600 _log($dbh, %loghash);
1601
1602 # once we get here, we should have suceeded.
1603 $dbh->commit;
1604 }; # end eval
1605
1606 if ($@) {
1607 $msg = $@;
1608 eval { $dbh->rollback; };
1609 $loghash{entry} = "Error deleting $zone: $msg ($failmsg)";
1610 if ($config{log_failures}) {
1611 _log($dbh, %loghash);
1612 $dbh->commit; # since we enabled transactions earlier
1613 }
1614 return ('FAIL', $loghash{entry});
1615 } else {
1616 return ('OK', $msg);
1617 }
1618
1619} # end delZone()
1620
1621
1622## DNSDB::domainName()
1623# Return the domain name based on a domain ID
1624# Takes a database handle and the domain ID
1625# Returns the domain name or undef on failure
1626sub domainName {
1627 $errstr = '';
1628 my $dbh = shift;
1629 my $domid = shift;
1630 my ($domname) = $dbh->selectrow_array("SELECT domain FROM domains WHERE domain_id=?", undef, ($domid) );
1631 $errstr = $DBI::errstr if !$domname;
1632 return $domname if $domname;
1633} # end domainName()
1634
1635
1636## DNSDB::revName()
1637# Return the reverse zone name based on an rDNS ID
1638# Takes a database handle and the rDNS ID
1639# Returns the reverse zone name or undef on failure
1640sub revName {
1641 $errstr = '';
1642 my $dbh = shift;
1643 my $revid = shift;
1644 my ($revname) = $dbh->selectrow_array("SELECT revnet FROM revzones WHERE rdns_id=?", undef, ($revid) );
1645 $errstr = $DBI::errstr if !$revname;
1646 return $revname if $revname;
1647} # end revName()
1648
1649
1650## DNSDB::domainID()
1651# Takes a database handle and domain name
1652# Returns the domain ID number
1653sub domainID {
1654 $errstr = '';
1655 my $dbh = shift;
1656 my $domain = shift;
1657 my ($domid) = $dbh->selectrow_array("SELECT domain_id FROM domains WHERE domain=?", undef, ($domain) );
1658 $errstr = $DBI::errstr if !$domid;
1659 return $domid if $domid;
1660} # end domainID()
1661
1662
1663## DNSDB::revID()
1664# Takes a database handle and reverse zone name
1665# Returns the rDNS ID number
1666sub revID {
1667 $errstr = '';
1668 my $dbh = shift;
1669 my $revzone = shift;
1670 my ($revid) = $dbh->selectrow_array("SELECT rdns_id FROM revzones WHERE revnet=?", undef, ($revzone) );
1671 $errstr = $DBI::errstr if !$revid;
1672 return $revid if $revid;
1673} # end revID()
1674
1675
1676## DNSDB::addRDNS
1677# Adds a reverse DNS zone
1678# Takes a database handle, CIDR block, reverse DNS pattern, numeric group,
1679# and boolean(ish) state (active/inactive)
1680# Returns a status code and message
1681sub addRDNS {
1682 my $dbh = shift;
1683 my $zone = NetAddr::IP->new(shift);
1684 return ('FAIL',"Zone name must be a valid CIDR netblock") unless ($zone && $zone->addr !~ /^0/);
1685 my $revpatt = shift; # construct a custom (A/AAAA+)? PTR template record
1686 my $group = shift;
1687 my $state = shift;
1688
1689 $state = 1 if $state =~ /^active$/;
1690 $state = 1 if $state =~ /^on$/;
1691 $state = 0 if $state =~ /^inactive$/;
1692 $state = 0 if $state =~ /^off$/;
1693
1694 return ('FAIL',"Invalid zone status") if $state !~ /^\d+$/;
1695
1696# quick check to start to see if we've already got one
1697 my ($rdns_id) = $dbh->selectrow_array("SELECT rdns_id FROM revzones WHERE revnet=?", undef, ("$zone"));
1698
1699 return ('FAIL', "Zone already exists") if $rdns_id;
1700
1701 # Allow transactions, and raise an exception on errors so we can catch it later.
1702 # Use local to make sure these get "reset" properly on exiting this block
1703 local $dbh->{AutoCommit} = 0;
1704 local $dbh->{RaiseError} = 1;
1705
1706 my $warnstr = '';
1707 my $defttl = 3600; # 1 hour should be reasonable. And unless things have gone horribly
1708 # wrong, we should have a value to override this anyway.
1709
1710 # Wrap all the SQL in a transaction
1711 eval {
1712 # insert the domain...
1713 $dbh->do("INSERT INTO revzones (revnet,group_id,status) VALUES (?,?,?)", undef, ($zone, $group, $state));
1714
1715 # get the ID...
1716 ($rdns_id) = $dbh->selectrow_array("SELECT currval('revzones_rdns_id_seq')");
1717
1718 _log($dbh, (rdns_id => $rdns_id, group_id => $group,
1719 entry => "Added ".($state ? 'active' : 'inactive')." reverse zone $zone"));
1720
1721 # ... and now we construct the standard records from the default set. NB: group should be variable.
1722 my $sth = $dbh->prepare("SELECT host,type,val,ttl FROM default_rev_records WHERE group_id=?");
1723 my $sth_in = $dbh->prepare("INSERT INTO records (rdns_id,domain_id,host,type,val,ttl)".
1724 " VALUES ($rdns_id,?,?,?,?,?)");
1725 $sth->execute($group);
1726 while (my ($host,$type,$val,$ttl) = $sth->fetchrow_array()) {
1727 # Silently skip v4/v6 mismatches. This is not an error, this is expected.
1728 if ($zone->{isv6}) {
1729 next if ($type == 65280 || $type == 65283);
1730 } else {
1731 next if ($type == 65281 || $type == 65284);
1732 }
1733
1734 $host =~ s/ADMINDOMAIN/$config{domain}/g;
1735
1736 # Check to make sure the IP stubs will fit in the zone. Under most usage failures here should be rare.
1737 # On failure, tack a note on to a warning string and continue without adding this record.
1738 # While we're at it, we substitute $zone for ZONE in the value.
1739 if ($val eq 'ZONE') {
1740 next if $revpatt; # If we've got a pattern, we skip the default record version.
1741##fixme? do we care if we have multiple whole-zone templates?
1742 $val = $zone->network;
1743 } elsif ($val =~ /ZONE/) {
1744 my $tmpval = $val;
1745 $tmpval =~ s/ZONE//;
1746 # Bend the rules and allow single-trailing-number PTR or PTR template records to be inserted
1747 # as either v4 or v6. May make this an off-by-default config flag
1748 # Note that the origin records that may trigger this **SHOULD** already have ZONE,\d
1749 if ($type == 12 || $type == 65282) {
1750 $tmpval =~ s/[,.]/::/ if ($tmpval =~ /^[,.]\d+$/ && $zone->{isv6});
1751 $tmpval =~ s/[,:]+/./ if ($tmpval =~ /^(?:,|::)\d+$/ && !$zone->{isv6});
1752 }
1753 my $addr;
1754 if (_ipparent($dbh, 'n', 'y', \$tmpval, $rdns_id, \$addr)) {
1755 $val = $addr->addr;
1756 } else {
1757 $warnstr .= "\nDefault record '$val $typemap{$type} $host' doesn't fit in $zone, skipping";
1758 next;
1759 }
1760 }
1761
1762 # Substitute $zone for ZONE in the hostname.
1763 $host = _ZONE($zone, $host);
1764
1765 # Fill in the forward domain ID if we can find it, otherwise:
1766 # Coerce type down to PTR or PTR template if we can't
1767 my $domid = 0;
1768 if ($type >= 65280) {
1769 if (!($domid = _hostparent($dbh, $host))) {
1770 $warnstr .= "\nRecord added as PTR instead of $typemap{$type}; domain not found for $host";
1771 $type = $reverse_typemap{PTR};
1772 $domid = 0; # just to be explicit.
1773 }
1774 }
1775
1776 $sth_in->execute($domid,$host,$type,$val,$ttl);
1777
1778 if ($typemap{$type} eq 'SOA') {
1779 my @tmp1 = split /:/, $host;
1780 my @tmp2 = split /:/, $val;
1781 _log($dbh, (rdns_id => $rdns_id, group_id => $group,
1782 entry => "[new $zone] Added SOA record [contact $tmp1[0]] [master $tmp1[1]] ".
1783 "[refresh $tmp2[0]] [retry $tmp2[1]] [expire $tmp2[2]] [minttl $tmp2[3]], TTL $ttl"));
1784 $defttl = $tmp2[3];
1785 } else {
1786 my $logentry = "[new $zone] Added record '$host $typemap{$type}";
1787 _log($dbh, (rdns_id => $rdns_id, domain_id => $domid, group_id => $group,
1788 entry => $logentry." $val', TTL $ttl"));
1789 }
1790 }
1791
1792 # Generate record based on provided pattern.
1793 if ($revpatt) {
1794 my $host;
1795 my $type = ($zone->{isv6} ? 65284 : 65283);
1796 my $val = $zone->network;
1797
1798 # Substitute $zone for ZONE in the hostname.
1799 $host = _ZONE($zone, $revpatt);
1800
1801 my $domid = 0;
1802 if (!($domid = _hostparent($dbh, $host))) {
1803 $warnstr .= "\nDefault pattern added as PTR template instead of $typemap{$type}; domain not found for $host";
1804 $type = 65282;
1805 $domid = 0; # just to be explicit.
1806 }
1807
1808 $sth_in->execute($domid,$host,$type,$val,$defttl);
1809 my $logentry = "[new $zone] Added record '$host $typemap{$type}";
1810 _log($dbh, (rdns_id => $rdns_id, domain_id => $domid, group_id => $group,
1811 entry => $logentry." $val', TTL $defttl from pattern"));
1812 }
1813
1814 # If there are warnings (presumably about default records skipped for cause) log them
1815 _log($dbh, (rdns_id => $rdns_id, group_id => $group, entry => "Warning(s) adding $zone:$warnstr"))
1816 if $warnstr;
1817
1818 # once we get here, we should have suceeded.
1819 $dbh->commit;
1820 }; # end eval
1821
1822 if ($@) {
1823 my $msg = $@;
1824 eval { $dbh->rollback; };
1825 _log($dbh, (group_id => $group, entry => "Failed adding reverse zone $zone ($msg)"))
1826 if $config{log_failures};
1827 $dbh->commit; # since we enabled transactions earlier
1828 return ('FAIL',$msg);
1829 } else {
1830 my $retcode = 'OK';
1831 if ($warnstr) {
1832 $resultstr = $warnstr;
1833 $retcode = 'WARN';
1834 }
1835 return ($retcode, $rdns_id);
1836 }
1837
1838} # end addRDNS()
1839
1840
1841## DNSDB::getZoneCount
1842# Get count of zones in group or groups
1843# Takes a database handle and hash containing:
1844# - the "current" group
1845# - an array of "acceptable" groups
1846# - a flag for forward/reverse zones
1847# - Optionally accept a "starts with" and/or "contains" filter argument
1848# Returns an integer count of the resulting zone list.
1849sub getZoneCount {
1850 my $dbh = shift;
1851
1852 my %args = @_;
1853
1854 my @filterargs;
1855 $args{startwith} = undef if $args{startwith} && $args{startwith} !~ /^(?:[a-z]|0-9)$/;
1856 push @filterargs, "^$args{startwith}" if $args{startwith};
1857 $args{filter} =~ s/\./\[\.\]/g if $args{filter}; # only match literal dots, usually in reverse zones
1858 push @filterargs, $args{filter} if $args{filter};
1859
1860 my $sql;
1861 # Not as compact, and fix-me-twice if the common bits get wrong, but much easier to read
1862 if ($args{revrec} eq 'n') {
1863 $sql = "SELECT count(*) FROM domains".
1864 " WHERE group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
1865 ($args{startwith} ? " AND domain ~* ?" : '').
1866 ($args{filter} ? " AND domain ~* ?" : '');
1867 } else {
1868 $sql = "SELECT count(*) FROM revzones".
1869 " WHERE group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
1870 ($args{startwith} ? " AND CAST(revnet AS VARCHAR) ~* ?" : '').
1871 ($args{filter} ? " AND CAST(revnet AS VARCHAR) ~* ?" : '');
1872 }
1873 my ($count) = $dbh->selectrow_array($sql, undef, @filterargs);
1874 return $count;
1875} # end getZoneCount()
1876
1877
1878## DNSDB::getZoneList()
1879# Get a list of zones in the specified group(s)
1880# Takes the same arguments as getZoneCount() above
1881# Returns a reference to an array of hashrefs suitable for feeding to HTML::Template
1882sub getZoneList {
1883 my $dbh = shift;
1884
1885 my %args = @_;
1886
1887 my @zonelist;
1888
1889 $args{sortorder} = 'ASC' if !grep /^$args{sortorder}$/, ('ASC','DESC');
1890 $args{offset} = 0 if !$args{offset} || $args{offset} !~ /^(?:all|\d+)$/;
1891
1892 my @filterargs;
1893 $args{startwith} = undef if $args{startwith} && $args{startwith} !~ /^(?:[a-z]|0-9)$/;
1894 push @filterargs, "^$args{startwith}" if $args{startwith};
1895 $args{filter} =~ s/\./\[\.\]/g if $args{filter}; # only match literal dots, usually in reverse zones
1896 push @filterargs, $args{filter} if $args{filter};
1897
1898 my $sql;
1899 # Not as compact, and fix-me-twice if the common bits get wrong, but much easier to read
1900 if ($args{revrec} eq 'n') {
1901 $args{sortby} = 'domain' if !grep /^$args{sortby}$/, ('domain','group','status');
1902 $sql = "SELECT domain_id,domain,status,groups.group_name AS group FROM domains".
1903 " INNER JOIN groups ON domains.group_id=groups.group_id".
1904 " WHERE domains.group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
1905 ($args{startwith} ? " AND domain ~* ?" : '').
1906 ($args{filter} ? " AND domain ~* ?" : '');
1907 } else {
1908##fixme: arguably startwith here is irrelevant. depends on the UI though.
1909 $args{sortby} = 'revnet' if !grep /^$args{sortby}$/, ('revnet','group','status');
1910 $sql = "SELECT rdns_id,revnet,status,groups.group_name AS group FROM revzones".
1911 " INNER JOIN groups ON revzones.group_id=groups.group_id".
1912 " WHERE revzones.group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
1913 ($args{startwith} ? " AND CAST(revnet AS VARCHAR) ~* ?" : '').
1914 ($args{filter} ? " AND CAST(revnet AS VARCHAR) ~* ?" : '');
1915 }
1916 # A common tail.
1917 $sql .= " ORDER BY ".($args{sortby} eq 'group' ? 'groups.group_name' : $args{sortby})." $args{sortorder} ".
1918 ($args{offset} eq 'all' ? '' : " LIMIT $config{perpage}".
1919 " OFFSET ".$args{offset}*$config{perpage});
1920 my $sth = $dbh->prepare($sql);
1921 $sth->execute(@filterargs);
1922 my $rownum = 0;
1923
1924 while (my @data = $sth->fetchrow_array) {
1925 my %row;
1926 $row{domainid} = $data[0];
1927 $row{domain} = $data[1];
1928 $row{status} = $data[2];
1929 $row{group} = $data[3];
1930 push @zonelist, \%row;
1931 }
1932
1933 return \@zonelist;
1934} # end getZoneList()
1935
1936
1937## DNSDB::addGroup()
1938# Add a group
1939# Takes a database handle, group name, parent group, hashref for permissions,
1940# and optional template-vs-cloneme flag for the default records
1941# Returns a status code and message
1942sub addGroup {
1943 $errstr = '';
1944 my $dbh = shift;
1945 my $groupname = shift;
1946 my $pargroup = shift;
1947 my $permissions = shift;
1948
1949 # 0 indicates "custom", hardcoded.
1950 # Any other value clones that group's default records, if it exists.
1951 my $inherit = shift || 0;
1952##fixme: need a flag to indicate clone records or <?> ?
1953
1954 # Allow transactions, and raise an exception on errors so we can catch it later.
1955 # Use local to make sure these get "reset" properly on exiting this block
1956 local $dbh->{AutoCommit} = 0;
1957 local $dbh->{RaiseError} = 1;
1958
1959 my ($group_id) = $dbh->selectrow_array("SELECT group_id FROM groups WHERE group_name=?", undef, ($groupname));
1960
1961 return ('FAIL', "Group already exists") if $group_id;
1962
1963 # Wrap all the SQL in a transaction
1964 eval {
1965 $dbh->do("INSERT INTO groups (parent_group_id,group_name) VALUES (?,?)", undef, ($pargroup, $groupname) );
1966
1967 my ($groupid) = $dbh->selectrow_array("SELECT currval('groups_group_id_seq')");
1968
1969 # We work through the whole set of permissions instead of specifying them so
1970 # that when we add a new permission, we don't have to change the code anywhere
1971 # that doesn't explicitly deal with that specific permission.
1972 my @permvals;
1973 foreach (@permtypes) {
1974 if (!defined ($permissions->{$_})) {
1975 push @permvals, 0;
1976 } else {
1977 push @permvals, $permissions->{$_};
1978 }
1979 }
1980 $dbh->do("INSERT INTO permissions (group_id,$permlist) values (?".',?'x($#permtypes+1).")",
1981 undef, ($groupid, @permvals) );
1982 my ($permid) = $dbh->selectrow_array("SELECT currval('permissions_permission_id_seq')");
1983 $dbh->do("UPDATE groups SET permission_id=$permid WHERE group_id=$groupid");
1984
1985 # Default records
1986 my $sthf = $dbh->prepare("INSERT INTO default_records (group_id,host,type,val,distance,weight,port,ttl) ".
1987 "VALUES ($groupid,?,?,?,?,?,?,?)");
1988 my $sthr = $dbh->prepare("INSERT INTO default_rev_records (group_id,host,type,val,ttl) ".
1989 "VALUES ($groupid,?,?,?,?)");
1990 if ($inherit) {
1991 # Duplicate records from parent. Actually relying on inherited records feels
1992 # very fragile, and it would be problematic to roll over at a later time.
1993 my $sth2 = $dbh->prepare("SELECT host,type,val,distance,weight,port,ttl FROM default_records WHERE group_id=?");
1994 $sth2->execute($pargroup);
1995 while (my @clonedata = $sth2->fetchrow_array) {
1996 $sthf->execute(@clonedata);
1997 }
1998 # And now the reverse records
1999 $sth2 = $dbh->prepare("SELECT host,type,val,ttl FROM default_rev_records WHERE group_id=?");
2000 $sth2->execute($pargroup);
2001 while (my @clonedata = $sth2->fetchrow_array) {
2002 $sthr->execute(@clonedata);
2003 }
2004 } else {
2005##fixme: Hardcoding is Bad, mmmmkaaaay?
2006 # reasonable basic defaults for SOA, MX, NS, and minimal hosting
2007 # could load from a config file, but somewhere along the line we need hardcoded bits.
2008 $sthf->execute('ns1.example.com:hostmaster.example.com', 6, '10800:3600:604800:10800', 0, 0, 0, 86400);
2009 $sthf->execute('DOMAIN', 1, '192.168.4.2', 0, 0, 0, 7200);
2010 $sthf->execute('DOMAIN', 15, 'mx.example.com', 10, 0, 0, 7200);
2011 $sthf->execute('DOMAIN', 2, 'ns1.example.com', 0, 0, 0, 7200);
2012 $sthf->execute('DOMAIN', 2, 'ns2.example.com', 0, 0, 0, 7200);
2013 $sthf->execute('www.DOMAIN', 5, 'DOMAIN', 0, 0, 0, 7200);
2014 # reasonable basic defaults for generic reverse zone. Same as initial SQL tabledef.
2015 $sthr->execute('hostmaster.ADMINDOMAIN:ns1.ADMINDOMAIN', 6, '10800:3600:604800:10800', 86400);
2016 $sthr->execute('unused-%r.ADMINDOMAIN', 65283, 'ZONE', 3600);
2017 }
2018
2019 _log($dbh, (group_id => $pargroup, entry => "Added group $groupname") );
2020
2021 # once we get here, we should have suceeded.
2022 $dbh->commit;
2023 }; # end eval
2024
2025 if ($@) {
2026 my $msg = $@;
2027 eval { $dbh->rollback; };
2028 if ($config{log_failures}) {
2029 _log($dbh, (group_id => $pargroup, entry => "Failed to add group $groupname: $msg") );
2030 $dbh->commit;
2031 }
2032 return ('FAIL',$msg);
2033 }
2034
2035 return ('OK','OK');
2036} # end addGroup()
2037
2038
2039## DNSDB::delGroup()
2040# Delete a group.
2041# Takes a group ID
2042# Returns a status code and message
2043sub delGroup {
2044 my $dbh = shift;
2045 my $groupid = shift;
2046
2047 # Allow transactions, and raise an exception on errors so we can catch it later.
2048 # Use local to make sure these get "reset" properly on exiting this block
2049 local $dbh->{AutoCommit} = 0;
2050 local $dbh->{RaiseError} = 1;
2051
2052##fixme: locate "knowable" error conditions and deal with them before the eval
2053# ... or inside, whatever.
2054# -> domains still exist in group
2055# -> ...
2056 my $failmsg = '';
2057 my $resultmsg = '';
2058
2059 # collect some pieces for logging and error messages
2060 my $groupname = groupName($dbh,$groupid);
2061 my $parid = parentID($dbh, (id => $groupid, type => 'group'));
2062
2063 # Wrap all the SQL in a transaction
2064 eval {
2065 # Check for Things in the group
2066 $failmsg = "Can't remove group $groupname";
2067 my ($grpcnt) = $dbh->selectrow_array("SELECT count(*) FROM groups WHERE parent_group_id=?", undef, ($groupid));
2068 die "$grpcnt groups still in group\n" if $grpcnt;
2069 my ($domcnt) = $dbh->selectrow_array("SELECT count(*) FROM domains WHERE group_id=?", undef, ($groupid));
2070 die "$domcnt domains still in group\n" if $domcnt;
2071 my ($usercnt) = $dbh->selectrow_array("SELECT count(*) FROM users WHERE group_id=?", undef, ($groupid));
2072 die "$usercnt users still in group\n" if $usercnt;
2073
2074 $failmsg = "Failed to delete default records for $groupname";
2075 $dbh->do("DELETE from default_records WHERE group_id=?", undef, ($groupid));
2076 $failmsg = "Failed to delete default reverse records for $groupname";
2077 $dbh->do("DELETE from default_rev_records WHERE group_id=?", undef, ($groupid));
2078 $failmsg = "Failed to remove group $groupname";
2079 $dbh->do("DELETE from groups WHERE group_id=?", undef, ($groupid));
2080
2081 _log($dbh, (group_id => $parid, entry => "Deleted group $groupname"));
2082 $resultmsg = "Deleted group $groupname";
2083
2084 # once we get here, we should have suceeded.
2085 $dbh->commit;
2086 }; # end eval
2087
2088 if ($@) {
2089 my $msg = $@;
2090 eval { $dbh->rollback; };
2091 if ($config{log_failures}) {
2092 _log($dbh, (group_id => $parid, entry => "$failmsg: $msg"));
2093 $dbh->commit; # since we enabled transactions earlier
2094 }
2095 return ('FAIL',"$failmsg: $msg");
2096 }
2097
2098 return ('OK',$resultmsg);
2099} # end delGroup()
2100
2101
2102## DNSDB::getChildren()
2103# Get a list of all groups whose parent^n is group <n>
2104# Takes a database handle, group ID, reference to an array to put the group IDs in,
2105# and an optional flag to return only immediate children or all children-of-children
2106# default to returning all children
2107# Calls itself
2108sub getChildren {
2109 $errstr = '';
2110 my $dbh = shift;
2111 my $rootgroup = shift;
2112 my $groupdest = shift;
2113 my $immed = shift || 'all';
2114
2115 # special break for default group; otherwise we get stuck.
2116 if ($rootgroup == 1) {
2117 # by definition, group 1 is the Root Of All Groups
2118 my $sth = $dbh->prepare("SELECT group_id FROM groups WHERE NOT (group_id=1)".
2119 ($immed ne 'all' ? " AND parent_group_id=1" : ''));
2120 $sth->execute;
2121 while (my @this = $sth->fetchrow_array) {
2122 push @$groupdest, @this;
2123 }
2124 } else {
2125 my $sth = $dbh->prepare("SELECT group_id FROM groups WHERE parent_group_id=?");
2126 $sth->execute($rootgroup);
2127 return if $sth->rows == 0;
2128 my @grouplist;
2129 while (my ($group) = $sth->fetchrow_array) {
2130 push @$groupdest, $group;
2131 getChildren($dbh,$group,$groupdest) if $immed eq 'all';
2132 }
2133 }
2134} # end getChildren()
2135
2136
2137## DNSDB::groupName()
2138# Return the group name based on a group ID
2139# Takes a database handle and the group ID
2140# Returns the group name or undef on failure
2141sub groupName {
2142 $errstr = '';
2143 my $dbh = shift;
2144 my $groupid = shift;
2145 my $sth = $dbh->prepare("SELECT group_name FROM groups WHERE group_id=?");
2146 $sth->execute($groupid);
2147 my ($groupname) = $sth->fetchrow_array();
2148 $errstr = $DBI::errstr if !$groupname;
2149 return $groupname if $groupname;
2150} # end groupName
2151
2152
2153## DNSDB::getGroupCount()
2154# Get count of subgroups in group or groups
2155# Takes a database handle and hash containing:
2156# - the "current" group
2157# - an array of "acceptable" groups
2158# - Optionally accept a "starts with" and/or "contains" filter argument
2159# Returns an integer count of the resulting group list.
2160sub getGroupCount {
2161 my $dbh = shift;
2162
2163 my %args = @_;
2164
2165 my @filterargs;
2166
2167 $args{startwith} = undef if $args{startwith} && $args{startwith} !~ /^(?:[a-z]|0-9)$/;
2168 push @filterargs, "^$args{startwith}" if $args{startwith};
2169 push @filterargs, $args{filter} if $args{filter};
2170
2171 my $sql = "SELECT count(*) FROM groups ".
2172 "WHERE parent_group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
2173 ($args{startwith} ? " AND group_name ~* ?" : '').
2174 ($args{filter} ? " AND group_name ~* ?" : '');
2175 my ($count) = $dbh->selectrow_array($sql, undef, (@filterargs) );
2176 $errstr = $dbh->errstr if !$count;
2177 return $count;
2178} # end getGroupCount
2179
2180
2181## DNSDB::getGroupList()
2182# Get a list of sub^n-groups in the specified group(s)
2183# Takes the same arguments as getGroupCount() above
2184# Returns an arrayref containing hashrefs suitable for feeding straight to HTML::Template
2185sub getGroupList {
2186 my $dbh = shift;
2187
2188 my %args = @_;
2189
2190 my @filterargs;
2191
2192 $args{startwith} = undef if $args{startwith} && $args{startwith} !~ /^(?:[a-z]|0-9)$/;
2193 push @filterargs, "^$args{startwith}" if $args{startwith};
2194 push @filterargs, $args{filter} if $args{filter};
2195
2196 # protection against bad or missing arguments
2197 $args{sortorder} = 'ASC' if !$args{sortorder};
2198 $args{offset} = 0 if !$args{offset};
2199
2200 # munge sortby for columns in database
2201 $args{sortby} = 'g.group_name' if $args{sortby} eq 'group';
2202 $args{sortby} = 'g2.group_name' if $args{sortby} eq 'parent';
2203
2204 my $sql = q(SELECT g.group_id AS groupid, g.group_name AS groupname, g2.group_name AS pgroup,
2205 count(distinct(u.username)) AS nusers, count(distinct(d.domain)) AS ndomains,
2206 count(distinct(r.revnet)) AS nrevzones
2207 FROM groups g
2208 INNER JOIN groups g2 ON g2.group_id=g.parent_group_id
2209 LEFT OUTER JOIN users u ON u.group_id=g.group_id
2210 LEFT OUTER JOIN domains d ON d.group_id=g.group_id
2211 LEFT OUTER JOIN revzones r ON r.group_id=g.group_id
2212 ).
2213 "WHERE g.parent_group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
2214 ($args{startwith} ? " AND g.group_name ~* ?" : '').
2215 ($args{filter} ? " AND g.group_name ~* ?" : '').
2216 " GROUP BY g.group_id, g.group_name, g2.group_name ".
2217 " ORDER BY $args{sortby} $args{sortorder} ".
2218 ($args{offset} eq 'all' ? '' : " LIMIT $config{perpage} OFFSET ".$args{offset}*$config{perpage});
2219 my $glist = $dbh->selectall_arrayref($sql, { Slice => {} }, (@filterargs) );
2220 $errstr = $dbh->errstr if !$glist;
2221 return $glist;
2222} # end getGroupList
2223
2224
2225## DNSDB::groupID()
2226# Return the group ID based on the group name
2227# Takes a database handle and the group name
2228# Returns the group ID or undef on failure
2229sub groupID {
2230 $errstr = '';
2231 my $dbh = shift;
2232 my $group = shift;
2233 my ($grpid) = $dbh->selectrow_array("SELECT group_id FROM groups WHERE group=?", undef, ($group) );
2234 $errstr = $DBI::errstr if !$grpid;
2235 return $grpid if $grpid;
2236} # end groupID()
2237
2238
2239## DNSDB::addUser()
2240# Add a user.
2241# Takes a DB handle, username, group ID, password, state (active/inactive).
2242# Optionally accepts:
2243# user type (user/admin) - defaults to user
2244# permissions string - defaults to inherit from group
2245# three valid forms:
2246# i - Inherit permissions
2247# c:<user_id> - Clone permissions from <user_id>
2248# C:<permission list> - Set these specific permissions
2249# first name - defaults to username
2250# last name - defaults to blank
2251# phone - defaults to blank (could put other data within column def)
2252# Returns (OK,<uid>) on success, (FAIL,<message>) on failure
2253sub addUser {
2254 $errstr = '';
2255 my $dbh = shift;
2256 my $username = shift;
2257 my $group = shift;
2258 my $pass = shift;
2259 my $state = shift;
2260
2261 return ('FAIL', "Missing one or more required entries") if !defined($state);
2262 return ('FAIL', "Username must not be blank") if !$username;
2263
2264 my $type = shift || 'u'; # create limited users by default - fwiw, not sure yet how this will interact with ACLs
2265
2266 my $permstring = shift || 'i'; # default is to inhert permissions from group
2267
2268 my $fname = shift || $username;
2269 my $lname = shift || '';
2270 my $phone = shift || ''; # not going format-check
2271
2272 my $sth = $dbh->prepare("SELECT user_id FROM users WHERE username=?");
2273 my $user_id;
2274
2275# quick check to start to see if we've already got one
2276 $sth->execute($username);
2277 ($user_id) = $sth->fetchrow_array;
2278
2279 return ('FAIL', "User already exists") if $user_id;
2280
2281 # Allow transactions, and raise an exception on errors so we can catch it later.
2282 # Use local to make sure these get "reset" properly on exiting this block
2283 local $dbh->{AutoCommit} = 0;
2284 local $dbh->{RaiseError} = 1;
2285
2286 # Wrap all the SQL in a transaction
2287 eval {
2288 # insert the user... note we set inherited perms by default since
2289 # it's simple and cleans up some other bits of state
2290 my $sth = $dbh->prepare("INSERT INTO users ".
2291 "(group_id,username,password,firstname,lastname,phone,type,status,permission_id,inherit_perm) ".
2292 "VALUES (?,?,?,?,?,?,?,?,(SELECT permission_id FROM permissions WHERE group_id=?),'t')");
2293 $sth->execute($group,$username,unix_md5_crypt($pass),$fname,$lname,$phone,$type,$state,$group);
2294
2295 # get the ID...
2296 ($user_id) = $dbh->selectrow_array("SELECT currval('users_user_id_seq')");
2297
2298# Permissions! Gotta set'em all!
2299 die "Invalid permission string $permstring"
2300 if $permstring !~ /^(?:
2301 i # inherit
2302 |c:\d+ # clone
2303 # custom. no, the leading , is not a typo
2304 |C:(?:,(?:group|user|domain|record|self)_(?:edit|create|delete))*
2305 )$/x;
2306# bleh. I'd call another function to do my dirty work, but we're in the middle of a transaction already.
2307 if ($permstring ne 'i') {
2308 # for cloned or custom permissions, we have to create a new permissions entry.
2309 my $clonesrc = $group;
2310 if ($permstring =~ /^c:(\d+)/) { $clonesrc = $1; }
2311 $dbh->do("INSERT INTO permissions ($permlist,user_id) ".
2312 "SELECT $permlist,? FROM permissions WHERE permission_id=".
2313 "(SELECT permission_id FROM permissions WHERE ".($permstring =~ /^c:/ ? 'user' : 'group')."_id=?)",
2314 undef, ($user_id,$clonesrc) );
2315 $dbh->do("UPDATE users SET permission_id=".
2316 "(SELECT permission_id FROM permissions WHERE user_id=?) ".
2317 "WHERE user_id=?", undef, ($user_id, $user_id) );
2318 }
2319 if ($permstring =~ /^C:/) {
2320 # finally for custom permissions, we set the passed-in permissions (and unset
2321 # any that might have been brought in by the clone operation above)
2322 my ($permid) = $dbh->selectrow_array("SELECT permission_id FROM permissions WHERE user_id=?",
2323 undef, ($user_id) );
2324 foreach (@permtypes) {
2325 if ($permstring =~ /,$_/) {
2326 $dbh->do("UPDATE permissions SET $_='t' WHERE permission_id=?", undef, ($permid) );
2327 } else {
2328 $dbh->do("UPDATE permissions SET $_='f' WHERE permission_id=?", undef, ($permid) );
2329 }
2330 }
2331 }
2332
2333 $dbh->do("UPDATE users SET inherit_perm='n' WHERE user_id=?", undef, ($user_id) );
2334
2335##fixme: add another table to hold name/email for log table?
2336
2337 _log($dbh, (group_id => $group, entry => "Added user $username ($fname $lname)"));
2338 # once we get here, we should have suceeded.
2339 $dbh->commit;
2340 }; # end eval
2341
2342 if ($@) {
2343 my $msg = $@;
2344 eval { $dbh->rollback; };
2345 if ($config{log_failures}) {
2346 _log($dbh, (group_id => $group, entry => "Error adding user $username: $msg"));
2347 $dbh->commit; # since we enabled transactions earlier
2348 }
2349 return ('FAIL',"Error adding user $username: $msg");
2350 }
2351
2352 return ('OK',"User $username ($fname $lname) added");
2353} # end addUser
2354
2355
2356## DNSDB::checkUser()
2357# Check user/pass combo on login
2358sub checkUser {
2359 my $dbh = shift;
2360 my $user = shift;
2361 my $inpass = shift;
2362
2363 my $sth = $dbh->prepare("SELECT user_id,group_id,password,firstname,lastname FROM users WHERE username=?");
2364 $sth->execute($user);
2365 my ($uid,$gid,$pass,$fname,$lname) = $sth->fetchrow_array;
2366 my $loginfailed = 1 if !defined($uid);
2367
2368 if ($pass =~ m|^\$1\$([A-Za-z0-9/.]+)\$|) {
2369 $loginfailed = 1 if $pass ne unix_md5_crypt($inpass,$1);
2370 } else {
2371 $loginfailed = 1 if $pass ne $inpass;
2372 }
2373
2374 # nnnngggg
2375 return ($uid, $gid);
2376} # end checkUser
2377
2378
2379## DNSDB:: updateUser()
2380# Update general data about user
2381sub updateUser {
2382 my $dbh = shift;
2383
2384##fixme: tweak calling convention so that we can update any given bit of data
2385 my $uid = shift;
2386 my $username = shift;
2387 my $group = shift;
2388 my $pass = shift;
2389 my $state = shift;
2390 my $type = shift || 'u';
2391 my $fname = shift || $username;
2392 my $lname = shift || '';
2393 my $phone = shift || ''; # not going format-check
2394
2395 my $resultmsg = '';
2396
2397 # Allow transactions, and raise an exception on errors so we can catch it later.
2398 # Use local to make sure these get "reset" properly on exiting this block
2399 local $dbh->{AutoCommit} = 0;
2400 local $dbh->{RaiseError} = 1;
2401
2402 my $sth;
2403
2404 # Password can be left blank; if so we assume there's one on file.
2405 # Actual blank passwords are bad, mm'kay?
2406 if (!$pass) {
2407 ($pass) = $dbh->selectrow_array("SELECT password FROM users WHERE user_id=?", undef, ($uid));
2408 } else {
2409 $pass = unix_md5_crypt($pass);
2410 }
2411
2412 eval {
2413 $dbh->do("UPDATE users SET username=?, password=?, firstname=?, lastname=?, phone=?, type=?, status=?".
2414 " WHERE user_id=?", undef, ($username, $pass, $fname, $lname, $phone, $type, $state, $uid));
2415 $resultmsg = "Updated user info for $username ($fname $lname)";
2416 _log($dbh, group_id => $group, entry => $resultmsg);
2417 $dbh->commit;
2418 };
2419 if ($@) {
2420 my $msg = $@;
2421 eval { $dbh->rollback; };
2422 if ($config{log_failures}) {
2423 _log($dbh, (group_id => $group, entry => "Error updating user $username: $msg"));
2424 $dbh->commit; # since we enabled transactions earlier
2425 }
2426 return ('FAIL',"Error updating user $username: $msg");
2427 }
2428
2429 return ('OK',$resultmsg);
2430} # end updateUser()
2431
2432
2433## DNSDB::delUser()
2434# Delete a user.
2435# Takes a database handle and user ID
2436# Returns a success/failure code and matching message
2437sub delUser {
2438 my $dbh = shift;
2439 my $userid = shift;
2440
2441 return ('FAIL',"Bad userid") if !defined($userid);
2442
2443 my $userdata = getUserData($dbh, $userid);
2444
2445 # Allow transactions, and raise an exception on errors so we can catch it later.
2446 # Use local to make sure these get "reset" properly on exiting this block
2447 local $dbh->{AutoCommit} = 0;
2448 local $dbh->{RaiseError} = 1;
2449
2450 eval {
2451 $dbh->do("DELETE FROM users WHERE user_id=?", undef, ($userid));
2452 _log($dbh, (group_id => $userdata->{group_id},
2453 entry => "Deleted user ID $userid/".$userdata->{username}.
2454 " (".$userdata->{firstname}." ".$userdata->{lastname}.")") );
2455 $dbh->commit;
2456 };
2457 if ($@) {
2458 my $msg = $@;
2459 eval { $dbh->rollback; };
2460 if ($config{log_failures}) {
2461 _log($dbh, (group_id => $userdata->{group_id}, entry => "Error deleting user ID ".
2462 "$userid/".$userdata->{username}.": $msg") );
2463 $dbh->commit;
2464 }
2465 return ('FAIL',"Error deleting user $userid/".$userdata->{username}.": $msg");
2466 }
2467
2468 return ('OK',"Deleted user ".$userdata->{username}." (".$userdata->{firstname}." ".$userdata->{lastname}.")");
2469} # end delUser
2470
2471
2472## DNSDB::userFullName()
2473# Return a pretty string!
2474# Takes a user_id and optional printf-ish string to indicate which pieces where:
2475# %u for the username
2476# %f for the first name
2477# %l for the last name
2478# All other text in the passed string will be left as-is.
2479##fixme: need a "smart" option too, so that missing/null/blank first/last names don't give funky output
2480sub userFullName {
2481 $errstr = '';
2482 my $dbh = shift;
2483 my $userid = shift;
2484 my $fullformat = shift || '%f %l (%u)';
2485 my $sth = $dbh->prepare("select username,firstname,lastname from users where user_id=?");
2486 $sth->execute($userid);
2487 my ($uname,$fname,$lname) = $sth->fetchrow_array();
2488 $errstr = $DBI::errstr if !$uname;
2489
2490 $fullformat =~ s/\%u/$uname/g;
2491 $fullformat =~ s/\%f/$fname/g;
2492 $fullformat =~ s/\%l/$lname/g;
2493
2494 return $fullformat;
2495} # end userFullName
2496
2497
2498## DNSDB::userStatus()
2499# Sets and/or returns a user's status
2500# Takes a database handle, user ID and optionally a status argument
2501# Returns undef on errors.
2502sub userStatus {
2503 my $dbh = shift;
2504 my $id = shift;
2505 my $newstatus = shift || 'mu';
2506
2507 return undef if $id !~ /^\d+$/;
2508
2509 my $userdata = getUserData($dbh, $id);
2510
2511 # Allow transactions, and raise an exception on errors so we can catch it later.
2512 # Use local to make sure these get "reset" properly on exiting this block
2513 local $dbh->{AutoCommit} = 0;
2514 local $dbh->{RaiseError} = 1;
2515
2516 if ($newstatus ne 'mu') {
2517 # ooo, fun! let's see what we were passed for status
2518 eval {
2519 $newstatus = 0 if $newstatus eq 'useroff';
2520 $newstatus = 1 if $newstatus eq 'useron';
2521 $dbh->do("UPDATE users SET status=? WHERE user_id=?", undef, ($newstatus, $id));
2522
2523 $resultstr = ($newstatus ? 'Enabled' : 'Disabled')." user ".$userdata->{username}.
2524 " (".$userdata->{firstname}." ".$userdata->{lastname}.")";
2525
2526 my %loghash;
2527 $loghash{group_id} = parentID($dbh, (id => $id, type => 'user'));
2528 $loghash{entry} = $resultstr;
2529 _log($dbh, %loghash);
2530
2531 $dbh->commit;
2532 };
2533 if ($@) {
2534 my $msg = $@;
2535 eval { $dbh->rollback; };
2536 $resultstr = '';
2537 $errstr = $msg;
2538##fixme: failure logging?
2539 return;
2540 }
2541 }
2542
2543 my ($status) = $dbh->selectrow_array("SELECT status FROM users WHERE user_id=?", undef, ($id));
2544 return $status;
2545} # end userStatus()
2546
2547
2548## DNSDB::getUserData()
2549# Get misc user data for display
2550sub getUserData {
2551 my $dbh = shift;
2552 my $uid = shift;
2553
2554 my $sth = $dbh->prepare("SELECT group_id,username,firstname,lastname,phone,type,status,inherit_perm ".
2555 "FROM users WHERE user_id=?");
2556 $sth->execute($uid);
2557 return $sth->fetchrow_hashref();
2558
2559} # end getUserData()
2560
2561
2562## DNSDB::getSOA()
2563# Return all suitable fields from an SOA record in separate elements of a hash
2564# Takes a database handle, default/live flag, domain/reverse flag, and parent ID
2565sub getSOA {
2566 $errstr = '';
2567 my $dbh = shift;
2568 my $def = shift;
2569 my $rev = shift;
2570 my $id = shift;
2571
2572 # (ab)use distance and weight columns to store SOA data? can't for default_rev_records...
2573 # - should really attach serial to the zone parent somewhere
2574
2575 my $sql = "SELECT record_id,host,val,ttl from "._rectable($def,$rev).
2576 " WHERE "._recparent($def,$rev)." = ? AND type=$reverse_typemap{SOA}";
2577 my $ret = $dbh->selectrow_hashref($sql, undef, ($id) );
2578 return if !$ret;
2579##fixme: stick a flag somewhere if the record doesn't exist. by the API, this is an impossible case, but...
2580
2581 ($ret->{contact},$ret->{prins}) = split /:/, $ret->{host};
2582 delete $ret->{host};
2583 ($ret->{refresh},$ret->{retry},$ret->{expire},$ret->{minttl}) = split /:/, $ret->{val};
2584 delete $ret->{val};
2585
2586 return $ret;
2587} # end getSOA()
2588
2589
2590## DNSDB::updateSOA()
2591# Update the specified SOA record
2592# Takes a database handle, default/live flag, forward/reverse flag, and SOA data hash
2593# Returns a two-element list with a result code and message
2594sub updateSOA {
2595 my $dbh = shift;
2596 my $defrec = shift;
2597 my $revrec = shift;
2598
2599 my %soa = @_;
2600
2601 my $oldsoa = getSOA($dbh, $defrec, $revrec, $soa{id});
2602
2603 my $msg;
2604 my %logdata;
2605 if ($defrec eq 'n') {
2606 $logdata{domain_id} = $soa{id} if $revrec eq 'n';
2607 $logdata{rdns_id} = $soa{id} if $revrec eq 'y';
2608 $logdata{group_id} = parentID($dbh, (id => $soa{id}, revrec => $revrec,
2609 type => ($revrec eq 'n' ? 'domain' : 'revzone') ) );
2610 } else {
2611 $logdata{group_id} = $soa{id};
2612 }
2613 my $parname = ($defrec eq 'y' ? groupName($dbh, $soa{id}) :
2614 ($revrec eq 'n' ? domainName($dbh, $soa{id}) : revName($dbh, $soa{id})) );
2615
2616 # Allow transactions, and raise an exception on errors so we can catch it later.
2617 # Use local to make sure these get "reset" properly on exiting this block
2618 local $dbh->{AutoCommit} = 0;
2619 local $dbh->{RaiseError} = 1;
2620
2621 eval {
2622 my $sql = "UPDATE "._rectable($defrec, $revrec)." SET host=?, val=?, ttl=? WHERE record_id=? AND type=6";
2623 $dbh->do($sql, undef, ("$soa{contact}:$soa{prins}", "$soa{refresh}:$soa{retry}:$soa{expire}:$soa{minttl}",
2624 $soa{ttl}, $oldsoa->{record_id}) );
2625 $msg = "Updated ".($defrec eq 'y' ? ($revrec eq 'y' ? 'default reverse ' : 'default ') : '').
2626 "SOA for $parname: ".
2627 "(ns $oldsoa->{prins}, contact $oldsoa->{contact}, refresh $oldsoa->{refresh},".
2628 " retry $oldsoa->{retry}, expire $oldsoa->{expire}, minTTL $oldsoa->{minttl}, TTL $oldsoa->{ttl}) to ".
2629 "(ns $soa{prins}, contact $soa{contact}, refresh $soa{refresh},".
2630 " retry $soa{retry}, expire $soa{expire}, minTTL $soa{minttl}, TTL $soa{ttl})";
2631
2632 $logdata{entry} = $msg;
2633 _log($dbh, %logdata);
2634
2635 $dbh->commit;
2636 };
2637 if ($@) {
2638 $msg = $@;
2639 eval { $dbh->rollback; };
2640 $logdata{entry} = "Error updating ".($defrec eq 'y' ? ($revrec eq 'y' ? 'default reverse zone ' : 'default ') : '').
2641 "SOA record for $parname: $msg";
2642 if ($config{log_failures}) {
2643 _log($dbh, %logdata);
2644 $dbh->commit;
2645 }
2646 return ('FAIL', $logdata{entry});
2647 } else {
2648 return ('OK', $msg);
2649 }
2650} # end updateSOA()
2651
2652
2653## DNSDB::getRecLine()
2654# Return all data fields for a zone record in separate elements of a hash
2655# Takes a database handle, default/live flag, forward/reverse flag, and record ID
2656sub getRecLine {
2657 $errstr = '';
2658 my $dbh = shift;
2659 my $defrec = shift;
2660 my $revrec = shift;
2661 my $id = shift;
2662
2663 my $sql = "SELECT record_id,host,type,val,ttl".($revrec eq 'n' ? ',distance,weight,port' : '').
2664 (($defrec eq 'y') ? ',group_id FROM ' : ',domain_id,rdns_id FROM ').
2665 _rectable($defrec,$revrec)." WHERE record_id=?";
2666 my $ret = $dbh->selectrow_hashref($sql, undef, ($id) );
2667
2668 if ($dbh->err) {
2669 $errstr = $DBI::errstr;
2670 return undef;
2671 }
2672
2673 if (!$ret) {
2674 $errstr = "No such record";
2675 return undef;
2676 }
2677
2678 # explicitly set a parent id
2679 if ($defrec eq 'y') {
2680 $ret->{parid} = $ret->{group_id};
2681 } else {
2682 $ret->{parid} = (($revrec eq 'n') ? $ret->{domain_id} : $ret->{rdns_id});
2683 # and a secondary if we have a custom type that lives in both a forward and reverse zone
2684 $ret->{secid} = (($revrec eq 'y') ? $ret->{domain_id} : $ret->{rdns_id}) if $ret->{type} > 65279;
2685 }
2686
2687 return $ret;
2688}
2689
2690
2691##fixme: should use above (getRecLine()) to get lines for below?
2692## DNSDB::getDomRecs()
2693# Return records for a domain
2694# Takes a database handle, default/live flag, group/domain ID, start,
2695# number of records, sort field, and sort order
2696# Returns a reference to an array of hashes
2697sub getDomRecs {
2698 $errstr = '';
2699 my $dbh = shift;
2700 my $def = shift;
2701 my $rev = shift;
2702 my $id = shift;
2703 my $nrecs = shift || 'all';
2704 my $nstart = shift || 0;
2705
2706## for order, need to map input to column names
2707 my $order = shift || 'host';
2708 my $direction = shift || 'ASC';
2709
2710 my $filter = shift || '';
2711
2712 my $sql = "SELECT r.record_id,r.host,r.type,r.val,r.ttl";
2713 $sql .= ",r.distance,r.weight,r.port" if $rev eq 'n';
2714 $sql .= " FROM "._rectable($def,$rev)." r ";
2715 $sql .= "INNER JOIN rectypes t ON r.type=t.val "; # for sorting by type alphabetically
2716 $sql .= "WHERE "._recparent($def,$rev)." = ?";
2717 $sql .= " AND NOT r.type=$reverse_typemap{SOA}";
2718 $sql .= " AND host ~* ?" if $filter;
2719 # use alphaorder column for "correct" ordering of sort-by-type instead of DNS RR type number
2720 $sql .= " ORDER BY ".($order eq 'type' ? 't.alphaorder' : "r.$order")." $direction";
2721
2722 my @bindvars = ($id);
2723 push @bindvars, $filter if $filter;
2724
2725 # just to be ultraparanoid about SQL injection vectors
2726 if ($nstart ne 'all') {
2727 $sql .= " LIMIT ? OFFSET ?";
2728 push @bindvars, $nrecs;
2729 push @bindvars, ($nstart*$nrecs);
2730 }
2731 my $sth = $dbh->prepare($sql) or warn $dbh->errstr;
2732 $sth->execute(@bindvars) or warn "$sql: ".$sth->errstr;
2733
2734 my @retbase;
2735 while (my $ref = $sth->fetchrow_hashref()) {
2736 push @retbase, $ref;
2737 }
2738
2739 my $ret = \@retbase;
2740 return $ret;
2741} # end getDomRecs()
2742
2743
2744## DNSDB::getRecCount()
2745# Return count of non-SOA records in zone (or default records in a group)
2746# Takes a database handle, default/live flag, reverse/forward flag, group/domain ID,
2747# and optional filtering modifier
2748# Returns the count
2749sub getRecCount {
2750 my $dbh = shift;
2751 my $defrec = shift;
2752 my $revrec = shift;
2753 my $id = shift;
2754 my $filter = shift || '';
2755
2756 # keep the nasties down, since we can't ?-sub this bit. :/
2757 # note this is chars allowed in DNS hostnames
2758 $filter =~ s/[^a-zA-Z0-9_.:-]//g;
2759
2760 my @bindvars = ($id);
2761 push @bindvars, $filter if $filter;
2762 my $sql = "SELECT count(*) FROM ".
2763 _rectable($defrec,$revrec).
2764 " WHERE "._recparent($defrec,$revrec)."=? ".
2765 "AND NOT type=$reverse_typemap{SOA}".
2766 ($filter ? " AND host ~* ?" : '');
2767 my ($count) = $dbh->selectrow_array($sql, undef, (@bindvars) );
2768
2769 return $count;
2770
2771} # end getRecCount()
2772
2773
2774## DNSDB::addRec()
2775# Add a new record to a domain or a group's default records
2776# Takes a database handle, default/live flag, group/domain ID,
2777# host, type, value, and TTL
2778# Some types require additional detail: "distance" for MX and SRV,
2779# and weight/port for SRV
2780# Returns a status code and detail message in case of error
2781##fixme: pass a hash with the record data, not a series of separate values
2782sub addRec {
2783 $errstr = '';
2784 my $dbh = shift;
2785 my $defrec = shift;
2786 my $revrec = shift;
2787 my $id = shift; # parent (group_id for defrecs, rdns_id for reverse records,
2788 # domain_id for domain records)
2789
2790 my $host = shift;
2791 my $rectype = shift; # reference so we can coerce it if "+"-types can't find both zones
2792 my $val = shift;
2793 my $ttl = shift;
2794
2795 # prep for validation
2796 my $addr = NetAddr::IP->new($$val);
2797 $$host =~ s/\.+$//; # FQDNs ending in . are an internal detail, and really shouldn't be exposed in the UI.
2798
2799 my $domid = 0;
2800 my $revid = 0;
2801
2802 my $retcode = 'OK'; # assume everything will go OK
2803 my $retmsg = '';
2804
2805 # do simple validation first
2806 return ('FAIL', "TTL must be numeric") unless $ttl =~ /^\d+$/;
2807
2808 # Quick check on hostname parts. Note the regex is more forgiving than the error message;
2809 # domain names technically are case-insensitive, and we use printf-like % codes for a couple
2810 # of types. Other things may also be added to validate default records of several flavours.
2811 return ('FAIL', "Hostnames may not contain anything other than (0-9 a-z . _)")
2812 if $defrec eq 'n' && $$host !~ /^[0-9a-z_%.-]+$/i;
2813
2814 # Collect these even if we're only doing a simple A record so we can call *any* validation sub
2815 my $dist = shift;
2816 my $weight = shift;
2817 my $port = shift;
2818
2819 my $fields;
2820 my @vallist;
2821
2822 # Call the validation sub for the type requested.
2823 ($retcode,$retmsg) = $validators{$$rectype}($dbh, (defrec => $defrec, revrec => $revrec, id => $id,
2824 host => $host, rectype => $rectype, val => $val, addr => $addr,
2825 dist => \$dist, port => \$port, weight => \$weight,
2826 fields => \$fields, vallist => \@vallist) );
2827
2828 return ($retcode,$retmsg) if $retcode eq 'FAIL';
2829
2830 # Set up database fields and bind parameters
2831 $fields .= "host,type,val,ttl,"._recparent($defrec,$revrec);
2832 push @vallist, ($$host,$$rectype,$$val,$ttl,$id);
2833 my $vallen = '?'.(',?'x$#vallist);
2834
2835 # Put together the success log entry. We have to use this horrible kludge
2836 # because domain_id and rdns_id may or may not be present, and if they are,
2837 # they're not at a guaranteed consistent index in the array. wheee!
2838 my %logdata;
2839 my @ftmp = split /,/, $fields;
2840 for (my $i=0; $i <= $#vallist; $i++) {
2841 $logdata{domain_id} = $vallist[$i] if $ftmp[$i] eq 'domain_id';
2842 $logdata{rdns_id} = $vallist[$i] if $ftmp[$i] eq 'rdns_id';
2843 }
2844 $logdata{group_id} = $id if $defrec eq 'y';
2845 $logdata{group_id} = parentID($dbh,
2846 (id => $id, type => ($revrec eq 'n' ? 'domain' : 'revzone'), revrec => $revrec) )
2847 if $defrec eq 'n';
2848 $logdata{entry} = "Added ".($defrec eq 'y' ? 'default record' : 'record')." '$$host $typemap{$$rectype} $$val";
2849 $logdata{entry} .= " [distance $dist]" if $typemap{$$rectype} eq 'MX';
2850 $logdata{entry} .= " [priority $dist] [weight $weight] [port $port]"
2851 if $typemap{$$rectype} eq 'SRV';
2852 $logdata{entry} .= "', TTL $ttl";
2853
2854 # Allow transactions, and raise an exception on errors so we can catch it later.
2855 # Use local to make sure these get "reset" properly on exiting this block
2856 local $dbh->{AutoCommit} = 0;
2857 local $dbh->{RaiseError} = 1;
2858
2859 eval {
2860 $dbh->do("INSERT INTO "._rectable($defrec, $revrec)." ($fields) VALUES ($vallen)",
2861 undef, @vallist);
2862 _log($dbh, %logdata);
2863 $dbh->commit;
2864 };
2865 if ($@) {
2866 my $msg = $@;
2867 eval { $dbh->rollback; };
2868 if ($config{log_failures}) {
2869 $logdata{entry} = "Failed adding ".($defrec eq 'y' ? 'default ' : '').
2870 "record '$$host $typemap{$$rectype} $$val', TTL $ttl ($msg)";
2871 _log($dbh, %logdata);
2872 $dbh->commit;
2873 }
2874 return ('FAIL',$msg);
2875 }
2876
2877 $resultstr = $logdata{entry};
2878 return ($retcode, $retmsg);
2879
2880} # end addRec()
2881
2882
2883## DNSDB::updateRec()
2884# Update a record
2885# Takes a database handle, default and reverse flags, record ID, immediate parent ID, and new record data.
2886# Returns a status code and message
2887sub updateRec {
2888 $errstr = '';
2889
2890 my $dbh = shift;
2891 my $defrec = shift;
2892 my $revrec = shift;
2893 my $id = shift;
2894 my $parid = shift; # immediate parent entity that we're descending from to update the record
2895
2896 # all records have these
2897 my $host = shift;
2898 my $hostbk = $$host; # Keep a backup copy of the original, so we can WARN if the update mangles the domain
2899 my $rectype = shift;
2900 my $val = shift;
2901 my $ttl = shift;
2902
2903 # prep for validation
2904 my $addr = NetAddr::IP->new($$val);
2905 $$host =~ s/\.+$//; # FQDNs ending in . are an internal detail, and really shouldn't be exposed in the UI.
2906
2907 my $domid = 0;
2908 my $revid = 0;
2909
2910 my $retcode = 'OK'; # assume everything will go OK
2911 my $retmsg = '';
2912
2913 # do simple validation first
2914 return ('FAIL', "TTL must be numeric") unless $ttl =~ /^\d+$/;
2915
2916 # Quick check on hostname parts. Note the regex is more forgiving than the error message;
2917 # domain names technically are case-insensitive, and we use printf-like % codes for a couple
2918 # of types. Other things may also be added to validate default records of several flavours.
2919 return ('FAIL', "Hostnames may not contain anything other than (0-9 a-z - . _)")
2920 if $defrec eq 'n' && $$host !~ /^[0-9a-z_%.-]+$/i;
2921
2922 # only MX and SRV will use these
2923 my $dist = shift || 0;
2924 my $weight = shift || 0;
2925 my $port = shift || 0;
2926
2927 my $fields;
2928 my @vallist;
2929
2930 # get old record data so we have the right parent ID
2931 # and for logging (eventually)
2932 my $oldrec = getRecLine($dbh, $defrec, $revrec, $id);
2933
2934 # Call the validation sub for the type requested.
2935 # Note the ID to pass here is the *parent*, not the record
2936 ($retcode,$retmsg) = $validators{$$rectype}($dbh, (defrec => $defrec, revrec => $revrec,
2937 id => ($defrec eq 'y' ? $oldrec->{group_id} : ($revrec eq 'n' ? $oldrec->{domain_id} : $oldrec->{rdns_id})),
2938 host => $host, rectype => $rectype, val => $val, addr => $addr,
2939 dist => \$dist, port => \$port, weight => \$weight,
2940 fields => \$fields, vallist => \@vallist,
2941 update => $id) );
2942
2943 return ($retcode,$retmsg) if $retcode eq 'FAIL';
2944
2945 # Set up database fields and bind parameters. Note only the optional fields
2946 # (distance, weight, port, secondary parent ID) are added in the validation call above
2947 $fields .= "host,type,val,ttl,"._recparent($defrec,$revrec);
2948 push @vallist, ($$host,$$rectype,$$val,$ttl,
2949 ($defrec eq 'y' ? $oldrec->{group_id} : ($revrec eq 'n' ? $oldrec->{domain_id} : $oldrec->{rdns_id})) );
2950
2951 # hack hack PTHUI
2952 # need to forcibly make sure we disassociate a record with a parent it's no longer related to.
2953 # eg, PTR records may not have a domain parent, or A/AAAA records may not have a revzone parent.
2954 # mainly needed for crossover types that got coerced down to "standard" types
2955 if ($defrec eq 'n') {
2956 if ($$rectype == $reverse_typemap{PTR}) {
2957 $fields .= ",domain_id";
2958 push @vallist, 0;
2959 }
2960 if ($$rectype == $reverse_typemap{A} || $$rectype == $reverse_typemap{AAAA}) {
2961 $fields .= ",rdns_id";
2962 push @vallist, 0;
2963 }
2964 }
2965
2966 # Fiddle the field list into something suitable for updates
2967 $fields =~ s/,/=?,/g;
2968 $fields .= "=?";
2969
2970 # Put together the success log entry. Horrible kludge from addRec() copied as-is since
2971 # we don't know whether the passed arguments or retrieved values for domain_id and rdns_id
2972 # will be maintained (due to "not-in-zone" validation changes)
2973 my %logdata;
2974 my @ftmp = split /,/, $fields;
2975 for (my $i=0; $i <= $#vallist; $i++) {
2976 $logdata{domain_id} = $vallist[$i] if $ftmp[$i] eq 'domain_id';
2977 $logdata{rdns_id} = $vallist[$i] if $ftmp[$i] eq 'rdns_id';
2978 }
2979 $logdata{group_id} = $parid if $defrec eq 'y';
2980 $logdata{group_id} = parentID($dbh,
2981 (id => $parid, type => ($revrec eq 'n' ? 'domain' : 'revzone'), revrec => $revrec) )
2982 if $defrec eq 'n';
2983 $logdata{entry} = "Updated ".($defrec eq 'y' ? 'default record' : 'record')." from\n".
2984 "'$oldrec->{host} $typemap{$oldrec->{type}} $oldrec->{val}";
2985 $logdata{entry} .= " [distance $oldrec->{distance}]" if $typemap{$oldrec->{type}} eq 'MX';
2986 $logdata{entry} .= " [priority $oldrec->{distance}] [weight $oldrec->{weight}] [port $oldrec->{port}]"
2987 if $typemap{$oldrec->{type}} eq 'SRV';
2988 $logdata{entry} .= "', TTL $oldrec->{ttl}\nto\n'$$host $typemap{$$rectype} $$val";
2989 $logdata{entry} .= " [distance $dist]" if $typemap{$$rectype} eq 'MX';
2990 $logdata{entry} .= " [priority $dist] [weight $weight] [port $port]" if $typemap{$$rectype} eq 'SRV';
2991 $logdata{entry} .= "', TTL $ttl";
2992
2993 local $dbh->{AutoCommit} = 0;
2994 local $dbh->{RaiseError} = 1;
2995
2996 eval {
2997 $dbh->do("UPDATE "._rectable($defrec,$revrec)." SET $fields WHERE record_id=?", undef, (@vallist, $id) );
2998 _log($dbh, %logdata);
2999 $dbh->commit;
3000 };
3001 if ($@) {
3002 my $msg = $@;
3003 eval { $dbh->rollback; };
3004 if ($config{log_failures}) {
3005 $logdata{entry} = "Failed updating ".($defrec eq 'y' ? 'default ' : '').
3006 "record '$oldrec->{host} $typemap{$oldrec->{type}} $oldrec->{val}', TTL $oldrec->{ttl} ($msg)";
3007 _log($dbh, %logdata);
3008 $dbh->commit;
3009 }
3010 return ('FAIL', $msg);
3011 }
3012
3013 $resultstr = $logdata{entry};
3014 return ($retcode, $retmsg);
3015} # end updateRec()
3016
3017
3018## DNSDB::delRec()
3019# Delete a record.
3020sub delRec {
3021 $errstr = '';
3022 my $dbh = shift;
3023 my $defrec = shift;
3024 my $revrec = shift;
3025 my $id = shift;
3026
3027 my $oldrec = getRecLine($dbh, $defrec, $revrec, $id);
3028
3029 # Allow transactions, and raise an exception on errors so we can catch it later.
3030 # Use local to make sure these get "reset" properly on exiting this block
3031 local $dbh->{AutoCommit} = 0;
3032 local $dbh->{RaiseError} = 1;
3033
3034 # Put together the log entry
3035 my %logdata;
3036 $logdata{domain_id} = $oldrec->{domain_id};
3037 $logdata{rdns_id} = $oldrec->{rdns_id};
3038 $logdata{group_id} = $oldrec->{group_id} if $defrec eq 'y';
3039 $logdata{group_id} = parentID($dbh,
3040 (id => $oldrec->{domain_id}, type => ($revrec eq 'n' ? 'domain' : 'revzone'), revrec => $revrec) )
3041 if $defrec eq 'n';
3042 $logdata{entry} = "Deleted ".($defrec eq 'y' ? 'default record ' : 'record ').
3043 "'$oldrec->{host} $typemap{$oldrec->{type}} $oldrec->{val}";
3044 $logdata{entry} .= " [distance $oldrec->{distance}]" if $typemap{$oldrec->{type}} eq 'MX';
3045 $logdata{entry} .= " [priority $oldrec->{distance}] [weight $oldrec->{weight}] [port $oldrec->{port}]"
3046 if $typemap{$oldrec->{type}} eq 'SRV';
3047 $logdata{entry} .= "', TTL $oldrec->{ttl}\n";
3048
3049 eval {
3050 my $sth = $dbh->do("DELETE FROM "._rectable($defrec,$revrec)." WHERE record_id=?", undef, ($id));
3051 _log($dbh, %logdata);
3052 $dbh->commit;
3053 };
3054 if ($@) {
3055 my $msg = $@;
3056 eval { $dbh->rollback; };
3057 if ($config{log_failures}) {
3058 $logdata{entry} = "Error deleting ".($defrec eq 'y' ? 'default record' : 'record').
3059 " '$oldrec->{host} $typemap{$oldrec->{type}} $oldrec->{val}', TTL $oldrec->{ttl} ($msg)";
3060 _log($dbh, %logdata);
3061 $dbh->commit;
3062 }
3063 return ('FAIL', $msg);
3064 }
3065
3066 return ('OK',$logdata{entry});
3067} # end delRec()
3068
3069
3070## DNSDB::getTypelist()
3071# Get a list of record types for various UI dropdowns
3072# Takes database handle, forward/reverse/lookup flag, and optional "tag as selected" indicator (defaults to A)
3073# Returns an arrayref to list of hashrefs perfect for HTML::Template
3074sub getTypelist {
3075 my $dbh = shift;
3076 my $recgroup = shift;
3077 my $type = shift || $reverse_typemap{A};
3078
3079 # also accepting $webvar{revrec}!
3080 $recgroup = 'f' if $recgroup eq 'n';
3081 $recgroup = 'r' if $recgroup eq 'y';
3082
3083 my $sql = "SELECT val,name FROM rectypes WHERE ";
3084 if ($recgroup eq 'r') {
3085 # reverse zone types
3086 $sql .= "stdflag=2 OR stdflag=3";
3087 } elsif ($recgroup eq 'l') {
3088 # DNS lookup types. Note we avoid our custom types >= 65280, since those are entirely internal.
3089 $sql .= "(stdflag=1 OR stdflag=2 OR stdflag=3) AND val < 65280";
3090 } else {
3091 # default; forward zone types. technically $type eq 'f' but not worth the error message.
3092 $sql .= "stdflag=1 OR stdflag=2";
3093 }
3094 $sql .= " ORDER BY listorder";
3095
3096 my $sth = $dbh->prepare($sql);
3097 $sth->execute;
3098 my @typelist;
3099 while (my ($rval,$rname) = $sth->fetchrow_array()) {
3100 my %row = ( recval => $rval, recname => $rname );
3101 $row{tselect} = 1 if $rval == $type;
3102 push @typelist, \%row;
3103 }
3104
3105 # Add SOA on lookups since it's not listed in other dropdowns.
3106 if ($recgroup eq 'l') {
3107 my %row = ( recval => $reverse_typemap{SOA}, recname => 'SOA' );
3108 $row{tselect} = 1 if $reverse_typemap{SOA} == $type;
3109 push @typelist, \%row;
3110 }
3111
3112 return \@typelist;
3113} # end getTypelist()
3114
3115
3116## DNSDB::parentID()
3117# Get ID of entity that is nearest parent to requested id
3118# Takes a database handle and a hash of entity ID, entity type, optional parent type flag
3119# (domain/reverse zone or group), and optional default/live and forward/reverse flags
3120# Returns the ID or undef on failure
3121sub parentID {
3122 my $dbh = shift;
3123
3124 my %args = @_;
3125
3126 # clean up the parent-type. Set it to group if not set; coerce revzone to domain for simpler logic
3127 $args{partype} = 'group' if !$args{partype};
3128 $args{partype} = 'domain' if $args{partype} eq 'revzone';
3129
3130 # clean up defrec and revrec. default to live record, forward zone
3131 $args{defrec} = 'n' if !$args{defrec};
3132 $args{revrec} = 'n' if !$args{revrec};
3133
3134 if ($par_type{$args{partype}} eq 'domain') {
3135 # only live records can have a domain/zone parent
3136 return unless ($args{type} eq 'record' && $args{defrec} eq 'n');
3137 my $result = $dbh->selectrow_hashref("SELECT ".($args{revrec} eq 'n' ? 'domain_id' : 'rdns_id').
3138 " FROM records WHERE record_id = ?",
3139 undef, ($args{id}) ) or return;
3140 return $result;
3141 } else {
3142 # snag some arguments that will either fall through or be overwritten to save some code duplication
3143 my $tmpid = $args{id};
3144 my $type = $args{type};
3145 if ($type eq 'record' && $args{defrec} eq 'n') {
3146 # Live records go through the records table first.
3147 ($tmpid) = $dbh->selectrow_array("SELECT ".($args{revrec} eq 'n' ? 'domain_id' : 'rdns_id').
3148 " FROM records WHERE record_id = ?",
3149 undef, ($args{id}) ) or return;
3150 $type = ($args{revrec} eq 'n' ? 'domain' : 'revzone');
3151 }
3152 my ($result) = $dbh->selectrow_array("SELECT $par_col{$type} FROM $par_tbl{$type} WHERE $id_col{$type} = ?",
3153 undef, ($tmpid) );
3154 return $result;
3155 }
3156# should be impossible to get here with even remotely sane arguments
3157 return;
3158} # end parentID()
3159
3160
3161## DNSDB::isParent()
3162# Returns true if $id1 is a parent of $id2, false otherwise
3163sub isParent {
3164 my $dbh = shift;
3165 my $id1 = shift;
3166 my $type1 = shift;
3167 my $id2 = shift;
3168 my $type2 = shift;
3169##todo: immediate, secondary, full (default)
3170
3171 # Return false on invalid types
3172 return 0 if !grep /^$type1$/, ('record','defrec','defrevrec','user','domain','revzone','group');
3173 return 0 if !grep /^$type2$/, ('record','defrec','defrevrec','user','domain','revzone','group');
3174
3175 # Return false on impossible relations
3176 return 0 if $type1 eq 'record'; # nothing may be a child of a record
3177 return 0 if $type1 eq 'defrec'; # nothing may be a child of a record
3178 return 0 if $type1 eq 'defrevrec'; # nothing may be a child of a record
3179 return 0 if $type1 eq 'user'; # nothing may be child of a user
3180 return 0 if $type1 eq 'domain' && $type2 ne 'record'; # domain may not be a parent of anything other than a record
3181 return 0 if $type1 eq 'revzone' && $type2 ne 'record';# reverse zone may not be a parent of anything other than a record
3182
3183 # ennnhhhh.... if we're passed an id of 0, it will never be found. usual
3184 # case would be the UI creating a new <thing>, and so we don't have an ID for
3185 # <thing> to look up yet. in that case the UI should check the parent as well.
3186 return 0 if $id1 == 0; # nothing can have a parent id of 0
3187 return 1 if $id2 == 0; # anything could have a child id of 0 (or "unknown")
3188
3189 # group 1 is the ultimate root parent
3190 return 1 if $type1 eq 'group' && $id1 == 1;
3191
3192 # groups are always (a) parent of themselves
3193 return 1 if $type1 eq 'group' && $type2 eq 'group' && $id1 == $id2;
3194
3195 my $id = $id2;
3196 my $type = $type2;
3197 my $foundparent = 0;
3198
3199 # Records are the only entity with two possible parents. We need to split the parent checks on
3200 # domain/rdns.
3201 if ($type eq 'record') {
3202 my ($dom,$rdns) = $dbh->selectrow_array("SELECT domain_id,rdns_id FROM records WHERE record_id=?",
3203 undef, ($id));
3204 # check immediate parent against request
3205 return 1 if $type1 eq 'domain' && $id1 == $dom;
3206 return 1 if $type1 eq 'revzone' && $id1 == $rdns;
3207 # if request is group, check *both* parents. Only check if the parent is nonzero though.
3208 return 1 if $dom && isParent($dbh, $id1, $type1, $dom, 'domain');
3209 return 1 if $rdns && isParent($dbh, $id1, $type1, $rdns, 'revzone');
3210 # exit here since we've executed the loop below by proxy in the above recursive calls.
3211 return 0;
3212 }
3213
3214# almost the same loop as getParents() above
3215 my $limiter = 0;
3216 while (1) {
3217 my $sql = "SELECT $par_col{$type} FROM $par_tbl{$type} WHERE $id_col{$type} = ?";
3218 my $result = $dbh->selectrow_hashref($sql,
3219 undef, ($id) );
3220 if (!$result) {
3221 $limiter++;
3222##fixme: how often will this happen on a live site? fail at max limiter <n>?
3223 warn "no results looking for $sql with id $id (depth $limiter)\n";
3224 last;
3225 }
3226 if ($result && $result->{$par_col{$type}} == $id1) {
3227 $foundparent = 1;
3228 last;
3229 } else {
3230##fixme: do we care about trying to return a "no such record/domain/user/group" error?
3231# should be impossible to create an inconsistent DB just with API calls.
3232 warn $dbh->errstr." $sql, $id" if $dbh->errstr;
3233 }
3234 # group 1 is its own parent. need this here more to break strange loops than for detecting a parent
3235 last if $result->{$par_col{$type}} == 1;
3236 $id = $result->{$par_col{$type}};
3237 $type = $par_type{$type};
3238 }
3239
3240 return $foundparent;
3241} # end isParent()
3242
3243
3244## DNSDB::zoneStatus()
3245# Returns and optionally sets a zone's status
3246# Takes a database handle, domain/revzone ID, forward/reverse flag, and optionally a status argument
3247# Returns status, or undef on errors.
3248sub zoneStatus {
3249 my $dbh = shift;
3250 my $id = shift;
3251 my $revrec = shift;
3252 my $newstatus = shift || 'mu';
3253
3254 return undef if $id !~ /^\d+$/;
3255
3256 # Allow transactions, and raise an exception on errors so we can catch it later.
3257 # Use local to make sure these get "reset" properly on exiting this block
3258 local $dbh->{AutoCommit} = 0;
3259 local $dbh->{RaiseError} = 1;
3260
3261 if ($newstatus ne 'mu') {
3262 # ooo, fun! let's see what we were passed for status
3263 eval {
3264 $newstatus = 0 if $newstatus eq 'domoff';
3265 $newstatus = 1 if $newstatus eq 'domon';
3266 $dbh->do("UPDATE ".($revrec eq 'n' ? 'domains' : 'revzones')." SET status=? WHERE ".
3267 ($revrec eq 'n' ? 'domain_id' : 'rdns_id')."=?", undef, ($newstatus,$id) );
3268
3269##fixme switch to more consise "Enabled <domain"/"Disabled <domain>" as with users?
3270 $resultstr = "Changed ".($revrec eq 'n' ? domainName($dbh, $id) : revName($dbh, $id)).
3271 " state to ".($newstatus ? 'active' : 'inactive');
3272
3273 my %loghash;
3274 $loghash{domain_id} = $id if $revrec eq 'n';
3275 $loghash{rdns_id} = $id if $revrec eq 'y';
3276 $loghash{group_id} = parentID($dbh,
3277 (id => $id, type => ($revrec eq 'n' ? 'domain' : 'revzone'), revrec => $revrec) );
3278 $loghash{entry} = $resultstr;
3279 _log($dbh, %loghash);
3280
3281 $dbh->commit;
3282 };
3283 if ($@) {
3284 my $msg = $@;
3285 eval { $dbh->rollback; };
3286 $resultstr = '';
3287 $errstr = $msg;
3288 return;
3289 }
3290 }
3291
3292 my ($status) = $dbh->selectrow_array("SELECT status FROM ".
3293 ($revrec eq 'n' ? "domains WHERE domain_id=?" : "revzones WHERE rdns_id=?"),
3294 undef, ($id) );
3295 return $status;
3296} # end zoneStatus()
3297
3298
3299## DNSDB::importAXFR
3300# Import a domain via AXFR
3301# Takes AXFR host, domain to transfer, group to put the domain in,
3302# and optionally:
3303# - active/inactive state flag (defaults to active)
3304# - overwrite-SOA flag (defaults to off)
3305# - overwrite-NS flag (defaults to off, doesn't affect subdomain NS records)
3306# Returns a status code (OK, WARN, or FAIL) and message - message should be blank
3307# if status is OK, but WARN includes conditions that are not fatal but should
3308# really be reported.
3309sub importAXFR {
3310 my $dbh = shift;
3311 my $ifrom_in = shift;
3312 my $zone = shift;
3313 my $group = shift;
3314 my $status = shift || 1;
3315 my $rwsoa = shift || 0;
3316 my $rwns = shift || 0;
3317 my $merge = shift || 0; # do we attempt to merge A/AAAA and PTR records whenever possible?
3318 # do we overload this with the fixme below?
3319##fixme: add mode to delete&replace, merge+overwrite, merge new?
3320
3321 my $nrecs = 0;
3322 my $soaflag = 0;
3323 my $nsflag = 0;
3324 my $warnmsg = '';
3325 my $ifrom;
3326
3327 my $rev = 'n';
3328 my $code = 'OK';
3329 my $msg = 'foobar?';
3330
3331 # choke on possible bad setting in ifrom
3332 # IPv4 and v6, and valid hostnames!
3333 ($ifrom) = ($ifrom_in =~ /^([0-9a-f\:.]+|[0-9a-z_.-]+)$/i);
3334 return ('FAIL', "Bad AXFR source host $ifrom")
3335 unless ($ifrom) = ($ifrom_in =~ /^([0-9a-f\:.]+|[0-9a-z_.-]+)$/i);
3336
3337 my $errmsg;
3338
3339 my $zone_id;
3340 my $domain_id = 0;
3341 my $rdns_id = 0;
3342 my $cidr;
3343
3344# magic happens! detect if we're importing a domain or a reverse zone
3345# while we're at it, figure out what the CIDR netblock is (if we got a .arpa)
3346# or what the formal .arpa zone is (if we got a CIDR netblock)
3347# Handles sub-octet v4 zones in the format specified in the Cricket Book, 2nd Ed, p217-218
3348
3349 if ($zone =~ m{(?:\.arpa\.?|/\d+)$}) {
3350 # we seem to have a reverse zone
3351 $rev = 'y';
3352
3353 if ($zone =~ /\.arpa\.?$/) {
3354 # we have a formal reverse zone. call _zone2cidr and get the CIDR block.
3355 ($code,$msg) = _zone2cidr($zone);
3356 return ($code, $msg) if $code eq 'FAIL';
3357 $cidr = $msg;
3358 } elsif ($zone =~ m|^[\d.]+/\d+$|) {
3359 # v4 revzone, CIDR netblock
3360 $cidr = NetAddr::IP->new($zone) or return ('FAIL',"$zone is not a valid CIDR block");
3361 $zone = _ZONE($cidr, 'ZONE.in-addr.arpa', 'r', '.');
3362 } elsif ($zone =~ m|^[a-fA-F\d:]+/\d+$|) {
3363 # v6 revzone, CIDR netblock
3364 $cidr = NetAddr::IP->new($zone) or return ('FAIL',"$zone is not a valid CIDR block");
3365 return ('FAIL', "$zone is not a nibble-aligned block") if $cidr->masklen % 4 != 0;
3366 $zone = _ZONE($cidr, 'ZONE.ip6.arpa', 'r', '.');
3367 } else {
3368 # there is. no. else!
3369 return ('FAIL', "Unknown zone name format");
3370 }
3371
3372 # quick check to start to see if we've already got one
3373
3374 ($zone_id) = $dbh->selectrow_array("SELECT rdns_id FROM revzones WHERE revnet=?",
3375 undef, ("$cidr"));
3376 $rdns_id = $zone_id;
3377 } else {
3378 # default to domain
3379 ($zone_id) = $dbh->selectrow_array("SELECT domain_id FROM domains WHERE domain=?",
3380 undef, ($zone));
3381 $domain_id = $zone_id;
3382 }
3383
3384 return ('FAIL', ($rev eq 'n' ? 'Domain' : 'Reverse zone')." already exists") if $zone_id;
3385
3386 # little local utility sub to swap $val and $host for revzone records.
3387 sub _revswap {
3388 my $rechost = shift;
3389 my $recdata = shift;
3390
3391 if ($rechost =~ /\.in-addr\.arpa\.?$/) {
3392 $rechost =~ s/\.in-addr\.arpa\.?$//;
3393 $rechost = join '.', reverse split /\./, $rechost;
3394 } else {
3395 $rechost =~ s/\.ip6\.arpa\.?$//;
3396 my @nibs = reverse split /\./, $rechost;
3397 $rechost = '';
3398 my $nc;
3399 foreach (@nibs) {
3400 $rechost.= $_;
3401 $rechost .= ":" if ++$nc % 4 == 0 && $nc < 32;
3402 }
3403 $rechost .= ":" if $nc < 32 && $rechost !~ /\*$/; # close netblock records?
3404##fixme: there's a case that ends up with a partial entry here:
3405# ip:add:re:ss::
3406# can't reproduce after letting it sit overnight after discovery. :(
3407#print "$rechost\n";
3408 # canonicalize with NetAddr::IP
3409 $rechost = NetAddr::IP->new($rechost)->addr unless $rechost =~ /\*$/;
3410 }
3411 return ($recdata,$rechost)
3412 }
3413
3414
3415 # Allow transactions, and raise an exception on errors so we can catch it later.
3416 # Use local to make sure these get "reset" properly on exiting this block
3417 local $dbh->{AutoCommit} = 0;
3418 local $dbh->{RaiseError} = 1;
3419
3420 my $sth;
3421 eval {
3422
3423 if ($rev eq 'n') {
3424##fixme: serial
3425 $dbh->do("INSERT INTO domains (domain,group_id,status) VALUES (?,?,?)", undef, ($zone,$group,$status) );
3426 # get domain id so we can do the records
3427 ($zone_id) = $dbh->selectrow_array("SELECT currval('domains_domain_id_seq')");
3428 $domain_id = $zone_id;
3429 _log($dbh, (group_id => $group, domain_id => $domain_id,
3430 entry => "[Added ".($status ? 'active' : 'inactive')." domain $zone via AXFR]") );
3431 } else {
3432##fixme: serial
3433 $dbh->do("INSERT INTO revzones (revnet,group_id,status) VALUES (?,?,?)", undef, ($cidr,$group,$status) );
3434 # get revzone id so we can do the records
3435 ($zone_id) = $dbh->selectrow_array("SELECT currval('revzones_rdns_id_seq')");
3436 $rdns_id = $zone_id;
3437 _log($dbh, (group_id => $group, rdns_id => $rdns_id,
3438 entry => "[Added ".($status ? 'active' : 'inactive')." reverse zone $cidr via AXFR]") );
3439 }
3440
3441## bizarre DBI<->Net::DNS interaction bug:
3442## sometimes a zone will cause an immediate commit-and-exit (sort of) of the while()
3443## fixed, apparently I was doing *something* odd, but not certain what it was that
3444## caused a commit instead of barfing
3445
3446 my $res = Net::DNS::Resolver->new;
3447 $res->nameservers($ifrom);
3448 $res->axfr_start($zone)
3449 or die "Couldn't begin AXFR\n";
3450
3451 $sth = $dbh->prepare("INSERT INTO records (domain_id,rdns_id,host,type,val,distance,weight,port,ttl)".
3452 " VALUES (?,?,?,?,?,?,?,?,?)");
3453
3454 # Stash info about sub-octet v4 revzones here so we don't have
3455 # to store the CNAMEs used to delegate a suboctet zone
3456 # $suboct{zone}{ns}[] -> array of nameservers
3457 # $suboct{zone}{cname}[] -> array of extant CNAMEs (Just In Case someone did something bizarre)
3458## commented pending actual use of this data. for now, we'll just
3459## auto-(re)create the CNAMEs in revzones on export
3460# my %suboct;
3461
3462 while (my $rr = $res->axfr_next()) {
3463
3464 my $val;
3465 my $distance = 0;
3466 my $weight = 0;
3467 my $port = 0;
3468 my $logfrag = '';
3469
3470 my $type = $rr->type;
3471 my $host = $rr->name;
3472 my $ttl = $rr->ttl;
3473
3474 $soaflag = 1 if $type eq 'SOA';
3475 $nsflag = 1 if $type eq 'NS';
3476
3477# "Primary" types:
3478# A, NS, CNAME, SOA, PTR(warn in forward), MX, TXT, AAAA, SRV, A6(ob), SPF
3479# maybe KEY
3480
3481# BIND supports:
3482# [standard]
3483# A AAAA CNAME MX NS PTR SOA TXT
3484# [variously experimental, obsolete, or obscure]
3485# 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
3486# ... if one can ever find the right magic to format them correctly
3487
3488# Net::DNS supports:
3489# RRSIG SIG NSAP NS NIMLOC NAPTR MX MR MINFO MG MB LOC ISDN IPSECKEY HINFO
3490# EID DNAME CNAME CERT APL AFSDB AAAA A DS NXT NSEC3PARAM NSEC3 NSEC KEY
3491# DNSKEY DLV X25 TXT TSIG TKEY SSHFP SRV SPF SOA RT RP PX PTR NULL APL::AplItem
3492
3493# nasty big ugly case-like thing here, since we have to do *some* different
3494# processing depending on the record. le sigh.
3495
3496##fixme: what record types other than TXT can/will have >255-byte payloads?
3497
3498 if ($type eq 'A') {
3499 $val = $rr->address;
3500 } elsif ($type eq 'NS') {
3501# hmm. should we warn here if subdomain NS'es are left alone?
3502 next if ($rwns && ($rr->name eq $zone));
3503 if ($rev eq 'y') {
3504 # revzones have records more or less reversed from forward zones.
3505 my ($tmpcode,$tmpmsg) = _zone2cidr($host);
3506 die "Error converting NS record: $tmpmsg" if $tmpcode eq 'FAIL'; # hmm. may not make sense...
3507 $val = "$tmpmsg";
3508 $host = $rr->nsdname;
3509 $logfrag = "Added record '$val $type $host', TTL $ttl";
3510# Tag and preserve. For now this is commented for a no-op, but we have Ideas for
3511# another custom storage type ("DELEGATE") that will use these subzone-delegation records
3512#if ($val ne "$cidr") {
3513# push @{$suboct{$val}{ns}}, $host;
3514#}
3515 } else {
3516 $val = $rr->nsdname;
3517 }
3518 $nsflag = 1;
3519 } elsif ($type eq 'CNAME') {
3520 if ($rev eq 'y') {
3521 # hmm. do we even want to bother with storing these at this level? Sub-octet delegation
3522 # by CNAME is essentially a record-publication hack, and we want to just represent the
3523 # "true" logical intentions as far down the stack as we can from the UI.
3524 ($host,$val) = _revswap($host,$rr->cname);
3525 $logfrag = "Added record '$val $type $host', TTL $ttl";
3526# Tag and preserve in case we want to commit them as-is later, but mostly we don't care.
3527# Commented pending actually doing something with possibly new type DELEGATE
3528#my $tmprev = $host;
3529#$tmprev =~ s/^\d+\.//;
3530#($code,$tmprev) = _zone2cidr($tmprev);
3531#push @{$suboct{"$tmprev"}{cname}}, $val;
3532 # Silently skip CNAMEs in revzones.
3533 next;
3534 } else {
3535 $val = $rr->cname;
3536 }
3537 } elsif ($type eq 'SOA') {
3538 next if $rwsoa;
3539 $host = $rr->rname.":".$rr->mname;
3540 $val = $rr->refresh.":".$rr->retry.":".$rr->expire.":".$rr->minimum;
3541 $soaflag = 1;
3542 } elsif ($type eq 'PTR') {
3543 ($host,$val) = _revswap($host,$rr->ptrdname);
3544 $logfrag = "Added record '$val $type $host', TTL $ttl";
3545 # hmm. PTR records should not be in forward zones.
3546 } elsif ($type eq 'MX') {
3547 $val = $rr->exchange;
3548 $distance = $rr->preference;
3549 } elsif ($type eq 'TXT') {
3550##fixme: Net::DNS docs say this should be deprecated for rdatastr() or char_str_list(),
3551## but don't really seem enthusiastic about it.
3552#print "should use rdatastr:\n\t".$rr->rdatastr."\n or char_str_list:\n\t".join(' ',$rr->char_str_list())."\n";
3553# rdatastr returns a BIND-targetted logical string, including opening and closing quotes
3554# char_str_list returns a list of the individual string fragments in the record
3555# txtdata returns the more useful all-in-one form (since we want to push such protocol
3556# details as far down the stack as we can)
3557# NB: this may turn out to be more troublesome if we ever have need of >512-byte TXT records.
3558 if ($rev eq 'y') {
3559 ($host,$val) = _revswap($host,$rr->txtdata);
3560 $logfrag = "Added record '$val $type $host', TTL $ttl";
3561 } else {
3562 $val = $rr->txtdata;
3563 }
3564 } elsif ($type eq 'SPF') {
3565##fixme: and the same caveat here, since it is apparently a clone of ::TXT
3566 $val = $rr->txtdata;
3567 } elsif ($type eq 'AAAA') {
3568 $val = $rr->address;
3569 } elsif ($type eq 'SRV') {
3570 $val = $rr->target;
3571 $distance = $rr->priority;
3572 $weight = $rr->weight;
3573 $port = $rr->port;
3574 } elsif ($type eq 'KEY') {
3575 # we don't actually know what to do with these...
3576 $val = $rr->flags.":".$rr->protocol.":".$rr->algorithm.":".$rr->key.":".$rr->keytag.":".$rr->privatekeyname;
3577 } else {
3578 $val = $rr->rdatastr;
3579 # Finding a different record type is not fatal.... just problematic.
3580 # We may not be able to export it correctly.
3581 $warnmsg .= "Unusual record ".$rr->name." ($type) found\n";
3582 }
3583
3584 my $logentry = "[AXFR ".($rev eq 'n' ? $zone : $cidr)."] ";
3585
3586 if ($merge) {
3587 if ($rev eq 'n') {
3588 # importing a domain; we have A and AAAA records that could be merged with matching PTR records
3589 my $etype;
3590 my ($erdns,$erid,$ettl) = $dbh->selectrow_array("SELECT rdns_id,record_id,ttl FROM records ".
3591 "WHERE host=? AND val=? AND type=12",
3592 undef, ($host, $val) );
3593 if ($erid) {
3594 if ($type eq 'A') { # PTR -> A+PTR
3595 $etype = 65280;
3596 $logentry .= "Merged A record with existing PTR record '$host A+PTR $val', TTL $ettl";
3597 }
3598 if ($type eq 'AAAA') { # PTR -> AAAA+PTR
3599 $etype = 65281;
3600 $logentry .= "Merged AAAA record with existing PTR record '$host AAAA+PTR $val', TTL $ettl";
3601 }
3602 $ettl = ($ettl < $ttl ? $ettl : $ttl); # use lower TTL
3603 $dbh->do("UPDATE records SET domain_id=?,ttl=?,type=? WHERE record_id=?", undef,
3604 ($domain_id, $ettl, $etype, $erid));
3605 $nrecs++;
3606 _log($dbh, (group_id => $group, domain_id => $domain_id, rdns_id => $erdns, entry => $logentry) );
3607 next; # while axfr_next
3608 }
3609 } # $rev eq 'n'
3610 else {
3611 # importing a revzone, we have PTR records that could be merged with matching A/AAAA records
3612 my ($domid,$erid,$ettl,$etype) = $dbh->selectrow_array("SELECT domain_id,record_id,ttl,type FROM records ".
3613 "WHERE host=? AND val=? AND (type=1 OR type=28)",
3614 undef, ($host, $val) );
3615 if ($erid) {
3616 if ($etype == 1) { # A -> A+PTR
3617 $etype = 65280;
3618 $logentry .= "Merged PTR record with existing matching A record '$host A+PTR $val', TTL $ettl";
3619 }
3620 if ($etype == 28) { # AAAA -> AAAA+PTR
3621 $etype = 65281;
3622 $logentry .= "Merged PTR record with existing matching AAAA record '$host AAAA+PTR $val', TTL $ettl";
3623 }
3624 $ettl = ($ettl < $ttl ? $ettl : $ttl); # use lower TTL
3625 $dbh->do("UPDATE records SET rdns_id=?,ttl=?,type=? WHERE record_id=?", undef,
3626 ($rdns_id, $ettl, $etype, $erid));
3627 $nrecs++;
3628 _log($dbh, (group_id => $group, domain_id => $domid, rdns_id => $rdns_id, entry => $logentry) );
3629 next; # while axfr_next
3630 }
3631 } # $rev eq 'y'
3632 } # if $merge
3633
3634 # Insert the new record
3635 $sth->execute($domain_id, $rdns_id, $host, $reverse_typemap{$type}, $val,
3636 $distance, $weight, $port, $ttl);
3637
3638 $nrecs++;
3639
3640 if ($type eq 'SOA') {
3641 # also !$rwsoa, but if that's set, it should be impossible to get here.
3642 my @tmp1 = split /:/, $host;
3643 my @tmp2 = split /:/, $val;
3644 $logentry .= "Added SOA record [contact $tmp1[0]] [master $tmp1[1]] ".
3645 "[refresh $tmp2[0]] [retry $tmp2[1]] [expire $tmp2[2]] [minttl $tmp2[3]], TTL $ttl";
3646 } elsif ($logfrag) {
3647 # special case for log entries we need to meddle with a little.
3648 $logentry .= $logfrag;
3649 } else {
3650 $logentry .= "Added record '$host $type";
3651 $logentry .= " [distance $distance]" if $type eq 'MX';
3652 $logentry .= " [priority $distance] [weight $weight] [port $port]" if $type eq 'SRV';
3653 $logentry .= " $val', TTL $ttl";
3654 }
3655 _log($dbh, (group_id => $group, domain_id => $domain_id, rdns_id => $rdns_id, entry => $logentry) );
3656
3657 } # while axfr_next
3658
3659# Detect and handle delegated subzones
3660# Placeholder for when we decide what to actually do with this, see previous comments in NS and CNAME handling.
3661#foreach (keys %suboct) {
3662# print "found ".($suboct{$_}{ns} ? @{$suboct{$_}{ns}} : '0')." NS records and ".
3663# ($suboct{$_}{cname} ? @{$suboct{$_}{cname}} : '0')." CNAMEs for $_\n";
3664#}
3665
3666 # Overwrite SOA record
3667 if ($rwsoa) {
3668 $soaflag = 1;
3669 my $sthgetsoa = $dbh->prepare("SELECT host,val,ttl FROM default_records WHERE group_id=? AND type=?");
3670 my $sthputsoa = $dbh->prepare("INSERT INTO records (domain_id,host,type,val,ttl) VALUES (?,?,?,?,?)");
3671 $sthgetsoa->execute($group,$reverse_typemap{SOA});
3672 while (my ($host,$val,$ttl) = $sthgetsoa->fetchrow_array()) {
3673 $host =~ s/DOMAIN/$zone/g;
3674 $val =~ s/DOMAIN/$zone/g;
3675 $sthputsoa->execute($zone_id,$host,$reverse_typemap{SOA},$val,$ttl);
3676 }
3677 }
3678
3679 # Overwrite NS records
3680 if ($rwns) {
3681 $nsflag = 1;
3682 my $sthgetns = $dbh->prepare("SELECT host,val,ttl FROM default_records WHERE group_id=? AND type=?");
3683 my $sthputns = $dbh->prepare("INSERT INTO records (domain_id,host,type,val,ttl) VALUES (?,?,?,?,?)");
3684 $sthgetns->execute($group,$reverse_typemap{NS});
3685 while (my ($host,$val,$ttl) = $sthgetns->fetchrow_array()) {
3686 $host =~ s/DOMAIN/$zone/g;
3687 $val =~ s/DOMAIN/$zone/g;
3688 $sthputns->execute($zone_id,$host,$reverse_typemap{NS},$val,$ttl);
3689 }
3690 }
3691
3692 die "No records found; either $ifrom is not authoritative or doesn't allow transfers\n" if !$nrecs;
3693 die "Bad zone: No SOA record!\n" if !$soaflag;
3694 die "Bad zone: No NS records!\n" if !$nsflag;
3695
3696 $dbh->commit;
3697
3698 };
3699
3700 if ($@) {
3701 my $msg = $@;
3702 eval { $dbh->rollback; };
3703 return ('FAIL',$msg." $warnmsg");
3704 } else {
3705 return ('WARN', $warnmsg) if $warnmsg;
3706 return ('OK',"Imported OK");
3707 }
3708
3709 # it should be impossible to get here.
3710 return ('WARN',"OOOK!");
3711} # end importAXFR()
3712
3713
3714## DNSDB::importBIND()
3715sub importBIND {
3716} # end importBIND()
3717
3718
3719## DNSDB::import_tinydns()
3720sub import_tinydns {
3721} # end import_tinydns()
3722
3723
3724## DNSDB::export()
3725# Export the DNS database, or a part of it
3726# Takes database handle, export type, optional arguments depending on type
3727# Writes zone data to targets as appropriate for type
3728sub export {
3729 my $dbh = shift;
3730 my $target = shift;
3731
3732 if ($target eq 'tiny') {
3733 __export_tiny($dbh,@_);
3734 }
3735# elsif ($target eq 'foo') {
3736# __export_foo($dbh,@_);
3737#}
3738# etc
3739
3740} # end export()
3741
3742
3743## DNSDB::__export_tiny
3744# Internal sub to implement tinyDNS (compatible) export
3745# Takes database handle, filehandle to write export to, optional argument(s)
3746# to determine which data gets exported
3747sub __export_tiny {
3748 my $dbh = shift;
3749 my $datafile = shift;
3750
3751##fixme: slurp up further options to specify particular zone(s) to export
3752
3753 ## Convert a bare number into an octal-coded pair of octets.
3754 # Take optional arg to indicate a decimal or hex input. Defaults to hex.
3755 sub octalize {
3756 my $tmp = shift;
3757 my $srctype = shift || 'h'; # default assumes hex string
3758 $tmp = sprintf "%0.4x", hex($tmp) if $srctype eq 'h'; # 0-pad hex to 4 digits
3759 $tmp = sprintf "%0.4x", $tmp if $srctype eq 'd'; # 0-pad decimal to 4 hex digits
3760 my @o = ($tmp =~ /^(..)(..)$/); # split into octets
3761 return sprintf "\\%0.3o\\%0.3o", hex($o[0]), hex($o[1]);;
3762 }
3763
3764##fixme: fail if $datafile isn't an open, writable file
3765
3766 # easy case - export all evarything
3767 # not-so-easy case - export item(s) specified
3768 # todo: figure out what kind of list we use to export items
3769
3770 my $domsth = $dbh->prepare("SELECT domain_id,domain,status FROM domains WHERE status=1");
3771 my $recsth = $dbh->prepare("SELECT host,type,val,distance,weight,port,ttl ".
3772 "FROM records WHERE domain_id=?");
3773 $domsth->execute();
3774 while (my ($domid,$dom,$domstat) = $domsth->fetchrow_array) {
3775 $recsth->execute($domid);
3776 while (my ($host,$type,$val,$dist,$weight,$port,$ttl) = $recsth->fetchrow_array) {
3777##fixme: need to store location in the db, and retrieve it here.
3778# temporarily hardcoded to empty so we can include it further down.
3779my $loc = '';
3780
3781##fixme: record validity timestamp. tinydns supports fiddling with timestamps.
3782# note $ttl must be set to 0 if we want to use tinydns's auto-expiring timestamps.
3783# timestamps are TAI64
3784# ~~ 2^62 + time()
3785my $stamp = '';
3786
3787# raw packet in unknown format: first byte indicates length
3788# of remaining data, allows up to 255 raw bytes
3789
3790##fixme? append . to all host/val hostnames
3791 if ($typemap{$type} eq 'SOA') {
3792
3793 # host contains pri-ns:responsible
3794 # val is abused to contain refresh:retry:expire:minttl
3795##fixme: "manual" serial vs tinydns-autoserial
3796 # let's be explicit about abusing $host and $val
3797 my ($email, $primary) = (split /:/, $host)[0,1];
3798 my ($refresh, $retry, $expire, $min_ttl) = (split /:/, $val)[0,1,2,3];
3799 print $datafile "Z$dom:$primary:$email"."::$refresh:$retry:$expire:$min_ttl:$ttl:$stamp:$loc\n";
3800
3801 } elsif ($typemap{$type} eq 'A') {
3802
3803 print $datafile "+$host:$val:$ttl:$stamp:$loc\n";
3804
3805 } elsif ($typemap{$type} eq 'NS') {
3806
3807 print $datafile "\&$host"."::$val:$ttl:$stamp:$loc\n";
3808
3809 } elsif ($typemap{$type} eq 'AAAA') {
3810
3811 print $datafile ":$host:28:";
3812 my $altgrp = 0;
3813 my @altconv;
3814 # Split in to up to 8 groups of hex digits (allows for IPv6 :: 0-collapsing)
3815 foreach (split /:/, $val) {
3816 if (/^$/) {
3817 # flag blank entry; this is a series of 0's of (currently) unknown length
3818 $altconv[$altgrp++] = 's';
3819 } else {
3820 # call sub to convert 1-4 hex digits to 2 string-rep octal bytes
3821 $altconv[$altgrp++] = octalize($_)
3822 }
3823 }
3824 foreach my $octet (@altconv) {
3825 # if not 's', output
3826 print $datafile $octet unless $octet =~ /^s$/;
3827 # if 's', output (9-array length)x literal '\000\000'
3828 print $datafile '\000\000'x(9-$altgrp) if $octet =~ /^s$/;
3829 }
3830 print $datafile ":$ttl:$stamp:$loc\n";
3831
3832 } elsif ($typemap{$type} eq 'MX') {
3833
3834 print $datafile "\@$host"."::$val:$dist:$ttl:$stamp:$loc\n";
3835
3836 } elsif ($typemap{$type} eq 'TXT') {
3837
3838##fixme: split v-e-r-y long TXT strings? will need to do so for BIND export, at least
3839 $val =~ s/:/\\072/g; # may need to replace other symbols
3840 print $datafile "'$host:$val:$ttl:$stamp:$loc\n";
3841
3842# by-hand TXT
3843#:deepnet.cx:16:2v\075spf1\040a\040a\072bacon.deepnet.cx\040a\072home.deepnet.cx\040-all:3600
3844#@ IN TXT "v=spf1 a a:bacon.deepnet.cx a:home.deepnet.cx -all"
3845#'deepnet.cx:v=spf1 a a\072bacon.deepnet.cx a\072home.deepnet.cx -all:3600
3846
3847#txttest IN TXT "v=foo bar:bob kn;ob' \" !@#$%^&*()-=_+[]{}<>?"
3848#: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
3849
3850# very long TXT record as brought in by axfr-get
3851# note tinydns does not support >512-byte RR data, need axfr-dns (for TCP support) for that
3852# also note, tinydns does not seem to support <512, >256-byte RRdata from axfr-get either. :/
3853#:longtxt.deepnet.cx:16:
3854#\170this is a very long txt record. it is really long. long. very long. really very long. this is a very long txt record.
3855#\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.
3856#\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.
3857#:3600
3858
3859 } elsif ($typemap{$type} eq 'CNAME') {
3860
3861 print $datafile "C$host:$val:$ttl:$stamp:$loc\n";
3862
3863 } elsif ($typemap{$type} eq 'SRV') {
3864
3865 # data is two-byte values for priority, weight, port, in that order,
3866 # followed by length/string data
3867
3868 print $datafile ":$host:33:".octalize($dist,'d').octalize($weight,'d').octalize($port,'d');
3869
3870 $val .= '.' if $val !~ /\.$/;
3871 foreach (split /\./, $val) {
3872 printf $datafile "\\%0.3o%s", length($_), $_;
3873 }
3874 print $datafile "\\000:$ttl:$stamp:$loc\n";
3875
3876 } elsif ($typemap{$type} eq 'RP') {
3877
3878 # RP consists of two mostly free-form strings.
3879 # The first is supposed to be an email address with @ replaced by . (as with the SOA contact)
3880 # The second is the "hostname" of a TXT record with more info.
3881 print $datafile ":$host:17:";
3882 my ($who,$what) = split /\s/, $val;
3883 foreach (split /\./, $who) {
3884 printf $datafile "\\%0.3o%s", length($_), $_;
3885 }
3886 print $datafile '\000';
3887 foreach (split /\./, $what) {
3888 printf $datafile "\\%0.3o%s", length($_), $_;
3889 }
3890 print $datafile "\\000:$ttl:$stamp:$loc\n";
3891
3892 } elsif ($typemap{$type} eq 'PTR') {
3893
3894 # must handle both IPv4 and IPv6
3895##work
3896 # data should already be in suitable reverse order.
3897 print $datafile "^$host:$val:$ttl:$stamp:$loc\n";
3898
3899 } else {
3900 # raw record. we don't know what's in here, so we ASS-U-ME the user has
3901 # put it in correctly, since either the user is messing directly with the
3902 # database, or the record was imported via AXFR
3903 # <split by char>
3904 # convert anything not a-zA-Z0-9.- to octal coding
3905
3906##fixme: add flag to export "unknown" record types - note we'll probably end up
3907# mangling them since they were written to the DB from Net::DNS::RR::<type>->rdatastr.
3908 #print $datafile ":$host:$type:$val:$ttl:$stamp:$loc\n";
3909
3910 } # record type if-else
3911
3912 } # while ($recsth)
3913 } # while ($domsth)
3914} # end __export_tiny()
3915
3916
3917## DNSDB::mailNotify()
3918# Sends notification mail to recipients regarding a DNSDB operation
3919sub mailNotify {
3920 my $dbh = shift;
3921 my ($subj,$message) = @_;
3922
3923 return if $config{mailhost} eq 'smtp.example.com'; # do nothing if still using default SMTP host.
3924
3925 my $mailer = Net::SMTP->new($config{mailhost}, Hello => "dnsadmin.$config{domain}");
3926
3927 my $mailsender = ($config{mailsender} ? $config{mailsender} : $config{mailnotify});
3928
3929 $mailer->mail($mailsender);
3930 $mailer->to($config{mailnotify});
3931 $mailer->data("From: \"$config{mailname}\" <$mailsender>\n",
3932 "To: <$config{mailnotify}>\n",
3933 "Date: ".strftime("%a, %d %b %Y %H:%M:%S %z",localtime)."\n",
3934 "Subject: $subj\n",
3935 "X-Mailer: DNSAdmin Notify v".sprintf("%.1d",$DNSDB::VERSION)."\n",
3936 "Organization: $config{orgname}\n",
3937 "\n$message\n");
3938 $mailer->quit;
3939}
3940
3941# shut Perl up
39421;
Note: See TracBrowser for help on using the repository browser.