source: trunk/DNSDB.pm@ 211

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

/trunk

Fix up error reporting in addRec(); don't want to cause unintelligible
database errors where we can catch data-type mismatches before touching
the DB.

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