source: trunk/DNSDB.pm@ 309

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

/trunk

Minor code review

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