source: trunk/DNSDB.pm@ 306

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

/trunk

Drop support for /31 sub-octet ranges in in-addr.arpa zone names in
favour of supporting an alternate scheme that uses the netmask as
the number after the dash. (You can't tell 24-31 -> (range) .24/29
apart from 24-31 (mask) -> .24/31 in isolation.)

Consider supporting / in the zone name too; however / is not
generally considered a valid character for domain name parts.

[ log -> ticket fixup: see #26 ]

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