source: trunk/DNSDB.pm@ 116

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

/trunk

Tighten addDomain()'s checking of domain state

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