source: trunk/DNSDB.pm@ 37

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

/trunk

AXFR import is now basically functional

  • could maybe use a few more recognized types
  • need to find someplace to stuff the serial from the imported SOA

Fix missing template substitution on regular new domain creation

  • Property svn:keywords set to Date Rev Author Id
File size: 29.8 KB
Line 
1# dns/trunk/DNSDB.pm
2# Abstraction functions for DNS administration
3###
4# SVN revision info
5# $Date: 2009-11-18 18:42:22 +0000 (Wed, 18 Nov 2009) $
6# SVN revision $Rev: 37 $
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;
17use Net::DNS;
18#use Net::SMTP;
19#use NetAddr::IP qw( Compact );
20#use POSIX;
21use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
22
23$VERSION = 0.1;
24@ISA = qw(Exporter);
25@EXPORT_OK = qw(
26 &initGlobals &connectDB &finish
27 &addDomain &delDomain &domainName
28 &addGroup &delGroup &getChildren &groupName
29 &addUser &delUser &userFullName
30 &getSOA &getRecLine &getDomRecs
31 &addRec &updateRec &delRec
32 &domStatus &importAXFR
33 %typemap %reverse_typemap
34 );
35
36@EXPORT = (); # Export nothing by default.
37%EXPORT_TAGS = ( ALL => [qw(
38 &initGlobals &connectDB &finish
39 &addDomain &delDomain &domainName
40 &addGroup &delGroup &getChildren &groupName
41 &addUser &delUser &userFullName
42 &getSOA &getRecLine &getDomRecs
43 &addRec &updateRec &delRec
44 &domStatus &importAXFR
45 %typemap %reverse_typemap
46 )]
47 );
48
49our $group = 1;
50our $errstr = '';
51
52# Halfway sane defaults for SOA, TTL, etc.
53our %def = qw (
54 contact hostmaster.DOMAIN
55 prins ns1.myserver.com
56 soattl 86400
57 refresh 10800
58 retry 3600
59 expire 604800
60 minttl 10800
61 ttl 10800
62);
63
64# DNS record type map and reverse map.
65# loaded from the database, from http://www.iana.org/assignments/dns-parameters
66our %typemap;
67our %reverse_typemap;
68
69##
70## Initialization and cleanup subs
71##
72
73## DNSDB::connectDB()
74# Creates connection to DNS database.
75# Requires the database name, username, and password.
76# Returns a handle to the db.
77# Set up for a PostgreSQL db; could be any transactional DBMS with the
78# right changes.
79sub connectDB {
80 $errstr = '';
81 my $dbname = shift;
82 my $user = shift;
83 my $pass = shift;
84 my $dbh;
85 my $DSN = "DBI:Pg:dbname=$dbname";
86
87 my $host = shift;
88 $DSN .= ";host=$host" if $host;
89
90# Note that we want to autocommit by default, and we will turn it off locally as necessary.
91# We may not want to print gobbledygook errors; YMMV. Have to ponder that further.
92 $dbh = DBI->connect($DSN, $user, $pass, {
93 AutoCommit => 1,
94 PrintError => 0
95 })
96 or return (undef, $DBI::errstr) if(!$dbh);
97
98# Return here if we can't select. Note that this indicates a
99# problem executing the select.
100 my $sth = $dbh->prepare("select group_id from groups limit 1");
101 $sth->execute();
102 return (undef,$DBI::errstr) if ($sth->err);
103
104# See if the select returned anything (or null data). This should
105# succeed if the select executed, but...
106 $sth->fetchrow();
107 return (undef,$DBI::errstr) if ($sth->err);
108
109 $sth->finish;
110
111# If we get here, we should be OK.
112 return ($dbh,"DB connection OK");
113} # end connectDB
114
115
116## DNSDB::finish()
117# Cleans up after database handles and so on.
118# Requires a database handle
119sub finish {
120 my $dbh = $_[0];
121 $dbh->disconnect;
122} # end finish
123
124
125## DNSDB::initGlobals()
126# Initialize global variables
127# NB: this does NOT include web-specific session variables!
128# Requires a database handle
129sub initGlobals {
130 my $dbh = shift;
131
132# load system-wide site defaults and things from config file
133 if (open SYSDEFAULTS, "</etc/dnsdb.conf") {
134##fixme - error check!
135 while (<SYSDEFAULTS>) {
136 next if /^\s*#/;
137 $def{contact} = $1 if /contact ?= ?([a-z0-9_.-]+)/i;
138 $def{prins} = $1 if /prins ?= ?([a-z0-9_.-]+)/i;
139 $def{soattl} = $1 if /soattl ?= ?([a-z0-9_.-]+)/i;
140 $def{refresh} = $1 if /refresh ?= ?([a-z0-9_.-]+)/i;
141 $def{retry} = $1 if /retry ?= ?([a-z0-9_.-]+)/i;
142 $def{expire} = $1 if /expire ?= ?([a-z0-9_.-]+)/i;
143 $def{minttl} = $1 if /minttl ?= ?([a-z0-9_.-]+)/i;
144 $def{ttl} = $1 if /ttl ?= ?([a-z0-9_.-]+)/i;
145##fixme? load DB user/pass from config file?
146 }
147 }
148# load from database
149 my $sth = $dbh->prepare("select val,name from rectypes");
150 $sth->execute;
151 while (my ($recval,$recname) = $sth->fetchrow_array()) {
152 $typemap{$recval} = $recname;
153 $reverse_typemap{$recname} = $recval;
154 }
155} # end initGlobals
156
157
158##
159## Processing subs
160##
161
162## DNSDB::addDomain()
163# Add a domain
164# Takes a database handle, domain name, numeric group, and boolean(ish) state (active/inactive)
165# Returns a status code and message
166sub addDomain {
167 $errstr = '';
168 my $dbh = shift;
169 return ('FAIL',"Need database handle") if !$dbh;
170 my $domain = shift;
171 return ('FAIL',"Need domain") if !defined($domain);
172 my $group = shift;
173 return ('FAIL',"Need group") if !defined($group);
174 my $state = shift;
175 return ('FAIL',"Need domain status") if !defined($state);
176
177 my $dom_id;
178
179 # Allow transactions, and raise an exception on errors so we can catch it later.
180 # Use local to make sure these get "reset" properly on exiting this block
181 local $dbh->{AutoCommit} = 0;
182 local $dbh->{RaiseError} = 1;
183
184 # Wrap all the SQL in a transaction
185 eval {
186 # insert the domain...
187 my $sth = $dbh->prepare("insert into domains (domain,group_id,status) values (?,?,?)");
188 $sth->execute($domain,$group,$state);
189
190 # get the ID...
191 $sth = $dbh->prepare("select domain_id from domains where domain='$domain'");
192 $sth->execute;
193 ($dom_id) = $sth->fetchrow_array();
194
195 # ... and now we construct the standard records from the default set. NB: group should be variable.
196 $sth = $dbh->prepare("select host,type,val,distance,weight,port,ttl from default_records where group_id=$group");
197 my $sth_in = $dbh->prepare("insert into records (domain_id,host,type,val,distance,weight,port,ttl)".
198 " values ($dom_id,?,?,?,?,?,?,?)");
199 $sth->execute;
200 while (my ($host,$type,$val,$dist,$weight,$port,$ttl) = $sth->fetchrow_array()) {
201 $host =~ s/DOMAIN/$domain/g;
202 $val =~ s/DOMAIN/$domain/g;
203 $sth_in->execute($host,$type,$val,$dist,$weight,$port,$ttl);
204 }
205
206 # once we get here, we should have suceeded.
207 $dbh->commit;
208 }; # end eval
209
210 if ($@) {
211 my $msg = $@;
212 eval { $dbh->rollback; };
213 return ('FAIL',$msg);
214 } else {
215 return ('OK',$dom_id);
216 }
217} # end addDomain
218
219
220## DNSDB::delDomain()
221# Delete a domain.
222# for now, just delete the records, then the domain.
223# later we may want to archive it in some way instead (status code 2, for example?)
224sub delDomain {
225 my $dbh = shift;
226 my $domid = shift;
227
228 # Allow transactions, and raise an exception on errors so we can catch it later.
229 # Use local to make sure these get "reset" properly on exiting this block
230 local $dbh->{AutoCommit} = 0;
231 local $dbh->{RaiseError} = 1;
232
233 my $failmsg = '';
234
235 # Wrap all the SQL in a transaction
236 eval {
237 my $sth = $dbh->prepare("delete from records where domain_id=?");
238 $failmsg = "Failure removing domain records";
239 $sth->execute($domid);
240 $sth = $dbh->prepare("delete from domains where domain_id=?");
241 $failmsg = "Failure removing domain";
242 $sth->execute($domid);
243
244 # once we get here, we should have suceeded.
245 $dbh->commit;
246 }; # end eval
247
248 if ($@) {
249 my $msg = $@;
250 eval { $dbh->rollback; };
251 return ('FAIL',"$failmsg: $msg");
252 } else {
253 return ('OK','OK');
254 }
255
256} # end delDomain()
257
258
259## DNSDB::domainName()
260# Return the domain name based on a domain ID
261# Takes a database handle and the domain ID
262# Returns the domain name or undef on failure
263sub domainName {
264 $errstr = '';
265 my $dbh = shift;
266 my $domid = shift;
267 my $sth = $dbh->prepare("select domain from domains where domain_id=?");
268 $sth->execute($domid);
269 my ($domname) = $sth->fetchrow_array();
270 $errstr = $DBI::errstr if !$domname;
271 return $domname if $domname;
272} # end domainName
273
274
275## DNSDB::addGroup()
276# Add a group
277# Takes a database handle, group name, parent group, and template-vs-cloneme flag
278# Returns a status code and message
279sub addGroup {
280 $errstr = '';
281 my $dbh = shift;
282 my $groupname = shift;
283 my $pargroup = shift;
284
285 # 0 indicates "template", hardcoded.
286 # Any other value clones that group's default records, if it exists.
287 my $torc = shift || 0;
288
289 # Allow transactions, and raise an exception on errors so we can catch it later.
290 # Use local to make sure these get "reset" properly on exiting this block
291 local $dbh->{AutoCommit} = 0;
292 local $dbh->{RaiseError} = 1;
293
294 # Wrap all the SQL in a transaction
295 eval {
296 my $sth = $dbh->prepare("INSERT INTO groups (parent_group_id,group_name) VALUES (?,?)");
297 $sth->execute($pargroup,$groupname);
298
299 $sth = $dbh->prepare("SELECT group_id FROM groups WHERE group_name=?");
300 $sth->execute($groupname);
301 my ($groupid) = $sth->fetchrow_array();
302
303 $sth = $dbh->prepare("INSERT INTO default_records (group_id,host,type,val,distance,weight,port,ttl) ".
304 "VALUES ($groupid,?,?,?,?,?,?,?)");
305 if ($torc) {
306 my $sth2 = $dbh->prepare("SELECT host,type,val,distance,weight,port,ttl FROM default_records WHERE group_id=?");
307 while (my @clonedata = $sth2->fetchrow_array) {
308 $sth->execute(@clonedata);
309 }
310 } else {
311 # reasonable basic defaults for SOA, MX, NS, and minimal hosting
312 # could load from a config file, but somewhere along the line we need hardcoded bits.
313 $sth->execute('ns1.example.com:hostmaster.example.com', 6, '10800:3600:604800:10800', 0, 0, 0, 86400);
314 $sth->execute('DOMAIN', 1, '192.168.4.2', 0, 0, 0, 7200);
315 $sth->execute('DOMAIN', 15, 'mx.example.com', 10, 0, 0, 7200);
316 $sth->execute('DOMAIN', 2, 'ns1.example.com', 0, 0, 0, 7200);
317 $sth->execute('DOMAIN', 2, 'ns2.example.com', 0, 0, 0, 7200);
318 $sth->execute('www.DOMAIN', 5, 'DOMAIN', 0, 0, 0, 7200);
319 }
320
321 # once we get here, we should have suceeded.
322 $dbh->commit;
323 }; # end eval
324
325 if ($@) {
326 my $msg = $@;
327 eval { $dbh->rollback; };
328 return ('FAIL',$msg);
329 } else {
330 return ('OK','OK');
331 }
332
333} # end addGroup()
334
335
336## DNSDB::delGroup()
337# Delete a group.
338# Takes a group ID
339# Returns a status code and message
340sub delGroup {
341 my $dbh = shift;
342 my $groupid = shift;
343
344 # Allow transactions, and raise an exception on errors so we can catch it later.
345 # Use local to make sure these get "reset" properly on exiting this block
346 local $dbh->{AutoCommit} = 0;
347 local $dbh->{RaiseError} = 1;
348
349##fixme: locate "knowable" error conditions and deal with them before the eval
350# ... or inside, whatever.
351# -> domains still exist in group
352# -> ...
353 my $failmsg = '';
354
355 # Wrap all the SQL in a transaction
356 eval {
357 my $sth = $dbh->prepare("SELECT count(*) FROM domains WHERE group_id=?");
358 $sth->execute($groupid);
359 my ($domcnt) = $sth->fetchrow_array;
360 $failmsg = "Can't remove group ".groupName($dbh,$groupid);
361 die "$domcnt domains still in group\n" if $domcnt;
362
363 $sth = $dbh->prepare("delete from default_records where group_id=?");
364 $failmsg = "Failed to delete default records for ".groupName($dbh,$groupid);
365 $sth->execute($groupid);
366 $sth = $dbh->prepare("delete from groups where group_id=?");
367 $failmsg = "Failed to remove group ".groupName($dbh,$groupid);
368 $sth->execute($groupid);
369
370 # once we get here, we should have suceeded.
371 $dbh->commit;
372 }; # end eval
373
374 if ($@) {
375 my $msg = $@;
376 eval { $dbh->rollback; };
377 return ('FAIL',"$failmsg: $msg");
378 } else {
379 return ('OK','OK');
380 }
381} # end delGroup()
382
383
384## DNSDB::getChildren()
385# Get a list of all groups whose parent^n is group <n>
386# Takes a database handle, group ID, reference to an array to put the group IDs in,
387# and an optional flag to return only immediate children or all children-of-children
388# default to returning all children
389# Calls itself
390sub getChildren {
391 $errstr = '';
392 my $dbh = shift;
393 my $rootgroup = shift;
394 my $groupdest = shift;
395 my $immed = shift || 'all';
396
397 # special break for default group; otherwise we get stuck.
398 if ($rootgroup == 1) {
399 # by definition, group 1 is the Root Of All Groups
400 my $sth = $dbh->prepare("SELECT group_id FROM groups WHERE NOT (group_id=1)".
401 ($immed ne 'all' ? " AND parent_group_id=1" : ''));
402 $sth->execute;
403 while (my @this = $sth->fetchrow_array) {
404 push @$groupdest, @this;
405 }
406 } else {
407 my $sth = $dbh->prepare("SELECT group_id FROM groups WHERE parent_group_id=?");
408 $sth->execute($rootgroup);
409 return if $sth->rows == 0;
410 my @grouplist;
411 while (my ($group) = $sth->fetchrow_array) {
412 push @$groupdest, $group;
413 getChildren($dbh,$group,$groupdest) if $immed eq 'all';
414 }
415 }
416} # end getChildren()
417
418
419## DNSDB::groupName()
420# Return the group name based on a group ID
421# Takes a database handle and the group ID
422# Returns the group name or undef on failure
423sub groupName {
424 $errstr = '';
425 my $dbh = shift;
426 my $groupid = shift;
427 my $sth = $dbh->prepare("SELECT group_name FROM groups WHERE group_id=?");
428 $sth->execute($groupid);
429 my ($groupname) = $sth->fetchrow_array();
430 $errstr = $DBI::errstr if !$groupname;
431 return $groupname if $groupname;
432} # end groupName
433
434
435## DNSDB::addUser()
436#
437sub addUser {
438 $errstr = '';
439 my $dbh = shift;
440 return ('FAIL',"Need database handle") if !$dbh;
441 my $username = shift;
442 return ('FAIL',"Missing username") if !defined($username);
443 my $group = shift;
444 return ('FAIL',"Missing group") if !defined($group);
445 my $pass = shift;
446 return ('FAIL',"Missing password") if !defined($pass);
447 my $state = shift;
448 return ('FAIL',"Need account status") if !defined($state);
449
450 my $type = shift || 'u'; # create limited users by default - fwiw, not sure yet how this will interact with ACLs
451
452 my $fname = shift || $username;
453 my $lname = shift || '';
454 my $phone = shift || ''; # not going format-check
455
456 my $user_id;
457
458 # Allow transactions, and raise an exception on errors so we can catch it later.
459 # Use local to make sure these get "reset" properly on exiting this block
460 local $dbh->{AutoCommit} = 0;
461 local $dbh->{RaiseError} = 1;
462
463 # Wrap all the SQL in a transaction
464 eval {
465 # insert the user...
466 my $sth = $dbh->prepare("INSERT INTO users (group_id,username,password,firstname,lastname,phone,type,status) ".
467 "VALUES (?,?,?,?,?,?,?,?)");
468 $sth->execute($group,$username,$pass,$fname,$lname,$phone,$type,$state);
469
470 # get the ID...
471 $sth = $dbh->prepare("select user_id from users where username=?");
472 $sth->execute($username);
473 ($user_id) = $sth->fetchrow_array();
474
475##fixme: add another table to hold name/email for log table?
476
477 # once we get here, we should have suceeded.
478 $dbh->commit;
479 }; # end eval
480
481 if ($@) {
482 my $msg = $@;
483 eval { $dbh->rollback; };
484 return ('FAIL',$msg);
485 } else {
486 return ('OK',$user_id);
487 }
488} # end addUser
489
490
491## DNSDB::delUser()
492#
493sub delUser {
494 my $dbh = shift;
495 return ('FAIL',"Need database handle") if !$dbh;
496 my $userid = shift;
497 return ('FAIL',"Missing userid") if !defined($userid);
498
499 my $sth = $dbh->prepare("delete from users where user_id=?");
500 $sth->execute($userid);
501
502 return ('FAIL',"Couldn't remove user: ".$sth->errstr) if $sth->err;
503
504 return ('OK','OK');
505
506} # end delUser
507
508
509## DNSDB::userFullName()
510# Return a pretty string!
511# Takes a user_id and optional printf-ish string to indicate which pieces where:
512# %u for the username
513# %f for the first name
514# %l for the last name
515# All other text in the passed string will be left as-is.
516##fixme: need a "smart" option too, so that missing/null/blank first/last names don't give funky output
517sub userFullName {
518 $errstr = '';
519 my $dbh = shift;
520 my $userid = shift;
521 my $fullformat = shift || '%f %l (%u)';
522 my $sth = $dbh->prepare("select username,firstname,lastname from users where user_id=?");
523 $sth->execute($userid);
524 my ($uname,$fname,$lname) = $sth->fetchrow_array();
525 $errstr = $DBI::errstr if !$uname;
526
527 $fullformat =~ s/\%u/$uname/g;
528 $fullformat =~ s/\%f/$fname/g;
529 $fullformat =~ s/\%l/$lname/g;
530
531 return $fullformat;
532} # end userFullName
533
534
535## DNSDB::editRecord()
536# Change an existing record
537# Takes a database handle, default/live flag, record ID, and new data and updates the data fields for it
538sub editRecord {
539 $errstr = '';
540 my $dbh = shift;
541 my $defflag = shift;
542 my $recid = shift;
543 my $host = shift;
544 my $address = shift;
545 my $distance = shift;
546 my $weight = shift;
547 my $port = shift;
548 my $ttl = shift;
549}
550
551
552## DNSDB::getSOA()
553# Return all suitable fields from an SOA record in separate elements of a hash
554# Takes a database handle, default/live flag, and group (default) or domain (live) ID
555sub getSOA {
556 $errstr = '';
557 my $dbh = shift;
558 my $def = shift;
559 my $id = shift;
560 my %ret;
561
562 my $sql = "select record_id,host,val,ttl from";
563 if ($def eq 'def' or $def eq 'y') {
564 $sql .= " default_records where group_id=$id and type=$reverse_typemap{SOA}";
565 } else {
566 # we're editing a live SOA record; find based on domain
567 $sql .= " records where domain_id=$id and type=$reverse_typemap{SOA}";
568 }
569 my $sth = $dbh->prepare($sql);
570 $sth->execute;
571
572 my ($recid,$host,$val,$ttl) = $sth->fetchrow_array();
573 my ($prins,$contact) = split /:/, $host;
574 my ($refresh,$retry,$expire,$minttl) = split /:/, $val;
575
576 $ret{recid} = $recid;
577 $ret{ttl} = $ttl;
578 $ret{prins} = $prins;
579 $ret{contact} = $contact;
580 $ret{refresh} = $refresh;
581 $ret{retry} = $retry;
582 $ret{expire} = $expire;
583 $ret{minttl} = $minttl;
584
585 return %ret;
586} # end getSOA()
587
588
589## DNSDB::getRecLine()
590# Return all data fields for a zone record in separate elements of a hash
591# Takes a database handle, default/live flag, and record ID
592sub getRecLine {
593 $errstr = '';
594 my $dbh = shift;
595 my $def = shift;
596 my $id = shift;
597
598 my $sql = "select record_id,host,type,val,distance,weight,port,ttl from ".
599 (($def eq 'def' or $def eq 'y') ? 'default_' : '').
600 "records where record_id=$id";
601print "MDEBUG: $sql<br>\n";
602 my $sth = $dbh->prepare($sql);
603 $sth->execute;
604
605 my ($recid,$host,$rtype,$val,$distance,$weight,$port,$ttl) = $sth->fetchrow_array();
606
607 if ($sth->err) {
608 $errstr = $DBI::errstr;
609 return undef;
610 }
611 my %ret;
612 $ret{recid} = $recid;
613 $ret{host} = $host;
614 $ret{type} = $rtype;
615 $ret{val} = $val;
616 $ret{distance}= $distance;
617 $ret{weight} = $weight;
618 $ret{port} = $port;
619 $ret{ttl} = $ttl;
620
621 return %ret;
622}
623
624
625##fixme: should use above (getRecLine()) to get lines for below?
626## DNSDB::getDomRecs()
627# Return records for a domain
628# Takes a database handle, default/live flag, group/domain ID, start,
629# number of records, sort field, and sort order
630# Returns a reference to an array of hashes
631sub getDomRecs {
632 $errstr = '';
633 my $dbh = shift;
634 my $type = shift;
635 my $id = shift;
636 my $nrecs = shift || 'all';
637 my $nstart = shift || 0;
638
639## for order, need to map input to column names
640 my $order = shift || 'host';
641
642 my $sql = "select record_id,host,type,val,distance,weight,port,ttl from";
643 if ($type eq 'def' or $type eq 'y') {
644 $sql .= " default_records where group_id=$id";
645 } else {
646 $sql .= " records where domain_id=$id";
647 }
648 $sql .= " and not type=$reverse_typemap{SOA} order by $order";
649##fixme: need to set nstart properly (offset is not internally multiplied with limit)
650 $sql .= " limit $nrecs offset ".($nstart*$nrecs) if $nstart ne 'all';
651
652 my $sth = $dbh->prepare($sql);
653 $sth->execute;
654
655 my @retbase;
656 while (my $ref = $sth->fetchrow_hashref()) {
657 push @retbase, $ref;
658 }
659
660 my $ret = \@retbase;
661 return $ret;
662} # end getDomRecs()
663
664
665## DNSDB::addRec()
666# Add a new record to a domain or a group's default records
667# Takes a database handle, default/live flag, group/domain ID,
668# host, type, value, and TTL
669# Some types require additional detail: "distance" for MX and SRV,
670# and weight/port for SRV
671# Returns a status code and detail message in case of error
672sub addRec {
673 $errstr = '';
674 my $dbh = shift;
675 my $defrec = shift;
676 my $id = shift;
677
678 my $host = shift;
679 my $rectype = shift;
680 my $val = shift;
681 my $ttl = shift;
682
683 my $fields = ($defrec eq 'y' ? 'group_id' : 'domain_id').",host,type,val,ttl";
684 my $vallen = "?,?,?,?,?";
685 my @vallist = ($id,$host,$rectype,$val,$ttl);
686
687 my $dist;
688 if ($rectype == $reverse_typemap{MX} or $rectype == $reverse_typemap{SRV}) {
689 $dist = shift;
690 return ('FAIL',"Need distance for $typemap{$rectype} record") if !defined($dist);
691 $fields .= ",distance";
692 $vallen .= ",?";
693 push @vallist, $dist;
694 }
695 my $weight;
696 my $port;
697 if ($rectype == $reverse_typemap{SRV}) {
698 # check for _service._protocol. NB: RFC2782 does not say "MUST"... nor "SHOULD"...
699 # it just says (paraphrased) "... is prepended with _ to prevent DNS collisions"
700 return ('FAIL',"SRV records must begin with _service._protocol")
701 if $host !~ /^_[A-Za-z]+\._[A-Za-z]+\.[a-z0-9-]+/;
702 $weight = shift;
703 $port = shift;
704 return ('FAIL',"Need weight and port for SRV record") if !defined($weight) or !defined($port);
705 $fields .= ",weight,port";
706 $vallen .= ",?,?";
707 push @vallist, ($weight,$port);
708 }
709
710 my $sql = "insert into ".($defrec eq 'y' ? 'default_' : '')."records ($fields) values ($vallen)";
711##fixme: use array for values, replace "vallist" with series of ?,?,? etc
712# something is bugging me about this...
713#warn "DEBUG: $sql";
714 my $sth = $dbh->prepare($sql);
715 $sth->execute(@vallist);
716
717 return ('FAIL',$sth->errstr) if $sth->err;
718
719 return ('OK','OK');
720} # end addRec()
721
722
723## DNSDB::updateRec()
724# Update a record
725sub updateRec {
726 $errstr = '';
727
728 my $dbh = shift;
729 my $defrec = shift;
730 my $id = shift;
731
732# all records have these
733 my $host = shift;
734 my $type = shift;
735 my $val = shift;
736 my $ttl = shift;
737
738 return('FAIL',"Missing standard argument(s)") if !defined($ttl);
739
740# only MX and SRV will use these
741 my $dist = 0;
742 my $weight = 0;
743 my $port = 0;
744
745 if ($type == $reverse_typemap{MX} || $type == $reverse_typemap{SRV}) {
746 $dist = shift;
747 return ('FAIL',"MX or SRV requires distance") if !defined($dist);
748 if ($type == $reverse_typemap{SRV}) {
749 $weight = shift;
750 return ('FAIL',"SRV requires weight") if !defined($weight);
751 $port = shift;
752 return ('FAIL',"SRV requires port") if !defined($port);
753 }
754 }
755
756 my $sth = $dbh->prepare("UPDATE ".($defrec eq 'y' ? 'default_' : '')."records ".
757 "SET host=?,type=?,val=?,ttl=?,distance=?,weight=?,port=? ".
758 "WHERE record_id=?");
759 $sth->execute($host,$type,$val,$ttl,$dist,$weight,$port,$id);
760
761 return ('FAIL',$sth->errstr."<br>\n$errstr<br>\n") if $sth->err;
762
763 return ('OK','OK');
764} # end updateRec()
765
766
767## DNSDB::delRec()
768# Delete a record.
769sub delRec {
770 $errstr = '';
771 my $dbh = shift;
772 my $defrec = shift;
773 my $id = shift;
774
775 my $sth = $dbh->prepare("delete from ".($defrec eq 'y' ? 'default_' : '')."records where record_id=?");
776 $sth->execute($id);
777
778 return ('FAIL',"Couldn't remove record: ".$sth->errstr) if $sth->err;
779
780 return ('OK','OK');
781} # end delRec()
782
783
784## DNSDB::domStatus()
785# Sets and/or returns a domain's status
786# Takes a database handle, domain ID and optionally a status argument
787# Returns undef on errors.
788sub domStatus {
789 my $dbh = shift;
790 my $id = shift;
791 my $newstatus = shift;
792
793 return undef if $id !~ /^\d+$/;
794
795 my $sth;
796
797# ooo, fun! let's see what we were passed for status
798 if ($newstatus) {
799 $sth = $dbh->prepare("update domains set status=? where domain_id=?");
800 # ass-u-me caller knows what's going on in full
801 if ($newstatus =~ /^[01]$/) { # only two valid for now.
802 $sth->execute($newstatus,$id);
803 } elsif ($newstatus =~ /^domo(?:n|ff)$/) {
804 $sth->execute(($newstatus eq 'domon' ? 1 : 0),$id);
805 }
806 }
807
808 $sth = $dbh->prepare("select status from domains where domain_id=?");
809 $sth->execute($id);
810 my ($status) = $sth->fetchrow_array;
811 return $status;
812} # end domStatus()
813
814
815## DNSDB::importAXFR
816# Import a domain via AXFR
817# Takes AXFR host, domain to transfer, group to put the domain in,
818# and optionally:
819# - active/inactive state flag (defaults to active)
820# - overwrite-SOA flag (defaults to off)
821# - overwrite-NS flag (defaults to off, doesn't affect subdomain NS records)
822# Returns a status code (OK, WARN, or FAIL) and message - message should be blank
823# if status is OK, but WARN includes conditions that are not fatal but should
824# really be reported.
825sub importAXFR {
826 my $dbh = shift;
827 my $ifrom_in = shift;
828 my $domain = shift;
829 my $group = shift;
830 my $status = shift || 1;
831 my $rwsoa = shift || 0;
832 my $rwns = shift || 0;
833
834##fixme: add mode to delete&replace, merge+overwrite, merge new?
835
836 my $nrecs = 0;
837 my $soaflag = 0;
838 my $nsflag = 0;
839 my $warnmsg = '';
840 my $ifrom;
841
842 # choke on possible bad setting in ifrom
843 # IPv4 and v6, and valid hostnames!
844 ($ifrom) = ($ifrom_in =~ /^([0-9a-f\:.]+|[0-9a-z_.-]+)$/i);
845 return ('FAIL', "Bad AXFR source host $ifrom")
846 unless ($ifrom) = ($ifrom_in =~ /^([0-9a-f\:.]+|[0-9a-z_.-]+)$/i);
847
848 # Allow transactions, and raise an exception on errors so we can catch it later.
849 # Use local to make sure these get "reset" properly on exiting this block
850 local $dbh->{AutoCommit} = 0;
851 local $dbh->{RaiseError} = 1;
852
853 my $sth = $dbh->prepare("SELECT domain_id FROM domains WHERE domain=?");
854 my $dom_id;
855
856# quick check to start to see if we've already got one
857 $sth->execute($domain);
858 ($dom_id) = $sth->fetchrow_array;
859
860 return ('FAIL', "Domain already exists") if $dom_id;
861
862 eval {
863 # can't do this, can't nest transactions. sigh.
864 #my ($dcode, $dmsg) = addDomain(dbh, domain, group, status);
865
866##fixme: serial
867 my $sth = $dbh->prepare("INSERT INTO domains (domain,group_id,status) VALUES (?,?,?)");
868 $sth->execute($domain,$group,$status);
869
870## bizarre DBI<->Net::DNS interaction bug:
871## sometimes a zone will cause an immediate commit-and-exit (sort of) of the while()
872## fixed, apparently I was doing *something* odd, but not certain what it was that
873## caused a commit instead of barfing
874
875 # get domain id so we can do the records
876 $sth = $dbh->prepare("SELECT domain_id FROM domains WHERE domain=?");
877 $sth->execute($domain);
878 ($dom_id) = $sth->fetchrow_array();
879
880 my $res = Net::DNS::Resolver->new;
881 $res->nameservers($ifrom);
882 $res->axfr_start($domain)
883 or die "Couldn't begin AXFR\n";
884
885 while (my $rr = $res->axfr_next()) {
886 my $type = $rr->type;
887
888 my $sql = "INSERT INTO records (domain_id,host,type,ttl,val";
889 my $vallen = "?,?,?,?,?";
890
891 $soaflag = 1 if $type eq 'SOA';
892 $nsflag = 1 if $type eq 'NS';
893
894 my @vallist = ($dom_id, $rr->name, $reverse_typemap{$type}, $rr->ttl);
895
896# "Primary" types:
897# A, NS, CNAME, SOA, PTR(warn in forward), MX, TXT, AAAA, SRV, A6(ob), SPF
898# maybe KEY
899
900# nasty big ugly case-like thing here, since we have to do *some* different
901# processing depending on the record. le sigh.
902
903 if ($type eq 'A') {
904 push @vallist, $rr->address;
905 } elsif ($type eq 'NS') {
906# hmm. should we warn here if subdomain NS'es are left alone?
907 next if ($rwns && ($rr->name eq $domain));
908 push @vallist, $rr->nsdname;
909 $nsflag = 1;
910 } elsif ($type eq 'CNAME') {
911 push @vallist, $rr->cname;
912 } elsif ($type eq 'SOA') {
913 next if $rwsoa;
914 $vallist[1] = $rr->mname.":".$rr->rname;
915 push @vallist, ($rr->refresh.":".$rr->retry.":".$rr->expire.":".$rr->minimum);
916 $soaflag = 1;
917 } elsif ($type eq 'PTR') {
918 # hmm. PTR records should not be in forward zones.
919 } elsif ($type eq 'MX') {
920 $sql .= ",distance";
921 $vallen .= ",?";
922 push @vallist, $rr->exchange;
923 push @vallist, $rr->preference;
924 } elsif ($type eq 'TXT') {
925##fixme: Net::DNS docs say this should be deprecated for rdatastr() or char_str_list(),
926## but don't really seem enthusiastic about it.
927 push @vallist, $rr->txtdata;
928 } elsif ($type eq 'SPF') {
929##fixme: and the same caveat here, since it is apparently a clone of ::TXT
930 push @vallist, $rr->txtdata;
931 } elsif ($type eq 'AAAA') {
932 push @vallist, $rr->address;
933 } elsif ($type eq 'SRV') {
934 $sql .= ",distance,weight,port" if $type eq 'SRV';
935 $vallen .= ",?,?,?" if $type eq 'SRV';
936 push @vallist, $rr->target;
937 push @vallist, $rr->priority;
938 push @vallist, $rr->weight;
939 push @vallist, $rr->port;
940 } elsif ($type eq 'KEY') {
941 # we don't actually know what to do with these...
942 push @vallist, ($rr->flags.":".$rr->protocol.":".$rr->algorithm.":".$rr->key.":".$rr->keytag.":".$rr->privatekeyname);
943 } else {
944 push @vallist, $rr->rdatastr;
945 # Finding a different record type is not fatal.... just problematic.
946 # We may not be able to export it correctly.
947 $warnmsg .= "Unusual record ".$rr->name." ($type) found\n";
948 }
949
950# BIND supports:
951# A CNAME HINFO MB(ex) MD(ob) MF(ob) MG(ex) MINFO(ex) MR(ex) MX NS NULL
952# PTR SOA TXT WKS AFSDB(ex) ISDN(ex) RP(ex) RT(ex) X25(ex) PX
953# ... if one can ever find the right magic to format them correctly
954
955# Net::DNS supports:
956# RRSIG SIG NSAP NS NIMLOC NAPTR MX MR MINFO MG MB LOC ISDN IPSECKEY HINFO
957# EID DNAME CNAME CERT APL AFSDB AAAA A DS NXT NSEC3PARAM NSEC3 NSEC KEY
958# DNSKEY DLV X25 TXT TSIG TKEY SSHFP SRV SPF SOA RT RP PX PTR NULL APL::AplItem
959
960 $sth = $dbh->prepare($sql.") VALUES (".$vallen.")") or die "problem preparing record insert SQL\n";
961 $sth->execute(@vallist) or die "failed to insert ".$rr->string.": ".$sth->errstr."\n";
962
963 $nrecs++;
964
965 } # while axfr_next
966
967 # Overwrite SOA record
968 if ($rwsoa) {
969 $soaflag = 1;
970 my $sthgetsoa = $dbh->prepare("SELECT host,val,ttl FROM default_records WHERE group_id=? AND type=?");
971 my $sthputsoa = $dbh->prepare("INSERT INTO records (domain_id,host,type,val,ttl) VALUES (?,?,?,?,?)");
972 $sthgetsoa->execute($group,$reverse_typemap{SOA});
973 while (my ($host,$val,$ttl) = $sthgetsoa->fetchrow_array()) {
974 $host =~ s/DOMAIN/$domain/g;
975 $val =~ s/DOMAIN/$domain/g;
976 $sthputsoa->execute($dom_id,$host,$reverse_typemap{SOA},$val,$ttl);
977 }
978 }
979
980 # Overwrite NS records
981 if ($rwns) {
982 $nsflag = 1;
983 my $sthgetns = $dbh->prepare("SELECT host,val,ttl FROM default_records WHERE group_id=? AND type=?");
984 my $sthputns = $dbh->prepare("INSERT INTO records (domain_id,host,type,val,ttl) VALUES (?,?,?,?,?)");
985 $sthgetns->execute($group,$reverse_typemap{NS});
986 while (my ($host,$val,$ttl) = $sthgetns->fetchrow_array()) {
987 $host =~ s/DOMAIN/$domain/g;
988 $val =~ s/DOMAIN/$domain/g;
989 $sthputns->execute($dom_id,$host,$reverse_typemap{NS},$val,$ttl);
990 }
991 }
992
993 die "No records found; either $ifrom is not authoritative or doesn't allow transfers\n" if !$nrecs;
994 die "Bad zone: No SOA record!\n" if !$soaflag;
995 die "Bad zone: No NS records!\n" if !$nsflag;
996
997 $dbh->commit;
998
999 };
1000
1001 if ($@) {
1002 my $msg = $@;
1003 eval { $dbh->rollback; };
1004 return ('FAIL',$msg." $warnmsg");
1005 } else {
1006 return ('WARN', $warnmsg) if $warnmsg;
1007 return ('OK',"ook");
1008 }
1009
1010 # it should be impossible to get here.
1011 return ('WARN',"OOOK!");
1012} # end importAXFR()
1013
1014
1015# shut Perl up
10161;
Note: See TracBrowser for help on using the repository browser.