source: trunk/DNSDB.pm@ 125

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

/trunk

Fill out the remaining stubbed RPC calls; other subs from DNSDB

aren't as cleanly exposeable

Minor error-handling tweak in DNSDB.pm while retrieving a record line

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