source: trunk/DNSDB.pm@ 33

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

/trunk

checkpoint, fleshing out axfr import

  • Property svn:keywords set to Date Rev Author Id
File size: 24.9 KB
Line 
1# dns/trunk/DNSDB.pm
2# Abstraction functions for DNS administration
3###
4# SVN revision info
5# $Date: 2009-11-10 22:51:55 +0000 (Tue, 10 Nov 2009) $
6# SVN revision $Rev: 33 $
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
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
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 $sth_in->execute($host,$type,$val,$dist,$weight,$port,$ttl);
203 }
204
205 # once we get here, we should have suceeded.
206 $dbh->commit;
207 }; # end eval
208
209 if ($@) {
210 my $msg = $@;
211 eval { $dbh->rollback; };
212 return ('FAIL',$msg);
213 } else {
214 return ('OK',$dom_id);
215 }
216} # end addDomain
217
218
219## DNSDB::delDomain()
220# Delete a domain.
221# for now, just delete the records, then the domain.
222# later we may want to archive it in some way instead (status code 2, for example?)
223sub delDomain {
224 my $dbh = shift;
225 my $domid = shift;
226
227 # Allow transactions, and raise an exception on errors so we can catch it later.
228 # Use local to make sure these get "reset" properly on exiting this block
229 local $dbh->{AutoCommit} = 0;
230 local $dbh->{RaiseError} = 1;
231
232 my $failmsg = '';
233
234 # Wrap all the SQL in a transaction
235 eval {
236 my $sth = $dbh->prepare("delete from records where domain_id=?");
237 $failmsg = "Failure removing domain records";
238 $sth->execute($domid);
239 $sth = $dbh->prepare("delete from domains where domain_id=?");
240 $failmsg = "Failure removing domain";
241 $sth->execute($domid);
242
243 # once we get here, we should have suceeded.
244 $dbh->commit;
245 }; # end eval
246
247 if ($@) {
248 my $msg = $@;
249 eval { $dbh->rollback; };
250 return ('FAIL',"$failmsg: $msg");
251 } else {
252 return ('OK','OK');
253 }
254
255} # end delDomain()
256
257
258## DNSDB::domainName()
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 domainName {
263 $errstr = '';
264 my $dbh = shift;
265 my $domid = shift;
266 my $sth = $dbh->prepare("select domain from domains where domain_id=?");
267 $sth->execute($domid);
268 my ($domname) = $sth->fetchrow_array();
269 $errstr = $DBI::errstr if !$domname;
270 return $domname if $domname;
271} # end domainName
272
273
274## DNSDB::addGroup()
275# Add a group
276# Takes a database handle, group name, parent group, and template-vs-cloneme flag
277# Returns a status code and message
278sub addGroup {
279 $errstr = '';
280 my $dbh = shift;
281 my $groupname = shift;
282 my $pargroup = shift;
283
284 # 0 indicates "template", hardcoded.
285 # Any other value clones that group's default records, if it exists.
286 my $torc = shift || 0;
287
288 # Allow transactions, and raise an exception on errors so we can catch it later.
289 # Use local to make sure these get "reset" properly on exiting this block
290 local $dbh->{AutoCommit} = 0;
291 local $dbh->{RaiseError} = 1;
292
293 # Wrap all the SQL in a transaction
294 eval {
295 my $sth = $dbh->prepare("INSERT INTO groups (parent_group_id,group_name) VALUES (?,?)");
296 $sth->execute($pargroup,$groupname);
297
298 $sth = $dbh->prepare("SELECT group_id FROM groups WHERE group_name=?");
299 $sth->execute($groupname);
300 my ($groupid) = $sth->fetchrow_array();
301
302 $sth = $dbh->prepare("INSERT INTO default_records (group_id,host,type,val,distance,weight,port,ttl) ".
303 "VALUES ($groupid,?,?,?,?,?,?,?)");
304 if ($torc) {
305 my $sth2 = $dbh->prepare("SELECT host,type,val,distance,weight,port,ttl FROM default_records WHERE group_id=?");
306 while (my @clonedata = $sth2->fetchrow_array) {
307 $sth->execute(@clonedata);
308 }
309 } else {
310 # reasonable basic defaults for SOA, MX, NS, and minimal hosting
311 # could load from a config file, but somewhere along the line we need hardcoded bits.
312 $sth->execute('ns1.example.com:hostmaster.example.com', 6, '10800:3600:604800:10800', 0, 0, 0, 86400);
313 $sth->execute('DOMAIN', 1, '192.168.4.2', 0, 0, 0, 7200);
314 $sth->execute('DOMAIN', 15, 'mx.example.com', 10, 0, 0, 7200);
315 $sth->execute('DOMAIN', 2, 'ns1.example.com', 0, 0, 0, 7200);
316 $sth->execute('DOMAIN', 2, 'ns2.example.com', 0, 0, 0, 7200);
317 $sth->execute('www.DOMAIN', 5, 'DOMAIN', 0, 0, 0, 7200);
318 }
319
320 # once we get here, we should have suceeded.
321 $dbh->commit;
322 }; # end eval
323
324 if ($@) {
325 my $msg = $@;
326 eval { $dbh->rollback; };
327 return ('FAIL',$msg);
328 } else {
329 return ('OK','OK');
330 }
331
332} # end addGroup()
333
334
335## DNSDB::delGroup()
336# Delete a group.
337# Takes a group ID
338# Returns a status code and message
339sub delGroup {
340 my $dbh = shift;
341 my $groupid = shift;
342
343 # Allow transactions, and raise an exception on errors so we can catch it later.
344 # Use local to make sure these get "reset" properly on exiting this block
345 local $dbh->{AutoCommit} = 0;
346 local $dbh->{RaiseError} = 1;
347
348##fixme: locate "knowable" error conditions and deal with them before the eval
349# ... or inside, whatever.
350# -> domains still exist in group
351# -> ...
352 my $failmsg = '';
353
354 # Wrap all the SQL in a transaction
355 eval {
356 my $sth = $dbh->prepare("SELECT count(*) FROM domains WHERE group_id=?");
357 $sth->execute($groupid);
358 my ($domcnt) = $sth->fetchrow_array;
359 $failmsg = "Can't remove group ".groupName($dbh,$groupid);
360 die "$domcnt domains still in group\n" if $domcnt;
361
362 $sth = $dbh->prepare("delete from default_records where group_id=?");
363 $failmsg = "Failed to delete default records for ".groupName($dbh,$groupid);
364 $sth->execute($groupid);
365 $sth = $dbh->prepare("delete from groups where group_id=?");
366 $failmsg = "Failed to remove group ".groupName($dbh,$groupid);
367 $sth->execute($groupid);
368
369 # once we get here, we should have suceeded.
370 $dbh->commit;
371 }; # end eval
372
373 if ($@) {
374 my $msg = $@;
375 eval { $dbh->rollback; };
376 return ('FAIL',"$failmsg: $msg");
377 } else {
378 return ('OK','OK');
379 }
380} # end delGroup()
381
382
383## DNSDB::getChildren()
384# Get a list of all groups whose parent^n is group <n>
385# Takes a database handle, group ID, reference to an array to put the group IDs in,
386# and an optional flag to return only immediate children or all children-of-children
387# default to returning all children
388# Calls itself
389sub getChildren {
390 $errstr = '';
391 my $dbh = shift;
392 my $rootgroup = shift;
393 my $groupdest = shift;
394 my $immed = shift || 'all';
395
396 # special break for default group; otherwise we get stuck.
397 if ($rootgroup == 1) {
398 # by definition, group 1 is the Root Of All Groups
399 my $sth = $dbh->prepare("SELECT group_id FROM groups WHERE NOT (group_id=1)".
400 ($immed ne 'all' ? " AND parent_group_id=1" : ''));
401 $sth->execute;
402 while (my @this = $sth->fetchrow_array) {
403 push @$groupdest, @this;
404 }
405 } else {
406 my $sth = $dbh->prepare("SELECT group_id FROM groups WHERE parent_group_id=?");
407 $sth->execute($rootgroup);
408 return if $sth->rows == 0;
409 my @grouplist;
410 while (my ($group) = $sth->fetchrow_array) {
411 push @$groupdest, $group;
412 getChildren($dbh,$group,$groupdest) if $immed eq 'all';
413 }
414 }
415} # end getChildren()
416
417
418## DNSDB::groupName()
419# Return the group name based on a group ID
420# Takes a database handle and the group ID
421# Returns the group name or undef on failure
422sub groupName {
423 $errstr = '';
424 my $dbh = shift;
425 my $groupid = shift;
426 my $sth = $dbh->prepare("SELECT group_name FROM groups WHERE group_id=?");
427 $sth->execute($groupid);
428 my ($groupname) = $sth->fetchrow_array();
429 $errstr = $DBI::errstr if !$groupname;
430 return $groupname if $groupname;
431} # end groupName
432
433
434## DNSDB::addUser()
435#
436sub addUser {
437 $errstr = '';
438 my $dbh = shift;
439 return ('FAIL',"Need database handle") if !$dbh;
440 my $username = shift;
441 return ('FAIL',"Missing username") if !defined($username);
442 my $group = shift;
443 return ('FAIL',"Missing group") if !defined($group);
444 my $pass = shift;
445 return ('FAIL',"Missing password") if !defined($pass);
446 my $state = shift;
447 return ('FAIL',"Need account status") if !defined($state);
448
449 my $type = shift || 'u'; # create limited users by default - fwiw, not sure yet how this will interact with ACLs
450
451 my $fname = shift || $username;
452 my $lname = shift || '';
453 my $phone = shift || ''; # not going format-check
454
455 my $user_id;
456
457 # Allow transactions, and raise an exception on errors so we can catch it later.
458 # Use local to make sure these get "reset" properly on exiting this block
459 local $dbh->{AutoCommit} = 0;
460 local $dbh->{RaiseError} = 1;
461
462 # Wrap all the SQL in a transaction
463 eval {
464 # insert the user...
465 my $sth = $dbh->prepare("INSERT INTO users (group_id,username,password,firstname,lastname,phone,type,status) ".
466 "VALUES (?,?,?,?,?,?,?,?)");
467 $sth->execute($group,$username,$pass,$fname,$lname,$phone,$type,$state);
468
469 # get the ID...
470 $sth = $dbh->prepare("select user_id from users where username=?");
471 $sth->execute($username);
472 ($user_id) = $sth->fetchrow_array();
473
474##fixme: add another table to hold name/email for log table?
475
476 # once we get here, we should have suceeded.
477 $dbh->commit;
478 }; # end eval
479
480 if ($@) {
481 my $msg = $@;
482 eval { $dbh->rollback; };
483 return ('FAIL',$msg);
484 } else {
485 return ('OK',$user_id);
486 }
487} # end addUser
488
489
490## DNSDB::delUser()
491#
492sub delUser {
493 my $dbh = shift;
494 return ('FAIL',"Need database handle") if !$dbh;
495 my $userid = shift;
496 return ('FAIL',"Missing userid") if !defined($userid);
497
498 my $sth = $dbh->prepare("delete from users where user_id=?");
499 $sth->execute($userid);
500
501 return ('FAIL',"Couldn't remove user: ".$sth->errstr) if $sth->err;
502
503 return ('OK','OK');
504
505} # end delUser
506
507
508## DNSDB::userFullName()
509# Return a pretty string!
510# Takes a user_id and optional printf-ish string to indicate which pieces where:
511# %u for the username
512# %f for the first name
513# %l for the last name
514# All other text in the passed string will be left as-is.
515##fixme: need a "smart" option too, so that missing/null/blank first/last names don't give funky output
516sub userFullName {
517 $errstr = '';
518 my $dbh = shift;
519 my $userid = shift;
520 my $fullformat = shift || '%f %l (%u)';
521 my $sth = $dbh->prepare("select username,firstname,lastname from users where user_id=?");
522 $sth->execute($userid);
523 my ($uname,$fname,$lname) = $sth->fetchrow_array();
524 $errstr = $DBI::errstr if !$uname;
525
526 $fullformat =~ s/\%u/$uname/g;
527 $fullformat =~ s/\%f/$fname/g;
528 $fullformat =~ s/\%l/$lname/g;
529
530 return $fullformat;
531} # end userFullName
532
533
534## DNSDB::editRecord()
535# Change an existing record
536# Takes a database handle, default/live flag, record ID, and new data and updates the data fields for it
537sub editRecord {
538 $errstr = '';
539 my $dbh = shift;
540 my $defflag = shift;
541 my $recid = shift;
542 my $host = shift;
543 my $address = shift;
544 my $distance = shift;
545 my $weight = shift;
546 my $port = shift;
547 my $ttl = shift;
548}
549
550
551## DNSDB::getSOA()
552# Return all suitable fields from an SOA record in separate elements of a hash
553# Takes a database handle, default/live flag, and group (default) or domain (live) ID
554sub getSOA {
555 $errstr = '';
556 my $dbh = shift;
557 my $def = shift;
558 my $id = shift;
559 my %ret;
560
561 my $sql = "select record_id,host,val,ttl from";
562 if ($def eq 'def' or $def eq 'y') {
563 $sql .= " default_records where group_id=$id and type=$reverse_typemap{SOA}";
564 } else {
565 # we're editing a live SOA record; find based on domain
566 $sql .= " records where domain_id=$id and type=$reverse_typemap{SOA}";
567 }
568 my $sth = $dbh->prepare($sql);
569 $sth->execute;
570
571 my ($recid,$host,$val,$ttl) = $sth->fetchrow_array();
572 my ($prins,$contact) = split /:/, $host;
573 my ($refresh,$retry,$expire,$minttl) = split /:/, $val;
574
575 $ret{recid} = $recid;
576 $ret{ttl} = $ttl;
577 $ret{prins} = $prins;
578 $ret{contact} = $contact;
579 $ret{refresh} = $refresh;
580 $ret{retry} = $retry;
581 $ret{expire} = $expire;
582 $ret{minttl} = $minttl;
583
584 return %ret;
585} # end getSOA()
586
587
588## DNSDB::getRecLine()
589# Return all data fields for a zone record in separate elements of a hash
590# Takes a database handle, default/live flag, and record ID
591sub getRecLine {
592 $errstr = '';
593 my $dbh = shift;
594 my $def = shift;
595 my $id = shift;
596
597 my $sql = "select record_id,host,type,val,distance,weight,port,ttl from ".
598 (($def eq 'def' or $def eq 'y') ? 'default_' : '').
599 "records where record_id=$id";
600print "MDEBUG: $sql<br>\n";
601 my $sth = $dbh->prepare($sql);
602 $sth->execute;
603
604 my ($recid,$host,$rtype,$val,$distance,$weight,$port,$ttl) = $sth->fetchrow_array();
605
606 if ($sth->err) {
607 $errstr = $DBI::errstr;
608 return undef;
609 }
610 my %ret;
611 $ret{recid} = $recid;
612 $ret{host} = $host;
613 $ret{type} = $rtype;
614 $ret{val} = $val;
615 $ret{distance}= $distance;
616 $ret{weight} = $weight;
617 $ret{port} = $port;
618 $ret{ttl} = $ttl;
619
620 return %ret;
621}
622
623
624##fixme: should use above (getRecLine()) to get lines for below?
625## DNSDB::getDomRecs()
626# Return records for a domain
627# Takes a database handle, default/live flag, group/domain ID, start,
628# number of records, sort field, and sort order
629# Returns a reference to an array of hashes
630sub getDomRecs {
631 $errstr = '';
632 my $dbh = shift;
633 my $type = shift;
634 my $id = shift;
635 my $nrecs = shift || 'all';
636 my $nstart = shift || 0;
637
638## for order, need to map input to column names
639 my $order = shift || 'host';
640
641 my $sql = "select record_id,host,type,val,distance,weight,port,ttl from";
642 if ($type eq 'def' or $type eq 'y') {
643 $sql .= " default_records where group_id=$id";
644 } else {
645 $sql .= " records where domain_id=$id";
646 }
647 $sql .= " and not type=$reverse_typemap{SOA} order by $order";
648##fixme: need to set nstart properly (offset is not internally multiplied with limit)
649 $sql .= " limit $nrecs offset ".($nstart*$nrecs) if $nstart ne 'all';
650
651 my $sth = $dbh->prepare($sql);
652 $sth->execute;
653
654 my @retbase;
655 while (my $ref = $sth->fetchrow_hashref()) {
656 push @retbase, $ref;
657 }
658
659 my $ret = \@retbase;
660 return $ret;
661} # end getDomRecs()
662
663
664## DNSDB::addRec()
665# Add a new record to a domain or a group's default records
666# Takes a database handle, default/live flag, group/domain ID,
667# host, type, value, and TTL
668# Some types require additional detail: "distance" for MX and SRV,
669# and weight/port for SRV
670# Returns a status code and detail message in case of error
671sub addRec {
672 $errstr = '';
673 my $dbh = shift;
674 my $defrec = shift;
675 my $id = shift;
676
677 my $host = shift;
678 my $rectype = shift;
679 my $val = shift;
680 my $ttl = shift;
681
682 my $fields = ($defrec eq 'y' ? 'group_id' : 'domain_id').",host,type,val,ttl";
683 my $vallen = "?,?,?,?,?";
684 my @vallist = ($id,$host,$rectype,$val,$ttl);
685
686 my $dist;
687 if ($rectype == $reverse_typemap{MX} or $rectype == $reverse_typemap{SRV}) {
688 $dist = shift;
689 return ('FAIL',"Need distance for $typemap{$rectype} record") if !defined($dist);
690 $fields .= ",distance";
691 $vallen .= ",?";
692 push @vallist, $dist;
693 }
694 my $weight;
695 my $port;
696 if ($rectype == $reverse_typemap{SRV}) {
697 # check for _service._protocol. NB: RFC2782 does not say "MUST"... nor "SHOULD"...
698 # it just says (paraphrased) "... is prepended with _ to prevent DNS collisions"
699 return ('FAIL',"SRV records must begin with _service._protocol")
700 if $host !~ /^_[A-Za-z]+\._[A-Za-z]+\.[a-z0-9-]+/;
701 $weight = shift;
702 $port = shift;
703 return ('FAIL',"Need weight and port for SRV record") if !defined($weight) or !defined($port);
704 $fields .= ",weight,port";
705 $vallen .= ",?,?";
706 push @vallist, ($weight,$port);
707 }
708
709 my $sql = "insert into ".($defrec eq 'y' ? 'default_' : '')."records ($fields) values ($vallen)";
710##fixme: use array for values, replace "vallist" with series of ?,?,? etc
711# something is bugging me about this...
712#warn "DEBUG: $sql";
713 my $sth = $dbh->prepare($sql);
714 $sth->execute(@vallist);
715
716 return ('FAIL',$sth->errstr) if $sth->err;
717
718 return ('OK','OK');
719} # end addRec()
720
721
722## DNSDB::updateRec()
723# Update a record
724sub updateRec {
725 $errstr = '';
726
727 my $dbh = shift;
728 my $defrec = shift;
729 my $id = shift;
730
731# all records have these
732 my $host = shift;
733 my $type = shift;
734 my $val = shift;
735 my $ttl = shift;
736
737 return('FAIL',"Missing standard argument(s)") if !defined($ttl);
738
739# only MX and SRV will use these
740 my $dist = 0;
741 my $weight = 0;
742 my $port = 0;
743
744 if ($type == $reverse_typemap{MX} || $type == $reverse_typemap{SRV}) {
745 $dist = shift;
746 return ('FAIL',"MX or SRV requires distance") if !defined($dist);
747 if ($type == $reverse_typemap{SRV}) {
748 $weight = shift;
749 return ('FAIL',"SRV requires weight") if !defined($weight);
750 $port = shift;
751 return ('FAIL',"SRV requires port") if !defined($port);
752 }
753 }
754
755 my $sth = $dbh->prepare("UPDATE ".($defrec eq 'y' ? 'default_' : '')."records ".
756 "SET host=?,type=?,val=?,ttl=?,distance=?,weight=?,port=? ".
757 "WHERE record_id=?");
758 $sth->execute($host,$type,$val,$ttl,$dist,$weight,$port,$id);
759
760 return ('FAIL',$sth->errstr."<br>\n$errstr<br>\n") if $sth->err;
761
762 return ('OK','OK');
763} # end updateRec()
764
765
766## DNSDB::delRec()
767# Delete a record.
768sub delRec {
769 $errstr = '';
770 my $dbh = shift;
771 my $defrec = shift;
772 my $id = shift;
773
774 my $sth = $dbh->prepare("delete from ".($defrec eq 'y' ? 'default_' : '')."records where record_id=?");
775 $sth->execute($id);
776
777 return ('FAIL',"Couldn't remove record: ".$sth->errstr) if $sth->err;
778
779 return ('OK','OK');
780} # end delRec()
781
782
783## DNSDB::domStatus()
784# Sets and/or returns a domain's status
785# Takes a database handle, domain ID and optionally a status argument
786# Returns undef on errors.
787sub domStatus {
788 my $dbh = shift;
789 my $id = shift;
790 my $newstatus = shift;
791
792 return undef if $id !~ /^\d+$/;
793
794 my $sth;
795
796# ooo, fun! let's see what we were passed for status
797 if ($newstatus) {
798 $sth = $dbh->prepare("update domains set status=? where domain_id=?");
799 # ass-u-me caller knows what's going on in full
800 if ($newstatus =~ /^[01]$/) { # only two valid for now.
801 $sth->execute($newstatus,$id);
802 } elsif ($newstatus =~ /^domo(?:n|ff)$/) {
803 $sth->execute(($newstatus eq 'domon' ? 1 : 0),$id);
804 }
805 }
806
807 $sth = $dbh->prepare("select status from domains where domain_id=?");
808 $sth->execute($id);
809 my ($status) = $sth->fetchrow_array;
810 return $status;
811} # end domStatus()
812
813
814## DNSDB::importAXFR
815# Import a domain via AXFR
816sub importAXFR {
817 my $dbh = shift;
818 my $ifrom = shift;
819 my $domain = shift;
820 my $group = shift;
821 my $status = shift || 1;
822 my $rwsoa = shift || 0;
823 my $rwns = shift || 0;
824##fixme: add mode to delete&replace, merge+overwrite, merge new?
825
826 my $res = Net::DNS::Resolver->new;
827$res->axfr_start($domain);
828my $nrecs = 0;
829my $flags = 0;
830
831 # Allow transactions, and raise an exception on errors so we can catch it later.
832 # Use local to make sure these get "reset" properly on exiting this block
833 local $dbh->{AutoCommit} = 0;
834 local $dbh->{RaiseError} = 1;
835
836 eval {
837 # can't do this, can't nest transactions. sigh.
838 #my ($dcode, $dmsg) = addDomain($dbh, $domain, $group, $status);
839
840##fixme: serial
841 my $sth = $dbh->prepare("INSERT INTO domains (domain,group_id,status) VALUES (?,?,?)");
842 $sth->execute($domain,$group,$state);
843
844 # get domain id so we can do the records
845 $sth = $dbh->prepare("select domain_id from domains where domain='$domain'");
846 $sth->execute;
847 ($dom_id) = $sth->fetchrow_array();
848
849 while (my $rr = $res->axfr_next) {
850 my $type = $rr->type;
851# nasty big ugly case-like thing here, since we have to do *some* different
852# processing depending on the record. le sigh.
853 my $sql = "INSERT INTO records (domain_id,host,type,val,ttl";
854 my $vallen = "?,?,?,?,?";
855 my $host,$val;
856
857##work
858# gnnnnnh. going to need to (rr->string) -> split -> <localvars>
859my @vallist;
860 if ($type eq 'SOA') {
861 $host = $rr->mname.":".$rr->rname;
862 $val = $rr->refresh.":".$rr->retry.":".$rr->expire.":".$rr->minimum;
863 }
864 if ($type eq 'MX' || $type eq 'SRV') {
865 $sql .= ",distance";
866 $vallen .= ",?";
867 $sql .= ",weight,port" if $type eq 'SRV';
868 $vallen .= ",?,?" if $type eq 'SRV';
869 }
870$sth = $dbh->prepare($sql.") VALUES (".$vallen.")");
871$sth->execute(@vallist);
872
873 #print $rr->rdata."\n";
874 }
875 };
876
877 if ($@) {
878 my $msg = $@;
879 eval { $dbh->rollback; };
880 return ('FAIL',$msg);
881 } else {
882 return ('OK',"ook");
883 }
884
885 return ('WARN',"
886} # end importAXFR()
887
888
889# shut Perl up
8901;
Note: See TracBrowser for help on using the repository browser.