source: trunk/DNSDB.pm@ 226

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

/trunk

Update addRec() for reverse zones, first pass. A+PTR and AAAA+PTR should be complete.
See #26.

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