source: trunk/DNSDB.pm@ 295

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

/trunk

Move entity-relationship reference hashes up into the same area
as other (semi)globals in DNSDB.pm since I was starting to add
an accidental duplicate of %par_tbl.
Move action logging for bulk domain change to DNSDB.pm: (See #35)

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