source: trunk/DNSDB.pm@ 368

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

/trunk

First stage implementation of export caching for performance. See #38.
A lot of the actual performance boost comes from indexes on a couple of
columns in WHERE clauses:

  • status column on domains and revzones
  • type, domain_id and rdns_id columns on records

Net speedup on ~100K records and ~3K zones was
~120s -> 20s (no cache) -> 4s (cache active)

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