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