source: trunk/DNSDB.pm@ 272

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

/trunk

Checkpoint; update record mostly patched up for reverse records.
See #26

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