1 | # dns/trunk/DNSDB.pm
|
---|
2 | # Abstraction functions for DNS administration
|
---|
3 | ##
|
---|
4 | # $Id: DNSDB.pm 419 2012-10-10 17:14:39Z 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.2; ##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 | # Spaces are evil.
|
---|
1391 | $host =~ s/^\s+//;
|
---|
1392 | $host =~ s/\s+$//;
|
---|
1393 | if ($typemap{$rectype} ne 'TXT') {
|
---|
1394 | # Leading or trailng spaces could be legit in TXT records.
|
---|
1395 | $val =~ s/^\s+//;
|
---|
1396 | $val =~ s/\s+$//;
|
---|
1397 | }
|
---|
1398 |
|
---|
1399 | # Validation
|
---|
1400 | my $addr = NetAddr::IP->new($val);
|
---|
1401 | if ($rectype == $reverse_typemap{A}) {
|
---|
1402 | return ('FAIL',$typemap{$rectype}." record must be a valid IPv4 address")
|
---|
1403 | unless $addr && !$addr->{isv6};
|
---|
1404 | }
|
---|
1405 | if ($rectype == $reverse_typemap{AAAA}) {
|
---|
1406 | return ('FAIL',$typemap{$rectype}." record must be a valid IPv6 address")
|
---|
1407 | unless $addr && $addr->{isv6};
|
---|
1408 | }
|
---|
1409 |
|
---|
1410 | return ('FAIL', "TTL must be numeric") unless $ttl =~ /^\d+$/;
|
---|
1411 |
|
---|
1412 | my $fields = ($defrec eq 'y' ? 'group_id' : 'domain_id').",host,type,val,ttl";
|
---|
1413 | my $vallen = "?,?,?,?,?";
|
---|
1414 | my @vallist = ($id,$host,$rectype,$val,$ttl);
|
---|
1415 |
|
---|
1416 | my $dist;
|
---|
1417 | if ($rectype == $reverse_typemap{MX} or $rectype == $reverse_typemap{SRV}) {
|
---|
1418 | $dist = shift;
|
---|
1419 | return ('FAIL',"Distance is required for $typemap{$rectype} records") unless defined($dist);
|
---|
1420 | $dist =~ s/\s*//g;
|
---|
1421 | return ('FAIL',"Distance is required, and must be numeric") unless $dist =~ /^\d+$/;
|
---|
1422 | $fields .= ",distance";
|
---|
1423 | $vallen .= ",?";
|
---|
1424 | push @vallist, $dist;
|
---|
1425 | }
|
---|
1426 | my $weight;
|
---|
1427 | my $port;
|
---|
1428 | if ($rectype == $reverse_typemap{SRV}) {
|
---|
1429 | # check for _service._protocol. NB: RFC2782 does not say "MUST"... nor "SHOULD"...
|
---|
1430 | # it just says (paraphrased) "... is prepended with _ to prevent DNS collisions"
|
---|
1431 | return ('FAIL',"SRV records must begin with _service._protocol [$host]")
|
---|
1432 | unless $host =~ /^_[A-Za-z]+\._[A-Za-z]+\.[a-zA-Z0-9-]+/;
|
---|
1433 | $weight = shift;
|
---|
1434 | $port = shift;
|
---|
1435 | return ('FAIL',"Port and weight are required for SRV records") unless defined($weight) && defined($port);
|
---|
1436 | $weight =~ s/\s*//g;
|
---|
1437 | $port =~ s/\s*//g;
|
---|
1438 | return ('FAIL',"Port and weight are required, and must be numeric")
|
---|
1439 | unless $weight =~ /^\d+$/ && $port =~ /^\d+$/;
|
---|
1440 | $fields .= ",weight,port";
|
---|
1441 | $vallen .= ",?,?";
|
---|
1442 | push @vallist, ($weight,$port);
|
---|
1443 | }
|
---|
1444 |
|
---|
1445 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
1446 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
1447 | local $dbh->{AutoCommit} = 0;
|
---|
1448 | local $dbh->{RaiseError} = 1;
|
---|
1449 |
|
---|
1450 | eval {
|
---|
1451 | $dbh->do("INSERT INTO ".($defrec eq 'y' ? 'default_' : '')."records ($fields) VALUES ($vallen)",
|
---|
1452 | undef, @vallist);
|
---|
1453 | $dbh->commit;
|
---|
1454 | };
|
---|
1455 | if ($@) {
|
---|
1456 | my $msg = $@;
|
---|
1457 | eval { $dbh->rollback; };
|
---|
1458 | return ('FAIL',$msg);
|
---|
1459 | }
|
---|
1460 |
|
---|
1461 | return ('OK','OK');
|
---|
1462 |
|
---|
1463 | } # end addRec()
|
---|
1464 |
|
---|
1465 |
|
---|
1466 | ## DNSDB::updateRec()
|
---|
1467 | # Update a record
|
---|
1468 | sub updateRec {
|
---|
1469 | $errstr = '';
|
---|
1470 |
|
---|
1471 | my $dbh = shift;
|
---|
1472 | my $defrec = shift;
|
---|
1473 | my $id = shift;
|
---|
1474 |
|
---|
1475 | # all records have these
|
---|
1476 | my $host = shift;
|
---|
1477 | my $type = shift;
|
---|
1478 | my $val = shift;
|
---|
1479 | my $ttl = shift;
|
---|
1480 |
|
---|
1481 | return('FAIL',"Missing standard argument(s)") if !defined($ttl);
|
---|
1482 |
|
---|
1483 | # Spaces are evil.
|
---|
1484 | $host =~ s/^\s+//;
|
---|
1485 | $host =~ s/\s+$//;
|
---|
1486 | if ($typemap{$type} ne 'TXT') {
|
---|
1487 | # Leading or trailng spaces could be legit in TXT records.
|
---|
1488 | $val =~ s/^\s+//;
|
---|
1489 | $val =~ s/\s+$//;
|
---|
1490 | }
|
---|
1491 |
|
---|
1492 | # only MX and SRV will use these
|
---|
1493 | my $dist = 0;
|
---|
1494 | my $weight = 0;
|
---|
1495 | my $port = 0;
|
---|
1496 |
|
---|
1497 | if ($type == $reverse_typemap{MX} || $type == $reverse_typemap{SRV}) {
|
---|
1498 | $dist = shift;
|
---|
1499 | $dist =~ s/\s+//g;
|
---|
1500 | return ('FAIL',"MX or SRV requires distance") if !defined($dist);
|
---|
1501 | return ('FAIL', "Distance must be numeric") unless $dist =~ /^\d+$/;
|
---|
1502 | if ($type == $reverse_typemap{SRV}) {
|
---|
1503 | $weight = shift;
|
---|
1504 | $weight =~ s/\s+//g;
|
---|
1505 | return ('FAIL',"SRV requires weight") if !defined($weight);
|
---|
1506 | return ('FAIL',"Weight must be numeric") unless $weight =~ /^\d+$/;
|
---|
1507 | $port = shift;
|
---|
1508 | $port =~ s/\s+//g;
|
---|
1509 | return ('FAIL',"SRV requires port") if !defined($port);
|
---|
1510 | return ('FAIL',"Port must be numeric") unless $port =~ /^\d+$/;
|
---|
1511 | }
|
---|
1512 | }
|
---|
1513 |
|
---|
1514 | # Enforce IP addresses on A and AAAA types
|
---|
1515 | my $addr = NetAddr::IP->new($val);
|
---|
1516 | if ($type == $reverse_typemap{A}) {
|
---|
1517 | return ('FAIL',$typemap{$type}." record must be a valid IPv4 address")
|
---|
1518 | unless $addr && !$addr->{isv6};
|
---|
1519 | }
|
---|
1520 | if ($type == $reverse_typemap{AAAA}) {
|
---|
1521 | return ('FAIL',$typemap{$type}." record must be a valid IPv6 address")
|
---|
1522 | unless $addr && $addr->{isv6};
|
---|
1523 | }
|
---|
1524 |
|
---|
1525 | # hmm.. this might work. except possibly for something pointing to "deadbeef.ca". <g>
|
---|
1526 | # if ($type == $reverse_typemap{NS} || $type == $reverse_typemap{MX} || $type == $reverse_typemap{SRV}) {
|
---|
1527 | # if ($val =~ /^\s*[\da-f:.]+\s*$/) {
|
---|
1528 | # return ('FAIL',"$val is not a valid IP address") if !$addr;
|
---|
1529 | # }
|
---|
1530 | # }
|
---|
1531 |
|
---|
1532 | local $dbh->{AutoCommit} = 0;
|
---|
1533 | local $dbh->{RaiseError} = 1;
|
---|
1534 |
|
---|
1535 | eval {
|
---|
1536 | $dbh->do("UPDATE ".($defrec eq 'y' ? 'default_' : '')."records ".
|
---|
1537 | "SET host=?,val=?,type=?,ttl=?,distance=?,weight=?,port=? ".
|
---|
1538 | "WHERE record_id=?", undef, ($host, $val, $type, $ttl, $dist, $weight, $port, $id) );
|
---|
1539 | $dbh->commit;
|
---|
1540 | };
|
---|
1541 | if ($@) {
|
---|
1542 | my $msg = $@;
|
---|
1543 | $dbh->rollback;
|
---|
1544 | return ('FAIL', $msg);
|
---|
1545 | }
|
---|
1546 |
|
---|
1547 | return ('OK','OK');
|
---|
1548 | } # end updateRec()
|
---|
1549 |
|
---|
1550 |
|
---|
1551 | ## DNSDB::delRec()
|
---|
1552 | # Delete a record.
|
---|
1553 | sub delRec {
|
---|
1554 | $errstr = '';
|
---|
1555 | my $dbh = shift;
|
---|
1556 | my $defrec = shift;
|
---|
1557 | my $id = shift;
|
---|
1558 |
|
---|
1559 | my $sth = $dbh->prepare("DELETE FROM ".($defrec eq 'y' ? 'default_' : '')."records WHERE record_id=?");
|
---|
1560 | $sth->execute($id);
|
---|
1561 |
|
---|
1562 | return ('FAIL',"Couldn't remove record: ".$sth->errstr) if $sth->err;
|
---|
1563 |
|
---|
1564 | return ('OK','OK');
|
---|
1565 | } # end delRec()
|
---|
1566 |
|
---|
1567 |
|
---|
1568 | # Reference hashes.
|
---|
1569 | my %par_tbl = (
|
---|
1570 | group => 'groups',
|
---|
1571 | user => 'users',
|
---|
1572 | defrec => 'default_records',
|
---|
1573 | domain => 'domains',
|
---|
1574 | record => 'records'
|
---|
1575 | );
|
---|
1576 | my %id_col = (
|
---|
1577 | group => 'group_id',
|
---|
1578 | user => 'user_id',
|
---|
1579 | defrec => 'record_id',
|
---|
1580 | domain => 'domain_id',
|
---|
1581 | record => 'record_id'
|
---|
1582 | );
|
---|
1583 | my %par_col = (
|
---|
1584 | group => 'parent_group_id',
|
---|
1585 | user => 'group_id',
|
---|
1586 | defrec => 'group_id',
|
---|
1587 | domain => 'group_id',
|
---|
1588 | record => 'domain_id'
|
---|
1589 | );
|
---|
1590 | my %par_type = (
|
---|
1591 | group => 'group',
|
---|
1592 | user => 'group',
|
---|
1593 | defrec => 'group',
|
---|
1594 | domain => 'group',
|
---|
1595 | record => 'domain'
|
---|
1596 | );
|
---|
1597 |
|
---|
1598 | ## DNSDB::getParents()
|
---|
1599 | # Find out which entities are parent to the requested id
|
---|
1600 | # Returns arrayref containing hash pairs of id/type
|
---|
1601 | sub getParents {
|
---|
1602 | my $dbh = shift;
|
---|
1603 | my $id = shift;
|
---|
1604 | my $type = shift;
|
---|
1605 | my $depth = shift || 'all'; # valid values: 'all', 'immed', <int> (stop at this group ID)
|
---|
1606 |
|
---|
1607 | my @parlist;
|
---|
1608 |
|
---|
1609 | while (1) {
|
---|
1610 | my $result = $dbh->selectrow_hashref("SELECT $par_col{$type} FROM $par_tbl{$type} WHERE $id_col{$type} = ?",
|
---|
1611 | undef, ($id) );
|
---|
1612 | my %tmp = ($result->{$par_col{$type}} => $par_type{$type});
|
---|
1613 | unshift @parlist, \%tmp;
|
---|
1614 | last if $result->{$par_col{$type}} == 1; # group 1 is its own parent
|
---|
1615 | $id = $result->{$par_col{$type}};
|
---|
1616 | $type = $par_type{$type};
|
---|
1617 | }
|
---|
1618 |
|
---|
1619 | return \@parlist;
|
---|
1620 |
|
---|
1621 | } # end getParents()
|
---|
1622 |
|
---|
1623 |
|
---|
1624 | ## DNSDB::isParent()
|
---|
1625 | # Returns true if $id1 is a parent of $id2, false otherwise
|
---|
1626 | sub isParent {
|
---|
1627 | my $dbh = shift;
|
---|
1628 | my $id1 = shift;
|
---|
1629 | my $type1 = shift;
|
---|
1630 | my $id2 = shift;
|
---|
1631 | my $type2 = shift;
|
---|
1632 | ##todo: immediate, secondary, full (default)
|
---|
1633 |
|
---|
1634 | # Return false on invalid types
|
---|
1635 | return 0 if !grep /^$type1$/, ('record','defrec','user','domain','group');
|
---|
1636 | return 0 if !grep /^$type2$/, ('record','defrec','user','domain','group');
|
---|
1637 |
|
---|
1638 | # Return false on impossible relations
|
---|
1639 | return 0 if $type1 eq 'record'; # nothing may be a child of a record
|
---|
1640 | return 0 if $type1 eq 'defrec'; # nothing may be a child of a record
|
---|
1641 | return 0 if $type1 eq 'user'; # nothing may be child of a user
|
---|
1642 | return 0 if $type1 eq 'domain' && $type2 ne 'record'; # domain may not be a parent of anything other than a record
|
---|
1643 |
|
---|
1644 | # ennnhhhh.... if we're passed an id of 0, it will never be found. usual
|
---|
1645 | # case would be the UI creating a new <thing>, and so we don't have an ID for
|
---|
1646 | # <thing> to look up yet. in that case the UI should check the parent as well.
|
---|
1647 | # argument for returning 1 is
|
---|
1648 | return 0 if $id1 == 0; # nothing can have a parent id of 0
|
---|
1649 | return 1 if $id2 == 0; # anything could have a child id of 0 (or "unknown")
|
---|
1650 |
|
---|
1651 | # group 1 is the ultimate root parent
|
---|
1652 | return 1 if $type1 eq 'group' && $id1 == 1;
|
---|
1653 |
|
---|
1654 | # groups are always (a) parent of themselves
|
---|
1655 | return 1 if $type1 eq 'group' && $type2 eq 'group' && $id1 == $id2;
|
---|
1656 |
|
---|
1657 | # almost the same loop as getParents() above
|
---|
1658 | my $id = $id2;
|
---|
1659 | my $type = $type2;
|
---|
1660 | my $foundparent = 0;
|
---|
1661 |
|
---|
1662 | my $limiter = 0;
|
---|
1663 | while (1) {
|
---|
1664 | my $sql = "SELECT $par_col{$type} FROM $par_tbl{$type} WHERE $id_col{$type} = ?";
|
---|
1665 | my $result = $dbh->selectrow_hashref($sql,
|
---|
1666 | undef, ($id) );
|
---|
1667 | if (!$result) {
|
---|
1668 | $limiter++;
|
---|
1669 | ##fixme: how often will this happen on a live site?
|
---|
1670 | warn "no results looking for $sql with id $id (depth $limiter)\n";
|
---|
1671 | last;
|
---|
1672 | }
|
---|
1673 | if ($result && $result->{$par_col{$type}} == $id1) {
|
---|
1674 | $foundparent = 1;
|
---|
1675 | last;
|
---|
1676 | } else {
|
---|
1677 | ##fixme: do we care about trying to return a "no such record/domain/user/group" error?
|
---|
1678 | warn $dbh->errstr." $sql, $id" if $dbh->errstr;
|
---|
1679 | }
|
---|
1680 | # group 1 is its own parent. need this here more to break strange loops than for detecting a parent
|
---|
1681 | last if $result->{$par_col{$type}} == 1;
|
---|
1682 | $id = $result->{$par_col{$type}};
|
---|
1683 | $type = $par_type{$type};
|
---|
1684 | }
|
---|
1685 |
|
---|
1686 | return $foundparent;
|
---|
1687 | } # end isParent()
|
---|
1688 |
|
---|
1689 |
|
---|
1690 | ## DNSDB::domStatus()
|
---|
1691 | # Sets and/or returns a domain's status
|
---|
1692 | # Takes a database handle, domain ID and optionally a status argument
|
---|
1693 | # Returns undef on errors.
|
---|
1694 | sub domStatus {
|
---|
1695 | my $dbh = shift;
|
---|
1696 | my $id = shift;
|
---|
1697 | my $newstatus = shift;
|
---|
1698 |
|
---|
1699 | return undef if $id !~ /^\d+$/;
|
---|
1700 |
|
---|
1701 | my $sth;
|
---|
1702 |
|
---|
1703 | # ooo, fun! let's see what we were passed for status
|
---|
1704 | if ($newstatus) {
|
---|
1705 | $sth = $dbh->prepare("update domains set status=? where domain_id=?");
|
---|
1706 | # ass-u-me caller knows what's going on in full
|
---|
1707 | if ($newstatus =~ /^[01]$/) { # only two valid for now.
|
---|
1708 | $sth->execute($newstatus,$id);
|
---|
1709 | } elsif ($newstatus =~ /^domo(?:n|ff)$/) {
|
---|
1710 | $sth->execute(($newstatus eq 'domon' ? 1 : 0),$id);
|
---|
1711 | }
|
---|
1712 | }
|
---|
1713 |
|
---|
1714 | $sth = $dbh->prepare("select status from domains where domain_id=?");
|
---|
1715 | $sth->execute($id);
|
---|
1716 | my ($status) = $sth->fetchrow_array;
|
---|
1717 | return $status;
|
---|
1718 | } # end domStatus()
|
---|
1719 |
|
---|
1720 |
|
---|
1721 | ## DNSDB::importAXFR
|
---|
1722 | # Import a domain via AXFR
|
---|
1723 | # Takes AXFR host, domain to transfer, group to put the domain in,
|
---|
1724 | # and optionally:
|
---|
1725 | # - active/inactive state flag (defaults to active)
|
---|
1726 | # - overwrite-SOA flag (defaults to off)
|
---|
1727 | # - overwrite-NS flag (defaults to off, doesn't affect subdomain NS records)
|
---|
1728 | # Returns a status code (OK, WARN, or FAIL) and message - message should be blank
|
---|
1729 | # if status is OK, but WARN includes conditions that are not fatal but should
|
---|
1730 | # really be reported.
|
---|
1731 | sub importAXFR {
|
---|
1732 | my $dbh = shift;
|
---|
1733 | my $ifrom_in = shift;
|
---|
1734 | my $domain = shift;
|
---|
1735 | my $group = shift;
|
---|
1736 | my $status = shift || 1;
|
---|
1737 | my $rwsoa = shift || 0;
|
---|
1738 | my $rwns = shift || 0;
|
---|
1739 |
|
---|
1740 | ##fixme: add mode to delete&replace, merge+overwrite, merge new?
|
---|
1741 |
|
---|
1742 | my $nrecs = 0;
|
---|
1743 | my $soaflag = 0;
|
---|
1744 | my $nsflag = 0;
|
---|
1745 | my $warnmsg = '';
|
---|
1746 | my $ifrom;
|
---|
1747 |
|
---|
1748 | # choke on possible bad setting in ifrom
|
---|
1749 | # IPv4 and v6, and valid hostnames!
|
---|
1750 | ($ifrom) = ($ifrom_in =~ /^([0-9a-f\:.]+|[0-9a-z_.-]+)$/i);
|
---|
1751 | return ('FAIL', "Bad AXFR source host $ifrom")
|
---|
1752 | unless ($ifrom) = ($ifrom_in =~ /^([0-9a-f\:.]+|[0-9a-z_.-]+)$/i);
|
---|
1753 |
|
---|
1754 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
1755 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
1756 | local $dbh->{AutoCommit} = 0;
|
---|
1757 | local $dbh->{RaiseError} = 1;
|
---|
1758 |
|
---|
1759 | my $sth = $dbh->prepare("SELECT domain_id FROM domains WHERE domain=?");
|
---|
1760 | my $dom_id;
|
---|
1761 |
|
---|
1762 | # quick check to start to see if we've already got one
|
---|
1763 | $sth->execute($domain);
|
---|
1764 | ($dom_id) = $sth->fetchrow_array;
|
---|
1765 |
|
---|
1766 | return ('FAIL', "Domain already exists") if $dom_id;
|
---|
1767 |
|
---|
1768 | eval {
|
---|
1769 | # can't do this, can't nest transactions. sigh.
|
---|
1770 | #my ($dcode, $dmsg) = addDomain(dbh, domain, group, status);
|
---|
1771 |
|
---|
1772 | ##fixme: serial
|
---|
1773 | my $sth = $dbh->prepare("INSERT INTO domains (domain,group_id,status) VALUES (?,?,?)");
|
---|
1774 | $sth->execute($domain,$group,$status);
|
---|
1775 |
|
---|
1776 | ## bizarre DBI<->Net::DNS interaction bug:
|
---|
1777 | ## sometimes a zone will cause an immediate commit-and-exit (sort of) of the while()
|
---|
1778 | ## fixed, apparently I was doing *something* odd, but not certain what it was that
|
---|
1779 | ## caused a commit instead of barfing
|
---|
1780 |
|
---|
1781 | # get domain id so we can do the records
|
---|
1782 | $sth = $dbh->prepare("SELECT domain_id FROM domains WHERE domain=?");
|
---|
1783 | $sth->execute($domain);
|
---|
1784 | ($dom_id) = $sth->fetchrow_array();
|
---|
1785 |
|
---|
1786 | my $res = Net::DNS::Resolver->new;
|
---|
1787 | $res->nameservers($ifrom);
|
---|
1788 | $res->axfr_start($domain)
|
---|
1789 | or die "Couldn't begin AXFR\n";
|
---|
1790 |
|
---|
1791 | while (my $rr = $res->axfr_next()) {
|
---|
1792 | my $type = $rr->type;
|
---|
1793 |
|
---|
1794 | my $sql = "INSERT INTO records (domain_id,host,type,ttl,val";
|
---|
1795 | my $vallen = "?,?,?,?,?";
|
---|
1796 |
|
---|
1797 | $soaflag = 1 if $type eq 'SOA';
|
---|
1798 | $nsflag = 1 if $type eq 'NS';
|
---|
1799 |
|
---|
1800 | my @vallist = ($dom_id, $rr->name, $reverse_typemap{$type}, $rr->ttl);
|
---|
1801 |
|
---|
1802 | # "Primary" types:
|
---|
1803 | # A, NS, CNAME, SOA, PTR(warn in forward), MX, TXT, AAAA, SRV, A6(ob), SPF
|
---|
1804 | # maybe KEY
|
---|
1805 |
|
---|
1806 | # nasty big ugly case-like thing here, since we have to do *some* different
|
---|
1807 | # processing depending on the record. le sigh.
|
---|
1808 |
|
---|
1809 | ##fixme: what record types other than TXT can/will have >255-byte payloads?
|
---|
1810 |
|
---|
1811 | if ($type eq 'A') {
|
---|
1812 | push @vallist, $rr->address;
|
---|
1813 | } elsif ($type eq 'NS') {
|
---|
1814 | # hmm. should we warn here if subdomain NS'es are left alone?
|
---|
1815 | next if ($rwns && ($rr->name eq $domain));
|
---|
1816 | push @vallist, $rr->nsdname;
|
---|
1817 | $nsflag = 1;
|
---|
1818 | } elsif ($type eq 'CNAME') {
|
---|
1819 | push @vallist, $rr->cname;
|
---|
1820 | } elsif ($type eq 'SOA') {
|
---|
1821 | next if $rwsoa;
|
---|
1822 | $vallist[1] = $rr->mname.":".$rr->rname;
|
---|
1823 | push @vallist, ($rr->refresh.":".$rr->retry.":".$rr->expire.":".$rr->minimum);
|
---|
1824 | $soaflag = 1;
|
---|
1825 | } elsif ($type eq 'PTR') {
|
---|
1826 | push @vallist, $rr->ptrdname;
|
---|
1827 | # hmm. PTR records should not be in forward zones.
|
---|
1828 | } elsif ($type eq 'MX') {
|
---|
1829 | $sql .= ",distance";
|
---|
1830 | $vallen .= ",?";
|
---|
1831 | push @vallist, $rr->exchange;
|
---|
1832 | push @vallist, $rr->preference;
|
---|
1833 | } elsif ($type eq 'TXT') {
|
---|
1834 | ##fixme: Net::DNS docs say this should be deprecated for rdatastr() or char_str_list(),
|
---|
1835 | ## but don't really seem enthusiastic about it.
|
---|
1836 | my $rrdata = $rr->txtdata;
|
---|
1837 | push @vallist, $rrdata;
|
---|
1838 | } elsif ($type eq 'SPF') {
|
---|
1839 | ##fixme: and the same caveat here, since it is apparently a clone of ::TXT
|
---|
1840 | my $rrdata = $rr->txtdata;
|
---|
1841 | push @vallist, $rrdata;
|
---|
1842 | } elsif ($type eq 'AAAA') {
|
---|
1843 | push @vallist, $rr->address;
|
---|
1844 | } elsif ($type eq 'SRV') {
|
---|
1845 | $sql .= ",distance,weight,port" if $type eq 'SRV';
|
---|
1846 | $vallen .= ",?,?,?" if $type eq 'SRV';
|
---|
1847 | push @vallist, $rr->target;
|
---|
1848 | push @vallist, $rr->priority;
|
---|
1849 | push @vallist, $rr->weight;
|
---|
1850 | push @vallist, $rr->port;
|
---|
1851 | } elsif ($type eq 'KEY') {
|
---|
1852 | # we don't actually know what to do with these...
|
---|
1853 | push @vallist, ($rr->flags.":".$rr->protocol.":".$rr->algorithm.":".$rr->key.":".$rr->keytag.":".$rr->privatekeyname);
|
---|
1854 | } else {
|
---|
1855 | my $rrdata = $rr->rdatastr;
|
---|
1856 | push @vallist, $rrdata;
|
---|
1857 | # Finding a different record type is not fatal.... just problematic.
|
---|
1858 | # We may not be able to export it correctly.
|
---|
1859 | $warnmsg .= "Unusual record ".$rr->name." ($type) found\n";
|
---|
1860 | }
|
---|
1861 |
|
---|
1862 | # BIND supports:
|
---|
1863 | # A CNAME HINFO MB(ex) MD(ob) MF(ob) MG(ex) MINFO(ex) MR(ex) MX NS NULL
|
---|
1864 | # PTR SOA TXT WKS AFSDB(ex) ISDN(ex) RP(ex) RT(ex) X25(ex) PX
|
---|
1865 | # ... if one can ever find the right magic to format them correctly
|
---|
1866 |
|
---|
1867 | # Net::DNS supports:
|
---|
1868 | # RRSIG SIG NSAP NS NIMLOC NAPTR MX MR MINFO MG MB LOC ISDN IPSECKEY HINFO
|
---|
1869 | # EID DNAME CNAME CERT APL AFSDB AAAA A DS NXT NSEC3PARAM NSEC3 NSEC KEY
|
---|
1870 | # DNSKEY DLV X25 TXT TSIG TKEY SSHFP SRV SPF SOA RT RP PX PTR NULL APL::AplItem
|
---|
1871 |
|
---|
1872 | $sth = $dbh->prepare($sql.") VALUES (".$vallen.")") or die "problem preparing record insert SQL\n";
|
---|
1873 | $sth->execute(@vallist) or die "failed to insert ".$rr->string.": ".$sth->errstr."\n";
|
---|
1874 |
|
---|
1875 | $nrecs++;
|
---|
1876 |
|
---|
1877 | } # while axfr_next
|
---|
1878 |
|
---|
1879 | # Overwrite SOA record
|
---|
1880 | if ($rwsoa) {
|
---|
1881 | $soaflag = 1;
|
---|
1882 | my $sthgetsoa = $dbh->prepare("SELECT host,val,ttl FROM default_records WHERE group_id=? AND type=?");
|
---|
1883 | my $sthputsoa = $dbh->prepare("INSERT INTO records (domain_id,host,type,val,ttl) VALUES (?,?,?,?,?)");
|
---|
1884 | $sthgetsoa->execute($group,$reverse_typemap{SOA});
|
---|
1885 | while (my ($host,$val,$ttl) = $sthgetsoa->fetchrow_array()) {
|
---|
1886 | $host =~ s/DOMAIN/$domain/g;
|
---|
1887 | $val =~ s/DOMAIN/$domain/g;
|
---|
1888 | $sthputsoa->execute($dom_id,$host,$reverse_typemap{SOA},$val,$ttl);
|
---|
1889 | }
|
---|
1890 | }
|
---|
1891 |
|
---|
1892 | # Overwrite NS records
|
---|
1893 | if ($rwns) {
|
---|
1894 | $nsflag = 1;
|
---|
1895 | my $sthgetns = $dbh->prepare("SELECT host,val,ttl FROM default_records WHERE group_id=? AND type=?");
|
---|
1896 | my $sthputns = $dbh->prepare("INSERT INTO records (domain_id,host,type,val,ttl) VALUES (?,?,?,?,?)");
|
---|
1897 | $sthgetns->execute($group,$reverse_typemap{NS});
|
---|
1898 | while (my ($host,$val,$ttl) = $sthgetns->fetchrow_array()) {
|
---|
1899 | $host =~ s/DOMAIN/$domain/g;
|
---|
1900 | $val =~ s/DOMAIN/$domain/g;
|
---|
1901 | $sthputns->execute($dom_id,$host,$reverse_typemap{NS},$val,$ttl);
|
---|
1902 | }
|
---|
1903 | }
|
---|
1904 |
|
---|
1905 | die "No records found; either $ifrom is not authoritative or doesn't allow transfers\n" if !$nrecs;
|
---|
1906 | die "Bad zone: No SOA record!\n" if !$soaflag;
|
---|
1907 | die "Bad zone: No NS records!\n" if !$nsflag;
|
---|
1908 |
|
---|
1909 | $dbh->commit;
|
---|
1910 |
|
---|
1911 | };
|
---|
1912 |
|
---|
1913 | if ($@) {
|
---|
1914 | my $msg = $@;
|
---|
1915 | eval { $dbh->rollback; };
|
---|
1916 | return ('FAIL',$msg." $warnmsg");
|
---|
1917 | } else {
|
---|
1918 | return ('WARN', $warnmsg) if $warnmsg;
|
---|
1919 | return ('OK',"Imported OK");
|
---|
1920 | }
|
---|
1921 |
|
---|
1922 | # it should be impossible to get here.
|
---|
1923 | return ('WARN',"OOOK!");
|
---|
1924 | } # end importAXFR()
|
---|
1925 |
|
---|
1926 |
|
---|
1927 | ## DNSDB::export()
|
---|
1928 | # Export the DNS database, or a part of it
|
---|
1929 | # Takes database handle, export type, optional arguments depending on type
|
---|
1930 | # Writes zone data to targets as appropriate for type
|
---|
1931 | sub export {
|
---|
1932 | my $dbh = shift;
|
---|
1933 | my $target = shift;
|
---|
1934 |
|
---|
1935 | if ($target eq 'tiny') {
|
---|
1936 | __export_tiny($dbh,@_);
|
---|
1937 | }
|
---|
1938 | # elsif ($target eq 'foo') {
|
---|
1939 | # __export_foo($dbh,@_);
|
---|
1940 | #}
|
---|
1941 | # etc
|
---|
1942 |
|
---|
1943 | } # end export()
|
---|
1944 |
|
---|
1945 |
|
---|
1946 | ## DNSDB::__export_tiny
|
---|
1947 | # Internal sub to implement tinyDNS (compatible) export
|
---|
1948 | # Takes database handle, filehandle to write export to, optional argument(s)
|
---|
1949 | # to determine which data gets exported
|
---|
1950 | sub __export_tiny {
|
---|
1951 | my $dbh = shift;
|
---|
1952 | my $datafile = shift;
|
---|
1953 |
|
---|
1954 | ##fixme: slurp up further options to specify particular zone(s) to export
|
---|
1955 |
|
---|
1956 | ## Convert a bare number into an octal-coded pair of octets.
|
---|
1957 | # Take optional arg to indicate a decimal or hex input. Defaults to hex.
|
---|
1958 | sub octalize {
|
---|
1959 | my $tmp = shift;
|
---|
1960 | my $srctype = shift || 'h'; # default assumes hex string
|
---|
1961 | $tmp = sprintf "%0.4x", hex($tmp) if $srctype eq 'h'; # 0-pad hex to 4 digits
|
---|
1962 | $tmp = sprintf "%0.4x", $tmp if $srctype eq 'd'; # 0-pad decimal to 4 hex digits
|
---|
1963 | my @o = ($tmp =~ /^(..)(..)$/); # split into octets
|
---|
1964 | return sprintf "\\%0.3o\\%0.3o", hex($o[0]), hex($o[1]);;
|
---|
1965 | }
|
---|
1966 |
|
---|
1967 | ##fixme: fail if $datafile isn't an open, writable file
|
---|
1968 |
|
---|
1969 | # easy case - export all evarything
|
---|
1970 | # not-so-easy case - export item(s) specified
|
---|
1971 | # todo: figure out what kind of list we use to export items
|
---|
1972 |
|
---|
1973 | my $domsth = $dbh->prepare("SELECT domain_id,domain,status FROM domains WHERE status=1");
|
---|
1974 | my $recsth = $dbh->prepare("SELECT host,type,val,distance,weight,port,ttl ".
|
---|
1975 | "FROM records WHERE domain_id=?");
|
---|
1976 | $domsth->execute();
|
---|
1977 | while (my ($domid,$dom,$domstat) = $domsth->fetchrow_array) {
|
---|
1978 | $recsth->execute($domid);
|
---|
1979 | while (my ($host,$type,$val,$dist,$weight,$port,$ttl) = $recsth->fetchrow_array) {
|
---|
1980 | ##fixme: need to store location in the db, and retrieve it here.
|
---|
1981 | # temporarily hardcoded to empty so we can include it further down.
|
---|
1982 | my $loc = '';
|
---|
1983 |
|
---|
1984 | ##fixme: record validity timestamp. tinydns supports fiddling with timestamps.
|
---|
1985 | # note $ttl must be set to 0 if we want to use tinydns's auto-expiring timestamps.
|
---|
1986 | # timestamps are TAI64
|
---|
1987 | # ~~ 2^62 + time()
|
---|
1988 | my $stamp = '';
|
---|
1989 |
|
---|
1990 | # raw packet in unknown format: first byte indicates length
|
---|
1991 | # of remaining data, allows up to 255 raw bytes
|
---|
1992 |
|
---|
1993 | # Spaces are evil.
|
---|
1994 | $host =~ s/^\s+//;
|
---|
1995 | $host =~ s/\s+$//;
|
---|
1996 | if ($typemap{$type} ne 'TXT') {
|
---|
1997 | # Leading or trailng spaces could be legit in TXT records.
|
---|
1998 | $val =~ s/^\s+//;
|
---|
1999 | $val =~ s/\s+$//;
|
---|
2000 | }
|
---|
2001 |
|
---|
2002 | ##fixme? append . to all host/val hostnames
|
---|
2003 | if ($typemap{$type} eq 'SOA') {
|
---|
2004 |
|
---|
2005 | # host contains pri-ns:responsible
|
---|
2006 | # val is abused to contain refresh:retry:expire:minttl
|
---|
2007 | ##fixme: "manual" serial vs tinydns-autoserial
|
---|
2008 | # let's be explicit about abusing $host and $val
|
---|
2009 | my ($email, $primary) = (split /:/, $host)[0,1];
|
---|
2010 | my ($refresh, $retry, $expire, $min_ttl) = (split /:/, $val)[0,1,2,3];
|
---|
2011 | print $datafile "Z$dom:$primary:$email"."::$refresh:$retry:$expire:$min_ttl:$ttl:$stamp:$loc\n";
|
---|
2012 |
|
---|
2013 | } elsif ($typemap{$type} eq 'A') {
|
---|
2014 |
|
---|
2015 | print $datafile "+$host:$val:$ttl:$stamp:$loc\n";
|
---|
2016 |
|
---|
2017 | } elsif ($typemap{$type} eq 'NS') {
|
---|
2018 |
|
---|
2019 | print $datafile "\&$host"."::$val:$ttl:$stamp:$loc\n";
|
---|
2020 |
|
---|
2021 | } elsif ($typemap{$type} eq 'AAAA') {
|
---|
2022 |
|
---|
2023 | print $datafile ":$host:28:";
|
---|
2024 | my $altgrp = 0;
|
---|
2025 | my @altconv;
|
---|
2026 | # Split in to up to 8 groups of hex digits (allows for IPv6 :: 0-collapsing)
|
---|
2027 | foreach (split /:/, $val) {
|
---|
2028 | if (/^$/) {
|
---|
2029 | # flag blank entry; this is a series of 0's of (currently) unknown length
|
---|
2030 | $altconv[$altgrp++] = 's';
|
---|
2031 | } else {
|
---|
2032 | # call sub to convert 1-4 hex digits to 2 string-rep octal bytes
|
---|
2033 | $altconv[$altgrp++] = octalize($_)
|
---|
2034 | }
|
---|
2035 | }
|
---|
2036 | foreach my $octet (@altconv) {
|
---|
2037 | # if not 's', output
|
---|
2038 | print $datafile $octet unless $octet =~ /^s$/;
|
---|
2039 | # if 's', output (9-array length)x literal '\000\000'
|
---|
2040 | print $datafile '\000\000'x(9-$altgrp) if $octet =~ /^s$/;
|
---|
2041 | }
|
---|
2042 | print $datafile ":$ttl:$stamp:$loc\n";
|
---|
2043 |
|
---|
2044 | } elsif ($typemap{$type} eq 'MX') {
|
---|
2045 |
|
---|
2046 | print $datafile "\@$host"."::$val:$dist:$ttl:$stamp:$loc\n";
|
---|
2047 |
|
---|
2048 | } elsif ($typemap{$type} eq 'TXT') {
|
---|
2049 |
|
---|
2050 | ##fixme: split v-e-r-y long TXT strings? will need to do so for BIND export, at least
|
---|
2051 | $val =~ s/:/\\072/g; # may need to replace other symbols
|
---|
2052 | print $datafile "'$host:$val:$ttl:$stamp:$loc\n";
|
---|
2053 |
|
---|
2054 | # by-hand TXT
|
---|
2055 | #:deepnet.cx:16:2v\075spf1\040a\040a\072bacon.deepnet.cx\040a\072home.deepnet.cx\040-all:3600
|
---|
2056 | #@ IN TXT "v=spf1 a a:bacon.deepnet.cx a:home.deepnet.cx -all"
|
---|
2057 | #'deepnet.cx:v=spf1 a a\072bacon.deepnet.cx a\072home.deepnet.cx -all:3600
|
---|
2058 |
|
---|
2059 | #txttest IN TXT "v=foo bar:bob kn;ob' \" !@#$%^&*()-=_+[]{}<>?"
|
---|
2060 | #: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
|
---|
2061 |
|
---|
2062 | # very long TXT record as brought in by axfr-get
|
---|
2063 | # note tinydns does not support >512-byte RR data, need axfr-dns (for TCP support) for that
|
---|
2064 | # also note, tinydns does not seem to support <512, >256-byte RRdata from axfr-get either. :/
|
---|
2065 | #:longtxt.deepnet.cx:16:
|
---|
2066 | #\170this is a very long txt record. it is really long. long. very long. really very long. this is a very long txt record.
|
---|
2067 | #\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.
|
---|
2068 | #\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.
|
---|
2069 | #:3600
|
---|
2070 |
|
---|
2071 | } elsif ($typemap{$type} eq 'CNAME') {
|
---|
2072 |
|
---|
2073 | print $datafile "C$host:$val:$ttl:$stamp:$loc\n";
|
---|
2074 |
|
---|
2075 | } elsif ($typemap{$type} eq 'SRV') {
|
---|
2076 |
|
---|
2077 | # data is two-byte values for priority, weight, port, in that order,
|
---|
2078 | # followed by length/string data
|
---|
2079 |
|
---|
2080 | print $datafile ":$host:33:".octalize($dist,'d').octalize($weight,'d').octalize($port,'d');
|
---|
2081 |
|
---|
2082 | $val .= '.' if $val !~ /\.$/;
|
---|
2083 | foreach (split /\./, $val) {
|
---|
2084 | printf $datafile "\\%0.3o%s", length($_), $_;
|
---|
2085 | }
|
---|
2086 | print $datafile "\\000:$ttl:$stamp:$loc\n";
|
---|
2087 |
|
---|
2088 | } elsif ($typemap{$type} eq 'RP') {
|
---|
2089 |
|
---|
2090 | # RP consists of two mostly free-form strings.
|
---|
2091 | # The first is supposed to be an email address with @ replaced by . (as with the SOA contact)
|
---|
2092 | # The second is the "hostname" of a TXT record with more info.
|
---|
2093 | print $datafile ":$host:17:";
|
---|
2094 | my ($who,$what) = split /\s/, $val;
|
---|
2095 | foreach (split /\./, $who) {
|
---|
2096 | printf $datafile "\\%0.3o%s", length($_), $_;
|
---|
2097 | }
|
---|
2098 | print $datafile '\000';
|
---|
2099 | foreach (split /\./, $what) {
|
---|
2100 | printf $datafile "\\%0.3o%s", length($_), $_;
|
---|
2101 | }
|
---|
2102 | print $datafile "\\000:$ttl:$stamp:$loc\n";
|
---|
2103 |
|
---|
2104 | } elsif ($typemap{$type} eq 'PTR') {
|
---|
2105 |
|
---|
2106 | # must handle both IPv4 and IPv6
|
---|
2107 | ##work
|
---|
2108 | # data should already be in suitable reverse order.
|
---|
2109 | print $datafile "^$host:$val:$ttl:$stamp:$loc\n";
|
---|
2110 |
|
---|
2111 | } else {
|
---|
2112 | # raw record. we don't know what's in here, so we ASS-U-ME the user has
|
---|
2113 | # put it in correctly, since either the user is messing directly with the
|
---|
2114 | # database, or the record was imported via AXFR
|
---|
2115 | # <split by char>
|
---|
2116 | # convert anything not a-zA-Z0-9.- to octal coding
|
---|
2117 |
|
---|
2118 | ##fixme: add flag to export "unknown" record types - note we'll probably end up
|
---|
2119 | # mangling them since they were written to the DB from Net::DNS::RR::<type>->rdatastr.
|
---|
2120 | #print $datafile ":$host:$type:$val:$ttl:$stamp:$loc\n";
|
---|
2121 |
|
---|
2122 | } # record type if-else
|
---|
2123 |
|
---|
2124 | } # while ($recsth)
|
---|
2125 | } # while ($domsth)
|
---|
2126 | } # end __export_tiny()
|
---|
2127 |
|
---|
2128 |
|
---|
2129 | ## DNSDB::mailNotify()
|
---|
2130 | # Sends notification mail to recipients regarding an IPDB operation
|
---|
2131 | sub mailNotify {
|
---|
2132 | my $dbh = shift;
|
---|
2133 | my ($subj,$message) = @_;
|
---|
2134 |
|
---|
2135 | return if $config{mailhost} eq 'smtp.example.com'; # do nothing if still using default SMTP host.
|
---|
2136 |
|
---|
2137 | my $mailer = Net::SMTP->new($config{mailhost}, Hello => "dnsadmin.$config{domain}");
|
---|
2138 |
|
---|
2139 | my $mailsender = ($config{mailsender} ? $config{mailsender} : $config{mailnotify});
|
---|
2140 |
|
---|
2141 | $mailer->mail($mailsender);
|
---|
2142 | $mailer->to($config{mailnotify});
|
---|
2143 | $mailer->data("From: \"$config{mailname}\" <$mailsender>\n",
|
---|
2144 | "To: <$config{mailnotify}>\n",
|
---|
2145 | "Date: ".strftime("%a, %d %b %Y %H:%M:%S %z",localtime)."\n",
|
---|
2146 | "Subject: $subj\n",
|
---|
2147 | "X-Mailer: DNSAdmin Notify v".sprintf("%.1d",$DNSDB::VERSION)."\n",
|
---|
2148 | "Organization: $config{orgname}\n",
|
---|
2149 | "\n$message\n");
|
---|
2150 | $mailer->quit;
|
---|
2151 | }
|
---|
2152 |
|
---|
2153 | # shut Perl up
|
---|
2154 | 1;
|
---|