source: trunk/DNSDB.pm@ 531

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

/trunk

Accept bare @ as a hostname for domain entries. Store the @, and
convert to the domain name on export. See #18.

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