source: trunk/dns.cgi@ 167

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

/trunk

Fix logging buglet with group delete inserting the group as NULL
under certain conditions

  • Property svn:executable set to *
  • Property svn:keywords set to Date Rev Author Id
File size: 77.9 KB
Line 
1#!/usr/bin/perl -w -T
2# dns/cgi-bin/dns.cgi
3###
4# SVN revision info
5# $Date: 2011-11-22 20:57:52 +0000 (Tue, 22 Nov 2011) $
6# SVN revision $Rev: 167 $
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 $delparent = parentID($webvar{id}, 'group','group');
782 my ($code,$msg) = delGroup($dbh, $webvar{id});
783 if ($code ne 'OK') {
784# need to find failure mode
785 logaction(0, $session->param("username"), $delparent, "Failure deleting group $deleteme: $msg");
786 changepage(page => "grpman", errmsg => "Error deleting group $deleteme: $msg");
787 } else {
788##fixme: need to clean up log when deleting a major container
789 logaction(0, $session->param("username"), $delparent, "Deleted group $deleteme");
790 changepage(page => "grpman", resultmsg => "Deleted group $deleteme");
791 }
792 } else {
793 # cancelled. whee!
794 changepage(page => "grpman");
795 }
796 $page->param(delgroupname => groupName($dbh, $webvar{id}));
797
798} elsif ($webvar{page} eq 'edgroup') {
799
800 changepage(page => "grpman", errmsg => "You are not permitted to edit groups")
801 unless ($permissions{admin} || $permissions{group_edit});
802
803 if ($webvar{action} eq 'updperms') {
804 # extra safety check; make sure user can't construct a URL to bypass ACLs
805 my %curperms;
806 getPermissions($dbh, 'group', $webvar{gid}, \%curperms);
807 my %chperms;
808 foreach (@permtypes) {
809 $webvar{$_} = 0 if !defined($webvar{$_});
810 $webvar{$_} = 1 if $webvar{$_} eq 'on';
811 $chperms{$_} = $webvar{$_} if $curperms{$_} ne $webvar{$_};
812 }
813 my ($code,$msg) = changePermissions($dbh, 'group', $webvar{gid}, \%chperms);
814 if ($code eq 'OK') {
815 logaction(0, $session->param("username"), $webvar{gid},
816 "Updated default permissions in group $webvar{gid} (".groupName($dbh, $webvar{gid}).")");
817 changepage(page => "grpman", resultmsg =>
818 "Updated default permissions in group ".groupName($dbh, $webvar{gid}));
819 }
820 # no point in doing extra work
821 fill_permissions($page, \%chperms);
822 $page->param(errmsg => $msg);
823 }
824 $page->param(gid => $webvar{gid});
825 $page->param(grpmeddle => groupName($dbh, $webvar{gid}));
826 my %grpperms;
827 getPermissions($dbh, 'group', $webvar{gid}, \%grpperms);
828 fill_permissions($page, \%grpperms);
829
830} elsif ($webvar{page} eq 'bulkdomain') {
831 # Bulk operations on domains. Note all but group move are available on the domain list.
832
833 changepage(page => "domlist", errmsg => "You are not permitted to make bulk domain changes")
834 unless ($permissions{admin} || $permissions{domain_edit} || $permissions{domain_create} || $permissions{domain_delete});
835
836 fill_grouplist("grouplist");
837
838##fixme
839##fixme push the SQL and direct database fiddling off into a sub in DNSDB.pm
840##fixme
841
842 my $sth = $dbh->prepare("SELECT count(*) FROM domains WHERE group_id=?");
843 $sth->execute($curgroup);
844 my ($count) = ($sth->fetchrow_array);
845
846 $page->param(curpage => $webvar{page});
847 fill_pgcount($count,'domains',groupName($dbh,$curgroup));
848 fill_fpnla($count);
849 $page->param(perpage => $perpage);
850
851 my @domlist;
852 my $sql = "SELECT domain_id,domain FROM domains".
853 " WHERE group_id=?".
854 " ORDER BY domain".
855 ($offset eq 'all' ? '' : " LIMIT $perpage OFFSET ".$offset*$perpage);
856 $sth = $dbh->prepare($sql);
857 $sth->execute($curgroup);
858 my $rownum = 0;
859 while (my @data = $sth->fetchrow_array) {
860 my %row;
861 $row{domid} = $data[0];
862 $row{domain} = $data[1];
863 $rownum++; # putting this in the expression below causes failures. *eyeroll*
864 $row{newrow} = $rownum % 5 == 0;
865 push @domlist, \%row;
866 }
867 $page->param(domtable => \@domlist);
868 # ACLs
869 $page->param(maymove => ($permissions{admin} || ($permissions{domain_edit} && $permissions{domain_create} && $permissions{domain_delete})));
870 $page->param(maystatus => $permissions{admin} || $permissions{domain_edit});
871 $page->param(maydelete => $permissions{admin} || $permissions{domain_delete});
872
873} elsif ($webvar{page} eq 'bulkchange') {
874
875 # security check - does the user have permission to access this entity?
876 if (!check_scope($webvar{destgroup}, 'group')) {
877 $page->param(errmsg => "You are not permitted to make bulk changes in the requested group");
878 goto DONEBULK;
879 }
880
881 if ($webvar{action} eq 'move') {
882 changepage(page => "domlist", errmsg => "You are not permitted to bulk-move domains")
883 unless ($permissions{admin} || ($permissions{domain_edit} && $permissions{domain_create} && $permissions{domain_delete}));
884 my $newgname = groupName($dbh,$webvar{destgroup});
885 $page->param(action => "Move to group $newgname");
886 my @bulkresults;
887 # nngh. due to alpha-sorting on the previous page, we can't use domid-numeric
888 # order here, and since we don't have the domain names until we go around this
889 # loop, we can't alpha-sort them here. :(
890 foreach (keys %webvar) {
891 my %row;
892 next unless $_ =~ /^dom_\d+$/;
893 # second security check - does the user have permission to meddle with this domain?
894 if (!check_scope($webvar{$_}, 'domain')) {
895 $row{domerr} = "You are not permitted to make changes to the requested domain";
896 $row{domain} = $webvar{$_};
897 push @bulkresults, \%row;
898 next;
899 }
900 $row{domain} = domainName($dbh,$webvar{$_});
901 my ($code, $msg) = changeGroup($dbh, 'domain', $webvar{$_}, $webvar{destgroup});
902 if ($code eq 'OK') {
903 logaction($webvar{$_}, $session->param("username"), parentID($webvar{$_}, 'dom', 'group'),
904 "Moved domain ".domainName($dbh, $webvar{$_})." to group $newgname");
905 $row{domok} = ($code eq 'OK');
906 } else {
907 logaction($webvar{$_}, $session->param("username"), parentID($webvar{$_}, 'dom', 'group'),
908 "Failure moving domain ".domainName($dbh, $webvar{$_})." to group $newgname: $msg");
909 }
910 $row{domerr} = $msg;
911 push @bulkresults, \%row;
912 }
913 $page->param(bulkresults => \@bulkresults);
914
915 } elsif ($webvar{action} eq 'deactivate' || $webvar{action} eq 'activate') {
916 changepage(page => "domlist", errmsg => "You are not permitted to bulk-$webvar{action} domains")
917 unless ($permissions{admin} || $permissions{domain_edit});
918 $page->param(action => "$webvar{action} domains");
919 my @bulkresults;
920 foreach (keys %webvar) {
921 my %row;
922 next unless $_ =~ /^dom_\d+$/;
923 # second security check - does the user have permission to meddle with this domain?
924 if (!check_scope($webvar{$_}, 'domain')) {
925 $row{domerr} = "You are not permitted to make changes to the requested domain";
926 $row{domain} = $webvar{$_};
927 push @bulkresults, \%row;
928 next;
929 }
930 $row{domain} = domainName($dbh,$webvar{$_});
931##fixme: error handling on status change
932 my $stat = domStatus($dbh,$webvar{$_},($webvar{action} eq 'activate' ? 'domon' : 'domoff'));
933 logaction($webvar{$_}, $session->param("username"), parentID($webvar{$_}, 'dom', 'group'),
934 "Changed domain ".domainName($dbh, $webvar{$_})." state to ".($stat ? 'active' : 'inactive'));
935 $row{domok} = 1;
936# $row{domok} = ($code eq 'OK');
937# $row{domerr} = $msg;
938 push @bulkresults, \%row;
939 }
940 $page->param(bulkresults => \@bulkresults);
941
942 } elsif ($webvar{action} eq 'delete') {
943 changepage(page => "domlist", errmsg => "You are not permitted to bulk-delete domains")
944 unless ($permissions{admin} || $permissions{domain_delete});
945 $page->param(action => "$webvar{action} domains");
946 my @bulkresults;
947 foreach (keys %webvar) {
948 my %row;
949 next unless $_ =~ /^dom_\d+$/;
950 # second security check - does the user have permission to meddle with this domain?
951 if (!check_scope($webvar{$_}, 'domain')) {
952 $row{domerr} = "You are not permitted to make changes to the requested domain";
953 $row{domain} = $webvar{$_};
954 push @bulkresults, \%row;
955 next;
956 }
957 $row{domain} = domainName($dbh,$webvar{$_});
958 my $pargroup = parentID($webvar{$_}, 'dom', 'group');
959 my $dom = domainName($dbh, $webvar{$_});
960 my ($code, $msg) = delDomain($dbh, $webvar{$_});
961 if ($code eq 'OK') {
962 logaction($webvar{$_}, $session->param("username"), $pargroup, "Deleted domain $dom");
963 $row{domok} = ($code eq 'OK');
964 } else {
965 logaction($webvar{$_}, $session->param("username"), $pargroup, "Failure deleting domain $dom: $msg");
966 }
967 $row{domerr} = $msg;
968 push @bulkresults, \%row;
969 }
970 $page->param(bulkresults => \@bulkresults);
971
972 } # move/(de)activate/delete if()
973
974 # not going to handle the unknown $webvar{action} else; it should not be possible in normal
975 # operations, and anyone who meddles with the URL gets what they deserve.
976
977 # Yes, this is a GOTO target. PTHBTTT.
978 DONEBULK: ;
979
980} elsif ($webvar{page} eq 'useradmin') {
981
982 if (defined($webvar{userstatus})) {
983 # security check - does the user have permission to access this entity?
984 my $flag = 0;
985 foreach (@viewablegroups) {
986 $flag = 1 if isParent($dbh, $_, 'group', $webvar{id}, 'user');
987 }
988 if ($flag) {
989 userStatus($dbh,$webvar{id},$webvar{userstatus});
990 } else {
991 $page->param(errmsg => "You are not permitted to view or change the requested user");
992 }
993 }
994
995 list_users();
996
997# Permissions!
998 $page->param(adduser => $permissions{admin} || $permissions{user_create});
999# should we block viewing other users? Vega blocks "editing"...
1000# NB: no "edit self" link as with groups here. maybe there should be?
1001# $page->param(eduser => $permissions{admin} || $permissions{user_edit});
1002 $page->param(deluser => $permissions{admin} || $permissions{user_delete});
1003
1004 $page->param(resultmsg => $webvar{resultmsg}) if $webvar{resultmsg};
1005 $page->param(warnmsg => $webvar{warnmsg}) if $webvar{warnmsg};
1006 $page->param(errmsg => $webvar{errmsg}) if $webvar{errmsg};
1007 $page->param(curpage => $webvar{page});
1008
1009} elsif ($webvar{page} eq 'user') {
1010
1011 # All user add/edit actions fall through the same page, since there aren't
1012 # really any hard differences between the templates
1013
1014 #fill_actypelist($webvar{accttype});
1015 fill_clonemelist();
1016 my %grpperms;
1017 getPermissions($dbh, 'group', $curgroup, \%grpperms);
1018
1019 my $grppermlist = new HTML::Template(filename => "$templatedir/permlist.tmpl");
1020 my %noaccess;
1021 fill_permissions($grppermlist, \%grpperms, \%noaccess);
1022 $grppermlist->param(info => 1);
1023 $page->param(grpperms => $grppermlist->output);
1024
1025 $page->param(is_admin => $permissions{admin});
1026
1027 $webvar{action} = '' if !$webvar{action};
1028
1029 if ($webvar{action} eq 'add' or $webvar{action} eq 'update') {
1030
1031 $page->param(add => 1) if $webvar{action} eq 'add';
1032
1033 my ($code,$msg);
1034
1035 my $alterperms = 0; # flag iff we need to force custom permissions due to user's current access limits
1036
1037 my %newperms; # we're going to prefill the existing permissions, so we can change them.
1038 getPermissions($dbh, 'user', $webvar{uid}, \%newperms);
1039
1040 if ($webvar{pass1} ne $webvar{pass2}) {
1041 $code = 'FAIL';
1042 $msg = "Passwords don't match";
1043 } else {
1044
1045 # assemble a permission string - far simpler than trying to pass an
1046 # indeterminate set of permission flags individually
1047
1048 # But first, we have to see if the user can add any particular
1049 # permissions; otherwise we have a priviledge escalation. Whee.
1050
1051 if (!$permissions{admin}) {
1052 my %grpperms;
1053 getPermissions($dbh, 'group', $curgroup, \%grpperms);
1054 my $ret = comparePermissions(\%permissions, \%grpperms);
1055 if ($ret eq '<' || $ret eq '!') {
1056 # User's permissions are not a superset or equivalent to group. Can't inherit
1057 # (and include access user doesn't currently have), so we force custom.
1058 $webvar{perms_type} = 'custom';
1059 $alterperms = 1;
1060 }
1061 }
1062
1063 my $permstring;
1064 if ($webvar{perms_type} eq 'custom') {
1065 $permstring = 'C:';
1066 foreach (@permtypes) {
1067 if ($permissions{admin} || $permissions{$_}) {
1068 $permstring .= ",$_" if defined($webvar{$_}) && $webvar{$_} eq 'on';
1069 $newperms{$_} = (defined($webvar{$_}) && $webvar{$_} eq 'on' ? 1 : 0);
1070 }
1071 }
1072 $page->param(perm_custom => 1);
1073 } elsif ($permissions{admin} && $webvar{perms_type} eq 'clone') {
1074 $permstring = "c:$webvar{clonesrc}";
1075 getPermissions($dbh, 'user', $webvar{clonesrc}, \%newperms);
1076 $page->param(perm_clone => 1);
1077 } else {
1078 $permstring = 'i';
1079 }
1080 if ($webvar{action} eq 'add') {
1081 changepage(page => "useradmin", errmsg => "You do not have permission to add new users")
1082 unless $permissions{admin} || $permissions{user_create};
1083 ($code,$msg) = addUser($dbh, $webvar{uname}, $curgroup, $webvar{pass1},
1084 ($webvar{makeactive} eq 'on' ? 1 : 0), $webvar{accttype}, $permstring,
1085 $webvar{fname}, $webvar{lname}, $webvar{phone});
1086 logaction(0, $session->param("username"), $curgroup, "Added user $webvar{uname} (uid $msg)")
1087 if $code eq 'OK';
1088 } else {
1089 changepage(page => "useradmin", errmsg => "You do not have permission to edit users")
1090 unless $permissions{admin} || $permissions{user_edit};
1091# User update is icky. I'd really like to do this in one atomic
1092# operation, but that would duplicate a **lot** of code in DNSDB.pm
1093 # Allowing for changing group, but not coding web support just yet.
1094 ($code,$msg) = updateUser($dbh, $webvar{uid}, $webvar{uname}, $webvar{gid}, $webvar{pass1},
1095 ($webvar{makeactive} eq 'on' ? 1 : 0), $webvar{accttype},
1096 $webvar{fname}, $webvar{lname}, $webvar{phone});
1097 if ($code eq 'OK') {
1098 $newperms{admin} = 1 if $webvar{accttype} eq 'S';
1099 ($code,$msg) = changePermissions($dbh, 'user', $webvar{uid}, \%newperms, ($permstring eq 'i'));
1100 }
1101 logaction(0, $session->param("username"), $curgroup,
1102 "Updated uid $webvar{uid}, user $webvar{uname} ($webvar{fname} $webvar{lname})");
1103 }
1104 }
1105
1106 if ($code eq 'OK') {
1107
1108 if ($alterperms) {
1109 changepage(page => "useradmin", warnmsg =>
1110 "You can only grant permissions you hold. $webvar{uname} ".
1111 ($webvar{action} eq 'add' ? 'added' : 'updated')." with reduced access.");
1112 } else {
1113 changepage(page => "useradmin", resultmsg => "Successfully ".
1114 ($webvar{action} eq 'add' ? 'added' : 'updated')." user $webvar{uname}");
1115 }
1116
1117 # add/update failed:
1118 } else {
1119 $page->param(add_failed => 1);
1120 $page->param(action => $webvar{action});
1121 $page->param(set_permgroup => 1);
1122 if ($webvar{perms_type} eq 'inherit') { # set permission class radio
1123 $page->param(perm_inherit => 1);
1124 } elsif ($webvar{perms_type} eq 'clone') {
1125 $page->param(perm_clone => 1);
1126 } else {
1127 $page->param(perm_custom => 1);
1128 }
1129 $page->param(uname => $webvar{uname});
1130 $page->param(fname => $webvar{fname});
1131 $page->param(lname => $webvar{lname});
1132 $page->param(pass1 => $webvar{pass1});
1133 $page->param(pass2 => $webvar{pass2});
1134 $page->param(errmsg => $msg);
1135 fill_permissions($page, \%newperms);
1136 fill_actypelist($webvar{accttype});
1137 fill_clonemelist();
1138##fixme: log
1139 }
1140
1141 } elsif ($webvar{action} eq 'edit') {
1142
1143 changepage(page => "useradmin", errmsg => "You do not have permission to edit users")
1144 unless $permissions{admin} || $permissions{user_edit};
1145
1146 $page->param(set_permgroup => 1);
1147 $page->param(action => 'update');
1148 $page->param(uid => $webvar{user});
1149 fill_clonemelist();
1150
1151 my $userinfo = getUserData($dbh,$webvar{user});
1152 fill_actypelist($userinfo->{type});
1153 # not using this yet, but adding it now means we can *much* more easily do so later.
1154 $page->param(gid => $webvar{group_id});
1155
1156 my %curperms;
1157 getPermissions($dbh, 'user', $webvar{user}, \%curperms);
1158 fill_permissions($page, \%curperms);
1159
1160 $page->param(uname => $userinfo->{username});
1161 $page->param(fname => $userinfo->{firstname});
1162 $page->param(lname => $userinfo->{lastname});
1163 $page->param(set_permgroup => 1);
1164 if ($userinfo->{inherit_perm}) {
1165 $page->param(perm_inherit => 1);
1166 } else {
1167 $page->param(perm_custom => 1);
1168 }
1169 } else {
1170 changepage(page => "useradmin", errmsg => "You are not allowed to add new users")
1171 unless $permissions{admin} || $permissions{user_create};
1172 # default is "new"
1173 $page->param(add => 1);
1174 $page->param(action => 'add');
1175 fill_permissions($page, \%grpperms);
1176 fill_actypelist();
1177 }
1178
1179} elsif ($webvar{page} eq 'deluser') {
1180
1181 changepage(page=> "useradmin", errmsg => "You are not allowed to delete users")
1182 unless $permissions{admin} || $permissions{user_delete};
1183
1184 $page->param(id => $webvar{id});
1185 # first pass = confirm y/n (sorta)
1186 if (!defined($webvar{del})) {
1187 $page->param(del_getconf => 1);
1188 $page->param(user => userFullName($dbh,$webvar{id}));
1189 } elsif ($webvar{del} eq 'ok') {
1190##fixme: find group id user is in (for logging) *before* we delete the user
1191##fixme: get other user data too for log
1192 my $userref = getUserData($dbh, $webvar{id});
1193 my ($code,$msg) = delUser($dbh, $webvar{id});
1194 if ($code ne 'OK') {
1195# need to find failure mode
1196 $page->param(del_failed => 1);
1197 $page->param(errmsg => $msg);
1198 list_users($curgroup);
1199#Error deleting user <TMPL_VAR NAME=delusername>: <TMPL_VAR NAME=errmsg>
1200 } else {
1201 # success. go back to the user list, do not pass "GO"
1202 # actions on users have a domain id of 0, always
1203 logaction(0, $session->param("username"), $curgroup, "Deleted user $webvar{id}/".$userref->{username}.
1204 " (".$userref->{lastname}.", ".$userref->{firstname}.")");
1205 changepage(page => "useradmin", resultmsg => "Deleted user ".$userref->{username}.
1206 " (".$userref->{lastname}.", ".$userref->{firstname}.")");
1207 }
1208 } else {
1209 # cancelled. whee!
1210 changepage(page => "useradmin");
1211 }
1212
1213} elsif ($webvar{page} eq 'dnsq') {
1214
1215 $page->param(qfor => $webvar{qfor}) if $webvar{qfor};
1216 fill_rectypes($webvar{type} ? $webvar{type} : '', 1);
1217 $page->param(nrecurse => $webvar{nrecurse}) if $webvar{nrecurse};
1218 $page->param(resolver => $webvar{resolver}) if $webvar{resolver};
1219
1220 if ($webvar{qfor}) {
1221 my $resolv = Net::DNS::Resolver->new;
1222 $resolv->tcp_timeout(5); # make me adjustable!
1223 $resolv->udp_timeout(5); # make me adjustable!
1224 $resolv->recurse(0) if $webvar{nrecurse};
1225 $resolv->nameservers($webvar{resolver}) if $webvar{resolver};
1226 my $query = $resolv->query($webvar{qfor}, $typemap{$webvar{type}});
1227 if ($query) {
1228
1229 $page->param(showresults => 1);
1230
1231 my @answer;
1232 foreach my $rr ($query->answer) {
1233# next unless $rr->type eq "A" or $rr->type eq 'NS';
1234 my %row;
1235 my ($host,$ttl,$class,$type,$data) =
1236 ($rr->string =~ /^([0-9a-zA-Z_.-]+)\s+(\d+)\s+([A-Za-z]+)\s+([A-Za-z]+)\s+(.+)$/s);
1237 $row{host} = $host;
1238 $row{ftype} = $type;
1239 $row{rdata} = ($type eq 'SOA' ? "<pre>$data</pre>" : $data);
1240 push @answer, \%row;
1241 }
1242 $page->param(answer => \@answer);
1243
1244 my @additional;
1245 foreach my $rr ($query->additional) {
1246# next unless $rr->type eq "A" or $rr->type eq 'NS';
1247 my %row;
1248 my ($host,$ttl,$class,$type,$data) =
1249 ($rr->string =~ /^([0-9a-zA-Z_.-]+)\s+(\d+)\s+([A-Za-z]+)\s+([A-Za-z]+)\s+(.+)$/);
1250 $row{host} = $host;
1251 $row{ftype} = $type;
1252 $row{rdata} = $data;
1253 push @additional, \%row;
1254 }
1255 $page->param(additional => \@additional);
1256
1257 my @authority;
1258 foreach my $rr ($query->authority) {
1259# next unless $rr->type eq "A" or $rr->type eq 'NS';
1260 my %row;
1261 my ($host,$ttl,$class,$type,$data) =
1262 ($rr->string =~ /^([0-9a-zA-Z_.-]+)\s+(\d+)\s+([A-Za-z]+)\s+([A-Za-z]+)\s+(.+)$/);
1263 $row{host} = $host;
1264 $row{ftype} = $type;
1265 $row{rdata} = $data;
1266 push @authority, \%row;
1267 }
1268 $page->param(authority => \@authority);
1269
1270 $page->param(usedresolver => $resolv->answerfrom);
1271 $page->param(frtype => $typemap{$webvar{type}});
1272
1273 } else {
1274 $page->param(errmsg => $resolv->errorstring);
1275 }
1276 }
1277 ## done DNS query
1278
1279} elsif ($webvar{page} eq 'axfr') {
1280
1281 changepage(page => "domlist", errmsg => "You are not permitted to import domains")
1282 unless ($permissions{admin} || $permissions{domain_create});
1283
1284 # don't need this while we've got the dropdown in the menu. hmm.
1285 fill_grouplist("grouplist");
1286
1287 $page->param(ifrom => $webvar{ifrom}) if $webvar{ifrom};
1288 $page->param(rwsoa => $webvar{rwsoa}) if $webvar{rwsoa};
1289 $page->param(rwns => $webvar{rwns}) if $webvar{rwns};
1290 $page->param(dominactive => 1) if (!$webvar{domactive} && $webvar{doit}); # eww.
1291 $page->param(importdoms => $webvar{importdoms}) if $webvar{importdoms};
1292
1293 # shut up warning about uninitialized variable
1294 $webvar{doit} = '' if !defined($webvar{doit});
1295
1296 if ($webvar{doit} eq 'y' && !$webvar{ifrom}) {
1297 $page->param(errmsg => "Need to set host to import from");
1298 } elsif ($webvar{doit} eq 'y' && !$webvar{importdoms}) {
1299 $page->param(errmsg => "Need domains to import");
1300 } elsif ($webvar{doit} eq 'y') {
1301
1302 # security check - does the user have permission to access this entity?
1303 if (!check_scope($webvar{group}, 'group')) {
1304 $page->param(errmsg => "You are not permitted to import domains into the requested group");
1305 goto DONEAXFR;
1306 }
1307
1308 my @domlist = split /\s+/, $webvar{importdoms};
1309 my @results;
1310 foreach my $domain (@domlist) {
1311 my %row;
1312 my ($code,$msg) = importAXFR($dbh, $webvar{ifrom}, $domain, $webvar{group},
1313 $webvar{domstatus}, $webvar{rwsoa}, $webvar{rwns});
1314 $row{domok} = $msg if $code eq 'OK';
1315 if ($code eq 'WARN') {
1316 $msg =~ s|\n|<br />|g;
1317 $row{domwarn} = $msg;
1318 }
1319 if ($code eq 'FAIL') {
1320 $msg =~ s|\n|<br />\n|g;
1321 $row{domerr} = $msg;
1322 }
1323 $msg = "<br />\n".$msg if $msg =~ m|<br />|;
1324 logaction(domainID($dbh, $domain), $session->param("username"), $webvar{group},
1325 "AXFR import $domain from $webvar{ifrom} ($code): $msg");
1326 $row{domain} = $domain;
1327 push @results, \%row;
1328 }
1329 $page->param(axfrresults => \@results);
1330 }
1331
1332 # Yes, this is a GOTO target. PTBHTTT.
1333 DONEAXFR: ;
1334
1335} elsif ($webvar{page} eq 'whoisq') {
1336
1337 if ($webvar{qfor}) {
1338 use Net::Whois::Raw;
1339 use Text::Wrap;
1340
1341# caching useful?
1342#$Net::Whois::Raw::CACHE_DIR = "/var/spool/pwhois/";
1343#$Net::Whois::Raw::CACHE_TIME = 60;
1344
1345 my ($dominfo, $whois_server) = whois($webvar{qfor});
1346##fixme: if we're given an IP, try rwhois as well as whois so we get the real final data
1347
1348 # le sigh. idjits spit out data without linefeeds...
1349 $Text::Wrap::columns = 88;
1350
1351# &%$@%@# high-bit crap. We should probably find a way to properly recode these
1352# instead of one-by-one. Note CGI::Simple's escapeHTML() doesn't do more than
1353# the bare minimum. :/
1354# Mainly an XHTML validation thing.
1355 $dominfo = $q->escapeHTML($dominfo);
1356 $dominfo =~ s/\xa9/\&copy;/g;
1357 $dominfo =~ s/\xae/\&reg;/g;
1358
1359 $page->param(qfor => $webvar{qfor});
1360 $page->param(dominfo => wrap('','',$dominfo));
1361 $page->param(whois_server => $whois_server);
1362 } else {
1363 $page->param(errmsg => "Missing host or domain to query in WHOIS") if $webvar{askaway};
1364 }
1365
1366} elsif ($webvar{page} eq 'log') {
1367
1368##fixme put in some real log-munching stuff
1369 my $sql = "SELECT user_id, email, name, entry, date_trunc('second',stamp) FROM log WHERE ";
1370 my $id = $curgroup; # we do this because the group log may be called from (almost) any page,
1371 # but the others are much more limited. this is probably non-optimal.
1372 if ($webvar{ltype} && $webvar{ltype} eq 'user') {
1373 $sql .= "user_id=?";
1374 $id = $webvar{id};
1375 $page->param(logfor => 'user '.userFullName($dbh,$id));
1376 } elsif ($webvar{ltype} && $webvar{ltype} eq 'dom') {
1377 $sql .= "domain_id=?";
1378 $id = $webvar{id};
1379 $page->param(logfor => 'domain '.domainName($dbh,$id));
1380 } else {
1381 # Default to listing curgroup log
1382 $sql .= "group_id=?";
1383 $page->param(logfor => 'group '.groupName($dbh,$id));
1384 }
1385 my $sth = $dbh->prepare($sql);
1386 $sth->execute($id);
1387 my @logbits;
1388 while (my ($uid, $email, $name, $entry, $stamp) = $sth->fetchrow_array) {
1389 my %row;
1390 $row{userfname} = $name;
1391 $row{userid} = $uid;
1392 $row{useremail} = $email;
1393 $row{logentry} = $entry;
1394 ($row{logtime}) = ($stamp =~ /^(.+)-\d\d$/);
1395 push @logbits, \%row;
1396 }
1397 $page->param(logentries => \@logbits);
1398
1399} # end $webvar{page} dance
1400
1401
1402# start output here so we can redirect pages.
1403print "Content-type: text/html\n\n", $header->output;
1404
1405##common bits
1406if ($webvar{page} ne 'login') {
1407 $page->param(username => $session->param("username"));
1408
1409 $page->param(group => $curgroup);
1410 $page->param(groupname => groupName($dbh,$curgroup));
1411 $page->param(logingrp => groupName($dbh,$logingroup));
1412 $page->param(logingrp_num => $logingroup);
1413
1414 $page->param(maydefrec => $permissions{admin});
1415 $page->param(mayimport => $permissions{admin} || $permissions{domain_create});
1416 $page->param(maybulk => $permissions{admin} || $permissions{domain_edit} || $permissions{domain_create} || $permissions{domain_delete});
1417
1418 $page->param(chggrps => ($permissions{admin} || $permissions{group_create} || $permissions{group_edit} || $permissions{group_delete}));
1419
1420 # group tree. should go elsewhere, probably
1421 my $tmpgrplist = fill_grptree($logingroup,$curgroup);
1422 $page->param(grptree => $tmpgrplist);
1423 $page->param(subs => ($tmpgrplist ? 1 : 0)); # probably not useful to pass gobs of data in for a boolean
1424 $page->param(inlogingrp => $curgroup == $logingroup);
1425
1426# fill in the URL-to-self
1427 $page->param(whereami => $uri_self);
1428}
1429
1430if (@debugbits) {
1431 print "<pre>\n";
1432 foreach (@debugbits) { print; }
1433 print "</pre>\n";
1434}
1435
1436# spit it out
1437print $page->output;
1438
1439if ($debugenv) {
1440 print "<div id=\"debug\">webvar keys: <pre>\n";
1441 foreach my $key (keys %webvar) {
1442 print "key: $key\tval: $webvar{$key}\n";
1443 }
1444 print "</pre>\nsession:\n<pre>\n";
1445 my $sesdata = $session->dataref();
1446 foreach my $key (keys %$sesdata) {
1447 print "key: $key\tval: ".$sesdata->{$key}."\n";
1448 }
1449 print "</pre>\nENV:\n<pre>\n";
1450 foreach my $key (keys %ENV) {
1451 print "key: $key\tval: $ENV{$key}\n";
1452 }
1453 print "</pre></div>\n";
1454}
1455
1456print $footer->output;
1457
1458# as per the docs, Just In Case
1459$session->flush();
1460
1461exit 0;
1462
1463
1464sub fill_grptree {
1465 my $root = shift;
1466 my $cur = shift;
1467 my $indent = shift || ' ';
1468
1469 my @childlist;
1470
1471 my $grptree = HTML::Template->new(filename => 'templates/grptree.tmpl');
1472 getChildren($dbh,$root,\@childlist,'immediate');
1473 return if $#childlist == -1;
1474 my @grouplist;
1475 foreach (@childlist) {
1476 my %row;
1477 $row{grpname} = groupName($dbh,$_);
1478 $row{grpnum} = $_;
1479 $row{whereami} = $uri_self;
1480 # for all that HTML::Template is supposed to keep the HTML out of the Perl, this is so much more compact...
1481# $row{grpdisp} = ($_ == $cur ? "<b>$row{grpname}</b>" : $row{grpname});
1482$row{curgrp} = ($_ == $cur);
1483$row{expanded} = isParent($dbh, $_, 'group', $cur, 'group');
1484$row{expanded} = 1 if $_ == $cur;
1485 $row{subs} = fill_grptree($_,$cur,$indent.' ');
1486 $row{indent} = $indent;
1487 push @grouplist, \%row;
1488 }
1489 $grptree->param(indent => $indent);
1490 $grptree->param(treelvl => \@grouplist);
1491 return $grptree->output;
1492}
1493
1494sub changepage {
1495 my %params = @_; # think this works the way I want...
1496
1497 # handle user check
1498 my $newurl = "http://$ENV{HTTP_HOST}$ENV{SCRIPT_NAME}?sid=$sid";
1499 foreach (keys %params) {
1500 $newurl .= "&$_=".$q->url_encode($params{$_});
1501 }
1502
1503 # Just In Case
1504 $session->flush();
1505
1506 print "Status: 302\nLocation: $newurl\n\n";
1507 exit;
1508} # end changepage
1509
1510sub fillsoa {
1511 my $def = shift;
1512 my $id = shift;
1513 my $domname = ($def eq 'y' ? '' : "DOMAIN");
1514
1515 $page->param(defrec => $def);
1516
1517# i had a good reason to do this when I wrote it...
1518# $page->param(domain => $domname);
1519# $page->param(group => $DNSDB::group);
1520 $page->param(isgrp => 1) if $def eq 'y';
1521 $page->param(parent => ($def eq 'y' ? groupName($dbh, $DNSDB::group) : domainName($dbh, $id)) );
1522
1523# defaults
1524 $page->param(defcontact => $DNSDB::def{contact});
1525 $page->param(defns => $DNSDB::def{prins});
1526 $page->param(defsoattl => $DNSDB::def{soattl});
1527 $page->param(defrefresh => $DNSDB::def{refresh});
1528 $page->param(defretry => $DNSDB::def{retry});
1529 $page->param(defexpire => $DNSDB::def{expire});
1530 $page->param(defminttl => $DNSDB::def{minttl});
1531
1532 # there are probably better ways to do this. TMTOWTDI.
1533 my %soa = getSOA($dbh,$def,$id);
1534
1535 $page->param(id => $id);
1536 $page->param(recid => $soa{recid});
1537 $page->param(prins => ($soa{prins} ? $soa{prins} : $DNSDB::def{prins}));
1538 $page->param(contact => ($soa{contact} ? $soa{contact} : $DNSDB::def{contact}));
1539 $page->param(refresh => ($soa{refresh} ? $soa{refresh} : $DNSDB::def{refresh}));
1540 $page->param(retry => ($soa{retry} ? $soa{retry} : $DNSDB::def{retry}));
1541 $page->param(expire => ($soa{expire} ? $soa{expire} : $DNSDB::def{expire}));
1542 $page->param(minttl => ($soa{minttl} ? $soa{minttl} : $DNSDB::def{minttl}));
1543 $page->param(ttl => ($soa{ttl} ? $soa{ttl} : $DNSDB::def{soattl}));
1544}
1545
1546sub showdomain {
1547 my $def = shift;
1548 my $id = shift;
1549
1550 # get the SOA first
1551 my %soa = getSOA($dbh,$def,$id);
1552
1553 $page->param(contact => $soa{contact});
1554 $page->param(prins => $soa{prins});
1555 $page->param(refresh => $soa{refresh});
1556 $page->param(retry => $soa{retry});
1557 $page->param(expire => $soa{expire});
1558 $page->param(minttl => $soa{minttl});
1559 $page->param(ttl => $soa{ttl});
1560
1561 my $foo2 = getDomRecs($dbh,$def,$id,$perpage,$webvar{offset},$sortby,$sortorder,$filter);
1562
1563 my $row = 0;
1564 foreach my $rec (@$foo2) {
1565 $rec->{type} = $typemap{$rec->{type}};
1566 $rec->{row} = $row % 2;
1567 $rec->{defrec} = $def;
1568 $rec->{sid} = $webvar{sid};
1569 $rec->{id} = $id;
1570 $rec->{distance} = 'n/a' unless ($rec->{type} eq 'MX' || $rec->{type} eq 'SRV');
1571 $rec->{weight} = 'n/a' unless ($rec->{type} eq 'SRV');
1572 $rec->{port} = 'n/a' unless ($rec->{type} eq 'SRV');
1573 $row++;
1574# ACLs
1575 $rec->{record_edit} = ($permissions{admin} || $permissions{record_edit});
1576 $rec->{record_delete} = ($permissions{admin} || $permissions{record_delete});
1577 }
1578 $page->param(reclist => $foo2);
1579}
1580
1581# fill in record type list on add/update/edit record template
1582sub fill_rectypes {
1583 my $type = shift || $reverse_typemap{A};
1584 my $soaflag = shift || 0;
1585
1586 my $sth = $dbh->prepare("SELECT val,name FROM rectypes WHERE stdflag=1 ORDER BY listorder");
1587 $sth->execute;
1588 my @typelist;
1589 while (my ($rval,$rname) = $sth->fetchrow_array()) {
1590 my %row = ( recval => $rval, recname => $rname );
1591 $row{tselect} = 1 if $rval == $type;
1592 push @typelist, \%row;
1593 }
1594 if ($soaflag) {
1595 my %row = ( recval => $reverse_typemap{SOA}, recname => 'SOA' );
1596 $row{tselect} = 1 if $reverse_typemap{SOA} == $type;
1597 push @typelist, \%row;
1598 }
1599 $page->param(typelist => \@typelist);
1600} # fill_rectypes
1601
1602sub fill_recdata {
1603 fill_rectypes($webvar{type});
1604
1605# le sigh. we may get called with many empty %webvar keys
1606 no warnings qw( uninitialized );
1607
1608##todo: allow BIND-style bare names, ASS-U-ME that the name is within the domain?
1609# prefill <domain> or DOMAIN in "Host" space for new records
1610 my $domroot = ($webvar{defrec} eq 'y' ? 'DOMAIN' : domainName($dbh,$webvar{parentid}));
1611 $page->param(name => $domroot);
1612 $page->param(address => $webvar{address});
1613 $page->param(distance => $webvar{distance})
1614 if ($webvar{type} == $reverse_typemap{MX} or $webvar{type} == $reverse_typemap{SRV});
1615 $page->param(weight => $webvar{weight}) if $webvar{type} == $reverse_typemap{SRV};
1616 $page->param(port => $webvar{port}) if $webvar{type} == $reverse_typemap{SRV};
1617# retrieve the right ttl instead of falling (way) back to the hardcoded system default
1618 my %soa = getSOA($dbh,$webvar{defrec},$webvar{parentid});
1619 $page->param(ttl => ($webvar{ttl} ? $webvar{ttl} : $soa{minttl}));
1620}
1621
1622sub fill_actypelist {
1623 my $curtype = shift || 'u';
1624
1625 my @actypes;
1626
1627 my %row1 = (actypeval => 'u', actypename => 'user');
1628 $row1{typesel} = 1 if $curtype eq 'u';
1629 push @actypes, \%row1;
1630
1631 my %row2 = (actypeval => 'S', actypename => 'superuser');
1632 $row2{typesel} = 1 if $curtype eq 'S';
1633 push @actypes, \%row2;
1634
1635 $page->param(actypelist => \@actypes);
1636}
1637
1638sub fill_clonemelist {
1639 my $sth = $dbh->prepare("SELECT username,user_id FROM users WHERE group_id=$curgroup");
1640 $sth->execute;
1641
1642 # shut up some warnings, but don't stomp on caller's state
1643 local $webvar{clonesrc} = 0 if !defined($webvar{clonesrc});
1644
1645 my @clonesrc;
1646 while (my ($username,$uid) = $sth->fetchrow_array) {
1647 my %row = (
1648 username => $username,
1649 uid => $uid,
1650 selected => ($webvar{clonesrc} == $uid ? 1 : 0)
1651 );
1652 push @clonesrc, \%row;
1653 }
1654 $page->param(clonesrc => \@clonesrc);
1655}
1656
1657sub fill_fpnla {
1658 my $count = shift;
1659 if ($offset eq 'all') {
1660 $page->param(perpage => $perpage);
1661# uhm....
1662 } else {
1663 # all these bits only have sensible behaviour if offset is numeric. err, probably.
1664 if ($count > $perpage) {
1665 # if there are more results than the default, always show the "all" link
1666 $page->param(navall => 1);
1667
1668 if ($offset > 0) {
1669 $page->param(navfirst => 1);
1670 $page->param(navprev => 1);
1671 $page->param(prevoffs => $offset-1);
1672 }
1673
1674 # show "next" and "last" links if we're not on the last page of results
1675 if ( (($offset+1) * $perpage - $count) < 0 ) {
1676 $page->param(navnext => 1);
1677 $page->param(nextoffs => $offset+1);
1678 $page->param(navlast => 1);
1679 $page->param(lastoffs => int (($count-1)/$perpage));
1680 }
1681 } else {
1682 $page->param(onepage => 1);
1683 }
1684 }
1685} # end fill_fpnla()
1686
1687sub fill_pgcount {
1688 my $pgcount = shift;
1689 my $pgtype = shift;
1690 my $parent = shift;
1691
1692 # Fix display/UI bug where if you are not on the first page of the list, and
1693 # you add a search term or click one of the "starts with" links, you end up
1694 # on a page showing nothing.
1695 # For bonus points, this reverts to the original offset on clicking the "All" link (mostly)
1696 if ($offset ne 'all') {
1697 $offset-- while ($offset * $perpage) >= $pgcount;
1698 }
1699
1700 $page->param(ntot => $pgcount);
1701 $page->param(nfirst => (($offset eq 'all' ? 0 : $offset)*$perpage+1));
1702 $page->param(npglast => ($offset eq 'all' ? $pgcount :
1703 ( (($offset+1)*$perpage) > $pgcount ? $pgcount : (($offset+1)*$perpage) )
1704 ));
1705 $page->param(pgtype => $pgtype);
1706 $page->param(parent => $parent);
1707 $page->param(filter => $filter);
1708} # end fill_pgcount()
1709
1710sub listdomains {
1711
1712 $searchsubs = $session->param($webvar{page}.'searchsubs');
1713
1714# ACLs
1715 $page->param(domain_create => ($permissions{admin} || $permissions{domain_create}) );
1716 $page->param(domain_edit => ($permissions{admin} || $permissions{domain_edit}) );
1717 $page->param(domain_delete => ($permissions{admin} || $permissions{domain_delete}) );
1718
1719 my @childgroups;
1720 getChildren($dbh, $curgroup, \@childgroups, 'all') if $searchsubs;
1721 my $childlist = join(',',@childgroups);
1722
1723 my $sql = "SELECT count(*) FROM domains WHERE group_id IN ($curgroup".($childlist ? ",$childlist" : '').")".
1724 ($startwith ? " AND domain ~* ?" : '').
1725 ($filter ? " AND domain ~* ?" : '');
1726 my $sth = $dbh->prepare($sql);
1727 $sth->execute(@filterargs);
1728 my ($count) = $sth->fetchrow_array;
1729
1730# fill page count and first-previous-next-last-all bits
1731 fill_pgcount($count,"domains",groupName($dbh,$curgroup));
1732 fill_fpnla($count);
1733
1734# sort/order
1735 $session->param($webvar{page}.'sortby', $webvar{sortby}) if $webvar{sortby};
1736 $session->param($webvar{page}.'order', $webvar{order}) if $webvar{order};
1737
1738 $sortby = $session->param($webvar{page}.'sortby') if $session->param($webvar{page}.'sortby');
1739 $sortorder = $session->param($webvar{page}.'order') if $session->param($webvar{page}.'order');
1740
1741# set up the headers
1742 my @cols = ('domain', 'status', 'group');
1743 my %colheads = (domain => 'Domain', status => 'Status', group => 'Group');
1744 fill_colheads($sortby, $sortorder, \@cols, \%colheads);
1745
1746 # hack! hack! pthbttt. have to rethink the status column storage,
1747 # or inactive comes "before" active. *sigh*
1748 $sortorder = ($sortorder eq 'ASC' ? 'DESC' : 'ASC') if $sortby eq 'status';
1749
1750# waffle, waffle - keep state on these as well as sortby, sortorder?
1751 $page->param("start$startwith" => 1) if $startwith && $startwith =~ /^(?:[a-z]|0-9)$/;
1752
1753 $page->param(filter => $filter) if $filter;
1754 $page->param(searchsubs => $searchsubs) if $searchsubs;
1755
1756##fixme
1757##fixme push the SQL and direct database fiddling off into a sub in DNSDB.pm
1758##fixme
1759
1760 $page->param(group => $curgroup);
1761 my @domlist;
1762 $sql = "SELECT domain_id,domain,status,groups.group_name AS group FROM domains".
1763 " INNER JOIN groups ON domains.group_id=groups.group_id".
1764 " WHERE domains.group_id IN ($curgroup".($childlist ? ",$childlist" : '').")".
1765 ($startwith ? " AND domain ~* ?" : '').
1766 ($filter ? " AND domain ~* ?" : '').
1767 " ORDER BY ".($sortby eq 'group' ? 'groups.group_name' : $sortby).
1768 " $sortorder ".($offset eq 'all' ? '' : " LIMIT $perpage OFFSET ".$offset*$perpage);
1769 $sth = $dbh->prepare($sql);
1770 $sth->execute(@filterargs);
1771 my $rownum = 0;
1772 while (my @data = $sth->fetchrow_array) {
1773 my %row;
1774 $row{domainid} = $data[0];
1775 $row{domain} = $data[1];
1776 $row{status} = ($data[2] ? 'Active' : 'Inactive');
1777 $row{group} = $data[3];
1778 $row{bg} = ($rownum++)%2;
1779 $row{mkactive} = !$data[2];
1780 $row{sid} = $sid;
1781 $row{offset} = $offset;
1782# ACLs
1783 $row{domain_edit} = ($permissions{admin} || $permissions{domain_edit});
1784 $row{domain_delete} = ($permissions{admin} || $permissions{domain_delete});
1785 push @domlist, \%row;
1786 }
1787 $page->param(domtable => \@domlist);
1788} # end listdomains()
1789
1790
1791sub listgroups {
1792
1793# security check - does the user have permission to view this entity?
1794 if (!(grep /^$curgroup$/, @viewablegroups)) {
1795 # hmm. Reset the current group to the login group? Yes. Prevents confusing behaviour elsewhere.
1796 $session->param('curgroup',$logingroup);
1797 $page->param(errmsg => "You are not permitted to view the requested group");
1798 $curgroup = $logingroup;
1799 }
1800
1801 my @childgroups;
1802 getChildren($dbh, $curgroup, \@childgroups, 'all') if $searchsubs;
1803 my $childlist = join(',',@childgroups);
1804
1805 my $sql = "SELECT count(*) FROM groups WHERE parent_group_id IN ($curgroup".($childlist ? ",$childlist" : '').")".
1806 ($startwith ? " AND group_name ~* ?" : '').
1807 ($filter ? " AND group_name ~* ?" : '');
1808 my $sth = $dbh->prepare($sql);
1809 $sth->execute(@filterargs);
1810 my ($count) = ($sth->fetchrow_array);
1811
1812# fill page count and first-previous-next-last-all bits
1813 fill_pgcount($count,"groups",'');
1814 fill_fpnla($count);
1815
1816 $page->param(gid => $curgroup);
1817
1818 $sortby = 'group';
1819# sort/order
1820 $session->param($webvar{page}.'sortby', $webvar{sortby}) if $webvar{sortby};
1821 $session->param($webvar{page}.'order', $webvar{order}) if $webvar{order};
1822
1823 $sortby = $session->param($webvar{page}.'sortby') if $session->param($webvar{page}.'sortby');
1824 $sortorder = $session->param($webvar{page}.'order') if $session->param($webvar{page}.'order');
1825
1826# set up the headers
1827 my @cols = ('group','parent','nusers','ndomains');
1828 my %colnames = (group => 'Group', parent => 'Parent Group', nusers => 'Users', ndomains => 'Domains');
1829 fill_colheads($sortby, $sortorder, \@cols, \%colnames);
1830
1831# waffle, waffle - keep state on these as well as sortby, sortorder?
1832 $page->param("start$startwith" => 1) if $startwith && $startwith =~ /^(?:[a-z]|0-9)$/;
1833
1834 $page->param(filter => $filter) if $filter;
1835 $page->param(searchsubs => $searchsubs) if $searchsubs;
1836
1837# munge sortby for columns in database
1838 $sortby = 'g.group_name' if $sortby eq 'group';
1839 $sortby = 'g2.group_name' if $sortby eq 'parent';
1840
1841 my @grouplist;
1842 $sql = "SELECT g.group_id, g.group_name, g2.group_name, ".
1843 "count(distinct(u.username)) AS nusers, count(distinct(d.domain)) AS ndomains ".
1844 "FROM groups g ".
1845 "INNER JOIN groups g2 ON g2.group_id=g.parent_group_id ".
1846 "LEFT OUTER JOIN users u ON u.group_id=g.group_id ".
1847 "LEFT OUTER JOIN domains d ON d.group_id=g.group_id ".
1848 "WHERE g.parent_group_id IN ($curgroup".($childlist ? ",$childlist" : '').") ".
1849 ($startwith ? " AND g.group_name ~* ?" : '').
1850 ($filter ? " AND g.group_name ~* ?" : '').
1851 " GROUP BY g.group_id, g.group_name, g2.group_name ".
1852 " ORDER BY $sortby $sortorder ".
1853 ($offset eq 'all' ? '' : " LIMIT $perpage OFFSET ".$offset*$perpage);
1854 $sth = $dbh->prepare($sql);
1855 $sth->execute(@filterargs);
1856
1857 my $rownum = 0;
1858 while (my @data = $sth->fetchrow_array) {
1859 my %row;
1860 $row{groupid} = $data[0];
1861 $row{groupname} = $data[1];
1862 $row{pgroup} = $data[2];
1863 $row{nusers} = $data[3];
1864 $row{ndomains} = $data[4];
1865 $row{bg} = ($rownum++)%2;
1866 $row{sid} = $sid;
1867 $row{edgrp} = ($permissions{admin} || $permissions{group_edit});
1868 $row{delgrp} = ($permissions{admin} || $permissions{group_delete});
1869 push @grouplist, \%row;
1870 }
1871 $page->param(grouptable => \@grouplist);
1872} # end listgroups()
1873
1874
1875sub fill_grouplist {
1876 my $template_var = shift;
1877 my $cur = shift || $curgroup;
1878
1879 my @childgroups;
1880 getChildren($dbh, $logingroup, \@childgroups, 'all');
1881 my $childlist = join(',',@childgroups);
1882
1883##fixme: need to reorder list so that we can display a pseudotree in group dropdowns
1884
1885 # weesa gonna discard parent_group_id for now
1886 my $sth = $dbh->prepare("SELECT group_id,parent_group_id,group_name FROM groups ".
1887 "WHERE group_id IN ($logingroup".($childlist ? ",$childlist" : '').")".
1888 "ORDER BY group_id");
1889 $sth->execute;
1890 my @grouplist;
1891 while (my ($groupid,$pargroup,$groupname) = $sth->fetchrow_array()) {
1892 my %row;
1893 $row{groupname} = $groupname;
1894 $row{groupval} = $groupid;
1895##fixme: need magic
1896## ... WTF?
1897# $row{defgroup} = '';
1898 $row{groupactive} = 1 if $groupid == $cur;
1899 push @grouplist, \%row;
1900 }
1901
1902 $page->param("$template_var" => \@grouplist);
1903
1904} # end fill_grouplist()
1905
1906
1907sub list_users {
1908
1909 my @childgroups;
1910 getChildren($dbh, $curgroup, \@childgroups, 'all') if $searchsubs;
1911 my $childlist = join(',',@childgroups);
1912
1913 my $sql = "SELECT count(*) FROM users WHERE group_id IN ($curgroup".($childlist ? ",$childlist" : '').")".
1914 ($startwith ? " AND username ~* ?" : '').
1915 ($filter ? " AND username ~* ?" : '');
1916 my $sth = $dbh->prepare($sql);
1917 $sth->execute(@filterargs);
1918 my ($count) = ($sth->fetchrow_array);
1919
1920# fill page count and first-previous-next-last-all bits
1921 fill_pgcount($count,"users",'');
1922 fill_fpnla($count);
1923
1924 $sortby = 'user';
1925# sort/order
1926 $session->param($webvar{page}.'sortby', $webvar{sortby}) if $webvar{sortby};
1927 $session->param($webvar{page}.'order', $webvar{order}) if $webvar{order};
1928
1929 $sortby = $session->param($webvar{page}.'sortby') if $session->param($webvar{page}.'sortby');
1930 $sortorder = $session->param($webvar{page}.'order') if $session->param($webvar{page}.'order');
1931
1932# set up the headers
1933 my @cols = ('user','fname','type','group','status');
1934 my %colnames = (user => 'Username', fname => 'Full Name', type => 'Type', group => 'Group', status => 'Status');
1935 fill_colheads($sortby, $sortorder, \@cols, \%colnames);
1936
1937# waffle, waffle - keep state on these as well as sortby, sortorder?
1938 $page->param("start$startwith" => 1) if $startwith && $startwith =~ /^(?:[a-z]|0-9)$/;
1939
1940 $page->param(filter => $filter) if $filter;
1941 $page->param(searchsubs => $searchsubs) if $searchsubs;
1942
1943# munge sortby for columns in database
1944 $sortby = 'u.username' if $sortby eq 'user';
1945 $sortby = 'u.type' if $sortby eq 'type';
1946 $sortby = 'g.group_name' if $sortby eq 'group';
1947 $sortby = 'u.status' if $sortby eq 'status';
1948
1949 my @userlist;
1950 $sql = "SELECT u.user_id, u.username, u.firstname || ' ' || u.lastname AS fname, u.type, g.group_name, u.status ".
1951 "FROM users u ".
1952 "INNER JOIN groups g ON u.group_id=g.group_id ".
1953 "WHERE u.group_id IN ($curgroup".($childlist ? ",$childlist" : '').")".
1954 ($startwith ? " AND u.username ~* ?" : '').
1955 ($filter ? " AND u.username ~* ?" : '').
1956 " ORDER BY $sortby $sortorder ".
1957 ($offset eq 'all' ? '' : " LIMIT $perpage OFFSET ".$offset*$perpage);
1958
1959 $sth = $dbh->prepare($sql);
1960 $sth->execute(@filterargs);
1961
1962 my $rownum = 0;
1963 while (my @data = $sth->fetchrow_array) {
1964 no warnings "uninitialized"; # Just In Case something stupid happens and a user gets no first or last name
1965 my %row;
1966 $row{userid} = $data[0];
1967 $row{username} = $data[1];
1968 $row{userfull} = $data[2];
1969 $row{usertype} = ($data[3] eq 'S' ? 'superuser' : "user");
1970 $row{usergroup} = $data[4];
1971 $row{active} = $data[5];
1972 $row{bg} = ($rownum++)%2;
1973 $row{sid} = $sid;
1974 $row{eduser} = ($permissions{admin} || $permissions{user_edit});
1975 $row{deluser} = ($permissions{admin} || $permissions{user_delete});
1976 push @userlist, \%row;
1977 }
1978 $page->param(usertable => \@userlist);
1979} # end list_users()
1980
1981
1982# Generate all of the glop necessary to add or not the appropriate marker/flag for
1983# the sort order and column in domain, user, group, and record lists
1984# Takes an array ref and hash ref
1985sub fill_colheads {
1986 my $sortby = shift;
1987 my $sortorder = shift;
1988 my $cols = shift;
1989 my $colnames = shift;
1990 my $custom = shift;
1991
1992 my @headings;
1993
1994 foreach my $col (@$cols) {
1995 my %coldata;
1996 $coldata{firstcol} = 1 if $col eq $cols->[0];
1997 $coldata{sid} = $sid;
1998 $coldata{page} = $webvar{page};
1999 $coldata{offset} = $webvar{offset} if $webvar{offset};
2000 $coldata{sortby} = $col;
2001 $coldata{colname} = $colnames->{$col};
2002 if ($col eq $sortby) {
2003 $coldata{order} = ($sortorder eq 'ASC' ? 'DESC' : 'ASC');
2004 $coldata{sortorder} = $sortorder;
2005 } else {
2006 $coldata{order} = 'ASC';
2007 }
2008 if ($custom) {
2009 foreach my $ckey (keys %$custom) {
2010 $coldata{$ckey} = $custom->{$ckey};
2011 }
2012 }
2013 push @headings, \%coldata;
2014 }
2015
2016 $page->param(colheads => \@headings);
2017
2018} # end fill_colheads()
2019
2020
2021sub logaction {
2022 my $domid = shift;
2023 my $username = shift;
2024 my $groupid = shift;
2025 my $entry = shift;
2026
2027##fixme: push SQL into DNSDB.pm
2028##fixme: add bits to retrieve group/domain name info to retain after entity is deleted?
2029 my $sth = $dbh->prepare("SELECT user_id, firstname || ' ' || lastname FROM users WHERE username=?");
2030 $sth->execute($username);
2031 my ($user_id, $fullname) = $sth->fetchrow_array;
2032
2033 $sth = $dbh->prepare("INSERT INTO log (domain_id,user_id,group_id,email,name,entry) ".
2034 "VALUES (?,?,?,?,?,?)") or warn $dbh->errstr;
2035 $sth->execute($domid,$user_id,$groupid,$username,$fullname,$entry) or warn $sth->errstr;
2036} # end logaction()
2037
2038
2039##fixme: generalize to return appropriate id on all cases (ie, use $partype)
2040sub parentID {
2041 my $id = shift;
2042 my $idtype = shift;
2043 my $partype = shift;
2044 my $defrec = shift || '';
2045
2046 my $sql = '';
2047
2048 if ($idtype eq 'dom') {
2049 return $id if $defrec eq 'y'; # "domain" + default records, we're really looking at a group.
2050 $sql = "SELECT group_id FROM domains WHERE domain_id=?";
2051 } elsif ($idtype eq 'rec') {
2052 if ($defrec eq 'y') {
2053 $sql = "SELECT group_id FROM default_records WHERE record_id=?";
2054 } else {
2055 $sql = "SELECT d.group_id FROM domains d".
2056 " INNER JOIN records r ON d.domain_id=r.domain_id".
2057 " WHERE r.record_id=?";
2058 }
2059 } elsif ($idtype eq 'group') {
2060 $sql = "SELECT parent_group_id FROM groups WHERE group_id=?";
2061 } elsif ($idtype eq 'user') {
2062 $sql = "SELECT group_id FROM users WHERE user_id=?";
2063 } else {
2064 return "FOO", "BAR"; # can't get here.... we think.
2065 }
2066 my $sth = $dbh->prepare($sql);
2067 $sth->execute($id);
2068 my ($retid) = $sth->fetchrow_array;
2069 return $retid if $retid;
2070 # ahh! fall of the edge of the world if things went sideways
2071 ##fixme: really need to do a little more error handling, I think
2072} # end parentID()
2073
2074
2075# we have to do this in a variety of places; let's make it consistent
2076sub fill_permissions {
2077 my $template = shift; # may need to do several sets on a single page
2078 my $permset = shift; # hashref to permissions on object
2079 my $usercan = shift || \%permissions; # allow alternate user-is-allowed permission block
2080
2081 foreach (@permtypes) {
2082 $template->param("may_$_" => ($usercan->{admin} || $usercan->{$_}));
2083 $template->param($_ => $permset->{$_});
2084 }
2085}
2086
2087# so simple when defined as a sub instead of inline. O_o
2088sub check_scope {
2089 my $entity = shift || '';
2090 my $entype = shift || '';
2091
2092 if ($entype eq 'group') {
2093 return 1 if grep /^$entity$/, @viewablegroups;
2094 } else {
2095 foreach (@viewablegroups) {
2096 return 1 if isParent($dbh, $_, 'group', $entity, $entype);
2097 }
2098 }
2099}
Note: See TracBrowser for help on using the repository browser.