source: trunk/DNSDB.pm@ 463

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

/trunk

Add another template expansion; '%blank%' will cause the template
record to not output any records. May be useful for eg a /30
where only the live IP should have a reverse entry.

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