source: trunk/dns.cgi@ 273

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

/trunk

Checkpoint; update record mostly patched up for reverse records.
See #26

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