source: trunk/DNSDB.pm@ 281

Last change on this file since 281 was 281, checked in by Kris Deugau, 13 years ago

/trunk

Clean up some lingering structural messes in DNSDB.pm

  • Make comment headers on all utility subs consistent
  • Move _log() into "utility subs" grouping. Remove commented user-info-finding code in passing.
  • Add heading comment on validation subs since it would be pretty much the same for all of them.

Fix a bug in addRec() in passing as well; weight and port were
shift'ed from the argument list in the wrong order.

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