source: trunk/DNSDB.pm@ 231

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

/trunk

Add info comments in TXT and RP validation subs; TXT records are

freeform, RP are arguably obsolete and not shown for new records
anyway.

Fill out SRV validation

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