source: trunk/DNSDB.pm@ 294

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

/trunk

"Move action logging for change group default permissions" mutated
into "Move action logging for (change group default permissions),
(add user), (update user), (update user permissions)". See #35.

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