source: trunk/DNSDB.pm@ 7

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

/trunk

checkpoint

  • 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-04 21:53:55 +0000 (Fri, 04 Sep 2009) $
6# SVN revision $Rev: 7 $
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##fixme
219return ('OK',"don't wanna!");
220
221 # Wrap all the SQL in a transaction
222 eval {
223 my $sth = $dbh->prepare("delete from records where domain_id=?");
224 $sth->execute($domid);
225 $sth = $dbh->prepare("delete from domains where domain_id=?");
226 $sth->execute($domid);
227
228 # once we get here, we should have suceeded.
229 $dbh->commit;
230 }; # end eval
231
232 if ($@) {
233 my $msg = $@;
234 eval { $dbh->rollback; };
235 return ('FAIL',$msg);
236 } else {
237 return ('OK','OK');
238 }
239
240} # end delDomain()
241
242
243## DNSDB::domainName()
244# Return the domain name based on a domain ID
245# Takes a database handle and the domain ID
246# Returns the domain name or undef on failure
247sub domainName {
248 $errstr = '';
249 my $dbh = shift;
250 my $domid = shift;
251 my $sth = $dbh->prepare("select domain from domains where domain_id=?");
252 $sth->execute($domid);
253 my ($domname) = $sth->fetchrow_array();
254 $errstr = $DBI::errstr if !$domname;
255 return $domname if $domname;
256} # end domainName
257
258
259## DNSDB::editRecord()
260# Change an existing record
261# Takes a database handle, default/live flag, record ID, and new data and updates the data fields for it
262sub editRecord {
263 $errstr = '';
264 my $dbh = shift;
265 my $defflag = shift;
266 my $recid = shift;
267 my $host = shift;
268 my $address = shift;
269 my $distance = shift;
270 my $weight = shift;
271 my $port = shift;
272 my $ttl = shift;
273}
274
275
276## DNSDB::getSOA()
277# Return all suitable fields from an SOA record in separate elements of a hash
278# Takes a database handle, default/live flag, and group (default) or domain (live) ID
279sub getSOA {
280 $errstr = '';
281 my $dbh = shift;
282 my $def = shift;
283 my $id = shift;
284 my %ret;
285
286 my $sql = "select record_id,host,val,ttl from";
287 if ($def eq 'def' or $def eq 'y') {
288 $sql .= " default_records where group_id=$id and type=$reverse_typemap{SOA}";
289 } else {
290 # we're editing a live SOA record; find based on domain
291 $sql .= " records where domain_id=$id and type=$reverse_typemap{SOA}";
292 }
293#print "getSOA DEBUG: $sql<br>\n";
294 my $sth = $dbh->prepare($sql);
295 $sth->execute;
296
297 my ($recid,$host,$val,$ttl) = $sth->fetchrow_array();
298 my ($prins,$contact) = split /:/, $host;
299 my ($refresh,$retry,$expire,$minttl) = split /:/, $val;
300
301 $ret{recid} = $recid;
302 $ret{ttl} = $ttl;
303 $ret{prins} = $prins;
304 $ret{contact} = $contact;
305 $ret{refresh} = $refresh;
306 $ret{retry} = $retry;
307 $ret{expire} = $expire;
308 $ret{minttl} = $minttl;
309
310 return %ret;
311} # end getSOA()
312
313
314## DNSDB::getRecLine()
315# Return all data fields for a zone record in separate elements of a hash
316# Takes a database handle, default/live flag, and record ID
317sub getRecLine {
318 $errstr = '';
319 my $dbh = shift;
320 my $def = shift;
321 my $id = shift;
322
323 my $sql = "select record_id,host,type,val,distance,weight,port,ttl from ".
324 (($def eq 'def' or $def eq 'y') ? 'default_' : '').
325 "records where record_id=$id";
326print "MDEBUG: $sql<br>\n";
327 my $sth = $dbh->prepare($sql);
328 $sth->execute;
329
330 my ($recid,$host,$rtype,$val,$distance,$weight,$port,$ttl) = $sth->fetchrow_array();
331
332 if ($sth->err) {
333 $errstr = $DBI::errstr;
334 return undef;
335 }
336 my %ret;
337 $ret{recid} = $recid;
338 $ret{host} = $host;
339 $ret{type} = $rtype;
340 $ret{val} = $val;
341 $ret{distance}= $distance;
342 $ret{weight} = $weight;
343 $ret{port} = $port;
344 $ret{ttl} = $ttl;
345
346 return %ret;
347}
348
349
350##fixme: should use above (getRecLine()) to get lines for below?
351## DNSDB::getDomRecs()
352# Return records for a domain
353# Takes a database handle, default/live flag, group/domain ID, start,
354# number of records, sort field, and sort order
355# Returns a reference to an array of hashes
356sub getDomRecs {
357 $errstr = '';
358 my $dbh = shift;
359 my $type = shift;
360 my $id = shift;
361 my $nrecs = shift || 'all';
362 my $nstart = shift || 0;
363
364## for order, need to map input to column names
365 my $order = shift || 'host';
366
367 my $sql = "select record_id,host,type,val,distance,weight,port,ttl from";
368 if ($type eq 'def' or $type eq 'y') {
369 $sql .= " default_records where group_id=$id";
370 } else {
371 $sql .= " records where domain_id=$id";
372 }
373 $sql .= " and not type=$reverse_typemap{SOA} order by $order";
374 $sql .= " limit $nrecs offset $nstart" if $nstart ne 'all';
375
376 my $sth = $dbh->prepare($sql);
377 $sth->execute;
378
379 my @retbase;
380 while (my $ref = $sth->fetchrow_hashref()) {
381 push @retbase, $ref;
382 }
383
384 my $ret = \@retbase;
385 return $ret;
386} # end getDomRecs()
387
388
389## DNSDB::addRec()
390# Add a new record to a domain or a group's default records
391# Takes a database handle, default/live flag, group/domain ID,
392# host, type, value, and TTL
393# Some types require additional detail: "distance" for MX and SRV,
394# and weight/port for SRV
395# Returns a status code and detail message in case of error
396sub addRec {
397 $errstr = '';
398 my $dbh = shift;
399 my $defrec = shift;
400 my $id = shift;
401
402 my $host = shift;
403 my $rectype = shift;
404 my $val = shift;
405 my $ttl = shift;
406
407 my $fields = ($defrec eq 'y' ? 'group_id' : 'domain_id').",host,type,val,ttl";
408 my $vallist = "$id,'$host',$rectype,'$val',$ttl";
409
410 my $dist;
411 if ($rectype == $reverse_typemap{MX} or $rectype == $reverse_typemap{SRV}) {
412 $dist = shift;
413 return ('FAIL',"Need distance for $typemap{$rectype} record") if !defined($dist);
414 $fields .= ",distance";
415 $vallist .= ",$dist";
416 }
417 my $weight;
418 my $port;
419 if ($rectype == $reverse_typemap{SRV}) {
420 $weight = shift;
421 $port = shift;
422 return ('FAIL',"Need weight and port for SRV record") if !defined($weight) or !defined($port);
423 $fields .= ",weight,port";
424 $vallist .= ",$weight,$port";
425 }
426
427 my $sql = "insert into ".($defrec eq 'y' ? 'default_' : '')."records ($fields) values ($vallist)";
428# something is bugging me about this...
429print "DEBUG: $sql<br>\n";
430 my $sth = $dbh->prepare($sql);
431 $sth->execute;
432
433 return ('FAIL',$sth->errstr) if $sth->err;
434
435 return ('OK','OK');
436} # end addRec()
437
438
439## DNSDB::delRec()
440# Delete a record.
441sub delRec {
442 $errstr = '';
443 my $dbh = shift;
444 my $defrec = shift;
445 my $id = shift;
446
447 my $sth = $dbh->prepare("delete from ".($defrec eq 'y' ? 'default_' : '')."records where record_id=?");
448 $sth->execute($id);
449
450 return ('FAIL',$sth->errstr) if $sth->err;
451
452 return ('OK','OK');
453} # end delRec()
454
455
456## DNSDB::domStatus()
457# Sets and/or returns a domain's status
458# Takes a database handle, domain ID and optionally a status argument
459# Returns undef on errors.
460sub domStatus {
461 my $dbh = shift;
462 my $id = shift;
463 my $newstatus = shift;
464
465 return undef if $id !~ /^\d+$/;
466
467 my $sth;
468
469# ooo, fun! let's see what we were passed for status
470 if ($newstatus) {
471 $sth = $dbh->prepare("update domains set status=? where domain_id=?");
472 # ass-u-me caller knows what's going on in full
473 if ($newstatus =~ /^[01]$/) { # only two valid for now.
474 $sth->execute($newstatus,$id);
475 } elsif ($newstatus =~ /^domo(?:n|ff)$/) {
476 $sth->execute(($newstatus eq 'domon' ? 1 : 0),$id);
477 }
478 }
479
480 $sth = $dbh->prepare("select status from domains where domain_id=?");
481 $sth->execute($id);
482 my ($status) = $sth->fetchrow_array;
483 return $status;
484} # end domStatus()
485
486
487# shut Perl up
4881;
Note: See TracBrowser for help on using the repository browser.