#!/usr/bin/perl -w -T # dns/cgi-bin/dns.cgi ### # SVN revision info # $Date: 2011-09-21 22:13:16 +0000 (Wed, 21 Sep 2011) $ # SVN revision $Rev: 128 $ # Last update by $Author: kdeugau $ ### # Copyright (C) 2008-2011 - Kris Deugau use strict; use warnings; use CGI::Carp qw (fatalsToBrowser); use CGI::Simple; use HTML::Template; use CGI::Session; use Crypt::PasswdMD5; use Digest::MD5 qw(md5_hex); use Net::DNS; use DBI; use Data::Dumper; #sub is_tainted { # # from perldoc perlsec # return ! eval { eval("#" . substr(join("", @_), 0, 0)); 1 }; #} #use Cwd 'abs_path'; #use File::Basename; #use lib dirname( abs_path $0 ); #die "argh! tainted!" if is_tainted($0); #die "argh! \@INC got tainted!" if is_tainted(@INC); # custom modules use lib '.'; use DNSDB qw(:ALL); my @debugbits; # temp, to be spit out near the end of processing my $debugenv = 1; # Let's do these templates right... my $templatedir = "templates"; my $sessiondir = "session"; # Set up the CGI object... my $q = new CGI::Simple; # ... and get query-string params as well as POST params if necessary $q->parse_query_string; # This is probably excessive fiddling, but it puts the parameters somewhere my fingers know about... my %webvar = $q->Vars; # persistent stuff needed on most/all pages my $sid = ($webvar{sid} ? $webvar{sid} : undef); my $session = new CGI::Session("driver:File", $sid, {Directory => $sessiondir}) or die CGI::Session->errstr(); #$sid = $session->id() if !$sid; if (!$sid) { # init stuff. can probably axe this down to just above if'n'when user manipulation happens $sid = $session->id(); # need to know the "upper" group the user can deal with; may as well # stick this in the session rather than calling out to the DB every time. $session->param('logingroup',1); $session->param('curgroup',1); # yes, we *do* need to track this too. er, probably. $session->param('domlistsortby','domain'); $session->param('domlistorder','ASC'); $session->param('useradminsortby','user'); $session->param('useradminorder','ASC'); $session->param('grpmansortby','group'); $session->param('grpmanorder','ASC'); $session->param('reclistsortby','host'); $session->param('reclistorder','ASC'); # $session->param('filter','login'); # $session->param('startwith','login'); # $session->param('searchsubs','login'); } # Just In Case. Stale sessions should not be resurrectable. if ($sid ne $session->id()) { changepage(page=> "login", sessexpired => 1); } my $logingroup = ($session->param('logingroup') ? $session->param('logingroup') : 1); my $curgroup = ($session->param('curgroup') ? $session->param('curgroup') : $logingroup); my $group = ($webvar{group} ? $webvar{group} : 1); # per-page startwith, filter, searchsubs $session->param($webvar{page}.'startwith', $webvar{startwith}) if defined($webvar{startwith}); $session->param($webvar{page}.'filter', $webvar{filter}) if defined($webvar{filter}); $webvar{searchsubs} =~ s/^n ?// if $webvar{searchsubs}; $session->param($webvar{page}.'searchsubs', $webvar{searchsubs}) if defined($webvar{searchsubs}); # decide which page to spit out... # also set $webvar{page} before we try to use it. $webvar{page} = 'login' if !$webvar{page}; my $startwith = $session->param($webvar{page}.'startwith'); my $filter = $session->param($webvar{page}.'filter'); my $searchsubs = $session->param($webvar{page}.'searchsubs'); # nrgh, can't handle login here because we don't have a database handle to check the user/pass with yet my $header = HTML::Template->new(filename => "$templatedir/header.tmpl"); my $footer = HTML::Template->new(filename => "$templatedir/footer.tmpl"); ## set up "URL to self" # @#$%@%@#% XHTML - & in a URL must be escaped. >:( my $uri_self = $ENV{REQUEST_URI}; $uri_self =~ s/\&([a-z])/\&\;$1/g; # le sigh. and we need to strip any previous action $uri_self =~ s/\&action=[^&]+//g; # and search filter options. these get stored in the session, but discarded # as soon as you switch to a different page. ##fixme: think about retaining these on a per-page basis, as well as offset; same as the sort-order bits no warnings qw(uninitialized); $uri_self =~ s/\&startwith=[a-z09-]*(\&)?/$1/g; $uri_self =~ s/\&searchsubs=[a-z09-]*(\&)?/$1/g; $uri_self =~ s/\&filter=[a-z09-]*(\&)?/$1/g; use warnings qw(uninitialized); # default #my $perpage = 15; my $perpage = 5; my $offset = ($webvar{offset} ? $webvar{offset} : 0); # NB: these must match the field name and SQL ascend/descend syntax respectively my $sortby = "domain"; my $sortorder = "ASC"; # now load some local system defaults (mainly DB connect info) # note this is not *absolutely* fatal, since there's a default dbname/user/pass in DNSDB.pm # we'll catch a bad DB connect string a little further down. if (!loadConfig()) { warn "Using default configuration; unable to load custom settings: $DNSDB::errstr"; } ##fixme: quit throwing the database handle around, and put all the SQL and direct DB fiddling into DNSDB.pm # dbname, user, pass, host (optional) my ($dbh,$msg) = connectDB($config{dbname}, $config{dbuser}, $config{dbpass}, $config{dbhost}); if (!$dbh) { print "Content-type: text/html\n\n"; print $header->output; my $errpage = HTML::Template->new(filename => "$templatedir/dberr.tmpl"); $errpage->param(errmsg => $msg); print $errpage->output; print $footer->output; exit; } # Load config pieces from the database. Ideally all but the DB user/pass/etc should be loaded here. initGlobals($dbh); # handle login redirect if ($webvar{action}) { if ($webvar{action} eq 'login') { # Snag ACL/permissions here too my $sth = $dbh->prepare("SELECT user_id,group_id,password,firstname,lastname FROM users WHERE username=?"); $sth->execute($webvar{username}); my ($uid,$gid,$pass,$fname,$lname) = $sth->fetchrow_array; $webvar{loginfailed} = 1 if !defined($uid); if ($pass =~ m|^\$1\$([A-Za-z0-9/.]+)\$|) { # native passwords (crypt-md5) $webvar{loginfailed} = 1 if $pass ne unix_md5_crypt($webvar{password},$1); } elsif ($pass =~ /^[0-9a-f]{32}$/) { # VegaDNS import (hex-coded MD5) $webvar{loginfailed} = 1 if $pass ne md5_hex($webvar{password}); } else { # plaintext (convenient now and then) $webvar{loginfailed} = 1 if $pass ne $webvar{password}; } # set session bits $session->param('logingroup',$gid); $session->param('curgroup',$gid); $session->param('uid',$uid); $session->param('username',$webvar{username}); changepage(page => "domlist") if !defined($webvar{loginfailed}); } elsif ($webvar{action} eq 'logout') { # delete the session $session->delete(); $session->flush(); my $newurl = "http://$ENV{HTTP_HOST}$ENV{SCRIPT_NAME}"; $newurl =~ s|/[^/]+$|/|; print "Status: 302\nLocation: $newurl\n\n"; exit; } elsif ($webvar{action} eq 'chgroup') { # fiddle session-stored group data # magic incantation to... uhhh... # ... and the "change group" bits... $uri_self =~ s/\&group=[^&]*//g; $session->param('curgroup', $webvar{group}); $curgroup = ($webvar{group} ? $webvar{group} : $session->param('curgroup')); } } # handle global webvar{action}s initPermissions($dbh,$session->param('uid')); ## Default page is a login page #my $page; # to be initialized as an HTML::Template entity sooner or later #if (!$webvar{page}) { # $page = HTML::Template->new(filename => "$templatedir/login.tmpl"); #} else { #} my $page = HTML::Template->new(filename => "$templatedir/$webvar{page}.tmpl"); $page->param(sid => $sid); if ($webvar{page} eq 'login') { $page->param(loginfailed => 1) if $webvar{loginfailed}; ##fixme: set up session init to actually *check* for session timeout $page->param(timeout => 1) if $webvar{sesstimeout}; } elsif ($webvar{page} eq 'domlist' or $webvar{page} eq 'index') { # hmm. seeing problems in some possibly-not-so-corner cases. # this currently only handles "domain on", "domain off" if (defined($webvar{action})) { my $stat = domStatus($dbh,$webvar{id},$webvar{action}); logaction($webvar{id}, $session->param("username"), parentID($webvar{id}, 'dom', 'group'), "Changed ".domainName($dbh, $webvar{id})." state to ".($stat ? 'active' : 'inactive')); } $page->param(curpage => $webvar{page}); $page->param(errmsg => $webvar{errmsg}) if $webvar{errmsg}; # if ($webvar{del_failed}) { # $page->param(del_failed => 1); # $page->param(errmsg => $webvar{errmsg}); # } listdomains(); } elsif ($webvar{page} eq 'newdomain') { changepage(page => "domlist", errmsg => "You are not permitted to add domains") unless ($permissions{admin} || $permissions{domain_create}); fill_grouplist("grouplist"); if ($webvar{add_failed}) { $page->param(add_failed => 1); $page->param(errmsg => $webvar{errmsg}); $page->param(domain => $webvar{domain}); } } elsif ($webvar{page} eq 'adddomain') { changepage(page => "domlist", errmsg => "You are not permitted to add domains") unless ($permissions{admin} || $permissions{domain_create}); my ($code,$msg) = addDomain($dbh,$webvar{domain},$webvar{group},($webvar{makeactive} eq 'on' ? 1 : 0)); if ($code eq 'OK') { logaction($msg, $session->param("username"), $webvar{group}, "Added domain $webvar{domain}"); changepage(page => "reclist", id => $msg); } else { logaction(0, $session->param("username"), $webvar{group}, "Failed adding domain $webvar{domain} ($msg)"); changepage(page => "newdomain", add_failed => 1, domain => $webvar{domain}, errmsg => $msg); } } elsif ($webvar{page} eq 'deldom') { changepage(page => "domlist", errmsg => "You are not permitted to delete domains") unless ($permissions{admin} || $permissions{domain_delete}); $page->param(id => $webvar{id}); # first pass = confirm y/n (sorta) if (!defined($webvar{del})) { $page->param(del_getconf => 1); $page->param(domain => domainName($dbh,$webvar{id})); } elsif ($webvar{del} eq 'ok') { my $pargroup = parentID($webvar{id}, 'dom', 'group'); my $dom = domainName($dbh, $webvar{id}); my ($code,$msg) = delDomain($dbh, $webvar{id}); if ($code ne 'OK') { # need to find failure mode logaction($webvar{id}, $session->param("username"), $pargroup, "Failed to delete domain $dom ($msg)"); changepage(page => "domlist", errmsg => "Error deleting domain $dom: $msg"); } else { logaction($webvar{id}, $session->param("username"), $pargroup, "Deleted domain $dom"); changepage(page => "domlist"); } } else { # cancelled. whee! changepage(page => "domlist"); } } elsif ($webvar{page} eq 'reclist') { $page->param(mayeditsoa => $permissions{admin} || $permissions{domain_edit}); ##fixme: ACL needs pondering. Does "edit domain" interact with record add/remove/etc? # Note this seems to be answered "no" in Vega. # ACLs $page->param(record_create => ($permissions{admin} || $permissions{record_create}) ); # $page->param(record_edit => ($permissions{admin} || $permissions{record_edit}) ); $page->param(record_delete => ($permissions{admin} || $permissions{record_delete}) ); # Handle record list for both default records (per-group) and live domain records $page->param(defrec => $webvar{defrec}); $page->param(id => $webvar{id}); $page->param(curpage => $webvar{page}); my $count = getRecCount($dbh, $webvar{defrec}, $webvar{id}); $sortby = 'host'; # sort/order $session->param($webvar{page}.'sortby', $webvar{sortby}) if $webvar{sortby}; $session->param($webvar{page}.'order', $webvar{order}) if $webvar{order}; $sortby = $session->param($webvar{page}.'sortby') if $session->param($webvar{page}.'sortby'); $sortorder = $session->param($webvar{page}.'order') if $session->param($webvar{page}.'order'); # set up the headers my @cols = ('host', 'type', 'val', 'distance', 'weight', 'port', 'ttl'); my %colheads = (host => 'Name', type => 'Type', val => 'Address', distance => 'Distance', weight => 'Weight', port => 'Port', ttl => 'TTL'); my %custom = (id => $webvar{id}, defrec => $webvar{defrec}); fill_colheads($sortby, $sortorder, \@cols, \%colheads, \%custom); # fill the page-count and first-previous-next-last-all details fill_pgcount($count,"records", ($webvar{defrec} eq 'y' ? "group ".groupName($dbh,$webvar{id}) : domainName($dbh,$webvar{id}))); fill_fpnla($count); # should put some params on this sub... $page->param(defrec => $webvar{defrec}); if ($webvar{defrec} eq 'y') { showdomain('y',$curgroup); } else { showdomain('n',$webvar{id}); $page->param(logdom => 1); } $page->param(errmsg => $webvar{errmsg}) if $webvar{errmsg}; } elsif ($webvar{page} eq 'record') { if ($webvar{recact} eq 'new') { changepage(page => "reclist", errmsg => "You are not permitted to add records", id => $webvar{parentid}) unless ($permissions{admin} || $permissions{record_create}); $page->param(todo => "Add record"); $page->param(recact => "add"); $page->param(parentid => $webvar{parentid}); $page->param(defrec => $webvar{defrec}); fill_recdata(); } elsif ($webvar{recact} eq 'add') { changepage(page => "reclist", errmsg => "You are not permitted to add records", id => $webvar{parentid}) unless ($permissions{admin} || $permissions{record_create}); my @recargs = ($dbh,$webvar{defrec},$webvar{parentid},$webvar{name},$webvar{type},$webvar{address},$webvar{ttl}); if ($webvar{type} == $reverse_typemap{MX} or $webvar{type} == $reverse_typemap{SRV}) { push @recargs, $webvar{distance}; if ($webvar{type} == $reverse_typemap{SRV}) { push @recargs, $webvar{weight}; push @recargs, $webvar{port}; } } my ($code,$msg) = addRec(@recargs); if ($code eq 'OK') { if ($webvar{defrec} eq 'y') { logaction(0, $session->param("username"), $webvar{parentid}, "Added default record '$webvar{name} $typemap{$webvar{type}} $webvar{address}', TTL $webvar{ttl}"); } else { logaction($webvar{parentid}, $session->param("username"), parentID($webvar{parentid}, 'dom', 'group'), "Added record '$webvar{name} $typemap{$webvar{type}} $webvar{address}', TTL $webvar{ttl}"); } changepage(page => "reclist", id => $webvar{parentid}, defrec => $webvar{defrec}); } else { $page->param(failed => 1); $page->param(errmsg => $msg); $page->param(wastrying => "adding"); $page->param(todo => "Add record"); $page->param(recact => "add"); $page->param(parentid => $webvar{parentid}); $page->param(defrec => $webvar{defrec}); $page->param(id => $webvar{id}); fill_recdata(); # populate the form... er, mostly. if ($webvar{defrec} eq 'y') { logaction(0, $session->param("username"), $webvar{parentid}, "Failed adding default record '$webvar{name} $typemap{$webvar{type}} $webvar{address}', TTL $webvar{ttl} ($msg)"); } else { logaction($webvar{parentid}, $session->param("username"), parentID($webvar{parentid}, 'dom', 'group'), "Failed adding record '$webvar{name} $typemap{$webvar{type}} $webvar{address}', TTL $webvar{ttl} ($msg)"); } } } elsif ($webvar{recact} eq 'edit') { changepage(page => "reclist", errmsg => "You are not permitted to edit records", id => $webvar{parentid}) unless ($permissions{admin} || $permissions{record_edit}); $page->param(todo => "Update record"); $page->param(recact => "update"); $page->param(parentid => $webvar{parentid}); $page->param(id => $webvar{id}); $page->param(defrec => $webvar{defrec}); my $recdata = getRecLine($dbh, $webvar{defrec}, $webvar{id}); $page->param(name => $recdata->{host}); $page->param(address => $recdata->{val}); $page->param(distance => $recdata->{distance}); $page->param(weight => $recdata->{weight}); $page->param(port => $recdata->{port}); $page->param(ttl => $recdata->{ttl}); fill_rectypes($recdata->{type}); } elsif ($webvar{recact} eq 'update') { changepage(page => "reclist", errmsg => "You are not permitted to edit records", id => $webvar{parentid}) unless ($permissions{admin} || $permissions{record_edit}); my ($code,$msg) = updateRec($dbh,$webvar{defrec},$webvar{id}, $webvar{name},$webvar{type},$webvar{address},$webvar{ttl}, $webvar{distance},$webvar{weight},$webvar{port}); if ($code eq 'OK') { ##fixme: need more magic to get proper group - if domain was fiddled # from search-subgroups listing, may not be "current" group # SELECT d.group_id FROM domains d INNER JOIN records r ON d.domain_id=r.domain_id WHERE r.record_id=? # $sth->execute($webvar{id}); ##log if ($webvar{defrec} eq 'y') { logaction(0, $session->param("username"), $webvar{parentid}, "Updated default record '$webvar{name} $typemap{$webvar{type}} $webvar{address}', TTL $webvar{ttl}"); } else { logaction($webvar{parentid}, $session->param("username"), parentID($webvar{id}, 'rec', 'group'), "Updated record '$webvar{name} $typemap{$webvar{type}} $webvar{address}', TTL $webvar{ttl}"); } changepage(page => "reclist", id => $webvar{parentid}, defrec => $webvar{defrec}); } else { $page->param(failed => 1); $page->param(errmsg => $msg); $page->param(wastrying => "updating"); $page->param(todo => "Update record"); $page->param(recact => "update"); $page->param(parentid => $webvar{parentid}); $page->param(defrec => $webvar{defrec}); $page->param(id => $webvar{id}); fill_recdata(); if ($webvar{defrec} eq 'y') { logaction(0, $session->param("username"), $webvar{parentid}, "Failed updating default record '$typemap{$webvar{type}} $webvar{name} $webvar{address}', TTL $webvar{ttl} ($msg)"); } else { logaction($webvar{parentid}, $session->param("username"), parentID($webvar{parentid}, 'dom', 'group'), "Failed updating record '$typemap{$webvar{type}} $webvar{name} $webvar{address}', TTL $webvar{ttl} ($msg)"); } } } if ($webvar{defrec} eq 'y') { $page->param(dohere => "default records in group ".groupName($dbh,$webvar{parentid})); } else { $page->param(parentid => $webvar{parentid}); $page->param(dohere => domainName($dbh,$webvar{parentid})); } } elsif ($webvar{page} eq 'delrec') { # This is a complete separate segment since it uses a different template from add/edit records above changepage(page => "reclist", errmsg => "You are not permitted to delete records", id => $webvar{parentid}) unless ($permissions{admin} || $permissions{record_delete}); $page->param(id => $webvar{id}); $page->param(defrec => $webvar{defrec}); $page->param(parentid => $webvar{parentid}); # first pass = confirm y/n (sorta) if (!defined($webvar{del})) { $page->param(del_getconf => 1); my $rec = getRecLine($dbh,$webvar{defrec},$webvar{id}); $page->param(host => $rec->{host}); $page->param(ftype => $typemap{$rec->{type}}); $page->param(recval => $rec->{val}); } elsif ($webvar{del} eq 'ok') { # get rec data before we try to delete it my $rec = getRecLine($dbh,$webvar{defrec},$webvar{id}); my ($code,$msg) = delRec($dbh,$webvar{defrec},$webvar{id}); if ($code ne 'OK') { ## need to find failure mode if ($webvar{defrec} eq 'y') { logaction(0, $session->param("username"), $rec->{parid}, "Failed deleting default record '$rec->{host} $typemap{$rec->{type}} $rec->{val}',". " TTL $rec->{ttl} ($msg)"); } else { logaction($rec->{parid}, $session->param("username"), parentID($rec->{parid}, 'dom', 'group'), "Failed deleting record '$rec->{host} $typemap{$rec->{type}} $rec->{val}', TTL $rec->{ttl} ($msg)"); } changepage(page => "reclist", id => $webvar{parentid}, defrec => $webvar{defrec}, errmsg => "Error deleting record: $msg"); # $page->param(del_failed => 1); # $page->param(errmsg => $msg); # showdomain($webvar{defrec}, $webvar{parentid}); } else { if ($webvar{defrec} eq 'y') { logaction(0, $session->param("username"), $rec->{parid}, "Deleted default record '$rec->{host} $typemap{$rec->{type}} $rec->{val}', TTL $rec->{ttl}"); } else { logaction($rec->{parid}, $session->param("username"), parentID($rec->{parid}, 'dom', 'group'), "Deleted record '$rec->{host} $typemap{$rec->{type}} $rec->{val}', TTL $rec->{ttl}"); } changepage(page => "reclist", id => $webvar{parentid}, defrec => $webvar{defrec}); } } else { changepage(page => "reclist", id => $webvar{parentid}, defrec => $webvar{defrec}); } } elsif ($webvar{page} eq 'editsoa') { changepage(page => "reclist", errmsg => "You are not permitted to edit domain SOA records", id => $webvar{id}) unless ($permissions{admin} || $permissions{domain_edit}); fillsoa($webvar{defrec},$webvar{id}); } elsif ($webvar{page} eq 'updatesoa') { changepage(page => "reclist", errmsg => "You are not permitted to edit domain SOA records", id => $webvar{id}) unless ($permissions{admin} || $permissions{domain_edit}); my $sth; my $sql = ''; # no domain ID, so we're editing the default SOA for a group (we don't care which one here) # plus a bit of magic to update the appropriate table $sql = "update ".($webvar{defrec} eq 'y' ? "default_records" : "records"). " set host='$webvar{prins}:$webvar{contact}',". " val='$webvar{refresh}:$webvar{retry}:$webvar{expire}:$webvar{minttl}',". " ttl=$webvar{ttl} where record_id=$webvar{recid}"; $sth = $dbh->prepare($sql); $sth->execute; if ($sth->err) { $page->param(update_failed => 1); $page->param(msg => $DBI::errstr); fillsoa($webvar{defrec},$webvar{id}); } else { ##fixme! need to set group ID properly here # SELECT group_id FROM domains WHERE domain_id=? # $sth->execute($webvar{id}); ##log logaction(0, $session->param("username"), $webvar{group}, "Updated SOA (ns $webvar{prins}, contact $webvar{contact}, refresh $webvar{refresh},". " retry $webvar{retry}, expire $webvar{expire}, minTTL $webvar{minttl}, TTL $webvar{ttl}"); changepage(page => "reclist", id => $webvar{id}, defrec => $webvar{defrec}); # $page->param(update_failed => 0); # showdomain('y',1); } } elsif ($webvar{page} eq 'grpman') { listgroups(); $page->param(curpage => $webvar{page}); } elsif ($webvar{page} eq 'newgrp') { changepage(page => "grpman", errmsg => "You are not permitted to add groups", id => $webvar{parentid}) unless ($permissions{admin} || $permissions{group_add}); # do.. uhh.. stuff.. if we have no webvar{action} if ($webvar{action} && $webvar{action} eq 'add') { my %newperms; foreach (@permtypes) { $newperms{$_} = 0; $newperms{$_} = (defined($webvar{$_}) && $webvar{$_} eq 'on' ? 1 : 0); } # not gonna provide the 4th param: template-or-clone flag, just yet my ($code,$msg) = addGroup($dbh, $webvar{newgroup}, $webvar{pargroup}, \%newperms); if ($code eq 'OK') { logaction(0, $session->param("username"), $webvar{pargroup}, "Added group $webvar{newgroup}"); changepage(page => "grpman"); } # no point in doing extra work fill_permissions($page, \%newperms); $page->param(add_failed => 1); $page->param(errmsg => $msg); $page->param(newgroup => $webvar{newgroup}); fill_grouplist('pargroup',$webvar{pargroup}); } else { fill_grouplist('pargroup',$curgroup); # fill default permissions with immediate parent's current ones my %parperms; getPermissions($dbh, 'group', $curgroup, \%parperms); fill_permissions($page, \%parperms); } } elsif ($webvar{page} eq 'delgrp') { changepage(page => "grpman", errmsg => "You are not permitted to delete groups", id => $webvar{parentid}) unless ($permissions{admin} || $permissions{group_delete}); $page->param(id => $webvar{id}); # first pass = confirm y/n (sorta) if (!defined($webvar{del})) { $page->param(del_getconf => 1); # $page->param(groupname => groupName($dbh,$webvar{id})); # print some neato things? # } else { # #whether actually deleting or cancelling we redirect to the group list, default format } elsif ($webvar{del} eq 'ok') { my $deleteme = groupName($dbh,$webvar{id}); # get this before we delete it... my ($code,$msg) = delGroup($dbh, $webvar{id}); if ($code ne 'OK') { # need to find failure mode logaction(0, $session->param("username"), $webvar{curgroup}, "Failure deleting group $deleteme: $msg"); changepage(page => "grpman", del_failed => 1, errmsg => $msg); } else { ##fixme: need to clean up log when deleting a major container logaction(0, $session->param("username"), $webvar{curgroup}, "Deleted group $deleteme"); # success. go back to the domain list, do not pass "GO" changepage(page => "grpman"); } } else { # cancelled. whee! changepage(page => "grpman"); } $page->param(delgroupname => groupName($dbh, $webvar{id})); } elsif ($webvar{page} eq 'edgroup') { changepage(page => "grpman", errmsg => "You are not permitted to edit groups", id => $webvar{parentid}) unless ($permissions{admin} || $permissions{group_edit}); if ($webvar{action} eq 'updperms') { # extra safety check; make sure user can't construct a URL to bypass ACLs my %curperms; getPermissions($dbh, 'group', $webvar{gid}, \%curperms); my %chperms; foreach (@permtypes) { $webvar{$_} = 0 if !defined($webvar{$_}); $webvar{$_} = 1 if $webvar{$_} eq 'on'; $chperms{$_} = $webvar{$_} if $curperms{$_} ne $webvar{$_}; } my ($code,$msg) = changePermissions($dbh, 'group', $webvar{gid}, \%chperms); if ($code eq 'OK') { logaction(0, $session->param("username"), $webvar{gid}, "Changed default permissions in group $webvar{gid}"); changepage(page => "grpman"); } # no point in doing extra work fill_permissions($page, \%chperms); $page->param(errmsg => $msg); } $page->param(gid => $webvar{gid}); $page->param(grpmeddle => groupName($dbh, $webvar{gid})); my %grpperms; getPermissions($dbh, 'group', $webvar{gid}, \%grpperms); fill_permissions($page, \%grpperms); } elsif ($webvar{page} eq 'bulkdomain') { # Bulk operations on domains. Note all but group move are available on the domain list. changepage(page => "domlist", errmsg => "You are not permitted to make bulk domain changes") unless ($permissions{admin} || $permissions{domain_edit} || $permissions{domain_create} || $permissions{domain_delete}); fill_grouplist("grouplist"); ##fixme ##fixme push the SQL and direct database fiddling off into a sub in DNSDB.pm ##fixme ##fixme: un-hardcode the limit? # $perpage = 50; my $sth = $dbh->prepare("SELECT count(*) FROM domains WHERE group_id=?"); $sth->execute($curgroup); my ($count) = ($sth->fetchrow_array); $page->param(curpage => $webvar{page}); fill_pgcount($count,'domains',groupName($dbh,$curgroup)); fill_fpnla($count); $page->param(offset => $offset); # since apparently this isn't set explicitly elsewhere. Who knew? $page->param(perpage => $perpage); my @domlist; my $sql = "SELECT domain_id,domain FROM domains". " WHERE group_id=?". " ORDER BY domain". ($offset eq 'all' ? '' : " LIMIT $perpage OFFSET ".$offset*$perpage); $sth = $dbh->prepare($sql); $sth->execute($curgroup); my $rownum = 0; while (my @data = $sth->fetchrow_array) { my %row; $row{domid} = $data[0]; $row{domain} = $data[1]; $rownum++; # putting this in the expression below causes failures. *eyeroll* $row{newrow} = $rownum % 5 == 0; push @domlist, \%row; } $page->param(domtable => \@domlist); # ACLs $page->param(maymove => ($permissions{admin} || ($permissions{domain_edit} && $permissions{domain_create} && $permissions{domain_delete}))); $page->param(maystatus => $permissions{admin} || $permissions{domain_edit}); $page->param(maydelete => $permissions{admin} || $permissions{domain_delete}); } elsif ($webvar{page} eq 'bulkchange') { if ($webvar{action} eq 'move') { changepage(page => "domlist", errmsg => "You are not permitted to bulk-move domains") unless ($permissions{admin} || ($permissions{domain_edit} && $permissions{domain_create} && $permissions{domain_delete})); my $newgname = groupName($dbh,$webvar{destgroup}); $page->param(action => "Move to group $newgname"); my @bulkresults; # nngh. due to alpha-sorting on the previous page, we can't use domid-numeric # order here, and since we don't have the domain names until we go around this # loop, we can't alpha-sort them here. :( foreach (keys %webvar) { my %row; next unless $_ =~ /^dom_\d+$/; $row{domain} = domainName($dbh,$webvar{$_}); my ($code, $msg) = changeGroup($dbh, 'domain', $webvar{$_}, $webvar{destgroup}); if ($code eq 'OK') { logaction($webvar{$_}, $session->param("username"), parentID($webvar{$_}, 'dom', 'group'), "Moved domain ".domainName($dbh, $webvar{$_})." to group $newgname"); $row{domok} = ($code eq 'OK'); } else { logaction($webvar{$_}, $session->param("username"), parentID($webvar{$_}, 'dom', 'group'), "Failure moving domain ".domainName($dbh, $webvar{$_})." to group $newgname: $msg"); } $row{domerr} = $msg; push @bulkresults, \%row; } $page->param(bulkresults => \@bulkresults); } elsif ($webvar{action} eq 'deactivate' || $webvar{action} eq 'activate') { changepage(page => "domlist", errmsg => "You are not permitted to bulk-$webvar{action} domains") unless ($permissions{admin} || $permissions{domain_edit}); $page->param(action => "$webvar{action} domains"); my @bulkresults; foreach (keys %webvar) { my %row; next unless $_ =~ /^dom_\d+$/; $row{domain} = domainName($dbh,$webvar{$_}); ##fixme: error handling on status change my $stat = domStatus($dbh,$webvar{$_},($webvar{action} eq 'activate' ? 'domon' : 'domoff')); logaction($webvar{$_}, $session->param("username"), parentID($webvar{$_}, 'dom', 'group'), "Changed domain ".domainName($dbh, $webvar{$_})." state to ".($stat ? 'active' : 'inactive')); $row{domok} = 1; # $row{domok} = ($code eq 'OK'); # $row{domerr} = $msg; push @bulkresults, \%row; } $page->param(bulkresults => \@bulkresults); } elsif ($webvar{action} eq 'delete') { changepage(page => "domlist", errmsg => "You are not permitted to bulk-delete domains") unless ($permissions{admin} || $permissions{domain_delete}); $page->param(action => "$webvar{action} domains"); my @bulkresults; foreach (keys %webvar) { my %row; next unless $_ =~ /^dom_\d+$/; $row{domain} = domainName($dbh,$webvar{$_}); my $pargroup = parentID($webvar{$_}, 'dom', 'group'); my $dom = domainName($dbh, $webvar{$_}); my ($code, $msg) = delDomain($dbh, $webvar{$_}); if ($code eq 'OK') { logaction($webvar{$_}, $session->param("username"), $pargroup, "Deleted domain $dom"); $row{domok} = ($code eq 'OK'); } else { logaction($webvar{$_}, $session->param("username"), $pargroup, "Failure deleting domain $dom: $msg"); } $row{domerr} = $msg; push @bulkresults, \%row; } $page->param(bulkresults => \@bulkresults); } # move/(de)activate/delete if() # not going to handle the unknown $webvar{action} else; it should not be possible in normal # operations, and anyone who meddles with the URL gets what they deserve. } elsif ($webvar{page} eq 'useradmin') { if (defined($webvar{action})) { userStatus($dbh,$webvar{id},$webvar{action}); } $page->param(curpage => $webvar{page}); list_users(); } elsif ($webvar{page} eq 'user') { # All user add/edit actions fall through the same page, since there aren't # really any hard differences between the templates #fill_actypelist($webvar{accttype}); fill_clonemelist(); my %grpperms; getPermissions($dbh, 'group', $curgroup, \%grpperms); my $grppermlist = new HTML::Template(filename => "$templatedir/permlist.tmpl"); my %noaccess; fill_permissions($grppermlist, \%grpperms, \%noaccess); $grppermlist->param(info => 1); $page->param(grpperms => $grppermlist->output); $page->param(is_admin => $permissions{admin}); $webvar{action} = '' if !$webvar{action}; if ($webvar{action} eq 'add' or $webvar{action} eq 'update') { $page->param(add => 1) if $webvar{action} eq 'add'; my ($code,$msg); my $alterperms = 0; # flag iff we need to force custom permissions due to user's current access limits my %newperms; # we're going to prefill the existing permissions, so we can change them. getPermissions($dbh, 'user', $webvar{uid}, \%newperms); if ($webvar{pass1} ne $webvar{pass2}) { $code = 'FAIL'; $msg = "Passwords don't match"; } else { # assemble a permission string - far simpler than trying to pass an # indeterminate set of permission flags individually # But first, we have to see if the user can add any particular # permissions; otherwise we have a priviledge escalation. Whee. if (!$permissions{admin}) { my %grpperms; getPermissions($dbh, 'group', $curgroup, \%grpperms); my $ret = comparePermissions(\%permissions, \%grpperms); if ($ret ne '<' && $ret ne '!') { # User's permissions are not a superset or equivalent to group. Can't inherit # (and include access user doesn't currently have), so we force custom. $webvar{perms_type} = 'custom'; $alterperms = 1; } } my $permstring; if ($webvar{perms_type} eq 'custom') { $permstring = 'C:'; foreach (@permtypes) { if ($permissions{admin} || $permissions{$_}) { $permstring .= ",$_" if defined($webvar{$_}) && $webvar{$_} eq 'on'; $newperms{$_} = (defined($webvar{$_}) && $webvar{$_} eq 'on' ? 1 : 0); } } $page->param(perm_custom => 1); } elsif ($permissions{admin} && $webvar{perms_type} eq 'clone') { $permstring = "c:$webvar{clonesrc}"; getPermissions($dbh, 'user', $webvar{clonesrc}, \%newperms); $page->param(perm_clone => 1); } else { $permstring = 'i'; } if ($webvar{action} eq 'add') { ($code,$msg) = addUser($dbh, $webvar{uname}, $curgroup, $webvar{pass1}, ($webvar{makeactive} eq 'on' ? 1 : 0), $webvar{accttype}, $permstring, $webvar{fname}, $webvar{lname}, $webvar{phone}); logaction(0, $session->param("username"), $curgroup, "Added user $webvar{uname} (uid $msg)") if $code eq 'OK'; } else { # User update is icky. I'd really like to do this in one atomic # operation, but that would duplicate a **lot** of code in DNSDB.pm # Allowing for changing group, but not coding web support just yet. ($code,$msg) = updateUser($dbh, $webvar{uid}, $webvar{uname}, $webvar{gid}, $webvar{pass1}, ($webvar{makeactive} eq 'on' ? 1 : 0), $webvar{accttype}, $webvar{fname}, $webvar{lname}, $webvar{phone}); if ($code eq 'OK') { $newperms{admin} = 1 if $webvar{accttype} eq 'S'; ($code,$msg) = changePermissions($dbh, 'user', $webvar{uid}, \%newperms, ($permstring eq 'i')); } logaction(0, $session->param("username"), $curgroup, "Updated uid $webvar{uid}, user $webvar{uname} ($webvar{fname} $webvar{lname})"); } } if ($code eq 'OK') { if ($alterperms) { changepage(page => "useradmin", warnmsg => "You can only grant permissions you hold. $webvar{uname} ". ($webvar{action} eq 'add' ? 'added' : 'updated')." with reduced access."); } else { changepage(page => "useradmin"); } # add/update failed: } else { $page->param(add_failed => 1); $page->param(action => $webvar{action}); $page->param(set_permgroup => 1); if ($webvar{perms_type} eq 'inherit') { # set permission class radio $page->param(perm_inherit => 1); } elsif ($webvar{perms_type} eq 'clone') { $page->param(perm_clone => 1); } else { $page->param(perm_custom => 1); } $page->param(uname => $webvar{uname}); $page->param(fname => $webvar{fname}); $page->param(lname => $webvar{lname}); $page->param(pass1 => $webvar{pass1}); $page->param(pass2 => $webvar{pass2}); $page->param(errmsg => $msg); fill_permissions($page, \%newperms); fill_actypelist($webvar{accttype}); fill_clonemelist(); ##fixme: log } } elsif ($webvar{action} eq 'edit') { $page->param(set_permgroup => 1); $page->param(action => 'update'); $page->param(uid => $webvar{user}); fill_clonemelist(); my $userinfo = getUserData($dbh,$webvar{user}); fill_actypelist($userinfo->{type}); # not using this yet, but adding it now means we can *much* more easily do so later. $page->param(gid => $webvar{group_id}); my %curperms; getPermissions($dbh, 'user', $webvar{user}, \%curperms); fill_permissions($page, \%curperms); $page->param(uname => $userinfo->{username}); $page->param(fname => $userinfo->{firstname}); $page->param(lname => $userinfo->{lastname}); $page->param(set_permgroup => 1); if ($userinfo->{inherit_perm}) { $page->param(perm_inherit => 1); } else { $page->param(perm_custom => 1); } ##work # } elsif ($webvar{action} eq 'update') { } else { # default is "new" $page->param(add => 1); $page->param(action => 'add'); fill_permissions($page, \%grpperms); fill_actypelist(); } } elsif ($webvar{page} eq 'newuser') { # foo? fill_actypelist(); fill_clonemelist(); my %grpperms; getPermissions($dbh, 'group', $curgroup, \%grpperms); fill_permissions($page, \%grpperms); my $grppermlist = new HTML::Template(filename => "$templatedir/permlist.tmpl"); my %noaccess; fill_permissions($grppermlist, \%grpperms, \%noaccess); $grppermlist->param(info => 1); $page->param(grpperms => $grppermlist->output); #} elsif ($webvar{page} eq 'adduser') { # # my ($code,$msg); # # if ($webvar{pass1} ne $webvar{pass2}) { # $code = 'FAIL'; # $msg = "Passwords don't match"; # } else { ## assemble a permission string - far simpler than trying to pass an ## indeterminate set of permission flags individually #my $permstring; #if ($webvar{perms_type} eq 'custom') { # $permstring = 'C:,g:,u:,d:,r:'; # $page->param(perm_custom => 1); #} elsif ($webvar{perms_type} eq 'clone') { # $permstring = 'c:'; # $page->param(perm_clone => 1); #} else { # $permstring = 'i'; ## $page->param(perm_inherit => 1); #} # ($code,$msg) = addUser($dbh,$webvar{uname}, $webvar{group}, $webvar{pass1}, # ($webvar{makeactive} eq 'on' ? 1 : 0), $webvar{accttype}, # $webvar{fname}, $webvar{lname}, $webvar{phone}); # } # ## hokay, a bit of magic to decide which page we hit. # if ($code eq 'OK') { ###log # logaction(0, $session->param("username"), $webvar{group}, # "Added user $webvar{uname} ($webvar{fname} $webvar{lname})"); # changepage(page => "useradmin"); # } else { ## oddity - apparently, xhtml 1.0 strict swallows username as an HTML::Template var. O_o # $page->param(add_failed => 1); # $page->param(uname => $webvar{uname}); # $page->param(fname => $webvar{fname}); # $page->param(lname => $webvar{lname}); # $page->param(pass1 => $webvar{pass1}); # $page->param(pass2 => $webvar{pass2}); # $page->param(errmsg => $msg); # fill_actypelist($webvar{accttype}); # fill_clonemelist(); # } # ## $page->param(add_failed => 1); # } elsif ($webvar{page} eq 'deluser') { $page->param(id => $webvar{id}); # first pass = confirm y/n (sorta) if (!defined($webvar{del})) { $page->param(del_getconf => 1); $page->param(user => userFullName($dbh,$webvar{id})); } elsif ($webvar{del} eq 'ok') { ##fixme: find group id user is in (for logging) *before* we delete the user ##fixme: get other user data too for log my $userref = getUserData($dbh, $webvar{id}); my ($code,$msg) = delUser($dbh, $webvar{id}); if ($code ne 'OK') { # need to find failure mode $page->param(del_failed => 1); $page->param(errmsg => $msg); list_users($curgroup); } else { # success. go back to the user list, do not pass "GO" # actions on users have a domain id of 0, always logaction(0, $session->param("username"), $curgroup, "Deleted user $webvar{id}/".$userref->{username}. " (".$userref->{lastname}.", ".$userref->{firstname}.")"); changepage(page => "useradmin"); } } else { # cancelled. whee! changepage(page => "useradmin"); } #} elsif ($webvar{page} eq 'edituser') { } elsif ($webvar{page} eq 'dnsq') { $page->param(qfor => $webvar{qfor}) if $webvar{qfor}; fill_rectypes($webvar{type} ? $webvar{type} : '', 1); $page->param(nrecurse => $webvar{nrecurse}) if $webvar{nrecurse}; $page->param(resolver => $webvar{resolver}) if $webvar{resolver}; if ($webvar{qfor}) { my $resolv = Net::DNS::Resolver->new; $resolv->tcp_timeout(5); # make me adjustable! $resolv->udp_timeout(5); # make me adjustable! $resolv->recurse(0) if $webvar{nrecurse}; $resolv->nameservers($webvar{resolver}) if $webvar{resolver}; my $query = $resolv->query($webvar{qfor}, $typemap{$webvar{type}}); if ($query) { $page->param(showresults => 1); my @answer; foreach my $rr ($query->answer) { # next unless $rr->type eq "A" or $rr->type eq 'NS'; my %row; my ($host,$ttl,$class,$type,$data) = ($rr->string =~ /^([0-9a-zA-Z_.-]+)\s+(\d+)\s+([A-Za-z]+)\s+([A-Za-z]+)\s+(.+)$/s); $row{host} = $host; $row{ftype} = $type; $row{rdata} = ($type eq 'SOA' ? "
$data
" : $data); push @answer, \%row; } $page->param(answer => \@answer); my @additional; foreach my $rr ($query->additional) { # next unless $rr->type eq "A" or $rr->type eq 'NS'; my %row; my ($host,$ttl,$class,$type,$data) = ($rr->string =~ /^([0-9a-zA-Z_.-]+)\s+(\d+)\s+([A-Za-z]+)\s+([A-Za-z]+)\s+(.+)$/); $row{host} = $host; $row{ftype} = $type; $row{rdata} = $data; push @additional, \%row; } $page->param(additional => \@additional); my @authority; foreach my $rr ($query->authority) { # next unless $rr->type eq "A" or $rr->type eq 'NS'; my %row; my ($host,$ttl,$class,$type,$data) = ($rr->string =~ /^([0-9a-zA-Z_.-]+)\s+(\d+)\s+([A-Za-z]+)\s+([A-Za-z]+)\s+(.+)$/); $row{host} = $host; $row{ftype} = $type; $row{rdata} = $data; push @authority, \%row; } $page->param(authority => \@authority); $page->param(usedresolver => $resolv->answerfrom); $page->param(frtype => $typemap{$webvar{type}}); } else { $page->param(errmsg => $resolv->errorstring); } } ## done DNS query } elsif ($webvar{page} eq 'axfr') { changepage(page => "domlist", errmsg => "You are not permitted to import domains") unless ($permissions{admin} || $permissions{domain_create}); # don't need this while we've got the dropdown in the menu. hmm. fill_grouplist("grouplist"); $page->param(ifrom => $webvar{ifrom}) if $webvar{ifrom}; $page->param(rwsoa => $webvar{rwsoa}) if $webvar{rwsoa}; $page->param(rwns => $webvar{rwns}) if $webvar{rwns}; $page->param(dominactive => 1) if (!$webvar{domactive} && $webvar{doit}); # eww. $page->param(importdoms => $webvar{importdoms}) if $webvar{importdoms}; # shut up warning about uninitialized variable $webvar{doit} = '' if !defined($webvar{doit}); if ($webvar{doit} eq 'y' && !$webvar{ifrom}) { $page->param(errmsg => "Need to set host to import from"); } elsif ($webvar{doit} eq 'y' && !$webvar{importdoms}) { $page->param(errmsg => "Need domains to import"); } elsif ($webvar{doit} eq 'y') { my @domlist = split /\s+/, $webvar{importdoms}; my @results; foreach my $domain (@domlist) { my %row; my ($code,$msg) = importAXFR($dbh, $webvar{ifrom}, $domain, $webvar{group}, $webvar{domstatus}, $webvar{rwsoa}, $webvar{rwns}); $row{domok} = $msg if $code eq 'OK'; if ($code eq 'WARN') { $msg =~ s|\n|
|g; $row{domwarn} = $msg; } if ($code eq 'FAIL') { $msg =~ s|\n|
\n|g; $row{domerr} = $msg; } $msg = "
\n".$msg if $msg =~ m|
|; logaction(domainID($dbh, $domain), $session->param("username"), $webvar{group}, "AXFR import $domain from $webvar{ifrom} ($code): $msg"); $row{domain} = $domain; push @results, \%row; } $page->param(axfrresults => \@results); } } elsif ($webvar{page} eq 'whoisq') { if ($webvar{qfor}) { use Net::Whois::Raw; use Text::Wrap; # caching useful? #$Net::Whois::Raw::CACHE_DIR = "/var/spool/pwhois/"; #$Net::Whois::Raw::CACHE_TIME = 60; my ($dominfo, $whois_server) = whois($webvar{qfor}); ##fixme: if we're given an IP, try rwhois as well as whois so we get the real final data # le sigh. idjits spit out data without linefeeds... $Text::Wrap::columns = 88; # &%$@%@# high-bit crap. We should probably find a way to properly recode these # instead of one-by-one. Note CGI::Simple's escapeHTML() doesn't do more than # the bare minimum. :/ # Mainly an XHTML validation thing. $dominfo = $q->escapeHTML($dominfo); $dominfo =~ s/\xa9/\©/g; $dominfo =~ s/\xae/\®/g; $page->param(qfor => $webvar{qfor}); $page->param(dominfo => wrap('','',$dominfo)); $page->param(whois_server => $whois_server); } else { $page->param(errmsg => "Missing host or domain to query in WHOIS") if $webvar{askaway}; } } elsif ($webvar{page} eq 'log') { ##fixme put in some real log-munching stuff ##fixme need to add bits to *create* log entries... my $sql = "SELECT user_id, email, name, entry, date_trunc('second',stamp) FROM log WHERE "; my $id = $curgroup; # we do this because the group log may be called from (almost) any page, # but the others are much more limited. this is probably non-optimal. if ($webvar{ltype} && $webvar{ltype} eq 'user') { $sql .= "user_id=?"; $id = $webvar{id}; $page->param(logfor => 'user '.userFullName($dbh,$id)); } elsif ($webvar{ltype} && $webvar{ltype} eq 'dom') { $sql .= "domain_id=?"; $id = $webvar{id}; $page->param(logfor => 'domain '.domainName($dbh,$id)); } else { # Default to listing curgroup log $sql .= "group_id=?"; $page->param(logfor => 'group '.groupName($dbh,$id)); } my $sth = $dbh->prepare($sql); $sth->execute($id); my @logbits; while (my ($uid, $email, $name, $entry, $stamp) = $sth->fetchrow_array) { my %row; $row{userfname} = $name; $row{userid} = $uid; $row{useremail} = $email; $row{logentry} = $entry; ($row{logtime}) = ($stamp =~ /^(.+)-\d\d$/); push @logbits, \%row; } $page->param(logentries => \@logbits); } # end $webvar{page} dance # start output here so we can redirect pages. print "Content-type: text/html\n\n", $header->output; ##common bits if ($webvar{page} ne 'login') { $page->param(username => $session->param("username")); $page->param(group => $curgroup); $page->param(groupname => groupName($dbh,$curgroup)); $page->param(logingrp => groupName($dbh,$logingroup)); $page->param(logingrp_num => $logingroup); $page->param(mayimport => $permissions{admin} || $permissions{domain_create}); $page->param(maybulk => $permissions{admin} || $permissions{domain_edit} || $permissions{domain_create} || $permissions{domain_delete}); # group tree. should go elsewhere, probably my $tmpgrplist = fill_grptree($logingroup,$curgroup); $page->param(grptree => $tmpgrplist); $page->param(subs => ($tmpgrplist ? 1 : 0)); # probably not useful to pass gobs of data in for a boolean $page->param(inlogingrp => $curgroup == $logingroup); # fill in the URL-to-self $page->param(whereami => $uri_self); } print "
\n";
foreach (@debugbits) { print; }
print "
\n"; # spit it out print $page->output; if ($debugenv) { print "
webvar keys:
\n";
  foreach my $key (keys %webvar) {
    print "key: $key\tval: $webvar{$key}\n";
  }
  print "
\nsession:\n
\n";
  my $sesdata = $session->dataref();
  foreach my $key (keys %$sesdata) {
    print "key: $key\tval: ".$sesdata->{$key}."\n";
  }
  print "
\nENV:\n
\n";
  foreach my $key (keys %ENV) {
    print "key: $key\tval: $ENV{$key}\n";
  }
  print "
\n"; } print $footer->output; # as per the docs, Just In Case $session->flush(); exit 0; sub fill_grptree { my $root = shift; my $cur = shift; my $indent = shift || ' '; my @childlist; my $grptree = HTML::Template->new(filename => 'templates/grptree.tmpl'); getChildren($dbh,$root,\@childlist,'immediate'); return if $#childlist == -1; my @grouplist; foreach (@childlist) { my %row; $row{grpname} = groupName($dbh,$_); $row{grpnum} = $_; $row{whereami} = $uri_self; # for all that HTML::Template is supposed to keep the HTML out of the Perl, this is so much more compact... # $row{grpdisp} = ($_ == $cur ? "$row{grpname}" : $row{grpname}); $row{curgrp} = ($_ == $cur); $row{expanded} = isParent($dbh, $_, 'group', $cur, 'group'); $row{expanded} = 1 if $_ == $cur; $row{subs} = fill_grptree($_,$cur,$indent.' '); $row{indent} = $indent; push @grouplist, \%row; } $grptree->param(indent => $indent); $grptree->param(treelvl => \@grouplist); return $grptree->output; } sub changepage { my %params = @_; # think this works the way I want... # handle user check my $newurl = "http://$ENV{HTTP_HOST}$ENV{SCRIPT_NAME}?sid=$sid"; foreach (keys %params) { $newurl .= "&$_=".$q->url_encode($params{$_}); } # Just In Case $session->flush(); print "Status: 302\nLocation: $newurl\n\n"; exit; } # end changepage sub fillsoa { my $def = shift; my $id = shift; my $domname = ($def eq 'y' ? '' : "DOMAIN"); $page->param(defrec => $def); # i had a good reason to do this when I wrote it... # $page->param(domain => $domname); # $page->param(group => $DNSDB::group); $page->param(isgrp => 1) if $def eq 'y'; $page->param(parent => ($def eq 'y' ? groupName($dbh, $DNSDB::group) : domainName($dbh, $id)) ); # defaults $page->param(defcontact => $DNSDB::def{contact}); $page->param(defns => $DNSDB::def{prins}); $page->param(defsoattl => $DNSDB::def{soattl}); $page->param(defrefresh => $DNSDB::def{refresh}); $page->param(defretry => $DNSDB::def{retry}); $page->param(defexpire => $DNSDB::def{expire}); $page->param(defminttl => $DNSDB::def{minttl}); # there are probably better ways to do this. TMTOWTDI. my %soa = getSOA($dbh,$def,$id); $page->param(id => $id); $page->param(recid => $soa{recid}); $page->param(prins => ($soa{prins} ? $soa{prins} : $DNSDB::def{prins})); $page->param(contact => ($soa{contact} ? $soa{contact} : $DNSDB::def{contact})); $page->param(refresh => ($soa{refresh} ? $soa{refresh} : $DNSDB::def{refresh})); $page->param(retry => ($soa{retry} ? $soa{retry} : $DNSDB::def{retry})); $page->param(expire => ($soa{expire} ? $soa{expire} : $DNSDB::def{expire})); $page->param(minttl => ($soa{minttl} ? $soa{minttl} : $DNSDB::def{minttl})); $page->param(ttl => ($soa{ttl} ? $soa{ttl} : $DNSDB::def{soattl})); } sub showdomain { my $def = shift; my $id = shift; # get the SOA first my %soa = getSOA($dbh,$def,$id); $page->param(recid => $soa{recid}); $page->param(contact => $soa{contact}); $page->param(prins => $soa{prins}); $page->param(refresh => $soa{refresh}); $page->param(retry => $soa{retry}); $page->param(expire => $soa{expire}); $page->param(minttl => $soa{minttl}); $page->param(ttl => $soa{ttl}); $startwith = $session->param($webvar{page}.'startwith'); $filter = $session->param($webvar{page}.'filter'); my $foo2 = getDomRecs($dbh,$def,$id,$perpage,$webvar{offset},$sortby,$sortorder); my $row = 0; foreach my $rec (@$foo2) { $rec->{type} = $typemap{$rec->{type}}; $rec->{row} = $row % 2; $rec->{defrec} = $def; $rec->{sid} = $webvar{sid}; $rec->{id} = $id; $rec->{distance} = 'n/a' unless ($rec->{type} eq 'MX' || $rec->{type} eq 'SRV'); $rec->{weight} = 'n/a' unless ($rec->{type} eq 'SRV'); $rec->{port} = 'n/a' unless ($rec->{type} eq 'SRV'); $row++; # ACLs $rec->{record_edit} = ($permissions{admin} || $permissions{record_edit}); $rec->{record_delete} = ($permissions{admin} || $permissions{record_delete}); } $page->param(reclist => $foo2); } # fill in record type list on add/update/edit record template sub fill_rectypes { my $type = shift || $reverse_typemap{A}; my $soaflag = shift || 0; my $sth = $dbh->prepare("SELECT val,name FROM rectypes WHERE stdflag=1 ORDER BY listorder"); $sth->execute; my @typelist; while (my ($rval,$rname) = $sth->fetchrow_array()) { my %row = ( recval => $rval, recname => $rname ); $row{tselect} = 1 if $rval == $type; push @typelist, \%row; } if ($soaflag) { my %row = ( recval => $reverse_typemap{SOA}, recname => 'SOA' ); $row{tselect} = 1 if $reverse_typemap{SOA} == $type; push @typelist, \%row; } $page->param(typelist => \@typelist); } # fill_rectypes sub fill_recdata { fill_rectypes($webvar{type}); # le sigh. we may get called with many empty %webvar keys no warnings qw( uninitialized ); ##todo: allow BIND-style bare names, ASS-U-ME that the name is within the domain? # prefill or DOMAIN in "Host" space for new records my $domroot = ($webvar{defrec} eq 'y' ? 'DOMAIN' : domainName($dbh,$webvar{parentid})); $page->param(name => $domroot); $page->param(address => $webvar{address}); $page->param(distance => $webvar{distance}) if ($webvar{type} == $reverse_typemap{MX} or $webvar{type} == $reverse_typemap{SRV}); $page->param(weight => $webvar{weight}) if $webvar{type} == $reverse_typemap{SRV}; $page->param(port => $webvar{port}) if $webvar{type} == $reverse_typemap{SRV}; # retrieve the right ttl instead of falling (way) back to the hardcoded system default my %soa = getSOA($dbh,$webvar{defrec},$webvar{parentid}); $page->param(ttl => ($webvar{ttl} ? $webvar{ttl} : $soa{minttl})); } sub fill_actypelist { my $curtype = shift || 'u'; my @actypes; my %row1 = (actypeval => 'u', actypename => 'user'); $row1{typesel} = 1 if $curtype eq 'u'; push @actypes, \%row1; my %row2 = (actypeval => 'S', actypename => 'superuser'); $row2{typesel} = 1 if $curtype eq 'S'; push @actypes, \%row2; $page->param(actypelist => \@actypes); } sub fill_clonemelist { my $sth = $dbh->prepare("SELECT username,user_id FROM users WHERE group_id=$curgroup"); $sth->execute; # shut up some warnings, but don't stomp on caller's state local $webvar{clonesrc} = 0 if !defined($webvar{clonesrc}); my @clonesrc; while (my ($username,$uid) = $sth->fetchrow_array) { my %row = ( username => $username, uid => $uid, selected => ($webvar{clonesrc} == $uid ? 1 : 0) ); push @clonesrc, \%row; } $page->param(clonesrc => \@clonesrc); } sub fill_fpnla { my $count = shift; if ($offset eq 'all') { $page->param(perpage => $perpage); # uhm.... } else { # all these bits only have sensible behaviour if offset is numeric. err, probably. if ($count > $perpage) { # if there are more results than the default, always show the "all" link $page->param(navall => 1); if ($offset > 0) { $page->param(navfirst => 1); $page->param(navprev => 1); $page->param(prevoffs => $offset-1); } # show "next" and "last" links if we're not on the last page of results if ( (($offset+1) * $perpage - $count) < 0 ) { $page->param(navnext => 1); $page->param(nextoffs => $offset+1); $page->param(navlast => 1); $page->param(lastoffs => int (($count-1)/$perpage)); } } else { $page->param(onepage => 1); } } } # end fill_fpnla() sub fill_pgcount { my $pgcount = shift; my $pgtype = shift; my $parent = shift; # Fix display/UI bug where if you are not on the first page of the list, and # you add a search term or click one of the "starts with" links, you end up # on a page showing nothing. # For bonus points, this reverts to the original offset on clicking the "All" link (mostly) $offset-- while ($offset * $perpage) >= $pgcount; $page->param(ntot => $pgcount); $page->param(nfirst => (($offset eq 'all' ? 0 : $offset)*$perpage+1)); $page->param(npglast => ($offset eq 'all' ? $pgcount : ( (($offset+1)*$perpage) > $pgcount ? $pgcount : (($offset+1)*$perpage) ) )); $page->param(pgtype => $pgtype); $page->param(parent => $parent); } # end fill_pgcount() sub listdomains { $startwith = $session->param($webvar{page}.'startwith'); $filter = $session->param($webvar{page}.'filter'); $searchsubs = $session->param($webvar{page}.'searchsubs'); # ACLs $page->param(domain_create => ($permissions{admin} || $permissions{domain_create}) ); $page->param(domain_edit => ($permissions{admin} || $permissions{domain_edit}) ); $page->param(domain_delete => ($permissions{admin} || $permissions{domain_delete}) ); ##fixme: $logingroup or $curgroup? my @childgroups; getChildren($dbh, $curgroup, \@childgroups, 'all') if $searchsubs; my $childlist = join(',',@childgroups); my $sql = "SELECT count(*) FROM domains WHERE group_id IN ($curgroup".($childlist ? ",$childlist" : '').")". ($startwith ? " AND domain ~* '^[$startwith]'" : ''). ($filter ? " AND domain ~* '$filter'" : ''); my $sth = $dbh->prepare($sql); $sth->execute; my ($count) = $sth->fetchrow_array; # fill page count and first-previous-next-last-all bits fill_pgcount($count,"domains",groupName($dbh,$curgroup)); fill_fpnla($count); # sort/order $session->param($webvar{page}.'sortby', $webvar{sortby}) if $webvar{sortby}; $session->param($webvar{page}.'order', $webvar{order}) if $webvar{order}; $sortby = $session->param($webvar{page}.'sortby') if $session->param($webvar{page}.'sortby'); $sortorder = $session->param($webvar{page}.'order') if $session->param($webvar{page}.'order'); # set up the headers my @cols = ('domain', 'status', 'group'); my %colheads = (domain => 'Domain', status => 'Status', group => 'Group'); fill_colheads($sortby, $sortorder, \@cols, \%colheads); # $page->param(sortorder => $sortorder); # hack! hack! pthbttt. have to rethink the status column storage, # or inactive comes "before" active. *sigh* $sortorder = ($sortorder eq 'ASC' ? 'DESC' : 'ASC') if $sortby eq 'status'; # waffle, waffle - keep state on these as well as sortby, sortorder? $page->param("start$startwith" => 1) if $startwith && $startwith =~ /^(?:[a-z]|0-9)$/; $page->param(filter => $filter) if $filter; $page->param(searchsubs => $searchsubs) if $searchsubs; ##fixme ##fixme push the SQL and direct database fiddling off into a sub in DNSDB.pm ##fixme $page->param(group => $curgroup); my @domlist; $sql = "SELECT domain_id,domain,status,groups.group_name AS group FROM domains". " INNER JOIN groups ON domains.group_id=groups.group_id". " WHERE domains.group_id IN ($curgroup".($childlist ? ",$childlist" : '').")". ##fixme: don't do variable subs in SQL, use placeholders and params in ->execute() ($startwith ? " AND domain ~* '^[$startwith]'" : ''). ($filter ? " AND domain ~* '$filter'" : ''). " ORDER BY ".($sortby eq 'group' ? 'groups.group_name' : $sortby). " $sortorder ".($offset eq 'all' ? '' : " LIMIT $perpage OFFSET ".$offset*$perpage); $sth = $dbh->prepare($sql); $sth->execute; my $rownum = 0; while (my @data = $sth->fetchrow_array) { my %row; $row{domainid} = $data[0]; $row{domain} = $data[1]; $row{status} = ($data[2] ? 'Active' : 'Inactive'); $row{group} = $data[3]; $row{bg} = ($rownum++)%2; # $row{mkactive} = ($data[2] eq 'inactive' ? 1 : 0); $row{mkactive} = !$data[2]; $row{sid} = $sid; $row{offset} = $offset; # ACLs $row{domain_edit} = ($permissions{admin} || $permissions{domain_edit}); $row{domain_delete} = ($permissions{admin} || $permissions{domain_delete}); ##fixme: need to clean up status indicator/usage/inversion push @domlist, \%row; } $page->param(domtable => \@domlist); } # end listdomains() sub listgroups { my @childgroups; getChildren($dbh, $logingroup, \@childgroups, 'all') if $searchsubs; my $childlist = join(',',@childgroups); my $sql = "SELECT count(*) FROM groups WHERE parent_group_id IN ($logingroup".($childlist ? ",$childlist" : '').")". ($startwith ? " AND group_name ~* '^[$startwith]'" : ''). ($filter ? " AND group_name ~* '$filter'" : ''); my $sth = $dbh->prepare($sql); $sth->execute; my ($count) = ($sth->fetchrow_array); # fill page count and first-previous-next-last-all bits ##fixme - hardcoded group bit fill_pgcount($count,"groups",''); fill_fpnla($count); $page->param(gid => $curgroup); $sortby = 'group'; # sort/order $session->param($webvar{page}.'sortby', $webvar{sortby}) if $webvar{sortby}; $session->param($webvar{page}.'order', $webvar{order}) if $webvar{order}; $sortby = $session->param($webvar{page}.'sortby') if $session->param($webvar{page}.'sortby'); $sortorder = $session->param($webvar{page}.'order') if $session->param($webvar{page}.'order'); # set up the headers my @cols = ('group','parent','nusers','ndomains'); my %colnames = (group => 'Group', parent => 'Parent Group', nusers => 'Users', ndomains => 'Domains'); fill_colheads($sortby, $sortorder, \@cols, \%colnames); # waffle, waffle - keep state on these as well as sortby, sortorder? $page->param("start$startwith" => 1) if $startwith && $startwith =~ /^(?:[a-z]|0-9)$/; $page->param(filter => $filter) if $filter; $page->param(searchsubs => $searchsubs) if $searchsubs; # munge sortby for columns in database $sortby = 'g.group_name' if $sortby eq 'group'; $sortby = 'g2.group_name' if $sortby eq 'parent'; my @grouplist; $sth = $dbh->prepare("SELECT g.group_id, g.group_name, g2.group_name, ". "count(distinct(u.username)) AS nusers, count(distinct(d.domain)) AS ndomains ". "FROM groups g ". "INNER JOIN groups g2 ON g2.group_id=g.parent_group_id ". "LEFT OUTER JOIN users u ON u.group_id=g.group_id ". "LEFT OUTER JOIN domains d ON d.group_id=g.group_id ". "WHERE g.parent_group_id IN ($logingroup".($childlist ? ",$childlist" : '').") ". ##fixme: don't do variable subs in SQL, use placeholders and params in ->execute() ($startwith ? " AND g.group_name ~* '^[$startwith]'" : ''). ($filter ? " AND g.group_name ~* '$filter'" : ''). " GROUP BY g.group_id, g.group_name, g2.group_name ". " ORDER BY $sortby $sortorder ". ($offset eq 'all' ? '' : " LIMIT $perpage OFFSET ".$offset*$perpage)); $sth->execute; my $rownum = 0; while (my @data = $sth->fetchrow_array) { my %row; $row{groupid} = $data[0]; $row{groupname} = $data[1]; $row{pgroup} = $data[2]; $row{nusers} = $data[3]; $row{ndomains} = $data[4]; $row{bg} = ($rownum++)%2; $row{sid} = $sid; push @grouplist, \%row; } $page->param(grouptable => \@grouplist); } # end listgroups() sub fill_grouplist { my $template_var = shift; my $cur = shift || $curgroup; my @childgroups; getChildren($dbh, $logingroup, \@childgroups, 'all'); my $childlist = join(',',@childgroups); ##fixme: need to reorder list so that we can display a pseudotree in group dropdowns # weesa gonna discard parent_group_id for now my $sth = $dbh->prepare("SELECT group_id,parent_group_id,group_name FROM groups ". "WHERE group_id IN ($logingroup".($childlist ? ",$childlist" : '').")". "ORDER BY group_id"); $sth->execute; my @grouplist; while (my ($groupid,$pargroup,$groupname) = $sth->fetchrow_array()) { my %row; $row{groupname} = $groupname; $row{groupval} = $groupid; ##fixme: need magic ## ... WTF? # $row{defgroup} = ''; $row{groupactive} = 1 if $groupid == $cur; push @grouplist, \%row; } $page->param("$template_var" => \@grouplist); } # end fill_grouplist() sub list_users { my @childgroups; getChildren($dbh, $curgroup, \@childgroups, 'all') if $searchsubs; my $childlist = join(',',@childgroups); my $sql = "SELECT count(*) FROM users WHERE group_id IN ($curgroup".($childlist ? ",$childlist" : '').")". ($startwith ? " AND username ~* '^[$startwith]'" : ''). ($filter ? " AND username ~* '$filter'" : ''); my $sth = $dbh->prepare($sql); $sth->execute; my ($count) = ($sth->fetchrow_array); # fill page count and first-previous-next-last-all bits ##fixme - hardcoded group bit fill_pgcount($count,"users",''); fill_fpnla($count); $sortby = 'user'; # sort/order $session->param($webvar{page}.'sortby', $webvar{sortby}) if $webvar{sortby}; $session->param($webvar{page}.'order', $webvar{order}) if $webvar{order}; $sortby = $session->param($webvar{page}.'sortby') if $session->param($webvar{page}.'sortby'); $sortorder = $session->param($webvar{page}.'order') if $session->param($webvar{page}.'order'); # set up the headers my @cols = ('user','fname','type','group','status'); my %colnames = (user => 'Username', fname => 'Full Name', type => 'Type', group => 'Group', status => 'Status'); fill_colheads($sortby, $sortorder, \@cols, \%colnames); # waffle, waffle - keep state on these as well as sortby, sortorder? $page->param("start$startwith" => 1) if $startwith && $startwith =~ /^(?:[a-z]|0-9)$/; $page->param(filter => $filter) if $filter; $page->param(searchsubs => $searchsubs) if $searchsubs; # munge sortby for columns in database $sortby = 'u.username' if $sortby eq 'user'; $sortby = 'u.type' if $sortby eq 'type'; $sortby = 'g.group_name' if $sortby eq 'group'; $sortby = 'u.status' if $sortby eq 'status'; my @userlist; $sql = "SELECT u.user_id, u.username, u.firstname || ' ' || u.lastname AS fname, u.type, g.group_name, u.status ". "FROM users u ". "INNER JOIN groups g ON u.group_id=g.group_id ". "WHERE u.group_id IN ($curgroup".($childlist ? ",$childlist" : '').")". ##fixme: don't do variable subs in SQL, use placeholders and params in ->execute() ($startwith ? " AND u.username ~* '^[$startwith]'" : ''). ($filter ? " AND u.username ~* '$filter'" : ''). " ORDER BY $sortby $sortorder ". ($offset eq 'all' ? '' : " LIMIT $perpage OFFSET ".$offset*$perpage); $sth = $dbh->prepare($sql); $sth->execute; my $rownum = 0; while (my @data = $sth->fetchrow_array) { no warnings "uninitialized"; # Just In Case something stupid happens and a user gets no first or last name my %row; $row{userid} = $data[0]; $row{username} = $data[1]; $row{userfull} = $data[2]; $row{usertype} = ($data[3] eq 'S' ? 'superuser' : "user"); $row{usergroup} = $data[4]; $row{active} = $data[5]; $row{bg} = ($rownum++)%2; $row{sid} = $sid; push @userlist, \%row; } $page->param(usertable => \@userlist); } # end list_users() # Generate all of the glop necessary to add or not the appropriate marker/flag for # the sort order and column in domain, user, group, and record lists # Takes an array ref and hash ref sub fill_colheads { my $sortby = shift; my $sortorder = shift; my $cols = shift; my $colnames = shift; my $custom = shift; my @headings; foreach my $col (@$cols) { my %coldata; $coldata{firstcol} = 1 if $col eq $cols->[0]; $coldata{sid} = $sid; $coldata{page} = $webvar{page}; $coldata{offset} = $webvar{offset} if $webvar{offset}; $coldata{sortby} = $col; $coldata{colname} = $colnames->{$col}; if ($col eq $sortby) { $coldata{order} = ($sortorder eq 'ASC' ? 'DESC' : 'ASC'); $coldata{sortorder} = $sortorder; } else { $coldata{order} = 'ASC'; } if ($custom) { foreach my $ckey (keys %$custom) { $coldata{$ckey} = $custom->{$ckey}; } } push @headings, \%coldata; } $page->param(colheads => \@headings); } # end fill_colheads() sub logaction { my $domid = shift; my $username = shift; my $groupid = shift; my $entry = shift; ##fixme: push SQL into DNSDB.pm ##fixme: add bits to retrieve group/domain name info to retain after entity is deleted? my $sth = $dbh->prepare("SELECT user_id, firstname || ' ' || lastname FROM users WHERE username=?"); $sth->execute($username); my ($user_id, $fullname) = $sth->fetchrow_array; $sth = $dbh->prepare("INSERT INTO log (domain_id,user_id,group_id,email,name,entry) ". "VALUES (?,?,?,?,?,?)") or warn $dbh->errstr; $sth->execute($domid,$user_id,$groupid,$username,$fullname,$entry) or warn $sth->errstr; } # end logaction() ##fixme: generalize to return appropriate id on all cases (ie, use $partype) sub parentID { my $id = shift; my $idtype = shift; my $partype = shift; my $defrec = shift || ''; my $sql = ''; if ($idtype eq 'dom') { return $id if $defrec eq 'y'; # "domain" + default records, we're really looking at a group. $sql = "SELECT group_id FROM domains WHERE domain_id=?"; } elsif ($idtype eq 'rec') { if ($defrec eq 'y') { $sql = "SELECT group_id FROM default_records WHERE record_id=?"; } else { return $sql = "SELECT d.group_id FROM domains d". " INNER JOIN records r ON d.domain_id=r.domain_id". " WHERE r.record_id=?"; } } elsif ($idtype eq 'group') { $sql = "SELECT parent_group_id FROM groups WHERE group_id=?"; } elsif ($idtype eq 'user') { $sql = "SELECT group_id FROM users WHERE user_id=?"; } else { return "FOO", "BAR"; # can't get here.... we think. } my $sth = $dbh->prepare($sql); $sth->execute($id); my ($retid) = $sth->fetchrow_array; return $retid if $retid; # ahh! fall of the edge of the world if things went sideways ##fixme: really need to do a little more error handling, I think } # end parentID() # we have to do this in a variety of places; let's make it consistent sub fill_permissions { my $template = shift; # may need to do several sets on a single page my $permset = shift; # hashref to permissions on object my $usercan = shift || \%permissions; # allow alternate user-is-allowed permission block foreach (@permtypes) { $template->param("may_$_" => ($usercan->{admin} || $usercan->{$_})); $template->param($_ => $permset->{$_}); } }