source: trunk/DNSDB.pm@ 102

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

/trunk

dns.cgi:

Prefill <domain> or DOMAIN in Hostname field on add record page
Set initial TTL correctly based on SOA record rather than hardcoded defaults

DNSDB.pm:

Tweak retrieval code to pull SOA's serial from distance field

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