source: trunk/DNSDB.pm@ 232

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

/trunk

Checkpoint - almost done PTR, A/AAAA+PTR types. Still need to
figure out validation on default-record inputs.

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