source: trunk/DNSDB.pm@ 196

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

/trunk

Minor fix on SRV validation; accept uppercase in the domain part
of the hostname. Found when trying to add a default SRV record.

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