1 | # dns/trunk/DNSDB.pm
|
---|
2 | # Abstraction functions for DNS administration
|
---|
3 | ###
|
---|
4 | # SVN revision info
|
---|
5 | # $Date: 2011-09-08 22:09:58 +0000 (Thu, 08 Sep 2011) $
|
---|
6 | # SVN revision $Rev: 121 $
|
---|
7 | # Last update by $Author: kdeugau $
|
---|
8 | ###
|
---|
9 | # Copyright (C) 2008 - Kris Deugau <kdeugau@deepnet.cx>
|
---|
10 |
|
---|
11 | package DNSDB;
|
---|
12 |
|
---|
13 | use strict;
|
---|
14 | use warnings;
|
---|
15 | use Exporter;
|
---|
16 | use DBI;
|
---|
17 | use Net::DNS;
|
---|
18 | use Crypt::PasswdMD5;
|
---|
19 | #use Net::SMTP;
|
---|
20 | #use NetAddr::IP qw( Compact );
|
---|
21 | #use POSIX;
|
---|
22 | use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
|
---|
23 |
|
---|
24 | $VERSION = 0.1;
|
---|
25 | @ISA = qw(Exporter);
|
---|
26 | @EXPORT_OK = qw(
|
---|
27 | &initGlobals
|
---|
28 | &initPermissions &getPermissions &changePermissions &comparePermissions
|
---|
29 | &changeGroup
|
---|
30 | &connectDB &finish
|
---|
31 | &addDomain &delDomain &domainName &domainID
|
---|
32 | &addGroup &delGroup &getChildren &groupName
|
---|
33 | &addUser &updateUser &delUser &userFullName &userStatus &getUserData
|
---|
34 | &getSOA &getRecLine &getDomRecs &getRecCount
|
---|
35 | &addRec &updateRec &delRec
|
---|
36 | &getParents
|
---|
37 | &isParent
|
---|
38 | &domStatus &importAXFR
|
---|
39 | &export
|
---|
40 | %typemap %reverse_typemap
|
---|
41 | %permissions @permtypes $permlist
|
---|
42 | );
|
---|
43 |
|
---|
44 | @EXPORT = (); # Export nothing by default.
|
---|
45 | %EXPORT_TAGS = ( ALL => [qw(
|
---|
46 | &initGlobals
|
---|
47 | &initPermissions &getPermissions &changePermissions &comparePermissions
|
---|
48 | &changeGroup
|
---|
49 | &connectDB &finish
|
---|
50 | &addDomain &delDomain &domainName &domainID
|
---|
51 | &addGroup &delGroup &getChildren &groupName
|
---|
52 | &addUser &updateUser &delUser &userFullName &userStatus &getUserData
|
---|
53 | &getSOA &getRecLine &getDomRecs &getRecCount
|
---|
54 | &addRec &updateRec &delRec
|
---|
55 | &getParents
|
---|
56 | &isParent
|
---|
57 | &domStatus &importAXFR
|
---|
58 | &export
|
---|
59 | %typemap %reverse_typemap
|
---|
60 | %permissions @permtypes $permlist
|
---|
61 | )]
|
---|
62 | );
|
---|
63 |
|
---|
64 | our $group = 1;
|
---|
65 | our $errstr = '';
|
---|
66 |
|
---|
67 | # Halfway sane defaults for SOA, TTL, etc.
|
---|
68 | # serial defaults to 0 for convenience.
|
---|
69 | # value will be either YYYYMMDDNN for BIND/etc, or auto-internal for tinydns
|
---|
70 | our %def = qw (
|
---|
71 | contact hostmaster.DOMAIN
|
---|
72 | prins ns1.myserver.com
|
---|
73 | serial 0
|
---|
74 | soattl 86400
|
---|
75 | refresh 10800
|
---|
76 | retry 3600
|
---|
77 | expire 604800
|
---|
78 | minttl 10800
|
---|
79 | ttl 10800
|
---|
80 | );
|
---|
81 |
|
---|
82 | # Arguably defined wholly in the db, but little reason to change without supporting code changes
|
---|
83 | our @permtypes = qw (
|
---|
84 | group_edit group_create group_delete
|
---|
85 | user_edit user_create user_delete
|
---|
86 | domain_edit domain_create domain_delete
|
---|
87 | record_edit record_create record_delete
|
---|
88 | self_edit admin
|
---|
89 | );
|
---|
90 | our $permlist = join(',',@permtypes);
|
---|
91 |
|
---|
92 | # DNS record type map and reverse map.
|
---|
93 | # loaded from the database, from http://www.iana.org/assignments/dns-parameters
|
---|
94 | our %typemap;
|
---|
95 | our %reverse_typemap;
|
---|
96 |
|
---|
97 | our %permissions;
|
---|
98 |
|
---|
99 | ##
|
---|
100 | ## Initialization and cleanup subs
|
---|
101 | ##
|
---|
102 |
|
---|
103 |
|
---|
104 | ## DNSDB::connectDB()
|
---|
105 | # Creates connection to DNS database.
|
---|
106 | # Requires the database name, username, and password.
|
---|
107 | # Returns a handle to the db.
|
---|
108 | # Set up for a PostgreSQL db; could be any transactional DBMS with the
|
---|
109 | # right changes.
|
---|
110 | sub connectDB {
|
---|
111 | $errstr = '';
|
---|
112 | my $dbname = shift;
|
---|
113 | my $user = shift;
|
---|
114 | my $pass = shift;
|
---|
115 | my $dbh;
|
---|
116 | my $DSN = "DBI:Pg:dbname=$dbname";
|
---|
117 |
|
---|
118 | my $host = shift;
|
---|
119 | $DSN .= ";host=$host" if $host;
|
---|
120 |
|
---|
121 | # Note that we want to autocommit by default, and we will turn it off locally as necessary.
|
---|
122 | # We may not want to print gobbledygook errors; YMMV. Have to ponder that further.
|
---|
123 | $dbh = DBI->connect($DSN, $user, $pass, {
|
---|
124 | AutoCommit => 1,
|
---|
125 | PrintError => 0
|
---|
126 | })
|
---|
127 | or return (undef, $DBI::errstr) if(!$dbh);
|
---|
128 |
|
---|
129 | # Return here if we can't select. Note that this indicates a
|
---|
130 | # problem executing the select.
|
---|
131 | my $sth = $dbh->prepare("select group_id from groups limit 1");
|
---|
132 | $sth->execute();
|
---|
133 | return (undef,$DBI::errstr) if ($sth->err);
|
---|
134 |
|
---|
135 | # See if the select returned anything (or null data). This should
|
---|
136 | # succeed if the select executed, but...
|
---|
137 | $sth->fetchrow();
|
---|
138 | return (undef,$DBI::errstr) if ($sth->err);
|
---|
139 |
|
---|
140 | $sth->finish;
|
---|
141 |
|
---|
142 | # If we get here, we should be OK.
|
---|
143 | return ($dbh,"DB connection OK");
|
---|
144 | } # end connectDB
|
---|
145 |
|
---|
146 |
|
---|
147 | ## DNSDB::finish()
|
---|
148 | # Cleans up after database handles and so on.
|
---|
149 | # Requires a database handle
|
---|
150 | sub finish {
|
---|
151 | my $dbh = $_[0];
|
---|
152 | $dbh->disconnect;
|
---|
153 | } # end finish
|
---|
154 |
|
---|
155 |
|
---|
156 | ## DNSDB::initGlobals()
|
---|
157 | # Initialize global variables
|
---|
158 | # NB: this does NOT include web-specific session variables!
|
---|
159 | # Requires a database handle
|
---|
160 | sub initGlobals {
|
---|
161 | my $dbh = shift;
|
---|
162 |
|
---|
163 | # load system-wide site defaults and things from config file
|
---|
164 | if (open SYSDEFAULTS, "</etc/dnsdb.conf") {
|
---|
165 | ##fixme - error check!
|
---|
166 | while (<SYSDEFAULTS>) {
|
---|
167 | next if /^\s*#/;
|
---|
168 | $def{contact} = $1 if /contact ?= ?([a-z0-9_.-]+)/i;
|
---|
169 | $def{prins} = $1 if /prins ?= ?([a-z0-9_.-]+)/i;
|
---|
170 | $def{soattl} = $1 if /soattl ?= ?([a-z0-9_.-]+)/i;
|
---|
171 | $def{refresh} = $1 if /refresh ?= ?([a-z0-9_.-]+)/i;
|
---|
172 | $def{retry} = $1 if /retry ?= ?([a-z0-9_.-]+)/i;
|
---|
173 | $def{expire} = $1 if /expire ?= ?([a-z0-9_.-]+)/i;
|
---|
174 | $def{minttl} = $1 if /minttl ?= ?([a-z0-9_.-]+)/i;
|
---|
175 | $def{ttl} = $1 if /ttl ?= ?([a-z0-9_.-]+)/i;
|
---|
176 | ##fixme? load DB user/pass from config file?
|
---|
177 | }
|
---|
178 | }
|
---|
179 | # load from database
|
---|
180 | my $sth = $dbh->prepare("select val,name from rectypes");
|
---|
181 | $sth->execute;
|
---|
182 | while (my ($recval,$recname) = $sth->fetchrow_array()) {
|
---|
183 | $typemap{$recval} = $recname;
|
---|
184 | $reverse_typemap{$recname} = $recval;
|
---|
185 | }
|
---|
186 | } # end initGlobals
|
---|
187 |
|
---|
188 |
|
---|
189 | ## DNSDB::initPermissions()
|
---|
190 | # Set up permissions global
|
---|
191 | # Takes database handle and UID
|
---|
192 | sub initPermissions {
|
---|
193 | my $dbh = shift;
|
---|
194 | my $uid = shift;
|
---|
195 |
|
---|
196 | # %permissions = $(getPermissions($dbh,'user',$uid));
|
---|
197 | getPermissions($dbh, 'user', $uid, \%permissions);
|
---|
198 |
|
---|
199 | } # end initPermissions()
|
---|
200 |
|
---|
201 |
|
---|
202 | ## DNSDB::getPermissions()
|
---|
203 | # Get permissions from DB
|
---|
204 | # Requires DB handle, group or user flag, ID, and hashref.
|
---|
205 | sub getPermissions {
|
---|
206 | my $dbh = shift;
|
---|
207 | my $type = shift;
|
---|
208 | my $id = shift;
|
---|
209 | my $hash = shift;
|
---|
210 |
|
---|
211 | my $sql = qq(
|
---|
212 | SELECT
|
---|
213 | p.admin,p.self_edit,
|
---|
214 | p.group_create,p.group_edit,p.group_delete,
|
---|
215 | p.user_create,p.user_edit,p.user_delete,
|
---|
216 | p.domain_create,p.domain_edit,p.domain_delete,
|
---|
217 | p.record_create,p.record_edit,p.record_delete
|
---|
218 | FROM permissions p
|
---|
219 | );
|
---|
220 | if ($type eq 'group') {
|
---|
221 | $sql .= qq(
|
---|
222 | JOIN groups g ON g.permission_id=p.permission_id
|
---|
223 | WHERE g.group_id=?
|
---|
224 | );
|
---|
225 | } else {
|
---|
226 | $sql .= qq(
|
---|
227 | JOIN users u ON u.permission_id=p.permission_id
|
---|
228 | WHERE u.user_id=?
|
---|
229 | );
|
---|
230 | }
|
---|
231 |
|
---|
232 | my $sth = $dbh->prepare($sql);
|
---|
233 |
|
---|
234 | $sth->execute($id) or die "argh: ".$sth->errstr;
|
---|
235 |
|
---|
236 | # my $permref = $sth->fetchrow_hashref;
|
---|
237 | # return $permref;
|
---|
238 | # $hash = $permref;
|
---|
239 | # Eww. Need to learn how to forcibly drop a hashref onto an existing hash.
|
---|
240 | ($hash->{admin},$hash->{self_edit},
|
---|
241 | $hash->{group_create},$hash->{group_edit},$hash->{group_delete},
|
---|
242 | $hash->{user_create},$hash->{user_edit},$hash->{user_delete},
|
---|
243 | $hash->{domain_create},$hash->{domain_edit},$hash->{domain_delete},
|
---|
244 | $hash->{record_create},$hash->{record_edit},$hash->{record_delete})
|
---|
245 | = $sth->fetchrow_array;
|
---|
246 |
|
---|
247 | } # end getPermissions()
|
---|
248 |
|
---|
249 |
|
---|
250 | ## DNSDB::changePermissions()
|
---|
251 | # Update an ACL entry
|
---|
252 | # Takes a db handle, type, owner-id, and hashref for the changed permissions.
|
---|
253 | sub changePermissions {
|
---|
254 | my $dbh = shift;
|
---|
255 | my $type = shift;
|
---|
256 | my $id = shift;
|
---|
257 | my $newperms = shift;
|
---|
258 | my $inherit = shift || 0;
|
---|
259 |
|
---|
260 | my $failmsg = '';
|
---|
261 |
|
---|
262 | # see if we're switching from inherited to custom. for bonus points,
|
---|
263 | # snag the permid and parent permid anyway, since we'll need the permid
|
---|
264 | # to set/alter custom perms, and both if we're switching from custom to
|
---|
265 | # inherited.
|
---|
266 | my $sth = $dbh->prepare("SELECT (u.permission_id=g.permission_id) AS was_inherited,u.permission_id,g.permission_id".
|
---|
267 | " FROM ".($type eq 'user' ? 'users' : 'groups')." u ".
|
---|
268 | " JOIN groups g ON u.".($type eq 'user' ? '' : 'parent_')."group_id=g.group_id ".
|
---|
269 | " WHERE u.".($type eq 'user' ? 'user' : 'group')."_id=?");
|
---|
270 | $sth->execute($id);
|
---|
271 |
|
---|
272 | my ($wasinherited,$permid,$parpermid) = $sth->fetchrow_array;
|
---|
273 |
|
---|
274 | # hack phtoui
|
---|
275 | # group id 1 is "special" in that it's it's own parent (err... possibly.)
|
---|
276 | # may make its parent id 0 which doesn't exist, and as a bonus is Perl-false.
|
---|
277 | $wasinherited = 0 if ($type eq 'group' && $id == 1);
|
---|
278 |
|
---|
279 | local $dbh->{AutoCommit} = 0;
|
---|
280 | local $dbh->{RaiseError} = 1;
|
---|
281 |
|
---|
282 | # Wrap all the SQL in a transaction
|
---|
283 | eval {
|
---|
284 | if ($inherit) {
|
---|
285 |
|
---|
286 | $dbh->do("UPDATE ".($type eq 'user' ? 'users' : 'groups')." SET inherit_perm='t',permission_id=? ".
|
---|
287 | "WHERE ".($type eq 'user' ? 'user' : 'group')."_id=?", undef, ($parpermid, $id) );
|
---|
288 | $dbh->do("DELETE FROM permissions WHERE permission_id=?", undef, ($permid) );
|
---|
289 |
|
---|
290 | } else {
|
---|
291 |
|
---|
292 | if ($wasinherited) { # munge new permission entry in if we're switching from inherited perms
|
---|
293 | ##fixme: need to add semirecursive bit to properly munge inherited permission ID on subgroups and users
|
---|
294 | # ... if'n'when we have groups with fully inherited permissions.
|
---|
295 | # SQL is coo
|
---|
296 | $dbh->do("INSERT INTO permissions ($permlist,".($type eq 'user' ? 'user' : 'group')."_id) ".
|
---|
297 | "SELECT $permlist,? FROM permissions WHERE permission_id=?", undef, ($id,$permid) );
|
---|
298 | ($permid) = $dbh->selectrow_array("SELECT permission_id FROM permissions ".
|
---|
299 | "WHERE ".($type eq 'user' ? 'user' : 'group')."_id=?", undef, ($id) );
|
---|
300 | $dbh->do("UPDATE ".($type eq 'user' ? 'users' : 'groups')." SET inherit_perm='f',permission_id=? ".
|
---|
301 | "WHERE ".($type eq 'user' ? 'user' : 'group')."_id=?", undef, ($permid, $id) );
|
---|
302 | }
|
---|
303 |
|
---|
304 | # and now set the permissions we were passed
|
---|
305 | foreach (@permtypes) {
|
---|
306 | if (defined ($newperms->{$_})) {
|
---|
307 | $dbh->do("UPDATE permissions SET $_=? WHERE permission_id=?", undef, ($newperms->{$_},$permid) );
|
---|
308 | }
|
---|
309 | }
|
---|
310 |
|
---|
311 | } # (inherited->)? custom
|
---|
312 |
|
---|
313 | $dbh->commit;
|
---|
314 | }; # end eval
|
---|
315 | if ($@) {
|
---|
316 | my $msg = $@;
|
---|
317 | eval { $dbh->rollback; };
|
---|
318 | return ('FAIL',"$failmsg: $msg ($permid)");
|
---|
319 | } else {
|
---|
320 | return ('OK',$permid);
|
---|
321 | }
|
---|
322 |
|
---|
323 | } # end changePermissions()
|
---|
324 |
|
---|
325 |
|
---|
326 | ## DNSDB::comparePermissions()
|
---|
327 | # Compare two permission hashes
|
---|
328 | # Returns '>', '<', '=', '!'
|
---|
329 | sub comparePermissions {
|
---|
330 | my $p1 = shift;
|
---|
331 | my $p2 = shift;
|
---|
332 |
|
---|
333 | my $retval = '='; # assume equality until proven otherwise
|
---|
334 |
|
---|
335 | no warnings "uninitialized";
|
---|
336 |
|
---|
337 | foreach (@permtypes) {
|
---|
338 | next if $p1->{$_} == $p2->{$_}; # equal is good
|
---|
339 | if ($p1->{$_} && !$p2->{$_}) {
|
---|
340 | if ($retval eq '<') { # if we've already found an unequal pair where
|
---|
341 | $retval = '!'; # $p2 has more access, and we now find a pair
|
---|
342 | last; # where $p1 has more access, the overall access
|
---|
343 | } # is neither greater or lesser, it's unequal.
|
---|
344 | $retval = '>';
|
---|
345 | }
|
---|
346 | if (!$p1->{$_} && $p2->{$_}) {
|
---|
347 | if ($retval eq '>') { # if we've already found an unequal pair where
|
---|
348 | $retval = '!'; # $p1 has more access, and we now find a pair
|
---|
349 | last; # where $p2 has more access, the overall access
|
---|
350 | } # is neither greater or lesser, it's unequal.
|
---|
351 | $retval = '<';
|
---|
352 | }
|
---|
353 | }
|
---|
354 | return $retval;
|
---|
355 | } # end comparePermissions()
|
---|
356 |
|
---|
357 |
|
---|
358 | ## DNSDB::changeGroup()
|
---|
359 | # Change group ID of an entity
|
---|
360 | # Takes a database handle, entity type, entity ID, and new group ID
|
---|
361 | sub changeGroup {
|
---|
362 | my $dbh = shift;
|
---|
363 | my $type = shift;
|
---|
364 | my $id = shift;
|
---|
365 | my $newgrp = shift;
|
---|
366 |
|
---|
367 | ##fixme: fail on not enough args
|
---|
368 | #return ('FAIL', "Missing
|
---|
369 |
|
---|
370 | if ($type eq 'domain') {
|
---|
371 | $dbh->do("UPDATE domains SET group_id=? WHERE domain_id=?", undef, ($newgrp, $id))
|
---|
372 | or return ('FAIL','Group change failed: '.$dbh->errstr);
|
---|
373 | } elsif ($type eq 'user') {
|
---|
374 | $dbh->do("UPDATE users SET group_id=? WHERE user_id=?", undef, ($newgrp, $id))
|
---|
375 | or return ('FAIL','Group change failed: '.$dbh->errstr);
|
---|
376 | } elsif ($type eq 'group') {
|
---|
377 | $dbh->do("UPDATE groups SET parent_group_id=? WHERE group_id=?", undef, ($newgrp, $id))
|
---|
378 | or return ('FAIL','Group change failed: '.$dbh->errstr);
|
---|
379 | }
|
---|
380 | return ('OK','OK');
|
---|
381 | } # end changeGroup()
|
---|
382 |
|
---|
383 |
|
---|
384 | ## DNSDB::_log()
|
---|
385 | # Log an action
|
---|
386 | # Internal sub
|
---|
387 | # Takes a database handle, <foo>, <bar>
|
---|
388 | sub _log {
|
---|
389 | } # end _log
|
---|
390 |
|
---|
391 |
|
---|
392 | ##
|
---|
393 | ## Processing subs
|
---|
394 | ##
|
---|
395 |
|
---|
396 | ## DNSDB::addDomain()
|
---|
397 | # Add a domain
|
---|
398 | # Takes a database handle, domain name, numeric group, and boolean(ish) state (active/inactive)
|
---|
399 | # Returns a status code and message
|
---|
400 | sub addDomain {
|
---|
401 | $errstr = '';
|
---|
402 | my $dbh = shift;
|
---|
403 | return ('FAIL',"Need database handle") if !$dbh;
|
---|
404 | my $domain = shift;
|
---|
405 | return ('FAIL',"Domain must not be blank") if !$domain;
|
---|
406 | my $group = shift;
|
---|
407 | return ('FAIL',"Need group") if !defined($group);
|
---|
408 | my $state = shift;
|
---|
409 | return ('FAIL',"Need domain status") if !defined($state);
|
---|
410 |
|
---|
411 | $state = 1 if $state =~ /^active$/;
|
---|
412 | $state = 1 if $state =~ /^on$/;
|
---|
413 | $state = 0 if $state =~ /^inactive$/;
|
---|
414 | $state = 0 if $state =~ /^off$/;
|
---|
415 |
|
---|
416 | return ('FAIL',"Invalid domain status") if $state !~ /^\d+$/;
|
---|
417 |
|
---|
418 | my $sth = $dbh->prepare("SELECT domain_id FROM domains WHERE domain=?");
|
---|
419 | my $dom_id;
|
---|
420 |
|
---|
421 | # quick check to start to see if we've already got one
|
---|
422 | $sth->execute($domain);
|
---|
423 | ($dom_id) = $sth->fetchrow_array;
|
---|
424 |
|
---|
425 | return ('FAIL', "Domain already exists") if $dom_id;
|
---|
426 |
|
---|
427 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
428 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
429 | local $dbh->{AutoCommit} = 0;
|
---|
430 | local $dbh->{RaiseError} = 1;
|
---|
431 |
|
---|
432 | # Wrap all the SQL in a transaction
|
---|
433 | eval {
|
---|
434 | # insert the domain...
|
---|
435 | my $sth = $dbh->prepare("insert into domains (domain,group_id,status) values (?,?,?)");
|
---|
436 | $sth->execute($domain,$group,$state);
|
---|
437 |
|
---|
438 | # get the ID...
|
---|
439 | $sth = $dbh->prepare("select domain_id from domains where domain='$domain'");
|
---|
440 | $sth->execute;
|
---|
441 | ($dom_id) = $sth->fetchrow_array();
|
---|
442 |
|
---|
443 | # ... and now we construct the standard records from the default set. NB: group should be variable.
|
---|
444 | $sth = $dbh->prepare("select host,type,val,distance,weight,port,ttl from default_records where group_id=$group");
|
---|
445 | my $sth_in = $dbh->prepare("insert into records (domain_id,host,type,val,distance,weight,port,ttl)".
|
---|
446 | " values ($dom_id,?,?,?,?,?,?,?)");
|
---|
447 | $sth->execute;
|
---|
448 | while (my ($host,$type,$val,$dist,$weight,$port,$ttl) = $sth->fetchrow_array()) {
|
---|
449 | $host =~ s/DOMAIN/$domain/g;
|
---|
450 | $val =~ s/DOMAIN/$domain/g;
|
---|
451 | $sth_in->execute($host,$type,$val,$dist,$weight,$port,$ttl);
|
---|
452 | }
|
---|
453 |
|
---|
454 | # once we get here, we should have suceeded.
|
---|
455 | $dbh->commit;
|
---|
456 | }; # end eval
|
---|
457 |
|
---|
458 | if ($@) {
|
---|
459 | my $msg = $@;
|
---|
460 | eval { $dbh->rollback; };
|
---|
461 | return ('FAIL',$msg);
|
---|
462 | } else {
|
---|
463 | return ('OK',$dom_id);
|
---|
464 | }
|
---|
465 | } # end addDomain
|
---|
466 |
|
---|
467 |
|
---|
468 | ## DNSDB::delDomain()
|
---|
469 | # Delete a domain.
|
---|
470 | # for now, just delete the records, then the domain.
|
---|
471 | # later we may want to archive it in some way instead (status code 2, for example?)
|
---|
472 | sub delDomain {
|
---|
473 | my $dbh = shift;
|
---|
474 | my $domid = shift;
|
---|
475 |
|
---|
476 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
477 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
478 | local $dbh->{AutoCommit} = 0;
|
---|
479 | local $dbh->{RaiseError} = 1;
|
---|
480 |
|
---|
481 | my $failmsg = '';
|
---|
482 |
|
---|
483 | # Wrap all the SQL in a transaction
|
---|
484 | eval {
|
---|
485 | my $sth = $dbh->prepare("delete from records where domain_id=?");
|
---|
486 | $failmsg = "Failure removing domain records";
|
---|
487 | $sth->execute($domid);
|
---|
488 | $sth = $dbh->prepare("delete from domains where domain_id=?");
|
---|
489 | $failmsg = "Failure removing domain";
|
---|
490 | $sth->execute($domid);
|
---|
491 |
|
---|
492 | # once we get here, we should have suceeded.
|
---|
493 | $dbh->commit;
|
---|
494 | }; # end eval
|
---|
495 |
|
---|
496 | if ($@) {
|
---|
497 | my $msg = $@;
|
---|
498 | eval { $dbh->rollback; };
|
---|
499 | return ('FAIL',"$failmsg: $msg");
|
---|
500 | } else {
|
---|
501 | return ('OK','OK');
|
---|
502 | }
|
---|
503 |
|
---|
504 | } # end delDomain()
|
---|
505 |
|
---|
506 |
|
---|
507 | ## DNSDB::domainName()
|
---|
508 | # Return the domain name based on a domain ID
|
---|
509 | # Takes a database handle and the domain ID
|
---|
510 | # Returns the domain name or undef on failure
|
---|
511 | sub domainName {
|
---|
512 | $errstr = '';
|
---|
513 | my $dbh = shift;
|
---|
514 | my $domid = shift;
|
---|
515 | my ($domname) = $dbh->selectrow_array("SELECT domain FROM domains WHERE domain_id=?", undef, ($domid) );
|
---|
516 | $errstr = $DBI::errstr if !$domname;
|
---|
517 | return $domname if $domname;
|
---|
518 | } # end domainName()
|
---|
519 |
|
---|
520 |
|
---|
521 | ## DNSDB::domainID()
|
---|
522 | # Takes a database handle and domain name
|
---|
523 | # Returns the domain ID number
|
---|
524 | sub domainID {
|
---|
525 | $errstr = '';
|
---|
526 | my $dbh = shift;
|
---|
527 | my $domain = shift;
|
---|
528 | my ($domid) = $dbh->selectrow_array("SELECT domain_id FROM domains WHERE domain=?", undef, ($domain) );
|
---|
529 | $errstr = $DBI::errstr if !$domid;
|
---|
530 | return $domid if $domid;
|
---|
531 | } # end domainID()
|
---|
532 |
|
---|
533 |
|
---|
534 | ## DNSDB::addGroup()
|
---|
535 | # Add a group
|
---|
536 | # Takes a database handle, group name, parent group, hashref for permissions,
|
---|
537 | # and optional template-vs-cloneme flag
|
---|
538 | # Returns a status code and message
|
---|
539 | sub addGroup {
|
---|
540 | $errstr = '';
|
---|
541 | my $dbh = shift;
|
---|
542 | my $groupname = shift;
|
---|
543 | my $pargroup = shift;
|
---|
544 | my $permissions = shift;
|
---|
545 |
|
---|
546 | # 0 indicates "custom", hardcoded.
|
---|
547 | # Any other value clones that group's default records, if it exists.
|
---|
548 | my $inherit = shift || 0;
|
---|
549 | ##fixme: need a flag to indicate clone records or <?> ?
|
---|
550 |
|
---|
551 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
552 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
553 | local $dbh->{AutoCommit} = 0;
|
---|
554 | local $dbh->{RaiseError} = 1;
|
---|
555 |
|
---|
556 | my $sth = $dbh->prepare("SELECT group_id FROM groups WHERE group_name=?");
|
---|
557 | my $group_id;
|
---|
558 |
|
---|
559 | # quick check to start to see if we've already got one
|
---|
560 | $sth->execute($groupname);
|
---|
561 | ($group_id) = $sth->fetchrow_array;
|
---|
562 |
|
---|
563 | return ('FAIL', "Group already exists") if $group_id;
|
---|
564 |
|
---|
565 | # Wrap all the SQL in a transaction
|
---|
566 | eval {
|
---|
567 | $sth = $dbh->prepare("INSERT INTO groups (parent_group_id,group_name) VALUES (?,?)");
|
---|
568 | $sth->execute($pargroup,$groupname);
|
---|
569 |
|
---|
570 | $sth = $dbh->prepare("SELECT group_id FROM groups WHERE group_name=?");
|
---|
571 | $sth->execute($groupname);
|
---|
572 | my ($groupid) = $sth->fetchrow_array();
|
---|
573 |
|
---|
574 | # Permissions
|
---|
575 | if ($inherit) {
|
---|
576 | } else {
|
---|
577 | my @permvals;
|
---|
578 | foreach (@permtypes) {
|
---|
579 | if (!defined ($permissions->{$_})) {
|
---|
580 | push @permvals, 0;
|
---|
581 | } else {
|
---|
582 | push @permvals, $permissions->{$_};
|
---|
583 | }
|
---|
584 | }
|
---|
585 |
|
---|
586 | $sth = $dbh->prepare("INSERT INTO permissions (group_id,$permlist) values (?".',?'x($#permtypes+1).")");
|
---|
587 | $sth->execute($groupid,@permvals);
|
---|
588 |
|
---|
589 | $sth = $dbh->prepare("SELECT permission_id FROM permissions WHERE group_id=?");
|
---|
590 | $sth->execute($groupid);
|
---|
591 | my ($permid) = $sth->fetchrow_array();
|
---|
592 |
|
---|
593 | $dbh->do("UPDATE groups SET permission_id=$permid WHERE group_id=$groupid");
|
---|
594 | } # done permission fiddling
|
---|
595 |
|
---|
596 | # Default records
|
---|
597 | $sth = $dbh->prepare("INSERT INTO default_records (group_id,host,type,val,distance,weight,port,ttl) ".
|
---|
598 | "VALUES ($groupid,?,?,?,?,?,?,?)");
|
---|
599 | if ($inherit) {
|
---|
600 | # Duplicate records from parent. Actually relying on inherited records feels
|
---|
601 | # very fragile, and it would be problematic to roll over at a later time.
|
---|
602 | my $sth2 = $dbh->prepare("SELECT host,type,val,distance,weight,port,ttl FROM default_records WHERE group_id=?");
|
---|
603 | $sth2->execute($pargroup);
|
---|
604 | while (my @clonedata = $sth2->fetchrow_array) {
|
---|
605 | $sth->execute(@clonedata);
|
---|
606 | }
|
---|
607 | } else {
|
---|
608 | ##fixme: Hardcoding is Bad, mmmmkaaaay?
|
---|
609 | # reasonable basic defaults for SOA, MX, NS, and minimal hosting
|
---|
610 | # could load from a config file, but somewhere along the line we need hardcoded bits.
|
---|
611 | $sth->execute('ns1.example.com:hostmaster.example.com', 6, '10800:3600:604800:10800', 0, 0, 0, 86400);
|
---|
612 | $sth->execute('DOMAIN', 1, '192.168.4.2', 0, 0, 0, 7200);
|
---|
613 | $sth->execute('DOMAIN', 15, 'mx.example.com', 10, 0, 0, 7200);
|
---|
614 | $sth->execute('DOMAIN', 2, 'ns1.example.com', 0, 0, 0, 7200);
|
---|
615 | $sth->execute('DOMAIN', 2, 'ns2.example.com', 0, 0, 0, 7200);
|
---|
616 | $sth->execute('www.DOMAIN', 5, 'DOMAIN', 0, 0, 0, 7200);
|
---|
617 | }
|
---|
618 |
|
---|
619 | # once we get here, we should have suceeded.
|
---|
620 | $dbh->commit;
|
---|
621 | }; # end eval
|
---|
622 |
|
---|
623 | if ($@) {
|
---|
624 | my $msg = $@;
|
---|
625 | eval { $dbh->rollback; };
|
---|
626 | return ('FAIL',$msg);
|
---|
627 | } else {
|
---|
628 | return ('OK','OK');
|
---|
629 | }
|
---|
630 |
|
---|
631 | } # end addGroup()
|
---|
632 |
|
---|
633 |
|
---|
634 | ## DNSDB::delGroup()
|
---|
635 | # Delete a group.
|
---|
636 | # Takes a group ID
|
---|
637 | # Returns a status code and message
|
---|
638 | sub delGroup {
|
---|
639 | my $dbh = shift;
|
---|
640 | my $groupid = shift;
|
---|
641 |
|
---|
642 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
643 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
644 | local $dbh->{AutoCommit} = 0;
|
---|
645 | local $dbh->{RaiseError} = 1;
|
---|
646 |
|
---|
647 | ##fixme: locate "knowable" error conditions and deal with them before the eval
|
---|
648 | # ... or inside, whatever.
|
---|
649 | # -> domains still exist in group
|
---|
650 | # -> ...
|
---|
651 | my $failmsg = '';
|
---|
652 |
|
---|
653 | # Wrap all the SQL in a transaction
|
---|
654 | eval {
|
---|
655 | my $sth = $dbh->prepare("SELECT count(*) FROM domains WHERE group_id=?");
|
---|
656 | $sth->execute($groupid);
|
---|
657 | my ($domcnt) = $sth->fetchrow_array;
|
---|
658 | $failmsg = "Can't remove group ".groupName($dbh,$groupid);
|
---|
659 | die "$domcnt domains still in group\n" if $domcnt;
|
---|
660 |
|
---|
661 | $sth = $dbh->prepare("delete from default_records where group_id=?");
|
---|
662 | $failmsg = "Failed to delete default records for ".groupName($dbh,$groupid);
|
---|
663 | $sth->execute($groupid);
|
---|
664 | $sth = $dbh->prepare("delete from groups where group_id=?");
|
---|
665 | $failmsg = "Failed to remove group ".groupName($dbh,$groupid);
|
---|
666 | $sth->execute($groupid);
|
---|
667 |
|
---|
668 | # once we get here, we should have suceeded.
|
---|
669 | $dbh->commit;
|
---|
670 | }; # end eval
|
---|
671 |
|
---|
672 | if ($@) {
|
---|
673 | my $msg = $@;
|
---|
674 | eval { $dbh->rollback; };
|
---|
675 | return ('FAIL',"$failmsg: $msg");
|
---|
676 | } else {
|
---|
677 | return ('OK','OK');
|
---|
678 | }
|
---|
679 | } # end delGroup()
|
---|
680 |
|
---|
681 |
|
---|
682 | ## DNSDB::getChildren()
|
---|
683 | # Get a list of all groups whose parent^n is group <n>
|
---|
684 | # Takes a database handle, group ID, reference to an array to put the group IDs in,
|
---|
685 | # and an optional flag to return only immediate children or all children-of-children
|
---|
686 | # default to returning all children
|
---|
687 | # Calls itself
|
---|
688 | sub getChildren {
|
---|
689 | $errstr = '';
|
---|
690 | my $dbh = shift;
|
---|
691 | my $rootgroup = shift;
|
---|
692 | my $groupdest = shift;
|
---|
693 | my $immed = shift || 'all';
|
---|
694 |
|
---|
695 | # special break for default group; otherwise we get stuck.
|
---|
696 | if ($rootgroup == 1) {
|
---|
697 | # by definition, group 1 is the Root Of All Groups
|
---|
698 | my $sth = $dbh->prepare("SELECT group_id FROM groups WHERE NOT (group_id=1)".
|
---|
699 | ($immed ne 'all' ? " AND parent_group_id=1" : ''));
|
---|
700 | $sth->execute;
|
---|
701 | while (my @this = $sth->fetchrow_array) {
|
---|
702 | push @$groupdest, @this;
|
---|
703 | }
|
---|
704 | } else {
|
---|
705 | my $sth = $dbh->prepare("SELECT group_id FROM groups WHERE parent_group_id=?");
|
---|
706 | $sth->execute($rootgroup);
|
---|
707 | return if $sth->rows == 0;
|
---|
708 | my @grouplist;
|
---|
709 | while (my ($group) = $sth->fetchrow_array) {
|
---|
710 | push @$groupdest, $group;
|
---|
711 | getChildren($dbh,$group,$groupdest) if $immed eq 'all';
|
---|
712 | }
|
---|
713 | }
|
---|
714 | } # end getChildren()
|
---|
715 |
|
---|
716 |
|
---|
717 | ## DNSDB::groupName()
|
---|
718 | # Return the group name based on a group ID
|
---|
719 | # Takes a database handle and the group ID
|
---|
720 | # Returns the group name or undef on failure
|
---|
721 | sub groupName {
|
---|
722 | $errstr = '';
|
---|
723 | my $dbh = shift;
|
---|
724 | my $groupid = shift;
|
---|
725 | my $sth = $dbh->prepare("SELECT group_name FROM groups WHERE group_id=?");
|
---|
726 | $sth->execute($groupid);
|
---|
727 | my ($groupname) = $sth->fetchrow_array();
|
---|
728 | $errstr = $DBI::errstr if !$groupname;
|
---|
729 | return $groupname if $groupname;
|
---|
730 | } # end groupName
|
---|
731 |
|
---|
732 |
|
---|
733 | ## DNSDB::groupID()
|
---|
734 | # Return the group ID based on the group name
|
---|
735 | # Takes a database handle and the group name
|
---|
736 | # Returns the group ID or undef on failure
|
---|
737 | sub groupID {
|
---|
738 | $errstr = '';
|
---|
739 | my $dbh = shift;
|
---|
740 | my $group = shift;
|
---|
741 | my ($grpid) = $dbh->selectrow_array("SELECT group_id FROM groups WHERE group=?", undef, ($group) );
|
---|
742 | $errstr = $DBI::errstr if !$grpid;
|
---|
743 | return $grpid if $grpid;
|
---|
744 | } # end groupID()
|
---|
745 |
|
---|
746 |
|
---|
747 | ## DNSDB::addUser()
|
---|
748 | # Add a user.
|
---|
749 | # Takes a DB handle, username, group ID, password, state (active/inactive).
|
---|
750 | # Optionally accepts:
|
---|
751 | # user type (user/admin) - defaults to user
|
---|
752 | # permissions string - defaults to inherit from group
|
---|
753 | # three valid forms:
|
---|
754 | # i - Inherit permissions
|
---|
755 | # c:<user_id> - Clone permissions from <user_id>
|
---|
756 | # C:<permission list> - Set these specific permissions
|
---|
757 | # first name - defaults to username
|
---|
758 | # last name - defaults to blank
|
---|
759 | # phone - defaults to blank (could put other data within column def)
|
---|
760 | # Returns (OK,<uid>) on success, (FAIL,<message>) on failure
|
---|
761 | sub addUser {
|
---|
762 | $errstr = '';
|
---|
763 | my $dbh = shift;
|
---|
764 | my $username = shift;
|
---|
765 | my $group = shift;
|
---|
766 | my $pass = shift;
|
---|
767 | my $state = shift;
|
---|
768 |
|
---|
769 | return ('FAIL', "Missing one or more required entries") if !defined($state);
|
---|
770 | return ('FAIL', "Username must not be blank") if !$username;
|
---|
771 |
|
---|
772 | my $type = shift || 'u'; # create limited users by default - fwiw, not sure yet how this will interact with ACLs
|
---|
773 |
|
---|
774 | my $permstring = shift || 'i'; # default is to inhert permissions from group
|
---|
775 |
|
---|
776 | my $fname = shift || $username;
|
---|
777 | my $lname = shift || '';
|
---|
778 | my $phone = shift || ''; # not going format-check
|
---|
779 |
|
---|
780 | my $sth = $dbh->prepare("SELECT user_id FROM users WHERE username=?");
|
---|
781 | my $user_id;
|
---|
782 |
|
---|
783 | # quick check to start to see if we've already got one
|
---|
784 | $sth->execute($username);
|
---|
785 | ($user_id) = $sth->fetchrow_array;
|
---|
786 |
|
---|
787 | return ('FAIL', "User already exists") if $user_id;
|
---|
788 |
|
---|
789 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
790 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
791 | local $dbh->{AutoCommit} = 0;
|
---|
792 | local $dbh->{RaiseError} = 1;
|
---|
793 |
|
---|
794 | my $failmsg = '';
|
---|
795 |
|
---|
796 | # Wrap all the SQL in a transaction
|
---|
797 | eval {
|
---|
798 | # insert the user... note we set inherited perms by default since
|
---|
799 | # it's simple and cleans up some other bits of state
|
---|
800 | my $sth = $dbh->prepare("INSERT INTO users ".
|
---|
801 | "(group_id,username,password,firstname,lastname,phone,type,status,permission_id,inherit_perm) ".
|
---|
802 | "VALUES (?,?,?,?,?,?,?,?,(SELECT permission_id FROM permissions WHERE group_id=?),'t')");
|
---|
803 | $sth->execute($group,$username,unix_md5_crypt($pass),$fname,$lname,$phone,$type,$state,$group);
|
---|
804 |
|
---|
805 | # get the ID...
|
---|
806 | ($user_id) = $dbh->selectrow_array("SELECT currval('users_user_id_seq')");
|
---|
807 |
|
---|
808 | # Permissions! Gotta set'em all!
|
---|
809 | die "Invalid permission string $permstring"
|
---|
810 | if $permstring !~ /^(?:
|
---|
811 | i # inherit
|
---|
812 | |c:\d+ # clone
|
---|
813 | # custom. no, the leading , is not a typo
|
---|
814 | |C:(?:,(?:group|user|domain|record|self)_(?:edit|create|delete))*
|
---|
815 | )$/x;
|
---|
816 | # bleh. I'd call another function to do my dirty work, but we're in the middle of a transaction already.
|
---|
817 | if ($permstring ne 'i') {
|
---|
818 | # for cloned or custom permissions, we have to create a new permissions entry.
|
---|
819 | my $clonesrc = $group;
|
---|
820 | if ($permstring =~ /^c:(\d+)/) { $clonesrc = $1; }
|
---|
821 | $dbh->do("INSERT INTO permissions ($permlist,user_id) ".
|
---|
822 | "SELECT $permlist,? FROM permissions WHERE permission_id=".
|
---|
823 | "(SELECT permission_id FROM permissions WHERE ".($permstring =~ /^c:/ ? 'user' : 'group')."_id=?)",
|
---|
824 | undef, ($user_id,$clonesrc) );
|
---|
825 | $dbh->do("UPDATE users SET permission_id=".
|
---|
826 | "(SELECT permission_id FROM permissions WHERE user_id=?) ".
|
---|
827 | "WHERE user_id=?", undef, ($user_id, $user_id) );
|
---|
828 | }
|
---|
829 | if ($permstring =~ /^C:/) {
|
---|
830 | # finally for custom permissions, we set the passed-in permissions (and unset
|
---|
831 | # any that might have been brought in by the clone operation above)
|
---|
832 | my ($permid) = $dbh->selectrow_array("SELECT permission_id FROM permissions WHERE user_id=?",
|
---|
833 | undef, ($user_id) );
|
---|
834 | foreach (@permtypes) {
|
---|
835 | if ($permstring =~ /,$_/) {
|
---|
836 | $dbh->do("UPDATE permissions SET $_='t' WHERE permission_id=?", undef, ($permid) );
|
---|
837 | } else {
|
---|
838 | $dbh->do("UPDATE permissions SET $_='f' WHERE permission_id=?", undef, ($permid) );
|
---|
839 | }
|
---|
840 | }
|
---|
841 | }
|
---|
842 |
|
---|
843 | $dbh->do("UPDATE users SET inherit_perm='n' WHERE user_id=?", undef, ($user_id) );
|
---|
844 |
|
---|
845 | ##fixme: add another table to hold name/email for log table?
|
---|
846 |
|
---|
847 | # once we get here, we should have suceeded.
|
---|
848 | $dbh->commit;
|
---|
849 | }; # end eval
|
---|
850 |
|
---|
851 | if ($@) {
|
---|
852 | my $msg = $@;
|
---|
853 | eval { $dbh->rollback; };
|
---|
854 | return ('FAIL',$msg." $failmsg");
|
---|
855 | } else {
|
---|
856 | return ('OK',$user_id);
|
---|
857 | }
|
---|
858 | } # end addUser
|
---|
859 |
|
---|
860 |
|
---|
861 | ## DNSDB::checkUser()
|
---|
862 | # Check user/pass combo on login
|
---|
863 | sub checkUser {
|
---|
864 | my $dbh = shift;
|
---|
865 | my $user = shift;
|
---|
866 | my $inpass = shift;
|
---|
867 |
|
---|
868 | my $sth = $dbh->prepare("SELECT user_id,group_id,password,firstname,lastname FROM users WHERE username=?");
|
---|
869 | $sth->execute($user);
|
---|
870 | my ($uid,$gid,$pass,$fname,$lname) = $sth->fetchrow_array;
|
---|
871 | my $loginfailed = 1 if !defined($uid);
|
---|
872 |
|
---|
873 | if ($pass =~ m|^\$1\$([A-Za-z0-9/.]+)\$|) {
|
---|
874 | $loginfailed = 1 if $pass ne unix_md5_crypt($inpass,$1);
|
---|
875 | } else {
|
---|
876 | $loginfailed = 1 if $pass ne $inpass;
|
---|
877 | }
|
---|
878 |
|
---|
879 | # nnnngggg
|
---|
880 | return ($uid, $gid);
|
---|
881 | } # end checkUser
|
---|
882 |
|
---|
883 |
|
---|
884 | ## DNSDB:: updateUser()
|
---|
885 | # Update general data about user
|
---|
886 | sub updateUser {
|
---|
887 | my $dbh = shift;
|
---|
888 |
|
---|
889 | ##fixme: tweak calling convention so that we can update any given bit of data
|
---|
890 | my $uid = shift;
|
---|
891 | my $username = shift;
|
---|
892 | my $group = shift;
|
---|
893 | my $pass = shift;
|
---|
894 | my $state = shift;
|
---|
895 | my $type = shift || 'u';
|
---|
896 | my $fname = shift || $username;
|
---|
897 | my $lname = shift || '';
|
---|
898 | my $phone = shift || ''; # not going format-check
|
---|
899 |
|
---|
900 | my $failmsg = '';
|
---|
901 |
|
---|
902 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
903 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
904 | local $dbh->{AutoCommit} = 0;
|
---|
905 | local $dbh->{RaiseError} = 1;
|
---|
906 |
|
---|
907 | my $sth;
|
---|
908 |
|
---|
909 | # Password can be left blank; if so we assume there's one on file.
|
---|
910 | # Actual blank passwords are bad, mm'kay?
|
---|
911 | if (!$pass) {
|
---|
912 | $sth = $dbh->prepare("SELECT password FROM users WHERE user_id=?");
|
---|
913 | $sth->execute($uid);
|
---|
914 | ($pass) = $sth->fetchrow_array;
|
---|
915 | } else {
|
---|
916 | $pass = unix_md5_crypt($pass);
|
---|
917 | }
|
---|
918 |
|
---|
919 | eval {
|
---|
920 | my $sth = $dbh->prepare(q(
|
---|
921 | UPDATE users
|
---|
922 | SET username=?, password=?, firstname=?, lastname=?, phone=?, type=?, status=?
|
---|
923 | WHERE user_id=?
|
---|
924 | )
|
---|
925 | );
|
---|
926 | $sth->execute($username, $pass, $fname, $lname, $phone, $type, $state, $uid);
|
---|
927 | $dbh->commit;
|
---|
928 | };
|
---|
929 | if ($@) {
|
---|
930 | my $msg = $@;
|
---|
931 | eval { $dbh->rollback; };
|
---|
932 | return ('FAIL',"$failmsg: $msg");
|
---|
933 | } else {
|
---|
934 | return ('OK','OK');
|
---|
935 | }
|
---|
936 | } # end updateUser()
|
---|
937 |
|
---|
938 |
|
---|
939 | ## DNSDB::delUser()
|
---|
940 | #
|
---|
941 | sub delUser {
|
---|
942 | my $dbh = shift;
|
---|
943 | return ('FAIL',"Need database handle") if !$dbh;
|
---|
944 | my $userid = shift;
|
---|
945 | return ('FAIL',"Missing userid") if !defined($userid);
|
---|
946 |
|
---|
947 | my $sth = $dbh->prepare("delete from users where user_id=?");
|
---|
948 | $sth->execute($userid);
|
---|
949 |
|
---|
950 | return ('FAIL',"Couldn't remove user: ".$sth->errstr) if $sth->err;
|
---|
951 |
|
---|
952 | return ('OK','OK');
|
---|
953 |
|
---|
954 | } # end delUser
|
---|
955 |
|
---|
956 |
|
---|
957 | ## DNSDB::userFullName()
|
---|
958 | # Return a pretty string!
|
---|
959 | # Takes a user_id and optional printf-ish string to indicate which pieces where:
|
---|
960 | # %u for the username
|
---|
961 | # %f for the first name
|
---|
962 | # %l for the last name
|
---|
963 | # All other text in the passed string will be left as-is.
|
---|
964 | ##fixme: need a "smart" option too, so that missing/null/blank first/last names don't give funky output
|
---|
965 | sub userFullName {
|
---|
966 | $errstr = '';
|
---|
967 | my $dbh = shift;
|
---|
968 | my $userid = shift;
|
---|
969 | my $fullformat = shift || '%f %l (%u)';
|
---|
970 | my $sth = $dbh->prepare("select username,firstname,lastname from users where user_id=?");
|
---|
971 | $sth->execute($userid);
|
---|
972 | my ($uname,$fname,$lname) = $sth->fetchrow_array();
|
---|
973 | $errstr = $DBI::errstr if !$uname;
|
---|
974 |
|
---|
975 | $fullformat =~ s/\%u/$uname/g;
|
---|
976 | $fullformat =~ s/\%f/$fname/g;
|
---|
977 | $fullformat =~ s/\%l/$lname/g;
|
---|
978 |
|
---|
979 | return $fullformat;
|
---|
980 | } # end userFullName
|
---|
981 |
|
---|
982 |
|
---|
983 | ## DNSDB::userStatus()
|
---|
984 | # Sets and/or returns a user's status
|
---|
985 | # Takes a database handle, user ID and optionally a status argument
|
---|
986 | # Returns undef on errors.
|
---|
987 | sub userStatus {
|
---|
988 | my $dbh = shift;
|
---|
989 | my $id = shift;
|
---|
990 | my $newstatus = shift;
|
---|
991 |
|
---|
992 | return undef if $id !~ /^\d+$/;
|
---|
993 |
|
---|
994 | my $sth;
|
---|
995 |
|
---|
996 | # ooo, fun! let's see what we were passed for status
|
---|
997 | if ($newstatus) {
|
---|
998 | $sth = $dbh->prepare("update users set status=? where user_id=?");
|
---|
999 | # ass-u-me caller knows what's going on in full
|
---|
1000 | if ($newstatus =~ /^[01]$/) { # only two valid for now.
|
---|
1001 | $sth->execute($newstatus,$id);
|
---|
1002 | } elsif ($newstatus =~ /^usero(?:n|ff)$/) {
|
---|
1003 | $sth->execute(($newstatus eq 'useron' ? 1 : 0),$id);
|
---|
1004 | }
|
---|
1005 | }
|
---|
1006 |
|
---|
1007 | $sth = $dbh->prepare("select status from users where user_id=?");
|
---|
1008 | $sth->execute($id);
|
---|
1009 | my ($status) = $sth->fetchrow_array;
|
---|
1010 | return $status;
|
---|
1011 | } # end userStatus()
|
---|
1012 |
|
---|
1013 |
|
---|
1014 | ## DNSDB::getUserData()
|
---|
1015 | # Get misc user data for display
|
---|
1016 | sub getUserData {
|
---|
1017 | my $dbh = shift;
|
---|
1018 | my $uid = shift;
|
---|
1019 |
|
---|
1020 | my $sth = $dbh->prepare("SELECT group_id,username,firstname,lastname,phone,type,status,inherit_perm ".
|
---|
1021 | "FROM users WHERE user_id=?");
|
---|
1022 | $sth->execute($uid);
|
---|
1023 | return $sth->fetchrow_hashref();
|
---|
1024 |
|
---|
1025 | } # end getUserData()
|
---|
1026 |
|
---|
1027 |
|
---|
1028 | ## DNSDB::getSOA()
|
---|
1029 | # Return all suitable fields from an SOA record in separate elements of a hash
|
---|
1030 | # Takes a database handle, default/live flag, and group (default) or domain (live) ID
|
---|
1031 | sub getSOA {
|
---|
1032 | $errstr = '';
|
---|
1033 | my $dbh = shift;
|
---|
1034 | my $def = shift;
|
---|
1035 | my $id = shift;
|
---|
1036 | my %ret;
|
---|
1037 |
|
---|
1038 | # (ab)use distance and weight columns to store SOA data
|
---|
1039 |
|
---|
1040 | my $sql = "SELECT record_id,host,val,ttl,distance from";
|
---|
1041 | if ($def eq 'def' or $def eq 'y') {
|
---|
1042 | $sql .= " default_records WHERE group_id=? AND type=$reverse_typemap{SOA}";
|
---|
1043 | } else {
|
---|
1044 | # we're editing a live SOA record; find based on domain
|
---|
1045 | $sql .= " records WHERE domain_id=? AND type=$reverse_typemap{SOA}";
|
---|
1046 | }
|
---|
1047 | my $sth = $dbh->prepare($sql);
|
---|
1048 | $sth->execute($id);
|
---|
1049 |
|
---|
1050 | my ($recid,$host,$val,$ttl,$serial) = $sth->fetchrow_array() or return;
|
---|
1051 | my ($prins,$contact) = split /:/, $host;
|
---|
1052 | my ($refresh,$retry,$expire,$minttl) = split /:/, $val;
|
---|
1053 |
|
---|
1054 | $ret{recid} = $recid;
|
---|
1055 | $ret{ttl} = $ttl;
|
---|
1056 | $ret{serial} = $serial;
|
---|
1057 | $ret{prins} = $prins;
|
---|
1058 | $ret{contact} = $contact;
|
---|
1059 | $ret{refresh} = $refresh;
|
---|
1060 | $ret{retry} = $retry;
|
---|
1061 | $ret{expire} = $expire;
|
---|
1062 | $ret{minttl} = $minttl;
|
---|
1063 |
|
---|
1064 | return %ret;
|
---|
1065 | } # end getSOA()
|
---|
1066 |
|
---|
1067 |
|
---|
1068 | ## DNSDB::getRecLine()
|
---|
1069 | # Return all data fields for a zone record in separate elements of a hash
|
---|
1070 | # Takes a database handle, default/live flag, and record ID
|
---|
1071 | sub getRecLine {
|
---|
1072 | $errstr = '';
|
---|
1073 | my $dbh = shift;
|
---|
1074 | my $def = shift;
|
---|
1075 | my $id = shift;
|
---|
1076 |
|
---|
1077 | my $sql = "SELECT r.record_id,r.host,r.type,r.val,r.distance,r.weight,r.port,r.ttl,r.longrec_id,l.recdata".
|
---|
1078 | (($def eq 'def' or $def eq 'y') ? ',r.group_id FROM default_' : ',r.domain_id FROM ').
|
---|
1079 | "records r LEFT OUTER JOIN longrecs l ON r.longrec_id=l.longrec_id WHERE record_id=?";
|
---|
1080 | my $ret = $dbh->selectrow_hashref($sql, undef, ($id) ) or warn $dbh->errstr;
|
---|
1081 |
|
---|
1082 | if ($dbh->err) {
|
---|
1083 | $errstr = $DBI::errstr;
|
---|
1084 | return undef;
|
---|
1085 | }
|
---|
1086 |
|
---|
1087 | $ret->{val} = $ret->{recdata} if $ret->{longrec_id}; # put the long data in the real value space
|
---|
1088 | delete $ret->{longrec_id}; # remove these since they shouldn't be exposed - the caller
|
---|
1089 | delete $ret->{recdata}; # should not care about "long records" vs normal ones.
|
---|
1090 | $ret->{parid} = (($def eq 'def' or $def eq 'y') ? $ret->{group_id} : $ret->{domain_id});
|
---|
1091 |
|
---|
1092 | return $ret;
|
---|
1093 | }
|
---|
1094 |
|
---|
1095 |
|
---|
1096 | ##fixme: should use above (getRecLine()) to get lines for below?
|
---|
1097 | ## DNSDB::getDomRecs()
|
---|
1098 | # Return records for a domain
|
---|
1099 | # Takes a database handle, default/live flag, group/domain ID, start,
|
---|
1100 | # number of records, sort field, and sort order
|
---|
1101 | # Returns a reference to an array of hashes
|
---|
1102 | sub getDomRecs {
|
---|
1103 | $errstr = '';
|
---|
1104 | my $dbh = shift;
|
---|
1105 | my $type = shift;
|
---|
1106 | my $id = shift;
|
---|
1107 | my $nrecs = shift || 'all';
|
---|
1108 | my $nstart = shift || 0;
|
---|
1109 |
|
---|
1110 | ## for order, need to map input to column names
|
---|
1111 | my $order = shift || 'host';
|
---|
1112 | my $direction = shift || 'ASC';
|
---|
1113 |
|
---|
1114 | $type = 'y' if $type eq 'def';
|
---|
1115 |
|
---|
1116 | my $sql = "SELECT r.record_id,r.host,r.type,r.val,r.distance,r.weight,r.port,r.ttl,r.longrec_id,l.recdata FROM ";
|
---|
1117 | $sql .= "default_" if $type eq 'y';
|
---|
1118 | $sql .= "records r ";
|
---|
1119 | $sql .= "INNER JOIN rectypes t ON r.type=t.val "; # for sorting by type alphabetically
|
---|
1120 | $sql .= "LEFT OUTER JOIN longrecs l ON r.longrec_id=l.longrec_id ";
|
---|
1121 | if ($type eq 'y') {
|
---|
1122 | $sql .= "WHERE r.group_id=?";
|
---|
1123 | } else {
|
---|
1124 | $sql .= "WHERE r.domain_id=?";
|
---|
1125 | }
|
---|
1126 | $sql .= " AND NOT r.type=$reverse_typemap{SOA}";
|
---|
1127 | # use alphaorder column for "correct" ordering of sort-by-type instead of DNS RR type number
|
---|
1128 | $sql .= " ORDER BY ".($order eq 'type' ? 't.alphaorder' : "r.$order")." $direction";
|
---|
1129 | $sql .= " LIMIT $nrecs OFFSET ".($nstart*$nrecs) if $nstart ne 'all';
|
---|
1130 |
|
---|
1131 | my $sth = $dbh->prepare($sql) or warn $dbh->errstr;
|
---|
1132 | $sth->execute($id) or warn "$sql: ".$sth->errstr;
|
---|
1133 |
|
---|
1134 | my @retbase;
|
---|
1135 | while (my $ref = $sth->fetchrow_hashref()) {
|
---|
1136 | $ref->{val} = $ref->{recdata} if $ref->{longrec_id}; # put the long data in the real value space
|
---|
1137 | delete $ref->{longrec_id}; # remove these since they shouldn't be exposed - the caller
|
---|
1138 | delete $ref->{recdata}; # should not care about "long records" vs normal ones.
|
---|
1139 | push @retbase, $ref;
|
---|
1140 | }
|
---|
1141 |
|
---|
1142 | my $ret = \@retbase;
|
---|
1143 | return $ret;
|
---|
1144 | } # end getDomRecs()
|
---|
1145 |
|
---|
1146 |
|
---|
1147 | ## DNSDB::getRecCount()
|
---|
1148 | # Return count of non-SOA records in domain (or default records in a group)
|
---|
1149 | # Takes a database handle, default/live flag and group/domain ID
|
---|
1150 | # Returns the count
|
---|
1151 | sub getRecCount {
|
---|
1152 | my $dbh = shift;
|
---|
1153 | my $defrec = shift;
|
---|
1154 | my $id = shift;
|
---|
1155 |
|
---|
1156 | my ($count) = $dbh->selectrow_array("SELECT count(*) FROM ".
|
---|
1157 | ($defrec eq 'y' ? 'default_' : '')."records ".
|
---|
1158 | "WHERE ".($defrec eq 'y' ? 'group' : 'domain')."_id=? ".
|
---|
1159 | "AND NOT type=$reverse_typemap{SOA}", undef, ($id) );
|
---|
1160 |
|
---|
1161 | return $count;
|
---|
1162 |
|
---|
1163 | } # end getRecCount()
|
---|
1164 |
|
---|
1165 |
|
---|
1166 | ## DNSDB::addRec()
|
---|
1167 | # Add a new record to a domain or a group's default records
|
---|
1168 | # Takes a database handle, default/live flag, group/domain ID,
|
---|
1169 | # host, type, value, and TTL
|
---|
1170 | # Some types require additional detail: "distance" for MX and SRV,
|
---|
1171 | # and weight/port for SRV
|
---|
1172 | # Returns a status code and detail message in case of error
|
---|
1173 | sub addRec {
|
---|
1174 | $errstr = '';
|
---|
1175 | my $dbh = shift;
|
---|
1176 | my $defrec = shift;
|
---|
1177 | my $id = shift;
|
---|
1178 |
|
---|
1179 | my $host = shift;
|
---|
1180 | my $rectype = shift;
|
---|
1181 | my $val = shift;
|
---|
1182 | my $ttl = shift;
|
---|
1183 |
|
---|
1184 | my $fields = ($defrec eq 'y' ? 'group_id' : 'domain_id').",host,type,val,ttl";
|
---|
1185 | my $vallen = "?,?,?,?,?";
|
---|
1186 | my @vallist = ($id,$host,$rectype,$val,$ttl);
|
---|
1187 |
|
---|
1188 | my $dist;
|
---|
1189 | if ($rectype == $reverse_typemap{MX} or $rectype == $reverse_typemap{SRV}) {
|
---|
1190 | $dist = shift;
|
---|
1191 | return ('FAIL',"Need distance for $typemap{$rectype} record") if !defined($dist);
|
---|
1192 | $fields .= ",distance";
|
---|
1193 | $vallen .= ",?";
|
---|
1194 | push @vallist, $dist;
|
---|
1195 | }
|
---|
1196 | my $weight;
|
---|
1197 | my $port;
|
---|
1198 | if ($rectype == $reverse_typemap{SRV}) {
|
---|
1199 | # check for _service._protocol. NB: RFC2782 does not say "MUST"... nor "SHOULD"...
|
---|
1200 | # it just says (paraphrased) "... is prepended with _ to prevent DNS collisions"
|
---|
1201 | return ('FAIL',"SRV records must begin with _service._protocol")
|
---|
1202 | if $host !~ /^_[A-Za-z]+\._[A-Za-z]+\.[a-z0-9-]+/;
|
---|
1203 | $weight = shift;
|
---|
1204 | $port = shift;
|
---|
1205 | return ('FAIL',"Need weight and port for SRV record") if !defined($weight) or !defined($port);
|
---|
1206 | $fields .= ",weight,port";
|
---|
1207 | $vallen .= ",?,?";
|
---|
1208 | push @vallist, ($weight,$port);
|
---|
1209 | }
|
---|
1210 |
|
---|
1211 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
1212 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
1213 | local $dbh->{AutoCommit} = 0;
|
---|
1214 | local $dbh->{RaiseError} = 1;
|
---|
1215 |
|
---|
1216 | eval {
|
---|
1217 | if (length($val) > 100 ) {
|
---|
1218 | # extralong records get an entry in a separate table.
|
---|
1219 | $dbh->do("INSERT INTO longrecs (recdata) VALUES (?)", undef, ($val) );
|
---|
1220 | my ($longid) = $dbh->selectrow_array("SELECT longrec_id FROM longrecs WHERE recdata=?", undef, ($val) );
|
---|
1221 | $fields .= ",longrec_id";
|
---|
1222 | $vallen .= ",?";
|
---|
1223 | push @vallist, $longid;
|
---|
1224 | $vallist[3] = ''; # so we don't barf when we insert the main record
|
---|
1225 | }
|
---|
1226 | $dbh->do("INSERT INTO ".($defrec eq 'y' ? 'default_' : '')."records ($fields) VALUES ($vallen)",
|
---|
1227 | undef, @vallist);
|
---|
1228 | $dbh->commit;
|
---|
1229 | };
|
---|
1230 | if ($@) {
|
---|
1231 | my $msg = $@;
|
---|
1232 | eval { $dbh->rollback; };
|
---|
1233 | return ('FAIL',$msg);
|
---|
1234 | }
|
---|
1235 |
|
---|
1236 | return ('OK','OK');
|
---|
1237 |
|
---|
1238 | } # end addRec()
|
---|
1239 |
|
---|
1240 |
|
---|
1241 | ## DNSDB::updateRec()
|
---|
1242 | # Update a record
|
---|
1243 | sub updateRec {
|
---|
1244 | $errstr = '';
|
---|
1245 |
|
---|
1246 | my $dbh = shift;
|
---|
1247 | my $defrec = shift;
|
---|
1248 | my $id = shift;
|
---|
1249 |
|
---|
1250 | # all records have these
|
---|
1251 | my $host = shift;
|
---|
1252 | my $type = shift;
|
---|
1253 | my $val = shift;
|
---|
1254 | my $ttl = shift;
|
---|
1255 |
|
---|
1256 | return('FAIL',"Missing standard argument(s)") if !defined($ttl);
|
---|
1257 |
|
---|
1258 | # only MX and SRV will use these
|
---|
1259 | my $dist = 0;
|
---|
1260 | my $weight = 0;
|
---|
1261 | my $port = 0;
|
---|
1262 |
|
---|
1263 | if ($type == $reverse_typemap{MX} || $type == $reverse_typemap{SRV}) {
|
---|
1264 | $dist = shift;
|
---|
1265 | return ('FAIL',"MX or SRV requires distance") if !defined($dist);
|
---|
1266 | if ($type == $reverse_typemap{SRV}) {
|
---|
1267 | $weight = shift;
|
---|
1268 | return ('FAIL',"SRV requires weight") if !defined($weight);
|
---|
1269 | $port = shift;
|
---|
1270 | return ('FAIL',"SRV requires port") if !defined($port);
|
---|
1271 | }
|
---|
1272 | }
|
---|
1273 |
|
---|
1274 | # my $sql = "SELECT r.record_id,r.host,r.type,r.val,r.distance,r.weight,r.port,r.ttl,r.longrec_id,l.recdata FROM ";
|
---|
1275 | # $sql .= "default_" if $type eq 'y';
|
---|
1276 | # $sql .= "records r ";
|
---|
1277 | # $sql .= "LEFT OUTER JOIN longrecs l ON r.longrec_id=l.longrec_id ";
|
---|
1278 |
|
---|
1279 | # get the long record ID, if any
|
---|
1280 | my ($longid) = $dbh->selectrow_array("SELECT longrec_id FROM ".($defrec eq 'y' ? 'default_' : '')."records ".
|
---|
1281 | "WHERE record_id=?", undef, ($id) );
|
---|
1282 |
|
---|
1283 | local $dbh->{AutoCommit} = 0;
|
---|
1284 | local $dbh->{RaiseError} = 1;
|
---|
1285 |
|
---|
1286 | eval {
|
---|
1287 | # there's really no tidy way to squash this down. :/
|
---|
1288 | if (length($val) > 100) {
|
---|
1289 | if ($longid) {
|
---|
1290 | $dbh->do("UPDATE longrecs SET recdata=? WHERE longrec_id=?", undef, ($val, $longid) );
|
---|
1291 | } else {
|
---|
1292 | ##fixme: has to be a better way to be sure we get the right recid back once inserted...
|
---|
1293 | $dbh->do("INSERT INTO longrecs (recdata) VALUES (?)", undef, ($val) );
|
---|
1294 | my ($newlongid) = $dbh->selectrow_array("SELECT currval('longrecs_longrec_id_seq')");
|
---|
1295 | $dbh->do("UPDATE ".($defrec eq 'y' ? 'default_' : '')."records SET val=?,longrec_id=? ".
|
---|
1296 | "WHERE record_id=?", undef, ('', $newlongid, $id) );
|
---|
1297 | }
|
---|
1298 | } else {
|
---|
1299 | if ($longid) {
|
---|
1300 | $dbh->do("DELETE FROM longrecs WHERE longrec_id=?", undef, ($longid) );
|
---|
1301 | $dbh->do("UPDATE ".($defrec eq 'y' ? 'default_' : '')."records SET val=?,longrec_id=NULL ".
|
---|
1302 | "WHERE record_id=?", undef, ($val, $id) );
|
---|
1303 | } else {
|
---|
1304 | $dbh->do("UPDATE ".($defrec eq 'y' ? 'default_' : '')."records SET val=? ".
|
---|
1305 | "WHERE record_id=?", undef, ($val, $id) );
|
---|
1306 | }
|
---|
1307 | }
|
---|
1308 |
|
---|
1309 | $dbh->do("UPDATE ".($defrec eq 'y' ? 'default_' : '')."records ".
|
---|
1310 | "SET host=?,type=?,ttl=?,distance=?,weight=?,port=? ".
|
---|
1311 | "WHERE record_id=?", undef, ($host, $type, $ttl, $dist, $weight, $port, $id) );
|
---|
1312 |
|
---|
1313 | };
|
---|
1314 | if ($@) {
|
---|
1315 | my $msg = $@;
|
---|
1316 | $dbh->rollback;
|
---|
1317 | return ('FAIL', $msg);
|
---|
1318 | }
|
---|
1319 | # return ('FAIL',$sth->errstr."<br>\n$errstr<br>\n") if $sth->err;
|
---|
1320 |
|
---|
1321 | return ('OK','OK');
|
---|
1322 | } # end updateRec()
|
---|
1323 |
|
---|
1324 |
|
---|
1325 | ## DNSDB::delRec()
|
---|
1326 | # Delete a record.
|
---|
1327 | sub delRec {
|
---|
1328 | $errstr = '';
|
---|
1329 | my $dbh = shift;
|
---|
1330 | my $defrec = shift;
|
---|
1331 | my $id = shift;
|
---|
1332 |
|
---|
1333 | my $sth = $dbh->prepare("DELETE FROM ".($defrec eq 'y' ? 'default_' : '')."records WHERE record_id=?");
|
---|
1334 | $sth->execute($id);
|
---|
1335 |
|
---|
1336 | return ('FAIL',"Couldn't remove record: ".$sth->errstr) if $sth->err;
|
---|
1337 |
|
---|
1338 | return ('OK','OK');
|
---|
1339 | } # end delRec()
|
---|
1340 |
|
---|
1341 |
|
---|
1342 | # Reference hashes.
|
---|
1343 | my %par_tbl = (
|
---|
1344 | group => 'groups',
|
---|
1345 | user => 'users',
|
---|
1346 | defrec => 'default_records',
|
---|
1347 | domain => 'domains',
|
---|
1348 | record => 'records'
|
---|
1349 | );
|
---|
1350 | my %id_col = (
|
---|
1351 | group => 'group_id',
|
---|
1352 | user => 'user_id',
|
---|
1353 | defrec => 'record_id',
|
---|
1354 | domain => 'domain_id',
|
---|
1355 | record => 'record_id'
|
---|
1356 | );
|
---|
1357 | my %par_col = (
|
---|
1358 | group => 'parent_group_id',
|
---|
1359 | user => 'group_id',
|
---|
1360 | defrec => 'group_id',
|
---|
1361 | domain => 'group_id',
|
---|
1362 | record => 'domain_id'
|
---|
1363 | );
|
---|
1364 | my %par_type = (
|
---|
1365 | group => 'group',
|
---|
1366 | user => 'group',
|
---|
1367 | defrec => 'group',
|
---|
1368 | domain => 'group',
|
---|
1369 | record => 'domain'
|
---|
1370 | );
|
---|
1371 |
|
---|
1372 | ## DNSDB::getParents()
|
---|
1373 | # Find out which entities are parent to the requested id
|
---|
1374 | # Returns arrayref containing hash pairs of id/type
|
---|
1375 | sub getParents {
|
---|
1376 | my $dbh = shift;
|
---|
1377 | my $id = shift;
|
---|
1378 | my $type = shift;
|
---|
1379 | my $depth = shift || 'all'; # valid values: 'all', 'immed', <int> (stop at this group ID)
|
---|
1380 |
|
---|
1381 | my @parlist;
|
---|
1382 |
|
---|
1383 | while (1) {
|
---|
1384 | my $result = $dbh->selectrow_hashref("SELECT $par_col{$type} FROM $par_tbl{$type} WHERE $id_col{$type} = ?",
|
---|
1385 | undef, ($id) );
|
---|
1386 | unshift @parlist, ($result->{$par_col{$type}} => $par_type{$type});
|
---|
1387 | last if $result->{$par_col{$type}} == 1; # group 1 is its own parent
|
---|
1388 | $type = $par_type{$type};
|
---|
1389 | $id = $result->{$par_col{$type}};
|
---|
1390 | }
|
---|
1391 |
|
---|
1392 | return \@parlist;
|
---|
1393 |
|
---|
1394 | } # end getParents()
|
---|
1395 |
|
---|
1396 |
|
---|
1397 | ## DNSDB::isParent()
|
---|
1398 | # Returns true if $id1 is a parent of $id2, false otherwise
|
---|
1399 | sub isParent {
|
---|
1400 | my $dbh = shift;
|
---|
1401 | my $id1 = shift;
|
---|
1402 | my $type1 = shift;
|
---|
1403 | my $id2 = shift;
|
---|
1404 | my $type2 = shift;
|
---|
1405 | ##todo: immediate, secondary, full (default)
|
---|
1406 |
|
---|
1407 | # Return false on impossible relations
|
---|
1408 | return 0 if $type1 eq 'record'; # nothing may be a child of a record
|
---|
1409 | return 0 if $type1 eq 'defrec'; # nothing may be a child of a record
|
---|
1410 | return 0 if $type1 eq 'user'; # nothing may be child of a user
|
---|
1411 | return 0 if $type1 eq 'domain' && $type2 ne 'record'; # domain may not be a parent of anything other than a record
|
---|
1412 |
|
---|
1413 | # group 1 is the ultimate root parent
|
---|
1414 | return 1 if $type1 eq 'group' && $id1 == 1;
|
---|
1415 |
|
---|
1416 | # almost the same loop as getParents() above
|
---|
1417 | my $id = $id2;
|
---|
1418 | my $type = $type2;
|
---|
1419 | my $foundparent = 0;
|
---|
1420 | my $tmp = 0;
|
---|
1421 | while (1) {
|
---|
1422 | my $sql = "SELECT $par_col{$type} FROM $par_tbl{$type} WHERE $id_col{$type} = ?";
|
---|
1423 | my $result = $dbh->selectrow_hashref($sql,
|
---|
1424 | undef, ($id) ) or warn $dbh->errstr." $sql";
|
---|
1425 | if ($result->{$par_col{$type}} == $id1) {
|
---|
1426 | $foundparent = 1;
|
---|
1427 | last;
|
---|
1428 | }
|
---|
1429 | # group 1 is its own parent. need this here more to break strange loops than for detecting a parent
|
---|
1430 | last if $result->{$par_col{$type}} == 1;
|
---|
1431 | $type = $par_type{$type};
|
---|
1432 | $id = $result->{$par_col{$type}};
|
---|
1433 | last if $tmp++ > 10;
|
---|
1434 | }
|
---|
1435 |
|
---|
1436 | return $foundparent;
|
---|
1437 | } # end isParent()
|
---|
1438 |
|
---|
1439 |
|
---|
1440 | ## DNSDB::domStatus()
|
---|
1441 | # Sets and/or returns a domain's status
|
---|
1442 | # Takes a database handle, domain ID and optionally a status argument
|
---|
1443 | # Returns undef on errors.
|
---|
1444 | sub domStatus {
|
---|
1445 | my $dbh = shift;
|
---|
1446 | my $id = shift;
|
---|
1447 | my $newstatus = shift;
|
---|
1448 |
|
---|
1449 | return undef if $id !~ /^\d+$/;
|
---|
1450 |
|
---|
1451 | my $sth;
|
---|
1452 |
|
---|
1453 | # ooo, fun! let's see what we were passed for status
|
---|
1454 | if ($newstatus) {
|
---|
1455 | $sth = $dbh->prepare("update domains set status=? where domain_id=?");
|
---|
1456 | # ass-u-me caller knows what's going on in full
|
---|
1457 | if ($newstatus =~ /^[01]$/) { # only two valid for now.
|
---|
1458 | $sth->execute($newstatus,$id);
|
---|
1459 | } elsif ($newstatus =~ /^domo(?:n|ff)$/) {
|
---|
1460 | $sth->execute(($newstatus eq 'domon' ? 1 : 0),$id);
|
---|
1461 | }
|
---|
1462 | }
|
---|
1463 |
|
---|
1464 | $sth = $dbh->prepare("select status from domains where domain_id=?");
|
---|
1465 | $sth->execute($id);
|
---|
1466 | my ($status) = $sth->fetchrow_array;
|
---|
1467 | return $status;
|
---|
1468 | } # end domStatus()
|
---|
1469 |
|
---|
1470 |
|
---|
1471 | ## DNSDB::importAXFR
|
---|
1472 | # Import a domain via AXFR
|
---|
1473 | # Takes AXFR host, domain to transfer, group to put the domain in,
|
---|
1474 | # and optionally:
|
---|
1475 | # - active/inactive state flag (defaults to active)
|
---|
1476 | # - overwrite-SOA flag (defaults to off)
|
---|
1477 | # - overwrite-NS flag (defaults to off, doesn't affect subdomain NS records)
|
---|
1478 | # Returns a status code (OK, WARN, or FAIL) and message - message should be blank
|
---|
1479 | # if status is OK, but WARN includes conditions that are not fatal but should
|
---|
1480 | # really be reported.
|
---|
1481 | sub importAXFR {
|
---|
1482 | my $dbh = shift;
|
---|
1483 | my $ifrom_in = shift;
|
---|
1484 | my $domain = shift;
|
---|
1485 | my $group = shift;
|
---|
1486 | my $status = shift || 1;
|
---|
1487 | my $rwsoa = shift || 0;
|
---|
1488 | my $rwns = shift || 0;
|
---|
1489 |
|
---|
1490 | ##fixme: add mode to delete&replace, merge+overwrite, merge new?
|
---|
1491 |
|
---|
1492 | my $nrecs = 0;
|
---|
1493 | my $soaflag = 0;
|
---|
1494 | my $nsflag = 0;
|
---|
1495 | my $warnmsg = '';
|
---|
1496 | my $ifrom;
|
---|
1497 |
|
---|
1498 | # choke on possible bad setting in ifrom
|
---|
1499 | # IPv4 and v6, and valid hostnames!
|
---|
1500 | ($ifrom) = ($ifrom_in =~ /^([0-9a-f\:.]+|[0-9a-z_.-]+)$/i);
|
---|
1501 | return ('FAIL', "Bad AXFR source host $ifrom")
|
---|
1502 | unless ($ifrom) = ($ifrom_in =~ /^([0-9a-f\:.]+|[0-9a-z_.-]+)$/i);
|
---|
1503 |
|
---|
1504 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
1505 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
1506 | local $dbh->{AutoCommit} = 0;
|
---|
1507 | local $dbh->{RaiseError} = 1;
|
---|
1508 |
|
---|
1509 | my $sth = $dbh->prepare("SELECT domain_id FROM domains WHERE domain=?");
|
---|
1510 | my $dom_id;
|
---|
1511 |
|
---|
1512 | # quick check to start to see if we've already got one
|
---|
1513 | $sth->execute($domain);
|
---|
1514 | ($dom_id) = $sth->fetchrow_array;
|
---|
1515 |
|
---|
1516 | return ('FAIL', "Domain already exists") if $dom_id;
|
---|
1517 |
|
---|
1518 | eval {
|
---|
1519 | # can't do this, can't nest transactions. sigh.
|
---|
1520 | #my ($dcode, $dmsg) = addDomain(dbh, domain, group, status);
|
---|
1521 |
|
---|
1522 | ##fixme: serial
|
---|
1523 | my $sth = $dbh->prepare("INSERT INTO domains (domain,group_id,status) VALUES (?,?,?)");
|
---|
1524 | $sth->execute($domain,$group,$status);
|
---|
1525 |
|
---|
1526 | ## bizarre DBI<->Net::DNS interaction bug:
|
---|
1527 | ## sometimes a zone will cause an immediate commit-and-exit (sort of) of the while()
|
---|
1528 | ## fixed, apparently I was doing *something* odd, but not certain what it was that
|
---|
1529 | ## caused a commit instead of barfing
|
---|
1530 |
|
---|
1531 | # get domain id so we can do the records
|
---|
1532 | $sth = $dbh->prepare("SELECT domain_id FROM domains WHERE domain=?");
|
---|
1533 | $sth->execute($domain);
|
---|
1534 | ($dom_id) = $sth->fetchrow_array();
|
---|
1535 |
|
---|
1536 | my $res = Net::DNS::Resolver->new;
|
---|
1537 | $res->nameservers($ifrom);
|
---|
1538 | $res->axfr_start($domain)
|
---|
1539 | or die "Couldn't begin AXFR\n";
|
---|
1540 |
|
---|
1541 | while (my $rr = $res->axfr_next()) {
|
---|
1542 | my $type = $rr->type;
|
---|
1543 |
|
---|
1544 | my $sql = "INSERT INTO records (domain_id,host,type,ttl,val";
|
---|
1545 | my $vallen = "?,?,?,?,?";
|
---|
1546 |
|
---|
1547 | $soaflag = 1 if $type eq 'SOA';
|
---|
1548 | $nsflag = 1 if $type eq 'NS';
|
---|
1549 |
|
---|
1550 | my @vallist = ($dom_id, $rr->name, $reverse_typemap{$type}, $rr->ttl);
|
---|
1551 |
|
---|
1552 | # "Primary" types:
|
---|
1553 | # A, NS, CNAME, SOA, PTR(warn in forward), MX, TXT, AAAA, SRV, A6(ob), SPF
|
---|
1554 | # maybe KEY
|
---|
1555 |
|
---|
1556 | # nasty big ugly case-like thing here, since we have to do *some* different
|
---|
1557 | # processing depending on the record. le sigh.
|
---|
1558 |
|
---|
1559 | ##fixme: what record types other than TXT can/will have >255-byte payloads?
|
---|
1560 |
|
---|
1561 | if ($type eq 'A') {
|
---|
1562 | push @vallist, $rr->address;
|
---|
1563 | } elsif ($type eq 'NS') {
|
---|
1564 | # hmm. should we warn here if subdomain NS'es are left alone?
|
---|
1565 | next if ($rwns && ($rr->name eq $domain));
|
---|
1566 | push @vallist, $rr->nsdname;
|
---|
1567 | $nsflag = 1;
|
---|
1568 | } elsif ($type eq 'CNAME') {
|
---|
1569 | push @vallist, $rr->cname;
|
---|
1570 | } elsif ($type eq 'SOA') {
|
---|
1571 | next if $rwsoa;
|
---|
1572 | $vallist[1] = $rr->mname.":".$rr->rname;
|
---|
1573 | push @vallist, ($rr->refresh.":".$rr->retry.":".$rr->expire.":".$rr->minimum);
|
---|
1574 | $soaflag = 1;
|
---|
1575 | } elsif ($type eq 'PTR') {
|
---|
1576 | push @vallist, $rr->ptrdname;
|
---|
1577 | # hmm. PTR records should not be in forward zones.
|
---|
1578 | } elsif ($type eq 'MX') {
|
---|
1579 | $sql .= ",distance";
|
---|
1580 | $vallen .= ",?";
|
---|
1581 | push @vallist, $rr->exchange;
|
---|
1582 | push @vallist, $rr->preference;
|
---|
1583 | } elsif ($type eq 'TXT') {
|
---|
1584 | ##fixme: Net::DNS docs say this should be deprecated for rdatastr() or char_str_list(),
|
---|
1585 | ## but don't really seem enthusiastic about it.
|
---|
1586 | my $rrdata = $rr->txtdata;
|
---|
1587 | if (length($rrdata) > 100 ) {
|
---|
1588 | # extralong records get an entry in a separate table.
|
---|
1589 | $dbh->do("INSERT INTO longrecs (recdata) VALUES (?)", undef, ($rrdata) );
|
---|
1590 | my ($longid) = $dbh->selectrow_array("SELECT longrec_id FROM longrecs WHERE recdata=?", undef, ($rrdata) );
|
---|
1591 | $sql .= ",longrec_id";
|
---|
1592 | $vallen .= ",?";
|
---|
1593 | push @vallist, '';
|
---|
1594 | push @vallist, $longid;
|
---|
1595 | } else {
|
---|
1596 | push @vallist, $rrdata;
|
---|
1597 | }
|
---|
1598 | } elsif ($type eq 'SPF') {
|
---|
1599 | ##fixme: and the same caveat here, since it is apparently a clone of ::TXT
|
---|
1600 | my $rrdata = $rr->txtdata;
|
---|
1601 | if (length($rrdata) > 100 ) {
|
---|
1602 | # extralong records get an entry in a separate table.
|
---|
1603 | $dbh->do("INSERT INTO longrecs (recdata) VALUES (?)", undef, ($rrdata) );
|
---|
1604 | my ($longid) = $dbh->selectrow_array("SELECT longrec_id FROM longrecs WHERE recdata=?", undef, ($rrdata) );
|
---|
1605 | $sql .= ",longrec_id";
|
---|
1606 | $vallen .= ",?";
|
---|
1607 | push @vallist, '';
|
---|
1608 | push @vallist, $longid;
|
---|
1609 | } else {
|
---|
1610 | push @vallist, $rrdata;
|
---|
1611 | }
|
---|
1612 | } elsif ($type eq 'AAAA') {
|
---|
1613 | push @vallist, $rr->address;
|
---|
1614 | } elsif ($type eq 'SRV') {
|
---|
1615 | $sql .= ",distance,weight,port" if $type eq 'SRV';
|
---|
1616 | $vallen .= ",?,?,?" if $type eq 'SRV';
|
---|
1617 | push @vallist, $rr->target;
|
---|
1618 | push @vallist, $rr->priority;
|
---|
1619 | push @vallist, $rr->weight;
|
---|
1620 | push @vallist, $rr->port;
|
---|
1621 | } elsif ($type eq 'KEY') {
|
---|
1622 | # we don't actually know what to do with these...
|
---|
1623 | push @vallist, ($rr->flags.":".$rr->protocol.":".$rr->algorithm.":".$rr->key.":".$rr->keytag.":".$rr->privatekeyname);
|
---|
1624 | } else {
|
---|
1625 | my $rrdata = $rr->rdatastr;
|
---|
1626 | if (length($rrdata) > 100 ) {
|
---|
1627 | # extralong records get an entry in a separate table.
|
---|
1628 | $dbh->do("INSERT INTO longrecs (recdata) VALUES (?)", undef, ($rrdata) );
|
---|
1629 | my ($longid) = $dbh->selectrow_array("SELECT longrec_id FROM longrecs WHERE recdata=?", undef, ($rrdata) );
|
---|
1630 | $sql .= ",longrec_id";
|
---|
1631 | $vallen .= ",?";
|
---|
1632 | push @vallist, '';
|
---|
1633 | push @vallist, $longid;
|
---|
1634 | } else {
|
---|
1635 | push @vallist, $rrdata;
|
---|
1636 | }
|
---|
1637 | # Finding a different record type is not fatal.... just problematic.
|
---|
1638 | # We may not be able to export it correctly.
|
---|
1639 | $warnmsg .= "Unusual record ".$rr->name." ($type) found\n";
|
---|
1640 | }
|
---|
1641 |
|
---|
1642 | # BIND supports:
|
---|
1643 | # A CNAME HINFO MB(ex) MD(ob) MF(ob) MG(ex) MINFO(ex) MR(ex) MX NS NULL
|
---|
1644 | # PTR SOA TXT WKS AFSDB(ex) ISDN(ex) RP(ex) RT(ex) X25(ex) PX
|
---|
1645 | # ... if one can ever find the right magic to format them correctly
|
---|
1646 |
|
---|
1647 | # Net::DNS supports:
|
---|
1648 | # RRSIG SIG NSAP NS NIMLOC NAPTR MX MR MINFO MG MB LOC ISDN IPSECKEY HINFO
|
---|
1649 | # EID DNAME CNAME CERT APL AFSDB AAAA A DS NXT NSEC3PARAM NSEC3 NSEC KEY
|
---|
1650 | # DNSKEY DLV X25 TXT TSIG TKEY SSHFP SRV SPF SOA RT RP PX PTR NULL APL::AplItem
|
---|
1651 |
|
---|
1652 | $sth = $dbh->prepare($sql.") VALUES (".$vallen.")") or die "problem preparing record insert SQL\n";
|
---|
1653 | $sth->execute(@vallist) or die "failed to insert ".$rr->string.": ".$sth->errstr."\n";
|
---|
1654 |
|
---|
1655 | $nrecs++;
|
---|
1656 |
|
---|
1657 | } # while axfr_next
|
---|
1658 |
|
---|
1659 | # Overwrite SOA record
|
---|
1660 | if ($rwsoa) {
|
---|
1661 | $soaflag = 1;
|
---|
1662 | my $sthgetsoa = $dbh->prepare("SELECT host,val,ttl FROM default_records WHERE group_id=? AND type=?");
|
---|
1663 | my $sthputsoa = $dbh->prepare("INSERT INTO records (domain_id,host,type,val,ttl) VALUES (?,?,?,?,?)");
|
---|
1664 | $sthgetsoa->execute($group,$reverse_typemap{SOA});
|
---|
1665 | while (my ($host,$val,$ttl) = $sthgetsoa->fetchrow_array()) {
|
---|
1666 | $host =~ s/DOMAIN/$domain/g;
|
---|
1667 | $val =~ s/DOMAIN/$domain/g;
|
---|
1668 | $sthputsoa->execute($dom_id,$host,$reverse_typemap{SOA},$val,$ttl);
|
---|
1669 | }
|
---|
1670 | }
|
---|
1671 |
|
---|
1672 | # Overwrite NS records
|
---|
1673 | if ($rwns) {
|
---|
1674 | $nsflag = 1;
|
---|
1675 | my $sthgetns = $dbh->prepare("SELECT host,val,ttl FROM default_records WHERE group_id=? AND type=?");
|
---|
1676 | my $sthputns = $dbh->prepare("INSERT INTO records (domain_id,host,type,val,ttl) VALUES (?,?,?,?,?)");
|
---|
1677 | $sthgetns->execute($group,$reverse_typemap{NS});
|
---|
1678 | while (my ($host,$val,$ttl) = $sthgetns->fetchrow_array()) {
|
---|
1679 | $host =~ s/DOMAIN/$domain/g;
|
---|
1680 | $val =~ s/DOMAIN/$domain/g;
|
---|
1681 | $sthputns->execute($dom_id,$host,$reverse_typemap{NS},$val,$ttl);
|
---|
1682 | }
|
---|
1683 | }
|
---|
1684 |
|
---|
1685 | die "No records found; either $ifrom is not authoritative or doesn't allow transfers\n" if !$nrecs;
|
---|
1686 | die "Bad zone: No SOA record!\n" if !$soaflag;
|
---|
1687 | die "Bad zone: No NS records!\n" if !$nsflag;
|
---|
1688 |
|
---|
1689 | $dbh->commit;
|
---|
1690 |
|
---|
1691 | };
|
---|
1692 |
|
---|
1693 | if ($@) {
|
---|
1694 | my $msg = $@;
|
---|
1695 | eval { $dbh->rollback; };
|
---|
1696 | return ('FAIL',$msg." $warnmsg");
|
---|
1697 | } else {
|
---|
1698 | return ('WARN', $warnmsg) if $warnmsg;
|
---|
1699 | return ('OK',"Imported OK");
|
---|
1700 | }
|
---|
1701 |
|
---|
1702 | # it should be impossible to get here.
|
---|
1703 | return ('WARN',"OOOK!");
|
---|
1704 | } # end importAXFR()
|
---|
1705 |
|
---|
1706 |
|
---|
1707 | ## DNSDB::export()
|
---|
1708 | # Export the DNS database, or a part of it
|
---|
1709 | # Takes database handle, export type, optional arguments depending on type
|
---|
1710 | # Writes zone data to targets as appropriate for type
|
---|
1711 | sub export {
|
---|
1712 | my $dbh = shift;
|
---|
1713 | my $target = shift;
|
---|
1714 |
|
---|
1715 | if ($target eq 'tiny') {
|
---|
1716 | __export_tiny($dbh,@_);
|
---|
1717 | }
|
---|
1718 | # elsif ($target eq 'foo') {
|
---|
1719 | # __export_foo($dbh,@_);
|
---|
1720 | #}
|
---|
1721 | # etc
|
---|
1722 |
|
---|
1723 | } # end export()
|
---|
1724 |
|
---|
1725 |
|
---|
1726 | ## DNSDB::__export_tiny
|
---|
1727 | # Internal sub to implement tinyDNS (compatible) export
|
---|
1728 | # Takes database handle, filehandle to write export to, optional argument(s)
|
---|
1729 | # to determine which data gets exported
|
---|
1730 | sub __export_tiny {
|
---|
1731 | my $dbh = shift;
|
---|
1732 | my $datafile = shift;
|
---|
1733 |
|
---|
1734 | ##fixme: slurp up further options to specify particular zone(s) to export
|
---|
1735 |
|
---|
1736 | ## Convert a bare number into an octal-coded pair of octets.
|
---|
1737 | # Take optional arg to indicate a decimal or hex input. Defaults to hex.
|
---|
1738 | sub octalize {
|
---|
1739 | my $tmp = shift;
|
---|
1740 | my $srctype = shift || 'h'; # default assumes hex string
|
---|
1741 | $tmp = sprintf "%0.4x", hex($tmp) if $srctype eq 'h'; # 0-pad hex to 4 digits
|
---|
1742 | $tmp = sprintf "%0.4x", $tmp if $srctype eq 'd'; # 0-pad decimal to 4 hex digits
|
---|
1743 | my @o = ($tmp =~ /^(..)(..)$/); # split into octets
|
---|
1744 | return sprintf "\\%0.3o\\%0.3o", hex($o[0]), hex($o[1]);;
|
---|
1745 | }
|
---|
1746 |
|
---|
1747 | ##fixme: fail if $datafile isn't an open, writable file
|
---|
1748 |
|
---|
1749 | # easy case - export all evarything
|
---|
1750 | # not-so-easy case - export item(s) specified
|
---|
1751 | # todo: figure out what kind of list we use to export items
|
---|
1752 |
|
---|
1753 | my $domsth = $dbh->prepare("SELECT domain_id,domain,status FROM domains WHERE status=1");
|
---|
1754 | my $recsth = $dbh->prepare("SELECT r.host,r.type,r.val,r.distance,r.weight,r.port,r.ttl,l.recdata ".
|
---|
1755 | "FROM records r LEFT OUTER JOIN longrecs l ON r.longrec_id=l.longrec_id WHERE domain_id=?");
|
---|
1756 | $domsth->execute();
|
---|
1757 | while (my ($domid,$dom,$domstat) = $domsth->fetchrow_array) {
|
---|
1758 | $recsth->execute($domid);
|
---|
1759 | while (my ($host,$type,$val,$dist,$weight,$port,$ttl,$lval) = $recsth->fetchrow_array) {
|
---|
1760 | ##fixme: need to store location in the db, and retrieve it here.
|
---|
1761 | # temporarily hardcoded to empty so we can include it further down.
|
---|
1762 | my $loc = '';
|
---|
1763 |
|
---|
1764 | ##fixme: record validity timestamp. tinydns supports fiddling with timestamps.
|
---|
1765 | # note $ttl must be set to 0 if we want to use tinydns's auto-expiring timestamps.
|
---|
1766 | # timestamps are TAI64
|
---|
1767 | # ~~ 2^62 + time()
|
---|
1768 | my $stamp = '';
|
---|
1769 |
|
---|
1770 | $val = $lval if $lval;
|
---|
1771 |
|
---|
1772 | # raw packet in unknown format: first byte indicates length
|
---|
1773 | # of remaining data, allows up to 255 raw bytes
|
---|
1774 |
|
---|
1775 | ##fixme? append . to all host/val hostnames
|
---|
1776 | if ($typemap{$type} eq 'SOA') {
|
---|
1777 |
|
---|
1778 | # host contains pri-ns:responsible
|
---|
1779 | # val is abused to contain refresh:retry:expire:minttl
|
---|
1780 | ##fixme: "manual" serial vs tinydns-autoserial
|
---|
1781 | print $datafile "Z$host"."::$val:$ttl:$stamp:$loc\n";
|
---|
1782 |
|
---|
1783 | } elsif ($typemap{$type} eq 'A') {
|
---|
1784 |
|
---|
1785 | print $datafile "+$host:$val:$ttl:$stamp:$loc\n";
|
---|
1786 |
|
---|
1787 | } elsif ($typemap{$type} eq 'NS') {
|
---|
1788 |
|
---|
1789 | print $datafile "\&$host"."::$val:$ttl:$stamp:$loc\n";
|
---|
1790 |
|
---|
1791 | } elsif ($typemap{$type} eq 'AAAA') {
|
---|
1792 |
|
---|
1793 | print $datafile ":$host:28:";
|
---|
1794 | my $altgrp = 0;
|
---|
1795 | my @altconv;
|
---|
1796 | # Split in to up to 8 groups of hex digits (allows for IPv6 :: 0-collapsing)
|
---|
1797 | foreach (split /:/, $val) {
|
---|
1798 | if (/^$/) {
|
---|
1799 | # flag blank entry; this is a series of 0's of (currently) unknown length
|
---|
1800 | $altconv[$altgrp++] = 's';
|
---|
1801 | } else {
|
---|
1802 | # call sub to convert 1-4 hex digits to 2 string-rep octal bytes
|
---|
1803 | $altconv[$altgrp++] = octalize($_)
|
---|
1804 | }
|
---|
1805 | }
|
---|
1806 | foreach my $octet (@altconv) {
|
---|
1807 | # if not 's', output
|
---|
1808 | print $datafile $octet unless $octet =~ /^s$/;
|
---|
1809 | # if 's', output (9-array length)x literal '\000\000'
|
---|
1810 | print $datafile '\000\000'x(9-$altgrp) if $octet =~ /^s$/;
|
---|
1811 | }
|
---|
1812 | print $datafile ":$ttl:$stamp:$loc\n";
|
---|
1813 |
|
---|
1814 | } elsif ($typemap{$type} eq 'MX') {
|
---|
1815 |
|
---|
1816 | print $datafile "\@$host"."::$val:$dist:$ttl:$stamp:$loc\n";
|
---|
1817 |
|
---|
1818 | } elsif ($typemap{$type} eq 'TXT') {
|
---|
1819 |
|
---|
1820 | ##fixme: split v-e-r-y long TXT strings? will need to do so for BIND export, at least
|
---|
1821 | $val =~ s/:/\\072/g; # may need to replace other symbols
|
---|
1822 | print $datafile "'$host:$val:$ttl:$stamp:$loc\n";
|
---|
1823 |
|
---|
1824 | # by-hand TXT
|
---|
1825 | #:deepnet.cx:16:2v\075spf1\040a\040a\072bacon.deepnet.cx\040a\072home.deepnet.cx\040-all:3600
|
---|
1826 | #@ IN TXT "v=spf1 a a:bacon.deepnet.cx a:home.deepnet.cx -all"
|
---|
1827 | #'deepnet.cx:v=spf1 a a\072bacon.deepnet.cx a\072home.deepnet.cx -all:3600
|
---|
1828 |
|
---|
1829 | #txttest IN TXT "v=foo bar:bob kn;ob' \" !@#$%^&*()-=_+[]{}<>?"
|
---|
1830 | #:txttest.deepnet.cx:16:\054v\075foo\040bar\072bob\040kn\073ob\047\040\042\040\041\100\043\044\045\136\046\052\050\051-\075\137\053\133\135\173\175\074\076\077:3600
|
---|
1831 |
|
---|
1832 | # very long TXT record as brought in by axfr-get
|
---|
1833 | # note tinydns does not support >512-byte RR data, need axfr-dns (for TCP support) for that
|
---|
1834 | # also note, tinydns does not seem to support <512, >256-byte RRdata from axfr-get either. :/
|
---|
1835 | #:longtxt.deepnet.cx:16:
|
---|
1836 | #\170this is a very long txt record. it is really long. long. very long. really very long. this is a very long txt record.
|
---|
1837 | #\263 it is really long. long. very long. really very long. this is a very long txt record. it is really long. long. very long. really very long. this is a very long txt record.
|
---|
1838 | #\351 it is really long. long. very long. really very long.this is a very long txt record. it is really long. long. very long. really very long. this is a very long txt record. it is really long. long. very long. really very long.
|
---|
1839 | #:3600
|
---|
1840 |
|
---|
1841 | } elsif ($typemap{$type} eq 'CNAME') {
|
---|
1842 |
|
---|
1843 | print $datafile "C$host:$val:$ttl:$stamp:$loc\n";
|
---|
1844 |
|
---|
1845 | } elsif ($typemap{$type} eq 'SRV') {
|
---|
1846 |
|
---|
1847 | # data is two-byte values for priority, weight, port, in that order,
|
---|
1848 | # followed by length/string data
|
---|
1849 |
|
---|
1850 | print $datafile ":$host:33:".octalize($dist,'d').octalize($weight,'d').octalize($port,'d');
|
---|
1851 |
|
---|
1852 | $val .= '.' if $val !~ /\.$/;
|
---|
1853 | foreach (split /\./, $val) {
|
---|
1854 | printf $datafile "\\%0.3o%s", length($_), $_;
|
---|
1855 | }
|
---|
1856 | print $datafile "\\000:$ttl:$stamp:$loc\n";
|
---|
1857 |
|
---|
1858 | } elsif ($typemap{$type} eq 'RP') {
|
---|
1859 |
|
---|
1860 | # RP consists of two mostly free-form strings.
|
---|
1861 | # The first is supposed to be an email address with @ replaced by . (as with the SOA contact)
|
---|
1862 | # The second is the "hostname" of a TXT record with more info.
|
---|
1863 | print $datafile ":$host:17:";
|
---|
1864 | my ($who,$what) = split /\s/, $val;
|
---|
1865 | foreach (split /\./, $who) {
|
---|
1866 | printf $datafile "\\%0.3o%s", length($_), $_;
|
---|
1867 | }
|
---|
1868 | print $datafile '\000';
|
---|
1869 | foreach (split /\./, $what) {
|
---|
1870 | printf $datafile "\\%0.3o%s", length($_), $_;
|
---|
1871 | }
|
---|
1872 | print $datafile "\\000:$ttl:$stamp:$loc\n";
|
---|
1873 |
|
---|
1874 | } elsif ($typemap{$type} eq 'PTR') {
|
---|
1875 |
|
---|
1876 | # must handle both IPv4 and IPv6
|
---|
1877 | ##work
|
---|
1878 | # data should already be in suitable reverse order.
|
---|
1879 | print $datafile "^$host:$val:$ttl:$stamp:$loc\n";
|
---|
1880 |
|
---|
1881 | } else {
|
---|
1882 | # raw record. we don't know what's in here, so we ASS-U-ME the user has
|
---|
1883 | # put it in correctly, since either the user is messing directly with the
|
---|
1884 | # database, or the record was imported via AXFR
|
---|
1885 | # <split by char>
|
---|
1886 | # convert anything not a-zA-Z0-9.- to octal coding
|
---|
1887 |
|
---|
1888 | ##fixme: add flag to export "unknown" record types - note we'll probably end up
|
---|
1889 | # mangling them since they were written to the DB from Net::DNS::RR::<type>->rdatastr.
|
---|
1890 | #print $datafile ":$host:$type:$val:$ttl:$stamp:$loc\n";
|
---|
1891 |
|
---|
1892 | } # record type if-else
|
---|
1893 |
|
---|
1894 | } # while ($recsth)
|
---|
1895 | } # while ($domsth)
|
---|
1896 | } # end __export_tiny()
|
---|
1897 |
|
---|
1898 |
|
---|
1899 | # shut Perl up
|
---|
1900 | 1;
|
---|