source: trunk/DNSDB.pm@ 337

Last change on this file since 337 was 337, checked in by Kris Deugau, 13 years ago

/trunk

Checkpoint updating export for reverse DNS. See #26.

  • _template4_expand moved up to join its relatives _ZONE and _zone2cidr
  • SOA export updated to properly output multiple real SOA records if a logical v4 reverse zone is not octet-aligned
  • PTR template and A+PTR template should now be complete
  • Zone and record SELECTs updated so that records are retrieved in an order that lets us export the more specific records first so we can exclude those IPs from the 1->many template record expansion

SOA and (A+)PTR template changes should probably be tested
further for odd edge cases

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