source: trunk/dns.cgi@ 260

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

/trunk

First pass adding add-reverse-zone.

  • add newrdns/addrdns templates
  • add handling in dns.cgi for pages, copy-paste-modify'ed from add-domain
  • add addRDNS() in DNSDB.pm, copy-paste-modify'ed from addDomain()

addRDNS() still needs extension at the ##work to properly substitute
ZONE in hostname and value fields as well as pick and choose default
records (ie, skip A+PTR in v6 zones, and skip AAAA+PTR in v4 zones)
See #26

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