source: trunk/DNSDB.pm@ 18

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

/trunk

checkpoint

  • Property svn:keywords set to Date Rev Author Id
File size: 16.8 KB
Line 
1# dns/trunk/DNSDB.pm
2# Abstraction functions for DNS administration
3###
4# SVN revision info
5# $Date: 2009-10-08 21:29:50 +0000 (Thu, 08 Oct 2009) $
6# SVN revision $Rev: 18 $
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 &addGroup &grpName &getSOA
26 &getRecLine &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 &addGroup &grpName &getSOA
33 &getRecLine &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::addGroup()
259# Add a group
260# Takes a database handle, group name, parent group, and template-vs-cloneme flag
261# Returns a status code and message
262sub addGroup {
263 $errstr = '';
264 my $dbh = shift;
265 my $grpname = shift;
266 my $pargrp = shift;
267
268 # 0 indicates "template", hardcoded.
269 # Any other value clones that group's default records, if it exists.
270 my $torc = shift || 0;
271
272 # Allow transactions, and raise an exception on errors so we can catch it later.
273 # Use local to make sure these get "reset" properly on exiting this block
274 local $dbh->{AutoCommit} = 0;
275 local $dbh->{RaiseError} = 1;
276
277 # Wrap all the SQL in a transaction
278 eval {
279 my $sth = $dbh->prepare("INSERT INTO groups (parent_group_id,group_name) VALUES (?,?)");
280 $sth->execute($pargrp,$grpname);
281
282 $sth = $dbh->prepare("SELECT group_id FROM groups WHERE group_name=?");
283 $sth->execute($grpname);
284 my ($grpid) = $sth->fetchrow_array();
285
286 $sth = $dbh->prepare("INSERT INTO default_records (group_id,host,type,val,distance,weight,port,ttl) ".
287 "VALUES ($grpid,?,?,?,?,?,?,?)");
288 if ($torc) {
289 my $sth2 = $dbh->prepare("SELECT host,type,val,distance,weight,port,ttl FROM default_records WHERE group_id=?");
290 while (my @clonedata = $sth2->fetchrow_array) {
291 $sth->execute(@clonedata);
292 }
293 } else {
294 # reasonable basic defaults for SOA, MX, NS, and minimal hosting
295 # could load from a config file, but somewhere along the line we need hardcoded bits.
296 $sth->execute('ns1.example.com:hostmaster.example.com', 6, '10800:3600:604800:10800', 0, 0, 0, 86400);
297 $sth->execute('DOMAIN', 1, '192.168.4.2', 0, 0, 0, 7200);
298 $sth->execute('DOMAIN', 15, 'mx.example.com', 10, 0, 0, 7200);
299 $sth->execute('DOMAIN', 2, 'ns1.example.com', 0, 0, 0, 7200);
300 $sth->execute('DOMAIN', 2, 'ns2.example.com', 0, 0, 0, 7200);
301 $sth->execute('www.DOMAIN', 5, 'DOMAIN', 0, 0, 0, 7200);
302 }
303
304die "epic FAIL.. hahahah, just testing!\n";
305 # once we get here, we should have suceeded.
306 $dbh->commit;
307 }; # end eval
308
309 if ($@) {
310 my $msg = $@;
311 eval { $dbh->rollback; };
312 return ('FAIL',$msg);
313 } else {
314 return ('OK','OK');
315 }
316
317} # end addGroup()
318
319
320## DNSDB::grpName()
321# Return the group name based on a group ID
322# Takes a database handle and the group ID
323# Returns the group name or undef on failure
324sub grpName {
325 $errstr = '';
326 my $dbh = shift;
327 my $grpid = shift;
328 my $sth = $dbh->prepare("select name from groups where group_id=?");
329 $sth->execute($grpid);
330 my ($grpname) = $sth->fetchrow_array();
331 $errstr = $DBI::errstr if !$grpname;
332 return $grpname if $grpname;
333} # end domainName
334
335
336## DNSDB::editRecord()
337# Change an existing record
338# Takes a database handle, default/live flag, record ID, and new data and updates the data fields for it
339sub editRecord {
340 $errstr = '';
341 my $dbh = shift;
342 my $defflag = shift;
343 my $recid = shift;
344 my $host = shift;
345 my $address = shift;
346 my $distance = shift;
347 my $weight = shift;
348 my $port = shift;
349 my $ttl = shift;
350}
351
352
353## DNSDB::getSOA()
354# Return all suitable fields from an SOA record in separate elements of a hash
355# Takes a database handle, default/live flag, and group (default) or domain (live) ID
356sub getSOA {
357 $errstr = '';
358 my $dbh = shift;
359 my $def = shift;
360 my $id = shift;
361 my %ret;
362
363 my $sql = "select record_id,host,val,ttl from";
364 if ($def eq 'def' or $def eq 'y') {
365 $sql .= " default_records where group_id=$id and type=$reverse_typemap{SOA}";
366 } else {
367 # we're editing a live SOA record; find based on domain
368 $sql .= " records where domain_id=$id and type=$reverse_typemap{SOA}";
369 }
370#print "getSOA DEBUG: $sql<br>\n";
371 my $sth = $dbh->prepare($sql);
372 $sth->execute;
373
374 my ($recid,$host,$val,$ttl) = $sth->fetchrow_array();
375 my ($prins,$contact) = split /:/, $host;
376 my ($refresh,$retry,$expire,$minttl) = split /:/, $val;
377
378 $ret{recid} = $recid;
379 $ret{ttl} = $ttl;
380 $ret{prins} = $prins;
381 $ret{contact} = $contact;
382 $ret{refresh} = $refresh;
383 $ret{retry} = $retry;
384 $ret{expire} = $expire;
385 $ret{minttl} = $minttl;
386
387 return %ret;
388} # end getSOA()
389
390
391## DNSDB::getRecLine()
392# Return all data fields for a zone record in separate elements of a hash
393# Takes a database handle, default/live flag, and record ID
394sub getRecLine {
395 $errstr = '';
396 my $dbh = shift;
397 my $def = shift;
398 my $id = shift;
399
400 my $sql = "select record_id,host,type,val,distance,weight,port,ttl from ".
401 (($def eq 'def' or $def eq 'y') ? 'default_' : '').
402 "records where record_id=$id";
403print "MDEBUG: $sql<br>\n";
404 my $sth = $dbh->prepare($sql);
405 $sth->execute;
406
407 my ($recid,$host,$rtype,$val,$distance,$weight,$port,$ttl) = $sth->fetchrow_array();
408
409 if ($sth->err) {
410 $errstr = $DBI::errstr;
411 return undef;
412 }
413 my %ret;
414 $ret{recid} = $recid;
415 $ret{host} = $host;
416 $ret{type} = $rtype;
417 $ret{val} = $val;
418 $ret{distance}= $distance;
419 $ret{weight} = $weight;
420 $ret{port} = $port;
421 $ret{ttl} = $ttl;
422
423 return %ret;
424}
425
426
427##fixme: should use above (getRecLine()) to get lines for below?
428## DNSDB::getDomRecs()
429# Return records for a domain
430# Takes a database handle, default/live flag, group/domain ID, start,
431# number of records, sort field, and sort order
432# Returns a reference to an array of hashes
433sub getDomRecs {
434 $errstr = '';
435 my $dbh = shift;
436 my $type = shift;
437 my $id = shift;
438 my $nrecs = shift || 'all';
439 my $nstart = shift || 0;
440
441## for order, need to map input to column names
442 my $order = shift || 'host';
443
444 my $sql = "select record_id,host,type,val,distance,weight,port,ttl from";
445 if ($type eq 'def' or $type eq 'y') {
446 $sql .= " default_records where group_id=$id";
447 } else {
448 $sql .= " records where domain_id=$id";
449 }
450 $sql .= " and not type=$reverse_typemap{SOA} order by $order";
451##fixme: need to set nstart properly (offset is not internally multiplied with limit)
452 $sql .= " limit $nrecs offset ".($nstart*$nrecs) if $nstart ne 'all';
453
454 my $sth = $dbh->prepare($sql);
455 $sth->execute;
456
457 my @retbase;
458 while (my $ref = $sth->fetchrow_hashref()) {
459 push @retbase, $ref;
460 }
461
462 my $ret = \@retbase;
463 return $ret;
464} # end getDomRecs()
465
466
467## DNSDB::addRec()
468# Add a new record to a domain or a group's default records
469# Takes a database handle, default/live flag, group/domain ID,
470# host, type, value, and TTL
471# Some types require additional detail: "distance" for MX and SRV,
472# and weight/port for SRV
473# Returns a status code and detail message in case of error
474sub addRec {
475 $errstr = '';
476 my $dbh = shift;
477 my $defrec = shift;
478 my $id = shift;
479
480 my $host = shift;
481 my $rectype = shift;
482 my $val = shift;
483 my $ttl = shift;
484
485 my $fields = ($defrec eq 'y' ? 'group_id' : 'domain_id').",host,type,val,ttl";
486 my $vallist = "$id,'$host',$rectype,'$val',$ttl";
487
488 my $dist;
489 if ($rectype == $reverse_typemap{MX} or $rectype == $reverse_typemap{SRV}) {
490 $dist = shift;
491 return ('FAIL',"Need distance for $typemap{$rectype} record") if !defined($dist);
492 $fields .= ",distance";
493 $vallist .= ",$dist";
494 }
495 my $weight;
496 my $port;
497 if ($rectype == $reverse_typemap{SRV}) {
498 $weight = shift;
499 $port = shift;
500 return ('FAIL',"Need weight and port for SRV record") if !defined($weight) or !defined($port);
501 $fields .= ",weight,port";
502 $vallist .= ",$weight,$port";
503 }
504
505 my $sql = "insert into ".($defrec eq 'y' ? 'default_' : '')."records ($fields) values ($vallist)";
506# something is bugging me about this...
507#warn "DEBUG: $sql";
508 my $sth = $dbh->prepare($sql);
509 $sth->execute;
510
511 return ('FAIL',$sth->errstr) if $sth->err;
512
513 return ('OK','OK');
514} # end addRec()
515
516
517## DNSDB::updateRec()
518# Update a record
519sub updateRec {
520 $errstr = '';
521
522 my $dbh = shift;
523 my $defrec = shift;
524 my $id = shift;
525
526# all records have these
527 my $host = shift;
528 my $type = shift;
529 my $val = shift;
530 my $ttl = shift;
531
532 return('FAIL',"Missing standard argument(s)") if !defined($ttl);
533
534# only MX and SRV will use these
535 my $dist = 0;
536 my $weight = 0;
537 my $port = 0;
538
539 if ($type == $reverse_typemap{MX} || $type == $reverse_typemap{SRV}) {
540 $dist = shift;
541 return ('FAIL',"MX or SRV requires distance") if !defined($dist);
542 if ($type == $reverse_typemap{SRV}) {
543 $weight = shift;
544 return ('FAIL',"SRV requires weight") if !defined($weight);
545 $port = shift;
546 return ('FAIL',"SRV requires port") if !defined($port);
547 }
548 }
549
550 my $sth = $dbh->prepare("UPDATE ".($defrec eq 'y' ? 'default_' : '')."records ".
551 "SET host=?,type=?,val=?,ttl=?,distance=?,weight=?,port=? ".
552 "WHERE record_id=?");
553 $sth->execute($host,$type,$val,$ttl,$dist,$weight,$port,$id);
554
555 return ('FAIL',$sth->errstr."<br>\n$errstr<br>\n") if $sth->err;
556
557 return ('OK','OK');
558} # end updateRec()
559
560
561## DNSDB::delRec()
562# Delete a record.
563sub delRec {
564 $errstr = '';
565 my $dbh = shift;
566 my $defrec = shift;
567 my $id = shift;
568
569 my $sth = $dbh->prepare("delete from ".($defrec eq 'y' ? 'default_' : '')."records where record_id=?");
570 $sth->execute($id);
571
572 return ('FAIL',$sth->errstr) if $sth->err;
573
574 return ('OK','OK');
575} # end delRec()
576
577
578## DNSDB::domStatus()
579# Sets and/or returns a domain's status
580# Takes a database handle, domain ID and optionally a status argument
581# Returns undef on errors.
582sub domStatus {
583 my $dbh = shift;
584 my $id = shift;
585 my $newstatus = shift;
586
587 return undef if $id !~ /^\d+$/;
588
589 my $sth;
590
591# ooo, fun! let's see what we were passed for status
592 if ($newstatus) {
593 $sth = $dbh->prepare("update domains set status=? where domain_id=?");
594 # ass-u-me caller knows what's going on in full
595 if ($newstatus =~ /^[01]$/) { # only two valid for now.
596 $sth->execute($newstatus,$id);
597 } elsif ($newstatus =~ /^domo(?:n|ff)$/) {
598 $sth->execute(($newstatus eq 'domon' ? 1 : 0),$id);
599 }
600 }
601
602 $sth = $dbh->prepare("select status from domains where domain_id=?");
603 $sth->execute($id);
604 my ($status) = $sth->fetchrow_array;
605 return $status;
606} # end domStatus()
607
608
609# shut Perl up
6101;
Note: See TracBrowser for help on using the repository browser.