source: trunk/DNSDB.pm@ 228

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

/trunk

Refactoring record data validation, first pass.
Stub out validation subs for all supported types, and fill a hash

with function references for *all* types in initGlobals()

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