source: trunk/DNSDB.pm@ 115

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

/trunk

Mostly complete functionality of bulk group move

  • Property svn:keywords set to Date Rev Author Id
File size: 56.0 KB
Line 
1# dns/trunk/DNSDB.pm
2# Abstraction functions for DNS administration
3###
4# SVN revision info
5# $Date: 2011-08-02 22:54:07 +0000 (Tue, 02 Aug 2011) $
6# SVN revision $Rev: 112 $
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 &changeGroup
30 &connectDB &finish
31 &addDomain &delDomain &domainName &domainID
32 &addGroup &delGroup &getChildren &groupName
33 &addUser &updateUser &delUser &userFullName &userStatus &getUserData
34 &getSOA &getRecLine &getDomRecs &getRecCount
35 &addRec &updateRec &delRec
36 &domStatus &importAXFR
37 &export
38 %typemap %reverse_typemap
39 %permissions @permtypes $permlist
40 );
41
42@EXPORT = (); # Export nothing by default.
43%EXPORT_TAGS = ( ALL => [qw(
44 &initGlobals
45 &initPermissions &getPermissions &changePermissions &comparePermissions
46 &changeGroup
47 &connectDB &finish
48 &addDomain &delDomain &domainName &domainID
49 &addGroup &delGroup &getChildren &groupName
50 &addUser &updateUser &delUser &userFullName &userStatus &getUserData
51 &getSOA &getRecLine &getDomRecs &getRecCount
52 &addRec &updateRec &delRec
53 &domStatus &importAXFR
54 &export
55 %typemap %reverse_typemap
56 %permissions @permtypes $permlist
57 )]
58 );
59
60our $group = 1;
61our $errstr = '';
62
63# Halfway sane defaults for SOA, TTL, etc.
64# serial defaults to 0 for convenience.
65# value will be either YYYYMMDDNN for BIND/etc, or auto-internal for tinydns
66our %def = qw (
67 contact hostmaster.DOMAIN
68 prins ns1.myserver.com
69 serial 0
70 soattl 86400
71 refresh 10800
72 retry 3600
73 expire 604800
74 minttl 10800
75 ttl 10800
76);
77
78# Arguably defined wholly in the db, but little reason to change without supporting code changes
79our @permtypes = qw (
80 group_edit group_create group_delete
81 user_edit user_create user_delete
82 domain_edit domain_create domain_delete
83 record_edit record_create record_delete
84 self_edit admin
85);
86our $permlist = join(',',@permtypes);
87
88# DNS record type map and reverse map.
89# loaded from the database, from http://www.iana.org/assignments/dns-parameters
90our %typemap;
91our %reverse_typemap;
92
93our %permissions;
94
95##
96## Initialization and cleanup subs
97##
98
99
100## DNSDB::connectDB()
101# Creates connection to DNS database.
102# Requires the database name, username, and password.
103# Returns a handle to the db.
104# Set up for a PostgreSQL db; could be any transactional DBMS with the
105# right changes.
106sub connectDB {
107 $errstr = '';
108 my $dbname = shift;
109 my $user = shift;
110 my $pass = shift;
111 my $dbh;
112 my $DSN = "DBI:Pg:dbname=$dbname";
113
114 my $host = shift;
115 $DSN .= ";host=$host" if $host;
116
117# Note that we want to autocommit by default, and we will turn it off locally as necessary.
118# We may not want to print gobbledygook errors; YMMV. Have to ponder that further.
119 $dbh = DBI->connect($DSN, $user, $pass, {
120 AutoCommit => 1,
121 PrintError => 0
122 })
123 or return (undef, $DBI::errstr) if(!$dbh);
124
125# Return here if we can't select. Note that this indicates a
126# problem executing the select.
127 my $sth = $dbh->prepare("select group_id from groups limit 1");
128 $sth->execute();
129 return (undef,$DBI::errstr) if ($sth->err);
130
131# See if the select returned anything (or null data). This should
132# succeed if the select executed, but...
133 $sth->fetchrow();
134 return (undef,$DBI::errstr) if ($sth->err);
135
136 $sth->finish;
137
138# If we get here, we should be OK.
139 return ($dbh,"DB connection OK");
140} # end connectDB
141
142
143## DNSDB::finish()
144# Cleans up after database handles and so on.
145# Requires a database handle
146sub finish {
147 my $dbh = $_[0];
148 $dbh->disconnect;
149} # end finish
150
151
152## DNSDB::initGlobals()
153# Initialize global variables
154# NB: this does NOT include web-specific session variables!
155# Requires a database handle
156sub initGlobals {
157 my $dbh = shift;
158
159# load system-wide site defaults and things from config file
160 if (open SYSDEFAULTS, "</etc/dnsdb.conf") {
161##fixme - error check!
162 while (<SYSDEFAULTS>) {
163 next if /^\s*#/;
164 $def{contact} = $1 if /contact ?= ?([a-z0-9_.-]+)/i;
165 $def{prins} = $1 if /prins ?= ?([a-z0-9_.-]+)/i;
166 $def{soattl} = $1 if /soattl ?= ?([a-z0-9_.-]+)/i;
167 $def{refresh} = $1 if /refresh ?= ?([a-z0-9_.-]+)/i;
168 $def{retry} = $1 if /retry ?= ?([a-z0-9_.-]+)/i;
169 $def{expire} = $1 if /expire ?= ?([a-z0-9_.-]+)/i;
170 $def{minttl} = $1 if /minttl ?= ?([a-z0-9_.-]+)/i;
171 $def{ttl} = $1 if /ttl ?= ?([a-z0-9_.-]+)/i;
172##fixme? load DB user/pass from config file?
173 }
174 }
175# load from database
176 my $sth = $dbh->prepare("select val,name from rectypes");
177 $sth->execute;
178 while (my ($recval,$recname) = $sth->fetchrow_array()) {
179 $typemap{$recval} = $recname;
180 $reverse_typemap{$recname} = $recval;
181 }
182} # end initGlobals
183
184
185## DNSDB::initPermissions()
186# Set up permissions global
187# Takes database handle and UID
188sub initPermissions {
189 my $dbh = shift;
190 my $uid = shift;
191
192# %permissions = $(getPermissions($dbh,'user',$uid));
193 getPermissions($dbh, 'user', $uid, \%permissions);
194
195} # end initPermissions()
196
197
198## DNSDB::getPermissions()
199# Get permissions from DB
200# Requires DB handle, group or user flag, ID, and hashref.
201sub getPermissions {
202 my $dbh = shift;
203 my $type = shift;
204 my $id = shift;
205 my $hash = shift;
206
207 my $sql = qq(
208 SELECT
209 p.admin,p.self_edit,
210 p.group_create,p.group_edit,p.group_delete,
211 p.user_create,p.user_edit,p.user_delete,
212 p.domain_create,p.domain_edit,p.domain_delete,
213 p.record_create,p.record_edit,p.record_delete
214 FROM permissions p
215 );
216 if ($type eq 'group') {
217 $sql .= qq(
218 JOIN groups g ON g.permission_id=p.permission_id
219 WHERE g.group_id=?
220 );
221 } else {
222 $sql .= qq(
223 JOIN users u ON u.permission_id=p.permission_id
224 WHERE u.user_id=?
225 );
226 }
227
228 my $sth = $dbh->prepare($sql);
229
230 $sth->execute($id) or die "argh: ".$sth->errstr;
231
232# my $permref = $sth->fetchrow_hashref;
233# return $permref;
234# $hash = $permref;
235# Eww. Need to learn how to forcibly drop a hashref onto an existing hash.
236 ($hash->{admin},$hash->{self_edit},
237 $hash->{group_create},$hash->{group_edit},$hash->{group_delete},
238 $hash->{user_create},$hash->{user_edit},$hash->{user_delete},
239 $hash->{domain_create},$hash->{domain_edit},$hash->{domain_delete},
240 $hash->{record_create},$hash->{record_edit},$hash->{record_delete})
241 = $sth->fetchrow_array;
242
243} # end getPermissions()
244
245
246## DNSDB::changePermissions()
247# Update an ACL entry
248# Takes a db handle, type, owner-id, and hashref for the changed permissions.
249sub changePermissions {
250 my $dbh = shift;
251 my $type = shift;
252 my $id = shift;
253 my $newperms = shift;
254 my $inherit = shift || 0;
255
256 my $failmsg = '';
257
258 # see if we're switching from inherited to custom. for bonus points,
259 # snag the permid and parent permid anyway, since we'll need the permid
260 # to set/alter custom perms, and both if we're switching from custom to
261 # inherited.
262 my $sth = $dbh->prepare("SELECT (u.permission_id=g.permission_id) AS was_inherited,u.permission_id,g.permission_id".
263 " FROM ".($type eq 'user' ? 'users' : 'groups')." u ".
264 " JOIN groups g ON u.".($type eq 'user' ? '' : 'parent_')."group_id=g.group_id ".
265 " WHERE u.".($type eq 'user' ? 'user' : 'group')."_id=?");
266 $sth->execute($id);
267
268 my ($wasinherited,$permid,$parpermid) = $sth->fetchrow_array;
269
270# hack phtoui
271# group id 1 is "special" in that it's it's own parent (err... possibly.)
272# may make its parent id 0 which doesn't exist, and as a bonus is Perl-false.
273 $wasinherited = 0 if ($type eq 'group' && $id == 1);
274
275 local $dbh->{AutoCommit} = 0;
276 local $dbh->{RaiseError} = 1;
277
278 # Wrap all the SQL in a transaction
279 eval {
280 if ($inherit) {
281
282 $dbh->do("UPDATE ".($type eq 'user' ? 'users' : 'groups')." SET inherit_perm='t',permission_id=? ".
283 "WHERE ".($type eq 'user' ? 'user' : 'group')."_id=?", undef, ($parpermid, $id) );
284 $dbh->do("DELETE FROM permissions WHERE permission_id=?", undef, ($permid) );
285
286 } else {
287
288 if ($wasinherited) { # munge new permission entry in if we're switching from inherited perms
289##fixme: need to add semirecursive bit to properly munge inherited permission ID on subgroups and users
290# ... if'n'when we have groups with fully inherited permissions.
291 # SQL is coo
292 $dbh->do("INSERT INTO permissions ($permlist,".($type eq 'user' ? 'user' : 'group')."_id) ".
293 "SELECT $permlist,? FROM permissions WHERE permission_id=?", undef, ($id,$permid) );
294 ($permid) = $dbh->selectrow_array("SELECT permission_id FROM permissions ".
295 "WHERE ".($type eq 'user' ? 'user' : 'group')."_id=?", undef, ($id) );
296 $dbh->do("UPDATE ".($type eq 'user' ? 'users' : 'groups')." SET inherit_perm='f',permission_id=? ".
297 "WHERE ".($type eq 'user' ? 'user' : 'group')."_id=?", undef, ($permid, $id) );
298 }
299
300 # and now set the permissions we were passed
301 foreach (@permtypes) {
302 if (defined ($newperms->{$_})) {
303 $dbh->do("UPDATE permissions SET $_=? WHERE permission_id=?", undef, ($newperms->{$_},$permid) );
304 }
305 }
306
307 } # (inherited->)? custom
308
309 $dbh->commit;
310 }; # end eval
311 if ($@) {
312 my $msg = $@;
313 eval { $dbh->rollback; };
314 return ('FAIL',"$failmsg: $msg ($permid)");
315 } else {
316 return ('OK',$permid);
317 }
318
319} # end changePermissions()
320
321
322## DNSDB::comparePermissions()
323# Compare two permission hashes
324# Returns '>', '<', '=', '!'
325sub comparePermissions {
326 my $p1 = shift;
327 my $p2 = shift;
328
329 my $retval = '='; # assume equality until proven otherwise
330
331 no warnings "uninitialized";
332
333 foreach (@permtypes) {
334 next if $p1->{$_} == $p2->{$_}; # equal is good
335 if ($p1->{$_} && !$p2->{$_}) {
336 if ($retval eq '<') { # if we've already found an unequal pair where
337 $retval = '!'; # $p2 has more access, and we now find a pair
338 last; # where $p1 has more access, the overall access
339 } # is neither greater or lesser, it's unequal.
340 $retval = '>';
341 }
342 if (!$p1->{$_} && $p2->{$_}) {
343 if ($retval eq '>') { # if we've already found an unequal pair where
344 $retval = '!'; # $p1 has more access, and we now find a pair
345 last; # where $p2 has more access, the overall access
346 } # is neither greater or lesser, it's unequal.
347 $retval = '<';
348 }
349 }
350 return $retval;
351} # end comparePermissions()
352
353
354## DNSDB::changeGroup()
355# Change group ID of an entity
356# Takes a database handle, entity type, entity ID, and new group ID
357sub changeGroup {
358 my $dbh = shift;
359 my $type = shift;
360 my $id = shift;
361 my $newgrp = shift;
362
363##fixme: fail on not enough args
364 #return ('FAIL', "Missing
365
366 if ($type eq 'domain') {
367 $dbh->do("UPDATE domains SET group_id=? WHERE domain_id=?", undef, ($newgrp, $id))
368 or return ('FAIL','Group change failed: '.$dbh->errstr);
369 } elsif ($type eq 'user') {
370 $dbh->do("UPDATE users SET group_id=? WHERE user_id=?", undef, ($newgrp, $id))
371 or return ('FAIL','Group change failed: '.$dbh->errstr);
372 } elsif ($type eq 'group') {
373 $dbh->do("UPDATE groups SET parent_group_id=? WHERE group_id=?", undef, ($newgrp, $id))
374 or return ('FAIL','Group change failed: '.$dbh->errstr);
375 }
376 return ('OK','OK');
377} # end changeGroup()
378
379
380## DNSDB::_log()
381# Log an action
382# Internal sub
383# Takes a database handle, <foo>, <bar>
384sub _log {
385} # end _log
386
387
388##
389## Processing subs
390##
391
392## DNSDB::addDomain()
393# Add a domain
394# Takes a database handle, domain name, numeric group, and boolean(ish) state (active/inactive)
395# Returns a status code and message
396sub addDomain {
397 $errstr = '';
398 my $dbh = shift;
399 return ('FAIL',"Need database handle") if !$dbh;
400 my $domain = shift;
401 return ('FAIL',"Domain must not be blank") if !$domain;
402 my $group = shift;
403 return ('FAIL',"Need group") if !defined($group);
404 my $state = shift;
405 return ('FAIL',"Need domain status") if !defined($state);
406
407 my $sth = $dbh->prepare("SELECT domain_id FROM domains WHERE domain=?");
408 my $dom_id;
409
410# quick check to start to see if we've already got one
411 $sth->execute($domain);
412 ($dom_id) = $sth->fetchrow_array;
413
414 return ('FAIL', "Domain already exists") if $dom_id;
415
416 # Allow transactions, and raise an exception on errors so we can catch it later.
417 # Use local to make sure these get "reset" properly on exiting this block
418 local $dbh->{AutoCommit} = 0;
419 local $dbh->{RaiseError} = 1;
420
421 # Wrap all the SQL in a transaction
422 eval {
423 # insert the domain...
424 my $sth = $dbh->prepare("insert into domains (domain,group_id,status) values (?,?,?)");
425 $sth->execute($domain,$group,$state);
426
427 # get the ID...
428 $sth = $dbh->prepare("select domain_id from domains where domain='$domain'");
429 $sth->execute;
430 ($dom_id) = $sth->fetchrow_array();
431
432 # ... and now we construct the standard records from the default set. NB: group should be variable.
433 $sth = $dbh->prepare("select host,type,val,distance,weight,port,ttl from default_records where group_id=$group");
434 my $sth_in = $dbh->prepare("insert into records (domain_id,host,type,val,distance,weight,port,ttl)".
435 " values ($dom_id,?,?,?,?,?,?,?)");
436 $sth->execute;
437 while (my ($host,$type,$val,$dist,$weight,$port,$ttl) = $sth->fetchrow_array()) {
438 $host =~ s/DOMAIN/$domain/g;
439 $val =~ s/DOMAIN/$domain/g;
440 $sth_in->execute($host,$type,$val,$dist,$weight,$port,$ttl);
441 }
442
443 # once we get here, we should have suceeded.
444 $dbh->commit;
445 }; # end eval
446
447 if ($@) {
448 my $msg = $@;
449 eval { $dbh->rollback; };
450 return ('FAIL',$msg);
451 } else {
452 return ('OK',$dom_id);
453 }
454} # end addDomain
455
456
457## DNSDB::delDomain()
458# Delete a domain.
459# for now, just delete the records, then the domain.
460# later we may want to archive it in some way instead (status code 2, for example?)
461sub delDomain {
462 my $dbh = shift;
463 my $domid = shift;
464
465 # Allow transactions, and raise an exception on errors so we can catch it later.
466 # Use local to make sure these get "reset" properly on exiting this block
467 local $dbh->{AutoCommit} = 0;
468 local $dbh->{RaiseError} = 1;
469
470 my $failmsg = '';
471
472 # Wrap all the SQL in a transaction
473 eval {
474 my $sth = $dbh->prepare("delete from records where domain_id=?");
475 $failmsg = "Failure removing domain records";
476 $sth->execute($domid);
477 $sth = $dbh->prepare("delete from domains where domain_id=?");
478 $failmsg = "Failure removing domain";
479 $sth->execute($domid);
480
481 # once we get here, we should have suceeded.
482 $dbh->commit;
483 }; # end eval
484
485 if ($@) {
486 my $msg = $@;
487 eval { $dbh->rollback; };
488 return ('FAIL',"$failmsg: $msg");
489 } else {
490 return ('OK','OK');
491 }
492
493} # end delDomain()
494
495
496## DNSDB::domainName()
497# Return the domain name based on a domain ID
498# Takes a database handle and the domain ID
499# Returns the domain name or undef on failure
500sub domainName {
501 $errstr = '';
502 my $dbh = shift;
503 my $domid = shift;
504 my ($domname) = $dbh->selectrow_array("SELECT domain FROM domains WHERE domain_id=?", undef, ($domid) );
505 $errstr = $DBI::errstr if !$domname;
506 return $domname if $domname;
507} # end domainName()
508
509
510## DNSDB::domainID()
511# Takes a database handle and domain name
512# Returns the domain ID number
513sub domainID {
514 $errstr = '';
515 my $dbh = shift;
516 my $domain = shift;
517 my ($domid) = $dbh->selectrow_array("SELECT domain_id FROM domains WHERE domain=?", undef, ($domain) );
518 $errstr = $DBI::errstr if !$domid;
519 return $domid if $domid;
520} # end domainID()
521
522
523## DNSDB::addGroup()
524# Add a group
525# Takes a database handle, group name, parent group, hashref for permissions,
526# and optional template-vs-cloneme flag
527# Returns a status code and message
528sub addGroup {
529 $errstr = '';
530 my $dbh = shift;
531 my $groupname = shift;
532 my $pargroup = shift;
533 my $permissions = shift;
534
535 # 0 indicates "custom", hardcoded.
536 # Any other value clones that group's default records, if it exists.
537 my $inherit = shift || 0;
538##fixme: need a flag to indicate clone records or <?> ?
539
540 # Allow transactions, and raise an exception on errors so we can catch it later.
541 # Use local to make sure these get "reset" properly on exiting this block
542 local $dbh->{AutoCommit} = 0;
543 local $dbh->{RaiseError} = 1;
544
545 my $sth = $dbh->prepare("SELECT group_id FROM groups WHERE group_name=?");
546 my $group_id;
547
548# quick check to start to see if we've already got one
549 $sth->execute($groupname);
550 ($group_id) = $sth->fetchrow_array;
551
552 return ('FAIL', "Group already exists") if $group_id;
553
554 # Wrap all the SQL in a transaction
555 eval {
556 $sth = $dbh->prepare("INSERT INTO groups (parent_group_id,group_name) VALUES (?,?)");
557 $sth->execute($pargroup,$groupname);
558
559 $sth = $dbh->prepare("SELECT group_id FROM groups WHERE group_name=?");
560 $sth->execute($groupname);
561 my ($groupid) = $sth->fetchrow_array();
562
563# Permissions
564 if ($inherit) {
565 } else {
566 my @permvals;
567 foreach (@permtypes) {
568 if (!defined ($permissions->{$_})) {
569 push @permvals, 0;
570 } else {
571 push @permvals, $permissions->{$_};
572 }
573 }
574
575 $sth = $dbh->prepare("INSERT INTO permissions (group_id,$permlist) values (?".',?'x($#permtypes+1).")");
576 $sth->execute($groupid,@permvals);
577
578 $sth = $dbh->prepare("SELECT permission_id FROM permissions WHERE group_id=?");
579 $sth->execute($groupid);
580 my ($permid) = $sth->fetchrow_array();
581
582 $dbh->do("UPDATE groups SET permission_id=$permid WHERE group_id=$groupid");
583 } # done permission fiddling
584
585# Default records
586 $sth = $dbh->prepare("INSERT INTO default_records (group_id,host,type,val,distance,weight,port,ttl) ".
587 "VALUES ($groupid,?,?,?,?,?,?,?)");
588 if ($inherit) {
589 # Duplicate records from parent. Actually relying on inherited records feels
590 # very fragile, and it would be problematic to roll over at a later time.
591 my $sth2 = $dbh->prepare("SELECT host,type,val,distance,weight,port,ttl FROM default_records WHERE group_id=?");
592 $sth2->execute($pargroup);
593 while (my @clonedata = $sth2->fetchrow_array) {
594 $sth->execute(@clonedata);
595 }
596 } else {
597##fixme: Hardcoding is Bad, mmmmkaaaay?
598 # reasonable basic defaults for SOA, MX, NS, and minimal hosting
599 # could load from a config file, but somewhere along the line we need hardcoded bits.
600 $sth->execute('ns1.example.com:hostmaster.example.com', 6, '10800:3600:604800:10800', 0, 0, 0, 86400);
601 $sth->execute('DOMAIN', 1, '192.168.4.2', 0, 0, 0, 7200);
602 $sth->execute('DOMAIN', 15, 'mx.example.com', 10, 0, 0, 7200);
603 $sth->execute('DOMAIN', 2, 'ns1.example.com', 0, 0, 0, 7200);
604 $sth->execute('DOMAIN', 2, 'ns2.example.com', 0, 0, 0, 7200);
605 $sth->execute('www.DOMAIN', 5, 'DOMAIN', 0, 0, 0, 7200);
606 }
607
608 # once we get here, we should have suceeded.
609 $dbh->commit;
610 }; # end eval
611
612 if ($@) {
613 my $msg = $@;
614 eval { $dbh->rollback; };
615 return ('FAIL',$msg);
616 } else {
617 return ('OK','OK');
618 }
619
620} # end addGroup()
621
622
623## DNSDB::delGroup()
624# Delete a group.
625# Takes a group ID
626# Returns a status code and message
627sub delGroup {
628 my $dbh = shift;
629 my $groupid = shift;
630
631 # Allow transactions, and raise an exception on errors so we can catch it later.
632 # Use local to make sure these get "reset" properly on exiting this block
633 local $dbh->{AutoCommit} = 0;
634 local $dbh->{RaiseError} = 1;
635
636##fixme: locate "knowable" error conditions and deal with them before the eval
637# ... or inside, whatever.
638# -> domains still exist in group
639# -> ...
640 my $failmsg = '';
641
642 # Wrap all the SQL in a transaction
643 eval {
644 my $sth = $dbh->prepare("SELECT count(*) FROM domains WHERE group_id=?");
645 $sth->execute($groupid);
646 my ($domcnt) = $sth->fetchrow_array;
647 $failmsg = "Can't remove group ".groupName($dbh,$groupid);
648 die "$domcnt domains still in group\n" if $domcnt;
649
650 $sth = $dbh->prepare("delete from default_records where group_id=?");
651 $failmsg = "Failed to delete default records for ".groupName($dbh,$groupid);
652 $sth->execute($groupid);
653 $sth = $dbh->prepare("delete from groups where group_id=?");
654 $failmsg = "Failed to remove group ".groupName($dbh,$groupid);
655 $sth->execute($groupid);
656
657 # once we get here, we should have suceeded.
658 $dbh->commit;
659 }; # end eval
660
661 if ($@) {
662 my $msg = $@;
663 eval { $dbh->rollback; };
664 return ('FAIL',"$failmsg: $msg");
665 } else {
666 return ('OK','OK');
667 }
668} # end delGroup()
669
670
671## DNSDB::getChildren()
672# Get a list of all groups whose parent^n is group <n>
673# Takes a database handle, group ID, reference to an array to put the group IDs in,
674# and an optional flag to return only immediate children or all children-of-children
675# default to returning all children
676# Calls itself
677sub getChildren {
678 $errstr = '';
679 my $dbh = shift;
680 my $rootgroup = shift;
681 my $groupdest = shift;
682 my $immed = shift || 'all';
683
684 # special break for default group; otherwise we get stuck.
685 if ($rootgroup == 1) {
686 # by definition, group 1 is the Root Of All Groups
687 my $sth = $dbh->prepare("SELECT group_id FROM groups WHERE NOT (group_id=1)".
688 ($immed ne 'all' ? " AND parent_group_id=1" : ''));
689 $sth->execute;
690 while (my @this = $sth->fetchrow_array) {
691 push @$groupdest, @this;
692 }
693 } else {
694 my $sth = $dbh->prepare("SELECT group_id FROM groups WHERE parent_group_id=?");
695 $sth->execute($rootgroup);
696 return if $sth->rows == 0;
697 my @grouplist;
698 while (my ($group) = $sth->fetchrow_array) {
699 push @$groupdest, $group;
700 getChildren($dbh,$group,$groupdest) if $immed eq 'all';
701 }
702 }
703} # end getChildren()
704
705
706## DNSDB::groupName()
707# Return the group name based on a group ID
708# Takes a database handle and the group ID
709# Returns the group name or undef on failure
710sub groupName {
711 $errstr = '';
712 my $dbh = shift;
713 my $groupid = shift;
714 my $sth = $dbh->prepare("SELECT group_name FROM groups WHERE group_id=?");
715 $sth->execute($groupid);
716 my ($groupname) = $sth->fetchrow_array();
717 $errstr = $DBI::errstr if !$groupname;
718 return $groupname if $groupname;
719} # end groupName
720
721
722## DNSDB::addUser()
723# Add a user.
724# Takes a DB handle, username, group ID, password, state (active/inactive).
725# Optionally accepts:
726# user type (user/admin) - defaults to user
727# permissions string - defaults to inherit from group
728# three valid forms:
729# i - Inherit permissions
730# c:<user_id> - Clone permissions from <user_id>
731# C:<permission list> - Set these specific permissions
732# first name - defaults to username
733# last name - defaults to blank
734# phone - defaults to blank (could put other data within column def)
735# Returns (OK,<uid>) on success, (FAIL,<message>) on failure
736sub addUser {
737 $errstr = '';
738 my $dbh = shift;
739 my $username = shift;
740 my $group = shift;
741 my $pass = shift;
742 my $state = shift;
743
744 return ('FAIL', "Missing one or more required entries") if !defined($state);
745 return ('FAIL', "Username must not be blank") if !$username;
746
747 my $type = shift || 'u'; # create limited users by default - fwiw, not sure yet how this will interact with ACLs
748
749 my $permstring = shift || 'i'; # default is to inhert permissions from group
750
751 my $fname = shift || $username;
752 my $lname = shift || '';
753 my $phone = shift || ''; # not going format-check
754
755 my $sth = $dbh->prepare("SELECT user_id FROM users WHERE username=?");
756 my $user_id;
757
758# quick check to start to see if we've already got one
759 $sth->execute($username);
760 ($user_id) = $sth->fetchrow_array;
761
762 return ('FAIL', "User already exists") if $user_id;
763
764 # Allow transactions, and raise an exception on errors so we can catch it later.
765 # Use local to make sure these get "reset" properly on exiting this block
766 local $dbh->{AutoCommit} = 0;
767 local $dbh->{RaiseError} = 1;
768
769 my $failmsg = '';
770
771 # Wrap all the SQL in a transaction
772 eval {
773 # insert the user... note we set inherited perms by default since
774 # it's simple and cleans up some other bits of state
775 my $sth = $dbh->prepare("INSERT INTO users ".
776 "(group_id,username,password,firstname,lastname,phone,type,status,permission_id,inherit_perm) ".
777 "VALUES (?,?,?,?,?,?,?,?,(SELECT permission_id FROM permissions WHERE group_id=?),'t')");
778 $sth->execute($group,$username,unix_md5_crypt($pass),$fname,$lname,$phone,$type,$state,$group);
779
780 # get the ID...
781 ($user_id) = $dbh->selectrow_array("SELECT currval('users_user_id_seq')");
782
783# Permissions! Gotta set'em all!
784 die "Invalid permission string $permstring"
785 if $permstring !~ /^(?:
786 i # inherit
787 |c:\d+ # clone
788 # custom. no, the leading , is not a typo
789 |C:(?:,(?:group|user|domain|record|self)_(?:edit|create|delete))*
790 )$/x;
791# bleh. I'd call another function to do my dirty work, but we're in the middle of a transaction already.
792 if ($permstring ne 'i') {
793 # for cloned or custom permissions, we have to create a new permissions entry.
794 my $clonesrc = $group;
795 if ($permstring =~ /^c:(\d+)/) { $clonesrc = $1; }
796 $dbh->do("INSERT INTO permissions ($permlist,user_id) ".
797 "SELECT $permlist,? FROM permissions WHERE permission_id=".
798 "(SELECT permission_id FROM permissions WHERE ".($permstring =~ /^c:/ ? 'user' : 'group')."_id=?)",
799 undef, ($user_id,$clonesrc) );
800 $dbh->do("UPDATE users SET permission_id=".
801 "(SELECT permission_id FROM permissions WHERE user_id=?) ".
802 "WHERE user_id=?", undef, ($user_id, $user_id) );
803 }
804 if ($permstring =~ /^C:/) {
805 # finally for custom permissions, we set the passed-in permissions (and unset
806 # any that might have been brought in by the clone operation above)
807 my ($permid) = $dbh->selectrow_array("SELECT permission_id FROM permissions WHERE user_id=?",
808 undef, ($user_id) );
809 foreach (@permtypes) {
810 if ($permstring =~ /,$_/) {
811 $dbh->do("UPDATE permissions SET $_='t' WHERE permission_id=?", undef, ($permid) );
812 } else {
813 $dbh->do("UPDATE permissions SET $_='f' WHERE permission_id=?", undef, ($permid) );
814 }
815 }
816 }
817
818 $dbh->do("UPDATE users SET inherit_perm='n' WHERE user_id=?", undef, ($user_id) );
819
820##fixme: add another table to hold name/email for log table?
821
822 # once we get here, we should have suceeded.
823 $dbh->commit;
824 }; # end eval
825
826 if ($@) {
827 my $msg = $@;
828 eval { $dbh->rollback; };
829 return ('FAIL',$msg." $failmsg");
830 } else {
831 return ('OK',$user_id);
832 }
833} # end addUser
834
835
836## DNSDB::checkUser()
837# Check user/pass combo on login
838sub checkUser {
839 my $dbh = shift;
840 my $user = shift;
841 my $inpass = shift;
842
843 my $sth = $dbh->prepare("SELECT user_id,group_id,password,firstname,lastname FROM users WHERE username=?");
844 $sth->execute($user);
845 my ($uid,$gid,$pass,$fname,$lname) = $sth->fetchrow_array;
846 my $loginfailed = 1 if !defined($uid);
847
848 if ($pass =~ m|^\$1\$([A-Za-z0-9/.]+)\$|) {
849 $loginfailed = 1 if $pass ne unix_md5_crypt($inpass,$1);
850 } else {
851 $loginfailed = 1 if $pass ne $inpass;
852 }
853
854 # nnnngggg
855 return ($uid, $gid);
856} # end checkUser
857
858
859## DNSDB:: updateUser()
860# Update general data about user
861sub updateUser {
862 my $dbh = shift;
863 my $uid = shift;
864 my $username = shift;
865 my $group = shift;
866 my $pass = shift;
867 my $state = shift;
868 my $type = shift || 'u';
869 my $fname = shift || $username;
870 my $lname = shift || '';
871 my $phone = shift || ''; # not going format-check
872
873 my $failmsg = '';
874
875 # Allow transactions, and raise an exception on errors so we can catch it later.
876 # Use local to make sure these get "reset" properly on exiting this block
877 local $dbh->{AutoCommit} = 0;
878 local $dbh->{RaiseError} = 1;
879
880 my $sth;
881
882 # Password can be left blank; if so we assume there's one on file.
883 # Actual blank passwords are bad, mm'kay?
884 if (!$pass) {
885 $sth = $dbh->prepare("SELECT password FROM users WHERE user_id=?");
886 $sth->execute($uid);
887 ($pass) = $sth->fetchrow_array;
888 } else {
889 $pass = unix_md5_crypt($pass);
890 }
891
892 eval {
893 my $sth = $dbh->prepare(q(
894 UPDATE users
895 SET username=?, password=?, firstname=?, lastname=?, phone=?, type=?, status=?
896 WHERE user_id=?
897 )
898 );
899 $sth->execute($username, $pass, $fname, $lname, $phone, $type, $state, $uid);
900 $dbh->commit;
901 };
902 if ($@) {
903 my $msg = $@;
904 eval { $dbh->rollback; };
905 return ('FAIL',"$failmsg: $msg");
906 } else {
907 return ('OK','OK');
908 }
909} # end updateUser()
910
911
912## DNSDB::delUser()
913#
914sub delUser {
915 my $dbh = shift;
916 return ('FAIL',"Need database handle") if !$dbh;
917 my $userid = shift;
918 return ('FAIL',"Missing userid") if !defined($userid);
919
920 my $sth = $dbh->prepare("delete from users where user_id=?");
921 $sth->execute($userid);
922
923 return ('FAIL',"Couldn't remove user: ".$sth->errstr) if $sth->err;
924
925 return ('OK','OK');
926
927} # end delUser
928
929
930## DNSDB::userFullName()
931# Return a pretty string!
932# Takes a user_id and optional printf-ish string to indicate which pieces where:
933# %u for the username
934# %f for the first name
935# %l for the last name
936# All other text in the passed string will be left as-is.
937##fixme: need a "smart" option too, so that missing/null/blank first/last names don't give funky output
938sub userFullName {
939 $errstr = '';
940 my $dbh = shift;
941 my $userid = shift;
942 my $fullformat = shift || '%f %l (%u)';
943 my $sth = $dbh->prepare("select username,firstname,lastname from users where user_id=?");
944 $sth->execute($userid);
945 my ($uname,$fname,$lname) = $sth->fetchrow_array();
946 $errstr = $DBI::errstr if !$uname;
947
948 $fullformat =~ s/\%u/$uname/g;
949 $fullformat =~ s/\%f/$fname/g;
950 $fullformat =~ s/\%l/$lname/g;
951
952 return $fullformat;
953} # end userFullName
954
955
956## DNSDB::userStatus()
957# Sets and/or returns a user's status
958# Takes a database handle, user ID and optionally a status argument
959# Returns undef on errors.
960sub userStatus {
961 my $dbh = shift;
962 my $id = shift;
963 my $newstatus = shift;
964
965 return undef if $id !~ /^\d+$/;
966
967 my $sth;
968
969# ooo, fun! let's see what we were passed for status
970 if ($newstatus) {
971 $sth = $dbh->prepare("update users set status=? where user_id=?");
972 # ass-u-me caller knows what's going on in full
973 if ($newstatus =~ /^[01]$/) { # only two valid for now.
974 $sth->execute($newstatus,$id);
975 } elsif ($newstatus =~ /^usero(?:n|ff)$/) {
976 $sth->execute(($newstatus eq 'useron' ? 1 : 0),$id);
977 }
978 }
979
980 $sth = $dbh->prepare("select status from users where user_id=?");
981 $sth->execute($id);
982 my ($status) = $sth->fetchrow_array;
983 return $status;
984} # end userStatus()
985
986
987## DNSDB::getUserData()
988# Get misc user data for display
989sub getUserData {
990 my $dbh = shift;
991 my $uid = shift;
992
993 my $sth = $dbh->prepare("SELECT group_id,username,firstname,lastname,phone,type,status,inherit_perm ".
994 "FROM users WHERE user_id=?");
995 $sth->execute($uid);
996 return $sth->fetchrow_hashref();
997
998} # end getUserData()
999
1000
1001## DNSDB::getSOA()
1002# Return all suitable fields from an SOA record in separate elements of a hash
1003# Takes a database handle, default/live flag, and group (default) or domain (live) ID
1004sub getSOA {
1005 $errstr = '';
1006 my $dbh = shift;
1007 my $def = shift;
1008 my $id = shift;
1009 my %ret;
1010
1011 # (ab)use distance and weight columns to store SOA data
1012
1013 my $sql = "SELECT record_id,host,val,ttl,distance from";
1014 if ($def eq 'def' or $def eq 'y') {
1015 $sql .= " default_records WHERE group_id=? AND type=$reverse_typemap{SOA}";
1016 } else {
1017 # we're editing a live SOA record; find based on domain
1018 $sql .= " records WHERE domain_id=? AND type=$reverse_typemap{SOA}";
1019 }
1020 my $sth = $dbh->prepare($sql);
1021 $sth->execute($id);
1022
1023 my ($recid,$host,$val,$ttl,$serial) = $sth->fetchrow_array();
1024 my ($prins,$contact) = split /:/, $host;
1025 my ($refresh,$retry,$expire,$minttl) = split /:/, $val;
1026
1027 $ret{recid} = $recid;
1028 $ret{ttl} = $ttl;
1029 $ret{serial} = $serial;
1030 $ret{prins} = $prins;
1031 $ret{contact} = $contact;
1032 $ret{refresh} = $refresh;
1033 $ret{retry} = $retry;
1034 $ret{expire} = $expire;
1035 $ret{minttl} = $minttl;
1036
1037 return %ret;
1038} # end getSOA()
1039
1040
1041## DNSDB::getRecLine()
1042# Return all data fields for a zone record in separate elements of a hash
1043# Takes a database handle, default/live flag, and record ID
1044sub getRecLine {
1045 $errstr = '';
1046 my $dbh = shift;
1047 my $def = shift;
1048 my $id = shift;
1049
1050 my $sql = "SELECT r.record_id,r.host,r.type,r.val,r.distance,r.weight,r.port,r.ttl,r.longrec_id,l.recdata".
1051 (($def eq 'def' or $def eq 'y') ? ',r.group_id FROM default_' : ',r.domain_id FROM ').
1052 "records r LEFT OUTER JOIN longrecs l ON r.longrec_id=l.longrec_id WHERE record_id=?";
1053 my $ret = $dbh->selectrow_hashref($sql, undef, ($id) ) or warn $dbh->errstr;
1054
1055 if ($dbh->err) {
1056 $errstr = $DBI::errstr;
1057 return undef;
1058 }
1059
1060 $ret->{val} = $ret->{recdata} if $ret->{longrec_id}; # put the long data in the real value space
1061 delete $ret->{longrec_id}; # remove these since they shouldn't be exposed - the caller
1062 delete $ret->{recdata}; # should not care about "long records" vs normal ones.
1063 $ret->{parid} = (($def eq 'def' or $def eq 'y') ? $ret->{group_id} : $ret->{domain_id});
1064
1065 return $ret;
1066}
1067
1068
1069##fixme: should use above (getRecLine()) to get lines for below?
1070## DNSDB::getDomRecs()
1071# Return records for a domain
1072# Takes a database handle, default/live flag, group/domain ID, start,
1073# number of records, sort field, and sort order
1074# Returns a reference to an array of hashes
1075sub getDomRecs {
1076 $errstr = '';
1077 my $dbh = shift;
1078 my $type = shift;
1079 my $id = shift;
1080 my $nrecs = shift || 'all';
1081 my $nstart = shift || 0;
1082
1083## for order, need to map input to column names
1084 my $order = shift || 'host';
1085 my $direction = shift || 'ASC';
1086
1087 $type = 'y' if $type eq 'def';
1088
1089 my $sql = "SELECT r.record_id,r.host,r.type,r.val,r.distance,r.weight,r.port,r.ttl,r.longrec_id,l.recdata FROM ";
1090 $sql .= "default_" if $type eq 'y';
1091 $sql .= "records r ";
1092 $sql .= "INNER JOIN rectypes t ON r.type=t.val "; # for sorting by type alphabetically
1093 $sql .= "LEFT OUTER JOIN longrecs l ON r.longrec_id=l.longrec_id ";
1094 if ($type eq 'y') {
1095 $sql .= "WHERE r.group_id=?";
1096 } else {
1097 $sql .= "WHERE r.domain_id=?";
1098 }
1099 $sql .= " AND NOT r.type=$reverse_typemap{SOA}";
1100 # use alphaorder column for "correct" ordering of sort-by-type instead of DNS RR type number
1101 $sql .= " ORDER BY ".($order eq 'type' ? 't.alphaorder' : "r.$order")." $direction";
1102 $sql .= " LIMIT $nrecs OFFSET ".($nstart*$nrecs) if $nstart ne 'all';
1103
1104 my $sth = $dbh->prepare($sql) or warn $dbh->errstr;
1105 $sth->execute($id) or warn "$sql: ".$sth->errstr;
1106
1107 my @retbase;
1108 while (my $ref = $sth->fetchrow_hashref()) {
1109 $ref->{val} = $ref->{recdata} if $ref->{longrec_id}; # put the long data in the real value space
1110 delete $ref->{longrec_id}; # remove these since they shouldn't be exposed - the caller
1111 delete $ref->{recdata}; # should not care about "long records" vs normal ones.
1112 push @retbase, $ref;
1113 }
1114
1115 my $ret = \@retbase;
1116 return $ret;
1117} # end getDomRecs()
1118
1119
1120## DNSDB::getRecCount()
1121# Return count of non-SOA records in domain (or default records in a group)
1122# Takes a database handle, default/live flag and group/domain ID
1123# Returns the count
1124sub getRecCount {
1125 my $dbh = shift;
1126 my $defrec = shift;
1127 my $id = shift;
1128
1129 my ($count) = $dbh->selectrow_array("SELECT count(*) FROM ".
1130 ($defrec eq 'y' ? 'default_' : '')."records ".
1131 "WHERE ".($defrec eq 'y' ? 'group' : 'domain')."_id=? ".
1132 "AND NOT type=$reverse_typemap{SOA}", undef, ($id) );
1133
1134 return $count;
1135
1136} # end getRecCount()
1137
1138
1139## DNSDB::addRec()
1140# Add a new record to a domain or a group's default records
1141# Takes a database handle, default/live flag, group/domain ID,
1142# host, type, value, and TTL
1143# Some types require additional detail: "distance" for MX and SRV,
1144# and weight/port for SRV
1145# Returns a status code and detail message in case of error
1146sub addRec {
1147 $errstr = '';
1148 my $dbh = shift;
1149 my $defrec = shift;
1150 my $id = shift;
1151
1152 my $host = shift;
1153 my $rectype = shift;
1154 my $val = shift;
1155 my $ttl = shift;
1156
1157 my $fields = ($defrec eq 'y' ? 'group_id' : 'domain_id').",host,type,val,ttl";
1158 my $vallen = "?,?,?,?,?";
1159 my @vallist = ($id,$host,$rectype,$val,$ttl);
1160
1161 my $dist;
1162 if ($rectype == $reverse_typemap{MX} or $rectype == $reverse_typemap{SRV}) {
1163 $dist = shift;
1164 return ('FAIL',"Need distance for $typemap{$rectype} record") if !defined($dist);
1165 $fields .= ",distance";
1166 $vallen .= ",?";
1167 push @vallist, $dist;
1168 }
1169 my $weight;
1170 my $port;
1171 if ($rectype == $reverse_typemap{SRV}) {
1172 # check for _service._protocol. NB: RFC2782 does not say "MUST"... nor "SHOULD"...
1173 # it just says (paraphrased) "... is prepended with _ to prevent DNS collisions"
1174 return ('FAIL',"SRV records must begin with _service._protocol")
1175 if $host !~ /^_[A-Za-z]+\._[A-Za-z]+\.[a-z0-9-]+/;
1176 $weight = shift;
1177 $port = shift;
1178 return ('FAIL',"Need weight and port for SRV record") if !defined($weight) or !defined($port);
1179 $fields .= ",weight,port";
1180 $vallen .= ",?,?";
1181 push @vallist, ($weight,$port);
1182 }
1183
1184 # Allow transactions, and raise an exception on errors so we can catch it later.
1185 # Use local to make sure these get "reset" properly on exiting this block
1186 local $dbh->{AutoCommit} = 0;
1187 local $dbh->{RaiseError} = 1;
1188
1189 eval {
1190 if (length($val) > 100 ) {
1191 # extralong records get an entry in a separate table.
1192 $dbh->do("INSERT INTO longrecs (recdata) VALUES (?)", undef, ($val) );
1193 my ($longid) = $dbh->selectrow_array("SELECT longrec_id FROM longrecs WHERE recdata=?", undef, ($val) );
1194 $fields .= ",longrec_id";
1195 $vallen .= ",?";
1196 push @vallist, $longid;
1197 $vallist[3] = ''; # so we don't barf when we insert the main record
1198 }
1199 $dbh->do("INSERT INTO ".($defrec eq 'y' ? 'default_' : '')."records ($fields) VALUES ($vallen)",
1200 undef, @vallist);
1201 $dbh->commit;
1202 };
1203 if ($@) {
1204 my $msg = $@;
1205 eval { $dbh->rollback; };
1206 return ('FAIL',$msg);
1207 }
1208
1209 return ('OK','OK');
1210
1211} # end addRec()
1212
1213
1214## DNSDB::updateRec()
1215# Update a record
1216sub updateRec {
1217 $errstr = '';
1218
1219 my $dbh = shift;
1220 my $defrec = shift;
1221 my $id = shift;
1222
1223# all records have these
1224 my $host = shift;
1225 my $type = shift;
1226 my $val = shift;
1227 my $ttl = shift;
1228
1229 return('FAIL',"Missing standard argument(s)") if !defined($ttl);
1230
1231# only MX and SRV will use these
1232 my $dist = 0;
1233 my $weight = 0;
1234 my $port = 0;
1235
1236 if ($type == $reverse_typemap{MX} || $type == $reverse_typemap{SRV}) {
1237 $dist = shift;
1238 return ('FAIL',"MX or SRV requires distance") if !defined($dist);
1239 if ($type == $reverse_typemap{SRV}) {
1240 $weight = shift;
1241 return ('FAIL',"SRV requires weight") if !defined($weight);
1242 $port = shift;
1243 return ('FAIL',"SRV requires port") if !defined($port);
1244 }
1245 }
1246
1247# my $sql = "SELECT r.record_id,r.host,r.type,r.val,r.distance,r.weight,r.port,r.ttl,r.longrec_id,l.recdata FROM ";
1248# $sql .= "default_" if $type eq 'y';
1249# $sql .= "records r ";
1250# $sql .= "LEFT OUTER JOIN longrecs l ON r.longrec_id=l.longrec_id ";
1251
1252 # get the long record ID, if any
1253 my ($longid) = $dbh->selectrow_array("SELECT longrec_id FROM ".($defrec eq 'y' ? 'default_' : '')."records ".
1254 "WHERE record_id=?", undef, ($id) );
1255
1256 local $dbh->{AutoCommit} = 0;
1257 local $dbh->{RaiseError} = 1;
1258
1259 eval {
1260 # there's really no tidy way to squash this down. :/
1261 if (length($val) > 100) {
1262 if ($longid) {
1263 $dbh->do("UPDATE longrecs SET recdata=? WHERE longrec_id=?", undef, ($val, $longid) );
1264 } else {
1265##fixme: has to be a better way to be sure we get the right recid back once inserted...
1266 $dbh->do("INSERT INTO longrecs (recdata) VALUES (?)", undef, ($val) );
1267 my ($newlongid) = $dbh->selectrow_array("SELECT currval('longrecs_longrec_id_seq')");
1268 $dbh->do("UPDATE ".($defrec eq 'y' ? 'default_' : '')."records SET val=?,longrec_id=? ".
1269 "WHERE record_id=?", undef, ('', $newlongid, $id) );
1270 }
1271 } else {
1272 if ($longid) {
1273 $dbh->do("DELETE FROM longrecs WHERE longrec_id=?", undef, ($longid) );
1274 $dbh->do("UPDATE ".($defrec eq 'y' ? 'default_' : '')."records SET val=?,longrec_id=NULL ".
1275 "WHERE record_id=?", undef, ($val, $id) );
1276 } else {
1277 $dbh->do("UPDATE ".($defrec eq 'y' ? 'default_' : '')."records SET val=? ".
1278 "WHERE record_id=?", undef, ($val, $id) );
1279 }
1280 }
1281
1282 $dbh->do("UPDATE ".($defrec eq 'y' ? 'default_' : '')."records ".
1283 "SET host=?,type=?,ttl=?,distance=?,weight=?,port=? ".
1284 "WHERE record_id=?", undef, ($host, $type, $ttl, $dist, $weight, $port, $id) );
1285
1286 };
1287 if ($@) {
1288 my $msg = $@;
1289 $dbh->rollback;
1290 return ('FAIL', $msg);
1291 }
1292# return ('FAIL',$sth->errstr."<br>\n$errstr<br>\n") if $sth->err;
1293
1294 return ('OK','OK');
1295} # end updateRec()
1296
1297
1298## DNSDB::delRec()
1299# Delete a record.
1300sub delRec {
1301 $errstr = '';
1302 my $dbh = shift;
1303 my $defrec = shift;
1304 my $id = shift;
1305
1306 my $sth = $dbh->prepare("DELETE FROM ".($defrec eq 'y' ? 'default_' : '')."records WHERE record_id=?");
1307 $sth->execute($id);
1308
1309 return ('FAIL',"Couldn't remove record: ".$sth->errstr) if $sth->err;
1310
1311 return ('OK','OK');
1312} # end delRec()
1313
1314
1315## DNSDB::domStatus()
1316# Sets and/or returns a domain's status
1317# Takes a database handle, domain ID and optionally a status argument
1318# Returns undef on errors.
1319sub domStatus {
1320 my $dbh = shift;
1321 my $id = shift;
1322 my $newstatus = shift;
1323
1324 return undef if $id !~ /^\d+$/;
1325
1326 my $sth;
1327
1328# ooo, fun! let's see what we were passed for status
1329 if ($newstatus) {
1330 $sth = $dbh->prepare("update domains set status=? where domain_id=?");
1331 # ass-u-me caller knows what's going on in full
1332 if ($newstatus =~ /^[01]$/) { # only two valid for now.
1333 $sth->execute($newstatus,$id);
1334 } elsif ($newstatus =~ /^domo(?:n|ff)$/) {
1335 $sth->execute(($newstatus eq 'domon' ? 1 : 0),$id);
1336 }
1337 }
1338
1339 $sth = $dbh->prepare("select status from domains where domain_id=?");
1340 $sth->execute($id);
1341 my ($status) = $sth->fetchrow_array;
1342 return $status;
1343} # end domStatus()
1344
1345
1346## DNSDB::importAXFR
1347# Import a domain via AXFR
1348# Takes AXFR host, domain to transfer, group to put the domain in,
1349# and optionally:
1350# - active/inactive state flag (defaults to active)
1351# - overwrite-SOA flag (defaults to off)
1352# - overwrite-NS flag (defaults to off, doesn't affect subdomain NS records)
1353# Returns a status code (OK, WARN, or FAIL) and message - message should be blank
1354# if status is OK, but WARN includes conditions that are not fatal but should
1355# really be reported.
1356sub importAXFR {
1357 my $dbh = shift;
1358 my $ifrom_in = shift;
1359 my $domain = shift;
1360 my $group = shift;
1361 my $status = shift || 1;
1362 my $rwsoa = shift || 0;
1363 my $rwns = shift || 0;
1364
1365##fixme: add mode to delete&replace, merge+overwrite, merge new?
1366
1367 my $nrecs = 0;
1368 my $soaflag = 0;
1369 my $nsflag = 0;
1370 my $warnmsg = '';
1371 my $ifrom;
1372
1373 # choke on possible bad setting in ifrom
1374 # IPv4 and v6, and valid hostnames!
1375 ($ifrom) = ($ifrom_in =~ /^([0-9a-f\:.]+|[0-9a-z_.-]+)$/i);
1376 return ('FAIL', "Bad AXFR source host $ifrom")
1377 unless ($ifrom) = ($ifrom_in =~ /^([0-9a-f\:.]+|[0-9a-z_.-]+)$/i);
1378
1379 # Allow transactions, and raise an exception on errors so we can catch it later.
1380 # Use local to make sure these get "reset" properly on exiting this block
1381 local $dbh->{AutoCommit} = 0;
1382 local $dbh->{RaiseError} = 1;
1383
1384 my $sth = $dbh->prepare("SELECT domain_id FROM domains WHERE domain=?");
1385 my $dom_id;
1386
1387# quick check to start to see if we've already got one
1388 $sth->execute($domain);
1389 ($dom_id) = $sth->fetchrow_array;
1390
1391 return ('FAIL', "Domain already exists") if $dom_id;
1392
1393 eval {
1394 # can't do this, can't nest transactions. sigh.
1395 #my ($dcode, $dmsg) = addDomain(dbh, domain, group, status);
1396
1397##fixme: serial
1398 my $sth = $dbh->prepare("INSERT INTO domains (domain,group_id,status) VALUES (?,?,?)");
1399 $sth->execute($domain,$group,$status);
1400
1401## bizarre DBI<->Net::DNS interaction bug:
1402## sometimes a zone will cause an immediate commit-and-exit (sort of) of the while()
1403## fixed, apparently I was doing *something* odd, but not certain what it was that
1404## caused a commit instead of barfing
1405
1406 # get domain id so we can do the records
1407 $sth = $dbh->prepare("SELECT domain_id FROM domains WHERE domain=?");
1408 $sth->execute($domain);
1409 ($dom_id) = $sth->fetchrow_array();
1410
1411 my $res = Net::DNS::Resolver->new;
1412 $res->nameservers($ifrom);
1413 $res->axfr_start($domain)
1414 or die "Couldn't begin AXFR\n";
1415
1416 while (my $rr = $res->axfr_next()) {
1417 my $type = $rr->type;
1418
1419 my $sql = "INSERT INTO records (domain_id,host,type,ttl,val";
1420 my $vallen = "?,?,?,?,?";
1421
1422 $soaflag = 1 if $type eq 'SOA';
1423 $nsflag = 1 if $type eq 'NS';
1424
1425 my @vallist = ($dom_id, $rr->name, $reverse_typemap{$type}, $rr->ttl);
1426
1427# "Primary" types:
1428# A, NS, CNAME, SOA, PTR(warn in forward), MX, TXT, AAAA, SRV, A6(ob), SPF
1429# maybe KEY
1430
1431# nasty big ugly case-like thing here, since we have to do *some* different
1432# processing depending on the record. le sigh.
1433
1434##fixme: what record types other than TXT can/will have >255-byte payloads?
1435
1436 if ($type eq 'A') {
1437 push @vallist, $rr->address;
1438 } elsif ($type eq 'NS') {
1439# hmm. should we warn here if subdomain NS'es are left alone?
1440 next if ($rwns && ($rr->name eq $domain));
1441 push @vallist, $rr->nsdname;
1442 $nsflag = 1;
1443 } elsif ($type eq 'CNAME') {
1444 push @vallist, $rr->cname;
1445 } elsif ($type eq 'SOA') {
1446 next if $rwsoa;
1447 $vallist[1] = $rr->mname.":".$rr->rname;
1448 push @vallist, ($rr->refresh.":".$rr->retry.":".$rr->expire.":".$rr->minimum);
1449 $soaflag = 1;
1450 } elsif ($type eq 'PTR') {
1451 push @vallist, $rr->ptrdname;
1452 # hmm. PTR records should not be in forward zones.
1453 } elsif ($type eq 'MX') {
1454 $sql .= ",distance";
1455 $vallen .= ",?";
1456 push @vallist, $rr->exchange;
1457 push @vallist, $rr->preference;
1458 } elsif ($type eq 'TXT') {
1459##fixme: Net::DNS docs say this should be deprecated for rdatastr() or char_str_list(),
1460## but don't really seem enthusiastic about it.
1461 my $rrdata = $rr->txtdata;
1462 if (length($rrdata) > 100 ) {
1463 # extralong records get an entry in a separate table.
1464 $dbh->do("INSERT INTO longrecs (recdata) VALUES (?)", undef, ($rrdata) );
1465 my ($longid) = $dbh->selectrow_array("SELECT longrec_id FROM longrecs WHERE recdata=?", undef, ($rrdata) );
1466 $sql .= ",longrec_id";
1467 $vallen .= ",?";
1468 push @vallist, '';
1469 push @vallist, $longid;
1470 } else {
1471 push @vallist, $rrdata;
1472 }
1473 } elsif ($type eq 'SPF') {
1474##fixme: and the same caveat here, since it is apparently a clone of ::TXT
1475 my $rrdata = $rr->txtdata;
1476 if (length($rrdata) > 100 ) {
1477 # extralong records get an entry in a separate table.
1478 $dbh->do("INSERT INTO longrecs (recdata) VALUES (?)", undef, ($rrdata) );
1479 my ($longid) = $dbh->selectrow_array("SELECT longrec_id FROM longrecs WHERE recdata=?", undef, ($rrdata) );
1480 $sql .= ",longrec_id";
1481 $vallen .= ",?";
1482 push @vallist, '';
1483 push @vallist, $longid;
1484 } else {
1485 push @vallist, $rrdata;
1486 }
1487 } elsif ($type eq 'AAAA') {
1488 push @vallist, $rr->address;
1489 } elsif ($type eq 'SRV') {
1490 $sql .= ",distance,weight,port" if $type eq 'SRV';
1491 $vallen .= ",?,?,?" if $type eq 'SRV';
1492 push @vallist, $rr->target;
1493 push @vallist, $rr->priority;
1494 push @vallist, $rr->weight;
1495 push @vallist, $rr->port;
1496 } elsif ($type eq 'KEY') {
1497 # we don't actually know what to do with these...
1498 push @vallist, ($rr->flags.":".$rr->protocol.":".$rr->algorithm.":".$rr->key.":".$rr->keytag.":".$rr->privatekeyname);
1499 } else {
1500 my $rrdata = $rr->rdatastr;
1501 if (length($rrdata) > 100 ) {
1502 # extralong records get an entry in a separate table.
1503 $dbh->do("INSERT INTO longrecs (recdata) VALUES (?)", undef, ($rrdata) );
1504 my ($longid) = $dbh->selectrow_array("SELECT longrec_id FROM longrecs WHERE recdata=?", undef, ($rrdata) );
1505 $sql .= ",longrec_id";
1506 $vallen .= ",?";
1507 push @vallist, '';
1508 push @vallist, $longid;
1509 } else {
1510 push @vallist, $rrdata;
1511 }
1512 # Finding a different record type is not fatal.... just problematic.
1513 # We may not be able to export it correctly.
1514 $warnmsg .= "Unusual record ".$rr->name." ($type) found\n";
1515 }
1516
1517# BIND supports:
1518# A CNAME HINFO MB(ex) MD(ob) MF(ob) MG(ex) MINFO(ex) MR(ex) MX NS NULL
1519# PTR SOA TXT WKS AFSDB(ex) ISDN(ex) RP(ex) RT(ex) X25(ex) PX
1520# ... if one can ever find the right magic to format them correctly
1521
1522# Net::DNS supports:
1523# RRSIG SIG NSAP NS NIMLOC NAPTR MX MR MINFO MG MB LOC ISDN IPSECKEY HINFO
1524# EID DNAME CNAME CERT APL AFSDB AAAA A DS NXT NSEC3PARAM NSEC3 NSEC KEY
1525# DNSKEY DLV X25 TXT TSIG TKEY SSHFP SRV SPF SOA RT RP PX PTR NULL APL::AplItem
1526
1527 $sth = $dbh->prepare($sql.") VALUES (".$vallen.")") or die "problem preparing record insert SQL\n";
1528 $sth->execute(@vallist) or die "failed to insert ".$rr->string.": ".$sth->errstr."\n";
1529
1530 $nrecs++;
1531
1532 } # while axfr_next
1533
1534 # Overwrite SOA record
1535 if ($rwsoa) {
1536 $soaflag = 1;
1537 my $sthgetsoa = $dbh->prepare("SELECT host,val,ttl FROM default_records WHERE group_id=? AND type=?");
1538 my $sthputsoa = $dbh->prepare("INSERT INTO records (domain_id,host,type,val,ttl) VALUES (?,?,?,?,?)");
1539 $sthgetsoa->execute($group,$reverse_typemap{SOA});
1540 while (my ($host,$val,$ttl) = $sthgetsoa->fetchrow_array()) {
1541 $host =~ s/DOMAIN/$domain/g;
1542 $val =~ s/DOMAIN/$domain/g;
1543 $sthputsoa->execute($dom_id,$host,$reverse_typemap{SOA},$val,$ttl);
1544 }
1545 }
1546
1547 # Overwrite NS records
1548 if ($rwns) {
1549 $nsflag = 1;
1550 my $sthgetns = $dbh->prepare("SELECT host,val,ttl FROM default_records WHERE group_id=? AND type=?");
1551 my $sthputns = $dbh->prepare("INSERT INTO records (domain_id,host,type,val,ttl) VALUES (?,?,?,?,?)");
1552 $sthgetns->execute($group,$reverse_typemap{NS});
1553 while (my ($host,$val,$ttl) = $sthgetns->fetchrow_array()) {
1554 $host =~ s/DOMAIN/$domain/g;
1555 $val =~ s/DOMAIN/$domain/g;
1556 $sthputns->execute($dom_id,$host,$reverse_typemap{NS},$val,$ttl);
1557 }
1558 }
1559
1560 die "No records found; either $ifrom is not authoritative or doesn't allow transfers\n" if !$nrecs;
1561 die "Bad zone: No SOA record!\n" if !$soaflag;
1562 die "Bad zone: No NS records!\n" if !$nsflag;
1563
1564 $dbh->commit;
1565
1566 };
1567
1568 if ($@) {
1569 my $msg = $@;
1570 eval { $dbh->rollback; };
1571 return ('FAIL',$msg." $warnmsg");
1572 } else {
1573 return ('WARN', $warnmsg) if $warnmsg;
1574 return ('OK',"Imported OK");
1575 }
1576
1577 # it should be impossible to get here.
1578 return ('WARN',"OOOK!");
1579} # end importAXFR()
1580
1581
1582## DNSDB::export()
1583# Export the DNS database, or a part of it
1584# Takes database handle, export type, optional arguments depending on type
1585# Writes zone data to targets as appropriate for type
1586sub export {
1587 my $dbh = shift;
1588 my $target = shift;
1589
1590 if ($target eq 'tiny') {
1591 __export_tiny($dbh,@_);
1592 }
1593# elsif ($target eq 'foo') {
1594# __export_foo($dbh,@_);
1595#}
1596# etc
1597
1598} # end export()
1599
1600
1601## DNSDB::__export_tiny
1602# Internal sub to implement tinyDNS (compatible) export
1603# Takes database handle, filehandle to write export to, optional argument(s)
1604# to determine which data gets exported
1605sub __export_tiny {
1606 my $dbh = shift;
1607 my $datafile = shift;
1608
1609##fixme: slurp up further options to specify particular zone(s) to export
1610
1611 ## Convert a bare number into an octal-coded pair of octets.
1612 # Take optional arg to indicate a decimal or hex input. Defaults to hex.
1613 sub octalize {
1614 my $tmp = shift;
1615 my $srctype = shift || 'h'; # default assumes hex string
1616 $tmp = sprintf "%0.4x", hex($tmp) if $srctype eq 'h'; # 0-pad hex to 4 digits
1617 $tmp = sprintf "%0.4x", $tmp if $srctype eq 'd'; # 0-pad decimal to 4 hex digits
1618 my @o = ($tmp =~ /^(..)(..)$/); # split into octets
1619 return sprintf "\\%0.3o\\%0.3o", hex($o[0]), hex($o[1]);;
1620 }
1621
1622##fixme: fail if $datafile isn't an open, writable file
1623
1624 # easy case - export all evarything
1625 # not-so-easy case - export item(s) specified
1626 # todo: figure out what kind of list we use to export items
1627
1628 my $domsth = $dbh->prepare("SELECT domain_id,domain,status FROM domains WHERE status=1");
1629 my $recsth = $dbh->prepare("SELECT r.host,r.type,r.val,r.distance,r.weight,r.port,r.ttl,l.recdata ".
1630 "FROM records r LEFT OUTER JOIN longrecs l ON r.longrec_id=l.longrec_id WHERE domain_id=?");
1631 $domsth->execute();
1632 while (my ($domid,$dom,$domstat) = $domsth->fetchrow_array) {
1633 $recsth->execute($domid);
1634 while (my ($host,$type,$val,$dist,$weight,$port,$ttl,$lval) = $recsth->fetchrow_array) {
1635##fixme: need to store location in the db, and retrieve it here.
1636# temporarily hardcoded to empty so we can include it further down.
1637my $loc = '';
1638
1639##fixme: record validity timestamp. tinydns supports fiddling with timestamps.
1640# note $ttl must be set to 0 if we want to use tinydns's auto-expiring timestamps.
1641# timestamps are TAI64
1642# ~~ 2^62 + time()
1643my $stamp = '';
1644
1645 $val = $lval if $lval;
1646
1647# raw packet in unknown format: first byte indicates length
1648# of remaining data, allows up to 255 raw bytes
1649
1650##fixme? append . to all host/val hostnames
1651 if ($typemap{$type} eq 'SOA') {
1652
1653 # host contains pri-ns:responsible
1654 # val is abused to contain refresh:retry:expire:minttl
1655##fixme: "manual" serial vs tinydns-autoserial
1656 print $datafile "Z$host"."::$val:$ttl:$stamp:$loc\n";
1657
1658 } elsif ($typemap{$type} eq 'A') {
1659
1660 print $datafile "+$host:$val:$ttl:$stamp:$loc\n";
1661
1662 } elsif ($typemap{$type} eq 'NS') {
1663
1664 print $datafile "\&$host"."::$val:$ttl:$stamp:$loc\n";
1665
1666 } elsif ($typemap{$type} eq 'AAAA') {
1667
1668 print $datafile ":$host:28:";
1669 my $altgrp = 0;
1670 my @altconv;
1671 # Split in to up to 8 groups of hex digits (allows for IPv6 :: 0-collapsing)
1672 foreach (split /:/, $val) {
1673 if (/^$/) {
1674 # flag blank entry; this is a series of 0's of (currently) unknown length
1675 $altconv[$altgrp++] = 's';
1676 } else {
1677 # call sub to convert 1-4 hex digits to 2 string-rep octal bytes
1678 $altconv[$altgrp++] = octalize($_)
1679 }
1680 }
1681 foreach my $octet (@altconv) {
1682 # if not 's', output
1683 print $datafile $octet unless $octet =~ /^s$/;
1684 # if 's', output (9-array length)x literal '\000\000'
1685 print $datafile '\000\000'x(9-$altgrp) if $octet =~ /^s$/;
1686 }
1687 print $datafile ":$ttl:$stamp:$loc\n";
1688
1689 } elsif ($typemap{$type} eq 'MX') {
1690
1691 print $datafile "\@$host"."::$val:$dist:$ttl:$stamp:$loc\n";
1692
1693 } elsif ($typemap{$type} eq 'TXT') {
1694
1695##fixme: split v-e-r-y long TXT strings? will need to do so for BIND export, at least
1696 $val =~ s/:/\\072/g; # may need to replace other symbols
1697 print $datafile "'$host:$val:$ttl:$stamp:$loc\n";
1698
1699# by-hand TXT
1700#:deepnet.cx:16:2v\075spf1\040a\040a\072bacon.deepnet.cx\040a\072home.deepnet.cx\040-all:3600
1701#@ IN TXT "v=spf1 a a:bacon.deepnet.cx a:home.deepnet.cx -all"
1702#'deepnet.cx:v=spf1 a a\072bacon.deepnet.cx a\072home.deepnet.cx -all:3600
1703
1704#txttest IN TXT "v=foo bar:bob kn;ob' \" !@#$%^&*()-=_+[]{}<>?"
1705#:txttest.deepnet.cx:16:\054v\075foo\040bar\072bob\040kn\073ob\047\040\042\040\041\100\043\044\045\136\046\052\050\051-\075\137\053\133\135\173\175\074\076\077:3600
1706
1707# very long TXT record as brought in by axfr-get
1708# note tinydns does not support >512-byte RR data, need axfr-dns (for TCP support) for that
1709# also note, tinydns does not seem to support <512, >256-byte RRdata from axfr-get either. :/
1710#:longtxt.deepnet.cx:16:
1711#\170this is a very long txt record. it is really long. long. very long. really very long. this is a very long txt record.
1712#\263 it is really long. long. very long. really very long. this is a very long txt record. it is really long. long. very long. really very long. this is a very long txt record.
1713#\351 it is really long. long. very long. really very long.this is a very long txt record. it is really long. long. very long. really very long. this is a very long txt record. it is really long. long. very long. really very long.
1714#:3600
1715
1716 } elsif ($typemap{$type} eq 'CNAME') {
1717
1718 print $datafile "C$host:$val:$ttl:$stamp:$loc\n";
1719
1720 } elsif ($typemap{$type} eq 'SRV') {
1721
1722 # data is two-byte values for priority, weight, port, in that order,
1723 # followed by length/string data
1724
1725 print $datafile ":$host:33:".octalize($dist,'d').octalize($weight,'d').octalize($port,'d');
1726
1727 $val .= '.' if $val !~ /\.$/;
1728 foreach (split /\./, $val) {
1729 printf $datafile "\\%0.3o%s", length($_), $_;
1730 }
1731 print $datafile "\\000:$ttl:$stamp:$loc\n";
1732
1733 } elsif ($typemap{$type} eq 'RP') {
1734
1735 # RP consists of two mostly free-form strings.
1736 # The first is supposed to be an email address with @ replaced by . (as with the SOA contact)
1737 # The second is the "hostname" of a TXT record with more info.
1738 print $datafile ":$host:17:";
1739 my ($who,$what) = split /\s/, $val;
1740 foreach (split /\./, $who) {
1741 printf $datafile "\\%0.3o%s", length($_), $_;
1742 }
1743 print $datafile '\000';
1744 foreach (split /\./, $what) {
1745 printf $datafile "\\%0.3o%s", length($_), $_;
1746 }
1747 print $datafile "\\000:$ttl:$stamp:$loc\n";
1748
1749 } elsif ($typemap{$type} eq 'PTR') {
1750
1751 # must handle both IPv4 and IPv6
1752##work
1753 # data should already be in suitable reverse order.
1754 print $datafile "^$host:$val:$ttl:$stamp:$loc\n";
1755
1756 } else {
1757 # raw record. we don't know what's in here, so we ASS-U-ME the user has
1758 # put it in correctly, since either the user is messing directly with the
1759 # database, or the record was imported via AXFR
1760 # <split by char>
1761 # convert anything not a-zA-Z0-9.- to octal coding
1762
1763##fixme: add flag to export "unknown" record types - note we'll probably end up
1764# mangling them since they were written to the DB from Net::DNS::RR::<type>->rdatastr.
1765 #print $datafile ":$host:$type:$val:$ttl:$stamp:$loc\n";
1766
1767 } # record type if-else
1768
1769 } # while ($recsth)
1770 } # while ($domsth)
1771} # end __export_tiny()
1772
1773
1774# shut Perl up
17751;
Note: See TracBrowser for help on using the repository browser.