source: trunk/dns.cgi@ 277

Last change on this file since 277 was 277, checked in by Kris Deugau, 12 years ago

/trunk

Checkpoint: Clean up SOA editing and extend for reverse zones.
Mostly complete; still need to finish shuffling arguments to
get logging moved into DNSDB.pm
See #26

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