source: trunk/DNSDB.pm@ 464

Last change on this file since 464 was 464, checked in by Kris Deugau, 11 years ago

/trunk

Trim stale global that never got used anyway.

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