source: branches/stable/dns.cgi@ 544

Last change on this file since 544 was 544, checked in by Kris Deugau, 11 years ago

/branches/stable

Merge reverse DNS work; 1 of mumble

  • from branch creation through r261

Minor conflicts in dns.cgi and DNSDB.pm

  • Property svn:executable set to *
  • Property svn:keywords set to Date Rev Author Id
File size: 89.7 KB
Line 
1#!/usr/bin/perl -w -T
2# Main web UI script for DeepNet DNS Administrator
3##
4# $Id: dns.cgi 544 2013-12-10 22:15:56Z 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
21use strict;
22use warnings;
23
24use CGI::Carp qw (fatalsToBrowser);
25use CGI::Simple;
26use HTML::Template;
27use CGI::Session;
28use Crypt::PasswdMD5;
29use Digest::MD5 qw(md5_hex);
30use Net::DNS;
31use DBI;
32use Data::Dumper;
33
34#sub is_tainted {
35# # from perldoc perlsec
36# return ! eval { eval("#" . substr(join("", @_), 0, 0)); 1 };
37#}
38#use Cwd 'abs_path';
39#use File::Basename;
40#use lib dirname( abs_path $0 );
41#die "argh! tainted!" if is_tainted($0);
42#die "argh! \@INC got tainted!" if is_tainted(@INC);
43
44# don't remove! required for GNU/FHS-ish install from tarball
45use lib '.'; ##uselib##
46
47use DNSDB qw(:ALL);
48
49my @debugbits; # temp, to be spit out near the end of processing
50my $debugenv = 0;
51
52# Let's do these templates right...
53my $templatedir = "templates";
54
55# Set up the CGI object...
56my $q = new CGI::Simple;
57# ... and get query-string params as well as POST params if necessary
58$q->parse_query_string;
59
60# This is probably excessive fiddling, but it puts the parameters somewhere my fingers know about...
61my %webvar = $q->Vars;
62
63# shut up some warnings, in case we arrive somewhere we forgot to set this
64$webvar{defrec} = 'n' if !$webvar{defrec}; # non-default records
65$webvar{revrec} = 'n' if !$webvar{revrec}; # non-reverse (domain) records
66
67# load some local system defaults (mainly DB connect info)
68# note this is not *absolutely* fatal, since there's a default dbname/user/pass in DNSDB.pm
69# we'll catch a bad DB connect string once we get to trying that
70##fixme: pass params to loadConfig, and use them there, to allow one codebase to support multiple sites
71if (!loadConfig()) {
72 warn "Using default configuration; unable to load custom settings: $DNSDB::errstr";
73}
74
75# persistent stuff needed on most/all pages
76my $sid = ($webvar{sid} ? $webvar{sid} : undef);
77my $session = new CGI::Session("driver:File", $sid, {Directory => $config{sessiondir}})
78 or die CGI::Session->errstr();
79#$sid = $session->id() if !$sid;
80if (!$sid) {
81 # init stuff. can probably axe this down to just above if'n'when user manipulation happens
82 $sid = $session->id();
83 $session->expire($config{timeout});
84# need to know the "upper" group the user can deal with; may as well
85# stick this in the session rather than calling out to the DB every time.
86 $session->param('logingroup',1);
87 $session->param('curgroup',1); # yes, we *do* need to track this too. er, probably.
88 $session->param('domlistsortby','domain');
89 $session->param('domlistorder','ASC');
90 $session->param('revzonessortby','revnet');
91 $session->param('revzonesorder','ASC');
92 $session->param('useradminsortby','user');
93 $session->param('useradminorder','ASC');
94 $session->param('grpmansortby','group');
95 $session->param('grpmanorder','ASC');
96 $session->param('reclistsortby','host');
97 $session->param('reclistorder','ASC');
98}
99
100# Just In Case. Stale sessions should not be resurrectable.
101if ($sid ne $session->id()) {
102 $sid = '';
103 changepage(page=> "login", sessexpired => 1);
104}
105
106# normal expiry, more or less
107if ($session->is_expired) {
108 $sid = '';
109 changepage(page=> "login", sessexpired => 1);
110}
111
112my $logingroup = ($session->param('logingroup') ? $session->param('logingroup') : 1);
113my $curgroup = ($session->param('curgroup') ? $session->param('curgroup') : $logingroup);
114
115# decide which page to spit out...
116# also set $webvar{page} before we try to use it.
117$webvar{page} = 'login' if !$webvar{page};
118
119# per-page startwith, filter, searchsubs
120
121##fixme: complain-munge-and-continue with non-"[a-z0-9-.]" filter and startwith
122$webvar{startwith} =~ s/^(0-9|[a-z]).*/$1/ if $webvar{startwith};
123# not much call for chars not allowed in domain names
124$webvar{filter} =~ s/[^a-zA-Z0-9_.:@-]//g if $webvar{filter};
125## only set 'y' if box is checked, no other values legal
126## however, see https://secure.deepnet.cx/trac/dnsadmin/ticket/31
127# first, drop obvious fakes
128delete $webvar{searchsubs} if $webvar{searchsubs} && $webvar{searchsubs} !~ /^[ny]/;
129# strip the known "turn me off!" bit.
130$webvar{searchsubs} =~ s/^n\s?// if $webvar{searchsubs};
131# strip non-y/n - note this legitimately allows {searchsubs} to go empty
132$webvar{searchsubs} =~ s/[^yn]//g if $webvar{searchsubs};
133
134$session->param($webvar{page}.'startwith', $webvar{startwith}) if defined($webvar{startwith});
135$session->param($webvar{page}.'filter', $webvar{filter}) if defined($webvar{filter});
136$session->param($webvar{page}.'searchsubs', $webvar{searchsubs}) if defined($webvar{searchsubs});
137
138my $startwith = $session->param($webvar{page}.'startwith');
139my $filter = $session->param($webvar{page}.'filter');
140my $searchsubs = $session->param($webvar{page}.'searchsubs');
141
142# ... and assemble the args
143my @filterargs;
144push @filterargs, "^[$startwith]" if $startwith;
145push @filterargs, $filter if $filter;
146
147# nrgh, can't handle login here because we don't have a database handle to check the user/pass with yet
148
149my $header = HTML::Template->new(filename => "$templatedir/header.tmpl");
150my $footer = HTML::Template->new(filename => "$templatedir/footer.tmpl");
151$header->param(orgname => $config{orgname}) if $config{orgname} ne 'Example Corp';
152$footer->param(version => $DNSDB::VERSION);
153
154## set up "URL to self"
155# @#$%@%@#% XHTML - & in a URL must be escaped. >:(
156my $uri_self = $ENV{REQUEST_URI};
157$uri_self =~ s/\&([a-z])/\&amp\;$1/g;
158
159# le sigh. and we need to strip any previous action
160$uri_self =~ s/\&amp;action=[^&]+//g;
161
162# and search filter options. these get stored in the session, but discarded
163# as soon as you switch to a different page.
164##fixme: think about retaining these on a per-page basis, as well as offset; same as the sort-order bits
165no warnings qw(uninitialized);
166$uri_self =~ s/\&amp;startwith=[a-z09-]*(\&)?/$1/g;
167$uri_self =~ s/\&amp;searchsubs=[a-z09-]*(\&)?/$1/g;
168$uri_self =~ s/\&amp;filter=[a-z09-]*(\&)?/$1/g;
169use warnings qw(uninitialized);
170
171# Fix up $uri_self so we don't lose the session/page
172$uri_self .= "?sid=$sid&amp;page=$webvar{page}" if $uri_self =~ m{/dns.cgi$};
173$uri_self = "$ENV{SCRIPT_NAME}?sid=$sid&amp;page=$webvar{page}$1" if $uri_self =~ m{/dns.cgi\&(.+)$};
174
175# pagination
176my $perpage = 15;
177$perpage = $config{perpage} if $config{perpage};
178my $offset = ($webvar{offset} ? $webvar{offset} : 0);
179
180# NB: these must match the field name and SQL ascend/descend syntax respectively
181my $sortby = "domain";
182my $sortorder = "ASC";
183
184##fixme: quit throwing the database handle around, and put all the SQL and direct DB fiddling into DNSDB.pm
185# dbname, user, pass, host (optional)
186my ($dbh,$msg) = connectDB($config{dbname}, $config{dbuser}, $config{dbpass}, $config{dbhost});
187
188if (!$dbh) {
189 print "Content-type: text/html\n\n";
190 print $header->output;
191 my $errpage = HTML::Template->new(filename => "$templatedir/dberr.tmpl");
192 $errpage->param(errmsg => $msg);
193 print $errpage->output;
194 print $footer->output;
195 exit;
196}
197
198# Load config pieces from the database. Ideally all but the DB user/pass/etc should be loaded here.
199initGlobals($dbh);
200
201# security check - does the user have permission to view this entity?
202# this is a prep step used "many" places
203my @viewablegroups;
204getChildren($dbh, $logingroup, \@viewablegroups, 'all');
205push @viewablegroups, $logingroup;
206
207my $page;
208eval {
209 # sigh. can't set loop_context_vars or global_vars once instantiated.
210 $page = HTML::Template->new(filename => "$templatedir/$webvar{page}.tmpl",
211 loop_context_vars => 1, global_vars => 1);
212};
213if ($@) {
214 my $msg = $@;
215 $page = HTML::Template->new(filename => "$templatedir/badpage.tmpl");
216 if (-e "$templatedir/$webvar{page}.tmpl") {
217 $page->param(badtemplate => $q->escapeHTML($msg));
218 } else {
219 warn "Bad page $webvar{page} requested";
220 $page->param(badpage => $q->escapeHTML($webvar{page}));
221 }
222 $webvar{page} = 'badpage';
223}
224
225# handle login redirect
226if ($webvar{action}) {
227 if ($webvar{action} eq 'login') {
228 # Snag ACL/permissions here too
229 my $sth = $dbh->prepare("SELECT user_id,group_id,password,firstname,lastname,status FROM users WHERE username=?");
230 $sth->execute($webvar{username});
231
232 if (my ($uid,$gid,$pass,$fname,$lname,$status) = $sth->fetchrow_array) {
233 $webvar{password} = '' if !$webvar{password};
234 if (!$status) {
235 $webvar{loginfailed} = 1;
236 } elsif ($pass =~ m|^\$1\$([A-Za-z0-9/.]+)\$|) {
237 # native passwords (crypt-md5)
238 $webvar{loginfailed} = 1 if $pass ne unix_md5_crypt($webvar{password},$1);
239 } elsif ($pass =~ /^[0-9a-f]{32}$/) {
240 # VegaDNS import (hex-coded MD5)
241 $webvar{loginfailed} = 1 if $pass ne md5_hex($webvar{password});
242 } else {
243 # plaintext (convenient now and then)
244 $webvar{loginfailed} = 1 if $pass ne $webvar{password};
245 }
246
247 # set session bits
248 $session->param('logingroup',$gid);
249 $session->param('curgroup',$gid);
250 $session->param('uid',$uid);
251 $session->param('username',$webvar{username});
252
253 changepage(page => "domlist") if !defined($webvar{loginfailed});
254
255 } else {
256 $webvar{loginfailed} = 1;
257 } # user data fetch check
258
259 } elsif ($webvar{action} eq 'logout') {
260 # delete the session
261 $session->delete();
262 $session->flush();
263
264 my $newurl = "http://$ENV{HTTP_HOST}$ENV{SCRIPT_NAME}";
265 $newurl =~ s|/[^/]+$|/|;
266 print "Status: 302\nLocation: $newurl\n\n";
267 exit;
268
269 } elsif ($webvar{action} eq 'chgroup') {
270 # fiddle session-stored group data
271 # magic incantation to... uhhh...
272
273 # ... and the "change group" bits...
274 $uri_self =~ s/\&amp;group=[^&]*//g;
275
276 # security check - does the user have permission to view this entity?
277 my $errmsg;
278 if (!(grep /^$webvar{group}$/, @viewablegroups)) {
279 # hmm. Reset the current group to the login group? Yes. Prevents confusing behaviour elsewhere.
280 $session->param('curgroup',$logingroup);
281 $webvar{group} = $logingroup;
282 $curgroup = $logingroup;
283 $errmsg = "You are not permitted to view or make changes in the requested group";
284 $page->param(errmsg => $errmsg);
285 }
286
287 $session->param('curgroup', $webvar{group});
288 $curgroup = ($webvar{group} ? $webvar{group} : $session->param('curgroup'));
289
290 # I hate special cases.
291##fixme: probably need to handle webvar{revrec}=='y' too
292 if ($webvar{page} eq 'reclist' && $webvar{defrec} eq 'y') {
293 my %args = (page => $webvar{page}, id => $curgroup, defrec => $webvar{defrec}, revrec => $webvar{revrec});
294 $args{errmsg} = $errmsg if $errmsg;
295 changepage(%args);
296 }
297
298 }
299} # handle global webvar{action}s
300
301initPermissions($dbh,$session->param('uid'));
302
303$page->param(sid => $sid) unless $webvar{page} eq 'login'; # no session ID on the login page
304
305if ($webvar{page} eq 'login') {
306
307 $page->param(loginfailed => 1) if $webvar{loginfailed};
308 $page->param(sessexpired => 1) if $webvar{sessexpired};
309# $page->param(orgname => $config{orgname}) if $config{orgname} ne 'Example Corp';
310 $page->param(version => $DNSDB::VERSION);
311
312} elsif ($webvar{page} eq 'domlist' or $webvar{page} eq 'index') {
313
314 $page->param(domlist => 1);
315
316# hmm. seeing problems in some possibly-not-so-corner cases.
317# this currently only handles "domain on", "domain off"
318 if (defined($webvar{domstatus})) {
319 # security check - does the user have permission to access this entity?
320 my $flag = 0;
321 foreach (@viewablegroups) {
322 $flag = 1 if isParent($dbh, $_, 'group', $webvar{id}, 'domain');
323 }
324 if ($flag && ($permissions{admin} || $permissions{domain_edit})) {
325 my $stat = domStatus($dbh,$webvar{id},$webvar{domstatus});
326##fixme switch to more consise "Enabled <domain"/"Disabled <domain>" as with users?
327 logaction($webvar{id}, $session->param("username"),
328 parentID($dbh, (id => $webvar{id}, type => 'domain', revrec => $webvar{revrec})),
329 "Changed ".domainName($dbh, $webvar{id})." state to ".($stat ? 'active' : 'inactive'));
330 $page->param(resultmsg => "Changed ".domainName($dbh, $webvar{id})." state to ".
331 ($stat ? 'active' : 'inactive'));
332 } else {
333 $page->param(errmsg => "You are not permitted to view or change the requested domain");
334 }
335 $uri_self =~ s/\&amp;domstatus=[^&]*//g; # clean up URL for stuffing into templates
336 }
337
338 if ($session->param('resultmsg')) {
339 $page->param(resultmsg => $session->param('resultmsg'));
340 $session->clear('resultmsg');
341 }
342 if ($session->param('errmsg')) {
343 $page->param(errmsg => $session->param('errmsg'));
344 $session->clear('errmsg');
345 }
346
347 $page->param(curpage => $webvar{page});
348
349 listdomains();
350
351} elsif ($webvar{page} eq 'newdomain') {
352
353 changepage(page => "domlist", errmsg => "You are not permitted to add domains")
354 unless ($permissions{admin} || $permissions{domain_create});
355
356 fill_grouplist("grouplist");
357
358 if ($session->param('add_failed')) {
359 $session->clear('add_failed');
360 $page->param(add_failed => 1);
361 $page->param(errmsg => $session->param('errmsg'));
362 $session->clear('errmsg');
363 $page->param(domain => $webvar{domain});
364 }
365
366} elsif ($webvar{page} eq 'adddomain') {
367
368 changepage(page => "domlist", errmsg => "You are not permitted to add domains")
369 unless ($permissions{admin} || $permissions{domain_create});
370
371 # security check - does the user have permission to access this entity?
372 if (!check_scope(id => $webvar{group}, type => 'group')) {
373 $session->param('add_failed', 1);
374##fixme: domain a security risk for XSS?
375 changepage(page => "newdomain", domain => $webvar{domain},
376 errmsg => "You do not have permission to add a domain to the requested group");
377 }
378
379 $webvar{makeactive} = 0 if !defined($webvar{makeactive});
380
381 my ($code,$msg) = addDomain($dbh,$webvar{domain},$webvar{group},($webvar{makeactive} eq 'on' ? 1 : 0),
382 (username => $session->param("username"), id => $session->param("uid")));
383
384 if ($code eq 'OK') {
385 mailNotify($dbh, "New ".($webvar{makeactive} eq 'on' ? 'Active' : 'Inactive')." Domain Created",
386 ($webvar{makeactive} eq 'on' ? 'Active' : 'Inactive').qq( domain "$webvar{domain}" added by ).
387 $session->param("username"));
388 changepage(page => "reclist", id => $msg);
389 } else {
390 logaction(0, $session->param("username"), $webvar{group}, "Failed adding domain $webvar{domain} ($msg)")
391 if $config{log_failures};
392 $session->param('add_failed', 1);
393##fixme: domain a security risk for XSS?
394##fixme: keep active/inactive state, group selection
395 changepage(page => "newdomain", domain => $webvar{domain}, errmsg => $msg);
396 }
397
398} elsif ($webvar{page} eq 'deldom') {
399
400 changepage(page => "domlist", errmsg => "You are not permitted to delete domains")
401 unless ($permissions{admin} || $permissions{domain_delete});
402
403 # security check - does the user have permission to access this entity?
404 if (!check_scope(id => $webvar{id}, type => 'domain')) {
405 changepage(page => "domlist", errmsg => "You do not have permission to delete the requested domain");
406 }
407
408 $page->param(id => $webvar{id});
409
410 # first pass = confirm y/n (sorta)
411 if (!defined($webvar{del})) {
412
413 $page->param(del_getconf => 1);
414 $page->param(domain => domainName($dbh,$webvar{id}));
415
416 } elsif ($webvar{del} eq 'ok') {
417 my $pargroup = parentID($dbh, (id => $webvar{id}, type => 'domain', revrec => $webvar{revrec}));
418 my $dom = domainName($dbh, $webvar{id});
419 my ($code,$msg) = delDomain($dbh, $webvar{id});
420 if ($code eq 'OK') {
421 logaction($webvar{id}, $session->param("username"), $pargroup, "Deleted domain $dom");
422 changepage(page => "domlist", resultmsg => "Deleted domain $dom");
423 } else {
424 logaction($webvar{id}, $session->param("username"), $pargroup, "Failed to delete domain $dom ($msg)")
425 if $config{log_failures};
426 changepage(page => "domlist", errmsg => "Error deleting domain $dom: $msg");
427 }
428
429 } else {
430 # cancelled. whee!
431 changepage(page => "domlist");
432 }
433
434} elsif ($webvar{page} eq 'revzones') {
435
436 $webvar{revrec} = 'y';
437 $page->param(curpage => $webvar{page});
438 listzones();
439
440} elsif ($webvar{page} eq 'newrevzone') {
441
442## scope/access check - use domain settings? invent new (bleh)
443 changepage(page => "revzones", errmsg => "You are not permitted to add reverse zones")
444 unless ($permissions{admin} || $permissions{domain_create});
445
446 fill_grouplist("grouplist");
447
448 if ($webvar{add_failed}) {
449 $page->param(add_failed => 1);
450 $page->param(errmsg => $webvar{errmsg});
451 $page->param(revzone => $webvar{revzone});
452 $page->param(revpatt => $webvar{revpatt});
453 }
454
455} elsif ($webvar{page} eq 'addrevzone') {
456
457 changepage(page => "revzones", errmsg => "You are not permitted to add reverse zones")
458 unless ($permissions{admin} || $permissions{domain_create});
459
460 # security check - does the user have permission to access this entity?
461 if (!check_scope(id => $webvar{group}, type => 'group')) {
462 changepage(page => "newrevzone", add_failed => 1, revzone => $webvar{revzone}, revpatt => $webvar{revpatt},
463 errmsg => "You do not have permission to add a reverse zone to the requested group");
464 }
465
466 my ($code,$msg) = addRDNS($dbh, $webvar{revzone}, $webvar{revpatt}, $webvar{group},
467 ($webvar{makeactive} eq 'on' ? 1 : 0),
468 (username => $session->param("username"), id => $session->param("uid")) );
469
470 if ($code eq 'OK') {
471 logaction(0, $session->param("username"), $webvar{group}, "Added reverse zone $webvar{revzone}", $msg);
472 changepage(page => "reclist", id => $msg, revrec => 'y');
473 } else {
474 logaction(0, $session->param("username"), $webvar{group}, "Failed adding reverse zone $webvar{revzone} ($msg)");
475 changepage(page => "newrevzone", add_failed => 1, revzone => $webvar{revzone}, revpatt => $webvar{revpatt},
476 errmsg => $msg);
477 }
478
479#} elsif ($webvar{page} eq 'delrevzone') {
480
481} elsif ($webvar{page} eq 'reclist') {
482
483 # security check - does the user have permission to view this entity?
484 if (!check_scope(id => $webvar{id}, type =>
485 ($webvar{defrec} eq 'y' ? 'group' : ($webvar{revrec} eq 'y' ? 'revzone' : 'domain')))) {
486 $page->param(errmsg => "You are not permitted to view or change the requested ".
487 ($webvar{defrec} eq 'y' ? "group's default records" :
488 ($webvar{revrec} eq 'y' ? "reverse zone's records" : "domain's records")));
489 $page->param(perm_err => 1); # this causes the template to skip the record listing output.
490 goto DONERECLIST; # and now we skip filling in the content which is not printed due to perm_err above
491 }
492
493# hmm. where do we send them?
494 if ($webvar{defrec} eq 'y' && !$permissions{admin}) {
495 $page->param(errmsg => "You are not permitted to edit default records");
496 $page->param(perm_err => 1);
497 } else {
498
499 $page->param(mayeditsoa => $permissions{admin} || $permissions{domain_edit});
500##fixme: ACL needs pondering. Does "edit domain" interact with record add/remove/etc?
501# Note this seems to be answered "no" in Vega.
502# ACLs
503 $page->param(record_create => ($permissions{admin} || $permissions{record_create}) );
504# we don't have any general edit links on the page; they're all embedded in the TMPL_LOOP
505# $page->param(record_edit => ($permissions{admin} || $permissions{record_edit}) );
506 $page->param(record_delete => ($permissions{admin} || $permissions{record_delete}) );
507
508 # Handle record list for both default records (per-group) and live domain records
509
510 $page->param(defrec => $webvar{defrec});
511 $page->param(revrec => $webvar{revrec});
512 $page->param(id => $webvar{id});
513 $page->param(curpage => $webvar{page});
514
515 my $count = getRecCount($dbh, $webvar{defrec}, $webvar{revrec}, $webvar{id}, $filter);
516
517 $sortby = 'host';
518# sort/order
519 $session->param($webvar{page}.'sortby', $webvar{sortby}) if $webvar{sortby};
520 $session->param($webvar{page}.'order', $webvar{order}) if $webvar{order};
521
522 $sortby = $session->param($webvar{page}.'sortby') if $session->param($webvar{page}.'sortby');
523 $sortorder = $session->param($webvar{page}.'order') if $session->param($webvar{page}.'order');
524
525# set up the headers
526 my @cols;
527 my %colheads;
528 if ($webvar{revrec} eq 'n') {
529 @cols = ('host', 'type', 'val', 'distance', 'weight', 'port', 'ttl');
530 %colheads = (host => 'Name', type => 'Type', val => 'Address',
531 distance => 'Distance', weight => 'Weight', port => 'Port', ttl => 'TTL');
532 } else {
533 @cols = ('host', 'type', 'val', 'ttl');
534 %colheads = (host => 'IP Address', type => 'Type', val => 'Hostname', ttl => 'TTL');
535 }
536 my %custom = (id => $webvar{id}, defrec => $webvar{defrec}, revrec => $webvar{revrec});
537 fill_colheads($sortby, $sortorder, \@cols, \%colheads, \%custom);
538
539# fill the page-count and first-previous-next-last-all details
540 fill_pgcount($count,"records",
541 ($webvar{defrec} eq 'y' ? "group ".groupName($dbh,$webvar{id}) :
542 ($webvar{revrec} eq 'y' ? revName($dbh,$webvar{id}) : domainName($dbh,$webvar{id}))
543 ));
544 fill_fpnla($count); # should put some params on this sub...
545
546 $page->param(defrec => $webvar{defrec});
547 showzone($webvar{defrec}, $webvar{revrec}, $webvar{id});
548 if ($webvar{defrec} eq 'n') {
549# showzone('n',$webvar{id});
550##fixme: permission for viewing logs?
551##fixme: determine which slice of the log we view (group, domain, revzone)
552 if ($webvar{revrec} eq 'n') {
553 $page->param(logdom => 1);
554 } else {
555 $page->param(logrdns => 1);
556 }
557 }
558
559 if ($session->param('resultmsg')) {
560 $page->param(resultmsg => $session->param('resultmsg'));
561 $session->clear('resultmsg');
562 }
563 if ($session->param('warnmsg')) {
564 $page->param(warnmsg => $session->param('warnmsg'));
565 $session->clear('warnmsg');
566 }
567 if ($session->param('errmsg')) {
568 $page->param(errmsg => $session->param('errmsg'));
569 $session->clear('errmsg');
570 }
571
572 } # close "you can't edit default records" check
573
574 # Yes, this is a GOTO target. PTBHTTT.
575 DONERECLIST: ;
576
577} elsif ($webvar{page} eq 'record') {
578
579 # security check - does the user have permission to access this entity?
580 if (!check_scope(id => $webvar{id}, type =>
581 ($webvar{defrec} eq 'y' ? ($webvar{revrec} eq 'y' ? 'defrevrec' : 'defrec') : 'record'))) {
582 $page->param(perm_err => "You are not permitted to edit the requested record");
583 goto DONEREC;
584 }
585 # round 2, check the parent.
586 if (!check_scope(id => $webvar{parentid}, type =>
587 ($webvar{defrec} eq 'y' ? 'group' : ($webvar{revrec} eq 'y' ? 'revzone' : 'domain')))) {
588 my $msg = ($webvar{defrec} eq 'y' ?
589 "You are not permitted to add or edit default records in the requested group" :
590 "You are not permitted to add or edit records in the requested domain/zone");
591 $page->param(perm_err => $msg);
592 goto DONEREC;
593 }
594
595 $page->param(defrec => $webvar{defrec});
596 $page->param(revrec => $webvar{revrec});
597 $page->param(fwdzone => $webvar{revrec} eq 'n');
598
599 if ($webvar{recact} eq 'new') {
600
601 changepage(page => "reclist", errmsg => "You are not permitted to add records", id => $webvar{parentid})
602 unless ($permissions{admin} || $permissions{record_create});
603
604 $page->param(todo => "Add record");
605 $page->param(recact => "add");
606 $page->param(parentid => $webvar{parentid});
607
608 fill_recdata();
609
610 } elsif ($webvar{recact} eq 'add') {
611
612 changepage(page => "reclist", errmsg => "You are not permitted to add records", id => $webvar{parentid})
613 unless ($permissions{admin} || $permissions{record_create});
614
615 my @recargs = ($dbh,$webvar{defrec},$webvar{revrec},$webvar{parentid},
616 \$webvar{name},\$webvar{type},\$webvar{address},$webvar{ttl});
617 if ($webvar{type} == $reverse_typemap{MX} or $webvar{type} == $reverse_typemap{SRV}) {
618 push @recargs, $webvar{distance};
619 if ($webvar{type} == $reverse_typemap{SRV}) {
620 push @recargs, $webvar{weight};
621 push @recargs, $webvar{port};
622 }
623 }
624
625 my ($code,$msg) = addRec(@recargs);
626
627 if ($code eq 'OK' || $code eq 'WARN') {
628 my $restr;
629 if ($webvar{defrec} eq 'y') {
630 $restr = "Added default record '$webvar{name} $typemap{$webvar{type}}";
631 $restr .= " [distance $webvar{distance}]" if $typemap{$webvar{type}} eq 'MX';
632 $restr .= " [priority $webvar{distance}] [weight $webvar{weight}] [port $webvar{port}]"
633 if $typemap{$webvar{type}} eq 'SRV';
634 $restr .= " $webvar{address}', TTL $webvar{ttl}";
635 logaction(0, $session->param("username"), $webvar{parentid}, $restr);
636 } else {
637 $restr = "Added record '$webvar{name} $typemap{$webvar{type}}";
638 $restr .= " [distance $webvar{distance}]" if $typemap{$webvar{type}} eq 'MX';
639 $restr .= " [priority $webvar{distance}] [weight $webvar{weight}] [port $webvar{port}]"
640 if $typemap{$webvar{type}} eq 'SRV';
641 $restr .= " $webvar{address}', TTL $webvar{ttl}";
642 logaction($webvar{parentid}, $session->param("username"),
643 parentID($dbh, (id => $webvar{parentid}, type => 'domain', revrec => $webvar{revrec})), $restr);
644 }
645 my %pageparams = (page => "reclist", id => $webvar{parentid},
646 defrec => $webvar{defrec}, revrec => $webvar{revrec});
647 $pageparams{warnmsg} = $msg."<br><br>\n".$restr if $code eq 'WARN';
648 $pageparams{resultmsg} = $restr if $code eq 'OK';
649 changepage(%pageparams);
650 } else {
651 $page->param(failed => 1);
652 $page->param(errmsg => $msg);
653 $page->param(wastrying => "adding");
654 $page->param(todo => "Add record");
655 $page->param(recact => "add");
656 $page->param(parentid => $webvar{parentid});
657 $page->param(id => $webvar{id});
658 fill_recdata(); # populate the form... er, mostly.
659 if ($config{log_failures}) {
660 if ($webvar{defrec} eq 'y') {
661 logaction(0, $session->param("username"), $webvar{parentid},
662 "Failed adding default record '$webvar{name} $typemap{$webvar{type}} $webvar{address}', TTL $webvar{ttl} ($msg)");
663 } else {
664 logaction($webvar{parentid}, $session->param("username"),
665 parentID($dbh, (id => $webvar{parentid}, type => 'domain', revrec => $webvar{revrec})),
666 "Failed adding record '$webvar{name} $typemap{$webvar{type}} $webvar{address}', TTL $webvar{ttl} ($msg)");
667 }
668 }
669 }
670
671 } elsif ($webvar{recact} eq 'edit') {
672
673 changepage(page => "reclist", errmsg => "You are not permitted to edit records", id => $webvar{parentid})
674 unless ($permissions{admin} || $permissions{record_edit});
675
676 $page->param(todo => "Update record");
677 $page->param(recact => "update");
678 $page->param(parentid => $webvar{parentid});
679 $page->param(id => $webvar{id});
680 my $recdata = getRecLine($dbh, $webvar{defrec}, $webvar{revrec}, $webvar{id});
681 $page->param(name => $recdata->{host});
682 $page->param(address => $recdata->{val});
683 $page->param(distance => $recdata->{distance});
684 $page->param(weight => $recdata->{weight});
685 $page->param(port => $recdata->{port});
686 $page->param(ttl => $recdata->{ttl});
687 $page->param(typelist => getTypelist($dbh, $webvar{revrec}, $webvar{type}));
688
689 } elsif ($webvar{recact} eq 'update') {
690
691 changepage(page => "reclist", errmsg => "You are not permitted to edit records", id => $webvar{parentid})
692 unless ($permissions{admin} || $permissions{record_edit});
693
694 # prevent out-of-domain records from getting added by appending the domain, or DOMAIN for default records
695 my $pname = ($webvar{defrec} eq 'y' ? 'DOMAIN' : domainName($dbh,$webvar{parentid}));
696 $webvar{name} =~ s/\s+$//;
697 $webvar{name} =~ s/\.*$/\.$pname/ if $webvar{name} !~ /$pname$/;
698
699 # get current/previous record info so we can log "updated 'foo A 1.2.3.4' to 'foo A 2.3.4.5'"
700 my $oldrec = getRecLine($dbh, $webvar{defrec}, $webvar{revrec}, $webvar{id});
701
702 my ($code,$msg) = updateRec($dbh,$webvar{defrec},$webvar{id},
703 $webvar{name},$webvar{type},$webvar{address},$webvar{ttl},
704 $webvar{distance},$webvar{weight},$webvar{port});
705
706 if ($code eq 'OK') {
707##fixme: retrieve old record info for full logging of change
708 if ($webvar{defrec} eq 'y') {
709 my $restr = "Updated default record from '$oldrec->{host} $typemap{$oldrec->{type}} $oldrec->{val}', TTL $oldrec->{ttl}\n".
710 "to '$webvar{name} $typemap{$webvar{type}} $webvar{address}', TTL $webvar{ttl}";
711 logaction(0, $session->param("username"), $webvar{parentid}, $restr);
712 changepage(page => "reclist", id => $webvar{parentid}, defrec => $webvar{defrec}, resultmsg => $restr);
713 } else {
714 my $restr = "Updated record from '$oldrec->{host} $typemap{$oldrec->{type}} $oldrec->{val}', TTL $oldrec->{ttl}\n".
715 "to '$webvar{name} $typemap{$webvar{type}} $webvar{address}', TTL $webvar{ttl}";
716 logaction($webvar{parentid}, $session->param("username"),
717 parentID($dbh, (id => $webvar{id}, type => 'record', defrec => $webvar{defrec},
718 revrec => $webvar{revrec}, partype => 'group')),
719 $restr);
720 changepage(page => "reclist", id => $webvar{parentid}, defrec => $webvar{defrec}, resultmsg => $restr);
721 }
722 } else {
723 $page->param(failed => 1);
724 $page->param(errmsg => $msg);
725 $page->param(wastrying => "updating");
726 $page->param(todo => "Update record");
727 $page->param(recact => "update");
728 $page->param(parentid => $webvar{parentid});
729 $page->param(id => $webvar{id});
730 fill_recdata();
731 if ($config{log_failures}) {
732 if ($webvar{defrec} eq 'y') {
733 logaction(0, $session->param("username"), $webvar{parentid},
734 "Failed updating default record '$typemap{$webvar{type}} $webvar{name} $webvar{address}', TTL $webvar{ttl} ($msg)");
735 } else {
736 logaction($webvar{parentid}, $session->param("username"),
737 parentID($dbh, (id => $webvar{parentid}, type => 'domain', revrec => $webvar{revrec})),
738 "Failed updating record '$typemap{$webvar{type}} $webvar{name} $webvar{address}', TTL $webvar{ttl} ($msg)");
739 }
740 }
741 }
742 }
743
744 if ($webvar{defrec} eq 'y') {
745 $page->param(dohere => "default records in group ".groupName($dbh,$webvar{parentid}));
746 } else {
747 $page->param(parentid => $webvar{parentid});
748 $page->param(dohere => domainName($dbh,$webvar{parentid})) if $webvar{revrec} eq 'n';
749 $page->param(dohere => revName($dbh,$webvar{parentid})) if $webvar{revrec} eq 'y';
750 }
751
752 # Yes, this is a GOTO target. PTBHTTT.
753 DONEREC: ;
754
755} elsif ($webvar{page} eq 'delrec') {
756
757 # This is a complete separate segment since it uses a different template from add/edit records above
758
759 changepage(page => "reclist", errmsg => "You are not permitted to delete records", id => $webvar{parentid},
760 defrec => $webvar{defrec}, revrec => $webvar{revrec})
761 unless ($permissions{admin} || $permissions{record_delete});
762
763 if (!check_scope(id => $webvar{id}, type =>
764 ($webvar{defrec} eq 'y' ? ($webvar{revrec} eq 'y' ? 'defrevrec' : 'defrec') : 'record'))) {
765 # redirect to domlist because we don't have permission for the entity requested
766 changepage(page => 'domlist', revrec => $webvar{revrec},
767 errmsg => "You do not have permission to delete records in the requested ".
768 ($webvar{defrec} eq 'y' ? 'group' : 'domain'));
769 }
770
771 $page->param(id => $webvar{id});
772 $page->param(defrec => $webvar{defrec});
773 $page->param(revrec => $webvar{revrec});
774 $page->param(parentid => $webvar{parentid});
775 # first pass = confirm y/n (sorta)
776 if (!defined($webvar{del})) {
777 $page->param(del_getconf => 1);
778 my $rec = getRecLine($dbh, $webvar{defrec}, $webvar{revrec}, $webvar{id});
779 $page->param(host => $rec->{host});
780 $page->param(ftype => $typemap{$rec->{type}});
781 $page->param(recval => $rec->{val});
782 } elsif ($webvar{del} eq 'ok') {
783# get rec data before we try to delete it
784 my $rec = getRecLine($dbh, $webvar{defrec}, $webvar{revrec}, $webvar{id});
785 my ($code,$msg) = delRec($dbh, $webvar{defrec}, $webvar{revrec}, $webvar{id});
786 if ($code eq 'OK') {
787 if ($webvar{defrec} eq 'y') {
788 my $recclass = ($webvar{revrec} eq 'n' ? 'default record' : 'default reverse record');
789##fixme: log distance for MX; log port/weight/distance for SRV
790 my $restr = "Deleted $recclass '$rec->{host} $typemap{$rec->{type}} $rec->{val}', TTL $rec->{ttl}";
791 logaction(0, $session->param("username"), $rec->{parid}, $restr);
792 changepage(page => "reclist", id => $webvar{parentid}, defrec => $webvar{defrec},
793 revrec => $webvar{revrec}, resultmsg => $restr);
794 } else {
795 my $recclass = ($webvar{revrec} eq 'n' ? 'record' : 'reverse record');
796 my $restr = "Deleted $recclass '$rec->{host} $typemap{$rec->{type}} $rec->{val}', TTL $rec->{ttl}";
797 logaction($rec->{parid}, $session->param("username"),
798 parentID($dbh, (id => $rec->{parid}, type => 'domain', revrec => $webvar{revrec})),
799 $restr);
800 changepage(page => "reclist", id => $webvar{parentid}, defrec => $webvar{defrec},
801 revrec => $webvar{revrec}, resultmsg => $restr);
802 }
803 } else {
804## need to find failure mode
805 if ($config{log_failures}) {
806 if ($webvar{defrec} eq 'y') {
807 logaction(0, $session->param("username"), $rec->{parid},
808 "Failed deleting default record '$rec->{host} $typemap{$rec->{type}} $rec->{val}',".
809 " TTL $rec->{ttl} ($msg)");
810 } else {
811 logaction($rec->{parid}, $session->param("username"),
812 parentID($dbh, (id => $rec->{parid}, type => 'domain', revrec => $webvar{revrec})),
813 "Failed deleting record '$rec->{host} $typemap{$rec->{type}} $rec->{val}', TTL $rec->{ttl} ($msg)");
814 }
815 }
816 changepage(page => "reclist", id => $webvar{parentid}, defrec => $webvar{defrec},
817 revrec => $webvar{revrec}, errmsg => "Error deleting record: $msg");
818 }
819 } else {
820 changepage(page => "reclist", id => $webvar{parentid}, defrec => $webvar{defrec}, revrec => $webvar{revrec});
821 }
822
823} elsif ($webvar{page} eq 'editsoa') {
824
825 # security check - does the user have permission to view this entity?
826 # id is domain/revzone/group id
827 if (!check_scope(id => $webvar{id}, type =>
828 ($webvar{defrec} eq 'y' ? 'group' : ($webvar{revrec} eq 'y' ? 'revzone' : 'domain')))) {
829 changepage(page => 'domlist', errmsg => "You do not have permission to edit the ".
830 ($webvar{defrec} eq 'y' ? 'default ' : '')."SOA record for the requested ".
831 ($webvar{defrec} eq 'y' ? 'group' : 'domain'));
832 }
833
834 if ($webvar{defrec} eq 'y') {
835 changepage(page => "domlist", errmsg => "You are not permitted to edit default records")
836 unless $permissions{admin};
837 } else {
838 changepage(page => "reclist", errmsg => "You are not permitted to edit domain SOA records", id => $webvar{id})
839 unless ($permissions{admin} || $permissions{domain_edit});
840 }
841
842 fillsoa($webvar{defrec},$webvar{id});
843
844} elsif ($webvar{page} eq 'updatesoa') {
845
846 # security check - does the user have permission to view this entity?
847 # pass 1, record ID
848 if (!check_scope(id => $webvar{recid}, type =>
849 ($webvar{defrec} eq 'y' ? ($webvar{revrec} eq 'y' ? 'defrevrec' : 'defrec') : 'record'))) {
850 changepage(page => 'domlist', errmsg => "You do not have permission to edit the requested SOA record");
851 }
852 # pass 2, parent (group or domain) ID
853 if (!check_scope(id => $webvar{id}, type =>
854 ($webvar{defrec} eq 'y' ? 'group' : ($webvar{revrec} eq 'y' ? 'revzone' : 'domain')))) {
855 changepage(page => 'domlist', errmsg => "You do not have permission to edit the ".
856 ($webvar{defrec} eq 'y' ? 'default ' : '')."SOA record for the requested ".
857 ($webvar{defrec} eq 'y' ? 'group' : 'domain'));
858 }
859
860 changepage(page => "reclist", errmsg => "You are not permitted to edit domain SOA records", id => $webvar{id})
861 unless ($permissions{admin} || $permissions{domain_edit});
862
863 # get old SOA for log
864 my %soa = getSOA($dbh,$webvar{defrec},$webvar{id});
865
866 my $sth;
867##fixme: push SQL into DNSDB.pm
868##fixme: data validation: make sure {recid} is really the SOA for {id}
869 # no domain ID, so we're editing the default SOA for a group (we don't care which one here)
870 # plus a bit of magic to update the appropriate table
871 my $sql = "UPDATE ".($webvar{defrec} eq 'y' ? "default_records" : "records").
872 " SET host=?, val=?, ttl=? WHERE record_id=?";
873 $sth = $dbh->prepare($sql);
874 $sth->execute("$webvar{contact}:$webvar{prins}",
875 "$webvar{refresh}:$webvar{retry}:$webvar{expire}:$webvar{minttl}",
876 $webvar{ttl},
877 $webvar{recid});
878
879 if ($sth->err) {
880 $page->param(update_failed => 1);
881 $page->param(msg => $DBI::errstr);
882 fillsoa($webvar{defrec},$webvar{id});
883##fixme: faillog
884 } else {
885
886 # do this in the order of "default to most common case"
887 my $loggroup;
888 my $logdomain = $webvar{id};
889 if ($webvar{defrec} eq 'y') {
890 $loggroup = $webvar{id};
891 $logdomain = 0;
892 } else {
893 $loggroup = parentID($dbh, (id => $logdomain, type => 'domain', revrec => $webvar{revrec}));
894 }
895
896 logaction($logdomain, $session->param("username"), $loggroup,
897 "Updated ".($webvar{defrec} eq 'y' ? 'default ' : '')."SOA for ".
898 ($webvar{defrec} eq 'y' ? groupName($dbh, $webvar{id}) : domainName($dbh, $webvar{id}) ).
899 ": (ns $soa{prins}, contact $soa{contact}, refresh $soa{refresh},".
900 " retry $soa{retry}, expire $soa{expire}, minTTL $soa{minttl}, TTL $soa{ttl}) to ".
901 "(ns $webvar{prins}, contact $webvar{contact}, refresh $webvar{refresh},".
902 " retry $webvar{retry}, expire $webvar{expire}, minTTL $webvar{minttl}, TTL $webvar{ttl})");
903 changepage(page => "reclist", id => $webvar{id}, defrec => $webvar{defrec},
904 resultmsg => "SOA record updated");
905 }
906
907} elsif ($webvar{page} eq 'grpman') {
908
909 listgroups();
910
911# Permissions!
912 $page->param(addgrp => $permissions{admin} || $permissions{group_create});
913 $page->param(edgrp => $permissions{admin} || $permissions{group_edit});
914 $page->param(delgrp => $permissions{admin} || $permissions{group_delete});
915
916 if ($session->param('resultmsg')) {
917 $page->param(resultmsg => $session->param('resultmsg'));
918 $session->clear('resultmsg');
919 }
920 if ($session->param('warnmsg')) {
921 $page->param(warnmsg => $session->param('warnmsg'));
922 $session->clear('warnmsg');
923 }
924 if ($session->param('errmsg')) {
925 $page->param(errmsg => $session->param('errmsg'));
926 $session->clear('errmsg');
927 }
928 $page->param(curpage => $webvar{page});
929
930} elsif ($webvar{page} eq 'newgrp') {
931
932 changepage(page => "grpman", errmsg => "You are not permitted to add groups")
933 unless ($permissions{admin} || $permissions{group_create});
934
935 # do.. uhh.. stuff.. if we have no webvar{grpaction}
936 if ($webvar{grpaction} && $webvar{grpaction} eq 'add') {
937
938 # security check - does the user have permission to access this entity?
939 if (!check_scope(id => $webvar{pargroup}, type => 'group')) {
940 changepage(page => "grpman", errmsg => "You are not permitted to add a group to the requested parent group");
941 }
942
943 my %newperms;
944 my $alterperms = 0;
945 foreach (@permtypes) {
946 $newperms{$_} = 0;
947 if ($permissions{admin} || $permissions{$_}) {
948 $newperms{$_} = (defined($webvar{$_}) && $webvar{$_} eq 'on' ? 1 : 0);
949 } else {
950 $alterperms = 1;
951 }
952 }
953 # force inheritance of parent group's default records with inherit flag,
954 # otherwise we end up with the hardcoded defaults from DNSDB.pm. See
955 # https://secure.deepnet.cx/trac/dnsadmin/ticket/8 for the UI enhancement
956 # that will make this variable.
957 my ($code,$msg) = addGroup($dbh, $webvar{newgroup}, $webvar{pargroup}, \%newperms, 1);
958 if ($code eq 'OK') {
959 logaction(0, $session->param("username"), $webvar{pargroup}, "Added group $webvar{newgroup}");
960 if ($alterperms) {
961 changepage(page => "grpman", warnmsg =>
962 "You can only grant permissions you hold. New group $webvar{newgroup} added with reduced access.");
963 } else {
964 changepage(page => "grpman", resultmsg => "Added group $webvar{newgroup}");
965 }
966 } # fallthrough else
967 logaction(0, $session->param("username"), $webvar{pargroup}, "Failed to add group $webvar{newgroup}: $msg")
968 if $config{log_failures};
969 # no point in doing extra work
970 fill_permissions($page, \%newperms);
971 $page->param(add_failed => 1);
972 $page->param(errmsg => $msg);
973 $page->param(newgroup => $webvar{newgroup});
974 fill_grouplist('pargroup',$webvar{pargroup});
975 } else {
976 fill_grouplist('pargroup',$curgroup);
977 # fill default permissions with immediate parent's current ones
978 my %parperms;
979 getPermissions($dbh, 'group', $curgroup, \%parperms);
980 fill_permissions($page, \%parperms);
981 }
982
983} elsif ($webvar{page} eq 'delgrp') {
984
985 changepage(page => "grpman", errmsg => "You are not permitted to delete groups", id => $webvar{parentid})
986 unless ($permissions{admin} || $permissions{group_delete});
987
988 # security check - does the user have permission to access this entity?
989 if (!check_scope(id => $webvar{id}, type => 'group')) {
990 changepage(page => "grpman", errmsg => "You are not permitted to delete the requested group");
991 }
992
993 $page->param(id => $webvar{id});
994 # first pass = confirm y/n (sorta)
995 if (!defined($webvar{del})) {
996 $page->param(del_getconf => 1);
997
998##fixme
999# do a check for "group has stuff in it", and splatter a big warning
1000# up along with an unchecked-by-default check box to YES DAMMIT DELETE THE WHOLE THING
1001
1002 } elsif ($webvar{del} eq 'ok') {
1003 my $deleteme = groupName($dbh,$webvar{id}); # get this before we delete it...
1004 my $delparent = parentID($dbh, (id => $webvar{id}, type => 'group'));
1005 my ($code,$msg) = delGroup($dbh, $webvar{id});
1006 if ($code eq 'OK') {
1007##fixme: need to clean up log when deleting a major container
1008 logaction(0, $session->param("username"), $delparent, "Deleted group $deleteme");
1009 changepage(page => "grpman", resultmsg => "Deleted group $deleteme");
1010 } else {
1011# need to find failure mode
1012 logaction(0, $session->param("username"), $delparent, "Failed to delete group $deleteme: $msg")
1013 if $config{log_failures};
1014 changepage(page => "grpman", errmsg => "Error deleting group $deleteme: $msg");
1015 }
1016 } else {
1017 # cancelled. whee!
1018 changepage(page => "grpman");
1019 }
1020 $page->param(delgroupname => groupName($dbh, $webvar{id}));
1021
1022} elsif ($webvar{page} eq 'edgroup') {
1023
1024 changepage(page => "grpman", errmsg => "You are not permitted to edit groups")
1025 unless ($permissions{admin} || $permissions{group_edit});
1026
1027 # security check - does the user have permission to access this entity?
1028 if (!check_scope(id => $webvar{gid}, type => 'group')) {
1029 changepage(page => "grpman", errmsg => "You are not permitted to edit the requested group");
1030 }
1031
1032 if ($webvar{grpaction} eq 'updperms') {
1033 # extra safety check; make sure user can't construct a URL to bypass ACLs
1034 my %curperms;
1035 getPermissions($dbh, 'group', $webvar{gid}, \%curperms);
1036 my %chperms;
1037 my $alterperms = 0;
1038 foreach (@permtypes) {
1039 $webvar{$_} = 0 if !defined($webvar{$_});
1040 $webvar{$_} = 1 if $webvar{$_} eq 'on';
1041 if ($permissions{admin} || $permissions{$_}) {
1042 $chperms{$_} = $webvar{$_} if $curperms{$_} ne $webvar{$_};
1043 } else {
1044 $alterperms = 1;
1045 $chperms{$_} = 0;
1046 }
1047 }
1048 my ($code,$msg) = changePermissions($dbh, 'group', $webvar{gid}, \%chperms);
1049 if ($code eq 'OK') {
1050 logaction(0, $session->param("username"), $webvar{gid},
1051 "Updated default permissions in group $webvar{gid} (".groupName($dbh, $webvar{gid}).")");
1052 if ($alterperms) {
1053 changepage(page => "grpman", warnmsg =>
1054 "You can only grant permissions you hold. Default permissions in group ".
1055 groupName($dbh, $webvar{gid})." updated with reduced access");
1056 } else {
1057 changepage(page => "grpman", resultmsg =>
1058 "Updated default permissions in group ".groupName($dbh, $webvar{gid}));
1059 }
1060 } # fallthrough else
1061 logaction(0, $session->param("username"), $webvar{gid}, "Failed to update default permissions in group ".
1062 groupName($dbh, $webvar{gid}).": $msg")
1063 if $config{log_failures};
1064 # no point in doing extra work
1065 fill_permissions($page, \%chperms);
1066 $page->param(errmsg => $msg);
1067 }
1068 $page->param(gid => $webvar{gid});
1069 $page->param(grpmeddle => groupName($dbh, $webvar{gid}));
1070 my %grpperms;
1071 getPermissions($dbh, 'group', $webvar{gid}, \%grpperms);
1072 fill_permissions($page, \%grpperms);
1073
1074} elsif ($webvar{page} eq 'bulkdomain') {
1075 # Bulk operations on domains. Note all but group move are available on the domain list.
1076
1077 changepage(page => "domlist", errmsg => "You are not permitted to make bulk domain changes")
1078 unless ($permissions{admin} || $permissions{domain_edit} || $permissions{domain_create} || $permissions{domain_delete});
1079
1080 fill_grouplist("grouplist");
1081
1082##fixme
1083##fixme push the SQL and direct database fiddling off into a sub in DNSDB.pm
1084##fixme
1085
1086 my $sth = $dbh->prepare("SELECT count(*) FROM domains WHERE group_id=?");
1087 $sth->execute($curgroup);
1088 my ($count) = ($sth->fetchrow_array);
1089
1090 $page->param(curpage => $webvar{page});
1091 fill_pgcount($count,'domains',groupName($dbh,$curgroup));
1092 fill_fpnla($count);
1093 $page->param(perpage => $perpage);
1094
1095 my @domlist;
1096 my $sql = "SELECT domain_id,domain FROM domains".
1097 " WHERE group_id=?".
1098 " ORDER BY domain".
1099 ($offset eq 'all' ? '' : " LIMIT $perpage OFFSET ".$offset*$perpage);
1100 $sth = $dbh->prepare($sql);
1101 $sth->execute($curgroup);
1102 my $rownum = 0;
1103 while (my @data = $sth->fetchrow_array) {
1104 my %row;
1105 $row{domid} = $data[0];
1106 $row{domain} = $data[1];
1107 $rownum++; # putting this in the expression below causes failures. *eyeroll*
1108 $row{newrow} = $rownum % 5 == 0;
1109 push @domlist, \%row;
1110 }
1111 $page->param(domtable => \@domlist);
1112 # ACLs
1113 $page->param(maymove => ($permissions{admin} || ($permissions{domain_edit} && $permissions{domain_create} && $permissions{domain_delete})));
1114 $page->param(maystatus => $permissions{admin} || $permissions{domain_edit});
1115 $page->param(maydelete => $permissions{admin} || $permissions{domain_delete});
1116
1117} elsif ($webvar{page} eq 'bulkchange') {
1118
1119 # security check - does the user have permission to access this entity?
1120 if (!check_scope(id => $webvar{destgroup}, type => 'group')) {
1121 $page->param(errmsg => "You are not permitted to make bulk changes in the requested group");
1122 goto DONEBULK;
1123 }
1124
1125 if ($webvar{bulkaction} eq 'move') {
1126 changepage(page => "domlist", errmsg => "You are not permitted to bulk-move domains")
1127 unless ($permissions{admin} || ($permissions{domain_edit} && $permissions{domain_create} && $permissions{domain_delete}));
1128 my $newgname = groupName($dbh,$webvar{destgroup});
1129 $page->param(action => "Move to group $newgname");
1130 my @bulkresults;
1131 # nngh. due to alpha-sorting on the previous page, we can't use domid-numeric
1132 # order here, and since we don't have the domain names until we go around this
1133 # loop, we can't alpha-sort them here. :(
1134 foreach (keys %webvar) {
1135 my %row;
1136 next unless $_ =~ /^dom_\d+$/;
1137 # second security check - does the user have permission to meddle with this domain?
1138 if (!check_scope(id => $webvar{$_}, type => 'domain')) {
1139 $row{domerr} = "You are not permitted to make changes to the requested domain";
1140 $row{domain} = $webvar{$_};
1141 push @bulkresults, \%row;
1142 next;
1143 }
1144 $row{domain} = domainName($dbh,$webvar{$_});
1145 my ($code, $msg) = changeGroup($dbh, 'domain', $webvar{$_}, $webvar{destgroup});
1146 if ($code eq 'OK') {
1147 logaction($webvar{$_}, $session->param("username"),
1148 parentID($dbh, (id => $webvar{$_}, type => 'domain', revrec => $webvar{revrec})),
1149 "Moved domain ".domainName($dbh, $webvar{$_})." to group $newgname");
1150 $row{domok} = ($code eq 'OK');
1151 } else {
1152 logaction($webvar{$_}, $session->param("username"),
1153 parentID($dbh, (id => $webvar{$_}, type => 'domain', revrec => $webvar{revrec})),
1154 "Failed to move domain ".domainName($dbh, $webvar{$_})." to group $newgname: $msg")
1155 if $config{log_failures};
1156 }
1157 $row{domerr} = $msg;
1158 push @bulkresults, \%row;
1159 }
1160 $page->param(bulkresults => \@bulkresults);
1161
1162 } elsif ($webvar{bulkaction} eq 'deactivate' || $webvar{bulkaction} eq 'activate') {
1163 changepage(page => "domlist", errmsg => "You are not permitted to bulk-$webvar{bulkaction} domains")
1164 unless ($permissions{admin} || $permissions{domain_edit});
1165 $page->param(action => "$webvar{bulkaction} domains");
1166 my @bulkresults;
1167 foreach (keys %webvar) {
1168 my %row;
1169 next unless $_ =~ /^dom_\d+$/;
1170 # second security check - does the user have permission to meddle with this domain?
1171 if (!check_scope(id => $webvar{$_}, type => 'domain')) {
1172 $row{domerr} = "You are not permitted to make changes to the requested domain";
1173 $row{domain} = $webvar{$_};
1174 push @bulkresults, \%row;
1175 next;
1176 }
1177 $row{domain} = domainName($dbh,$webvar{$_});
1178##fixme: error handling on status change
1179 my $stat = domStatus($dbh,$webvar{$_},($webvar{bulkaction} eq 'activate' ? 'domon' : 'domoff'));
1180 logaction($webvar{$_}, $session->param("username"),
1181 parentID($dbh, (id => $webvar{$_}, type => 'domain', revrec => $webvar{revrec})),
1182 "Changed domain ".domainName($dbh, $webvar{$_})." state to ".($stat ? 'active' : 'inactive'));
1183 $row{domok} = 1;
1184# $row{domok} = ($code eq 'OK');
1185# $row{domerr} = $msg;
1186 push @bulkresults, \%row;
1187 }
1188 $page->param(bulkresults => \@bulkresults);
1189
1190 } elsif ($webvar{bulkaction} eq 'delete') {
1191 changepage(page => "domlist", errmsg => "You are not permitted to bulk-delete domains")
1192 unless ($permissions{admin} || $permissions{domain_delete});
1193 $page->param(action => "$webvar{bulkaction} domains");
1194 my @bulkresults;
1195 foreach (keys %webvar) {
1196 my %row;
1197 next unless $_ =~ /^dom_\d+$/;
1198 # second security check - does the user have permission to meddle with this domain?
1199 if (!check_scope(id => $webvar{$_}, type => 'domain')) {
1200 $row{domerr} = "You are not permitted to make changes to the requested domain";
1201 $row{domain} = $webvar{$_};
1202 push @bulkresults, \%row;
1203 next;
1204 }
1205 $row{domain} = domainName($dbh,$webvar{$_});
1206 my $pargroup = parentID($dbh, (id => $webvar{$_}, type => 'domain', revrec => $webvar{revrec}));
1207 my $dom = domainName($dbh, $webvar{$_});
1208 my ($code, $msg) = delDomain($dbh, $webvar{$_});
1209 if ($code eq 'OK') {
1210 logaction($webvar{$_}, $session->param("username"), $pargroup, "Deleted domain $dom");
1211 $row{domok} = ($code eq 'OK');
1212 } else {
1213 logaction($webvar{$_}, $session->param("username"), $pargroup, "Failed to delete domain $dom: $msg")
1214 if $config{log_failures};
1215 }
1216 $row{domerr} = $msg;
1217 push @bulkresults, \%row;
1218 }
1219 $page->param(bulkresults => \@bulkresults);
1220
1221 } # move/(de)activate/delete if()
1222
1223 # not going to handle the unknown $webvar{action} else; it should not be possible in normal
1224 # operations, and anyone who meddles with the URL gets what they deserve.
1225
1226 # Yes, this is a GOTO target. PTHBTTT.
1227 DONEBULK: ;
1228
1229} elsif ($webvar{page} eq 'useradmin') {
1230
1231 if (defined($webvar{userstatus})) {
1232 # security check - does the user have permission to access this entity?
1233 my $flag = 0;
1234 foreach (@viewablegroups) {
1235 $flag = 1 if isParent($dbh, $_, 'group', $webvar{id}, 'user');
1236 }
1237 if ($flag && ($permissions{admin} || $permissions{user_edit})) {
1238 my $stat = userStatus($dbh,$webvar{id},$webvar{userstatus});
1239 logaction(0, $session->param("username"), parentID($dbh, (id => $webvar{id}, type => 'user')),
1240 ($stat ? 'Enabled' : 'Disabled')." ".userFullName($dbh, $webvar{id}, '%u'));
1241 $page->param(resultmsg => ($stat ? 'Enabled' : 'Disabled')." ".userFullName($dbh, $webvar{id}, '%u'));
1242 } else {
1243 $page->param(errmsg => "You are not permitted to view or change the requested user");
1244 }
1245 $uri_self =~ s/\&amp;userstatus=[^&]*//g; # clean up URL for stuffing into templates
1246 }
1247
1248 list_users();
1249
1250# Permissions!
1251 $page->param(adduser => $permissions{admin} || $permissions{user_create});
1252# should we block viewing other users? Vega blocks "editing"...
1253# NB: no "edit self" link as with groups here. maybe there should be?
1254# $page->param(eduser => $permissions{admin} || $permissions{user_edit});
1255 $page->param(deluser => $permissions{admin} || $permissions{user_delete});
1256
1257 if ($session->param('resultmsg')) {
1258 $page->param(resultmsg => $session->param('resultmsg'));
1259 $session->clear('resultmsg');
1260 }
1261 if ($session->param('warnmsg')) {
1262 $page->param(warnmsg => $session->param('warnmsg'));
1263 $session->clear('warnmsg');
1264 }
1265 if ($session->param('errmsg')) {
1266 $page->param(errmsg => $session->param('errmsg'));
1267 $session->clear('errmsg');
1268 }
1269 $page->param(curpage => $webvar{page});
1270
1271} elsif ($webvar{page} eq 'user') {
1272
1273 # All user add/edit actions fall through the same page, since there aren't
1274 # really any hard differences between the templates
1275
1276 #fill_actypelist($webvar{accttype});
1277 fill_clonemelist();
1278 my %grpperms;
1279 getPermissions($dbh, 'group', $curgroup, \%grpperms);
1280
1281 my $grppermlist = new HTML::Template(filename => "$templatedir/permlist.tmpl");
1282 my %noaccess;
1283 fill_permissions($grppermlist, \%grpperms, \%noaccess);
1284 $grppermlist->param(info => 1);
1285 $page->param(grpperms => $grppermlist->output);
1286
1287 $page->param(is_admin => $permissions{admin});
1288
1289 $webvar{useraction} = '' if !$webvar{useraction};
1290
1291 if ($webvar{useraction} eq 'add' or $webvar{useraction} eq 'update') {
1292
1293 $page->param(add => 1) if $webvar{useraction} eq 'add';
1294
1295 my ($code,$msg);
1296
1297 my $alterperms = 0; # flag iff we need to force custom permissions due to user's current access limits
1298
1299 my %newperms; # we're going to prefill the existing permissions, so we can change them.
1300 getPermissions($dbh, 'user', $webvar{uid}, \%newperms);
1301
1302 if ($webvar{pass1} ne $webvar{pass2}) {
1303 $code = 'FAIL';
1304 $msg = "Passwords don't match";
1305 } else {
1306
1307 # assemble a permission string - far simpler than trying to pass an
1308 # indeterminate set of permission flags individually
1309
1310 # But first, we have to see if the user can add any particular
1311 # permissions; otherwise we have a priviledge escalation. Whee.
1312
1313 if (!$permissions{admin}) {
1314 my %grpperms;
1315 getPermissions($dbh, 'group', $curgroup, \%grpperms);
1316 my $ret = comparePermissions(\%permissions, \%grpperms);
1317 if ($ret eq '<' || $ret eq '!') {
1318 # User's permissions are not a superset or equivalent to group. Can't inherit
1319 # (and include access user doesn't currently have), so we force custom.
1320 $webvar{perms_type} = 'custom';
1321 $alterperms = 1;
1322 }
1323 }
1324
1325 my $permstring;
1326 if ($webvar{perms_type} eq 'custom') {
1327 $permstring = 'C:';
1328 foreach (@permtypes) {
1329 if ($permissions{admin} || $permissions{$_}) {
1330 $permstring .= ",$_" if defined($webvar{$_}) && $webvar{$_} eq 'on';
1331 $newperms{$_} = (defined($webvar{$_}) && $webvar{$_} eq 'on' ? 1 : 0);
1332 }
1333 }
1334 $page->param(perm_custom => 1);
1335 } elsif ($permissions{admin} && $webvar{perms_type} eq 'clone') {
1336 $permstring = "c:$webvar{clonesrc}";
1337 getPermissions($dbh, 'user', $webvar{clonesrc}, \%newperms);
1338 $page->param(perm_clone => 1);
1339 } else {
1340 $permstring = 'i';
1341 }
1342 if ($webvar{useraction} eq 'add') {
1343 changepage(page => "useradmin", errmsg => "You do not have permission to add new users")
1344 unless $permissions{admin} || $permissions{user_create};
1345 # no scope check; user is created in the current group
1346 ($code,$msg) = addUser($dbh, $webvar{uname}, $curgroup, $webvar{pass1},
1347 ($webvar{makeactive} eq 'on' ? 1 : 0), $webvar{accttype}, $permstring,
1348 $webvar{fname}, $webvar{lname}, $webvar{phone});
1349 logaction(0, $session->param("username"), $curgroup, "Added user $webvar{uname} (uid $msg)")
1350 if $code eq 'OK';
1351 } else {
1352 changepage(page => "useradmin", errmsg => "You do not have permission to edit users")
1353 unless $permissions{admin} || $permissions{user_edit};
1354 # security check - does the user have permission to access this entity?
1355 if (!check_scope(id => $webvar{user}, type => 'user')) {
1356 changepage(page => "useradmin", errmsg => "You do not have permission to edit the requested user");
1357 }
1358# User update is icky. I'd really like to do this in one atomic
1359# operation, but that would duplicate a **lot** of code in DNSDB.pm
1360 # Allowing for changing group, but not coding web support just yet.
1361 ($code,$msg) = updateUser($dbh, $webvar{uid}, $webvar{uname}, $webvar{gid}, $webvar{pass1},
1362 ($webvar{makeactive} eq 'on' ? 1 : 0), $webvar{accttype},
1363 $webvar{fname}, $webvar{lname}, $webvar{phone});
1364 if ($code eq 'OK') {
1365 $newperms{admin} = 1 if $webvar{accttype} eq 'S';
1366 ($code,$msg) = changePermissions($dbh, 'user', $webvar{uid}, \%newperms, ($permstring eq 'i'));
1367 logaction(0, $session->param("username"), $curgroup,
1368 "Updated uid $webvar{uid}, user $webvar{uname} ($webvar{fname} $webvar{lname})");
1369 }
1370 }
1371 }
1372
1373 if ($code eq 'OK') {
1374
1375 if ($alterperms) {
1376 changepage(page => "useradmin", warnmsg =>
1377 "You can only grant permissions you hold. $webvar{uname} ".
1378 ($webvar{useraction} eq 'add' ? 'added' : 'updated')." with reduced access.");
1379 } else {
1380 changepage(page => "useradmin", resultmsg => "Successfully ".
1381 ($webvar{useraction} eq 'add' ? 'added' : 'updated')." user $webvar{uname}");
1382 }
1383
1384 # add/update failed:
1385 } else {
1386 $page->param(add_failed => 1);
1387 $page->param(action => $webvar{useraction});
1388 $page->param(set_permgroup => 1);
1389 if ($webvar{perms_type} eq 'inherit') { # set permission class radio
1390 $page->param(perm_inherit => 1);
1391 } elsif ($webvar{perms_type} eq 'clone') {
1392 $page->param(perm_clone => 1);
1393 } else {
1394 $page->param(perm_custom => 1);
1395 }
1396 $page->param(uname => $webvar{uname});
1397 $page->param(fname => $webvar{fname});
1398 $page->param(lname => $webvar{lname});
1399 $page->param(pass1 => $webvar{pass1});
1400 $page->param(pass2 => $webvar{pass2});
1401 $page->param(errmsg => $msg);
1402 fill_permissions($page, \%newperms);
1403 fill_actypelist($webvar{accttype});
1404 fill_clonemelist();
1405 logaction(0, $session->param("username"), $curgroup, "Failed to $webvar{useraction} user ".
1406 "$webvar{uname}: $msg")
1407 if $config{log_failures};
1408 }
1409
1410 } elsif ($webvar{useraction} eq 'edit') {
1411
1412 changepage(page => "useradmin", errmsg => "You do not have permission to edit users")
1413 unless $permissions{admin} || $permissions{user_edit};
1414
1415 # security check - does the user have permission to access this entity?
1416 if (!check_scope(id => $webvar{user}, type => 'user')) {
1417 changepage(page => "useradmin", errmsg => "You do not have permission to edit the requested user");
1418 }
1419
1420 $page->param(set_permgroup => 1);
1421 $page->param(action => 'update');
1422 $page->param(uid => $webvar{user});
1423 fill_clonemelist();
1424
1425 my $userinfo = getUserData($dbh,$webvar{user});
1426 fill_actypelist($userinfo->{type});
1427 # not using this yet, but adding it now means we can *much* more easily do so later.
1428 $page->param(gid => $webvar{group_id});
1429
1430 my %curperms;
1431 getPermissions($dbh, 'user', $webvar{user}, \%curperms);
1432 fill_permissions($page, \%curperms);
1433
1434 $page->param(uname => $userinfo->{username});
1435 $page->param(fname => $userinfo->{firstname});
1436 $page->param(lname => $userinfo->{lastname});
1437 $page->param(set_permgroup => 1);
1438 if ($userinfo->{inherit_perm}) {
1439 $page->param(perm_inherit => 1);
1440 } else {
1441 $page->param(perm_custom => 1);
1442 }
1443 } else {
1444 changepage(page => "useradmin", errmsg => "You are not allowed to add new users")
1445 unless $permissions{admin} || $permissions{user_create};
1446 # default is "new"
1447 $page->param(add => 1);
1448 $page->param(action => 'add');
1449 fill_permissions($page, \%grpperms);
1450 fill_actypelist();
1451 }
1452
1453} elsif ($webvar{page} eq 'deluser') {
1454
1455 changepage(page=> "useradmin", errmsg => "You are not allowed to delete users")
1456 unless $permissions{admin} || $permissions{user_delete};
1457
1458 # security check - does the user have permission to access this entity?
1459 if (!check_scope(id => $webvar{id}, type => 'user')) {
1460 changepage(page => "useradmin", errmsg => "You are not permitted to delete the requested user");
1461 }
1462
1463 $page->param(id => $webvar{id});
1464 # first pass = confirm y/n (sorta)
1465 if (!defined($webvar{del})) {
1466 $page->param(del_getconf => 1);
1467 $page->param(user => userFullName($dbh,$webvar{id}));
1468 } elsif ($webvar{del} eq 'ok') {
1469##fixme: find group id user is in (for logging) *before* we delete the user
1470##fixme: get other user data too for log
1471 my $userref = getUserData($dbh, $webvar{id});
1472 my ($code,$msg) = delUser($dbh, $webvar{id});
1473 if ($code eq 'OK') {
1474 # success. go back to the user list, do not pass "GO"
1475 # actions on users have a domain id of 0, always
1476 logaction(0, $session->param("username"), $curgroup, "Deleted user $webvar{id}/".$userref->{username}.
1477 " (".$userref->{lastname}.", ".$userref->{firstname}.")");
1478 changepage(page => "useradmin", resultmsg => "Deleted user ".$userref->{username}.
1479 " (".$userref->{lastname}.", ".$userref->{firstname}.")");
1480 } else {
1481# need to find failure mode
1482 $page->param(del_failed => 1);
1483 $page->param(errmsg => $msg);
1484 list_users($curgroup);
1485 logaction(0, $session->param("username"), $curgroup, "Failed to delete user ".
1486 "$webvar{id}/".$userref->{username}.": $msg")
1487 if $config{log_failures};
1488 }
1489 } else {
1490 # cancelled. whee!
1491 changepage(page => "useradmin");
1492 }
1493
1494} elsif ($webvar{page} eq 'dnsq') {
1495
1496 $page->param(qfor => $webvar{qfor}) if $webvar{qfor};
1497 $page->param(typelist => getTypelist($dbh, 'l', ($webvar{type} ? $webvar{type} : undef)));
1498 $page->param(nrecurse => $webvar{nrecurse}) if $webvar{nrecurse};
1499 $page->param(resolver => $webvar{resolver}) if $webvar{resolver};
1500
1501 if ($webvar{qfor}) {
1502 my $resolv = Net::DNS::Resolver->new;
1503 $resolv->tcp_timeout(5); # make me adjustable!
1504 $resolv->udp_timeout(5); # make me adjustable!
1505 $resolv->recurse(0) if $webvar{nrecurse};
1506 $resolv->nameservers($webvar{resolver}) if $webvar{resolver};
1507 my $query = $resolv->query($webvar{qfor}, $typemap{$webvar{type}});
1508 if ($query) {
1509
1510 $page->param(showresults => 1);
1511
1512 my @answer;
1513 foreach my $rr ($query->answer) {
1514# next unless $rr->type eq "A" or $rr->type eq 'NS';
1515 my %row;
1516 my ($host,$ttl,$class,$type,$data) =
1517 ($rr->string =~ /^([0-9a-zA-Z_.-]+)\s+(\d+)\s+([A-Za-z]+)\s+([A-Za-z]+)\s+(.+)$/s);
1518 $row{host} = $host;
1519 $row{ftype} = $type;
1520 $row{rdata} = ($type eq 'SOA' ? "<pre>$data</pre>" : $data);
1521 push @answer, \%row;
1522 }
1523 $page->param(answer => \@answer);
1524
1525 my @additional;
1526 foreach my $rr ($query->additional) {
1527# next unless $rr->type eq "A" or $rr->type eq 'NS';
1528 my %row;
1529 my ($host,$ttl,$class,$type,$data) =
1530 ($rr->string =~ /^([0-9a-zA-Z_.-]+)\s+(\d+)\s+([A-Za-z]+)\s+([A-Za-z]+)\s+(.+)$/);
1531 $row{host} = $host;
1532 $row{ftype} = $type;
1533 $row{rdata} = $data;
1534 push @additional, \%row;
1535 }
1536 $page->param(additional => \@additional);
1537
1538 my @authority;
1539 foreach my $rr ($query->authority) {
1540# next unless $rr->type eq "A" or $rr->type eq 'NS';
1541 my %row;
1542 my ($host,$ttl,$class,$type,$data) =
1543 ($rr->string =~ /^([0-9a-zA-Z_.-]+)\s+(\d+)\s+([A-Za-z]+)\s+([A-Za-z]+)\s+(.+)$/);
1544 $row{host} = $host;
1545 $row{ftype} = $type;
1546 $row{rdata} = $data;
1547 push @authority, \%row;
1548 }
1549 $page->param(authority => \@authority);
1550
1551 $page->param(usedresolver => $resolv->answerfrom);
1552 $page->param(frtype => $typemap{$webvar{type}});
1553
1554 } else {
1555 $page->param(errmsg => $resolv->errorstring);
1556 }
1557 }
1558 ## done DNS query
1559
1560} elsif ($webvar{page} eq 'axfr') {
1561
1562 changepage(page => "domlist", errmsg => "You are not permitted to import domains")
1563 unless ($permissions{admin} || $permissions{domain_create});
1564
1565 # don't need this while we've got the dropdown in the menu. hmm.
1566 fill_grouplist("grouplist");
1567
1568 $page->param(ifrom => $webvar{ifrom}) if $webvar{ifrom};
1569 $page->param(rwsoa => $webvar{rwsoa}) if $webvar{rwsoa};
1570 $page->param(rwns => $webvar{rwns}) if $webvar{rwns};
1571 $page->param(forcettl => $webvar{forcettl}) if $webvar{forcettl};
1572 $page->param(newttl => $webvar{newttl}) if $webvar{newttl};
1573 $page->param(dominactive => 1) if (!$webvar{domactive} && $webvar{doit}); # eww.
1574 $page->param(importdoms => $webvar{importdoms}) if $webvar{importdoms};
1575
1576 # shut up warning about uninitialized variable
1577 $webvar{doit} = '' if !defined($webvar{doit});
1578
1579 if ($webvar{doit} eq 'y' && !$webvar{ifrom}) {
1580 $page->param(errmsg => "Need to set host to import from");
1581 } elsif ($webvar{doit} eq 'y' && !$webvar{importdoms}) {
1582 $page->param(errmsg => "Need domains to import");
1583 } elsif ($webvar{doit} eq 'y') {
1584
1585 # security check - does the user have permission to access this entity?
1586 if (!check_scope(id => $webvar{group}, type => 'group')) {
1587 $page->param(errmsg => "You are not permitted to import domains into the requested group");
1588 goto DONEAXFR;
1589 }
1590
1591 my @domlist = split /\s+/, $webvar{importdoms};
1592 my @results;
1593 foreach my $domain (@domlist) {
1594 my %row;
1595 my ($code,$msg) = importAXFR($dbh, $webvar{ifrom}, $domain, $webvar{group},
1596 $webvar{domstatus}, $webvar{rwsoa}, $webvar{rwns}, ($webvar{forcettl} ? $webvar{newttl} : 0) );
1597 $row{domok} = $msg if $code eq 'OK';
1598 if ($code eq 'WARN') {
1599 $msg =~ s|\n|<br />|g;
1600 $row{domwarn} = $msg;
1601 }
1602 if ($code eq 'FAIL') {
1603 $msg =~ s|\n|<br />\n|g;
1604 $row{domerr} = $msg;
1605 }
1606 $msg = "<br />\n".$msg if $msg =~ m|<br />|;
1607 logaction(domainID($dbh, $domain), $session->param("username"), $webvar{group},
1608 "AXFR import $domain from $webvar{ifrom} ($code): $msg");
1609 $row{domain} = $domain;
1610 push @results, \%row;
1611 }
1612 $page->param(axfrresults => \@results);
1613 }
1614
1615 # Yes, this is a GOTO target. PTBHTTT.
1616 DONEAXFR: ;
1617
1618} elsif ($webvar{page} eq 'whoisq') {
1619
1620 if ($webvar{qfor}) {
1621 use Net::Whois::Raw;
1622 use Text::Wrap;
1623
1624# caching useful?
1625#$Net::Whois::Raw::CACHE_DIR = "/var/spool/pwhois/";
1626#$Net::Whois::Raw::CACHE_TIME = 60;
1627
1628 my ($dominfo, $whois_server) = whois($webvar{qfor});
1629##fixme: if we're given an IP, try rwhois as well as whois so we get the real final data
1630
1631 # le sigh. idjits spit out data without linefeeds...
1632 $Text::Wrap::columns = 88;
1633
1634# &%$@%@# high-bit crap. We should probably find a way to properly recode these
1635# instead of one-by-one. Note CGI::Simple's escapeHTML() doesn't do more than
1636# the bare minimum. :/
1637# Mainly an XHTML validation thing.
1638 $dominfo = $q->escapeHTML($dominfo);
1639 $dominfo =~ s/\xa9/\&copy;/g;
1640 $dominfo =~ s/\xae/\&reg;/g;
1641
1642 $page->param(qfor => $webvar{qfor});
1643 $page->param(dominfo => wrap('','',$dominfo));
1644 $page->param(whois_server => $whois_server);
1645 } else {
1646 $page->param(errmsg => "Missing host or domain to query in WHOIS") if $webvar{askaway};
1647 }
1648
1649} elsif ($webvar{page} eq 'log') {
1650
1651##fixme put in some real log-munching stuff
1652 my $sql = "SELECT user_id, email, name, entry, date_trunc('second',stamp) FROM log WHERE ";
1653 my $id = $curgroup; # we do this because the group log may be called from (almost) any page,
1654 # but the others are much more limited. this is probably non-optimal.
1655
1656 if ($webvar{ltype} && $webvar{ltype} eq 'user') {
1657 $sql .= "user_id=?";
1658 $id = $webvar{id};
1659 if (!check_scope(id => $id, type => 'user')) {
1660 $page->param(errmsg => "You are not permitted to view log entries for the requested user");
1661 goto DONELOG;
1662 }
1663 $page->param(logfor => 'user '.userFullName($dbh,$id));
1664 } elsif ($webvar{ltype} && $webvar{ltype} eq 'dom') {
1665 $sql .= "domain_id=?";
1666 $id = $webvar{id};
1667 if (!check_scope(id => $id, type => 'domain')) {
1668 $page->param(errmsg => "You are not permitted to view log entries for the requested domain");
1669 goto DONELOG;
1670 }
1671 $page->param(logfor => 'domain '.domainName($dbh,$id));
1672 } elsif ($webvar{ltype} && $webvar{ltype} eq 'rdns') {
1673 $sql .= "rdns_id=?";
1674 $id = $webvar{id};
1675 if (!check_scope(id => $id, type => 'revzone')) {
1676 $page->param(errmsg => "You are not permitted to view log entries for the requested reverse zone");
1677 goto DONELOG;
1678 }
1679 $page->param(logfor => 'reverse zone '.revName($dbh,$id));
1680 } else {
1681 # Default to listing curgroup log
1682 $sql .= "group_id=?";
1683 $page->param(logfor => 'group '.groupName($dbh,$id));
1684 # note that scope limitations are applied via the change-group check;
1685 # group log is always for the "current" group
1686 }
1687##fixme:
1688# - filtering
1689# - show reverse zone column?
1690# - pagination/limiting number of records - put newest-first so user
1691# doesn't always need to go to the last page for recent activity?
1692 my $sth = $dbh->prepare($sql);
1693 $sth->execute($id);
1694 my @logbits;
1695 while (my ($uid, $email, $name, $entry, $stamp) = $sth->fetchrow_array) {
1696 my %row;
1697 $row{userfname} = $name;
1698 $row{userid} = $uid;
1699 $row{useremail} = $email;
1700 $row{logentry} = $entry;
1701 ($row{logtime}) = ($stamp =~ /^(.+)-\d\d$/);
1702 push @logbits, \%row;
1703 }
1704 $page->param(logentries => \@logbits);
1705
1706 # scope check fail target
1707 DONELOG: ;
1708
1709} # end $webvar{page} dance
1710
1711
1712# start output here so we can redirect pages.
1713print "Content-type: text/html\n\n", $header->output;
1714
1715##common bits
1716if ($webvar{page} ne 'login' && $webvar{page} ne 'badpage') {
1717 $page->param(username => $session->param("username"));
1718
1719 $page->param(group => $curgroup);
1720 $page->param(groupname => groupName($dbh,$curgroup));
1721 $page->param(logingrp => groupName($dbh,$logingroup));
1722 $page->param(logingrp_num => $logingroup);
1723
1724##fixme
1725 $page->param(mayrdns => 1);
1726
1727 $page->param(maydefrec => $permissions{admin});
1728 $page->param(mayimport => $permissions{admin} || $permissions{domain_create});
1729 $page->param(maybulk => $permissions{admin} || $permissions{domain_edit} || $permissions{domain_create} || $permissions{domain_delete});
1730
1731 $page->param(chggrps => ($permissions{admin} || $permissions{group_create} || $permissions{group_edit} || $permissions{group_delete}));
1732
1733 # group tree. should go elsewhere, probably
1734 my $tmpgrplist = fill_grptree($logingroup,$curgroup);
1735 $page->param(grptree => $tmpgrplist);
1736 $page->param(subs => ($tmpgrplist ? 1 : 0)); # probably not useful to pass gobs of data in for a boolean
1737 $page->param(inlogingrp => $curgroup == $logingroup);
1738
1739# fill in the URL-to-self
1740 $page->param(whereami => $uri_self);
1741}
1742
1743if (@debugbits) {
1744 print "<pre>\n";
1745 foreach (@debugbits) { print; }
1746 print "</pre>\n";
1747}
1748
1749# spit it out
1750print $page->output;
1751
1752if ($debugenv) {
1753 print "<div id=\"debug\">webvar keys: <pre>\n";
1754 foreach my $key (keys %webvar) {
1755 print "key: $key\tval: $webvar{$key}\n";
1756 }
1757 print "</pre>\nsession:\n<pre>\n";
1758 my $sesdata = $session->dataref();
1759 foreach my $key (keys %$sesdata) {
1760 print "key: $key\tval: ".$sesdata->{$key}."\n";
1761 }
1762 print "</pre>\nENV:\n<pre>\n";
1763 foreach my $key (keys %ENV) {
1764 print "key: $key\tval: $ENV{$key}\n";
1765 }
1766 print "</pre></div>\n";
1767}
1768
1769print $footer->output;
1770
1771# as per the docs, Just In Case
1772$session->flush();
1773
1774exit 0;
1775
1776
1777sub fill_grptree {
1778 my $root = shift;
1779 my $cur = shift;
1780 my $indent = shift || ' ';
1781
1782 my @childlist;
1783
1784 my $grptree = HTML::Template->new(filename => 'templates/grptree.tmpl');
1785 getChildren($dbh,$root,\@childlist,'immediate');
1786 return if $#childlist == -1;
1787 my @grouplist;
1788 foreach (@childlist) {
1789 my %row;
1790 $row{grpname} = groupName($dbh,$_);
1791 $row{grpnum} = $_;
1792 $row{whereami} = $uri_self;
1793 $row{curgrp} = ($_ == $cur);
1794 $row{expanded} = isParent($dbh, $_, 'group', $cur, 'group');
1795 $row{expanded} = 1 if $_ == $cur;
1796 $row{subs} = fill_grptree($_,$cur,$indent.' ');
1797 $row{indent} = $indent;
1798 push @grouplist, \%row;
1799 }
1800 $grptree->param(indent => $indent);
1801 $grptree->param(treelvl => \@grouplist);
1802 return $grptree->output;
1803}
1804
1805sub changepage {
1806 my %params = @_; # think this works the way I want...
1807
1808 # cross-site scripting fixup. instead of passing error messages by URL/form
1809 # variable, put them in the session where the nasty user can't meddle.
1810 # these are done here since it's far simpler to pass them in from wherever
1811 # than set them locally everywhere.
1812 foreach my $sessme ('resultmsg','warnmsg','errmsg') {
1813 if ($params{$sessme}) {
1814 $session->param($sessme, $params{$sessme});
1815 delete $params{$sessme};
1816 }
1817 }
1818
1819 # handle user check
1820 my $newurl = "http://$ENV{HTTP_HOST}$ENV{SCRIPT_NAME}?sid=$sid";
1821 foreach (sort keys %params) {
1822 $newurl .= "&$_=".$q->url_encode($params{$_});
1823 }
1824
1825 # Just In Case
1826 $session->flush();
1827
1828 print "Status: 302\nLocation: $newurl\n\n";
1829 exit;
1830} # end changepage
1831
1832sub fillsoa {
1833 my $def = shift;
1834 my $id = shift;
1835 my $domname = ($def eq 'y' ? '' : "DOMAIN");
1836
1837 $page->param(defrec => $def);
1838
1839# i had a good reason to do this when I wrote it...
1840# $page->param(domain => $domname);
1841# $page->param(group => $DNSDB::group);
1842 $page->param(isgrp => 1) if $def eq 'y';
1843 $page->param(parent => ($def eq 'y' ? groupName($dbh, $DNSDB::group) : domainName($dbh, $id)) );
1844
1845# defaults
1846 $page->param(defcontact => $DNSDB::def{contact});
1847 $page->param(defns => $DNSDB::def{prins});
1848 $page->param(defsoattl => $DNSDB::def{soattl});
1849 $page->param(defrefresh => $DNSDB::def{refresh});
1850 $page->param(defretry => $DNSDB::def{retry});
1851 $page->param(defexpire => $DNSDB::def{expire});
1852 $page->param(defminttl => $DNSDB::def{minttl});
1853
1854 # there are probably better ways to do this. TMTOWTDI.
1855 my %soa = getSOA($dbh,$def,$id);
1856
1857 $page->param(id => $id);
1858 $page->param(recid => $soa{recid});
1859 $page->param(prins => ($soa{prins} ? $soa{prins} : $DNSDB::def{prins}));
1860 $page->param(contact => ($soa{contact} ? $soa{contact} : $DNSDB::def{contact}));
1861 $page->param(refresh => ($soa{refresh} ? $soa{refresh} : $DNSDB::def{refresh}));
1862 $page->param(retry => ($soa{retry} ? $soa{retry} : $DNSDB::def{retry}));
1863 $page->param(expire => ($soa{expire} ? $soa{expire} : $DNSDB::def{expire}));
1864 $page->param(minttl => ($soa{minttl} ? $soa{minttl} : $DNSDB::def{minttl}));
1865 $page->param(ttl => ($soa{ttl} ? $soa{ttl} : $DNSDB::def{soattl}));
1866}
1867
1868sub showzone {
1869 my $def = shift;
1870 my $rev = shift;
1871 my $id = shift;
1872
1873 # get the SOA first
1874 my %soa = getSOA($dbh,$def,$rev,$id);
1875
1876 $page->param(contact => $soa{contact});
1877 $page->param(prins => $soa{prins});
1878 $page->param(refresh => $soa{refresh});
1879 $page->param(retry => $soa{retry});
1880 $page->param(expire => $soa{expire});
1881 $page->param(minttl => $soa{minttl});
1882 $page->param(ttl => $soa{ttl});
1883
1884 my $foo2 = getDomRecs($dbh,$def,$rev,$id,$perpage,$webvar{offset},$sortby,$sortorder,$filter);
1885
1886 my $row = 0;
1887 foreach my $rec (@$foo2) {
1888 $rec->{type} = $typemap{$rec->{type}};
1889 $rec->{row} = $row % 2;
1890 $rec->{defrec} = $def;
1891 $rec->{revrec} = $rev;
1892 $rec->{sid} = $webvar{sid};
1893 $rec->{id} = $id;
1894 $rec->{fwdzone} = $rev eq 'n';
1895 $rec->{distance} = 'n/a' unless ($rec->{type} eq 'MX' || $rec->{type} eq 'SRV');
1896 $rec->{weight} = 'n/a' unless ($rec->{type} eq 'SRV');
1897 $rec->{port} = 'n/a' unless ($rec->{type} eq 'SRV');
1898 $row++;
1899# ACLs
1900 $rec->{record_edit} = ($permissions{admin} || $permissions{record_edit});
1901 $rec->{record_delete} = ($permissions{admin} || $permissions{record_delete});
1902 }
1903 $page->param(reclist => $foo2);
1904}
1905
1906sub fill_recdata {
1907 $page->param(typelist => getTypelist($dbh, $webvar{revrec}, $webvar{type}));
1908
1909# le sigh. we may get called with many empty %webvar keys
1910 no warnings qw( uninitialized );
1911
1912##todo: allow BIND-style bare names, ASS-U-ME that the name is within the domain?
1913# prefill <domain> or DOMAIN in "Host" space for new records
1914 if ($webvar{revrec} eq 'n') {
1915 my $domroot = ($webvar{defrec} eq 'y' ? 'DOMAIN' : domainName($dbh,$webvar{parentid}));
1916 $page->param(name => $domroot);
1917 $page->param(address => $webvar{address});
1918 $page->param(distance => $webvar{distance})
1919 if ($webvar{type} == $reverse_typemap{MX} or $webvar{type} == $reverse_typemap{SRV});
1920 $page->param(weight => $webvar{weight}) if $webvar{type} == $reverse_typemap{SRV};
1921 $page->param(port => $webvar{port}) if $webvar{type} == $reverse_typemap{SRV};
1922 } else {
1923 my $domroot = ($webvar{defrec} eq 'y' ? 'ADMINDOMAIN' : ".$config{domain}");
1924 $page->param(name => ($webvar{name} ? $webvar{name} : $domroot));
1925 my $zname = ($webvar{defrec} eq 'y' ? 'ZONE' : revName($dbh,$webvar{parentid}));
1926 $zname =~ s|\d*/\d+$||;
1927 $page->param(address => ($webvar{address} ? $webvar{address} : $zname));
1928 }
1929# retrieve the right ttl instead of falling (way) back to the hardcoded system default
1930 my %soa = getSOA($dbh,$webvar{defrec},$webvar{revrec},$webvar{parentid});
1931 $page->param(ttl => ($webvar{ttl} ? $webvar{ttl} : $soa{minttl}));
1932}
1933
1934sub fill_actypelist {
1935 my $curtype = shift || 'u';
1936
1937 my @actypes;
1938
1939 my %row1 = (actypeval => 'u', actypename => 'user');
1940 $row1{typesel} = 1 if $curtype eq 'u';
1941 push @actypes, \%row1;
1942
1943 my %row2 = (actypeval => 'S', actypename => 'superuser');
1944 $row2{typesel} = 1 if $curtype eq 'S';
1945 push @actypes, \%row2;
1946
1947 $page->param(actypelist => \@actypes);
1948}
1949
1950sub fill_clonemelist {
1951 my $sth = $dbh->prepare("SELECT username,user_id FROM users WHERE group_id=$curgroup");
1952 $sth->execute;
1953
1954 # shut up some warnings, but don't stomp on caller's state
1955 local $webvar{clonesrc} = 0 if !defined($webvar{clonesrc});
1956
1957 my @clonesrc;
1958 while (my ($username,$uid) = $sth->fetchrow_array) {
1959 my %row = (
1960 username => $username,
1961 uid => $uid,
1962 selected => ($webvar{clonesrc} == $uid ? 1 : 0)
1963 );
1964 push @clonesrc, \%row;
1965 }
1966 $page->param(clonesrc => \@clonesrc);
1967}
1968
1969sub fill_fpnla {
1970 my $count = shift;
1971 if ($offset eq 'all') {
1972 $page->param(perpage => $perpage);
1973# uhm....
1974 } else {
1975 # all these bits only have sensible behaviour if offset is numeric. err, probably.
1976 if ($count > $perpage) {
1977 # if there are more results than the default, always show the "all" link
1978 $page->param(navall => 1);
1979
1980 if ($offset > 0) {
1981 $page->param(navfirst => 1);
1982 $page->param(navprev => 1);
1983 $page->param(prevoffs => $offset-1);
1984 }
1985
1986 # show "next" and "last" links if we're not on the last page of results
1987 if ( (($offset+1) * $perpage - $count) < 0 ) {
1988 $page->param(navnext => 1);
1989 $page->param(nextoffs => $offset+1);
1990 $page->param(navlast => 1);
1991 $page->param(lastoffs => int (($count-1)/$perpage));
1992 }
1993 } else {
1994 $page->param(onepage => 1);
1995 }
1996 }
1997} # end fill_fpnla()
1998
1999sub fill_pgcount {
2000 my $pgcount = shift;
2001 my $pgtype = shift;
2002 my $parent = shift;
2003
2004 # Fix display/UI bug where if you are not on the first page of the list, and
2005 # you add a search term or click one of the "starts with" links, you end up
2006 # on a page showing nothing.
2007 # For bonus points, this reverts to the original offset on clicking the "All" link (mostly)
2008 if ($offset ne 'all') {
2009 $offset-- while ($offset * $perpage) >= $pgcount;
2010 }
2011
2012 $page->param(ntot => $pgcount);
2013 $page->param(nfirst => (($offset eq 'all' ? 0 : $offset)*$perpage+1));
2014 $page->param(npglast => ($offset eq 'all' ? $pgcount :
2015 ( (($offset+1)*$perpage) > $pgcount ? $pgcount : (($offset+1)*$perpage) )
2016 ));
2017 $page->param(pgtype => $pgtype);
2018 $page->param(parent => $parent);
2019 $page->param(filter => $filter);
2020} # end fill_pgcount()
2021
2022
2023sub listdomains { listzones(); } # temp
2024
2025sub listzones {
2026# ACLs
2027 $page->param(domain_create => ($permissions{admin} || $permissions{domain_create}) );
2028 $page->param(domain_edit => ($permissions{admin} || $permissions{domain_edit}) );
2029 $page->param(domain_delete => ($permissions{admin} || $permissions{domain_delete}) );
2030
2031 my @childgroups;
2032 getChildren($dbh, $curgroup, \@childgroups, 'all') if $searchsubs;
2033 my $childlist = join(',',@childgroups);
2034
2035 my $count = getZoneCount($dbh, (childlist => $childlist, curgroup => $curgroup, revrec => $webvar{revrec},
2036 filter => ($filter ? $filter : undef), startwith => ($startwith ? $startwith : undef) ) );
2037
2038# fill page count and first-previous-next-last-all bits
2039 fill_pgcount($count,($webvar{revrec} eq 'n' ? 'domains' : 'revzones'),groupName($dbh,$curgroup));
2040 fill_fpnla($count);
2041
2042# sort/order
2043 $session->param($webvar{page}.'sortby', $webvar{sortby}) if $webvar{sortby};
2044 $session->param($webvar{page}.'order', $webvar{order}) if $webvar{order};
2045
2046 $sortby = $session->param($webvar{page}.'sortby') if $session->param($webvar{page}.'sortby');
2047 $sortorder = $session->param($webvar{page}.'order') if $session->param($webvar{page}.'order');
2048
2049# set up the headers
2050 my @cols = (($webvar{revrec} eq 'n' ? 'domain' : 'revnet'), 'status', 'group');
2051 my %colheads = (domain => 'Domain', revnet => 'Reverse Zone', status => 'Status', group => 'Group');
2052 fill_colheads($sortby, $sortorder, \@cols, \%colheads);
2053
2054 # hack! hack! pthbttt. have to rethink the status column storage,
2055 # or inactive comes "before" active. *sigh*
2056 $sortorder = ($sortorder eq 'ASC' ? 'DESC' : 'ASC') if $sortby eq 'status';
2057
2058# waffle, waffle - keep state on these as well as sortby, sortorder?
2059##fixme: put this higher so the count doesn't get munched?
2060 $page->param("start$startwith" => 1) if $startwith && $startwith =~ /^(?:[a-z]|0-9)$/;
2061
2062 $page->param(filter => $filter) if $filter;
2063 $page->param(searchsubs => $searchsubs) if $searchsubs;
2064
2065 $page->param(group => $curgroup);
2066
2067 my $zonelist = getZoneList($dbh, (childlist => $childlist, curgroup => $curgroup,
2068 revrec => $webvar{revrec},
2069 filter => ($filter ? $filter : undef), startwith => ($startwith ? $startwith : undef),
2070 offset => $webvar{offset}, sortby => $sortby, sortorder => $sortorder
2071 ) );
2072# probably don't need this, keeping for reference for now
2073# foreach (@$zonelist) {
2074# }
2075 $page->param(domtable => $zonelist);
2076} # end listdomains()
2077
2078
2079sub listgroups {
2080
2081# security check - does the user have permission to view this entity?
2082 if (!(grep /^$curgroup$/, @viewablegroups)) {
2083 # hmm. Reset the current group to the login group? Yes. Prevents confusing behaviour elsewhere.
2084 $session->param('curgroup',$logingroup);
2085 $page->param(errmsg => "You are not permitted to view the requested group");
2086 $curgroup = $logingroup;
2087 }
2088
2089 my @childgroups;
2090 getChildren($dbh, $curgroup, \@childgroups, 'all') if $searchsubs;
2091 my $childlist = join(',',@childgroups);
2092
2093 my $sql = "SELECT count(*) FROM groups WHERE parent_group_id IN ($curgroup".($childlist ? ",$childlist" : '').")".
2094 ($startwith ? " AND group_name ~* ?" : '').
2095 ($filter ? " AND group_name ~* ?" : '');
2096 my $sth = $dbh->prepare($sql);
2097 $sth->execute(@filterargs);
2098 my ($count) = ($sth->fetchrow_array);
2099
2100# fill page count and first-previous-next-last-all bits
2101 fill_pgcount($count,"groups",'');
2102 fill_fpnla($count);
2103
2104 $page->param(gid => $curgroup);
2105
2106 $sortby = 'group';
2107# sort/order
2108 $session->param($webvar{page}.'sortby', $webvar{sortby}) if $webvar{sortby};
2109 $session->param($webvar{page}.'order', $webvar{order}) if $webvar{order};
2110
2111 $sortby = $session->param($webvar{page}.'sortby') if $session->param($webvar{page}.'sortby');
2112 $sortorder = $session->param($webvar{page}.'order') if $session->param($webvar{page}.'order');
2113
2114# set up the headers
2115 my @cols = ('group','parent','nusers','ndomains');
2116 my %colnames = (group => 'Group', parent => 'Parent Group', nusers => 'Users', ndomains => 'Domains');
2117 fill_colheads($sortby, $sortorder, \@cols, \%colnames);
2118
2119# waffle, waffle - keep state on these as well as sortby, sortorder?
2120 $page->param("start$startwith" => 1) if $startwith && $startwith =~ /^(?:[a-z]|0-9)$/;
2121
2122 $page->param(filter => $filter) if $filter;
2123 $page->param(searchsubs => $searchsubs) if $searchsubs;
2124
2125# munge sortby for columns in database
2126 $sortby = 'g.group_name' if $sortby eq 'group';
2127 $sortby = 'g2.group_name' if $sortby eq 'parent';
2128
2129 my @grouplist;
2130 $sql = "SELECT g.group_id, g.group_name, g2.group_name, ".
2131 "count(distinct(u.username)) AS nusers, count(distinct(d.domain)) AS ndomains ".
2132 "FROM groups g ".
2133 "INNER JOIN groups g2 ON g2.group_id=g.parent_group_id ".
2134 "LEFT OUTER JOIN users u ON u.group_id=g.group_id ".
2135 "LEFT OUTER JOIN domains d ON d.group_id=g.group_id ".
2136 "WHERE g.parent_group_id IN ($curgroup".($childlist ? ",$childlist" : '').") ".
2137 ($startwith ? " AND g.group_name ~* ?" : '').
2138 ($filter ? " AND g.group_name ~* ?" : '').
2139 " GROUP BY g.group_id, g.group_name, g2.group_name ".
2140 " ORDER BY $sortby $sortorder ".
2141 ($offset eq 'all' ? '' : " LIMIT $perpage OFFSET ".$offset*$perpage);
2142 $sth = $dbh->prepare($sql);
2143 $sth->execute(@filterargs);
2144
2145 my $rownum = 0;
2146 while (my @data = $sth->fetchrow_array) {
2147 my %row;
2148 $row{groupid} = $data[0];
2149 $row{groupname} = $data[1];
2150 $row{pgroup} = $data[2];
2151 $row{nusers} = $data[3];
2152 $row{ndomains} = $data[4];
2153 $row{bg} = ($rownum++)%2;
2154 $row{sid} = $sid;
2155 $row{edgrp} = ($permissions{admin} || $permissions{group_edit});
2156 $row{delgrp} = ($permissions{admin} || $permissions{group_delete});
2157 push @grouplist, \%row;
2158 }
2159 $page->param(grouptable => \@grouplist);
2160} # end listgroups()
2161
2162
2163sub fill_grouplist {
2164 my $template_var = shift;
2165 my $cur = shift || $curgroup;
2166
2167 my @childgroups;
2168 getChildren($dbh, $logingroup, \@childgroups, 'all');
2169 my $childlist = join(',',@childgroups);
2170
2171##fixme: need to reorder list so that we can display a pseudotree in group dropdowns
2172
2173 # weesa gonna discard parent_group_id for now
2174 my $sth = $dbh->prepare("SELECT group_id,parent_group_id,group_name FROM groups ".
2175 "WHERE group_id IN ($logingroup".($childlist ? ",$childlist" : '').")".
2176 "ORDER BY group_id");
2177 $sth->execute;
2178 my @grouplist;
2179 while (my ($groupid,$pargroup,$groupname) = $sth->fetchrow_array()) {
2180 my %row;
2181 $row{groupname} = $groupname;
2182 $row{groupval} = $groupid;
2183##fixme: need magic
2184## ... WTF?
2185# $row{defgroup} = '';
2186 $row{groupactive} = 1 if $groupid == $cur;
2187 push @grouplist, \%row;
2188 }
2189
2190 $page->param("$template_var" => \@grouplist);
2191
2192} # end fill_grouplist()
2193
2194
2195sub list_users {
2196
2197 my @childgroups;
2198 getChildren($dbh, $curgroup, \@childgroups, 'all') if $searchsubs;
2199 my $childlist = join(',',@childgroups);
2200
2201 my $sql = "SELECT count(*) FROM users WHERE group_id IN ($curgroup".($childlist ? ",$childlist" : '').")".
2202 ($startwith ? " AND username ~* ?" : '').
2203 ($filter ? " AND username ~* ?" : '');
2204 my $sth = $dbh->prepare($sql);
2205 $sth->execute(@filterargs);
2206 my ($count) = ($sth->fetchrow_array);
2207
2208# fill page count and first-previous-next-last-all bits
2209 fill_pgcount($count,"users",'');
2210 fill_fpnla($count);
2211
2212 $sortby = 'user';
2213# sort/order
2214 $session->param($webvar{page}.'sortby', $webvar{sortby}) if $webvar{sortby};
2215 $session->param($webvar{page}.'order', $webvar{order}) if $webvar{order};
2216
2217 $sortby = $session->param($webvar{page}.'sortby') if $session->param($webvar{page}.'sortby');
2218 $sortorder = $session->param($webvar{page}.'order') if $session->param($webvar{page}.'order');
2219
2220# set up the headers
2221 my @cols = ('user','fname','type','group','status');
2222 my %colnames = (user => 'Username', fname => 'Full Name', type => 'Type', group => 'Group', status => 'Status');
2223 fill_colheads($sortby, $sortorder, \@cols, \%colnames);
2224
2225# waffle, waffle - keep state on these as well as sortby, sortorder?
2226 $page->param("start$startwith" => 1) if $startwith && $startwith =~ /^(?:[a-z]|0-9)$/;
2227
2228 $page->param(filter => $filter) if $filter;
2229 $page->param(searchsubs => $searchsubs) if $searchsubs;
2230
2231# munge sortby for columns in database
2232 $sortby = 'u.username' if $sortby eq 'user';
2233 $sortby = 'u.type' if $sortby eq 'type';
2234 $sortby = 'g.group_name' if $sortby eq 'group';
2235 $sortby = 'u.status' if $sortby eq 'status';
2236
2237 my @userlist;
2238 $sql = "SELECT u.user_id, u.username, u.firstname || ' ' || u.lastname AS fname, u.type, g.group_name, u.status ".
2239 "FROM users u ".
2240 "INNER JOIN groups g ON u.group_id=g.group_id ".
2241 "WHERE u.group_id IN ($curgroup".($childlist ? ",$childlist" : '').")".
2242 ($startwith ? " AND u.username ~* ?" : '').
2243 ($filter ? " AND u.username ~* ?" : '').
2244 " ORDER BY $sortby $sortorder ".
2245 ($offset eq 'all' ? '' : " LIMIT $perpage OFFSET ".$offset*$perpage);
2246
2247 $sth = $dbh->prepare($sql);
2248 $sth->execute(@filterargs);
2249
2250 my $rownum = 0;
2251 while (my @data = $sth->fetchrow_array) {
2252 no warnings "uninitialized"; # Just In Case something stupid happens and a user gets no first or last name
2253 my %row;
2254 $row{userid} = $data[0];
2255 $row{username} = $data[1];
2256 $row{userfull} = $data[2];
2257 $row{usertype} = ($data[3] eq 'S' ? 'superuser' : "user");
2258 $row{usergroup} = $data[4];
2259 $row{active} = $data[5];
2260 $row{bg} = ($rownum++)%2;
2261 $row{sid} = $sid;
2262 $row{eduser} = ($permissions{admin} || $permissions{user_edit});
2263 $row{deluser} = ($permissions{admin} || $permissions{user_delete});
2264 push @userlist, \%row;
2265 }
2266 $page->param(usertable => \@userlist);
2267} # end list_users()
2268
2269
2270# Generate all of the glop necessary to add or not the appropriate marker/flag for
2271# the sort order and column in domain, user, group, and record lists
2272# Takes an array ref and hash ref
2273sub fill_colheads {
2274 my $sortby = shift;
2275 my $sortorder = shift;
2276 my $cols = shift;
2277 my $colnames = shift;
2278 my $custom = shift;
2279
2280 my @headings;
2281
2282 foreach my $col (@$cols) {
2283 my %coldata;
2284 $coldata{firstcol} = 1 if $col eq $cols->[0];
2285 $coldata{sid} = $sid;
2286 $coldata{page} = $webvar{page};
2287 $coldata{offset} = $webvar{offset} if $webvar{offset};
2288 $coldata{sortby} = $col;
2289 $coldata{colname} = $colnames->{$col};
2290 if ($col eq $sortby) {
2291 $coldata{order} = ($sortorder eq 'ASC' ? 'DESC' : 'ASC');
2292 $coldata{sortorder} = $sortorder;
2293 } else {
2294 $coldata{order} = 'ASC';
2295 }
2296 if ($custom) {
2297 foreach my $ckey (keys %$custom) {
2298 $coldata{$ckey} = $custom->{$ckey};
2299 }
2300 }
2301 push @headings, \%coldata;
2302 }
2303
2304 $page->param(colheads => \@headings);
2305
2306} # end fill_colheads()
2307
2308
2309sub logaction {
2310 my $domid = shift;
2311 my $username = shift;
2312 my $groupid = shift;
2313 my $entry = shift;
2314 my $revid = shift || 0;
2315
2316##fixme: push SQL into DNSDB.pm
2317##fixme: add bits to retrieve group/domain name info to retain after entity is deleted?
2318 my $sth = $dbh->prepare("SELECT user_id, firstname || ' ' || lastname FROM users WHERE username=?");
2319 $sth->execute($username);
2320 my ($user_id, $fullname) = $sth->fetchrow_array;
2321
2322 $sth = $dbh->prepare("INSERT INTO log (domain_id,user_id,group_id,email,name,entry,rdns_id) ".
2323 "VALUES (?,?,?,?,?,?,?)") or warn $dbh->errstr;
2324 $sth->execute($domid,$user_id,$groupid,$username,$fullname,$entry,$revid) or warn $sth->errstr;
2325} # end logaction()
2326
2327
2328# we have to do this in a variety of places; let's make it consistent
2329sub fill_permissions {
2330 my $template = shift; # may need to do several sets on a single page
2331 my $permset = shift; # hashref to permissions on object
2332 my $usercan = shift || \%permissions; # allow alternate user-is-allowed permission block
2333
2334 foreach (@permtypes) {
2335 $template->param("may_$_" => ($usercan->{admin} || $usercan->{$_}));
2336 $template->param($_ => $permset->{$_});
2337 }
2338}
2339
2340# so simple when defined as a sub instead of inline. O_o
2341sub check_scope {
2342 my %args = @_;
2343 my $entity = $args{id} || 0; # prevent the shooting of feet with SQL "... intcolumn = '' ..."
2344 my $entype = $args{type} || '';
2345
2346 if ($entype eq 'group') {
2347 return 1 if grep /^$entity$/, @viewablegroups;
2348 } else {
2349 foreach (@viewablegroups) {
2350 return 1 if isParent($dbh, $_, 'group', $entity, $entype);
2351 }
2352 }
2353}
Note: See TracBrowser for help on using the repository browser.