source: trunk/dns.cgi@ 195

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

/trunk

More log behaviour tweaking

  • fix broken detail-logging of MX/SRV records on record add
  • add flag to control failure logging
  • fix broken user fullname grabber in _log

Tweak config loading with a few new options

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