source: trunk/DNSDB.pm@ 235

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

/trunk

Validation for addRec() now functional with %validators hash
Several more tweaks and cleanups in A, AAAA, PTR, and A/AAAA+PTR records
dns.cgi now reports WARN conditions on add record
Minor typos in reclist.tmpl and record.tmpl fixed

  • Property svn:keywords set to Date Rev Author Id
File size: 84.4 KB
RevLine 
[2]1# dns/trunk/DNSDB.pm
2# Abstraction functions for DNS administration
3###
4# SVN revision info
5# $Date: 2012-02-16 21:14:36 +0000 (Thu, 16 Feb 2012) $
6# SVN revision $Rev: 234 $
7# Last update by $Author: kdeugau $
8###
[175]9# Copyright (C) 2008-2011 - Kris Deugau <kdeugau@deepnet.cx>
[2]10
11package DNSDB;
12
13use strict;
14use warnings;
15use Exporter;
16use DBI;
[33]17use Net::DNS;
[65]18use Crypt::PasswdMD5;
[198]19use Net::SMTP;
[226]20use NetAddr::IP qw(:lower);
[198]21use POSIX;
[2]22use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
23
[200]24$VERSION = 0.1; ##VERSION##
[2]25@ISA = qw(Exporter);
26@EXPORT_OK = qw(
[67]27 &initGlobals
28 &initPermissions &getPermissions &changePermissions &comparePermissions
[112]29 &changeGroup
[128]30 &loadConfig &connectDB &finish
[91]31 &addDomain &delDomain &domainName &domainID
[22]32 &addGroup &delGroup &getChildren &groupName
[83]33 &addUser &updateUser &delUser &userFullName &userStatus &getUserData
[91]34 &getSOA &getRecLine &getDomRecs &getRecCount
[22]35 &addRec &updateRec &delRec
[225]36 &getTypelist
37 &getParents
[117]38 &isParent
[34]39 &domStatus &importAXFR
[103]40 &export
[197]41 &mailNotify
[128]42 %typemap %reverse_typemap %config
[66]43 %permissions @permtypes $permlist
[2]44 );
45
46@EXPORT = (); # Export nothing by default.
47%EXPORT_TAGS = ( ALL => [qw(
[67]48 &initGlobals
49 &initPermissions &getPermissions &changePermissions &comparePermissions
[112]50 &changeGroup
[128]51 &loadConfig &connectDB &finish
[91]52 &addDomain &delDomain &domainName &domainID
[22]53 &addGroup &delGroup &getChildren &groupName
[83]54 &addUser &updateUser &delUser &userFullName &userStatus &getUserData
[91]55 &getSOA &getRecLine &getDomRecs &getRecCount
[22]56 &addRec &updateRec &delRec
[225]57 &getTypelist
58 &getParents
[117]59 &isParent
[34]60 &domStatus &importAXFR
[103]61 &export
[197]62 &mailNotify
[128]63 %typemap %reverse_typemap %config
[66]64 %permissions @permtypes $permlist
[2]65 )]
66 );
67
68our $group = 1;
69our $errstr = '';
70
71# Halfway sane defaults for SOA, TTL, etc.
[101]72# serial defaults to 0 for convenience.
73# value will be either YYYYMMDDNN for BIND/etc, or auto-internal for tinydns
[2]74our %def = qw (
75 contact hostmaster.DOMAIN
76 prins ns1.myserver.com
[101]77 serial 0
[2]78 soattl 86400
79 refresh 10800
80 retry 3600
81 expire 604800
82 minttl 10800
83 ttl 10800
84);
85
[66]86# Arguably defined wholly in the db, but little reason to change without supporting code changes
87our @permtypes = qw (
88 group_edit group_create group_delete
89 user_edit user_create user_delete
90 domain_edit domain_create domain_delete
91 record_edit record_create record_delete
92 self_edit admin
93);
94our $permlist = join(',',@permtypes);
95
[2]96# DNS record type map and reverse map.
97# loaded from the database, from http://www.iana.org/assignments/dns-parameters
98our %typemap;
99our %reverse_typemap;
100
[65]101our %permissions;
[55]102
[128]103# Prepopulate a basic config. Note some of these *will* cause errors if left unset.
[195]104# note: add appropriate stanzas in loadConfig to parse these
[128]105our %config = (
106 # Database connection info
107 dbname => 'dnsdb',
108 dbuser => 'dnsdb',
109 dbpass => 'secret',
110 dbhost => '',
111
112 # Email notice settings
113 mailhost => 'smtp.example.com',
[195]114 mailnotify => 'dnsdb@example.com', # to
115 mailsender => 'dnsdb@example.com', # from
[128]116 mailname => 'DNS Administration',
[195]117 orgname => 'Example Corp',
118 domain => 'example.com',
[128]119
120 # Template directory
121 templatedir => 'templates/',
122# fmeh. this is a real web path, not a logical internal one. hm..
[163]123# cssdir => 'templates/',
[216]124 sessiondir => 'session/',
[163]125
126 # Session params
[195]127 timeout => '3600', # 1 hour default
128
129 # Other miscellanea
130 log_failures => 1, # log all evarthing by default
[201]131 perpage => 15,
[128]132 );
133
[228]134## (Semi)private variables
135# Hash of functions for validating record types. Filled in initGlobals() since
136# it relies on visibility flags from the rectypes table in the DB
137my %validators;
[128]138
[228]139
[2]140##
[225]141## utility functions
[224]142# _rectable()
143# Takes default+rdns flags, returns appropriate table name
144sub _rectable {
145 my $def = shift;
146 my $rev = shift;
147
148 return 'records' if $def ne 'y';
149 return 'default_records' if $rev ne 'y';
150 return 'default_rev_records';
151} # end _rectable()
152
153# _recparent()
154# Takes default+rdns flags, returns appropriate parent-id column name
155sub _recparent {
156 my $def = shift;
157 my $rev = shift;
158
159 return 'group_id' if $def eq 'y';
160 return 'rdns_id' if $rev eq 'y';
161 return 'domain_id';
162} # end _recparent()
163
[226]164# Check an IP to be added in a reverse zone to see if it's really in the requested parent.
165# Takes a database handle, default and reverse flags, IP (fragment) to check, parent zone ID,
166# and a reference to a NetAddr::IP object (also used to pass back a fully-reconstructed IP for
167# database insertion)
168sub _ipparent {
169 my $dbh = shift;
170 my $defrec = shift;
171 my $revrec = shift;
172 my $val = shift;
173 my $id = shift;
174 my $addr = shift;
[224]175
[232]176 return if $revrec ne 'y'; # this sub not useful in forward zones
177
178 $$addr = NetAddr::IP->new($$val); #necessary?
179
[226]180 # subsub to split, reverse, and overlay an IP fragment on a netblock
181 sub __rev_overlay {
182 my $splitme = shift; # ':' or '.', m'lud?
183 my $parnet = shift;
184 my $val = shift;
185 my $addr = shift;
186
187 my $joinme = $splitme;
188 $splitme = '\.' if $splitme eq '.';
[232]189 my @working = reverse(split($splitme, $parnet->addr));
190 my @parts = reverse(split($splitme, $$val));
[226]191 for (my $i = 0; $i <= $#parts; $i++) {
192 $working[$i] = $parts[$i];
193 }
[232]194 my $checkme = NetAddr::IP->new(join($joinme, reverse(@working))) or return 0;
195 return 0 unless $checkme->within($parnet);
[226]196 $$addr = $checkme; # force "correct" IP to be recorded.
197 return 1;
198 }
199
200 my ($parstr) = $dbh->selectrow_array("SELECT revnet FROM revzones WHERE rdns_id = ?", undef, ($id));
201 my $parnet = NetAddr::IP->new($parstr);
202
203 # Fail early on v6-in-v4 or v4-in-v6. We're not accepting these ATM.
[232]204 return 0 if $parnet->addr =~ /\./ && $$val =~ /:/;
205 return 0 if $parnet->addr =~ /:/ && $$val =~ /\./;
[226]206
[234]207 if ($$addr && $$val =~ /^[\da-fA-F][\da-fA-F:]+[\da-fA-F]$/) {
[232]208 # the only case where NetAddr::IP's acceptance of legitimate IPs is "correct" is for a proper IPv6 address.
209 # the rest we have to restructure before fiddling. *sigh*
210 return 1 if $$addr->within($parnet);
211 } else {
212 # We don't have a complete IP in $$val (yet)
213 if ($parnet->addr =~ /:/) {
214 $$val =~ s/^:+//; # gotta strip'em all...
[226]215 return __rev_overlay(':', $parnet, $val, $addr);
216 }
[232]217 if ($parnet->addr =~ /\./) {
218 $$val =~ s/^\.+//;
219 return __rev_overlay('.', $parnet, $val, $addr);
220 }
[226]221 # should be impossible to get here...
222 }
223 # ... and here.
224 # can't do nuttin' in forward zones
225} # end _ipparent()
226
[232]227# A little different than _ipparent above; this tries to *find* the parent zone of a hostname
228sub _hostparent {
229 my $dbh = shift;
230 my $hname = shift;
231
232 my @hostbits = split /\./, $hname;
233 my $sth = $dbh->prepare("SELECT count(*),domain_id FROM domains WHERE domain = ? GROUP BY domain_id");
234 foreach (@hostbits) {
235 $sth->execute($hname);
236 my ($found, $parid) = $sth->fetchrow_array;
237 if ($found) {
238 return $parid;
239 }
240 $hname =~ s/^$_\.//;
241 }
242} # end _hostparent()
[228]243
[224]244##
[228]245## Record validation subs.
246##
247
248# A record
249sub _validate_1 {
[229]250 my $dbh = shift;
251
[230]252 my %args = @_;
[229]253
[230]254 return ('FAIL', 'Reverse zones cannot contain A records') if $args{revrec} eq 'y';
[229]255
256 # Coerce all hostnames to end in ".DOMAIN" for group/default records,
257 # or the intended parent domain for live records.
[230]258 my $pname = ($args{defrec} eq 'y' ? 'DOMAIN' : domainName($dbh,$args{id}));
259 ${$args{host}} =~ s/\.*$/\.$pname/ if ${$args{host}} !~ /$pname$/;
[229]260
261 # Check IP is well-formed, and that it's a v4 address
[234]262 # Fail on "compact" IPv4 variants, because they are not consistent and predictable.
[232]263 return ('FAIL',"$typemap{${$args{rectype}}} record must be a valid IPv4 address")
[234]264 unless ${$args{val}} =~ /^\d+\.\d+\.\d+\.\d+$/;
265 return ('FAIL',"$typemap{${$args{rectype}}} record must be a valid IPv4 address")
[230]266 unless $args{addr} && !$args{addr}->{isv6};
[229]267 # coerce IP/value to normalized form for storage
[230]268 ${$args{val}} = $args{addr}->addr;
[229]269
[228]270 return ('OK','OK');
271} # done A record
272
273# NS record
274sub _validate_2 {
[230]275 my $dbh = shift;
276
277 my %args = @_;
278
279 # Coerce the hostname to "DOMAIN" for forward default records, "ZONE" for reverse default records,
280 # or the intended parent zone for live records.
281##fixme: allow for delegating <subdomain>.DOMAIN?
282 if ($args{revrec} eq 'y') {
283 my $pname = ($args{defrec} eq 'y' ? 'ZONE' : revName($dbh,$args{id}));
284 ${$args{host}} = $pname if ${$args{host}} ne $pname;
285 } else {
286 my $pname = ($args{defrec} eq 'y' ? 'DOMAIN' : domainName($dbh,$args{id}));
287 ${$args{host}} = $pname if ${$args{host}} ne $pname;
288 }
289
290# Let this lie for now. Needs more magic.
291# # Check IP is well-formed, and that it's a v4 address
292# return ('FAIL',"A record must be a valid IPv4 address")
293# unless $addr && !$addr->{isv6};
294# # coerce IP/value to normalized form for storage
295# $$val = $addr->addr;
296
[228]297 return ('OK','OK');
298} # done NS record
299
300# CNAME record
301sub _validate_5 {
[230]302 my $dbh = shift;
303
304 my %args = @_;
305
306# Not really true, but these are only useful for delegating smaller-than-/24 IP blocks.
307# This is fundamentally a messy operation and should really just be taken care of by the
308# export process, not manual maintenance of the necessary records.
309 return ('FAIL', 'Reverse zones cannot contain CNAME records') if $args{revrec} eq 'y';
310
311 # Coerce all hostnames to end in ".DOMAIN" for group/default records,
312 # or the intended parent domain for live records.
313 my $pname = ($args{defrec} eq 'y' ? 'DOMAIN' : domainName($dbh,$args{id}));
314 ${$args{host}} =~ s/\.*$/\.$pname/ if ${$args{host}} !~ /$pname$/;
315
[228]316 return ('OK','OK');
317} # done CNAME record
318
319# SOA record
320sub _validate_6 {
[230]321 # Smart monkeys won't stick their fingers in here; we have
322 # separate dedicated routines to deal with SOA records.
[228]323 return ('OK','OK');
324} # done SOA record
325
326# PTR record
327sub _validate_12 {
[232]328 my $dbh = shift;
329
330 my %args = @_;
331
332 if ($args{revrec} eq 'y') {
333 if ($args{defrec} eq 'n') {
334 return ('FAIL', "IP or IP fragment ${$args{val}} is not within ".revName($dbh, $args{id}))
335 unless _ipparent($dbh, $args{defrec}, $args{revrec}, $args{val}, $args{id}, \$args{addr});
336 ${$args{val}} = $args{addr}->addr;
337 } else {
[234]338 if (${$args{val}} =~ /\./) {
339 # looks like a v4 or fragment
340 if (${$args{val}} =~ /^\d+\.\d+\.\d+\.\d+$/) {
341 # woo! a complete IP! validate it and normalize, or fail.
342 $args{addr} = NetAddr::IP->new(${$args{val}})
343 or return ('FAIL', "IP/value looks like IPv4 but isn't valid");
344 ${$args{val}} = $args{addr}->addr;
345 } else {
346 ${$args{val}} =~ s/^\.*/ZONE./;
347 }
348 } elsif (${$args{val}} =~ /[a-f:]/) {
349 # looks like a v6 or fragment
350 ${$args{val}} =~ s/^:*/ZONE::/ if !$args{addr};
351 if ($args{addr}) {
352 if ($args{addr}->addr =~ /^0/) {
353 ${$args{val}} =~ s/^:*/ZONE::/;
354 } else {
355 ${$args{val}} = $args{addr}->addr;
356 }
357 }
358 } else {
359 # bare number (probably). These could be v4 or v6, so we'll
360 # expand on these on creation of a reverse zone.
361 ${$args{val}} = "ZONE,${$args{val}}";
362 }
363 ${$args{host}} =~ s/\.*$/\.$config{domain}/ if ${$args{host}} !~ /$config{domain}$/;
[232]364 }
365
366# Multiple PTR records do NOT generally do what most people believe they do,
367# and tend to fail in the most awkward way possible. Check and warn.
368# We use $val instead of $addr->addr since we may be in a defrec, and may have eg "ZONE::42" or "ZONE.12"
369 my ($ptrcount) = $dbh->selectrow_array("SELECT count(*) FROM "._rectable($args{defrec},$args{revrec}).
370 " WHERE val = ?", undef, ${$args{val}});
371 return ('WARN', "PTR record for ${$args{val}} already exists; adding another will probably not do what you want")
372 if $ptrcount;
373 } else {
374 # Not absolutely true but only useful if you hack things up for sub-/24 v4 reverse delegations
375 # Simpler to just create the reverse zone and grant access for the customer to edit it, and create direct
376 # PTR records on export
377 return ('FAIL',"Forward zones cannot contain PTR records");
378 }
379
[228]380 return ('OK','OK');
381} # done PTR record
382
383# MX record
384sub _validate_15 {
[230]385 my $dbh = shift;
386
387 my %args = @_;
388
389# Not absolutely true but WTF use is an MX record for a reverse zone?
390 return ('FAIL', 'Reverse zones cannot contain MX records') if $args{revrec} eq 'y';
391
392 return ('FAIL', "Distance is required for MX records") unless defined(${$args{dist}});
393 ${$args{dist}} =~ s/\s*//g;
394 return ('FAIL',"Distance is required, and must be numeric") unless ${$args{dist}} =~ /^\d+$/;
395
396 ${$args{fields}} = "distance,";
397 push @{$args{vallist}}, ${$args{dist}};
398
399 # Coerce all hostnames to end in ".DOMAIN" for group/default records,
400 # or the intended parent domain for live records.
401 my $pname = ($args{defrec} eq 'y' ? 'DOMAIN' : domainName($dbh,$args{id}));
402 ${$args{host}} =~ s/\.*$/\.$pname/ if ${$args{host}} !~ /$pname$/;
403
[228]404 return ('OK','OK');
405} # done MX record
406
407# TXT record
408sub _validate_16 {
[231]409 # Could arguably put a WARN return here on very long (>512) records
[228]410 return ('OK','OK');
411} # done TXT record
412
413# RP record
414sub _validate_17 {
[231]415 # Probably have to validate these some day
[228]416 return ('OK','OK');
417} # done RP record
418
419# AAAA record
420sub _validate_28 {
[229]421 my $dbh = shift;
422
[230]423 my %args = @_;
[229]424
[230]425 return ('FAIL', 'Reverse zones cannot contain AAAA records') if $args{revrec} eq 'y';
[229]426
427 # Coerce all hostnames to end in ".DOMAIN" for group/default records,
428 # or the intended parent domain for live records.
[230]429 my $pname = ($args{defrec} eq 'y' ? 'DOMAIN' : domainName($dbh,$args{id}));
430 ${$args{host}} =~ s/\.*$/\.$pname/ if ${$args{host}} !~ /$pname$/;
[229]431
432 # Check IP is well-formed, and that it's a v6 address
[232]433 return ('FAIL',"$typemap{${$args{rectype}}} record must be a valid IPv6 address")
[230]434 unless $args{addr} && $args{addr}->{isv6};
[229]435 # coerce IP/value to normalized form for storage
[230]436 ${$args{val}} = $args{addr}->addr;
[229]437
[228]438 return ('OK','OK');
439} # done AAAA record
440
441# SRV record
442sub _validate_33 {
[231]443 my $dbh = shift;
444
445 my %args = @_;
446
447# Not absolutely true but WTF use is an SRV record for a reverse zone?
448 return ('FAIL', 'Reverse zones cannot contain SRV records') if $args{revrec} eq 'y';
449
450 return ('FAIL', "Distance is required for SRV records") unless defined(${$args{dist}});
451 ${$args{dist}} =~ s/\s*//g;
452 return ('FAIL',"Distance is required, and must be numeric") unless ${$args{dist}} =~ /^\d+$/;
453
454 return ('FAIL',"SRV records must begin with _service._protocol [${$args{host}}]")
455 unless ${$args{host}} =~ /^_[A-Za-z]+\._[A-Za-z]+\.[a-zA-Z0-9-]+/;
456 return ('FAIL',"Port and weight are required for SRV records")
457 unless defined(${$args{weight}}) && defined(${$args{port}});
458 ${$args{weight}} =~ s/\s*//g;
459 ${$args{port}} =~ s/\s*//g;
460
461 return ('FAIL',"Port and weight are required, and must be numeric")
462 unless ${$args{weight}} =~ /^\d+$/ && ${$args{port}} =~ /^\d+$/;
463
464 ${$args{fields}} = "distance,weight,port,";
465 push @{$args{vallist}}, (${$args{dist}}, ${$args{weight}}, ${$args{port}});
466
467 # Coerce all hostnames to end in ".DOMAIN" for group/default records,
468 # or the intended parent domain for live records.
469 my $pname = ($args{defrec} eq 'y' ? 'DOMAIN' : domainName($dbh,$args{id}));
470 ${$args{host}} =~ s/\.*$/\.$pname/ if ${$args{host}} !~ /$pname$/;
471
[228]472 return ('OK','OK');
473} # done SRV record
474
475# Now the custom types
476
[232]477# A+PTR record. With a very little bit of magic we can also use this sub to validate AAAA+PTR. Whee!
[228]478sub _validate_65280 {
[232]479 my $dbh = shift;
480
481 my %args = @_;
482
483 my $code = 'OK';
484 my $msg = 'OK';
485
486 if ($args{defrec} eq 'n') {
487 # live record; revrec determines whether we validate the PTR or A component first.
[233]488
[232]489 if ($args{revrec} eq 'y') {
490 ($code,$msg) = _validate_12($dbh, %args);
491 return ($code,$msg) if $code eq 'FAIL';
492
493 # Check if the reqested domain exists. If not, coerce the type down to PTR and warn.
494 if (!(${$args{domid}} = _hostparent($dbh, ${$args{host}}))) {
495 my $addmsg = "Record added as PTR instead of $typemap{${$args{rectype}}}; domain not found for ${$args{host}}";
496 $msg .= "\n$addmsg" if $code eq 'WARN';
497 $msg = $addmsg if $code eq 'OK';
498 ${$args{rectype}} = $reverse_typemap{PTR};
499 return ('WARN', $msg);
500 }
501
502 } else {
503 ($code,$msg) = _validate_1($dbh, %args) if ${$args{rectype}} == 65280;
504 ($code,$msg) = _validate_28($dbh, %args) if ${$args{rectype}} == 65281;
505 return ($code,$msg) if $code eq 'FAIL';
506
507 # Check if the requested reverse zone exists - note, an IP fragment won't
508 # work here since we don't *know* which parent to put it in.
[233]509 # ${$args{val}} has been validated as a valid IP by now, in one of the above calls.
[232]510 my ($revid) = $dbh->selectrow_array("SELECT rdns_id FROM revzones WHERE revnet >> ?".
511 " ORDER BY masklen(revnet) DESC", undef, (${$args{val}}));
512 if (!$revid) {
513 $msg = "Record added as ".(${$args{rectype}} == 65280 ? 'A' : 'AAAA').
514 " instead of $typemap{${$args{rectype}}}; reverse zone not found for ${$args{val}}";
515 ${$args{rectype}} = (${$args{rectype}} == 65280 ? $reverse_typemap{A} : $reverse_typemap{AAAA});
516 return ('WARN', $msg);
517 }
518
519 # Check for duplicate PTRs. Note we don't have to play games with $code and $msg, because
520 # by definition there can't be duplicate PTRs if the reverse zone isn't managed here.
521 my ($ptrcount) = $dbh->selectrow_array("SELECT count(*) FROM "._rectable($args{defrec},$args{revrec}).
522 " WHERE val = ?", undef, ${$args{val}});
523 if ($ptrcount) {
524 $msg = "PTR record for ${$args{val}} already exists; adding another will probably not do what you want";
525 $code = 'WARN';
526 }
527
528 ${$args{fields}} .= "rdns_id,";
529 push @{$args{vallist}}, $revid;
530 }
531
[233]532 } else { # defrec eq 'y'
533 if ($args{revrec} eq 'y') {
534 ($code,$msg) = _validate_12($dbh, %args);
535 return ($code,$msg) if $code eq 'FAIL';
536 if (${$args{rectype}} == 65280) {
537 return ('FAIL',"A+PTR record must be a valid IPv4 address or fragment")
538 if ${$args{val}} =~ /:/;
[234]539 ${$args{val}} =~ s/^ZONE,/ZONE./; # Clean up after uncertain IP-fragment-type from _validate_12
[233]540 } elsif (${$args{rectype}} == 65281) {
541 return ('FAIL',"AAAA+PTR record must be a valid IPv6 address or fragment")
542 if ${$args{val}} =~ /\./;
[234]543 ${$args{val}} =~ s/^ZONE,/ZONE::/; # Clean up after uncertain IP-fragment-type from _validate_12
[233]544 }
545 } else {
546 # This is easy. I also can't see a real use-case for A/AAAA+PTR in *all* forward
547 # domains, since you wouldn't be able to substitute both domain and reverse zone
548 # sanely, and you'd end up with guaranteed over-replicated PTR records that would
549 # confuse the hell out of pretty much anything that uses them.
[234]550##fixme: make this a config flag?
[233]551 return ('FAIL', "$typemap{${$args{rectype}}} records not allowed in default domains");
552 }
[232]553 }
554
555 return ($code, $msg);
[228]556} # done A+PTR record
557
558# AAAA+PTR record
[232]559# A+PTR above has been magicked to handle AAAA+PTR as well.
[228]560sub _validate_65281 {
[232]561 return _validate_65280(@_);
[228]562} # done AAAA+PTR record
563
564# PTR template record
565sub _validate_65282 {
566 return ('OK','OK');
567} # done PTR template record
568
569# A+PTR template record
570sub _validate_65283 {
571 return ('OK','OK');
572} # done AAAA+PTR template record
573
574# AAAA+PTR template record
575sub _validate_65284 {
576 return ('OK','OK');
577} # done AAAA+PTR template record
578
579
580
581##
[2]582## Initialization and cleanup subs
583##
584
[55]585
[128]586## DNSDB::loadConfig()
587# Load the minimum required initial state (DB connect info) from a config file
588# Load misc other bits while we're at it.
589# Takes an optional basename and config path to look for
590# Populates the %config and %def hashes
591sub loadConfig {
592 my $basename = shift || ''; # this will work OK
[218]593##fixme $basename isn't doing what I think I thought I was trying to do.
[128]594
595 my $deferr = ''; # place to put error from default config file in case we can't find either one
596
[219]597 my $configroot = "/etc/dnsdb"; ##CFG_LEAF##
[128]598 $configroot = '' if $basename =~ m|^/|;
599 $basename .= ".conf" if $basename !~ /\.conf$/;
600 my $defconfig = "$configroot/dnsdb.conf";
601 my $siteconfig = "$configroot/$basename";
602
603 # System defaults
[131]604 __cfgload("$defconfig") or $deferr = $errstr;
[128]605
[131]606 # Per-site-ish settings.
607 if ($basename ne '.conf') {
608 unless (__cfgload("$siteconfig")) {
609 $errstr = ($deferr ? "Error opening default config file $defconfig: $deferr\n" : '').
[128]610 "Error opening site config file $siteconfig";
[131]611 return;
612 }
[128]613 }
614
[195]615 # Munge log_failures.
616 if ($config{log_failures} ne '1' && $config{log_failures} ne '0') {
617 # true/false, on/off, yes/no all valid.
618 if ($config{log_failures} =~ /^(?:true|false|on|off|yes|no)$/) {
619 if ($config{log_failures} =~ /(?:true|on|yes)/) {
620 $config{log_failures} = 1;
621 } else {
622 $config{log_failures} = 0;
623 }
624 } else {
625 $errstr = "Bad log_failures setting $config{log_failures}";
626 $config{log_failures} = 1;
627 # Bad setting shouldn't be fatal.
628 # return 2;
629 }
630 }
631
[128]632 # All good, clear the error and go home.
633 $errstr = '';
634 return 1;
635} # end loadConfig()
636
637
638## DNSDB::__cfgload()
639# Private sub to parse a config file and load it into %config
640# Takes a file handle on an open config file
641sub __cfgload {
642 $errstr = '';
643 my $cfgfile = shift;
[131]644
[128]645 if (open CFG, "<$cfgfile") {
646 while (<CFG>) {
647 chomp;
648 s/^\s*//;
649 next if /^#/;
650 next if /^$/;
651# hmm. more complex bits in this file might require [heading] headers, maybe?
652# $mode = $1 if /^\[(a-z)+]/;
653 # DB connect info
654 $config{dbname} = $1 if /^dbname\s*=\s*([a-z0-9_.-]+)/i;
655 $config{dbuser} = $1 if /^dbuser\s*=\s*([a-z0-9_.-]+)/i;
656 $config{dbpass} = $1 if /^dbpass\s*=\s*([a-z0-9_.-]+)/i;
657 $config{dbhost} = $1 if /^dbhost\s*=\s*([a-z0-9_.-]+)/i;
658 # SOA defaults
659 $def{contact} = $1 if /^contact\s*=\s*([a-z0-9_.-]+)/i;
660 $def{prins} = $1 if /^prins\s*=\s*([a-z0-9_.-]+)/i;
[201]661 $def{soattl} = $1 if /^soattl\s*=\s*(\d+)/i;
662 $def{refresh} = $1 if /^refresh\s*=\s*(\d+)/i;
663 $def{retry} = $1 if /^retry\s*=\s*(\d+)/i;
664 $def{expire} = $1 if /^expire\s*=\s*(\d+)/i;
665 $def{minttl} = $1 if /^minttl\s*=\s*(\d+)/i;
666 $def{ttl} = $1 if /^ttl\s*=\s*(\d+)/i;
[128]667 # Mail settings
668 $config{mailhost} = $1 if /^mailhost\s*=\s*([a-z0-9_.-]+)/i;
[198]669 $config{mailnotify} = $1 if /^mailnotify\s*=\s*([a-z0-9_.\@-]+)/i;
670 $config{mailsender} = $1 if /^mailsender\s*=\s*([a-z0-9_.\@-]+)/i;
[128]671 $config{mailname} = $1 if /^mailname\s*=\s*([a-z0-9\s_.-]+)/i;
[195]672 $config{orgname} = $1 if /^orgname\s*=\s*([a-z0-9\s_.,'-]+)/i;
673 $config{domain} = $1 if /^domain\s*=\s*([a-z0-9_.-]+)/i;
[163]674 # session - note this is fed directly to CGI::Session
[216]675 $config{timeout} = $1 if /^[tT][iI][mM][eE][oO][uU][tT]\s*=\s*(\d+[smhdwMy]?)/;
676 $config{sessiondir} = $1 if m{^sessiondir\s*=\s*([a-z0-9/_.-]+)}i;
[201]677 # misc
[195]678 $config{log_failures} = $1 if /^log_failures\s*=\s*([a-z01]+)/i;
[201]679 $config{perpage} = $1 if /^perpage\s*=\s*(\d+)/i;
[128]680 }
681 close CFG;
682 } else {
683 $errstr = $!;
684 return;
685 }
686 return 1;
687} # end __cfgload()
688
689
[2]690## DNSDB::connectDB()
691# Creates connection to DNS database.
692# Requires the database name, username, and password.
693# Returns a handle to the db.
694# Set up for a PostgreSQL db; could be any transactional DBMS with the
695# right changes.
696sub connectDB {
697 $errstr = '';
[15]698 my $dbname = shift;
699 my $user = shift;
700 my $pass = shift;
[2]701 my $dbh;
702 my $DSN = "DBI:Pg:dbname=$dbname";
703
704 my $host = shift;
705 $DSN .= ";host=$host" if $host;
706
707# Note that we want to autocommit by default, and we will turn it off locally as necessary.
708# We may not want to print gobbledygook errors; YMMV. Have to ponder that further.
709 $dbh = DBI->connect($DSN, $user, $pass, {
710 AutoCommit => 1,
711 PrintError => 0
712 })
713 or return (undef, $DBI::errstr) if(!$dbh);
714
[212]715##fixme: initialize the DB if we can't find the table (since, by definition, there's
716# nothing there if we can't select from it...)
717 my $tblsth = $dbh->prepare("SELECT count(*) FROM pg_catalog.pg_class WHERE relkind='r' AND relname=?");
718 my ($tblcount) = $dbh->selectrow_array($tblsth, undef, ('misc'));
719 return (undef,$DBI::errstr) if $dbh->err;
720
721#if ($tblcount == 0) {
722# # create tables one at a time, checking for each.
723# return (undef, "check table misc missing");
724#}
725
726
727# Return here if we can't select.
728# This should retrieve the dbversion key.
729 my $sth = $dbh->prepare("SELECT key,value FROM misc WHERE misc_id=1");
[2]730 $sth->execute();
731 return (undef,$DBI::errstr) if ($sth->err);
732
[212]733##fixme: do stuff to the DB on version mismatch
734# x.y series should upgrade on $DNSDB::VERSION > misc(key=>version)
735# DB should be downward-compatible; column defaults should give sane (if possibly
736# useless-and-needs-help) values in columns an older software stack doesn't know about.
737
[2]738# See if the select returned anything (or null data). This should
739# succeed if the select executed, but...
740 $sth->fetchrow();
741 return (undef,$DBI::errstr) if ($sth->err);
742
743 $sth->finish;
744
745# If we get here, we should be OK.
746 return ($dbh,"DB connection OK");
747} # end connectDB
748
749
750## DNSDB::finish()
751# Cleans up after database handles and so on.
752# Requires a database handle
753sub finish {
754 my $dbh = $_[0];
755 $dbh->disconnect;
756} # end finish
757
758
759## DNSDB::initGlobals()
760# Initialize global variables
761# NB: this does NOT include web-specific session variables!
762# Requires a database handle
763sub initGlobals {
764 my $dbh = shift;
765
[208]766# load record types from database
[228]767 my $sth = $dbh->prepare("SELECT val,name,stdflag FROM rectypes");
[2]768 $sth->execute;
[228]769 while (my ($recval,$recname,$stdflag) = $sth->fetchrow_array()) {
[2]770 $typemap{$recval} = $recname;
771 $reverse_typemap{$recname} = $recval;
[228]772 # now we fill the record validation function hash
773 if ($stdflag < 5) {
774 my $fn = "_validate_$recval";
775 $validators{$recval} = \&$fn;
776 } else {
777 my $fn = "sub { return ('FAIL','Type $recval ($recname) not supported'); }";
778 $validators{$recval} = eval $fn;
779 }
[2]780 }
781} # end initGlobals
782
783
[65]784## DNSDB::initPermissions()
785# Set up permissions global
786# Takes database handle and UID
787sub initPermissions {
788 my $dbh = shift;
789 my $uid = shift;
790
791# %permissions = $(getPermissions($dbh,'user',$uid));
792 getPermissions($dbh, 'user', $uid, \%permissions);
793
794} # end initPermissions()
795
796
797## DNSDB::getPermissions()
798# Get permissions from DB
799# Requires DB handle, group or user flag, ID, and hashref.
800sub getPermissions {
801 my $dbh = shift;
802 my $type = shift;
803 my $id = shift;
804 my $hash = shift;
805
806 my $sql = qq(
807 SELECT
808 p.admin,p.self_edit,
809 p.group_create,p.group_edit,p.group_delete,
810 p.user_create,p.user_edit,p.user_delete,
811 p.domain_create,p.domain_edit,p.domain_delete,
812 p.record_create,p.record_edit,p.record_delete
813 FROM permissions p
814 );
815 if ($type eq 'group') {
816 $sql .= qq(
817 JOIN groups g ON g.permission_id=p.permission_id
818 WHERE g.group_id=?
819 );
820 } else {
821 $sql .= qq(
822 JOIN users u ON u.permission_id=p.permission_id
823 WHERE u.user_id=?
824 );
825 }
826
827 my $sth = $dbh->prepare($sql);
828
829 $sth->execute($id) or die "argh: ".$sth->errstr;
830
831# my $permref = $sth->fetchrow_hashref;
832# return $permref;
833# $hash = $permref;
834# Eww. Need to learn how to forcibly drop a hashref onto an existing hash.
835 ($hash->{admin},$hash->{self_edit},
836 $hash->{group_create},$hash->{group_edit},$hash->{group_delete},
837 $hash->{user_create},$hash->{user_edit},$hash->{user_delete},
838 $hash->{domain_create},$hash->{domain_edit},$hash->{domain_delete},
839 $hash->{record_create},$hash->{record_edit},$hash->{record_delete})
840 = $sth->fetchrow_array;
841
842} # end getPermissions()
843
844
845## DNSDB::changePermissions()
846# Update an ACL entry
847# Takes a db handle, type, owner-id, and hashref for the changed permissions.
848sub changePermissions {
849 my $dbh = shift;
850 my $type = shift;
851 my $id = shift;
852 my $newperms = shift;
[87]853 my $inherit = shift || 0;
[65]854
[78]855 my $failmsg = '';
[66]856
[87]857 # see if we're switching from inherited to custom. for bonus points,
858 # snag the permid and parent permid anyway, since we'll need the permid
859 # to set/alter custom perms, and both if we're switching from custom to
860 # inherited.
861 my $sth = $dbh->prepare("SELECT (u.permission_id=g.permission_id) AS was_inherited,u.permission_id,g.permission_id".
[65]862 " FROM ".($type eq 'user' ? 'users' : 'groups')." u ".
[66]863 " JOIN groups g ON u.".($type eq 'user' ? '' : 'parent_')."group_id=g.group_id ".
[65]864 " WHERE u.".($type eq 'user' ? 'user' : 'group')."_id=?");
865 $sth->execute($id);
866
[87]867 my ($wasinherited,$permid,$parpermid) = $sth->fetchrow_array;
[66]868
[78]869# hack phtoui
870# group id 1 is "special" in that it's it's own parent (err... possibly.)
871# may make its parent id 0 which doesn't exist, and as a bonus is Perl-false.
872 $wasinherited = 0 if ($type eq 'group' && $id == 1);
873
[66]874 local $dbh->{AutoCommit} = 0;
875 local $dbh->{RaiseError} = 1;
876
877 # Wrap all the SQL in a transaction
878 eval {
[87]879 if ($inherit) {
880
881 $dbh->do("UPDATE ".($type eq 'user' ? 'users' : 'groups')." SET inherit_perm='t',permission_id=? ".
882 "WHERE ".($type eq 'user' ? 'user' : 'group')."_id=?", undef, ($parpermid, $id) );
883 $dbh->do("DELETE FROM permissions WHERE permission_id=?", undef, ($permid) );
884
885 } else {
886
887 if ($wasinherited) { # munge new permission entry in if we're switching from inherited perms
[66]888##fixme: need to add semirecursive bit to properly munge inherited permission ID on subgroups and users
[87]889# ... if'n'when we have groups with fully inherited permissions.
890 # SQL is coo
891 $dbh->do("INSERT INTO permissions ($permlist,".($type eq 'user' ? 'user' : 'group')."_id) ".
892 "SELECT $permlist,? FROM permissions WHERE permission_id=?", undef, ($id,$permid) );
893 ($permid) = $dbh->selectrow_array("SELECT permission_id FROM permissions ".
894 "WHERE ".($type eq 'user' ? 'user' : 'group')."_id=?", undef, ($id) );
895 $dbh->do("UPDATE ".($type eq 'user' ? 'users' : 'groups')." SET inherit_perm='f',permission_id=? ".
896 "WHERE ".($type eq 'user' ? 'user' : 'group')."_id=?", undef, ($permid, $id) );
[66]897 }
[78]898
[87]899 # and now set the permissions we were passed
900 foreach (@permtypes) {
901 if (defined ($newperms->{$_})) {
902 $dbh->do("UPDATE permissions SET $_=? WHERE permission_id=?", undef, ($newperms->{$_},$permid) );
903 }
904 }
905
906 } # (inherited->)? custom
907
[66]908 $dbh->commit;
909 }; # end eval
910 if ($@) {
911 my $msg = $@;
912 eval { $dbh->rollback; };
[87]913 return ('FAIL',"$failmsg: $msg ($permid)");
[66]914 } else {
915 return ('OK',$permid);
916 }
917
[65]918} # end changePermissions()
919
920
[67]921## DNSDB::comparePermissions()
922# Compare two permission hashes
923# Returns '>', '<', '=', '!'
924sub comparePermissions {
925 my $p1 = shift;
926 my $p2 = shift;
927
928 my $retval = '='; # assume equality until proven otherwise
929
930 no warnings "uninitialized";
931
932 foreach (@permtypes) {
933 next if $p1->{$_} == $p2->{$_}; # equal is good
934 if ($p1->{$_} && !$p2->{$_}) {
935 if ($retval eq '<') { # if we've already found an unequal pair where
936 $retval = '!'; # $p2 has more access, and we now find a pair
937 last; # where $p1 has more access, the overall access
938 } # is neither greater or lesser, it's unequal.
939 $retval = '>';
940 }
941 if (!$p1->{$_} && $p2->{$_}) {
942 if ($retval eq '>') { # if we've already found an unequal pair where
943 $retval = '!'; # $p1 has more access, and we now find a pair
944 last; # where $p2 has more access, the overall access
945 } # is neither greater or lesser, it's unequal.
946 $retval = '<';
947 }
948 }
949 return $retval;
950} # end comparePermissions()
951
952
[112]953## DNSDB::changeGroup()
954# Change group ID of an entity
955# Takes a database handle, entity type, entity ID, and new group ID
956sub changeGroup {
957 my $dbh = shift;
958 my $type = shift;
959 my $id = shift;
960 my $newgrp = shift;
961
962##fixme: fail on not enough args
963 #return ('FAIL', "Missing
964
965 if ($type eq 'domain') {
966 $dbh->do("UPDATE domains SET group_id=? WHERE domain_id=?", undef, ($newgrp, $id))
967 or return ('FAIL','Group change failed: '.$dbh->errstr);
968 } elsif ($type eq 'user') {
969 $dbh->do("UPDATE users SET group_id=? WHERE user_id=?", undef, ($newgrp, $id))
970 or return ('FAIL','Group change failed: '.$dbh->errstr);
971 } elsif ($type eq 'group') {
972 $dbh->do("UPDATE groups SET parent_group_id=? WHERE group_id=?", undef, ($newgrp, $id))
973 or return ('FAIL','Group change failed: '.$dbh->errstr);
974 }
975 return ('OK','OK');
976} # end changeGroup()
977
978
[55]979## DNSDB::_log()
980# Log an action
981# Internal sub
[192]982# Takes a database handle, domain_id, user_id, group_id, email, name and log entry
[193]983##fixme: convert to trailing hash for user info
984# User info must contain a (user ID OR username)+fullname
[55]985sub _log {
[190]986 my $dbh = shift;
987 my ($domain_id,$user_id,$group_id,$username,$name,$entry) = @_;
988
[193]989##fixme: need better way(s?) to snag userinfo for log entries. don't want to have
990# to pass around yet *another* constant (already passing $dbh, shouldn't need to)
[195]991 my $fullname;
[193]992 if (!$user_id) {
[195]993 ($user_id, $fullname) = $dbh->selectrow_array("SELECT user_id, firstname || ' ' || lastname FROM users".
[193]994 " WHERE username=?", undef, ($username));
995 } elsif (!$username) {
[195]996 ($username, $fullname) = $dbh->selectrow_array("SELECT username, firstname || ' ' || lastname FROM users".
[193]997 " WHERE user_id=?", undef, ($user_id));
[195]998 } else {
999 ($fullname) = $dbh->selectrow_array("SELECT firstname || ' ' || lastname FROM users".
1000 " WHERE user_id=?", undef, ($user_id));
[193]1001 }
1002
1003 $name = $fullname if !$name;
1004
[190]1005##fixme: farm out the actual logging to different subs for file, syslog, internal, etc based on config
1006 $dbh->do("INSERT INTO log (domain_id,user_id,group_id,email,name,entry) VALUES (?,?,?,?,?,?)", undef,
1007 ($domain_id,$user_id,$group_id,$username,$name,$entry));
1008# 123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890
1009# 1 2 3 4 5 6 7
[55]1010} # end _log
1011
1012
[2]1013##
1014## Processing subs
1015##
1016
1017## DNSDB::addDomain()
1018# Add a domain
[190]1019# Takes a database handle, domain name, numeric group, boolean(ish) state (active/inactive),
1020# and user info hash (for logging).
[2]1021# Returns a status code and message
1022sub addDomain {
1023 $errstr = '';
1024 my $dbh = shift;
1025 return ('FAIL',"Need database handle") if !$dbh;
1026 my $domain = shift;
[91]1027 return ('FAIL',"Domain must not be blank") if !$domain;
[2]1028 my $group = shift;
1029 return ('FAIL',"Need group") if !defined($group);
1030 my $state = shift;
1031 return ('FAIL',"Need domain status") if !defined($state);
1032
[190]1033 my %userinfo = @_; # remaining bits.
1034# user ID, username, user full name
1035
[116]1036 $state = 1 if $state =~ /^active$/;
1037 $state = 1 if $state =~ /^on$/;
1038 $state = 0 if $state =~ /^inactive$/;
1039 $state = 0 if $state =~ /^off$/;
1040
1041 return ('FAIL',"Invalid domain status") if $state !~ /^\d+$/;
1042
[190]1043 return ('FAIL', "Invalid characters in domain") if $domain !~ /^[a-zA-Z0-9_.-]+$/;
1044
[38]1045 my $sth = $dbh->prepare("SELECT domain_id FROM domains WHERE domain=?");
[3]1046 my $dom_id;
1047
[38]1048# quick check to start to see if we've already got one
1049 $sth->execute($domain);
1050 ($dom_id) = $sth->fetchrow_array;
1051
1052 return ('FAIL', "Domain already exists") if $dom_id;
1053
[2]1054 # Allow transactions, and raise an exception on errors so we can catch it later.
1055 # Use local to make sure these get "reset" properly on exiting this block
1056 local $dbh->{AutoCommit} = 0;
1057 local $dbh->{RaiseError} = 1;
1058
1059 # Wrap all the SQL in a transaction
1060 eval {
1061 # insert the domain...
[190]1062 $dbh->do("INSERT INTO domains (domain,group_id,status) VALUES (?,?,?)", undef, ($domain, $group, $state));
[2]1063
1064 # get the ID...
[190]1065 ($dom_id) = $dbh->selectrow_array("SELECT domain_id FROM domains WHERE domain=?", undef, ($domain));
[2]1066
[190]1067 _log($dbh, $dom_id, $userinfo{id}, $group, $userinfo{name}, $userinfo{fullname},
1068 "Added ".($state ? 'active' : 'inactive')." domain $domain");
1069
[2]1070 # ... and now we construct the standard records from the default set. NB: group should be variable.
[190]1071 my $sth = $dbh->prepare("SELECT host,type,val,distance,weight,port,ttl FROM default_records WHERE group_id=?");
1072 my $sth_in = $dbh->prepare("INSERT INTO records (domain_id,host,type,val,distance,weight,port,ttl)".
1073 " VALUES ($dom_id,?,?,?,?,?,?,?)");
1074 $sth->execute($group);
[3]1075 while (my ($host,$type,$val,$dist,$weight,$port,$ttl) = $sth->fetchrow_array()) {
[2]1076 $host =~ s/DOMAIN/$domain/g;
[37]1077 $val =~ s/DOMAIN/$domain/g;
[3]1078 $sth_in->execute($host,$type,$val,$dist,$weight,$port,$ttl);
[190]1079 if ($typemap{$type} eq 'SOA') {
1080 my @tmp1 = split /:/, $host;
1081 my @tmp2 = split /:/, $val;
1082 _log($dbh, $dom_id, $userinfo{id}, $group, $userinfo{name}, $userinfo{fullname},
1083 "[new $domain] Added SOA record [contact $tmp1[0]] [master $tmp1[1]] ".
1084 "[refresh $tmp2[0]] [retry $tmp2[1]] [expire $tmp2[2]] [minttl $tmp2[3]], TTL $ttl");
1085 } else {
1086 my $logentry = "[new $domain] Added record '$host $typemap{$type}";
1087 $logentry .= " [distance $dist]" if $typemap{$type} eq 'MX';
1088 $logentry .= " [priority $dist] [weight $weight] [port $port]" if $typemap{$type} eq 'SRV';
1089 _log($dbh, $dom_id, $userinfo{id}, $group, $userinfo{name}, $userinfo{fullname},
1090 $logentry." $val', TTL $ttl");
1091 }
[2]1092 }
1093
1094 # once we get here, we should have suceeded.
1095 $dbh->commit;
1096 }; # end eval
1097
1098 if ($@) {
1099 my $msg = $@;
1100 eval { $dbh->rollback; };
[193]1101 return ('FAIL',$msg);
[2]1102 } else {
[3]1103 return ('OK',$dom_id);
[2]1104 }
1105} # end addDomain
1106
1107
[3]1108## DNSDB::delDomain()
1109# Delete a domain.
1110# for now, just delete the records, then the domain.
1111# later we may want to archive it in some way instead (status code 2, for example?)
1112sub delDomain {
1113 my $dbh = shift;
[5]1114 my $domid = shift;
[3]1115
1116 # Allow transactions, and raise an exception on errors so we can catch it later.
1117 # Use local to make sure these get "reset" properly on exiting this block
1118 local $dbh->{AutoCommit} = 0;
1119 local $dbh->{RaiseError} = 1;
1120
[23]1121 my $failmsg = '';
1122
[3]1123 # Wrap all the SQL in a transaction
1124 eval {
[5]1125 my $sth = $dbh->prepare("delete from records where domain_id=?");
[23]1126 $failmsg = "Failure removing domain records";
[5]1127 $sth->execute($domid);
1128 $sth = $dbh->prepare("delete from domains where domain_id=?");
[23]1129 $failmsg = "Failure removing domain";
[5]1130 $sth->execute($domid);
[3]1131
1132 # once we get here, we should have suceeded.
[23]1133 $dbh->commit;
[3]1134 }; # end eval
1135
1136 if ($@) {
1137 my $msg = $@;
1138 eval { $dbh->rollback; };
[23]1139 return ('FAIL',"$failmsg: $msg");
[3]1140 } else {
1141 return ('OK','OK');
1142 }
1143
1144} # end delDomain()
1145
1146
[2]1147## DNSDB::domainName()
1148# Return the domain name based on a domain ID
1149# Takes a database handle and the domain ID
1150# Returns the domain name or undef on failure
1151sub domainName {
1152 $errstr = '';
1153 my $dbh = shift;
1154 my $domid = shift;
[91]1155 my ($domname) = $dbh->selectrow_array("SELECT domain FROM domains WHERE domain_id=?", undef, ($domid) );
[2]1156 $errstr = $DBI::errstr if !$domname;
1157 return $domname if $domname;
[91]1158} # end domainName()
[2]1159
1160
[224]1161## DNSDB::revName()
1162# Return the reverse zone name based on an rDNS ID
1163# Takes a database handle and the rDNS ID
1164# Returns the reverse zone name or undef on failure
1165sub revName {
1166 $errstr = '';
1167 my $dbh = shift;
1168 my $revid = shift;
1169 my ($revname) = $dbh->selectrow_array("SELECT revnet FROM revzones WHERE rdns_id=?", undef, ($revid) );
1170 $errstr = $DBI::errstr if !$revname;
1171 return $revname if $revname;
1172} # end revName()
1173
1174
[91]1175## DNSDB::domainID()
1176# Takes a database handle and domain name
1177# Returns the domain ID number
1178sub domainID {
1179 $errstr = '';
1180 my $dbh = shift;
1181 my $domain = shift;
1182 my ($domid) = $dbh->selectrow_array("SELECT domain_id FROM domains WHERE domain=?", undef, ($domain) );
1183 $errstr = $DBI::errstr if !$domid;
1184 return $domid if $domid;
1185} # end domainID()
1186
1187
[18]1188## DNSDB::addGroup()
1189# Add a group
[66]1190# Takes a database handle, group name, parent group, hashref for permissions,
1191# and optional template-vs-cloneme flag
[18]1192# Returns a status code and message
1193sub addGroup {
1194 $errstr = '';
1195 my $dbh = shift;
[20]1196 my $groupname = shift;
1197 my $pargroup = shift;
[66]1198 my $permissions = shift;
[18]1199
[66]1200 # 0 indicates "custom", hardcoded.
[18]1201 # Any other value clones that group's default records, if it exists.
[66]1202 my $inherit = shift || 0;
1203##fixme: need a flag to indicate clone records or <?> ?
[18]1204
1205 # Allow transactions, and raise an exception on errors so we can catch it later.
1206 # Use local to make sure these get "reset" properly on exiting this block
1207 local $dbh->{AutoCommit} = 0;
1208 local $dbh->{RaiseError} = 1;
1209
[38]1210 my $sth = $dbh->prepare("SELECT group_id FROM groups WHERE group_name=?");
1211 my $group_id;
1212
1213# quick check to start to see if we've already got one
1214 $sth->execute($groupname);
1215 ($group_id) = $sth->fetchrow_array;
1216
1217 return ('FAIL', "Group already exists") if $group_id;
1218
[18]1219 # Wrap all the SQL in a transaction
1220 eval {
[38]1221 $sth = $dbh->prepare("INSERT INTO groups (parent_group_id,group_name) VALUES (?,?)");
[20]1222 $sth->execute($pargroup,$groupname);
[18]1223
1224 $sth = $dbh->prepare("SELECT group_id FROM groups WHERE group_name=?");
[20]1225 $sth->execute($groupname);
1226 my ($groupid) = $sth->fetchrow_array();
[18]1227
[66]1228# Permissions
1229 if ($inherit) {
1230 } else {
1231 my @permvals;
1232 foreach (@permtypes) {
1233 if (!defined ($permissions->{$_})) {
1234 push @permvals, 0;
1235 } else {
1236 push @permvals, $permissions->{$_};
1237 }
1238 }
1239
1240 $sth = $dbh->prepare("INSERT INTO permissions (group_id,$permlist) values (?".',?'x($#permtypes+1).")");
1241 $sth->execute($groupid,@permvals);
1242
1243 $sth = $dbh->prepare("SELECT permission_id FROM permissions WHERE group_id=?");
1244 $sth->execute($groupid);
1245 my ($permid) = $sth->fetchrow_array();
1246
1247 $dbh->do("UPDATE groups SET permission_id=$permid WHERE group_id=$groupid");
1248 } # done permission fiddling
1249
1250# Default records
[18]1251 $sth = $dbh->prepare("INSERT INTO default_records (group_id,host,type,val,distance,weight,port,ttl) ".
[20]1252 "VALUES ($groupid,?,?,?,?,?,?,?)");
[66]1253 if ($inherit) {
[87]1254 # Duplicate records from parent. Actually relying on inherited records feels
1255 # very fragile, and it would be problematic to roll over at a later time.
[18]1256 my $sth2 = $dbh->prepare("SELECT host,type,val,distance,weight,port,ttl FROM default_records WHERE group_id=?");
[87]1257 $sth2->execute($pargroup);
[18]1258 while (my @clonedata = $sth2->fetchrow_array) {
1259 $sth->execute(@clonedata);
1260 }
1261 } else {
[66]1262##fixme: Hardcoding is Bad, mmmmkaaaay?
[18]1263 # reasonable basic defaults for SOA, MX, NS, and minimal hosting
1264 # could load from a config file, but somewhere along the line we need hardcoded bits.
1265 $sth->execute('ns1.example.com:hostmaster.example.com', 6, '10800:3600:604800:10800', 0, 0, 0, 86400);
1266 $sth->execute('DOMAIN', 1, '192.168.4.2', 0, 0, 0, 7200);
1267 $sth->execute('DOMAIN', 15, 'mx.example.com', 10, 0, 0, 7200);
1268 $sth->execute('DOMAIN', 2, 'ns1.example.com', 0, 0, 0, 7200);
1269 $sth->execute('DOMAIN', 2, 'ns2.example.com', 0, 0, 0, 7200);
1270 $sth->execute('www.DOMAIN', 5, 'DOMAIN', 0, 0, 0, 7200);
1271 }
1272
1273 # once we get here, we should have suceeded.
1274 $dbh->commit;
1275 }; # end eval
1276
1277 if ($@) {
1278 my $msg = $@;
1279 eval { $dbh->rollback; };
1280 return ('FAIL',$msg);
1281 } else {
1282 return ('OK','OK');
1283 }
1284
1285} # end addGroup()
1286
1287
[22]1288## DNSDB::delGroup()
1289# Delete a group.
1290# Takes a group ID
1291# Returns a status code and message
1292sub delGroup {
1293 my $dbh = shift;
1294 my $groupid = shift;
1295
1296 # Allow transactions, and raise an exception on errors so we can catch it later.
1297 # Use local to make sure these get "reset" properly on exiting this block
1298 local $dbh->{AutoCommit} = 0;
1299 local $dbh->{RaiseError} = 1;
1300
1301##fixme: locate "knowable" error conditions and deal with them before the eval
[23]1302# ... or inside, whatever.
[22]1303# -> domains still exist in group
1304# -> ...
[23]1305 my $failmsg = '';
[22]1306
1307 # Wrap all the SQL in a transaction
1308 eval {
[23]1309 my $sth = $dbh->prepare("SELECT count(*) FROM domains WHERE group_id=?");
[22]1310 $sth->execute($groupid);
[23]1311 my ($domcnt) = $sth->fetchrow_array;
1312 $failmsg = "Can't remove group ".groupName($dbh,$groupid);
1313 die "$domcnt domains still in group\n" if $domcnt;
1314
1315 $sth = $dbh->prepare("delete from default_records where group_id=?");
1316 $failmsg = "Failed to delete default records for ".groupName($dbh,$groupid);
1317 $sth->execute($groupid);
[22]1318 $sth = $dbh->prepare("delete from groups where group_id=?");
[23]1319 $failmsg = "Failed to remove group ".groupName($dbh,$groupid);
[22]1320 $sth->execute($groupid);
1321
1322 # once we get here, we should have suceeded.
1323 $dbh->commit;
1324 }; # end eval
1325
1326 if ($@) {
1327 my $msg = $@;
1328 eval { $dbh->rollback; };
[23]1329 return ('FAIL',"$failmsg: $msg");
[22]1330 } else {
1331 return ('OK','OK');
1332 }
1333} # end delGroup()
1334
1335
[19]1336## DNSDB::getChildren()
1337# Get a list of all groups whose parent^n is group <n>
[24]1338# Takes a database handle, group ID, reference to an array to put the group IDs in,
1339# and an optional flag to return only immediate children or all children-of-children
1340# default to returning all children
[19]1341# Calls itself
1342sub getChildren {
1343 $errstr = '';
1344 my $dbh = shift;
[20]1345 my $rootgroup = shift;
1346 my $groupdest = shift;
[24]1347 my $immed = shift || 'all';
[19]1348
1349 # special break for default group; otherwise we get stuck.
[20]1350 if ($rootgroup == 1) {
[19]1351 # by definition, group 1 is the Root Of All Groups
[24]1352 my $sth = $dbh->prepare("SELECT group_id FROM groups WHERE NOT (group_id=1)".
1353 ($immed ne 'all' ? " AND parent_group_id=1" : ''));
[19]1354 $sth->execute;
1355 while (my @this = $sth->fetchrow_array) {
[20]1356 push @$groupdest, @this;
[19]1357 }
1358 } else {
1359 my $sth = $dbh->prepare("SELECT group_id FROM groups WHERE parent_group_id=?");
[20]1360 $sth->execute($rootgroup);
[19]1361 return if $sth->rows == 0;
[20]1362 my @grouplist;
1363 while (my ($group) = $sth->fetchrow_array) {
1364 push @$groupdest, $group;
[24]1365 getChildren($dbh,$group,$groupdest) if $immed eq 'all';
[19]1366 }
1367 }
1368} # end getChildren()
1369
1370
[20]1371## DNSDB::groupName()
[17]1372# Return the group name based on a group ID
1373# Takes a database handle and the group ID
1374# Returns the group name or undef on failure
[20]1375sub groupName {
[13]1376 $errstr = '';
1377 my $dbh = shift;
[20]1378 my $groupid = shift;
1379 my $sth = $dbh->prepare("SELECT group_name FROM groups WHERE group_id=?");
1380 $sth->execute($groupid);
1381 my ($groupname) = $sth->fetchrow_array();
1382 $errstr = $DBI::errstr if !$groupname;
1383 return $groupname if $groupname;
1384} # end groupName
[13]1385
1386
[118]1387## DNSDB::groupID()
1388# Return the group ID based on the group name
1389# Takes a database handle and the group name
1390# Returns the group ID or undef on failure
1391sub groupID {
1392 $errstr = '';
1393 my $dbh = shift;
1394 my $group = shift;
1395 my ($grpid) = $dbh->selectrow_array("SELECT group_id FROM groups WHERE group=?", undef, ($group) );
1396 $errstr = $DBI::errstr if !$grpid;
1397 return $grpid if $grpid;
1398} # end groupID()
1399
1400
[24]1401## DNSDB::addUser()
[87]1402# Add a user.
1403# Takes a DB handle, username, group ID, password, state (active/inactive).
1404# Optionally accepts:
1405# user type (user/admin) - defaults to user
1406# permissions string - defaults to inherit from group
1407# three valid forms:
1408# i - Inherit permissions
1409# c:<user_id> - Clone permissions from <user_id>
1410# C:<permission list> - Set these specific permissions
1411# first name - defaults to username
1412# last name - defaults to blank
1413# phone - defaults to blank (could put other data within column def)
[90]1414# Returns (OK,<uid>) on success, (FAIL,<message>) on failure
[24]1415sub addUser {
1416 $errstr = '';
1417 my $dbh = shift;
1418 my $username = shift;
1419 my $group = shift;
1420 my $pass = shift;
1421 my $state = shift;
[25]1422
[90]1423 return ('FAIL', "Missing one or more required entries") if !defined($state);
1424 return ('FAIL', "Username must not be blank") if !$username;
[87]1425
[25]1426 my $type = shift || 'u'; # create limited users by default - fwiw, not sure yet how this will interact with ACLs
1427
[67]1428 my $permstring = shift || 'i'; # default is to inhert permissions from group
1429
[25]1430 my $fname = shift || $username;
[24]1431 my $lname = shift || '';
[25]1432 my $phone = shift || ''; # not going format-check
[24]1433
[38]1434 my $sth = $dbh->prepare("SELECT user_id FROM users WHERE username=?");
[24]1435 my $user_id;
1436
[38]1437# quick check to start to see if we've already got one
1438 $sth->execute($username);
1439 ($user_id) = $sth->fetchrow_array;
1440
1441 return ('FAIL', "User already exists") if $user_id;
1442
[24]1443 # Allow transactions, and raise an exception on errors so we can catch it later.
1444 # Use local to make sure these get "reset" properly on exiting this block
1445 local $dbh->{AutoCommit} = 0;
1446 local $dbh->{RaiseError} = 1;
1447
[94]1448 my $failmsg = '';
1449
[24]1450 # Wrap all the SQL in a transaction
1451 eval {
[87]1452 # insert the user... note we set inherited perms by default since
1453 # it's simple and cleans up some other bits of state
1454 my $sth = $dbh->prepare("INSERT INTO users ".
1455 "(group_id,username,password,firstname,lastname,phone,type,status,permission_id,inherit_perm) ".
1456 "VALUES (?,?,?,?,?,?,?,?,(SELECT permission_id FROM permissions WHERE group_id=?),'t')");
1457 $sth->execute($group,$username,unix_md5_crypt($pass),$fname,$lname,$phone,$type,$state,$group);
[24]1458
1459 # get the ID...
[94]1460 ($user_id) = $dbh->selectrow_array("SELECT currval('users_user_id_seq')");
[24]1461
[87]1462# Permissions! Gotta set'em all!
1463 die "Invalid permission string $permstring"
1464 if $permstring !~ /^(?:
1465 i # inherit
1466 |c:\d+ # clone
1467 # custom. no, the leading , is not a typo
[111]1468 |C:(?:,(?:group|user|domain|record|self)_(?:edit|create|delete))*
[87]1469 )$/x;
1470# bleh. I'd call another function to do my dirty work, but we're in the middle of a transaction already.
1471 if ($permstring ne 'i') {
1472 # for cloned or custom permissions, we have to create a new permissions entry.
1473 my $clonesrc = $group;
1474 if ($permstring =~ /^c:(\d+)/) { $clonesrc = $1; }
1475 $dbh->do("INSERT INTO permissions ($permlist,user_id) ".
1476 "SELECT $permlist,? FROM permissions WHERE permission_id=".
1477 "(SELECT permission_id FROM permissions WHERE ".($permstring =~ /^c:/ ? 'user' : 'group')."_id=?)",
1478 undef, ($user_id,$clonesrc) );
1479 $dbh->do("UPDATE users SET permission_id=".
1480 "(SELECT permission_id FROM permissions WHERE user_id=?) ".
1481 "WHERE user_id=?", undef, ($user_id, $user_id) );
1482 }
1483 if ($permstring =~ /^C:/) {
1484 # finally for custom permissions, we set the passed-in permissions (and unset
1485 # any that might have been brought in by the clone operation above)
1486 my ($permid) = $dbh->selectrow_array("SELECT permission_id FROM permissions WHERE user_id=?",
1487 undef, ($user_id) );
1488 foreach (@permtypes) {
1489 if ($permstring =~ /,$_/) {
1490 $dbh->do("UPDATE permissions SET $_='t' WHERE permission_id=?", undef, ($permid) );
1491 } else {
1492 $dbh->do("UPDATE permissions SET $_='f' WHERE permission_id=?", undef, ($permid) );
1493 }
1494 }
1495 }
1496
1497 $dbh->do("UPDATE users SET inherit_perm='n' WHERE user_id=?", undef, ($user_id) );
1498
[25]1499##fixme: add another table to hold name/email for log table?
1500
[24]1501 # once we get here, we should have suceeded.
1502 $dbh->commit;
1503 }; # end eval
1504
1505 if ($@) {
1506 my $msg = $@;
1507 eval { $dbh->rollback; };
[87]1508 return ('FAIL',$msg." $failmsg");
[24]1509 } else {
1510 return ('OK',$user_id);
1511 }
1512} # end addUser
1513
1514
[55]1515## DNSDB::checkUser()
1516# Check user/pass combo on login
1517sub checkUser {
1518 my $dbh = shift;
1519 my $user = shift;
[56]1520 my $inpass = shift;
[55]1521
1522 my $sth = $dbh->prepare("SELECT user_id,group_id,password,firstname,lastname FROM users WHERE username=?");
1523 $sth->execute($user);
1524 my ($uid,$gid,$pass,$fname,$lname) = $sth->fetchrow_array;
1525 my $loginfailed = 1 if !defined($uid);
1526
1527 if ($pass =~ m|^\$1\$([A-Za-z0-9/.]+)\$|) {
[56]1528 $loginfailed = 1 if $pass ne unix_md5_crypt($inpass,$1);
[55]1529 } else {
[56]1530 $loginfailed = 1 if $pass ne $inpass;
[55]1531 }
1532
1533 # nnnngggg
1534 return ($uid, $gid);
1535} # end checkUser
1536
1537
[83]1538## DNSDB:: updateUser()
[90]1539# Update general data about user
[83]1540sub updateUser {
1541 my $dbh = shift;
[118]1542
1543##fixme: tweak calling convention so that we can update any given bit of data
[83]1544 my $uid = shift;
1545 my $username = shift;
1546 my $group = shift;
1547 my $pass = shift;
1548 my $state = shift;
[87]1549 my $type = shift || 'u';
[83]1550 my $fname = shift || $username;
1551 my $lname = shift || '';
1552 my $phone = shift || ''; # not going format-check
1553
1554 my $failmsg = '';
1555
1556 # Allow transactions, and raise an exception on errors so we can catch it later.
1557 # Use local to make sure these get "reset" properly on exiting this block
1558 local $dbh->{AutoCommit} = 0;
1559 local $dbh->{RaiseError} = 1;
1560
1561 my $sth;
1562
1563 # Password can be left blank; if so we assume there's one on file.
1564 # Actual blank passwords are bad, mm'kay?
1565 if (!$pass) {
1566 $sth = $dbh->prepare("SELECT password FROM users WHERE user_id=?");
1567 $sth->execute($uid);
1568 ($pass) = $sth->fetchrow_array;
1569 } else {
1570 $pass = unix_md5_crypt($pass);
1571 }
1572
1573 eval {
1574 my $sth = $dbh->prepare(q(
1575 UPDATE users
1576 SET username=?, password=?, firstname=?, lastname=?, phone=?, type=?, status=?
1577 WHERE user_id=?
1578 )
1579 );
1580 $sth->execute($username, $pass, $fname, $lname, $phone, $type, $state, $uid);
1581 $dbh->commit;
1582 };
1583 if ($@) {
1584 my $msg = $@;
1585 eval { $dbh->rollback; };
1586 return ('FAIL',"$failmsg: $msg");
1587 } else {
1588 return ('OK','OK');
1589 }
1590} # end updateUser()
1591
1592
[24]1593## DNSDB::delUser()
1594#
1595sub delUser {
[25]1596 my $dbh = shift;
1597 return ('FAIL',"Need database handle") if !$dbh;
1598 my $userid = shift;
1599 return ('FAIL',"Missing userid") if !defined($userid);
1600
1601 my $sth = $dbh->prepare("delete from users where user_id=?");
1602 $sth->execute($userid);
1603
1604 return ('FAIL',"Couldn't remove user: ".$sth->errstr) if $sth->err;
1605
1606 return ('OK','OK');
1607
[24]1608} # end delUser
1609
1610
[25]1611## DNSDB::userFullName()
1612# Return a pretty string!
1613# Takes a user_id and optional printf-ish string to indicate which pieces where:
1614# %u for the username
1615# %f for the first name
1616# %l for the last name
1617# All other text in the passed string will be left as-is.
1618##fixme: need a "smart" option too, so that missing/null/blank first/last names don't give funky output
1619sub userFullName {
1620 $errstr = '';
1621 my $dbh = shift;
1622 my $userid = shift;
1623 my $fullformat = shift || '%f %l (%u)';
1624 my $sth = $dbh->prepare("select username,firstname,lastname from users where user_id=?");
1625 $sth->execute($userid);
1626 my ($uname,$fname,$lname) = $sth->fetchrow_array();
1627 $errstr = $DBI::errstr if !$uname;
1628
1629 $fullformat =~ s/\%u/$uname/g;
1630 $fullformat =~ s/\%f/$fname/g;
1631 $fullformat =~ s/\%l/$lname/g;
1632
1633 return $fullformat;
1634} # end userFullName
1635
1636
[51]1637## DNSDB::userStatus()
1638# Sets and/or returns a user's status
1639# Takes a database handle, user ID and optionally a status argument
1640# Returns undef on errors.
1641sub userStatus {
1642 my $dbh = shift;
1643 my $id = shift;
1644 my $newstatus = shift;
1645
1646 return undef if $id !~ /^\d+$/;
1647
1648 my $sth;
1649
1650# ooo, fun! let's see what we were passed for status
1651 if ($newstatus) {
1652 $sth = $dbh->prepare("update users set status=? where user_id=?");
1653 # ass-u-me caller knows what's going on in full
1654 if ($newstatus =~ /^[01]$/) { # only two valid for now.
1655 $sth->execute($newstatus,$id);
1656 } elsif ($newstatus =~ /^usero(?:n|ff)$/) {
1657 $sth->execute(($newstatus eq 'useron' ? 1 : 0),$id);
1658 }
1659 }
1660
1661 $sth = $dbh->prepare("select status from users where user_id=?");
1662 $sth->execute($id);
1663 my ($status) = $sth->fetchrow_array;
1664 return $status;
1665} # end userStatus()
1666
1667
[83]1668## DNSDB::getUserData()
1669# Get misc user data for display
1670sub getUserData {
1671 my $dbh = shift;
1672 my $uid = shift;
1673
1674 my $sth = $dbh->prepare("SELECT group_id,username,firstname,lastname,phone,type,status,inherit_perm ".
1675 "FROM users WHERE user_id=?");
1676 $sth->execute($uid);
1677 return $sth->fetchrow_hashref();
1678
1679} # end getUserData()
1680
1681
[2]1682## DNSDB::getSOA()
1683# Return all suitable fields from an SOA record in separate elements of a hash
[224]1684# Takes a database handle, default/live flag, domain/reverse flag, and parent ID
[2]1685sub getSOA {
1686 $errstr = '';
1687 my $dbh = shift;
1688 my $def = shift;
[224]1689 my $rev = shift;
[2]1690 my $id = shift;
1691 my %ret;
1692
[224]1693 # (ab)use distance and weight columns to store SOA data? can't for default_rev_records...
1694 # - should really attach serial to the zone parent somewhere
[101]1695
[224]1696 my $sql = "SELECT record_id,host,val,ttl from "._rectable($def,$rev).
1697 " WHERE "._recparent($def,$rev)." = ? AND type=$reverse_typemap{SOA}";
1698
[2]1699 my $sth = $dbh->prepare($sql);
[101]1700 $sth->execute($id);
[2]1701
[224]1702 my ($recid,$host,$val,$ttl) = $sth->fetchrow_array() or return;
[202]1703 my ($contact,$prins) = split /:/, $host;
[2]1704 my ($refresh,$retry,$expire,$minttl) = split /:/, $val;
1705
1706 $ret{recid} = $recid;
1707 $ret{ttl} = $ttl;
[224]1708# $ret{serial} = $serial; # ca't use distance for serial with default_rev_records
[2]1709 $ret{prins} = $prins;
1710 $ret{contact} = $contact;
1711 $ret{refresh} = $refresh;
1712 $ret{retry} = $retry;
1713 $ret{expire} = $expire;
1714 $ret{minttl} = $minttl;
1715
1716 return %ret;
1717} # end getSOA()
1718
1719
1720## DNSDB::getRecLine()
1721# Return all data fields for a zone record in separate elements of a hash
1722# Takes a database handle, default/live flag, and record ID
1723sub getRecLine {
1724 $errstr = '';
1725 my $dbh = shift;
1726 my $def = shift;
1727 my $id = shift;
1728
[130]1729 my $sql = "SELECT record_id,host,type,val,distance,weight,port,ttl".
1730 (($def eq 'def' or $def eq 'y') ? ',group_id FROM default_' : ',domain_id FROM ').
1731 "records WHERE record_id=?";
[123]1732 my $ret = $dbh->selectrow_hashref($sql, undef, ($id) );
[2]1733
[90]1734 if ($dbh->err) {
[2]1735 $errstr = $DBI::errstr;
1736 return undef;
1737 }
1738
[123]1739 if (!$ret) {
1740 $errstr = "No such record";
1741 return undef;
1742 }
1743
[107]1744 $ret->{parid} = (($def eq 'def' or $def eq 'y') ? $ret->{group_id} : $ret->{domain_id});
[90]1745
1746 return $ret;
[2]1747}
1748
1749
1750##fixme: should use above (getRecLine()) to get lines for below?
1751## DNSDB::getDomRecs()
1752# Return records for a domain
1753# Takes a database handle, default/live flag, group/domain ID, start,
1754# number of records, sort field, and sort order
1755# Returns a reference to an array of hashes
1756sub getDomRecs {
1757 $errstr = '';
1758 my $dbh = shift;
[224]1759 my $def = shift;
1760 my $rev = shift;
[2]1761 my $id = shift;
[4]1762 my $nrecs = shift || 'all';
1763 my $nstart = shift || 0;
[2]1764
[4]1765## for order, need to map input to column names
1766 my $order = shift || 'host';
[72]1767 my $direction = shift || 'ASC';
[4]1768
[135]1769 my $filter = shift || '';
1770
[224]1771 my $sql = "SELECT r.record_id,r.host,r.type,r.val,r.ttl";
1772 $sql .= ",r.distance,r.weight,r.port" if $rev eq 'n';
1773 $sql .= " FROM "._rectable($def,$rev)." r ";
[104]1774 $sql .= "INNER JOIN rectypes t ON r.type=t.val "; # for sorting by type alphabetically
[224]1775 $sql .= "WHERE "._recparent($def,$rev)." = ?";
[104]1776 $sql .= " AND NOT r.type=$reverse_typemap{SOA}";
[160]1777 $sql .= " AND host ~* ?" if $filter;
[104]1778 # use alphaorder column for "correct" ordering of sort-by-type instead of DNS RR type number
1779 $sql .= " ORDER BY ".($order eq 'type' ? 't.alphaorder' : "r.$order")." $direction";
[4]1780
[222]1781 my @bindvars = ($id);
1782 push @bindvars, $filter if $filter;
[224]1783
1784 # just to be ultraparanoid about SQL injection vectors
1785 if ($nstart ne 'all') {
1786 $sql .= " LIMIT ? OFFSET ?";
1787 push @bindvars, $nrecs;
1788 push @bindvars, ($nstart*$nrecs);
1789 }
[90]1790 my $sth = $dbh->prepare($sql) or warn $dbh->errstr;
[222]1791 $sth->execute(@bindvars) or warn "$sql: ".$sth->errstr;
[2]1792
1793 my @retbase;
1794 while (my $ref = $sth->fetchrow_hashref()) {
1795 push @retbase, $ref;
1796 }
1797
1798 my $ret = \@retbase;
1799 return $ret;
1800} # end getDomRecs()
1801
1802
[91]1803## DNSDB::getRecCount()
[224]1804# Return count of non-SOA records in zone (or default records in a group)
1805# Takes a database handle, default/live flag, reverse/forward flag, group/domain ID,
1806# and optional filtering modifier
[91]1807# Returns the count
1808sub getRecCount {
1809 my $dbh = shift;
1810 my $defrec = shift;
[224]1811 my $revrec = shift;
[91]1812 my $id = shift;
[135]1813 my $filter = shift || '';
[91]1814
[135]1815 # keep the nasties down, since we can't ?-sub this bit. :/
1816 # note this is chars allowed in DNS hostnames
1817 $filter =~ s/[^a-zA-Z0-9_.:-]//g;
1818
[222]1819 my @bindvars = ($id);
1820 push @bindvars, $filter if $filter;
[224]1821 my $sql = "SELECT count(*) FROM ".
1822 _rectable($defrec,$revrec).
1823 " WHERE "._recparent($defrec,$revrec)."=? ".
1824 "AND NOT type=$reverse_typemap{SOA}".
1825 ($filter ? " AND host ~* ?" : '');
1826 my ($count) = $dbh->selectrow_array($sql, undef, (@bindvars) );
[91]1827
1828 return $count;
1829
1830} # end getRecCount()
1831
1832
[3]1833## DNSDB::addRec()
[2]1834# Add a new record to a domain or a group's default records
1835# Takes a database handle, default/live flag, group/domain ID,
1836# host, type, value, and TTL
1837# Some types require additional detail: "distance" for MX and SRV,
1838# and weight/port for SRV
1839# Returns a status code and detail message in case of error
[234]1840##fixme: pass a hash with the record data, not a series of separate values
[2]1841sub addRec {
1842 $errstr = '';
1843 my $dbh = shift;
1844 my $defrec = shift;
[226]1845 my $revrec = shift;
1846 my $id = shift; # parent (group_id for defrecs, rdns_id for reverse records,
1847 # domain_id for domain records)
[2]1848
1849 my $host = shift;
[234]1850 my $rectype = shift; # reference so we can coerce it if "+"-types can't find both zones
[2]1851 my $val = shift;
1852 my $ttl = shift;
1853
[226]1854 # prep for validation
[223]1855 my $addr = NetAddr::IP->new($val);
[226]1856 $host =~ s/\.+$//; # FQDNs ending in . are an internal detail, and really shouldn't be exposed in the UI.
1857
1858 my $domid = 0;
1859 my $revid = 0;
1860
1861 my $retcode = 'OK'; # assume everything will go OK
1862 my $retmsg = '';
1863
1864 # do simple validation first
1865 return ('FAIL', "TTL must be numeric") unless $ttl =~ /^\d+$/;
1866
[234]1867 # Quick check on hostname parts. Note the regex is more forgiving than the error message;
1868 # domain names technically are case-insensitive, and we use printf-like % codes for a couple
1869 # of types. Other things may also be added to validate default records of several flavours.
1870 return ('FAIL', "Hostnames may not contain anything other than (0-9 a-z . _)")
1871 if $defrec eq 'n' && $host !~ /^[0-9a-z_%.]+$/i;
[226]1872
[234]1873 # Collect these even if we're only doing a simple A record so we can call *any* validation sub
1874 my $dist = shift;
1875 my $port = shift;
1876 my $weight = shift;
[226]1877
[234]1878 my $fields;
1879 my @vallist;
[226]1880
[234]1881 # Call the validation sub for the type requested.
1882 ($retcode,$retmsg) = $validators{$$rectype}($dbh, (defrec => $defrec, revrec => $revrec, id => $id,
1883 host => \$host, rectype => $rectype, val => \$val, addr => $addr,
1884 dist => \$dist, port => \$port, weight => \$weight,
1885 fields => \$fields, vallist => \@vallist) );
[129]1886
[234]1887 return ($retcode,$retmsg) if $retcode eq 'FAIL';
[209]1888
[234]1889 # Set up database fields and bind parameters
1890 $fields .= "host,type,val,ttl,"._recparent($defrec,$revrec);
1891 push @vallist, ($host,$$rectype,$val,$ttl,$id);
1892 my $vallen = '?'.(',?'x$#vallist);
[2]1893
[90]1894 # Allow transactions, and raise an exception on errors so we can catch it later.
1895 # Use local to make sure these get "reset" properly on exiting this block
1896 local $dbh->{AutoCommit} = 0;
1897 local $dbh->{RaiseError} = 1;
[2]1898
[90]1899 eval {
[234]1900 $dbh->do("INSERT INTO "._rectable($defrec, $revrec)."records ($fields) VALUES ($vallen)",
[90]1901 undef, @vallist);
1902 $dbh->commit;
1903 };
1904 if ($@) {
1905 my $msg = $@;
1906 eval { $dbh->rollback; };
1907 return ('FAIL',$msg);
1908 }
[2]1909
[226]1910 return ($retcode, $retmsg);
[90]1911
[2]1912} # end addRec()
1913
1914
[16]1915## DNSDB::updateRec()
1916# Update a record
1917sub updateRec {
1918 $errstr = '';
[17]1919
[16]1920 my $dbh = shift;
1921 my $defrec = shift;
1922 my $id = shift;
1923
1924# all records have these
1925 my $host = shift;
1926 my $type = shift;
1927 my $val = shift;
1928 my $ttl = shift;
1929
1930 return('FAIL',"Missing standard argument(s)") if !defined($ttl);
1931
1932# only MX and SRV will use these
1933 my $dist = 0;
1934 my $weight = 0;
1935 my $port = 0;
1936
1937 if ($type == $reverse_typemap{MX} || $type == $reverse_typemap{SRV}) {
[17]1938 $dist = shift;
[223]1939 $dist =~ s/\s+//g;
[17]1940 return ('FAIL',"MX or SRV requires distance") if !defined($dist);
[223]1941 return ('FAIL', "Distance must be numeric") unless $dist =~ /^\d+$/;
[16]1942 if ($type == $reverse_typemap{SRV}) {
[17]1943 $weight = shift;
[223]1944 $weight =~ s/\s+//g;
[17]1945 return ('FAIL',"SRV requires weight") if !defined($weight);
[223]1946 return ('FAIL',"Weight must be numeric") unless $weight =~ /^\d+$/;
[17]1947 $port = shift;
[223]1948 $port =~ s/\s+//g;
[17]1949 return ('FAIL',"SRV requires port") if !defined($port);
[223]1950 return ('FAIL',"Port must be numeric") unless $port =~ /^\d+$/;
[16]1951 }
1952 }
1953
[223]1954# Enforce IP addresses on A and AAAA types
1955 my $addr = NetAddr::IP->new($val);
1956 if ($type == $reverse_typemap{A}) {
1957 return ('FAIL',$typemap{$type}." record must be a valid IPv4 address")
1958 unless $addr && !$addr->{isv6};
1959 }
1960 if ($type == $reverse_typemap{AAAA}) {
1961 return ('FAIL',$typemap{$type}." record must be a valid IPv6 address")
1962 unless $addr && $addr->{isv6};
1963 }
1964
1965# hmm.. this might work. except possibly for something pointing to "deadbeef.ca". <g>
1966# if ($type == $reverse_typemap{NS} || $type == $reverse_typemap{MX} || $type == $reverse_typemap{SRV}) {
1967# if ($val =~ /^\s*[\da-f:.]+\s*$/) {
1968# return ('FAIL',"$val is not a valid IP address") if !$addr;
1969# }
1970# }
1971
[90]1972 local $dbh->{AutoCommit} = 0;
1973 local $dbh->{RaiseError} = 1;
1974
1975 eval {
1976 $dbh->do("UPDATE ".($defrec eq 'y' ? 'default_' : '')."records ".
[130]1977 "SET host=?,val=?,type=?,ttl=?,distance=?,weight=?,port=? ".
1978 "WHERE record_id=?", undef, ($host, $val, $type, $ttl, $dist, $weight, $port, $id) );
1979 $dbh->commit;
[90]1980 };
1981 if ($@) {
1982 my $msg = $@;
1983 $dbh->rollback;
1984 return ('FAIL', $msg);
1985 }
1986
[16]1987 return ('OK','OK');
1988} # end updateRec()
1989
1990
[3]1991## DNSDB::delRec()
1992# Delete a record.
1993sub delRec {
1994 $errstr = '';
1995 my $dbh = shift;
1996 my $defrec = shift;
1997 my $id = shift;
1998
[62]1999 my $sth = $dbh->prepare("DELETE FROM ".($defrec eq 'y' ? 'default_' : '')."records WHERE record_id=?");
[3]2000 $sth->execute($id);
2001
[23]2002 return ('FAIL',"Couldn't remove record: ".$sth->errstr) if $sth->err;
[3]2003
2004 return ('OK','OK');
2005} # end delRec()
2006
2007
[117]2008 # Reference hashes.
2009 my %par_tbl = (
2010 group => 'groups',
2011 user => 'users',
2012 defrec => 'default_records',
2013 domain => 'domains',
2014 record => 'records'
2015 );
2016 my %id_col = (
2017 group => 'group_id',
2018 user => 'user_id',
2019 defrec => 'record_id',
2020 domain => 'domain_id',
2021 record => 'record_id'
2022 );
2023 my %par_col = (
2024 group => 'parent_group_id',
2025 user => 'group_id',
2026 defrec => 'group_id',
2027 domain => 'group_id',
2028 record => 'domain_id'
2029 );
2030 my %par_type = (
2031 group => 'group',
2032 user => 'group',
2033 defrec => 'group',
2034 domain => 'group',
2035 record => 'domain'
2036 );
2037
[225]2038
2039## DNSDB::getTypelist()
2040# Get a list of record types for various UI dropdowns
2041# Takes database handle, forward/reverse/lookup flag, and optional "tag as selected" indicator (defaults to A)
2042# Returns an arrayref to list of hashrefs perfect for HTML::Template
2043sub getTypelist {
2044 my $dbh = shift;
2045 my $recgroup = shift;
2046 my $type = shift || $reverse_typemap{A};
2047
2048 # also accepting $webvar{revrec}!
2049 $recgroup = 'f' if $recgroup eq 'n';
2050 $recgroup = 'r' if $recgroup eq 'y';
2051
2052 my $sql = "SELECT val,name FROM rectypes WHERE ";
2053 if ($recgroup eq 'r') {
2054 # reverse zone types
2055 $sql .= "stdflag=2 OR stdflag=3";
2056 } elsif ($recgroup eq 'l') {
2057 # DNS lookup types. Note we avoid our custom types >= 65280, since those are entirely internal.
2058 $sql .= "(stdflag=1 OR stdflag=2 OR stdflag=3) AND val < 65280";
2059 } else {
2060 # default; forward zone types. technically $type eq 'f' but not worth the error message.
2061 $sql .= "stdflag=1 OR stdflag=2";
2062 }
2063 $sql .= " ORDER BY listorder";
2064
2065 my $sth = $dbh->prepare($sql);
2066 $sth->execute;
2067 my @typelist;
2068 while (my ($rval,$rname) = $sth->fetchrow_array()) {
2069 my %row = ( recval => $rval, recname => $rname );
2070 $row{tselect} = 1 if $rval == $type;
2071 push @typelist, \%row;
2072 }
2073
2074 # Add SOA on lookups since it's not listed in other dropdowns.
2075 if ($recgroup eq 'l') {
2076 my %row = ( recval => $reverse_typemap{SOA}, recname => 'SOA' );
2077 $row{tselect} = 1 if $reverse_typemap{SOA} == $type;
2078 push @typelist, \%row;
2079 }
2080
2081 return \@typelist;
2082} # end getTypelist()
2083
2084
[116]2085## DNSDB::getParents()
2086# Find out which entities are parent to the requested id
2087# Returns arrayref containing hash pairs of id/type
2088sub getParents {
2089 my $dbh = shift;
2090 my $id = shift;
2091 my $type = shift;
[117]2092 my $depth = shift || 'all'; # valid values: 'all', 'immed', <int> (stop at this group ID)
[116]2093
[117]2094 my @parlist;
[116]2095
[117]2096 while (1) {
2097 my $result = $dbh->selectrow_hashref("SELECT $par_col{$type} FROM $par_tbl{$type} WHERE $id_col{$type} = ?",
2098 undef, ($id) );
[152]2099 my %tmp = ($result->{$par_col{$type}} => $par_type{$type});
2100 unshift @parlist, \%tmp;
[117]2101 last if $result->{$par_col{$type}} == 1; # group 1 is its own parent
[152]2102 $id = $result->{$par_col{$type}};
[117]2103 $type = $par_type{$type};
[116]2104 }
2105
[117]2106 return \@parlist;
[116]2107
2108} # end getParents()
2109
2110
[117]2111## DNSDB::isParent()
2112# Returns true if $id1 is a parent of $id2, false otherwise
2113sub isParent {
2114 my $dbh = shift;
2115 my $id1 = shift;
2116 my $type1 = shift;
2117 my $id2 = shift;
2118 my $type2 = shift;
2119##todo: immediate, secondary, full (default)
2120
[157]2121 # Return false on invalid types
2122 return 0 if !grep /^$type1$/, ('record','defrec','user','domain','group');
2123 return 0 if !grep /^$type2$/, ('record','defrec','user','domain','group');
2124
[117]2125 # Return false on impossible relations
2126 return 0 if $type1 eq 'record'; # nothing may be a child of a record
2127 return 0 if $type1 eq 'defrec'; # nothing may be a child of a record
2128 return 0 if $type1 eq 'user'; # nothing may be child of a user
2129 return 0 if $type1 eq 'domain' && $type2 ne 'record'; # domain may not be a parent of anything other than a record
2130
[186]2131 # ennnhhhh.... if we're passed an id of 0, it will never be found. usual
2132 # case would be the UI creating a new <thing>, and so we don't have an ID for
2133 # <thing> to look up yet. in that case the UI should check the parent as well.
2134 # argument for returning 1 is
2135 return 0 if $id1 == 0; # nothing can have a parent id of 0
2136 return 1 if $id2 == 0; # anything could have a child id of 0 (or "unknown")
2137
[117]2138 # group 1 is the ultimate root parent
2139 return 1 if $type1 eq 'group' && $id1 == 1;
2140
[155]2141 # groups are always (a) parent of themselves
2142 return 1 if $type1 eq 'group' && $type2 eq 'group' && $id1 == $id2;
2143
[117]2144# almost the same loop as getParents() above
2145 my $id = $id2;
2146 my $type = $type2;
2147 my $foundparent = 0;
[155]2148
[186]2149 my $limiter = 0;
[117]2150 while (1) {
[155]2151 my $sql = "SELECT $par_col{$type} FROM $par_tbl{$type} WHERE $id_col{$type} = ?";
[117]2152 my $result = $dbh->selectrow_hashref($sql,
[157]2153 undef, ($id) );
[186]2154 if (!$result) {
2155 $limiter++;
2156##fixme: how often will this happen on a live site?
2157 warn "no results looking for $sql with id $id (depth $limiter)\n";
2158 last;
2159 }
[157]2160 if ($result && $result->{$par_col{$type}} == $id1) {
[117]2161 $foundparent = 1;
2162 last;
[157]2163 } else {
2164##fixme: do we care about trying to return a "no such record/domain/user/group" error?
2165 warn $dbh->errstr." $sql, $id" if $dbh->errstr;
[117]2166 }
2167 # group 1 is its own parent. need this here more to break strange loops than for detecting a parent
2168 last if $result->{$par_col{$type}} == 1;
[152]2169 $id = $result->{$par_col{$type}};
[117]2170 $type = $par_type{$type};
2171 }
2172
2173 return $foundparent;
2174} # end isParent()
2175
2176
[3]2177## DNSDB::domStatus()
2178# Sets and/or returns a domain's status
2179# Takes a database handle, domain ID and optionally a status argument
2180# Returns undef on errors.
2181sub domStatus {
2182 my $dbh = shift;
2183 my $id = shift;
2184 my $newstatus = shift;
2185
2186 return undef if $id !~ /^\d+$/;
2187
2188 my $sth;
2189
2190# ooo, fun! let's see what we were passed for status
2191 if ($newstatus) {
2192 $sth = $dbh->prepare("update domains set status=? where domain_id=?");
2193 # ass-u-me caller knows what's going on in full
2194 if ($newstatus =~ /^[01]$/) { # only two valid for now.
2195 $sth->execute($newstatus,$id);
2196 } elsif ($newstatus =~ /^domo(?:n|ff)$/) {
2197 $sth->execute(($newstatus eq 'domon' ? 1 : 0),$id);
2198 }
2199 }
2200
2201 $sth = $dbh->prepare("select status from domains where domain_id=?");
2202 $sth->execute($id);
2203 my ($status) = $sth->fetchrow_array;
2204 return $status;
2205} # end domStatus()
2206
2207
[33]2208## DNSDB::importAXFR
2209# Import a domain via AXFR
[37]2210# Takes AXFR host, domain to transfer, group to put the domain in,
2211# and optionally:
2212# - active/inactive state flag (defaults to active)
2213# - overwrite-SOA flag (defaults to off)
2214# - overwrite-NS flag (defaults to off, doesn't affect subdomain NS records)
2215# Returns a status code (OK, WARN, or FAIL) and message - message should be blank
2216# if status is OK, but WARN includes conditions that are not fatal but should
2217# really be reported.
[33]2218sub importAXFR {
2219 my $dbh = shift;
[35]2220 my $ifrom_in = shift;
[33]2221 my $domain = shift;
2222 my $group = shift;
2223 my $status = shift || 1;
2224 my $rwsoa = shift || 0;
2225 my $rwns = shift || 0;
[37]2226
[33]2227##fixme: add mode to delete&replace, merge+overwrite, merge new?
2228
[37]2229 my $nrecs = 0;
2230 my $soaflag = 0;
2231 my $nsflag = 0;
2232 my $warnmsg = '';
2233 my $ifrom;
[33]2234
[35]2235 # choke on possible bad setting in ifrom
[37]2236 # IPv4 and v6, and valid hostnames!
[35]2237 ($ifrom) = ($ifrom_in =~ /^([0-9a-f\:.]+|[0-9a-z_.-]+)$/i);
2238 return ('FAIL', "Bad AXFR source host $ifrom")
2239 unless ($ifrom) = ($ifrom_in =~ /^([0-9a-f\:.]+|[0-9a-z_.-]+)$/i);
2240
[33]2241 # Allow transactions, and raise an exception on errors so we can catch it later.
2242 # Use local to make sure these get "reset" properly on exiting this block
2243 local $dbh->{AutoCommit} = 0;
2244 local $dbh->{RaiseError} = 1;
2245
[37]2246 my $sth = $dbh->prepare("SELECT domain_id FROM domains WHERE domain=?");
[34]2247 my $dom_id;
2248
[35]2249# quick check to start to see if we've already got one
[37]2250 $sth->execute($domain);
2251 ($dom_id) = $sth->fetchrow_array;
[35]2252
2253 return ('FAIL', "Domain already exists") if $dom_id;
2254
[33]2255 eval {
2256 # can't do this, can't nest transactions. sigh.
[35]2257 #my ($dcode, $dmsg) = addDomain(dbh, domain, group, status);
[33]2258
2259##fixme: serial
[37]2260 my $sth = $dbh->prepare("INSERT INTO domains (domain,group_id,status) VALUES (?,?,?)");
2261 $sth->execute($domain,$group,$status);
[33]2262
[35]2263## bizarre DBI<->Net::DNS interaction bug:
2264## sometimes a zone will cause an immediate commit-and-exit (sort of) of the while()
[37]2265## fixed, apparently I was doing *something* odd, but not certain what it was that
2266## caused a commit instead of barfing
[35]2267
[33]2268 # get domain id so we can do the records
[37]2269 $sth = $dbh->prepare("SELECT domain_id FROM domains WHERE domain=?");
2270 $sth->execute($domain);
2271 ($dom_id) = $sth->fetchrow_array();
[33]2272
[34]2273 my $res = Net::DNS::Resolver->new;
[35]2274 $res->nameservers($ifrom);
2275 $res->axfr_start($domain)
2276 or die "Couldn't begin AXFR\n";
[34]2277
[35]2278 while (my $rr = $res->axfr_next()) {
[33]2279 my $type = $rr->type;
[35]2280
[34]2281 my $sql = "INSERT INTO records (domain_id,host,type,ttl,val";
[33]2282 my $vallen = "?,?,?,?,?";
2283
[37]2284 $soaflag = 1 if $type eq 'SOA';
2285 $nsflag = 1 if $type eq 'NS';
[35]2286
2287 my @vallist = ($dom_id, $rr->name, $reverse_typemap{$type}, $rr->ttl);
[34]2288
2289# "Primary" types:
2290# A, NS, CNAME, SOA, PTR(warn in forward), MX, TXT, AAAA, SRV, A6(ob), SPF
2291# maybe KEY
2292
[35]2293# nasty big ugly case-like thing here, since we have to do *some* different
2294# processing depending on the record. le sigh.
2295
[105]2296##fixme: what record types other than TXT can/will have >255-byte payloads?
2297
[34]2298 if ($type eq 'A') {
2299 push @vallist, $rr->address;
2300 } elsif ($type eq 'NS') {
[37]2301# hmm. should we warn here if subdomain NS'es are left alone?
2302 next if ($rwns && ($rr->name eq $domain));
[34]2303 push @vallist, $rr->nsdname;
[35]2304 $nsflag = 1;
[34]2305 } elsif ($type eq 'CNAME') {
2306 push @vallist, $rr->cname;
2307 } elsif ($type eq 'SOA') {
[37]2308 next if $rwsoa;
[34]2309 $vallist[1] = $rr->mname.":".$rr->rname;
2310 push @vallist, ($rr->refresh.":".$rr->retry.":".$rr->expire.":".$rr->minimum);
[35]2311 $soaflag = 1;
[34]2312 } elsif ($type eq 'PTR') {
[105]2313 push @vallist, $rr->ptrdname;
[34]2314 # hmm. PTR records should not be in forward zones.
2315 } elsif ($type eq 'MX') {
[33]2316 $sql .= ",distance";
2317 $vallen .= ",?";
[34]2318 push @vallist, $rr->exchange;
2319 push @vallist, $rr->preference;
2320 } elsif ($type eq 'TXT') {
2321##fixme: Net::DNS docs say this should be deprecated for rdatastr() or char_str_list(),
2322## but don't really seem enthusiastic about it.
[105]2323 my $rrdata = $rr->txtdata;
[130]2324 push @vallist, $rrdata;
[34]2325 } elsif ($type eq 'SPF') {
2326##fixme: and the same caveat here, since it is apparently a clone of ::TXT
[105]2327 my $rrdata = $rr->txtdata;
[130]2328 push @vallist, $rrdata;
[34]2329 } elsif ($type eq 'AAAA') {
2330 push @vallist, $rr->address;
2331 } elsif ($type eq 'SRV') {
2332 $sql .= ",distance,weight,port" if $type eq 'SRV';
2333 $vallen .= ",?,?,?" if $type eq 'SRV';
[37]2334 push @vallist, $rr->target;
[34]2335 push @vallist, $rr->priority;
2336 push @vallist, $rr->weight;
2337 push @vallist, $rr->port;
2338 } elsif ($type eq 'KEY') {
[35]2339 # we don't actually know what to do with these...
[34]2340 push @vallist, ($rr->flags.":".$rr->protocol.":".$rr->algorithm.":".$rr->key.":".$rr->keytag.":".$rr->privatekeyname);
[35]2341 } else {
[105]2342 my $rrdata = $rr->rdatastr;
[130]2343 push @vallist, $rrdata;
[35]2344 # Finding a different record type is not fatal.... just problematic.
[37]2345 # We may not be able to export it correctly.
[35]2346 $warnmsg .= "Unusual record ".$rr->name." ($type) found\n";
[33]2347 }
2348
[34]2349# BIND supports:
2350# A CNAME HINFO MB(ex) MD(ob) MF(ob) MG(ex) MINFO(ex) MR(ex) MX NS NULL
2351# PTR SOA TXT WKS AFSDB(ex) ISDN(ex) RP(ex) RT(ex) X25(ex) PX
2352# ... if one can ever find the right magic to format them correctly
2353
2354# Net::DNS supports:
2355# RRSIG SIG NSAP NS NIMLOC NAPTR MX MR MINFO MG MB LOC ISDN IPSECKEY HINFO
2356# EID DNAME CNAME CERT APL AFSDB AAAA A DS NXT NSEC3PARAM NSEC3 NSEC KEY
2357# DNSKEY DLV X25 TXT TSIG TKEY SSHFP SRV SPF SOA RT RP PX PTR NULL APL::AplItem
2358
[37]2359 $sth = $dbh->prepare($sql.") VALUES (".$vallen.")") or die "problem preparing record insert SQL\n";
2360 $sth->execute(@vallist) or die "failed to insert ".$rr->string.": ".$sth->errstr."\n";
[34]2361
[37]2362 $nrecs++;
[34]2363
[37]2364 } # while axfr_next
2365
2366 # Overwrite SOA record
2367 if ($rwsoa) {
2368 $soaflag = 1;
2369 my $sthgetsoa = $dbh->prepare("SELECT host,val,ttl FROM default_records WHERE group_id=? AND type=?");
2370 my $sthputsoa = $dbh->prepare("INSERT INTO records (domain_id,host,type,val,ttl) VALUES (?,?,?,?,?)");
2371 $sthgetsoa->execute($group,$reverse_typemap{SOA});
2372 while (my ($host,$val,$ttl) = $sthgetsoa->fetchrow_array()) {
2373 $host =~ s/DOMAIN/$domain/g;
2374 $val =~ s/DOMAIN/$domain/g;
2375 $sthputsoa->execute($dom_id,$host,$reverse_typemap{SOA},$val,$ttl);
[34]2376 }
[37]2377 }
[34]2378
[37]2379 # Overwrite NS records
2380 if ($rwns) {
2381 $nsflag = 1;
2382 my $sthgetns = $dbh->prepare("SELECT host,val,ttl FROM default_records WHERE group_id=? AND type=?");
2383 my $sthputns = $dbh->prepare("INSERT INTO records (domain_id,host,type,val,ttl) VALUES (?,?,?,?,?)");
2384 $sthgetns->execute($group,$reverse_typemap{NS});
2385 while (my ($host,$val,$ttl) = $sthgetns->fetchrow_array()) {
2386 $host =~ s/DOMAIN/$domain/g;
2387 $val =~ s/DOMAIN/$domain/g;
2388 $sthputns->execute($dom_id,$host,$reverse_typemap{NS},$val,$ttl);
2389 }
2390 }
[34]2391
[35]2392 die "No records found; either $ifrom is not authoritative or doesn't allow transfers\n" if !$nrecs;
2393 die "Bad zone: No SOA record!\n" if !$soaflag;
2394 die "Bad zone: No NS records!\n" if !$nsflag;
2395
[37]2396 $dbh->commit;
[35]2397
[33]2398 };
2399
2400 if ($@) {
2401 my $msg = $@;
2402 eval { $dbh->rollback; };
[34]2403 return ('FAIL',$msg." $warnmsg");
[33]2404 } else {
[35]2405 return ('WARN', $warnmsg) if $warnmsg;
[91]2406 return ('OK',"Imported OK");
[33]2407 }
2408
[37]2409 # it should be impossible to get here.
[34]2410 return ('WARN',"OOOK!");
[33]2411} # end importAXFR()
2412
2413
[103]2414## DNSDB::export()
2415# Export the DNS database, or a part of it
2416# Takes database handle, export type, optional arguments depending on type
2417# Writes zone data to targets as appropriate for type
2418sub export {
2419 my $dbh = shift;
2420 my $target = shift;
2421
2422 if ($target eq 'tiny') {
2423 __export_tiny($dbh,@_);
2424 }
2425# elsif ($target eq 'foo') {
2426# __export_foo($dbh,@_);
2427#}
2428# etc
2429
2430} # end export()
2431
2432
2433## DNSDB::__export_tiny
2434# Internal sub to implement tinyDNS (compatible) export
2435# Takes database handle, filehandle to write export to, optional argument(s)
2436# to determine which data gets exported
2437sub __export_tiny {
2438 my $dbh = shift;
2439 my $datafile = shift;
2440
2441##fixme: slurp up further options to specify particular zone(s) to export
2442
2443 ## Convert a bare number into an octal-coded pair of octets.
2444 # Take optional arg to indicate a decimal or hex input. Defaults to hex.
2445 sub octalize {
2446 my $tmp = shift;
2447 my $srctype = shift || 'h'; # default assumes hex string
2448 $tmp = sprintf "%0.4x", hex($tmp) if $srctype eq 'h'; # 0-pad hex to 4 digits
2449 $tmp = sprintf "%0.4x", $tmp if $srctype eq 'd'; # 0-pad decimal to 4 hex digits
2450 my @o = ($tmp =~ /^(..)(..)$/); # split into octets
2451 return sprintf "\\%0.3o\\%0.3o", hex($o[0]), hex($o[1]);;
2452 }
2453
2454##fixme: fail if $datafile isn't an open, writable file
2455
2456 # easy case - export all evarything
2457 # not-so-easy case - export item(s) specified
2458 # todo: figure out what kind of list we use to export items
2459
2460 my $domsth = $dbh->prepare("SELECT domain_id,domain,status FROM domains WHERE status=1");
[130]2461 my $recsth = $dbh->prepare("SELECT host,type,val,distance,weight,port,ttl ".
2462 "FROM records WHERE domain_id=?");
[103]2463 $domsth->execute();
2464 while (my ($domid,$dom,$domstat) = $domsth->fetchrow_array) {
2465 $recsth->execute($domid);
[130]2466 while (my ($host,$type,$val,$dist,$weight,$port,$ttl) = $recsth->fetchrow_array) {
[108]2467##fixme: need to store location in the db, and retrieve it here.
2468# temporarily hardcoded to empty so we can include it further down.
2469my $loc = '';
2470
2471##fixme: record validity timestamp. tinydns supports fiddling with timestamps.
2472# note $ttl must be set to 0 if we want to use tinydns's auto-expiring timestamps.
2473# timestamps are TAI64
2474# ~~ 2^62 + time()
2475my $stamp = '';
2476
[103]2477# raw packet in unknown format: first byte indicates length
2478# of remaining data, allows up to 255 raw bytes
2479
2480##fixme? append . to all host/val hostnames
2481 if ($typemap{$type} eq 'SOA') {
2482
2483 # host contains pri-ns:responsible
2484 # val is abused to contain refresh:retry:expire:minttl
2485##fixme: "manual" serial vs tinydns-autoserial
[202]2486 # let's be explicit about abusing $host and $val
2487 my ($email, $primary) = (split /:/, $host)[0,1];
2488 my ($refresh, $retry, $expire, $min_ttl) = (split /:/, $val)[0,1,2,3];
2489 print $datafile "Z$dom:$primary:$email"."::$refresh:$retry:$expire:$min_ttl:$ttl:$stamp:$loc\n";
[103]2490
2491 } elsif ($typemap{$type} eq 'A') {
2492
[108]2493 print $datafile "+$host:$val:$ttl:$stamp:$loc\n";
[103]2494
2495 } elsif ($typemap{$type} eq 'NS') {
2496
[108]2497 print $datafile "\&$host"."::$val:$ttl:$stamp:$loc\n";
[103]2498
2499 } elsif ($typemap{$type} eq 'AAAA') {
2500
2501 print $datafile ":$host:28:";
2502 my $altgrp = 0;
2503 my @altconv;
[108]2504 # Split in to up to 8 groups of hex digits (allows for IPv6 :: 0-collapsing)
[103]2505 foreach (split /:/, $val) {
2506 if (/^$/) {
2507 # flag blank entry; this is a series of 0's of (currently) unknown length
2508 $altconv[$altgrp++] = 's';
2509 } else {
2510 # call sub to convert 1-4 hex digits to 2 string-rep octal bytes
2511 $altconv[$altgrp++] = octalize($_)
2512 }
2513 }
2514 foreach my $octet (@altconv) {
2515 # if not 's', output
2516 print $datafile $octet unless $octet =~ /^s$/;
2517 # if 's', output (9-array length)x literal '\000\000'
2518 print $datafile '\000\000'x(9-$altgrp) if $octet =~ /^s$/;
2519 }
[108]2520 print $datafile ":$ttl:$stamp:$loc\n";
[103]2521
2522 } elsif ($typemap{$type} eq 'MX') {
2523
[108]2524 print $datafile "\@$host"."::$val:$dist:$ttl:$stamp:$loc\n";
[103]2525
2526 } elsif ($typemap{$type} eq 'TXT') {
2527
2528##fixme: split v-e-r-y long TXT strings? will need to do so for BIND export, at least
2529 $val =~ s/:/\\072/g; # may need to replace other symbols
[108]2530 print $datafile "'$host:$val:$ttl:$stamp:$loc\n";
[103]2531
2532# by-hand TXT
2533#:deepnet.cx:16:2v\075spf1\040a\040a\072bacon.deepnet.cx\040a\072home.deepnet.cx\040-all:3600
2534#@ IN TXT "v=spf1 a a:bacon.deepnet.cx a:home.deepnet.cx -all"
2535#'deepnet.cx:v=spf1 a a\072bacon.deepnet.cx a\072home.deepnet.cx -all:3600
2536
2537#txttest IN TXT "v=foo bar:bob kn;ob' \" !@#$%^&*()-=_+[]{}<>?"
2538#: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
2539
2540# very long TXT record as brought in by axfr-get
2541# note tinydns does not support >512-byte RR data, need axfr-dns (for TCP support) for that
2542# also note, tinydns does not seem to support <512, >256-byte RRdata from axfr-get either. :/
2543#:longtxt.deepnet.cx:16:
2544#\170this is a very long txt record. it is really long. long. very long. really very long. this is a very long txt record.
2545#\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.
2546#\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.
2547#:3600
2548
2549 } elsif ($typemap{$type} eq 'CNAME') {
2550
[108]2551 print $datafile "C$host:$val:$ttl:$stamp:$loc\n";
[103]2552
2553 } elsif ($typemap{$type} eq 'SRV') {
2554
2555 # data is two-byte values for priority, weight, port, in that order,
2556 # followed by length/string data
2557
2558 print $datafile ":$host:33:".octalize($dist,'d').octalize($weight,'d').octalize($port,'d');
2559
2560 $val .= '.' if $val !~ /\.$/;
2561 foreach (split /\./, $val) {
2562 printf $datafile "\\%0.3o%s", length($_), $_;
2563 }
[108]2564 print $datafile "\\000:$ttl:$stamp:$loc\n";
[103]2565
2566 } elsif ($typemap{$type} eq 'RP') {
2567
2568 # RP consists of two mostly free-form strings.
2569 # The first is supposed to be an email address with @ replaced by . (as with the SOA contact)
2570 # The second is the "hostname" of a TXT record with more info.
2571 print $datafile ":$host:17:";
2572 my ($who,$what) = split /\s/, $val;
2573 foreach (split /\./, $who) {
2574 printf $datafile "\\%0.3o%s", length($_), $_;
2575 }
2576 print $datafile '\000';
2577 foreach (split /\./, $what) {
2578 printf $datafile "\\%0.3o%s", length($_), $_;
2579 }
[108]2580 print $datafile "\\000:$ttl:$stamp:$loc\n";
[103]2581
2582 } elsif ($typemap{$type} eq 'PTR') {
2583
2584 # must handle both IPv4 and IPv6
2585##work
[108]2586 # data should already be in suitable reverse order.
2587 print $datafile "^$host:$val:$ttl:$stamp:$loc\n";
[103]2588
[108]2589 } else {
2590 # raw record. we don't know what's in here, so we ASS-U-ME the user has
2591 # put it in correctly, since either the user is messing directly with the
2592 # database, or the record was imported via AXFR
2593 # <split by char>
2594 # convert anything not a-zA-Z0-9.- to octal coding
2595
2596##fixme: add flag to export "unknown" record types - note we'll probably end up
2597# mangling them since they were written to the DB from Net::DNS::RR::<type>->rdatastr.
2598 #print $datafile ":$host:$type:$val:$ttl:$stamp:$loc\n";
2599
[103]2600 } # record type if-else
2601
2602 } # while ($recsth)
2603 } # while ($domsth)
2604} # end __export_tiny()
2605
2606
[197]2607## DNSDB::mailNotify()
2608# Sends notification mail to recipients regarding an IPDB operation
2609sub mailNotify {
2610 my $dbh = shift;
2611 my ($subj,$message) = @_;
2612
2613 return if $config{mailhost} eq 'smtp.example.com'; # do nothing if still using default SMTP host.
2614
2615 my $mailer = Net::SMTP->new($config{mailhost}, Hello => "dnsadmin.$config{domain}");
2616
2617 my $mailsender = ($config{mailsender} ? $config{mailsender} : $config{mailnotify});
2618
2619 $mailer->mail($mailsender);
2620 $mailer->to($config{mailnotify});
[198]2621 $mailer->data("From: \"$config{mailname}\" <$mailsender>\n",
2622 "To: <$config{mailnotify}>\n",
[197]2623 "Date: ".strftime("%a, %d %b %Y %H:%M:%S %z",localtime)."\n",
2624 "Subject: $subj\n",
2625 "X-Mailer: DNSAdmin Notify v".sprintf("%.1d",$DNSDB::VERSION)."\n",
2626 "Organization: $config{orgname}\n",
2627 "\n$message\n");
2628 $mailer->quit;
2629}
2630
[2]2631# shut Perl up
26321;
Note: See TracBrowser for help on using the repository browser.