source: trunk/DNSDB.pm@ 340

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

/trunk

Fill in validation stubs for type 65282 (PTR template) and
65283 (A+PTR template). See #26.

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