source: trunk/DNSDB.pm@ 387

Last change on this file since 387 was 387, checked in by Kris Deugau, 12 years ago

/trunk

Add a new permission record_locchg to separate changing the
location of a record from the abaility to edit a record or
change the location definition. See #10.

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