source: trunk/DNSDB.pm@ 74

Last change on this file since 74 was 72, checked in by Kris Deugau, 14 years ago

/trunk

Checkpoint - adding sort-on-title-click to record list columns

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