File:  [LON-CAPA] / loncom / auth / lonacc.pm
Revision 1.118: download - view: text, annotated - select for diffs
Sun Nov 16 02:46:19 2008 UTC (15 years, 6 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
Bug 5719 Size limits for File Upload in Essay response.
 - Max. cumulative size for submitted files applies to total for all files submitted to a particular essayresponse item. Default is 100 MB.
 - In course context, &lonacc:get_posted_cgi() will now no longer add file contents to %env if size exceeds max. for item.
 - Additional checks in essayresponse::file_submission() will assign award as "EXCESS_FILESIZE" if total of all files being submitted for sinle essayresponse item exceed max set via
PARM.
 - Modification to $Apache::lonhomework::results{"resource.$part.$id.$which"} to now include a comma separated list of only those submitted files which passed both the filetype and size tests.

    1: # The LearningOnline Network
    2: # Cookie Based Access Handler
    3: #
    4: # $Id: lonacc.pm,v 1.118 2008/11/16 02:46:19 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: package Apache::lonacc;
   31: 
   32: use strict;
   33: use Apache::Constants qw(:common :http :methods);
   34: use Apache::File;
   35: use Apache::lonnet;
   36: use Apache::loncommon();
   37: use Apache::lonlocal;
   38: use Apache::restrictedaccess();
   39: use Apache::blockedaccess(); 
   40: use Fcntl qw(:flock);
   41: use LONCAPA;
   42: 
   43: sub cleanup {
   44:     my ($r)=@_;
   45:     if (! $r->is_initial_req()) { return DECLINED; }
   46:     &Apache::lonnet::save_cache();
   47:     &Apache::lontexconvert::jsMath_reset();
   48:     return OK;
   49: }
   50: 
   51: sub goodbye {
   52:     my ($r)=@_;
   53:     &Apache::lonnet::goodbye();
   54:     return DONE;
   55: }
   56: 
   57: ###############################################
   58: 
   59: sub get_posted_cgi {
   60:     my ($r,$fields) = @_;
   61: 
   62:     my $buffer;
   63:     if ($r->header_in('Content-length')) {
   64: 	$r->read($buffer,$r->header_in('Content-length'),0);
   65:     }
   66:     my $content_type = $r->header_in('Content-type');
   67:     if ($content_type !~ m{^multipart/form-data}) {
   68: 	my @pairs=split(/&/,$buffer);
   69: 	my $pair;
   70: 	foreach $pair (@pairs) {
   71: 	    my ($name,$value) = split(/=/,$pair);
   72: 	    $value =~ tr/+/ /;
   73: 	    $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
   74: 	    $name  =~ tr/+/ /;
   75: 	    $name  =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
   76:             if (ref($fields) eq 'ARRAY') {
   77:                 next if (!grep(/^\Q$name\E$/,@{$fields}));
   78:             }
   79: 	    &Apache::loncommon::add_to_env("form.$name",$value);
   80: 	}
   81:     } else {
   82: 	my ($contentsep) = ($content_type =~ /boundary=\"?([^\";,]+)\"?/);
   83: 	my @lines = split (/\n/,$buffer);
   84: 	my $name='';
   85: 	my $value='';
   86: 	my $fname='';
   87: 	my $fmime='';
   88: 	my $i;
   89: 	for ($i=0;$i<=$#lines;$i++) {
   90: 	    if ($lines[$i]=~/^--\Q$contentsep\E/) {
   91: 		if ($name) {
   92: 		    chomp($value);
   93:                     if (ref($fields) eq 'ARRAY') {
   94:                         next if (!grep(/^\Q$name\E$/,@{$fields}));
   95:                     }
   96:                     if ($fname) {
   97:                         if ($env{'form.symb'} ne '') {
   98:                             my $size = (length($value))/(1024.0 * 1024.0);
   99:                             if (&upload_size_allowed($name,$size,$fname) eq 'ok') {
  100:                                 $env{"form.$name.filename"}=$fname;
  101:                                 $env{"form.$name.mimetype"}=$fmime;
  102:                                 &Apache::loncommon::add_to_env("form.$name",$value);
  103:                             }
  104:                         } else {
  105:                             $env{"form.$name.filename"}=$fname;
  106:                             $env{"form.$name.mimetype"}=$fmime;
  107:                             &Apache::loncommon::add_to_env("form.$name",$value);
  108:                         }
  109:                     } else {
  110:                         $value=~s/\s+$//s;
  111:                         &Apache::loncommon::add_to_env("form.$name",$value);
  112:                     }
  113: 		}
  114: 		if ($i<$#lines) {
  115: 		    $i++;
  116: 		    $lines[$i]=~
  117: 		/Content\-Disposition\:\s*form\-data\;\s*name\=\"([^\"]+)\"/i;
  118: 		    $name=$1;
  119: 		    $value='';
  120: 		    if ($lines[$i]=~/filename\=\"([^\"]+)\"/i) {
  121: 			$fname=$1;
  122: 			if 
  123:                             ($lines[$i+1]=~/Content\-Type\:\s*([\w\-\/]+)/i) {
  124: 				$fmime=$1;
  125: 				$i++;
  126: 			    } else {
  127: 				$fmime='';
  128: 			    }
  129: 		    } else {
  130: 			$fname='';
  131: 			$fmime='';
  132: 		    }
  133: 		    $i++;
  134: 		}
  135: 	    } else {
  136: 		$value.=$lines[$i]."\n";
  137: 	    }
  138: 	}
  139:     }
  140: #
  141: # Digested POSTed values
  142: #
  143: # Remember the way this was originally done (GET or POST)
  144: #
  145:     $env{'request.method'}=$ENV{'REQUEST_METHOD'};
  146: #
  147: # There may also be stuff in the query string
  148: # Tell subsequent handlers that this was GET, not POST, so they can access query string.
  149: # Also, unset POSTed content length to cover all tracks.
  150: #
  151: 
  152:     $r->method_number(M_GET);
  153: 
  154:     $r->method('GET');
  155:     $r->headers_in->unset('Content-length');
  156: }
  157: 
  158: #
  159: # Perform size checks for file uploads to essayresponse items in course context.
  160: #
  161: # Add form.HWFILESIZE.$part_$id to %env with file size (MB)
  162: # If file exceeds maximum allowed size, add form.HWFILETOOBIG.$part_$id to %env.
  163: #
  164:  
  165: sub upload_size_allowed {
  166:     my ($name,$size,$fname) = @_;
  167:     if ($name =~ /^HWFILE(\w+)$/) {
  168:         my $ident = $1;
  169:         my $item = 'HWFILESIZE'.$ident;
  170:         &Apache::loncommon::add_to_env("form.$item",$size);
  171:         my $maxsize= &Apache::lonnet::EXT("resource.$ident.maxfilesize");
  172:         if (!$maxsize) {
  173:             $maxsize = 100.0;
  174:         }
  175:         if ($size > $maxsize) {
  176:             my $warn = 'HWFILETOOBIG'.$ident;
  177:             &Apache::loncommon::add_to_env("form.$warn",$fname);
  178:             return;
  179:         }
  180:     }
  181:     return 'ok';
  182: }
  183: 
  184: # handle the case of the single sign on user, at this point $r->user 
  185: # will be set and valid now need to find the loncapa user info and possibly
  186: # balance them
  187: # returns OK if it was a SSO and user was handled
  188: #         undef if not SSO or no means to hanle the user
  189: 
  190: sub sso_login {
  191:     my ($r,$handle) = @_;
  192: 
  193:     my $lonidsdir=$r->dir_config('lonIDsDir');
  194:     if (!($r->user 
  195: 	  && (!defined($env{'user.name'}) && !defined($env{'user.domain'}))
  196: 	  && ($handle eq ''))) {
  197: 	# not an SSO case or already logged in
  198: 	return undef;
  199:     }
  200: 
  201:     my ($user) = ($r->user =~ m/([a-zA-Z0-9_\-@.]*)/);
  202: 
  203:     my $domain = $r->dir_config('lonDefDomain');
  204:     my $home=&Apache::lonnet::homeserver($user,$domain);
  205:     if ($home !~ /(con_lost|no_host|no_such_host)/) {
  206: 	&Apache::lonnet::logthis(" SSO authorized user $user ");
  207: 	if ($r->dir_config("lonBalancer") eq 'yes') {
  208: 	    # login but immeaditly go to switch server to find us a new 
  209: 	    # machine
  210: 	    &Apache::lonauth::success($r,$user,$domain,$home,'noredirect');
  211:             $env{'request.sso.login'} = 1;
  212:             if (defined($r->dir_config("lonSSOReloginServer"))) {
  213:                 $env{'request.sso.reloginserver'} =
  214:                     $r->dir_config('lonSSOReloginServer');
  215:             }
  216: 	    $r->internal_redirect('/adm/switchserver');
  217: 	    $r->set_handlers('PerlHandler'=> undef);
  218: 	} else {
  219: 	    # need to login them in, so generate the need data that
  220: 	    # migrate expects to do login
  221: 	    my %info=('ip'        => $r->connection->remote_ip(),
  222: 		      'domain'    => $domain,
  223: 		      'username'  => $user,
  224: 		      'server'    => $r->dir_config('lonHostID'),
  225: 		      'sso.login' => 1
  226: 		      );
  227:             if ($r->dir_config("ssodirecturl") == 1) {
  228:                 $info{'origurl'} = $r->uri;
  229:             }
  230:             if (defined($r->dir_config("lonSSOReloginServer"))) {
  231:                 $info{'sso.reloginserver'} = 
  232:                     $r->dir_config('lonSSOReloginServer'); 
  233:             }
  234: 	    my $token = 
  235: 		&Apache::lonnet::tmpput(\%info,
  236: 					$r->dir_config('lonHostID'));
  237: 	    $env{'form.token'} = $token;
  238: 	    $r->internal_redirect('/adm/migrateuser');
  239: 	    $r->set_handlers('PerlHandler'=> undef);
  240: 	}
  241: 	return OK;
  242:     } elsif (defined($r->dir_config('lonSSOUserUnknownRedirect'))) {
  243: 	&Apache::lonnet::logthis(" SSO authorized unknown user $user ");
  244:         $r->subprocess_env->set('SSOUserUnknown' => $user);
  245:         $r->subprocess_env->set('SSOUserDomain' => $domain);
  246:         my @cancreate;
  247:         my %domconfig =
  248:             &Apache::lonnet::get_dom('configuration',['usercreation'],$domain);
  249:         if (ref($domconfig{'usercreation'}) eq 'HASH') {
  250:             if (ref($domconfig{'usercreation'}{'cancreate'}) eq 'HASH') {
  251:                 if (ref($domconfig{'usercreation'}{'cancreate'}{'selfcreate'}) eq 'ARRAY') {
  252:                     @cancreate = @{$domconfig{'usercreation'}{'cancreate'}{'selfcreate'}};
  253:                 } elsif (($domconfig{'usercreation'}{'cancreate'}{'selfcreate'} ne 'none') && 
  254:                          ($domconfig{'usercreation'}{'cancreate'}{'selfcreate'} ne '')) {
  255:                     @cancreate = ($domconfig{'usercreation'}{'cancreate'}{'selfcreate'});
  256:                 }
  257:             }
  258:         }
  259:         if (grep(/^sso$/,@cancreate)) {
  260:             $r->internal_redirect('/adm/createaccount');
  261:         } else {
  262: 	    $r->internal_redirect($r->dir_config('lonSSOUserUnknownRedirect'));
  263:         }
  264: 	$r->set_handlers('PerlHandler'=> undef);
  265: 	return OK;
  266:     }
  267:     return undef;
  268: }
  269: 
  270: sub handler {
  271:     my $r = shift;
  272:     my $requrl=$r->uri;
  273:     if (&Apache::lonnet::is_domainimage($requrl)) {
  274:         return OK;
  275:     }
  276: 
  277:     
  278:     my $handle = &Apache::lonnet::check_for_valid_session($r);
  279: 
  280:     my $result = &sso_login($r,$handle);
  281:     if (defined($result)) {
  282: 	return $result;
  283:     }
  284: 
  285: 
  286:     if ($r->dir_config("lonBalancer") eq 'yes') {
  287: 	$r->set_handlers('PerlResponseHandler'=>
  288: 			 [\&Apache::switchserver::handler]);
  289:     }
  290:     
  291:     if ($handle eq '') {
  292: 	$r->log_reason("Cookie $handle not valid", $r->filename); 
  293:     } elsif ($handle ne '') {
  294: 
  295: # ------------------------------------------------------ Initialize Environment
  296: 	my $lonidsdir=$r->dir_config('lonIDsDir');
  297: 	&Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle);
  298: 
  299: # --------------------------------------------------------- Initialize Language
  300: 
  301: 	&Apache::lonlocal::get_language_handle($r);
  302: 
  303:     }
  304: 
  305: # -------------------------------------------------- Should be a valid user now
  306:     if ($env{'user.name'} ne '' && $env{'user.domain'} ne '') {
  307: # -------------------------------------------------------------- Resource State
  308: 
  309: 	if ($requrl=~/^\/+(res|uploaded)\//) {
  310: 	    $env{'request.state'} = "published";
  311: 	} else {
  312: 	    $env{'request.state'} = 'unknown';
  313: 	}
  314: 	$env{'request.filename'} = $r->filename;
  315: 	$env{'request.noversionuri'} = &Apache::lonnet::deversion($requrl);
  316: # -------------------------------------------------------- Load POST parameters
  317: 
  318: 	&Apache::lonacc::get_posted_cgi($r);
  319: 
  320: # ---------------------------------------------------------------- Check access
  321: 	my $now = time;
  322: 	if ($requrl !~ m{^/(?:adm|public|prtspool)/}
  323: 	    || $requrl =~ /^\/adm\/.*\/(smppg|bulletinboard)(\?|$ )/x) {
  324: 	    my $access=&Apache::lonnet::allowed('bre',$requrl);
  325: 	    if ($access eq '1') {
  326: 		$env{'user.error.msg'}="$requrl:bre:0:0:Choose Course";
  327: 		return HTTP_NOT_ACCEPTABLE; 
  328: 	    }
  329: 	    if ($access eq 'A') {
  330: 		&Apache::restrictedaccess::setup_handler($r);
  331: 		return OK;
  332: 	    }
  333:             if ($access eq 'B') {
  334:                 &Apache::blockedaccess::setup_handler($r);
  335:                 return OK;
  336:             }
  337: 	    if (($access ne '2') && ($access ne 'F')) {
  338: 		$env{'user.error.msg'}="$requrl:bre:1:1:Access Denied";
  339: 		return HTTP_NOT_ACCEPTABLE; 
  340: 	    }
  341: 	}
  342: 	if ($requrl =~ m|^/prtspool/|) {
  343: 	    my $start='/prtspool/'.$env{'user.name'}.'_'.
  344: 		$env{'user.domain'};
  345: 	    if ($requrl !~ /^\Q$start\E/) {
  346: 		$env{'user.error.msg'}="$requrl:bre:1:1:Access Denied";
  347: 		return HTTP_NOT_ACCEPTABLE;
  348: 	    }
  349: 	}
  350: 	if ($requrl =~ m|^/zipspool/|) {
  351: 	    my $start='/zipspool/zipout/'.$env{'user.name'}.":".
  352: 		$env{'user.domain'};
  353: 	    if ($requrl !~ /^\Q$start\E/) {
  354: 		$env{'user.error.msg'}="$requrl:bre:1:1:Access Denied";
  355: 		return HTTP_NOT_ACCEPTABLE;
  356: 	    }
  357: 	}
  358: 	if ($env{'user.name'} eq 'public' && 
  359: 	    $env{'user.domain'} eq 'public' &&
  360: 	    $requrl !~ m{^/+(res|public|uploaded)/} &&
  361: 	    $requrl !~ m{^/adm/[^/]+/[^/]+/aboutme/portfolio$ }x &&
  362: 	    $requrl !~ m{^/+adm/(help|logout|restrictedaccess|randomlabel\.png)}) {
  363: 	    $env{'request.querystring'}=$r->args;
  364: 	    $env{'request.firsturl'}=$requrl;
  365: 	    return FORBIDDEN;
  366: 	}
  367: # ------------------------------------------------------------- This is allowed
  368: 	if ($env{'request.course.id'}) {
  369: 	    &Apache::lonnet::countacc($requrl);
  370: 	    $requrl=~/\.(\w+)$/;
  371: 	    if ((&Apache::loncommon::fileembstyle($1) eq 'ssi') ||
  372: 		($requrl=~/^\/adm\/.*\/(aboutme|navmaps|smppg|bulletinboard)(\?|$ )/x) ||
  373: 		($requrl=~/^\/adm\/wrapper\//) ||
  374: 		($requrl=~m|^/adm/coursedocs/showdoc/|) ||
  375: 		($requrl=~m|\.problem/smpedit$|) ||
  376: 		($requrl=~/^\/public\/.*\/syllabus$/)) {
  377: # ------------------------------------- This is serious stuff, get symb and log
  378: 		my $query=$r->args;
  379: 		my $symb;
  380: 		if ($query) {
  381: 		    &Apache::loncommon::get_unprocessed_cgi($query,['symb']);
  382: 		}
  383: 		if ($env{'form.symb'}) {
  384: 		    $symb=&Apache::lonnet::symbclean($env{'form.symb'});
  385: 		    if ($requrl =~ m|^/adm/wrapper/|
  386: 			|| $requrl =~ m|^/adm/coursedocs/showdoc/|) {
  387: 			my ($map,$mid,$murl)=&Apache::lonnet::decode_symb($symb);
  388: 			&Apache::lonnet::symblist($map,$murl => [$murl,$mid],
  389: 						  'last_known' =>[$murl,$mid]);
  390: 		    } elsif ((&Apache::lonnet::symbverify($symb,$requrl)) ||
  391: 			     (($requrl=~m|(.*)/smpedit$|) &&
  392: 			      &Apache::lonnet::symbverify($symb,$1))) {
  393: 			my ($map,$mid,$murl)=&Apache::lonnet::decode_symb($symb);
  394: 			&Apache::lonnet::symblist($map,$murl => [$murl,$mid],
  395: 						  'last_known' =>[$murl,$mid]);
  396: 		    } else {
  397: 			$r->log_reason('Invalid symb for '.$requrl.': '.
  398: 				       $symb);
  399: 			$env{'user.error.msg'}=
  400: 			    "$requrl:bre:1:1:Invalid Access";
  401: 			return HTTP_NOT_ACCEPTABLE; 
  402: 		    }
  403: 		} else {
  404: 		    $symb=&Apache::lonnet::symbread($requrl);
  405: 		    if (&Apache::lonnet::is_on_map($requrl) && $symb &&
  406: 			!&Apache::lonnet::symbverify($symb,$requrl)) {
  407: 			$r->log_reason('Invalid symb for '.$requrl.': '.$symb);
  408: 			$env{'user.error.msg'}=
  409: 			    "$requrl:bre:1:1:Invalid Access";
  410: 			return HTTP_NOT_ACCEPTABLE; 
  411: 		    }
  412: 		    if ($symb) {
  413: 			my ($map,$mid,$murl)=
  414: 			    &Apache::lonnet::decode_symb($symb);
  415: 			&Apache::lonnet::symblist($map,$murl =>[$murl,$mid],
  416: 						  'last_known' =>[$murl,$mid]);
  417: 		    }
  418: 		}
  419: 		$env{'request.symb'}=$symb;
  420: 		&Apache::lonnet::courseacclog($symb);
  421: 	    } else {
  422: # ------------------------------------------------------- This is other content
  423: 		&Apache::lonnet::courseacclog($requrl);    
  424: 	    }
  425: 	}
  426: 	return OK;
  427:     }
  428: # -------------------------------------------- See if this is a public resource
  429:     if ($requrl=~m|^/+adm/+help/+|) {
  430:  	return OK;
  431:     }
  432: # ------------------------------------ See if this is a viewable portfolio file
  433:     if (&Apache::lonnet::is_portfolio_url($requrl)) {
  434: 	my $access=&Apache::lonnet::allowed('bre',$requrl);
  435: 	if ($access eq 'A') {
  436: 	    &Apache::restrictedaccess::setup_handler($r);
  437: 	    return OK;
  438: 	}
  439: 	if (($access ne '2') && ($access ne 'F')) {
  440: 	    $env{'user.error.msg'}="$requrl:bre:1:1:Access Denied";
  441: 	    return HTTP_NOT_ACCEPTABLE;
  442: 	}
  443:     }
  444: 
  445: # -------------------------------------------------------------- Not authorized
  446:     $requrl=~/\.(\w+)$/;
  447: #    if ((&Apache::loncommon::fileembstyle($1) eq 'ssi') ||
  448: #        ($requrl=~/^\/adm\/(roles|logout|email|menu|remote)/) ||
  449: #        ($requrl=~m|^/prtspool/|)) {
  450: # -------------------------- Store where they wanted to go and get login screen
  451: 	$env{'request.querystring'}=$r->args;
  452: 	$env{'request.firsturl'}=$requrl;
  453:        return FORBIDDEN;
  454: #   } else {
  455: # --------------------------------------------------------------------- Goodbye
  456: #       return HTTP_BAD_REQUEST;
  457: #   }
  458: }
  459: 
  460: 1;
  461: __END__
  462: 
  463: =head1 NAME
  464: 
  465: Apache::lonacc - Cookie Based Access Handler
  466: 
  467: =head1 SYNOPSIS
  468: 
  469: Invoked (for various locations) by /etc/httpd/conf/srm.conf:
  470: 
  471:  PerlAccessHandler       Apache::lonacc
  472: 
  473: =head1 INTRODUCTION
  474: 
  475: This module enables cookie based authentication and is used
  476: to control access for many different LON-CAPA URIs.
  477: 
  478: Whenever the client sends the cookie back to the server, 
  479: this cookie is handled by either lonacc.pm or loncacc.pm
  480: (see srm.conf for what is invoked when).  If
  481: the cookie is missing or invalid, the user is re-challenged
  482: for login information.
  483: 
  484: This is part of the LearningOnline Network with CAPA project
  485: described at http://www.lon-capa.org.
  486: 
  487: =head1 HANDLER SUBROUTINE
  488: 
  489: This routine is called by Apache and mod_perl.
  490: 
  491: =over 4
  492: 
  493: =item *
  494: 
  495: transfer profile into environment
  496: 
  497: =item *
  498: 
  499: load POST parameters
  500: 
  501: =item *
  502: 
  503: check access
  504: 
  505: =item *
  506: 
  507: if allowed, get symb, log, generate course statistics if applicable
  508: 
  509: =item *
  510: 
  511: otherwise return error
  512: 
  513: =item *
  514: 
  515: see if public resource
  516: 
  517: =item *
  518: 
  519: store attempted access
  520: 
  521: =back
  522: 
  523: =cut

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