source: trunk/DNSDB.pm@ 99

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

/trunk

Remove a few stale ##fixme notes
Minor formatting nitpick cleanup
Use "SELECT currval..." when adding a user to get the new user ID
Remove stale stub editRecord() since it's been superceded by updateRec()

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