source: trunk/dns.cgi@ 170

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

/trunk

Fix another lurking error-log mess-maker when adding a record. See #25.

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