source: trunk/DNSDB.pm@ 224

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

/trunk

Start adding rDNS (See #26)

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