source: trunk/dns.cgi@ 268

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

/trunk

*Still* missed a piece. Really fix reverse record list sorting.

For sure this time.

See #26

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