source: trunk/dns.cgi@ 175

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

/trunk

Security review (See #30)

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