source: trunk/dns.cgi@ 203

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

/trunk

Fix bug in SOA handling; Vega stores "contact:primary-ns" in the
host field, not "primary-ns:contact"... so we do too until we come
up with a completely different and better way to handle SOA records.

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