source: branches/stable/DNSDB.pm@ 584

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

/branches/stable

Merge forward bugfixes and option additions from /trunk r570 through r581

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