source: trunk/DNSDB.pm@ 229

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

/trunk

Record validation refactoring
Complete A and AAAA record (*almost* identical)

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