source: trunk/DNSDB.pm@ 92

Last change on this file since 92 was 91, checked in by Kris Deugau, 14 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
RevLine 
[2]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;
[33]17use Net::DNS;
[65]18use Crypt::PasswdMD5;
[2]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(
[67]27 &initGlobals
28 &initPermissions &getPermissions &changePermissions &comparePermissions
[65]29 &connectDB &finish
[91]30 &addDomain &delDomain &domainName &domainID
[22]31 &addGroup &delGroup &getChildren &groupName
[83]32 &addUser &updateUser &delUser &userFullName &userStatus &getUserData
[91]33 &getSOA &getRecLine &getDomRecs &getRecCount
[22]34 &addRec &updateRec &delRec
[34]35 &domStatus &importAXFR
[2]36 %typemap %reverse_typemap
[66]37 %permissions @permtypes $permlist
[2]38 );
39
40@EXPORT = (); # Export nothing by default.
41%EXPORT_TAGS = ( ALL => [qw(
[67]42 &initGlobals
43 &initPermissions &getPermissions &changePermissions &comparePermissions
[65]44 &connectDB &finish
[91]45 &addDomain &delDomain &domainName &domainID
[22]46 &addGroup &delGroup &getChildren &groupName
[83]47 &addUser &updateUser &delUser &userFullName &userStatus &getUserData
[91]48 &getSOA &getRecLine &getDomRecs &getRecCount
[22]49 &addRec &updateRec &delRec
[34]50 &domStatus &importAXFR
[2]51 %typemap %reverse_typemap
[66]52 %permissions @permtypes $permlist
[2]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
[66]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
[2]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
[65]86our %permissions;
[55]87
[2]88##
89## Initialization and cleanup subs
90##
91
[55]92
[2]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 = '';
[15]101 my $dbname = shift;
102 my $user = shift;
103 my $pass = shift;
[2]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
[29]153 if (open SYSDEFAULTS, "</etc/dnsdb.conf") {
[2]154##fixme - error check!
[29]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;
[2]165##fixme? load DB user/pass from config file?
[29]166 }
[2]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
[65]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.
[87]242##fixme: Must handle case of changing object's permissions from custom to inherited
[65]243sub changePermissions {
244 my $dbh = shift;
245 my $type = shift;
246 my $id = shift;
247 my $newperms = shift;
[87]248 my $inherit = shift || 0;
[65]249
[78]250 my $failmsg = '';
[66]251
[87]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".
[65]257 " FROM ".($type eq 'user' ? 'users' : 'groups')." u ".
[66]258 " JOIN groups g ON u.".($type eq 'user' ? '' : 'parent_')."group_id=g.group_id ".
[65]259 " WHERE u.".($type eq 'user' ? 'user' : 'group')."_id=?");
260 $sth->execute($id);
261
[87]262 my ($wasinherited,$permid,$parpermid) = $sth->fetchrow_array;
[66]263
[78]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
[66]269 local $dbh->{AutoCommit} = 0;
270 local $dbh->{RaiseError} = 1;
271
272 # Wrap all the SQL in a transaction
273 eval {
[87]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
[66]283##fixme: need to add semirecursive bit to properly munge inherited permission ID on subgroups and users
[87]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) );
[66]292 }
[78]293
[87]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
[66]303 $dbh->commit;
304 }; # end eval
305 if ($@) {
306 my $msg = $@;
307 eval { $dbh->rollback; };
[87]308 return ('FAIL',"$failmsg: $msg ($permid)");
[66]309 } else {
310 return ('OK',$permid);
311 }
312
[65]313} # end changePermissions()
314
315
[67]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
[55]348## DNSDB::_log()
349# Log an action
350# Internal sub
351# Takes a database handle, <foo>, <bar>
352sub _log {
353} # end _log
354
355
[2]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;
[91]369 return ('FAIL',"Domain must not be blank") if !$domain;
[2]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
[38]375 my $sth = $dbh->prepare("SELECT domain_id FROM domains WHERE domain=?");
[3]376 my $dom_id;
377
[38]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
[2]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;
[3]398 ($dom_id) = $sth->fetchrow_array();
[2]399
400 # ... and now we construct the standard records from the default set. NB: group should be variable.
[3]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,?,?,?,?,?,?,?)");
[2]404 $sth->execute;
[3]405 while (my ($host,$type,$val,$dist,$weight,$port,$ttl) = $sth->fetchrow_array()) {
[2]406 $host =~ s/DOMAIN/$domain/g;
[37]407 $val =~ s/DOMAIN/$domain/g;
[3]408 $sth_in->execute($host,$type,$val,$dist,$weight,$port,$ttl);
[2]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 {
[3]420 return ('OK',$dom_id);
[2]421 }
422} # end addDomain
423
424
[3]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;
[5]431 my $domid = shift;
[3]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
[23]438 my $failmsg = '';
439
[3]440 # Wrap all the SQL in a transaction
441 eval {
[5]442 my $sth = $dbh->prepare("delete from records where domain_id=?");
[23]443 $failmsg = "Failure removing domain records";
[5]444 $sth->execute($domid);
445 $sth = $dbh->prepare("delete from domains where domain_id=?");
[23]446 $failmsg = "Failure removing domain";
[5]447 $sth->execute($domid);
[3]448
449 # once we get here, we should have suceeded.
[23]450 $dbh->commit;
[3]451 }; # end eval
452
453 if ($@) {
454 my $msg = $@;
455 eval { $dbh->rollback; };
[23]456 return ('FAIL',"$failmsg: $msg");
[3]457 } else {
458 return ('OK','OK');
459 }
460
461} # end delDomain()
462
463
[2]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;
[91]472 my ($domname) = $dbh->selectrow_array("SELECT domain FROM domains WHERE domain_id=?", undef, ($domid) );
[2]473 $errstr = $DBI::errstr if !$domname;
474 return $domname if $domname;
[91]475} # end domainName()
[2]476
477
[91]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
[18]491## DNSDB::addGroup()
492# Add a group
[66]493# Takes a database handle, group name, parent group, hashref for permissions,
494# and optional template-vs-cloneme flag
[18]495# Returns a status code and message
496sub addGroup {
497 $errstr = '';
498 my $dbh = shift;
[20]499 my $groupname = shift;
500 my $pargroup = shift;
[66]501 my $permissions = shift;
[18]502
[66]503 # 0 indicates "custom", hardcoded.
[18]504 # Any other value clones that group's default records, if it exists.
[66]505 my $inherit = shift || 0;
506##fixme: need a flag to indicate clone records or <?> ?
[18]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
[38]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
[18]522 # Wrap all the SQL in a transaction
523 eval {
[38]524 $sth = $dbh->prepare("INSERT INTO groups (parent_group_id,group_name) VALUES (?,?)");
[20]525 $sth->execute($pargroup,$groupname);
[18]526
527 $sth = $dbh->prepare("SELECT group_id FROM groups WHERE group_name=?");
[20]528 $sth->execute($groupname);
529 my ($groupid) = $sth->fetchrow_array();
[18]530
[66]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
[18]554 $sth = $dbh->prepare("INSERT INTO default_records (group_id,host,type,val,distance,weight,port,ttl) ".
[20]555 "VALUES ($groupid,?,?,?,?,?,?,?)");
[66]556 if ($inherit) {
[87]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.
[18]559 my $sth2 = $dbh->prepare("SELECT host,type,val,distance,weight,port,ttl FROM default_records WHERE group_id=?");
[87]560 $sth2->execute($pargroup);
[18]561 while (my @clonedata = $sth2->fetchrow_array) {
562 $sth->execute(@clonedata);
563 }
564 } else {
[66]565##fixme: Hardcoding is Bad, mmmmkaaaay?
[18]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
[22]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
[23]605# ... or inside, whatever.
[22]606# -> domains still exist in group
607# -> ...
[23]608 my $failmsg = '';
[22]609
610 # Wrap all the SQL in a transaction
611 eval {
[23]612 my $sth = $dbh->prepare("SELECT count(*) FROM domains WHERE group_id=?");
[22]613 $sth->execute($groupid);
[23]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);
[22]621 $sth = $dbh->prepare("delete from groups where group_id=?");
[23]622 $failmsg = "Failed to remove group ".groupName($dbh,$groupid);
[22]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; };
[23]632 return ('FAIL',"$failmsg: $msg");
[22]633 } else {
634 return ('OK','OK');
635 }
636} # end delGroup()
637
638
[19]639## DNSDB::getChildren()
640# Get a list of all groups whose parent^n is group <n>
[24]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
[19]644# Calls itself
645sub getChildren {
646 $errstr = '';
647 my $dbh = shift;
[20]648 my $rootgroup = shift;
649 my $groupdest = shift;
[24]650 my $immed = shift || 'all';
[19]651
652 # special break for default group; otherwise we get stuck.
[20]653 if ($rootgroup == 1) {
[19]654 # by definition, group 1 is the Root Of All Groups
[24]655 my $sth = $dbh->prepare("SELECT group_id FROM groups WHERE NOT (group_id=1)".
656 ($immed ne 'all' ? " AND parent_group_id=1" : ''));
[19]657 $sth->execute;
658 while (my @this = $sth->fetchrow_array) {
[20]659 push @$groupdest, @this;
[19]660 }
661 } else {
662 my $sth = $dbh->prepare("SELECT group_id FROM groups WHERE parent_group_id=?");
[20]663 $sth->execute($rootgroup);
[19]664 return if $sth->rows == 0;
[20]665 my @grouplist;
666 while (my ($group) = $sth->fetchrow_array) {
667 push @$groupdest, $group;
[24]668 getChildren($dbh,$group,$groupdest) if $immed eq 'all';
[19]669 }
670 }
671} # end getChildren()
672
673
[20]674## DNSDB::groupName()
[17]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
[20]678sub groupName {
[13]679 $errstr = '';
680 my $dbh = shift;
[20]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
[13]688
689
[24]690## DNSDB::addUser()
[87]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)
[90]703# Returns (OK,<uid>) on success, (FAIL,<message>) on failure
[24]704sub addUser {
705 $errstr = '';
706 my $dbh = shift;
707 my $username = shift;
708 my $group = shift;
709 my $pass = shift;
710 my $state = shift;
[25]711
[90]712 return ('FAIL', "Missing one or more required entries") if !defined($state);
713 return ('FAIL', "Username must not be blank") if !$username;
[87]714
[25]715 my $type = shift || 'u'; # create limited users by default - fwiw, not sure yet how this will interact with ACLs
716
[67]717 my $permstring = shift || 'i'; # default is to inhert permissions from group
718
[25]719 my $fname = shift || $username;
[24]720 my $lname = shift || '';
[25]721 my $phone = shift || ''; # not going format-check
[24]722
[38]723 my $sth = $dbh->prepare("SELECT user_id FROM users WHERE username=?");
[24]724 my $user_id;
725
[38]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
[24]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
[87]737my $failmsg;
[24]738 # Wrap all the SQL in a transaction
739 eval {
[87]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);
[24]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
[87]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
[25]789##fixme: add another table to hold name/email for log table?
[87]790#die "dying horribly ($permstring, $user_id)";
[25]791
[24]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; };
[87]799 return ('FAIL',$msg." $failmsg");
[24]800 } else {
801 return ('OK',$user_id);
802 }
803} # end addUser
804
805
[55]806## DNSDB::checkUser()
807# Check user/pass combo on login
808sub checkUser {
809 my $dbh = shift;
810 my $user = shift;
[56]811 my $inpass = shift;
[55]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/.]+)\$|) {
[56]819 $loginfailed = 1 if $pass ne unix_md5_crypt($inpass,$1);
[55]820 } else {
[56]821 $loginfailed = 1 if $pass ne $inpass;
[55]822 }
823
824 # nnnngggg
825 return ($uid, $gid);
826} # end checkUser
827
828
[83]829## DNSDB:: updateUser()
[90]830# Update general data about user
[83]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;
[87]838 my $type = shift || 'u';
[83]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
[24]882## DNSDB::delUser()
883#
884sub delUser {
[25]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
[24]897} # end delUser
898
899
[25]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
[51]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
[83]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
[2]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
[90]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;
[2]1038
[90]1039 if ($dbh->err) {
[2]1040 $errstr = $DBI::errstr;
1041 return undef;
1042 }
1043
[90]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;
[2]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;
[4]1063 my $nrecs = shift || 'all';
1064 my $nstart = shift || 0;
[2]1065
[4]1066## for order, need to map input to column names
1067 my $order = shift || 'host';
[72]1068 my $direction = shift || 'ASC';
[4]1069
[90]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=?";
[2]1078 } else {
[90]1079 $sql .= "WHERE r.domain_id=?";
[2]1080 }
[90]1081 $sql .= " AND NOT r.type=$reverse_typemap{SOA} ORDER BY r.$order $direction";
[15]1082##fixme: need to set nstart properly (offset is not internally multiplied with limit)
[90]1083 $sql .= " LIMIT $nrecs OFFSET ".($nstart*$nrecs) if $nstart ne 'all';
[4]1084
[90]1085 my $sth = $dbh->prepare($sql) or warn $dbh->errstr;
1086 $sth->execute($id) or warn "$sql: ".$sth->errstr;
[2]1087
1088 my @retbase;
1089 while (my $ref = $sth->fetchrow_hashref()) {
[90]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.
[2]1093 push @retbase, $ref;
1094 }
1095
1096 my $ret = \@retbase;
1097 return $ret;
1098} # end getDomRecs()
1099
1100
[91]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
[3]1120## DNSDB::addRec()
[2]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";
[24]1139 my $vallen = "?,?,?,?,?";
1140 my @vallist = ($id,$host,$rectype,$val,$ttl);
[2]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";
[24]1147 $vallen .= ",?";
1148 push @vallist, $dist;
[2]1149 }
1150 my $weight;
1151 my $port;
1152 if ($rectype == $reverse_typemap{SRV}) {
[24]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-]+/;
[2]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";
[24]1161 $vallen .= ",?,?";
1162 push @vallist, ($weight,$port);
[2]1163 }
1164
[90]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;
[2]1169
[90]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 }
[2]1189
1190 return ('OK','OK');
[90]1191
[2]1192} # end addRec()
1193
1194
[16]1195## DNSDB::updateRec()
1196# Update a record
1197sub updateRec {
1198 $errstr = '';
[17]1199
[16]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}) {
[17]1218 $dist = shift;
1219 return ('FAIL',"MX or SRV requires distance") if !defined($dist);
[16]1220 if ($type == $reverse_typemap{SRV}) {
[17]1221 $weight = shift;
1222 return ('FAIL',"SRV requires weight") if !defined($weight);
1223 $port = shift;
1224 return ('FAIL',"SRV requires port") if !defined($port);
[16]1225 }
1226 }
1227
[90]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 ";
[16]1232
[90]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) );
[16]1236
[90]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
[16]1275 return ('OK','OK');
1276} # end updateRec()
1277
1278
[3]1279## DNSDB::delRec()
1280# Delete a record.
1281sub delRec {
1282 $errstr = '';
1283 my $dbh = shift;
1284 my $defrec = shift;
1285 my $id = shift;
1286
[62]1287 my $sth = $dbh->prepare("DELETE FROM ".($defrec eq 'y' ? 'default_' : '')."records WHERE record_id=?");
[3]1288 $sth->execute($id);
1289
[23]1290 return ('FAIL',"Couldn't remove record: ".$sth->errstr) if $sth->err;
[3]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
[33]1327## DNSDB::importAXFR
1328# Import a domain via AXFR
[37]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.
[33]1337sub importAXFR {
1338 my $dbh = shift;
[35]1339 my $ifrom_in = shift;
[33]1340 my $domain = shift;
1341 my $group = shift;
1342 my $status = shift || 1;
1343 my $rwsoa = shift || 0;
1344 my $rwns = shift || 0;
[37]1345
[33]1346##fixme: add mode to delete&replace, merge+overwrite, merge new?
1347
[37]1348 my $nrecs = 0;
1349 my $soaflag = 0;
1350 my $nsflag = 0;
1351 my $warnmsg = '';
1352 my $ifrom;
[33]1353
[35]1354 # choke on possible bad setting in ifrom
[37]1355 # IPv4 and v6, and valid hostnames!
[35]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
[33]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
[37]1365 my $sth = $dbh->prepare("SELECT domain_id FROM domains WHERE domain=?");
[34]1366 my $dom_id;
1367
[35]1368# quick check to start to see if we've already got one
[37]1369 $sth->execute($domain);
1370 ($dom_id) = $sth->fetchrow_array;
[35]1371
1372 return ('FAIL', "Domain already exists") if $dom_id;
1373
[33]1374 eval {
1375 # can't do this, can't nest transactions. sigh.
[35]1376 #my ($dcode, $dmsg) = addDomain(dbh, domain, group, status);
[33]1377
1378##fixme: serial
[37]1379 my $sth = $dbh->prepare("INSERT INTO domains (domain,group_id,status) VALUES (?,?,?)");
1380 $sth->execute($domain,$group,$status);
[33]1381
[35]1382## bizarre DBI<->Net::DNS interaction bug:
1383## sometimes a zone will cause an immediate commit-and-exit (sort of) of the while()
[37]1384## fixed, apparently I was doing *something* odd, but not certain what it was that
1385## caused a commit instead of barfing
[35]1386
[33]1387 # get domain id so we can do the records
[37]1388 $sth = $dbh->prepare("SELECT domain_id FROM domains WHERE domain=?");
1389 $sth->execute($domain);
1390 ($dom_id) = $sth->fetchrow_array();
[33]1391
[34]1392 my $res = Net::DNS::Resolver->new;
[35]1393 $res->nameservers($ifrom);
1394 $res->axfr_start($domain)
1395 or die "Couldn't begin AXFR\n";
[34]1396
[35]1397 while (my $rr = $res->axfr_next()) {
[33]1398 my $type = $rr->type;
[35]1399
[34]1400 my $sql = "INSERT INTO records (domain_id,host,type,ttl,val";
[33]1401 my $vallen = "?,?,?,?,?";
1402
[37]1403 $soaflag = 1 if $type eq 'SOA';
1404 $nsflag = 1 if $type eq 'NS';
[35]1405
1406 my @vallist = ($dom_id, $rr->name, $reverse_typemap{$type}, $rr->ttl);
[34]1407
1408# "Primary" types:
1409# A, NS, CNAME, SOA, PTR(warn in forward), MX, TXT, AAAA, SRV, A6(ob), SPF
1410# maybe KEY
1411
[35]1412# nasty big ugly case-like thing here, since we have to do *some* different
1413# processing depending on the record. le sigh.
1414
[34]1415 if ($type eq 'A') {
1416 push @vallist, $rr->address;
1417 } elsif ($type eq 'NS') {
[37]1418# hmm. should we warn here if subdomain NS'es are left alone?
1419 next if ($rwns && ($rr->name eq $domain));
[34]1420 push @vallist, $rr->nsdname;
[35]1421 $nsflag = 1;
[34]1422 } elsif ($type eq 'CNAME') {
1423 push @vallist, $rr->cname;
1424 } elsif ($type eq 'SOA') {
[37]1425 next if $rwsoa;
[34]1426 $vallist[1] = $rr->mname.":".$rr->rname;
1427 push @vallist, ($rr->refresh.":".$rr->retry.":".$rr->expire.":".$rr->minimum);
[35]1428 $soaflag = 1;
[34]1429 } elsif ($type eq 'PTR') {
1430 # hmm. PTR records should not be in forward zones.
1431 } elsif ($type eq 'MX') {
[33]1432 $sql .= ",distance";
1433 $vallen .= ",?";
[34]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';
[37]1448 push @vallist, $rr->target;
[34]1449 push @vallist, $rr->priority;
1450 push @vallist, $rr->weight;
1451 push @vallist, $rr->port;
1452 } elsif ($type eq 'KEY') {
[35]1453 # we don't actually know what to do with these...
[34]1454 push @vallist, ($rr->flags.":".$rr->protocol.":".$rr->algorithm.":".$rr->key.":".$rr->keytag.":".$rr->privatekeyname);
[35]1455 } else {
[37]1456 push @vallist, $rr->rdatastr;
[35]1457 # Finding a different record type is not fatal.... just problematic.
[37]1458 # We may not be able to export it correctly.
[35]1459 $warnmsg .= "Unusual record ".$rr->name." ($type) found\n";
[33]1460 }
1461
[34]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
[37]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";
[34]1474
[37]1475 $nrecs++;
[34]1476
[37]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);
[34]1489 }
[37]1490 }
[34]1491
[37]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 }
[34]1504
[35]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
[37]1509 $dbh->commit;
[35]1510
[33]1511 };
1512
1513 if ($@) {
1514 my $msg = $@;
1515 eval { $dbh->rollback; };
[34]1516 return ('FAIL',$msg." $warnmsg");
[33]1517 } else {
[35]1518 return ('WARN', $warnmsg) if $warnmsg;
[91]1519 return ('OK',"Imported OK");
[33]1520 }
1521
[37]1522 # it should be impossible to get here.
[34]1523 return ('WARN',"OOOK!");
[33]1524} # end importAXFR()
1525
1526
[2]1527# shut Perl up
15281;
Note: See TracBrowser for help on using the repository browser.