source: trunk/dns.cgi@ 285

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

/trunk

Move action logging for zone delete (deldom/delrevzone) into delZone()
See #35

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