# dns/trunk/DNSDB.pm # Abstraction functions for DNS administration ### # SVN revision info # $Date: 2010-01-12 16:24:00 +0000 (Tue, 12 Jan 2010) $ # SVN revision $Rev: 56 $ # Last update by $Author: kdeugau $ ### # Copyright (C) 2008 - Kris Deugau package DNSDB; use strict; use warnings; use Exporter; use DBI; use Net::DNS; #use Net::SMTP; #use NetAddr::IP qw( Compact ); #use POSIX; use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS); $VERSION = 0.1; @ISA = qw(Exporter); @EXPORT_OK = qw( &initGlobals &connectDB &finish &addDomain &delDomain &domainName &addGroup &delGroup &getChildren &groupName &addUser &delUser &userFullName &userStatus &getSOA &getRecLine &getDomRecs &addRec &updateRec &delRec &domStatus &importAXFR %typemap %reverse_typemap ); @EXPORT = (); # Export nothing by default. %EXPORT_TAGS = ( ALL => [qw( &initGlobals &connectDB &finish &addDomain &delDomain &domainName &addGroup &delGroup &getChildren &groupName &addUser &delUser &userFullName &userStatus &getSOA &getRecLine &getDomRecs &addRec &updateRec &delRec &domStatus &importAXFR %typemap %reverse_typemap )] ); our $group = 1; our $errstr = ''; # Halfway sane defaults for SOA, TTL, etc. our %def = qw ( contact hostmaster.DOMAIN prins ns1.myserver.com soattl 86400 refresh 10800 retry 3600 expire 604800 minttl 10800 ttl 10800 ); # DNS record type map and reverse map. # loaded from the database, from http://www.iana.org/assignments/dns-parameters our %typemap; our %reverse_typemap; ## ## Initialization and cleanup subs ## ## DNSDB::connectDB() # Creates connection to DNS database. # Requires the database name, username, and password. # Returns a handle to the db. # Set up for a PostgreSQL db; could be any transactional DBMS with the # right changes. sub connectDB { $errstr = ''; my $dbname = shift; my $user = shift; my $pass = shift; my $dbh; my $DSN = "DBI:Pg:dbname=$dbname"; my $host = shift; $DSN .= ";host=$host" if $host; # Note that we want to autocommit by default, and we will turn it off locally as necessary. # We may not want to print gobbledygook errors; YMMV. Have to ponder that further. $dbh = DBI->connect($DSN, $user, $pass, { AutoCommit => 1, PrintError => 0 }) or return (undef, $DBI::errstr) if(!$dbh); # Return here if we can't select. Note that this indicates a # problem executing the select. my $sth = $dbh->prepare("select group_id from groups limit 1"); $sth->execute(); return (undef,$DBI::errstr) if ($sth->err); # See if the select returned anything (or null data). This should # succeed if the select executed, but... $sth->fetchrow(); return (undef,$DBI::errstr) if ($sth->err); $sth->finish; # If we get here, we should be OK. return ($dbh,"DB connection OK"); } # end connectDB ## DNSDB::finish() # Cleans up after database handles and so on. # Requires a database handle sub finish { my $dbh = $_[0]; $dbh->disconnect; } # end finish ## DNSDB::initGlobals() # Initialize global variables # NB: this does NOT include web-specific session variables! # Requires a database handle sub initGlobals { my $dbh = shift; # load system-wide site defaults and things from config file if (open SYSDEFAULTS, ") { next if /^\s*#/; $def{contact} = $1 if /contact ?= ?([a-z0-9_.-]+)/i; $def{prins} = $1 if /prins ?= ?([a-z0-9_.-]+)/i; $def{soattl} = $1 if /soattl ?= ?([a-z0-9_.-]+)/i; $def{refresh} = $1 if /refresh ?= ?([a-z0-9_.-]+)/i; $def{retry} = $1 if /retry ?= ?([a-z0-9_.-]+)/i; $def{expire} = $1 if /expire ?= ?([a-z0-9_.-]+)/i; $def{minttl} = $1 if /minttl ?= ?([a-z0-9_.-]+)/i; $def{ttl} = $1 if /ttl ?= ?([a-z0-9_.-]+)/i; ##fixme? load DB user/pass from config file? } } # load from database my $sth = $dbh->prepare("select val,name from rectypes"); $sth->execute; while (my ($recval,$recname) = $sth->fetchrow_array()) { $typemap{$recval} = $recname; $reverse_typemap{$recname} = $recval; } } # end initGlobals ## DNSDB::_log() # Log an action # Internal sub # Takes a database handle, , sub _log { } # end _log ## ## Processing subs ## ## DNSDB::addDomain() # Add a domain # Takes a database handle, domain name, numeric group, and boolean(ish) state (active/inactive) # Returns a status code and message sub addDomain { $errstr = ''; my $dbh = shift; return ('FAIL',"Need database handle") if !$dbh; my $domain = shift; return ('FAIL',"Need domain") if !defined($domain); my $group = shift; return ('FAIL',"Need group") if !defined($group); my $state = shift; return ('FAIL',"Need domain status") if !defined($state); my $sth = $dbh->prepare("SELECT domain_id FROM domains WHERE domain=?"); my $dom_id; # quick check to start to see if we've already got one $sth->execute($domain); ($dom_id) = $sth->fetchrow_array; return ('FAIL', "Domain already exists") if $dom_id; # Allow transactions, and raise an exception on errors so we can catch it later. # Use local to make sure these get "reset" properly on exiting this block local $dbh->{AutoCommit} = 0; local $dbh->{RaiseError} = 1; # Wrap all the SQL in a transaction eval { # insert the domain... my $sth = $dbh->prepare("insert into domains (domain,group_id,status) values (?,?,?)"); $sth->execute($domain,$group,$state); # get the ID... $sth = $dbh->prepare("select domain_id from domains where domain='$domain'"); $sth->execute; ($dom_id) = $sth->fetchrow_array(); # ... and now we construct the standard records from the default set. NB: group should be variable. $sth = $dbh->prepare("select host,type,val,distance,weight,port,ttl from default_records where group_id=$group"); my $sth_in = $dbh->prepare("insert into records (domain_id,host,type,val,distance,weight,port,ttl)". " values ($dom_id,?,?,?,?,?,?,?)"); $sth->execute; while (my ($host,$type,$val,$dist,$weight,$port,$ttl) = $sth->fetchrow_array()) { $host =~ s/DOMAIN/$domain/g; $val =~ s/DOMAIN/$domain/g; $sth_in->execute($host,$type,$val,$dist,$weight,$port,$ttl); } # once we get here, we should have suceeded. $dbh->commit; }; # end eval if ($@) { my $msg = $@; eval { $dbh->rollback; }; return ('FAIL',$msg); } else { return ('OK',$dom_id); } } # end addDomain ## DNSDB::delDomain() # Delete a domain. # for now, just delete the records, then the domain. # later we may want to archive it in some way instead (status code 2, for example?) sub delDomain { my $dbh = shift; my $domid = shift; # Allow transactions, and raise an exception on errors so we can catch it later. # Use local to make sure these get "reset" properly on exiting this block local $dbh->{AutoCommit} = 0; local $dbh->{RaiseError} = 1; my $failmsg = ''; # Wrap all the SQL in a transaction eval { my $sth = $dbh->prepare("delete from records where domain_id=?"); $failmsg = "Failure removing domain records"; $sth->execute($domid); $sth = $dbh->prepare("delete from domains where domain_id=?"); $failmsg = "Failure removing domain"; $sth->execute($domid); # once we get here, we should have suceeded. $dbh->commit; }; # end eval if ($@) { my $msg = $@; eval { $dbh->rollback; }; return ('FAIL',"$failmsg: $msg"); } else { return ('OK','OK'); } } # end delDomain() ## DNSDB::domainName() # Return the domain name based on a domain ID # Takes a database handle and the domain ID # Returns the domain name or undef on failure sub domainName { $errstr = ''; my $dbh = shift; my $domid = shift; my $sth = $dbh->prepare("select domain from domains where domain_id=?"); $sth->execute($domid); my ($domname) = $sth->fetchrow_array(); $errstr = $DBI::errstr if !$domname; return $domname if $domname; } # end domainName ## DNSDB::addGroup() # Add a group # Takes a database handle, group name, parent group, and template-vs-cloneme flag # Returns a status code and message sub addGroup { $errstr = ''; my $dbh = shift; my $groupname = shift; my $pargroup = shift; # 0 indicates "template", hardcoded. # Any other value clones that group's default records, if it exists. my $torc = shift || 0; # Allow transactions, and raise an exception on errors so we can catch it later. # Use local to make sure these get "reset" properly on exiting this block local $dbh->{AutoCommit} = 0; local $dbh->{RaiseError} = 1; my $sth = $dbh->prepare("SELECT group_id FROM groups WHERE group_name=?"); my $group_id; # quick check to start to see if we've already got one $sth->execute($groupname); ($group_id) = $sth->fetchrow_array; return ('FAIL', "Group already exists") if $group_id; # Wrap all the SQL in a transaction eval { $sth = $dbh->prepare("INSERT INTO groups (parent_group_id,group_name) VALUES (?,?)"); $sth->execute($pargroup,$groupname); $sth = $dbh->prepare("SELECT group_id FROM groups WHERE group_name=?"); $sth->execute($groupname); my ($groupid) = $sth->fetchrow_array(); $sth = $dbh->prepare("INSERT INTO default_records (group_id,host,type,val,distance,weight,port,ttl) ". "VALUES ($groupid,?,?,?,?,?,?,?)"); if ($torc) { my $sth2 = $dbh->prepare("SELECT host,type,val,distance,weight,port,ttl FROM default_records WHERE group_id=?"); while (my @clonedata = $sth2->fetchrow_array) { $sth->execute(@clonedata); } } else { # reasonable basic defaults for SOA, MX, NS, and minimal hosting # could load from a config file, but somewhere along the line we need hardcoded bits. $sth->execute('ns1.example.com:hostmaster.example.com', 6, '10800:3600:604800:10800', 0, 0, 0, 86400); $sth->execute('DOMAIN', 1, '192.168.4.2', 0, 0, 0, 7200); $sth->execute('DOMAIN', 15, 'mx.example.com', 10, 0, 0, 7200); $sth->execute('DOMAIN', 2, 'ns1.example.com', 0, 0, 0, 7200); $sth->execute('DOMAIN', 2, 'ns2.example.com', 0, 0, 0, 7200); $sth->execute('www.DOMAIN', 5, 'DOMAIN', 0, 0, 0, 7200); } # once we get here, we should have suceeded. $dbh->commit; }; # end eval if ($@) { my $msg = $@; eval { $dbh->rollback; }; return ('FAIL',$msg); } else { return ('OK','OK'); } } # end addGroup() ## DNSDB::delGroup() # Delete a group. # Takes a group ID # Returns a status code and message sub delGroup { my $dbh = shift; my $groupid = shift; # Allow transactions, and raise an exception on errors so we can catch it later. # Use local to make sure these get "reset" properly on exiting this block local $dbh->{AutoCommit} = 0; local $dbh->{RaiseError} = 1; ##fixme: locate "knowable" error conditions and deal with them before the eval # ... or inside, whatever. # -> domains still exist in group # -> ... my $failmsg = ''; # Wrap all the SQL in a transaction eval { my $sth = $dbh->prepare("SELECT count(*) FROM domains WHERE group_id=?"); $sth->execute($groupid); my ($domcnt) = $sth->fetchrow_array; $failmsg = "Can't remove group ".groupName($dbh,$groupid); die "$domcnt domains still in group\n" if $domcnt; $sth = $dbh->prepare("delete from default_records where group_id=?"); $failmsg = "Failed to delete default records for ".groupName($dbh,$groupid); $sth->execute($groupid); $sth = $dbh->prepare("delete from groups where group_id=?"); $failmsg = "Failed to remove group ".groupName($dbh,$groupid); $sth->execute($groupid); # once we get here, we should have suceeded. $dbh->commit; }; # end eval if ($@) { my $msg = $@; eval { $dbh->rollback; }; return ('FAIL',"$failmsg: $msg"); } else { return ('OK','OK'); } } # end delGroup() ## DNSDB::getChildren() # Get a list of all groups whose parent^n is group # Takes a database handle, group ID, reference to an array to put the group IDs in, # and an optional flag to return only immediate children or all children-of-children # default to returning all children # Calls itself sub getChildren { $errstr = ''; my $dbh = shift; my $rootgroup = shift; my $groupdest = shift; my $immed = shift || 'all'; # special break for default group; otherwise we get stuck. if ($rootgroup == 1) { # by definition, group 1 is the Root Of All Groups my $sth = $dbh->prepare("SELECT group_id FROM groups WHERE NOT (group_id=1)". ($immed ne 'all' ? " AND parent_group_id=1" : '')); $sth->execute; while (my @this = $sth->fetchrow_array) { push @$groupdest, @this; } } else { my $sth = $dbh->prepare("SELECT group_id FROM groups WHERE parent_group_id=?"); $sth->execute($rootgroup); return if $sth->rows == 0; my @grouplist; while (my ($group) = $sth->fetchrow_array) { push @$groupdest, $group; getChildren($dbh,$group,$groupdest) if $immed eq 'all'; } } } # end getChildren() ## DNSDB::groupName() # Return the group name based on a group ID # Takes a database handle and the group ID # Returns the group name or undef on failure sub groupName { $errstr = ''; my $dbh = shift; my $groupid = shift; my $sth = $dbh->prepare("SELECT group_name FROM groups WHERE group_id=?"); $sth->execute($groupid); my ($groupname) = $sth->fetchrow_array(); $errstr = $DBI::errstr if !$groupname; return $groupname if $groupname; } # end groupName ## DNSDB::addUser() # sub addUser { $errstr = ''; my $dbh = shift; return ('FAIL',"Need database handle") if !$dbh; my $username = shift; return ('FAIL',"Missing username") if !defined($username); my $group = shift; return ('FAIL',"Missing group") if !defined($group); my $pass = shift; return ('FAIL',"Missing password") if !defined($pass); my $state = shift; return ('FAIL',"Need account status") if !defined($state); my $type = shift || 'u'; # create limited users by default - fwiw, not sure yet how this will interact with ACLs my $fname = shift || $username; my $lname = shift || ''; my $phone = shift || ''; # not going format-check my $sth = $dbh->prepare("SELECT user_id FROM users WHERE username=?"); my $user_id; # quick check to start to see if we've already got one $sth->execute($username); ($user_id) = $sth->fetchrow_array; return ('FAIL', "User already exists") if $user_id; # Allow transactions, and raise an exception on errors so we can catch it later. # Use local to make sure these get "reset" properly on exiting this block local $dbh->{AutoCommit} = 0; local $dbh->{RaiseError} = 1; # Wrap all the SQL in a transaction eval { # insert the user... my $sth = $dbh->prepare("INSERT INTO users (group_id,username,password,firstname,lastname,phone,type,status) ". "VALUES (?,?,?,?,?,?,?,?)"); $sth->execute($group,$username,unix_md5_crypt($pass),$fname,$lname,$phone,$type,$state); # get the ID... $sth = $dbh->prepare("select user_id from users where username=?"); $sth->execute($username); ($user_id) = $sth->fetchrow_array(); ##fixme: add another table to hold name/email for log table? # once we get here, we should have suceeded. $dbh->commit; }; # end eval if ($@) { my $msg = $@; eval { $dbh->rollback; }; return ('FAIL',$msg); } else { return ('OK',$user_id); } } # end addUser ## DNSDB::checkUser() # Check user/pass combo on login sub checkUser { my $dbh = shift; my $user = shift; my $inpass = shift; my $sth = $dbh->prepare("SELECT user_id,group_id,password,firstname,lastname FROM users WHERE username=?"); $sth->execute($user); my ($uid,$gid,$pass,$fname,$lname) = $sth->fetchrow_array; my $loginfailed = 1 if !defined($uid); if ($pass =~ m|^\$1\$([A-Za-z0-9/.]+)\$|) { $loginfailed = 1 if $pass ne unix_md5_crypt($inpass,$1); } else { $loginfailed = 1 if $pass ne $inpass; } # nnnngggg return ($uid, $gid); } # end checkUser ## DNSDB::delUser() # sub delUser { my $dbh = shift; return ('FAIL',"Need database handle") if !$dbh; my $userid = shift; return ('FAIL',"Missing userid") if !defined($userid); my $sth = $dbh->prepare("delete from users where user_id=?"); $sth->execute($userid); return ('FAIL',"Couldn't remove user: ".$sth->errstr) if $sth->err; return ('OK','OK'); } # end delUser ## DNSDB::userFullName() # Return a pretty string! # Takes a user_id and optional printf-ish string to indicate which pieces where: # %u for the username # %f for the first name # %l for the last name # All other text in the passed string will be left as-is. ##fixme: need a "smart" option too, so that missing/null/blank first/last names don't give funky output sub userFullName { $errstr = ''; my $dbh = shift; my $userid = shift; my $fullformat = shift || '%f %l (%u)'; my $sth = $dbh->prepare("select username,firstname,lastname from users where user_id=?"); $sth->execute($userid); my ($uname,$fname,$lname) = $sth->fetchrow_array(); $errstr = $DBI::errstr if !$uname; $fullformat =~ s/\%u/$uname/g; $fullformat =~ s/\%f/$fname/g; $fullformat =~ s/\%l/$lname/g; return $fullformat; } # end userFullName ## DNSDB::userStatus() # Sets and/or returns a user's status # Takes a database handle, user ID and optionally a status argument # Returns undef on errors. sub userStatus { my $dbh = shift; my $id = shift; my $newstatus = shift; return undef if $id !~ /^\d+$/; my $sth; # ooo, fun! let's see what we were passed for status if ($newstatus) { $sth = $dbh->prepare("update users set status=? where user_id=?"); # ass-u-me caller knows what's going on in full if ($newstatus =~ /^[01]$/) { # only two valid for now. $sth->execute($newstatus,$id); } elsif ($newstatus =~ /^usero(?:n|ff)$/) { $sth->execute(($newstatus eq 'useron' ? 1 : 0),$id); } } $sth = $dbh->prepare("select status from users where user_id=?"); $sth->execute($id); my ($status) = $sth->fetchrow_array; return $status; } # end userStatus() ## DNSDB::editRecord() # Change an existing record # Takes a database handle, default/live flag, record ID, and new data and updates the data fields for it sub editRecord { $errstr = ''; my $dbh = shift; my $defflag = shift; my $recid = shift; my $host = shift; my $address = shift; my $distance = shift; my $weight = shift; my $port = shift; my $ttl = shift; } ## DNSDB::getSOA() # Return all suitable fields from an SOA record in separate elements of a hash # Takes a database handle, default/live flag, and group (default) or domain (live) ID sub getSOA { $errstr = ''; my $dbh = shift; my $def = shift; my $id = shift; my %ret; my $sql = "select record_id,host,val,ttl from"; if ($def eq 'def' or $def eq 'y') { $sql .= " default_records where group_id=$id and type=$reverse_typemap{SOA}"; } else { # we're editing a live SOA record; find based on domain $sql .= " records where domain_id=$id and type=$reverse_typemap{SOA}"; } my $sth = $dbh->prepare($sql); $sth->execute; my ($recid,$host,$val,$ttl) = $sth->fetchrow_array(); my ($prins,$contact) = split /:/, $host; my ($refresh,$retry,$expire,$minttl) = split /:/, $val; $ret{recid} = $recid; $ret{ttl} = $ttl; $ret{prins} = $prins; $ret{contact} = $contact; $ret{refresh} = $refresh; $ret{retry} = $retry; $ret{expire} = $expire; $ret{minttl} = $minttl; return %ret; } # end getSOA() ## DNSDB::getRecLine() # Return all data fields for a zone record in separate elements of a hash # Takes a database handle, default/live flag, and record ID sub getRecLine { $errstr = ''; my $dbh = shift; my $def = shift; my $id = shift; my $sql = "select record_id,host,type,val,distance,weight,port,ttl from ". (($def eq 'def' or $def eq 'y') ? 'default_' : ''). "records where record_id=$id"; print "MDEBUG: $sql
\n"; my $sth = $dbh->prepare($sql); $sth->execute; my ($recid,$host,$rtype,$val,$distance,$weight,$port,$ttl) = $sth->fetchrow_array(); if ($sth->err) { $errstr = $DBI::errstr; return undef; } my %ret; $ret{recid} = $recid; $ret{host} = $host; $ret{type} = $rtype; $ret{val} = $val; $ret{distance}= $distance; $ret{weight} = $weight; $ret{port} = $port; $ret{ttl} = $ttl; return %ret; } ##fixme: should use above (getRecLine()) to get lines for below? ## DNSDB::getDomRecs() # Return records for a domain # Takes a database handle, default/live flag, group/domain ID, start, # number of records, sort field, and sort order # Returns a reference to an array of hashes sub getDomRecs { $errstr = ''; my $dbh = shift; my $type = shift; my $id = shift; my $nrecs = shift || 'all'; my $nstart = shift || 0; ## for order, need to map input to column names my $order = shift || 'host'; my $sql = "select record_id,host,type,val,distance,weight,port,ttl from"; if ($type eq 'def' or $type eq 'y') { $sql .= " default_records where group_id=$id"; } else { $sql .= " records where domain_id=$id"; } $sql .= " and not type=$reverse_typemap{SOA} order by $order"; ##fixme: need to set nstart properly (offset is not internally multiplied with limit) $sql .= " limit $nrecs offset ".($nstart*$nrecs) if $nstart ne 'all'; my $sth = $dbh->prepare($sql); $sth->execute; my @retbase; while (my $ref = $sth->fetchrow_hashref()) { push @retbase, $ref; } my $ret = \@retbase; return $ret; } # end getDomRecs() ## DNSDB::addRec() # Add a new record to a domain or a group's default records # Takes a database handle, default/live flag, group/domain ID, # host, type, value, and TTL # Some types require additional detail: "distance" for MX and SRV, # and weight/port for SRV # Returns a status code and detail message in case of error sub addRec { $errstr = ''; my $dbh = shift; my $defrec = shift; my $id = shift; my $host = shift; my $rectype = shift; my $val = shift; my $ttl = shift; my $fields = ($defrec eq 'y' ? 'group_id' : 'domain_id').",host,type,val,ttl"; my $vallen = "?,?,?,?,?"; my @vallist = ($id,$host,$rectype,$val,$ttl); my $dist; if ($rectype == $reverse_typemap{MX} or $rectype == $reverse_typemap{SRV}) { $dist = shift; return ('FAIL',"Need distance for $typemap{$rectype} record") if !defined($dist); $fields .= ",distance"; $vallen .= ",?"; push @vallist, $dist; } my $weight; my $port; if ($rectype == $reverse_typemap{SRV}) { # check for _service._protocol. NB: RFC2782 does not say "MUST"... nor "SHOULD"... # it just says (paraphrased) "... is prepended with _ to prevent DNS collisions" return ('FAIL',"SRV records must begin with _service._protocol") if $host !~ /^_[A-Za-z]+\._[A-Za-z]+\.[a-z0-9-]+/; $weight = shift; $port = shift; return ('FAIL',"Need weight and port for SRV record") if !defined($weight) or !defined($port); $fields .= ",weight,port"; $vallen .= ",?,?"; push @vallist, ($weight,$port); } my $sql = "insert into ".($defrec eq 'y' ? 'default_' : '')."records ($fields) values ($vallen)"; ##fixme: use array for values, replace "vallist" with series of ?,?,? etc # something is bugging me about this... #warn "DEBUG: $sql"; my $sth = $dbh->prepare($sql); $sth->execute(@vallist); return ('FAIL',$sth->errstr) if $sth->err; return ('OK','OK'); } # end addRec() ## DNSDB::updateRec() # Update a record sub updateRec { $errstr = ''; my $dbh = shift; my $defrec = shift; my $id = shift; # all records have these my $host = shift; my $type = shift; my $val = shift; my $ttl = shift; return('FAIL',"Missing standard argument(s)") if !defined($ttl); # only MX and SRV will use these my $dist = 0; my $weight = 0; my $port = 0; if ($type == $reverse_typemap{MX} || $type == $reverse_typemap{SRV}) { $dist = shift; return ('FAIL',"MX or SRV requires distance") if !defined($dist); if ($type == $reverse_typemap{SRV}) { $weight = shift; return ('FAIL',"SRV requires weight") if !defined($weight); $port = shift; return ('FAIL',"SRV requires port") if !defined($port); } } my $sth = $dbh->prepare("UPDATE ".($defrec eq 'y' ? 'default_' : '')."records ". "SET host=?,type=?,val=?,ttl=?,distance=?,weight=?,port=? ". "WHERE record_id=?"); $sth->execute($host,$type,$val,$ttl,$dist,$weight,$port,$id); return ('FAIL',$sth->errstr."
\n$errstr
\n") if $sth->err; return ('OK','OK'); } # end updateRec() ## DNSDB::delRec() # Delete a record. sub delRec { $errstr = ''; my $dbh = shift; my $defrec = shift; my $id = shift; my $sth = $dbh->prepare("delete from ".($defrec eq 'y' ? 'default_' : '')."records where record_id=?"); $sth->execute($id); return ('FAIL',"Couldn't remove record: ".$sth->errstr) if $sth->err; return ('OK','OK'); } # end delRec() ## DNSDB::domStatus() # Sets and/or returns a domain's status # Takes a database handle, domain ID and optionally a status argument # Returns undef on errors. sub domStatus { my $dbh = shift; my $id = shift; my $newstatus = shift; return undef if $id !~ /^\d+$/; my $sth; # ooo, fun! let's see what we were passed for status if ($newstatus) { $sth = $dbh->prepare("update domains set status=? where domain_id=?"); # ass-u-me caller knows what's going on in full if ($newstatus =~ /^[01]$/) { # only two valid for now. $sth->execute($newstatus,$id); } elsif ($newstatus =~ /^domo(?:n|ff)$/) { $sth->execute(($newstatus eq 'domon' ? 1 : 0),$id); } } $sth = $dbh->prepare("select status from domains where domain_id=?"); $sth->execute($id); my ($status) = $sth->fetchrow_array; return $status; } # end domStatus() ## DNSDB::importAXFR # Import a domain via AXFR # Takes AXFR host, domain to transfer, group to put the domain in, # and optionally: # - active/inactive state flag (defaults to active) # - overwrite-SOA flag (defaults to off) # - overwrite-NS flag (defaults to off, doesn't affect subdomain NS records) # Returns a status code (OK, WARN, or FAIL) and message - message should be blank # if status is OK, but WARN includes conditions that are not fatal but should # really be reported. sub importAXFR { my $dbh = shift; my $ifrom_in = shift; my $domain = shift; my $group = shift; my $status = shift || 1; my $rwsoa = shift || 0; my $rwns = shift || 0; ##fixme: add mode to delete&replace, merge+overwrite, merge new? my $nrecs = 0; my $soaflag = 0; my $nsflag = 0; my $warnmsg = ''; my $ifrom; # choke on possible bad setting in ifrom # IPv4 and v6, and valid hostnames! ($ifrom) = ($ifrom_in =~ /^([0-9a-f\:.]+|[0-9a-z_.-]+)$/i); return ('FAIL', "Bad AXFR source host $ifrom") unless ($ifrom) = ($ifrom_in =~ /^([0-9a-f\:.]+|[0-9a-z_.-]+)$/i); # Allow transactions, and raise an exception on errors so we can catch it later. # Use local to make sure these get "reset" properly on exiting this block local $dbh->{AutoCommit} = 0; local $dbh->{RaiseError} = 1; my $sth = $dbh->prepare("SELECT domain_id FROM domains WHERE domain=?"); my $dom_id; # quick check to start to see if we've already got one $sth->execute($domain); ($dom_id) = $sth->fetchrow_array; return ('FAIL', "Domain already exists") if $dom_id; eval { # can't do this, can't nest transactions. sigh. #my ($dcode, $dmsg) = addDomain(dbh, domain, group, status); ##fixme: serial my $sth = $dbh->prepare("INSERT INTO domains (domain,group_id,status) VALUES (?,?,?)"); $sth->execute($domain,$group,$status); ## bizarre DBI<->Net::DNS interaction bug: ## sometimes a zone will cause an immediate commit-and-exit (sort of) of the while() ## fixed, apparently I was doing *something* odd, but not certain what it was that ## caused a commit instead of barfing # get domain id so we can do the records $sth = $dbh->prepare("SELECT domain_id FROM domains WHERE domain=?"); $sth->execute($domain); ($dom_id) = $sth->fetchrow_array(); my $res = Net::DNS::Resolver->new; $res->nameservers($ifrom); $res->axfr_start($domain) or die "Couldn't begin AXFR\n"; while (my $rr = $res->axfr_next()) { my $type = $rr->type; my $sql = "INSERT INTO records (domain_id,host,type,ttl,val"; my $vallen = "?,?,?,?,?"; $soaflag = 1 if $type eq 'SOA'; $nsflag = 1 if $type eq 'NS'; my @vallist = ($dom_id, $rr->name, $reverse_typemap{$type}, $rr->ttl); # "Primary" types: # A, NS, CNAME, SOA, PTR(warn in forward), MX, TXT, AAAA, SRV, A6(ob), SPF # maybe KEY # nasty big ugly case-like thing here, since we have to do *some* different # processing depending on the record. le sigh. if ($type eq 'A') { push @vallist, $rr->address; } elsif ($type eq 'NS') { # hmm. should we warn here if subdomain NS'es are left alone? next if ($rwns && ($rr->name eq $domain)); push @vallist, $rr->nsdname; $nsflag = 1; } elsif ($type eq 'CNAME') { push @vallist, $rr->cname; } elsif ($type eq 'SOA') { next if $rwsoa; $vallist[1] = $rr->mname.":".$rr->rname; push @vallist, ($rr->refresh.":".$rr->retry.":".$rr->expire.":".$rr->minimum); $soaflag = 1; } elsif ($type eq 'PTR') { # hmm. PTR records should not be in forward zones. } elsif ($type eq 'MX') { $sql .= ",distance"; $vallen .= ",?"; push @vallist, $rr->exchange; push @vallist, $rr->preference; } elsif ($type eq 'TXT') { ##fixme: Net::DNS docs say this should be deprecated for rdatastr() or char_str_list(), ## but don't really seem enthusiastic about it. push @vallist, $rr->txtdata; } elsif ($type eq 'SPF') { ##fixme: and the same caveat here, since it is apparently a clone of ::TXT push @vallist, $rr->txtdata; } elsif ($type eq 'AAAA') { push @vallist, $rr->address; } elsif ($type eq 'SRV') { $sql .= ",distance,weight,port" if $type eq 'SRV'; $vallen .= ",?,?,?" if $type eq 'SRV'; push @vallist, $rr->target; push @vallist, $rr->priority; push @vallist, $rr->weight; push @vallist, $rr->port; } elsif ($type eq 'KEY') { # we don't actually know what to do with these... push @vallist, ($rr->flags.":".$rr->protocol.":".$rr->algorithm.":".$rr->key.":".$rr->keytag.":".$rr->privatekeyname); } else { push @vallist, $rr->rdatastr; # Finding a different record type is not fatal.... just problematic. # We may not be able to export it correctly. $warnmsg .= "Unusual record ".$rr->name." ($type) found\n"; } # BIND supports: # A CNAME HINFO MB(ex) MD(ob) MF(ob) MG(ex) MINFO(ex) MR(ex) MX NS NULL # PTR SOA TXT WKS AFSDB(ex) ISDN(ex) RP(ex) RT(ex) X25(ex) PX # ... if one can ever find the right magic to format them correctly # Net::DNS supports: # RRSIG SIG NSAP NS NIMLOC NAPTR MX MR MINFO MG MB LOC ISDN IPSECKEY HINFO # EID DNAME CNAME CERT APL AFSDB AAAA A DS NXT NSEC3PARAM NSEC3 NSEC KEY # DNSKEY DLV X25 TXT TSIG TKEY SSHFP SRV SPF SOA RT RP PX PTR NULL APL::AplItem $sth = $dbh->prepare($sql.") VALUES (".$vallen.")") or die "problem preparing record insert SQL\n"; $sth->execute(@vallist) or die "failed to insert ".$rr->string.": ".$sth->errstr."\n"; $nrecs++; } # while axfr_next # Overwrite SOA record if ($rwsoa) { $soaflag = 1; my $sthgetsoa = $dbh->prepare("SELECT host,val,ttl FROM default_records WHERE group_id=? AND type=?"); my $sthputsoa = $dbh->prepare("INSERT INTO records (domain_id,host,type,val,ttl) VALUES (?,?,?,?,?)"); $sthgetsoa->execute($group,$reverse_typemap{SOA}); while (my ($host,$val,$ttl) = $sthgetsoa->fetchrow_array()) { $host =~ s/DOMAIN/$domain/g; $val =~ s/DOMAIN/$domain/g; $sthputsoa->execute($dom_id,$host,$reverse_typemap{SOA},$val,$ttl); } } # Overwrite NS records if ($rwns) { $nsflag = 1; my $sthgetns = $dbh->prepare("SELECT host,val,ttl FROM default_records WHERE group_id=? AND type=?"); my $sthputns = $dbh->prepare("INSERT INTO records (domain_id,host,type,val,ttl) VALUES (?,?,?,?,?)"); $sthgetns->execute($group,$reverse_typemap{NS}); while (my ($host,$val,$ttl) = $sthgetns->fetchrow_array()) { $host =~ s/DOMAIN/$domain/g; $val =~ s/DOMAIN/$domain/g; $sthputns->execute($dom_id,$host,$reverse_typemap{NS},$val,$ttl); } } die "No records found; either $ifrom is not authoritative or doesn't allow transfers\n" if !$nrecs; die "Bad zone: No SOA record!\n" if !$soaflag; die "Bad zone: No NS records!\n" if !$nsflag; $dbh->commit; }; if ($@) { my $msg = $@; eval { $dbh->rollback; }; return ('FAIL',$msg." $warnmsg"); } else { return ('WARN', $warnmsg) if $warnmsg; return ('OK',"ook"); } # it should be impossible to get here. return ('WARN',"OOOK!"); } # end importAXFR() # shut Perl up 1;