source: trunk/DNSDB.pm@ 297

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

/trunk

Move action logging for user delete into delUser(). See #35
Tweak log entry/result message for userStatus() for consistency
and clarity

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