source: trunk/DNSDB.pm@ 201

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

/trunk

Add perpage to config load
Switch SOA defaults to only pick up digits in config. Could be

updated to parse eg 1h, 2w, 30m, etc

Add group-tree open/closed pointer images to MANIFEST
Add an explicit value for makeactive on the newdomain template

to plug up a minor error log leak

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