source: trunk/DNSDB.pm@ 303

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

/trunk

Checkpoint - still finding rough edges in AXFR import
[ log -> ticket fixup: see #26 ]

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