source: trunk/DNSDB.pm@ 300

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

/trunk

Fix really silly bug that allowed adding the same reverse zone
more than once

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