source: trunk/DNSDB.pm@ 193

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

/trunk

Hack _log() to dig up user data when (not if) it's missing. Better solution needed.
Clean up debugging statements in addDomain()
Add some ##fixme's to dns.cgi
Log distance, port, weight as needed for new MX, SRV records

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