source: trunk/DNSDB.pm@ 457

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

/trunk

Refiddle getRevPattern() again, so that it looks for all PTR types.

  • Property svn:keywords set to Date Rev Author Id
File size: 184.2 KB
Line 
1# dns/trunk/DNSDB.pm
2# Abstraction functions for DNS administration
3##
4# $Id: DNSDB.pm 457 2013-01-17 18:56:14Z 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 }
1307 }
1308 close CFG;
1309 } else {
1310 $errstr = $!;
1311 return;
1312 }
1313 return 1;
1314} # end __cfgload()
1315
1316
1317## DNSDB::connectDB()
1318# Creates connection to DNS database.
1319# Requires the database name, username, and password.
1320# Returns a handle to the db.
1321# Set up for a PostgreSQL db; could be any transactional DBMS with the
1322# right changes.
1323sub connectDB {
1324 $errstr = '';
1325 my $dbname = shift;
1326 my $user = shift;
1327 my $pass = shift;
1328 my $dbh;
1329 my $DSN = "DBI:Pg:dbname=$dbname";
1330
1331 my $host = shift;
1332 $DSN .= ";host=$host" if $host;
1333
1334# Note that we want to autocommit by default, and we will turn it off locally as necessary.
1335# We may not want to print gobbledygook errors; YMMV. Have to ponder that further.
1336 $dbh = DBI->connect($DSN, $user, $pass, {
1337 AutoCommit => 1,
1338 PrintError => 0
1339 })
1340 or return (undef, $DBI::errstr) if(!$dbh);
1341
1342##fixme: initialize the DB if we can't find the table (since, by definition, there's
1343# nothing there if we can't select from it...)
1344 my $tblsth = $dbh->prepare("SELECT count(*) FROM pg_catalog.pg_class WHERE relkind='r' AND relname=?");
1345 my ($tblcount) = $dbh->selectrow_array($tblsth, undef, ('misc'));
1346 return (undef,$DBI::errstr) if $dbh->err;
1347
1348#if ($tblcount == 0) {
1349# # create tables one at a time, checking for each.
1350# return (undef, "check table misc missing");
1351#}
1352
1353
1354# Return here if we can't select.
1355# This should retrieve the dbversion key.
1356 my $sth = $dbh->prepare("SELECT key,value FROM misc WHERE misc_id=1");
1357 $sth->execute();
1358 return (undef,$DBI::errstr) if ($sth->err);
1359
1360##fixme: do stuff to the DB on version mismatch
1361# x.y series should upgrade on $DNSDB::VERSION > misc(key=>version)
1362# DB should be downward-compatible; column defaults should give sane (if possibly
1363# useless-and-needs-help) values in columns an older software stack doesn't know about.
1364
1365# See if the select returned anything (or null data). This should
1366# succeed if the select executed, but...
1367 $sth->fetchrow();
1368 return (undef,$DBI::errstr) if ($sth->err);
1369
1370 $sth->finish;
1371
1372# If we get here, we should be OK.
1373 return ($dbh,"DB connection OK");
1374} # end connectDB
1375
1376
1377## DNSDB::finish()
1378# Cleans up after database handles and so on.
1379# Requires a database handle
1380sub finish {
1381 my $dbh = $_[0];
1382 $dbh->disconnect;
1383} # end finish
1384
1385
1386## DNSDB::initGlobals()
1387# Initialize global variables
1388# NB: this does NOT include web-specific session variables!
1389# Requires a database handle
1390sub initGlobals {
1391 my $dbh = shift;
1392
1393# load record types from database
1394 my $sth = $dbh->prepare("SELECT val,name,stdflag FROM rectypes");
1395 $sth->execute;
1396 while (my ($recval,$recname,$stdflag) = $sth->fetchrow_array()) {
1397 $typemap{$recval} = $recname;
1398 $reverse_typemap{$recname} = $recval;
1399 # now we fill the record validation function hash
1400 if ($stdflag < 5) {
1401 my $fn = "_validate_$recval";
1402 $validators{$recval} = \&$fn;
1403 } else {
1404 my $fn = "sub { return ('FAIL','Type $recval ($recname) not supported'); }";
1405 $validators{$recval} = eval $fn;
1406 }
1407 }
1408} # end initGlobals
1409
1410
1411## DNSDB::initRPC()
1412# Takes a database handle, remote username, and remote fullname.
1413# Sets up the RPC logging-pseudouser if needed.
1414# Sets the %userdata hash for logging.
1415# Returns undef on failure
1416sub initRPC {
1417 my $dbh = shift;
1418 my %args = @_;
1419
1420 return if !$args{username};
1421 return if !$args{fullname};
1422
1423 $args{username} = "$args{username}/$args{rpcsys}";
1424
1425 my $tmpuser = $dbh->selectrow_hashref("SELECT username,user_id AS userid,group_id,firstname,lastname,status".
1426 " FROM users WHERE username=?", undef, ($args{username}) );
1427 if (!$tmpuser) {
1428 $dbh->do("INSERT INTO users (username,password,firstname,type) VALUES (?,'RPC',?,'R')", undef,
1429 ($args{username}, $args{fullname}) );
1430 $tmpuser = $dbh->selectrow_hashref("SELECT username,user_id AS userid,group_id,firstname,lastname,status".
1431 " FROM users WHERE username=?", undef, ($args{username}) );
1432 }
1433 %userdata = %{$tmpuser};
1434 $userdata{lastname} = '' if !$userdata{lastname};
1435 $userdata{fullname} = "$userdata{firstname} $userdata{lastname} ($args{rpcsys})";
1436 return 1 if $tmpuser;
1437} # end initRPC()
1438
1439
1440## DNSDB::login()
1441# Takes a database handle, username and password
1442# Returns a userdata hash (UID, GID, username, fullname parts) if username exists,
1443# password matches the one on file, and account is not disabled
1444# Returns undef otherwise
1445sub login {
1446 my $dbh = shift;
1447 my $user = shift;
1448 my $pass = shift;
1449
1450 my $userinfo = $dbh->selectrow_hashref("SELECT user_id,group_id,password,firstname,lastname,status".
1451 " FROM users WHERE username=?",
1452 undef, ($user) );
1453 return if !$userinfo;
1454 return if !$userinfo->{status};
1455
1456 if ($userinfo->{password} =~ m|^\$1\$([A-Za-z0-9/.]+)\$|) {
1457 # native passwords (crypt-md5)
1458 return if $userinfo->{password} ne unix_md5_crypt($pass,$1);
1459 } elsif ($userinfo->{password} =~ /^[0-9a-f]{32}$/) {
1460 # VegaDNS import (hex-coded MD5)
1461 return if $userinfo->{password} ne md5_hex($pass);
1462 } else {
1463 # plaintext (convenient now and then)
1464 return if $userinfo->{password} ne $pass;
1465 }
1466
1467 return $userinfo;
1468} # end login()
1469
1470
1471## DNSDB::initActionLog()
1472# Set up action logging. Takes a database handle and user ID
1473# Sets some internal globals and Does The Right Thing to set up a logging channel.
1474# This sets up _log() to spew out log entries to the defined channel without worrying
1475# about having to open a file or a syslog channel
1476##fixme Need to call _initActionLog_blah() for various logging channels, configured
1477# via dnsdb.conf, in $config{log_channel} or something
1478# See https://secure.deepnet.cx/trac/dnsadmin/ticket/21
1479sub initActionLog {
1480 my $dbh = shift;
1481 my $uid = shift;
1482
1483 return if !$uid;
1484
1485 # snag user info for logging. there's got to be a way to not have to pass this back
1486 # and forth from a caller, but web usage means no persistence we can rely on from
1487 # the server side.
1488 my ($username,$fullname) = $dbh->selectrow_array("SELECT username, firstname || ' ' || lastname".
1489 " FROM users WHERE user_id=?", undef, ($uid));
1490##fixme: errors are unpossible!
1491
1492 $userdata{username} = $username;
1493 $userdata{userid} = $uid;
1494 $userdata{fullname} = $fullname;
1495
1496 # convert to real check once we have other logging channels
1497 # if ($config{log_channel} eq 'sql') {
1498 # Open Log, Sez Me!
1499 # }
1500
1501} # end initActionLog
1502
1503
1504## DNSDB::initPermissions()
1505# Set up permissions global
1506# Takes database handle and UID
1507sub initPermissions {
1508 my $dbh = shift;
1509 my $uid = shift;
1510
1511# %permissions = $(getPermissions($dbh,'user',$uid));
1512 getPermissions($dbh, 'user', $uid, \%permissions);
1513
1514} # end initPermissions()
1515
1516
1517## DNSDB::getPermissions()
1518# Get permissions from DB
1519# Requires DB handle, group or user flag, ID, and hashref.
1520sub getPermissions {
1521 my $dbh = shift;
1522 my $type = shift;
1523 my $id = shift;
1524 my $hash = shift;
1525
1526 my $sql = qq(
1527 SELECT
1528 p.admin,p.self_edit,
1529 p.group_create,p.group_edit,p.group_delete,
1530 p.user_create,p.user_edit,p.user_delete,
1531 p.domain_create,p.domain_edit,p.domain_delete,
1532 p.record_create,p.record_edit,p.record_delete,p.record_locchg,
1533 p.location_create,p.location_edit,p.location_delete,p.location_view
1534 FROM permissions p
1535 );
1536 if ($type eq 'group') {
1537 $sql .= qq(
1538 JOIN groups g ON g.permission_id=p.permission_id
1539 WHERE g.group_id=?
1540 );
1541 } else {
1542 $sql .= qq(
1543 JOIN users u ON u.permission_id=p.permission_id
1544 WHERE u.user_id=?
1545 );
1546 }
1547
1548 my $sth = $dbh->prepare($sql);
1549
1550 $sth->execute($id) or die "argh: ".$sth->errstr;
1551
1552# my $permref = $sth->fetchrow_hashref;
1553# return $permref;
1554# $hash = $permref;
1555# Eww. Need to learn how to forcibly drop a hashref onto an existing hash.
1556 ($hash->{admin},$hash->{self_edit},
1557 $hash->{group_create},$hash->{group_edit},$hash->{group_delete},
1558 $hash->{user_create},$hash->{user_edit},$hash->{user_delete},
1559 $hash->{domain_create},$hash->{domain_edit},$hash->{domain_delete},
1560 $hash->{record_create},$hash->{record_edit},$hash->{record_delete},$hash->{record_locchg},
1561 $hash->{location_create},$hash->{location_edit},$hash->{location_delete},$hash->{location_view}
1562 ) = $sth->fetchrow_array;
1563
1564} # end getPermissions()
1565
1566
1567## DNSDB::changePermissions()
1568# Update an ACL entry
1569# Takes a db handle, type, owner-id, and hashref for the changed permissions.
1570sub changePermissions {
1571 my $dbh = shift;
1572 my $type = shift;
1573 my $id = shift;
1574 my $newperms = shift;
1575 my $inherit = shift || 0;
1576
1577 my $resultmsg = '';
1578
1579 # see if we're switching from inherited to custom. for bonus points,
1580 # snag the permid and parent permid anyway, since we'll need the permid
1581 # to set/alter custom perms, and both if we're switching from custom to
1582 # inherited.
1583 my $sth = $dbh->prepare("SELECT (u.permission_id=g.permission_id) AS was_inherited,u.permission_id,g.permission_id,".
1584 ($type eq 'user' ? 'u.group_id,u.username' : 'u.parent_group_id,u.group_name').
1585 " FROM ".($type eq 'user' ? 'users' : 'groups')." u ".
1586 " JOIN groups g ON u.".($type eq 'user' ? '' : 'parent_')."group_id=g.group_id ".
1587 " WHERE u.".($type eq 'user' ? 'user' : 'group')."_id=?");
1588 $sth->execute($id);
1589
1590 my ($wasinherited,$permid,$parpermid,$parid,$name) = $sth->fetchrow_array;
1591
1592# hack phtoui
1593# group id 1 is "special" in that it's it's own parent (err... possibly.)
1594# may make its parent id 0 which doesn't exist, and as a bonus is Perl-false.
1595 $wasinherited = 0 if ($type eq 'group' && $id == 1);
1596
1597 local $dbh->{AutoCommit} = 0;
1598 local $dbh->{RaiseError} = 1;
1599
1600 # Wrap all the SQL in a transaction
1601 eval {
1602 if ($inherit) {
1603
1604 $dbh->do("UPDATE ".($type eq 'user' ? 'users' : 'groups')." SET inherit_perm='t',permission_id=? ".
1605 "WHERE ".($type eq 'user' ? 'user' : 'group')."_id=?", undef, ($parpermid, $id) );
1606 $dbh->do("DELETE FROM permissions WHERE permission_id=?", undef, ($permid) );
1607
1608 } else {
1609
1610 if ($wasinherited) { # munge new permission entry in if we're switching from inherited perms
1611##fixme: need to add semirecursive bit to properly munge inherited permission ID on subgroups and users
1612# ... if'n'when we have groups with fully inherited permissions.
1613 # SQL is coo
1614 $dbh->do("INSERT INTO permissions ($permlist,".($type eq 'user' ? 'user' : 'group')."_id) ".
1615 "SELECT $permlist,? FROM permissions WHERE permission_id=?", undef, ($id,$permid) );
1616 ($permid) = $dbh->selectrow_array("SELECT permission_id FROM permissions ".
1617 "WHERE ".($type eq 'user' ? 'user' : 'group')."_id=?", undef, ($id) );
1618 $dbh->do("UPDATE ".($type eq 'user' ? 'users' : 'groups')." SET inherit_perm='f',permission_id=? ".
1619 "WHERE ".($type eq 'user' ? 'user' : 'group')."_id=?", undef, ($permid, $id) );
1620 }
1621
1622 # and now set the permissions we were passed
1623 foreach (@permtypes) {
1624 if (defined ($newperms->{$_})) {
1625 $dbh->do("UPDATE permissions SET $_=? WHERE permission_id=?", undef, ($newperms->{$_},$permid) );
1626 }
1627 }
1628
1629 } # (inherited->)? custom
1630
1631 if ($type eq 'user') {
1632 $resultmsg = "Updated permissions for user $name";
1633 } else {
1634 $resultmsg = "Updated default permissions for group $name";
1635 }
1636 _log($dbh, (group_id => ($type eq 'user' ? $parid : $id), entry => $resultmsg));
1637 $dbh->commit;
1638 }; # end eval
1639 if ($@) {
1640 my $msg = $@;
1641 eval { $dbh->rollback; };
1642 return ('FAIL',"Error changing permissions: $msg");
1643 }
1644
1645 return ('OK',$resultmsg);
1646} # end changePermissions()
1647
1648
1649## DNSDB::comparePermissions()
1650# Compare two permission hashes
1651# Returns '>', '<', '=', '!'
1652sub comparePermissions {
1653 my $p1 = shift;
1654 my $p2 = shift;
1655
1656 my $retval = '='; # assume equality until proven otherwise
1657
1658 no warnings "uninitialized";
1659
1660 foreach (@permtypes) {
1661 next if $p1->{$_} == $p2->{$_}; # equal is good
1662 if ($p1->{$_} && !$p2->{$_}) {
1663 if ($retval eq '<') { # if we've already found an unequal pair where
1664 $retval = '!'; # $p2 has more access, and we now find a pair
1665 last; # where $p1 has more access, the overall access
1666 } # is neither greater or lesser, it's unequal.
1667 $retval = '>';
1668 }
1669 if (!$p1->{$_} && $p2->{$_}) {
1670 if ($retval eq '>') { # if we've already found an unequal pair where
1671 $retval = '!'; # $p1 has more access, and we now find a pair
1672 last; # where $p2 has more access, the overall access
1673 } # is neither greater or lesser, it's unequal.
1674 $retval = '<';
1675 }
1676 }
1677 return $retval;
1678} # end comparePermissions()
1679
1680
1681## DNSDB::changeGroup()
1682# Change group ID of an entity
1683# Takes a database handle, entity type, entity ID, and new group ID
1684sub changeGroup {
1685 my $dbh = shift;
1686 my $type = shift;
1687 my $id = shift;
1688 my $newgrp = shift;
1689
1690##fixme: fail on not enough args
1691 #return ('FAIL', "Missing
1692
1693 return ('FAIL', "Can't change the group of a $type")
1694 unless grep /^$type$/, ('domain','revzone','user','group'); # could be extended for defrecs?
1695
1696 # Collect some names for logging and messages
1697 my $entname;
1698 if ($type eq 'domain') {
1699 $entname = domainName($dbh, $id);
1700 } elsif ($type eq 'revzone') {
1701 $entname = revName($dbh, $id);
1702 } elsif ($type eq 'user') {
1703 $entname = userFullName($dbh, $id, '%u');
1704 } elsif ($type eq 'group') {
1705 $entname = groupName($dbh, $id);
1706 }
1707
1708 my ($oldgid) = $dbh->selectrow_array("SELECT group_id FROM $par_tbl{$type} WHERE $id_col{$type}=?",
1709 undef, ($id));
1710 my $oldgname = groupName($dbh, $oldgid);
1711 my $newgname = groupName($dbh, $newgrp);
1712
1713 return ('FAIL', "Can't move things into a group that doesn't exist") if !$newgname;
1714
1715 return ('WARN', "Nothing to do, new group is the same as the old group") if $oldgid == $newgrp;
1716
1717 # Allow transactions, and raise an exception on errors so we can catch it later.
1718 # Use local to make sure these get "reset" properly on exiting this block
1719 local $dbh->{AutoCommit} = 0;
1720 local $dbh->{RaiseError} = 1;
1721
1722 eval {
1723 $dbh->do("UPDATE $par_tbl{$type} SET group_id=? WHERE $id_col{$type}=?", undef, ($newgrp, $id));
1724 # Log the change in both the old and new groups
1725 _log($dbh, (group_id => $oldgid, entry => "Moved $type $entname from $oldgname to $newgname"));
1726 _log($dbh, (group_id => $newgrp, entry => "Moved $type $entname from $oldgname to $newgname"));
1727 $dbh->commit;
1728 };
1729 if ($@) {
1730 my $msg = $@;
1731 eval { $dbh->rollback; };
1732 if ($config{log_failures}) {
1733 _log($dbh, (group_id => $oldgid, entry => "Error moving $type $entname to $newgname: $msg"));
1734 $dbh->commit; # since we enabled transactions earlier
1735 }
1736 return ('FAIL',"Error moving $type $entname to $newgname: $msg");
1737 }
1738
1739 return ('OK',"Moved $type $entname from $oldgname to $newgname");
1740} # end changeGroup()
1741
1742
1743##
1744## Processing subs
1745##
1746
1747## DNSDB::addDomain()
1748# Add a domain
1749# Takes a database handle, domain name, numeric group, boolean(ish) state (active/inactive),
1750# and user info hash (for logging).
1751# Returns a status code and message
1752sub addDomain {
1753 $errstr = '';
1754 my $dbh = shift;
1755 return ('FAIL',"Need database handle") if !$dbh;
1756 my $domain = shift;
1757 return ('FAIL',"Domain must not be blank") if !$domain;
1758 my $group = shift;
1759 return ('FAIL',"Need group") if !defined($group);
1760 my $state = shift;
1761 return ('FAIL',"Need domain status") if !defined($state);
1762
1763 $state = 1 if $state =~ /^active$/;
1764 $state = 1 if $state =~ /^on$/;
1765 $state = 0 if $state =~ /^inactive$/;
1766 $state = 0 if $state =~ /^off$/;
1767
1768 return ('FAIL',"Invalid domain status") if $state !~ /^\d+$/;
1769
1770 return ('FAIL', "Invalid characters in domain") if $domain !~ /^[a-zA-Z0-9_.-]+$/;
1771
1772 my $sth = $dbh->prepare("SELECT domain_id FROM domains WHERE lower(domain) = lower(?)");
1773 my $dom_id;
1774
1775# quick check to start to see if we've already got one
1776 $sth->execute($domain);
1777 ($dom_id) = $sth->fetchrow_array;
1778
1779 return ('FAIL', "Domain already exists") if $dom_id;
1780
1781 # Allow transactions, and raise an exception on errors so we can catch it later.
1782 # Use local to make sure these get "reset" properly on exiting this block
1783 local $dbh->{AutoCommit} = 0;
1784 local $dbh->{RaiseError} = 1;
1785
1786 # Wrap all the SQL in a transaction
1787 eval {
1788 # insert the domain...
1789 $dbh->do("INSERT INTO domains (domain,group_id,status) VALUES (?,?,?)", undef, ($domain, $group, $state));
1790
1791 # get the ID...
1792 ($dom_id) = $dbh->selectrow_array("SELECT domain_id FROM domains WHERE lower(domain) = lower(?)",
1793 undef, ($domain));
1794
1795 _log($dbh, (domain_id => $dom_id, group_id => $group,
1796 entry => "Added ".($state ? 'active' : 'inactive')." domain $domain"));
1797
1798 # ... and now we construct the standard records from the default set. NB: group should be variable.
1799 my $sth = $dbh->prepare("SELECT host,type,val,distance,weight,port,ttl FROM default_records WHERE group_id=?");
1800 my $sth_in = $dbh->prepare("INSERT INTO records (domain_id,host,type,val,distance,weight,port,ttl)".
1801 " VALUES ($dom_id,?,?,?,?,?,?,?)");
1802 $sth->execute($group);
1803 while (my ($host,$type,$val,$dist,$weight,$port,$ttl) = $sth->fetchrow_array()) {
1804 $host =~ s/DOMAIN/$domain/g;
1805 $val =~ s/DOMAIN/$domain/g;
1806 $sth_in->execute($host,$type,$val,$dist,$weight,$port,$ttl);
1807 if ($typemap{$type} eq 'SOA') {
1808 my @tmp1 = split /:/, $host;
1809 my @tmp2 = split /:/, $val;
1810 _log($dbh, (domain_id => $dom_id, group_id => $group,
1811 entry => "[new $domain] Added SOA record [contact $tmp1[0]] [master $tmp1[1]] ".
1812 "[refresh $tmp2[0]] [retry $tmp2[1]] [expire $tmp2[2]] [minttl $tmp2[3]], TTL $ttl"));
1813 } else {
1814 my $logentry = "[new $domain] Added record '$host $typemap{$type}";
1815 $logentry .= " [distance $dist]" if $typemap{$type} eq 'MX';
1816 $logentry .= " [priority $dist] [weight $weight] [port $port]" if $typemap{$type} eq 'SRV';
1817 _log($dbh, (domain_id => $dom_id, group_id => $group,
1818 entry => $logentry." $val', TTL $ttl"));
1819 }
1820 }
1821
1822 # once we get here, we should have suceeded.
1823 $dbh->commit;
1824 }; # end eval
1825
1826 if ($@) {
1827 my $msg = $@;
1828 eval { $dbh->rollback; };
1829 _log($dbh, (group_id => $group, entry => "Failed adding domain $domain ($msg)"))
1830 if $config{log_failures};
1831 $dbh->commit; # since we enabled transactions earlier
1832 return ('FAIL',$msg);
1833 } else {
1834 return ('OK',$dom_id);
1835 }
1836} # end addDomain
1837
1838
1839## DNSDB::delZone()
1840# Delete a forward or reverse zone.
1841# Takes a database handle, zone ID, and forward/reverse flag.
1842# for now, just delete the records, then the domain.
1843# later we may want to archive it in some way instead (status code 2, for example?)
1844sub delZone {
1845 my $dbh = shift;
1846 my $zoneid = shift;
1847 my $revrec = shift;
1848
1849 # Allow transactions, and raise an exception on errors so we can catch it later.
1850 # Use local to make sure these get "reset" properly on exiting this block
1851 local $dbh->{AutoCommit} = 0;
1852 local $dbh->{RaiseError} = 1;
1853
1854 my $msg = '';
1855 my $failmsg = '';
1856 my $zone = ($revrec eq 'n' ? domainName($dbh, $zoneid) : revName($dbh, $zoneid));
1857
1858 return ('FAIL', ($revrec eq 'n' ? 'Domain' : 'Reverse zone')." ID $zoneid doesn't exist") if !$zone;
1859
1860 # Set this up here since we may use if if $config{log_failures} is enabled
1861 my %loghash;
1862 $loghash{domain_id} = $zoneid if $revrec eq 'n';
1863 $loghash{rdns_id} = $zoneid if $revrec eq 'y';
1864 $loghash{group_id} = parentID($dbh,
1865 (id => $zoneid, type => ($revrec eq 'n' ? 'domain' : 'revzone'), revrec => $revrec) );
1866
1867 # Wrap all the SQL in a transaction
1868 eval {
1869 # Disentangle custom record types before removing the
1870 # ones that are only in the zone to be deleted
1871 if ($revrec eq 'n') {
1872 my $sth = $dbh->prepare("UPDATE records SET type=?,domain_id=0 WHERE domain_id=? AND type=?");
1873 $failmsg = "Failure converting multizone types to single-zone";
1874 $sth->execute($reverse_typemap{PTR}, $zoneid, 65280);
1875 $sth->execute($reverse_typemap{PTR}, $zoneid, 65281);
1876 $sth->execute(65282, $zoneid, 65283);
1877 $sth->execute(65282, $zoneid, 65284);
1878 $failmsg = "Failure removing domain records";
1879 $dbh->do("DELETE FROM records WHERE domain_id=?", undef, ($zoneid));
1880 $failmsg = "Failure removing domain";
1881 $dbh->do("DELETE FROM domains WHERE domain_id=?", undef, ($zoneid));
1882 } else {
1883 my $sth = $dbh->prepare("UPDATE records SET type=?,rdns_id=0 WHERE rdns_id=? AND type=?");
1884 $failmsg = "Failure converting multizone types to single-zone";
1885 $sth->execute($reverse_typemap{A}, $zoneid, 65280);
1886 $sth->execute($reverse_typemap{AAAA}, $zoneid, 65281);
1887# We don't have an "A template" or "AAAA template" type, although it might be useful for symmetry.
1888# $sth->execute(65286?, $zoneid, 65283);
1889# $sth->execute(65286?, $zoneid, 65284);
1890 $failmsg = "Failure removing reverse records";
1891 $dbh->do("DELETE FROM records WHERE rdns_id=?", undef, ($zoneid));
1892 $failmsg = "Failure removing reverse zone";
1893 $dbh->do("DELETE FROM revzones WHERE rdns_id=?", undef, ($zoneid));
1894 }
1895
1896 $msg = "Deleted ".($revrec eq 'n' ? 'domain' : 'reverse zone')." $zone";
1897 $loghash{entry} = $msg;
1898 _log($dbh, %loghash);
1899
1900 # once we get here, we should have suceeded.
1901 $dbh->commit;
1902 }; # end eval
1903
1904 if ($@) {
1905 $msg = $@;
1906 eval { $dbh->rollback; };
1907 $loghash{entry} = "Error deleting $zone: $msg ($failmsg)";
1908 if ($config{log_failures}) {
1909 _log($dbh, %loghash);
1910 $dbh->commit; # since we enabled transactions earlier
1911 }
1912 return ('FAIL', $loghash{entry});
1913 } else {
1914 return ('OK', $msg);
1915 }
1916
1917} # end delZone()
1918
1919
1920## DNSDB::domainName()
1921# Return the domain name based on a domain ID
1922# Takes a database handle and the domain ID
1923# Returns the domain name or undef on failure
1924sub domainName {
1925 $errstr = '';
1926 my $dbh = shift;
1927 my $domid = shift;
1928 my ($domname) = $dbh->selectrow_array("SELECT domain FROM domains WHERE domain_id=?", undef, ($domid) );
1929 $errstr = $DBI::errstr if !$domname;
1930 return $domname if $domname;
1931} # end domainName()
1932
1933
1934## DNSDB::revName()
1935# Return the reverse zone name based on an rDNS ID
1936# Takes a database handle and the rDNS ID
1937# Returns the reverse zone name or undef on failure
1938sub revName {
1939 $errstr = '';
1940 my $dbh = shift;
1941 my $revid = shift;
1942 my ($revname) = $dbh->selectrow_array("SELECT revnet FROM revzones WHERE rdns_id=?", undef, ($revid) );
1943 $errstr = $DBI::errstr if !$revname;
1944 return $revname if $revname;
1945} # end revName()
1946
1947
1948## DNSDB::domainID()
1949# Takes a database handle and domain name
1950# Returns the domain ID number
1951sub domainID {
1952 $errstr = '';
1953 my $dbh = shift;
1954 my $domain = shift;
1955 my ($domid) = $dbh->selectrow_array("SELECT domain_id FROM domains WHERE lower(domain) = lower(?)",
1956 undef, ($domain) );
1957 $errstr = $DBI::errstr if !$domid;
1958 return $domid if $domid;
1959} # end domainID()
1960
1961
1962## DNSDB::revID()
1963# Takes a database handle and reverse zone name
1964# Returns the rDNS ID number
1965sub revID {
1966 $errstr = '';
1967 my $dbh = shift;
1968 my $revzone = shift;
1969 my ($revid) = $dbh->selectrow_array("SELECT rdns_id FROM revzones WHERE revnet=?", undef, ($revzone) );
1970 $errstr = $DBI::errstr if !$revid;
1971 return $revid if $revid;
1972} # end revID()
1973
1974
1975## DNSDB::addRDNS
1976# Adds a reverse DNS zone
1977# Takes a database handle, CIDR block, reverse DNS pattern, numeric group,
1978# and boolean(ish) state (active/inactive)
1979# Returns a status code and message
1980sub addRDNS {
1981 my $dbh = shift;
1982 my $zone = NetAddr::IP->new(shift);
1983
1984 return ('FAIL',"Zone name must be a valid CIDR netblock") unless ($zone && $zone->addr !~ /^0/);
1985 my $revpatt = shift; # construct a custom (A/AAAA+)? PTR template record
1986 my $group = shift;
1987 my $state = shift;
1988 my $defloc = shift || '';
1989
1990 $state = 1 if $state =~ /^active$/;
1991 $state = 1 if $state =~ /^on$/;
1992 $state = 0 if $state =~ /^inactive$/;
1993 $state = 0 if $state =~ /^off$/;
1994
1995 return ('FAIL',"Invalid zone status") if $state !~ /^\d+$/;
1996
1997# quick check to start to see if we've already got one
1998 my ($rdns_id) = $dbh->selectrow_array("SELECT rdns_id FROM revzones WHERE revnet=?", undef, ("$zone"));
1999
2000 return ('FAIL', "Zone already exists") if $rdns_id;
2001
2002 # Allow transactions, and raise an exception on errors so we can catch it later.
2003 # Use local to make sure these get "reset" properly on exiting this block
2004 local $dbh->{AutoCommit} = 0;
2005 local $dbh->{RaiseError} = 1;
2006
2007 my $warnstr = '';
2008 my $defttl = 3600; # 1 hour should be reasonable. And unless things have gone horribly
2009 # wrong, we should have a value to override this anyway.
2010
2011 # Wrap all the SQL in a transaction
2012 eval {
2013 # insert the zone...
2014 $dbh->do("INSERT INTO revzones (revnet,group_id,status,default_location) VALUES (?,?,?,?)", undef,
2015 ($zone, $group, $state, $defloc) );
2016
2017 # get the ID...
2018 ($rdns_id) = $dbh->selectrow_array("SELECT currval('revzones_rdns_id_seq')");
2019
2020 _log($dbh, (rdns_id => $rdns_id, group_id => $group,
2021 entry => "Added ".($state ? 'active' : 'inactive')." reverse zone $zone"));
2022
2023 # ... and now we construct the standard records from the default set. NB: group should be variable.
2024 my $sth = $dbh->prepare("SELECT host,type,val,ttl FROM default_rev_records WHERE group_id=?");
2025 my $sth_in = $dbh->prepare("INSERT INTO records (rdns_id,domain_id,host,type,val,ttl,location)".
2026 " VALUES ($rdns_id,?,?,?,?,?,?)");
2027 $sth->execute($group);
2028 while (my ($host,$type,$val,$ttl) = $sth->fetchrow_array()) {
2029 # Silently skip v4/v6 mismatches. This is not an error, this is expected.
2030 if ($zone->{isv6}) {
2031 next if ($type == 65280 || $type == 65283);
2032 } else {
2033 next if ($type == 65281 || $type == 65284);
2034 }
2035
2036 $host =~ s/ADMINDOMAIN/$config{domain}/g;
2037
2038 # Check to make sure the IP stubs will fit in the zone. Under most usage failures here should be rare.
2039 # On failure, tack a note on to a warning string and continue without adding this record.
2040 # While we're at it, we substitute $zone for ZONE in the value.
2041 if ($val eq 'ZONE') {
2042 # If we've got a pattern, we skip the default record version on (A+)PTR-template types
2043 next if $revpatt && ($type == 65282 || $type == 65283);
2044##fixme? do we care if we have multiple whole-zone templates?
2045 $val = $zone->network;
2046 } elsif ($val =~ /ZONE/) {
2047 my $tmpval = $val;
2048 $tmpval =~ s/ZONE//;
2049 # Bend the rules and allow single-trailing-number PTR or PTR template records to be inserted
2050 # as either v4 or v6. May make this an off-by-default config flag
2051 # Note that the origin records that may trigger this **SHOULD** already have ZONE,\d
2052 if ($type == 12 || $type == 65282) {
2053 $tmpval =~ s/[,.]/::/ if ($tmpval =~ /^[,.]\d+$/ && $zone->{isv6});
2054 $tmpval =~ s/[,:]+/./ if ($tmpval =~ /^(?:,|::)\d+$/ && !$zone->{isv6});
2055 }
2056 my $addr;
2057 if (_ipparent($dbh, 'n', 'y', \$tmpval, $rdns_id, \$addr)) {
2058 $val = $addr->addr;
2059 } else {
2060 $warnstr .= "\nDefault record '$val $typemap{$type} $host' doesn't fit in $zone, skipping";
2061 next;
2062 }
2063 }
2064
2065 # Substitute $zone for ZONE in the hostname, but only for non-NS records.
2066 # NS records get this substitution on the value instead.
2067 $host = _ZONE($zone, $host) if $type != 2;
2068
2069 # Fill in the forward domain ID if we can find it, otherwise:
2070 # Coerce type down to PTR or PTR template if we can't
2071 my $domid = 0;
2072 if ($type >= 65280) {
2073 if (!($domid = _hostparent($dbh, $host))) {
2074 $warnstr .= "\nRecord added as PTR instead of $typemap{$type}; domain not found for $host";
2075 $type = $reverse_typemap{PTR};
2076 $domid = 0; # just to be explicit.
2077 }
2078 }
2079
2080 $sth_in->execute($domid,$host,$type,$val,$ttl,$defloc);
2081
2082 if ($typemap{$type} eq 'SOA') {
2083 my @tmp1 = split /:/, $host;
2084 my @tmp2 = split /:/, $val;
2085 _log($dbh, (rdns_id => $rdns_id, group_id => $group,
2086 entry => "[new $zone] Added SOA record [contact $tmp1[0]] [master $tmp1[1]] ".
2087 "[refresh $tmp2[0]] [retry $tmp2[1]] [expire $tmp2[2]] [minttl $tmp2[3]], TTL $ttl"));
2088 $defttl = $tmp2[3];
2089 } else {
2090 my $logentry = "[new $zone] Added record '$host $typemap{$type} $val', TTL $ttl";
2091 $logentry .= ", default location ".getLoc($dbh, $defloc)->{description} if $defloc;
2092 _log($dbh, (rdns_id => $rdns_id, domain_id => $domid, group_id => $group, entry => $logentry) );
2093 }
2094 }
2095
2096 # Generate record based on provided pattern.
2097 if ($revpatt) {
2098 my $host;
2099 my $type = ($zone->{isv6} ? 65284 : 65283);
2100 my $val = $zone->network;
2101
2102 # Substitute $zone for ZONE in the hostname.
2103 $host = _ZONE($zone, $revpatt);
2104
2105 my $domid = 0;
2106 if (!($domid = _hostparent($dbh, $host))) {
2107 $warnstr .= "\nDefault pattern added as PTR template instead of $typemap{$type}; domain not found for $host";
2108 $type = 65282;
2109 $domid = 0; # just to be explicit.
2110 }
2111
2112 $sth_in->execute($domid,$host,$type,$val,$defttl,$defloc);
2113 my $logentry = "[new $zone] Added record '$host $typemap{$type}";
2114 _log($dbh, (rdns_id => $rdns_id, domain_id => $domid, group_id => $group,
2115 entry => $logentry." $val', TTL $defttl from pattern"));
2116 }
2117
2118 # If there are warnings (presumably about default records skipped for cause) log them
2119 _log($dbh, (rdns_id => $rdns_id, group_id => $group, entry => "Warning(s) adding $zone:$warnstr"))
2120 if $warnstr;
2121
2122 # once we get here, we should have suceeded.
2123 $dbh->commit;
2124 }; # end eval
2125
2126 if ($@) {
2127 my $msg = $@;
2128 eval { $dbh->rollback; };
2129 _log($dbh, (group_id => $group, entry => "Failed adding reverse zone $zone ($msg)"))
2130 if $config{log_failures};
2131 $dbh->commit; # since we enabled transactions earlier
2132 return ('FAIL',$msg);
2133 } else {
2134 my $retcode = 'OK';
2135 if ($warnstr) {
2136 $resultstr = $warnstr;
2137 $retcode = 'WARN';
2138 }
2139 return ($retcode, $rdns_id);
2140 }
2141
2142} # end addRDNS()
2143
2144
2145## DNSDB::getZoneCount
2146# Get count of zones in group or groups
2147# Takes a database handle and hash containing:
2148# - the "current" group
2149# - an array of "acceptable" groups
2150# - a flag for forward/reverse zones
2151# - Optionally accept a "starts with" and/or "contains" filter argument
2152# Returns an integer count of the resulting zone list.
2153sub getZoneCount {
2154 my $dbh = shift;
2155
2156 my %args = @_;
2157
2158 my @filterargs;
2159 $args{startwith} = undef if $args{startwith} && $args{startwith} !~ /^(?:[a-z]|0-9)$/;
2160 push @filterargs, "^$args{startwith}" if $args{startwith};
2161 $args{filter} =~ s/\./\[\.\]/g if $args{filter}; # only match literal dots, usually in reverse zones
2162 push @filterargs, $args{filter} if $args{filter};
2163
2164 my $sql;
2165 # Not as compact, and fix-me-twice if the common bits get wrong, but much easier to read
2166 if ($args{revrec} eq 'n') {
2167 $sql = "SELECT count(*) FROM domains".
2168 " WHERE group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
2169 ($args{startwith} ? " AND domain ~* ?" : '').
2170 ($args{filter} ? " AND domain ~* ?" : '');
2171 } else {
2172 $sql = "SELECT count(*) FROM revzones".
2173 " WHERE group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
2174 ($args{startwith} ? " AND CAST(revnet AS VARCHAR) ~* ?" : '').
2175 ($args{filter} ? " AND CAST(revnet AS VARCHAR) ~* ?" : '');
2176 }
2177 my ($count) = $dbh->selectrow_array($sql, undef, @filterargs);
2178 return $count;
2179} # end getZoneCount()
2180
2181
2182## DNSDB::getZoneList()
2183# Get a list of zones in the specified group(s)
2184# Takes the same arguments as getZoneCount() above
2185# Returns a reference to an array of hashrefs suitable for feeding to HTML::Template
2186sub getZoneList {
2187 my $dbh = shift;
2188
2189 my %args = @_;
2190
2191 my @zonelist;
2192
2193 $args{sortorder} = 'ASC' if !grep /^$args{sortorder}$/, ('ASC','DESC');
2194 $args{offset} = 0 if !$args{offset} || $args{offset} !~ /^(?:all|\d+)$/;
2195
2196 my @filterargs;
2197 $args{startwith} = undef if $args{startwith} && $args{startwith} !~ /^(?:[a-z]|0-9)$/;
2198 push @filterargs, "^$args{startwith}" if $args{startwith};
2199 $args{filter} =~ s/\./\[\.\]/g if $args{filter}; # only match literal dots, usually in reverse zones
2200 push @filterargs, $args{filter} if $args{filter};
2201
2202 my $sql;
2203 # Not as compact, and fix-me-twice if the common bits get wrong, but much easier to read
2204 if ($args{revrec} eq 'n') {
2205 $args{sortby} = 'domain' if !grep /^$args{sortby}$/, ('domain','group','status');
2206 $sql = "SELECT domain_id,domain,status,groups.group_name AS group FROM domains".
2207 " INNER JOIN groups ON domains.group_id=groups.group_id".
2208 " WHERE domains.group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
2209 ($args{startwith} ? " AND domain ~* ?" : '').
2210 ($args{filter} ? " AND domain ~* ?" : '');
2211 } else {
2212##fixme: arguably startwith here is irrelevant. depends on the UI though.
2213 $args{sortby} = 'revnet' if !grep /^$args{sortby}$/, ('revnet','group','status');
2214 $sql = "SELECT rdns_id,revnet,status,groups.group_name AS group FROM revzones".
2215 " INNER JOIN groups ON revzones.group_id=groups.group_id".
2216 " WHERE revzones.group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
2217 ($args{startwith} ? " AND CAST(revnet AS VARCHAR) ~* ?" : '').
2218 ($args{filter} ? " AND CAST(revnet AS VARCHAR) ~* ?" : '');
2219 }
2220 # A common tail.
2221 $sql .= " ORDER BY ".($args{sortby} eq 'group' ? 'groups.group_name' : $args{sortby})." $args{sortorder} ".
2222 ($args{offset} eq 'all' ? '' : " LIMIT $config{perpage}".
2223 " OFFSET ".$args{offset}*$config{perpage});
2224 my $sth = $dbh->prepare($sql);
2225 $sth->execute(@filterargs);
2226 my $rownum = 0;
2227
2228 while (my @data = $sth->fetchrow_array) {
2229 my %row;
2230 $row{domain_id} = $data[0];
2231 $row{domain} = $data[1];
2232 $row{status} = $data[2];
2233 $row{group} = $data[3];
2234 push @zonelist, \%row;
2235 }
2236
2237 return \@zonelist;
2238} # end getZoneList()
2239
2240
2241## DNSDB::getZoneLocation()
2242# Retrieve the default location for a zone.
2243# Takes a database handle, forward/reverse flag, and zone ID
2244sub getZoneLocation {
2245 my $dbh = shift;
2246 my $revrec = shift;
2247 my $zoneid = shift;
2248
2249 my ($loc) = $dbh->selectrow_array("SELECT default_location FROM ".
2250 ($revrec eq 'n' ? 'domains WHERE domain_id = ?' : 'revzones WHERE rdns_id = ?'),
2251 undef, ($zoneid));
2252 return $loc;
2253} # end getZoneLocation()
2254
2255
2256## DNSDB::addGroup()
2257# Add a group
2258# Takes a database handle, group name, parent group, hashref for permissions,
2259# and optional template-vs-cloneme flag for the default records
2260# Returns a status code and message
2261sub addGroup {
2262 $errstr = '';
2263 my $dbh = shift;
2264 my $groupname = shift;
2265 my $pargroup = shift;
2266 my $permissions = shift;
2267
2268 # 0 indicates "custom", hardcoded.
2269 # Any other value clones that group's default records, if it exists.
2270 my $inherit = shift || 0;
2271##fixme: need a flag to indicate clone records or <?> ?
2272
2273 # Allow transactions, and raise an exception on errors so we can catch it later.
2274 # Use local to make sure these get "reset" properly on exiting this block
2275 local $dbh->{AutoCommit} = 0;
2276 local $dbh->{RaiseError} = 1;
2277
2278 my ($group_id) = $dbh->selectrow_array("SELECT group_id FROM groups WHERE group_name=?", undef, ($groupname));
2279
2280 return ('FAIL', "Group already exists") if $group_id;
2281
2282 # Wrap all the SQL in a transaction
2283 eval {
2284 $dbh->do("INSERT INTO groups (parent_group_id,group_name) VALUES (?,?)", undef, ($pargroup, $groupname) );
2285
2286 my ($groupid) = $dbh->selectrow_array("SELECT currval('groups_group_id_seq')");
2287
2288 # We work through the whole set of permissions instead of specifying them so
2289 # that when we add a new permission, we don't have to change the code anywhere
2290 # that doesn't explicitly deal with that specific permission.
2291 my @permvals;
2292 foreach (@permtypes) {
2293 if (!defined ($permissions->{$_})) {
2294 push @permvals, 0;
2295 } else {
2296 push @permvals, $permissions->{$_};
2297 }
2298 }
2299 $dbh->do("INSERT INTO permissions (group_id,$permlist) values (?".',?'x($#permtypes+1).")",
2300 undef, ($groupid, @permvals) );
2301 my ($permid) = $dbh->selectrow_array("SELECT currval('permissions_permission_id_seq')");
2302 $dbh->do("UPDATE groups SET permission_id=$permid WHERE group_id=$groupid");
2303
2304 # Default records
2305 my $sthf = $dbh->prepare("INSERT INTO default_records (group_id,host,type,val,distance,weight,port,ttl) ".
2306 "VALUES ($groupid,?,?,?,?,?,?,?)");
2307 my $sthr = $dbh->prepare("INSERT INTO default_rev_records (group_id,host,type,val,ttl) ".
2308 "VALUES ($groupid,?,?,?,?)");
2309 if ($inherit) {
2310 # Duplicate records from parent. Actually relying on inherited records feels
2311 # very fragile, and it would be problematic to roll over at a later time.
2312 my $sth2 = $dbh->prepare("SELECT host,type,val,distance,weight,port,ttl FROM default_records WHERE group_id=?");
2313 $sth2->execute($pargroup);
2314 while (my @clonedata = $sth2->fetchrow_array) {
2315 $sthf->execute(@clonedata);
2316 }
2317 # And now the reverse records
2318 $sth2 = $dbh->prepare("SELECT host,type,val,ttl FROM default_rev_records WHERE group_id=?");
2319 $sth2->execute($pargroup);
2320 while (my @clonedata = $sth2->fetchrow_array) {
2321 $sthr->execute(@clonedata);
2322 }
2323 } else {
2324##fixme: Hardcoding is Bad, mmmmkaaaay?
2325 # reasonable basic defaults for SOA, MX, NS, and minimal hosting
2326 # could load from a config file, but somewhere along the line we need hardcoded bits.
2327 $sthf->execute('ns1.example.com:hostmaster.example.com', 6, '10800:3600:604800:10800', 0, 0, 0, 86400);
2328 $sthf->execute('DOMAIN', 1, '192.168.4.2', 0, 0, 0, 7200);
2329 $sthf->execute('DOMAIN', 15, 'mx.example.com', 10, 0, 0, 7200);
2330 $sthf->execute('DOMAIN', 2, 'ns1.example.com', 0, 0, 0, 7200);
2331 $sthf->execute('DOMAIN', 2, 'ns2.example.com', 0, 0, 0, 7200);
2332 $sthf->execute('www.DOMAIN', 5, 'DOMAIN', 0, 0, 0, 7200);
2333 # reasonable basic defaults for generic reverse zone. Same as initial SQL tabledef.
2334 $sthr->execute('hostmaster.ADMINDOMAIN:ns1.ADMINDOMAIN', 6, '10800:3600:604800:10800', 86400);
2335 $sthr->execute('unused-%r.ADMINDOMAIN', 65283, 'ZONE', 3600);
2336 }
2337
2338 _log($dbh, (group_id => $pargroup, entry => "Added group $groupname") );
2339
2340 # once we get here, we should have suceeded.
2341 $dbh->commit;
2342 }; # end eval
2343
2344 if ($@) {
2345 my $msg = $@;
2346 eval { $dbh->rollback; };
2347 if ($config{log_failures}) {
2348 _log($dbh, (group_id => $pargroup, entry => "Failed to add group $groupname: $msg") );
2349 $dbh->commit;
2350 }
2351 return ('FAIL',$msg);
2352 }
2353
2354 return ('OK','OK');
2355} # end addGroup()
2356
2357
2358## DNSDB::delGroup()
2359# Delete a group.
2360# Takes a group ID
2361# Returns a status code and message
2362sub delGroup {
2363 my $dbh = shift;
2364 my $groupid = shift;
2365
2366 # Allow transactions, and raise an exception on errors so we can catch it later.
2367 # Use local to make sure these get "reset" properly on exiting this block
2368 local $dbh->{AutoCommit} = 0;
2369 local $dbh->{RaiseError} = 1;
2370
2371##fixme: locate "knowable" error conditions and deal with them before the eval
2372# ... or inside, whatever.
2373# -> domains still exist in group
2374# -> ...
2375 my $failmsg = '';
2376 my $resultmsg = '';
2377
2378 # collect some pieces for logging and error messages
2379 my $groupname = groupName($dbh,$groupid);
2380 my $parid = parentID($dbh, (id => $groupid, type => 'group'));
2381
2382 # Wrap all the SQL in a transaction
2383 eval {
2384 # Check for Things in the group
2385 $failmsg = "Can't remove group $groupname";
2386 my ($grpcnt) = $dbh->selectrow_array("SELECT count(*) FROM groups WHERE parent_group_id=?", undef, ($groupid));
2387 die "$grpcnt groups still in group\n" if $grpcnt;
2388 my ($domcnt) = $dbh->selectrow_array("SELECT count(*) FROM domains WHERE group_id=?", undef, ($groupid));
2389 die "$domcnt domains still in group\n" if $domcnt;
2390 my ($usercnt) = $dbh->selectrow_array("SELECT count(*) FROM users WHERE group_id=?", undef, ($groupid));
2391 die "$usercnt users still in group\n" if $usercnt;
2392
2393 $failmsg = "Failed to delete default records for $groupname";
2394 $dbh->do("DELETE from default_records WHERE group_id=?", undef, ($groupid));
2395 $failmsg = "Failed to delete default reverse records for $groupname";
2396 $dbh->do("DELETE from default_rev_records WHERE group_id=?", undef, ($groupid));
2397 $failmsg = "Failed to remove group $groupname";
2398 $dbh->do("DELETE from groups WHERE group_id=?", undef, ($groupid));
2399
2400 _log($dbh, (group_id => $parid, entry => "Deleted group $groupname"));
2401 $resultmsg = "Deleted group $groupname";
2402
2403 # once we get here, we should have suceeded.
2404 $dbh->commit;
2405 }; # end eval
2406
2407 if ($@) {
2408 my $msg = $@;
2409 eval { $dbh->rollback; };
2410 if ($config{log_failures}) {
2411 _log($dbh, (group_id => $parid, entry => "$failmsg: $msg"));
2412 $dbh->commit; # since we enabled transactions earlier
2413 }
2414 return ('FAIL',"$failmsg: $msg");
2415 }
2416
2417 return ('OK',$resultmsg);
2418} # end delGroup()
2419
2420
2421## DNSDB::getChildren()
2422# Get a list of all groups whose parent^n is group <n>
2423# Takes a database handle, group ID, reference to an array to put the group IDs in,
2424# and an optional flag to return only immediate children or all children-of-children
2425# default to returning all children
2426# Calls itself
2427sub getChildren {
2428 $errstr = '';
2429 my $dbh = shift;
2430 my $rootgroup = shift;
2431 my $groupdest = shift;
2432 my $immed = shift || 'all';
2433
2434 # special break for default group; otherwise we get stuck.
2435 if ($rootgroup == 1) {
2436 # by definition, group 1 is the Root Of All Groups
2437 my $sth = $dbh->prepare("SELECT group_id FROM groups WHERE NOT (group_id=1)".
2438 ($immed ne 'all' ? " AND parent_group_id=1" : '')." ORDER BY group_name");
2439 $sth->execute;
2440 while (my @this = $sth->fetchrow_array) {
2441 push @$groupdest, @this;
2442 }
2443 } else {
2444 my $sth = $dbh->prepare("SELECT group_id FROM groups WHERE parent_group_id=? ORDER BY group_name");
2445 $sth->execute($rootgroup);
2446 return if $sth->rows == 0;
2447 my @grouplist;
2448 while (my ($group) = $sth->fetchrow_array) {
2449 push @$groupdest, $group;
2450 getChildren($dbh,$group,$groupdest) if $immed eq 'all';
2451 }
2452 }
2453} # end getChildren()
2454
2455
2456## DNSDB::groupName()
2457# Return the group name based on a group ID
2458# Takes a database handle and the group ID
2459# Returns the group name or undef on failure
2460sub groupName {
2461 $errstr = '';
2462 my $dbh = shift;
2463 my $groupid = shift;
2464 my $sth = $dbh->prepare("SELECT group_name FROM groups WHERE group_id=?");
2465 $sth->execute($groupid);
2466 my ($groupname) = $sth->fetchrow_array();
2467 $errstr = $DBI::errstr if !$groupname;
2468 return $groupname if $groupname;
2469} # end groupName
2470
2471
2472## DNSDB::getGroupCount()
2473# Get count of subgroups in group or groups
2474# Takes a database handle and hash containing:
2475# - the "current" group
2476# - an array of "acceptable" groups
2477# - Optionally accept a "starts with" and/or "contains" filter argument
2478# Returns an integer count of the resulting group list.
2479sub getGroupCount {
2480 my $dbh = shift;
2481
2482 my %args = @_;
2483
2484 my @filterargs;
2485
2486 $args{startwith} = undef if $args{startwith} && $args{startwith} !~ /^(?:[a-z]|0-9)$/;
2487 push @filterargs, "^$args{startwith}" if $args{startwith};
2488 push @filterargs, $args{filter} if $args{filter};
2489
2490 my $sql = "SELECT count(*) FROM groups ".
2491 "WHERE parent_group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
2492 ($args{startwith} ? " AND group_name ~* ?" : '').
2493 ($args{filter} ? " AND group_name ~* ?" : '');
2494 my ($count) = $dbh->selectrow_array($sql, undef, (@filterargs) );
2495 $errstr = $dbh->errstr if !$count;
2496 return $count;
2497} # end getGroupCount
2498
2499
2500## DNSDB::getGroupList()
2501# Get a list of sub^n-groups in the specified group(s)
2502# Takes the same arguments as getGroupCount() above
2503# Returns an arrayref containing hashrefs suitable for feeding straight to HTML::Template
2504sub getGroupList {
2505 my $dbh = shift;
2506
2507 my %args = @_;
2508
2509 my @filterargs;
2510
2511 $args{startwith} = undef if $args{startwith} && $args{startwith} !~ /^(?:[a-z]|0-9)$/;
2512 push @filterargs, "^$args{startwith}" if $args{startwith};
2513 push @filterargs, $args{filter} if $args{filter};
2514
2515 # protection against bad or missing arguments
2516 $args{sortorder} = 'ASC' if !$args{sortorder};
2517 $args{offset} = 0 if !$args{offset} || $args{offset} !~ /^(?:all|\d+)$/;
2518
2519 # munge sortby for columns in database
2520 $args{sortby} = 'g.group_name' if $args{sortby} eq 'group';
2521 $args{sortby} = 'g2.group_name' if $args{sortby} eq 'parent';
2522
2523 my $sql = q(SELECT g.group_id AS groupid, g.group_name AS groupname, g2.group_name AS pgroup
2524 FROM groups g
2525 INNER JOIN groups g2 ON g2.group_id=g.parent_group_id
2526 ).
2527 " WHERE g.parent_group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
2528 ($args{startwith} ? " AND g.group_name ~* ?" : '').
2529 ($args{filter} ? " AND g.group_name ~* ?" : '').
2530 " GROUP BY g.group_id, g.group_name, g2.group_name ".
2531 " ORDER BY $args{sortby} $args{sortorder} ".
2532 ($args{offset} eq 'all' ? '' : " LIMIT $config{perpage} OFFSET ".$args{offset}*$config{perpage});
2533 my $glist = $dbh->selectall_arrayref($sql, { Slice => {} }, (@filterargs) );
2534 $errstr = $dbh->errstr if !$glist;
2535
2536 # LEFT JOINs make the result set balloon beyond sanity just to include counts;
2537 # this means there's lots of crunching needed to trim the result set back down.
2538 # So instead we track the order of the groups, and push the counts into the
2539 # arrayref result separately.
2540##fixme: put this whole sub in a transaction? might be
2541# needed for accurate results on very busy systems.
2542##fixme: large group lists need prepared statements?
2543#my $ucsth = $dbh->prepare("SELECT count(*) FROM users WHERE group_id=?");
2544#my $dcsth = $dbh->prepare("SELECT count(*) FROM domains WHERE group_id=?");
2545#my $rcsth = $dbh->prepare("SELECT count(*) FROM revzones WHERE group_id=?");
2546 foreach (@{$glist}) {
2547 my ($ucnt) = $dbh->selectrow_array("SELECT count(*) FROM users WHERE group_id=?", undef, ($$_{groupid}));
2548 $$_{nusers} = $ucnt;
2549 my ($dcnt) = $dbh->selectrow_array("SELECT count(*) FROM domains WHERE group_id=?", undef, ($$_{groupid}));
2550 $$_{ndomains} = $dcnt;
2551 my ($rcnt) = $dbh->selectrow_array("SELECT count(*) FROM revzones WHERE group_id=?", undef, ($$_{groupid}));
2552 $$_{nrevzones} = $rcnt;
2553 }
2554
2555 return $glist;
2556} # end getGroupList
2557
2558
2559## DNSDB::groupID()
2560# Return the group ID based on the group name
2561# Takes a database handle and the group name
2562# Returns the group ID or undef on failure
2563sub groupID {
2564 $errstr = '';
2565 my $dbh = shift;
2566 my $group = shift;
2567 my ($grpid) = $dbh->selectrow_array("SELECT group_id FROM groups WHERE group_name=?", undef, ($group) );
2568 $errstr = $DBI::errstr if !$grpid;
2569 return $grpid if $grpid;
2570} # end groupID()
2571
2572
2573## DNSDB::addUser()
2574# Add a user.
2575# Takes a DB handle, username, group ID, password, state (active/inactive).
2576# Optionally accepts:
2577# user type (user/admin) - defaults to user
2578# permissions string - defaults to inherit from group
2579# three valid forms:
2580# i - Inherit permissions
2581# c:<user_id> - Clone permissions from <user_id>
2582# C:<permission list> - Set these specific permissions
2583# first name - defaults to username
2584# last name - defaults to blank
2585# phone - defaults to blank (could put other data within column def)
2586# Returns (OK,<uid>) on success, (FAIL,<message>) on failure
2587sub addUser {
2588 $errstr = '';
2589 my $dbh = shift;
2590 my $username = shift;
2591 my $group = shift;
2592 my $pass = shift;
2593 my $state = shift;
2594
2595 return ('FAIL', "Missing one or more required entries") if !defined($state);
2596 return ('FAIL', "Username must not be blank") if !$username;
2597
2598 # Munge in some alternate state values
2599 $state = 1 if $state =~ /^active$/;
2600 $state = 1 if $state =~ /^on$/;
2601 $state = 0 if $state =~ /^inactive$/;
2602 $state = 0 if $state =~ /^off$/;
2603
2604 my $type = shift || 'u'; # create limited users by default - fwiw, not sure yet how this will interact with ACLs
2605
2606 my $permstring = shift || 'i'; # default is to inhert permissions from group
2607
2608 my $fname = shift || $username;
2609 my $lname = shift || '';
2610 my $phone = shift || ''; # not going format-check
2611
2612 my $sth = $dbh->prepare("SELECT user_id FROM users WHERE username=?");
2613 my $user_id;
2614
2615# quick check to start to see if we've already got one
2616 $sth->execute($username);
2617 ($user_id) = $sth->fetchrow_array;
2618
2619 return ('FAIL', "User already exists") if $user_id;
2620
2621 # Allow transactions, and raise an exception on errors so we can catch it later.
2622 # Use local to make sure these get "reset" properly on exiting this block
2623 local $dbh->{AutoCommit} = 0;
2624 local $dbh->{RaiseError} = 1;
2625
2626 # Wrap all the SQL in a transaction
2627 eval {
2628 # insert the user... note we set inherited perms by default since
2629 # it's simple and cleans up some other bits of state
2630 my $sth = $dbh->prepare("INSERT INTO users ".
2631 "(group_id,username,password,firstname,lastname,phone,type,status,permission_id,inherit_perm) ".
2632 "VALUES (?,?,?,?,?,?,?,?,(SELECT permission_id FROM permissions WHERE group_id=?),'t')");
2633 $sth->execute($group,$username,unix_md5_crypt($pass),$fname,$lname,$phone,$type,$state,$group);
2634
2635 # get the ID...
2636 ($user_id) = $dbh->selectrow_array("SELECT currval('users_user_id_seq')");
2637
2638# Permissions! Gotta set'em all!
2639 die "Invalid permission string $permstring\n"
2640 if $permstring !~ /^(?:
2641 i # inherit
2642 |c:\d+ # clone
2643 # custom. no, the leading , is not a typo
2644 |C:(?:,(?:group|user|domain|record|location|self)_(?:edit|create|delete|locchg|view))*
2645 )$/x;
2646# bleh. I'd call another function to do my dirty work, but we're in the middle of a transaction already.
2647 if ($permstring ne 'i') {
2648 # for cloned or custom permissions, we have to create a new permissions entry.
2649 my $clonesrc = $group;
2650 if ($permstring =~ /^c:(\d+)/) { $clonesrc = $1; }
2651 $dbh->do("INSERT INTO permissions ($permlist,user_id) ".
2652 "SELECT $permlist,? FROM permissions WHERE permission_id=".
2653 "(SELECT permission_id FROM permissions WHERE ".($permstring =~ /^c:/ ? 'user' : 'group')."_id=?)",
2654 undef, ($user_id,$clonesrc) );
2655 $dbh->do("UPDATE users SET permission_id=".
2656 "(SELECT permission_id FROM permissions WHERE user_id=?) ".
2657 "WHERE user_id=?", undef, ($user_id, $user_id) );
2658 }
2659 if ($permstring =~ /^C:/) {
2660 # finally for custom permissions, we set the passed-in permissions (and unset
2661 # any that might have been brought in by the clone operation above)
2662 my ($permid) = $dbh->selectrow_array("SELECT permission_id FROM permissions WHERE user_id=?",
2663 undef, ($user_id) );
2664 foreach (@permtypes) {
2665 if ($permstring =~ /,$_/) {
2666 $dbh->do("UPDATE permissions SET $_='t' WHERE permission_id=?", undef, ($permid) );
2667 } else {
2668 $dbh->do("UPDATE permissions SET $_='f' WHERE permission_id=?", undef, ($permid) );
2669 }
2670 }
2671 }
2672
2673 $dbh->do("UPDATE users SET inherit_perm='n' WHERE user_id=?", undef, ($user_id) );
2674
2675##fixme: add another table to hold name/email for log table?
2676
2677 _log($dbh, (group_id => $group, entry => "Added user $username ($fname $lname)"));
2678 # once we get here, we should have suceeded.
2679 $dbh->commit;
2680 }; # end eval
2681
2682 if ($@) {
2683 my $msg = $@;
2684 eval { $dbh->rollback; };
2685 if ($config{log_failures}) {
2686 _log($dbh, (group_id => $group, entry => "Error adding user $username: $msg"));
2687 $dbh->commit; # since we enabled transactions earlier
2688 }
2689 return ('FAIL',"Error adding user $username: $msg");
2690 }
2691
2692 return ('OK',"User $username ($fname $lname) added");
2693} # end addUser
2694
2695
2696## DNSDB::getUserCount()
2697# Get count of users in group
2698# Takes a database handle and hash containing at least the current group, and optionally:
2699# - a reference list of secondary groups
2700# - a filter string
2701# - a "Starts with" string
2702sub getUserCount {
2703 my $dbh = shift;
2704
2705 my %args = @_;
2706
2707 my @filterargs;
2708
2709 $args{startwith} = undef if $args{startwith} && $args{startwith} !~ /^(?:[a-z]|0-9)$/;
2710 push @filterargs, "^$args{startwith}" if $args{startwith};
2711 push @filterargs, $args{filter} if $args{filter};
2712
2713
2714 my $sql = "SELECT count(*) FROM users ".
2715 "WHERE group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
2716 ($args{startwith} ? " AND username ~* ?" : '').
2717 ($args{filter} ? " AND username ~* ?" : '');
2718 my ($count) = $dbh->selectrow_array($sql, undef, (@filterargs) );
2719 $errstr = $dbh->errstr if !$count;
2720 return $count;
2721} # end getUserCount()
2722
2723
2724## DNSDB::getUserList()
2725# Get list of users
2726# Takes the same arguments as getUserCount() above, plus optional:
2727# - sort field
2728# - sort order
2729# - offset/return-all-everything flag (defaults to $perpage records)
2730sub getUserList {
2731 my $dbh = shift;
2732
2733 my %args = @_;
2734
2735 my @filterargs;
2736
2737 $args{startwith} = undef if $args{startwith} && $args{startwith} !~ /^(?:[a-z]|0-9)$/;
2738 push @filterargs, "^$args{startwith}" if $args{startwith};
2739 push @filterargs, $args{filter} if $args{filter};
2740
2741 # better to request sorts on "simple" names, but it means we need to map it to real columns
2742 my %sortmap = (user => 'u.username', type => 'u.type', group => 'g.group_name', status => 'u.status',
2743 fname => 'fname');
2744 $args{sortby} = $sortmap{$args{sortby}};
2745
2746 # protection against bad or missing arguments
2747 $args{sortorder} = 'ASC' if !$args{sortorder};
2748 $args{sortby} = 'u.username' if !$args{sortby};
2749 $args{offset} = 0 if !$args{offset} || $args{offset} !~ /^(?:all|\d+)$/;
2750
2751 my $sql = "SELECT u.user_id, u.username, u.firstname || ' ' || u.lastname AS fname, u.type, g.group_name, u.status ".
2752 "FROM users u ".
2753 "INNER JOIN groups g ON u.group_id=g.group_id ".
2754 "WHERE u.group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
2755 ($args{startwith} ? " AND u.username ~* ?" : '').
2756 ($args{filter} ? " AND u.username ~* ?" : '').
2757 " AND NOT u.type = 'R' ".
2758 " ORDER BY $args{sortby} $args{sortorder} ".
2759 ($args{offset} eq 'all' ? '' : " LIMIT $config{perpage} OFFSET ".$args{offset}*$config{perpage});
2760 my $ulist = $dbh->selectall_arrayref($sql, { Slice => {} }, (@filterargs) );
2761 $errstr = $dbh->errstr if !$ulist;
2762 return $ulist;
2763} # end getUserList()
2764
2765
2766## DNSDB::getUserDropdown()
2767# Get a list of usernames for use in a dropdown menu.
2768# Takes a database handle, current group, and optional "tag this as selected" flag.
2769# Returns a reference to a list of hashrefs suitable to feeding to HTML::Template
2770sub getUserDropdown {
2771 my $dbh = shift;
2772 my $grp = shift;
2773 my $sel = shift || 0;
2774
2775 my $sth = $dbh->prepare("SELECT username,user_id FROM users WHERE group_id=?");
2776 $sth->execute($grp);
2777
2778 my @userlist;
2779 while (my ($username,$uid) = $sth->fetchrow_array) {
2780 my %row = (
2781 username => $username,
2782 uid => $uid,
2783 selected => ($sel == $uid ? 1 : 0)
2784 );
2785 push @userlist, \%row;
2786 }
2787 return \@userlist;
2788} # end getUserDropdown()
2789
2790
2791## DNSDB::checkUser()
2792# Check user/pass combo on login
2793sub checkUser {
2794 my $dbh = shift;
2795 my $user = shift;
2796 my $inpass = shift;
2797
2798 my $sth = $dbh->prepare("SELECT user_id,group_id,password,firstname,lastname FROM users WHERE username=?");
2799 $sth->execute($user);
2800 my ($uid,$gid,$pass,$fname,$lname) = $sth->fetchrow_array;
2801 my $loginfailed = 1 if !defined($uid);
2802
2803 if ($pass =~ m|^\$1\$([A-Za-z0-9/.]+)\$|) {
2804 $loginfailed = 1 if $pass ne unix_md5_crypt($inpass,$1);
2805 } else {
2806 $loginfailed = 1 if $pass ne $inpass;
2807 }
2808
2809 # nnnngggg
2810 return ($uid, $gid);
2811} # end checkUser
2812
2813
2814## DNSDB:: updateUser()
2815# Update general data about user
2816sub updateUser {
2817 my $dbh = shift;
2818
2819##fixme: tweak calling convention so that we can update any given bit of data
2820 my $uid = shift;
2821 my $username = shift;
2822 my $group = shift;
2823 my $pass = shift;
2824 my $state = shift;
2825 my $type = shift || 'u';
2826 my $fname = shift || $username;
2827 my $lname = shift || '';
2828 my $phone = shift || ''; # not going format-check
2829
2830 my $resultmsg = '';
2831
2832 # Munge in some alternate state values
2833 $state = 1 if $state =~ /^active$/;
2834 $state = 1 if $state =~ /^on$/;
2835 $state = 0 if $state =~ /^inactive$/;
2836 $state = 0 if $state =~ /^off$/;
2837
2838 # Allow transactions, and raise an exception on errors so we can catch it later.
2839 # Use local to make sure these get "reset" properly on exiting this block
2840 local $dbh->{AutoCommit} = 0;
2841 local $dbh->{RaiseError} = 1;
2842
2843 my $sth;
2844
2845 # Password can be left blank; if so we assume there's one on file.
2846 # Actual blank passwords are bad, mm'kay?
2847 if (!$pass) {
2848 ($pass) = $dbh->selectrow_array("SELECT password FROM users WHERE user_id=?", undef, ($uid));
2849 } else {
2850 $pass = unix_md5_crypt($pass);
2851 }
2852
2853 eval {
2854 $dbh->do("UPDATE users SET username=?, password=?, firstname=?, lastname=?, phone=?, type=?, status=?".
2855 " WHERE user_id=?", undef, ($username, $pass, $fname, $lname, $phone, $type, $state, $uid));
2856 $resultmsg = "Updated user info for $username ($fname $lname)";
2857 _log($dbh, group_id => $group, entry => $resultmsg);
2858 $dbh->commit;
2859 };
2860 if ($@) {
2861 my $msg = $@;
2862 eval { $dbh->rollback; };
2863 if ($config{log_failures}) {
2864 _log($dbh, (group_id => $group, entry => "Error updating user $username: $msg"));
2865 $dbh->commit; # since we enabled transactions earlier
2866 }
2867 return ('FAIL',"Error updating user $username: $msg");
2868 }
2869
2870 return ('OK',$resultmsg);
2871} # end updateUser()
2872
2873
2874## DNSDB::delUser()
2875# Delete a user.
2876# Takes a database handle and user ID
2877# Returns a success/failure code and matching message
2878sub delUser {
2879 my $dbh = shift;
2880 my $userid = shift;
2881
2882 return ('FAIL',"Bad userid") if !defined($userid);
2883
2884 my $userdata = getUserData($dbh, $userid);
2885
2886 # Allow transactions, and raise an exception on errors so we can catch it later.
2887 # Use local to make sure these get "reset" properly on exiting this block
2888 local $dbh->{AutoCommit} = 0;
2889 local $dbh->{RaiseError} = 1;
2890
2891 eval {
2892 $dbh->do("DELETE FROM users WHERE user_id=?", undef, ($userid));
2893 _log($dbh, (group_id => $userdata->{group_id},
2894 entry => "Deleted user ID $userid/".$userdata->{username}.
2895 " (".$userdata->{firstname}." ".$userdata->{lastname}.")") );
2896 $dbh->commit;
2897 };
2898 if ($@) {
2899 my $msg = $@;
2900 eval { $dbh->rollback; };
2901 if ($config{log_failures}) {
2902 _log($dbh, (group_id => $userdata->{group_id}, entry => "Error deleting user ID ".
2903 "$userid/".$userdata->{username}.": $msg") );
2904 $dbh->commit;
2905 }
2906 return ('FAIL',"Error deleting user $userid/".$userdata->{username}.": $msg");
2907 }
2908
2909 return ('OK',"Deleted user ".$userdata->{username}." (".$userdata->{firstname}." ".$userdata->{lastname}.")");
2910} # end delUser
2911
2912
2913## DNSDB::userFullName()
2914# Return a pretty string!
2915# Takes a user_id and optional printf-ish string to indicate which pieces where:
2916# %u for the username
2917# %f for the first name
2918# %l for the last name
2919# All other text in the passed string will be left as-is.
2920##fixme: need a "smart" option too, so that missing/null/blank first/last names don't give funky output
2921sub userFullName {
2922 $errstr = '';
2923 my $dbh = shift;
2924 my $userid = shift;
2925 my $fullformat = shift || '%f %l (%u)';
2926 my $sth = $dbh->prepare("select username,firstname,lastname from users where user_id=?");
2927 $sth->execute($userid);
2928 my ($uname,$fname,$lname) = $sth->fetchrow_array();
2929 $errstr = $DBI::errstr if !$uname;
2930
2931 $fullformat =~ s/\%u/$uname/g;
2932 $fullformat =~ s/\%f/$fname/g;
2933 $fullformat =~ s/\%l/$lname/g;
2934
2935 return $fullformat;
2936} # end userFullName
2937
2938
2939## DNSDB::userStatus()
2940# Sets and/or returns a user's status
2941# Takes a database handle, user ID and optionally a status argument
2942# Returns undef on errors.
2943sub userStatus {
2944 my $dbh = shift;
2945 my $id = shift;
2946 my $newstatus = shift || 'mu';
2947
2948 return undef if $id !~ /^\d+$/;
2949
2950 my $userdata = getUserData($dbh, $id);
2951
2952 # Allow transactions, and raise an exception on errors so we can catch it later.
2953 # Use local to make sure these get "reset" properly on exiting this block
2954 local $dbh->{AutoCommit} = 0;
2955 local $dbh->{RaiseError} = 1;
2956
2957 if ($newstatus ne 'mu') {
2958 # ooo, fun! let's see what we were passed for status
2959 eval {
2960 $newstatus = 0 if $newstatus eq 'useroff';
2961 $newstatus = 1 if $newstatus eq 'useron';
2962 $dbh->do("UPDATE users SET status=? WHERE user_id=?", undef, ($newstatus, $id));
2963
2964 $resultstr = ($newstatus ? 'Enabled' : 'Disabled')." user ".$userdata->{username}.
2965 " (".$userdata->{firstname}." ".$userdata->{lastname}.")";
2966
2967 my %loghash;
2968 $loghash{group_id} = parentID($dbh, (id => $id, type => 'user'));
2969 $loghash{entry} = $resultstr;
2970 _log($dbh, %loghash);
2971
2972 $dbh->commit;
2973 };
2974 if ($@) {
2975 my $msg = $@;
2976 eval { $dbh->rollback; };
2977 $resultstr = '';
2978 $errstr = $msg;
2979##fixme: failure logging?
2980 return;
2981 }
2982 }
2983
2984 my ($status) = $dbh->selectrow_array("SELECT status FROM users WHERE user_id=?", undef, ($id));
2985 return $status;
2986} # end userStatus()
2987
2988
2989## DNSDB::getUserData()
2990# Get misc user data for display
2991sub getUserData {
2992 my $dbh = shift;
2993 my $uid = shift;
2994
2995 my $sth = $dbh->prepare("SELECT group_id,username,firstname,lastname,phone,type,status,inherit_perm ".
2996 "FROM users WHERE user_id=?");
2997 $sth->execute($uid);
2998 return $sth->fetchrow_hashref();
2999} # end getUserData()
3000
3001
3002## DNSDB::addLoc()
3003# Add a new location.
3004# Takes a database handle, group ID, short and long description, and a comma-separated
3005# list of IP addresses.
3006# Returns ('OK',<location>) on success, ('FAIL',<failmsg>) on failure
3007sub addLoc {
3008 my $dbh = shift;
3009 my $grp = shift;
3010 my $shdesc = shift;
3011 my $comments = shift;
3012 my $iplist = shift;
3013
3014 # $shdesc gets set to the generated location ID if possible, but these can be de-undefined here.
3015 $comments = '' if !$comments;
3016 $iplist = '' if !$iplist;
3017
3018 my $loc;
3019
3020 # Generate a location ID. This is, by spec, a two-character widget. We'll use [a-z][a-z]
3021 # for now; 676 locations should satisfy all but the largest of the huge networks.
3022 # Not sure whether these are case-sensitive, or what other rules might apply - in any case
3023 # the absolute maximum is 16K (256*256) since it's parsed by tinydns as a two-character field.
3024
3025# add just after "my $origloc = $loc;":
3026# # These expand the possible space from 26^2 to 52^2 [* note in testing only 2052 were achieved],
3027# # and wrap it around.
3028# # Yes, they skip a couple of possibles. No, I don't care.
3029# $loc = 'aA' if $loc eq 'zz';
3030# $loc = 'Aa' if $loc eq 'zZ';
3031# $loc = 'ZA' if $loc eq 'Zz';
3032# $loc = 'aa' if $loc eq 'ZZ';
3033
3034 # Allow transactions, and raise an exception on errors so we can catch it later.
3035 # Use local to make sure these get "reset" properly on exiting this block
3036 local $dbh->{AutoCommit} = 0;
3037 local $dbh->{RaiseError} = 1;
3038
3039##fixme: There is probably a far better way to do this. Sequential increments
3040# are marginally less stupid that pure random generation though, and the existence
3041# check makes sure we don't stomp on an imported one.
3042
3043 eval {
3044 # Get the "last" location. Note this is the only use for loc_id, because selecting on location Does Funky Things
3045 ($loc) = $dbh->selectrow_array("SELECT location FROM locations ORDER BY loc_id DESC LIMIT 1");
3046 ($loc) = ($loc =~ /^(..)/);
3047 my $origloc = $loc;
3048 $loc = 'aa' if !$loc;
3049 # Make a change...
3050 $loc++;
3051 # ... and keep changing if it exists
3052 while ($dbh->selectrow_array("SELECT count(*) FROM locations WHERE location LIKE ?", undef, ($loc.'%'))) {
3053 $loc++;
3054 ($loc) = ($loc =~ /^(..)/);
3055 die "too many locations in use, can't add another one\n" if $loc eq $origloc;
3056##fixme: really need to handle this case faster somehow
3057#if $loc eq $origloc die "<thwap> bad admin: all locations used, your network is too fragmented";
3058 }
3059 # And now we should have a unique location. tinydns fundamentally limits the
3060 # number of these but there's no doc on what characters are valid.
3061 $shdesc = $loc if !$shdesc;
3062 $dbh->do("INSERT INTO locations (location, group_id, iplist, description, comments) VALUES (?,?,?,?,?)",
3063 undef, ($loc, $grp, $iplist, $shdesc, $comments) );
3064 _log($dbh, entry => "Added location ($shdesc, '$iplist')");
3065 $dbh->commit;
3066 };
3067 if ($@) {
3068 my $msg = $@;
3069 eval { $dbh->rollback; };
3070 if ($config{log_failures}) {
3071 $shdesc = $loc if !$shdesc;
3072 _log($dbh, (entry => "Failed adding location ($shdesc, '$iplist'): $msg"));
3073 $dbh->commit;
3074 }
3075 return ('FAIL',$msg);
3076 }
3077
3078 return ('OK',$loc);
3079} # end addLoc()
3080
3081
3082## DNSDB::updateLoc()
3083# Update details of a location.
3084# Takes a database handle, location ID, group ID, short description,
3085# long comments/notes, and comma/space-separated IP list
3086# Returns a result code and message
3087sub updateLoc {
3088 my $dbh = shift;
3089 my $loc = shift;
3090 my $grp = shift;
3091 my $shdesc = shift;
3092 my $comments = shift;
3093 my $iplist = shift;
3094
3095 $shdesc = '' if !$shdesc;
3096 $comments = '' if !$comments;
3097 $iplist = '' if !$iplist;
3098
3099 # Allow transactions, and raise an exception on errors so we can catch it later.
3100 # Use local to make sure these get "reset" properly on exiting this block
3101 local $dbh->{AutoCommit} = 0;
3102 local $dbh->{RaiseError} = 1;
3103
3104 my $oldloc = getLoc($dbh, $loc);
3105 my $okmsg = "Updated location (".$oldloc->{description}.", '".$oldloc->{iplist}."') to ($shdesc, '$iplist')";
3106
3107 eval {
3108 $dbh->do("UPDATE locations SET group_id=?,iplist=?,description=?,comments=? WHERE location=?",
3109 undef, ($grp, $iplist, $shdesc, $comments, $loc) );
3110 _log($dbh, entry => $okmsg);
3111 $dbh->commit;
3112 };
3113 if ($@) {
3114 my $msg = $@;
3115 eval { $dbh->rollback; };
3116 if ($config{log_failures}) {
3117 $shdesc = $loc if !$shdesc;
3118 _log($dbh, (entry => "Failed updating location ($shdesc, '$iplist'): $msg"));
3119 $dbh->commit;
3120 }
3121 return ('FAIL',$msg);
3122 }
3123
3124 return ('OK',$okmsg);
3125} # end updateLoc()
3126
3127
3128## DNSDB::delLoc()
3129sub delLoc {
3130 my $dbh = shift;
3131 my $loc = shift;
3132
3133 # Allow transactions, and raise an exception on errors so we can catch it later.
3134 # Use local to make sure these get "reset" properly on exiting this block
3135 local $dbh->{AutoCommit} = 0;
3136 local $dbh->{RaiseError} = 1;
3137
3138 my $oldloc = getLoc($dbh, $loc);
3139 my $olddesc = ($oldloc->{description} ? $oldloc->{description} : $loc);
3140 my $okmsg = "Deleted location ($olddesc, '".$oldloc->{iplist}."')";
3141
3142 eval {
3143 # Check for records with this location first. Deleting a location without deleting records
3144 # tagged for that location will render them unpublished without other warning.
3145 my ($r) = $dbh->selectrow_array("SELECT record_id FROM records WHERE location=? LIMIT 1", undef, ($loc) );
3146 die "Records still exist in location $olddesc\n" if $r;
3147 $dbh->do("DELETE FROM locations WHERE location=?", undef, ($loc) );
3148 _log($dbh, entry => $okmsg);
3149 $dbh->commit;
3150 };
3151 if ($@) {
3152 my $msg = $@;
3153 eval { $dbh->rollback; };
3154 if ($config{log_failures}) {
3155 _log($dbh, (entry => "Failed to delete location ($olddesc, '$oldloc->{iplist}'): $msg"));
3156 $dbh->commit;
3157 }
3158 return ('FAIL', "Failed to delete location ($olddesc, '$oldloc->{iplist}'): $msg");
3159 }
3160
3161 return ('OK',$okmsg);
3162} # end delLoc()
3163
3164
3165## DNSDB::getLoc()
3166# Get details about a location/view
3167# Takes a database handle and location ID.
3168# Returns a reference to a hash containing the group ID, IP list, description, and comments/notes
3169sub getLoc {
3170 my $dbh = shift;
3171 my $loc = shift;
3172
3173 my $sth = $dbh->prepare("SELECT group_id,iplist,description,comments FROM locations WHERE location=?");
3174 $sth->execute($loc);
3175 return $sth->fetchrow_hashref();
3176} # end getLoc()
3177
3178
3179## DNSDB::getLocCount()
3180# Get count of locations/views
3181# Takes a database handle and hash containing at least the current group, and optionally:
3182# - a reference list of secondary groups
3183# - a filter string
3184# - a "Starts with" string
3185sub getLocCount {
3186 my $dbh = shift;
3187
3188 my %args = @_;
3189
3190 my @filterargs;
3191
3192 $args{startwith} = undef if $args{startwith} && $args{startwith} !~ /^(?:[a-z]|0-9)$/;
3193 push @filterargs, "^$args{startwith}" if $args{startwith};
3194 push @filterargs, $args{filter} if $args{filter};
3195
3196
3197 my $sql = "SELECT count(*) FROM locations ".
3198 "WHERE group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
3199 ($args{startwith} ? " AND description ~* ?" : '').
3200 ($args{filter} ? " AND description ~* ?" : '');
3201 my ($count) = $dbh->selectrow_array($sql, undef, (@filterargs) );
3202 $errstr = $dbh->errstr if !$count;
3203 return $count;
3204} # end getLocCount()
3205
3206
3207## DNSDB::getLocList()
3208sub getLocList {
3209 my $dbh = shift;
3210
3211 my %args = @_;
3212
3213 my @filterargs;
3214
3215 $args{startwith} = undef if $args{startwith} && $args{startwith} !~ /^(?:[a-z]|0-9)$/;
3216 push @filterargs, "^$args{startwith}" if $args{startwith};
3217 push @filterargs, $args{filter} if $args{filter};
3218
3219 # better to request sorts on "simple" names, but it means we need to map it to real columns
3220# my %sortmap = (user => 'u.username', type => 'u.type', group => 'g.group_name', status => 'u.status',
3221# fname => 'fname');
3222# $args{sortby} = $sortmap{$args{sortby}};
3223
3224 # protection against bad or missing arguments
3225 $args{sortorder} = 'ASC' if !$args{sortorder};
3226 $args{sortby} = 'l.description' if !$args{sortby};
3227 $args{offset} = 0 if !$args{offset} || $args{offset} !~ /^(?:all|\d+)$/;
3228
3229 my $sql = "SELECT l.location, l.description, l.iplist, g.group_name ".
3230 "FROM locations l ".
3231 "INNER JOIN groups g ON l.group_id=g.group_id ".
3232 "WHERE l.group_id IN ($args{curgroup}".($args{childlist} ? ",$args{childlist}" : '').")".
3233 ($args{startwith} ? " AND l.description ~* ?" : '').
3234 ($args{filter} ? " AND l.description ~* ?" : '').
3235 " ORDER BY $args{sortby} $args{sortorder} ".
3236 ($args{offset} eq 'all' ? '' : " LIMIT $config{perpage} OFFSET ".$args{offset}*$config{perpage});
3237 my $ulist = $dbh->selectall_arrayref($sql, { Slice => {} }, (@filterargs) );
3238 $errstr = $dbh->errstr if !$ulist;
3239 return $ulist;
3240} # end getLocList()
3241
3242
3243## DNSDB::getLocDropdown()
3244# Get a list of location names for use in a dropdown menu.
3245# Takes a database handle, current group, and optional "tag this as selected" flag.
3246# Returns a reference to a list of hashrefs suitable to feeding to HTML::Template
3247sub getLocDropdown {
3248 my $dbh = shift;
3249 my $grp = shift;
3250 my $sel = shift || '';
3251
3252 my $sth = $dbh->prepare(qq(
3253 SELECT description,location FROM locations
3254 WHERE group_id=?
3255 ORDER BY description
3256 ) );
3257 $sth->execute($grp);
3258
3259 my @loclist;
3260 push @loclist, { locname => "(Default/All)", loc => '', selected => ($sel ? 0 : ($sel eq '' ? 1 : 0)) };
3261 while (my ($locname, $loc) = $sth->fetchrow_array) {
3262 my %row = (
3263 locname => $locname,
3264 loc => $loc,
3265 selected => ($sel eq $loc ? 1 : 0)
3266 );
3267 push @loclist, \%row;
3268 }
3269 return \@loclist;
3270} # end getLocDropdown()
3271
3272
3273## DNSDB::getSOA()
3274# Return all suitable fields from an SOA record in separate elements of a hash
3275# Takes a database handle, default/live flag, domain/reverse flag, and parent ID
3276sub getSOA {
3277 $errstr = '';
3278 my $dbh = shift;
3279 my $def = shift;
3280 my $rev = shift;
3281 my $id = shift;
3282
3283 # (ab)use distance and weight columns to store SOA data? can't for default_rev_records...
3284 # - should really attach serial to the zone parent somewhere
3285
3286 my $sql = "SELECT record_id,host,val,ttl from "._rectable($def,$rev).
3287 " WHERE "._recparent($def,$rev)." = ? AND type=$reverse_typemap{SOA}";
3288 my $ret = $dbh->selectrow_hashref($sql, undef, ($id) );
3289 return if !$ret;
3290##fixme: stick a flag somewhere if the record doesn't exist. by the API, this is an impossible case, but...
3291
3292 ($ret->{contact},$ret->{prins}) = split /:/, $ret->{host};
3293 delete $ret->{host};
3294 ($ret->{refresh},$ret->{retry},$ret->{expire},$ret->{minttl}) = split /:/, $ret->{val};
3295 delete $ret->{val};
3296
3297 return $ret;
3298} # end getSOA()
3299
3300
3301## DNSDB::updateSOA()
3302# Update the specified SOA record
3303# Takes a database handle, default/live flag, forward/reverse flag, and SOA data hash
3304# Returns a two-element list with a result code and message
3305sub updateSOA {
3306 my $dbh = shift;
3307 my $defrec = shift;
3308 my $revrec = shift;
3309
3310 my %soa = @_;
3311
3312 my $oldsoa = getSOA($dbh, $defrec, $revrec, $soa{id});
3313
3314 my $msg;
3315 my %logdata;
3316 if ($defrec eq 'n') {
3317 $logdata{domain_id} = $soa{id} if $revrec eq 'n';
3318 $logdata{rdns_id} = $soa{id} if $revrec eq 'y';
3319 $logdata{group_id} = parentID($dbh, (id => $soa{id}, revrec => $revrec,
3320 type => ($revrec eq 'n' ? 'domain' : 'revzone') ) );
3321 } else {
3322 $logdata{group_id} = $soa{id};
3323 }
3324 my $parname = ($defrec eq 'y' ? groupName($dbh, $soa{id}) :
3325 ($revrec eq 'n' ? domainName($dbh, $soa{id}) : revName($dbh, $soa{id})) );
3326
3327 # Allow transactions, and raise an exception on errors so we can catch it later.
3328 # Use local to make sure these get "reset" properly on exiting this block
3329 local $dbh->{AutoCommit} = 0;
3330 local $dbh->{RaiseError} = 1;
3331
3332 eval {
3333 my $sql = "UPDATE "._rectable($defrec, $revrec)." SET host=?, val=?, ttl=? WHERE record_id=? AND type=6";
3334 $dbh->do($sql, undef, ("$soa{contact}:$soa{prins}", "$soa{refresh}:$soa{retry}:$soa{expire}:$soa{minttl}",
3335 $soa{ttl}, $oldsoa->{record_id}) );
3336 $msg = "Updated ".($defrec eq 'y' ? ($revrec eq 'y' ? 'default reverse ' : 'default ') : '').
3337 "SOA for $parname: ".
3338 "(ns $oldsoa->{prins}, contact $oldsoa->{contact}, refresh $oldsoa->{refresh},".
3339 " retry $oldsoa->{retry}, expire $oldsoa->{expire}, minTTL $oldsoa->{minttl}, TTL $oldsoa->{ttl}) to ".
3340 "(ns $soa{prins}, contact $soa{contact}, refresh $soa{refresh},".
3341 " retry $soa{retry}, expire $soa{expire}, minTTL $soa{minttl}, TTL $soa{ttl})";
3342
3343 $logdata{entry} = $msg;
3344 _log($dbh, %logdata);
3345
3346 $dbh->commit;
3347 };
3348 if ($@) {
3349 $msg = $@;
3350 eval { $dbh->rollback; };
3351 $logdata{entry} = "Error updating ".($defrec eq 'y' ? ($revrec eq 'y' ? 'default reverse zone ' : 'default ') : '').
3352 "SOA record for $parname: $msg";
3353 if ($config{log_failures}) {
3354 _log($dbh, %logdata);
3355 $dbh->commit;
3356 }
3357 return ('FAIL', $logdata{entry});
3358 } else {
3359 return ('OK', $msg);
3360 }
3361} # end updateSOA()
3362
3363
3364## DNSDB::getRecLine()
3365# Return all data fields for a zone record in separate elements of a hash
3366# Takes a database handle, default/live flag, forward/reverse flag, and record ID
3367sub getRecLine {
3368 $errstr = '';
3369 my $dbh = shift;
3370 my $defrec = shift;
3371 my $revrec = shift;
3372 my $id = shift;
3373
3374 my $sql = "SELECT record_id,host,type,val,ttl".
3375 ($defrec eq 'n' ? ',location' : '').
3376 ($revrec eq 'n' ? ',distance,weight,port' : '').
3377 (($defrec eq 'y') ? ',group_id FROM ' : ',domain_id,rdns_id FROM ').
3378 _rectable($defrec,$revrec)." WHERE record_id=?";
3379 my $ret = $dbh->selectrow_hashref($sql, undef, ($id) );
3380
3381 if ($dbh->err) {
3382 $errstr = $DBI::errstr;
3383 return undef;
3384 }
3385
3386 if (!$ret) {
3387 $errstr = "No such record";
3388 return undef;
3389 }
3390
3391 # explicitly set a parent id
3392 if ($defrec eq 'y') {
3393 $ret->{parid} = $ret->{group_id};
3394 } else {
3395 $ret->{parid} = (($revrec eq 'n') ? $ret->{domain_id} : $ret->{rdns_id});
3396 # and a secondary if we have a custom type that lives in both a forward and reverse zone
3397 $ret->{secid} = (($revrec eq 'y') ? $ret->{domain_id} : $ret->{rdns_id}) if $ret->{type} > 65279;
3398 }
3399 $ret->{address} = $ret->{val}; # because.
3400
3401 return $ret;
3402}
3403
3404
3405##fixme: should use above (getRecLine()) to get lines for below?
3406## DNSDB::getDomRecs()
3407# Return records for a domain
3408# Takes a database handle, default/live flag, group/domain ID, start,
3409# number of records, sort field, and sort order
3410# Returns a reference to an array of hashes
3411sub getDomRecs {
3412 $errstr = '';
3413 my $dbh = shift;
3414
3415 my %args = @_;
3416
3417 my @filterargs;
3418
3419 push @filterargs, $args{filter} if $args{filter};
3420
3421 # protection against bad or missing arguments
3422 $args{sortorder} = 'ASC' if !$args{sortorder};
3423 $args{sortby} = 'host' if !$args{sortby} && $args{revrec} eq 'n'; # default sort by host on domain record list
3424 $args{sortby} = 'val' if !$args{sortby} && $args{revrec} eq 'y'; # default sort by IP on revzone record list
3425 $args{offset} = 0 if !$args{offset} || $args{offset} !~ /^(?:all|\d+)$/;
3426
3427 # sort reverse zones on IP, correctly
3428 # do other fiddling with $args{sortby} while we're at it.
3429 # whee! multisort means just passing comma-separated fields in sortby!
3430 my $newsort = '';
3431 foreach my $sf (split /,/, $args{sortby}) {
3432 $sf = "r.$sf";
3433 $sf =~ s/r\.val/CAST (r.val AS inet)/
3434 if $args{revrec} eq 'y' && $args{defrec} eq 'n';
3435 $sf =~ s/r\.type/t.alphaorder/;
3436 $newsort .= ",$sf";
3437 }
3438 $newsort =~ s/^,//;
3439
3440 my $sql = "SELECT r.record_id,r.host,r.type,r.val,r.ttl";
3441 $sql .= ",l.description AS locname" if $args{defrec} eq 'n';
3442 $sql .= ",r.distance,r.weight,r.port" if $args{revrec} eq 'n';
3443 $sql .= " FROM "._rectable($args{defrec},$args{revrec})." r ";
3444 $sql .= "INNER JOIN rectypes t ON r.type=t.val "; # for sorting by type alphabetically
3445 $sql .= "LEFT JOIN locations l ON r.location=l.location " if $args{defrec} eq 'n';
3446 $sql .= "WHERE "._recparent($args{defrec},$args{revrec})." = ?";
3447 $sql .= " AND NOT r.type=$reverse_typemap{SOA}";
3448 $sql .= " AND (r.host ~* ? OR r.val ~* ?)" if $args{filter};
3449 $sql .= " ORDER BY $newsort $args{sortorder}";
3450 # ensure consistent ordering by sorting on record_id too
3451 $sql .= ", record_id $args{sortorder}";
3452 $sql .= ($args{offset} eq 'all' ? '' : " LIMIT $config{perpage} OFFSET ".$args{offset}*$config{perpage});
3453
3454 my @bindvars = ($args{id});
3455 push @bindvars, ($args{filter},$args{filter}) if $args{filter};
3456
3457 my $ret = $dbh->selectall_arrayref($sql, { Slice => {} }, (@bindvars) );
3458 return $ret;
3459} # end getDomRecs()
3460
3461
3462## DNSDB::getRecCount()
3463# Return count of non-SOA records in zone (or default records in a group)
3464# Takes a database handle, default/live flag, reverse/forward flag, group/domain ID,
3465# and optional filtering modifier
3466# Returns the count
3467sub getRecCount {
3468 my $dbh = shift;
3469 my $defrec = shift;
3470 my $revrec = shift;
3471 my $id = shift;
3472 my $filter = shift || '';
3473
3474 # keep the nasties down, since we can't ?-sub this bit. :/
3475 # note this is chars allowed in DNS hostnames
3476 $filter =~ s/[^a-zA-Z0-9_.:-]//g;
3477
3478 my @bindvars = ($id);
3479 push @bindvars, $filter if $filter;
3480 my $sql = "SELECT count(*) FROM ".
3481 _rectable($defrec,$revrec).
3482 " WHERE "._recparent($defrec,$revrec)."=? ".
3483 "AND NOT type=$reverse_typemap{SOA}".
3484 ($filter ? " AND host ~* ?" : '');
3485 my ($count) = $dbh->selectrow_array($sql, undef, (@bindvars) );
3486
3487 return $count;
3488
3489} # end getRecCount()
3490
3491
3492## DNSDB::addRec()
3493# Add a new record to a domain or a group's default records
3494# Takes a database handle, default/live flag, group/domain ID,
3495# host, type, value, and TTL
3496# Some types require additional detail: "distance" for MX and SRV,
3497# and weight/port for SRV
3498# Returns a status code and detail message in case of error
3499##fixme: pass a hash with the record data, not a series of separate values
3500sub addRec {
3501 $errstr = '';
3502 my $dbh = shift;
3503 my $defrec = shift;
3504 my $revrec = shift;
3505 my $id = shift; # parent (group_id for defrecs, rdns_id for reverse records,
3506 # domain_id for domain records)
3507
3508 my $host = shift;
3509 my $rectype = shift; # reference so we can coerce it if "+"-types can't find both zones
3510 my $val = shift;
3511 my $ttl = shift;
3512 my $location = shift;
3513 $location = '' if !$location;
3514
3515 # Spaces are evil.
3516 $$host =~ s/^\s+//;
3517 $$host =~ s/\s+$//;
3518 if ($typemap{$$rectype} ne 'TXT') {
3519 # Leading or trailng spaces could be legit in TXT records.
3520 $$val =~ s/^\s+//;
3521 $$val =~ s/\s+$//;
3522 }
3523
3524 # prep for validation
3525 my $addr = NetAddr::IP->new($$val);
3526 $$host =~ s/\.+$//; # FQDNs ending in . are an internal detail, and really shouldn't be exposed in the UI.
3527
3528 my $domid = 0;
3529 my $revid = 0;
3530
3531 my $retcode = 'OK'; # assume everything will go OK
3532 my $retmsg = '';
3533
3534 # do simple validation first
3535 return ('FAIL', "TTL must be numeric") unless $ttl =~ /^\d+$/;
3536
3537 # Quick check on hostname parts. Note the regex is more forgiving than the error message;
3538 # domain names technically are case-insensitive, and we use printf-like % codes for a couple
3539 # of types. Other things may also be added to validate default records of several flavours.
3540 return ('FAIL', "Hostnames may not contain anything other than (0-9 a-z . _)")
3541 if $defrec eq 'n' && ($revrec eq 'y' ? $$rectype != $reverse_typemap{TXT} : 1) &&
3542 $$host !~ /^[0-9a-z_%.-]+$/i;
3543
3544 # Collect these even if we're only doing a simple A record so we can call *any* validation sub
3545 my $dist = shift;
3546 my $weight = shift;
3547 my $port = shift;
3548
3549 my $fields;
3550 my @vallist;
3551
3552 # Call the validation sub for the type requested.
3553 ($retcode,$retmsg) = $validators{$$rectype}($dbh, (defrec => $defrec, revrec => $revrec, id => $id,
3554 host => $host, rectype => $rectype, val => $val, addr => $addr,
3555 dist => \$dist, port => \$port, weight => \$weight,
3556 fields => \$fields, vallist => \@vallist) );
3557
3558 return ($retcode,$retmsg) if $retcode eq 'FAIL';
3559
3560 # Set up database fields and bind parameters
3561 $fields .= "host,type,val,ttl,location,"._recparent($defrec,$revrec);
3562 push @vallist, ($$host,$$rectype,$$val,$ttl,$location,$id);
3563 my $vallen = '?'.(',?'x$#vallist);
3564
3565 # Put together the success log entry. We have to use this horrible kludge
3566 # because domain_id and rdns_id may or may not be present, and if they are,
3567 # they're not at a guaranteed consistent index in the array. wheee!
3568 my %logdata;
3569 my @ftmp = split /,/, $fields;
3570 for (my $i=0; $i <= $#vallist; $i++) {
3571 $logdata{domain_id} = $vallist[$i] if $ftmp[$i] eq 'domain_id';
3572 $logdata{rdns_id} = $vallist[$i] if $ftmp[$i] eq 'rdns_id';
3573 }
3574 $logdata{group_id} = $id if $defrec eq 'y';
3575 $logdata{group_id} = parentID($dbh,
3576 (id => $id, type => ($revrec eq 'n' ? 'domain' : 'revzone'), revrec => $revrec) )
3577 if $defrec eq 'n';
3578 $logdata{entry} = "Added ".($defrec eq 'y' ? 'default record' : 'record');
3579 # NS records for revzones get special treatment
3580 if ($revrec eq 'y' && $$rectype == 2) {
3581 $logdata{entry} .= " '$$val $typemap{$$rectype} $$host";
3582 } else {
3583 $logdata{entry} .= " '$$host $typemap{$$rectype} $$val";
3584 }
3585
3586 $logdata{entry} .= " [distance $dist]" if $typemap{$$rectype} eq 'MX';
3587 $logdata{entry} .= " [priority $dist] [weight $weight] [port $port]"
3588 if $typemap{$$rectype} eq 'SRV';
3589 $logdata{entry} .= "', TTL $ttl";
3590 $logdata{entry} .= ", location ".getLoc($dbh, $location)->{description} if $location;
3591
3592 # Allow transactions, and raise an exception on errors so we can catch it later.
3593 # Use local to make sure these get "reset" properly on exiting this block
3594 local $dbh->{AutoCommit} = 0;
3595 local $dbh->{RaiseError} = 1;
3596
3597 eval {
3598 $dbh->do("INSERT INTO "._rectable($defrec, $revrec)." ($fields) VALUES ($vallen)",
3599 undef, @vallist);
3600 _log($dbh, %logdata);
3601 $dbh->commit;
3602 };
3603 if ($@) {
3604 my $msg = $@;
3605 eval { $dbh->rollback; };
3606 if ($config{log_failures}) {
3607 $logdata{entry} = "Failed adding ".($defrec eq 'y' ? 'default ' : '').
3608 "record '$$host $typemap{$$rectype} $$val', TTL $ttl ($msg)";
3609 _log($dbh, %logdata);
3610 $dbh->commit;
3611 }
3612 return ('FAIL',$msg);
3613 }
3614
3615 $resultstr = $logdata{entry};
3616 return ($retcode, $retmsg);
3617
3618} # end addRec()
3619
3620
3621## DNSDB::updateRec()
3622# Update a record
3623# Takes a database handle, default and reverse flags, record ID, immediate parent ID, and new record data.
3624# Returns a status code and message
3625sub updateRec {
3626 $errstr = '';
3627
3628 my $dbh = shift;
3629 my $defrec = shift;
3630 my $revrec = shift;
3631 my $id = shift;
3632 my $parid = shift; # immediate parent entity that we're descending from to update the record
3633
3634 # all records have these
3635 my $host = shift;
3636 my $hostbk = $$host; # Keep a backup copy of the original, so we can WARN if the update mangles the domain
3637 my $rectype = shift;
3638 my $val = shift;
3639 my $ttl = shift;
3640 my $location = shift; # may be empty/null/undef depending on caller
3641 $location = '' if !$location;
3642
3643 # Spaces are evil.
3644 $$host =~ s/^\s+//;
3645 $$host =~ s/\s+$//;
3646 if ($typemap{$$rectype} ne 'TXT') {
3647 # Leading or trailng spaces could be legit in TXT records.
3648 $$val =~ s/^\s+//;
3649 $$val =~ s/\s+$//;
3650 }
3651
3652 # prep for validation
3653 my $addr = NetAddr::IP->new($$val);
3654 $$host =~ s/\.+$//; # FQDNs ending in . are an internal detail, and really shouldn't be exposed in the UI.
3655
3656 my $domid = 0;
3657 my $revid = 0;
3658
3659 my $retcode = 'OK'; # assume everything will go OK
3660 my $retmsg = '';
3661
3662 # do simple validation first
3663 return ('FAIL', "TTL must be numeric") unless $ttl =~ /^\d+$/;
3664
3665 # Quick check on hostname parts. Note the regex is more forgiving than the error message;
3666 # domain names technically are case-insensitive, and we use printf-like % codes for a couple
3667 # of types. Other things may also be added to validate default records of several flavours.
3668 return ('FAIL', "Hostnames may not contain anything other than (0-9 a-z - . _)")
3669 if $defrec eq 'n' && ($revrec eq 'y' ? $$rectype != $reverse_typemap{TXT} : 1) &&
3670 $$host !~ /^[0-9a-z_%.-]+$/i;
3671
3672 # only MX and SRV will use these
3673 my $dist = shift || 0;
3674 my $weight = shift || 0;
3675 my $port = shift || 0;
3676
3677 my $fields;
3678 my @vallist;
3679
3680 # get old record data so we have the right parent ID
3681 # and for logging (eventually)
3682 my $oldrec = getRecLine($dbh, $defrec, $revrec, $id);
3683
3684 # Call the validation sub for the type requested.
3685 # Note the ID to pass here is the *parent*, not the record
3686 ($retcode,$retmsg) = $validators{$$rectype}($dbh, (defrec => $defrec, revrec => $revrec,
3687 id => ($defrec eq 'y' ? $oldrec->{group_id} : ($revrec eq 'n' ? $oldrec->{domain_id} : $oldrec->{rdns_id})),
3688 host => $host, rectype => $rectype, val => $val, addr => $addr,
3689 dist => \$dist, port => \$port, weight => \$weight,
3690 fields => \$fields, vallist => \@vallist,
3691 update => $id) );
3692
3693 return ($retcode,$retmsg) if $retcode eq 'FAIL';
3694
3695 # Set up database fields and bind parameters. Note only the optional fields
3696 # (distance, weight, port, secondary parent ID) are added in the validation call above
3697 $fields .= "host,type,val,ttl,"._recparent($defrec,$revrec);
3698 push @vallist, ($$host,$$rectype,$$val,$ttl,
3699 ($defrec eq 'y' ? $oldrec->{group_id} : ($revrec eq 'n' ? $oldrec->{domain_id} : $oldrec->{rdns_id})) );
3700
3701 # locations are not for default records, silly coder!
3702 if ($defrec eq 'n') {
3703 $fields .= ",location";
3704 push @vallist, $location;
3705 }
3706
3707 # hack hack PTHUI
3708 # need to forcibly make sure we disassociate a record with a parent it's no longer related to.
3709 # eg, PTR records may not have a domain parent, or A/AAAA records may not have a revzone parent.
3710 # mainly needed for crossover types that got coerced down to "standard" types
3711 if ($defrec eq 'n') {
3712 if ($$rectype == $reverse_typemap{PTR}) {
3713 $fields .= ",domain_id";
3714 push @vallist, 0;
3715 }
3716 if ($$rectype == $reverse_typemap{A} || $$rectype == $reverse_typemap{AAAA}) {
3717 $fields .= ",rdns_id";
3718 push @vallist, 0;
3719 }
3720 }
3721 # fix fat-finger-originated record type changes
3722 if ($$rectype == 65285) {
3723 $fields .= ",rdns_id" if $revrec eq 'n';
3724 $fields .= ",domain_id" if $revrec eq 'y';
3725 push @vallist, 0;
3726 }
3727 if ($defrec eq 'n') {
3728 $domid = $parid if $revrec eq 'n';
3729 $revid = $parid if $revrec eq 'y';
3730 }
3731
3732 # Put together the success log entry. Horrible kludge from addRec() copied as-is since
3733 # we don't know whether the passed arguments or retrieved values for domain_id and rdns_id
3734 # will be maintained (due to "not-in-zone" validation changes)
3735 my %logdata;
3736 $logdata{domain_id} = $domid;
3737 $logdata{rdns_id} = $revid;
3738 my @ftmp = split /,/, $fields;
3739 for (my $i=0; $i <= $#vallist; $i++) {
3740 $logdata{domain_id} = $vallist[$i] if $ftmp[$i] eq 'domain_id';
3741 $logdata{rdns_id} = $vallist[$i] if $ftmp[$i] eq 'rdns_id';
3742 }
3743 $logdata{group_id} = $parid if $defrec eq 'y';
3744 $logdata{group_id} = parentID($dbh,
3745 (id => $parid, type => ($revrec eq 'n' ? 'domain' : 'revzone'), revrec => $revrec) )
3746 if $defrec eq 'n';
3747 $logdata{entry} = "Updated ".($defrec eq 'y' ? 'default record' : 'record')." from\n";
3748 # NS records for revzones get special treatment
3749 if ($revrec eq 'y' && $$rectype == 2) {
3750 $logdata{entry} .= " '$oldrec->{val} $typemap{$oldrec->{type}} $oldrec->{host}";
3751 } else {
3752 $logdata{entry} .= " '$oldrec->{host} $typemap{$oldrec->{type}} $oldrec->{val}";
3753 }
3754 $logdata{entry} .= " [distance $oldrec->{distance}]" if $typemap{$oldrec->{type}} eq 'MX';
3755 $logdata{entry} .= " [priority $oldrec->{distance}] [weight $oldrec->{weight}] [port $oldrec->{port}]"
3756 if $typemap{$oldrec->{type}} eq 'SRV';
3757 $logdata{entry} .= "', TTL $oldrec->{ttl}";
3758 $logdata{entry} .= ", location ".getLoc($dbh, $oldrec->{location})->{description} if $oldrec->{location};
3759 $logdata{entry} .= "\nto\n";
3760 # More NS special
3761 if ($revrec eq 'y' && $$rectype == 2) {
3762 $logdata{entry} .= "'$$val $typemap{$$rectype} $$host";
3763 } else {
3764 $logdata{entry} .= "'$$host $typemap{$$rectype} $$val";
3765 }
3766 $logdata{entry} .= " [distance $dist]" if $typemap{$$rectype} eq 'MX';
3767 $logdata{entry} .= " [priority $dist] [weight $weight] [port $port]" if $typemap{$$rectype} eq 'SRV';
3768 $logdata{entry} .= "', TTL $ttl";
3769 $logdata{entry} .= ", location ".getLoc($dbh, $location)->{description} if $location;
3770
3771 local $dbh->{AutoCommit} = 0;
3772 local $dbh->{RaiseError} = 1;
3773
3774 # Fiddle the field list into something suitable for updates
3775 $fields =~ s/,/=?,/g;
3776 $fields .= "=?";
3777
3778 eval {
3779 $dbh->do("UPDATE "._rectable($defrec,$revrec)." SET $fields WHERE record_id=?", undef, (@vallist, $id) );
3780 _log($dbh, %logdata);
3781 $dbh->commit;
3782 };
3783 if ($@) {
3784 my $msg = $@;
3785 eval { $dbh->rollback; };
3786 if ($config{log_failures}) {
3787 $logdata{entry} = "Failed updating ".($defrec eq 'y' ? 'default ' : '').
3788 "record '$oldrec->{host} $typemap{$oldrec->{type}} $oldrec->{val}', TTL $oldrec->{ttl} ($msg)";
3789 _log($dbh, %logdata);
3790 $dbh->commit;
3791 }
3792 return ('FAIL', $msg);
3793 }
3794
3795 $resultstr = $logdata{entry};
3796 return ($retcode, $retmsg);
3797} # end updateRec()
3798
3799
3800## DNSDB::delRec()
3801# Delete a record.
3802sub delRec {
3803 $errstr = '';
3804 my $dbh = shift;
3805 my $defrec = shift;
3806 my $revrec = shift;
3807 my $id = shift;
3808
3809 my $oldrec = getRecLine($dbh, $defrec, $revrec, $id);
3810
3811 # Allow transactions, and raise an exception on errors so we can catch it later.
3812 # Use local to make sure these get "reset" properly on exiting this block
3813 local $dbh->{AutoCommit} = 0;
3814 local $dbh->{RaiseError} = 1;
3815
3816 # Put together the log entry
3817 my %logdata;
3818 $logdata{domain_id} = $oldrec->{domain_id};
3819 $logdata{rdns_id} = $oldrec->{rdns_id};
3820 $logdata{group_id} = $oldrec->{group_id} if $defrec eq 'y';
3821 $logdata{group_id} = parentID($dbh,
3822 (id => $oldrec->{domain_id}, type => ($revrec eq 'n' ? 'domain' : 'revzone'), revrec => $revrec) )
3823 if $defrec eq 'n';
3824 $logdata{entry} = "Deleted ".($defrec eq 'y' ? 'default record ' : 'record ').
3825 "'$oldrec->{host} $typemap{$oldrec->{type}} $oldrec->{val}";
3826 $logdata{entry} .= " [distance $oldrec->{distance}]" if $typemap{$oldrec->{type}} eq 'MX';
3827 $logdata{entry} .= " [priority $oldrec->{distance}] [weight $oldrec->{weight}] [port $oldrec->{port}]"
3828 if $typemap{$oldrec->{type}} eq 'SRV';
3829 $logdata{entry} .= "', TTL $oldrec->{ttl}";
3830 $logdata{entry} .= ", location ".getLoc($dbh, $oldrec->{location})->{description} if $oldrec->{location};
3831
3832 eval {
3833 my $sth = $dbh->do("DELETE FROM "._rectable($defrec,$revrec)." WHERE record_id=?", undef, ($id));
3834 _log($dbh, %logdata);
3835 $dbh->commit;
3836 };
3837 if ($@) {
3838 my $msg = $@;
3839 eval { $dbh->rollback; };
3840 if ($config{log_failures}) {
3841 $logdata{entry} = "Error deleting ".($defrec eq 'y' ? 'default record' : 'record').
3842 " '$oldrec->{host} $typemap{$oldrec->{type}} $oldrec->{val}', TTL $oldrec->{ttl} ($msg)";
3843 _log($dbh, %logdata);
3844 $dbh->commit;
3845 }
3846 return ('FAIL', $msg);
3847 }
3848
3849 return ('OK',$logdata{entry});
3850} # end delRec()
3851
3852
3853## DNSDB::getLogCount()
3854# Get a count of log entries
3855# Takes a database handle and a hash containing at least:
3856# - Entity ID and entity type as the primary log "slice"
3857sub getLogCount {
3858 my $dbh = shift;
3859
3860 my %args = @_;
3861
3862 my @filterargs;
3863##fixme: which fields do we want to filter on?
3864# push @filterargs,
3865
3866 $errstr = 'Missing primary parent ID and/or type';
3867 # fail early if we don't have a "prime" ID to look for log entries for
3868 return if !$args{id};
3869
3870 # or if the prime id type is missing or invalid
3871 return if !$args{logtype};
3872 $args{logtype} = 'revzone' if $args{logtype} eq 'rdns'; # hack pthui
3873 $args{logtype} = 'domain' if $args{logtype} eq 'dom'; # hack pthui
3874 return if !grep /^$args{logtype}$/, ('group', 'domain', 'revzone', 'user');
3875
3876 $args{logtype} = 'revzone' if $args{logtype} eq 'rdns'; # hack pthui
3877
3878 my $sql = "SELECT count(*) FROM log ".
3879 "WHERE $id_col{$args{logtype}}=?".
3880 ($args{filter} ? " AND entry ~* ?" : '');
3881 my ($count) = $dbh->selectrow_array($sql, undef, ($args{id}, @filterargs) );
3882 $errstr = $dbh->errstr if !$count;
3883 return $count;
3884} # end getLogCount()
3885
3886
3887## DNSDB::getLogEntries()
3888# Get a list of log entries
3889# Takes arguments as with getLogCount() above, plus optional:
3890# - sort field
3891# - sort order
3892# - offset for pagination
3893sub getLogEntries {
3894 my $dbh = shift;
3895
3896 my %args = @_;
3897
3898 my @filterargs;
3899
3900 # fail early if we don't have a "prime" ID to look for log entries for
3901 return if !$args{id};
3902
3903 # or if the prime id type is missing or invalid
3904 return if !$args{logtype};
3905 $args{logtype} = 'revzone' if $args{logtype} eq 'rdns'; # hack pthui
3906 $args{logtype} = 'domain' if $args{logtype} eq 'dom'; # hack pthui
3907 return if !grep /^$args{logtype}$/, ('group', 'domain', 'revzone', 'user');
3908
3909 # Sorting defaults
3910 $args{sortby} = 'stamp' if !$args{sortby};
3911 $args{sortorder} = 'DESC' if !$args{sortorder};
3912 $args{offset} = 0 if !$args{offset} || $args{offset} !~ /^(?:all|\d+)$/;
3913
3914 my %sortmap = (fname => 'name', username => 'email', entry => 'entry', stamp => 'stamp');
3915 $args{sortby} = $sortmap{$args{sortby}};
3916
3917 my $sql = "SELECT user_id AS userid, email AS useremail, name AS userfname, entry AS logentry, ".
3918 "date_trunc('second',stamp) AS logtime ".
3919 "FROM log ".
3920 "WHERE $id_col{$args{logtype}}=?".
3921 ($args{filter} ? " AND entry ~* ?" : '').
3922 " ORDER BY $args{sortby} $args{sortorder}, log_id $args{sortorder}".
3923 ($args{offset} eq 'all' ? '' : " LIMIT $config{perpage} OFFSET ".$args{offset}*$config{perpage});
3924 my $loglist = $dbh->selectall_arrayref($sql, { Slice => {} }, ($args{id}, @filterargs) );
3925 $errstr = $dbh->errstr if !$loglist;
3926 return $loglist;
3927} # end getLogEntries()
3928
3929
3930## IPDB::getRevPattern()
3931# Get the narrowest template pattern applicable to a passed CIDR address (may be a netblock or an IP)
3932sub getRevPattern {
3933 my $dbh = shift;
3934 my $cidr = shift;
3935 my $group = shift || 1; # just in case
3936
3937 my ($revpatt) = $dbh->selectrow_array("SELECT r.host FROM records r JOIN revzones z ON r.rdns_id=z.rdns_id ".
3938 "WHERE (r.type in (12,65280,65281,65282,65283,65284)) AND z.group_id=? AND CAST (r.val AS inet) >>= ? ".
3939 "ORDER BY CAST (r.val AS inet) DESC LIMIT 1", undef, ($group, $cidr) );
3940 return $revpatt;
3941} # end getRevPattern()
3942
3943
3944## DNSDB::getTypelist()
3945# Get a list of record types for various UI dropdowns
3946# Takes database handle, forward/reverse/lookup flag, and optional "tag as selected" indicator (defaults to A)
3947# Returns an arrayref to list of hashrefs perfect for HTML::Template
3948sub getTypelist {
3949 my $dbh = shift;
3950 my $recgroup = shift;
3951 my $type = shift || $reverse_typemap{A};
3952
3953 # also accepting $webvar{revrec}!
3954 $recgroup = 'f' if $recgroup eq 'n';
3955 $recgroup = 'r' if $recgroup eq 'y';
3956
3957 my $sql = "SELECT val,name FROM rectypes WHERE ";
3958 if ($recgroup eq 'r') {
3959 # reverse zone types
3960 $sql .= "stdflag=2 OR stdflag=3";
3961 } elsif ($recgroup eq 'l') {
3962 # DNS lookup types. Note we avoid our custom types >= 65280, since those are entirely internal.
3963 $sql .= "(stdflag=1 OR stdflag=2 OR stdflag=3) AND val < 65280";
3964 } else {
3965 # default; forward zone types. technically $type eq 'f' but not worth the error message.
3966 $sql .= "stdflag=1 OR stdflag=2";
3967 }
3968 $sql .= " ORDER BY listorder";
3969
3970 my $sth = $dbh->prepare($sql);
3971 $sth->execute;
3972 my @typelist;
3973 while (my ($rval,$rname) = $sth->fetchrow_array()) {
3974 my %row = ( recval => $rval, recname => $rname );
3975 $row{tselect} = 1 if $rval == $type;
3976 push @typelist, \%row;
3977 }
3978
3979 # Add SOA on lookups since it's not listed in other dropdowns.
3980 if ($recgroup eq 'l') {
3981 my %row = ( recval => $reverse_typemap{SOA}, recname => 'SOA' );
3982 $row{tselect} = 1 if $reverse_typemap{SOA} == $type;
3983 push @typelist, \%row;
3984 }
3985
3986 return \@typelist;
3987} # end getTypelist()
3988
3989
3990## DNSDB::parentID()
3991# Get ID of entity that is nearest parent to requested id
3992# Takes a database handle and a hash of entity ID, entity type, optional parent type flag
3993# (domain/reverse zone or group), and optional default/live and forward/reverse flags
3994# Returns the ID or undef on failure
3995sub parentID {
3996 my $dbh = shift;
3997
3998 my %args = @_;
3999
4000 # clean up the parent-type. Set it to group if not set; coerce revzone to domain for simpler logic
4001 $args{partype} = 'group' if !$args{partype};
4002 $args{partype} = 'domain' if $args{partype} eq 'revzone';
4003
4004 # clean up defrec and revrec. default to live record, forward zone
4005 $args{defrec} = 'n' if !$args{defrec};
4006 $args{revrec} = 'n' if !$args{revrec};
4007
4008 if ($par_type{$args{partype}} eq 'domain') {
4009 # only live records can have a domain/zone parent
4010 return unless ($args{type} eq 'record' && $args{defrec} eq 'n');
4011 my $result = $dbh->selectrow_hashref("SELECT ".($args{revrec} eq 'n' ? 'domain_id' : 'rdns_id').
4012 " FROM records WHERE record_id = ?",
4013 undef, ($args{id}) ) or return;
4014 return $result;
4015 } else {
4016 # snag some arguments that will either fall through or be overwritten to save some code duplication
4017 my $tmpid = $args{id};
4018 my $type = $args{type};
4019 if ($type eq 'record' && $args{defrec} eq 'n') {
4020 # Live records go through the records table first.
4021 ($tmpid) = $dbh->selectrow_array("SELECT ".($args{revrec} eq 'n' ? 'domain_id' : 'rdns_id').
4022 " FROM records WHERE record_id = ?",
4023 undef, ($args{id}) ) or return;
4024 $type = ($args{revrec} eq 'n' ? 'domain' : 'revzone');
4025 }
4026 my ($result) = $dbh->selectrow_array("SELECT $par_col{$type} FROM $par_tbl{$type} WHERE $id_col{$type} = ?",
4027 undef, ($tmpid) );
4028 return $result;
4029 }
4030# should be impossible to get here with even remotely sane arguments
4031 return;
4032} # end parentID()
4033
4034
4035## DNSDB::isParent()
4036# Returns true if $id1 is a parent of $id2, false otherwise
4037sub isParent {
4038 my $dbh = shift;
4039 my $id1 = shift;
4040 my $type1 = shift;
4041 my $id2 = shift;
4042 my $type2 = shift;
4043##todo: immediate, secondary, full (default)
4044
4045 # Return false on invalid types
4046 return 0 if !grep /^$type1$/, ('record','defrec','defrevrec','user','domain','revzone','group');
4047 return 0 if !grep /^$type2$/, ('record','defrec','defrevrec','user','domain','revzone','group');
4048
4049 # Return false on impossible relations
4050 return 0 if $type1 eq 'record'; # nothing may be a child of a record
4051 return 0 if $type1 eq 'defrec'; # nothing may be a child of a record
4052 return 0 if $type1 eq 'defrevrec'; # nothing may be a child of a record
4053 return 0 if $type1 eq 'user'; # nothing may be child of a user
4054 return 0 if $type1 eq 'domain' && $type2 ne 'record'; # domain may not be a parent of anything other than a record
4055 return 0 if $type1 eq 'revzone' && $type2 ne 'record';# reverse zone may not be a parent of anything other than a record
4056
4057 # ennnhhhh.... if we're passed an id of 0, it will never be found. usual
4058 # case would be the UI creating a new <thing>, and so we don't have an ID for
4059 # <thing> to look up yet. in that case the UI should check the parent as well.
4060 return 0 if $id1 == 0; # nothing can have a parent id of 0
4061 return 1 if $id2 == 0; # anything could have a child id of 0 (or "unknown")
4062
4063 # group 1 is the ultimate root parent
4064 return 1 if $type1 eq 'group' && $id1 == 1;
4065
4066 # groups are always (a) parent of themselves
4067 return 1 if $type1 eq 'group' && $type2 eq 'group' && $id1 == $id2;
4068
4069 my $id = $id2;
4070 my $type = $type2;
4071 my $foundparent = 0;
4072
4073 # Records are the only entity with two possible parents. We need to split the parent checks on
4074 # domain/rdns.
4075 if ($type eq 'record') {
4076 my ($dom,$rdns) = $dbh->selectrow_array("SELECT domain_id,rdns_id FROM records WHERE record_id=?",
4077 undef, ($id));
4078 # check immediate parent against request
4079 return 1 if $type1 eq 'domain' && $id1 == $dom;
4080 return 1 if $type1 eq 'revzone' && $id1 == $rdns;
4081 # if request is group, check *both* parents. Only check if the parent is nonzero though.
4082 return 1 if $dom && isParent($dbh, $id1, $type1, $dom, 'domain');
4083 return 1 if $rdns && isParent($dbh, $id1, $type1, $rdns, 'revzone');
4084 # exit here since we've executed the loop below by proxy in the above recursive calls.
4085 return 0;
4086 }
4087
4088# almost the same loop as getParents() above
4089 my $limiter = 0;
4090 while (1) {
4091 my $sql = "SELECT $par_col{$type} FROM $par_tbl{$type} WHERE $id_col{$type} = ?";
4092 my $result = $dbh->selectrow_hashref($sql,
4093 undef, ($id) );
4094 if (!$result) {
4095 $limiter++;
4096##fixme: how often will this happen on a live site? fail at max limiter <n>?
4097 warn "no results looking for $sql with id $id (depth $limiter)\n";
4098 last;
4099 }
4100 if ($result && $result->{$par_col{$type}} == $id1) {
4101 $foundparent = 1;
4102 last;
4103 } else {
4104##fixme: do we care about trying to return a "no such record/domain/user/group" error?
4105# should be impossible to create an inconsistent DB just with API calls.
4106 warn $dbh->errstr." $sql, $id" if $dbh->errstr;
4107 }
4108 # group 1 is its own parent. need this here more to break strange loops than for detecting a parent
4109 last if $result->{$par_col{$type}} == 1;
4110 $id = $result->{$par_col{$type}};
4111 $type = $par_type{$type};
4112 }
4113
4114 return $foundparent;
4115} # end isParent()
4116
4117
4118## DNSDB::zoneStatus()
4119# Returns and optionally sets a zone's status
4120# Takes a database handle, domain/revzone ID, forward/reverse flag, and optionally a status argument
4121# Returns status, or undef on errors.
4122sub zoneStatus {
4123 my $dbh = shift;
4124 my $id = shift;
4125 my $revrec = shift;
4126 my $newstatus = shift || 'mu';
4127
4128 return undef if $id !~ /^\d+$/;
4129
4130 # Allow transactions, and raise an exception on errors so we can catch it later.
4131 # Use local to make sure these get "reset" properly on exiting this block
4132 local $dbh->{AutoCommit} = 0;
4133 local $dbh->{RaiseError} = 1;
4134
4135 if ($newstatus ne 'mu') {
4136 # ooo, fun! let's see what we were passed for status
4137 eval {
4138 $newstatus = 0 if $newstatus eq 'domoff';
4139 $newstatus = 1 if $newstatus eq 'domon';
4140 $dbh->do("UPDATE ".($revrec eq 'n' ? 'domains' : 'revzones')." SET status=? WHERE ".
4141 ($revrec eq 'n' ? 'domain_id' : 'rdns_id')."=?", undef, ($newstatus,$id) );
4142
4143##fixme switch to more consise "Enabled <domain"/"Disabled <domain>" as with users?
4144 $resultstr = "Changed ".($revrec eq 'n' ? domainName($dbh, $id) : revName($dbh, $id)).
4145 " state to ".($newstatus ? 'active' : 'inactive');
4146
4147 my %loghash;
4148 $loghash{domain_id} = $id if $revrec eq 'n';
4149 $loghash{rdns_id} = $id if $revrec eq 'y';
4150 $loghash{group_id} = parentID($dbh,
4151 (id => $id, type => ($revrec eq 'n' ? 'domain' : 'revzone'), revrec => $revrec) );
4152 $loghash{entry} = $resultstr;
4153 _log($dbh, %loghash);
4154
4155 $dbh->commit;
4156 };
4157 if ($@) {
4158 my $msg = $@;
4159 eval { $dbh->rollback; };
4160 $resultstr = '';
4161 $errstr = $msg;
4162 return;
4163 }
4164 }
4165
4166 my ($status) = $dbh->selectrow_array("SELECT status FROM ".
4167 ($revrec eq 'n' ? "domains WHERE domain_id=?" : "revzones WHERE rdns_id=?"),
4168 undef, ($id) );
4169 return $status;
4170} # end zoneStatus()
4171
4172
4173## DNSDB::getZonesByCIDR()
4174# Get a list of zone names and IDs that records for a passed CIDR block are within.
4175sub getZonesByCIDR {
4176 my $dbh = shift;
4177 my %args = @_;
4178
4179 my $result = $dbh->selectall_arrayref("SELECT rdns_id,revnet FROM revzones WHERE revnet >>= ? OR revnet <<= ?",
4180 { Slice => {} }, ($args{cidr}, $args{cidr}) );
4181 return $result;
4182} # end getZonesByCIDR()
4183
4184
4185## DNSDB::importAXFR
4186# Import a domain via AXFR
4187# Takes AXFR host, domain to transfer, group to put the domain in,
4188# and optionally:
4189# - active/inactive state flag (defaults to active)
4190# - overwrite-SOA flag (defaults to off)
4191# - overwrite-NS flag (defaults to off, doesn't affect subdomain NS records)
4192# Returns a status code (OK, WARN, or FAIL) and message - message should be blank
4193# if status is OK, but WARN includes conditions that are not fatal but should
4194# really be reported.
4195sub importAXFR {
4196 my $dbh = shift;
4197 my $ifrom_in = shift;
4198 my $zone = shift;
4199 my $group = shift;
4200 my $status = shift;
4201 $status = (defined($status) ? $status : 0); # force sane semantics, and allow passing "null" (inactive) status
4202 my $rwsoa = shift || 0;
4203 my $rwns = shift || 0;
4204 my $newttl = shift;
4205 my $merge = shift || 0; # do we attempt to merge A/AAAA and PTR records whenever possible?
4206 # do we overload this with the fixme below?
4207##fixme: add mode to delete&replace, merge+overwrite, merge new?
4208
4209 my $nrecs = 0;
4210 my $soaflag = 0;
4211 my $nsflag = 0;
4212 my $warnmsg = '';
4213 my $ifrom;
4214
4215 my $rev = 'n';
4216 my $code = 'OK';
4217 my $msg = 'foobar?';
4218
4219 # choke on possible bad setting in ifrom
4220 # IPv4 and v6, and valid hostnames!
4221 ($ifrom) = ($ifrom_in =~ /^([0-9a-f\:.]+|[0-9a-z_.-]+)$/i);
4222 return ('FAIL', "Bad AXFR source host $ifrom")
4223 unless ($ifrom) = ($ifrom_in =~ /^([0-9a-f\:.]+|[0-9a-z_.-]+)$/i);
4224
4225 my $errmsg;
4226
4227 my $zone_id;
4228 my $domain_id = 0;
4229 my $rdns_id = 0;
4230 my $cidr;
4231
4232# magic happens! detect if we're importing a domain or a reverse zone
4233# while we're at it, figure out what the CIDR netblock is (if we got a .arpa)
4234# or what the formal .arpa zone is (if we got a CIDR netblock)
4235# Handles sub-octet v4 zones in the format specified in the Cricket Book, 2nd Ed, p217-218
4236
4237 if ($zone =~ m{(?:\.arpa\.?|/\d+)$}) {
4238 # we seem to have a reverse zone
4239 $rev = 'y';
4240
4241 if ($zone =~ /\.arpa\.?$/) {
4242 # we have a formal reverse zone. call _zone2cidr and get the CIDR block.
4243 ($code,$msg) = _zone2cidr($zone);
4244 return ($code, $msg) if $code eq 'FAIL';
4245 $cidr = $msg;
4246 } elsif ($zone =~ m|^[\d.]+/\d+$|) {
4247 # v4 revzone, CIDR netblock
4248 $cidr = NetAddr::IP->new($zone) or return ('FAIL',"$zone is not a valid CIDR block");
4249 $zone = _ZONE($cidr, 'ZONE.in-addr.arpa', 'r', '.');
4250 } elsif ($zone =~ m|^[a-fA-F\d:]+/\d+$|) {
4251 # v6 revzone, CIDR netblock
4252 $cidr = NetAddr::IP->new($zone) or return ('FAIL',"$zone is not a valid CIDR block");
4253 return ('FAIL', "$zone is not a nibble-aligned block") if $cidr->masklen % 4 != 0;
4254 $zone = _ZONE($cidr, 'ZONE.ip6.arpa', 'r', '.');
4255 } else {
4256 # there is. no. else!
4257 return ('FAIL', "Unknown zone name format");
4258 }
4259
4260 # quick check to start to see if we've already got one
4261
4262 ($zone_id) = $dbh->selectrow_array("SELECT rdns_id FROM revzones WHERE revnet=?",
4263 undef, ("$cidr"));
4264 $rdns_id = $zone_id;
4265 } else {
4266 # default to domain
4267 ($zone_id) = $dbh->selectrow_array("SELECT domain_id FROM domains WHERE lower(domain) = lower(?)",
4268 undef, ($zone));
4269 $domain_id = $zone_id;
4270 }
4271
4272 return ('FAIL', ($rev eq 'n' ? 'Domain' : 'Reverse zone')." already exists") if $zone_id;
4273
4274 # little local utility sub to swap $val and $host for revzone records.
4275 sub _revswap {
4276 my $rechost = shift;
4277 my $recdata = shift;
4278
4279 if ($rechost =~ /\.in-addr\.arpa\.?$/) {
4280 $rechost =~ s/\.in-addr\.arpa\.?$//;
4281 $rechost = join '.', reverse split /\./, $rechost;
4282 } else {
4283 $rechost =~ s/\.ip6\.arpa\.?$//;
4284 my @nibs = reverse split /\./, $rechost;
4285 $rechost = '';
4286 my $nc;
4287 foreach (@nibs) {
4288 $rechost.= $_;
4289 $rechost .= ":" if ++$nc % 4 == 0 && $nc < 32;
4290 }
4291 $rechost .= ":" if $nc < 32 && $rechost !~ /\*$/; # close netblock records?
4292##fixme: there's a case that ends up with a partial entry here:
4293# ip:add:re:ss::
4294# can't reproduce after letting it sit overnight after discovery. :(
4295#print "$rechost\n";
4296 # canonicalize with NetAddr::IP
4297 $rechost = NetAddr::IP->new($rechost)->addr unless $rechost =~ /\*$/;
4298 }
4299 return ($recdata,$rechost)
4300 }
4301
4302
4303 # Allow transactions, and raise an exception on errors so we can catch it later.
4304 # Use local to make sure these get "reset" properly on exiting this block
4305 local $dbh->{AutoCommit} = 0;
4306 local $dbh->{RaiseError} = 1;
4307
4308 my $sth;
4309 eval {
4310
4311 if ($rev eq 'n') {
4312##fixme: serial
4313 $dbh->do("INSERT INTO domains (domain,group_id,status) VALUES (?,?,?)", undef, ($zone,$group,$status) );
4314 # get domain id so we can do the records
4315 ($zone_id) = $dbh->selectrow_array("SELECT currval('domains_domain_id_seq')");
4316 $domain_id = $zone_id;
4317 _log($dbh, (group_id => $group, domain_id => $domain_id,
4318 entry => "[Added ".($status ? 'active' : 'inactive')." domain $zone via AXFR]") );
4319 } else {
4320##fixme: serial
4321 $dbh->do("INSERT INTO revzones (revnet,group_id,status) VALUES (?,?,?)", undef, ($cidr,$group,$status) );
4322 # get revzone id so we can do the records
4323 ($zone_id) = $dbh->selectrow_array("SELECT currval('revzones_rdns_id_seq')");
4324 $rdns_id = $zone_id;
4325 _log($dbh, (group_id => $group, rdns_id => $rdns_id,
4326 entry => "[Added ".($status ? 'active' : 'inactive')." reverse zone $cidr via AXFR]") );
4327 }
4328
4329## bizarre DBI<->Net::DNS interaction bug:
4330## sometimes a zone will cause an immediate commit-and-exit (sort of) of the while()
4331## fixed, apparently I was doing *something* odd, but not certain what it was that
4332## caused a commit instead of barfing
4333
4334 my $res = Net::DNS::Resolver->new;
4335 $res->nameservers($ifrom);
4336 $res->axfr_start($zone)
4337 or die "Couldn't begin AXFR\n";
4338
4339 $sth = $dbh->prepare("INSERT INTO records (domain_id,rdns_id,host,type,val,distance,weight,port,ttl)".
4340 " VALUES (?,?,?,?,?,?,?,?,?)");
4341
4342 # Stash info about sub-octet v4 revzones here so we don't have
4343 # to store the CNAMEs used to delegate a suboctet zone
4344 # $suboct{zone}{ns}[] -> array of nameservers
4345 # $suboct{zone}{cname}[] -> array of extant CNAMEs (Just In Case someone did something bizarre)
4346## commented pending actual use of this data. for now, we'll just
4347## auto-(re)create the CNAMEs in revzones on export
4348# my %suboct;
4349
4350 while (my $rr = $res->axfr_next()) {
4351
4352 my $val;
4353 my $distance = 0;
4354 my $weight = 0;
4355 my $port = 0;
4356 my $logfrag = '';
4357
4358 my $type = $rr->type;
4359 my $host = $rr->name;
4360 my $ttl = ($newttl ? $newttl : $rr->ttl); # allow force-override TTLs
4361
4362 $soaflag = 1 if $type eq 'SOA';
4363 $nsflag = 1 if $type eq 'NS';
4364
4365# "Primary" types:
4366# A, NS, CNAME, SOA, PTR(warn in forward), MX, TXT, AAAA, SRV, A6(ob), SPF
4367# maybe KEY
4368
4369# BIND supports:
4370# [standard]
4371# A AAAA CNAME MX NS PTR SOA TXT
4372# [variously experimental, obsolete, or obscure]
4373# 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
4374# ... if one can ever find the right magic to format them correctly
4375
4376# Net::DNS supports:
4377# RRSIG SIG NSAP NS NIMLOC NAPTR MX MR MINFO MG MB LOC ISDN IPSECKEY HINFO
4378# EID DNAME CNAME CERT APL AFSDB AAAA A DS NXT NSEC3PARAM NSEC3 NSEC KEY
4379# DNSKEY DLV X25 TXT TSIG TKEY SSHFP SRV SPF SOA RT RP PX PTR NULL APL::AplItem
4380
4381# nasty big ugly case-like thing here, since we have to do *some* different
4382# processing depending on the record. le sigh.
4383
4384##fixme: what record types other than TXT can/will have >255-byte payloads?
4385
4386 if ($type eq 'A') {
4387 $val = $rr->address;
4388 } elsif ($type eq 'NS') {
4389# hmm. should we warn here if subdomain NS'es are left alone?
4390 next if ($rwns && ($rr->name eq $zone));
4391 if ($rev eq 'y') {
4392 # revzones have records more or less reversed from forward zones.
4393 my ($tmpcode,$tmpmsg) = _zone2cidr($host);
4394 die "Error converting NS record: $tmpmsg\n" if $tmpcode eq 'FAIL'; # hmm. may not make sense...
4395 $val = "$tmpmsg";
4396 $host = $rr->nsdname;
4397 $logfrag = "Added record '$val $type $host', TTL $ttl";
4398# Tag and preserve. For now this is commented for a no-op, but we have Ideas for
4399# another custom storage type ("DELEGATE") that will use these subzone-delegation records
4400#if ($val ne "$cidr") {
4401# push @{$suboct{$val}{ns}}, $host;
4402#}
4403 } else {
4404 $val = $rr->nsdname;
4405 }
4406 $nsflag = 1;
4407 } elsif ($type eq 'CNAME') {
4408 if ($rev eq 'y') {
4409 # hmm. do we even want to bother with storing these at this level? Sub-octet delegation
4410 # by CNAME is essentially a record-publication hack, and we want to just represent the
4411 # "true" logical intentions as far down the stack as we can from the UI.
4412 ($host,$val) = _revswap($host,$rr->cname);
4413 $logfrag = "Added record '$val $type $host', TTL $ttl";
4414# Tag and preserve in case we want to commit them as-is later, but mostly we don't care.
4415# Commented pending actually doing something with possibly new type DELEGATE
4416#my $tmprev = $host;
4417#$tmprev =~ s/^\d+\.//;
4418#($code,$tmprev) = _zone2cidr($tmprev);
4419#push @{$suboct{"$tmprev"}{cname}}, $val;
4420 # Silently skip CNAMEs in revzones.
4421 next;
4422 } else {
4423 $val = $rr->cname;
4424 }
4425 } elsif ($type eq 'SOA') {
4426 next if $rwsoa;
4427 $host = $rr->rname.":".$rr->mname;
4428 $val = $rr->refresh.":".$rr->retry.":".$rr->expire.":".$rr->minimum;
4429 $soaflag = 1;
4430 } elsif ($type eq 'PTR') {
4431 ($host,$val) = _revswap($host,$rr->ptrdname);
4432 $logfrag = "Added record '$val $type $host', TTL $ttl";
4433 # hmm. PTR records should not be in forward zones.
4434 } elsif ($type eq 'MX') {
4435 $val = $rr->exchange;
4436 $distance = $rr->preference;
4437 } elsif ($type eq 'TXT') {
4438##fixme: Net::DNS docs say this should be deprecated for rdatastr() or char_str_list(),
4439## but don't really seem enthusiastic about it.
4440#print "should use rdatastr:\n\t".$rr->rdatastr."\n or char_str_list:\n\t".join(' ',$rr->char_str_list())."\n";
4441# rdatastr returns a BIND-targetted logical string, including opening and closing quotes
4442# char_str_list returns a list of the individual string fragments in the record
4443# txtdata returns the more useful all-in-one form (since we want to push such protocol
4444# details as far down the stack as we can)
4445# NB: this may turn out to be more troublesome if we ever have need of >512-byte TXT records.
4446 if ($rev eq 'y') {
4447 ($host,$val) = _revswap($host,$rr->txtdata);
4448 $logfrag = "Added record '$val $type $host', TTL $ttl";
4449 } else {
4450 $val = $rr->txtdata;
4451 }
4452 } elsif ($type eq 'SPF') {
4453##fixme: and the same caveat here, since it is apparently a clone of ::TXT
4454 $val = $rr->txtdata;
4455 } elsif ($type eq 'AAAA') {
4456 $val = $rr->address;
4457 } elsif ($type eq 'SRV') {
4458 $val = $rr->target;
4459 $distance = $rr->priority;
4460 $weight = $rr->weight;
4461 $port = $rr->port;
4462 } elsif ($type eq 'KEY') {
4463 # we don't actually know what to do with these...
4464 $val = $rr->flags.":".$rr->protocol.":".$rr->algorithm.":".$rr->key.":".$rr->keytag.":".$rr->privatekeyname;
4465 } else {
4466 $val = $rr->rdatastr;
4467 # Finding a different record type is not fatal.... just problematic.
4468 # We may not be able to export it correctly.
4469 $warnmsg .= "Unusual record ".$rr->name." ($type) found\n";
4470 }
4471
4472 my $logentry = "[AXFR ".($rev eq 'n' ? $zone : $cidr)."] ";
4473
4474 if ($merge) {
4475 if ($rev eq 'n') {
4476 # importing a domain; we have A and AAAA records that could be merged with matching PTR records
4477 my $etype;
4478 my ($erdns,$erid,$ettl) = $dbh->selectrow_array("SELECT rdns_id,record_id,ttl FROM records ".
4479 "WHERE host=? AND val=? AND type=12",
4480 undef, ($host, $val) );
4481 if ($erid) {
4482 if ($type eq 'A') { # PTR -> A+PTR
4483 $etype = 65280;
4484 $logentry .= "Merged A record with existing PTR record '$host A+PTR $val', TTL $ettl";
4485 }
4486 if ($type eq 'AAAA') { # PTR -> AAAA+PTR
4487 $etype = 65281;
4488 $logentry .= "Merged AAAA record with existing PTR record '$host AAAA+PTR $val', TTL $ettl";
4489 }
4490 $ettl = ($ettl < $ttl ? $ettl : $ttl); # use lower TTL
4491 $dbh->do("UPDATE records SET domain_id=?,ttl=?,type=? WHERE record_id=?", undef,
4492 ($domain_id, $ettl, $etype, $erid));
4493 $nrecs++;
4494 _log($dbh, (group_id => $group, domain_id => $domain_id, rdns_id => $erdns, entry => $logentry) );
4495 next; # while axfr_next
4496 }
4497 } # $rev eq 'n'
4498 else {
4499 # importing a revzone, we have PTR records that could be merged with matching A/AAAA records
4500 my ($domid,$erid,$ettl,$etype) = $dbh->selectrow_array("SELECT domain_id,record_id,ttl,type FROM records ".
4501 "WHERE host=? AND val=? AND (type=1 OR type=28)",
4502 undef, ($host, $val) );
4503 if ($erid) {
4504 if ($etype == 1) { # A -> A+PTR
4505 $etype = 65280;
4506 $logentry .= "Merged PTR record with existing matching A record '$host A+PTR $val', TTL $ettl";
4507 }
4508 if ($etype == 28) { # AAAA -> AAAA+PTR
4509 $etype = 65281;
4510 $logentry .= "Merged PTR record with existing matching AAAA record '$host AAAA+PTR $val', TTL $ettl";
4511 }
4512 $ettl = ($ettl < $ttl ? $ettl : $ttl); # use lower TTL
4513 $dbh->do("UPDATE records SET rdns_id=?,ttl=?,type=? WHERE record_id=?", undef,
4514 ($rdns_id, $ettl, $etype, $erid));
4515 $nrecs++;
4516 _log($dbh, (group_id => $group, domain_id => $domid, rdns_id => $rdns_id, entry => $logentry) );
4517 next; # while axfr_next
4518 }
4519 } # $rev eq 'y'
4520 } # if $merge
4521
4522 # Insert the new record
4523 $sth->execute($domain_id, $rdns_id, $host, $reverse_typemap{$type}, $val,
4524 $distance, $weight, $port, $ttl);
4525
4526 $nrecs++;
4527
4528 if ($type eq 'SOA') {
4529 # also !$rwsoa, but if that's set, it should be impossible to get here.
4530 my @tmp1 = split /:/, $host;
4531 my @tmp2 = split /:/, $val;
4532 $logentry .= "Added SOA record [contact $tmp1[0]] [master $tmp1[1]] ".
4533 "[refresh $tmp2[0]] [retry $tmp2[1]] [expire $tmp2[2]] [minttl $tmp2[3]], TTL $ttl";
4534 } elsif ($logfrag) {
4535 # special case for log entries we need to meddle with a little.
4536 $logentry .= $logfrag;
4537 } else {
4538 $logentry .= "Added record '$host $type";
4539 $logentry .= " [distance $distance]" if $type eq 'MX';
4540 $logentry .= " [priority $distance] [weight $weight] [port $port]" if $type eq 'SRV';
4541 $logentry .= " $val', TTL $ttl";
4542 }
4543 _log($dbh, (group_id => $group, domain_id => $domain_id, rdns_id => $rdns_id, entry => $logentry) );
4544
4545 } # while axfr_next
4546
4547# Detect and handle delegated subzones
4548# Placeholder for when we decide what to actually do with this, see previous comments in NS and CNAME handling.
4549#foreach (keys %suboct) {
4550# print "found ".($suboct{$_}{ns} ? @{$suboct{$_}{ns}} : '0')." NS records and ".
4551# ($suboct{$_}{cname} ? @{$suboct{$_}{cname}} : '0')." CNAMEs for $_\n";
4552#}
4553
4554 # Overwrite SOA record
4555 if ($rwsoa) {
4556 $soaflag = 1;
4557 my $sthgetsoa = $dbh->prepare("SELECT host,val,ttl FROM default_records WHERE group_id=? AND type=?");
4558 my $sthputsoa = $dbh->prepare("INSERT INTO records (domain_id,host,type,val,ttl) VALUES (?,?,?,?,?)");
4559 $sthgetsoa->execute($group,$reverse_typemap{SOA});
4560 while (my ($host,$val,$ttl) = $sthgetsoa->fetchrow_array()) {
4561 $host =~ s/DOMAIN/$zone/g;
4562 $val =~ s/DOMAIN/$zone/g;
4563 $sthputsoa->execute($zone_id,$host,$reverse_typemap{SOA},$val,$ttl);
4564 }
4565 }
4566
4567 # Overwrite NS records
4568 if ($rwns) {
4569 $nsflag = 1;
4570 my $sthgetns = $dbh->prepare("SELECT host,val,ttl FROM default_records WHERE group_id=? AND type=?");
4571 my $sthputns = $dbh->prepare("INSERT INTO records (domain_id,host,type,val,ttl) VALUES (?,?,?,?,?)");
4572 $sthgetns->execute($group,$reverse_typemap{NS});
4573 while (my ($host,$val,$ttl) = $sthgetns->fetchrow_array()) {
4574 $host =~ s/DOMAIN/$zone/g;
4575 $val =~ s/DOMAIN/$zone/g;
4576 $sthputns->execute($zone_id,$host,$reverse_typemap{NS},$val,$ttl);
4577 }
4578 }
4579
4580 die "No records found; either $ifrom is not authoritative or doesn't allow transfers\n" if !$nrecs;
4581 die "Bad zone: No SOA record!\n" if !$soaflag;
4582 die "Bad zone: No NS records!\n" if !$nsflag;
4583
4584 $dbh->commit;
4585
4586 };
4587
4588 if ($@) {
4589 my $msg = $@;
4590 eval { $dbh->rollback; };
4591 return ('FAIL',$msg." $warnmsg");
4592 } else {
4593 return ('WARN', $warnmsg) if $warnmsg;
4594 return ('OK',"Imported OK");
4595 }
4596
4597 # it should be impossible to get here.
4598 return ('WARN',"OOOK!");
4599} # end importAXFR()
4600
4601
4602## DNSDB::importBIND()
4603sub importBIND {
4604} # end importBIND()
4605
4606
4607## DNSDB::import_tinydns()
4608sub import_tinydns {
4609} # end import_tinydns()
4610
4611
4612## DNSDB::export()
4613# Export the DNS database, or a part of it
4614# Takes database handle, export type, optional arguments depending on type
4615# Writes zone data to targets as appropriate for type
4616sub export {
4617 my $dbh = shift;
4618 my $target = shift;
4619
4620 if ($target eq 'tiny') {
4621 __export_tiny($dbh,@_);
4622 }
4623# elsif ($target eq 'foo') {
4624# __export_foo($dbh,@_);
4625#}
4626# etc
4627
4628} # end export()
4629
4630
4631## DNSDB::__export_tiny
4632# Internal sub to implement tinyDNS (compatible) export
4633# Takes database handle, filehandle to write export to, optional argument(s)
4634# to determine which data gets exported
4635sub __export_tiny {
4636 my $dbh = shift;
4637 my $datafile = shift;
4638
4639##fixme: slurp up further options to specify particular zone(s) to export
4640
4641##fixme: fail if $datafile isn't an open, writable file
4642
4643 # easy case - export all evarything
4644 # not-so-easy case - export item(s) specified
4645 # todo: figure out what kind of list we use to export items
4646
4647# raw packet in unknown format: first byte indicates length
4648# of remaining data, allows up to 255 raw bytes
4649
4650 # Locations/views - worth including in the caching setup?
4651 my $lochash = $dbh->selectall_hashref("SELECT location,iplist FROM locations", 'location');
4652 foreach my $location (keys %$lochash) {
4653 foreach my $ipprefix (split /[,\s]+/, $lochash->{$location}{iplist}) {
4654 $ipprefix =~ s/\s+//g;
4655 $ipprefix = new NetAddr::IP $ipprefix;
4656##fixme: how to handle IPv6?
4657next if $ipprefix->{isv6};
4658 # have to account for /nn CIDR entries. tinydns only speaks octet-sliced prefix.
4659 if ($ipprefix->masklen <= 8) {
4660 foreach ($ipprefix->split(8)) {
4661 my $tmp = $_->addr;
4662 $tmp =~ s/\.\d+\.\d+\.\d+$//;
4663 print $datafile "%$location:$tmp\n";
4664 }
4665 } elsif ($ipprefix->masklen <= 16) {
4666 foreach ($ipprefix->split(16)) {
4667 my $tmp = $_->addr;
4668 $tmp =~ s/\.\d+\.\d+$//;
4669 print $datafile "%$location:$tmp\n";
4670 }
4671 } elsif ($ipprefix->masklen <= 24) {
4672 foreach ($ipprefix->split(24)) {
4673 my $tmp = $_->addr;
4674 $tmp =~ s/\.\d+$//;
4675 print $datafile "%$location:$tmp\n";
4676 }
4677 } else {
4678 foreach ($ipprefix->split(32)) {
4679 print $datafile "%$location:".$_->addr."\n";
4680 }
4681 }
4682 }
4683 print $datafile "%$location\n" if !$lochash->{$location}{iplist};
4684 }
4685
4686 # tracking hash so we don't double-export A+PTR or AAAA+PTR records.
4687 my %recflags;
4688
4689 my $domsth = $dbh->prepare("SELECT domain_id,domain,status,changed FROM domains WHERE status=1");
4690 my $recsth = $dbh->prepare("SELECT host,type,val,distance,weight,port,ttl,record_id,location ".
4691 "FROM records WHERE domain_id=? AND type < 65280"); # Just exclude all types relating to rDNS
4692 my $zonesth = $dbh->prepare("UPDATE domains SET changed='n' WHERE domain_id=?");
4693 $domsth->execute();
4694 while (my ($domid,$dom,$domstat,$changed) = $domsth->fetchrow_array) {
4695##fixme: need to find a way to block opening symlinked files without introducing a race.
4696# O_NOFOLLOW
4697# If pathname is a symbolic link, then the open fails. This is a FreeBSD extension, which was
4698# added to Linux in version 2.1.126. Symbolic links in earlier components of the pathname will
4699# still be followed.
4700# but that doesn't help other platforms. :/
4701 sysopen(ZONECACHE, "$config{exportcache}/$dom", O_RDWR|O_CREAT);
4702 flock(ZONECACHE, LOCK_EX);
4703 if ($changed || -s "$config{exportcache}/$dom" == 0) {
4704 $recsth->execute($domid);
4705 while (my ($host,$type,$val,$dist,$weight,$port,$ttl,$recid,$loc) = $recsth->fetchrow_array) {
4706 next if $recflags{$recid};
4707
4708 $loc = '' if !$loc; # de-nullify - just in case
4709##fixme: handle case of record-with-location-that-doesn't-exist better.
4710# note this currently fails safe (tested) - records with a location that
4711# doesn't exist will not be sent to any client
4712# $loc = '' if !$lochash->{$loc};
4713
4714##fixme: record validity timestamp. tinydns supports fiddling with timestamps.
4715# note $ttl must be set to 0 if we want to use tinydns's auto-expiring timestamps.
4716# timestamps are TAI64
4717# ~~ 2^62 + time()
4718 my $stamp = '';
4719
4720 # support tinydns' auto-TTL
4721 $ttl = '' if $ttl == '0';
4722
4723 # Spaces are evil.
4724 $host =~ s/^\s+//;
4725 $host =~ s/\s+$//;
4726 if ($typemap{$type} ne 'TXT') {
4727 # Leading or trailng spaces could be legit in TXT records.
4728 $val =~ s/^\s+//;
4729 $val =~ s/\s+$//;
4730 }
4731
4732 _printrec_tiny(*ZONECACHE, 'n', \%recflags,
4733 $dom, $host, $type, $val, $dist, $weight, $port, $ttl, $loc, $stamp)
4734 if *ZONECACHE;
4735
4736 # in case the zone shrunk, get rid of garbage at the end of the file.
4737 truncate(ZONECACHE, tell(ZONECACHE));
4738
4739 $recflags{$recid} = 1;
4740 } # while ($recsth)
4741 }
4742 # stream from cache, whether freshly created or existing
4743 print $datafile $_ while <ZONECACHE>;
4744 close ZONECACHE;
4745 # mark domain as unmodified
4746 $zonesth->execute($domid);
4747 } # while ($domsth)
4748
4749 my $revsth = $dbh->prepare("SELECT rdns_id,revnet,status,changed FROM revzones WHERE status=1 ".
4750 "ORDER BY masklen(revnet) DESC");
4751
4752# For reasons unknown, we can't sanely UNION these statements. Feh.
4753# Supposedly it should work though (note last 3 lines):
4754## PG manual
4755#UNION Clause
4756#
4757#The UNION clause has this general form:
4758#
4759# select_statement UNION [ ALL ] select_statement
4760#
4761#select_statement is any SELECT statement without an ORDER BY, LIMIT, FOR UPDATE, or FOR SHARE clause. (ORDER BY
4762#and LIMIT can be attached to a subexpression if it is enclosed in parentheses. Without parentheses, these
4763#clauses will be taken to apply to the result of the UNION, not to its right-hand input expression.)
4764 my $soasth = $dbh->prepare("SELECT host,type,val,distance,weight,port,ttl,record_id,location ".
4765 "FROM records WHERE rdns_id=? AND type=6");
4766 $recsth = $dbh->prepare("SELECT host,type,val,distance,weight,port,ttl,record_id,location ".
4767 "FROM records WHERE rdns_id=? AND not type=6 ".
4768 "ORDER BY masklen(CAST(val AS inet)) DESC, CAST(val AS inet)");
4769 $zonesth = $dbh->prepare("UPDATE revzones SET changed='n' WHERE rdns_id=?");
4770 $revsth->execute();
4771 while (my ($revid,$revzone,$revstat,$changed) = $revsth->fetchrow_array) {
4772##fixme: need to find a way to block opening symlinked files without introducing a race.
4773# O_NOFOLLOW
4774# If pathname is a symbolic link, then the open fails. This is a FreeBSD extension, which was
4775# added to Linux in version 2.1.126. Symbolic links in earlier components of the pathname will
4776# still be followed.
4777# but that doesn't help other platforms. :/
4778 my $tmpzone = NetAddr::IP->new($revzone);
4779 sysopen(ZONECACHE, "$config{exportcache}/".$tmpzone->network->addr, O_RDWR|O_CREAT);
4780 flock(ZONECACHE, LOCK_EX);
4781 if ($changed || -s "$config{exportcache}/".$tmpzone->network->addr == 0) {
4782 # need to fetch this separately since the rest of the records all (should) have real IPs in val
4783 $soasth->execute($revid);
4784 my (@zsoa) = $soasth->fetchrow_array();
4785 _printrec_tiny(*ZONECACHE,'y',\%recflags,$revzone,
4786 $zsoa[0],$zsoa[1],$zsoa[2],$zsoa[3],$zsoa[4],$zsoa[5],$zsoa[6],$zsoa[8],'');
4787
4788 $recsth->execute($revid);
4789 while (my ($host,$type,$val,$dist,$weight,$port,$ttl,$recid,$loc) = $recsth->fetchrow_array) {
4790 next if $recflags{$recid};
4791
4792 $loc = '' if !$loc; # de-nullify - just in case
4793##fixme: handle case of record-with-location-that-doesn't-exist better.
4794# note this currently fails safe (tested) - records with a location that
4795# doesn't exist will not be sent to any client
4796# $loc = '' if !$lochash->{$loc};
4797
4798##fixme: record validity timestamp. tinydns supports fiddling with timestamps.
4799# note $ttl must be set to 0 if we want to use tinydns's auto-expiring timestamps.
4800# timestamps are TAI64
4801# ~~ 2^62 + time()
4802 my $stamp = '';
4803
4804 # support tinydns' auto-TTL
4805 $ttl = '' if $ttl == '0';
4806
4807 _printrec_tiny(*ZONECACHE, 'y', \%recflags, $revzone,
4808 $host, $type, $val, $dist, $weight, $port, $ttl, $loc, $stamp)
4809 if *ZONECACHE;
4810
4811 # in case the zone shrunk, get rid of garbage at the end of the file.
4812 truncate(ZONECACHE, tell(ZONECACHE));
4813
4814 $recflags{$recid} = 1;
4815 } # while ($recsth)
4816 }
4817 # stream from cache, whether freshly created or existing
4818 print $datafile $_ while <ZONECACHE>;
4819 close ZONECACHE;
4820 # mark zone as unmodified
4821 $zonesth->execute($revid);
4822 } # while ($domsth)
4823
4824} # end __export_tiny()
4825
4826
4827# Utility sub for __export_tiny above
4828sub _printrec_tiny {
4829 my ($datafile,$revrec,$recflags,$zone,$host,$type,$val,$dist,$weight,$port,$ttl,$loc,$stamp) = @_;
4830
4831 ## Convert a bare number into an octal-coded pair of octets.
4832 # Take optional arg to indicate a decimal or hex input. Defaults to hex.
4833 sub octalize {
4834 my $tmp = shift;
4835 my $srctype = shift || 'h'; # default assumes hex string
4836 $tmp = sprintf "%0.4x", hex($tmp) if $srctype eq 'h'; # 0-pad hex to 4 digits
4837 $tmp = sprintf "%0.4x", $tmp if $srctype eq 'd'; # 0-pad decimal to 4 hex digits
4838 my @o = ($tmp =~ /^(..)(..)$/); # split into octets
4839 return sprintf "\\%0.3o\\%0.3o", hex($o[0]), hex($o[1]);;
4840 }
4841
4842## WARNING: This works to export even the whole Internet's worth of IP space...
4843## if you have the disk/RAM to handle the dataset, and you call this sub based on /16-sized chunks
4844## A /16 took ~3 seconds with a handful of separate records; adding a /8 pushed export time out to ~13m:40s
4845## 0/0 is estimated to take ~54 hours and ~256G of disk
4846## RAM usage depends on how many non-template entries you have in the set.
4847## This should probably be done on record addition rather than export; large blocks may need to be done in a
4848## forked process
4849 sub __publish_subnet {
4850 my $sub = shift;
4851 my $recflags = shift;
4852 my $hpat = shift;
4853 my $fh = shift;
4854 my $ttl = shift;
4855 my $stamp = shift;
4856 my $loc = shift;
4857 my $ptronly = shift || 0;
4858
4859 my $iplist = $sub->splitref(32);
4860 foreach (@$iplist) {
4861 my $ip = $_->addr;
4862 # make as if we split the non-octet-aligned block into octet-aligned blocks as with SOA
4863 next if $ip =~ /\.(0|255)$/;
4864 next if $$recflags{$ip};
4865 $$recflags{$ip}++;
4866 my $rec = $hpat; # start fresh with the template for each IP
4867 _template4_expand(\$rec, $ip);
4868 print $fh ($ptronly ? "^"._ZONE($_, 'ZONE.in-addr.arpa', 'r', '.').":$rec" : "=$rec:$ip").
4869 ":$ttl:$stamp:$loc\n";
4870 }
4871 }
4872
4873##fixme? append . to all host/val hostnames
4874 if ($typemap{$type} eq 'SOA') {
4875
4876 # host contains pri-ns:responsible
4877 # val is abused to contain refresh:retry:expire:minttl
4878##fixme: "manual" serial vs tinydns-autoserial
4879 # let's be explicit about abusing $host and $val
4880 my ($email, $primary) = (split /:/, $host)[0,1];
4881 my ($refresh, $retry, $expire, $min_ttl) = (split /:/, $val)[0,1,2,3];
4882 if ($revrec eq 'y') {
4883##fixme: have to publish SOA records for each v4 /24 in sub-/16, and each /16 in sub-/8
4884# what about v6?
4885# -> only need SOA for local chunks offset from reverse delegation boundaries, so v6 is fine
4886 $zone = NetAddr::IP->new($zone);
4887 # handle split-n-multiply SOA for off-octet (8 < mask < 16) or (16 < mask < 24) v4 zones
4888 if (!$zone->{isv6} && ($zone->masklen < 24) && ($zone->masklen % 8 != 0)) {
4889 foreach my $szone ($zone->split($zone->masklen + (8 - $zone->masklen % 8))) {
4890 $szone = _ZONE($szone, 'ZONE.in-addr.arpa', 'r', '.');
4891 print $datafile "Z$szone:$primary:$email"."::$refresh:$retry:$expire:$min_ttl:$ttl:$stamp:$loc\n";
4892 }
4893 return; # skips "default" bits just below
4894 }
4895 $zone = _ZONE($zone, 'ZONE', 'r', '.').($zone->{isv6} ? '.ip6.arpa' : '.in-addr.arpa');
4896 }
4897 print $datafile "Z$zone:$primary:$email"."::$refresh:$retry:$expire:$min_ttl:$ttl:$stamp:$loc\n";
4898
4899 } elsif ($typemap{$type} eq 'A') {
4900
4901 print $datafile "+$host:$val:$ttl:$stamp:$loc\n";
4902
4903 } elsif ($typemap{$type} eq 'NS') {
4904
4905 if ($revrec eq 'y') {
4906 $val = NetAddr::IP->new($val);
4907 # handle split-n-multiply SOA for off-octet (8 < mask < 16) or (16 < mask < 24) v4 zones
4908 if (!$val->{isv6} && ($val->masklen < 24) && ($val->masklen % 8 != 0)) {
4909 foreach my $szone ($val->split($val->masklen + (8 - $val->masklen % 8))) {
4910 my $szone2 = _ZONE($szone, 'ZONE.in-addr.arpa', 'r', '.');
4911 next if $$recflags{$szone2} && $$recflags{$szone2} > $val->masklen;
4912 print $datafile "\&$szone2"."::$host:$ttl:$stamp:$loc\n";
4913 $$recflags{$szone2} = $val->masklen;
4914 }
4915 } elsif ($val->{isv6} && ($val->masklen < 64) && ($val->masklen % 4 !=0)) {
4916 foreach my $szone ($val->split($val->masklen + (4 - $val->masklen % 4))) {
4917 my $szone2 = _ZONE($szone, 'ZONE.ip6.arpa', 'r', '.');
4918 next if $$recflags{$szone2} && $$recflags{$szone2} > $val->masklen;
4919 print $datafile "\&$szone2"."::$host:$ttl:$stamp:$loc\n";
4920 $$recflags{$szone2} = $val->masklen;
4921 }
4922 } else {
4923 my $val2 = _ZONE($val, 'ZONE', 'r', '.').($val->{isv6} ? '.ip6.arpa' : '.in-addr.arpa');
4924 print $datafile "\&$val2"."::$host:$ttl:$stamp:$loc\n";
4925 $$recflags{$val2} = $val->masklen;
4926 }
4927 } else {
4928 print $datafile "\&$host"."::$val:$ttl:$stamp:$loc\n";
4929 }
4930
4931 } elsif ($typemap{$type} eq 'AAAA') {
4932
4933 print $datafile ":$host:28:";
4934 my $altgrp = 0;
4935 my @altconv;
4936 # Split in to up to 8 groups of hex digits (allows for IPv6 :: 0-collapsing)
4937 foreach (split /:/, $val) {
4938 if (/^$/) {
4939 # flag blank entry; this is a series of 0's of (currently) unknown length
4940 $altconv[$altgrp++] = 's';
4941 } else {
4942 # call sub to convert 1-4 hex digits to 2 string-rep octal bytes
4943 $altconv[$altgrp++] = octalize($_)
4944 }
4945 }
4946 foreach my $octet (@altconv) {
4947 # if not 's', output
4948 print $datafile $octet unless $octet =~ /^s$/;
4949 # if 's', output (9-array length)x literal '\000\000'
4950 print $datafile '\000\000'x(9-$altgrp) if $octet =~ /^s$/;
4951 }
4952 print $datafile ":$ttl:$stamp:$loc\n";
4953
4954 } elsif ($typemap{$type} eq 'MX') {
4955
4956 print $datafile "\@$host"."::$val:$dist:$ttl:$stamp:$loc\n";
4957
4958 } elsif ($typemap{$type} eq 'TXT') {
4959
4960##fixme: split v-e-r-y long TXT strings? will need to do so for BIND export, at least
4961 if ($revrec eq 'n') {
4962 $val =~ s/:/\\072/g; # may need to replace other symbols
4963 print $datafile "'$host:$val:$ttl:$stamp:$loc\n";
4964 } else {
4965 $host =~ s/:/\\072/g; # may need to replace other symbols
4966 my $val2 = NetAddr::IP->new($val);
4967 print $datafile "'"._ZONE($val2, 'ZONE', 'r', '.').($val2->{isv6} ? '.ip6.arpa' : '.in-addr.arpa').
4968 ":$host:$ttl:$stamp:$loc\n";
4969 }
4970
4971# by-hand TXT
4972#:deepnet.cx:16:2v\075spf1\040a\040a\072bacon.deepnet.cx\040a\072home.deepnet.cx\040-all:3600
4973#@ IN TXT "v=spf1 a a:bacon.deepnet.cx a:home.deepnet.cx -all"
4974#'deepnet.cx:v=spf1 a a\072bacon.deepnet.cx a\072home.deepnet.cx -all:3600
4975
4976#txttest IN TXT "v=foo bar:bob kn;ob' \" !@#$%^&*()-=_+[]{}<>?"
4977#: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
4978
4979# very long TXT record as brought in by axfr-get
4980# note tinydns does not support >512-byte RR data, need axfr-dns (for TCP support) for that
4981# also note, tinydns does not seem to support <512, >256-byte RRdata from axfr-get either. :/
4982#:longtxt.deepnet.cx:16:
4983#\170this is a very long txt record. it is really long. long. very long. really very long. this is a very long txt record.
4984#\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.
4985#\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.
4986#:3600
4987
4988 } elsif ($typemap{$type} eq 'CNAME') {
4989
4990 if ($revrec eq 'n') {
4991 print $datafile "C$host:$val:$ttl:$stamp:$loc\n";
4992 } else {
4993 my $val2 = NetAddr::IP->new($val);
4994 print $datafile "C"._ZONE($val2, 'ZONE', 'r', '.').($val2->{isv6} ? '.ip6.arpa' : '.in-addr.arpa').
4995 ":$host:$ttl:$stamp:$loc\n";
4996 }
4997
4998 } elsif ($typemap{$type} eq 'SRV') {
4999
5000 # data is two-byte values for priority, weight, port, in that order,
5001 # followed by length/string data
5002
5003 print $datafile ":$host:33:".octalize($dist,'d').octalize($weight,'d').octalize($port,'d');
5004
5005 $val .= '.' if $val !~ /\.$/;
5006 foreach (split /\./, $val) {
5007 printf $datafile "\\%0.3o%s", length($_), $_;
5008 }
5009 print $datafile "\\000:$ttl:$stamp:$loc\n";
5010
5011 } elsif ($typemap{$type} eq 'RP') {
5012
5013 # RP consists of two mostly free-form strings.
5014 # The first is supposed to be an email address with @ replaced by . (as with the SOA contact)
5015 # The second is the "hostname" of a TXT record with more info.
5016 print $datafile ":$host:17:";
5017 my ($who,$what) = split /\s/, $val;
5018 foreach (split /\./, $who) {
5019 printf $datafile "\\%0.3o%s", length($_), $_;
5020 }
5021 print $datafile '\000';
5022 foreach (split /\./, $what) {
5023 printf $datafile "\\%0.3o%s", length($_), $_;
5024 }
5025 print $datafile "\\000:$ttl:$stamp:$loc\n";
5026
5027 } elsif ($typemap{$type} eq 'PTR') {
5028
5029 $zone = NetAddr::IP->new($zone);
5030 $$recflags{$val}++;
5031 if (!$zone->{isv6} && $zone->masklen > 24) {
5032 ($val) = ($val =~ /\.(\d+)$/);
5033 print $datafile "^$val."._ZONE($zone, 'ZONE', 'r', '.').'.in-addr.arpa'.
5034 ":$host:ttl:$stamp:$loc\n";
5035 } else {
5036 $val = NetAddr::IP->new($val);
5037 print $datafile "^".
5038 _ZONE($val, 'ZONE', 'r', '.').($val->{isv6} ? '.ip6.arpa' : '.in-addr.arpa').
5039 ":$host:$ttl:$stamp:$loc\n";
5040 }
5041
5042 } elsif ($type == 65280) { # A+PTR
5043
5044 $$recflags{$val}++;
5045 print $datafile "=$host:$val:$ttl:$stamp:$loc\n";
5046
5047 } elsif ($type == 65281) { # AAAA+PTR
5048
5049#$$recflags{$val}++;
5050 # treat these as two separate records. since tinydns doesn't have
5051 # a native combined type, we have to create them separately anyway.
5052 if ($revrec eq 'n') {
5053 $type = 28;
5054 } else {
5055 $type = 12;
5056 }
5057 _printrec_tiny($datafile,$revrec,$recflags,$zone,$host,$type,$val,$dist,$weight,$port,$ttl,$loc,$stamp);
5058##fixme: add a config flag to indicate use of the patch from http://www.fefe.de/dns/
5059# type 6 is for AAAA+PTR, type 3 is for AAAA
5060
5061 } elsif ($type == 65282) { # PTR template
5062
5063 # only useful for v4 with standard DNS software, since this expands all
5064 # IPs in $zone (or possibly $val?) with autogenerated records
5065 $val = NetAddr::IP->new($val);
5066 return if $val->{isv6};
5067
5068 if ($val->masklen <= 16) {
5069 foreach my $sub ($val->split(16)) {
5070 __publish_subnet($sub, $recflags, $host, $datafile, $ttl, $stamp, $loc, 1);
5071 }
5072 } else {
5073 __publish_subnet($val, $recflags, $host, $datafile, $ttl, $stamp, $loc, 1);
5074 }
5075
5076 } elsif ($type == 65283) { # A+PTR template
5077
5078 $val = NetAddr::IP->new($val);
5079 # Just In Case. An A+PTR should be impossible to add to a v6 revzone via API.
5080 return if $val->{isv6};
5081
5082 if ($val->masklen <= 16) {
5083 foreach my $sub ($val->split(16)) {
5084 __publish_subnet($sub, $recflags, $host, $datafile, $ttl, $stamp, $loc, 0);
5085 }
5086 } else {
5087 __publish_subnet($val, $recflags, $host, $datafile, $ttl, $stamp, $loc, 0);
5088 }
5089
5090 } elsif ($type == 65284) { # AAAA+PTR template
5091 # Stub for completeness. Could be exported to DNS software that supports
5092 # some degree of internal automagic in generic-record-creation
5093 # (eg http://search.cpan.org/dist/AllKnowingDNS/ )
5094
5095 } elsif ($type == 65285) { # Delegation
5096 # This is intended for reverse zones, but may prove useful in forward zones.
5097
5098 # All delegations need to create one or more NS records. The NS record handler knows what to do.
5099 _printrec_tiny($datafile,$revrec,$recflags,$zone,$host,$reverse_typemap{'NS'},
5100 $val,$dist,$weight,$port,$ttl,$loc,$stamp);
5101 if ($revrec eq 'y') {
5102 # In the case of a sub-/24 v4 reverse delegation, we need to generate CNAMEs
5103 # to redirect all of the individual IP lookups as well.
5104 # Not sure how this would actually resolve if a /24 or larger was delegated
5105 # one way, and a sub-/24 in that >=/24 was delegated elsewhere...
5106 my $dblock = NetAddr::IP->new($val);
5107 if (!$dblock->{isv6} && $dblock->masklen > 24) {
5108 my @subs = $dblock->split;
5109 foreach (@subs) {
5110 next if $$recflags{"$_"};
5111 my ($oct) = ($_->addr =~ /(\d+)$/);
5112 print $datafile "C"._ZONE($_, 'ZONE.in-addr.arpa', 'r', '.').":$oct.".
5113 _ZONE($dblock, 'ZONE.in-addr.arpa', 'r', '.').":$ttl:$stamp:$loc\n";
5114 $$recflags{"$_"}++;
5115 }
5116 }
5117 }
5118
5119##
5120## Uncommon types. These will need better UI support Any Day Sometime Maybe(TM).
5121##
5122
5123 } elsif ($type == 44) { # SSHFP
5124 my ($algo,$fpt,$fp) = split /\s+/, $val;
5125
5126 my $rec = sprintf ":$host:44:\\%0.3o\\%0.3o", $algo, $fpt;
5127 while (my ($byte) = ($fp =~ /^(..)/) ) {
5128 $rec .= sprintf "\\%0.3o", hex($byte);
5129 $fp =~ s/^..//;
5130 }
5131 print $datafile "$rec:$ttl:$stamp:$loc\n";
5132
5133 } else {
5134 # raw record. we don't know what's in here, so we ASS-U-ME the user has
5135 # put it in correctly, since either the user is messing directly with the
5136 # database, or the record was imported via AXFR
5137 # <split by char>
5138 # convert anything not a-zA-Z0-9.- to octal coding
5139
5140##fixme: add flag to export "unknown" record types - note we'll probably end up
5141# mangling them since they were written to the DB from Net::DNS::RR::<type>->rdatastr.
5142 #print $datafile ":$host:$type:$val:$ttl:$stamp:$loc\n";
5143
5144 } # record type if-else
5145
5146} # end _printrec_tiny()
5147
5148
5149## DNSDB::mailNotify()
5150# Sends notification mail to recipients regarding a DNSDB operation
5151sub mailNotify {
5152 my $dbh = shift;
5153 my ($subj,$message) = @_;
5154
5155 return if $config{mailhost} eq 'smtp.example.com'; # do nothing if still using default SMTP host.
5156
5157 my $mailer = Net::SMTP->new($config{mailhost}, Hello => "dnsadmin.$config{domain}");
5158
5159 my $mailsender = ($config{mailsender} ? $config{mailsender} : $config{mailnotify});
5160
5161 $mailer->mail($mailsender);
5162 $mailer->to($config{mailnotify});
5163 $mailer->data("From: \"$config{mailname}\" <$mailsender>\n",
5164 "To: <$config{mailnotify}>\n",
5165 "Date: ".strftime("%a, %d %b %Y %H:%M:%S %z",localtime)."\n",
5166 "Subject: $subj\n",
5167 "X-Mailer: DNSAdmin Notify v".sprintf("%.1d",$DNSDB::VERSION)."\n",
5168 "Organization: $config{orgname}\n",
5169 "\n$message\n");
5170 $mailer->quit;
5171}
5172
5173# shut Perl up
51741;
Note: See TracBrowser for help on using the repository browser.