source: trunk/DNSDB.pm@ 12

Last change on this file since 12 was 10, checked in by Kris Deugau, 15 years ago

/trunk

Move domain list generation into a sub; it's needed from several places
Confirm domain deletion works as expected; reenable actual deletion.
Misc comment-docs

  • Property svn:keywords set to Date Rev Author Id
File size: 12.9 KB
Line 
1# dns/trunk/DNSDB.pm
2# Abstraction functions for DNS administration
3###
4# SVN revision info
5# $Date: 2009-09-10 17:34:34 +0000 (Thu, 10 Sep 2009) $
6# SVN revision $Rev: 10 $
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;
17#use Net::SMTP;
18#use NetAddr::IP qw( Compact );
19#use POSIX;
20use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
21
22$VERSION = 0.1;
23@ISA = qw(Exporter);
24@EXPORT_OK = qw(
25 &initGlobals &connectDB &finish &addDomain &delDomain &domainName &getSOA &getRecLine &getDomRecs
26 &addRec &delRec &domStatus
27 %typemap %reverse_typemap
28 );
29
30@EXPORT = (); # Export nothing by default.
31%EXPORT_TAGS = ( ALL => [qw(
32 &initGlobals &connectDB &finish &addDomain &delDomain &domainName &getSOA &getRecLine &getDomRecs
33 &addRec &delRec &domStatus
34 %typemap %reverse_typemap
35 )]
36 );
37
38our $group = 1;
39our $errstr = '';
40
41# Halfway sane defaults for SOA, TTL, etc.
42our %def = qw (
43 contact hostmaster.DOMAIN
44 prins ns1.myserver.com
45 soattl 86400
46 refresh 10800
47 retry 3600
48 expire 604800
49 minttl 10800
50 ttl 10800
51);
52
53# DNS record type map and reverse map.
54# loaded from the database, from http://www.iana.org/assignments/dns-parameters
55our %typemap;
56our %reverse_typemap;
57
58##
59## Initialization and cleanup subs
60##
61
62## DNSDB::connectDB()
63# Creates connection to DNS database.
64# Requires the database name, username, and password.
65# Returns a handle to the db.
66# Set up for a PostgreSQL db; could be any transactional DBMS with the
67# right changes.
68sub connectDB {
69 $errstr = '';
70 my ($dbname,$user,$pass) = @_;
71 my $dbh;
72 my $DSN = "DBI:Pg:dbname=$dbname";
73
74 my $host = shift;
75 $DSN .= ";host=$host" if $host;
76
77# Note that we want to autocommit by default, and we will turn it off locally as necessary.
78# We may not want to print gobbledygook errors; YMMV. Have to ponder that further.
79 $dbh = DBI->connect($DSN, $user, $pass, {
80 AutoCommit => 1,
81 PrintError => 0
82 })
83 or return (undef, $DBI::errstr) if(!$dbh);
84
85# Return here if we can't select. Note that this indicates a
86# problem executing the select.
87 my $sth = $dbh->prepare("select group_id from groups limit 1");
88 $sth->execute();
89 return (undef,$DBI::errstr) if ($sth->err);
90
91# See if the select returned anything (or null data). This should
92# succeed if the select executed, but...
93 $sth->fetchrow();
94 return (undef,$DBI::errstr) if ($sth->err);
95
96 $sth->finish;
97
98# If we get here, we should be OK.
99 return ($dbh,"DB connection OK");
100} # end connectDB
101
102
103## DNSDB::finish()
104# Cleans up after database handles and so on.
105# Requires a database handle
106sub finish {
107 my $dbh = $_[0];
108 $dbh->disconnect;
109} # end finish
110
111
112## DNSDB::initGlobals()
113# Initialize global variables
114# NB: this does NOT include web-specific session variables!
115# Requires a database handle
116sub initGlobals {
117 my $dbh = shift;
118
119# load system-wide site defaults and things from config file
120 open SYSDEFAULTS, "</etc/dnsdb.conf";
121##fixme - error check!
122 while (<SYSDEFAULTS>) {
123 next if /^\s*#/;
124 $def{contact} = $1 if /contact ?= ?([a-z0-9_.-]+)/i;
125 $def{prins} = $1 if /prins ?= ?([a-z0-9_.-]+)/i;
126 $def{soattl} = $1 if /soattl ?= ?([a-z0-9_.-]+)/i;
127 $def{refresh} = $1 if /refresh ?= ?([a-z0-9_.-]+)/i;
128 $def{retry} = $1 if /retry ?= ?([a-z0-9_.-]+)/i;
129 $def{expire} = $1 if /expire ?= ?([a-z0-9_.-]+)/i;
130 $def{minttl} = $1 if /minttl ?= ?([a-z0-9_.-]+)/i;
131 $def{ttl} = $1 if /ttl ?= ?([a-z0-9_.-]+)/i;
132##fixme? load DB user/pass from config file?
133 }
134# load from database
135 my $sth = $dbh->prepare("select val,name from rectypes");
136 $sth->execute;
137 while (my ($recval,$recname) = $sth->fetchrow_array()) {
138 $typemap{$recval} = $recname;
139 $reverse_typemap{$recname} = $recval;
140 }
141} # end initGlobals
142
143
144##
145## Processing subs
146##
147
148## DNSDB::addDomain()
149# Add a domain
150# Takes a database handle, domain name, numeric group, and boolean(ish) state (active/inactive)
151# Returns a status code and message
152sub addDomain {
153 $errstr = '';
154 my $dbh = shift;
155 return ('FAIL',"Need database handle") if !$dbh;
156 my $domain = shift;
157 return ('FAIL',"Need domain") if !defined($domain);
158 my $group = shift;
159 return ('FAIL',"Need group") if !defined($group);
160 my $state = shift;
161 return ('FAIL',"Need domain status") if !defined($state);
162
163 my $dom_id;
164
165 # Allow transactions, and raise an exception on errors so we can catch it later.
166 # Use local to make sure these get "reset" properly on exiting this block
167 local $dbh->{AutoCommit} = 0;
168 local $dbh->{RaiseError} = 1;
169
170 # Wrap all the SQL in a transaction
171 eval {
172 # insert the domain...
173 my $sth = $dbh->prepare("insert into domains (domain,group_id,status) values (?,?,?)");
174 $sth->execute($domain,$group,$state);
175
176 # get the ID...
177 $sth = $dbh->prepare("select domain_id from domains where domain='$domain'");
178 $sth->execute;
179 ($dom_id) = $sth->fetchrow_array();
180
181 # ... and now we construct the standard records from the default set. NB: group should be variable.
182 $sth = $dbh->prepare("select host,type,val,distance,weight,port,ttl from default_records where group_id=$group");
183 my $sth_in = $dbh->prepare("insert into records (domain_id,host,type,val,distance,weight,port,ttl)".
184 " values ($dom_id,?,?,?,?,?,?,?)");
185 $sth->execute;
186 while (my ($host,$type,$val,$dist,$weight,$port,$ttl) = $sth->fetchrow_array()) {
187 $host =~ s/DOMAIN/$domain/g;
188 $sth_in->execute($host,$type,$val,$dist,$weight,$port,$ttl);
189 }
190
191 # once we get here, we should have suceeded.
192 $dbh->commit;
193 }; # end eval
194
195 if ($@) {
196 my $msg = $@;
197 eval { $dbh->rollback; };
198 return ('FAIL',$msg);
199 } else {
200 return ('OK',$dom_id);
201 }
202} # end addDomain
203
204
205## DNSDB::delDomain()
206# Delete a domain.
207# for now, just delete the records, then the domain.
208# later we may want to archive it in some way instead (status code 2, for example?)
209sub delDomain {
210 my $dbh = shift;
211 my $domid = shift;
212
213 # Allow transactions, and raise an exception on errors so we can catch it later.
214 # Use local to make sure these get "reset" properly on exiting this block
215 local $dbh->{AutoCommit} = 0;
216 local $dbh->{RaiseError} = 1;
217
218 # Wrap all the SQL in a transaction
219 eval {
220 my $sth = $dbh->prepare("delete from records where domain_id=?");
221 $sth->execute($domid);
222 $sth = $dbh->prepare("delete from domains where domain_id=?");
223 $sth->execute($domid);
224
225 # once we get here, we should have suceeded.
226 $dbh->commit;
227 }; # end eval
228
229 if ($@) {
230 my $msg = $@;
231 eval { $dbh->rollback; };
232 return ('FAIL',$msg);
233 } else {
234 return ('OK','OK');
235 }
236
237} # end delDomain()
238
239
240## DNSDB::domainName()
241# Return the domain name based on a domain ID
242# Takes a database handle and the domain ID
243# Returns the domain name or undef on failure
244sub domainName {
245 $errstr = '';
246 my $dbh = shift;
247 my $domid = shift;
248 my $sth = $dbh->prepare("select domain from domains where domain_id=?");
249 $sth->execute($domid);
250 my ($domname) = $sth->fetchrow_array();
251 $errstr = $DBI::errstr if !$domname;
252 return $domname if $domname;
253} # end domainName
254
255
256## DNSDB::editRecord()
257# Change an existing record
258# Takes a database handle, default/live flag, record ID, and new data and updates the data fields for it
259sub editRecord {
260 $errstr = '';
261 my $dbh = shift;
262 my $defflag = shift;
263 my $recid = shift;
264 my $host = shift;
265 my $address = shift;
266 my $distance = shift;
267 my $weight = shift;
268 my $port = shift;
269 my $ttl = shift;
270}
271
272
273## DNSDB::getSOA()
274# Return all suitable fields from an SOA record in separate elements of a hash
275# Takes a database handle, default/live flag, and group (default) or domain (live) ID
276sub getSOA {
277 $errstr = '';
278 my $dbh = shift;
279 my $def = shift;
280 my $id = shift;
281 my %ret;
282
283 my $sql = "select record_id,host,val,ttl from";
284 if ($def eq 'def' or $def eq 'y') {
285 $sql .= " default_records where group_id=$id and type=$reverse_typemap{SOA}";
286 } else {
287 # we're editing a live SOA record; find based on domain
288 $sql .= " records where domain_id=$id and type=$reverse_typemap{SOA}";
289 }
290#print "getSOA DEBUG: $sql<br>\n";
291 my $sth = $dbh->prepare($sql);
292 $sth->execute;
293
294 my ($recid,$host,$val,$ttl) = $sth->fetchrow_array();
295 my ($prins,$contact) = split /:/, $host;
296 my ($refresh,$retry,$expire,$minttl) = split /:/, $val;
297
298 $ret{recid} = $recid;
299 $ret{ttl} = $ttl;
300 $ret{prins} = $prins;
301 $ret{contact} = $contact;
302 $ret{refresh} = $refresh;
303 $ret{retry} = $retry;
304 $ret{expire} = $expire;
305 $ret{minttl} = $minttl;
306
307 return %ret;
308} # end getSOA()
309
310
311## DNSDB::getRecLine()
312# Return all data fields for a zone record in separate elements of a hash
313# Takes a database handle, default/live flag, and record ID
314sub getRecLine {
315 $errstr = '';
316 my $dbh = shift;
317 my $def = shift;
318 my $id = shift;
319
320 my $sql = "select record_id,host,type,val,distance,weight,port,ttl from ".
321 (($def eq 'def' or $def eq 'y') ? 'default_' : '').
322 "records where record_id=$id";
323print "MDEBUG: $sql<br>\n";
324 my $sth = $dbh->prepare($sql);
325 $sth->execute;
326
327 my ($recid,$host,$rtype,$val,$distance,$weight,$port,$ttl) = $sth->fetchrow_array();
328
329 if ($sth->err) {
330 $errstr = $DBI::errstr;
331 return undef;
332 }
333 my %ret;
334 $ret{recid} = $recid;
335 $ret{host} = $host;
336 $ret{type} = $rtype;
337 $ret{val} = $val;
338 $ret{distance}= $distance;
339 $ret{weight} = $weight;
340 $ret{port} = $port;
341 $ret{ttl} = $ttl;
342
343 return %ret;
344}
345
346
347##fixme: should use above (getRecLine()) to get lines for below?
348## DNSDB::getDomRecs()
349# Return records for a domain
350# Takes a database handle, default/live flag, group/domain ID, start,
351# number of records, sort field, and sort order
352# Returns a reference to an array of hashes
353sub getDomRecs {
354 $errstr = '';
355 my $dbh = shift;
356 my $type = shift;
357 my $id = shift;
358 my $nrecs = shift || 'all';
359 my $nstart = shift || 0;
360
361## for order, need to map input to column names
362 my $order = shift || 'host';
363
364 my $sql = "select record_id,host,type,val,distance,weight,port,ttl from";
365 if ($type eq 'def' or $type eq 'y') {
366 $sql .= " default_records where group_id=$id";
367 } else {
368 $sql .= " records where domain_id=$id";
369 }
370 $sql .= " and not type=$reverse_typemap{SOA} order by $order";
371 $sql .= " limit $nrecs offset $nstart" if $nstart ne 'all';
372
373 my $sth = $dbh->prepare($sql);
374 $sth->execute;
375
376 my @retbase;
377 while (my $ref = $sth->fetchrow_hashref()) {
378 push @retbase, $ref;
379 }
380
381 my $ret = \@retbase;
382 return $ret;
383} # end getDomRecs()
384
385
386## DNSDB::addRec()
387# Add a new record to a domain or a group's default records
388# Takes a database handle, default/live flag, group/domain ID,
389# host, type, value, and TTL
390# Some types require additional detail: "distance" for MX and SRV,
391# and weight/port for SRV
392# Returns a status code and detail message in case of error
393sub addRec {
394 $errstr = '';
395 my $dbh = shift;
396 my $defrec = shift;
397 my $id = shift;
398
399 my $host = shift;
400 my $rectype = shift;
401 my $val = shift;
402 my $ttl = shift;
403
404 my $fields = ($defrec eq 'y' ? 'group_id' : 'domain_id').",host,type,val,ttl";
405 my $vallist = "$id,'$host',$rectype,'$val',$ttl";
406
407 my $dist;
408 if ($rectype == $reverse_typemap{MX} or $rectype == $reverse_typemap{SRV}) {
409 $dist = shift;
410 return ('FAIL',"Need distance for $typemap{$rectype} record") if !defined($dist);
411 $fields .= ",distance";
412 $vallist .= ",$dist";
413 }
414 my $weight;
415 my $port;
416 if ($rectype == $reverse_typemap{SRV}) {
417 $weight = shift;
418 $port = shift;
419 return ('FAIL',"Need weight and port for SRV record") if !defined($weight) or !defined($port);
420 $fields .= ",weight,port";
421 $vallist .= ",$weight,$port";
422 }
423
424 my $sql = "insert into ".($defrec eq 'y' ? 'default_' : '')."records ($fields) values ($vallist)";
425# something is bugging me about this...
426print "DEBUG: $sql<br>\n";
427 my $sth = $dbh->prepare($sql);
428 $sth->execute;
429
430 return ('FAIL',$sth->errstr) if $sth->err;
431
432 return ('OK','OK');
433} # end addRec()
434
435
436## DNSDB::delRec()
437# Delete a record.
438sub delRec {
439 $errstr = '';
440 my $dbh = shift;
441 my $defrec = shift;
442 my $id = shift;
443
444 my $sth = $dbh->prepare("delete from ".($defrec eq 'y' ? 'default_' : '')."records where record_id=?");
445 $sth->execute($id);
446
447 return ('FAIL',$sth->errstr) if $sth->err;
448
449 return ('OK','OK');
450} # end delRec()
451
452
453## DNSDB::domStatus()
454# Sets and/or returns a domain's status
455# Takes a database handle, domain ID and optionally a status argument
456# Returns undef on errors.
457sub domStatus {
458 my $dbh = shift;
459 my $id = shift;
460 my $newstatus = shift;
461
462 return undef if $id !~ /^\d+$/;
463
464 my $sth;
465
466# ooo, fun! let's see what we were passed for status
467 if ($newstatus) {
468 $sth = $dbh->prepare("update domains set status=? where domain_id=?");
469 # ass-u-me caller knows what's going on in full
470 if ($newstatus =~ /^[01]$/) { # only two valid for now.
471 $sth->execute($newstatus,$id);
472 } elsif ($newstatus =~ /^domo(?:n|ff)$/) {
473 $sth->execute(($newstatus eq 'domon' ? 1 : 0),$id);
474 }
475 }
476
477 $sth = $dbh->prepare("select status from domains where domain_id=?");
478 $sth->execute($id);
479 my ($status) = $sth->fetchrow_array;
480 return $status;
481} # end domStatus()
482
483
484# shut Perl up
4851;
Note: See TracBrowser for help on using the repository browser.