source: trunk/DNSDB.pm@ 65

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

/trunk

checkpoint, adding permissions/ACL support

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