File:  [LON-CAPA] / loncom / auth / lonacc.pm
Revision 1.159.2.21: download - view: text, annotated - select for diffs
Sun Dec 12 00:53:57 2021 UTC (2 years, 5 months ago) by raeburn
Branches: version_2_11_X
CVS tags: version_2_11_4_uiuc, version_2_11_4_msu, version_2_11_4
- For 2.11
  Backport 1.189, 1.190, 1.191, 1.196, 1.199, 1.200 (part) 1.201, 1.202

    1: # The LearningOnline Network
    2: # Cookie Based Access Handler
    3: #
    4: # $Id: lonacc.pm,v 1.159.2.21 2021/12/12 00:53:57 raeburn Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: ###
   29: 
   30: =head1 NAME
   31: 
   32: Apache::lonacc - Cookie Based Access Handler
   33: 
   34: =head1 SYNOPSIS
   35: 
   36: Invoked (for various locations) by /etc/httpd/conf/srm.conf:
   37: 
   38:  PerlAccessHandler       Apache::lonacc
   39: 
   40: =head1 INTRODUCTION
   41: 
   42: This module enables cookie based authentication and is used
   43: to control access for many different LON-CAPA URIs.
   44: 
   45: Whenever the client sends the cookie back to the server, 
   46: this cookie is handled by either lonacc.pm or loncacc.pm
   47: (see srm.conf for what is invoked when).  If
   48: the cookie is missing or invalid, the user is re-challenged
   49: for login information.
   50: 
   51: This is part of the LearningOnline Network with CAPA project
   52: described at http://www.lon-capa.org.
   53: 
   54: =head1 HANDLER SUBROUTINE
   55: 
   56: This routine is called by Apache and mod_perl.
   57: 
   58: =over 4
   59: 
   60: =item *
   61: 
   62: transfer profile into environment
   63: 
   64: =item *
   65: 
   66: load POST parameters
   67: 
   68: =item *
   69: 
   70: check access
   71: 
   72: =item *
   73: 
   74: if allowed, get symb, log, generate course statistics if applicable
   75: 
   76: =item *
   77: 
   78: otherwise return error
   79: 
   80: =item *
   81: 
   82: see if public resource
   83: 
   84: =item *
   85: 
   86: store attempted access
   87: 
   88: =back
   89: 
   90: =head1 NOTABLE SUBROUTINES
   91: 
   92: =cut
   93: 
   94: 
   95: package Apache::lonacc;
   96: 
   97: use strict;
   98: use Apache::Constants qw(:common :http :methods);
   99: use Apache::File;
  100: use Apache::lonnet;
  101: use Apache::loncommon();
  102: use Apache::lonlocal;
  103: use Apache::restrictedaccess();
  104: use Apache::blockedaccess();
  105: use Fcntl qw(:flock);
  106: use LONCAPA qw(:DEFAULT :match);
  107: 
  108: sub cleanup {
  109:     my ($r)=@_;
  110:     if (! $r->is_initial_req()) { return DECLINED; }
  111:     &Apache::lonnet::save_cache();
  112:     return OK;
  113: }
  114: 
  115: sub goodbye {
  116:     my ($r)=@_;
  117:     &Apache::lonnet::goodbye();
  118:     return DONE;
  119: }
  120: 
  121: ###############################################
  122: 
  123: sub get_posted_cgi {
  124:     my ($r,$fields) = @_;
  125: 
  126:     my $buffer;
  127:     if ($r->header_in('Content-length')) {
  128: 	$r->read($buffer,$r->header_in('Content-length'),0);
  129:     }
  130:     my $content_type = $r->header_in('Content-type');
  131:     if ($content_type !~ m{^multipart/form-data}) {
  132: 	my @pairs=split(/&/,$buffer);
  133: 	my $pair;
  134: 	foreach $pair (@pairs) {
  135: 	    my ($name,$value) = split(/=/,$pair);
  136: 	    $value =~ tr/+/ /;
  137: 	    $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
  138: 	    $name  =~ tr/+/ /;
  139: 	    $name  =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
  140:             if (ref($fields) eq 'ARRAY') {
  141:                 next if (!grep(/^\Q$name\E$/,@{$fields}));
  142:             }
  143: 	    &Apache::loncommon::add_to_env("form.$name",$value);
  144: 	}
  145:     } else {
  146: 	my ($contentsep) = ($content_type =~ /boundary=\"?([^\";,]+)\"?/);
  147: 	my @lines = split (/\n/,$buffer);
  148: 	my $name='';
  149: 	my $value='';
  150: 	my $fname='';
  151: 	my $fmime='';
  152: 	my $i;
  153: 	for ($i=0;$i<=$#lines;$i++) {
  154: 	    if ($lines[$i]=~/^--\Q$contentsep\E/) {
  155: 		if ($name) {
  156:                     chomp($value);
  157:                     if (($r->uri eq '/adm/portfolio') && 
  158:                         ($name eq 'uploaddoc')) {
  159:                         if (length($value) == 1) {
  160:                             $value=~s/[\r\n]$//;
  161:                         }
  162:                     }
  163:                     if ($fname =~ /\.(xls|doc|ppt)(x|m)$/i) {
  164:                         $value=~s/[\r\n]$//;
  165:                     }
  166:                     if (ref($fields) eq 'ARRAY') {
  167:                         next if (!grep(/^\Q$name\E$/,@{$fields}));
  168:                     }
  169:                     if ($fname) {
  170:                         if ($env{'form.symb'} ne '') {
  171:                             my $size = (length($value))/(1024.0 * 1024.0);
  172:                             if (&upload_size_allowed($name,$size,$fname) eq 'ok') {
  173:                                 $env{"form.$name.filename"}=$fname;
  174:                                 $env{"form.$name.mimetype"}=$fmime;
  175:                                 &Apache::loncommon::add_to_env("form.$name",$value);
  176:                             }
  177:                         } else {
  178:                             $env{"form.$name.filename"}=$fname;
  179:                             $env{"form.$name.mimetype"}=$fmime;
  180:                             &Apache::loncommon::add_to_env("form.$name",$value);
  181:                         }
  182:                     } else {
  183:                         $value=~s/\s+$//s;
  184:                         &Apache::loncommon::add_to_env("form.$name",$value);
  185:                     }
  186: 		}
  187: 		if ($i<$#lines) {
  188: 		    $i++;
  189: 		    $lines[$i]=~
  190: 		/Content\-Disposition\:\s*form\-data\;\s*name\=\"([^\"]+)\"/i;
  191: 		    $name=$1;
  192: 		    $value='';
  193: 		    if ($lines[$i]=~/filename\=\"([^\"]+)\"/i) {
  194: 			$fname=$1;
  195: 			if 
  196:                             ($lines[$i+1]=~/Content\-Type\:\s*([\w\-\/]+)/i) {
  197: 				$fmime=$1;
  198: 				$i++;
  199: 			    } else {
  200: 				$fmime='';
  201: 			    }
  202: 		    } else {
  203: 			$fname='';
  204: 			$fmime='';
  205: 		    }
  206: 		    $i++;
  207: 		}
  208: 	    } else {
  209: 		$value.=$lines[$i]."\n";
  210: 	    }
  211: 	}
  212:     }
  213: #
  214: # Digested POSTed values
  215: #
  216: # Remember the way this was originally done (GET or POST)
  217: #
  218:     $env{'request.method'}=$ENV{'REQUEST_METHOD'};
  219: #
  220: # There may also be stuff in the query string
  221: # Tell subsequent handlers that this was GET, not POST, so they can access query string.
  222: # Also, unset POSTed content length to cover all tracks.
  223: #
  224: 
  225:     $r->method_number(M_GET);
  226: 
  227:     $r->method('GET');
  228:     $r->headers_in->unset('Content-length');
  229: }
  230: 
  231: =pod
  232: 
  233: =over
  234: 
  235: =item upload_size_allowed()
  236: 
  237: 	Perform size checks for file uploads to essayresponse items in course context.
  238: 	
  239: 	Add form.HWFILESIZE.$part_$id to %env with file size (MB)
  240: 	If file exceeds maximum allowed size, add form.HWFILETOOBIG.$part_$id to %env.
  241: 
  242: =cut
  243:  
  244: sub upload_size_allowed {
  245:     my ($name,$size,$fname) = @_;
  246:     if ($name =~ /^HWFILE(\w+)$/) {
  247:         my $ident = $1;
  248:         my $item = 'HWFILESIZE'.$ident;
  249:         my $savesize = sprintf("%.6f",$size);
  250:         &Apache::loncommon::add_to_env("form.$item",$savesize);
  251:         my $maxsize= &Apache::lonnet::EXT("resource.$ident.maxfilesize");
  252:         if (!$maxsize) {
  253:             $maxsize = 10.0; # FIXME This should become a domain configuration.
  254:         }
  255:         if ($size > $maxsize) {
  256:             my $warn = 'HWFILETOOBIG'.$ident;
  257:             &Apache::loncommon::add_to_env("form.$warn",$fname);
  258:             return;
  259:         }
  260:     }
  261:     return 'ok';
  262: }
  263: 
  264: =pod
  265: 
  266: =item sso_login()
  267: 
  268: 	handle the case of the single sign on user, at this point $r->user 
  269: 	will be set and valid; now need to find the loncapa user info, and possibly
  270: 	balance them. If $r->user() is set this means either it was either set by
  271:         SSO or by checkauthen.pm, if a valid cookie was found. The latter case can
  272:         be identified by the third arg ($usename), except when lonacc is called in 
  273:         an internal redirect to /adm/switchserver (e.g., load-balancing following
  274:         successful authentication) -- no cookie set yet.  For that particular case
  275:         simply skip the call to sso_login(). 
  276: 
  277: 	returns OK if it was SSO and user was handled.
  278:         returns undef if not SSO or no means to handle the user.
  279:         
  280: =cut
  281: 
  282: sub sso_login {
  283:     my ($r,$handle,$username) = @_;
  284: 
  285:     if (($r->user eq '') || ($username ne '') || ($r->user eq 'public:public') ||
  286:         (defined($env{'user.name'}) && (defined($env{'user.domain'}))
  287: 	  && ($handle ne ''))) {
  288: 	# not an SSO case or already logged in
  289: 	return undef;
  290:     }
  291: 
  292:     my ($user) = ($r->user =~ m/^($match_username)$/);
  293:     if ($user eq '') {
  294:         return undef;
  295:     }
  296: 
  297:     my $query = $r->args;
  298:     my %form;
  299:     if ($query) {
  300:         my @items = ('role','symb','iptoken','origurl','logtoken');
  301:         &Apache::loncommon::get_unprocessed_cgi($query,\@items);
  302:         foreach my $item (@items) {
  303:             if (defined($env{'form.'.$item})) {
  304:                 $form{$item} = $env{'form.'.$item};
  305:             }
  306:         }
  307:     }
  308: 
  309:     my %sessiondata;
  310:     if ($form{'iptoken'}) {
  311:         %sessiondata = &Apache::lonnet::tmpget($form{'iptoken'});
  312:         my $delete = &Apache::lonnet::tmpdel($form{'iptoken'});
  313:         unless ($sessiondata{'sessionserver'}) {
  314:             delete($form{'iptoken'});
  315:         }
  316:     }
  317: 
  318: #
  319: # If Shibboleth auth is in use, and a dual SSO and non-SSO login page
  320: # is in use, then the query string will contain the logtoken item with
  321: # a value set to the name of a .tmp file in /home/httpd/perl/tmp
  322: # containing the url to display after authentication, and also,
  323: # optionally, role and symb.
  324: #
  325: # Otherwise the query string may contain role and symb.
  326: #
  327: 
  328:     if ($form{'logtoken'}) {
  329:         my ($firsturl,@rest);
  330:         my $lonhost = $r->dir_config('lonHostID');
  331:         my $tmpinfo = &Apache::lonnet::reply('tmpget:'.$form{'logtoken'},$lonhost);
  332:         my $delete = &Apache::lonnet::tmpdel($form{'logtoken'});
  333:         unless (($tmpinfo=~/^error/) || ($tmpinfo eq 'con_lost') ||
  334:                 ($tmpinfo eq 'no_such_host')) {
  335:             (undef,$firsturl,@rest) = split(/&/,$tmpinfo);
  336:             if ($firsturl ne '') {
  337:                 $firsturl = &unescape($firsturl);
  338:             }
  339:             foreach my $item (@rest) {
  340:                 my ($key,$value) = split(/=/,$item);
  341:                 $form{$key} = &unescape($value);
  342:             }
  343:             if ($form{'iptoken'}) {
  344:                 %sessiondata = &Apache::lonnet::tmpget($form{'iptoken'});
  345:                 my $delete = &Apache::lonnet::tmpdel($form{'iptoken'});
  346:             }
  347:         }
  348:     }
  349: 
  350:     my $domain = $r->dir_config('lonSSOUserDomain');
  351:     if ($domain eq '') {
  352:         $domain = $r->dir_config('lonDefDomain');
  353:     }
  354:     my $home=&Apache::lonnet::homeserver($user,$domain);
  355:     if ($home !~ /(con_lost|no_host|no_such_host)/) {
  356: 	&Apache::lonnet::logthis(" SSO authorized user $user ");
  357:         my ($is_balancer,$otherserver,$hosthere);
  358:         if ($form{'iptoken'}) {
  359:             if (($sessiondata{'domain'} eq $domain) &&
  360:                 ($sessiondata{'username'} eq $user)) {
  361:                 $hosthere = 1;
  362:             }
  363:         }
  364:         unless ($hosthere) {
  365:             ($is_balancer,$otherserver) =
  366:                 &Apache::lonnet::check_loadbalancing($user,$domain,'login');
  367:             if ($is_balancer) {
  368:                 # Check if browser sent a LON-CAPA load balancer cookie (and this is a balancer)
  369:                 my ($found_server,$balancer_cookie) = &Apache::lonnet::check_for_balancer_cookie($r);
  370:                 if (($found_server) && ($balancer_cookie =~ /^\Q$domain\E_\Q$user\E_/)) {
  371:                     $otherserver = $found_server;
  372:                 } elsif ($otherserver eq '') {
  373:                     my $lowest_load;
  374:                     ($otherserver,undef,undef,undef,$lowest_load) = &Apache::lonnet::choose_server($domain);
  375:                     if ($lowest_load > 100) {
  376:                         $otherserver = &Apache::lonnet::spareserver($r,$lowest_load,$lowest_load,1,$domain);
  377:                     }
  378:                     if ($otherserver ne '') {
  379:                         my @hosts = &Apache::lonnet::current_machine_ids();
  380:                         if (grep(/^\Q$otherserver\E$/,@hosts)) {
  381:                             $hosthere = $otherserver;
  382:                         }
  383:                     }
  384:                 }
  385:             }
  386:         }
  387: 	if (($is_balancer) && (!$hosthere)) {
  388: 	    # login but immediately go to switch server to find us a new 
  389: 	    # machine
  390: 	    &Apache::lonauth::success($r,$user,$domain,$home,'noredirect');
  391:             foreach my $item (keys(%form)) {
  392:                 $env{'form.'.$item} = $form{$item};
  393:             }
  394:             unless (($form{'symb'}) || ($form{'origurl'})) {
  395:                 unless (($r->uri eq '/adm/roles') || ($r->uri eq '/adm/sso')) {
  396:                     $env{'form.origurl'} = $r->uri;
  397:                 }
  398:             }
  399:             $env{'request.sso.login'} = 1;
  400:             if (defined($r->dir_config("lonSSOReloginServer"))) {
  401:                 $env{'request.sso.reloginserver'} =
  402:                     $r->dir_config('lonSSOReloginServer');
  403:             }
  404:             my $redirecturl = '/adm/switchserver';
  405:             if ($otherserver ne '') {
  406:                 $redirecturl .= '?otherserver='.$otherserver;
  407:             }
  408: 	    $r->internal_redirect($redirecturl);
  409: 	    $r->set_handlers('PerlHandler'=> undef);
  410: 	} else {
  411: 	    # need to login them in, so generate the need data that
  412: 	    # migrate expects to do login
  413:             my $ip = &Apache::lonnet::get_requestor_ip($r);
  414: 	    my %info=('ip'        => $ip,
  415: 		      'domain'    => $domain,
  416: 		      'username'  => $user,
  417: 		      'server'    => $r->dir_config('lonHostID'),
  418: 		      'sso.login' => 1
  419: 		      );
  420:             foreach my $item ('role','symb','iptoken','origurl') {
  421:                 if (exists($form{$item})) {
  422:                     $info{$item} = $form{$item};
  423:                 } elsif ($sessiondata{$item} ne '') {
  424:                     $info{$item} = $sessiondata{$item};
  425:                 }
  426:             }
  427:             unless (($info{'symb'}) || ($info{'origurl'})) {
  428:                 unless (($r->uri eq '/adm/roles') || ($r->uri eq '/adm/sso')) {
  429:                     $info{'origurl'} = $r->uri; 
  430:                 }
  431:             }
  432:             if ($r->dir_config("ssodirecturl") == 1) {
  433:                 $info{'origurl'} = $r->uri;
  434:             }
  435:             if (defined($r->dir_config("lonSSOReloginServer"))) {
  436:                 $info{'sso.reloginserver'} = 
  437:                     $r->dir_config('lonSSOReloginServer'); 
  438:             }
  439:             if (($is_balancer) && ($hosthere)) {
  440:                 $info{'noloadbalance'} = $hosthere;
  441:             }
  442: 	    my $token = 
  443: 		&Apache::lonnet::tmpput(\%info,
  444: 					$r->dir_config('lonHostID'));
  445: 	    $env{'form.token'} = $token;
  446: 	    $r->internal_redirect('/adm/migrateuser');
  447: 	    $r->set_handlers('PerlHandler'=> undef);
  448: 	}
  449: 	return OK;
  450:     } else {
  451: 	&Apache::lonnet::logthis(" SSO authorized unknown user $user ");
  452:         my @cancreate;
  453:         my %domconfig =
  454:             &Apache::lonnet::get_dom('configuration',['usercreation'],$domain);
  455:         if (ref($domconfig{'usercreation'}) eq 'HASH') {
  456:             if (ref($domconfig{'usercreation'}{'cancreate'}) eq 'HASH') {
  457:                 if (ref($domconfig{'usercreation'}{'cancreate'}{'selfcreate'}) eq 'ARRAY') {
  458:                     @cancreate = @{$domconfig{'usercreation'}{'cancreate'}{'selfcreate'}};
  459:                 } elsif (($domconfig{'usercreation'}{'cancreate'}{'selfcreate'} ne 'none') && 
  460:                          ($domconfig{'usercreation'}{'cancreate'}{'selfcreate'} ne '')) {
  461:                     @cancreate = ($domconfig{'usercreation'}{'cancreate'}{'selfcreate'});
  462:                 }
  463:             }
  464:         }
  465:         if ((grep(/^sso$/,@cancreate)) || (defined($r->dir_config('lonSSOUserUnknownRedirect')))) {
  466:             $r->subprocess_env->set('SSOUserUnknown' => $user);
  467:             $r->subprocess_env->set('SSOUserDomain' => $domain);
  468:             if (grep(/^sso$/,@cancreate)) {
  469: #FIXME - need to preserve origurl, role and symb for use after account
  470: # creation
  471:                 $r->set_handlers('PerlHandler'=> [\&Apache::createaccount::handler]);
  472:                 $r->handler('perl-script');
  473:             } else {
  474: 	        $r->internal_redirect($r->dir_config('lonSSOUserUnknownRedirect'));
  475:                 $r->set_handlers('PerlHandler'=> undef);
  476:             }
  477: 	    return OK;
  478:         }
  479:     }
  480:     return undef;
  481: }
  482: 
  483: sub handler {
  484:     my $r = shift;
  485:     my $requrl=$r->uri;
  486: 
  487:     if ($requrl =~ m{^/res/adm/pages/[^/]+\.(gif|png)$}) {
  488:         return OK;
  489:     }
  490: 
  491:     if (&Apache::lonnet::is_domainimage($requrl)) {
  492:         return OK;
  493:     }
  494: 
  495:     my %user;
  496:     my $handle = &Apache::lonnet::check_for_valid_session($r,undef,\%user);
  497: 
  498:     unless (($requrl eq '/adm/switchserver') && (!$r->is_initial_req())) {
  499:         my $result = &sso_login($r,$handle,$user{'name'});
  500:         if (defined($result)) {
  501: 	    return $result;
  502:         }
  503:     }
  504: 
  505:     my ($is_balancer,$otherserver);
  506: 
  507:     if ($handle eq '') {
  508:         unless ((($requrl eq '/adm/switchserver') && (!$r->is_initial_req())) ||
  509:                 ($requrl =~ m{^/public/$match_domain/$match_courseid/syllabus}) ||
  510:                 ($requrl =~ m{^/adm/help/}) || ($requrl eq '/adm/sso') ||
  511:                 ($requrl =~ m{^/res/$match_domain/$match_username/})) {
  512: 	    $r->log_reason("Cookie not valid", $r->filename);
  513:         }
  514:     } elsif ($handle ne '') {
  515: 
  516: # ------------------------------------------------------ Initialize Environment
  517: 	my $lonidsdir=$r->dir_config('lonIDsDir');
  518: 	&Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle);
  519: 
  520: # --------------------------------------------------------- Initialize Language
  521: 
  522: 	&Apache::lonlocal::get_language_handle($r);
  523: 
  524:     }
  525: 
  526: # -------------------------------------------------- Should be a valid user now
  527:     if ($env{'user.name'} ne '' && $env{'user.domain'} ne '') {
  528: # -------------------------------------------------------------- Resource State
  529: 
  530:         my ($cdom,$cnum);
  531:         if ($env{'request.course.id'}) {
  532:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
  533:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
  534:         }
  535: 	if ($requrl=~/^\/+(res|uploaded)\//) {
  536: 	    $env{'request.state'} = "published";
  537: 	} else {
  538: 	    $env{'request.state'} = 'unknown';
  539: 	}
  540: 	$env{'request.filename'} = $r->filename;
  541: 	$env{'request.noversionuri'} = &Apache::lonnet::deversion($requrl);
  542:         my ($suppext,$checkabsolute);
  543:         if ($requrl =~ m{^/adm/wrapper/ext/}) {
  544:             my $query = $r->args;
  545:             if ($query) {
  546:                 my $preserved;
  547:                 foreach my $pair (split(/&/,$query)) {
  548:                     my ($name, $value) = split(/=/,$pair);
  549:                     unless (($name eq 'symb') || ($name eq 'usehttp')) {
  550:                         $preserved .= $pair.'&';
  551:                     }
  552:                     if (($env{'request.course.id'}) && ($name eq 'folderpath')) {
  553:                         if ($value =~ /^supplemental/) {
  554:                             $suppext = 1;
  555:                         }
  556:                     }
  557:                 }
  558:                 $preserved =~ s/\&$//;
  559:                 if ($preserved) {
  560:                     $env{'request.external.querystring'} = $preserved;
  561:                 }
  562:             }
  563:             if ($env{'request.course.id'}) {
  564:                 $checkabsolute = 1;
  565:             }
  566:         } elsif ($env{'request.course.id'} &&
  567:                  (($requrl =~ m{^/adm/$match_domain/$match_username/aboutme$}) ||
  568:                   ($requrl =~ m{^/public/$cdom/$cnum/syllabus$}))) {
  569:             my $query = $r->args;
  570:             if ($query) {
  571:                 foreach my $pair (split(/&/,$query)) {
  572:                     my ($name, $value) = split(/=/,$pair);
  573:                     if ($name eq 'folderpath') {
  574:                         if ($value =~ /^supplemental/) {
  575:                             $suppext = 1;
  576:                         }
  577:                         last;
  578:                     }
  579:                 }
  580:             }
  581:             if ($requrl =~ m{^/public/$cdom/$cnum/syllabus$}) {
  582:                 $checkabsolute = 1;
  583:             }
  584:         }
  585:         if ($checkabsolute) {
  586:             my $hostname = $r->hostname();
  587:             my $lonhost = &Apache::lonnet::host_from_dns($hostname);
  588:             if ($lonhost) {
  589:                 my $actual = &Apache::lonnet::absolute_url($hostname,1,1);
  590:                 my $expected = $Apache::lonnet::protocol{$lonhost}.'://'.$hostname;
  591:                 unless ($actual eq $expected) {
  592:                     $env{'request.use_absolute'} = $expected;
  593:                 }
  594:             }
  595:         }
  596: # -------------------------------------------------------- Load POST parameters
  597: 
  598: 	&Apache::lonacc::get_posted_cgi($r);
  599: 
  600: # ------------------------------------------------------ Check if load balancer 
  601: 
  602:         my $checkexempt;
  603:         if ($env{'user.loadbalexempt'} eq $r->dir_config('lonHostID')) {
  604:             if ($env{'user.loadbalcheck.time'} + 600 > time) {
  605:                 $checkexempt = 1;
  606:             }
  607:         }
  608:         if ($env{'user.noloadbalance'} eq $r->dir_config('lonHostID')) {
  609:             $checkexempt = 1;
  610:         }
  611:         unless (($checkexempt) || (($requrl eq '/adm/switchserver') && (!$r->is_initial_req()))) {
  612:             ($is_balancer,$otherserver) =
  613:                 &Apache::lonnet::check_loadbalancing($env{'user.name'},
  614:                                                      $env{'user.domain'});
  615:             if ($is_balancer) {
  616:                 # Check if browser sent a LON-CAPA load balancer cookie (and this is a balancer)
  617:                 my ($found_server,$balancer_cookie) = &Apache::lonnet::check_for_balancer_cookie($r);
  618:                 if (($found_server) && ($balancer_cookie =~ /^\Q$env{'user.domain'}\E_\Q$env{'user.name'}\E_/)) {
  619:                     $otherserver = $found_server;
  620:                 }
  621:                 unless ($requrl eq '/adm/switchserver') {
  622:                     $r->set_handlers('PerlResponseHandler'=>
  623:                                      [\&Apache::switchserver::handler]);
  624:                 }
  625:                 if ($otherserver ne '') {
  626:                     $env{'form.otherserver'} = $otherserver;
  627:                 }
  628:                 unless (($env{'form.origurl'}) || ($r->uri eq '/adm/roles') ||
  629:                         ($r->uri eq '/adm/switchserver') || ($r->uri eq '/adm/sso')) {
  630:                     $env{'form.origurl'} = $r->uri;
  631:                 }
  632:             }
  633:         }
  634: 
  635: # ---------------------------------------------------------------- Check access
  636: 	my $now = time;
  637:         my ($check_symb,$check_access,$check_block,$access,$poss_symb);
  638: 	if ($requrl !~ m{^/(?:adm|public|(?:prt|zip)spool)/}
  639: 	    || $requrl =~ /^\/adm\/.*\/(smppg|bulletinboard)(\?|$ )/x) {
  640:             $check_access = 1;
  641:         }
  642:         if ((!$check_access) && ($env{'request.course.id'})) {
  643:             if (($requrl eq '/adm/viewclasslist') ||
  644:                 ($requrl =~ m{^(/adm/wrapper|)\Q/uploaded/$cdom/$cnum/docs/\E}) ||
  645:                 ($requrl =~ m{^/adm/.*/aboutme$}) ||
  646:                 ($requrl=~m{^/adm/coursedocs/showdoc/})) {
  647:                 $check_block = 1;
  648:             }
  649:         }
  650:         if (($env{'request.course.id'}) && (!$suppext)) {
  651:             $requrl=~/\.(\w+)$/;
  652:             if ((&Apache::loncommon::fileembstyle($1) eq 'ssi') ||
  653:                 ($requrl=~/^\/adm\/.*\/(aboutme|smppg|bulletinboard)(\?|$ )/x) ||
  654:                 ($requrl=~/^\/adm\/wrapper\//) ||
  655:                 ($requrl=~m|^/adm/coursedocs/showdoc/|) ||
  656:                 ($requrl=~m|\.problem/smpedit$|) ||
  657:                 ($requrl=~/^\/public\/.*\/syllabus$/) ||
  658:                 ($requrl=~/^\/adm\/(viewclasslist|navmaps)$/) ||
  659:                 ($requrl=~/^\/adm\/.*\/aboutme\/portfolio(\?|$)/)) {
  660:                 $check_symb = 1;
  661:             }
  662:         }
  663:         if (($check_access) || ($check_block)) {
  664:             if ($check_symb) {
  665:                 if ($env{'form.symb'}) {
  666:                     $poss_symb=&Apache::lonnet::symbclean($env{'form.symb'});
  667:                 } elsif (($env{'request.course.id'}) && ($r->args ne '')) {
  668:                     my $query = $r->args;
  669:                     foreach my $pair (split(/&/,$query)) {
  670:                         my ($name, $value) = split(/=/,$pair);
  671:                         $name = &unescape($name);
  672:                         $value =~ tr/+/ /;
  673:                         $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
  674:                         if ($name eq 'symb') {
  675:                             $poss_symb = &Apache::lonnet::symbclean($value);
  676:                             last;
  677:                         }
  678:                     }
  679:                 }
  680:                 if ($poss_symb) {
  681:                     my ($possmap,$resid,$url)=&Apache::lonnet::decode_symb($poss_symb);
  682:                     $url = &Apache::lonnet::clutter($url);
  683:                     my $toplevelmap = $env{'course.'.$env{'request.course.id'}.'.url'};
  684:                     unless (($url eq $requrl) && (($possmap eq $toplevelmap) ||
  685:                                                   (&Apache::lonnet::is_on_map($possmap)))) {
  686:                         undef($poss_symb);
  687:                     }
  688:                     if ($poss_symb) {
  689:                         if ((!$env{'request.role.adv'}) && ($env{'acc.randomout'}) &&
  690:                             ($env{'acc.randomout'}=~/\&\Q$poss_symb\E\&/)) {
  691:                             undef($poss_symb);
  692:                         }
  693:                     }
  694:                 }
  695:                 if ($poss_symb) {
  696:                     $access=&Apache::lonnet::allowed('bre',$requrl,$poss_symb);
  697:                 } else {
  698:                     $access=&Apache::lonnet::allowed('bre',$requrl,'','','','',1);
  699:                 }
  700:             } else {
  701:                 my $clientip = &Apache::lonnet::get_requestor_ip($r);
  702:                 $access=&Apache::lonnet::allowed('bre',$requrl,'','',$clientip);
  703:             }
  704:         }
  705:         if ($check_block) {
  706:             if ($access eq 'B') {
  707:                 if ($poss_symb) {
  708:                     if (&Apache::lonnet::symbverify($poss_symb,$requrl)) {
  709:                         $env{'request.symb'} = $poss_symb;
  710:                     }
  711:                 }
  712:                 &Apache::blockedaccess::setup_handler($r);
  713:                 return OK;
  714:             }
  715:         } elsif ($check_access) { 
  716:             if ($handle eq '') {
  717:                 unless ($access eq 'F') {
  718:                     if ($requrl =~ m{^/res/$match_domain/$match_username/}) {
  719:                         $r->log_reason("Cookie not valid", $r->filename);
  720:                     }
  721:                 }
  722:             }
  723: 	    if ($access eq '1') {
  724: 		$env{'user.error.msg'}="$requrl:bre:0:0:Choose Course";
  725: 		return HTTP_NOT_ACCEPTABLE; 
  726: 	    }
  727: 	    if ($access eq 'A') {
  728: 		&Apache::restrictedaccess::setup_handler($r);
  729: 		return OK;
  730: 	    }
  731:             if ($access eq 'B') {
  732:                 if ($poss_symb) {
  733:                     if (&Apache::lonnet::symbverify($poss_symb,$requrl)) {
  734:                         $env{'request.symb'} = $poss_symb;
  735:                     }
  736:                 }
  737:                 &Apache::blockedaccess::setup_handler($r);
  738:                 return OK;
  739:             }
  740: 	    if (($access ne '2') && ($access ne 'F')) {
  741:                 if ($requrl =~ m{^/res/}) {
  742:                     $access = &Apache::lonnet::allowed('bro',$requrl);
  743:                     if ($access ne 'F') {
  744:                         if ($requrl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
  745:                             $access = &Apache::lonnet::allowed('bre','/res/lib/templates/simpleproblem.problem');
  746:                             if ($access ne 'F') {
  747:                                 $env{'user.error.msg'}="$requrl:bre:1:1:Access Denied";
  748:                                 return HTTP_NOT_ACCEPTABLE;
  749:                             }
  750:                         } else {
  751:                             $env{'user.error.msg'}="$requrl:bre:1:1:Access Denied";
  752:                             return HTTP_NOT_ACCEPTABLE;
  753:                         }
  754:                     }
  755:                 } elsif (($handle =~ /^publicuser_\d+$/) && (&Apache::lonnet::is_portfolio_url($requrl))) {
  756:                     my $clientip = &Apache::lonnet::get_requestor_ip($r);
  757:                     if (&Apache::lonnet::allowed('bre',$requrl,undef,undef,$clientip) ne 'F') {
  758:                         $env{'user.error.msg'}="$requrl:bre:1:1:Access Denied";
  759:                         return HTTP_NOT_ACCEPTABLE;
  760:                     }
  761:                 } else {
  762: 		    $env{'user.error.msg'}="$requrl:bre:1:1:Access Denied";
  763: 		    return HTTP_NOT_ACCEPTABLE;
  764:                 }
  765: 	    }
  766: 	}
  767: 	if ($requrl =~ m|^/prtspool/|) {
  768: 	    my $start='/prtspool/'.$env{'user.name'}.'_'.
  769: 		$env{'user.domain'};
  770: 	    if ($requrl !~ /^\Q$start\E/) {
  771: 		$env{'user.error.msg'}="$requrl:bre:1:1:Access Denied";
  772: 		return HTTP_NOT_ACCEPTABLE;
  773: 	    }
  774: 	}
  775: 	if ($requrl =~ m|^/zipspool/|) {
  776: 	    my $start='/zipspool/zipout/'.$env{'user.name'}.":".
  777: 		$env{'user.domain'};
  778: 	    if ($requrl !~ /^\Q$start\E/) {
  779: 		$env{'user.error.msg'}="$requrl:bre:1:1:Access Denied";
  780: 		return HTTP_NOT_ACCEPTABLE;
  781: 	    }
  782: 	}
  783: 	if ($env{'user.name'} eq 'public' && 
  784: 	    $env{'user.domain'} eq 'public' &&
  785: 	    $requrl !~ m{^/+(res|public|uploaded)/} &&
  786: 	    $requrl !~ m{^/adm/[^/]+/[^/]+/aboutme/portfolio$ }x &&
  787:             $requrl !~ m{^/adm/blockingstatus/.*$} &&
  788: 	    $requrl !~ m{^/+adm/(help|logout|restrictedaccess|randomlabel\.png)}) {
  789: 	    $env{'request.querystring'}=$r->args;
  790: 	    $env{'request.firsturl'}=$requrl;
  791: 	    return FORBIDDEN;
  792: 	}
  793: # ------------------------------------------------------------- This is allowed
  794: 	if ($env{'request.course.id'}) {
  795: 	    &Apache::lonnet::countacc($requrl);
  796:             my $query=$r->args;
  797:             if ($check_symb) {
  798: # ------------------------------------- This is serious stuff, get symb and log
  799: 		my $symb;
  800: 		if ($query) {
  801: 		    &Apache::loncommon::get_unprocessed_cgi($query,['symb','folderpath']);
  802: 		}
  803: 		if ($env{'form.symb'}) {
  804: 		    $symb=&Apache::lonnet::symbclean($env{'form.symb'});
  805:                     if (($requrl eq '/adm/navmaps') ||
  806:                         ($requrl =~ m{^/adm/wrapper/}) ||
  807:                         ($requrl =~ m{^/adm/coursedocs/showdoc/})) {
  808:                         unless (&Apache::lonnet::symbverify($symb,$requrl)) {
  809:                             if (&Apache::lonnet::is_on_map($requrl)) {
  810:                                 $symb = &Apache::lonnet::symbread($requrl);
  811:                                 unless (&Apache::lonnet::symbverify($symb,$requrl)) {
  812:                                     undef($symb);
  813:                                 }
  814:                             }
  815:                         }
  816:                         if ($symb) {
  817:                             if ($requrl eq '/adm/navmaps') {
  818:                                 my ($map,$mid,$murl)=&Apache::lonnet::decode_symb($symb);
  819:                                 &Apache::lonnet::symblist($map,$murl => [$murl,$mid]);
  820:                             } elsif (($requrl =~ m{^/adm/wrapper/}) ||
  821:                                      ($requrl =~ m{^/adm/coursedocs/showdoc/})) {
  822:                                 my ($map,$mid,$murl)=&Apache::lonnet::decode_symb($symb);
  823:                                 if ($map =~ /\.page$/) {
  824:                                     my $mapsymb = &Apache::lonnet::symbread($map);
  825:                                     ($map,$mid,$murl)=&Apache::lonnet::decode_symb($mapsymb);
  826:                                 }
  827:                                 &Apache::lonnet::symblist($map,$murl => [$murl,$mid],
  828:                                                           'last_known' =>[$murl,$mid]);
  829:                             }
  830:                         }
  831: 		    } elsif ((&Apache::lonnet::symbverify($symb,$requrl)) ||
  832: 			     (($requrl=~m|(.*)/smpedit$|) &&
  833: 			      &Apache::lonnet::symbverify($symb,$1)) ||
  834:                              (($requrl=~m|(.*/aboutme)/portfolio$|) &&
  835:                               &Apache::lonnet::symbverify($symb,$1))) {
  836: 			my ($map,$mid,$murl)=&Apache::lonnet::decode_symb($symb);
  837:                         if (($map =~ /\.page$/) && ($requrl !~ /\.page$/)) {
  838:                             my $mapsymb = &Apache::lonnet::symbread($map);
  839:                             ($map,$mid,$murl)=&Apache::lonnet::decode_symb($mapsymb);
  840:                         }
  841: 			&Apache::lonnet::symblist($map,$murl => [$murl,$mid],
  842: 						  'last_known' =>[$murl,$mid]);
  843: 		    } else {
  844: 			$r->log_reason('Invalid symb for '.$requrl.': '.
  845: 				       $symb);
  846: 			$env{'user.error.msg'}=
  847: 			    "$requrl:bre:1:1:Invalid Access";
  848: 			return HTTP_NOT_ACCEPTABLE; 
  849: 		    }
  850: 		} else {
  851:                     if ($requrl=~m{^(/adm/.*/aboutme)/portfolio$}) {
  852:                         $requrl = $1;
  853:                     }
  854: 		    $symb=&Apache::lonnet::symbread($requrl);
  855:                     if (&Apache::lonnet::is_on_map($requrl) && $symb) {
  856:                         my ($encstate,$invalidsymb);
  857:                         unless (&Apache::lonnet::symbverify($symb,$requrl,\$encstate)) {
  858:                             $invalidsymb = 1;
  859:                             #
  860:                             # If $env{'request.enc'} inconsistent with encryption expected for $symb
  861:                             # retrieved by lonnet::symbread(), call again to check for an instance of
  862:                             # $requrl in the course for which expected encryption matches request.enc.
  863:                             # If symb for different instance passes lonnet::symbverify(), use that as
  864:                             # the symb for $requrl and call &Apache::lonnet::allowed() for that symb.
  865:                             # Report invalid symb if there is no other symb. Redirect to /adm/ambiguous
  866:                             # if multiple possible symbs consistent with request.enc available for $requrl.
  867:                             #
  868:                             if (($env{'request.enc'} && !$encstate) || (!$env{'request.enc'} && $encstate)) {
  869:                                 my %possibles;
  870:                                 my $nocache = 1;
  871:                                 my $oldsymb = $symb;
  872:                                 $symb = &Apache::lonnet::symbread($requrl,'','','',\%possibles,$nocache);
  873:                                 if (($symb) && ($symb ne $oldsymb)) {
  874:                                     if (&Apache::lonnet::symbverify($symb,$requrl)) {
  875:                                         my $access=&Apache::lonnet::allowed('bre',$requrl,$symb);
  876:                                         if ($access eq 'B') {
  877:                                             $env{'request.symb'} = $symb;
  878:                                             &Apache::blockedaccess::setup_handler($r);
  879:                                             return OK;
  880:                                         } elsif (($access eq '2') || ($access eq 'F')) {
  881:                                             $invalidsymb = '';
  882:                                         }
  883:                                     }
  884:                                 } elsif (keys(%possibles) > 1) {
  885:                                     $r->internal_redirect('/adm/ambiguous');
  886:                                     return OK;
  887:                                 }
  888:                             }
  889:                             if ($invalidsymb) {
  890:                                 if ($requrl eq '/adm/navmaps') {
  891:                                     undef($symb);
  892:                                 } else {
  893:                                     $r->log_reason('Invalid symb for '.$requrl.': '.$symb);
  894:                                     $env{'user.error.msg'}=
  895:                                         "$requrl:bre:1:1:Invalid Access";
  896:                                     return HTTP_NOT_ACCEPTABLE;
  897:                                 }
  898:                             }
  899:                         }
  900:                     }
  901: 		    if ($symb) {
  902: 			my ($map,$mid,$murl)=
  903: 			    &Apache::lonnet::decode_symb($symb);
  904:                         if ($requrl eq '/adm/navmaps') {
  905:                             &Apache::lonnet::symblist($map,$murl =>[$murl,$mid]);
  906:                         } else {
  907:                             if (($map =~ /\.page$/) && ($requrl !~ /\.page$/)) {
  908:                                 my $mapsymb = &Apache::lonnet::symbread($map);
  909:                                 ($map,$mid,$murl)=&Apache::lonnet::decode_symb($mapsymb);
  910:                             }
  911:                             &Apache::lonnet::symblist($map,$murl =>[$murl,$mid],
  912:                                                       'last_known' =>[$murl,$mid]);
  913:                         }
  914: 		    }
  915: 		}
  916: 		$env{'request.symb'}=$symb;
  917:                 if (($env{'request.symbread.cached.'}) && ($env{'request.symbread.cached.'} ne $symb)) {
  918:                     $env{'request.symbread.cached.'} = $symb;
  919:                 }
  920: 		&Apache::lonnet::courseacclog($symb);
  921: 	    } else {
  922: # ------------------------------------------------------- This is other content
  923: 		&Apache::lonnet::courseacclog($requrl);    
  924: 	    }
  925:             if ($requrl =~ m{^/+uploaded/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/.+\.html?$}) {
  926:                 if (&Apache::lonnet::allowed('mdc',$env{'request.course.id'})) {
  927:                     if ($query) {
  928:                         &Apache::loncommon::get_unprocessed_cgi($query,['forceedit']);
  929:                         if ($env{'form.forceedit'}) {
  930:                             $env{'request.state'} = 'edit';
  931:                         }
  932:                     }
  933:                 }
  934:             } elsif ($requrl =~ m{^/+uploaded/\Q$cdom\E/\Q$cnum\E/portfolio/syllabus/.+\.html?$}) {
  935:                 if (&Apache::lonnet::allowed('mdc',$env{'request.course.id'})) {
  936:                     if ($query) {
  937:                         &Apache::loncommon::get_unprocessed_cgi($query,['forceedit','editmode']);
  938:                         if (($env{'form.forceedit'}) || ($env{'form.editmode'})) {
  939:                             $env{'request.state'} = 'edit';
  940:                         }
  941:                     }
  942:                 }
  943:             }
  944: 	}
  945: 	return OK;
  946:     } else {
  947:         my $defdom=$r->dir_config('lonDefDomain');
  948:         ($is_balancer,$otherserver) =
  949:             &Apache::lonnet::check_loadbalancing(undef,$defdom);
  950:         if ($is_balancer) {
  951:             $r->set_handlers('PerlResponseHandler'=>
  952:                              [\&Apache::switchserver::handler]);
  953:             if ($otherserver ne '') {
  954:                 $env{'form.otherserver'} = $otherserver;
  955:             }
  956:         }
  957:     }
  958: # -------------------------------------------- See if this is a public resource
  959:     if ($requrl=~m|^/+adm/+help/+|) {
  960:  	return OK;
  961:     }
  962: # ------------------------------------ See if this is a viewable portfolio file
  963:     if (&Apache::lonnet::is_portfolio_url($requrl)) {
  964:         my $clientip = &Apache::lonnet::get_requestor_ip($r);
  965: 	my $access=&Apache::lonnet::allowed('bre',$requrl,undef,undef,$clientip);
  966: 	if ($access eq 'A') {
  967: 	    &Apache::restrictedaccess::setup_handler($r);
  968: 	    return OK;
  969: 	}
  970: 	if (($access ne '2') && ($access ne 'F')) {
  971: 	    $env{'user.error.msg'}="$requrl:bre:1:1:Access Denied";
  972: 	    return HTTP_NOT_ACCEPTABLE;
  973: 	}
  974:     }
  975: 
  976: # -------------------------------------------------------------- Not authorized
  977:     $requrl=~/\.(\w+)$/;
  978: #    if ((&Apache::loncommon::fileembstyle($1) eq 'ssi') ||
  979: #        ($requrl=~/^\/adm\/(roles|logout|email|menu|remote)/) ||
  980: #        ($requrl=~m|^/prtspool/|)) {
  981: # -------------------------- Store where they wanted to go and get login screen
  982: 	$env{'request.querystring'}=$r->args;
  983: 	$env{'request.firsturl'}=$requrl;
  984:        return FORBIDDEN;
  985: #   } else {
  986: # --------------------------------------------------------------------- Goodbye
  987: #       return HTTP_BAD_REQUEST;
  988: #   }
  989: }
  990: 
  991: 1;
  992: __END__
  993: 
  994: =pod
  995: 
  996: =back
  997: 
  998: =cut
  999: 

FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>