source: trunk/dns.cgi@ 173

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

/trunk

Security audit (see #30)

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