File:  [LON-CAPA] / loncom / auth / lonacc.pm
Revision 1.190: download - view: text, annotated - select for diffs
Tue May 4 18:47:37 2021 UTC (3 years ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Bug 6914.
  Replace hostname with alias when creating absolute URLs, if alias in use.

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

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