source: trunk/DNSDB.pm@ 91

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

/trunk

SQL tabledef update:

  • Tweak log table definition to cope with looooong entries (mainly from AXFR warnings)

DNSDB.pm:

  • Add domainID and getRecCount subs in DNSDB
  • Return more user-friendly error on attempting to add a domain with no name
  • Nitpick-tweak DB calls and SQL formatting in domainName()
  • Replace placeholderish OK message in importAXFR()

dns.cgi:

  • Trim some more direct SQL out in reclist
  • Uninitialized-variable cleanup in AXFR import
  • Add logging to AXFR import
  • Don't complain about uninitialized variables in record-display
  • Property svn:keywords set to Date Rev Author Id
File size: 46.9 KB
Line 
1# dns/trunk/DNSDB.pm
2# Abstraction functions for DNS administration
3###
4# SVN revision info
5# $Date: 2011-04-13 20:00:10 +0000 (Wed, 13 Apr 2011) $
6# SVN revision $Rev: 91 $
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.
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',"Domain must not be blank") if !$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 ($domname) = $dbh->selectrow_array("SELECT domain FROM domains WHERE domain_id=?", undef, ($domid) );
473 $errstr = $DBI::errstr if !$domname;
474 return $domname if $domname;
475} # end domainName()
476
477
478## DNSDB::domainID()
479# Takes a database handle and domain name
480# Returns the domain ID number
481sub domainID {
482 $errstr = '';
483 my $dbh = shift;
484 my $domain = shift;
485 my ($domid) = $dbh->selectrow_array("SELECT domain_id FROM domains WHERE domain=?", undef, ($domain) );
486 $errstr = $DBI::errstr if !$domid;
487 return $domid if $domid;
488} # end domainID()
489
490
491## DNSDB::addGroup()
492# Add a group
493# Takes a database handle, group name, parent group, hashref for permissions,
494# and optional template-vs-cloneme flag
495# Returns a status code and message
496sub addGroup {
497 $errstr = '';
498 my $dbh = shift;
499 my $groupname = shift;
500 my $pargroup = shift;
501 my $permissions = shift;
502
503 # 0 indicates "custom", hardcoded.
504 # Any other value clones that group's default records, if it exists.
505 my $inherit = shift || 0;
506##fixme: need a flag to indicate clone records or <?> ?
507
508 # Allow transactions, and raise an exception on errors so we can catch it later.
509 # Use local to make sure these get "reset" properly on exiting this block
510 local $dbh->{AutoCommit} = 0;
511 local $dbh->{RaiseError} = 1;
512
513 my $sth = $dbh->prepare("SELECT group_id FROM groups WHERE group_name=?");
514 my $group_id;
515
516# quick check to start to see if we've already got one
517 $sth->execute($groupname);
518 ($group_id) = $sth->fetchrow_array;
519
520 return ('FAIL', "Group already exists") if $group_id;
521
522 # Wrap all the SQL in a transaction
523 eval {
524 $sth = $dbh->prepare("INSERT INTO groups (parent_group_id,group_name) VALUES (?,?)");
525 $sth->execute($pargroup,$groupname);
526
527 $sth = $dbh->prepare("SELECT group_id FROM groups WHERE group_name=?");
528 $sth->execute($groupname);
529 my ($groupid) = $sth->fetchrow_array();
530
531# Permissions
532 if ($inherit) {
533 } else {
534 my @permvals;
535 foreach (@permtypes) {
536 if (!defined ($permissions->{$_})) {
537 push @permvals, 0;
538 } else {
539 push @permvals, $permissions->{$_};
540 }
541 }
542
543 $sth = $dbh->prepare("INSERT INTO permissions (group_id,$permlist) values (?".',?'x($#permtypes+1).")");
544 $sth->execute($groupid,@permvals);
545
546 $sth = $dbh->prepare("SELECT permission_id FROM permissions WHERE group_id=?");
547 $sth->execute($groupid);
548 my ($permid) = $sth->fetchrow_array();
549
550 $dbh->do("UPDATE groups SET permission_id=$permid WHERE group_id=$groupid");
551 } # done permission fiddling
552
553# Default records
554 $sth = $dbh->prepare("INSERT INTO default_records (group_id,host,type,val,distance,weight,port,ttl) ".
555 "VALUES ($groupid,?,?,?,?,?,?,?)");
556 if ($inherit) {
557 # Duplicate records from parent. Actually relying on inherited records feels
558 # very fragile, and it would be problematic to roll over at a later time.
559 my $sth2 = $dbh->prepare("SELECT host,type,val,distance,weight,port,ttl FROM default_records WHERE group_id=?");
560 $sth2->execute($pargroup);
561 while (my @clonedata = $sth2->fetchrow_array) {
562 $sth->execute(@clonedata);
563 }
564 } else {
565##fixme: Hardcoding is Bad, mmmmkaaaay?
566 # reasonable basic defaults for SOA, MX, NS, and minimal hosting
567 # could load from a config file, but somewhere along the line we need hardcoded bits.
568 $sth->execute('ns1.example.com:hostmaster.example.com', 6, '10800:3600:604800:10800', 0, 0, 0, 86400);
569 $sth->execute('DOMAIN', 1, '192.168.4.2', 0, 0, 0, 7200);
570 $sth->execute('DOMAIN', 15, 'mx.example.com', 10, 0, 0, 7200);
571 $sth->execute('DOMAIN', 2, 'ns1.example.com', 0, 0, 0, 7200);
572 $sth->execute('DOMAIN', 2, 'ns2.example.com', 0, 0, 0, 7200);
573 $sth->execute('www.DOMAIN', 5, 'DOMAIN', 0, 0, 0, 7200);
574 }
575
576 # once we get here, we should have suceeded.
577 $dbh->commit;
578 }; # end eval
579
580 if ($@) {
581 my $msg = $@;
582 eval { $dbh->rollback; };
583 return ('FAIL',$msg);
584 } else {
585 return ('OK','OK');
586 }
587
588} # end addGroup()
589
590
591## DNSDB::delGroup()
592# Delete a group.
593# Takes a group ID
594# Returns a status code and message
595sub delGroup {
596 my $dbh = shift;
597 my $groupid = shift;
598
599 # Allow transactions, and raise an exception on errors so we can catch it later.
600 # Use local to make sure these get "reset" properly on exiting this block
601 local $dbh->{AutoCommit} = 0;
602 local $dbh->{RaiseError} = 1;
603
604##fixme: locate "knowable" error conditions and deal with them before the eval
605# ... or inside, whatever.
606# -> domains still exist in group
607# -> ...
608 my $failmsg = '';
609
610 # Wrap all the SQL in a transaction
611 eval {
612 my $sth = $dbh->prepare("SELECT count(*) FROM domains WHERE group_id=?");
613 $sth->execute($groupid);
614 my ($domcnt) = $sth->fetchrow_array;
615 $failmsg = "Can't remove group ".groupName($dbh,$groupid);
616 die "$domcnt domains still in group\n" if $domcnt;
617
618 $sth = $dbh->prepare("delete from default_records where group_id=?");
619 $failmsg = "Failed to delete default records for ".groupName($dbh,$groupid);
620 $sth->execute($groupid);
621 $sth = $dbh->prepare("delete from groups where group_id=?");
622 $failmsg = "Failed to remove group ".groupName($dbh,$groupid);
623 $sth->execute($groupid);
624
625 # once we get here, we should have suceeded.
626 $dbh->commit;
627 }; # end eval
628
629 if ($@) {
630 my $msg = $@;
631 eval { $dbh->rollback; };
632 return ('FAIL',"$failmsg: $msg");
633 } else {
634 return ('OK','OK');
635 }
636} # end delGroup()
637
638
639## DNSDB::getChildren()
640# Get a list of all groups whose parent^n is group <n>
641# Takes a database handle, group ID, reference to an array to put the group IDs in,
642# and an optional flag to return only immediate children or all children-of-children
643# default to returning all children
644# Calls itself
645sub getChildren {
646 $errstr = '';
647 my $dbh = shift;
648 my $rootgroup = shift;
649 my $groupdest = shift;
650 my $immed = shift || 'all';
651
652 # special break for default group; otherwise we get stuck.
653 if ($rootgroup == 1) {
654 # by definition, group 1 is the Root Of All Groups
655 my $sth = $dbh->prepare("SELECT group_id FROM groups WHERE NOT (group_id=1)".
656 ($immed ne 'all' ? " AND parent_group_id=1" : ''));
657 $sth->execute;
658 while (my @this = $sth->fetchrow_array) {
659 push @$groupdest, @this;
660 }
661 } else {
662 my $sth = $dbh->prepare("SELECT group_id FROM groups WHERE parent_group_id=?");
663 $sth->execute($rootgroup);
664 return if $sth->rows == 0;
665 my @grouplist;
666 while (my ($group) = $sth->fetchrow_array) {
667 push @$groupdest, $group;
668 getChildren($dbh,$group,$groupdest) if $immed eq 'all';
669 }
670 }
671} # end getChildren()
672
673
674## DNSDB::groupName()
675# Return the group name based on a group ID
676# Takes a database handle and the group ID
677# Returns the group name or undef on failure
678sub groupName {
679 $errstr = '';
680 my $dbh = shift;
681 my $groupid = shift;
682 my $sth = $dbh->prepare("SELECT group_name FROM groups WHERE group_id=?");
683 $sth->execute($groupid);
684 my ($groupname) = $sth->fetchrow_array();
685 $errstr = $DBI::errstr if !$groupname;
686 return $groupname if $groupname;
687} # end groupName
688
689
690## DNSDB::addUser()
691# Add a user.
692# Takes a DB handle, username, group ID, password, state (active/inactive).
693# Optionally accepts:
694# user type (user/admin) - defaults to user
695# permissions string - defaults to inherit from group
696# three valid forms:
697# i - Inherit permissions
698# c:<user_id> - Clone permissions from <user_id>
699# C:<permission list> - Set these specific permissions
700# first name - defaults to username
701# last name - defaults to blank
702# phone - defaults to blank (could put other data within column def)
703# Returns (OK,<uid>) on success, (FAIL,<message>) on failure
704sub addUser {
705 $errstr = '';
706 my $dbh = shift;
707 my $username = shift;
708 my $group = shift;
709 my $pass = shift;
710 my $state = shift;
711
712 return ('FAIL', "Missing one or more required entries") if !defined($state);
713 return ('FAIL', "Username must not be blank") if !$username;
714
715 my $type = shift || 'u'; # create limited users by default - fwiw, not sure yet how this will interact with ACLs
716
717 my $permstring = shift || 'i'; # default is to inhert permissions from group
718
719 my $fname = shift || $username;
720 my $lname = shift || '';
721 my $phone = shift || ''; # not going format-check
722
723 my $sth = $dbh->prepare("SELECT user_id FROM users WHERE username=?");
724 my $user_id;
725
726# quick check to start to see if we've already got one
727 $sth->execute($username);
728 ($user_id) = $sth->fetchrow_array;
729
730 return ('FAIL', "User already exists") if $user_id;
731
732 # Allow transactions, and raise an exception on errors so we can catch it later.
733 # Use local to make sure these get "reset" properly on exiting this block
734 local $dbh->{AutoCommit} = 0;
735 local $dbh->{RaiseError} = 1;
736
737my $failmsg;
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 $sth = $dbh->prepare("select user_id from users where username=?");
749 $sth->execute($username);
750 ($user_id) = $sth->fetchrow_array();
751
752# Permissions! Gotta set'em all!
753 die "Invalid permission string $permstring"
754 if $permstring !~ /^(?:
755 i # inherit
756 |c:\d+ # clone
757 # custom. no, the leading , is not a typo
758 |C:(?:,(?:group|user|domain|record|self)_(?:edit|create|delete))+
759 )$/x;
760# bleh. I'd call another function to do my dirty work, but we're in the middle of a transaction already.
761 if ($permstring ne 'i') {
762 # for cloned or custom permissions, we have to create a new permissions entry.
763 my $clonesrc = $group;
764 if ($permstring =~ /^c:(\d+)/) { $clonesrc = $1; }
765 $dbh->do("INSERT INTO permissions ($permlist,user_id) ".
766 "SELECT $permlist,? FROM permissions WHERE permission_id=".
767 "(SELECT permission_id FROM permissions WHERE ".($permstring =~ /^c:/ ? 'user' : 'group')."_id=?)",
768 undef, ($user_id,$clonesrc) );
769 $dbh->do("UPDATE users SET permission_id=".
770 "(SELECT permission_id FROM permissions WHERE user_id=?) ".
771 "WHERE user_id=?", undef, ($user_id, $user_id) );
772 }
773 if ($permstring =~ /^C:/) {
774 # finally for custom permissions, we set the passed-in permissions (and unset
775 # any that might have been brought in by the clone operation above)
776 my ($permid) = $dbh->selectrow_array("SELECT permission_id FROM permissions WHERE user_id=?",
777 undef, ($user_id) );
778 foreach (@permtypes) {
779 if ($permstring =~ /,$_/) {
780 $dbh->do("UPDATE permissions SET $_='t' WHERE permission_id=?", undef, ($permid) );
781 } else {
782 $dbh->do("UPDATE permissions SET $_='f' WHERE permission_id=?", undef, ($permid) );
783 }
784 }
785 }
786
787 $dbh->do("UPDATE users SET inherit_perm='n' WHERE user_id=?", undef, ($user_id) );
788
789##fixme: add another table to hold name/email for log table?
790#die "dying horribly ($permstring, $user_id)";
791
792 # once we get here, we should have suceeded.
793 $dbh->commit;
794 }; # end eval
795
796 if ($@) {
797 my $msg = $@;
798 eval { $dbh->rollback; };
799 return ('FAIL',$msg." $failmsg");
800 } else {
801 return ('OK',$user_id);
802 }
803} # end addUser
804
805
806## DNSDB::checkUser()
807# Check user/pass combo on login
808sub checkUser {
809 my $dbh = shift;
810 my $user = shift;
811 my $inpass = shift;
812
813 my $sth = $dbh->prepare("SELECT user_id,group_id,password,firstname,lastname FROM users WHERE username=?");
814 $sth->execute($user);
815 my ($uid,$gid,$pass,$fname,$lname) = $sth->fetchrow_array;
816 my $loginfailed = 1 if !defined($uid);
817
818 if ($pass =~ m|^\$1\$([A-Za-z0-9/.]+)\$|) {
819 $loginfailed = 1 if $pass ne unix_md5_crypt($inpass,$1);
820 } else {
821 $loginfailed = 1 if $pass ne $inpass;
822 }
823
824 # nnnngggg
825 return ($uid, $gid);
826} # end checkUser
827
828
829## DNSDB:: updateUser()
830# Update general data about user
831sub updateUser {
832 my $dbh = shift;
833 my $uid = shift;
834 my $username = shift;
835 my $group = shift;
836 my $pass = shift;
837 my $state = shift;
838 my $type = shift || 'u';
839 my $fname = shift || $username;
840 my $lname = shift || '';
841 my $phone = shift || ''; # not going format-check
842
843 my $failmsg = '';
844
845 # Allow transactions, and raise an exception on errors so we can catch it later.
846 # Use local to make sure these get "reset" properly on exiting this block
847 local $dbh->{AutoCommit} = 0;
848 local $dbh->{RaiseError} = 1;
849
850 my $sth;
851
852 # Password can be left blank; if so we assume there's one on file.
853 # Actual blank passwords are bad, mm'kay?
854 if (!$pass) {
855 $sth = $dbh->prepare("SELECT password FROM users WHERE user_id=?");
856 $sth->execute($uid);
857 ($pass) = $sth->fetchrow_array;
858 } else {
859 $pass = unix_md5_crypt($pass);
860 }
861
862 eval {
863 my $sth = $dbh->prepare(q(
864 UPDATE users
865 SET username=?, password=?, firstname=?, lastname=?, phone=?, type=?, status=?
866 WHERE user_id=?
867 )
868 );
869 $sth->execute($username, $pass, $fname, $lname, $phone, $type, $state, $uid);
870 $dbh->commit;
871 };
872 if ($@) {
873 my $msg = $@;
874 eval { $dbh->rollback; };
875 return ('FAIL',"$failmsg: $msg");
876 } else {
877 return ('OK','OK');
878 }
879} # end updateUser()
880
881
882## DNSDB::delUser()
883#
884sub delUser {
885 my $dbh = shift;
886 return ('FAIL',"Need database handle") if !$dbh;
887 my $userid = shift;
888 return ('FAIL',"Missing userid") if !defined($userid);
889
890 my $sth = $dbh->prepare("delete from users where user_id=?");
891 $sth->execute($userid);
892
893 return ('FAIL',"Couldn't remove user: ".$sth->errstr) if $sth->err;
894
895 return ('OK','OK');
896
897} # end delUser
898
899
900## DNSDB::userFullName()
901# Return a pretty string!
902# Takes a user_id and optional printf-ish string to indicate which pieces where:
903# %u for the username
904# %f for the first name
905# %l for the last name
906# All other text in the passed string will be left as-is.
907##fixme: need a "smart" option too, so that missing/null/blank first/last names don't give funky output
908sub userFullName {
909 $errstr = '';
910 my $dbh = shift;
911 my $userid = shift;
912 my $fullformat = shift || '%f %l (%u)';
913 my $sth = $dbh->prepare("select username,firstname,lastname from users where user_id=?");
914 $sth->execute($userid);
915 my ($uname,$fname,$lname) = $sth->fetchrow_array();
916 $errstr = $DBI::errstr if !$uname;
917
918 $fullformat =~ s/\%u/$uname/g;
919 $fullformat =~ s/\%f/$fname/g;
920 $fullformat =~ s/\%l/$lname/g;
921
922 return $fullformat;
923} # end userFullName
924
925
926## DNSDB::userStatus()
927# Sets and/or returns a user's status
928# Takes a database handle, user ID and optionally a status argument
929# Returns undef on errors.
930sub userStatus {
931 my $dbh = shift;
932 my $id = shift;
933 my $newstatus = shift;
934
935 return undef if $id !~ /^\d+$/;
936
937 my $sth;
938
939# ooo, fun! let's see what we were passed for status
940 if ($newstatus) {
941 $sth = $dbh->prepare("update users set status=? where user_id=?");
942 # ass-u-me caller knows what's going on in full
943 if ($newstatus =~ /^[01]$/) { # only two valid for now.
944 $sth->execute($newstatus,$id);
945 } elsif ($newstatus =~ /^usero(?:n|ff)$/) {
946 $sth->execute(($newstatus eq 'useron' ? 1 : 0),$id);
947 }
948 }
949
950 $sth = $dbh->prepare("select status from users where user_id=?");
951 $sth->execute($id);
952 my ($status) = $sth->fetchrow_array;
953 return $status;
954} # end userStatus()
955
956
957## DNSDB::getUserData()
958# Get misc user data for display
959sub getUserData {
960 my $dbh = shift;
961 my $uid = shift;
962
963 my $sth = $dbh->prepare("SELECT group_id,username,firstname,lastname,phone,type,status,inherit_perm ".
964 "FROM users WHERE user_id=?");
965 $sth->execute($uid);
966 return $sth->fetchrow_hashref();
967
968} # end getUserData()
969
970
971## DNSDB::editRecord()
972# Change an existing record
973# Takes a database handle, default/live flag, record ID, and new data and updates the data fields for it
974sub editRecord {
975 $errstr = '';
976 my $dbh = shift;
977 my $defflag = shift;
978 my $recid = shift;
979 my $host = shift;
980 my $address = shift;
981 my $distance = shift;
982 my $weight = shift;
983 my $port = shift;
984 my $ttl = shift;
985}
986
987
988## DNSDB::getSOA()
989# Return all suitable fields from an SOA record in separate elements of a hash
990# Takes a database handle, default/live flag, and group (default) or domain (live) ID
991sub getSOA {
992 $errstr = '';
993 my $dbh = shift;
994 my $def = shift;
995 my $id = shift;
996 my %ret;
997
998 my $sql = "select record_id,host,val,ttl from";
999 if ($def eq 'def' or $def eq 'y') {
1000 $sql .= " default_records where group_id=$id and type=$reverse_typemap{SOA}";
1001 } else {
1002 # we're editing a live SOA record; find based on domain
1003 $sql .= " records where domain_id=$id and type=$reverse_typemap{SOA}";
1004 }
1005 my $sth = $dbh->prepare($sql);
1006 $sth->execute;
1007
1008 my ($recid,$host,$val,$ttl) = $sth->fetchrow_array();
1009 my ($prins,$contact) = split /:/, $host;
1010 my ($refresh,$retry,$expire,$minttl) = split /:/, $val;
1011
1012 $ret{recid} = $recid;
1013 $ret{ttl} = $ttl;
1014 $ret{prins} = $prins;
1015 $ret{contact} = $contact;
1016 $ret{refresh} = $refresh;
1017 $ret{retry} = $retry;
1018 $ret{expire} = $expire;
1019 $ret{minttl} = $minttl;
1020
1021 return %ret;
1022} # end getSOA()
1023
1024
1025## DNSDB::getRecLine()
1026# Return all data fields for a zone record in separate elements of a hash
1027# Takes a database handle, default/live flag, and record ID
1028sub getRecLine {
1029 $errstr = '';
1030 my $dbh = shift;
1031 my $def = shift;
1032 my $id = shift;
1033
1034 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".
1035 (($def eq 'def' or $def eq 'y') ? ',r.group_id FROM default_' : ',r.domain_id FROM ').
1036 "records r LEFT OUTER JOIN longrecs l ON r.longrec_id=l.longrec_id WHERE record_id=?";
1037 my $ret = $dbh->selectrow_hashref($sql, undef, ($id) ) or warn $dbh->errstr;
1038
1039 if ($dbh->err) {
1040 $errstr = $DBI::errstr;
1041 return undef;
1042 }
1043
1044 $ret->{val} = $ret->{recdata} if $ret->{longrec_id}; # put the long data in the real value space
1045 delete $ret->{longrec_id}; # remove these since they shouldn't be exposed - the caller
1046 delete $ret->{recdata}; # should not care about "long records" vs normal ones.
1047
1048 return $ret;
1049}
1050
1051
1052##fixme: should use above (getRecLine()) to get lines for below?
1053## DNSDB::getDomRecs()
1054# Return records for a domain
1055# Takes a database handle, default/live flag, group/domain ID, start,
1056# number of records, sort field, and sort order
1057# Returns a reference to an array of hashes
1058sub getDomRecs {
1059 $errstr = '';
1060 my $dbh = shift;
1061 my $type = shift;
1062 my $id = shift;
1063 my $nrecs = shift || 'all';
1064 my $nstart = shift || 0;
1065
1066## for order, need to map input to column names
1067 my $order = shift || 'host';
1068 my $direction = shift || 'ASC';
1069
1070 $type = 'y' if $type eq 'def';
1071
1072 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 ";
1073 $sql .= "default_" if $type eq 'y';
1074 $sql .= "records r ";
1075 $sql .= "LEFT OUTER JOIN longrecs l ON r.longrec_id=l.longrec_id ";
1076 if ($type eq 'y') {
1077 $sql .= "WHERE r.group_id=?";
1078 } else {
1079 $sql .= "WHERE r.domain_id=?";
1080 }
1081 $sql .= " AND NOT r.type=$reverse_typemap{SOA} ORDER BY r.$order $direction";
1082##fixme: need to set nstart properly (offset is not internally multiplied with limit)
1083 $sql .= " LIMIT $nrecs OFFSET ".($nstart*$nrecs) if $nstart ne 'all';
1084
1085 my $sth = $dbh->prepare($sql) or warn $dbh->errstr;
1086 $sth->execute($id) or warn "$sql: ".$sth->errstr;
1087
1088 my @retbase;
1089 while (my $ref = $sth->fetchrow_hashref()) {
1090 $ref->{val} = $ref->{recdata} if $ref->{longrec_id}; # put the long data in the real value space
1091 delete $ref->{longrec_id}; # remove these since they shouldn't be exposed - the caller
1092 delete $ref->{recdata}; # should not care about "long records" vs normal ones.
1093 push @retbase, $ref;
1094 }
1095
1096 my $ret = \@retbase;
1097 return $ret;
1098} # end getDomRecs()
1099
1100
1101## DNSDB::getRecCount()
1102# Return count of non-SOA records in domain (or default records in a group)
1103# Takes a database handle, default/live flag and group/domain ID
1104# Returns the count
1105sub getRecCount {
1106 my $dbh = shift;
1107 my $defrec = shift;
1108 my $id = shift;
1109
1110 my ($count) = $dbh->selectrow_array("SELECT count(*) FROM ".
1111 ($defrec eq 'y' ? 'default_' : '')."records ".
1112 "WHERE ".($defrec eq 'y' ? 'group' : 'domain')."_id=? ".
1113 "AND NOT type=$reverse_typemap{SOA}", undef, ($id) );
1114
1115 return $count;
1116
1117} # end getRecCount()
1118
1119
1120## DNSDB::addRec()
1121# Add a new record to a domain or a group's default records
1122# Takes a database handle, default/live flag, group/domain ID,
1123# host, type, value, and TTL
1124# Some types require additional detail: "distance" for MX and SRV,
1125# and weight/port for SRV
1126# Returns a status code and detail message in case of error
1127sub addRec {
1128 $errstr = '';
1129 my $dbh = shift;
1130 my $defrec = shift;
1131 my $id = shift;
1132
1133 my $host = shift;
1134 my $rectype = shift;
1135 my $val = shift;
1136 my $ttl = shift;
1137
1138 my $fields = ($defrec eq 'y' ? 'group_id' : 'domain_id').",host,type,val,ttl";
1139 my $vallen = "?,?,?,?,?";
1140 my @vallist = ($id,$host,$rectype,$val,$ttl);
1141
1142 my $dist;
1143 if ($rectype == $reverse_typemap{MX} or $rectype == $reverse_typemap{SRV}) {
1144 $dist = shift;
1145 return ('FAIL',"Need distance for $typemap{$rectype} record") if !defined($dist);
1146 $fields .= ",distance";
1147 $vallen .= ",?";
1148 push @vallist, $dist;
1149 }
1150 my $weight;
1151 my $port;
1152 if ($rectype == $reverse_typemap{SRV}) {
1153 # check for _service._protocol. NB: RFC2782 does not say "MUST"... nor "SHOULD"...
1154 # it just says (paraphrased) "... is prepended with _ to prevent DNS collisions"
1155 return ('FAIL',"SRV records must begin with _service._protocol")
1156 if $host !~ /^_[A-Za-z]+\._[A-Za-z]+\.[a-z0-9-]+/;
1157 $weight = shift;
1158 $port = shift;
1159 return ('FAIL',"Need weight and port for SRV record") if !defined($weight) or !defined($port);
1160 $fields .= ",weight,port";
1161 $vallen .= ",?,?";
1162 push @vallist, ($weight,$port);
1163 }
1164
1165 # Allow transactions, and raise an exception on errors so we can catch it later.
1166 # Use local to make sure these get "reset" properly on exiting this block
1167 local $dbh->{AutoCommit} = 0;
1168 local $dbh->{RaiseError} = 1;
1169
1170 eval {
1171 if (length($val) > 100 ) {
1172 # extralong records get an entry in a separate table.
1173 $dbh->do("INSERT INTO longrecs (recdata) VALUES (?)", undef, ($val) );
1174 my ($longid) = $dbh->selectrow_array("SELECT longrec_id FROM longrecs WHERE recdata=?", undef, ($val) );
1175 $fields .= ",longrec_id";
1176 $vallen .= ",?";
1177 push @vallist, $longid;
1178 $vallist[3] = ''; # so we don't barf when we insert the main record
1179 }
1180 $dbh->do("INSERT INTO ".($defrec eq 'y' ? 'default_' : '')."records ($fields) VALUES ($vallen)",
1181 undef, @vallist);
1182 $dbh->commit;
1183 };
1184 if ($@) {
1185 my $msg = $@;
1186 eval { $dbh->rollback; };
1187 return ('FAIL',$msg);
1188 }
1189
1190 return ('OK','OK');
1191
1192} # end addRec()
1193
1194
1195## DNSDB::updateRec()
1196# Update a record
1197sub updateRec {
1198 $errstr = '';
1199
1200 my $dbh = shift;
1201 my $defrec = shift;
1202 my $id = shift;
1203
1204# all records have these
1205 my $host = shift;
1206 my $type = shift;
1207 my $val = shift;
1208 my $ttl = shift;
1209
1210 return('FAIL',"Missing standard argument(s)") if !defined($ttl);
1211
1212# only MX and SRV will use these
1213 my $dist = 0;
1214 my $weight = 0;
1215 my $port = 0;
1216
1217 if ($type == $reverse_typemap{MX} || $type == $reverse_typemap{SRV}) {
1218 $dist = shift;
1219 return ('FAIL',"MX or SRV requires distance") if !defined($dist);
1220 if ($type == $reverse_typemap{SRV}) {
1221 $weight = shift;
1222 return ('FAIL',"SRV requires weight") if !defined($weight);
1223 $port = shift;
1224 return ('FAIL',"SRV requires port") if !defined($port);
1225 }
1226 }
1227
1228# 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 ";
1229# $sql .= "default_" if $type eq 'y';
1230# $sql .= "records r ";
1231# $sql .= "LEFT OUTER JOIN longrecs l ON r.longrec_id=l.longrec_id ";
1232
1233 # get the long record ID, if any
1234 my ($longid) = $dbh->selectrow_array("SELECT longrec_id FROM ".($defrec eq 'y' ? 'default_' : '')."records ".
1235 "WHERE record_id=?", undef, ($id) );
1236
1237 local $dbh->{AutoCommit} = 0;
1238 local $dbh->{RaiseError} = 1;
1239
1240 eval {
1241 # there's really no tidy way to squash this down. :/
1242 if (length($val) > 100) {
1243 if ($longid) {
1244 $dbh->do("UPDATE longrecs SET recdata=? WHERE longrec_id=?", undef, ($val, $longid) );
1245 } else {
1246##fixme: has to be a better way to be sure we get the right recid back once inserted...
1247 $dbh->do("INSERT INTO longrecs (recdata) VALUES (?)", undef, ($val) );
1248 my ($newlongid) = $dbh->selectrow_array("SELECT currval('longrecs_longrec_id_seq')");
1249 $dbh->do("UPDATE ".($defrec eq 'y' ? 'default_' : '')."records SET val=?,longrec_id=? ".
1250 "WHERE record_id=?", undef, ('', $newlongid, $id) );
1251 }
1252 } else {
1253 if ($longid) {
1254 $dbh->do("DELETE FROM longrecs WHERE longrec_id=?", undef, ($longid) );
1255 $dbh->do("UPDATE ".($defrec eq 'y' ? 'default_' : '')."records SET val=?,longrec_id=NULL ".
1256 "WHERE record_id=?", undef, ($val, $id) );
1257 } else {
1258 $dbh->do("UPDATE ".($defrec eq 'y' ? 'default_' : '')."records SET val=? ".
1259 "WHERE record_id=?", undef, ($val, $id) );
1260 }
1261 }
1262
1263 $dbh->do("UPDATE ".($defrec eq 'y' ? 'default_' : '')."records ".
1264 "SET host=?,type=?,ttl=?,distance=?,weight=?,port=? ".
1265 "WHERE record_id=?", undef, ($host, $type, $ttl, $dist, $weight, $port, $id) );
1266
1267 };
1268 if ($@) {
1269 my $msg = $@;
1270 $dbh->rollback;
1271 return ('FAIL', $msg);
1272 }
1273# return ('FAIL',$sth->errstr."<br>\n$errstr<br>\n") if $sth->err;
1274
1275 return ('OK','OK');
1276} # end updateRec()
1277
1278
1279## DNSDB::delRec()
1280# Delete a record.
1281sub delRec {
1282 $errstr = '';
1283 my $dbh = shift;
1284 my $defrec = shift;
1285 my $id = shift;
1286
1287 my $sth = $dbh->prepare("DELETE FROM ".($defrec eq 'y' ? 'default_' : '')."records WHERE record_id=?");
1288 $sth->execute($id);
1289
1290 return ('FAIL',"Couldn't remove record: ".$sth->errstr) if $sth->err;
1291
1292 return ('OK','OK');
1293} # end delRec()
1294
1295
1296## DNSDB::domStatus()
1297# Sets and/or returns a domain's status
1298# Takes a database handle, domain ID and optionally a status argument
1299# Returns undef on errors.
1300sub domStatus {
1301 my $dbh = shift;
1302 my $id = shift;
1303 my $newstatus = shift;
1304
1305 return undef if $id !~ /^\d+$/;
1306
1307 my $sth;
1308
1309# ooo, fun! let's see what we were passed for status
1310 if ($newstatus) {
1311 $sth = $dbh->prepare("update domains set status=? where domain_id=?");
1312 # ass-u-me caller knows what's going on in full
1313 if ($newstatus =~ /^[01]$/) { # only two valid for now.
1314 $sth->execute($newstatus,$id);
1315 } elsif ($newstatus =~ /^domo(?:n|ff)$/) {
1316 $sth->execute(($newstatus eq 'domon' ? 1 : 0),$id);
1317 }
1318 }
1319
1320 $sth = $dbh->prepare("select status from domains where domain_id=?");
1321 $sth->execute($id);
1322 my ($status) = $sth->fetchrow_array;
1323 return $status;
1324} # end domStatus()
1325
1326
1327## DNSDB::importAXFR
1328# Import a domain via AXFR
1329# Takes AXFR host, domain to transfer, group to put the domain in,
1330# and optionally:
1331# - active/inactive state flag (defaults to active)
1332# - overwrite-SOA flag (defaults to off)
1333# - overwrite-NS flag (defaults to off, doesn't affect subdomain NS records)
1334# Returns a status code (OK, WARN, or FAIL) and message - message should be blank
1335# if status is OK, but WARN includes conditions that are not fatal but should
1336# really be reported.
1337sub importAXFR {
1338 my $dbh = shift;
1339 my $ifrom_in = shift;
1340 my $domain = shift;
1341 my $group = shift;
1342 my $status = shift || 1;
1343 my $rwsoa = shift || 0;
1344 my $rwns = shift || 0;
1345
1346##fixme: add mode to delete&replace, merge+overwrite, merge new?
1347
1348 my $nrecs = 0;
1349 my $soaflag = 0;
1350 my $nsflag = 0;
1351 my $warnmsg = '';
1352 my $ifrom;
1353
1354 # choke on possible bad setting in ifrom
1355 # IPv4 and v6, and valid hostnames!
1356 ($ifrom) = ($ifrom_in =~ /^([0-9a-f\:.]+|[0-9a-z_.-]+)$/i);
1357 return ('FAIL', "Bad AXFR source host $ifrom")
1358 unless ($ifrom) = ($ifrom_in =~ /^([0-9a-f\:.]+|[0-9a-z_.-]+)$/i);
1359
1360 # Allow transactions, and raise an exception on errors so we can catch it later.
1361 # Use local to make sure these get "reset" properly on exiting this block
1362 local $dbh->{AutoCommit} = 0;
1363 local $dbh->{RaiseError} = 1;
1364
1365 my $sth = $dbh->prepare("SELECT domain_id FROM domains WHERE domain=?");
1366 my $dom_id;
1367
1368# quick check to start to see if we've already got one
1369 $sth->execute($domain);
1370 ($dom_id) = $sth->fetchrow_array;
1371
1372 return ('FAIL', "Domain already exists") if $dom_id;
1373
1374 eval {
1375 # can't do this, can't nest transactions. sigh.
1376 #my ($dcode, $dmsg) = addDomain(dbh, domain, group, status);
1377
1378##fixme: serial
1379 my $sth = $dbh->prepare("INSERT INTO domains (domain,group_id,status) VALUES (?,?,?)");
1380 $sth->execute($domain,$group,$status);
1381
1382## bizarre DBI<->Net::DNS interaction bug:
1383## sometimes a zone will cause an immediate commit-and-exit (sort of) of the while()
1384## fixed, apparently I was doing *something* odd, but not certain what it was that
1385## caused a commit instead of barfing
1386
1387 # get domain id so we can do the records
1388 $sth = $dbh->prepare("SELECT domain_id FROM domains WHERE domain=?");
1389 $sth->execute($domain);
1390 ($dom_id) = $sth->fetchrow_array();
1391
1392 my $res = Net::DNS::Resolver->new;
1393 $res->nameservers($ifrom);
1394 $res->axfr_start($domain)
1395 or die "Couldn't begin AXFR\n";
1396
1397 while (my $rr = $res->axfr_next()) {
1398 my $type = $rr->type;
1399
1400 my $sql = "INSERT INTO records (domain_id,host,type,ttl,val";
1401 my $vallen = "?,?,?,?,?";
1402
1403 $soaflag = 1 if $type eq 'SOA';
1404 $nsflag = 1 if $type eq 'NS';
1405
1406 my @vallist = ($dom_id, $rr->name, $reverse_typemap{$type}, $rr->ttl);
1407
1408# "Primary" types:
1409# A, NS, CNAME, SOA, PTR(warn in forward), MX, TXT, AAAA, SRV, A6(ob), SPF
1410# maybe KEY
1411
1412# nasty big ugly case-like thing here, since we have to do *some* different
1413# processing depending on the record. le sigh.
1414
1415 if ($type eq 'A') {
1416 push @vallist, $rr->address;
1417 } elsif ($type eq 'NS') {
1418# hmm. should we warn here if subdomain NS'es are left alone?
1419 next if ($rwns && ($rr->name eq $domain));
1420 push @vallist, $rr->nsdname;
1421 $nsflag = 1;
1422 } elsif ($type eq 'CNAME') {
1423 push @vallist, $rr->cname;
1424 } elsif ($type eq 'SOA') {
1425 next if $rwsoa;
1426 $vallist[1] = $rr->mname.":".$rr->rname;
1427 push @vallist, ($rr->refresh.":".$rr->retry.":".$rr->expire.":".$rr->minimum);
1428 $soaflag = 1;
1429 } elsif ($type eq 'PTR') {
1430 # hmm. PTR records should not be in forward zones.
1431 } elsif ($type eq 'MX') {
1432 $sql .= ",distance";
1433 $vallen .= ",?";
1434 push @vallist, $rr->exchange;
1435 push @vallist, $rr->preference;
1436 } elsif ($type eq 'TXT') {
1437##fixme: Net::DNS docs say this should be deprecated for rdatastr() or char_str_list(),
1438## but don't really seem enthusiastic about it.
1439 push @vallist, $rr->txtdata;
1440 } elsif ($type eq 'SPF') {
1441##fixme: and the same caveat here, since it is apparently a clone of ::TXT
1442 push @vallist, $rr->txtdata;
1443 } elsif ($type eq 'AAAA') {
1444 push @vallist, $rr->address;
1445 } elsif ($type eq 'SRV') {
1446 $sql .= ",distance,weight,port" if $type eq 'SRV';
1447 $vallen .= ",?,?,?" if $type eq 'SRV';
1448 push @vallist, $rr->target;
1449 push @vallist, $rr->priority;
1450 push @vallist, $rr->weight;
1451 push @vallist, $rr->port;
1452 } elsif ($type eq 'KEY') {
1453 # we don't actually know what to do with these...
1454 push @vallist, ($rr->flags.":".$rr->protocol.":".$rr->algorithm.":".$rr->key.":".$rr->keytag.":".$rr->privatekeyname);
1455 } else {
1456 push @vallist, $rr->rdatastr;
1457 # Finding a different record type is not fatal.... just problematic.
1458 # We may not be able to export it correctly.
1459 $warnmsg .= "Unusual record ".$rr->name." ($type) found\n";
1460 }
1461
1462# BIND supports:
1463# A CNAME HINFO MB(ex) MD(ob) MF(ob) MG(ex) MINFO(ex) MR(ex) MX NS NULL
1464# PTR SOA TXT WKS AFSDB(ex) ISDN(ex) RP(ex) RT(ex) X25(ex) PX
1465# ... if one can ever find the right magic to format them correctly
1466
1467# Net::DNS supports:
1468# RRSIG SIG NSAP NS NIMLOC NAPTR MX MR MINFO MG MB LOC ISDN IPSECKEY HINFO
1469# EID DNAME CNAME CERT APL AFSDB AAAA A DS NXT NSEC3PARAM NSEC3 NSEC KEY
1470# DNSKEY DLV X25 TXT TSIG TKEY SSHFP SRV SPF SOA RT RP PX PTR NULL APL::AplItem
1471
1472 $sth = $dbh->prepare($sql.") VALUES (".$vallen.")") or die "problem preparing record insert SQL\n";
1473 $sth->execute(@vallist) or die "failed to insert ".$rr->string.": ".$sth->errstr."\n";
1474
1475 $nrecs++;
1476
1477 } # while axfr_next
1478
1479 # Overwrite SOA record
1480 if ($rwsoa) {
1481 $soaflag = 1;
1482 my $sthgetsoa = $dbh->prepare("SELECT host,val,ttl FROM default_records WHERE group_id=? AND type=?");
1483 my $sthputsoa = $dbh->prepare("INSERT INTO records (domain_id,host,type,val,ttl) VALUES (?,?,?,?,?)");
1484 $sthgetsoa->execute($group,$reverse_typemap{SOA});
1485 while (my ($host,$val,$ttl) = $sthgetsoa->fetchrow_array()) {
1486 $host =~ s/DOMAIN/$domain/g;
1487 $val =~ s/DOMAIN/$domain/g;
1488 $sthputsoa->execute($dom_id,$host,$reverse_typemap{SOA},$val,$ttl);
1489 }
1490 }
1491
1492 # Overwrite NS records
1493 if ($rwns) {
1494 $nsflag = 1;
1495 my $sthgetns = $dbh->prepare("SELECT host,val,ttl FROM default_records WHERE group_id=? AND type=?");
1496 my $sthputns = $dbh->prepare("INSERT INTO records (domain_id,host,type,val,ttl) VALUES (?,?,?,?,?)");
1497 $sthgetns->execute($group,$reverse_typemap{NS});
1498 while (my ($host,$val,$ttl) = $sthgetns->fetchrow_array()) {
1499 $host =~ s/DOMAIN/$domain/g;
1500 $val =~ s/DOMAIN/$domain/g;
1501 $sthputns->execute($dom_id,$host,$reverse_typemap{NS},$val,$ttl);
1502 }
1503 }
1504
1505 die "No records found; either $ifrom is not authoritative or doesn't allow transfers\n" if !$nrecs;
1506 die "Bad zone: No SOA record!\n" if !$soaflag;
1507 die "Bad zone: No NS records!\n" if !$nsflag;
1508
1509 $dbh->commit;
1510
1511 };
1512
1513 if ($@) {
1514 my $msg = $@;
1515 eval { $dbh->rollback; };
1516 return ('FAIL',$msg." $warnmsg");
1517 } else {
1518 return ('WARN', $warnmsg) if $warnmsg;
1519 return ('OK',"Imported OK");
1520 }
1521
1522 # it should be impossible to get here.
1523 return ('WARN',"OOOK!");
1524} # end importAXFR()
1525
1526
1527# shut Perl up
15281;
Note: See TracBrowser for help on using the repository browser.