source: trunk/DNSDB.pm@ 90

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

/trunk

Checkpoint

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