source: trunk/dns.cgi@ 286

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

/trunk

Convert action logging for "Add reverse zone" to DNSDB-internal. See #35

  • don't pass userdata, either in the upstream caller (dns.cgi) or internally to _log()
  • don't expect userdata to be passed in

Fix up some warning-message-propagation in addRDNS()
Remove domain_id from addDomain() failure logging; if the domain wasn't
added then the log can't usefully refer to it by domain ID.
File off stale ##fixme's on reclist page
Fine-tune handling of message parameters in changepage(); if we're
going to go to the effort of converting newlines to <br> we should
use the result.

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