source: trunk/DNSDB.pm@ 220

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

/trunk

Add some nifty bits to allow packaged or install-via-make-install
setups to keep multiple versions, same as the run-from-the-tarball
Add .spec file

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