source: trunk/dns.cgi@ 163

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

/trunk

Session management

  • expire sessions properly
  • remove session ID from login page
  • load session timeout value from config file

Remove some more stale comments
Fix centering of login box on login page

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