source: trunk/DNSDB.pm@ 197

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

/trunk

Prepare for spamming! Add mailNotify() stolen and trimmed back from
https://secure.deepnet.cx/svn/ipdb/cgi-bin/IPDB.pm

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