source: trunk/dns.cgi@ 236

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

/trunk

Validation for addRec() now functional with %validators hash
Several more tweaks and cleanups in A, AAAA, PTR, and A/AAAA+PTR records
dns.cgi now reports WARN conditions on add record
Minor typos in reclist.tmpl and record.tmpl fixed

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