source: trunk/DNSDB.pm@ 230

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

/trunk

Fill out _validate_* subs for NS, CNAME, and MX.
Put comment in _6 (SOA) to remind me that SOA records are handled

completely separately from others

Converted A and AAAA to pass all everything except the database

handle in a hash; I realized while filling out _validate_15()
(MX) that trying to pass arguments in a defined order was going
to get stupid very fast.

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