source: trunk/DNSDB.pm@ 107

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

/trunk

Fix mishandling of record data retrieved before deleting said record.
Tweak logging on record deletion - probably failing due to

mishandling the retrieval.

  • Property svn:keywords set to Date Rev Author Id
File size: 54.1 KB
RevLine 
[2]1# dns/trunk/DNSDB.pm
2# Abstraction functions for DNS administration
3###
4# SVN revision info
5# $Date: 2011-07-19 20:50:08 +0000 (Tue, 19 Jul 2011) $
6# SVN revision $Rev: 107 $
7# Last update by $Author: kdeugau $
8###
9# Copyright (C) 2008 - Kris Deugau <kdeugau@deepnet.cx>
10
11package DNSDB;
12
13use strict;
14use warnings;
15use Exporter;
16use DBI;
[33]17use Net::DNS;
[65]18use Crypt::PasswdMD5;
[2]19#use Net::SMTP;
20#use NetAddr::IP qw( Compact );
21#use POSIX;
22use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
23
24$VERSION = 0.1;
25@ISA = qw(Exporter);
26@EXPORT_OK = qw(
[67]27 &initGlobals
28 &initPermissions &getPermissions &changePermissions &comparePermissions
[65]29 &connectDB &finish
[91]30 &addDomain &delDomain &domainName &domainID
[22]31 &addGroup &delGroup &getChildren &groupName
[83]32 &addUser &updateUser &delUser &userFullName &userStatus &getUserData
[91]33 &getSOA &getRecLine &getDomRecs &getRecCount
[22]34 &addRec &updateRec &delRec
[34]35 &domStatus &importAXFR
[103]36 &export
[2]37 %typemap %reverse_typemap
[66]38 %permissions @permtypes $permlist
[2]39 );
40
41@EXPORT = (); # Export nothing by default.
42%EXPORT_TAGS = ( ALL => [qw(
[67]43 &initGlobals
44 &initPermissions &getPermissions &changePermissions &comparePermissions
[65]45 &connectDB &finish
[91]46 &addDomain &delDomain &domainName &domainID
[22]47 &addGroup &delGroup &getChildren &groupName
[83]48 &addUser &updateUser &delUser &userFullName &userStatus &getUserData
[91]49 &getSOA &getRecLine &getDomRecs &getRecCount
[22]50 &addRec &updateRec &delRec
[34]51 &domStatus &importAXFR
[103]52 &export
[2]53 %typemap %reverse_typemap
[66]54 %permissions @permtypes $permlist
[2]55 )]
56 );
57
58our $group = 1;
59our $errstr = '';
60
61# Halfway sane defaults for SOA, TTL, etc.
[101]62# serial defaults to 0 for convenience.
63# value will be either YYYYMMDDNN for BIND/etc, or auto-internal for tinydns
[2]64our %def = qw (
65 contact hostmaster.DOMAIN
66 prins ns1.myserver.com
[101]67 serial 0
[2]68 soattl 86400
69 refresh 10800
70 retry 3600
71 expire 604800
72 minttl 10800
73 ttl 10800
74);
75
[66]76# Arguably defined wholly in the db, but little reason to change without supporting code changes
77our @permtypes = qw (
78 group_edit group_create group_delete
79 user_edit user_create user_delete
80 domain_edit domain_create domain_delete
81 record_edit record_create record_delete
82 self_edit admin
83);
84our $permlist = join(',',@permtypes);
85
[2]86# DNS record type map and reverse map.
87# loaded from the database, from http://www.iana.org/assignments/dns-parameters
88our %typemap;
89our %reverse_typemap;
90
[65]91our %permissions;
[55]92
[2]93##
94## Initialization and cleanup subs
95##
96
[55]97
[2]98## DNSDB::connectDB()
99# Creates connection to DNS database.
100# Requires the database name, username, and password.
101# Returns a handle to the db.
102# Set up for a PostgreSQL db; could be any transactional DBMS with the
103# right changes.
104sub connectDB {
105 $errstr = '';
[15]106 my $dbname = shift;
107 my $user = shift;
108 my $pass = shift;
[2]109 my $dbh;
110 my $DSN = "DBI:Pg:dbname=$dbname";
111
112 my $host = shift;
113 $DSN .= ";host=$host" if $host;
114
115# Note that we want to autocommit by default, and we will turn it off locally as necessary.
116# We may not want to print gobbledygook errors; YMMV. Have to ponder that further.
117 $dbh = DBI->connect($DSN, $user, $pass, {
118 AutoCommit => 1,
119 PrintError => 0
120 })
121 or return (undef, $DBI::errstr) if(!$dbh);
122
123# Return here if we can't select. Note that this indicates a
124# problem executing the select.
125 my $sth = $dbh->prepare("select group_id from groups limit 1");
126 $sth->execute();
127 return (undef,$DBI::errstr) if ($sth->err);
128
129# See if the select returned anything (or null data). This should
130# succeed if the select executed, but...
131 $sth->fetchrow();
132 return (undef,$DBI::errstr) if ($sth->err);
133
134 $sth->finish;
135
136# If we get here, we should be OK.
137 return ($dbh,"DB connection OK");
138} # end connectDB
139
140
141## DNSDB::finish()
142# Cleans up after database handles and so on.
143# Requires a database handle
144sub finish {
145 my $dbh = $_[0];
146 $dbh->disconnect;
147} # end finish
148
149
150## DNSDB::initGlobals()
151# Initialize global variables
152# NB: this does NOT include web-specific session variables!
153# Requires a database handle
154sub initGlobals {
155 my $dbh = shift;
156
157# load system-wide site defaults and things from config file
[29]158 if (open SYSDEFAULTS, "</etc/dnsdb.conf") {
[2]159##fixme - error check!
[29]160 while (<SYSDEFAULTS>) {
161 next if /^\s*#/;
162 $def{contact} = $1 if /contact ?= ?([a-z0-9_.-]+)/i;
163 $def{prins} = $1 if /prins ?= ?([a-z0-9_.-]+)/i;
164 $def{soattl} = $1 if /soattl ?= ?([a-z0-9_.-]+)/i;
165 $def{refresh} = $1 if /refresh ?= ?([a-z0-9_.-]+)/i;
166 $def{retry} = $1 if /retry ?= ?([a-z0-9_.-]+)/i;
167 $def{expire} = $1 if /expire ?= ?([a-z0-9_.-]+)/i;
168 $def{minttl} = $1 if /minttl ?= ?([a-z0-9_.-]+)/i;
169 $def{ttl} = $1 if /ttl ?= ?([a-z0-9_.-]+)/i;
[2]170##fixme? load DB user/pass from config file?
[29]171 }
[2]172 }
173# load from database
174 my $sth = $dbh->prepare("select val,name from rectypes");
175 $sth->execute;
176 while (my ($recval,$recname) = $sth->fetchrow_array()) {
177 $typemap{$recval} = $recname;
178 $reverse_typemap{$recname} = $recval;
179 }
180} # end initGlobals
181
182
[65]183## DNSDB::initPermissions()
184# Set up permissions global
185# Takes database handle and UID
186sub initPermissions {
187 my $dbh = shift;
188 my $uid = shift;
189
190# %permissions = $(getPermissions($dbh,'user',$uid));
191 getPermissions($dbh, 'user', $uid, \%permissions);
192
193} # end initPermissions()
194
195
196## DNSDB::getPermissions()
197# Get permissions from DB
198# Requires DB handle, group or user flag, ID, and hashref.
199sub getPermissions {
200 my $dbh = shift;
201 my $type = shift;
202 my $id = shift;
203 my $hash = shift;
204
205 my $sql = qq(
206 SELECT
207 p.admin,p.self_edit,
208 p.group_create,p.group_edit,p.group_delete,
209 p.user_create,p.user_edit,p.user_delete,
210 p.domain_create,p.domain_edit,p.domain_delete,
211 p.record_create,p.record_edit,p.record_delete
212 FROM permissions p
213 );
214 if ($type eq 'group') {
215 $sql .= qq(
216 JOIN groups g ON g.permission_id=p.permission_id
217 WHERE g.group_id=?
218 );
219 } else {
220 $sql .= qq(
221 JOIN users u ON u.permission_id=p.permission_id
222 WHERE u.user_id=?
223 );
224 }
225
226 my $sth = $dbh->prepare($sql);
227
228 $sth->execute($id) or die "argh: ".$sth->errstr;
229
230# my $permref = $sth->fetchrow_hashref;
231# return $permref;
232# $hash = $permref;
233# Eww. Need to learn how to forcibly drop a hashref onto an existing hash.
234 ($hash->{admin},$hash->{self_edit},
235 $hash->{group_create},$hash->{group_edit},$hash->{group_delete},
236 $hash->{user_create},$hash->{user_edit},$hash->{user_delete},
237 $hash->{domain_create},$hash->{domain_edit},$hash->{domain_delete},
238 $hash->{record_create},$hash->{record_edit},$hash->{record_delete})
239 = $sth->fetchrow_array;
240
241} # end getPermissions()
242
243
244## DNSDB::changePermissions()
245# Update an ACL entry
246# Takes a db handle, type, owner-id, and hashref for the changed permissions.
247sub changePermissions {
248 my $dbh = shift;
249 my $type = shift;
250 my $id = shift;
251 my $newperms = shift;
[87]252 my $inherit = shift || 0;
[65]253
[78]254 my $failmsg = '';
[66]255
[87]256 # see if we're switching from inherited to custom. for bonus points,
257 # snag the permid and parent permid anyway, since we'll need the permid
258 # to set/alter custom perms, and both if we're switching from custom to
259 # inherited.
260 my $sth = $dbh->prepare("SELECT (u.permission_id=g.permission_id) AS was_inherited,u.permission_id,g.permission_id".
[65]261 " FROM ".($type eq 'user' ? 'users' : 'groups')." u ".
[66]262 " JOIN groups g ON u.".($type eq 'user' ? '' : 'parent_')."group_id=g.group_id ".
[65]263 " WHERE u.".($type eq 'user' ? 'user' : 'group')."_id=?");
264 $sth->execute($id);
265
[87]266 my ($wasinherited,$permid,$parpermid) = $sth->fetchrow_array;
[66]267
[78]268# hack phtoui
269# group id 1 is "special" in that it's it's own parent (err... possibly.)
270# may make its parent id 0 which doesn't exist, and as a bonus is Perl-false.
271 $wasinherited = 0 if ($type eq 'group' && $id == 1);
272
[66]273 local $dbh->{AutoCommit} = 0;
274 local $dbh->{RaiseError} = 1;
275
276 # Wrap all the SQL in a transaction
277 eval {
[87]278 if ($inherit) {
279
280 $dbh->do("UPDATE ".($type eq 'user' ? 'users' : 'groups')." SET inherit_perm='t',permission_id=? ".
281 "WHERE ".($type eq 'user' ? 'user' : 'group')."_id=?", undef, ($parpermid, $id) );
282 $dbh->do("DELETE FROM permissions WHERE permission_id=?", undef, ($permid) );
283
284 } else {
285
286 if ($wasinherited) { # munge new permission entry in if we're switching from inherited perms
[66]287##fixme: need to add semirecursive bit to properly munge inherited permission ID on subgroups and users
[87]288# ... if'n'when we have groups with fully inherited permissions.
289 # SQL is coo
290 $dbh->do("INSERT INTO permissions ($permlist,".($type eq 'user' ? 'user' : 'group')."_id) ".
291 "SELECT $permlist,? FROM permissions WHERE permission_id=?", undef, ($id,$permid) );
292 ($permid) = $dbh->selectrow_array("SELECT permission_id FROM permissions ".
293 "WHERE ".($type eq 'user' ? 'user' : 'group')."_id=?", undef, ($id) );
294 $dbh->do("UPDATE ".($type eq 'user' ? 'users' : 'groups')." SET inherit_perm='f',permission_id=? ".
295 "WHERE ".($type eq 'user' ? 'user' : 'group')."_id=?", undef, ($permid, $id) );
[66]296 }
[78]297
[87]298 # and now set the permissions we were passed
299 foreach (@permtypes) {
300 if (defined ($newperms->{$_})) {
301 $dbh->do("UPDATE permissions SET $_=? WHERE permission_id=?", undef, ($newperms->{$_},$permid) );
302 }
303 }
304
305 } # (inherited->)? custom
306
[66]307 $dbh->commit;
308 }; # end eval
309 if ($@) {
310 my $msg = $@;
311 eval { $dbh->rollback; };
[87]312 return ('FAIL',"$failmsg: $msg ($permid)");
[66]313 } else {
314 return ('OK',$permid);
315 }
316
[65]317} # end changePermissions()
318
319
[67]320## DNSDB::comparePermissions()
321# Compare two permission hashes
322# Returns '>', '<', '=', '!'
323sub comparePermissions {
324 my $p1 = shift;
325 my $p2 = shift;
326
327 my $retval = '='; # assume equality until proven otherwise
328
329 no warnings "uninitialized";
330
331 foreach (@permtypes) {
332 next if $p1->{$_} == $p2->{$_}; # equal is good
333 if ($p1->{$_} && !$p2->{$_}) {
334 if ($retval eq '<') { # if we've already found an unequal pair where
335 $retval = '!'; # $p2 has more access, and we now find a pair
336 last; # where $p1 has more access, the overall access
337 } # is neither greater or lesser, it's unequal.
338 $retval = '>';
339 }
340 if (!$p1->{$_} && $p2->{$_}) {
341 if ($retval eq '>') { # if we've already found an unequal pair where
342 $retval = '!'; # $p1 has more access, and we now find a pair
343 last; # where $p2 has more access, the overall access
344 } # is neither greater or lesser, it's unequal.
345 $retval = '<';
346 }
347 }
348 return $retval;
349} # end comparePermissions()
350
351
[55]352## DNSDB::_log()
353# Log an action
354# Internal sub
355# Takes a database handle, <foo>, <bar>
356sub _log {
357} # end _log
358
359
[2]360##
361## Processing subs
362##
363
364## DNSDB::addDomain()
365# Add a domain
366# Takes a database handle, domain name, numeric group, and boolean(ish) state (active/inactive)
367# Returns a status code and message
368sub addDomain {
369 $errstr = '';
370 my $dbh = shift;
371 return ('FAIL',"Need database handle") if !$dbh;
372 my $domain = shift;
[91]373 return ('FAIL',"Domain must not be blank") if !$domain;
[2]374 my $group = shift;
375 return ('FAIL',"Need group") if !defined($group);
376 my $state = shift;
377 return ('FAIL',"Need domain status") if !defined($state);
378
[38]379 my $sth = $dbh->prepare("SELECT domain_id FROM domains WHERE domain=?");
[3]380 my $dom_id;
381
[38]382# quick check to start to see if we've already got one
383 $sth->execute($domain);
384 ($dom_id) = $sth->fetchrow_array;
385
386 return ('FAIL', "Domain already exists") if $dom_id;
387
[2]388 # Allow transactions, and raise an exception on errors so we can catch it later.
389 # Use local to make sure these get "reset" properly on exiting this block
390 local $dbh->{AutoCommit} = 0;
391 local $dbh->{RaiseError} = 1;
392
393 # Wrap all the SQL in a transaction
394 eval {
395 # insert the domain...
396 my $sth = $dbh->prepare("insert into domains (domain,group_id,status) values (?,?,?)");
397 $sth->execute($domain,$group,$state);
398
399 # get the ID...
400 $sth = $dbh->prepare("select domain_id from domains where domain='$domain'");
401 $sth->execute;
[3]402 ($dom_id) = $sth->fetchrow_array();
[2]403
404 # ... and now we construct the standard records from the default set. NB: group should be variable.
[3]405 $sth = $dbh->prepare("select host,type,val,distance,weight,port,ttl from default_records where group_id=$group");
406 my $sth_in = $dbh->prepare("insert into records (domain_id,host,type,val,distance,weight,port,ttl)".
407 " values ($dom_id,?,?,?,?,?,?,?)");
[2]408 $sth->execute;
[3]409 while (my ($host,$type,$val,$dist,$weight,$port,$ttl) = $sth->fetchrow_array()) {
[2]410 $host =~ s/DOMAIN/$domain/g;
[37]411 $val =~ s/DOMAIN/$domain/g;
[3]412 $sth_in->execute($host,$type,$val,$dist,$weight,$port,$ttl);
[2]413 }
414
415 # once we get here, we should have suceeded.
416 $dbh->commit;
417 }; # end eval
418
419 if ($@) {
420 my $msg = $@;
421 eval { $dbh->rollback; };
422 return ('FAIL',$msg);
423 } else {
[3]424 return ('OK',$dom_id);
[2]425 }
426} # end addDomain
427
428
[3]429## DNSDB::delDomain()
430# Delete a domain.
431# for now, just delete the records, then the domain.
432# later we may want to archive it in some way instead (status code 2, for example?)
433sub delDomain {
434 my $dbh = shift;
[5]435 my $domid = shift;
[3]436
437 # Allow transactions, and raise an exception on errors so we can catch it later.
438 # Use local to make sure these get "reset" properly on exiting this block
439 local $dbh->{AutoCommit} = 0;
440 local $dbh->{RaiseError} = 1;
441
[23]442 my $failmsg = '';
443
[3]444 # Wrap all the SQL in a transaction
445 eval {
[5]446 my $sth = $dbh->prepare("delete from records where domain_id=?");
[23]447 $failmsg = "Failure removing domain records";
[5]448 $sth->execute($domid);
449 $sth = $dbh->prepare("delete from domains where domain_id=?");
[23]450 $failmsg = "Failure removing domain";
[5]451 $sth->execute($domid);
[3]452
453 # once we get here, we should have suceeded.
[23]454 $dbh->commit;
[3]455 }; # end eval
456
457 if ($@) {
458 my $msg = $@;
459 eval { $dbh->rollback; };
[23]460 return ('FAIL',"$failmsg: $msg");
[3]461 } else {
462 return ('OK','OK');
463 }
464
465} # end delDomain()
466
467
[2]468## DNSDB::domainName()
469# Return the domain name based on a domain ID
470# Takes a database handle and the domain ID
471# Returns the domain name or undef on failure
472sub domainName {
473 $errstr = '';
474 my $dbh = shift;
475 my $domid = shift;
[91]476 my ($domname) = $dbh->selectrow_array("SELECT domain FROM domains WHERE domain_id=?", undef, ($domid) );
[2]477 $errstr = $DBI::errstr if !$domname;
478 return $domname if $domname;
[91]479} # end domainName()
[2]480
481
[91]482## DNSDB::domainID()
483# Takes a database handle and domain name
484# Returns the domain ID number
485sub domainID {
486 $errstr = '';
487 my $dbh = shift;
488 my $domain = shift;
489 my ($domid) = $dbh->selectrow_array("SELECT domain_id FROM domains WHERE domain=?", undef, ($domain) );
490 $errstr = $DBI::errstr if !$domid;
491 return $domid if $domid;
492} # end domainID()
493
494
[18]495## DNSDB::addGroup()
496# Add a group
[66]497# Takes a database handle, group name, parent group, hashref for permissions,
498# and optional template-vs-cloneme flag
[18]499# Returns a status code and message
500sub addGroup {
501 $errstr = '';
502 my $dbh = shift;
[20]503 my $groupname = shift;
504 my $pargroup = shift;
[66]505 my $permissions = shift;
[18]506
[66]507 # 0 indicates "custom", hardcoded.
[18]508 # Any other value clones that group's default records, if it exists.
[66]509 my $inherit = shift || 0;
510##fixme: need a flag to indicate clone records or <?> ?
[18]511
512 # Allow transactions, and raise an exception on errors so we can catch it later.
513 # Use local to make sure these get "reset" properly on exiting this block
514 local $dbh->{AutoCommit} = 0;
515 local $dbh->{RaiseError} = 1;
516
[38]517 my $sth = $dbh->prepare("SELECT group_id FROM groups WHERE group_name=?");
518 my $group_id;
519
520# quick check to start to see if we've already got one
521 $sth->execute($groupname);
522 ($group_id) = $sth->fetchrow_array;
523
524 return ('FAIL', "Group already exists") if $group_id;
525
[18]526 # Wrap all the SQL in a transaction
527 eval {
[38]528 $sth = $dbh->prepare("INSERT INTO groups (parent_group_id,group_name) VALUES (?,?)");
[20]529 $sth->execute($pargroup,$groupname);
[18]530
531 $sth = $dbh->prepare("SELECT group_id FROM groups WHERE group_name=?");
[20]532 $sth->execute($groupname);
533 my ($groupid) = $sth->fetchrow_array();
[18]534
[66]535# Permissions
536 if ($inherit) {
537 } else {
538 my @permvals;
539 foreach (@permtypes) {
540 if (!defined ($permissions->{$_})) {
541 push @permvals, 0;
542 } else {
543 push @permvals, $permissions->{$_};
544 }
545 }
546
547 $sth = $dbh->prepare("INSERT INTO permissions (group_id,$permlist) values (?".',?'x($#permtypes+1).")");
548 $sth->execute($groupid,@permvals);
549
550 $sth = $dbh->prepare("SELECT permission_id FROM permissions WHERE group_id=?");
551 $sth->execute($groupid);
552 my ($permid) = $sth->fetchrow_array();
553
554 $dbh->do("UPDATE groups SET permission_id=$permid WHERE group_id=$groupid");
555 } # done permission fiddling
556
557# Default records
[18]558 $sth = $dbh->prepare("INSERT INTO default_records (group_id,host,type,val,distance,weight,port,ttl) ".
[20]559 "VALUES ($groupid,?,?,?,?,?,?,?)");
[66]560 if ($inherit) {
[87]561 # Duplicate records from parent. Actually relying on inherited records feels
562 # very fragile, and it would be problematic to roll over at a later time.
[18]563 my $sth2 = $dbh->prepare("SELECT host,type,val,distance,weight,port,ttl FROM default_records WHERE group_id=?");
[87]564 $sth2->execute($pargroup);
[18]565 while (my @clonedata = $sth2->fetchrow_array) {
566 $sth->execute(@clonedata);
567 }
568 } else {
[66]569##fixme: Hardcoding is Bad, mmmmkaaaay?
[18]570 # reasonable basic defaults for SOA, MX, NS, and minimal hosting
571 # could load from a config file, but somewhere along the line we need hardcoded bits.
572 $sth->execute('ns1.example.com:hostmaster.example.com', 6, '10800:3600:604800:10800', 0, 0, 0, 86400);
573 $sth->execute('DOMAIN', 1, '192.168.4.2', 0, 0, 0, 7200);
574 $sth->execute('DOMAIN', 15, 'mx.example.com', 10, 0, 0, 7200);
575 $sth->execute('DOMAIN', 2, 'ns1.example.com', 0, 0, 0, 7200);
576 $sth->execute('DOMAIN', 2, 'ns2.example.com', 0, 0, 0, 7200);
577 $sth->execute('www.DOMAIN', 5, 'DOMAIN', 0, 0, 0, 7200);
578 }
579
580 # once we get here, we should have suceeded.
581 $dbh->commit;
582 }; # end eval
583
584 if ($@) {
585 my $msg = $@;
586 eval { $dbh->rollback; };
587 return ('FAIL',$msg);
588 } else {
589 return ('OK','OK');
590 }
591
592} # end addGroup()
593
594
[22]595## DNSDB::delGroup()
596# Delete a group.
597# Takes a group ID
598# Returns a status code and message
599sub delGroup {
600 my $dbh = shift;
601 my $groupid = shift;
602
603 # Allow transactions, and raise an exception on errors so we can catch it later.
604 # Use local to make sure these get "reset" properly on exiting this block
605 local $dbh->{AutoCommit} = 0;
606 local $dbh->{RaiseError} = 1;
607
608##fixme: locate "knowable" error conditions and deal with them before the eval
[23]609# ... or inside, whatever.
[22]610# -> domains still exist in group
611# -> ...
[23]612 my $failmsg = '';
[22]613
614 # Wrap all the SQL in a transaction
615 eval {
[23]616 my $sth = $dbh->prepare("SELECT count(*) FROM domains WHERE group_id=?");
[22]617 $sth->execute($groupid);
[23]618 my ($domcnt) = $sth->fetchrow_array;
619 $failmsg = "Can't remove group ".groupName($dbh,$groupid);
620 die "$domcnt domains still in group\n" if $domcnt;
621
622 $sth = $dbh->prepare("delete from default_records where group_id=?");
623 $failmsg = "Failed to delete default records for ".groupName($dbh,$groupid);
624 $sth->execute($groupid);
[22]625 $sth = $dbh->prepare("delete from groups where group_id=?");
[23]626 $failmsg = "Failed to remove group ".groupName($dbh,$groupid);
[22]627 $sth->execute($groupid);
628
629 # once we get here, we should have suceeded.
630 $dbh->commit;
631 }; # end eval
632
633 if ($@) {
634 my $msg = $@;
635 eval { $dbh->rollback; };
[23]636 return ('FAIL',"$failmsg: $msg");
[22]637 } else {
638 return ('OK','OK');
639 }
640} # end delGroup()
641
642
[19]643## DNSDB::getChildren()
644# Get a list of all groups whose parent^n is group <n>
[24]645# Takes a database handle, group ID, reference to an array to put the group IDs in,
646# and an optional flag to return only immediate children or all children-of-children
647# default to returning all children
[19]648# Calls itself
649sub getChildren {
650 $errstr = '';
651 my $dbh = shift;
[20]652 my $rootgroup = shift;
653 my $groupdest = shift;
[24]654 my $immed = shift || 'all';
[19]655
656 # special break for default group; otherwise we get stuck.
[20]657 if ($rootgroup == 1) {
[19]658 # by definition, group 1 is the Root Of All Groups
[24]659 my $sth = $dbh->prepare("SELECT group_id FROM groups WHERE NOT (group_id=1)".
660 ($immed ne 'all' ? " AND parent_group_id=1" : ''));
[19]661 $sth->execute;
662 while (my @this = $sth->fetchrow_array) {
[20]663 push @$groupdest, @this;
[19]664 }
665 } else {
666 my $sth = $dbh->prepare("SELECT group_id FROM groups WHERE parent_group_id=?");
[20]667 $sth->execute($rootgroup);
[19]668 return if $sth->rows == 0;
[20]669 my @grouplist;
670 while (my ($group) = $sth->fetchrow_array) {
671 push @$groupdest, $group;
[24]672 getChildren($dbh,$group,$groupdest) if $immed eq 'all';
[19]673 }
674 }
675} # end getChildren()
676
677
[20]678## DNSDB::groupName()
[17]679# Return the group name based on a group ID
680# Takes a database handle and the group ID
681# Returns the group name or undef on failure
[20]682sub groupName {
[13]683 $errstr = '';
684 my $dbh = shift;
[20]685 my $groupid = shift;
686 my $sth = $dbh->prepare("SELECT group_name FROM groups WHERE group_id=?");
687 $sth->execute($groupid);
688 my ($groupname) = $sth->fetchrow_array();
689 $errstr = $DBI::errstr if !$groupname;
690 return $groupname if $groupname;
691} # end groupName
[13]692
693
[24]694## DNSDB::addUser()
[87]695# Add a user.
696# Takes a DB handle, username, group ID, password, state (active/inactive).
697# Optionally accepts:
698# user type (user/admin) - defaults to user
699# permissions string - defaults to inherit from group
700# three valid forms:
701# i - Inherit permissions
702# c:<user_id> - Clone permissions from <user_id>
703# C:<permission list> - Set these specific permissions
704# first name - defaults to username
705# last name - defaults to blank
706# phone - defaults to blank (could put other data within column def)
[90]707# Returns (OK,<uid>) on success, (FAIL,<message>) on failure
[24]708sub addUser {
709 $errstr = '';
710 my $dbh = shift;
711 my $username = shift;
712 my $group = shift;
713 my $pass = shift;
714 my $state = shift;
[25]715
[90]716 return ('FAIL', "Missing one or more required entries") if !defined($state);
717 return ('FAIL', "Username must not be blank") if !$username;
[87]718
[25]719 my $type = shift || 'u'; # create limited users by default - fwiw, not sure yet how this will interact with ACLs
720
[67]721 my $permstring = shift || 'i'; # default is to inhert permissions from group
722
[25]723 my $fname = shift || $username;
[24]724 my $lname = shift || '';
[25]725 my $phone = shift || ''; # not going format-check
[24]726
[38]727 my $sth = $dbh->prepare("SELECT user_id FROM users WHERE username=?");
[24]728 my $user_id;
729
[38]730# quick check to start to see if we've already got one
731 $sth->execute($username);
732 ($user_id) = $sth->fetchrow_array;
733
734 return ('FAIL', "User already exists") if $user_id;
735
[24]736 # Allow transactions, and raise an exception on errors so we can catch it later.
737 # Use local to make sure these get "reset" properly on exiting this block
738 local $dbh->{AutoCommit} = 0;
739 local $dbh->{RaiseError} = 1;
740
[94]741 my $failmsg = '';
742
[24]743 # Wrap all the SQL in a transaction
744 eval {
[87]745 # insert the user... note we set inherited perms by default since
746 # it's simple and cleans up some other bits of state
747 my $sth = $dbh->prepare("INSERT INTO users ".
748 "(group_id,username,password,firstname,lastname,phone,type,status,permission_id,inherit_perm) ".
749 "VALUES (?,?,?,?,?,?,?,?,(SELECT permission_id FROM permissions WHERE group_id=?),'t')");
750 $sth->execute($group,$username,unix_md5_crypt($pass),$fname,$lname,$phone,$type,$state,$group);
[24]751
752 # get the ID...
[94]753 ($user_id) = $dbh->selectrow_array("SELECT currval('users_user_id_seq')");
[24]754
[87]755# Permissions! Gotta set'em all!
756 die "Invalid permission string $permstring"
757 if $permstring !~ /^(?:
758 i # inherit
759 |c:\d+ # clone
760 # custom. no, the leading , is not a typo
761 |C:(?:,(?:group|user|domain|record|self)_(?:edit|create|delete))+
762 )$/x;
763# bleh. I'd call another function to do my dirty work, but we're in the middle of a transaction already.
764 if ($permstring ne 'i') {
765 # for cloned or custom permissions, we have to create a new permissions entry.
766 my $clonesrc = $group;
767 if ($permstring =~ /^c:(\d+)/) { $clonesrc = $1; }
768 $dbh->do("INSERT INTO permissions ($permlist,user_id) ".
769 "SELECT $permlist,? FROM permissions WHERE permission_id=".
770 "(SELECT permission_id FROM permissions WHERE ".($permstring =~ /^c:/ ? 'user' : 'group')."_id=?)",
771 undef, ($user_id,$clonesrc) );
772 $dbh->do("UPDATE users SET permission_id=".
773 "(SELECT permission_id FROM permissions WHERE user_id=?) ".
774 "WHERE user_id=?", undef, ($user_id, $user_id) );
775 }
776 if ($permstring =~ /^C:/) {
777 # finally for custom permissions, we set the passed-in permissions (and unset
778 # any that might have been brought in by the clone operation above)
779 my ($permid) = $dbh->selectrow_array("SELECT permission_id FROM permissions WHERE user_id=?",
780 undef, ($user_id) );
781 foreach (@permtypes) {
782 if ($permstring =~ /,$_/) {
783 $dbh->do("UPDATE permissions SET $_='t' WHERE permission_id=?", undef, ($permid) );
784 } else {
785 $dbh->do("UPDATE permissions SET $_='f' WHERE permission_id=?", undef, ($permid) );
786 }
787 }
788 }
789
790 $dbh->do("UPDATE users SET inherit_perm='n' WHERE user_id=?", undef, ($user_id) );
791
[25]792##fixme: add another table to hold name/email for log table?
793
[24]794 # once we get here, we should have suceeded.
795 $dbh->commit;
796 }; # end eval
797
798 if ($@) {
799 my $msg = $@;
800 eval { $dbh->rollback; };
[87]801 return ('FAIL',$msg." $failmsg");
[24]802 } else {
803 return ('OK',$user_id);
804 }
805} # end addUser
806
807
[55]808## DNSDB::checkUser()
809# Check user/pass combo on login
810sub checkUser {
811 my $dbh = shift;
812 my $user = shift;
[56]813 my $inpass = shift;
[55]814
815 my $sth = $dbh->prepare("SELECT user_id,group_id,password,firstname,lastname FROM users WHERE username=?");
816 $sth->execute($user);
817 my ($uid,$gid,$pass,$fname,$lname) = $sth->fetchrow_array;
818 my $loginfailed = 1 if !defined($uid);
819
820 if ($pass =~ m|^\$1\$([A-Za-z0-9/.]+)\$|) {
[56]821 $loginfailed = 1 if $pass ne unix_md5_crypt($inpass,$1);
[55]822 } else {
[56]823 $loginfailed = 1 if $pass ne $inpass;
[55]824 }
825
826 # nnnngggg
827 return ($uid, $gid);
828} # end checkUser
829
830
[83]831## DNSDB:: updateUser()
[90]832# Update general data about user
[83]833sub updateUser {
834 my $dbh = shift;
835 my $uid = shift;
836 my $username = shift;
837 my $group = shift;
838 my $pass = shift;
839 my $state = shift;
[87]840 my $type = shift || 'u';
[83]841 my $fname = shift || $username;
842 my $lname = shift || '';
843 my $phone = shift || ''; # not going format-check
844
845 my $failmsg = '';
846
847 # Allow transactions, and raise an exception on errors so we can catch it later.
848 # Use local to make sure these get "reset" properly on exiting this block
849 local $dbh->{AutoCommit} = 0;
850 local $dbh->{RaiseError} = 1;
851
852 my $sth;
853
854 # Password can be left blank; if so we assume there's one on file.
855 # Actual blank passwords are bad, mm'kay?
856 if (!$pass) {
857 $sth = $dbh->prepare("SELECT password FROM users WHERE user_id=?");
858 $sth->execute($uid);
859 ($pass) = $sth->fetchrow_array;
860 } else {
861 $pass = unix_md5_crypt($pass);
862 }
863
864 eval {
865 my $sth = $dbh->prepare(q(
866 UPDATE users
867 SET username=?, password=?, firstname=?, lastname=?, phone=?, type=?, status=?
868 WHERE user_id=?
869 )
870 );
871 $sth->execute($username, $pass, $fname, $lname, $phone, $type, $state, $uid);
872 $dbh->commit;
873 };
874 if ($@) {
875 my $msg = $@;
876 eval { $dbh->rollback; };
877 return ('FAIL',"$failmsg: $msg");
878 } else {
879 return ('OK','OK');
880 }
881} # end updateUser()
882
883
[24]884## DNSDB::delUser()
885#
886sub delUser {
[25]887 my $dbh = shift;
888 return ('FAIL',"Need database handle") if !$dbh;
889 my $userid = shift;
890 return ('FAIL',"Missing userid") if !defined($userid);
891
892 my $sth = $dbh->prepare("delete from users where user_id=?");
893 $sth->execute($userid);
894
895 return ('FAIL',"Couldn't remove user: ".$sth->errstr) if $sth->err;
896
897 return ('OK','OK');
898
[24]899} # end delUser
900
901
[25]902## DNSDB::userFullName()
903# Return a pretty string!
904# Takes a user_id and optional printf-ish string to indicate which pieces where:
905# %u for the username
906# %f for the first name
907# %l for the last name
908# All other text in the passed string will be left as-is.
909##fixme: need a "smart" option too, so that missing/null/blank first/last names don't give funky output
910sub userFullName {
911 $errstr = '';
912 my $dbh = shift;
913 my $userid = shift;
914 my $fullformat = shift || '%f %l (%u)';
915 my $sth = $dbh->prepare("select username,firstname,lastname from users where user_id=?");
916 $sth->execute($userid);
917 my ($uname,$fname,$lname) = $sth->fetchrow_array();
918 $errstr = $DBI::errstr if !$uname;
919
920 $fullformat =~ s/\%u/$uname/g;
921 $fullformat =~ s/\%f/$fname/g;
922 $fullformat =~ s/\%l/$lname/g;
923
924 return $fullformat;
925} # end userFullName
926
927
[51]928## DNSDB::userStatus()
929# Sets and/or returns a user's status
930# Takes a database handle, user ID and optionally a status argument
931# Returns undef on errors.
932sub userStatus {
933 my $dbh = shift;
934 my $id = shift;
935 my $newstatus = shift;
936
937 return undef if $id !~ /^\d+$/;
938
939 my $sth;
940
941# ooo, fun! let's see what we were passed for status
942 if ($newstatus) {
943 $sth = $dbh->prepare("update users set status=? where user_id=?");
944 # ass-u-me caller knows what's going on in full
945 if ($newstatus =~ /^[01]$/) { # only two valid for now.
946 $sth->execute($newstatus,$id);
947 } elsif ($newstatus =~ /^usero(?:n|ff)$/) {
948 $sth->execute(($newstatus eq 'useron' ? 1 : 0),$id);
949 }
950 }
951
952 $sth = $dbh->prepare("select status from users where user_id=?");
953 $sth->execute($id);
954 my ($status) = $sth->fetchrow_array;
955 return $status;
956} # end userStatus()
957
958
[83]959## DNSDB::getUserData()
960# Get misc user data for display
961sub getUserData {
962 my $dbh = shift;
963 my $uid = shift;
964
965 my $sth = $dbh->prepare("SELECT group_id,username,firstname,lastname,phone,type,status,inherit_perm ".
966 "FROM users WHERE user_id=?");
967 $sth->execute($uid);
968 return $sth->fetchrow_hashref();
969
970} # end getUserData()
971
972
[2]973## DNSDB::getSOA()
974# Return all suitable fields from an SOA record in separate elements of a hash
975# Takes a database handle, default/live flag, and group (default) or domain (live) ID
976sub getSOA {
977 $errstr = '';
978 my $dbh = shift;
979 my $def = shift;
980 my $id = shift;
981 my %ret;
982
[101]983 # (ab)use distance and weight columns to store SOA data
984
985 my $sql = "SELECT record_id,host,val,ttl,distance from";
[2]986 if ($def eq 'def' or $def eq 'y') {
[101]987 $sql .= " default_records WHERE group_id=? AND type=$reverse_typemap{SOA}";
[2]988 } else {
989 # we're editing a live SOA record; find based on domain
[101]990 $sql .= " records WHERE domain_id=? AND type=$reverse_typemap{SOA}";
[2]991 }
992 my $sth = $dbh->prepare($sql);
[101]993 $sth->execute($id);
[2]994
[101]995 my ($recid,$host,$val,$ttl,$serial) = $sth->fetchrow_array();
[2]996 my ($prins,$contact) = split /:/, $host;
997 my ($refresh,$retry,$expire,$minttl) = split /:/, $val;
998
999 $ret{recid} = $recid;
1000 $ret{ttl} = $ttl;
[101]1001 $ret{serial} = $serial;
[2]1002 $ret{prins} = $prins;
1003 $ret{contact} = $contact;
1004 $ret{refresh} = $refresh;
1005 $ret{retry} = $retry;
1006 $ret{expire} = $expire;
1007 $ret{minttl} = $minttl;
1008
1009 return %ret;
1010} # end getSOA()
1011
1012
1013## DNSDB::getRecLine()
1014# Return all data fields for a zone record in separate elements of a hash
1015# Takes a database handle, default/live flag, and record ID
1016sub getRecLine {
1017 $errstr = '';
1018 my $dbh = shift;
1019 my $def = shift;
1020 my $id = shift;
1021
[90]1022 my $sql = "SELECT r.record_id,r.host,r.type,r.val,r.distance,r.weight,r.port,r.ttl,r.longrec_id,l.recdata".
1023 (($def eq 'def' or $def eq 'y') ? ',r.group_id FROM default_' : ',r.domain_id FROM ').
1024 "records r LEFT OUTER JOIN longrecs l ON r.longrec_id=l.longrec_id WHERE record_id=?";
1025 my $ret = $dbh->selectrow_hashref($sql, undef, ($id) ) or warn $dbh->errstr;
[2]1026
[90]1027 if ($dbh->err) {
[2]1028 $errstr = $DBI::errstr;
1029 return undef;
1030 }
1031
[90]1032 $ret->{val} = $ret->{recdata} if $ret->{longrec_id}; # put the long data in the real value space
1033 delete $ret->{longrec_id}; # remove these since they shouldn't be exposed - the caller
1034 delete $ret->{recdata}; # should not care about "long records" vs normal ones.
[107]1035 $ret->{parid} = (($def eq 'def' or $def eq 'y') ? $ret->{group_id} : $ret->{domain_id});
[90]1036
1037 return $ret;
[2]1038}
1039
1040
1041##fixme: should use above (getRecLine()) to get lines for below?
1042## DNSDB::getDomRecs()
1043# Return records for a domain
1044# Takes a database handle, default/live flag, group/domain ID, start,
1045# number of records, sort field, and sort order
1046# Returns a reference to an array of hashes
1047sub getDomRecs {
1048 $errstr = '';
1049 my $dbh = shift;
1050 my $type = shift;
1051 my $id = shift;
[4]1052 my $nrecs = shift || 'all';
1053 my $nstart = shift || 0;
[2]1054
[4]1055## for order, need to map input to column names
1056 my $order = shift || 'host';
[72]1057 my $direction = shift || 'ASC';
[4]1058
[90]1059 $type = 'y' if $type eq 'def';
1060
1061 my $sql = "SELECT r.record_id,r.host,r.type,r.val,r.distance,r.weight,r.port,r.ttl,r.longrec_id,l.recdata FROM ";
1062 $sql .= "default_" if $type eq 'y';
1063 $sql .= "records r ";
[104]1064 $sql .= "INNER JOIN rectypes t ON r.type=t.val "; # for sorting by type alphabetically
[90]1065 $sql .= "LEFT OUTER JOIN longrecs l ON r.longrec_id=l.longrec_id ";
1066 if ($type eq 'y') {
1067 $sql .= "WHERE r.group_id=?";
[2]1068 } else {
[90]1069 $sql .= "WHERE r.domain_id=?";
[2]1070 }
[104]1071 $sql .= " AND NOT r.type=$reverse_typemap{SOA}";
1072 # use alphaorder column for "correct" ordering of sort-by-type instead of DNS RR type number
1073 $sql .= " ORDER BY ".($order eq 'type' ? 't.alphaorder' : "r.$order")." $direction";
[90]1074 $sql .= " LIMIT $nrecs OFFSET ".($nstart*$nrecs) if $nstart ne 'all';
[4]1075
[90]1076 my $sth = $dbh->prepare($sql) or warn $dbh->errstr;
1077 $sth->execute($id) or warn "$sql: ".$sth->errstr;
[2]1078
1079 my @retbase;
1080 while (my $ref = $sth->fetchrow_hashref()) {
[90]1081 $ref->{val} = $ref->{recdata} if $ref->{longrec_id}; # put the long data in the real value space
1082 delete $ref->{longrec_id}; # remove these since they shouldn't be exposed - the caller
1083 delete $ref->{recdata}; # should not care about "long records" vs normal ones.
[2]1084 push @retbase, $ref;
1085 }
1086
1087 my $ret = \@retbase;
1088 return $ret;
1089} # end getDomRecs()
1090
1091
[91]1092## DNSDB::getRecCount()
1093# Return count of non-SOA records in domain (or default records in a group)
1094# Takes a database handle, default/live flag and group/domain ID
1095# Returns the count
1096sub getRecCount {
1097 my $dbh = shift;
1098 my $defrec = shift;
1099 my $id = shift;
1100
1101 my ($count) = $dbh->selectrow_array("SELECT count(*) FROM ".
1102 ($defrec eq 'y' ? 'default_' : '')."records ".
1103 "WHERE ".($defrec eq 'y' ? 'group' : 'domain')."_id=? ".
1104 "AND NOT type=$reverse_typemap{SOA}", undef, ($id) );
1105
1106 return $count;
1107
1108} # end getRecCount()
1109
1110
[3]1111## DNSDB::addRec()
[2]1112# Add a new record to a domain or a group's default records
1113# Takes a database handle, default/live flag, group/domain ID,
1114# host, type, value, and TTL
1115# Some types require additional detail: "distance" for MX and SRV,
1116# and weight/port for SRV
1117# Returns a status code and detail message in case of error
1118sub addRec {
1119 $errstr = '';
1120 my $dbh = shift;
1121 my $defrec = shift;
1122 my $id = shift;
1123
1124 my $host = shift;
1125 my $rectype = shift;
1126 my $val = shift;
1127 my $ttl = shift;
1128
1129 my $fields = ($defrec eq 'y' ? 'group_id' : 'domain_id').",host,type,val,ttl";
[24]1130 my $vallen = "?,?,?,?,?";
1131 my @vallist = ($id,$host,$rectype,$val,$ttl);
[2]1132
1133 my $dist;
1134 if ($rectype == $reverse_typemap{MX} or $rectype == $reverse_typemap{SRV}) {
1135 $dist = shift;
1136 return ('FAIL',"Need distance for $typemap{$rectype} record") if !defined($dist);
1137 $fields .= ",distance";
[24]1138 $vallen .= ",?";
1139 push @vallist, $dist;
[2]1140 }
1141 my $weight;
1142 my $port;
1143 if ($rectype == $reverse_typemap{SRV}) {
[24]1144 # check for _service._protocol. NB: RFC2782 does not say "MUST"... nor "SHOULD"...
1145 # it just says (paraphrased) "... is prepended with _ to prevent DNS collisions"
1146 return ('FAIL',"SRV records must begin with _service._protocol")
1147 if $host !~ /^_[A-Za-z]+\._[A-Za-z]+\.[a-z0-9-]+/;
[2]1148 $weight = shift;
1149 $port = shift;
1150 return ('FAIL',"Need weight and port for SRV record") if !defined($weight) or !defined($port);
1151 $fields .= ",weight,port";
[24]1152 $vallen .= ",?,?";
1153 push @vallist, ($weight,$port);
[2]1154 }
1155
[90]1156 # Allow transactions, and raise an exception on errors so we can catch it later.
1157 # Use local to make sure these get "reset" properly on exiting this block
1158 local $dbh->{AutoCommit} = 0;
1159 local $dbh->{RaiseError} = 1;
[2]1160
[90]1161 eval {
1162 if (length($val) > 100 ) {
1163 # extralong records get an entry in a separate table.
1164 $dbh->do("INSERT INTO longrecs (recdata) VALUES (?)", undef, ($val) );
1165 my ($longid) = $dbh->selectrow_array("SELECT longrec_id FROM longrecs WHERE recdata=?", undef, ($val) );
1166 $fields .= ",longrec_id";
1167 $vallen .= ",?";
1168 push @vallist, $longid;
1169 $vallist[3] = ''; # so we don't barf when we insert the main record
1170 }
1171 $dbh->do("INSERT INTO ".($defrec eq 'y' ? 'default_' : '')."records ($fields) VALUES ($vallen)",
1172 undef, @vallist);
1173 $dbh->commit;
1174 };
1175 if ($@) {
1176 my $msg = $@;
1177 eval { $dbh->rollback; };
1178 return ('FAIL',$msg);
1179 }
[2]1180
1181 return ('OK','OK');
[90]1182
[2]1183} # end addRec()
1184
1185
[16]1186## DNSDB::updateRec()
1187# Update a record
1188sub updateRec {
1189 $errstr = '';
[17]1190
[16]1191 my $dbh = shift;
1192 my $defrec = shift;
1193 my $id = shift;
1194
1195# all records have these
1196 my $host = shift;
1197 my $type = shift;
1198 my $val = shift;
1199 my $ttl = shift;
1200
1201 return('FAIL',"Missing standard argument(s)") if !defined($ttl);
1202
1203# only MX and SRV will use these
1204 my $dist = 0;
1205 my $weight = 0;
1206 my $port = 0;
1207
1208 if ($type == $reverse_typemap{MX} || $type == $reverse_typemap{SRV}) {
[17]1209 $dist = shift;
1210 return ('FAIL',"MX or SRV requires distance") if !defined($dist);
[16]1211 if ($type == $reverse_typemap{SRV}) {
[17]1212 $weight = shift;
1213 return ('FAIL',"SRV requires weight") if !defined($weight);
1214 $port = shift;
1215 return ('FAIL',"SRV requires port") if !defined($port);
[16]1216 }
1217 }
1218
[90]1219# my $sql = "SELECT r.record_id,r.host,r.type,r.val,r.distance,r.weight,r.port,r.ttl,r.longrec_id,l.recdata FROM ";
1220# $sql .= "default_" if $type eq 'y';
1221# $sql .= "records r ";
1222# $sql .= "LEFT OUTER JOIN longrecs l ON r.longrec_id=l.longrec_id ";
[16]1223
[90]1224 # get the long record ID, if any
1225 my ($longid) = $dbh->selectrow_array("SELECT longrec_id FROM ".($defrec eq 'y' ? 'default_' : '')."records ".
1226 "WHERE record_id=?", undef, ($id) );
[16]1227
[90]1228 local $dbh->{AutoCommit} = 0;
1229 local $dbh->{RaiseError} = 1;
1230
1231 eval {
1232 # there's really no tidy way to squash this down. :/
1233 if (length($val) > 100) {
1234 if ($longid) {
1235 $dbh->do("UPDATE longrecs SET recdata=? WHERE longrec_id=?", undef, ($val, $longid) );
1236 } else {
1237##fixme: has to be a better way to be sure we get the right recid back once inserted...
1238 $dbh->do("INSERT INTO longrecs (recdata) VALUES (?)", undef, ($val) );
1239 my ($newlongid) = $dbh->selectrow_array("SELECT currval('longrecs_longrec_id_seq')");
1240 $dbh->do("UPDATE ".($defrec eq 'y' ? 'default_' : '')."records SET val=?,longrec_id=? ".
1241 "WHERE record_id=?", undef, ('', $newlongid, $id) );
1242 }
1243 } else {
1244 if ($longid) {
1245 $dbh->do("DELETE FROM longrecs WHERE longrec_id=?", undef, ($longid) );
1246 $dbh->do("UPDATE ".($defrec eq 'y' ? 'default_' : '')."records SET val=?,longrec_id=NULL ".
1247 "WHERE record_id=?", undef, ($val, $id) );
1248 } else {
1249 $dbh->do("UPDATE ".($defrec eq 'y' ? 'default_' : '')."records SET val=? ".
1250 "WHERE record_id=?", undef, ($val, $id) );
1251 }
1252 }
1253
1254 $dbh->do("UPDATE ".($defrec eq 'y' ? 'default_' : '')."records ".
1255 "SET host=?,type=?,ttl=?,distance=?,weight=?,port=? ".
1256 "WHERE record_id=?", undef, ($host, $type, $ttl, $dist, $weight, $port, $id) );
1257
1258 };
1259 if ($@) {
1260 my $msg = $@;
1261 $dbh->rollback;
1262 return ('FAIL', $msg);
1263 }
1264# return ('FAIL',$sth->errstr."<br>\n$errstr<br>\n") if $sth->err;
1265
[16]1266 return ('OK','OK');
1267} # end updateRec()
1268
1269
[3]1270## DNSDB::delRec()
1271# Delete a record.
1272sub delRec {
1273 $errstr = '';
1274 my $dbh = shift;
1275 my $defrec = shift;
1276 my $id = shift;
1277
[62]1278 my $sth = $dbh->prepare("DELETE FROM ".($defrec eq 'y' ? 'default_' : '')."records WHERE record_id=?");
[3]1279 $sth->execute($id);
1280
[23]1281 return ('FAIL',"Couldn't remove record: ".$sth->errstr) if $sth->err;
[3]1282
1283 return ('OK','OK');
1284} # end delRec()
1285
1286
1287## DNSDB::domStatus()
1288# Sets and/or returns a domain's status
1289# Takes a database handle, domain ID and optionally a status argument
1290# Returns undef on errors.
1291sub domStatus {
1292 my $dbh = shift;
1293 my $id = shift;
1294 my $newstatus = shift;
1295
1296 return undef if $id !~ /^\d+$/;
1297
1298 my $sth;
1299
1300# ooo, fun! let's see what we were passed for status
1301 if ($newstatus) {
1302 $sth = $dbh->prepare("update domains set status=? where domain_id=?");
1303 # ass-u-me caller knows what's going on in full
1304 if ($newstatus =~ /^[01]$/) { # only two valid for now.
1305 $sth->execute($newstatus,$id);
1306 } elsif ($newstatus =~ /^domo(?:n|ff)$/) {
1307 $sth->execute(($newstatus eq 'domon' ? 1 : 0),$id);
1308 }
1309 }
1310
1311 $sth = $dbh->prepare("select status from domains where domain_id=?");
1312 $sth->execute($id);
1313 my ($status) = $sth->fetchrow_array;
1314 return $status;
1315} # end domStatus()
1316
1317
[33]1318## DNSDB::importAXFR
1319# Import a domain via AXFR
[37]1320# Takes AXFR host, domain to transfer, group to put the domain in,
1321# and optionally:
1322# - active/inactive state flag (defaults to active)
1323# - overwrite-SOA flag (defaults to off)
1324# - overwrite-NS flag (defaults to off, doesn't affect subdomain NS records)
1325# Returns a status code (OK, WARN, or FAIL) and message - message should be blank
1326# if status is OK, but WARN includes conditions that are not fatal but should
1327# really be reported.
[33]1328sub importAXFR {
1329 my $dbh = shift;
[35]1330 my $ifrom_in = shift;
[33]1331 my $domain = shift;
1332 my $group = shift;
1333 my $status = shift || 1;
1334 my $rwsoa = shift || 0;
1335 my $rwns = shift || 0;
[37]1336
[33]1337##fixme: add mode to delete&replace, merge+overwrite, merge new?
1338
[37]1339 my $nrecs = 0;
1340 my $soaflag = 0;
1341 my $nsflag = 0;
1342 my $warnmsg = '';
1343 my $ifrom;
[33]1344
[35]1345 # choke on possible bad setting in ifrom
[37]1346 # IPv4 and v6, and valid hostnames!
[35]1347 ($ifrom) = ($ifrom_in =~ /^([0-9a-f\:.]+|[0-9a-z_.-]+)$/i);
1348 return ('FAIL', "Bad AXFR source host $ifrom")
1349 unless ($ifrom) = ($ifrom_in =~ /^([0-9a-f\:.]+|[0-9a-z_.-]+)$/i);
1350
[33]1351 # Allow transactions, and raise an exception on errors so we can catch it later.
1352 # Use local to make sure these get "reset" properly on exiting this block
1353 local $dbh->{AutoCommit} = 0;
1354 local $dbh->{RaiseError} = 1;
1355
[37]1356 my $sth = $dbh->prepare("SELECT domain_id FROM domains WHERE domain=?");
[34]1357 my $dom_id;
1358
[35]1359# quick check to start to see if we've already got one
[37]1360 $sth->execute($domain);
1361 ($dom_id) = $sth->fetchrow_array;
[35]1362
1363 return ('FAIL', "Domain already exists") if $dom_id;
1364
[33]1365 eval {
1366 # can't do this, can't nest transactions. sigh.
[35]1367 #my ($dcode, $dmsg) = addDomain(dbh, domain, group, status);
[33]1368
1369##fixme: serial
[37]1370 my $sth = $dbh->prepare("INSERT INTO domains (domain,group_id,status) VALUES (?,?,?)");
1371 $sth->execute($domain,$group,$status);
[33]1372
[35]1373## bizarre DBI<->Net::DNS interaction bug:
1374## sometimes a zone will cause an immediate commit-and-exit (sort of) of the while()
[37]1375## fixed, apparently I was doing *something* odd, but not certain what it was that
1376## caused a commit instead of barfing
[35]1377
[33]1378 # get domain id so we can do the records
[37]1379 $sth = $dbh->prepare("SELECT domain_id FROM domains WHERE domain=?");
1380 $sth->execute($domain);
1381 ($dom_id) = $sth->fetchrow_array();
[33]1382
[34]1383 my $res = Net::DNS::Resolver->new;
[35]1384 $res->nameservers($ifrom);
1385 $res->axfr_start($domain)
1386 or die "Couldn't begin AXFR\n";
[34]1387
[35]1388 while (my $rr = $res->axfr_next()) {
[33]1389 my $type = $rr->type;
[35]1390
[34]1391 my $sql = "INSERT INTO records (domain_id,host,type,ttl,val";
[33]1392 my $vallen = "?,?,?,?,?";
1393
[37]1394 $soaflag = 1 if $type eq 'SOA';
1395 $nsflag = 1 if $type eq 'NS';
[35]1396
1397 my @vallist = ($dom_id, $rr->name, $reverse_typemap{$type}, $rr->ttl);
[34]1398
1399# "Primary" types:
1400# A, NS, CNAME, SOA, PTR(warn in forward), MX, TXT, AAAA, SRV, A6(ob), SPF
1401# maybe KEY
1402
[35]1403# nasty big ugly case-like thing here, since we have to do *some* different
1404# processing depending on the record. le sigh.
1405
[105]1406##fixme: what record types other than TXT can/will have >255-byte payloads?
1407
[34]1408 if ($type eq 'A') {
1409 push @vallist, $rr->address;
1410 } elsif ($type eq 'NS') {
[37]1411# hmm. should we warn here if subdomain NS'es are left alone?
1412 next if ($rwns && ($rr->name eq $domain));
[34]1413 push @vallist, $rr->nsdname;
[35]1414 $nsflag = 1;
[34]1415 } elsif ($type eq 'CNAME') {
1416 push @vallist, $rr->cname;
1417 } elsif ($type eq 'SOA') {
[37]1418 next if $rwsoa;
[34]1419 $vallist[1] = $rr->mname.":".$rr->rname;
1420 push @vallist, ($rr->refresh.":".$rr->retry.":".$rr->expire.":".$rr->minimum);
[35]1421 $soaflag = 1;
[34]1422 } elsif ($type eq 'PTR') {
[105]1423 push @vallist, $rr->ptrdname;
[34]1424 # hmm. PTR records should not be in forward zones.
1425 } elsif ($type eq 'MX') {
[33]1426 $sql .= ",distance";
1427 $vallen .= ",?";
[34]1428 push @vallist, $rr->exchange;
1429 push @vallist, $rr->preference;
1430 } elsif ($type eq 'TXT') {
1431##fixme: Net::DNS docs say this should be deprecated for rdatastr() or char_str_list(),
1432## but don't really seem enthusiastic about it.
[105]1433 my $rrdata = $rr->txtdata;
1434 if (length($rrdata) > 100 ) {
1435 # extralong records get an entry in a separate table.
1436 $dbh->do("INSERT INTO longrecs (recdata) VALUES (?)", undef, ($rrdata) );
1437 my ($longid) = $dbh->selectrow_array("SELECT longrec_id FROM longrecs WHERE recdata=?", undef, ($rrdata) );
1438 $sql .= ",longrec_id";
1439 $vallen .= ",?";
1440 push @vallist, '';
1441 push @vallist, $longid;
1442 } else {
1443 push @vallist, $rrdata;
1444 }
[34]1445 } elsif ($type eq 'SPF') {
1446##fixme: and the same caveat here, since it is apparently a clone of ::TXT
[105]1447 my $rrdata = $rr->txtdata;
1448 if (length($rrdata) > 100 ) {
1449 # extralong records get an entry in a separate table.
1450 $dbh->do("INSERT INTO longrecs (recdata) VALUES (?)", undef, ($rrdata) );
1451 my ($longid) = $dbh->selectrow_array("SELECT longrec_id FROM longrecs WHERE recdata=?", undef, ($rrdata) );
1452 $sql .= ",longrec_id";
1453 $vallen .= ",?";
1454 push @vallist, '';
1455 push @vallist, $longid;
1456 } else {
1457 push @vallist, $rrdata;
1458 }
[34]1459 } elsif ($type eq 'AAAA') {
1460 push @vallist, $rr->address;
1461 } elsif ($type eq 'SRV') {
1462 $sql .= ",distance,weight,port" if $type eq 'SRV';
1463 $vallen .= ",?,?,?" if $type eq 'SRV';
[37]1464 push @vallist, $rr->target;
[34]1465 push @vallist, $rr->priority;
1466 push @vallist, $rr->weight;
1467 push @vallist, $rr->port;
1468 } elsif ($type eq 'KEY') {
[35]1469 # we don't actually know what to do with these...
[34]1470 push @vallist, ($rr->flags.":".$rr->protocol.":".$rr->algorithm.":".$rr->key.":".$rr->keytag.":".$rr->privatekeyname);
[35]1471 } else {
[105]1472 my $rrdata = $rr->rdatastr;
1473 if (length($rrdata) > 100 ) {
1474 # extralong records get an entry in a separate table.
1475 $dbh->do("INSERT INTO longrecs (recdata) VALUES (?)", undef, ($rrdata) );
1476 my ($longid) = $dbh->selectrow_array("SELECT longrec_id FROM longrecs WHERE recdata=?", undef, ($rrdata) );
1477 $sql .= ",longrec_id";
1478 $vallen .= ",?";
1479 push @vallist, '';
1480 push @vallist, $longid;
1481 } else {
1482 push @vallist, $rrdata;
1483 }
[35]1484 # Finding a different record type is not fatal.... just problematic.
[37]1485 # We may not be able to export it correctly.
[35]1486 $warnmsg .= "Unusual record ".$rr->name." ($type) found\n";
[33]1487 }
1488
[34]1489# BIND supports:
1490# A CNAME HINFO MB(ex) MD(ob) MF(ob) MG(ex) MINFO(ex) MR(ex) MX NS NULL
1491# PTR SOA TXT WKS AFSDB(ex) ISDN(ex) RP(ex) RT(ex) X25(ex) PX
1492# ... if one can ever find the right magic to format them correctly
1493
1494# Net::DNS supports:
1495# RRSIG SIG NSAP NS NIMLOC NAPTR MX MR MINFO MG MB LOC ISDN IPSECKEY HINFO
1496# EID DNAME CNAME CERT APL AFSDB AAAA A DS NXT NSEC3PARAM NSEC3 NSEC KEY
1497# DNSKEY DLV X25 TXT TSIG TKEY SSHFP SRV SPF SOA RT RP PX PTR NULL APL::AplItem
1498
[37]1499 $sth = $dbh->prepare($sql.") VALUES (".$vallen.")") or die "problem preparing record insert SQL\n";
1500 $sth->execute(@vallist) or die "failed to insert ".$rr->string.": ".$sth->errstr."\n";
[34]1501
[37]1502 $nrecs++;
[34]1503
[37]1504 } # while axfr_next
1505
1506 # Overwrite SOA record
1507 if ($rwsoa) {
1508 $soaflag = 1;
1509 my $sthgetsoa = $dbh->prepare("SELECT host,val,ttl FROM default_records WHERE group_id=? AND type=?");
1510 my $sthputsoa = $dbh->prepare("INSERT INTO records (domain_id,host,type,val,ttl) VALUES (?,?,?,?,?)");
1511 $sthgetsoa->execute($group,$reverse_typemap{SOA});
1512 while (my ($host,$val,$ttl) = $sthgetsoa->fetchrow_array()) {
1513 $host =~ s/DOMAIN/$domain/g;
1514 $val =~ s/DOMAIN/$domain/g;
1515 $sthputsoa->execute($dom_id,$host,$reverse_typemap{SOA},$val,$ttl);
[34]1516 }
[37]1517 }
[34]1518
[37]1519 # Overwrite NS records
1520 if ($rwns) {
1521 $nsflag = 1;
1522 my $sthgetns = $dbh->prepare("SELECT host,val,ttl FROM default_records WHERE group_id=? AND type=?");
1523 my $sthputns = $dbh->prepare("INSERT INTO records (domain_id,host,type,val,ttl) VALUES (?,?,?,?,?)");
1524 $sthgetns->execute($group,$reverse_typemap{NS});
1525 while (my ($host,$val,$ttl) = $sthgetns->fetchrow_array()) {
1526 $host =~ s/DOMAIN/$domain/g;
1527 $val =~ s/DOMAIN/$domain/g;
1528 $sthputns->execute($dom_id,$host,$reverse_typemap{NS},$val,$ttl);
1529 }
1530 }
[34]1531
[35]1532 die "No records found; either $ifrom is not authoritative or doesn't allow transfers\n" if !$nrecs;
1533 die "Bad zone: No SOA record!\n" if !$soaflag;
1534 die "Bad zone: No NS records!\n" if !$nsflag;
1535
[37]1536 $dbh->commit;
[35]1537
[33]1538 };
1539
1540 if ($@) {
1541 my $msg = $@;
1542 eval { $dbh->rollback; };
[34]1543 return ('FAIL',$msg." $warnmsg");
[33]1544 } else {
[35]1545 return ('WARN', $warnmsg) if $warnmsg;
[91]1546 return ('OK',"Imported OK");
[33]1547 }
1548
[37]1549 # it should be impossible to get here.
[34]1550 return ('WARN',"OOOK!");
[33]1551} # end importAXFR()
1552
1553
[103]1554## DNSDB::export()
1555# Export the DNS database, or a part of it
1556# Takes database handle, export type, optional arguments depending on type
1557# Writes zone data to targets as appropriate for type
1558sub export {
1559 my $dbh = shift;
1560 my $target = shift;
1561
1562 if ($target eq 'tiny') {
1563 __export_tiny($dbh,@_);
1564 }
1565# elsif ($target eq 'foo') {
1566# __export_foo($dbh,@_);
1567#}
1568# etc
1569
1570} # end export()
1571
1572
1573## DNSDB::__export_tiny
1574# Internal sub to implement tinyDNS (compatible) export
1575# Takes database handle, filehandle to write export to, optional argument(s)
1576# to determine which data gets exported
1577sub __export_tiny {
1578 my $dbh = shift;
1579 my $datafile = shift;
1580
1581##fixme: slurp up further options to specify particular zone(s) to export
1582
1583 ## Convert a bare number into an octal-coded pair of octets.
1584 # Take optional arg to indicate a decimal or hex input. Defaults to hex.
1585 sub octalize {
1586 my $tmp = shift;
1587 my $srctype = shift || 'h'; # default assumes hex string
1588 $tmp = sprintf "%0.4x", hex($tmp) if $srctype eq 'h'; # 0-pad hex to 4 digits
1589 $tmp = sprintf "%0.4x", $tmp if $srctype eq 'd'; # 0-pad decimal to 4 hex digits
1590 my @o = ($tmp =~ /^(..)(..)$/); # split into octets
1591 return sprintf "\\%0.3o\\%0.3o", hex($o[0]), hex($o[1]);;
1592 }
1593
1594##fixme: fail if $datafile isn't an open, writable file
1595
1596 # easy case - export all evarything
1597 # not-so-easy case - export item(s) specified
1598 # todo: figure out what kind of list we use to export items
1599
1600 my $domsth = $dbh->prepare("SELECT domain_id,domain,status FROM domains WHERE status=1");
1601 my $recsth = $dbh->prepare("SELECT r.host,r.type,r.val,r.distance,r.weight,r.port,r.ttl,l.recdata ".
1602 "FROM records r LEFT OUTER JOIN longrecs l ON r.longrec_id=l.longrec_id WHERE domain_id=?");
1603 $domsth->execute();
1604 while (my ($domid,$dom,$domstat) = $domsth->fetchrow_array) {
1605 $recsth->execute($domid);
1606 while (my ($host,$type,$val,$dist,$weight,$port,$ttl,$lval) = $recsth->fetchrow_array) {
1607 $val = $lval if $lval;
1608
1609# raw packet in unknown format: first byte indicates length
1610# of remaining data, allows up to 255 raw bytes
1611
1612##fixme? append . to all host/val hostnames
1613 if ($typemap{$type} eq 'SOA') {
1614
1615 # host contains pri-ns:responsible
1616 # val is abused to contain refresh:retry:expire:minttl
1617##fixme: "manual" serial vs tinydns-autoserial
1618 print $datafile "Z$host"."::$val:$ttl\n";
1619
1620 } elsif ($typemap{$type} eq 'A') {
1621
1622 print $datafile "+$host:$val:$ttl\n";
1623
1624 } elsif ($typemap{$type} eq 'NS') {
1625
1626 print $datafile "\&$host"."::$val:$ttl\n";
1627
1628 } elsif ($typemap{$type} eq 'AAAA') {
1629
1630 print $datafile ":$host:28:";
1631 my $altgrp = 0;
1632 my @altconv;
1633 # Split in to up to 8 groups of hex digits (allows for :: 0-collapsing)
1634 foreach (split /:/, $val) {
1635 if (/^$/) {
1636 # flag blank entry; this is a series of 0's of (currently) unknown length
1637 $altconv[$altgrp++] = 's';
1638 } else {
1639 # call sub to convert 1-4 hex digits to 2 string-rep octal bytes
1640 $altconv[$altgrp++] = octalize($_)
1641 }
1642 }
1643 foreach my $octet (@altconv) {
1644 # if not 's', output
1645 print $datafile $octet unless $octet =~ /^s$/;
1646 # if 's', output (9-array length)x literal '\000\000'
1647 print $datafile '\000\000'x(9-$altgrp) if $octet =~ /^s$/;
1648 }
1649 print $datafile ":$ttl\n";
1650
1651 } elsif ($typemap{$type} eq 'MX') {
1652
1653 print $datafile "\@$host"."::$val:$dist:$ttl\n";
1654
1655 } elsif ($typemap{$type} eq 'TXT') {
1656
1657##fixme: split v-e-r-y long TXT strings? will need to do so for BIND export, at least
1658 $val =~ s/:/\\072/g; # may need to replace other symbols
1659 print $datafile "'$host:$val:$ttl\n";
1660
1661# by-hand TXT
1662#:deepnet.cx:16:2v\075spf1\040a\040a\072bacon.deepnet.cx\040a\072home.deepnet.cx\040-all:3600
1663#@ IN TXT "v=spf1 a a:bacon.deepnet.cx a:home.deepnet.cx -all"
1664#'deepnet.cx:v=spf1 a a\072bacon.deepnet.cx a\072home.deepnet.cx -all:3600
1665
1666#txttest IN TXT "v=foo bar:bob kn;ob' \" !@#$%^&*()-=_+[]{}<>?"
1667#: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
1668
1669# very long TXT record as brought in by axfr-get
1670# note tinydns does not support >512-byte RR data, need axfr-dns (for TCP support) for that
1671# also note, tinydns does not seem to support <512, >256-byte RRdata from axfr-get either. :/
1672#:longtxt.deepnet.cx:16:
1673#\170this is a very long txt record. it is really long. long. very long. really very long. this is a very long txt record.
1674#\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.
1675#\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.
1676#:3600
1677
1678 } elsif ($typemap{$type} eq 'CNAME') {
1679
1680 print $datafile "C$host:$val:$ttl\n";
1681
1682 } elsif ($typemap{$type} eq 'SRV') {
1683
1684 # data is two-byte values for priority, weight, port, in that order,
1685 # followed by length/string data
1686
1687 print $datafile ":$host:33:".octalize($dist,'d').octalize($weight,'d').octalize($port,'d');
1688
1689 $val .= '.' if $val !~ /\.$/;
1690 foreach (split /\./, $val) {
1691 printf $datafile "\\%0.3o%s", length($_), $_;
1692 }
1693 print $datafile "\\000:$ttl\n";
1694
1695 } elsif ($typemap{$type} eq 'RP') {
1696
1697 # RP consists of two mostly free-form strings.
1698 # The first is supposed to be an email address with @ replaced by . (as with the SOA contact)
1699 # The second is the "hostname" of a TXT record with more info.
1700 print $datafile ":$host:17:";
1701 my ($who,$what) = split /\s/, $val;
1702 foreach (split /\./, $who) {
1703 printf $datafile "\\%0.3o%s", length($_), $_;
1704 }
1705 print $datafile '\000';
1706 foreach (split /\./, $what) {
1707 printf $datafile "\\%0.3o%s", length($_), $_;
1708 }
1709 print $datafile "\\000:$ttl\n";
1710
1711 } elsif ($typemap{$type} eq 'PTR') {
1712
1713 # must handle both IPv4 and IPv6
1714##work
1715
1716 } # record type if-else
1717
1718 } # while ($recsth)
1719 } # while ($domsth)
1720} # end __export_tiny()
1721
1722
[2]1723# shut Perl up
17241;
Note: See TracBrowser for help on using the repository browser.