source: trunk/DNSDB.pm@ 83

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

/trunk

Checkpoint; partial completion of user editing.

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