source: trunk/DNSDB.pm@ 16

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

/trunk

checkpoint

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