source: trunk/dns.cgi@ 162

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

/trunk

Add scope checks - domain add/delete
Tweak scope check on record list
Add scope checks on editsoa/updatesoa pages
Clean up SQL with bind parameters for SOA update
Properly log SOA changes
Move AXFR scope check where it will actually have something to trigger on
Drop a handful of stale ##work/##fixme comments
Tweak SOA data template - remove recid from edit link. It's only

used on the actual update, and should be used as a data-validation
check Any Day Real Soon Now(TM)

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