source: trunk/dns.cgi@ 282

Last change on this file since 282 was 280, checked in by Kris Deugau, 13 years ago

/trunk

Fix login bug introduced with r279 that didn't use the right
source to put the username into the session storage

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