source: trunk/DNSDB.pm@ 312

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

/trunk

Fix lurking bug in _ZONE that retained an extra 0 on CIDR to
full ip6.arpa zone name conversions with whole-nibble blocks

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