source: trunk/DNSDB.pm@ 346

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

/trunk

Delegation type now exports correctly, or at least as correctly as the
input data can manage. Nested super-/24 and sub-/24 delegations may
not resolve correctly depending on whether a DNS server hands out only
the super-/24 delegation records or only the CNAMEs for the sub-/24, or
both.

As a nice bonus, it doesn't matter for most delegations whether you use
explicit NS records or the "Delegation" pseudotype. Only sub-/24
delegations will not be fully created (including the CNAMEs for each IP)
with just NS records.

See #26.

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