source: trunk/DNSDB.pm@ 66

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

/trunk

Basic group permissions editing functional - enforcing is trivial

  • add group now adds the permissions entry. TBD: permission inheritance
  • edit group Does The Right Thing(TM) - either editing the existing entry, or converting an inherited permission group to a separate one. still needs to rewrite subgroup and contained user inherited permissions
  • the HTML permissions table rows have been moved. edit-user should pick this up, and will require calling the template explicitly so as to show both the default and custom permissions.
  • the list of individual permissions have been moved to a list in DNSDB.pm code that refers to this should not assume any given length - this makes adding new permission types (somewhat) easier

Tweak menu group-tree CSS (again) add some (broken) images

  • this should probalby revert to an earlier setup that uses an image as the <li> bullet point rather than pushing the text to the right, since many (most?) nodes will usually be leaf nodes

HTML changes not validated

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