source: trunk/DNSDB.pm@ 87

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

/trunk

Checkpoint. Permissions manipulation should be complete.
Still need to set up permissions *checking*.

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