source: trunk/DNSDB.pm@ 214

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

/trunk

Begin setting up the barest sketch of what will eventually become
a complete automagical DB init/upgrade feature. See #34.

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