source: trunk/DNSDB.pm@ 331

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

/trunk

Tweak getChildren() a little with a trailing sort-by-name. This
makes the ordering of groups predictable, and allows indentation
of the list in dropdowns.

This should probably be extended to be able to sort on some other
criteria.

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