source: trunk/dns.cgi@ 209

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

/trunk

Fix up error reporting in addRec(); don't want to cause unintelligible
database errors where we can catch data-type mismatches before touching
the DB.

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