source: trunk/DNSDB.pm@ 326

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

/trunk

Move SQL for clone-this-user dropdown into DNSDB.pm. See #1

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