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