source: trunk/DNSDB.pm@ 216

Last change on this file since 216 was 216, checked in by Kris Deugau, 12 years ago

/trunk

Found some not-so-little things missing for a tarball

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