source: trunk/DNSDB.pm@ 191

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

/trunk

Minor fix in dns-rpc.cgi to load DB user/pass/etc with loadConfig

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